Add provider key cycle stats reset handling

This commit is contained in:
fawney19
2026-05-07 03:23:20 +08:00
parent 6c0ac2e8da
commit 10e679bb2f
35 changed files with 1443 additions and 273 deletions

View File

@@ -75,19 +75,21 @@
<!-- 子节点同提供商的其他尝试不包含首次 -->
<div
v-if="group.retryCount > 0 && isGroupSelected(group)"
v-if="group.retryCount > 0"
class="sub-dots"
>
<button
v-for="(attempt, idx) in group.allAttempts.slice(1)"
:key="attempt.id"
type="button"
class="sub-dot"
:class="[
getStatusColorClass(getDisplayStatus(attempt)),
{ active: selectedAttemptIndex === idx + 1 }
{ active: isAttemptSelected(group, idx + 1) }
]"
:title="attempt.key_name || `Key ${idx + 2}`"
@click.stop="selectedAttemptIndex = idx + 1"
:title="formatAttemptDotTitle(attempt)"
:aria-label="formatAttemptDotTitle(attempt)"
@click.stop="selectAttemptInGroup(group, idx + 1)"
/>
</div>
</div>
@@ -780,20 +782,28 @@ const STATUS_PRIORITY: Record<string, number> = {
success: 4,
}
// 候选时间线(按实际执行顺序排序)
const isParticipatedCandidate = (candidate: CandidateRecord): boolean => {
if (candidate.status === 'available' || candidate.status === 'unused') return false
if (candidate.status === 'pending' && !candidate.started_at) return false
return true
}
const compareBySchedulingOrder = (a: CandidateRecord, b: CandidateRecord): number => {
if (a.candidate_index !== b.candidate_index) {
return a.candidate_index - b.candidate_index
}
if (a.retry_index !== b.retry_index) {
return a.retry_index - b.retry_index
}
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
}
// 候选时间线按调度顺序排序lazy 加载的跳过候选通常没有 started_at
const rawTimeline = computed<CandidateRecord[]>(() => {
if (!trace.value) return []
return [...trace.value.candidates]
.filter(c => TIMELINE_STATUS.includes(c.status))
.sort((a, b) => {
const startedA = a.started_at ? new Date(a.started_at).getTime() : Infinity
const startedB = b.started_at ? new Date(b.started_at).getTime() : Infinity
if (startedA !== startedB) return startedA - startedB
if (a.candidate_index !== b.candidate_index) {
return a.candidate_index - b.candidate_index
}
return a.retry_index - b.retry_index
})
.sort(compareBySchedulingOrder)
})
@@ -919,7 +929,7 @@ const buildProviderGroups = (items: CandidateRecord[]): NodeGroup[] => {
// 将相同 Provider 的所有请求合并为组(同提供商的 Key 放在子节点)
const groupedTimeline = computed<NodeGroup[]>(() => {
const providerGroups = buildProviderGroups(timeline.value)
const providerGroups = buildProviderGroups(timeline.value.filter(isParticipatedCandidate))
if (poolAttemptsByGroup.value.size === 0) {
return providerGroups
}
@@ -929,12 +939,7 @@ const groupedTimeline = computed<NodeGroup[]>(() => {
const poolGroups: NodeGroup[] = []
for (const [groupId, attemptsRaw] of poolAttemptsByGroup.value.entries()) {
const attempts = [...attemptsRaw].sort((a, b) => {
if (a.candidate_index !== b.candidate_index) {
return a.candidate_index - b.candidate_index
}
return a.retry_index - b.retry_index
})
const attempts = [...attemptsRaw].sort(compareBySchedulingOrder)
if (attempts.length === 0) continue
const visibleAttempts = buildPoolGroupVisibleAttempts(attempts)
@@ -1638,6 +1643,32 @@ const selectFirstAttempt = (group: NodeGroup) => {
}
}
const selectAttemptInGroup = (group: NodeGroup, attemptIndex: number) => {
const groupIndex = groupedTimeline.value.findIndex(g => g.id === group.id && g.startIndex === group.startIndex)
if (groupIndex < 0) return
selectedGroupIndex.value = groupIndex
selectedAttemptIndex.value = attemptIndex
}
const isAttemptSelected = (group: NodeGroup, attemptIndex: number) => {
return isGroupSelected(group) && selectedAttemptIndex.value === attemptIndex
}
const formatCandidateAttemptIndex = (attempt: CandidateRecord): string => {
return attempt.retry_index > 0
? `#${attempt.candidate_index}.${attempt.retry_index}`
: `#${attempt.candidate_index}`
}
const formatAttemptDotTitle = (attempt: CandidateRecord): string => {
const parts = [
formatCandidateAttemptIndex(attempt),
attempt.key_name || attempt.key_account_label || attempt.key_preview || '未知 Key',
getStatusLabel(getDisplayStatus(attempt)),
]
return parts.filter(Boolean).join(' · ')
}
// 导航到上/下一组
const navigateGroup = (direction: number) => {
const newIndex = selectedGroupIndex.value + direction
@@ -1837,8 +1868,17 @@ const getStatusColorClass = (status: string) => {
}
// 展示状态:进行中态优先(包括 started 但未 finished 的中间态),再按 HTTP 状态码兜底
const getDisplayStatus = (attempt: CandidateRecord | null | undefined): string => {
function getDisplayStatus(attempt: CandidateRecord | null | undefined): string {
if (!attempt) return 'available'
if (
attempt.status === 'success' ||
attempt.status === 'failed' ||
attempt.status === 'cancelled' ||
attempt.status === 'skipped' ||
attempt.status === 'stream_interrupted'
) {
return attempt.status
}
const hasFinished = Boolean(attempt.finished_at)
const isExplicitPending = (attempt.status === 'pending' || attempt.status === 'streaming') && !hasFinished
const isImplicitPending = Boolean(

View File

@@ -311,10 +311,10 @@
<colgroup v-if="isAdmin">
<col class="w-[8%]">
<col class="w-[12%]">
<col class="w-[14%]">
<col class="w-[16%]">
<col class="w-[16%]">
<col class="w-[17%]">
<col class="w-[6%]">
<col class="w-[15%]">
<col class="w-[10%]">
<col class="w-[10%]">
<col class="w-[6%]">
<col class="w-[9%]">
@@ -322,9 +322,9 @@
<colgroup v-else>
<col class="w-[9%]">
<col class="w-[17%]">
<col class="w-[24%]">
<col class="w-[15%]">
<col class="w-[7%]">
<col class="w-[22%]">
<col class="w-[14%]">
<col class="w-[10%]">
<col class="w-[11%]">
<col class="w-[7%]">
<col class="w-[10%]">
@@ -360,7 +360,7 @@
密钥
</TableHead>
<SortableTableHead
class="h-12 font-semibold w-[16%]"
:class="['h-12 font-semibold', isAdmin ? 'w-[14%]' : 'w-[22%]']"
column-key="model"
:sortable="false"
:filter-active="filterModel !== '__all__'"
@@ -397,7 +397,7 @@
</template>
</SortableTableHead>
<SortableTableHead
class="h-12 font-semibold w-[17%]"
:class="['h-12 font-semibold', isAdmin ? 'w-[15%]' : 'w-[14%]']"
column-key="api_format"
:sortable="false"
:filter-active="filterApiFormat !== '__all__'"
@@ -415,7 +415,7 @@
</template>
</SortableTableHead>
<SortableTableHead
class="h-12 font-semibold w-[6%] text-center"
class="h-12 font-semibold w-[10%] text-center"
column-key="status"
:sortable="false"
align="center"
@@ -509,7 +509,7 @@
</div>
</TableCell>
<TableCell
class="font-medium py-4 w-[16%]"
:class="['font-medium py-4', isAdmin ? 'w-[14%]' : 'w-[22%]']"
:title="getModelTooltip(record)"
>
<div
@@ -596,7 +596,7 @@
</div>
</TableCell>
<TableCell
class="py-4 w-[17%]"
:class="['py-4', isAdmin ? 'w-[15%]' : 'w-[14%]']"
:title="getApiFormatTooltip(record)"
>
<!-- 有格式转换或同族格式差异两行显示 -->
@@ -631,7 +631,7 @@
class="text-muted-foreground text-xs"
>-</span>
</TableCell>
<TableCell class="text-center py-4 w-[6%]">
<TableCell class="text-center py-4 w-[10%]">
<!-- 优先显示请求状态 -->
<Badge
v-if="getDisplayStatus(record) === 'pending'"

View File

@@ -0,0 +1,272 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createApp, defineComponent, h, nextTick, type App } from 'vue'
import type { CandidateRecord, RequestTrace } from '@/api/requestTrace'
import HorizontalRequestTimeline from '../HorizontalRequestTimeline.vue'
vi.mock('@/components/ui/card.vue', async () => {
const { defineComponent, h } = await import('vue')
return {
default: defineComponent({
name: 'CardStub',
setup(_, { slots }) {
return () => h('section', slots.default?.())
},
}),
}
})
vi.mock('@/components/ui/badge.vue', async () => {
const { defineComponent, h } = await import('vue')
return {
default: defineComponent({
name: 'BadgeStub',
setup(_, { slots }) {
return () => h('span', slots.default?.())
},
}),
}
})
vi.mock('@/components/ui/skeleton.vue', async () => {
const { defineComponent, h } = await import('vue')
return {
default: defineComponent({
name: 'SkeletonStub',
setup() {
return () => h('div')
},
}),
}
})
vi.mock('../JsonContentPanel.vue', async () => {
const { defineComponent, h } = await import('vue')
return {
default: defineComponent({
name: 'JsonContentPanelStub',
setup() {
return () => h('div')
},
}),
}
})
vi.mock('lucide-vue-next', async () => {
const { defineComponent, h } = await import('vue')
const Icon = defineComponent({
name: 'IconStub',
setup() {
return () => h('span')
},
})
return {
ChevronLeft: Icon,
ChevronRight: Icon,
ExternalLink: Icon,
}
})
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
function buildCandidate(overrides: Partial<CandidateRecord> = {}): CandidateRecord {
return {
id: 'cand-1',
request_id: 'req-1',
candidate_index: 0,
retry_index: 0,
provider_id: 'provider-1',
provider_name: 'Provider 1',
key_id: 'key-1',
key_name: 'Key 1',
status: 'failed',
is_cached: false,
created_at: '2026-05-06T12:00:00.000Z',
started_at: '2026-05-06T12:00:00.000Z',
finished_at: '2026-05-06T12:00:01.000Z',
...overrides,
}
}
function buildTrace(candidates: CandidateRecord[]): RequestTrace {
return {
request_id: 'req-1',
total_candidates: candidates.length,
final_status: 'success',
total_latency_ms: 1000,
candidates,
}
}
function mountTimeline(traceData: RequestTrace) {
const root = document.createElement('div')
document.body.appendChild(root)
const app = createApp(HorizontalRequestTimeline, {
requestId: traceData.request_id,
traceData,
})
app.mount(root)
mountedApps.push({ app, root })
return root
}
afterEach(() => {
for (const { app, root } of mountedApps.splice(0)) {
app.unmount()
root.remove()
}
})
describe('HorizontalRequestTimeline', () => {
it('keeps attempted keys visible for ordinary provider groups that are not selected', async () => {
const trace = buildTrace([
buildCandidate({
id: 'provider-a-key-1',
provider_id: 'provider-a',
provider_name: 'Provider A',
key_id: 'key-a-1',
key_name: 'Key A1',
candidate_index: 0,
status: 'failed',
}),
buildCandidate({
id: 'provider-a-key-2',
provider_id: 'provider-a',
provider_name: 'Provider A',
key_id: 'key-a-2',
key_name: 'Key A2',
candidate_index: 1,
status: 'failed',
}),
buildCandidate({
id: 'provider-b-key-1',
provider_id: 'provider-b',
provider_name: 'Provider B',
key_id: 'key-b-1',
key_name: 'Key B1',
candidate_index: 2,
status: 'failed',
}),
buildCandidate({
id: 'provider-b-key-2',
provider_id: 'provider-b',
provider_name: 'Provider B',
key_id: 'key-b-2',
key_name: 'Key B2',
candidate_index: 3,
status: 'success',
}),
])
const root = mountTimeline(trace)
await nextTick()
const subDots = [...root.querySelectorAll<HTMLButtonElement>('.sub-dot')]
expect(subDots).toHaveLength(2)
expect(subDots.map(dot => dot.getAttribute('title'))).toEqual([
'#1 · Key A2 · 失败',
'#3 · Key B2 · 成功',
])
})
it('orders visible candidates by scheduling index and hides unstarted lazy candidates', async () => {
const trace = buildTrace([
buildCandidate({
id: 'cand-success',
provider_id: 'provider-success',
provider_name: 'Provider Success',
key_id: 'key-success',
key_name: 'Success Key',
candidate_index: 4,
status: 'success',
started_at: '2026-05-06T12:00:04.000Z',
finished_at: '2026-05-06T12:00:05.000Z',
}),
buildCandidate({
id: 'cand-available',
provider_id: 'provider-available',
provider_name: 'Provider Available',
key_id: 'key-available',
key_name: 'Available Key',
candidate_index: 0,
status: 'available',
started_at: undefined,
finished_at: undefined,
}),
buildCandidate({
id: 'cand-skipped',
provider_id: 'provider-skipped',
provider_name: 'Provider Skipped',
key_id: 'key-skipped',
key_name: 'Skipped Key',
candidate_index: 1,
status: 'skipped',
started_at: undefined,
finished_at: undefined,
}),
buildCandidate({
id: 'cand-pending-unstarted',
provider_id: 'provider-pending',
provider_name: 'Provider Pending',
key_id: 'key-pending',
key_name: 'Pending Key',
candidate_index: 2,
status: 'pending',
started_at: undefined,
finished_at: undefined,
}),
buildCandidate({
id: 'cand-failed',
provider_id: 'provider-failed',
provider_name: 'Provider Failed',
key_id: 'key-failed',
key_name: 'Failed Key',
candidate_index: 3,
status: 'failed',
started_at: '2026-05-06T12:00:03.000Z',
finished_at: '2026-05-06T12:00:04.000Z',
}),
])
const root = mountTimeline(trace)
await nextTick()
const labels = [...root.querySelectorAll<HTMLElement>('.node-label')]
.map(label => label.textContent?.trim())
expect(labels).toEqual(['Provider Skipped', 'Provider Failed', 'Provider Success'])
})
it('uses candidate terminal status for node colors instead of overriding with HTTP code', async () => {
const trace = buildTrace([
buildCandidate({
id: 'cand-body-error',
provider_id: 'provider-body-error',
provider_name: 'Provider Body Error',
key_id: 'key-body-error',
key_name: 'Body Error Key',
candidate_index: 0,
status: 'failed',
status_code: 200,
}),
buildCandidate({
id: 'cand-success',
provider_id: 'provider-success',
provider_name: 'Provider Success',
key_id: 'key-success',
key_name: 'Success Key',
candidate_index: 1,
status: 'success',
status_code: 200,
}),
])
const root = mountTimeline(trace)
await nextTick()
const nodeDots = [...root.querySelectorAll<HTMLElement>('.node-dot')]
expect(nodeDots[0].classList.contains('status-failed')).toBe(true)
expect(nodeDots[0].classList.contains('status-success')).toBe(false)
expect(nodeDots[1].classList.contains('status-success')).toBe(true)
})
})

View File

@@ -189,7 +189,7 @@ describe('poolTrace', () => {
expect(isAttemptedCandidate(buildCandidate({ status: 'unused' }))).toBe(false)
})
it('shows only attempted pool children when attempted nodes exist', () => {
it('keeps skipped pool children visible when attempted nodes exist', () => {
const attempts = buildPoolGroupVisibleAttempts([
buildCandidate({
id: 'cand-skipped',
@@ -210,10 +210,10 @@ describe('poolTrace', () => {
}),
])
expect(attempts.map(item => item.id)).toEqual(['cand-failed', 'cand-success'])
expect(attempts.map(item => item.id)).toEqual(['cand-skipped', 'cand-failed', 'cand-success'])
})
it('collapses all-skipped pool nodes to a single provider node', () => {
it('keeps all skipped pool children visible', () => {
const attempts = buildPoolGroupVisibleAttempts([
buildCandidate({
id: 'cand-skipped-1',
@@ -227,6 +227,6 @@ describe('poolTrace', () => {
}),
])
expect(attempts.map(item => item.id)).toEqual(['cand-skipped-2'])
expect(attempts.map(item => item.id)).toEqual(['cand-skipped-1', 'cand-skipped-2'])
})
})

View File

@@ -91,12 +91,19 @@ describe('usage status helpers', () => {
expect(isUsageRecordFailed(record)).toBe(true)
})
it('treats explicit success status code as authoritative for the timeline', () => {
it('prefers terminal request lifecycle status over status code for the timeline', () => {
expect(resolveTimelineFinalStatus({
traceFinalStatus: 'success',
requestStatus: 'failed',
statusCode: 200,
})).toBe('success')
})).toBe('failed')
})
it('prefers terminal trace status over status code when request lifecycle is absent', () => {
expect(resolveTimelineFinalStatus({
traceFinalStatus: 'failed',
statusCode: 200,
})).toBe('failed')
})
it('falls back to request lifecycle status when status code and trace are missing', () => {

View File

@@ -68,14 +68,7 @@ export const isAttemptedCandidate = (
export function buildPoolGroupVisibleAttempts(
attempts: CandidateRecord[],
): CandidateRecord[] {
if (attempts.length === 0) return []
const attempted = attempts.filter(isAttemptedCandidate)
if (attempted.length > 0) {
return attempted
}
return [attempts[attempts.length - 1]]
return attempts.filter(isPoolParticipatedCandidate)
}
export const parseTimelineStatus = (value: unknown): CandidateRecord['status'] | null => {

View File

@@ -272,8 +272,9 @@ export function resolveTimelineFinalStatus(params: {
requestStatus?: RequestStatusLike
statusCode?: number
}): TimelineFinalStatus {
if (typeof params.statusCode === 'number') {
return params.statusCode >= 200 && params.statusCode < 400 ? 'success' : 'failed'
const requestStatus = mapRequestStatusToTimelineStatus(params.requestStatus)
if (requestStatus === 'success' || requestStatus === 'failed' || requestStatus === 'cancelled') {
return requestStatus
}
const traceStatus = normalizeTimelineFinalStatus(params.traceFinalStatus)
@@ -281,9 +282,8 @@ export function resolveTimelineFinalStatus(params: {
return traceStatus
}
const requestStatus = mapRequestStatusToTimelineStatus(params.requestStatus)
if (requestStatus === 'success' || requestStatus === 'failed' || requestStatus === 'cancelled') {
return requestStatus
if (typeof params.statusCode === 'number') {
return params.statusCode >= 200 && params.statusCode < 400 ? 'success' : 'failed'
}
if (params.hasPendingCandidates) {