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
6 changes: 5 additions & 1 deletion backend/internal/repository/ops_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -931,7 +931,11 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) {
}
if p := strings.TrimSpace(filter.Platform); p != "" {
args = append(args, p)
clauses = append(clauses, "e.platform = $"+itoa(len(args)))
match := "e.platform = $" + itoa(len(args))
if p == "unknown" {
match = "(" + match + " OR e.platform IS NULL OR e.platform = '')"
}
clauses = append(clauses, match)
}
if filter.GroupID != nil && *filter.GroupID > 0 {
args = append(args, *filter.GroupID)
Expand Down
7 changes: 7 additions & 0 deletions backend/internal/repository/ops_repo_error_where_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
)

func TestBuildOpsErrorLogsWhere_UnknownPlatformIncludesLegacyRows(t *testing.T) {
where, args := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{Platform: "unknown"})
if len(args) != 1 || args[0] != "unknown" || !strings.Contains(where, "(e.platform = $1 OR e.platform IS NULL OR e.platform = '')") {
t.Fatalf("unexpected platform filter: %s, %v", where, args)
}
}

func TestBuildOpsErrorLogsWhere_QueryUsesQualifiedColumns(t *testing.T) {
filter := &service.OpsErrorLogFilter{
Query: "ACCESS_DENIED",
Expand Down
7 changes: 4 additions & 3 deletions frontend/src/components/admin/usage/UsageFilters.vue
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@
</div>

<template v-if="!identityOnly">
<div v-if="mode === 'usage' && !observerMode" data-testid="usage-platform-filter" class="w-full sm:w-52">
<div v-if="showPlatformFilter" data-testid="usage-platform-filter" class="w-full sm:w-52">
<label for="usage-platform" class="input-label flex items-center gap-1.5">
{{ t('admin.usage.platform') }}
<NewFeatureBadge v-if="noticeUserId != null" :notice-id="NEW_FEATURE_NOTICES.adminUsagePlatform" :user-id="noticeUserId" />
<NewFeatureBadge v-if="noticeUserId != null" :notice-id="mode === 'errors' ? NEW_FEATURE_NOTICES.adminErrorPlatform : NEW_FEATURE_NOTICES.adminUsagePlatform" :user-id="noticeUserId" />
</label>
<Select
id="usage-platform"
Expand Down Expand Up @@ -216,7 +216,7 @@
</template>
</div>
</div>
<p v-if="!identityOnly && mode === 'usage' && !observerMode" id="usage-platform-hint" class="mt-3 text-xs text-gray-500 dark:text-gray-400">{{ t('admin.usage.platformHistoryHint') }}</p>
<p v-if="!identityOnly && showPlatformFilter" id="usage-platform-hint" class="mt-3 text-xs text-gray-500 dark:text-gray-400">{{ t('admin.usage.platformHistoryHint') }}</p>
</div>
</template>

Expand Down Expand Up @@ -305,6 +305,7 @@ const modelOptions = computed<SelectOption[]>(() => [
{ value: null, label: t('admin.usage.allModels') },
...(props.modelOptions ?? []).map((m) => ({ value: m, label: m })),
])
const showPlatformFilter = computed(() => !observerMode && (props.mode === 'usage' || props.mode === 'errors'))
const platformOptions = computed<SelectOption[]>(() => [
{ value: null, label: t('admin.usage.allPlatforms') },
...CONCRETE_PLATFORM_OPTIONS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ describe('UsageFilters — identity-only traffic filters', () => {
})

describe('admin usage platform filter', () => {
it.each(['errors', 'ranking', 'connections', 'latency'] as const)('keeps the platform selector out of %s', async mode => {
it.each(['ranking', 'connections', 'latency'] as const)('keeps the platform selector out of %s', async mode => {
const wrapper = mountFilters(defaultFilters(), mode)
await flushPromises()
expect(wrapper.find('[data-testid="usage-platform-filter"]').exists()).toBe(false)
Expand All @@ -459,8 +459,8 @@ describe('admin usage platform filter', () => {
wrapper.unmount()
})

it('offers a server-side platform filter alongside the group filter', async () => {
const wrapper = mountFilters()
it.each(['usage', 'errors'] as const)('offers the platform selector alongside the group filter in %s', async mode => {
const wrapper = mountFilters(defaultFilters(), mode)
await flushPromises()
expect(wrapper.find('[data-testid="usage-platform-filter"]').exists(),
'admin usage details must offer a platform selector').toBe(true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ describe('NewFeatureBadge', () => {
['QQ community', NEW_FEATURE_NOTICES.qqCommunity],
['QQ reward coupons', NEW_FEATURE_NOTICES.qqRewardCoupons],
['moderation upstream scope', NEW_FEATURE_NOTICES.moderationUpstreamAccountScope],
['admin error platform', NEW_FEATURE_NOTICES.adminErrorPlatform],
['admin usage platform', NEW_FEATURE_NOTICES.adminUsagePlatform],
['user ID copy', NEW_FEATURE_NOTICES.userIdCopy],
['Antigravity usage query', NEW_FEATURE_NOTICES.antigravityUsageQuery],
Expand Down
1 change: 1 addition & 0 deletions frontend/src/constants/newFeatureNotices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const NEW_FEATURE_NOTICES = {
accountOpsProviderBalance: 'account-ops-provider-wallet-balance',
accountOpsOAuthLifecycle: 'account-ops-oauth-lifecycle',
moderationUpstreamAccountScope: 'moderation-upstream-account-scope',
adminErrorPlatform: 'admin-error-platform-filter',
adminUsagePlatform: 'admin-usage-platform-filter-initial-announcement',
usageTrendRate: 'usage-trend-tooltip-rpm-tpm-initial-announcement',
priorityCacheWeight: 'priority-cache-weight-initial-announcement',
Expand Down
14 changes: 12 additions & 2 deletions frontend/src/views/admin/UsageView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,10 @@ const applyFilters = () => {
if (activeTab.value === 'errors') {
loadAdminErrors()
} else {
errRequestSeq++
errLoading.value = false
errRows.value = []
errTotal.value = 0
}
}
const refreshData = () => {
Expand Down Expand Up @@ -929,7 +932,7 @@ const rankingRef = ref<InstanceType<typeof UserTokenRanking> | null>(null)

const switchTab = (tab: DetailTab) => {
if (!detailTabs.value.some(item => item.key === tab)) return
const clearPlatform = tab !== 'usage' && !!filters.value.platform
const clearPlatform = tab !== 'usage' && tab !== 'errors' && !!filters.value.platform
if (clearPlatform) filters.value.platform = undefined
activeTab.value = tab
if (clearPlatform) applyFilters()
Expand All @@ -956,8 +959,10 @@ const toRFC3339 = (value: string | undefined, endExclusive = false): string | un
return date.toISOString()
}

let errRequestSeq = 0
const loadAdminErrors = async () => {
if (!canViewErrors.value) return
const seq = ++errRequestSeq
errLoading.value = true
try {
const resp = await (props.observerMode ? observerUsageAPI.listErrors : listErrorLogs)({
Expand All @@ -972,19 +977,24 @@ const loadAdminErrors = async () => {
account_id: filters.value.account_id ?? undefined,
group_id: filters.value.group_id ?? undefined,
model: filters.value.model || undefined,
platform: props.observerMode ? undefined : filters.value.platform,
phase: filters.value.error_phase || undefined,
category: filters.value.error_category || undefined,
status_codes: filters.value.status_code != null ? String(filters.value.status_code) : undefined,
sort_by: errSortBy.value,
sort_order: errSortOrder.value,
})
if (seq !== errRequestSeq) return
errRows.value = resp.items
errTotal.value = resp.total
} catch (error) {
if (seq !== errRequestSeq) return
errRows.value = []
errTotal.value = 0
console.error('Failed to load admin errors:', error)
appStore.showError(t('usage.errors.failedToLoad'))
} finally {
errLoading.value = false
if (seq === errRequestSeq) errLoading.value = false
}
}

Expand Down
15 changes: 12 additions & 3 deletions frontend/src/views/admin/__tests__/UsageView.platform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'
import zh from '@/i18n/locales/zh'
import en from '@/i18n/locales/en'

const api = vi.hoisted(() => ({ list: vi.fn(), stats: vi.fn(), export: vi.fn(), models: vi.fn(), snapshot: vi.fn(), breakdown: vi.fn() }))
const api = vi.hoisted(() => ({ errors: vi.fn(), list: vi.fn(), stats: vi.fn(), export: vi.fn(), models: vi.fn(), snapshot: vi.fn(), breakdown: vi.fn() }))
vi.mock('vue-chartjs', () => ({ Doughnut: { template: '<div />' } }))
vi.mock('@/api/admin/dashboard', () => ({ getUserBreakdown: api.breakdown }))
vi.mock('@/stores/auth', () => ({ useAuthStore: () => ({ user: { id: 41 } }) }))
Expand All @@ -24,7 +24,7 @@ vi.mock('@/api/admin', () => ({ adminAPI: {
dashboard: { getModelStats: api.models, getSnapshotV2: api.snapshot },
groups: { list: vi.fn().mockResolvedValue({ items: [{ id: 7, name: 'Synthetic group' }] }) },
} }))
vi.mock('@/api/admin/ops', () => ({ listErrorLogs: vi.fn().mockResolvedValue({ items: [], total: 0 }) }))
vi.mock('@/api/admin/ops', () => ({ listErrorLogs: api.errors }))
vi.mock('@/api/admin/usage', () => ({ adminUsageAPI: { list: api.export } }))
vi.mock('xlsx', () => ({ utils: { aoa_to_sheet: vi.fn(() => ({})), sheet_add_aoa: vi.fn(), book_new: vi.fn(() => ({})), book_append_sheet: vi.fn() }, write: vi.fn(() => new Uint8Array()) }))
vi.mock('file-saver', () => ({ saveAs: vi.fn() }))
Expand Down Expand Up @@ -57,6 +57,7 @@ describe('admin usage platform behavior with real filters', () => {
setActivePinia(createPinia())
vi.clearAllMocks()
api.list.mockResolvedValue({ items: [], total: 220, pages: 11 })
api.errors.mockResolvedValue({ items: [], total: 0 })
api.stats.mockResolvedValue({ total_requests: 220 })
api.models.mockResolvedValue({ models: [] })
api.snapshot.mockResolvedValue({ trend: [], models: [], groups: [] })
Expand Down Expand Up @@ -218,7 +219,7 @@ describe('admin usage platform behavior with real filters', () => {
expect(chart.text()).toContain('b@example.invalid')
})

it('clears the detail-only platform when switching tabs and disables unsupported cleanup', async () => {
it('shares platform between usage and errors, and clears it on unsupported tabs', async () => {
render()
await flushPromises()
await choose(wrapper.get('[data-testid="usage-platform-filter"]'), 'OpenAI')
Expand All @@ -227,6 +228,14 @@ describe('admin usage platform behavior with real filters', () => {
const tabs = wrapper.findAll('[data-testid="usage-detail-tab"]')
await tabs[1].trigger('click')
await flushPromises()
expect(wrapper.get('[data-testid="usage-platform-filter"] .select-trigger').text()).toBe('OpenAI')
expect(api.errors.mock.lastCall?.[0]).toMatchObject({ platform: 'openai', page: 1 })
await choose(wrapper.get('[data-testid="usage-platform-filter"]'), 'Unknown (legacy)')
expect(api.errors.mock.lastCall?.[0]).toMatchObject({ platform: 'unknown', page: 1 })
await tabs[0].trigger('click')
expect(wrapper.get('[data-testid="usage-platform-filter"] .select-trigger').text()).toBe('Unknown (legacy)')
await tabs[2].trigger('click')
await flushPromises()
expect(wrapper.find('[data-testid="usage-platform-filter"]').exists()).toBe(false)
expect(api.stats.mock.lastCall?.[0].platform).toBeFalsy()
await tabs[0].trigger('click')
Expand Down
Loading