Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ FRONTEND_CRITICAL_VITEST := \
src/utils/__tests__/usageTps.spec.ts \
src/utils/__tests__/usageCacheRate.spec.ts \
src/utils/__tests__/usageRate.spec.ts \
src/components/charts/__tests__/TokenUsageTrend.spec.ts \
src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts \
src/router/__tests__/feature-access.spec.ts \
src/api/admin/__tests__/requestCaptures.spec.ts \
Expand Down
30 changes: 26 additions & 4 deletions frontend/src/components/charts/TokenUsageTrend.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
<template>
<div class="card p-4">
<h3 class="mb-4 text-sm font-semibold text-gray-900 dark:text-white">
<h3 class="mb-4 flex items-center gap-2 text-sm font-semibold text-gray-900 dark:text-white">
{{ t('admin.dashboard.tokenUsageTrend') }}
<NewFeatureBadge
v-if="showRate && noticeUserId != null"
:notice-id="NEW_FEATURE_NOTICES.usageTrendRate"
:user-id="noticeUserId"
/>
</h3>
<div v-if="loading" class="flex h-48 items-center justify-center">
<LoadingSpinner />
Expand Down Expand Up @@ -34,7 +39,10 @@ import {
} from 'chart.js'
import { Line } from 'vue-chartjs'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
import NewFeatureBadge from '@/components/common/NewFeatureBadge.vue'
import { NEW_FEATURE_NOTICES } from '@/constants/newFeatureNotices'
import type { TrendDataPoint } from '@/types'
import { formatUsageRate, usageTrendRates, type UsageTrendRateContext } from '@/utils/usageRate'

