fix(panel): restore missing i18n keys and localize en-US trend/CSV dates

- Add header.scopeAll and header.scopeAllShort in zh-CN and en-US and align StepTableWidget cost width estimation with formatUsd
- Format trend chart hover titles, x-axis tick tooltips, and CSV summary/trend rows per active locale instead of hardcoded Chinese date labels
- Add static t(...) key completeness and bilingual trend/CSV regression checks
This commit is contained in:
fish
2026-11-24 15:25:07 +09:00
parent 173e21c607
commit 4da6420ac1
9 changed files with 298 additions and 25 deletions
+79 -12
View File
@@ -1291,6 +1291,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'header.statusQuotaCached': '额度缓存', 'header.statusQuotaCached': '额度缓存',
'header.statusQuotaOffline': '额度离线', 'header.statusQuotaOffline': '额度离线',
'header.statusLive': '监控中', 'header.statusLive': '监控中',
'header.scopeAll': '全部代理',
'header.scopeAllShort': '全',
'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…', 'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…',
'select.searchPlaceholder': '输入关键词筛选…', 'select.searchPlaceholder': '输入关键词筛选…',
'select.noMatches': '没有匹配的选项', 'select.noMatches': '没有匹配的选项',
@@ -2192,6 +2194,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaCached': 'Quota Cached',
'header.statusQuotaOffline': 'Quota Offline', 'header.statusQuotaOffline': 'Quota Offline',
'header.statusLive': 'Monitoring', 'header.statusLive': 'Monitoring',
'header.scopeAll': 'All Agents',
'header.scopeAllShort': 'All',
'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…', 'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…',
'select.searchPlaceholder': 'Filter options…', 'select.searchPlaceholder': 'Filter options…',
'select.noMatches': 'No matching items', 'select.noMatches': 'No matching items',
@@ -4062,7 +4066,7 @@ return { defineComponent };
})(); })();
// --- src/core/formatters.js --- // --- src/core/formatters.js ---
const { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { const { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatTrendSlotFullLabel, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => {
/** /**
* @fileoverview Pure formatting utilities for speed metrics, token counts, * @fileoverview Pure formatting utilities for speed metrics, token counts,
* USD estimates, countdown timers, and custom datetime displays. * USD estimates, countdown timers, and custom datetime displays.
@@ -4074,6 +4078,14 @@ const EN_MONTH_SHORT = Object.freeze([
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
]); ]);
const ZH_WEEKDAY_SHORT = Object.freeze([
'周日', '周一', '周二', '周三', '周四', '周五', '周六',
]);
const EN_WEEKDAY_SHORT = Object.freeze([
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
]);
function formatMetric(value, unit = '') { function formatMetric(value, unit = '') {
if (!Number.isFinite(value)) return '—'; if (!Number.isFinite(value)) return '—';
const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1); const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1);
@@ -4163,6 +4175,59 @@ function formatDateSpanBadge(startMs, endMs) {
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
} }
function formatTrendSlotFullLabel(slot, { locale, showFullYear = false } = {}) {
const en =
typeof locale === 'string' && locale.trim()
? locale.trim().toLowerCase().startsWith('en')
: isEnglishLocale();
const sMs = Number(slot?.startMs);
if (Number.isFinite(sMs) && sMs > 0) {
const sd = new Date(sMs);
const pad2 = (n) => String(n).padStart(2, '0');
const rawFull = String(slot?.fullLabel || '');
const includeYear = Boolean(
showFullYear || /^\d{4}年/.test(rawFull) || sd.getFullYear() !== new Date().getFullYear()
);
const gran = String(slot?.granularity || '').toLowerCase();
const isSubDay =
gran === 'minute' ||
gran === 'hour' ||
(!gran && Number(slot?.endMs) > sMs && Number(slot.endMs) - sMs <= 3600_000 * 2);
if (isSubDay) {
const eMs = Number(slot?.endMs);
const ed = Number.isFinite(eMs) && eMs > 0 ? new Date(eMs) : new Date(sMs + 3600_000);
const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`;
const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`;
if (en) {
const mon = EN_MONTH_SHORT[sd.getMonth()] || '';
return includeYear
? `${mon} ${sd.getDate()}, ${sd.getFullYear()}, ${hh} - ${endHh}`
: `${mon} ${sd.getDate()}, ${hh} - ${endHh}`;
}
const yearPrefix = includeYear ? `${sd.getFullYear()}年` : '';
return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`;
}
if (en) {
const mon = EN_MONTH_SHORT[sd.getMonth()] || '';
const wday = EN_WEEKDAY_SHORT[sd.getDay()] || '';
return includeYear
? `${mon} ${sd.getDate()}, ${sd.getFullYear()} (${wday})`
: `${mon} ${sd.getDate()} (${wday})`;
}
const yearPrefix = includeYear ? `${sd.getFullYear()}年` : '';
return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${ZH_WEEKDAY_SHORT[sd.getDay()] || ''})`;
}
const rawFull = String(slot?.fullLabel || '').trim();
const rawShort = String(slot?.label || '').trim();
if (en && rawFull && /[\u4e00-\u9fff]/.test(rawFull)) {
return rawShort || rawFull;
}
return rawFull || rawShort;
}
function formatUsd(amount, { precise = false } = {}) { function formatUsd(amount, { precise = false } = {}) {
if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending'); if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending');
const val = Number(amount || 0); const val = Number(amount || 0);
@@ -5428,7 +5493,7 @@ function buildDeterministicModelColorMap(models = []) {
return colorMap; return colorMap;
} }
return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatTrendSlotFullLabel, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap };
})(); })();
// --- src/core/stepInspector.js --- // --- src/core/stepInspector.js ---
@@ -6754,8 +6819,10 @@ const { escapeCsvCell, sanitizeExportFilename, buildConsumptionExportBaseName, b
const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/; const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/;
const RANGE_LABELS_ZH = Object.freeze({ const RANGE_LABELS_ZH = Object.freeze({
'5h': '近5小时',
today: '今日', today: '今日',
'24h': '近24小时', '24h': '近24小时',
week: '本周',
'7d': '近7天', '7d': '近7天',
'14d': '近14天', '14d': '近14天',
'30d': '近30天', '30d': '近30天',
@@ -6765,8 +6832,10 @@ const RANGE_LABELS_ZH = Object.freeze({
}); });
const RANGE_LABELS_EN = Object.freeze({ const RANGE_LABELS_EN = Object.freeze({
'5h': 'Last 5 Hours',
today: 'Today', today: 'Today',
'24h': 'Last 24 Hours', '24h': 'Last 24 Hours',
week: 'This Week',
'7d': 'Last 7 Days', '7d': 'Last 7 Days',
'14d': 'Last 14 Days', '14d': 'Last 14 Days',
'30d': 'Last 30 Days', '30d': 'Last 30 Days',
@@ -7567,8 +7636,10 @@ function buildStepsMarkdownReport(
function buildConsumptionCsv( function buildConsumptionCsv(
consumption, consumption,
modelBreakdown = [], modelBreakdown = [],
{ displaySettings = {}, includeBom = true } = {} { displaySettings = {}, includeBom = true, locale } = {}
) { ) {
const en = resolveExportEnglish(locale);
const effectiveLocale = en ? 'en-US' : 'zh-CN';
const cons = consumption || {}; const cons = consumption || {};
const acc = cons.account || {}; const acc = cons.account || {};
const range = cons.selectedRange || {}; const range = cons.selectedRange || {};
@@ -7594,7 +7665,7 @@ function buildConsumptionCsv(
]), ]),
csvRow([ csvRow([
'summary', 'summary',
range.label || range.key || 'all', resolveLocalizedRangeLabel(range, en),
Number(acc.calls || 0), Number(acc.calls || 0),
Number(acc.inputTokens || 0), Number(acc.inputTokens || 0),
Number(acc.cacheReadTokens || 0), Number(acc.cacheReadTokens || 0),
@@ -7662,7 +7733,7 @@ function buildConsumptionCsv(
rows.push( rows.push(
csvRow([ csvRow([
'trend', 'trend',
slot.fullLabel || slot.label || '', formatTrendSlotFullLabel(slot, { locale: effectiveLocale }) || slot.label || '',
Number(slot.calls || 0), Number(slot.calls || 0),
Number(slot.inputTokens || 0), Number(slot.inputTokens || 0),
Number(slot.cacheReadTokens || 0), Number(slot.cacheReadTokens || 0),
@@ -14342,7 +14413,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
const slotTok = safeSlotTokens(slot.tokens); const slotTok = safeSlotTokens(slot.tokens);
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
tooltipContent.update({ tooltipContent.update({
title: slot.fullLabel || slot.label || '--', title: formatTrendSlotFullLabel(slot) || slot.label || '--',
calls: slot.calls, calls: slot.calls,
totalTokens: slotTok, totalTokens: slotTok,
costText: formatUsd(slotCost, { costText: formatUsd(slotCost, {
@@ -15121,7 +15192,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
const tickEl = h('span', { const tickEl = h('span', {
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
text: slot.label || '', text: slot.label || '',
title: slot.fullLabel || slot.label || '', title: formatTrendSlotFullLabel(slot) || slot.label || '',
}); });
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
tickEl.onclick = () => { tickEl.onclick = () => {
@@ -22324,11 +22395,7 @@ function estTokenChars(val) {
} }
function estCostWidth(st) { function estCostWidth(st) {
const c = st?.costUsd; return estProportionalTextWidth(formatUsd(st?.costUsd, { precise: true }));
if (c == null || !Number.isFinite(Number(c))) {
return st?.isPricingPending ? estProportionalTextWidth(t('fmt.pricingPending')) : 1;
}
return estProportionalTextWidth(formatUsd(Number(c)));
} }
function estSegmentChars(seg, st) { function estSegmentChars(seg, st) {
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title> <title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795495980631"> <link rel="stylesheet" href="/styles.css?v=1795501504789">
<script src="/preload.js"></script> <script src="/preload.js"></script>
</head> </head>
<body> <body>
<div id="app-root"></div> <div id="app-root"></div>
<script src="/app.js?v=1795495980631"></script> <script src="/app.js?v=1795501504789"></script>
</body> </body>
</html> </html>
@@ -13,7 +13,11 @@ import {
patchStyleVar, patchStyleVar,
patchText, patchText,
} from '../../core/domPatch.js'; } from '../../core/domPatch.js';
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js'; import {
formatTokensPrecise,
formatTrendSlotFullLabel,
formatUsd,
} from '../../core/formatters.js';
import { SVG_NS } from '../../icons/SvgIcon.js'; import { SVG_NS } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, t } from '../../i18n/index.js'; import { getEffectiveLocale, t } from '../../i18n/index.js';
import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js'; import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js';
@@ -738,7 +742,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
const slotTok = safeSlotTokens(slot.tokens); const slotTok = safeSlotTokens(slot.tokens);
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
tooltipContent.update({ tooltipContent.update({
title: slot.fullLabel || slot.label || '--', title: formatTrendSlotFullLabel(slot) || slot.label || '--',
calls: slot.calls, calls: slot.calls,
totalTokens: slotTok, totalTokens: slotTok,
costText: formatUsd(slotCost, { costText: formatUsd(slotCost, {
@@ -1517,7 +1521,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
const tickEl = h('span', { const tickEl = h('span', {
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
text: slot.label || '', text: slot.label || '',
title: slot.fullLabel || slot.label || '', title: formatTrendSlotFullLabel(slot) || slot.label || '',
}); });
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
tickEl.onclick = () => { tickEl.onclick = () => {
@@ -94,11 +94,7 @@ function estTokenChars(val) {
} }
function estCostWidth(st) { function estCostWidth(st) {
const c = st?.costUsd; return estProportionalTextWidth(formatUsd(st?.costUsd, { precise: true }));
if (c == null || !Number.isFinite(Number(c))) {
return st?.isPricingPending ? estProportionalTextWidth(t('fmt.pricingPending')) : 1;
}
return estProportionalTextWidth(formatUsd(Number(c)));
} }
function estSegmentChars(seg, st) { function estSegmentChars(seg, st) {
+61
View File
@@ -21,6 +21,14 @@ const EN_MONTH_SHORT = Object.freeze([
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
]); ]);
const ZH_WEEKDAY_SHORT = Object.freeze([
'周日', '周一', '周二', '周三', '周四', '周五', '周六',
]);
const EN_WEEKDAY_SHORT = Object.freeze([
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
]);
export function formatMetric(value, unit = '') { export function formatMetric(value, unit = '') {
if (!Number.isFinite(value)) return '—'; if (!Number.isFinite(value)) return '—';
const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1); const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1);
@@ -110,6 +118,59 @@ export function formatDateSpanBadge(startMs, endMs) {
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
} }
export function formatTrendSlotFullLabel(slot, { locale, showFullYear = false } = {}) {
const en =
typeof locale === 'string' && locale.trim()
? locale.trim().toLowerCase().startsWith('en')
: isEnglishLocale();
const sMs = Number(slot?.startMs);
if (Number.isFinite(sMs) && sMs > 0) {
const sd = new Date(sMs);
const pad2 = (n) => String(n).padStart(2, '0');
const rawFull = String(slot?.fullLabel || '');
const includeYear = Boolean(
showFullYear || /^\d{4}年/.test(rawFull) || sd.getFullYear() !== new Date().getFullYear()
);
const gran = String(slot?.granularity || '').toLowerCase();
const isSubDay =
gran === 'minute' ||
gran === 'hour' ||
(!gran && Number(slot?.endMs) > sMs && Number(slot.endMs) - sMs <= 3600_000 * 2);
if (isSubDay) {
const eMs = Number(slot?.endMs);
const ed = Number.isFinite(eMs) && eMs > 0 ? new Date(eMs) : new Date(sMs + 3600_000);
const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`;
const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`;
if (en) {
const mon = EN_MONTH_SHORT[sd.getMonth()] || '';
return includeYear
? `${mon} ${sd.getDate()}, ${sd.getFullYear()}, ${hh} - ${endHh}`
: `${mon} ${sd.getDate()}, ${hh} - ${endHh}`;
}
const yearPrefix = includeYear ? `${sd.getFullYear()}年` : '';
return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`;
}
if (en) {
const mon = EN_MONTH_SHORT[sd.getMonth()] || '';
const wday = EN_WEEKDAY_SHORT[sd.getDay()] || '';
return includeYear
? `${mon} ${sd.getDate()}, ${sd.getFullYear()} (${wday})`
: `${mon} ${sd.getDate()} (${wday})`;
}
const yearPrefix = includeYear ? `${sd.getFullYear()}年` : '';
return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${ZH_WEEKDAY_SHORT[sd.getDay()] || ''})`;
}
const rawFull = String(slot?.fullLabel || '').trim();
const rawShort = String(slot?.label || '').trim();
if (en && rawFull && /[\u4e00-\u9fff]/.test(rawFull)) {
return rawShort || rawFull;
}
return rawFull || rawShort;
}
export function formatUsd(amount, { precise = false } = {}) { export function formatUsd(amount, { precise = false } = {}) {
if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending'); if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending');
const val = Number(amount || 0); const val = Number(amount || 0);
+10 -3
View File
@@ -11,6 +11,7 @@ import {
formatPctNumber, formatPctNumber,
formatSpeedMetric, formatSpeedMetric,
formatTokensPrecise, formatTokensPrecise,
formatTrendSlotFullLabel,
formatUsd, formatUsd,
mergeModelsByDisplayName, mergeModelsByDisplayName,
resolveModelDisplayInfo, resolveModelDisplayInfo,
@@ -20,8 +21,10 @@ import { buildXlsxWorkbookBytes } from './xlsxBuilder.js';
const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/; const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/;
const RANGE_LABELS_ZH = Object.freeze({ const RANGE_LABELS_ZH = Object.freeze({
'5h': '近5小时',
today: '今日', today: '今日',
'24h': '近24小时', '24h': '近24小时',
week: '本周',
'7d': '近7天', '7d': '近7天',
'14d': '近14天', '14d': '近14天',
'30d': '近30天', '30d': '近30天',
@@ -31,8 +34,10 @@ const RANGE_LABELS_ZH = Object.freeze({
}); });
const RANGE_LABELS_EN = Object.freeze({ const RANGE_LABELS_EN = Object.freeze({
'5h': 'Last 5 Hours',
today: 'Today', today: 'Today',
'24h': 'Last 24 Hours', '24h': 'Last 24 Hours',
week: 'This Week',
'7d': 'Last 7 Days', '7d': 'Last 7 Days',
'14d': 'Last 14 Days', '14d': 'Last 14 Days',
'30d': 'Last 30 Days', '30d': 'Last 30 Days',
@@ -833,8 +838,10 @@ export function buildStepsMarkdownReport(
export function buildConsumptionCsv( export function buildConsumptionCsv(
consumption, consumption,
modelBreakdown = [], modelBreakdown = [],
{ displaySettings = {}, includeBom = true } = {} { displaySettings = {}, includeBom = true, locale } = {}
) { ) {
const en = resolveExportEnglish(locale);
const effectiveLocale = en ? 'en-US' : 'zh-CN';
const cons = consumption || {}; const cons = consumption || {};
const acc = cons.account || {}; const acc = cons.account || {};
const range = cons.selectedRange || {}; const range = cons.selectedRange || {};
@@ -860,7 +867,7 @@ export function buildConsumptionCsv(
]), ]),
csvRow([ csvRow([
'summary', 'summary',
range.label || range.key || 'all', resolveLocalizedRangeLabel(range, en),
Number(acc.calls || 0), Number(acc.calls || 0),
Number(acc.inputTokens || 0), Number(acc.inputTokens || 0),
Number(acc.cacheReadTokens || 0), Number(acc.cacheReadTokens || 0),
@@ -928,7 +935,7 @@ export function buildConsumptionCsv(
rows.push( rows.push(
csvRow([ csvRow([
'trend', 'trend',
slot.fullLabel || slot.label || '', formatTrendSlotFullLabel(slot, { locale: effectiveLocale }) || slot.label || '',
Number(slot.calls || 0), Number(slot.calls || 0),
Number(slot.inputTokens || 0), Number(slot.inputTokens || 0),
Number(slot.cacheReadTokens || 0), Number(slot.cacheReadTokens || 0),
+2
View File
@@ -32,6 +32,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaCached': 'Quota Cached',
'header.statusQuotaOffline': 'Quota Offline', 'header.statusQuotaOffline': 'Quota Offline',
'header.statusLive': 'Monitoring', 'header.statusLive': 'Monitoring',
'header.scopeAll': 'All Agents',
'header.scopeAllShort': 'All',
'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…', 'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…',
'select.searchPlaceholder': 'Filter options…', 'select.searchPlaceholder': 'Filter options…',
'select.noMatches': 'No matching items', 'select.noMatches': 'No matching items',
+2
View File
@@ -32,6 +32,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'header.statusQuotaCached': '额度缓存', 'header.statusQuotaCached': '额度缓存',
'header.statusQuotaOffline': '额度离线', 'header.statusQuotaOffline': '额度离线',
'header.statusLive': '监控中', 'header.statusLive': '监控中',
'header.scopeAll': '全部代理',
'header.scopeAllShort': '全',
'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…', 'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…',
'select.searchPlaceholder': '输入关键词筛选…', 'select.searchPlaceholder': '输入关键词筛选…',
'select.noMatches': '没有匹配的选项', 'select.noMatches': '没有匹配的选项',
@@ -1507,3 +1507,137 @@ test('5h quota cycle includes cycle-opening compaction CHECKPOINT and cross-boun
assert.equal(payload.consumption.account.calls, 4); assert.equal(payload.consumption.account.calls, 4);
assert.equal(payload.consumption.account.totalTokens, 491_000); assert.equal(payload.consumption.account.totalTokens, 491_000);
}); });
test('i18n static t(...) key completeness guard, scopeAll formatters, and localized en-US trend/CSV date labels', async () => {
const { I18N_MESSAGES_ZH_CN } = await import('../src/i18n/zh-CN.js');
const { I18N_MESSAGES_EN_US } = await import('../src/i18n/en-US.js');
const { setI18nLanguage } = await import('../src/i18n/index.js');
const {
formatAgentBadgeText,
formatAgentLabel,
formatTrendSlotFullLabel,
} = await import('../src/core/formatters.js');
const { buildStructurePreviewTelemetry } = await import('../src/components/settings/structurePreviewMock.js');
const { buildConsumptionCsv } = await import('../src/core/reportExporter.js');
const { createTrendAreaChart } = await import('../src/components/charts/TrendAreaChart.js');
const { createMockDom } = await import('./mock-dom.mjs');
// 1. Every static t('...') call across sidecars/panel/src/** resolves in both zh-CN and en-US
const srcRoot = fileURLToPath(new URL('../src', import.meta.url));
const walkJs = (dir) => {
const out = [];
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, ent.name);
if (ent.isDirectory()) out.push(...walkJs(p));
else if (ent.name.endsWith('.js') || ent.name.endsWith('.mjs')) out.push(p);
}
return out;
};
const zhKeys = new Set(Object.keys(I18N_MESSAGES_ZH_CN));
const enKeys = new Set(Object.keys(I18N_MESSAGES_EN_US));
assert.deepEqual([...zhKeys].filter((k) => !enKeys.has(k)), []);
assert.deepEqual([...enKeys].filter((k) => !zhKeys.has(k)), []);
const missingKeys = [];
for (const filePath of walkJs(srcRoot)) {
const srcText = fs.readFileSync(filePath, 'utf8');
const re = /(?<![.\w])t\(\s*(['"])([^'"]+)\1/g;
let m;
while ((m = re.exec(srcText)) !== null) {
const k = m[2];
if (!zhKeys.has(k) || !enKeys.has(k)) {
missingKeys.push(`${filePath}:${k}`);
}
}
}
assert.deepEqual(missingKeys, []);
// 2. agentKind === 'all' & structurePreviewMock never leak raw key strings
const prevDoc = globalThis.document;
const prevWin = globalThis.window;
const { document } = createMockDom();
globalThis.document = document;
globalThis.window = {
location: { origin: 'http://127.0.0.1:41234', href: 'http://127.0.0.1:41234/' },
addEventListener() {},
removeEventListener() {},
};
try {
setI18nLanguage('zh-CN');
assert.equal(formatAgentBadgeText({ agentKind: 'all' }), '全');
assert.equal(formatAgentLabel({ agentKind: 'all' }), '全部代理');
assert.equal(buildStructurePreviewTelemetry().activeConversation.aggregated.badgeText, '全');
setI18nLanguage('en-US');
assert.equal(formatAgentBadgeText({ agentKind: 'all' }), 'All');
assert.equal(formatAgentLabel({ agentKind: 'all' }), 'All Agents');
assert.equal(buildStructurePreviewTelemetry().activeConversation.aggregated.badgeText, 'All');
// 3. TrendAreaChart tooltip + X-axis tick title & CSV export localize dates in en-US without hardcoded Chinese
const localStart = new Date(new Date().getFullYear(), 10, 24, 10, 0, 0, 0).getTime();
const localEnd = localStart + 3600_000;
const hourlySlot = {
index: 0,
startMs: localStart,
endMs: localEnd,
granularity: 'hour',
label: '10:00',
fullLabel: '11月24日 10:00 - 11:00',
tokens: 12_000,
inputTokens: 8_000,
cacheReadTokens: 3_000,
outputTokens: 1_000,
costUsd: 0.05,
calls: 2,
};
const dailySlot = {
index: 0,
startMs: new Date(2025, 10, 24, 0, 0, 0, 0).getTime(),
endMs: new Date(2025, 10, 25, 0, 0, 0, 0).getTime(),
granularity: 'day',
label: '11/24',
fullLabel: '2025年11月24日 (周一)',
tokens: 25_000,
calls: 4,
costUsd: 0.12,
};
assert.equal(formatTrendSlotFullLabel(hourlySlot, { locale: 'en-US' }), 'Nov 24, 10:00 - 11:00');
assert.equal(formatTrendSlotFullLabel(hourlySlot, { locale: 'zh-CN' }), '11月24日 10:00 - 11:00');
assert.equal(formatTrendSlotFullLabel(dailySlot, { locale: 'en-US' }), 'Nov 24, 2025 (Mon)');
assert.equal(formatTrendSlotFullLabel(dailySlot, { locale: 'zh-CN' }), '2025年11月24日 (周一)');
const chart = createTrendAreaChart();
setI18nLanguage('en-US');
chart.update([hourlySlot, { ...hourlySlot, index: 1, startMs: localEnd, endMs: localEnd + 3600_000, label: '11:00', fullLabel: '11月24日 11:00 - 12:00' }]);
const enTicks = chart.el.querySelectorAll('.trend-x-tick');
assert.equal(enTicks[0].getAttribute('title'), 'Nov 24, 10:00 - 11:00');
enTicks[0].onclick?.();
assert.match(chart.el.textContent, /Nov 24, 10:00 - 11:00/);
assert.doesNotMatch(chart.el.textContent, /11月24日/);
setI18nLanguage('zh-CN');
chart.update([hourlySlot, { ...hourlySlot, index: 1, startMs: localEnd, endMs: localEnd + 3600_000, label: '11:00', fullLabel: '11月24日 11:00 - 12:00' }]);
const zhTicks = chart.el.querySelectorAll('.trend-x-tick');
assert.equal(zhTicks[0].getAttribute('title'), '11月24日 10:00 - 11:00');
chart.destroy();
const csvEn = buildConsumptionCsv(
{
selectedRange: { key: 'cycle', label: '当前周期' },
account: { calls: 2, inputTokens: 8000, cacheReadTokens: 3000, outputTokens: 1000, totalTokens: 12000, cacheHitPct: 27.3, costUsd: 0.05, savedCostUsd: 0.01 },
trendSeries: [hourlySlot],
},
[],
{ locale: 'en-US', includeBom: false }
);
assert.match(csvEn, /summary,Current Cycle,/);
assert.match(csvEn, /trend,"Nov 24, 10:00 - 11:00",/);
assert.doesNotMatch(csvEn, /[\u4e00-\u9fff]/);
} finally {
setI18nLanguage('zh-CN');
globalThis.document = prevDoc;
globalThis.window = prevWin;
}
});