feat(web/default): unified UI overhaul — Base UI migration, theme presets, rankings dashboard, and table toolbar refactor (#4633)
* 🎨 feat(web/default): add shadcn-style theme presets, radius prefs, and fix selection badges Integrate the qn-platform–style OKLCH color system into the default frontend while keeping the existing blue-tinted dark tokens for the default theme. Add [data-theme-preset] palettes for seven named presets plus the default zinc-like scale, define [data-theme-radius] overrides so user radius beats preset --radius, and align the Tailwind @custom-variant dark helper with .dark usage. Introduce ThemeCustomizationProvider to own preset and radius state, persist choices in cookies (theme-preset, theme-radius), and sync data-theme-preset / data-theme-radius on <html>. Wrap the tree in main.tsx. Extend ConfigDrawer with theme preset swatches (scoped data-theme-preset) and radius previews wired to context; refactor swatch/card markup so selected CircleCheck badges sit outside clipped rows (remove outer overflow-hidden that hid the centered checkmark). Add i18n keys for preset names, radius, and accessibility labels across en, zh, fr, ja, ru, vi. * 🎨 fix(web): align segmented controls with theme radius tokens - Replace hard-coded inner pill radii (rounded-[5px]) on dashboard chart toolbars with radius-md so the active state follows --radius when users change Radius in Theme Settings. - Use nested radii consistent with TabsList/TabsTrigger: outer rounded-lg (var(--radius)) and inner rounded-md (calc(var(--radius) - 2px)) so the track and active thumb stay concentric at small scales (e.g. 0.3rem) instead of a squared “focus” block inside a rounded shell. - Apply the same pattern to pricing SegmentedControl and the segmented groups in consumption-distribution-chart, model-charts, and user-charts. Verified: bun run typecheck (web/default) * ✨ feat(pricing): enrich model details with uptime sparkline and API documentation Add a compact 30-day uptime sparkline (OpenRouter-style bars + aggregate %) with per-day tooltips, surface it in a status row under quick stats and in the per-group performance table, and extend mock data so uptime series are stable and optionally scoped by group. Introduce an API tab with Shiki-highlighted code samples (cURL, Python, TypeScript, JavaScript), endpoint-type switching, authentication guidance, a supported-parameters table, and mock per-group RPM/TPM/RPD limits. Infer vendor, tokenizer, license, and data-retention hints for a provider & data privacy card on the Overview tab (capabilities/modalities stay with model identity; rate limits stay with the API tab). Update i18n for all new user-facing strings across en, zh, fr, ja, ru, and vi. * 🏆 feat(rankings): add comprehensive rankings dashboard Add a mock-data powered rankings experience with period tabs, model, app, and vendor leaderboards, market share and history charts, movers, new releases, and per-category sections while backend analytics are pending. Link ranked models to pricing details and ranked vendors to filtered pricing results, and include localized copy for all supported frontend locales. * fix(theme): correct theme preset selection state - update Base UI Radio selectors to use data-checked/data-unchecked states. - fix unchecked theme options still showing selected indicators. - isolate the default theme preview tokens to prevent preset changes from leaking into it. * fix(setup): correct usage mode radio state - use Base UI data-checked/data-unchecked states for RadioGroup styling. - hide radio indicators when options are unchecked to avoid setup page display issues. - drive usage mode card and icon selection styles from Base UI state. * fix(auth): submit sign-in and sign-up forms * 🎨 refactor: Align default theme with shadcn Base Nova and prune legacy customization Migrate shadcn UI to Base UI primitives via CLI (`base-nova` / `components.json`) and reinstall full component registry with `--overwrite`, including Hugeicons-backed widgets and newly added registry components. - Remove custom multi-preset/theme-radius system (`ThemeCustomizationProvider`, cookies, preset UI from config drawer); rely on official semantic CSS tokens + light/dark only. - Replace `theme.css` with shadcn’s documented neutral `:root`/`.dark` palette and `@theme inline` mappings (plus skeleton token vars for existing shimmer usage). - Update global styles for Base UI: collapsible animation uses `--collapsible-panel-height`; clarify scroll-lock override comment. Application compatibility: - Keep minimal shims where app code diverged from official APIs (popover collision props, combobox legacy `options` callers, Spinner prop typing). - Switch interactive styling from Radix-era `data-state` / `--radix-*` selectors to Base UI semantics (`data-open`, `data-popup-open`, `data-panel-open`, `--anchor-width`, etc.) Tooling / docs / build: - Rename Rsbuild vendor chunk grouping to `@base-ui` + transitive `@radix-ui`. - Refresh AGENTS.md / CLAUDE.md / classic→default sync skill for Base UI stack. - Bump `package.json` / lockfile for shadcn-postinstall deps (Hugeicons, chart stack, themes, etc.) Verified: `bun run typecheck` passes. Note: `bun run lint` still reports pre-existing hooks rule violations elsewhere; not addressed in this change. * 🎨 chore(web/default): unify table toolbar, relocate usage stats, refine filters - Refactor DataTableToolbar to a single wrapping flex row with a right-aligned action cluster (Reset / Search / View / Expand) for a cleaner Ant Design Pro–style filter bar; remove the dedicated stats row and the toolbar `stats` prop. - Move Common Logs summary badges (Usage / RPM / TPM) and the sensitive- data visibility toggle into the page header via CommonLogsHeaderActions and SectionPageLayout.Actions so the toolbar stays focused on filters. - Slim CommonLogsFilterBar props (no stats / preActions eye control). - Improve CompactDateTimeRangePicker: show minute-precision labels on the trigger (seconds omitted; aligns with datetime-local inputs); widen the trigger on sm+ breakpoints so the full range is visible without truncation; apply the same width in task logs filters. - Simplify DataTableViewOptions: text-only “View” trigger, no sliders icon. - Earlier layout tweak: extra top padding on SectionPageLayout scroll content so control focus rings are not clipped by overflow. * feat(web/default): Base UI migration and component foundation Migrate from Radix UI to Base UI, rewrite core UI primitives, update dependencies (recharts, date-fns, next-themes), add shadcn agent skill documentation, and refresh AI element components. This is the foundational work from the v2/localmain lineage that was not covered by the individual feature commits above. --------- Co-authored-by: t0ng7u <dev@aiass.cc> Co-authored-by: QuentinHsu <xuquentinyang@gmail.com>
This commit is contained in:
@@ -32,9 +32,9 @@ export function CacheTooltip({
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Zap className={`size-3 flex-shrink-0 ${color}`} />
|
||||
</TooltipTrigger>
|
||||
<TooltipTrigger
|
||||
render={<Zap className={`size-3 flex-shrink-0 ${color}`} />}
|
||||
></TooltipTrigger>
|
||||
<TooltipContent side='top'>
|
||||
<p className='text-xs'>
|
||||
{label}: {formatTokens(tokens)}
|
||||
@@ -144,7 +144,8 @@ export function createDurationColumn<T>(config: {
|
||||
return <span className='text-muted-foreground/60 text-xs'>-</span>
|
||||
}
|
||||
|
||||
const variant = duration.durationSec > warningThresholdSec ? 'red' : 'green'
|
||||
const variant =
|
||||
duration.durationSec > warningThresholdSec ? 'red' : 'green'
|
||||
|
||||
return (
|
||||
<span
|
||||
@@ -269,7 +270,7 @@ export function createProgressColumn<T>(config: {
|
||||
return <span className='text-muted-foreground/60 text-xs'>-</span>
|
||||
}
|
||||
return (
|
||||
<span className='inline-flex items-center rounded-md border border-border/60 bg-muted/30 px-1.5 py-0.5 font-mono text-xs'>
|
||||
<span className='border-border/60 bg-muted/30 inline-flex items-center rounded-md border px-1.5 py-0.5 font-mono text-xs'>
|
||||
{progress}
|
||||
</span>
|
||||
)
|
||||
|
||||
+88
-94
@@ -2,6 +2,7 @@ import { useState } from 'react'
|
||||
import { type ColumnDef } from '@tanstack/react-table'
|
||||
import { CircleAlert, Sparkles, KeyRound } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getUserAvatarFallback, getUserAvatarStyle } from '@/lib/avatar'
|
||||
import { formatBillingCurrencyFromUSD } from '@/lib/currency'
|
||||
import {
|
||||
formatUseTime,
|
||||
@@ -17,10 +18,7 @@ import {
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { DataTableColumnHeader } from '@/components/data-table'
|
||||
import {
|
||||
StatusBadge,
|
||||
type StatusBadgeProps,
|
||||
} from '@/components/status-badge'
|
||||
import { StatusBadge, type StatusBadgeProps } from '@/components/status-badge'
|
||||
import type { UsageLog } from '../../data/schema'
|
||||
import {
|
||||
formatModelName,
|
||||
@@ -31,7 +29,6 @@ import {
|
||||
parseLogOther,
|
||||
isViolationFeeLog,
|
||||
} from '../../lib/format'
|
||||
import { getLogAvatarStyle } from '../../lib/avatar-color'
|
||||
import {
|
||||
isDisplayableLogType,
|
||||
isTimingLogType,
|
||||
@@ -131,11 +128,9 @@ function buildDetailSegments(
|
||||
|
||||
const cacheEntries = tieredSummary.priceEntries
|
||||
.filter((entry) =>
|
||||
[
|
||||
'cacheReadPrice',
|
||||
'cacheCreatePrice',
|
||||
'cacheCreate1hPrice',
|
||||
].includes(entry.field)
|
||||
['cacheReadPrice', 'cacheCreatePrice', 'cacheCreate1hPrice'].includes(
|
||||
entry.field
|
||||
)
|
||||
)
|
||||
.map((entry) => {
|
||||
return formatPriceCompact(entry.price)
|
||||
@@ -194,8 +189,7 @@ function buildDetailSegments(
|
||||
other.cache_ratio != null && other.cache_ratio !== 1
|
||||
? formatPriceCompact(inputPriceUSD * other.cache_ratio)
|
||||
: null,
|
||||
other.cache_creation_ratio != null &&
|
||||
other.cache_creation_ratio !== 1
|
||||
other.cache_creation_ratio != null && other.cache_creation_ratio !== 1
|
||||
? formatPriceCompact(inputPriceUSD * other.cache_creation_ratio)
|
||||
: null,
|
||||
other.cache_creation_ratio_1h != null &&
|
||||
@@ -285,11 +279,8 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
<DataTableColumnHeader column={column} title={t('Channel')} />
|
||||
),
|
||||
cell: function ChannelCell({ row }) {
|
||||
const {
|
||||
sensitiveVisible,
|
||||
setAffinityTarget,
|
||||
setAffinityDialogOpen,
|
||||
} = useUsageLogsContext()
|
||||
const { sensitiveVisible, setAffinityTarget, setAffinityDialogOpen } =
|
||||
useUsageLogsContext()
|
||||
const log = row.original
|
||||
|
||||
if (!isDisplayableLogType(log.type)) return null
|
||||
@@ -310,48 +301,52 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className='flex max-w-[160px] flex-col gap-0.5'>
|
||||
<div className='relative inline-flex w-fit'>
|
||||
<StatusBadge
|
||||
label={channelIdDisplay}
|
||||
autoColor={String(log.channel)}
|
||||
copyText={String(log.channel)}
|
||||
size='sm'
|
||||
className='font-mono'
|
||||
/>
|
||||
{affinity && (
|
||||
<button
|
||||
type='button'
|
||||
className='absolute -top-1 -right-1 leading-none text-amber-500'
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setAffinityTarget({
|
||||
rule_name: affinity.rule_name || '',
|
||||
using_group:
|
||||
affinity.using_group ||
|
||||
affinity.selected_group ||
|
||||
'',
|
||||
key_hint: affinity.key_hint || '',
|
||||
key_fp: affinity.key_fp || '',
|
||||
})
|
||||
setAffinityDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Sparkles className='size-3 fill-current' />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{log.channel_name && (
|
||||
<span className='text-muted-foreground/70 truncate text-[11px]'>
|
||||
{channelName}
|
||||
</span>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<div className='flex max-w-[160px] flex-col gap-0.5' />
|
||||
}
|
||||
>
|
||||
<div className='relative inline-flex w-fit'>
|
||||
<StatusBadge
|
||||
label={channelIdDisplay}
|
||||
autoColor={String(log.channel)}
|
||||
copyText={String(log.channel)}
|
||||
size='sm'
|
||||
className='font-mono'
|
||||
/>
|
||||
{affinity && (
|
||||
<button
|
||||
type='button'
|
||||
className='absolute -top-1 -right-1 leading-none text-amber-500'
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setAffinityTarget({
|
||||
rule_name: affinity.rule_name || '',
|
||||
using_group:
|
||||
affinity.using_group ||
|
||||
affinity.selected_group ||
|
||||
'',
|
||||
key_hint: affinity.key_hint || '',
|
||||
key_fp: affinity.key_fp || '',
|
||||
})
|
||||
setAffinityDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Sparkles className='size-3 fill-current' />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{log.channel_name && (
|
||||
<span className='text-muted-foreground/70 truncate text-[11px]'>
|
||||
{channelName}
|
||||
</span>
|
||||
)}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className='space-y-1'>
|
||||
<p>{sensitiveVisible ? channelDisplay : channelIdDisplay}</p>
|
||||
<p>
|
||||
{sensitiveVisible ? channelDisplay : channelIdDisplay}
|
||||
</p>
|
||||
{channelChain && (
|
||||
<p className='text-muted-foreground text-xs'>
|
||||
{t('Chain')}: {channelChain}
|
||||
@@ -387,11 +382,8 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
<DataTableColumnHeader column={column} title={t('User')} />
|
||||
),
|
||||
cell: function UserCell({ row }) {
|
||||
const {
|
||||
sensitiveVisible,
|
||||
setSelectedUserId,
|
||||
setUserInfoDialogOpen,
|
||||
} = useUsageLogsContext()
|
||||
const { sensitiveVisible, setSelectedUserId, setUserInfoDialogOpen } =
|
||||
useUsageLogsContext()
|
||||
const log = row.original
|
||||
|
||||
if (!log.username) return null
|
||||
@@ -406,7 +398,7 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
setUserInfoDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Avatar className='size-6 ring-1 ring-border/60'>
|
||||
<Avatar className='ring-border/60 size-6 ring-1'>
|
||||
<AvatarFallback
|
||||
className={cn(
|
||||
'text-[11px] font-semibold',
|
||||
@@ -414,13 +406,11 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
)}
|
||||
style={
|
||||
sensitiveVisible
|
||||
? getLogAvatarStyle(log.username)
|
||||
? getUserAvatarStyle(log.username)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{sensitiveVisible
|
||||
? log.username.charAt(0).toUpperCase()
|
||||
: '•'}
|
||||
{sensitiveVisible ? getUserAvatarFallback(log.username) : '•'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className='text-muted-foreground truncate text-sm hover:underline'>
|
||||
@@ -467,7 +457,7 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
copyText={sensitiveVisible ? tokenName : undefined}
|
||||
size='sm'
|
||||
showDot={false}
|
||||
className='max-w-full overflow-hidden rounded-md border border-border/60 bg-muted/30 px-1.5 py-0.5 font-mono text-foreground'
|
||||
className='border-border/60 bg-muted/30 text-foreground max-w-full overflow-hidden rounded-md border px-1.5 py-0.5 font-mono'
|
||||
/>
|
||||
{metaParts.length > 0 && (
|
||||
<span className='text-muted-foreground/60 truncate text-[11px]'>
|
||||
@@ -521,10 +511,7 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
useTime > 0 && log.completion_tokens > 0
|
||||
? log.completion_tokens / useTime
|
||||
: null
|
||||
const timeVariant = getResponseTimeColor(
|
||||
useTime,
|
||||
log.completion_tokens
|
||||
)
|
||||
const timeVariant = getResponseTimeColor(useTime, log.completion_tokens)
|
||||
const frtVariant = frt ? getFirstResponseTimeColor(frt / 1000) : null
|
||||
|
||||
const pillBg: Record<string, string> = {
|
||||
@@ -565,21 +552,22 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
/>
|
||||
{formatUseTime(useTime)}
|
||||
</span>
|
||||
{log.is_stream && (frt != null && frt > 0 ? (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center rounded-md px-1.5 py-0.5 font-mono text-xs font-medium',
|
||||
pillBg[frtVariant!],
|
||||
pillText[frtVariant!]
|
||||
)}
|
||||
>
|
||||
{formatUseTime(frt / 1000)}
|
||||
</span>
|
||||
) : (
|
||||
<span className='inline-flex items-center rounded-md border border-border/60 px-1.5 py-0.5 text-[11px] text-muted-foreground/50'>
|
||||
N/A
|
||||
</span>
|
||||
))}
|
||||
{log.is_stream &&
|
||||
(frt != null && frt > 0 ? (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center rounded-md px-1.5 py-0.5 font-mono text-xs font-medium',
|
||||
pillBg[frtVariant!],
|
||||
pillText[frtVariant!]
|
||||
)}
|
||||
>
|
||||
{formatUseTime(frt / 1000)}
|
||||
</span>
|
||||
) : (
|
||||
<span className='border-border/60 text-muted-foreground/50 inline-flex items-center rounded-md border px-1.5 py-0.5 text-[11px]'>
|
||||
N/A
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className='flex items-center gap-1 text-[11px]'>
|
||||
<span className='text-muted-foreground/60'>
|
||||
@@ -599,9 +587,9 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
other.stream_status.status !== 'ok' && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<CircleAlert className='size-3 text-red-500' />
|
||||
</TooltipTrigger>
|
||||
<TooltipTrigger
|
||||
render={<CircleAlert className='size-3 text-red-500' />}
|
||||
></TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className='space-y-0.5 text-xs'>
|
||||
<p>
|
||||
@@ -654,7 +642,8 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
return (
|
||||
<div className='flex flex-col gap-0.5'>
|
||||
<span className='font-mono text-xs font-medium tabular-nums'>
|
||||
{promptTokens.toLocaleString()} / {completionTokens.toLocaleString()}
|
||||
{promptTokens.toLocaleString()} /{' '}
|
||||
{completionTokens.toLocaleString()}
|
||||
</span>
|
||||
{(cacheReadTokens > 0 || cacheWriteTokens > 0) && (
|
||||
<div className='flex items-center gap-1 text-[11px]'>
|
||||
@@ -693,11 +682,16 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className='inline-flex items-center gap-1 rounded-md border border-emerald-200 bg-emerald-50 px-1.5 py-0.5 text-xs font-medium text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300'>
|
||||
<span className='size-1.5 rounded-full bg-emerald-500' aria-hidden='true' />
|
||||
{t('Subscription')}
|
||||
</span>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span className='inline-flex items-center gap-1 rounded-md border border-emerald-200 bg-emerald-50 px-1.5 py-0.5 text-xs font-medium text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300' />
|
||||
}
|
||||
>
|
||||
<span
|
||||
className='size-1.5 rounded-full bg-emerald-500'
|
||||
aria-hidden='true'
|
||||
/>
|
||||
{t('Subscription')}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<span>
|
||||
@@ -713,7 +707,7 @@ export function useCommonLogsColumns(isAdmin: boolean): ColumnDef<UsageLog>[] {
|
||||
|
||||
return (
|
||||
<div className='flex flex-col gap-0.5'>
|
||||
<span className='border-border/80 inline-flex w-fit items-center rounded-md border bg-muted/60 px-1.5 py-0.5 font-mono text-xs font-semibold tabular-nums'>
|
||||
<span className='border-border/80 bg-muted/60 inline-flex w-fit items-center rounded-md border px-1.5 py-0.5 font-mono text-xs font-semibold tabular-nums'>
|
||||
{quotaStr}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -140,7 +140,7 @@ export function useDrawingLogsColumns(
|
||||
autoColor={mjId}
|
||||
size='sm'
|
||||
showDot={false}
|
||||
className='max-w-full truncate rounded-md border border-border/60 bg-muted/30 px-1.5 py-0.5 font-mono'
|
||||
className='border-border/60 bg-muted/30 max-w-full truncate rounded-md border px-1.5 py-0.5 font-mono'
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
+48
-59
@@ -3,24 +3,21 @@ import { useState, useMemo } from 'react'
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import { Music } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getUserAvatarFallback, getUserAvatarStyle } from '@/lib/avatar'
|
||||
import { formatTimestampToDate } from '@/lib/format'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
|
||||
import { DataTableColumnHeader } from '@/components/data-table'
|
||||
import { StatusBadge } from '@/components/status-badge'
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
|
||||
import { TASK_ACTIONS, TASK_STATUS } from '../../constants'
|
||||
import {
|
||||
taskActionMapper,
|
||||
taskStatusMapper,
|
||||
} from '../../lib/mappers'
|
||||
import { taskActionMapper, taskStatusMapper } from '../../lib/mappers'
|
||||
import type { TaskLog } from '../../types'
|
||||
import { getLogAvatarStyle } from '../../lib/avatar-color'
|
||||
import { useUsageLogsContext } from '../usage-logs-provider'
|
||||
import {
|
||||
AudioPreviewDialog,
|
||||
type AudioClip,
|
||||
} from '../dialogs/audio-preview-dialog'
|
||||
import { FailReasonDialog } from '../dialogs/fail-reason-dialog'
|
||||
import { useUsageLogsContext } from '../usage-logs-provider'
|
||||
import {
|
||||
createDurationColumn,
|
||||
createChannelColumn,
|
||||
@@ -60,7 +57,7 @@ function AudioPreviewCell({ log }: { log: TaskLog }) {
|
||||
className='group flex items-center gap-1 text-left text-xs'
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<Music className='size-3 text-muted-foreground' />
|
||||
<Music className='text-muted-foreground size-3' />
|
||||
<span className='text-foreground leading-snug group-hover:underline'>
|
||||
{t('Click to preview audio')}
|
||||
</span>
|
||||
@@ -106,56 +103,48 @@ export function useTaskLogsColumns(isAdmin: boolean): ColumnDef<TaskLog>[] {
|
||||
]
|
||||
|
||||
if (isAdmin) {
|
||||
columns.push(
|
||||
createChannelColumn<TaskLog>({ headerLabel: t('Channel') }),
|
||||
{
|
||||
id: 'user',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('User')} />
|
||||
),
|
||||
cell: function UserCell({ row }) {
|
||||
const {
|
||||
sensitiveVisible,
|
||||
setSelectedUserId,
|
||||
setUserInfoDialogOpen,
|
||||
} = useUsageLogsContext()
|
||||
const log = row.original
|
||||
const displayName = log.username || String(log.user_id || '?')
|
||||
columns.push(createChannelColumn<TaskLog>({ headerLabel: t('Channel') }), {
|
||||
id: 'user',
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title={t('User')} />
|
||||
),
|
||||
cell: function UserCell({ row }) {
|
||||
const { sensitiveVisible, setSelectedUserId, setUserInfoDialogOpen } =
|
||||
useUsageLogsContext()
|
||||
const log = row.original
|
||||
const displayName = log.username || String(log.user_id || '?')
|
||||
|
||||
return (
|
||||
<button
|
||||
type='button'
|
||||
className='flex items-center gap-1.5 text-left'
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setSelectedUserId(log.user_id)
|
||||
setUserInfoDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Avatar className='size-6 ring-1 ring-border/60'>
|
||||
<AvatarFallback
|
||||
className={cn(
|
||||
'text-[11px] font-semibold',
|
||||
!sensitiveVisible && 'bg-muted text-muted-foreground'
|
||||
)}
|
||||
style={
|
||||
sensitiveVisible ? getLogAvatarStyle(displayName) : undefined
|
||||
}
|
||||
>
|
||||
{sensitiveVisible
|
||||
? displayName.charAt(0).toUpperCase()
|
||||
: '•'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className='text-muted-foreground truncate text-sm hover:underline'>
|
||||
{sensitiveVisible ? displayName : '••••'}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
},
|
||||
meta: { label: t('User'), mobileHidden: true },
|
||||
}
|
||||
)
|
||||
return (
|
||||
<button
|
||||
type='button'
|
||||
className='flex items-center gap-1.5 text-left'
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setSelectedUserId(log.user_id)
|
||||
setUserInfoDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Avatar className='ring-border/60 size-6 ring-1'>
|
||||
<AvatarFallback
|
||||
className={cn(
|
||||
'text-[11px] font-semibold',
|
||||
!sensitiveVisible && 'bg-muted text-muted-foreground'
|
||||
)}
|
||||
style={
|
||||
sensitiveVisible ? getUserAvatarStyle(displayName) : undefined
|
||||
}
|
||||
>
|
||||
{sensitiveVisible ? getUserAvatarFallback(displayName) : '•'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className='text-muted-foreground truncate text-sm hover:underline'>
|
||||
{sensitiveVisible ? displayName : '••••'}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
},
|
||||
meta: { label: t('User'), mobileHidden: true },
|
||||
})
|
||||
}
|
||||
|
||||
columns.push(
|
||||
@@ -177,7 +166,7 @@ export function useTaskLogsColumns(isAdmin: boolean): ColumnDef<TaskLog>[] {
|
||||
autoColor={taskId}
|
||||
size='sm'
|
||||
showDot={false}
|
||||
className='max-w-full truncate rounded-md border border-border/60 bg-muted/30 px-1.5 py-0.5 font-mono'
|
||||
className='border-border/60 bg-muted/30 max-w-full truncate rounded-md border px-1.5 py-0.5 font-mono'
|
||||
/>
|
||||
<span className='text-muted-foreground/60 truncate text-[11px]'>
|
||||
{t(log.platform)} · {t(taskActionMapper.getLabel(log.action))}
|
||||
@@ -257,7 +246,7 @@ export function useTaskLogsColumns(isAdmin: boolean): ColumnDef<TaskLog>[] {
|
||||
href={videoUrl}
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='text-xs text-foreground hover:underline'
|
||||
className='text-foreground text-xs hover:underline'
|
||||
>
|
||||
{t('Click to preview video')}
|
||||
</a>
|
||||
|
||||
+100
-157
@@ -1,11 +1,9 @@
|
||||
import { useState, useEffect, useCallback, type ReactNode } from 'react'
|
||||
import { useNavigate, getRouteApi } from '@tanstack/react-router'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useQueryClient, useIsFetching } from '@tanstack/react-query'
|
||||
import { ChevronDown, Eye, EyeOff, Loader2, RotateCcw, Search } from 'lucide-react'
|
||||
import { useNavigate, getRouteApi } from '@tanstack/react-router'
|
||||
import { type Table } from '@tanstack/react-table'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useIsAdmin } from '@/hooks/use-admin'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Select,
|
||||
@@ -14,6 +12,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { DataTableToolbar } from '@/components/data-table'
|
||||
import { LOG_TYPES } from '../constants'
|
||||
import { buildSearchParams } from '../lib/filter'
|
||||
import { getDefaultTimeRange } from '../lib/utils'
|
||||
@@ -30,24 +29,21 @@ function isLogTypeValue(value: string): value is LogTypeValue {
|
||||
return (logTypeValues as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
interface CommonLogsFilterBarProps {
|
||||
stats?: ReactNode
|
||||
viewOptions?: ReactNode
|
||||
interface CommonLogsFilterBarProps<TData> {
|
||||
table: Table<TData>
|
||||
}
|
||||
|
||||
export function CommonLogsFilterBar({
|
||||
stats,
|
||||
viewOptions,
|
||||
}: CommonLogsFilterBarProps) {
|
||||
export function CommonLogsFilterBar<TData>(
|
||||
props: CommonLogsFilterBarProps<TData>
|
||||
) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const searchParams = route.useSearch()
|
||||
const isAdmin = useIsAdmin()
|
||||
const { sensitiveVisible, setSensitiveVisible } = useUsageLogsContext()
|
||||
const { sensitiveVisible } = useUsageLogsContext()
|
||||
const fetchingLogs = useIsFetching({ queryKey: ['logs'] })
|
||||
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [filters, setFilters] = useState<CommonLogFilters>(() => {
|
||||
const { start, end } = getDefaultTimeRange()
|
||||
return { startTime: start, endTime: end }
|
||||
@@ -140,10 +136,16 @@ export function CommonLogsFilterBar({
|
||||
!!filters.channel ||
|
||||
!!filters.requestId
|
||||
|
||||
const hasAdditionalFilters =
|
||||
!!filters.model || !!filters.group || !!logType || hasExpandedFilters
|
||||
|
||||
const inputClass = 'w-full sm:w-[140px] lg:w-[160px]'
|
||||
const sensitiveType = sensitiveVisible ? 'text' : 'password'
|
||||
|
||||
return (
|
||||
<div className='space-y-2 sm:space-y-3'>
|
||||
{/* Primary filter row */}
|
||||
<div className='grid grid-cols-2 gap-1.5 sm:grid-cols-4 sm:gap-2 lg:grid-cols-[minmax(280px,2fr)_minmax(140px,1fr)_minmax(120px,1fr)_minmax(120px,0.8fr)_auto]'>
|
||||
<DataTableToolbar
|
||||
table={props.table}
|
||||
customSearch={
|
||||
<CompactDateTimeRangePicker
|
||||
start={filters.startTime}
|
||||
end={filters.endTime}
|
||||
@@ -151,148 +153,89 @@ export function CommonLogsFilterBar({
|
||||
handleChange('startTime', start)
|
||||
handleChange('endTime', end)
|
||||
}}
|
||||
className='col-span-2 lg:col-span-1'
|
||||
className='w-full sm:w-[340px]'
|
||||
/>
|
||||
<Input
|
||||
placeholder={t('Model Name')}
|
||||
value={filters.model || ''}
|
||||
onChange={(e) => handleChange('model', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
/>
|
||||
<Input
|
||||
placeholder={t('Group')}
|
||||
type={sensitiveVisible ? 'text' : 'password'}
|
||||
value={filters.group || ''}
|
||||
onChange={(e) => handleChange('group', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
/>
|
||||
<Select
|
||||
value={logType}
|
||||
onValueChange={(value) => {
|
||||
setLogType(isLogTypeValue(value) ? value : '')
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className='h-9'>
|
||||
<SelectValue placeholder={t('All Types')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value='all'>{t('All Types')}</SelectItem>
|
||||
{LOG_TYPES.map((type) => (
|
||||
<SelectItem key={type.value} value={String(type.value)}>
|
||||
{t(type.label)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<button
|
||||
type='button'
|
||||
className={cn(
|
||||
'text-muted-foreground hover:text-foreground flex h-9 items-center gap-1 rounded-md px-2 text-xs transition-colors',
|
||||
hasExpandedFilters && !expanded && 'text-primary'
|
||||
)}
|
||||
onClick={() => setExpanded((p) => !p)}
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-3.5 transition-transform duration-200',
|
||||
expanded && 'rotate-180'
|
||||
)}
|
||||
}
|
||||
additionalSearch={
|
||||
<>
|
||||
<Input
|
||||
placeholder={t('Model Name')}
|
||||
value={filters.model || ''}
|
||||
onChange={(e) => handleChange('model', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={inputClass}
|
||||
/>
|
||||
{expanded ? t('Collapse') : t('Expand')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Expandable filter row */}
|
||||
<div
|
||||
className={cn(
|
||||
'grid gap-2 overflow-hidden transition-all duration-200',
|
||||
expanded
|
||||
? 'grid-rows-[1fr] opacity-100'
|
||||
: 'grid-rows-[0fr] opacity-0'
|
||||
)}
|
||||
>
|
||||
<div className='min-h-0 overflow-hidden'>
|
||||
<div className='grid grid-cols-2 gap-1.5 sm:grid-cols-4 sm:gap-2'>
|
||||
<Input
|
||||
placeholder={t('Token Name')}
|
||||
type={sensitiveVisible ? 'text' : 'password'}
|
||||
value={filters.token || ''}
|
||||
onChange={(e) => handleChange('token', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
/>
|
||||
{isAdmin && (
|
||||
<Input
|
||||
placeholder={t('Username')}
|
||||
type={sensitiveVisible ? 'text' : 'password'}
|
||||
value={filters.username || ''}
|
||||
onChange={(e) => handleChange('username', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
/>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Input
|
||||
placeholder={t('Channel ID')}
|
||||
value={filters.channel || ''}
|
||||
onChange={(e) => handleChange('channel', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
/>
|
||||
)}
|
||||
<Input
|
||||
placeholder={t('Request ID')}
|
||||
value={filters.requestId || ''}
|
||||
onChange={(e) => handleChange('requestId', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions row */}
|
||||
<div className='flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between'>
|
||||
<div className='flex min-w-0 flex-wrap items-center gap-2 sm:gap-3'>
|
||||
{stats && <div className='min-w-0'>{stats}</div>}
|
||||
</div>
|
||||
|
||||
<div className='flex shrink-0 items-center gap-2 self-end sm:self-auto'>
|
||||
<button
|
||||
type='button'
|
||||
className='text-muted-foreground hover:text-foreground inline-flex size-8 items-center justify-center rounded-md border transition-colors'
|
||||
title={sensitiveVisible ? t('Hide') : t('Show')}
|
||||
aria-label={sensitiveVisible ? t('Hide') : t('Show')}
|
||||
onClick={() => setSensitiveVisible(!sensitiveVisible)}
|
||||
<Input
|
||||
placeholder={t('Group')}
|
||||
type={sensitiveType}
|
||||
value={filters.group || ''}
|
||||
onChange={(e) => handleChange('group', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={inputClass}
|
||||
/>
|
||||
<Select
|
||||
value={logType}
|
||||
onValueChange={(value) => {
|
||||
setLogType(value !== null && isLogTypeValue(value) ? value : '')
|
||||
}}
|
||||
>
|
||||
{sensitiveVisible ? (
|
||||
<Eye className='size-3.5' />
|
||||
) : (
|
||||
<EyeOff className='size-3.5' />
|
||||
)}
|
||||
</button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-8'
|
||||
onClick={handleReset}
|
||||
>
|
||||
<RotateCcw className='size-3.5' />
|
||||
{t('Reset')}
|
||||
</Button>
|
||||
<Button size='sm' className='h-8' onClick={handleApply} disabled={fetchingLogs > 0}>
|
||||
{fetchingLogs > 0 ? (
|
||||
<Loader2 className='size-3.5 animate-spin' />
|
||||
) : (
|
||||
<Search className='size-3.5' />
|
||||
)}
|
||||
{t('Search')}
|
||||
</Button>
|
||||
{viewOptions}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<SelectTrigger className={inputClass}>
|
||||
<SelectValue placeholder={t('All Types')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value='all'>{t('All Types')}</SelectItem>
|
||||
{LOG_TYPES.map((type) => (
|
||||
<SelectItem key={type.value} value={String(type.value)}>
|
||||
{t(type.label)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</>
|
||||
}
|
||||
expandable={
|
||||
<>
|
||||
<Input
|
||||
placeholder={t('Token Name')}
|
||||
type={sensitiveType}
|
||||
value={filters.token || ''}
|
||||
onChange={(e) => handleChange('token', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={inputClass}
|
||||
/>
|
||||
{isAdmin && (
|
||||
<Input
|
||||
placeholder={t('Username')}
|
||||
type={sensitiveType}
|
||||
value={filters.username || ''}
|
||||
onChange={(e) => handleChange('username', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={inputClass}
|
||||
/>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<Input
|
||||
placeholder={t('Channel ID')}
|
||||
value={filters.channel || ''}
|
||||
onChange={(e) => handleChange('channel', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={inputClass}
|
||||
/>
|
||||
)}
|
||||
<Input
|
||||
placeholder={t('Request ID')}
|
||||
value={filters.requestId || ''}
|
||||
onChange={(e) => handleChange('requestId', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={inputClass}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
hasExpandedActiveFilters={hasExpandedFilters}
|
||||
hasAdditionalFilters={hasAdditionalFilters}
|
||||
onSearch={handleApply}
|
||||
searchLoading={fetchingLogs > 0}
|
||||
onReset={handleReset}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { Eye, EyeOff } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { CommonLogsStats } from './common-logs-stats'
|
||||
import { useUsageLogsContext } from './usage-logs-provider'
|
||||
|
||||
/**
|
||||
* Page-header actions for the Common Logs view: live usage stats plus a
|
||||
* toggle for masking sensitive values (token names, usernames, group names,
|
||||
* and the quota figure shown in stats). Both controls live in the page
|
||||
* header so the toolbar below stays focused on filter inputs and form
|
||||
* actions only.
|
||||
*/
|
||||
export function CommonLogsHeaderActions() {
|
||||
const { t } = useTranslation()
|
||||
const { sensitiveVisible, setSensitiveVisible } = useUsageLogsContext()
|
||||
|
||||
return (
|
||||
<div className='flex flex-wrap items-center gap-2'>
|
||||
<CommonLogsStats />
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
onClick={() => setSensitiveVisible(!sensitiveVisible)}
|
||||
aria-label={sensitiveVisible ? t('Hide') : t('Show')}
|
||||
className='text-muted-foreground hover:text-foreground size-7'
|
||||
/>
|
||||
}
|
||||
>
|
||||
{sensitiveVisible ? <Eye /> : <EyeOff />}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{sensitiveVisible ? t('Hide') : t('Show')}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,10 +18,10 @@ function StatBadge(props: {
|
||||
accent: string
|
||||
}) {
|
||||
return (
|
||||
<span className='inline-flex h-7 items-center gap-2 rounded-md border border-border/60 bg-muted/25 px-2.5 text-xs shadow-xs'>
|
||||
<span className='border-border/60 bg-muted/25 inline-flex h-7 items-center gap-2 rounded-md border px-2.5 text-xs shadow-xs'>
|
||||
<span className={cn('h-3.5 w-0.5 rounded-full', props.accent)} />
|
||||
<span className='text-muted-foreground'>{props.label}</span>
|
||||
<span className='font-mono font-semibold tabular-nums text-foreground/85'>
|
||||
<span className='text-foreground/85 font-mono font-semibold tabular-nums'>
|
||||
{props.value}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
+25
-16
@@ -41,8 +41,12 @@ export function CompactDateTimeRangePicker({
|
||||
|
||||
const label = useMemo(() => {
|
||||
if (!start && !end) return t('Date Range')
|
||||
const startText = start ? dayjs(start).format('YYYY-MM-DD HH:mm:ss') : '-'
|
||||
const endText = end ? dayjs(end).format('YYYY-MM-DD HH:mm:ss') : '-'
|
||||
// The popover's <input type="datetime-local"> only supports minute
|
||||
// precision, so seconds are always 00 (manual pick) or 59 (preset
|
||||
// end-of-day). Hide them in the trigger label to keep the button
|
||||
// width compact while still showing the meaningful timestamp.
|
||||
const startText = start ? dayjs(start).format('YYYY-MM-DD HH:mm') : '-'
|
||||
const endText = end ? dayjs(end).format('YYYY-MM-DD HH:mm') : '-'
|
||||
return `${startText} ~ ${endText}`
|
||||
}, [end, start, t])
|
||||
|
||||
@@ -95,21 +99,26 @@ export function CompactDateTimeRangePicker({
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={handleOpenChange}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
className={cn(
|
||||
'h-9 w-full justify-start gap-2 px-3 font-mono text-xs font-normal',
|
||||
!start && !end && 'text-muted-foreground',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<CalendarDays className='text-muted-foreground size-4 shrink-0' />
|
||||
<span className='truncate'>{label}</span>
|
||||
</Button>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
className={cn(
|
||||
'w-full justify-start gap-2 px-2.5 font-mono text-xs font-normal',
|
||||
!start && !end && 'text-muted-foreground',
|
||||
className
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<CalendarDays className='text-muted-foreground size-4 shrink-0' />
|
||||
<span className='truncate'>{label}</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align='start' className='w-[min(520px,calc(100vw-2rem))] p-3'>
|
||||
<PopoverContent
|
||||
align='start'
|
||||
className='w-[min(520px,calc(100vw-2rem))] p-3'
|
||||
>
|
||||
<div className='space-y-3'>
|
||||
<div className='grid gap-2 sm:grid-cols-[1fr_auto_1fr] sm:items-end'>
|
||||
<div className='space-y-1.5'>
|
||||
|
||||
@@ -69,7 +69,7 @@ function DetailRow(props: {
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'min-w-0 max-w-full text-xs break-all sm:break-words',
|
||||
'max-w-full min-w-0 text-xs break-all sm:break-words',
|
||||
props.mono && 'font-mono',
|
||||
props.muted && 'text-muted-foreground'
|
||||
)}
|
||||
@@ -491,7 +491,7 @@ export function DetailsDialog(props: DetailsDialogProps) {
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className='max-h-[70vh] min-w-0 overflow-hidden pr-2 max-sm:max-h-[calc(100dvh-7rem)] sm:pr-4'>
|
||||
<div className='w-full min-w-0 max-w-full space-y-2.5 overflow-hidden py-1 sm:space-y-3'>
|
||||
<div className='w-full max-w-full min-w-0 space-y-2.5 overflow-hidden py-1 sm:space-y-3'>
|
||||
{/* Overview section - key identifiers */}
|
||||
<div className='min-w-0 space-y-1'>
|
||||
{props.log.request_id && (
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
/**
|
||||
* Reusable components for filter dialogs
|
||||
*/
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
// ============================================================================
|
||||
// Filter Input Component
|
||||
// ============================================================================
|
||||
|
||||
interface FilterInputProps {
|
||||
id: string
|
||||
label: string
|
||||
placeholder: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
export function FilterInput({
|
||||
id,
|
||||
label,
|
||||
placeholder,
|
||||
value,
|
||||
onChange,
|
||||
}: FilterInputProps) {
|
||||
return (
|
||||
<div className='grid gap-2'>
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
<Input
|
||||
id={id}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Section Divider Component
|
||||
// ============================================================================
|
||||
|
||||
interface SectionDividerProps {
|
||||
label: string
|
||||
}
|
||||
|
||||
export function SectionDivider({ label }: SectionDividerProps) {
|
||||
return (
|
||||
<div className='relative'>
|
||||
<div className='absolute inset-0 flex items-center'>
|
||||
<span className='w-full border-t' />
|
||||
</div>
|
||||
<div className='relative flex justify-center text-xs uppercase'>
|
||||
<span className='bg-background text-muted-foreground px-2'>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
-371
@@ -1,371 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useNavigate, getRouteApi } from '@tanstack/react-router'
|
||||
import { Search, RotateCcw, Calendar } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getNormalizedDateRange } from '@/lib/time'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useIsAdmin } from '@/hooks/use-admin'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ComboboxInput } from '@/components/ui/combobox-input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { DateTimePicker } from '@/components/datetime-picker'
|
||||
import { getApiKeys } from '@/features/keys/api'
|
||||
import { TIME_RANGE_PRESETS } from '../../constants'
|
||||
import { buildSearchParams, getLogCategoryLabel } from '../../lib/filter'
|
||||
import { getDefaultTimeRange } from '../../lib/utils'
|
||||
import type {
|
||||
LogCategory,
|
||||
LogFilters,
|
||||
CommonLogFilters,
|
||||
DrawingLogFilters,
|
||||
TaskLogFilters,
|
||||
} from '../../types'
|
||||
import { FilterInput, SectionDivider } from './filter-components'
|
||||
|
||||
const route = getRouteApi('/_authenticated/usage-logs/$section')
|
||||
|
||||
interface UsageLogsFilterDialogProps {
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
onFilterChange?: (filters: LogFilters) => void
|
||||
logCategory: LogCategory
|
||||
}
|
||||
|
||||
export function UsageLogsFilterDialog({
|
||||
open: controlledOpen,
|
||||
onOpenChange: controlledOnOpenChange,
|
||||
onFilterChange,
|
||||
logCategory,
|
||||
}: UsageLogsFilterDialogProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const searchParams = route.useSearch()
|
||||
const isAdmin = useIsAdmin()
|
||||
const [internalOpen, setInternalOpen] = useState(false)
|
||||
|
||||
const open = controlledOpen ?? internalOpen
|
||||
const setOpen = controlledOnOpenChange ?? setInternalOpen
|
||||
|
||||
const [filters, setFilters] = useState<LogFilters>(() => {
|
||||
const { start, end } = getDefaultTimeRange()
|
||||
return { startTime: start, endTime: end }
|
||||
})
|
||||
const [selectedRange, setSelectedRange] = useState<number | null>(null)
|
||||
|
||||
const { data: tokensData } = useQuery({
|
||||
queryKey: ['api-keys', 'filter', open, logCategory],
|
||||
queryFn: () => getApiKeys({ p: 1, size: 200 }),
|
||||
enabled: open && logCategory === 'common',
|
||||
})
|
||||
|
||||
const tokenNameOptions = useMemo(() => {
|
||||
const items = tokensData?.data?.items ?? []
|
||||
const seen = new Set<string>()
|
||||
return items
|
||||
.filter((item) => {
|
||||
if (seen.has(item.name)) return false
|
||||
seen.add(item.name)
|
||||
return true
|
||||
})
|
||||
.map((item) => ({ value: item.name, label: item.name }))
|
||||
}, [tokensData?.data?.items])
|
||||
|
||||
// Sync filters from URL
|
||||
useEffect(() => {
|
||||
const urlFilters: Partial<LogFilters> = {}
|
||||
|
||||
if (searchParams.startTime)
|
||||
urlFilters.startTime = new Date(searchParams.startTime)
|
||||
if (searchParams.endTime)
|
||||
urlFilters.endTime = new Date(searchParams.endTime)
|
||||
if (searchParams.channel) urlFilters.channel = String(searchParams.channel)
|
||||
|
||||
if (logCategory === 'common') {
|
||||
if (searchParams.model)
|
||||
(urlFilters as CommonLogFilters).model = searchParams.model
|
||||
if (searchParams.token)
|
||||
(urlFilters as CommonLogFilters).token = searchParams.token
|
||||
if (searchParams.group)
|
||||
(urlFilters as CommonLogFilters).group = searchParams.group
|
||||
if (searchParams.username)
|
||||
(urlFilters as CommonLogFilters).username = searchParams.username
|
||||
if (searchParams.requestId)
|
||||
(urlFilters as CommonLogFilters).requestId = searchParams.requestId
|
||||
} else if (logCategory === 'drawing') {
|
||||
if (searchParams.filter)
|
||||
(urlFilters as DrawingLogFilters).mjId = searchParams.filter
|
||||
} else if (logCategory === 'task') {
|
||||
if (searchParams.filter)
|
||||
(urlFilters as TaskLogFilters).taskId = searchParams.filter
|
||||
}
|
||||
|
||||
if (Object.keys(urlFilters).length > 0) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setFilters((prev: LogFilters) => ({ ...prev, ...urlFilters }))
|
||||
setSelectedRange(null)
|
||||
}
|
||||
}, [
|
||||
logCategory,
|
||||
searchParams.startTime,
|
||||
searchParams.endTime,
|
||||
searchParams.channel,
|
||||
searchParams.model,
|
||||
searchParams.token,
|
||||
searchParams.group,
|
||||
searchParams.username,
|
||||
searchParams.requestId,
|
||||
searchParams.filter,
|
||||
])
|
||||
|
||||
const handleChange = useCallback(
|
||||
(field: string, value: Date | string | undefined) => {
|
||||
setFilters((prev: LogFilters) => ({ ...prev, [field]: value }))
|
||||
if (field === 'startTime' || field === 'endTime') {
|
||||
setSelectedRange(null)
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const handleQuickRange = useCallback((days: number) => {
|
||||
const { start, end } = getNormalizedDateRange(days)
|
||||
setFilters((prev: LogFilters) => ({
|
||||
...prev,
|
||||
startTime: start,
|
||||
endTime: end,
|
||||
}))
|
||||
setSelectedRange(days)
|
||||
}, [])
|
||||
|
||||
const navigateWithFilters = useCallback(
|
||||
(searchUpdate: Record<string, unknown>) => {
|
||||
navigate({
|
||||
to: '/usage-logs/$section',
|
||||
params: { section: logCategory },
|
||||
search: (prev: Record<string, unknown>) => ({
|
||||
...prev,
|
||||
...searchUpdate,
|
||||
}),
|
||||
})
|
||||
},
|
||||
[navigate, logCategory]
|
||||
)
|
||||
|
||||
const handleApply = useCallback(() => {
|
||||
const filterParams = buildSearchParams(filters, logCategory)
|
||||
navigateWithFilters(filterParams)
|
||||
onFilterChange?.(filters)
|
||||
setOpen(false)
|
||||
}, [filters, logCategory, navigateWithFilters, onFilterChange, setOpen])
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
const { start, end } = getDefaultTimeRange()
|
||||
const resetFilters: LogFilters = { startTime: start, endTime: end }
|
||||
|
||||
setFilters(resetFilters)
|
||||
setSelectedRange(null)
|
||||
|
||||
navigate({
|
||||
to: '/usage-logs/$section',
|
||||
params: { section: logCategory },
|
||||
search: {
|
||||
page: 1,
|
||||
startTime: start.getTime(),
|
||||
endTime: end.getTime(),
|
||||
},
|
||||
})
|
||||
|
||||
onFilterChange?.(resetFilters)
|
||||
setOpen(false)
|
||||
}, [navigate, logCategory, onFilterChange, setOpen])
|
||||
|
||||
// Render category-specific filters
|
||||
const renderCategoryFilters = () => {
|
||||
switch (logCategory) {
|
||||
case 'common': {
|
||||
const commonFilters = filters as CommonLogFilters
|
||||
return (
|
||||
<>
|
||||
<FilterInput
|
||||
id='model'
|
||||
label={t('Model Name')}
|
||||
placeholder={t('e.g., gpt-4, claude-3')}
|
||||
value={commonFilters.model || ''}
|
||||
onChange={(value) => handleChange('model', value)}
|
||||
/>
|
||||
<div className='grid gap-2'>
|
||||
<Label htmlFor='token'>{t('Token Name')}</Label>
|
||||
<ComboboxInput
|
||||
id='token'
|
||||
options={tokenNameOptions}
|
||||
value={commonFilters.token || ''}
|
||||
onValueChange={(v) => handleChange('token', v)}
|
||||
placeholder={t('Filter by token name')}
|
||||
emptyText={t('No token found.')}
|
||||
/>
|
||||
</div>
|
||||
<FilterInput
|
||||
id='group'
|
||||
label={t('Group')}
|
||||
placeholder={t('Filter by group')}
|
||||
value={commonFilters.group || ''}
|
||||
onChange={(value) => handleChange('group', value)}
|
||||
/>
|
||||
{isAdmin && (
|
||||
<FilterInput
|
||||
id='username'
|
||||
label={t('Username')}
|
||||
placeholder={t('Filter by username')}
|
||||
value={commonFilters.username || ''}
|
||||
onChange={(value) => handleChange('username', value)}
|
||||
/>
|
||||
)}
|
||||
<FilterInput
|
||||
id='requestId'
|
||||
label={t('Request ID')}
|
||||
placeholder={t('Filter by request ID')}
|
||||
value={commonFilters.requestId || ''}
|
||||
onChange={(value) => handleChange('requestId', value)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
case 'drawing': {
|
||||
const drawingFilters = filters as DrawingLogFilters
|
||||
return (
|
||||
<FilterInput
|
||||
id='mjId'
|
||||
label={t('Task ID')}
|
||||
placeholder={t('Filter by task ID')}
|
||||
value={drawingFilters.mjId || ''}
|
||||
onChange={(value) => handleChange('mjId', value)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
case 'task': {
|
||||
const taskFilters = filters as TaskLogFilters
|
||||
return (
|
||||
<FilterInput
|
||||
id='taskId'
|
||||
label={t('Task ID')}
|
||||
placeholder={t('Filter by task ID')}
|
||||
value={taskFilters.taskId || ''}
|
||||
onChange={(value) => handleChange('taskId', value)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className='flex max-h-[calc(100dvh-2rem)] flex-col max-sm:h-dvh max-sm:w-screen max-sm:max-w-none max-sm:rounded-none max-sm:p-4 sm:max-w-lg'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t('Filter')} {t(getLogCategoryLabel(logCategory))} {t('Logs')}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('Set filters to narrow down your log search results.')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className='min-h-0 flex-1 pr-3 sm:max-h-[60vh] sm:pr-4'>
|
||||
<div className='grid gap-3 py-3 sm:gap-4 sm:py-4'>
|
||||
{/* Quick time range selection */}
|
||||
<div className='grid gap-2'>
|
||||
<Label className='flex items-center gap-2'>
|
||||
<Calendar className='h-4 w-4' />
|
||||
{t('Quick Range')}
|
||||
</Label>
|
||||
<div className='grid grid-cols-2 gap-2 sm:flex'>
|
||||
{TIME_RANGE_PRESETS.map((range) => (
|
||||
<Button
|
||||
key={range.days}
|
||||
type='button'
|
||||
size='sm'
|
||||
variant={
|
||||
selectedRange === range.days ? 'default' : 'outline'
|
||||
}
|
||||
onClick={() => handleQuickRange(range.days)}
|
||||
className={cn(
|
||||
'flex-1',
|
||||
selectedRange === range.days &&
|
||||
'ring-ring ring-2 ring-offset-2'
|
||||
)}
|
||||
>
|
||||
{t(range.label)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SectionDivider label={t('Custom Time Range')} />
|
||||
|
||||
{/* Custom time range */}
|
||||
<div className='grid gap-3 sm:gap-4'>
|
||||
<div className='grid gap-2'>
|
||||
<Label htmlFor='start_time'>{t('Start Time')}</Label>
|
||||
<DateTimePicker
|
||||
value={filters.startTime}
|
||||
onChange={(date) =>
|
||||
handleChange('startTime', date || undefined)
|
||||
}
|
||||
placeholder={t('Select start time')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='grid gap-2'>
|
||||
<Label htmlFor='end_time'>{t('End Time')}</Label>
|
||||
<DateTimePicker
|
||||
value={filters.endTime}
|
||||
onChange={(date) =>
|
||||
handleChange('endTime', date || undefined)
|
||||
}
|
||||
placeholder={t('Select end time')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SectionDivider label={t('Filters')} />
|
||||
|
||||
{renderCategoryFilters()}
|
||||
|
||||
{/* Channel filter (admin only, all log types) */}
|
||||
{isAdmin && (
|
||||
<FilterInput
|
||||
id='channel'
|
||||
label={t('Channel ID')}
|
||||
placeholder={t('Filter by channel ID')}
|
||||
value={filters.channel || ''}
|
||||
onChange={(value) => handleChange('channel', value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter className='grid grid-cols-2 gap-2 sm:flex'>
|
||||
<Button onClick={handleReset} variant='outline' type='button'>
|
||||
<RotateCcw className='mr-2 h-4 w-4' />
|
||||
{t('Reset')}
|
||||
</Button>
|
||||
<Button onClick={handleApply} type='submit'>
|
||||
<Search className='mr-2 h-4 w-4' />
|
||||
{t('Apply Filters')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -83,7 +83,7 @@ function ModelBadgeContent(props: ModelBadgeProps) {
|
||||
showDot={!provider}
|
||||
autoColor={provider ? undefined : props.modelName}
|
||||
className={cn(
|
||||
'rounded-md border border-border/60 bg-muted/30 px-1.5 py-0.5 font-mono',
|
||||
'border-border/60 bg-muted/30 rounded-md border px-1.5 py-0.5 font-mono',
|
||||
provider && 'text-foreground',
|
||||
props.className
|
||||
)}
|
||||
@@ -113,11 +113,13 @@ export function ModelBadge(props: ModelBadgeProps) {
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button type='button' className='inline-flex items-center gap-1'>
|
||||
<ModelBadgeContent {...props} />
|
||||
<Route className='text-muted-foreground size-3 shrink-0' />
|
||||
</button>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<button type='button' className='inline-flex items-center gap-1' />
|
||||
}
|
||||
>
|
||||
<ModelBadgeContent {...props} />
|
||||
<Route className='text-muted-foreground size-3 shrink-0' />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className='w-72'>
|
||||
<div className='space-y-2'>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState, useEffect, useCallback, type ReactNode } from 'react'
|
||||
import { useNavigate, getRouteApi } from '@tanstack/react-router'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useQueryClient, useIsFetching } from '@tanstack/react-query'
|
||||
import { Loader2, RotateCcw, Search } from 'lucide-react'
|
||||
import { useNavigate, getRouteApi } from '@tanstack/react-router'
|
||||
import { type Table } from '@tanstack/react-table'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useIsAdmin } from '@/hooks/use-admin'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { DataTableToolbar } from '@/components/data-table'
|
||||
import { buildSearchParams } from '../lib/filter'
|
||||
import { getDefaultTimeRange } from '../lib/utils'
|
||||
import type { DrawingLogFilters, LogCategory, TaskLogFilters } from '../types'
|
||||
@@ -16,13 +16,9 @@ const route = getRouteApi('/_authenticated/usage-logs/$section')
|
||||
type TaskLikeLogCategory = Extract<LogCategory, 'drawing' | 'task'>
|
||||
type TaskLogsFilters = DrawingLogFilters | TaskLogFilters
|
||||
|
||||
interface TaskLogsFilterBarProps {
|
||||
interface TaskLogsFilterBarProps<TData> {
|
||||
table: Table<TData>
|
||||
logCategory: TaskLikeLogCategory
|
||||
viewOptions?: ReactNode
|
||||
}
|
||||
|
||||
function getFilterPlaceholder(_logCategory: TaskLikeLogCategory): string {
|
||||
return 'Filter by task ID'
|
||||
}
|
||||
|
||||
function getFilterValue(
|
||||
@@ -46,7 +42,7 @@ function setFilterValue(
|
||||
return { ...filters, taskId: value }
|
||||
}
|
||||
|
||||
export function TaskLogsFilterBar(props: TaskLogsFilterBarProps) {
|
||||
export function TaskLogsFilterBar<TData>(props: TaskLogsFilterBarProps<TData>) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
@@ -62,9 +58,13 @@ export function TaskLogsFilterBar(props: TaskLogsFilterBarProps) {
|
||||
useEffect(() => {
|
||||
const { start, end } = getDefaultTimeRange()
|
||||
const baseFilters = {
|
||||
startTime: searchParams.startTime ? new Date(searchParams.startTime) : start,
|
||||
startTime: searchParams.startTime
|
||||
? new Date(searchParams.startTime)
|
||||
: start,
|
||||
endTime: searchParams.endTime ? new Date(searchParams.endTime) : end,
|
||||
...(searchParams.channel ? { channel: String(searchParams.channel) } : {}),
|
||||
...(searchParams.channel
|
||||
? { channel: String(searchParams.channel) }
|
||||
: {}),
|
||||
}
|
||||
const next: TaskLogsFilters =
|
||||
props.logCategory === 'drawing'
|
||||
@@ -137,9 +137,18 @@ export function TaskLogsFilterBar(props: TaskLogsFilterBarProps) {
|
||||
[props.logCategory]
|
||||
)
|
||||
|
||||
const filterValue = getFilterValue(filters, props.logCategory)
|
||||
const placeholder =
|
||||
props.logCategory === 'drawing'
|
||||
? t('Filter by Midjourney task ID')
|
||||
: t('Filter by task ID')
|
||||
const inputClass = 'w-full sm:w-[180px] lg:w-[200px]'
|
||||
const hasAdditionalFilters = !!filterValue || !!filters.channel
|
||||
|
||||
return (
|
||||
<div className='space-y-2 sm:space-y-3'>
|
||||
<div className='grid grid-cols-2 gap-1.5 sm:gap-2 lg:grid-cols-[minmax(280px,2fr)_minmax(180px,1fr)_minmax(120px,0.8fr)_auto]'>
|
||||
<DataTableToolbar
|
||||
table={props.table}
|
||||
customSearch={
|
||||
<CompactDateTimeRangePicker
|
||||
start={filters.startTime}
|
||||
end={filters.endTime}
|
||||
@@ -147,51 +156,34 @@ export function TaskLogsFilterBar(props: TaskLogsFilterBarProps) {
|
||||
handleChange('startTime', start)
|
||||
handleChange('endTime', end)
|
||||
}}
|
||||
className='col-span-2 lg:col-span-1'
|
||||
className='w-full sm:w-[340px]'
|
||||
/>
|
||||
<Input
|
||||
aria-label={t('Task ID')}
|
||||
placeholder={t(getFilterPlaceholder(props.logCategory))}
|
||||
value={getFilterValue(filters, props.logCategory)}
|
||||
onChange={(e) => handleFilterChange(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
/>
|
||||
{isAdmin && (
|
||||
}
|
||||
additionalSearch={
|
||||
<>
|
||||
<Input
|
||||
placeholder={t('Channel ID')}
|
||||
value={filters.channel || ''}
|
||||
onChange={(e) => handleChange('channel', e.target.value)}
|
||||
aria-label={t('Task ID')}
|
||||
placeholder={placeholder}
|
||||
value={filterValue}
|
||||
onChange={(e) => handleFilterChange(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className='h-9'
|
||||
className={inputClass}
|
||||
/>
|
||||
)}
|
||||
<div className='col-span-2 flex shrink-0 items-center justify-end gap-1.5 sm:gap-2 lg:col-span-1'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-8'
|
||||
onClick={handleReset}
|
||||
>
|
||||
<RotateCcw className='size-3.5' />
|
||||
{t('Reset')}
|
||||
</Button>
|
||||
<Button
|
||||
size='sm'
|
||||
className='h-8'
|
||||
onClick={handleApply}
|
||||
disabled={fetchingLogs > 0}
|
||||
>
|
||||
{fetchingLogs > 0 ? (
|
||||
<Loader2 className='size-3.5 animate-spin' />
|
||||
) : (
|
||||
<Search className='size-3.5' />
|
||||
)}
|
||||
{t('Search')}
|
||||
</Button>
|
||||
{props.viewOptions}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isAdmin && (
|
||||
<Input
|
||||
placeholder={t('Channel ID')}
|
||||
value={filters.channel || ''}
|
||||
onChange={(e) => handleChange('channel', e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={inputClass}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
hasAdditionalFilters={hasAdditionalFilters}
|
||||
onSearch={handleApply}
|
||||
searchLoading={fetchingLogs > 0}
|
||||
onReset={handleReset}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { Search } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { LogCategory } from '../types'
|
||||
import { UsageLogsFilterDialog } from './dialogs/usage-logs-filter-dialog'
|
||||
|
||||
interface UsageLogsPrimaryButtonsProps {
|
||||
logCategory: LogCategory
|
||||
}
|
||||
|
||||
export function UsageLogsPrimaryButtons({
|
||||
logCategory,
|
||||
}: UsageLogsPrimaryButtonsProps) {
|
||||
const { t } = useTranslation()
|
||||
const [filterDialogOpen, setFilterDialogOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<div className='flex gap-2'>
|
||||
<Button size='sm' onClick={() => setFilterDialogOpen(true)}>
|
||||
<Search className='h-4 w-4' />
|
||||
{t('Search')}
|
||||
</Button>
|
||||
|
||||
<UsageLogsFilterDialog
|
||||
open={filterDialogOpen}
|
||||
onOpenChange={setFilterDialogOpen}
|
||||
logCategory={logCategory}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+37
-115
@@ -17,28 +17,13 @@ import { toast } from 'sonner'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useIsAdmin } from '@/hooks/use-admin'
|
||||
import { useTableUrlState } from '@/hooks/use-table-url-state'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
DataTablePagination,
|
||||
DataTableViewOptions,
|
||||
TableSkeleton,
|
||||
TableEmpty,
|
||||
MobileCardList,
|
||||
} from '@/components/data-table'
|
||||
import { PageFooterPortal } from '@/components/layout'
|
||||
import { TableCell, TableRow } from '@/components/ui/table'
|
||||
import { DataTablePage } from '@/components/data-table'
|
||||
import { DEFAULT_LOGS_DATA, LOG_TYPE_ENUM } from '../constants'
|
||||
import { useColumnsByCategory } from '../lib/columns'
|
||||
import { fetchLogsByCategory } from '../lib/utils'
|
||||
import type { LogCategory } from '../types'
|
||||
import { CommonLogsFilterBar } from './common-logs-filter-bar'
|
||||
import { CommonLogsStats } from './common-logs-stats'
|
||||
import { TaskLogsFilterBar } from './task-logs-filter-bar'
|
||||
|
||||
const route = getRouteApi('/_authenticated/usage-logs/$section')
|
||||
@@ -157,105 +142,42 @@ export function UsageLogsTable({ logCategory }: UsageLogsTableProps) {
|
||||
|
||||
const isCommon = logCategory === 'common'
|
||||
|
||||
const renderRows = () => {
|
||||
const rows = table.getRowModel().rows
|
||||
if (rows.length === 0) return null
|
||||
|
||||
return rows.map((row) => {
|
||||
const logType = (row.original as Record<string, unknown>).type as
|
||||
| number
|
||||
| undefined
|
||||
const tintClass =
|
||||
isCommon && logType != null ? (logTypeRowTint[logType] ?? '') : ''
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
className={cn('transition-colors', tintClass)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id} className={isCommon ? 'py-2' : 'py-3.5'}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='space-y-3 sm:space-y-4'>
|
||||
{logCategory === 'common' ? (
|
||||
<div className='rounded-md border bg-card/50 p-2 shadow-xs sm:p-3'>
|
||||
<CommonLogsFilterBar
|
||||
stats={<CommonLogsStats />}
|
||||
viewOptions={<DataTableViewOptions table={table} />}
|
||||
/>
|
||||
</div>
|
||||
<DataTablePage
|
||||
table={table}
|
||||
columns={columns as ColumnDef<Record<string, unknown>>[]}
|
||||
isLoading={isLoadingData}
|
||||
isFetching={isFetching}
|
||||
emptyTitle={t('No Logs Found')}
|
||||
emptyDescription={t(
|
||||
'No usage logs available. Logs will appear here once API calls are made.'
|
||||
)}
|
||||
skeletonKeyPrefix='usage-log-skeleton'
|
||||
tableHeaderClassName='bg-muted/30 sticky top-0 z-10'
|
||||
toolbar={
|
||||
isCommon ? (
|
||||
<CommonLogsFilterBar table={table} />
|
||||
) : (
|
||||
<div className='rounded-md border bg-card/50 p-2 shadow-xs sm:p-3'>
|
||||
<TaskLogsFilterBar
|
||||
logCategory={logCategory}
|
||||
viewOptions={<DataTableViewOptions table={table} />}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{isMobile ? (
|
||||
<MobileCardList
|
||||
table={table}
|
||||
isLoading={isLoadingData}
|
||||
emptyTitle={t('No Logs Found')}
|
||||
emptyDescription={t(
|
||||
'No usage logs available. Logs will appear here once API calls are made.'
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
'overflow-hidden rounded-md border transition-opacity duration-150',
|
||||
isFetching && !isLoadingData && 'pointer-events-none opacity-50'
|
||||
)}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader className='bg-muted/30 sticky top-0 z-10'>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoadingData ? (
|
||||
<TableSkeleton table={table} keyPrefix='usage-log-skeleton' />
|
||||
) : table.getRowModel().rows.length === 0 ? (
|
||||
<TableEmpty
|
||||
colSpan={columns.length}
|
||||
title={t('No Logs Found')}
|
||||
description={t(
|
||||
'No usage logs available. Logs will appear here once API calls are made.'
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
renderRows()
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<PageFooterPortal>
|
||||
<DataTablePagination table={table} />
|
||||
</PageFooterPortal>
|
||||
</>
|
||||
<TaskLogsFilterBar table={table} logCategory={logCategory} />
|
||||
)
|
||||
}
|
||||
renderRow={(row) => {
|
||||
const logType = (row.original as Record<string, unknown>).type as
|
||||
| number
|
||||
| undefined
|
||||
const tintClass =
|
||||
isCommon && logType != null ? (logTypeRowTint[logType] ?? '') : ''
|
||||
|
||||
return (
|
||||
<TableRow key={row.id} className={cn('transition-colors', tintClass)}>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id} className={isCommon ? 'py-2' : 'py-3.5'}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
+11
-4
@@ -6,6 +6,7 @@ import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { SectionPageLayout } from '@/components/layout'
|
||||
import type { NavGroup } from '@/components/layout/types'
|
||||
import { CacheStatsDialog } from '@/features/system-settings/general/channel-affinity/cache-stats-dialog'
|
||||
import { CommonLogsHeaderActions } from './components/common-logs-header-actions'
|
||||
import { UserInfoDialog } from './components/dialogs/user-info-dialog'
|
||||
import {
|
||||
UsageLogsProvider,
|
||||
@@ -75,9 +76,8 @@ function UsageLogsContent() {
|
||||
if (!('url' in item) || typeof item.url !== 'string') return null
|
||||
return item.url.split('/').pop() ?? null
|
||||
})
|
||||
.filter(
|
||||
(section): section is UsageLogsSectionId =>
|
||||
Boolean(section && isUsageLogsSectionId(section))
|
||||
.filter((section): section is UsageLogsSectionId =>
|
||||
Boolean(section && isUsageLogsSectionId(section))
|
||||
),
|
||||
[filteredTabGroups]
|
||||
)
|
||||
@@ -100,10 +100,17 @@ function UsageLogsContent() {
|
||||
return (
|
||||
<>
|
||||
<SectionPageLayout>
|
||||
<SectionPageLayout.Title>{t(pageMeta.titleKey)}</SectionPageLayout.Title>
|
||||
<SectionPageLayout.Title>
|
||||
{t(pageMeta.titleKey)}
|
||||
</SectionPageLayout.Title>
|
||||
<SectionPageLayout.Description>
|
||||
{t(pageMeta.descriptionKey)}
|
||||
</SectionPageLayout.Description>
|
||||
{activeCategory === 'common' && (
|
||||
<SectionPageLayout.Actions>
|
||||
<CommonLogsHeaderActions />
|
||||
</SectionPageLayout.Actions>
|
||||
)}
|
||||
<SectionPageLayout.Content>
|
||||
<div className='space-y-4'>
|
||||
{showTaskSwitcher && (
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
export interface LogAvatarStyle {
|
||||
backgroundColor: string
|
||||
color: string
|
||||
}
|
||||
|
||||
function hashString(value: string): number {
|
||||
let hash = 0
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
hash = (hash * 31 + value.charCodeAt(i)) >>> 0
|
||||
}
|
||||
return hash
|
||||
}
|
||||
|
||||
export function getLogAvatarStyle(name: string): LogAvatarStyle {
|
||||
const hash = hashString(name)
|
||||
const hue = hash % 360
|
||||
const saturation = 54 + (hash % 8)
|
||||
const lightness = 52 + ((hash >> 4) % 8)
|
||||
|
||||
return {
|
||||
backgroundColor: `hsl(${hue} ${saturation}% ${lightness}% / 0.82)`,
|
||||
color: 'white',
|
||||
}
|
||||
}
|
||||
+34
-34
@@ -39,8 +39,8 @@ const PARAM_OVERRIDE_ACTION_MAP: Record<string, string> = {
|
||||
* Get localized label for a param override action
|
||||
*/
|
||||
export function getParamOverrideActionLabel(
|
||||
action: string,
|
||||
t: (key: string) => string
|
||||
action: string,
|
||||
t: (key: string) => string
|
||||
): string {
|
||||
const key = PARAM_OVERRIDE_ACTION_MAP[action.toLowerCase()]
|
||||
return key ? t(key) : action
|
||||
@@ -50,7 +50,7 @@ export function getParamOverrideActionLabel(
|
||||
* Parse a param override audit line into action and content
|
||||
*/
|
||||
export function parseAuditLine(
|
||||
line: string
|
||||
line: string
|
||||
): { action: string; content: string } | null {
|
||||
if (typeof line !== 'string') return null
|
||||
const firstSpace = line.indexOf(' ')
|
||||
@@ -67,9 +67,9 @@ export function parseAuditLine(
|
||||
export function isViolationFeeLog(other: LogOtherData | null): boolean {
|
||||
if (!other) return false
|
||||
return (
|
||||
other.violation_fee === true ||
|
||||
Boolean(other.violation_fee_code) ||
|
||||
Boolean(other.violation_fee_marker)
|
||||
other.violation_fee === true ||
|
||||
Boolean(other.violation_fee_code) ||
|
||||
Boolean(other.violation_fee_marker)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ export function parseLogOther(other: string): LogOtherData | null {
|
||||
* Get time color based on duration (in seconds)
|
||||
*/
|
||||
export function getTimeColor(
|
||||
seconds: number
|
||||
seconds: number
|
||||
): 'success' | 'warning' | 'danger' {
|
||||
if (seconds < 10) return 'success'
|
||||
if (seconds < 30) return 'warning'
|
||||
@@ -102,7 +102,7 @@ export function getTimeColor(
|
||||
* Get first-response-token color based on latency (in seconds)
|
||||
*/
|
||||
export function getFirstResponseTimeColor(
|
||||
seconds: number
|
||||
seconds: number
|
||||
): 'success' | 'warning' | 'danger' {
|
||||
if (seconds < 5) return 'success'
|
||||
if (seconds < 10) return 'warning'
|
||||
@@ -113,7 +113,7 @@ export function getFirstResponseTimeColor(
|
||||
* Get throughput color based on generated tokens per second
|
||||
*/
|
||||
export function getThroughputColor(
|
||||
tokensPerSecond: number
|
||||
tokensPerSecond: number
|
||||
): 'success' | 'warning' | 'danger' {
|
||||
if (tokensPerSecond >= 30) return 'success'
|
||||
if (tokensPerSecond >= 15) return 'warning'
|
||||
@@ -124,8 +124,8 @@ export function getThroughputColor(
|
||||
* Get response color using throughput only when enough output tokens exist.
|
||||
*/
|
||||
export function getResponseTimeColor(
|
||||
seconds: number,
|
||||
completionTokens: number
|
||||
seconds: number,
|
||||
completionTokens: number
|
||||
): 'success' | 'warning' | 'danger' {
|
||||
if (completionTokens < 100 || seconds <= 0) return getTimeColor(seconds)
|
||||
return getThroughputColor(completionTokens / seconds)
|
||||
@@ -141,9 +141,9 @@ export function formatModelName(log: UsageLog): {
|
||||
} {
|
||||
const other = parseLogOther(log.other)
|
||||
const isMapped = !!(
|
||||
other?.is_model_mapped &&
|
||||
other?.upstream_model_name &&
|
||||
other.upstream_model_name !== ''
|
||||
other?.is_model_mapped &&
|
||||
other?.upstream_model_name &&
|
||||
other.upstream_model_name !== ''
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -161,9 +161,9 @@ export function decodeBillingExprB64(exprB64: string | undefined): string {
|
||||
if (!exprB64) return ''
|
||||
try {
|
||||
const binaryString =
|
||||
typeof window !== 'undefined'
|
||||
? window.atob(exprB64)
|
||||
: Buffer.from(exprB64, 'base64').toString('binary')
|
||||
typeof window !== 'undefined'
|
||||
? window.atob(exprB64)
|
||||
: Buffer.from(exprB64, 'base64').toString('binary')
|
||||
const bytes = new Uint8Array(binaryString.length)
|
||||
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
@@ -175,9 +175,9 @@ export function decodeBillingExprB64(exprB64: string | undefined): string {
|
||||
}
|
||||
|
||||
return decodeURIComponent(
|
||||
Array.prototype.map
|
||||
.call(bytes, (byte: number) => '%' + byte.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
Array.prototype.map
|
||||
.call(bytes, (byte: number) => '%' + byte.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
)
|
||||
} catch {
|
||||
return ''
|
||||
@@ -190,8 +190,8 @@ export function decodeBillingExprB64(exprB64: string | undefined): string {
|
||||
* that would display guessed unit prices.
|
||||
*/
|
||||
export function resolveMatchedTier(
|
||||
tiers: ParsedTier[],
|
||||
matchedLabel: string | undefined
|
||||
tiers: ParsedTier[],
|
||||
matchedLabel: string | undefined
|
||||
): ParsedTier | null {
|
||||
if (tiers.length === 0) return null
|
||||
if (!matchedLabel) return null
|
||||
@@ -220,19 +220,19 @@ export interface TieredBillingSummary {
|
||||
* not exercise the cache path (mirrors the classic frontend behaviour).
|
||||
*/
|
||||
export function hasAnyCacheTokens(
|
||||
other: LogOtherData | null | undefined
|
||||
other: LogOtherData | null | undefined
|
||||
): boolean {
|
||||
if (!other) return false
|
||||
return (
|
||||
(other.cache_tokens || 0) > 0 ||
|
||||
(other.cache_creation_tokens || 0) > 0 ||
|
||||
(other.cache_creation_tokens_5m || 0) > 0 ||
|
||||
(other.cache_creation_tokens_1h || 0) > 0
|
||||
(other.cache_tokens || 0) > 0 ||
|
||||
(other.cache_creation_tokens || 0) > 0 ||
|
||||
(other.cache_creation_tokens_5m || 0) > 0 ||
|
||||
(other.cache_creation_tokens_1h || 0) > 0
|
||||
)
|
||||
}
|
||||
|
||||
export function getTieredBillingSummary(
|
||||
other: LogOtherData | null
|
||||
other: LogOtherData | null
|
||||
): TieredBillingSummary | null {
|
||||
if (!other || other.billing_mode !== 'tiered_expr') return null
|
||||
const exprStr = decodeBillingExprB64(other.expr_b64)
|
||||
@@ -267,16 +267,16 @@ export function getTieredBillingSummary(
|
||||
* @param unit - Unit of the timestamps ('seconds' or 'milliseconds')
|
||||
*/
|
||||
export function formatDuration(
|
||||
submitTime?: number,
|
||||
finishTime?: number,
|
||||
unit: 'seconds' | 'milliseconds' = 'milliseconds'
|
||||
submitTime?: number,
|
||||
finishTime?: number,
|
||||
unit: 'seconds' | 'milliseconds' = 'milliseconds'
|
||||
): { durationSec: number; variant: StatusBadgeProps['variant'] } | null {
|
||||
if (!submitTime || !finishTime) return null
|
||||
|
||||
const durationSec =
|
||||
unit === 'milliseconds'
|
||||
? (finishTime - submitTime) / 1000
|
||||
: finishTime - submitTime
|
||||
unit === 'milliseconds'
|
||||
? (finishTime - submitTime) / 1000
|
||||
: finishTime - submitTime
|
||||
|
||||
return { durationSec, variant: durationSec > 60 ? 'red' : 'green' }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user