ChartJS.register(
CategoryScale,
Expand All @@ -49,10 +57,21 @@ ChartJS.register(

const { t } = useI18n()

const props = defineProps<{
const props = withDefaults(defineProps<{
trendData: TrendDataPoint[]
loading?: boolean
}>()
/** Add each bucket's average RPM/TPM to the tooltip, using rateContext. */
showRate?: boolean
/** The range and granularity trendData was loaded for. */
rateContext?: UsageTrendRateContext | null
/** Admin who owns the new-feature badge dismissal; omit to hide the badge. */
noticeUserId?: number | null
}>(), {
loading: false,
showRate: false,
rateContext: null,
noticeUserId: null,
})

const isDarkMode = computed(() => {
return document.documentElement.classList.contains('dark')
Expand Down Expand Up @@ -155,7 +174,10 @@ const lineOptions = computed(() => ({
const dataIndex = tooltipItems[0]?.dataIndex
if (dataIndex !== undefined && props.trendData[dataIndex]) {
const data = props.trendData[dataIndex]
return `Actual: $${formatCost(data.actual_cost)} | Standard: $${formatCost(data.cost)}`
const cost = `Actual: $${formatCost(data.actual_cost)} | Standard: $${formatCost(data.cost)}`
if (!props.showRate) return cost
const { rpm, tpm } = usageTrendRates(data, props.rateContext)
return [cost, `RPM: ${formatUsageRate(rpm)} | TPM: ${formatUsageRate(tpm)}`]
}
return ''
}
Expand Down
59 changes: 58 additions & 1 deletion frontend/src/components/charts/__tests__/TokenUsageTrend.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { Line } from 'vue-chartjs'

import TokenUsageTrend from '../TokenUsageTrend.vue'

Expand Down Expand Up @@ -117,4 +118,60 @@ describe('TokenUsageTrend', () => {
// Hit rate = 500 / (200 + 500 + 300) * 100 = 50%
expect(hitRateDataset.data[0]).toBe(50)
})
})
})
describe('TokenUsageTrend RPM/TPM tooltip', () => {
const point = {
date: '2026-11-13 17:00',
requests: 46,
input_tokens: 1_000_000,
output_tokens: 300_000,
cache_creation_tokens: 0,
cache_read_tokens: 1_000_000,
total_tokens: 2_300_000,
cost: 12,
actual_cost: 6,
}
// The first 23 minutes of the 17:00 hour in Shanghai.
const rateContext = {
window: { start: '2026-11-13T09:37:00Z', end: '2026-11-14T09:37:00Z', now: Date.parse('2026-11-14T09:37:00Z') },
granularity: 'hour',
serverTimezone: 'Asia/Shanghai',
serverUTCOffset: '+08:00',
}
const mountTrend = (props: Record<string, unknown>) => mount(TokenUsageTrend, {
props: { trendData: [point], ...props },
global: { stubs: { LoadingSpinner: true, NewFeatureBadge: true } },
})
const footer = (wrapper: ReturnType<typeof mountTrend>) =>
wrapper.findComponent(Line as any).props('options').plugins.tooltip.callbacks.footer([{ dataIndex: 0 }])

it('keeps the cost-only footer and no badge unless enabled', () => {
const wrapper = mountTrend({ rateContext, noticeUserId: 7 })
expect(footer(wrapper)).toBe('Actual: $6.00 | Standard: $12.00')
expect(wrapper.findComponent({ name: 'NewFeatureBadge' }).exists()).toBe(false)
})

it('adds the bucket RPM and TPM over the minutes it covers', () => {
const wrapper = mountTrend({ showRate: true, rateContext })
expect(footer(wrapper)).toEqual(['Actual: $6.00 | Standard: $12.00', 'RPM: 2.00 | TPM: 100.00K'])
})

it('shows dashes until the trend has a rate context', () => {
const wrapper = mountTrend({ showRate: true })
expect(footer(wrapper)).toEqual(['Actual: $6.00 | Standard: $12.00', 'RPM: — | TPM: —'])
})

it('shows the new-feature badge beside the title only for an admin', () => {
const withAdmin = mountTrend({ showRate: true, rateContext, noticeUserId: 7 })
const badge = withAdmin.findComponent({ name: 'NewFeatureBadge' })
expect(badge.exists()).toBe(true)
expect(badge.props()).toMatchObject({
noticeId: 'usage-trend-tooltip-rpm-tpm-initial-announcement',
userId: 7,
})
expect(withAdmin.find('h3').element.contains(badge.element)).toBe(true)

const withoutAdmin = mountTrend({ showRate: true, rateContext })
expect(withoutAdmin.findComponent({ name: 'NewFeatureBadge' }).exists()).toBe(false)
})
})
1 change: 1 addition & 0 deletions frontend/src/constants/newFeatureNotices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
export const NEW_FEATURE_NOTICES = {
adminUsagePlatform: 'admin-usage-platform-filter-initial-announcement',
usageTrendRate: 'usage-trend-tooltip-rpm-tpm-initial-announcement',
priorityCacheWeight: 'priority-cache-weight-initial-announcement',
openai409OmitEncryptedHistory: 'openai-409-omit-encrypted-history-beta',
openai400OmitEncryptedHistory: 'openai-400-omit-encrypted-history-beta',
Expand Down
148 changes: 146 additions & 2 deletions frontend/src/utils/__tests__/usageRate.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { describe, expect, it } from 'vitest'

import { formatUsageRate, resolveUsageStatsWindow, usagePerMinute, usageRateWindowMinutes } from '../usageRate'
import {
formatUsageRate,
resolveUsageStatsWindow,
usagePerMinute,
usageRateWindowMinutes,
usageTrendBucketMinutes,
usageTrendRates,
} from '../usageRate'

const localMs = (year: number, month: number, day: number, hour = 0, minute = 0) =>
new Date(year, month - 1, day, hour, minute).getTime()
Expand All @@ -14,7 +21,9 @@ describe('usageRate', () => {

it('treats calendar dates like the API: local midnight to the end of the last day', () => {
const now = localMs(2026, 11, 20, 12)
expect(usageRateWindowMinutes({ start: '2026-11-01', end: '2026-11-07', now })).toBe(7 * 1440)
// 7 days of 1440 minutes, plus the hour a DST change on 2026-11-01 adds in zones such as America/Los_Angeles.
expect(usageRateWindowMinutes({ start: '2026-11-01', end: '2026-11-07', now }))
.toBe((localMs(2026, 11, 8) - localMs(2026, 11, 1)) / 60_000)
})

it('counts a range that includes now only up to now', () => {
Expand Down Expand Up @@ -76,6 +85,141 @@ describe('usageRate', () => {
expect(usagePerMinute(undefined, { start: '2026-11-09', end: '2026-11-09', now: localMs(2026, 11, 10) })).toBeNull()
})

describe('trend buckets', () => {
const shanghai = { serverTimezone: 'Asia/Shanghai', serverUTCOffset: '+08:00' }
// Rolling 24 hours ending 2026-11-14 17:37 in Shanghai.
const rolling = {
...shanghai,
granularity: 'hour',
window: { start: '2026-11-13T09:37:00Z', end: '2026-11-14T09:37:00Z', now: Date.parse('2026-11-14T09:37:00Z') },
}

it('counts only the minutes of an hour bucket inside the range and up to now', () => {
expect(usageTrendBucketMinutes('2026-11-13 16:00', rolling)).toBeNull()
expect(usageTrendBucketMinutes('2026-11-13 17:00', rolling)).toBe(23)
expect(usageTrendBucketMinutes('2026-11-13 18:00', rolling)).toBe(60)
expect(usageTrendBucketMinutes('2026-11-14 17:00', rolling)).toBe(37)
expect(usageTrendBucketMinutes('2026-11-14 18:00', rolling)).toBeNull()
expect(usageTrendRates({ date: '2026-11-13 17:00', requests: 46, total_tokens: 2_300_000 }, rolling))
.toEqual({ rpm: 2, tpm: 100_000 })
})

it('counts a day bucket in the server zone, with today only up to now', () => {
const ctx = {
...shanghai,
granularity: 'day',
// 2026-11-13 00:00 to 2026-11-15 00:00 in Shanghai, requested at 11-14 12:00 there.
window: { start: '2026-11-12T16:00:00Z', end: '2026-11-14T16:00:00Z', now: Date.parse('2026-11-14T04:00:00Z') },
}
expect(usageTrendBucketMinutes('2026-11-13', ctx)).toBe(1440)
expect(usageTrendBucketMinutes('2026-11-14', ctx)).toBe(720)
})

it('follows DST changes in the server zone', () => {
const ctx = {
serverTimezone: 'America/New_York',
serverUTCOffset: '-05:00',
window: { start: '2026-01-01T00:00:00Z', end: '2027-01-01T00:00:00Z', now: Date.parse('2027-01-01T00:00:00Z') },
}
const hour = { ...ctx, granularity: 'hour' }
const day = { ...ctx, granularity: 'day' }
// Clocks go back at 02:00 on 2026-11-01, so the backend labels two hours "01:00".
expect(usageTrendBucketMinutes('2026-11-01 00:00', hour)).toBe(60)
expect(usageTrendBucketMinutes('2026-11-01 01:00', hour)).toBe(120)
expect(usageTrendBucketMinutes('2026-11-01 02:00', hour)).toBe(60)
expect(usageTrendBucketMinutes('2026-11-01', day)).toBe(1500)
expect(usageTrendBucketMinutes('2026-11-02', day)).toBe(1440)
// Clocks skip 02:00 on 2026-03-08.
expect(usageTrendBucketMinutes('2026-03-08 01:00', hour)).toBe(60)
expect(usageTrendBucketMinutes('2026-03-08 03:00', hour)).toBe(60)
expect(usageTrendBucketMinutes('2026-03-08', day)).toBe(1380)
})

it('falls back to the server UTC offset when the zone name is not an IANA zone', () => {
expect(usageTrendBucketMinutes('2026-11-13 17:00', { ...rolling, serverTimezone: 'Local' })).toBe(23)
const ctx = {
serverUTCOffset: '-03:30',
granularity: 'hour',
window: { start: '2026-11-13T08:45:00Z', end: '', now: Date.parse('2026-11-14T00:00:00Z') },
}
// 05:00 at -03:30 starts at 08:30Z.
expect(usageTrendBucketMinutes('2026-11-13 05:00', ctx)).toBe(45)
})

it('has no rate while the server zone is unknown instead of guessing the browser zone', () => {
for (const zone of [{}, { serverTimezone: null, serverUTCOffset: null }, { serverTimezone: 'Local' }]) {
expect(usageTrendBucketMinutes('2026-11-13 18:00', { ...rolling, serverTimezone: undefined, serverUTCOffset: undefined, ...zone }))
.toBeNull()
}
})

describe('a fold that repeats two hours (Antarctica/Troll, +02 → +00 at 2026-10-25 01:00Z)', () => {
const troll = (window: { start?: string; end?: string; now: number }, granularity = 'hour') => ({
serverTimezone: 'Antarctica/Troll',
granularity,
window: { start: '', end: '', ...window },
})
const later = Date.parse('2026-10-27T00:00:00Z')

it('sums the separate UTC hours behind one label', () => {
// 01:00 is 23:00–00:00Z and 01:00–02:00Z; 02:00 is 00:00–01:00Z and 02:00–03:00Z.
expect(usageTrendBucketMinutes('2026-10-25 00:00', troll({ now: later }))).toBe(60)
expect(usageTrendBucketMinutes('2026-10-25 01:00', troll({ now: later }))).toBe(120)
expect(usageTrendBucketMinutes('2026-10-25 02:00', troll({ now: later }))).toBe(120)
expect(usageTrendBucketMinutes('2026-10-25 03:00', troll({ now: later }))).toBe(60)
expect(usageTrendBucketMinutes('2026-10-25', troll({ now: later }, 'day'))).toBe(26 * 60)
})

it('clips each UTC hour separately', () => {
// Only the second 01:00 lies in the range.
expect(usageTrendBucketMinutes('2026-10-25 01:00', troll({ start: '2026-10-25T01:00:00Z', now: later }))).toBe(60)
// Half of the first 01:00 plus all of the second.
expect(usageTrendBucketMinutes('2026-10-25 01:00', troll({ start: '2026-10-24T23:30:00Z', now: later }))).toBe(90)
// The range ends between the two 01:00 hours: the gap (local 02:00) is not counted.
expect(usageTrendBucketMinutes('2026-10-25 01:00', troll({ end: '2026-10-25T01:30:00Z', now: later }))).toBe(90)
// Requested during the second 02:00: the first is complete, the second half done.
expect(usageTrendBucketMinutes('2026-10-25 02:00', troll({ now: Date.parse('2026-10-25T02:30:00Z') }))).toBe(90)
})

it('leaves out the two skipped hours of the spring gap', () => {
const spring = Date.parse('2026-03-31T00:00:00Z')
expect(usageTrendBucketMinutes('2026-03-29 00:00', troll({ now: spring }))).toBe(60)
expect(usageTrendBucketMinutes('2026-03-29 03:00', troll({ now: spring }))).toBe(60)
expect(usageTrendBucketMinutes('2026-03-29', troll({ now: spring }, 'day'))).toBe(22 * 60)
})
})

it('handles a half-hour fold (Australia/Lord_Howe, 02:00 +11 → 01:30 +10:30 on 2026-04-05)', () => {
const ctx = {
serverTimezone: 'Australia/Lord_Howe',
granularity: 'hour',
window: { start: '', end: '', now: Date.parse('2026-04-06T00:00:00Z') },
}
expect(usageTrendBucketMinutes('2026-04-05 01:00', ctx)).toBe(90)
expect(usageTrendBucketMinutes('2026-04-05 02:00', ctx)).toBe(60)
expect(usageTrendBucketMinutes('2026-04-05', { ...ctx, granularity: 'day' })).toBe(24.5 * 60)
})

it('bounds a bucket by itself on a range side that was not sent', () => {
const ctx = { ...rolling, window: { start: '', end: '', now: Date.parse('2026-11-14T00:00:00Z') } }
expect(usageTrendBucketMinutes('2026-11-13 17:00', ctx)).toBe(60)
expect(usageTrendBucketMinutes('2026-11-14 07:00', ctx)).toBe(60)
expect(usageTrendBucketMinutes('2026-11-14 08:00', ctx)).toBeNull()
})

it.each([
['no context', '2026-11-13 17:00', null],
['a day label on an hourly trend', '2026-11-13', rolling],
['an hour label on a daily trend', '2026-11-13 17:00', { ...rolling, granularity: 'day' }],
['an unsupported granularity', '2026-11-13', { ...rolling, granularity: 'week' }],
['an invalid range start', '2026-11-13 18:00', { ...rolling, window: { ...rolling.window, start: 'not-a-date' } }],
['an invalid request time', '2026-11-13 18:00', { ...rolling, window: { ...rolling.window, now: Number.NaN } }],
])('has no trend rate for %s', (_, label, ctx) => {
expect(usageTrendBucketMinutes(label, ctx)).toBeNull()
expect(usageTrendRates({ date: label, requests: 10, total_tokens: 10 }, ctx)).toEqual({ rpm: null, tpm: null })
})
})

it.each([
[null, '—'],
[0, '0'],
Expand Down
Loading
Loading