refactor(auth): replace dashboard sessions with stateless tokens and session control (#6329)
* refactor(auth): replace dashboard sessions with stateless tokens * feat(auth): harden session issuance and distributed enforcement * fix(proxy): preserve trusted proxy compatibility defaults * refactor: address dashboard auth review feedback * refactor: remove classic frontend and flatten web app
This commit is contained in:
@@ -0,0 +1,454 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Tag as TagIcon } from 'lucide-react'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { StaticDataTable } from '@/components/data-table'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useSystemConfigStore } from '@/stores/system-config-store'
|
||||
|
||||
import {
|
||||
BILLING_PRICING_VARS,
|
||||
MATCH_CONTAINS,
|
||||
MATCH_EQ,
|
||||
MATCH_EXISTS,
|
||||
MATCH_GTE,
|
||||
MATCH_LT,
|
||||
MATCH_RANGE,
|
||||
SOURCE_TIME,
|
||||
normalizeTierLabel,
|
||||
parseTiersFromExpr,
|
||||
splitBillingExprAndRequestRules,
|
||||
tryParseRequestRuleExpr,
|
||||
type ParsedTier,
|
||||
type RequestCondition,
|
||||
type RequestRuleGroup,
|
||||
type TierCondition,
|
||||
} from '../lib/billing-expr'
|
||||
|
||||
type DynamicPricingBreakdownProps = {
|
||||
billingExpr: string | null | undefined
|
||||
/**
|
||||
* Label of the tier that fired for the current request. When provided,
|
||||
* the corresponding row is highlighted and tagged as "Matched". Used by
|
||||
* the usage-log details dialog to show which tier the engine selected.
|
||||
*/
|
||||
matchedTierLabel?: string | null
|
||||
/**
|
||||
* Hide cache-pricing columns regardless of the per-tier values. The log
|
||||
* details dialog passes this when the actual request did not consume any
|
||||
* cache tokens, so users only see pricing rows that were relevant to the
|
||||
* call they are inspecting. Defaults to false (show all configured prices).
|
||||
*/
|
||||
hideCacheColumns?: boolean
|
||||
/**
|
||||
* Dense rendering for the usage-log details dialog: drops the colored
|
||||
* icon header and uses the dialog's small text sizes. Defaults to false.
|
||||
*/
|
||||
compact?: boolean
|
||||
}
|
||||
|
||||
const VAR_LABELS: Record<string, string> = {
|
||||
p: 'Input',
|
||||
c: 'Output',
|
||||
len: 'Length',
|
||||
}
|
||||
const OP_LABELS: Record<string, string> = {
|
||||
'<': '<',
|
||||
'<=': '≤',
|
||||
'>': '>',
|
||||
'>=': '≥',
|
||||
}
|
||||
const TIME_FUNC_LABELS: Record<string, string> = {
|
||||
hour: 'Hour',
|
||||
minute: 'Minute',
|
||||
weekday: 'Weekday',
|
||||
month: 'Month',
|
||||
day: 'Day',
|
||||
}
|
||||
|
||||
function formatTokenHint(value: string | number): string {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n) || n === 0) return ''
|
||||
if (n >= 1_000_000) {
|
||||
return `${(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`
|
||||
}
|
||||
if (n >= 1000) {
|
||||
return `${(n / 1000).toFixed(n % 1000 === 0 ? 0 : 1)}K`
|
||||
}
|
||||
return String(n)
|
||||
}
|
||||
|
||||
function formatConditionSummary(
|
||||
conditions: TierCondition[],
|
||||
t: (key: string) => string
|
||||
): string {
|
||||
return conditions
|
||||
.map((c) => {
|
||||
const varLabel = t(VAR_LABELS[c.var] || c.var)
|
||||
const hint = formatTokenHint(c.value)
|
||||
return `${varLabel} ${OP_LABELS[c.op] || c.op} ${hint || c.value}`
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(' && ')
|
||||
}
|
||||
|
||||
function describeCondition(
|
||||
cond: RequestCondition,
|
||||
t: (key: string) => string
|
||||
): string {
|
||||
if (cond.source === SOURCE_TIME) {
|
||||
const fn = t(TIME_FUNC_LABELS[cond.timeFunc] || cond.timeFunc)
|
||||
const tz = cond.timezone || 'UTC'
|
||||
if (cond.mode === MATCH_RANGE) {
|
||||
return `${fn} ${cond.rangeStart}:00~${cond.rangeEnd}:00 (${tz})`
|
||||
}
|
||||
const opMap: Record<string, string> = {
|
||||
[MATCH_EQ]: '=',
|
||||
[MATCH_GTE]: '≥',
|
||||
[MATCH_LT]: '<',
|
||||
}
|
||||
return `${fn} ${opMap[cond.mode] || '='} ${cond.value} (${tz})`
|
||||
}
|
||||
const src = cond.source === 'header' ? t('Header') : t('Body param')
|
||||
const path = cond.path || ''
|
||||
if (cond.mode === MATCH_EXISTS) return `${src} ${path} ${t('Exists')}`
|
||||
if (cond.mode === MATCH_CONTAINS) {
|
||||
return `${src} ${path} ${t('Contains')} "${cond.value}"`
|
||||
}
|
||||
const opMap: Record<string, string> = {
|
||||
eq: '=',
|
||||
gt: '>',
|
||||
gte: '≥',
|
||||
lt: '<',
|
||||
lte: '≤',
|
||||
}
|
||||
return `${src} ${path} ${opMap[cond.mode] || '='} ${cond.value}`
|
||||
}
|
||||
|
||||
function describeGroup(
|
||||
group: RequestRuleGroup,
|
||||
t: (key: string) => string
|
||||
): string {
|
||||
return (group.conditions || [])
|
||||
.map((c) => describeCondition(c, t))
|
||||
.join(' && ')
|
||||
}
|
||||
|
||||
export function DynamicPricingBreakdown({
|
||||
billingExpr,
|
||||
matchedTierLabel,
|
||||
hideCacheColumns = false,
|
||||
compact = false,
|
||||
}: DynamicPricingBreakdownProps) {
|
||||
const { t } = useTranslation()
|
||||
const expr = billingExpr || ''
|
||||
const currency = useSystemConfigStore((s) => s.config.currency)
|
||||
|
||||
const { symbol, rate } = useMemo(() => {
|
||||
if (currency.quotaDisplayType === 'CNY') {
|
||||
return { symbol: '¥', rate: currency.usdExchangeRate || 7 }
|
||||
}
|
||||
if (currency.quotaDisplayType === 'CUSTOM') {
|
||||
return {
|
||||
symbol: currency.customCurrencySymbol || '¤',
|
||||
rate: currency.customCurrencyExchangeRate || 1,
|
||||
}
|
||||
}
|
||||
return { symbol: '$', rate: 1 }
|
||||
}, [currency])
|
||||
|
||||
const { tiers, ruleGroups } = useMemo(() => {
|
||||
const split = splitBillingExprAndRequestRules(expr)
|
||||
const parsedTiers = parseTiersFromExpr(split.billingExpr)
|
||||
const parsedRules = tryParseRequestRuleExpr(split.requestRuleExpr || '')
|
||||
return {
|
||||
tiers: parsedTiers,
|
||||
ruleGroups: parsedRules || [],
|
||||
}
|
||||
}, [expr])
|
||||
|
||||
const hasTiers = tiers.length > 0
|
||||
const hasRules = ruleGroups.length > 0
|
||||
const normalizedMatchedTierLabel = normalizeTierLabel(
|
||||
matchedTierLabel ?? undefined
|
||||
)
|
||||
|
||||
if (!expr) return null
|
||||
|
||||
if (!hasTiers) {
|
||||
return (
|
||||
<section className={cn('min-w-0', !compact && 'py-4')}>
|
||||
{!compact && (
|
||||
<div className='mb-3 flex items-center gap-2'>
|
||||
<span className='inline-flex size-6 items-center justify-center rounded-lg bg-amber-100 text-amber-700 shadow-sm dark:bg-amber-500/20 dark:text-amber-300'>
|
||||
<TagIcon className='size-3.5' />
|
||||
</span>
|
||||
<div>
|
||||
<div className='text-foreground text-base font-medium'>
|
||||
{t('Special billing expression')}
|
||||
</div>
|
||||
<div className='text-muted-foreground text-xs'>
|
||||
{t('Unable to parse structured pricing')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className='text-muted-foreground mb-1 text-[10px] font-medium tracking-wider uppercase'>
|
||||
{t('Raw expression')}
|
||||
</div>
|
||||
<code className='text-muted-foreground block text-xs break-all'>
|
||||
{expr}
|
||||
</code>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const visiblePriceFields = BILLING_PRICING_VARS.filter((v) => {
|
||||
if (!hasTiers) return false
|
||||
if (hideCacheColumns && v.group === 'cache') return false
|
||||
return tiers.some(
|
||||
(tier) => Number(tier[v.field as string as keyof ParsedTier] || 0) > 0
|
||||
)
|
||||
})
|
||||
|
||||
return (
|
||||
<section className={cn('min-w-0', !compact && 'py-3 sm:py-4')}>
|
||||
{!compact && (
|
||||
<div className='mb-3 flex items-start gap-2 sm:mb-4'>
|
||||
<span className='mt-0.5 inline-flex size-6 items-center justify-center rounded-lg bg-amber-100 text-amber-700 shadow-sm dark:bg-amber-500/20 dark:text-amber-300'>
|
||||
<TagIcon className='size-3.5' />
|
||||
</span>
|
||||
<div>
|
||||
<div className='text-foreground text-base font-medium'>
|
||||
{t('Dynamic Pricing')}
|
||||
</div>
|
||||
<div className='text-muted-foreground text-xs'>
|
||||
{t('Prices vary by usage tier and request conditions')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasTiers && (
|
||||
<div className={cn(compact ? cn(hasRules && 'mb-2') : 'mb-3 sm:mb-4')}>
|
||||
<div
|
||||
className={
|
||||
compact
|
||||
? 'text-muted-foreground mb-1.5 text-xs font-medium'
|
||||
: 'text-foreground mb-2 text-sm font-semibold'
|
||||
}
|
||||
>
|
||||
{t('Tiered price table')}
|
||||
</div>
|
||||
<div className='space-y-1.5 sm:hidden'>
|
||||
{tiers.map((tier, i) => {
|
||||
const condSummary = formatConditionSummary(tier.conditions, t)
|
||||
const isMatched =
|
||||
matchedTierLabel != null &&
|
||||
matchedTierLabel !== '' &&
|
||||
tier.label === matchedTierLabel
|
||||
return (
|
||||
<div
|
||||
key={`tier-mobile-${i}`}
|
||||
className={cn(
|
||||
'rounded-md border p-2',
|
||||
isMatched && 'border-emerald-500/40 bg-emerald-500/10'
|
||||
)}
|
||||
>
|
||||
<div className='mb-1.5 flex flex-wrap items-center gap-1.5'>
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300'
|
||||
>
|
||||
{tier.label || t('Default')}
|
||||
</Badge>
|
||||
{isMatched && (
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'
|
||||
>
|
||||
{t('Matched')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{condSummary && (
|
||||
<div className='text-muted-foreground mb-1.5 text-xs'>
|
||||
{condSummary}
|
||||
</div>
|
||||
)}
|
||||
<div className='grid grid-cols-2 gap-x-3 gap-y-1.5'>
|
||||
{visiblePriceFields.map((v) => {
|
||||
const value = Number(
|
||||
tier[v.field as string as keyof ParsedTier] || 0
|
||||
)
|
||||
return (
|
||||
<div key={v.field} className='min-w-0'>
|
||||
<div className='text-muted-foreground truncate text-[10px] font-medium tracking-wider uppercase'>
|
||||
{t(v.shortLabel)}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'truncate font-mono',
|
||||
compact ? 'text-xs' : 'text-sm font-semibold'
|
||||
)}
|
||||
>
|
||||
{value > 0
|
||||
? `${symbol}${(value * rate).toFixed(4)}`
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<StaticDataTable
|
||||
className='hidden rounded-none border-0 sm:block'
|
||||
tableClassName={
|
||||
compact
|
||||
? '[&_td]:text-xs [&_td_*]:text-xs [&_th]:text-xs [&_th_*]:text-xs'
|
||||
: 'text-sm'
|
||||
}
|
||||
headerRowClassName='hover:bg-transparent'
|
||||
data={tiers}
|
||||
getRowKey={(_tier, index) => `tier-${index}`}
|
||||
getRowClassName={(tier) => {
|
||||
const isMatched =
|
||||
normalizedMatchedTierLabel !== '' &&
|
||||
normalizeTierLabel(tier.label) === normalizedMatchedTierLabel
|
||||
return cn(
|
||||
isMatched &&
|
||||
'bg-emerald-50/70 hover:bg-emerald-50/70 dark:bg-emerald-500/10 dark:hover:bg-emerald-500/10'
|
||||
)
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
id: 'tier',
|
||||
header: t('Tier'),
|
||||
className: cn(
|
||||
'text-muted-foreground py-2 font-medium',
|
||||
compact && 'h-8'
|
||||
),
|
||||
cellClassName: cn('align-top', compact ? 'py-2' : 'py-2.5'),
|
||||
cell: (tier) => {
|
||||
const condSummary = formatConditionSummary(tier.conditions, t)
|
||||
const isMatched =
|
||||
normalizedMatchedTierLabel !== '' &&
|
||||
normalizeTierLabel(tier.label) ===
|
||||
normalizedMatchedTierLabel
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-wrap items-center gap-1.5'>
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300'
|
||||
>
|
||||
{tier.label || t('Default')}
|
||||
</Badge>
|
||||
{isMatched && (
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'
|
||||
>
|
||||
{t('Matched')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{condSummary && (
|
||||
<div className='text-muted-foreground mt-1 text-xs'>
|
||||
{condSummary}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
},
|
||||
},
|
||||
...visiblePriceFields.map((v, index) => ({
|
||||
id: v.field ?? `price-${index}`,
|
||||
header: t(v.shortLabel),
|
||||
className: cn(
|
||||
'text-muted-foreground py-2 text-right font-medium',
|
||||
compact && 'h-8'
|
||||
),
|
||||
cellClassName: cn(
|
||||
'text-right align-top font-mono',
|
||||
compact ? 'py-2' : 'py-2.5'
|
||||
),
|
||||
cell: (tier: ParsedTier) => {
|
||||
const value = Number(
|
||||
tier[v.field as string as keyof ParsedTier] || 0
|
||||
)
|
||||
return value > 0 ? (
|
||||
<span className={cn(!compact && 'font-semibold')}>
|
||||
{`${symbol}${(value * rate).toFixed(4)}`}
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
)
|
||||
},
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasRules && (
|
||||
<div>
|
||||
<div
|
||||
className={
|
||||
compact
|
||||
? 'text-muted-foreground mb-1.5 text-xs font-medium'
|
||||
: 'text-foreground mb-2 text-sm font-semibold'
|
||||
}
|
||||
>
|
||||
{t('Conditional multipliers')}
|
||||
</div>
|
||||
<ul className='space-y-1.5'>
|
||||
{ruleGroups.map((group, gi) => (
|
||||
<li
|
||||
key={`group-${gi}`}
|
||||
className='bg-muted/50 flex items-center justify-between gap-3 rounded-md px-3 py-2'
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'text-foreground break-all',
|
||||
compact ? 'text-xs' : 'text-sm'
|
||||
)}
|
||||
>
|
||||
{describeGroup(group, t)}
|
||||
</span>
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='shrink-0 bg-orange-100 text-orange-700 dark:bg-orange-500/20 dark:text-orange-300'
|
||||
>
|
||||
{group.multiplier}x
|
||||
</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Search } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
export interface EmptyStateProps {
|
||||
searchQuery?: string
|
||||
hasActiveFilters: boolean
|
||||
onClearFilters: () => void
|
||||
}
|
||||
|
||||
export function EmptyState(props: EmptyStateProps) {
|
||||
const { t } = useTranslation()
|
||||
const hasSearch = Boolean(props.searchQuery?.trim())
|
||||
|
||||
return (
|
||||
<div className='flex min-h-[320px] flex-col items-center justify-center rounded-lg border border-dashed px-6 py-12 text-center'>
|
||||
<Search className='text-muted-foreground/40 mb-3 size-10' />
|
||||
|
||||
<h3 className='text-foreground mb-1 text-base font-semibold'>
|
||||
{t('No models found')}
|
||||
</h3>
|
||||
|
||||
<p className='text-muted-foreground mb-5 max-w-xs text-sm'>
|
||||
{hasSearch
|
||||
? t(
|
||||
'No results for "{{query}}". Try adjusting your search or filters.',
|
||||
{ query: props.searchQuery }
|
||||
)
|
||||
: t('No models match your current filters.')}
|
||||
</p>
|
||||
|
||||
{(props.hasActiveFilters || hasSearch) && (
|
||||
<Button variant='outline' size='sm' onClick={props.onClearFilters}>
|
||||
{t('Clear all filters')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
export { PricingSidebar } from './pricing-sidebar'
|
||||
export { PricingToolbar } from './pricing-toolbar'
|
||||
export { ModelCard } from './model-card'
|
||||
export { ModelCardGrid } from './model-card-grid'
|
||||
export { LoadingSkeleton } from './loading-skeleton'
|
||||
export { EmptyState } from './empty-state'
|
||||
export { SearchBar } from './search-bar'
|
||||
export {
|
||||
ModelDetails,
|
||||
ModelDetailsContent,
|
||||
ModelDetailsDrawer,
|
||||
} from './model-details'
|
||||
export { PricingTable } from './pricing-table'
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
import { VIEW_MODES, type ViewMode } from '../constants'
|
||||
|
||||
export interface LoadingSkeletonProps {
|
||||
viewMode?: ViewMode
|
||||
}
|
||||
|
||||
export function LoadingSkeleton(props: LoadingSkeletonProps) {
|
||||
const viewMode = props.viewMode ?? VIEW_MODES.CARD
|
||||
|
||||
return (
|
||||
<div className='space-y-5'>
|
||||
<div className='space-y-1.5'>
|
||||
<Skeleton className='h-8 w-40' />
|
||||
<Skeleton className='h-4 w-52' />
|
||||
</div>
|
||||
<Skeleton className='h-10 w-full rounded-lg' />
|
||||
<FilterBarSkeleton />
|
||||
{viewMode === VIEW_MODES.TABLE ? (
|
||||
<TableContentSkeleton />
|
||||
) : (
|
||||
<CardContentSkeleton />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContentSkeleton() {
|
||||
return (
|
||||
<div className='grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3'>
|
||||
{Array.from({ length: 9 }).map((_, i) => (
|
||||
<div key={i} className='rounded-xl border p-5'>
|
||||
<div className='flex items-start justify-between gap-3'>
|
||||
<div className='flex min-w-0 items-start gap-3'>
|
||||
<Skeleton className='size-10 shrink-0 rounded-xl' />
|
||||
<div className='min-w-0 flex-1 space-y-2'>
|
||||
<Skeleton className='h-5 w-36' />
|
||||
<Skeleton className='h-3.5 w-48' />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className='h-8 w-16 rounded-md' />
|
||||
</div>
|
||||
<div className='mt-4 space-y-2'>
|
||||
<Skeleton className='h-3.5 w-full' />
|
||||
<Skeleton className='h-3.5 w-4/5' />
|
||||
</div>
|
||||
<div className='mt-4 flex items-center gap-2'>
|
||||
<Skeleton className='h-4 w-24' />
|
||||
<Skeleton className='h-4 w-16' />
|
||||
</div>
|
||||
<div className='mt-2 flex items-center gap-3'>
|
||||
<Skeleton className='h-3.5 w-14' />
|
||||
<Skeleton className='h-3.5 w-14' />
|
||||
<Skeleton className='h-3.5 w-8' />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FilterBarSkeleton() {
|
||||
return (
|
||||
<div className='space-y-3'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='flex flex-1 flex-wrap items-center gap-2'>
|
||||
{[80, 90, 75, 85, 70].map((width, i) => (
|
||||
<Skeleton
|
||||
key={i}
|
||||
className='h-8 rounded-lg'
|
||||
style={{ width: `${width}px` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Skeleton className='h-8 w-24 rounded-lg' />
|
||||
<Skeleton className='h-8 w-20 rounded-lg' />
|
||||
<Skeleton className='h-8 w-24' />
|
||||
<Skeleton className='h-8 w-20 rounded-lg' />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className='h-5 w-24' />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableContentSkeleton() {
|
||||
const columns = [
|
||||
{ width: 200 },
|
||||
{ width: 100 },
|
||||
{ width: 100 },
|
||||
{ width: 100 },
|
||||
{ width: 80 },
|
||||
{ width: 100 },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className='space-y-4'>
|
||||
<div className='overflow-hidden rounded-lg border'>
|
||||
<div className='bg-muted/30 border-b px-4 py-3'>
|
||||
<div className='flex items-center gap-4'>
|
||||
{columns.map((col, i) => (
|
||||
<Skeleton
|
||||
key={i}
|
||||
className='h-4'
|
||||
style={{ width: `${col.width}px` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{Array.from({ length: 10 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className='flex items-center gap-4 border-b px-4 py-3 last:border-b-0'
|
||||
>
|
||||
{columns.map((col, j) => (
|
||||
<Skeleton
|
||||
key={j}
|
||||
className='h-5'
|
||||
style={{ width: `${col.width}px` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Skeleton className='h-5 w-32' />
|
||||
<div className='flex items-center gap-2'>
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Skeleton key={i} className='size-8' />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { StatusBadge, type StatusVariant } from '@/components/status-badge'
|
||||
|
||||
import { isDynamicPricingModel } from '../lib/dynamic-price'
|
||||
import { isTokenBasedModel } from '../lib/model-helpers'
|
||||
import type { PricingModel } from '../types'
|
||||
|
||||
interface ModelBillingModeBadgeProps {
|
||||
model: PricingModel
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function ModelBillingModeBadge(props: ModelBillingModeBadgeProps) {
|
||||
const { t } = useTranslation()
|
||||
let label = t('Per Request')
|
||||
let variant: StatusVariant = 'purple'
|
||||
|
||||
if (isDynamicPricingModel(props.model)) {
|
||||
label = t('Dynamic Pricing')
|
||||
variant = 'warning'
|
||||
} else if (isTokenBasedModel(props.model)) {
|
||||
label = t('Token-based')
|
||||
variant = 'info'
|
||||
}
|
||||
|
||||
return (
|
||||
<StatusBadge
|
||||
label={label}
|
||||
variant={variant}
|
||||
copyable={false}
|
||||
size='sm'
|
||||
className={props.className}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { getPerfMetricsSummary } from '@/features/performance-metrics/api'
|
||||
|
||||
import { DEFAULT_PRICING_PAGE_SIZE, DEFAULT_TOKEN_UNIT } from '../constants'
|
||||
import type { PricingModel, TokenUnit } from '../types'
|
||||
import { ModelCard } from './model-card'
|
||||
import type { ModelPerfBadgeData } from './model-perf-badge'
|
||||
|
||||
export interface ModelCardGridProps {
|
||||
models: PricingModel[]
|
||||
onModelClick: (modelName: string) => void
|
||||
priceRate?: number
|
||||
usdExchangeRate?: number
|
||||
tokenUnit?: TokenUnit
|
||||
showRechargePrice?: boolean
|
||||
selectedGroup?: string
|
||||
}
|
||||
|
||||
export function ModelCardGrid(props: ModelCardGridProps) {
|
||||
const { t } = useTranslation()
|
||||
const [page, setPage] = useState(1)
|
||||
const pageSize = DEFAULT_PRICING_PAGE_SIZE
|
||||
const tokenUnit = props.tokenUnit ?? DEFAULT_TOKEN_UNIT
|
||||
const totalPages = Math.max(1, Math.ceil(props.models.length / pageSize))
|
||||
const currentPage = Math.min(page, totalPages)
|
||||
|
||||
const perfQuery = useQuery({
|
||||
queryKey: ['perf-metrics-summary', 24],
|
||||
queryFn: () => getPerfMetricsSummary(24),
|
||||
staleTime: 60 * 1000,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const pagedModels = useMemo(() => {
|
||||
const start = (currentPage - 1) * pageSize
|
||||
return props.models.slice(start, start + pageSize)
|
||||
}, [currentPage, pageSize, props.models])
|
||||
|
||||
const perfMap = useMemo(() => {
|
||||
const map = new Map<string, ModelPerfBadgeData>()
|
||||
for (const model of perfQuery.data?.data?.models ?? []) {
|
||||
map.set(model.model_name, model)
|
||||
}
|
||||
return map
|
||||
}, [perfQuery.data])
|
||||
|
||||
if (props.models.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='space-y-4 sm:space-y-5'>
|
||||
<div className='grid grid-cols-1 gap-3 sm:gap-4 md:grid-cols-2 lg:grid-cols-3'>
|
||||
{pagedModels.map((model) => (
|
||||
<ModelCard
|
||||
key={model.id ?? model.model_name}
|
||||
model={model}
|
||||
tokenUnit={tokenUnit}
|
||||
priceRate={props.priceRate}
|
||||
usdExchangeRate={props.usdExchangeRate}
|
||||
showRechargePrice={props.showRechargePrice}
|
||||
selectedGroup={props.selectedGroup}
|
||||
perf={perfMap.get(model.model_name || '')}
|
||||
onClick={() => props.onModelClick(model.model_name || '')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className='text-muted-foreground flex flex-col items-center justify-between gap-3 border-t px-4 py-3 text-sm sm:flex-row'>
|
||||
<p className='text-muted-foreground'>
|
||||
{t('Page {{current}} of {{total}}', {
|
||||
current: currentPage,
|
||||
total: totalPages,
|
||||
})}
|
||||
</p>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={() => setPage((current) => Math.max(1, current - 1))}
|
||||
disabled={currentPage <= 1}
|
||||
className='gap-1.5'
|
||||
>
|
||||
<ChevronLeft className='size-4' />
|
||||
{t('Previous page')}
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={() =>
|
||||
setPage((current) => Math.min(totalPages, current + 1))
|
||||
}
|
||||
disabled={currentPage >= totalPages}
|
||||
className='gap-1.5'
|
||||
>
|
||||
{t('Next page')}
|
||||
<ChevronRight className='size-4' />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { ChevronRight, Copy } from 'lucide-react'
|
||||
import { memo, type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
|
||||
import { getLobeIcon } from '@/lib/lobe-icon'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { DEFAULT_TOKEN_UNIT } from '../constants'
|
||||
import {
|
||||
getDynamicDisplayGroupRatio,
|
||||
getDynamicPricingSummary,
|
||||
} from '../lib/dynamic-price'
|
||||
import { parseTags } from '../lib/filters'
|
||||
import { isTokenBasedModel } from '../lib/model-helpers'
|
||||
import { formatPrice, formatRequestPrice } from '../lib/price'
|
||||
import type { PricingModel, TokenUnit } from '../types'
|
||||
import { ModelBillingModeBadge } from './model-billing-mode-badge'
|
||||
import { ModelPerfBadge, type ModelPerfBadgeData } from './model-perf-badge'
|
||||
|
||||
export interface ModelCardProps {
|
||||
model: PricingModel
|
||||
onClick: () => void
|
||||
priceRate?: number
|
||||
usdExchangeRate?: number
|
||||
tokenUnit?: TokenUnit
|
||||
showRechargePrice?: boolean
|
||||
selectedGroup?: string
|
||||
perf?: ModelPerfBadgeData
|
||||
}
|
||||
|
||||
export const ModelCard = memo(function ModelCard(props: ModelCardProps) {
|
||||
const { t } = useTranslation()
|
||||
const { copyToClipboard } = useCopyToClipboard()
|
||||
const tokenUnit = props.tokenUnit ?? DEFAULT_TOKEN_UNIT
|
||||
const priceRate = props.priceRate ?? 1
|
||||
const usdExchangeRate = props.usdExchangeRate ?? 1
|
||||
const showRechargePrice = props.showRechargePrice ?? false
|
||||
const isTokenBased = isTokenBasedModel(props.model)
|
||||
const tokenUnitLabel = tokenUnit === 'K' ? '1K' : '1M'
|
||||
const tags = parseTags(props.model.tags)
|
||||
const groups = props.model.enable_groups || []
|
||||
const endpoints = props.model.supported_endpoint_types || []
|
||||
const modelIconKey = props.model.icon || props.model.vendor_icon
|
||||
const modelIcon = modelIconKey ? getLobeIcon(modelIconKey, 28) : null
|
||||
const initial = props.model.model_name?.charAt(0).toUpperCase() || '?'
|
||||
const isDynamicPricing =
|
||||
props.model.billing_mode === 'tiered_expr' &&
|
||||
Boolean(props.model.billing_expr)
|
||||
const hasCachedPrice = isTokenBased && props.model.cache_ratio != null
|
||||
const dynamicSummary = isDynamicPricing
|
||||
? getDynamicPricingSummary(props.model, {
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
groupRatioMultiplier: getDynamicDisplayGroupRatio(
|
||||
props.model,
|
||||
props.selectedGroup
|
||||
),
|
||||
})
|
||||
: null
|
||||
|
||||
const primaryGroup = groups[0]
|
||||
const bottomTags = [...endpoints.slice(0, 2), ...tags.slice(0, 2)]
|
||||
const hiddenCount =
|
||||
Math.max(groups.length - 1, 0) +
|
||||
Math.max(endpoints.length - 2, 0) +
|
||||
Math.max(tags.length - 2, 0)
|
||||
|
||||
const handleCopy = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
copyToClipboard(props.model.model_name || '')
|
||||
}
|
||||
|
||||
let priceSummary: ReactNode
|
||||
if (dynamicSummary) {
|
||||
if (dynamicSummary.isSpecialExpression) {
|
||||
priceSummary = (
|
||||
<span className='min-w-0'>
|
||||
<span className='text-amber-700 dark:text-amber-300'>
|
||||
{t('Special billing expression')}
|
||||
</span>
|
||||
<code className='text-muted-foreground/70 mt-0.5 line-clamp-1 block font-mono text-[11px] break-all'>
|
||||
{dynamicSummary.rawExpression}
|
||||
</code>
|
||||
</span>
|
||||
)
|
||||
} else if (dynamicSummary.primaryEntries.length > 0) {
|
||||
priceSummary = (
|
||||
<>
|
||||
{dynamicSummary.primaryEntries.map((entry) => (
|
||||
<span
|
||||
key={entry.key}
|
||||
className='text-muted-foreground whitespace-nowrap'
|
||||
>
|
||||
{t(entry.shortLabel)}{' '}
|
||||
<span className='text-foreground font-mono font-semibold'>
|
||||
{entry.formatted}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
priceSummary = (
|
||||
<span className='text-muted-foreground text-sm'>
|
||||
{t('Dynamic Pricing')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
} else if (isTokenBased) {
|
||||
priceSummary = (
|
||||
<>
|
||||
<span className='text-muted-foreground whitespace-nowrap'>
|
||||
{t('Input')}{' '}
|
||||
<span className='text-foreground font-mono font-semibold'>
|
||||
{formatPrice(
|
||||
props.model,
|
||||
'input',
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
props.selectedGroup
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
<span className='text-muted-foreground whitespace-nowrap'>
|
||||
{t('Output')}{' '}
|
||||
<span className='text-foreground font-mono font-semibold'>
|
||||
{formatPrice(
|
||||
props.model,
|
||||
'output',
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
props.selectedGroup
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
{hasCachedPrice && (
|
||||
<span className='text-muted-foreground whitespace-nowrap'>
|
||||
{t('Cached')}{' '}
|
||||
<span className='text-foreground font-mono font-semibold'>
|
||||
{formatPrice(
|
||||
props.model,
|
||||
'cache',
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
props.selectedGroup
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
priceSummary = (
|
||||
<span className='text-muted-foreground whitespace-nowrap'>
|
||||
<span className='text-foreground font-mono font-semibold'>
|
||||
{formatRequestPrice(
|
||||
props.model,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
props.selectedGroup
|
||||
)}
|
||||
</span>{' '}
|
||||
/ {t('request')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group relative flex flex-col rounded-xl border p-3 transition-colors sm:p-5',
|
||||
'hover:bg-muted/20'
|
||||
)}
|
||||
>
|
||||
{/* Header: icon + name + price + actions */}
|
||||
<div className='flex items-start justify-between gap-2.5 sm:gap-3'>
|
||||
<div className='flex min-w-0 items-start gap-2.5 sm:gap-3'>
|
||||
<div className='bg-muted/40 flex size-9 shrink-0 items-center justify-center rounded-lg sm:size-10 sm:rounded-xl'>
|
||||
{modelIcon || (
|
||||
<span className='text-muted-foreground text-sm font-bold'>
|
||||
{initial}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className='min-w-0'>
|
||||
<h3 className='text-foreground truncate font-mono text-[15px] leading-tight font-bold'>
|
||||
{props.model.model_name}
|
||||
</h3>
|
||||
<div className='mt-0.5 flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-sm sm:mt-1 sm:gap-x-3'>
|
||||
{priceSummary}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='flex shrink-0 items-center gap-1.5'>
|
||||
<button
|
||||
type='button'
|
||||
onClick={props.onClick}
|
||||
className='text-muted-foreground hover:text-foreground hover:bg-muted inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs transition-colors sm:px-2.5 sm:py-1.5'
|
||||
>
|
||||
{t('Details')}
|
||||
<ChevronRight className='size-3.5' />
|
||||
</button>
|
||||
<button
|
||||
type='button'
|
||||
onClick={handleCopy}
|
||||
className='text-muted-foreground hover:text-foreground hover:bg-muted rounded-md border p-1.5 transition-colors'
|
||||
title={t('Copy')}
|
||||
>
|
||||
<Copy className='size-3.5' />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className='text-muted-foreground mt-2 line-clamp-1 flex-1 text-[13px] leading-relaxed sm:mt-4 sm:line-clamp-2 sm:min-h-[2.5rem]'>
|
||||
{props.model.description || t('No description available.')}
|
||||
</p>
|
||||
|
||||
{/* Footer: left metadata and right performance summary share row alignment */}
|
||||
<div className='mt-2 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-2 gap-y-1 sm:mt-4'>
|
||||
<div className='flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1'>
|
||||
{primaryGroup && (
|
||||
<span className='text-muted-foreground text-sm font-medium'>
|
||||
{primaryGroup}
|
||||
</span>
|
||||
)}
|
||||
<ModelBillingModeBadge model={props.model} />
|
||||
</div>
|
||||
<ModelPerfBadge perf={props.perf} className='row-span-2 self-start' />
|
||||
|
||||
<div className='flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-0.5 sm:gap-x-3 sm:gap-y-1'>
|
||||
{bottomTags.map((item) => (
|
||||
<span key={item} className='text-muted-foreground/70 text-xs'>
|
||||
{item}
|
||||
</span>
|
||||
))}
|
||||
<span className='text-muted-foreground/50 text-xs'>
|
||||
{tokenUnitLabel}
|
||||
</span>
|
||||
{hiddenCount > 0 && (
|
||||
<span className='text-muted-foreground/40 text-xs'>
|
||||
+{hiddenCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,793 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import {
|
||||
ChevronRight,
|
||||
Gauge,
|
||||
KeyRound,
|
||||
ScrollText,
|
||||
Sigma,
|
||||
Zap,
|
||||
} from 'lucide-react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { BundledLanguage } from 'shiki/bundle/web'
|
||||
|
||||
import {
|
||||
CodeBlock,
|
||||
CodeBlockCopyButton,
|
||||
} from '@/components/ai-elements/code-block'
|
||||
import {
|
||||
StaticDataTable,
|
||||
staticDataTableClassNames as tableStyles,
|
||||
} from '@/components/data-table'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { useStatus } from '@/hooks/use-status'
|
||||
|
||||
import {
|
||||
buildRateLimits,
|
||||
buildSupportedParameters,
|
||||
formatRateLimit,
|
||||
type SupportedParameter,
|
||||
} from '../lib/mock-stats'
|
||||
import { replaceModelInPath } from '../lib/model-helpers'
|
||||
import type { PricingModel } from '../types'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Code-sample registry
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// Each sample is keyed by language and endpoint type. The endpoint type comes
|
||||
// from the model's `supported_endpoint_types`; we render samples only for the
|
||||
// types the model actually supports. This keeps copy-pasted code accurate and
|
||||
// provider-shaped (OpenAI vs Anthropic vs Gemini, etc.).
|
||||
|
||||
type Lang = 'curl' | 'python' | 'typescript' | 'javascript'
|
||||
|
||||
const LANG_LABELS: Record<Lang, string> = {
|
||||
curl: 'cURL',
|
||||
python: 'Python',
|
||||
typescript: 'TypeScript',
|
||||
javascript: 'JavaScript',
|
||||
}
|
||||
|
||||
const LANG_HIGHLIGHT: Record<Lang, BundledLanguage> = {
|
||||
curl: 'bash',
|
||||
python: 'python',
|
||||
typescript: 'typescript',
|
||||
javascript: 'javascript',
|
||||
}
|
||||
|
||||
type SampleContext = {
|
||||
baseUrl: string
|
||||
apiKeyEnv: string
|
||||
modelName: string
|
||||
endpointType: string
|
||||
endpointPath: string
|
||||
}
|
||||
|
||||
function buildChatSample(lang: Lang, ctx: SampleContext): string {
|
||||
const url = `${ctx.baseUrl}${ctx.endpointPath}`
|
||||
const isResponses = ctx.endpointType === 'openai-response'
|
||||
const isReasoning = /^o[1-4]|reasoning|thinking|deepseek-r/i.test(
|
||||
ctx.modelName
|
||||
)
|
||||
const userMessage = 'Explain quantum entanglement in one paragraph.'
|
||||
|
||||
const bodyJson = isResponses
|
||||
? JSON.stringify({ model: ctx.modelName, input: userMessage }, null, 2)
|
||||
: JSON.stringify(
|
||||
{
|
||||
model: ctx.modelName,
|
||||
messages: [{ role: 'user', content: userMessage }],
|
||||
...(isReasoning ? {} : { temperature: 0.7 }),
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
|
||||
const fnCall = isResponses ? 'responses.create' : 'chat.completions.create'
|
||||
|
||||
if (lang === 'curl') {
|
||||
return [
|
||||
`curl ${url} \\`,
|
||||
` -H "Authorization: Bearer $${ctx.apiKeyEnv}" \\`,
|
||||
` -H "Content-Type: application/json" \\`,
|
||||
` -d '${bodyJson.replace(/\n/g, '\n ')}'`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
if (lang === 'python') {
|
||||
return [
|
||||
'from openai import OpenAI',
|
||||
'',
|
||||
'client = OpenAI(',
|
||||
` base_url="${ctx.baseUrl}/v1",`,
|
||||
` api_key="<YOUR_API_KEY>",`,
|
||||
')',
|
||||
'',
|
||||
isResponses
|
||||
? `response = client.${fnCall}(\n model="${ctx.modelName}",\n input="${userMessage}",\n)\n\nprint(response.output_text)`
|
||||
: `completion = client.${fnCall}(\n model="${ctx.modelName}",\n messages=[\n {"role": "user", "content": "${userMessage}"}\n ],\n)\n\nprint(completion.choices[0].message.content)`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
if (lang === 'typescript') {
|
||||
return [
|
||||
`import OpenAI from 'openai'`,
|
||||
'',
|
||||
`const client = new OpenAI({`,
|
||||
` baseURL: '${ctx.baseUrl}/v1',`,
|
||||
` apiKey: process.env.${ctx.apiKeyEnv},`,
|
||||
`})`,
|
||||
'',
|
||||
isResponses
|
||||
? `const response = await client.${fnCall}({\n model: '${ctx.modelName}',\n input: '${userMessage}',\n})\n\nconsole.log(response.output_text)`
|
||||
: `const completion = await client.${fnCall}({\n model: '${ctx.modelName}',\n messages: [{ role: 'user', content: '${userMessage}' }],\n})\n\nconsole.log(completion.choices[0].message.content)`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
return [
|
||||
`const response = await fetch('${url}', {`,
|
||||
` method: 'POST',`,
|
||||
` headers: {`,
|
||||
` Authorization: \`Bearer \${process.env.${ctx.apiKeyEnv}}\`,`,
|
||||
` 'Content-Type': 'application/json',`,
|
||||
` },`,
|
||||
` body: JSON.stringify(${bodyJson}),`,
|
||||
`})`,
|
||||
'',
|
||||
`const data = await response.json()`,
|
||||
`console.log(data)`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildAnthropicSample(lang: Lang, ctx: SampleContext): string {
|
||||
const url = `${ctx.baseUrl}${ctx.endpointPath}`
|
||||
const userMessage = 'Explain quantum entanglement in one paragraph.'
|
||||
|
||||
if (lang === 'curl') {
|
||||
const body = JSON.stringify(
|
||||
{
|
||||
model: ctx.modelName,
|
||||
max_tokens: 1024,
|
||||
messages: [{ role: 'user', content: userMessage }],
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
return [
|
||||
`curl ${url} \\`,
|
||||
` -H "x-api-key: $${ctx.apiKeyEnv}" \\`,
|
||||
` -H "anthropic-version: 2023-06-01" \\`,
|
||||
` -H "Content-Type: application/json" \\`,
|
||||
` -d '${body.replace(/\n/g, '\n ')}'`,
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'python') {
|
||||
return [
|
||||
'import anthropic',
|
||||
'',
|
||||
'client = anthropic.Anthropic(',
|
||||
` base_url="${ctx.baseUrl}",`,
|
||||
` api_key="<YOUR_API_KEY>",`,
|
||||
')',
|
||||
'',
|
||||
`message = client.messages.create(`,
|
||||
` model="${ctx.modelName}",`,
|
||||
` max_tokens=1024,`,
|
||||
` messages=[{"role": "user", "content": "${userMessage}"}],`,
|
||||
')',
|
||||
'',
|
||||
'print(message.content[0].text)',
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'typescript') {
|
||||
return [
|
||||
`import Anthropic from '@anthropic-ai/sdk'`,
|
||||
'',
|
||||
`const client = new Anthropic({`,
|
||||
` baseURL: '${ctx.baseUrl}',`,
|
||||
` apiKey: process.env.${ctx.apiKeyEnv},`,
|
||||
`})`,
|
||||
'',
|
||||
`const message = await client.messages.create({`,
|
||||
` model: '${ctx.modelName}',`,
|
||||
` max_tokens: 1024,`,
|
||||
` messages: [{ role: 'user', content: '${userMessage}' }],`,
|
||||
`})`,
|
||||
'',
|
||||
`console.log(message.content[0].text)`,
|
||||
].join('\n')
|
||||
}
|
||||
return [
|
||||
`const response = await fetch('${url}', {`,
|
||||
` method: 'POST',`,
|
||||
` headers: {`,
|
||||
` 'x-api-key': process.env.${ctx.apiKeyEnv},`,
|
||||
` 'anthropic-version': '2023-06-01',`,
|
||||
` 'Content-Type': 'application/json',`,
|
||||
` },`,
|
||||
` body: JSON.stringify({`,
|
||||
` model: '${ctx.modelName}',`,
|
||||
` max_tokens: 1024,`,
|
||||
` messages: [{ role: 'user', content: '${userMessage}' }],`,
|
||||
` }),`,
|
||||
`})`,
|
||||
'',
|
||||
`const data = await response.json()`,
|
||||
`console.log(data.content[0].text)`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildGeminiSample(lang: Lang, ctx: SampleContext): string {
|
||||
const url = `${ctx.baseUrl}${ctx.endpointPath}?key=$${ctx.apiKeyEnv}`
|
||||
const userMessage = 'Explain quantum entanglement in one paragraph.'
|
||||
|
||||
if (lang === 'curl') {
|
||||
const body = JSON.stringify(
|
||||
{ contents: [{ parts: [{ text: userMessage }] }] },
|
||||
null,
|
||||
2
|
||||
)
|
||||
return [
|
||||
`curl '${url}' \\`,
|
||||
` -H 'Content-Type: application/json' \\`,
|
||||
` -d '${body.replace(/\n/g, '\n ')}'`,
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'python') {
|
||||
return [
|
||||
'import google.generativeai as genai',
|
||||
'',
|
||||
`genai.configure(api_key="<YOUR_API_KEY>")`,
|
||||
'',
|
||||
`model = genai.GenerativeModel("${ctx.modelName}")`,
|
||||
`response = model.generate_content("${userMessage}")`,
|
||||
'',
|
||||
`print(response.text)`,
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'typescript') {
|
||||
return [
|
||||
`import { GoogleGenerativeAI } from '@google/generative-ai'`,
|
||||
'',
|
||||
`const genAI = new GoogleGenerativeAI(process.env.${ctx.apiKeyEnv}!)`,
|
||||
`const model = genAI.getGenerativeModel({ model: '${ctx.modelName}' })`,
|
||||
'',
|
||||
`const result = await model.generateContent('${userMessage}')`,
|
||||
`console.log(result.response.text())`,
|
||||
].join('\n')
|
||||
}
|
||||
return [
|
||||
`const response = await fetch('${url}', {`,
|
||||
` method: 'POST',`,
|
||||
` headers: { 'Content-Type': 'application/json' },`,
|
||||
` body: JSON.stringify({`,
|
||||
` contents: [{ parts: [{ text: '${userMessage}' }] }],`,
|
||||
` }),`,
|
||||
`})`,
|
||||
'',
|
||||
`const data = await response.json()`,
|
||||
`console.log(data.candidates[0].content.parts[0].text)`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildEmbeddingSample(lang: Lang, ctx: SampleContext): string {
|
||||
const url = `${ctx.baseUrl}${ctx.endpointPath}`
|
||||
const text = 'The food was delicious and the waiter…'
|
||||
|
||||
if (lang === 'curl') {
|
||||
const body = JSON.stringify({ model: ctx.modelName, input: text }, null, 2)
|
||||
return [
|
||||
`curl ${url} \\`,
|
||||
` -H "Authorization: Bearer $${ctx.apiKeyEnv}" \\`,
|
||||
` -H "Content-Type: application/json" \\`,
|
||||
` -d '${body.replace(/\n/g, '\n ')}'`,
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'python') {
|
||||
return [
|
||||
'from openai import OpenAI',
|
||||
'',
|
||||
`client = OpenAI(base_url="${ctx.baseUrl}/v1", api_key="<YOUR_API_KEY>")`,
|
||||
'',
|
||||
'response = client.embeddings.create(',
|
||||
` model="${ctx.modelName}",`,
|
||||
` input="${text}",`,
|
||||
')',
|
||||
'',
|
||||
'print(response.data[0].embedding[:8])',
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'typescript') {
|
||||
return [
|
||||
`import OpenAI from 'openai'`,
|
||||
'',
|
||||
`const client = new OpenAI({`,
|
||||
` baseURL: '${ctx.baseUrl}/v1',`,
|
||||
` apiKey: process.env.${ctx.apiKeyEnv},`,
|
||||
`})`,
|
||||
'',
|
||||
`const response = await client.embeddings.create({`,
|
||||
` model: '${ctx.modelName}',`,
|
||||
` input: '${text}',`,
|
||||
`})`,
|
||||
'',
|
||||
`console.log(response.data[0].embedding.slice(0, 8))`,
|
||||
].join('\n')
|
||||
}
|
||||
return [
|
||||
`const response = await fetch('${url}', {`,
|
||||
` method: 'POST',`,
|
||||
` headers: {`,
|
||||
` Authorization: \`Bearer \${process.env.${ctx.apiKeyEnv}}\`,`,
|
||||
` 'Content-Type': 'application/json',`,
|
||||
` },`,
|
||||
` body: JSON.stringify({`,
|
||||
` model: '${ctx.modelName}',`,
|
||||
` input: '${text}',`,
|
||||
` }),`,
|
||||
`})`,
|
||||
'',
|
||||
`const data = await response.json()`,
|
||||
`console.log(data.data[0].embedding.slice(0, 8))`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildImageSample(lang: Lang, ctx: SampleContext): string {
|
||||
const url = `${ctx.baseUrl}${ctx.endpointPath}`
|
||||
const prompt = 'A serene koi pond at sunset, ukiyo-e style.'
|
||||
|
||||
if (lang === 'curl') {
|
||||
const body = JSON.stringify(
|
||||
{ model: ctx.modelName, prompt, size: '1024x1024', n: 1 },
|
||||
null,
|
||||
2
|
||||
)
|
||||
return [
|
||||
`curl ${url} \\`,
|
||||
` -H "Authorization: Bearer $${ctx.apiKeyEnv}" \\`,
|
||||
` -H "Content-Type: application/json" \\`,
|
||||
` -d '${body.replace(/\n/g, '\n ')}'`,
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'python') {
|
||||
return [
|
||||
'from openai import OpenAI',
|
||||
'',
|
||||
`client = OpenAI(base_url="${ctx.baseUrl}/v1", api_key="<YOUR_API_KEY>")`,
|
||||
'',
|
||||
'response = client.images.generate(',
|
||||
` model="${ctx.modelName}",`,
|
||||
` prompt="${prompt}",`,
|
||||
` size="1024x1024",`,
|
||||
` n=1,`,
|
||||
')',
|
||||
'',
|
||||
'print(response.data[0].url)',
|
||||
].join('\n')
|
||||
}
|
||||
if (lang === 'typescript') {
|
||||
return [
|
||||
`import OpenAI from 'openai'`,
|
||||
'',
|
||||
`const client = new OpenAI({`,
|
||||
` baseURL: '${ctx.baseUrl}/v1',`,
|
||||
` apiKey: process.env.${ctx.apiKeyEnv},`,
|
||||
`})`,
|
||||
'',
|
||||
`const response = await client.images.generate({`,
|
||||
` model: '${ctx.modelName}',`,
|
||||
` prompt: '${prompt}',`,
|
||||
` size: '1024x1024',`,
|
||||
` n: 1,`,
|
||||
`})`,
|
||||
'',
|
||||
`console.log(response.data[0].url)`,
|
||||
].join('\n')
|
||||
}
|
||||
return [
|
||||
`const response = await fetch('${url}', {`,
|
||||
` method: 'POST',`,
|
||||
` headers: {`,
|
||||
` Authorization: \`Bearer \${process.env.${ctx.apiKeyEnv}}\`,`,
|
||||
` 'Content-Type': 'application/json',`,
|
||||
` },`,
|
||||
` body: JSON.stringify({`,
|
||||
` model: '${ctx.modelName}',`,
|
||||
` prompt: '${prompt}',`,
|
||||
` size: '1024x1024',`,
|
||||
` n: 1,`,
|
||||
` }),`,
|
||||
`})`,
|
||||
'',
|
||||
`const data = await response.json()`,
|
||||
`console.log(data.data[0].url)`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function buildSample(
|
||||
lang: Lang,
|
||||
endpointType: string,
|
||||
ctx: SampleContext
|
||||
): string {
|
||||
if (endpointType === 'anthropic') return buildAnthropicSample(lang, ctx)
|
||||
if (endpointType === 'gemini') return buildGeminiSample(lang, ctx)
|
||||
if (endpointType === 'embeddings' || endpointType === 'jina-rerank')
|
||||
return buildEmbeddingSample(lang, ctx)
|
||||
if (endpointType === 'image-generation') return buildImageSample(lang, ctx)
|
||||
return buildChatSample(lang, ctx)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Code samples section
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function CodeSamplesSection(props: {
|
||||
model: PricingModel
|
||||
endpointMap: Record<string, { path?: string; method?: string }>
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { status } = useStatus()
|
||||
|
||||
const baseUrl = useMemo(() => {
|
||||
const candidate =
|
||||
(status as Record<string, unknown> | null)?.server_address ??
|
||||
(status as Record<string, unknown> | null)?.serverAddress ??
|
||||
(status?.data as Record<string, unknown> | undefined)?.server_address ??
|
||||
(status?.data as Record<string, unknown> | undefined)?.serverAddress
|
||||
if (candidate && typeof candidate === 'string') {
|
||||
return candidate.replace(/\/$/, '')
|
||||
}
|
||||
if (typeof window !== 'undefined') return window.location.origin
|
||||
return 'https://api.example.com'
|
||||
}, [status])
|
||||
|
||||
const endpoints = useMemo(() => {
|
||||
const types = props.model.supported_endpoint_types || []
|
||||
return types
|
||||
.map((type) => {
|
||||
const info = props.endpointMap[type] || {}
|
||||
let path = info.path || ''
|
||||
if (path && path.includes('{model}')) {
|
||||
path = replaceModelInPath(path, props.model.model_name || '')
|
||||
}
|
||||
return { type, path, method: info.method || 'POST' }
|
||||
})
|
||||
.filter((e) => Boolean(e.path))
|
||||
}, [props.model, props.endpointMap])
|
||||
|
||||
const [endpointType, setEndpointType] = useState<string>(
|
||||
endpoints[0]?.type ?? ''
|
||||
)
|
||||
const [lang, setLang] = useState<Lang>('curl')
|
||||
|
||||
const activeEndpoint = useMemo(() => {
|
||||
return endpoints.find((e) => e.type === endpointType) ?? endpoints[0]
|
||||
}, [endpointType, endpoints])
|
||||
|
||||
if (endpoints.length === 0 || !activeEndpoint) {
|
||||
return null
|
||||
}
|
||||
|
||||
const code = buildSample(lang, activeEndpoint.type, {
|
||||
baseUrl,
|
||||
apiKeyEnv: 'NEW_API_KEY',
|
||||
modelName: props.model.model_name || '',
|
||||
endpointType: activeEndpoint.type,
|
||||
endpointPath: activeEndpoint.path,
|
||||
})
|
||||
|
||||
return (
|
||||
<section>
|
||||
<SectionTitle icon={ScrollText}>{t('Code samples')}</SectionTitle>
|
||||
|
||||
<div className='flex flex-wrap items-center gap-2'>
|
||||
{endpoints.length > 1 && (
|
||||
<Tabs value={endpointType} onValueChange={setEndpointType}>
|
||||
<TabsList className='bg-muted/40 h-8 p-0.5'>
|
||||
{endpoints.map((ep) => (
|
||||
<TabsTrigger
|
||||
key={ep.type}
|
||||
value={ep.type}
|
||||
className='h-7 px-2.5 text-xs'
|
||||
>
|
||||
{ep.type}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
<Tabs
|
||||
value={lang}
|
||||
onValueChange={(v) => setLang(v as Lang)}
|
||||
className='ml-auto'
|
||||
>
|
||||
<TabsList className='bg-muted/40 h-8 p-0.5'>
|
||||
{(Object.keys(LANG_LABELS) as Lang[]).map((l) => (
|
||||
<TabsTrigger key={l} value={l} className='h-7 px-2.5 text-xs'>
|
||||
{LANG_LABELS[l]}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<div className='mt-3'>
|
||||
<CodeBlock code={code} language={LANG_HIGHLIGHT[lang]}>
|
||||
<CodeBlockCopyButton />
|
||||
</CodeBlock>
|
||||
</div>
|
||||
|
||||
<p className='text-muted-foreground mt-2 text-xs'>
|
||||
{t('Replace')}{' '}
|
||||
<code className='bg-muted rounded px-1 py-0.5 font-mono text-[11px]'>
|
||||
{'<YOUR_API_KEY>'}
|
||||
</code>{' '}
|
||||
{t('with the API key from your token settings.')}
|
||||
</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Supported parameters table
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function SupportedParametersSection(props: { model: PricingModel }) {
|
||||
const { t } = useTranslation()
|
||||
const params = useMemo(
|
||||
() => buildSupportedParameters(props.model),
|
||||
[props.model]
|
||||
)
|
||||
|
||||
if (params.length === 0) return null
|
||||
|
||||
return (
|
||||
<section>
|
||||
<SectionTitle icon={Sigma}>{t('Supported parameters')}</SectionTitle>
|
||||
<StaticDataTable
|
||||
className={tableStyles.sectionContainer}
|
||||
headerRowClassName={tableStyles.mutedHeaderRow}
|
||||
data={params}
|
||||
getRowKey={(param) => param.name}
|
||||
getRowClassName={() => 'hover:bg-muted/20'}
|
||||
columns={[
|
||||
{
|
||||
id: 'parameter',
|
||||
header: t('Parameter'),
|
||||
className: 'h-9 w-44',
|
||||
cellClassName: tableStyles.topCell,
|
||||
cell: (p) => (
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<code className='font-mono text-sm font-medium'>{p.name}</code>
|
||||
{p.required && (
|
||||
<Badge
|
||||
variant='outline'
|
||||
className='h-6 border-rose-500/40 px-2 text-sm text-rose-600 dark:text-rose-400'
|
||||
>
|
||||
{t('required')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'type',
|
||||
header: t('Type'),
|
||||
className: 'h-9 w-24',
|
||||
cellClassName: tableStyles.topCell,
|
||||
cell: (p) => (
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='h-7 rounded-full px-2.5 font-mono text-sm font-normal'
|
||||
>
|
||||
{p.type}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'range',
|
||||
header: t('Default / range'),
|
||||
className: 'h-9 w-32',
|
||||
cellClassName: tableStyles.topCell,
|
||||
cell: (p) => <ParamRangeCell param={p} />,
|
||||
},
|
||||
{
|
||||
id: 'description',
|
||||
header: t('Description'),
|
||||
className: 'h-9',
|
||||
cellClassName: tableStyles.topMutedCell,
|
||||
cell: (p) => t(p.descriptionKey),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function ParamRangeCell(props: { param: SupportedParameter }) {
|
||||
const { defaultValue, range, enumValues } = props.param
|
||||
if (defaultValue !== undefined) {
|
||||
return (
|
||||
<div className='flex flex-wrap items-center gap-1'>
|
||||
<span className='text-muted-foreground text-sm'>=</span>
|
||||
<code className='bg-muted rounded px-1.5 py-0.5 font-mono text-sm'>
|
||||
{String(defaultValue)}
|
||||
</code>
|
||||
{range && (
|
||||
<span className='text-muted-foreground text-sm'>{range}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (range) {
|
||||
return (
|
||||
<span className='text-muted-foreground font-mono text-sm'>{range}</span>
|
||||
)
|
||||
}
|
||||
if (enumValues && enumValues.length > 0) {
|
||||
return (
|
||||
<div className='flex flex-wrap gap-0.5'>
|
||||
{enumValues.map((v) => (
|
||||
<code
|
||||
key={v}
|
||||
className='bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-sm'
|
||||
>
|
||||
{v}
|
||||
</code>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return <span className='text-muted-foreground/60 text-sm'>—</span>
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rate-limits table
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function RateLimitsSection(props: { model: PricingModel }) {
|
||||
const { t } = useTranslation()
|
||||
const limits = useMemo(() => buildRateLimits(props.model), [props.model])
|
||||
|
||||
if (limits.length === 0) return null
|
||||
|
||||
return (
|
||||
<section>
|
||||
<SectionTitle icon={Gauge}>{t('Rate limits')}</SectionTitle>
|
||||
<StaticDataTable
|
||||
className={tableStyles.sectionContainer}
|
||||
headerRowClassName={tableStyles.mutedHeaderRow}
|
||||
data={limits}
|
||||
getRowKey={(limit) => limit.group}
|
||||
getRowClassName={() => 'hover:bg-muted/20'}
|
||||
columns={[
|
||||
{
|
||||
id: 'group',
|
||||
header: t('Group'),
|
||||
className: 'h-9',
|
||||
cellClassName: 'py-2 font-mono',
|
||||
cell: (limit) => limit.group,
|
||||
},
|
||||
{
|
||||
id: 'rpm',
|
||||
header: 'RPM',
|
||||
className: 'h-9 text-right',
|
||||
cellClassName: tableStyles.topNumericCell,
|
||||
cell: (limit) => formatRateLimit(limit.rpm),
|
||||
},
|
||||
{
|
||||
id: 'tpm',
|
||||
header: 'TPM',
|
||||
className: 'h-9 text-right',
|
||||
cellClassName: tableStyles.topNumericCell,
|
||||
cell: (limit) => formatRateLimit(limit.tpm),
|
||||
},
|
||||
{
|
||||
id: 'rpd',
|
||||
header: 'RPD',
|
||||
className: 'h-9 text-right',
|
||||
cellClassName: tableStyles.topNumericCell,
|
||||
cell: (limit) => formatRateLimit(limit.rpd),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<p className='text-muted-foreground mt-2 text-[11px] leading-relaxed'>
|
||||
{t(
|
||||
'RPM = requests per minute, TPM = tokens per minute, RPD = requests per day. Limits apply per token group.'
|
||||
)}
|
||||
</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Authentication preview
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function AuthSection() {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<section>
|
||||
<SectionTitle icon={KeyRound}>{t('Authentication')}</SectionTitle>
|
||||
<div className='border-border/60 bg-muted/20 flex items-start gap-2 rounded-lg border p-3'>
|
||||
<ChevronRight className='text-muted-foreground mt-0.5 size-3.5 shrink-0' />
|
||||
<div className='space-y-1.5 text-xs leading-relaxed'>
|
||||
<p>
|
||||
{t('All requests must include')}{' '}
|
||||
<code className='bg-muted rounded px-1 py-0.5 font-mono text-[11px]'>
|
||||
Authorization: Bearer <TOKEN>
|
||||
</code>{' '}
|
||||
{t('header. Anthropic-formatted endpoints accept the')}{' '}
|
||||
<code className='bg-muted rounded px-1 py-0.5 font-mono text-[11px]'>
|
||||
x-api-key
|
||||
</code>{' '}
|
||||
{t('header instead.')}
|
||||
</p>
|
||||
<p className='text-muted-foreground'>
|
||||
{t(
|
||||
'Generate tokens from the Tokens page; you can scope them to specific models, groups, IPs, and rate-limits.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Composite API tab
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function ModelDetailsApi(props: {
|
||||
model: PricingModel
|
||||
endpointMap: Record<string, { path?: string; method?: string }>
|
||||
}) {
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
<CodeSamplesSection model={props.model} endpointMap={props.endpointMap} />
|
||||
<AuthSection />
|
||||
<SupportedParametersSection model={props.model} />
|
||||
<RateLimitsSection model={props.model} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Local UI helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function SectionTitle(props: {
|
||||
children: React.ReactNode
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
}) {
|
||||
const Icon = props.icon
|
||||
return (
|
||||
<h3 className='text-foreground mb-3 flex items-center gap-1.5 text-sm font-semibold'>
|
||||
<Icon className='text-muted-foreground/70 size-3.5' />
|
||||
{props.children}
|
||||
</h3>
|
||||
)
|
||||
}
|
||||
|
||||
// Re-export so the parent can keep its own SectionTitle if it wants:
|
||||
export { Zap as ApiTabIcon }
|
||||
@@ -0,0 +1,235 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import {
|
||||
ArrowDownRight,
|
||||
ArrowUpRight,
|
||||
ExternalLink,
|
||||
Trophy,
|
||||
} from 'lucide-react'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
StaticDataTable,
|
||||
staticDataTableClassNames as tableStyles,
|
||||
} from '@/components/data-table'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import {
|
||||
buildAppRankings,
|
||||
formatTokenVolume,
|
||||
type AppRanking,
|
||||
} from '../lib/mock-stats'
|
||||
import type { PricingModel } from '../types'
|
||||
|
||||
const COMPACT_NUMBER = new Intl.NumberFormat(undefined, {
|
||||
notation: 'compact',
|
||||
maximumFractionDigits: 1,
|
||||
})
|
||||
|
||||
function RankBadge(props: { rank: number }) {
|
||||
const rank = props.rank
|
||||
const isPodium = rank <= 3
|
||||
const palette =
|
||||
rank === 1
|
||||
? 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300'
|
||||
: rank === 2
|
||||
? 'bg-slate-100 text-slate-700 dark:bg-slate-500/20 dark:text-slate-300'
|
||||
: rank === 3
|
||||
? 'bg-orange-100 text-orange-700 dark:bg-orange-500/20 dark:text-orange-300'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex size-7 shrink-0 items-center justify-center rounded-md font-mono text-xs font-bold tabular-nums',
|
||||
palette
|
||||
)}
|
||||
>
|
||||
{isPodium ? <Trophy className='size-3.5' /> : rank}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function GrowthChip(props: { value: number }) {
|
||||
const value = props.value
|
||||
const isUp = value > 0
|
||||
const isDown = value < 0
|
||||
const palette = isUp
|
||||
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'
|
||||
: isDown
|
||||
? 'bg-rose-100 text-rose-700 dark:bg-rose-500/20 dark:text-rose-300'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
const Icon = isUp ? ArrowUpRight : isDown ? ArrowDownRight : null
|
||||
const formatted = `${value > 0 ? '+' : ''}${value.toFixed(1)}%`
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 font-mono text-[11px] font-semibold tabular-nums',
|
||||
palette
|
||||
)}
|
||||
>
|
||||
{Icon && <Icon className='size-3' />}
|
||||
{formatted}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function AppLink(props: { app: AppRanking }) {
|
||||
if (!props.app.url) {
|
||||
return <span className='text-foreground'>{props.app.name}</span>
|
||||
}
|
||||
return (
|
||||
<a
|
||||
href={props.app.url}
|
||||
target='_blank'
|
||||
rel='noreferrer'
|
||||
className='text-foreground hover:text-primary inline-flex items-center gap-1 transition-colors'
|
||||
>
|
||||
{props.app.name}
|
||||
<ExternalLink className='text-muted-foreground/40 size-3' />
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
export function ModelDetailsApps(props: { model: PricingModel }) {
|
||||
const { t } = useTranslation()
|
||||
const apps = useMemo(() => buildAppRankings(props.model, 12), [props.model])
|
||||
|
||||
if (apps.length === 0) {
|
||||
return (
|
||||
<div className='text-muted-foreground rounded-lg border p-6 text-center text-sm'>
|
||||
{t('No app usage data available for this model.')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const totalMonthlyTokens = apps.reduce((s, a) => s + a.monthly_tokens, 0)
|
||||
const top = apps[0]
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='grid grid-cols-1 gap-2 sm:grid-cols-3'>
|
||||
<div className='bg-muted/20 rounded-lg border p-3'>
|
||||
<div className='text-muted-foreground text-[10px] font-medium tracking-wider uppercase'>
|
||||
{t('Tracked apps')}
|
||||
</div>
|
||||
<div className='text-foreground mt-1 font-mono text-lg font-semibold tabular-nums'>
|
||||
{apps.length}
|
||||
</div>
|
||||
<p className='text-muted-foreground/70 text-[11px]'>
|
||||
{t('Top integrations using this model')}
|
||||
</p>
|
||||
</div>
|
||||
<div className='bg-muted/20 rounded-lg border p-3'>
|
||||
<div className='text-muted-foreground text-[10px] font-medium tracking-wider uppercase'>
|
||||
{t('Monthly tokens')}
|
||||
</div>
|
||||
<div className='text-foreground mt-1 font-mono text-lg font-semibold tabular-nums'>
|
||||
{COMPACT_NUMBER.format(totalMonthlyTokens)}
|
||||
</div>
|
||||
<p className='text-muted-foreground/70 text-[11px]'>
|
||||
{t('Aggregated across the apps below')}
|
||||
</p>
|
||||
</div>
|
||||
<div className='bg-muted/20 rounded-lg border p-3'>
|
||||
<div className='text-muted-foreground text-[10px] font-medium tracking-wider uppercase'>
|
||||
{t('#1 by usage')}
|
||||
</div>
|
||||
<div className='text-foreground mt-1 truncate text-base font-semibold'>
|
||||
{top.name}
|
||||
</div>
|
||||
<p className='text-muted-foreground/70 truncate text-[11px]'>
|
||||
{top.category} · {formatTokenVolume(top.monthly_tokens)}{' '}
|
||||
{t('tokens / mo')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<StaticDataTable
|
||||
className='rounded-lg'
|
||||
tableClassName='text-sm'
|
||||
headerRowClassName={tableStyles.compactHeaderRow}
|
||||
data={apps}
|
||||
getRowKey={(app) => `${app.rank}-${app.name}`}
|
||||
columns={[
|
||||
{
|
||||
id: 'rank',
|
||||
header: '#',
|
||||
className: cn(tableStyles.compactHeaderCell, 'w-12'),
|
||||
cellClassName: tableStyles.compactCell,
|
||||
cell: (app) => <RankBadge rank={app.rank} />,
|
||||
},
|
||||
{
|
||||
id: 'app',
|
||||
header: t('App'),
|
||||
className: tableStyles.compactHeaderCell,
|
||||
cellClassName: tableStyles.compactCell,
|
||||
cell: (app) => (
|
||||
<div className='flex items-center gap-3'>
|
||||
<span className='bg-muted text-muted-foreground inline-flex size-7 shrink-0 items-center justify-center rounded-md font-bold'>
|
||||
{app.initial}
|
||||
</span>
|
||||
<div className='min-w-0'>
|
||||
<div className='text-sm font-medium'>
|
||||
<AppLink app={app} />
|
||||
</div>
|
||||
<p className='text-muted-foreground line-clamp-1 text-sm'>
|
||||
{app.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'category',
|
||||
header: t('Category'),
|
||||
className: cn(
|
||||
tableStyles.compactHeaderCell,
|
||||
'hidden md:table-cell'
|
||||
),
|
||||
cellClassName: cn(
|
||||
tableStyles.compactMutedCell,
|
||||
'hidden md:table-cell'
|
||||
),
|
||||
cell: (app) => app.category,
|
||||
},
|
||||
{
|
||||
id: 'monthly-tokens',
|
||||
header: t('Monthly tokens'),
|
||||
className: tableStyles.compactHeaderCellRight,
|
||||
cellClassName: cn(tableStyles.compactNumericCell, 'tabular-nums'),
|
||||
cell: (app) => formatTokenVolume(app.monthly_tokens),
|
||||
},
|
||||
{
|
||||
id: 'growth',
|
||||
header: t('30d change'),
|
||||
className: tableStyles.compactHeaderCellRight,
|
||||
cellClassName: cn(tableStyles.compactCell, 'text-right'),
|
||||
cell: (app) => <GrowthChip value={app.growth_pct} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<p className='text-muted-foreground/60 text-[11px] leading-relaxed'>
|
||||
{t(
|
||||
'App rankings shown here are simulated for preview purposes and will be replaced with live usage data once the backend integration is complete.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { VChart } from '@visactor/react-vchart'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { useThemeCustomization } from '@/context/theme-customization-provider'
|
||||
import { getSuccessRateColor } from '@/features/performance-metrics/lib/format'
|
||||
import { useThemeRadiusPx } from '@/lib/theme-radius'
|
||||
import { useChartTheme } from '@/lib/use-chart-theme'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { VCHART_OPTION } from '@/lib/vchart'
|
||||
|
||||
import type { LatencyTimePoint, UptimeDayPoint } from '../lib/mock-stats'
|
||||
|
||||
function formatHourLabel(iso: string): string {
|
||||
const date = new Date(iso)
|
||||
const hours = date.getHours()
|
||||
return `${String(hours).padStart(2, '0')}:00`
|
||||
}
|
||||
|
||||
function formatDayLabel(date: string): string {
|
||||
const parsed = new Date(date)
|
||||
if (date.includes('T')) {
|
||||
return parsed.toLocaleString(undefined, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
})
|
||||
}
|
||||
return parsed.toLocaleDateString(undefined, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})
|
||||
}
|
||||
|
||||
function getChartThemeTokens(resolvedTheme: string) {
|
||||
return {
|
||||
textColor:
|
||||
resolvedTheme === 'dark'
|
||||
? 'rgba(255, 255, 255, 0.68)'
|
||||
: 'rgba(15, 23, 42, 0.58)',
|
||||
gridColor:
|
||||
resolvedTheme === 'dark'
|
||||
? 'rgba(255, 255, 255, 0.12)'
|
||||
: 'rgba(15, 23, 42, 0.12)',
|
||||
}
|
||||
}
|
||||
|
||||
const UPTIME_AXIS_MAX = 100
|
||||
const UPTIME_FOCUSED_AXIS_MIN = 95
|
||||
const UPTIME_MINOR_OUTAGE_AXIS_MIN = 90
|
||||
|
||||
function toUptimeChartValue(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0
|
||||
return Math.min(UPTIME_AXIS_MAX, Math.max(0, value))
|
||||
}
|
||||
|
||||
function getUptimeAxisMin(values: number[]): number {
|
||||
const finiteValues = values.filter((value) => Number.isFinite(value))
|
||||
if (finiteValues.length === 0) return UPTIME_FOCUSED_AXIS_MIN
|
||||
|
||||
const minValue = Math.max(0, Math.min(...finiteValues))
|
||||
if (minValue >= UPTIME_FOCUSED_AXIS_MIN) return UPTIME_FOCUSED_AXIS_MIN
|
||||
if (minValue >= UPTIME_MINOR_OUTAGE_AXIS_MIN) {
|
||||
return UPTIME_MINOR_OUTAGE_AXIS_MIN
|
||||
}
|
||||
|
||||
return Math.max(0, Math.floor((minValue - 5) / 10) * 10)
|
||||
}
|
||||
|
||||
function stripUptimePointSuffix(value: string): string {
|
||||
return value.replace(/__(start|end)$/, '')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Latency trend chart (24h, multi-group point-line chart)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function LatencyTrendChart(props: {
|
||||
series: LatencyTimePoint[]
|
||||
className?: string
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { resolvedTheme, themeReady } = useChartTheme()
|
||||
const { textColor, gridColor } = getChartThemeTokens(resolvedTheme)
|
||||
|
||||
const spec = useMemo(() => {
|
||||
if (props.series.length === 0) return null
|
||||
const data = props.series.map((point) => ({
|
||||
time: formatHourLabel(point.timestamp),
|
||||
group: point.group,
|
||||
ttft: point.ttft_ms,
|
||||
}))
|
||||
return {
|
||||
type: 'line' as const,
|
||||
data: [{ id: 'latency', values: data }],
|
||||
xField: 'time',
|
||||
yField: 'ttft',
|
||||
seriesField: 'group',
|
||||
smooth: true,
|
||||
point: {
|
||||
visible: true,
|
||||
style: { size: 5, stroke: '#ffffff', lineWidth: 1.5 },
|
||||
},
|
||||
line: {
|
||||
style: { lineWidth: 2 },
|
||||
},
|
||||
legends: { visible: false },
|
||||
tooltip: {
|
||||
mark: {
|
||||
title: { value: (d: { time: string }) => d.time },
|
||||
content: [
|
||||
{
|
||||
key: t('Average TTFT'),
|
||||
value: (d: { ttft: number }) => `${Math.round(d.ttft)} ms`,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
axes: [
|
||||
{
|
||||
orient: 'bottom',
|
||||
label: {
|
||||
style: { fill: textColor, fontSize: 10 },
|
||||
},
|
||||
tick: { visible: false },
|
||||
},
|
||||
{
|
||||
orient: 'left',
|
||||
label: {
|
||||
formatMethod: (val: number | string) => `${val} ms`,
|
||||
style: { fill: textColor, fontSize: 10 },
|
||||
},
|
||||
grid: {
|
||||
visible: true,
|
||||
style: { lineDash: [3, 3], stroke: gridColor },
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}, [gridColor, props.series, t, textColor])
|
||||
|
||||
if (props.series.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'text-muted-foreground flex h-48 items-center justify-center rounded-lg border text-xs',
|
||||
props.className
|
||||
)}
|
||||
>
|
||||
{t('No latency data available')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('h-64 sm:h-72', props.className)}>
|
||||
{themeReady && spec && (
|
||||
<VChart
|
||||
key={`latency-${resolvedTheme}`}
|
||||
spec={{
|
||||
...spec,
|
||||
theme: resolvedTheme === 'dark' ? 'dark' : 'light',
|
||||
background: 'transparent',
|
||||
}}
|
||||
option={VCHART_OPTION}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Uptime trend chart (24h, point-line chart)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function UptimeTrendChart(props: {
|
||||
series: UptimeDayPoint[]
|
||||
className?: string
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { resolvedTheme, themeReady } = useChartTheme()
|
||||
const { textColor, gridColor } = getChartThemeTokens(resolvedTheme)
|
||||
|
||||
const spec = useMemo(() => {
|
||||
if (props.series.length === 0) return null
|
||||
|
||||
const rawData = props.series.map((point) => ({
|
||||
date: formatDayLabel(point.date),
|
||||
uptime: toUptimeChartValue(point.uptime_pct),
|
||||
incidents: point.incidents,
|
||||
outage: point.outage_minutes,
|
||||
}))
|
||||
const data =
|
||||
rawData.length === 1
|
||||
? [
|
||||
{ ...rawData[0], date: `${rawData[0].date}__start` },
|
||||
{ ...rawData[0], date: `${rawData[0].date}__end` },
|
||||
]
|
||||
: rawData
|
||||
const axisMin = getUptimeAxisMin(rawData.map((point) => point.uptime))
|
||||
|
||||
return {
|
||||
type: 'line' as const,
|
||||
data: [{ id: 'uptime', values: data }],
|
||||
xField: 'date',
|
||||
yField: 'uptime',
|
||||
smooth: true,
|
||||
line: {
|
||||
style: { stroke: '#10b981', lineWidth: 2 },
|
||||
},
|
||||
point: {
|
||||
visible: true,
|
||||
style: {
|
||||
size: 5,
|
||||
stroke: '#ffffff',
|
||||
lineWidth: 1.5,
|
||||
fill: (datum: { uptime: number }) =>
|
||||
getSuccessRateColor(datum.uptime),
|
||||
},
|
||||
},
|
||||
tooltip: {
|
||||
mark: {
|
||||
title: {
|
||||
value: (d: { date: string }) => stripUptimePointSuffix(d.date),
|
||||
},
|
||||
content: [
|
||||
{
|
||||
key: t('Uptime'),
|
||||
value: (d: { uptime: number }) => `${d.uptime.toFixed(2)}%`,
|
||||
},
|
||||
{
|
||||
key: t('Incidents'),
|
||||
value: (d: { incidents: number }) => `${d.incidents}`,
|
||||
},
|
||||
{
|
||||
key: t('Outage'),
|
||||
value: (d: { outage: number }) => `${d.outage} ${t('minutes')}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
axes: [
|
||||
{
|
||||
orient: 'bottom',
|
||||
label: {
|
||||
formatMethod: (val: number | string) =>
|
||||
stripUptimePointSuffix(String(val)),
|
||||
style: { fill: textColor, fontSize: 10 },
|
||||
autoLimit: true,
|
||||
},
|
||||
tick: { visible: false },
|
||||
},
|
||||
{
|
||||
orient: 'left',
|
||||
min: axisMin,
|
||||
max: UPTIME_AXIS_MAX,
|
||||
label: {
|
||||
formatMethod: (val: number | string) => `${val}%`,
|
||||
style: { fill: textColor, fontSize: 10 },
|
||||
},
|
||||
grid: {
|
||||
visible: true,
|
||||
style: { lineDash: [3, 3], stroke: gridColor },
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}, [gridColor, props.series, t, textColor])
|
||||
|
||||
if (props.series.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'text-muted-foreground flex h-48 items-center justify-center rounded-lg border text-xs',
|
||||
props.className
|
||||
)}
|
||||
>
|
||||
{t('No uptime data available')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('h-56 sm:h-64', props.className)}>
|
||||
{themeReady && spec && (
|
||||
<VChart
|
||||
key={`uptime-trend-${resolvedTheme}`}
|
||||
spec={{
|
||||
...spec,
|
||||
theme: resolvedTheme === 'dark' ? 'dark' : 'light',
|
||||
background: 'transparent',
|
||||
}}
|
||||
option={VCHART_OPTION}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Throughput by group (horizontal bar)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function ThroughputBarChart(props: {
|
||||
rows: { group: string; throughput_tps: number }[]
|
||||
className?: string
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { resolvedTheme, themeReady } = useChartTheme()
|
||||
const { textColor, gridColor } = getChartThemeTokens(resolvedTheme)
|
||||
const { customization } = useThemeCustomization()
|
||||
const barRadius = useThemeRadiusPx(
|
||||
'--radius-sm',
|
||||
`${customization.preset}:${customization.radius}`
|
||||
)
|
||||
|
||||
const filtered = useMemo(
|
||||
() => props.rows.filter((r) => r.throughput_tps > 0),
|
||||
[props.rows]
|
||||
)
|
||||
|
||||
const spec = useMemo(() => {
|
||||
if (filtered.length === 0) return null
|
||||
return {
|
||||
type: 'bar' as const,
|
||||
direction: 'horizontal' as const,
|
||||
data: [{ id: 'tput', values: filtered.map((r) => ({ ...r })) }],
|
||||
xField: 'throughput_tps',
|
||||
yField: 'group',
|
||||
bar: {
|
||||
style: {
|
||||
fill: '#6366f1',
|
||||
...(barRadius == null ? {} : { cornerRadius: barRadius }),
|
||||
},
|
||||
},
|
||||
label: {
|
||||
visible: true,
|
||||
position: 'right',
|
||||
style: { fontSize: 11, fill: textColor },
|
||||
formatMethod: (text: string) => `${text} t/s`,
|
||||
},
|
||||
axes: [
|
||||
{
|
||||
orient: 'left',
|
||||
label: { style: { fill: textColor, fontSize: 10 } },
|
||||
tick: { visible: false },
|
||||
},
|
||||
{
|
||||
orient: 'bottom',
|
||||
label: { style: { fill: textColor, fontSize: 10 } },
|
||||
grid: {
|
||||
visible: true,
|
||||
style: { lineDash: [3, 3], stroke: gridColor },
|
||||
},
|
||||
},
|
||||
],
|
||||
tooltip: {
|
||||
mark: {
|
||||
title: { value: (d: { group: string }) => d.group },
|
||||
content: [
|
||||
{
|
||||
key: t('Throughput'),
|
||||
value: (d: { throughput_tps: number }) =>
|
||||
`${d.throughput_tps.toFixed(1)} t/s`,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
}, [barRadius, filtered, gridColor, t, textColor])
|
||||
|
||||
if (filtered.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('h-48 sm:h-56', props.className)}>
|
||||
{themeReady && spec && (
|
||||
<VChart
|
||||
key={`tput-${resolvedTheme}`}
|
||||
spec={{
|
||||
...spec,
|
||||
theme: resolvedTheme === 'dark' ? 'dark' : 'light',
|
||||
background: 'transparent',
|
||||
}}
|
||||
option={VCHART_OPTION}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { AlertTriangle, HeartPulse, Timer } from 'lucide-react'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
StaticDataTable,
|
||||
staticDataTableClassNames as tableStyles,
|
||||
} from '@/components/data-table'
|
||||
import { GroupBadge } from '@/components/group-badge'
|
||||
import { getPerfMetrics } from '@/features/performance-metrics/api'
|
||||
import {
|
||||
formatLatency,
|
||||
formatThroughput,
|
||||
formatUptimePct,
|
||||
getSuccessRateTextClass,
|
||||
} from '@/features/performance-metrics/lib/format'
|
||||
import type { PerformanceGroup } from '@/features/performance-metrics/types'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { type UptimeDayPoint } from '../lib/mock-stats'
|
||||
import type { PricingModel } from '../types'
|
||||
import { LatencyTrendChart, UptimeTrendChart } from './model-details-charts'
|
||||
import { UptimeSparkline } from './model-details-uptime-sparkline'
|
||||
|
||||
function StatCard(props: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value: React.ReactNode
|
||||
hint?: string
|
||||
valueClassName?: string
|
||||
}) {
|
||||
const Icon = props.icon
|
||||
return (
|
||||
<div className='bg-background flex flex-col gap-1 rounded-lg border p-3'>
|
||||
<span className='text-muted-foreground inline-flex items-center gap-1.5 text-[10px] font-medium tracking-wider uppercase'>
|
||||
<Icon className='size-3' />
|
||||
{props.label}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'text-foreground font-mono text-lg font-semibold tabular-nums',
|
||||
props.valueClassName
|
||||
)}
|
||||
>
|
||||
{props.value}
|
||||
</span>
|
||||
{props.hint && (
|
||||
<span className='text-muted-foreground/70 text-[11px]'>
|
||||
{props.hint}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type PerformanceRow = {
|
||||
group: string
|
||||
avg_ttft_ms: number
|
||||
avg_latency_ms: number
|
||||
success_rate: number
|
||||
avg_tps: number
|
||||
}
|
||||
|
||||
function toUptimePct(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0
|
||||
const clamped = Math.min(100, Math.max(0, value))
|
||||
return Math.round(clamped * 100) / 100
|
||||
}
|
||||
|
||||
function toLatencySeries(groups: PerformanceGroup[]) {
|
||||
const byTs = new Map<number, number[]>()
|
||||
for (const group of groups) {
|
||||
for (const point of group.series) {
|
||||
if (point.avg_ttft_ms <= 0) continue
|
||||
const current = byTs.get(point.ts) ?? []
|
||||
current.push(point.avg_ttft_ms)
|
||||
byTs.set(point.ts, current)
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(byTs.entries())
|
||||
.sort(([a], [b]) => a - b)
|
||||
.map(([ts, values]) => ({
|
||||
timestamp: new Date(ts * 1000).toISOString(),
|
||||
group: 'latency',
|
||||
ttft_ms: Math.round(
|
||||
values.reduce((sum, value) => sum + value, 0) / values.length
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
function toUptimeSeries(groups: PerformanceGroup[]): UptimeDayPoint[] {
|
||||
const byTs = new Map<number, { rates: number[]; incidents: number }>()
|
||||
for (const group of groups) {
|
||||
for (const point of group.series) {
|
||||
const current = byTs.get(point.ts) ?? { rates: [], incidents: 0 }
|
||||
if (Number.isFinite(point.success_rate)) {
|
||||
const successRate = toUptimePct(point.success_rate)
|
||||
current.rates.push(successRate)
|
||||
if (successRate < 100) current.incidents += 1
|
||||
}
|
||||
byTs.set(point.ts, current)
|
||||
}
|
||||
}
|
||||
return Array.from(byTs.entries())
|
||||
.sort(([a], [b]) => a - b)
|
||||
.map(([ts, value]) => {
|
||||
const uptime =
|
||||
value.rates.length > 0
|
||||
? value.rates.reduce((sum, rate) => sum + rate, 0) /
|
||||
value.rates.length
|
||||
: 0
|
||||
return {
|
||||
date: new Date(ts * 1000).toISOString(),
|
||||
uptime_pct: toUptimePct(uptime),
|
||||
incidents: value.incidents,
|
||||
outage_minutes: 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function toGroupUptimeSeries(group: PerformanceGroup): UptimeDayPoint[] {
|
||||
return group.series.map((point) => {
|
||||
const successRate = toUptimePct(point.success_rate)
|
||||
return {
|
||||
date: new Date(point.ts * 1000).toISOString(),
|
||||
uptime_pct: successRate,
|
||||
incidents: successRate < 100 ? 1 : 0,
|
||||
outage_minutes: 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function average(
|
||||
rows: PerformanceRow[],
|
||||
field: 'avg_ttft_ms' | 'avg_latency_ms'
|
||||
) {
|
||||
const values = rows.map((row) => row[field]).filter((value) => value > 0)
|
||||
if (values.length === 0) return 0
|
||||
return Math.round(
|
||||
values.reduce((sum, value) => sum + value, 0) / values.length
|
||||
)
|
||||
}
|
||||
|
||||
export function ModelDetailsPerformance(props: { model: PricingModel }) {
|
||||
const { t } = useTranslation()
|
||||
const metricsQuery = useQuery({
|
||||
queryKey: ['perf-metrics', props.model.model_name],
|
||||
queryFn: () => getPerfMetrics(props.model.model_name, 24),
|
||||
staleTime: 60 * 1000,
|
||||
})
|
||||
const groups = useMemo(
|
||||
() => metricsQuery.data?.data.groups ?? [],
|
||||
[metricsQuery.data]
|
||||
)
|
||||
const performances = useMemo<PerformanceRow[]>(
|
||||
() =>
|
||||
groups.map((group) => ({
|
||||
group: group.group,
|
||||
avg_ttft_ms: group.avg_ttft_ms,
|
||||
avg_latency_ms: group.avg_latency_ms,
|
||||
success_rate: group.success_rate,
|
||||
avg_tps: group.avg_tps,
|
||||
})),
|
||||
[groups]
|
||||
)
|
||||
const latencySeries = useMemo(() => toLatencySeries(groups), [groups])
|
||||
const uptimeSeries = useMemo(() => toUptimeSeries(groups), [groups])
|
||||
const uptimeByGroup = useMemo<Record<string, UptimeDayPoint[]>>(() => {
|
||||
const map: Record<string, UptimeDayPoint[]> = {}
|
||||
for (const group of groups) {
|
||||
map[group.group] = toGroupUptimeSeries(group)
|
||||
}
|
||||
return map
|
||||
}, [groups])
|
||||
|
||||
if (metricsQuery.isLoading || performances.length === 0) {
|
||||
return (
|
||||
<div className='text-muted-foreground rounded-lg border p-6 text-center text-sm'>
|
||||
{t('Performance data is not yet available for this model.')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const tpsValues = performances
|
||||
.map((p) => p.avg_tps)
|
||||
.filter((value) => value > 0)
|
||||
const avgTps =
|
||||
tpsValues.length > 0
|
||||
? tpsValues.reduce((sum, value) => sum + value, 0) / tpsValues.length
|
||||
: 0
|
||||
const avgLatency = average(performances, 'avg_latency_ms')
|
||||
const successRates = performances
|
||||
.map((perf) => perf.success_rate)
|
||||
.filter((value) => Number.isFinite(value))
|
||||
const successRate =
|
||||
successRates.length > 0
|
||||
? successRates.reduce((sum, value) => sum + value, 0) /
|
||||
successRates.length
|
||||
: 0
|
||||
const incidentCount = uptimeSeries.reduce((s, p) => s + p.incidents, 0)
|
||||
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='grid grid-cols-1 gap-2 sm:grid-cols-3'>
|
||||
<StatCard
|
||||
icon={Timer}
|
||||
label='TPS'
|
||||
value={formatThroughput(avgTps)}
|
||||
hint={t('Sustained tokens per second')}
|
||||
/>
|
||||
<StatCard
|
||||
icon={Timer}
|
||||
label={t('Average latency')}
|
||||
value={formatLatency(avgLatency)}
|
||||
/>
|
||||
<StatCard
|
||||
icon={HeartPulse}
|
||||
label={t('Success rate')}
|
||||
value={formatUptimePct(successRate)}
|
||||
hint={
|
||||
incidentCount > 0
|
||||
? t('{{count}} incidents in the last 24 hours', {
|
||||
count: incidentCount,
|
||||
})
|
||||
: t('No incidents in the last 24 hours')
|
||||
}
|
||||
valueClassName={getSuccessRateTextClass(successRate)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={HeartPulse}
|
||||
title={t('Per-group performance')}
|
||||
description={t('Average latency, TTFT, TPS, and success rate')}
|
||||
/>
|
||||
<StaticDataTable
|
||||
className='rounded-lg'
|
||||
tableClassName='text-sm'
|
||||
headerRowClassName={tableStyles.compactHeaderRow}
|
||||
data={performances}
|
||||
getRowKey={(perf) => perf.group}
|
||||
columns={[
|
||||
{
|
||||
id: 'group',
|
||||
header: t('Group'),
|
||||
className: tableStyles.compactHeaderCell,
|
||||
cellClassName: tableStyles.compactCell,
|
||||
cell: (perf) => <GroupBadge group={perf.group} size='sm' />,
|
||||
},
|
||||
{
|
||||
id: 'tps',
|
||||
header: 'TPS',
|
||||
className: tableStyles.compactHeaderCellRight,
|
||||
cellClassName: tableStyles.compactNumericCell,
|
||||
cell: (perf) => formatThroughput(perf.avg_tps),
|
||||
},
|
||||
{
|
||||
id: 'ttft',
|
||||
header: t('Average TTFT'),
|
||||
className: tableStyles.compactHeaderCellRight,
|
||||
cellClassName: tableStyles.compactNumericCell,
|
||||
cell: (perf) => formatLatency(perf.avg_ttft_ms),
|
||||
},
|
||||
{
|
||||
id: 'latency',
|
||||
header: t('Average latency'),
|
||||
className: tableStyles.compactHeaderCellRight,
|
||||
cellClassName: tableStyles.compactMutedNumericCell,
|
||||
cell: (perf) => formatLatency(perf.avg_latency_ms),
|
||||
},
|
||||
{
|
||||
id: 'success',
|
||||
header: t('Success rate'),
|
||||
className: cn(tableStyles.compactHeaderCell, 'min-w-[180px]'),
|
||||
cellClassName: tableStyles.compactCell,
|
||||
cell: (perf) => (
|
||||
<UptimeSparkline
|
||||
size='sm'
|
||||
series={uptimeByGroup[perf.group] ?? []}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={Timer}
|
||||
title={t('Latency trend (last 24h)')}
|
||||
description={t('Average TTFT')}
|
||||
/>
|
||||
<LatencyTrendChart series={latencySeries} />
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<SectionHeader
|
||||
icon={HeartPulse}
|
||||
title={t('Availability (last 24h)')}
|
||||
description={
|
||||
incidentCount > 0
|
||||
? t(
|
||||
'Request success rate; {{incidents}} incident buckets in the last 24 hours',
|
||||
{
|
||||
incidents: incidentCount,
|
||||
}
|
||||
)
|
||||
: t('Request success rate sampled over the last 24 hours')
|
||||
}
|
||||
accent={
|
||||
incidentCount > 0 ? (
|
||||
<span className='inline-flex items-center gap-1 text-amber-600 dark:text-amber-400'>
|
||||
<AlertTriangle className='size-3.5' />
|
||||
{t('{{count}} incidents', {
|
||||
count: incidentCount,
|
||||
})}
|
||||
</span>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<UptimeTrendChart series={uptimeSeries} />
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SectionHeader(props: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
title: string
|
||||
description?: string
|
||||
accent?: React.ReactNode
|
||||
}) {
|
||||
const Icon = props.icon
|
||||
return (
|
||||
<div className='mb-2 flex flex-wrap items-center justify-between gap-2'>
|
||||
<div className='flex min-w-0 items-center gap-2'>
|
||||
<Icon className='text-muted-foreground/70 size-3.5 shrink-0' />
|
||||
<div className='min-w-0'>
|
||||
<div className='text-foreground text-sm font-semibold'>
|
||||
{props.title}
|
||||
</div>
|
||||
{props.description && (
|
||||
<p className='text-muted-foreground/80 text-xs'>
|
||||
{props.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{props.accent && (
|
||||
<div className='shrink-0 text-xs font-medium'>{props.accent}</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Activity, AlertCircle, CheckCircle2 } from 'lucide-react'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import {
|
||||
formatUptimePct,
|
||||
getSuccessRateDotClass,
|
||||
getSuccessRateTextClass,
|
||||
} from '@/features/performance-metrics/lib/format'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { aggregateUptime, type UptimeDayPoint } from '../lib/mock-stats'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Uptime sparkline
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// Compact 30-day uptime visualisation: a row of small coloured bars where:
|
||||
// - Bar colour reflects per-day uptime (green / amber / red)
|
||||
// - Bar height reflects severity (the worse the day, the shorter the bar)
|
||||
// - Hovering a bar reveals the exact date and uptime
|
||||
//
|
||||
// Useful as a header strip ("at-a-glance" status) and as a per-row visual
|
||||
// inside the per-group performance table.
|
||||
|
||||
type SparklineSize = 'sm' | 'md'
|
||||
|
||||
type UptimeSparklineProps = {
|
||||
series: UptimeDayPoint[]
|
||||
size?: SparklineSize
|
||||
showOverall?: boolean
|
||||
emptyLabel?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
function heightFor(uptime: number): string {
|
||||
if (uptime >= 99.9) return 'h-full'
|
||||
if (uptime >= 99.0) return 'h-[88%]'
|
||||
if (uptime >= 95.0) return 'h-[72%]'
|
||||
if (uptime >= 90.0) return 'h-[55%]'
|
||||
return 'h-[40%]'
|
||||
}
|
||||
|
||||
export function UptimeSparkline(props: UptimeSparklineProps) {
|
||||
const size = props.size ?? 'md'
|
||||
const showOverall = props.showOverall ?? true
|
||||
|
||||
if (props.series.length === 0) {
|
||||
return (
|
||||
<span className={cn('text-muted-foreground text-xs', props.className)}>
|
||||
{props.emptyLabel ?? '—'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const overall =
|
||||
props.series.reduce((s, p) => s + p.uptime_pct, 0) / props.series.length
|
||||
|
||||
const containerHeight = size === 'sm' ? 'h-3.5' : 'h-5'
|
||||
const barWidth = size === 'sm' ? 'w-[3px]' : 'w-1'
|
||||
const gap = size === 'sm' ? 'gap-px' : 'gap-[2px]'
|
||||
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2', props.className)}>
|
||||
<div
|
||||
className={cn('flex items-end', containerHeight, gap)}
|
||||
role='img'
|
||||
aria-label={`30 day uptime ${overall.toFixed(2)}%`}
|
||||
>
|
||||
{props.series.map((day) => (
|
||||
<Tooltip key={day.date}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-sm transition-opacity hover:opacity-80',
|
||||
barWidth,
|
||||
containerHeight,
|
||||
'flex items-end'
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'w-full rounded-sm',
|
||||
getSuccessRateDotClass(day.uptime_pct),
|
||||
heightFor(day.uptime_pct)
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side='top' className='font-mono text-xs'>
|
||||
<div className='font-medium'>{day.date}</div>
|
||||
<div>{day.uptime_pct.toFixed(2)}%</div>
|
||||
{day.outage_minutes > 0 && (
|
||||
<div className='text-muted-foreground'>
|
||||
{day.outage_minutes} min outage
|
||||
</div>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
{showOverall && (
|
||||
<span
|
||||
className={cn(
|
||||
'font-mono text-sm font-semibold tabular-nums',
|
||||
getSuccessRateTextClass(overall)
|
||||
)}
|
||||
>
|
||||
{overall.toFixed(1)}%
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Uptime status row — sparkline + summary text + status icon
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function UptimeStatusRow(props: {
|
||||
series: UptimeDayPoint[]
|
||||
className?: string
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const summary = useMemo(() => aggregateUptime(props.series), [props.series])
|
||||
const status = useMemo(() => {
|
||||
if (summary.uptime_pct >= 99.9) return 'operational'
|
||||
if (summary.uptime_pct >= 99.0) return 'minor'
|
||||
if (summary.uptime_pct >= 95.0) return 'degraded'
|
||||
return 'major'
|
||||
}, [summary.uptime_pct])
|
||||
|
||||
const StatusIcon =
|
||||
status === 'operational'
|
||||
? CheckCircle2
|
||||
: status === 'minor'
|
||||
? Activity
|
||||
: AlertCircle
|
||||
|
||||
const statusColour =
|
||||
status === 'operational'
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: status === 'minor'
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: status === 'degraded'
|
||||
? 'text-amber-600 dark:text-amber-400'
|
||||
: 'text-rose-600 dark:text-rose-400'
|
||||
|
||||
const statusLabel =
|
||||
status === 'operational'
|
||||
? t('All systems operational')
|
||||
: status === 'minor'
|
||||
? t('Minor blips in the last 30 days')
|
||||
: status === 'degraded'
|
||||
? t('Degraded performance recently')
|
||||
: t('Significant outages detected')
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'border-border/60 bg-muted/30 flex flex-wrap items-center gap-3 rounded-lg border px-3 py-2 sm:gap-4 sm:px-4',
|
||||
props.className
|
||||
)}
|
||||
>
|
||||
<div className='flex items-center gap-2'>
|
||||
<StatusIcon className={cn('size-4 shrink-0', statusColour)} />
|
||||
<span className='text-sm font-medium'>{t('Last 30 days uptime')}</span>
|
||||
</div>
|
||||
|
||||
<UptimeSparkline series={props.series} className='ml-auto' />
|
||||
|
||||
<div className='flex items-center gap-3 text-xs'>
|
||||
<span className={cn('font-medium', statusColour)}>{statusLabel}</span>
|
||||
{summary.incidents > 0 && (
|
||||
<span className='text-muted-foreground'>
|
||||
{summary.incidents}{' '}
|
||||
{summary.incidents === 1 ? t('incident') : t('incidents')}
|
||||
</span>
|
||||
)}
|
||||
{summary.outage_minutes > 0 && (
|
||||
<span className='text-muted-foreground'>
|
||||
{summary.outage_minutes} {t('min downtime')}
|
||||
</span>
|
||||
)}
|
||||
<span className='text-muted-foreground hidden sm:inline'>
|
||||
{formatUptimePct(summary.uptime_pct)} {t('overall')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+1351
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { getSuccessRateDotClass } from '@/features/performance-metrics/lib/format'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type ModelPerfBadgeData = {
|
||||
avg_latency_ms: number
|
||||
success_rate: number
|
||||
avg_tps: number
|
||||
recent_success_rates?: number[]
|
||||
}
|
||||
|
||||
export interface ModelPerfBadgeProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
perf: ModelPerfBadgeData | undefined
|
||||
}
|
||||
|
||||
function formatCompactNumber(value: number): string {
|
||||
if (!Number.isFinite(value) || value <= 0) return '—'
|
||||
return value > 1 ? String(Math.round(value)) : value.toFixed(1)
|
||||
}
|
||||
|
||||
function formatCompactLatency(ms: number): string {
|
||||
if (!Number.isFinite(ms) || ms <= 0) return '—'
|
||||
if (ms >= 1_000) return `${formatCompactNumber(ms / 1_000)}s`
|
||||
return `${formatCompactNumber(ms)}ms`
|
||||
}
|
||||
|
||||
function formatCompactThroughput(tps: number): string {
|
||||
if (!Number.isFinite(tps) || tps <= 0) return '—'
|
||||
if (tps >= 1_000) return `${formatCompactNumber(tps / 1_000)}Kt`
|
||||
return `${formatCompactNumber(tps)}t`
|
||||
}
|
||||
|
||||
export const ModelPerfBadge = memo(function ModelPerfBadge(
|
||||
props: ModelPerfBadgeProps
|
||||
) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
if (!props.perf) {
|
||||
return null
|
||||
}
|
||||
|
||||
const { avg_latency_ms, avg_tps, success_rate } = props.perf
|
||||
|
||||
const recentRates =
|
||||
props.perf.recent_success_rates?.filter((rate) => Number.isFinite(rate)) ??
|
||||
[]
|
||||
const statusRates =
|
||||
recentRates.length > 0 ? recentRates.slice(-3) : [success_rate]
|
||||
const statusBars = [
|
||||
...Array(Math.max(0, 3 - statusRates.length)).fill(null),
|
||||
...statusRates,
|
||||
].slice(-3)
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'hidden w-[132px] grid-cols-[38px_48px_30px] gap-x-2 text-right tabular-nums min-[460px]:grid',
|
||||
props.className
|
||||
)}
|
||||
>
|
||||
<div title={t('Average latency')} className='min-w-0'>
|
||||
<div className='text-muted-foreground/55 text-[10px] leading-4'>
|
||||
{t('Latency short')}
|
||||
</div>
|
||||
<div className='text-muted-foreground/80 font-mono text-xs leading-4 whitespace-nowrap'>
|
||||
{formatCompactLatency(avg_latency_ms)}
|
||||
</div>
|
||||
</div>
|
||||
<div title={t('Throughput')} className='min-w-0'>
|
||||
<div className='text-muted-foreground/55 truncate text-[10px] leading-4'>
|
||||
{t('Throughput short')}
|
||||
</div>
|
||||
<div className='text-muted-foreground/80 font-mono text-xs leading-4 whitespace-nowrap'>
|
||||
{formatCompactThroughput(avg_tps)}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
title={`${t('Success rate')}: ${success_rate.toFixed(1)}%`}
|
||||
className='min-w-0'
|
||||
>
|
||||
<div className='text-muted-foreground/55 truncate text-[10px] leading-4'>
|
||||
{t('Status short')}
|
||||
</div>
|
||||
<div className='flex h-4 items-center justify-end gap-0.5'>
|
||||
{statusBars.map((rate, index) => (
|
||||
<span
|
||||
key={`${index}-${rate ?? 'empty'}`}
|
||||
className={cn(
|
||||
'w-1 rounded-full',
|
||||
index === 0 && 'h-2',
|
||||
index === 1 && 'h-2.5',
|
||||
index === 2 && 'h-3',
|
||||
rate == null
|
||||
? index === 0
|
||||
? 'bg-muted-foreground/10'
|
||||
: 'bg-muted-foreground/15'
|
||||
: getSuccessRateDotClass(rate)
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,413 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
BadgeCell,
|
||||
BadgeListCell,
|
||||
DataTableColumnHeader,
|
||||
} from '@/components/data-table'
|
||||
import { GroupBadge } from '@/components/group-badge'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import { getLobeIcon } from '@/lib/lobe-icon'
|
||||
|
||||
import { DEFAULT_TOKEN_UNIT } from '../constants'
|
||||
import {
|
||||
getDynamicDisplayGroupRatio,
|
||||
getDynamicPricingSummary,
|
||||
} from '../lib/dynamic-price'
|
||||
import { parseTags } from '../lib/filters'
|
||||
import { isTokenBasedModel } from '../lib/model-helpers'
|
||||
import {
|
||||
formatPrice,
|
||||
formatRequestPrice,
|
||||
stripTrailingZeros,
|
||||
} from '../lib/price'
|
||||
import type { PricingModel, TokenUnit } from '../types'
|
||||
import { ModelBillingModeBadge } from './model-billing-mode-badge'
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Pricing Table Columns
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
export interface PricingColumnsOptions {
|
||||
tokenUnit?: TokenUnit
|
||||
priceRate?: number
|
||||
usdExchangeRate?: number
|
||||
showRechargePrice?: boolean
|
||||
selectedGroup?: string
|
||||
}
|
||||
|
||||
export function usePricingColumns(
|
||||
options: PricingColumnsOptions = {}
|
||||
): ColumnDef<PricingModel>[] {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
tokenUnit = DEFAULT_TOKEN_UNIT,
|
||||
priceRate = 1,
|
||||
usdExchangeRate = 1,
|
||||
showRechargePrice = false,
|
||||
selectedGroup,
|
||||
} = options
|
||||
|
||||
const tokenUnitLabel = tokenUnit === 'K' ? '1K' : '1M'
|
||||
|
||||
return [
|
||||
// Model column
|
||||
{
|
||||
accessorKey: 'model_name',
|
||||
meta: { label: t('Model') },
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('Model')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const model = row.original
|
||||
const modelIconKey = model.icon || model.vendor_icon
|
||||
const modelIcon = modelIconKey ? getLobeIcon(modelIconKey, 14) : null
|
||||
|
||||
return (
|
||||
<div className='flex max-w-full min-w-0 items-center gap-2'>
|
||||
{modelIcon}
|
||||
<span className='truncate font-mono text-sm font-medium'>
|
||||
{model.model_name}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
minSize: 200,
|
||||
},
|
||||
|
||||
// Type column
|
||||
{
|
||||
accessorKey: 'quota_type',
|
||||
header: t('Type'),
|
||||
cell: ({ row }) => (
|
||||
<ModelBillingModeBadge model={row.original} className='-ml-1.5' />
|
||||
),
|
||||
size: 110,
|
||||
enableSorting: false,
|
||||
},
|
||||
|
||||
// Price column
|
||||
{
|
||||
accessorKey: 'price',
|
||||
meta: { label: t('Price') },
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('Price')} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const model = row.original
|
||||
const dynamicSummary = getDynamicPricingSummary(model, {
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
groupRatioMultiplier: getDynamicDisplayGroupRatio(
|
||||
model,
|
||||
selectedGroup
|
||||
),
|
||||
})
|
||||
|
||||
if (dynamicSummary) {
|
||||
if (dynamicSummary.isSpecialExpression) {
|
||||
return (
|
||||
<div className='max-w-full min-w-0'>
|
||||
<div className='text-xs font-medium text-amber-700 dark:text-amber-300'>
|
||||
{t('Special billing expression')}
|
||||
</div>
|
||||
<div className='text-muted-foreground text-[11px]'>
|
||||
{t('Unable to parse structured pricing')}
|
||||
</div>
|
||||
<code className='text-muted-foreground/70 mt-1 line-clamp-2 block font-mono text-[10px] leading-relaxed break-all'>
|
||||
{dynamicSummary.rawExpression}
|
||||
</code>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const primaryEntries = dynamicSummary.primaryEntries.slice(0, 2)
|
||||
if (primaryEntries.length === 0) {
|
||||
return (
|
||||
<span className='text-muted-foreground text-xs'>
|
||||
{t('Dynamic Pricing')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='max-w-full min-w-0'>
|
||||
<span className='font-mono text-sm tabular-nums'>
|
||||
{primaryEntries.map((entry, index) => (
|
||||
<span key={entry.key}>
|
||||
{index > 0 && (
|
||||
<span className='text-muted-foreground/40 mx-1'>/</span>
|
||||
)}
|
||||
{stripTrailingZeros(entry.formatted)}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
<div className='text-muted-foreground/50 text-[10px]'>
|
||||
/ {tokenUnitLabel} tokens
|
||||
{dynamicSummary.tierCount > 1 &&
|
||||
` · ${t('{{count}} tiers', {
|
||||
count: dynamicSummary.tierCount,
|
||||
})}`}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const isTokenBased = isTokenBasedModel(model)
|
||||
|
||||
if (isTokenBased) {
|
||||
const inputPrice = stripTrailingZeros(
|
||||
formatPrice(
|
||||
model,
|
||||
'input',
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
selectedGroup
|
||||
)
|
||||
)
|
||||
const outputPrice = stripTrailingZeros(
|
||||
formatPrice(
|
||||
model,
|
||||
'output',
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
selectedGroup
|
||||
)
|
||||
)
|
||||
|
||||
return (
|
||||
<div className='max-w-full min-w-0'>
|
||||
<span className='font-mono text-sm tabular-nums'>
|
||||
{inputPrice}
|
||||
<span className='text-muted-foreground/40 mx-1'>/</span>
|
||||
{outputPrice}
|
||||
</span>
|
||||
<div className='text-muted-foreground/50 text-[10px]'>
|
||||
/ {tokenUnitLabel} tokens
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const price = stripTrailingZeros(
|
||||
formatRequestPrice(
|
||||
model,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
selectedGroup
|
||||
)
|
||||
)
|
||||
|
||||
return (
|
||||
<div className='max-w-full min-w-0'>
|
||||
<span className='font-mono text-sm tabular-nums'>{price}</span>
|
||||
<div className='text-muted-foreground/50 text-[10px]'>
|
||||
/ {t('request')}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
size: 180,
|
||||
enableSorting: false,
|
||||
},
|
||||
|
||||
// Cached price column (Vercel AI Gateway style)
|
||||
{
|
||||
id: 'cached_price',
|
||||
header: t('Cached'),
|
||||
cell: ({ row }) => {
|
||||
const model = row.original
|
||||
const dynamicSummary = getDynamicPricingSummary(model, {
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
groupRatioMultiplier: getDynamicDisplayGroupRatio(
|
||||
model,
|
||||
selectedGroup
|
||||
),
|
||||
})
|
||||
|
||||
if (dynamicSummary) {
|
||||
if (dynamicSummary.isSpecialExpression) {
|
||||
return (
|
||||
<span className='text-muted-foreground/50 text-xs'>
|
||||
{t('Special billing expression')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const cacheEntry = dynamicSummary.entries.find(
|
||||
(entry) => entry.field === 'cacheReadPrice'
|
||||
)
|
||||
if (!cacheEntry) {
|
||||
return <span className='text-muted-foreground/30 text-xs'>—</span>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='max-w-full min-w-0'>
|
||||
<span className='font-mono text-sm tabular-nums'>
|
||||
{stripTrailingZeros(cacheEntry.formatted)}
|
||||
</span>
|
||||
<div className='text-muted-foreground/50 text-[10px]'>
|
||||
/ {tokenUnitLabel}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const isTokenBased = isTokenBasedModel(model)
|
||||
|
||||
if (!isTokenBased || model.cache_ratio == null) {
|
||||
return <span className='text-muted-foreground/30 text-xs'>—</span>
|
||||
}
|
||||
|
||||
const cachedPrice = stripTrailingZeros(
|
||||
formatPrice(
|
||||
model,
|
||||
'cache',
|
||||
tokenUnit,
|
||||
showRechargePrice,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
selectedGroup
|
||||
)
|
||||
)
|
||||
|
||||
return (
|
||||
<div className='max-w-full min-w-0'>
|
||||
<span className='font-mono text-sm tabular-nums'>
|
||||
{cachedPrice}
|
||||
</span>
|
||||
<div className='text-muted-foreground/50 text-[10px]'>
|
||||
/ {tokenUnitLabel}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
size: 110,
|
||||
enableSorting: false,
|
||||
},
|
||||
|
||||
// Vendor column
|
||||
{
|
||||
accessorKey: 'vendor_name',
|
||||
header: t('Vendor'),
|
||||
cell: ({ row }) => {
|
||||
const model = row.original
|
||||
if (!model.vendor_name) {
|
||||
return <span className='text-muted-foreground/50 text-xs'>—</span>
|
||||
}
|
||||
const vendorIcon = model.vendor_icon
|
||||
? getLobeIcon(model.vendor_icon, 12)
|
||||
: null
|
||||
return (
|
||||
<BadgeCell className='gap-1.5'>
|
||||
{vendorIcon}
|
||||
<StatusBadge
|
||||
label={model.vendor_name}
|
||||
autoColor={model.vendor_name}
|
||||
size='sm'
|
||||
copyable={false}
|
||||
/>
|
||||
</BadgeCell>
|
||||
)
|
||||
},
|
||||
size: 130,
|
||||
enableSorting: false,
|
||||
},
|
||||
|
||||
// Tags column
|
||||
{
|
||||
accessorKey: 'tags',
|
||||
header: t('Tags'),
|
||||
cell: ({ row }) => {
|
||||
const tags = parseTags(row.original.tags)
|
||||
return (
|
||||
<BadgeListCell
|
||||
items={tags.map((tag) => (
|
||||
<StatusBadge
|
||||
key={tag}
|
||||
label={tag}
|
||||
autoColor={tag}
|
||||
size='sm'
|
||||
copyable={false}
|
||||
/>
|
||||
))}
|
||||
/>
|
||||
)
|
||||
},
|
||||
size: 140,
|
||||
enableSorting: false,
|
||||
},
|
||||
|
||||
// Endpoints column
|
||||
{
|
||||
accessorKey: 'supported_endpoint_types',
|
||||
header: t('Endpoints'),
|
||||
cell: ({ row }) => {
|
||||
const endpoints = row.original.supported_endpoint_types || []
|
||||
return (
|
||||
<BadgeListCell
|
||||
items={endpoints.map((ep) => (
|
||||
<StatusBadge
|
||||
key={ep}
|
||||
label={ep}
|
||||
autoColor={ep}
|
||||
size='sm'
|
||||
copyable={false}
|
||||
/>
|
||||
))}
|
||||
/>
|
||||
)
|
||||
},
|
||||
size: 130,
|
||||
enableSorting: false,
|
||||
},
|
||||
|
||||
// Enable Groups column
|
||||
{
|
||||
accessorKey: 'enable_groups',
|
||||
header: t('Groups'),
|
||||
cell: ({ row }) => {
|
||||
const groups = row.original.enable_groups || []
|
||||
return (
|
||||
<BadgeListCell
|
||||
items={groups.map((group) => (
|
||||
<GroupBadge key={group} group={group} size='sm' />
|
||||
))}
|
||||
tooltipClassName='max-w-[280px] p-2'
|
||||
/>
|
||||
)
|
||||
},
|
||||
size: 130,
|
||||
enableSorting: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { ChevronDown, RotateCcw } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible'
|
||||
import { getLobeIcon } from '@/lib/lobe-icon'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import {
|
||||
ENDPOINT_TYPES,
|
||||
FILTER_ALL,
|
||||
QUOTA_TYPES,
|
||||
getEndpointTypeLabels,
|
||||
getQuotaTypeLabels,
|
||||
} from '../constants'
|
||||
import { parseTags } from '../lib/filters'
|
||||
import type { PricingModel, PricingVendor } from '../types'
|
||||
|
||||
type FilterOption = {
|
||||
value: string
|
||||
label: string
|
||||
count?: number
|
||||
suffix?: string
|
||||
icon?: ReactNode
|
||||
}
|
||||
|
||||
type FilterSectionProps = {
|
||||
title: string
|
||||
value: string
|
||||
options: FilterOption[]
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
export interface PricingSidebarProps {
|
||||
quotaTypeFilter: string
|
||||
endpointTypeFilter: string
|
||||
vendorFilter: string
|
||||
groupFilter: string
|
||||
tagFilter: string
|
||||
onQuotaTypeChange: (value: string) => void
|
||||
onEndpointTypeChange: (value: string) => void
|
||||
onVendorChange: (value: string) => void
|
||||
onGroupChange: (value: string) => void
|
||||
onTagChange: (value: string) => void
|
||||
vendors: PricingVendor[]
|
||||
groups: string[]
|
||||
groupRatios?: Record<string, number>
|
||||
tags: string[]
|
||||
models: PricingModel[]
|
||||
hasActiveFilters: boolean
|
||||
onClearFilters: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
function countBy(
|
||||
models: PricingModel[],
|
||||
predicate: (model: PricingModel) => boolean
|
||||
): number {
|
||||
return models.reduce((count, model) => count + (predicate(model) ? 1 : 0), 0)
|
||||
}
|
||||
|
||||
function formatGroupRatio(ratio: number | undefined): string | undefined {
|
||||
if (ratio == null) return undefined
|
||||
const formatted = Number.isInteger(ratio)
|
||||
? ratio.toString()
|
||||
: ratio.toFixed(3).replace(/0+$/, '').replace(/\.$/, '')
|
||||
return `x${formatted}`
|
||||
}
|
||||
|
||||
function FilterChip(props: {
|
||||
option: FilterOption
|
||||
active: boolean
|
||||
onClick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type='button'
|
||||
onClick={props.onClick}
|
||||
className={cn(
|
||||
'group inline-flex max-w-full items-center gap-1.5 rounded-md border px-2 py-1 text-xs font-medium transition-all',
|
||||
props.active
|
||||
? 'border-foreground/30 bg-foreground/5 text-foreground shadow-sm'
|
||||
: 'border-border/70 bg-background text-muted-foreground hover:border-border hover:bg-muted/50 hover:text-foreground'
|
||||
)}
|
||||
title={props.option.label}
|
||||
>
|
||||
{props.option.icon && (
|
||||
<span className='shrink-0'>{props.option.icon}</span>
|
||||
)}
|
||||
<span className='truncate'>{props.option.label}</span>
|
||||
{(props.option.suffix || props.option.count != null) && (
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-md px-1.5 py-0.5 text-[12px]',
|
||||
props.active
|
||||
? 'bg-background text-foreground'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{props.option.suffix ?? props.option.count}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function FilterSection(props: FilterSectionProps) {
|
||||
return (
|
||||
<Collapsible
|
||||
defaultOpen
|
||||
className='border-border/70 border-b pb-3 last:border-b-0'
|
||||
>
|
||||
<CollapsibleTrigger className='group flex w-full items-center justify-between py-2.5 text-left'>
|
||||
<span className='text-foreground text-sm font-semibold'>
|
||||
{props.title}
|
||||
</span>
|
||||
<ChevronDown className='text-muted-foreground size-4 transition-transform group-data-[panel-open]:rotate-180' />
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className='flex flex-wrap gap-1.5'>
|
||||
{props.options.map((option) => (
|
||||
<FilterChip
|
||||
key={option.value}
|
||||
option={option}
|
||||
active={props.value === option.value}
|
||||
onClick={() => props.onChange(option.value)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
|
||||
export function PricingSidebar(props: PricingSidebarProps) {
|
||||
const { t } = useTranslation()
|
||||
const quotaTypeLabels = getQuotaTypeLabels(t)
|
||||
const endpointTypeLabels = getEndpointTypeLabels(t)
|
||||
|
||||
const vendorOptions: FilterOption[] = [
|
||||
{
|
||||
value: FILTER_ALL,
|
||||
label: t('All Vendors'),
|
||||
count: props.models.length,
|
||||
},
|
||||
...props.vendors
|
||||
.map((vendor) => ({
|
||||
value: vendor.name,
|
||||
label: vendor.name,
|
||||
count: countBy(
|
||||
props.models,
|
||||
(model) => model.vendor_name === vendor.name
|
||||
),
|
||||
icon: vendor.icon ? getLobeIcon(vendor.icon, 14) : undefined,
|
||||
}))
|
||||
.filter((vendor) => vendor.count > 0),
|
||||
]
|
||||
|
||||
const groupOptions: FilterOption[] = [
|
||||
{
|
||||
value: FILTER_ALL,
|
||||
label: t('All Groups'),
|
||||
},
|
||||
...props.groups.map((group) => ({
|
||||
value: group,
|
||||
label: group,
|
||||
suffix: formatGroupRatio(props.groupRatios?.[group]),
|
||||
})),
|
||||
]
|
||||
|
||||
const quotaOptions: FilterOption[] = [
|
||||
{
|
||||
value: QUOTA_TYPES.ALL,
|
||||
label: quotaTypeLabels[QUOTA_TYPES.ALL],
|
||||
count: props.models.length,
|
||||
},
|
||||
{
|
||||
value: QUOTA_TYPES.TOKEN,
|
||||
label: quotaTypeLabels[QUOTA_TYPES.TOKEN],
|
||||
count: countBy(props.models, (model) => model.quota_type === 0),
|
||||
},
|
||||
{
|
||||
value: QUOTA_TYPES.REQUEST,
|
||||
label: quotaTypeLabels[QUOTA_TYPES.REQUEST],
|
||||
count: countBy(props.models, (model) => model.quota_type === 1),
|
||||
},
|
||||
]
|
||||
|
||||
const tagOptions: FilterOption[] = [
|
||||
{
|
||||
value: FILTER_ALL,
|
||||
label: t('All Tags'),
|
||||
count: props.models.length,
|
||||
},
|
||||
...props.tags.map((tag) => ({
|
||||
value: tag,
|
||||
label: tag,
|
||||
count: countBy(props.models, (model) =>
|
||||
parseTags(model.tags)
|
||||
.map((item) => item.toLowerCase())
|
||||
.includes(tag.toLowerCase())
|
||||
),
|
||||
})),
|
||||
]
|
||||
|
||||
const endpointOptions: FilterOption[] = [
|
||||
{
|
||||
value: ENDPOINT_TYPES.ALL,
|
||||
label: endpointTypeLabels[ENDPOINT_TYPES.ALL],
|
||||
count: props.models.length,
|
||||
},
|
||||
...Object.entries(endpointTypeLabels)
|
||||
.filter(([value]) => value !== ENDPOINT_TYPES.ALL)
|
||||
.map(([value, label]) => ({
|
||||
value,
|
||||
label,
|
||||
count: countBy(
|
||||
props.models,
|
||||
(model) => model.supported_endpoint_types?.includes(value) ?? false
|
||||
),
|
||||
})),
|
||||
]
|
||||
|
||||
return (
|
||||
<aside className={cn('rounded-xl border p-3', props.className)}>
|
||||
<div className='mb-2.5 flex items-center justify-between gap-2'>
|
||||
<div>
|
||||
<h2 className='text-foreground text-sm font-bold'>{t('Filter')}</h2>
|
||||
<p className='text-muted-foreground mt-1 text-xs'>
|
||||
{t('Refine models by provider, group, type, and tags.')}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
onClick={props.onClearFilters}
|
||||
disabled={!props.hasActiveFilters}
|
||||
className='h-7 gap-1.5 px-2 text-xs'
|
||||
>
|
||||
<RotateCcw className='size-3.5' />
|
||||
{t('Reset')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{props.hasActiveFilters && (
|
||||
<Badge variant='secondary' className='mb-3'>
|
||||
{t('Filters active')}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
<div className='space-y-1'>
|
||||
<FilterSection
|
||||
title={t('Groups')}
|
||||
value={props.groupFilter}
|
||||
options={groupOptions}
|
||||
onChange={props.onGroupChange}
|
||||
/>
|
||||
<FilterSection
|
||||
title={t('All Vendors')}
|
||||
value={props.vendorFilter}
|
||||
options={vendorOptions}
|
||||
onChange={props.onVendorChange}
|
||||
/>
|
||||
<FilterSection
|
||||
title={t('Model Tags')}
|
||||
value={props.tagFilter}
|
||||
options={tagOptions}
|
||||
onChange={props.onTagChange}
|
||||
/>
|
||||
<FilterSection
|
||||
title={t('Pricing Type')}
|
||||
value={props.quotaTypeFilter}
|
||||
options={quotaOptions}
|
||||
onChange={props.onQuotaTypeChange}
|
||||
/>
|
||||
<FilterSection
|
||||
title={t('Endpoint Type')}
|
||||
value={props.endpointTypeFilter}
|
||||
options={endpointOptions}
|
||||
onChange={props.onEndpointTypeChange}
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import type { Row, PaginationState } from '@tanstack/react-table'
|
||||
import { useState, useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
DataTablePagination,
|
||||
DataTableRow,
|
||||
DataTableView,
|
||||
useDataTable,
|
||||
} from '@/components/data-table'
|
||||
|
||||
import { DEFAULT_PRICING_PAGE_SIZE, DEFAULT_TOKEN_UNIT } from '../constants'
|
||||
import type { PricingModel, TokenUnit } from '../types'
|
||||
import { usePricingColumns } from './pricing-columns'
|
||||
|
||||
export interface PricingTableProps {
|
||||
models: PricingModel[]
|
||||
isLoading?: boolean
|
||||
priceRate?: number
|
||||
usdExchangeRate?: number
|
||||
tokenUnit?: TokenUnit
|
||||
showRechargePrice?: boolean
|
||||
selectedGroup?: string
|
||||
onModelClick?: (modelName: string) => void
|
||||
}
|
||||
|
||||
export function PricingTable(props: PricingTableProps) {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
models,
|
||||
isLoading = false,
|
||||
priceRate = 1,
|
||||
usdExchangeRate = 1,
|
||||
tokenUnit = DEFAULT_TOKEN_UNIT,
|
||||
showRechargePrice = false,
|
||||
selectedGroup,
|
||||
onModelClick,
|
||||
} = props
|
||||
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: DEFAULT_PRICING_PAGE_SIZE,
|
||||
})
|
||||
|
||||
const columns = usePricingColumns({
|
||||
tokenUnit,
|
||||
priceRate,
|
||||
usdExchangeRate,
|
||||
showRechargePrice,
|
||||
selectedGroup,
|
||||
})
|
||||
|
||||
const { table } = useDataTable({
|
||||
data: models,
|
||||
columns,
|
||||
pageCount: Math.ceil(models.length / pagination.pageSize),
|
||||
pagination,
|
||||
onPaginationChange: setPagination,
|
||||
manualPagination: false,
|
||||
withFilteredRowModel: false,
|
||||
withSortedRowModel: false,
|
||||
withFacetedRowModel: false,
|
||||
})
|
||||
|
||||
const handleRowClick = useCallback(
|
||||
(model: PricingModel) => {
|
||||
onModelClick?.(model.model_name)
|
||||
},
|
||||
[onModelClick]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className='space-y-4'>
|
||||
<DataTableView
|
||||
table={table}
|
||||
isLoading={isLoading}
|
||||
emptyTitle={t('No Models Found')}
|
||||
emptyDescription={t('No models match your current filters.')}
|
||||
skeletonKeyPrefix='pricing-skeleton'
|
||||
applyHeaderSize
|
||||
getColumnClassName={(_columnId, kind) =>
|
||||
kind === 'header' ? 'text-muted-foreground font-medium' : undefined
|
||||
}
|
||||
renderRow={(row: Row<PricingModel>) => (
|
||||
<DataTableRow
|
||||
key={row.id}
|
||||
row={row}
|
||||
className='hover:bg-muted/30 cursor-pointer transition-colors'
|
||||
onClick={() => handleRowClick(row.original)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!isLoading && models.length > 0 && <DataTablePagination table={table} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { ArrowUpDown, Check, Filter, Grid2X2, Table2 } from 'lucide-react'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
sideDrawerContentClassName,
|
||||
sideDrawerFormClassName,
|
||||
sideDrawerHeaderClassName,
|
||||
} from '@/components/drawer-layout'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import {
|
||||
VIEW_MODES,
|
||||
getSortLabels,
|
||||
type SortOption,
|
||||
type ViewMode,
|
||||
} from '../constants'
|
||||
import type { PricingModel, PricingVendor, TokenUnit } from '../types'
|
||||
import { PricingSidebar } from './pricing-sidebar'
|
||||
|
||||
type SegmentOption = {
|
||||
value: string
|
||||
label?: string
|
||||
icon?: React.ComponentType<{ className?: string }>
|
||||
tooltip?: string
|
||||
}
|
||||
|
||||
export interface PricingToolbarProps {
|
||||
filteredCount: number
|
||||
totalCount?: number
|
||||
sortBy: string
|
||||
onSortChange: (value: string) => void
|
||||
tokenUnit: TokenUnit
|
||||
onTokenUnitChange: (value: TokenUnit) => void
|
||||
showRechargePrice: boolean
|
||||
onRechargePriceChange: (value: boolean) => void
|
||||
viewMode: ViewMode
|
||||
onViewModeChange: (value: ViewMode) => void
|
||||
quotaTypeFilter: string
|
||||
endpointTypeFilter: string
|
||||
vendorFilter: string
|
||||
groupFilter: string
|
||||
tagFilter: string
|
||||
onQuotaTypeChange: (value: string) => void
|
||||
onEndpointTypeChange: (value: string) => void
|
||||
onVendorChange: (value: string) => void
|
||||
onGroupChange: (value: string) => void
|
||||
onTagChange: (value: string) => void
|
||||
vendors: PricingVendor[]
|
||||
groups: string[]
|
||||
groupRatios?: Record<string, number>
|
||||
tags: string[]
|
||||
models: PricingModel[]
|
||||
hasActiveFilters: boolean
|
||||
activeFilterCount: number
|
||||
onClearFilters: () => void
|
||||
}
|
||||
|
||||
function SegmentedControl(props: {
|
||||
options: SegmentOption[]
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
ariaLabel: string
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
role='group'
|
||||
aria-label={props.ariaLabel}
|
||||
className='bg-muted/60 inline-flex h-8 items-center rounded-lg border p-0.5'
|
||||
>
|
||||
{props.options.map((option) => {
|
||||
const Icon = option.icon
|
||||
const isActive = option.value === props.value
|
||||
const button = (
|
||||
<button
|
||||
key={option.value}
|
||||
type='button'
|
||||
onClick={() => props.onChange(option.value)}
|
||||
aria-pressed={isActive}
|
||||
className={cn(
|
||||
'inline-flex h-full items-center justify-center rounded-md text-xs font-medium transition-all',
|
||||
Icon && !option.label ? 'w-7' : 'gap-1.5 px-3',
|
||||
isActive
|
||||
? 'bg-primary text-primary-foreground shadow-sm'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
{Icon && <Icon className='size-3.5' />}
|
||||
{option.label}
|
||||
</button>
|
||||
)
|
||||
|
||||
if (!option.tooltip) {
|
||||
return button
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip key={option.value}>
|
||||
<TooltipTrigger render={button}></TooltipTrigger>
|
||||
<TooltipContent side='bottom' className='text-xs'>
|
||||
{option.tooltip}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PricingToolbar(props: PricingToolbarProps) {
|
||||
const { t } = useTranslation()
|
||||
const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false)
|
||||
const sortLabels = getSortLabels(t)
|
||||
|
||||
const handleTokenUnitChange = useCallback(
|
||||
(value: string) => props.onTokenUnitChange(value as TokenUnit),
|
||||
[props]
|
||||
)
|
||||
|
||||
const handleViewModeChange = useCallback(
|
||||
(value: string) => props.onViewModeChange(value as ViewMode),
|
||||
[props]
|
||||
)
|
||||
|
||||
const handleRechargePriceChange = useCallback(
|
||||
(value: string) => props.onRechargePriceChange(value === 'recharge'),
|
||||
[props]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className='rounded-xl border p-3'>
|
||||
<div className='flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={() => setMobileFiltersOpen(true)}
|
||||
className='gap-1.5 xl:hidden'
|
||||
>
|
||||
<Filter className='size-4' />
|
||||
{t('Filter')}
|
||||
{props.activeFilterCount > 0 && (
|
||||
<Badge className='ml-0.5 size-5 justify-center p-0 text-[10px]'>
|
||||
{props.activeFilterCount}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<div className='text-muted-foreground flex items-baseline gap-1 text-sm'>
|
||||
<span className='text-foreground font-semibold tabular-nums'>
|
||||
{props.filteredCount.toLocaleString()}
|
||||
</span>
|
||||
<span>{props.filteredCount === 1 ? t('model') : t('models')}</span>
|
||||
{props.hasActiveFilters && props.totalCount && (
|
||||
<span className='text-muted-foreground/60 text-xs'>
|
||||
/ {props.totalCount.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-wrap items-center gap-2'>
|
||||
<div className='hidden items-center gap-2 sm:flex'>
|
||||
<SegmentedControl
|
||||
options={[
|
||||
{ value: 'standard', label: t('Standard') },
|
||||
{ value: 'recharge', label: t('Recharge') },
|
||||
]}
|
||||
value={props.showRechargePrice ? 'recharge' : 'standard'}
|
||||
onChange={handleRechargePriceChange}
|
||||
ariaLabel={t('Price display mode')}
|
||||
/>
|
||||
<SegmentedControl
|
||||
options={[
|
||||
{ value: 'M', label: '/1M' },
|
||||
{ value: 'K', label: '/1K' },
|
||||
]}
|
||||
value={props.tokenUnit}
|
||||
onChange={handleTokenUnitChange}
|
||||
ariaLabel={t('Token unit')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-8 gap-1.5 px-3 text-xs'
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ArrowUpDown className='size-3.5' />
|
||||
<span>{sortLabels[props.sortBy as SortOption] || t('Sort')}</span>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align='end' className='w-44'>
|
||||
{Object.entries(sortLabels).map(([value, label]) => (
|
||||
<DropdownMenuItem
|
||||
key={value}
|
||||
onClick={() => props.onSortChange(value)}
|
||||
className='gap-2'
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
'size-4 shrink-0',
|
||||
props.sortBy === value ? 'opacity-100' : 'opacity-0'
|
||||
)}
|
||||
/>
|
||||
{label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<SegmentedControl
|
||||
options={[
|
||||
{
|
||||
value: VIEW_MODES.CARD,
|
||||
icon: Grid2X2,
|
||||
tooltip: t('Card view'),
|
||||
},
|
||||
{
|
||||
value: VIEW_MODES.TABLE,
|
||||
icon: Table2,
|
||||
tooltip: t('Table view'),
|
||||
},
|
||||
]}
|
||||
value={props.viewMode}
|
||||
onChange={handleViewModeChange}
|
||||
ariaLabel={t('View mode')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Sheet open={mobileFiltersOpen} onOpenChange={setMobileFiltersOpen}>
|
||||
<SheetContent
|
||||
side='right'
|
||||
className={sideDrawerContentClassName('sm:max-w-md')}
|
||||
>
|
||||
<SheetHeader className={sideDrawerHeaderClassName()}>
|
||||
<SheetTitle>{t('Filter')}</SheetTitle>
|
||||
<SheetDescription>
|
||||
{t('Filter models by provider, group, type, endpoint, and tags.')}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className={sideDrawerFormClassName('gap-0')}>
|
||||
<PricingSidebar
|
||||
quotaTypeFilter={props.quotaTypeFilter}
|
||||
endpointTypeFilter={props.endpointTypeFilter}
|
||||
vendorFilter={props.vendorFilter}
|
||||
groupFilter={props.groupFilter}
|
||||
tagFilter={props.tagFilter}
|
||||
onQuotaTypeChange={props.onQuotaTypeChange}
|
||||
onEndpointTypeChange={props.onEndpointTypeChange}
|
||||
onVendorChange={props.onVendorChange}
|
||||
onGroupChange={props.onGroupChange}
|
||||
onTagChange={props.onTagChange}
|
||||
vendors={props.vendors}
|
||||
groups={props.groups}
|
||||
groupRatios={props.groupRatios}
|
||||
tags={props.tags}
|
||||
models={props.models}
|
||||
hasActiveFilters={props.hasActiveFilters}
|
||||
onClearFilters={props.onClearFilters}
|
||||
className='border-0 bg-transparent p-0 shadow-none'
|
||||
/>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
Copyright (C) 2023-2026 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { Search, X } from 'lucide-react'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface SearchBarProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onClear: () => void
|
||||
placeholder?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function SearchBar(props: SearchBarProps) {
|
||||
const { t } = useTranslation()
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
|
||||
e.preventDefault()
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
if (e.key === 'Escape' && document.activeElement === inputRef.current) {
|
||||
inputRef.current?.blur()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className={cn('relative', props.className)}>
|
||||
<Search className='text-muted-foreground/60 pointer-events-none absolute top-1/2 left-3.5 size-4 -translate-y-1/2' />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type='text'
|
||||
placeholder={props.placeholder || t('Search models...')}
|
||||
value={props.value}
|
||||
onChange={(e) => props.onChange(e.target.value)}
|
||||
className={cn(
|
||||
'border-border/60 bg-background placeholder:text-muted-foreground/50',
|
||||
'hover:border-border',
|
||||
'focus:border-primary/50 focus:ring-primary/20 focus:ring-2',
|
||||
'h-10 w-full rounded-lg border pr-16 pl-10 text-sm transition-all outline-none'
|
||||
)}
|
||||
aria-label={t('Search models')}
|
||||
/>
|
||||
<div className='absolute top-1/2 right-2.5 flex -translate-y-1/2 items-center gap-1'>
|
||||
{props.value ? (
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
onClick={props.onClear}
|
||||
className='text-muted-foreground/60 hover:text-foreground size-7'
|
||||
aria-label={t('Clear search')}
|
||||
>
|
||||
<X className='size-4' />
|
||||
</Button>
|
||||
) : (
|
||||
<kbd className='bg-muted text-muted-foreground pointer-events-none hidden rounded border px-1.5 py-0.5 font-mono text-[10px] sm:inline-block'>
|
||||
⌘K
|
||||
</kbd>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user