fix(admin): use account display names in sorting and usage (#815)

* fix(admin): use account display names in sorting and usage

Co-authored-by: Codex <noreply@openai.com>

* fix(ui): remove native tooltips from usage identity cells

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-12-01 11:10:24 +08:00
committed by GitHub
co-authored by Codex Zyy
parent eae19e211e
commit 329503d967
24 changed files with 146 additions and 46 deletions
@@ -55,7 +55,7 @@ pub struct AccountImportSettings {
/// 账号列表排序字段
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccountSortField {
Email,
Name,
Status,
PlanType,
Usage,
@@ -1169,6 +1169,7 @@ pub struct DiagnosticsObservation {
pub struct DiagnosticObservation {
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub account_authentication_kind: Option<String>,
@@ -1647,6 +1648,7 @@ pub struct DiagnosticsItem {
pub platform_icon: Option<String>,
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub account_authentication_kind: Option<String>,
pub account_plan_type: Option<String>,
/// 仅账号维度补充当前互联识别结果
@@ -379,6 +379,7 @@ impl ObservabilityService for DefaultObservabilityService {
account_upstream_peer: peers.get(&item.key).copied(),
key: item.key,
name: item.name,
account_email: item.account_email,
account_authentication_kind: item.account_authentication_kind,
account_plan_type_display: self.historical_plan_display(
item.account_plan_type_display,
@@ -550,6 +550,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
account_plan_type_display: None,
key: name.to_owned(),
name: name.to_owned(),
account_email: None,
request_count,
success_count: request_count,
failure_count: 0,
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
match value.trim() {
"email" => Some(AccountSortField::Email),
"name" => Some(AccountSortField::Name),
"status" => Some(AccountSortField::Status),
"planType" => Some(AccountSortField::PlanType),
"usage" => Some(AccountSortField::Usage),
@@ -1354,13 +1354,14 @@ pub(crate) fn diagnostics_view(
.map(|item| DiagnosticItemView {
providers: item.providers,
platform_icon: item.platform_icon,
key: item.key,
account_email: item.account_email,
authentication_kind: item.account_authentication_kind,
name: if item.name == "__none__" {
name: if item.key == "__none__" {
"未知".to_owned()
} else {
item.name
},
key: item.key,
request_count: item.request_count,
account_plan_type: item.account_plan_type,
account_plan_type_display: item.account_plan_type_display,
@@ -878,6 +878,7 @@ pub struct DiagnosticItemView {
pub platform_icon: Option<String>,
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub authentication_kind: Option<String>,
pub account_plan_type: Option<String>,
pub account_plan_type_display: Option<String>,
@@ -126,7 +126,7 @@ mod query {
"provider": "xai",
"search": " operator ",
"status": "normal",
"sortBy": "lastUsedAt",
"sortBy": "name",
"sortDirection": "desc"
}))
.expect("deserialize account query");
@@ -139,10 +139,7 @@ mod query {
));
assert_eq!(query.search.as_deref(), Some("operator"));
assert_eq!(query.status, Some(AccountStatus::Normal));
assert_eq!(
query.sort.expect("sort").field,
AccountSortField::LastUsedAt
);
assert_eq!(query.sort.expect("sort").field, AccountSortField::Name);
assert_eq!(
query.sort.expect("copy sort").direction,
SortDirection::Desc
@@ -753,7 +753,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
account_authentication_kind: authentication_kind.map(str::to_owned),
account_plan_type: plan_type.map(str::to_owned),
account_plan_type_display: None,
name: "diag@example.invalid".to_owned(),
account_email: Some("diag@example.invalid".to_owned()),
name: "__none__".to_owned(),
request_count: 2,
success_count: 2,
failure_count: 0,
@@ -813,11 +814,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
(
&value["data"]["items"][0]["key"],
&value["data"]["items"][0]["name"],
&value["data"]["items"][0]["accountEmail"],
&value["data"]["items"][0]["latencyP95Ms"],
&value["data"]["dimension"],
),
(
&serde_json::json!("acct_diag"),
&serde_json::json!("__none__"),
&serde_json::json!("diag@example.invalid"),
&serde_json::json!(3800),
&serde_json::json!("account"),
@@ -634,6 +634,7 @@ impl<'a> AnalyticsSnapshot<'a> {
observations.push(DiagnosticObservation {
key: key.clone(),
name: key,
account_email: None,
providers: state.providers.iter().cloned().collect(),
platform_icon: None,
account_authentication_kind: None,
@@ -672,9 +673,29 @@ impl<'a> AnalyticsSnapshot<'a> {
.map(|item| item.key.clone())
.collect::<Vec<_>>();
let statement = if dimension == DiagnosticDimension::Account {
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join provider_accounts a on a.id=requested.id left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
"select requested.id, coalesce(h.provider_kind, a.provider_kind) as provider_kind,
a.platform_icon, h.authentication_kind, h.plan_type, h.plan_type_display,
coalesce(h.account_name, h.account_email, requested.id) as name, h.account_email
from unnest($1::text[]) requested(id)
left join provider_accounts a on a.id = requested.id
left join lateral (
select provider_kind, provider_account_authentication_kind_snapshot as authentication_kind,
provider_account_plan_type_snapshot as plan_type,
provider_account_plan_type_display_snapshot as plan_type_display,
nullif(btrim(provider_account_name_snapshot), '') as account_name,
nullif(btrim(provider_account_email_snapshot), '') as account_email
from model_request_observations where provider_account_ref = requested.id
order by started_at desc, id desc limit 1
) h on true"
} else {
"select requested.id, null::text as provider_kind, null::text as platform_icon, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
"select requested.id, null::text as provider_kind, null::text as platform_icon,
null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display,
coalesce(h.client_api_key_name_snapshot, requested.id) as name, null::text as account_email
from unnest($1::text[]) requested(id)
left join lateral (
select client_api_key_name_snapshot from model_request_observations
where client_api_key_ref = requested.id order by started_at desc, id desc limit 1
) h on true"
};
let labels = sqlx::query(statement)
.bind(ids)
@@ -685,6 +706,7 @@ impl<'a> AnalyticsSnapshot<'a> {
let id: String = get(&row, "id")?;
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
item.name = get(&row, "name")?;
item.account_email = get(&row, "account_email")?;
item.providers = get::<Option<String>>(&row, "provider_kind")?
.into_iter()
.collect();
@@ -280,6 +280,7 @@ fn admin_diagnostic_observation(
admin_observability::DiagnosticObservation {
key: observation.key,
name: observation.name,
account_email: observation.account_email,
providers: observation.providers,
platform_icon: observation.platform_icon,
account_authentication_kind: observation.account_authentication_kind,
@@ -384,6 +384,7 @@ pub struct DiagnosticsObservation {
pub struct DiagnosticObservation {
pub key: String,
pub name: String,
pub account_email: Option<String>,
pub providers: Vec<String>,
pub platform_icon: Option<String>,
pub account_authentication_kind: Option<String>,
@@ -253,7 +253,9 @@ fn admin_account_order(sort: Option<AdminAccountSort>) -> String {
return "a.id asc".to_owned();
};
let expression = match sort.field {
AdminAccountSortField::Email => "a.email",
AdminAccountSortField::Name => {
"lower(coalesce(nullif(btrim(a.name), ''), nullif(btrim(a.email), ''), a.upstream_account_id, a.id))"
}
AdminAccountSortField::Status => {
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
}
@@ -2386,7 +2386,11 @@ async fn admin_observability_adapter_preserves_utc_queries_metrics_costs_and_det
.expect("admin diagnostics")
.items;
assert_eq!(diagnostics[0].key, "acct_observe");
assert_eq!(diagnostics[0].name, "account@example.invalid");
assert_eq!(diagnostics[0].name, "primary");
assert_eq!(
diagnostics[0].account_email.as_deref(),
Some("account@example.invalid")
);
assert_eq!(diagnostics[0].cost_coverage.provider_reported_count, 1);
assert_eq!(diagnostics[0].costs[0].amount.as_str(), "1.25");
@@ -2914,7 +2918,11 @@ async fn observability_queries_preserve_request_account_cost_and_diagnostic_fact
.expect("usage diagnostics")
.items;
assert_eq!(diagnostics[0].key, "acct_observe");
assert_eq!(diagnostics[0].name, "account@example.invalid");
assert_eq!(diagnostics[0].name, "primary");
assert_eq!(
diagnostics[0].account_email.as_deref(),
Some("account@example.invalid")
);
assert_eq!(diagnostics[0].request_count, 3);
assert_eq!(diagnostics[0].success_count, 2);
assert_eq!(diagnostics[0].failure_count, 1);
@@ -715,14 +715,18 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
let now = Utc::now();
let mut alpha = account("acct_alpha", "user-alpha");
alpha.name = "Zulu".to_owned();
alpha.email = Some("alpha@example.invalid".to_owned());
let mut beta = account("acct_beta", "user-beta");
beta.provider_kind = "xai".to_owned();
beta.name = "Team".to_owned();
beta.email = Some("beta@example.invalid".to_owned());
beta.credential_state = CredentialState::Banned;
let mut charlie = account("acct_charlie", "user-charlie");
charlie.name = "Team".to_owned();
charlie.email = Some("charlie@example.invalid".to_owned());
let mut invalid = account("acct_invalid", "user-invalid");
invalid.name = " ".to_owned();
invalid.email = Some("invalid@example.invalid".to_owned());
invalid.credential_state = CredentialState::Invalid;
let mut disabled = account("acct_disabled", "user-disabled");
@@ -850,6 +854,33 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
["acct_charlie", "acct_beta"]
);
let name_page = store
.list_accounts(
AccountListQuery {
page: 1,
page_size: PageSize::new(4).expect("page size"),
provider_kind: None,
group_filter: None,
search: None,
status: None,
sort: Some(AccountSort {
field: AccountSortField::Name,
direction: SortDirection::Desc,
}),
},
Default::default(),
)
.await
.expect("sort accounts by display name");
assert_eq!(
name_page
.items
.iter()
.map(|item| item.account.id.as_str())
.collect::<Vec<_>>(),
["acct_alpha", "acct_charlie", "acct_beta", "acct_invalid"]
);
let last_used_page = store
.list_accounts(
AccountListQuery {
+2 -1
View File
@@ -1323,7 +1323,7 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
- `provider`: `openai` 或 `xai`,省略或空值表示不过滤
- `groupId`: 分组 ID、`ungrouped`,或省略以不过滤
- `status`: `normal`、`quota_paused`、`quota_exhausted`、`rate_limited`、`disabled`、`error`
- `sortBy`: `email`、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt`
- `sortBy`: `name`(显示名称,缺失时依次使用邮箱、上游账号 ID、本地 ID)、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt`
- `sortDirection`: `asc`、`desc`
账号列表的 `search` 仅按字面量包含匹配名称和邮箱,不区分大小写;`%`、`_` 和 `\` 按普通字符处理
@@ -3162,6 +3162,7 @@ Client Key 的频率、并发和费用预算限制分别为 `key_rate_limited`
使用记录列表和错误排查列表的 `accountPlanType` / `accountPlanTypeDisplay` 来自记录保存的账号订阅快照。
Antigravity 的展示名取自请求时已观测到的 Google 套餐描述,快照缺少描述时为 `null`
账号维度诊断按账号 ID 分组,`name` 依次取最近请求快照的账号名称、邮箱和账号 ID,`accountEmail` 返回快照邮箱,其他维度为 `null`。
账号维度诊断使用该账号最近请求的订阅快照,并通过 `authenticationKind` 返回同一请求的认证类型快照;未保存的字段为 `null`,非账号维度的认证类型为 `null`
管理端请求列表及 Dashboard 最近请求中的 `accountNotes` 来自请求保存的账号备注快照,未保存时为 `null`
+1
View File
@@ -387,6 +387,7 @@ export interface UsageDiagnosticItem {
platformIcon: string | null
key: string
name: string
accountEmail: string | null
authenticationKind: string | null
accountPlanType: string | null
accountPlanTypeDisplay: string | null
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { UsageAccountIdentity } from './presenter'
import { computed } from 'vue'
import { usageAccountDisplay } from './presenter'
const props = defineProps<{ record: UsageAccountIdentity }>()
const display = computed(() => usageAccountDisplay(props.record))
</script>
<template>
<span class="block max-w-full truncate text-z-sm leading-none font-bold text-z-text">
{{ display.primary }}
</span>
<span v-if="display.secondary" class="mt-1 block max-w-full truncate font-mono text-z-xs text-z-text-secondary">
{{ display.secondary }}
</span>
</template>
@@ -7,10 +7,8 @@ import { ZTable } from '@codex-proxy/ui'
import { useI18n } from 'vue-i18n'
import AccountPlanBadge from '@/components/account-plan-badge/index.vue'
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
import {
usageAccountText,
usageUserAgent,
} from './presenter'
import { usageUserAgent } from './presenter'
import UsageAccountCell from './UsageAccountCell.vue'
import UsageBillingCell from './UsageBillingCell.vue'
import UsageClientIpCell from './UsageClientIpCell.vue'
import UsageErrorCell from './UsageErrorCell.vue'
@@ -63,11 +61,7 @@ const { t } = useI18n({ useScope: 'global' })
</template>
<template #accountEmail="{ row }">
<span
class="block max-w-full truncate font-mono text-z-sm leading-none font-bold text-z-text"
>
{{ usageAccountText(row) }}
</span>
<UsageAccountCell :record="row" />
<span
v-if="row.accountNotes?.trim()"
class="mt-1 block max-w-full truncate text-z-xs font-emphasis text-z-text-quaternary"
@@ -64,8 +64,24 @@ export function usageTransportTypeClass(transport?: string | null) {
return 'bg-z-fill-tertiary text-z-text-secondary'
}
export function usageAccountText(record: Pick<UsageCommonRecord, 'accountEmail' | 'accountName' | 'accountId'>) {
return record.accountEmail || record.accountName || record.accountId || '—'
export type UsageAccountIdentity = Pick<UsageCommonRecord, 'accountName' | 'accountEmail' | 'accountId'>
export function usageAccountDisplay(record: UsageAccountIdentity) {
const email = record.accountEmail?.trim()
const primary = record.accountName?.trim() || email || record.accountId || '—'
return {
primary,
secondary: email && email !== primary
? email
: '',
}
}
export function usageAccountText(record: UsageAccountIdentity) {
const { primary, secondary } = usageAccountDisplay(record)
return secondary
? `${primary} (${secondary})`
: primary
}
export function usageClientIp(record: { clientIp?: string | null }) {
+1 -1
View File
@@ -35,7 +35,7 @@ export const accountColumns = computed(() => (defineTableColumns<Account>([
label: t('accounts.account'),
kind: 'identity',
size: '2xl',
sortable: 'email',
sortable: 'name',
},
{
key: 'provider',
@@ -7,6 +7,7 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import AccountPlanBadge from '@/components/account-plan-badge/index.vue'
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
import { usageAccountDisplay } from '@/components/usage-records-table/presenter'
import { formatLocalizedCompactNumber as formatCompactNumber, formatDuration, formatPercent, formatUsd } from '@/utils/format'
const props = withDefaults(
@@ -123,26 +124,28 @@ type DiagnosticDisplayItem = Diagnostics['items'][number] & {
const displayItems = computed<DiagnosticDisplayItem[]>(() =>
(props.diagnostics?.items ?? []).map(item => ({
...item,
nameDisplay: diagnosticNameDisplay(item.name),
nameDisplay: diagnosticNameDisplay(item),
})),
)
const hasData = computed(() => !props.loading && displayItems.value.length > 0)
function diagnosticNameDisplay(name: string) {
const raw = name.trim() || t('common.values.unknown')
function diagnosticNameDisplay(item: Diagnostics['items'][number]) {
if (resultDimension.value === 'account')
return usageAccountDisplay({ accountName: item.name, accountEmail: item.accountEmail, accountId: item.key })
const raw = item.name.trim() || t('common.values.unknown')
const full
= resultDimension.value === 'transport'
? ({ websocket: 'WS', http_sse: 'SSE' }[raw] ?? raw)
: raw
if (resultDimension.value !== 'model' && resultDimension.value !== 'account') {
return { primary: full, secondary: '', full }
if (resultDimension.value !== 'model') {
return { primary: full, secondary: '' }
}
const [primary, secondary = ''] = full.split(/\s+(?:→|->)\s+/, 2)
return {
primary: primary || full,
secondary,
full,
}
}
</script>
@@ -139,6 +139,7 @@ const attempts = computed(() => (props.record?.attempts ?? []).map(attempt => ({
label: t('accounts.account'),
value: usageAccountText(attempt),
mono: true,
wrap: true,
},
{
label: t('usage.error.platform'),
@@ -1,7 +1,7 @@
<script setup lang="ts">
import type { EChartsOption } from 'echarts'
import type { UsageRecordDetail } from '@/api'
import type { UsageAttempt, UsageRecordDetail } from '@/api'
import { defineTableColumns, ZButton, ZDialog, ZTable } from '@codex-proxy/ui'
import { computed } from 'vue'
@@ -19,6 +19,7 @@ import {
usageTransportType,
usageUserAgent,
} from '@/components/usage-records-table/presenter'
import UsageAccountCell from '@/components/usage-records-table/UsageAccountCell.vue'
import { useChartPalette } from '@/composables/useChartPalette'
import { formatDuration, formatInteger } from '@/utils/format'
@@ -74,6 +75,7 @@ const requestItems = computed(() => [
label: t('accounts.account'),
value: accountDisplay.value,
mono: true,
wrap: true,
fullWidth: true,
},
{
@@ -240,8 +242,7 @@ interface AttemptRow {
model: string | null
transport: string
statusCode: number | null
accountLabel: string
accountId: string | null
account: UsageAttempt
latencyMs: number | null
}
@@ -282,7 +283,7 @@ const attemptColumns = computed(() => (defineTableColumns<AttemptRow>([
size: 'sm',
},
{
key: 'accountLabel',
key: 'account',
label: t('accounts.account'),
kind: 'mono',
size: '2xl',
@@ -304,8 +305,7 @@ const attemptRows = computed<AttemptRow[]>(() =>
model: attempt.model,
transport: attempt.transport,
statusCode: attempt.statusCode,
accountLabel: attempt.accountEmail || attempt.accountName || attempt.accountId || '—',
accountId: attempt.accountId,
account: attempt,
latencyMs: attempt.latencyMs,
})),
)
@@ -685,12 +685,8 @@ const tokenDonutOption = computed<EChartsOption>(() => {
:status-code="typeof row.statusCode === 'number' ? row.statusCode : null"
/>
</template>
<template #accountLabel="{ row }">
<span
class="block max-w-full truncate font-mono text-z-sm font-bold text-z-text"
>
{{ row.accountLabel }}
</span>
<template #account="{ row }">
<UsageAccountCell :record="row.account" />
</template>
<template #latencyMs="{ row }">
<span class="font-mono font-bold tabular-nums text-z-text">