var REQUEST_MONITOR_RECORD_VIEW_CACHE_LIMIT = 2200 window.RequestMonitorTab = { name: 'RequestMonitorTab', props: { records: { type: Array, default: () => [] }, maxRecords: { type: Number, default: 0 }, detailLoading: { type: Object, default: () => ({}) }, systemStats: { type: Object, default: () => ({ memory_mb: 0, disk_status: '未知', total_requests: 0, total_input_tokens: 0, total_output_tokens: 0, cpu_percent: 0, project_cpu: 0, memory_percent: 0, project_memory_percent: 0, running_count: 0, queued_count: 0 }) }, loading: { type: Boolean, default: false }, error: { type: String, default: '' }, // 系统统计是否在轮询(DASHBOARD_SYSTEM_STATS_ENABLED)。关闭时 systemStats // 恒为初值,「正在执行」不能直接信任它,需退回历史记录统计。 systemStatsEnabled: { type: Boolean, default: true } }, emits: ['refresh', 'load-detail'], data() { return { currentPage: 1, pageSize: 20, selectedRecord: null, showErrorStack: false, expandedTextBlocks: {}, query: '', statusFilter: 'all', includeMultimodal: true, analyticsRange: '7d', trendRange: '24h', showSystemLoad: false, rankingDimension: 'domain', monitorView: 'requests' } }, created() { this.recordViewCacheStore = new Map() this.recordViewCacheKeyOrder = [] }, computed: { recordSummary() { const items = Array.isArray(this.records) ? this.records.map((record, index) => this.toCachedRecordView(record, index)) : [] const sorted = this.recordsAreNewestFirst(items) ? items : items.slice().sort((a, b) => this.compareRecordsNewestFirst(a, b)) // 修复:KPI 与状态页签计数此前基于未过滤的 sorted,与「包含多模态」开关脱节。 // sorted 仍保留全量(排序/分页/查找依赖它),聚合统计一律改用 base 子集。 const base = this.includeMultimodal ? sorted : sorted.filter(item => !(item && item.is_multimodal)) const domains = new Map() const models = new Map() const durations = [] let success = 0 let successDurationTotal = 0 let promptTokens = 0 let responseTokens = 0 base.forEach(item => { if (item && item.success) { success += 1 successDurationTotal += Number(item.duration_ms || 0) } const duration = Number(item && item.duration_ms || 0) if (Number.isFinite(duration) && duration > 0) { durations.push(duration) } const estimate = item && item.token_estimate && typeof item.token_estimate === 'object' ? item.token_estimate : {} const itemPromptTokens = Math.max(0, Number(estimate.prompt || 0)) const itemResponseTokens = Math.max(0, Number(estimate.response || 0)) promptTokens += Number.isFinite(itemPromptTokens) ? itemPromptTokens : 0 responseTokens += Number.isFinite(itemResponseTokens) ? itemResponseTokens : 0 const domain = this.recordDomain(item) const current = domains.get(domain) || { domain, total: 0, success: 0, failed: 0, rate: 0 } current.total += 1 if (item && item.success) { current.success += 1 } else { current.failed += 1 } domains.set(domain, current) const model = String(item && (item.model || item.preset_name) || '未知').trim() || '未知' const modelCurrent = models.get(model) || { model, total: 0, success: 0, failed: 0, tokens: 0, rate: 0 } modelCurrent.total += 1 modelCurrent.tokens += (Number.isFinite(itemPromptTokens) ? itemPromptTokens : 0) + (Number.isFinite(itemResponseTokens) ? itemResponseTokens : 0) if (item && item.success) { modelCurrent.success += 1 } else { modelCurrent.failed += 1 } models.set(model, modelCurrent) }) const domainStats = Array.from(domains.values()) .map(item => ({ ...item, rate: item.total ? Math.round((item.success / item.total) * 100) : 0 })) .sort((a, b) => b.total - a.total || b.rate - a.rate) .slice(0, 10) const modelStats = Array.from(models.values()) .map(item => ({ ...item, rate: item.total ? Math.round((item.success / item.total) * 100) : 0 })) .sort((a, b) => b.total - a.total || b.tokens - a.tokens || b.rate - a.rate) .slice(0, 10) durations.sort((a, b) => a - b) const p95Index = durations.length ? Math.max(0, Math.ceil(durations.length * 0.95) - 1) : 0 return { sorted, base, success, failure: base.length - success, successRate: base.length ? Math.round((success / base.length) * 100) : 0, avgDuration: success ? Math.round(successDurationTotal / success) : 0, p95Duration: durations.length ? Math.round(durations[p95Index]) : 0, promptTokens, responseTokens, domainStats, modelStats } }, sortedRecords() { return this.recordSummary.sorted }, // 修复:只应用「包含多模态」过滤、不应用 statusFilter,供各类计数展示使用 baseRecords() { return this.recordSummary.base }, visibleRecords() { const page = Math.min(Math.max(1, this.currentPage), this.totalPages) const start = (page - 1) * this.pageSize return this.filteredRecords.slice(start, start + this.pageSize) }, hasMoreRecords() { return this.currentPage < this.totalPages }, totalPages() { return Math.max(1, Math.ceil(this.filteredRecords.length / this.pageSize)) }, paginationItems() { const total = this.totalPages const current = Math.min(Math.max(1, this.currentPage), total) const pages = new Set([1, total, current - 1, current, current + 1]) if (current <= 4) { [2, 3, 4, 5].forEach(page => pages.add(page)) } if (current >= total - 3) { [total - 4, total - 3, total - 2, total - 1].forEach(page => pages.add(page)) } const validPages = Array.from(pages) .filter(page => page >= 1 && page <= total) .sort((a, b) => a - b) const items = [] validPages.forEach((page, index) => { if (index > 0 && page - validPages[index - 1] > 1) { items.push({ key: 'ellipsis-' + page, page: null, label: '...' }) } items.push({ key: 'page-' + page, page, label: String(page) }) }) return items }, filteredRecords() { const query = String(this.query || '').trim().toLowerCase() // 修复:多模态过滤已在 baseRecords 完成,这里只负责 statusFilter 与关键词 return this.baseRecords.filter(record => { if (this.statusFilter === 'success' && !record.success) return false if (this.statusFilter === 'failed' && (record.success || record.status === 'cancelled')) return false if (this.statusFilter === 'cancelled' && record.status !== 'cancelled') return false if (!query) return true return [ record.id, record.__historyKey, record.__domain, record.model, record.preset_name, record.route_group, record.endpoint, record.request_type, record.__summaryText ].some(value => String(value || '').toLowerCase().includes(query)) }) }, runningCount() { // 修复:/api/system/request-history 结构上只保存终态记录(写入点全在 finalize 之后), // 靠它统计"正在执行"恒为 0。改读 /api/system/stats 的实时字段。 // 历史记录里的 running/queued 仅作为兜底(真实枚举为 queued/running/completed/cancelled/failed, // 此前写的 'pending'/'processing' 根本不存在于后端)。 // systemStats 关闭时(DASHBOARD_SYSTEM_STATS_ENABLED=false)不会轮询, // 字段恒为初值 0,此时退回历史记录统计而不是谎报 0。 if (this.liveCountsAvailable) { const live = Number((this.systemStats || {}).running_count) if (Number.isFinite(live) && live >= 0) return live } return this.baseRecords.filter(record => ['running', 'queued'].includes(String(record.status || '').toLowerCase())).length }, queuedCount() { if (!this.liveCountsAvailable) return 0 const queued = Number((this.systemStats || {}).queued_count) return Number.isFinite(queued) && queued >= 0 ? queued : 0 }, liveCountsAvailable() { // 只有在系统统计确实在轮询、且后端返回过实时计数字段时才信任它 const stats = this.systemStats || {} return Object.prototype.hasOwnProperty.call(stats, 'running_count') && !!this.systemStatsEnabled }, trendRangeSeconds() { if (this.trendRange === '1h') return 60 * 60 if (this.trendRange === '7d') return 7 * 24 * 60 * 60 return 24 * 60 * 60 }, trendBuckets() { const bucketCount = 10 const now = Math.max(Date.now() / 1000, this.sortedRecords.length ? this.recordSortTimestamp(this.sortedRecords[0]) : 0) const start = now - this.trendRangeSeconds const bucketSize = this.trendRangeSeconds / bucketCount const buckets = Array.from({ length: bucketCount }, (_, index) => ({ start: start + index * bucketSize, total: 0, success: 0, failed: 0 })) this.sortedRecords.forEach(record => { const timestamp = this.recordSortTimestamp(record) if (!timestamp || timestamp < start || timestamp > now) return const index = Math.min(bucketCount - 1, Math.max(0, Math.floor((timestamp - start) / bucketSize))) buckets[index].total += 1 if (record && record.success) { buckets[index].success += 1 } else { buckets[index].failed += 1 } }) return buckets }, trendMax() { return Math.max(1, ...this.trendBuckets.map(bucket => bucket.total)) }, trendLinePoints() { return this.trendBuckets.map((bucket, index) => { const x = 20 + index * (760 / Math.max(1, this.trendBuckets.length - 1)) const y = 205 - (bucket.total / this.trendMax) * 160 return x.toFixed(1) + ',' + y.toFixed(1) }).join(' ') }, trendAreaPoints() { return '20,220 ' + this.trendLinePoints + ' 780,220' }, trendTotal() { return this.trendBuckets.reduce((total, bucket) => total + bucket.total, 0) }, trendSuccessTotal() { return this.trendBuckets.reduce((total, bucket) => total + bucket.success, 0) }, trendFailureTotal() { return this.trendBuckets.reduce((total, bucket) => total + bucket.failed, 0) }, trendLabels() { const newest = this.trendBuckets[this.trendBuckets.length - 1] const oldest = this.trendBuckets[0] const format = value => new Date(value * 1000).toLocaleString('zh-CN', this.trendRange === '7d' ? { month: '2-digit', day: '2-digit' } : { hour: '2-digit', minute: '2-digit' }) return [format(oldest.start), format(oldest.start + this.trendRangeSeconds / 2), format(newest.start)] }, maxDomainTotal() { return Math.max(1, ...this.domainStats.map(item => item.total)) }, modelStats() { return this.recordSummary.modelStats }, rankingStats() { if (this.rankingDimension === 'model') { return this.modelStats.map(item => ({ key: item.model, label: item.model, total: item.total, success: item.success, failed: item.failed, rate: item.rate, meta: this.formatTokenNumber(item.tokens) + ' Token' })) } return this.domainStats.map(item => ({ key: item.domain, label: item.domain, total: item.total, success: item.success, failed: item.failed, rate: item.rate, meta: item.rate + '% 成功' })) }, maxRankingTotal() { return Math.max(1, ...this.rankingStats.map(item => item.total)) }, // 修复:详情抽屉里的 selectedRecord 是 this.records 的原始对象,不带 toRecordView 生成的 // __toolCallingErrorInfo,导致工具调用错误面板恒不显示;这里按需现算,且不污染原始数据。 selectedRecordToolCallingError() { return this.selectedRecord ? this.toolCallingErrorInfo(this.selectedRecord) : null }, successCount() { return this.recordSummary.success }, failureCount() { return this.recordSummary.failure }, cancelledCount() { // 修复:改用 baseRecords,与其它状态页签计数口径保持一致 return this.baseRecords.filter(record => String(record.status || '').toLowerCase() === 'cancelled').length }, globalSuccessRate() { return this.recordSummary.successRate }, domainStats() { return this.recordSummary.domainStats }, selectedTimingText() { if (!this.selectedRecord) return '' return '排队等待: ' + this.formatDurationMs(this.selectedRecord.queue_ms) + ' + 生成耗时: ' + this.formatDurationMs(this.selectedRecord.generation_ms) }, inputRatio() { const total = (this.systemStats.total_input_tokens || 0) + (this.systemStats.total_output_tokens || 0) return total ? Math.round((this.systemStats.total_input_tokens / total) * 100) : 50 }, outputRatio() { const total = (this.systemStats.total_input_tokens || 0) + (this.systemStats.total_output_tokens || 0) return total ? (100 - this.inputRatio) : 50 }, avgDuration() { return this.recordSummary.avgDuration }, p95Duration() { return this.recordSummary.p95Duration }, cumulativeTokens() { return Number(this.systemStats.total_input_tokens || 0) + Number(this.systemStats.total_output_tokens || 0) }, sampleTokens() { return Number(this.recordSummary.promptTokens || 0) + Number(this.recordSummary.responseTokens || 0) }, retentionLimit() { return Math.max(Number(this.maxRecords || 0), this.sortedRecords.length) }, retentionUsage() { return this.retentionLimit ? Math.min(100, Math.round((this.sortedRecords.length / this.retentionLimit) * 100)) : 0 }, analyticsRangeDays() { if (this.analyticsRange === '7d') return 7 if (this.analyticsRange === '30d') return 30 return null }, analyticsRecords() { if (!this.analyticsRangeDays) return this.sortedRecords const cutoff = Date.now() - this.analyticsRangeDays * 24 * 60 * 60 * 1000 return this.sortedRecords.filter(record => this.recordDate(record).getTime() >= cutoff) }, hourlyTokenBuckets() { const now = new Date() const buckets = Array.from({ length: 24 }, (_, hour) => ({ hour, prompt: 0, response: 0, total: 0, calls: 0 })) this.sortedRecords.forEach(record => { const date = this.recordDate(record) if (date.getFullYear() !== now.getFullYear() || date.getMonth() !== now.getMonth() || date.getDate() !== now.getDate()) return const tokens = this.recordTokens(record) const bucket = buckets[date.getHours()] bucket.prompt += tokens.prompt bucket.response += tokens.response bucket.total += tokens.total bucket.calls += 1 }) return buckets }, hourlyTokenMax() { return Math.max(1, ...this.hourlyTokenBuckets.map(bucket => Math.max(bucket.prompt, bucket.response))) }, hourlyYAxisLabels() { return this.chartYAxisLabels(this.hourlyTokenMax) }, hourlyValueLabels() { return [ this.chartPeakLabel(this.hourlyTokenBuckets, 'prompt', this.hourlyTokenMax, '输入'), this.chartPeakLabel(this.hourlyTokenBuckets, 'response', this.hourlyTokenMax, '输出') ].filter(Boolean) }, hourlyPromptPath() { return this.linePath(this.hourlyTokenBuckets, 'prompt', this.hourlyTokenMax) }, hourlyResponsePath() { return this.linePath(this.hourlyTokenBuckets, 'response', this.hourlyTokenMax) }, dailyTokenBuckets() { const totals = new Map() this.analyticsRecords.forEach(record => { const date = this.recordDate(record) const key = this.localDateKey(date) const current = totals.get(key) || { key, date, prompt: 0, response: 0, total: 0, calls: 0 } const tokens = this.recordTokens(record) current.prompt += tokens.prompt current.response += tokens.response current.total += tokens.total current.calls += 1 totals.set(key, current) }) if (!this.analyticsRangeDays) { return Array.from(totals.values()).sort((a, b) => a.key.localeCompare(b.key)) } const buckets = [] const today = new Date() today.setHours(12, 0, 0, 0) for (let offset = this.analyticsRangeDays - 1; offset >= 0; offset -= 1) { const date = new Date(today) date.setDate(today.getDate() - offset) const key = this.localDateKey(date) buckets.push(totals.get(key) || { key, date, prompt: 0, response: 0, total: 0, calls: 0 }) } return buckets }, dailyTokenMax() { return Math.max(1, ...this.dailyTokenBuckets.map(bucket => bucket.total)) }, dailyYAxisLabels() { return this.chartYAxisLabels(this.dailyTokenMax) }, dailyChartBars() { const count = Math.max(1, this.dailyTokenBuckets.length) const slot = 718 / count const width = Math.max(5, Math.min(22, slot * 0.44)) const gap = Math.max(2, Math.min(6, width * 0.28)) const stackWidth = (width - gap) / 2 return this.dailyTokenBuckets.map((bucket, index) => { const promptHeight = (bucket.prompt / this.dailyTokenMax) * 145 const responseHeight = (bucket.response / this.dailyTokenMax) * 145 return { ...bucket, x: 62 + slot * index + (slot - width) / 2, promptX: 62 + slot * index + (slot - width) / 2, responseX: 62 + slot * index + (slot - width) / 2 + stackWidth + gap, barWidth: stackWidth, promptHeight, responseHeight, promptY: 190 - promptHeight, responseY: 190 - responseHeight, pointX: 62 + slot * index + slot / 2, pointY: 190 - (bucket.total / this.dailyTokenMax) * 145 } }) }, dailyValueLabels() { return this.dailyChartBars .filter(bar => Number(bar.total || 0) > 0) .sort((a, b) => b.total - a.total) .slice(0, 3) .map(bar => ({ key: bar.key, x: bar.pointX, y: Math.max(34, bar.pointY - 12), text: this.formatTokenNumber(bar.total) })) }, dailyTotalPath() { return this.smoothLinePath(this.dailyChartBars.map(bar => ({ x: bar.pointX, y: bar.pointY }))) }, dailyChartLabels() { const buckets = this.dailyTokenBuckets if (!buckets.length) return [] const indexes = Array.from(new Set([0, Math.floor((buckets.length - 1) / 2), buckets.length - 1])) return indexes.map(index => ({ index, label: this.shortDate(buckets[index].date) })) }, analyticsModelStats() { const models = new Map() this.analyticsRecords.forEach(record => { const name = String(record && (record.model || record.preset_name) || '未知').trim() || '未知' const current = models.get(name) || { name, calls: 0, tokens: 0 } current.calls += 1 current.tokens += this.recordTokens(record).total models.set(name, current) }) return Array.from(models.values()) .sort((a, b) => b.tokens - a.tokens || b.calls - a.calls) .slice(0, 8) }, analyticsModelTotal() { return this.analyticsModelStats.reduce((total, item) => total + item.tokens, 0) }, modelDonutSegments() { const circumference = 364.425 const valueTotal = this.analyticsModelTotal || this.analyticsModelStats.reduce((total, item) => total + item.calls, 0) let consumed = 0 return this.analyticsModelStats.map((item, index) => { const value = this.analyticsModelTotal ? item.tokens : item.calls const length = valueTotal ? (value / valueTotal) * circumference : 0 const segment = { ...item, color: this.modelColor(index), dasharray: length + ' ' + Math.max(0, circumference - length), dashoffset: -consumed, percent: valueTotal ? Math.round((value / valueTotal) * 100) : 0 } consumed += length return segment }) }, analyticsSampleTotals() { return this.analyticsRecords.reduce((totals, record) => { const tokens = this.recordTokens(record) totals.prompt += tokens.prompt totals.response += tokens.response totals.total += tokens.total totals.calls += 1 return totals }, { prompt: 0, response: 0, total: 0, calls: 0 }) } }, watch: { records() { if (this.currentPage > this.totalPages) { this.currentPage = this.totalPages } if (this.selectedRecord && this.selectedRecord.id) { const selectedKey = String(this.selectedRecord.__historyKey || this.selectedRecord.history_key || '').trim() const current = this.resolveRecordForDetail(selectedKey, this.selectedRecord) if (current) { this.selectedRecord = current } } }, query() { this.currentPage = 1 }, statusFilter() { this.currentPage = 1 }, includeMultimodal() { this.currentPage = 1 } }, methods: { toCachedRecordView(record, index) { const source = record && typeof record === 'object' ? record : {} const cache = this.ensureRecordViewCache() const historyKey = this.recordKey(source, index) const signature = this.recordViewSignature(source, historyKey) const cached = cache.get(historyKey) if (cached && cached.signature === signature) { this.touchRecordViewCacheKey(historyKey) return cached.view } const view = this.toRecordView(record, index) cache.set(historyKey, { signature, view }) this.touchRecordViewCacheKey(historyKey) this.pruneRecordViewCache() return view }, ensureRecordViewCache() { if (!(this.recordViewCacheStore instanceof Map)) { this.recordViewCacheStore = new Map() } if (!Array.isArray(this.recordViewCacheKeyOrder)) { this.recordViewCacheKeyOrder = [] } return this.recordViewCacheStore }, touchRecordViewCacheKey(key) { const cacheKeys = Array.isArray(this.recordViewCacheKeyOrder) ? this.recordViewCacheKeyOrder : [] if (cacheKeys !== this.recordViewCacheKeyOrder) { this.recordViewCacheKeyOrder = cacheKeys } const existingIndex = cacheKeys.indexOf(key) if (existingIndex >= 0) { cacheKeys.splice(existingIndex, 1) } cacheKeys.push(key) }, pruneRecordViewCache() { const cache = this.ensureRecordViewCache() while (this.recordViewCacheKeyOrder.length > REQUEST_MONITOR_RECORD_VIEW_CACHE_LIMIT) { const staleKey = this.recordViewCacheKeyOrder.shift() cache.delete(staleKey) } }, recordViewSignature(record, historyKey) { const source = record && typeof record === 'object' ? record : {} const estimate = source.token_estimate && typeof source.token_estimate === 'object' ? source.token_estimate : {} const detailLengths = source.detail_text_lengths && typeof source.detail_text_lengths === 'object' ? source.detail_text_lengths : {} return [ historyKey, source.id, source.status, source.success ? 1 : 0, source.target_domain, source.route_domain, source.route_group, source.preset_name, source.tab_index, source.tab_id, source.model, source.endpoint, source.request_type, source.is_stream ? 1 : 0, source.is_multimodal ? 1 : 0, source.created_at, source.started_at, source.finished_at, source.duration_ms, source.queue_ms, source.generation_ms, source.summary, source.prompt_preview, source.response_preview, source.error_message, source.error_code, source.cancel_reason, source.media_count, source.has_detail ? 1 : 0, source.detail_loaded ? 1 : 0, detailLengths.prompt, detailLengths.response, detailLengths.error_stack, estimate.prompt, estimate.response, estimate.total, estimate.chars, this.recordViewTextSignature(source.prompt), this.recordViewTextSignature(source.response), this.recordViewTextSignature(source.error_stack) ].map(value => String(value ?? '')).join('\u001f') }, recordViewTextSignature(value) { if (value === undefined || value === null || value === '') return '' let text = '' if (typeof value === 'string') { text = value } else { try { text = JSON.stringify(value) } catch (error) { text = String(value) } } if (text.length <= 160) return text return text.length + ':' + this.recordViewTextHash(text) }, recordViewTextHash(text) { let hash = 2166136261 for (let index = 0; index < text.length; index += 1) { hash ^= text.charCodeAt(index) hash = Math.imul(hash, 16777619) } return (hash >>> 0).toString(36) }, toRecordView(record, index) { const source = record && typeof record === 'object' ? record : {} const domain = this.recordDomain(source) const toolCallingErrorInfo = this.toolCallingErrorInfo(source) const summarySource = toolCallingErrorInfo ? toolCallingErrorInfo.summary : (source.summary || source.response_preview || source.response || source.error_message) const success = !!source.success const historyKey = this.recordKey(source, index) const { payload, response_payload, prompt, response, error_stack, ...viewSource } = source return { ...viewSource, id: source.id || historyKey, __historyKey: historyKey, __domain: domain, __statusText: this.statusText(source), __statusIcon: success ? '🟢' : '🔴', __statusClasses: this.statusClasses(source), __statusPillClasses: this.statusPillClasses(source), __summaryText: this.compactText(summarySource, 52), __startedText: this.formatDateTime(source.started_at || source.created_at), __finishedText: this.formatDateTime(source.finished_at), __durationText: this.formatDurationMs(source.duration_ms), __tokenText: this.tokenEstimate(source), __tabLabel: this.tabLabel(source), __toolCallingErrorInfo: toolCallingErrorInfo } }, recordDomain(record) { const source = record && typeof record === 'object' ? record : {} return String(source.route_domain || source.__domain || source.target_domain || '未知域名').trim() || '未知域名' }, recordKey(record, index) { const source = record && typeof record === 'object' ? record : {} const key = String(source.history_key || '').trim() if (key) return key const id = String(source.id || '').trim() || ('record-' + index) return [ id, this.normalizeTimestamp(source.created_at), this.normalizeTimestamp(source.finished_at) ].join(':') }, normalizeTimestamp(value) { if (typeof value === 'number') { if (!Number.isFinite(value) || value <= 0) return 0 return value > 1000000000000 ? value / 1000 : value } const text = String(value || '').trim() if (!text) return 0 const numeric = Number(text) if (Number.isFinite(numeric) && numeric > 0) { return numeric > 1000000000000 ? numeric / 1000 : numeric } const parsed = Date.parse(text) return Number.isNaN(parsed) ? 0 : parsed / 1000 }, recordSortTimestamp(record) { if (!record) return 0 return this.normalizeTimestamp(record.finished_at) || this.normalizeTimestamp(record.started_at) || this.normalizeTimestamp(record.created_at) }, compareRecordsNewestFirst(left, right) { const delta = this.recordSortTimestamp(right) - this.recordSortTimestamp(left) if (delta !== 0) return delta return String(right && right.__historyKey || '').localeCompare(String(left && left.__historyKey || '')) }, recordsAreNewestFirst(items) { if (!Array.isArray(items) || items.length < 2) return true for (let index = 1; index < items.length; index += 1) { if (this.compareRecordsNewestFirst(items[index - 1], items[index]) > 0) { return false } } return true }, isRecordDetailLoading(record) { const keys = [ record && record.__historyKey, record && record.history_key, record && record.id ].map(value => String(value || '').trim()).filter(Boolean) return keys.some(key => !!this.detailLoading[key]) }, detailKey(record) { return String( record && (record.__historyKey || record.history_key || record.id) || '' ).trim() }, resolveRecordForDetail(recordOrKey, fallback = null) { const records = Array.isArray(this.records) ? this.records : [] const requestedKey = typeof recordOrKey === 'string' ? String(recordOrKey || '').trim() : this.detailKey(recordOrKey) if (requestedKey) { const current = records.find(item => { const itemKey = String(item && (item.__historyKey || item.history_key || '')).trim() if (itemKey && itemKey === requestedKey) return true const itemId = String(item && item.id || '').trim() return itemId && itemId === requestedKey }) if (current) { return current } } const fallbackKey = this.detailKey(fallback) if (fallbackKey) { const current = records.find(item => { const itemKey = String(item && (item.__historyKey || item.history_key || '')).trim() if (itemKey && itemKey === fallbackKey) return true const itemId = String(item && item.id || '').trim() return itemId && itemId === fallbackKey }) if (current) { return current } } return fallback }, refresh() { this.$emit('refresh') }, loadMore() { this.goToPage(this.currentPage + 1) }, goToPage(page) { const normalized = Math.min(Math.max(1, Number(page) || 1), this.totalPages) this.currentPage = normalized }, openRecord(record) { this.detailReturnFocus = document.activeElement this.selectedRecord = this.resolveRecordForDetail(record, record) this.showErrorStack = false this.expandedTextBlocks = {} this.$nextTick(() => this.$el.querySelector('.ops-request-drawer button')?.focus()) const key = this.detailKey(this.selectedRecord || record) if (record && key && record.has_detail && !record.detail_loaded) { this.$emit('load-detail', key) } }, closeRecord() { this.selectedRecord = null this.showErrorStack = false this.expandedTextBlocks = {} this.$nextTick(() => this.detailReturnFocus?.focus()) }, handleDetailKeydown(event) { if (event.key === 'Escape') { event.preventDefault() this.closeRecord() return } if (event.key !== 'Tab') return const controls = Array.from(event.currentTarget.querySelectorAll('button,textarea,input,select,[tabindex="0"]')) .filter(el => !el.disabled && el.getClientRects().length) const first = controls[0], last = controls[controls.length - 1] if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus() } if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() } }, formatDurationMs(value) { const ms = Number(value || 0) if (!Number.isFinite(ms) || ms <= 0) return '0s' if (ms < 1000) return Math.round(ms) + 'ms' return (ms / 1000).toFixed(ms >= 10000 ? 1 : 2).replace(/\.0$/, '') + 's' }, formatTime(value) { const timestamp = Number(value || 0) if (!timestamp) return '-' const date = new Date(timestamp * 1000) if (Number.isNaN(date.getTime())) return '-' return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) }, formatDateTime(value) { const timestamp = Number(value || 0) if (!timestamp) return '-' const date = new Date(timestamp * 1000) if (Number.isNaN(date.getTime())) return '-' return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) }, formatNumber(value) { return (Number(value) || 0).toLocaleString('zh-CN') }, formatPercent(value) { const num = Number(value) || 0 return num.toFixed(1).replace(/\.0$/, '') }, meterWidth(value) { const num = Number(value) || 0 return Math.max(0, Math.min(100, num)) + '%' }, formatTokenNumber(value) { const num = Number(value) || 0 if (num >= 1e9) { return parseFloat((num / 1e9).toFixed(2)) + 'B' } if (num >= 1e6) { return parseFloat((num / 1e6).toFixed(2)) + 'M' } if (num >= 1e4) { return parseFloat((num / 1e3).toFixed(2)) + 'K' } return num.toLocaleString('zh-CN') }, statusTone(record) { return record && record.success ? 'success' : 'failed' }, statusText(record) { if (record && record.success) return '成功' if (record && record.status === 'cancelled') return '已取消' return '失败' }, statusClasses(record) { if (record && record.success) { return 'border-emerald-200 bg-emerald-50/90 hover:bg-emerald-50 dark:border-emerald-500/25 dark:bg-emerald-900/10 dark:hover:bg-emerald-900/20' } return 'border-rose-200 bg-rose-50/90 hover:bg-rose-50 dark:border-rose-500/25 dark:bg-rose-900/10 dark:hover:bg-rose-900/20' }, statusPillClasses(record) { if (record && record.success) { return 'bg-emerald-100 text-emerald-700 ring-emerald-200 dark:bg-emerald-500/15 dark:text-emerald-200 dark:ring-emerald-500/30' } return 'bg-rose-100 text-rose-700 ring-rose-200 dark:bg-rose-500/15 dark:text-rose-200 dark:ring-rose-500/30' }, rateToneClass(rate) { if (rate >= 90) return 'bg-emerald-500' if (rate >= 70) return 'bg-amber-500' return 'bg-rose-500' }, rateBadge(rate) { if (rate >= 90) return '🟢' if (rate >= 70) return '🟡' return '🔴' }, trendBucketTitle(bucket) { const start = new Date(Number(bucket.start || 0) * 1000).toLocaleString('zh-CN') return start + ' · 成功 ' + bucket.success + ' · 失败 ' + bucket.failed }, trendBucketSuccessWidth(bucket) { if (!bucket || !bucket.total) return '0%' return Math.round((bucket.success / bucket.total) * 100) + '%' }, compactText(value, max = 50) { const text = String(value || '').replace(/\s+/g, ' ').trim() if (!text) return '暂无响应摘要' return text.length > max ? text.slice(0, max) + '...' : text }, toolCallingErrorInfo(record) { const source = record && typeof record === 'object' ? record : {} const errorCode = String(source.error_code || source.status || '').trim() const errorText = [ source.error_message, source.error_stack, source.summary, source.response_preview, source.response ].map(value => String(value || '')).join('\n') if (!errorText.includes('tool_call_validation_exhausted')) { return null } const marker = 'tool_call_validation_exhausted:' const markerIndex = errorText.indexOf(marker) const detail = markerIndex >= 0 ? errorText.slice(markerIndex + marker.length).split('\n')[0].trim() : '' return { code: errorCode || 'tool_calling_failed', title: '工具调用重试耗尽', summary: '工具调用重试耗尽:模型没有返回可执行的 tool_calls,系统已停止并返回错误,未降级为普通文本。', detail: detail || '没有可保留的工具调用,已阻止纯文本兜底。' } }, getDetailText(record, key) { if (!record) return '' if (key === 'prompt') { return String(record.prompt || record.prompt_preview || '暂无请求上下文') } return String(record.response || record.response_preview || record.error_message || '暂无响应内容') }, isTextBlockExpanded(key) { return !!this.expandedTextBlocks[key] }, getTextBlockPreview(record, key) { const text = this.getDetailText(record, key) if (this.isTextBlockExpanded(key) || text.length <= 6000) { return text } return text.slice(0, 6000) + '\n\n[已截断预览,点击展开全文]' }, shouldShowExpandTextButton(record, key) { const lengths = record && record.detail_text_lengths ? record.detail_text_lengths : {} return this.getDetailText(record, key).length > 6000 || Number(lengths[key] || 0) > 6000 }, expandTextButtonLabel(record, key) { if (this.isRecordDetailLoading(record)) return '加载中...' return this.isTextBlockExpanded(key) ? '收起' : '展开全文' }, toggleTextBlock(key) { if (this.isRecordDetailLoading(this.selectedRecord)) { return } this.expandedTextBlocks = { ...this.expandedTextBlocks, [key]: !this.expandedTextBlocks[key] } }, recordDate(record) { const timestamp = this.recordSortTimestamp(record) const date = new Date(timestamp > 0 ? timestamp * 1000 : 0) return Number.isNaN(date.getTime()) ? new Date(0) : date }, recordTokens(record) { const estimate = record && record.token_estimate && typeof record.token_estimate === 'object' ? record.token_estimate : {} const prompt = Math.max(0, Number(estimate.prompt || 0)) const response = Math.max(0, Number(estimate.response || 0)) return { prompt: Number.isFinite(prompt) ? prompt : 0, response: Number.isFinite(response) ? response : 0, total: (Number.isFinite(prompt) ? prompt : 0) + (Number.isFinite(response) ? response : 0) } }, localDateKey(date) { const pad = value => String(value).padStart(2, '0') return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) }, shortDate(date) { return String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0') }, chartYAxisLabels(maximum) { const max = Math.max(1, Number(maximum || 0)) return [1, 0.66, 0.31, 0].map((ratio, index) => { const y = [45, 95, 145, 190][index] return { key: index, y, text: this.formatTokenNumber(Math.round(max * ratio)) } }) }, chartPeakLabel(buckets, field, maximum, name) { if (!Array.isArray(buckets) || !buckets.length) return null let bestIndex = -1 let bestValue = 0 buckets.forEach((bucket, index) => { const value = Number(bucket && bucket[field] || 0) if (Number.isFinite(value) && value > bestValue) { bestValue = value bestIndex = index } }) if (bestIndex < 0 || bestValue <= 0) return null const count = Math.max(1, buckets.length - 1) const x = 62 + bestIndex * (718 / count) const y = 190 - (bestValue / Math.max(1, maximum)) * 145 return { key: field, x, y: Math.max(34, y - 12), text: name + ' ' + this.formatTokenNumber(bestValue) } }, chartLabelStyle(x, y) { return { left: (Number(x || 0) / 800 * 100).toFixed(3) + '%', top: (Number(y || 0) / 220 * 100).toFixed(3) + '%' } }, linePath(buckets, field, maximum) { const count = Math.max(1, buckets.length - 1) const points = buckets.map((bucket, index) => { const x = 62 + index * (718 / count) const y = 190 - (Number(bucket[field] || 0) / Math.max(1, maximum)) * 145 return { x, y } }) return this.smoothLinePath(points) }, smoothLinePath(points) { if (!Array.isArray(points) || !points.length) return '' const format = value => Number(value || 0).toFixed(1) const first = points[0] if (points.length === 1) { return 'M ' + format(first.x) + ' ' + format(first.y) } return points.slice(1).reduce((path, point, index) => { const previous = points[index] const controlOffset = Math.min(Math.abs(point.x - previous.x) * 0.42, 44) return path + ' C ' + format(previous.x + controlOffset) + ' ' + format(previous.y) + ' ' + format(point.x - controlOffset) + ' ' + format(point.y) + ' ' + format(point.x) + ' ' + format(point.y) }, 'M ' + format(first.x) + ' ' + format(first.y)) }, modelColor(index) { return ['#5d6b4d', '#8fbc8f', '#c8b89e', '#d4e4c1', '#3e4a32', '#a8b89a', '#b18f5e', '#7f8c78'][index % 8] }, analyticsRangeLabel() { if (this.analyticsRange === '7d') return '近 7 天' if (this.analyticsRange === '30d') return '近 30 天' return '全部历史' }, tokenEstimate(record) { const estimate = record && record.token_estimate ? record.token_estimate : {} return this.formatTokenNumber(estimate.total || 0) }, tabLabel(record) { const tabIndex = Number(record && record.tab_index || 0) if (tabIndex > 0) return 'Tab #' + tabIndex const tabId = String(record && record.tab_id || '').trim() return tabId ? tabId : '未绑定' } }, template: `
ACTIVITY
从一次请求开始,了解响应、用量与异常。
点击一条记录,查看输入输出与执行详情。
{{ query || statusFilter !== 'all' || !includeMultimodal ? '试试其他关键词,或清除筛选条件。' : '完成首个 API 请求后,可以在这里回看耗时、输入输出与异常。' }}
基于当前请求历史的真实时间分布
累计服务用量
{{ cumulativeTokens ? inputRatio + '% 的累计用量' : '暂无累计用量' }}
{{ cumulativeTokens ? outputRatio + '% 的累计用量' : '暂无累计用量' }}
当前样本 {{ formatNumber(analyticsSampleTotals.calls) }} 次
按本地时间统计当前保留历史中的输入与输出 Token
{{ analyticsRangeLabel() }} · {{ formatTokenNumber(analyticsSampleTotals.total) }} Token
按保留配置加载请求历史,已自动过滤超大 Base64 图片数据并进行智能输入输出统计。
默认展示最新 20 条,点击条目查看完整上下文。
按域名聚合统计成功率