diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index d6e10a8..45539d0 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2,7 +2,7 @@ 'use strict'; // --- shared/settings-normalization.mjs --- -const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi } = (() => { +const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -147,19 +147,19 @@ const MAX_POPOVER_WIDTH = 1080; const DEFAULT_POPOVER_WIDTH = 580; /** - * 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。 + * 归一化界面语言枚举(默认 `'auto'`,支持 `'zh-CN'` 及 `'en-US'`)。 * * @param {unknown} lang * @returns {'auto'|'zh-CN'|'en-US'} */ function normalizeLanguageSetting(lang) { const raw = String(lang ?? '').trim(); - if (!raw) return 'zh-CN'; + if (!raw) return 'auto'; const lower = raw.toLowerCase(); if (lower === 'auto' || lower === 'system') return 'auto'; if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; - return 'zh-CN'; + return 'auto'; } /** @@ -453,7 +453,24 @@ function normalizeStandalonePort(port) { } /** - * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * 归一化现代化 UI 开关(默认 `true`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +function normalizeModernUi(val) { + if (val === undefined || val === null || val === '') return true; + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + if (lower === 'false' || lower === '0' || lower === 'off') return false; + if (lower === 'true' || lower === '1' || lower === 'on') return true; + return true; + } + return Boolean(val); +} + +/** + * 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。 * * @param {unknown} val * @returns {boolean} @@ -465,7 +482,7 @@ function normalizeExperimentalModernUi(val) { } return Boolean(val); } -return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi }; +return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- @@ -1074,7 +1091,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusGenerating': '生成中{suffix}', 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', - 'header.statusLive': '实时 2s', + 'header.statusLive': '监控中', // Formatters & Common Labels 'fmt.pending': '待定', @@ -1488,10 +1505,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.gen.fontLg': '大', 'settings.gen.fontXl': '特大', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', - 'settings.gen.modernUi': '新 UI(实验性)', + 'settings.gen.modernUi': '现代化 UI', 'settings.gen.modernUiOff': '关闭', 'settings.gen.modernUiOn': '开启', - 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', + 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色及更流畅的现代过渡动画', 'settings.gen.updateTitle': '版本更新', 'settings.gen.updateMode': '更新方式', 'settings.gen.updateManual': '仅提示新版本,手动更新', @@ -1783,7 +1800,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusGenerating': 'Running{suffix}', 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', - 'header.statusLive': 'Live 2s', + 'header.statusLive': 'Monitoring', // Formatters & Common Labels 'fmt.pending': 'N/A', @@ -2197,7 +2214,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.gen.fontLg': 'Large', 'settings.gen.fontXl': 'XL', 'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact', - 'settings.gen.modernUi': 'Modern UI (Experimental)', + 'settings.gen.modernUi': 'Modern UI', 'settings.gen.modernUiOff': 'Off', 'settings.gen.modernUiOn': 'On', 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', @@ -2486,8 +2503,8 @@ function detectHostSystemLocale() { } const i18nStore = createReactiveStore({ - language: 'zh-CN', - locale: 'zh-CN', + language: 'auto', + locale: detectHostSystemLocale(), }); function setI18nLanguage(rawLang) { @@ -2528,7 +2545,7 @@ return { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nS })(); // --- src/core/appearance.js --- -const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot } = (() => { +const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, resolveSettingsModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot } = (() => { /** * @fileoverview Theme accent palette & panel font-scale appearance engine. * Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts, @@ -2570,13 +2587,27 @@ function normalizeClientFontScale(raw) { } function normalizeClientModernUi(raw) { + if (raw === undefined || raw === null || raw === '') return true; if (typeof raw === 'string') { const lower = raw.trim().toLowerCase(); - return lower === 'true' || lower === '1' || lower === 'on'; + if (lower === 'false' || lower === '0' || lower === 'off') return false; + if (lower === 'true' || lower === '1' || lower === 'on') return true; + return true; } return Boolean(raw); } +function resolveSettingsModernUi(settings) { + if (!settings || typeof settings !== 'object') return true; + if (settings.modernUi !== undefined) { + return normalizeClientModernUi(settings.modernUi); + } + if (settings.experimentalModernUi !== undefined) { + return normalizeClientModernUi(settings.experimentalModernUi); + } + return true; +} + /** * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. * @@ -2927,7 +2958,7 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = const colorScheme = detectHostColorScheme(targetEl); setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); - const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const isModernUi = resolveSettingsModernUi(settings); if (isModernUi) { setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); } else { @@ -2947,7 +2978,7 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = removeAttrIfPresent(targetEl, 'data-font-scale'); } } -return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot }; +return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, resolveSettingsModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot }; })(); // --- src/core/domPatch.js --- @@ -5253,10 +5284,10 @@ function isEquivalentTelemetry(prev, next) { const pSet = prev.settings; const nSet = next.settings; - if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; + if ((pSet?.language ?? 'auto') !== (nSet?.language ?? 'auto')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; - if (Boolean(pSet?.experimentalModernUi) !== Boolean(nSet?.experimentalModernUi)) return false; + if (resolveSettingsModernUi(pSet) !== resolveSettingsModernUi(nSet)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if ( (prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) || @@ -6420,7 +6451,11 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } - if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { + if (Object.prototype.hasOwnProperty.call(safePatch, 'modernUi')) { + const normModern = normalizeClientModernUi(safePatch.modernUi); + safePatch.modernUi = normModern; + safePatch.experimentalModernUi = normModern; + } else if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { @@ -15291,6 +15326,7 @@ function patchCapsuleOdometerText( if (!isModern || !/\d/.test(nextStr)) { if (prev?.active) { + el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); patchAttr(el, 'data-od-active', null); patchAttr(el, 'data-od-value', null); @@ -15307,6 +15343,7 @@ function patchCapsuleOdometerText( let nodes; if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) { + el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); nodes = new Map(); } else { @@ -15665,10 +15702,6 @@ const CapsuleBarWidget = defineComponent({ 'div', { className: 'preview-host-left is-composer', hidden: true }, [ - h('span', { className: 'preview-composer-chip' }, [ - h('span', { text: 'Auto' }), - createSvgIcon('chevron-down', { size: 10 }), - ]), h('span', { className: 'preview-composer-chip' }, [ h('span', { text: 'Carbon (High)' }), createSvgIcon('chevron-down', { size: 10 }), @@ -18890,9 +18923,9 @@ const { SettingsGeneralTab } = (() => { function getLanguageOptions() { return [ + { value: 'auto', label: t('settings.gen.langAuto') }, { value: 'zh-CN', label: t('settings.gen.langZh') }, { value: 'en-US', label: t('settings.gen.langEn') }, - { value: 'auto', label: t('settings.gen.langAuto') }, ]; } @@ -18907,8 +18940,8 @@ function getFontScaleOptions() { function getModernUiOptions() { return [ - { value: 'off', label: t('settings.gen.modernUiOff') }, { value: 'on', label: t('settings.gen.modernUiOn') }, + { value: 'off', label: t('settings.gen.modernUiOff') }, ]; } @@ -18936,10 +18969,10 @@ function formatCloudSyncTimeText(tsMs, updatedAt) { const SettingsGeneralTab = defineComponent({ name: 'SettingsGeneralTab', setup({ props, onCleanup }) { - let draftLanguage = 'zh-CN'; + let draftLanguage = 'auto'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; - let draftModernUi = false; + let draftModernUi = true; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; @@ -19081,10 +19114,10 @@ const SettingsGeneralTab = defineComponent({ const modernUiSwitch = SegmentedControl({ ariaLabel: t('settings.gen.modernUi'), - modelValue: 'off', + modelValue: 'on', options: getModernUiOptions(), onUpdateModelValue: async (val) => { - const nextModernUi = val === 'on'; + const nextModernUi = val !== 'off'; draftModernUi = nextModernUi; modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) { @@ -19094,6 +19127,7 @@ const SettingsGeneralTab = defineComponent({ ...(latestSettings || {}), themeAccent: draftThemeAccent, fontScale: draftFontScale, + modernUi: nextModernUi, experimentalModernUi: nextModernUi, }, { includeFontScale: true } @@ -19102,7 +19136,7 @@ const SettingsGeneralTab = defineComponent({ const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { - await saveSettingsPatch({ experimentalModernUi: nextModernUi }); + await saveSettingsPatch({ modernUi: nextModernUi }); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saved'), 1500); } @@ -19286,7 +19320,7 @@ const SettingsGeneralTab = defineComponent({ draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); - draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); + draftModernUi = resolveSettingsModernUi(settings); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin @@ -21032,7 +21066,7 @@ const SettingsOtherTab = defineComponent({ showMaintFeedback(t('settings.oth.resettingBtn'), 0); try { const res = await resetAllSettings(); - setI18nLanguage(res?.settings?.language || 'zh-CN'); + setI18nLanguage(res?.settings?.language || 'auto'); showMaintFeedback(t('settings.oth.resetAllDone'), 2800); } catch { showMaintFeedback(t('settings.saveFailed'), 2800); @@ -21704,6 +21738,22 @@ function getConsumptionTimeRangeOptions() { ]; } +function floorToStartOfMinuteMs(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(0, 0); + return d.getTime(); +} + +function ceilToEndOfMinuteMs(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(59, 999); + return d.getTime(); +} + const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -21711,6 +21761,7 @@ const ConsumptionView = defineComponent({ let draftStartMs = telemetryStore.getState().customStartMs; let draftEndMs = telemetryStore.getState().customEndMs; let hasUncommittedCustomDraft = false; + let hasCommittedCustomRange = false; const timeFilterSwitch = SegmentedControl({ ariaLabel: t('cons.rangeAria'), @@ -21719,6 +21770,19 @@ const ConsumptionView = defineComponent({ onUpdateModelValue: (nextRange) => { if (nextRange === 'custom') { const st = telemetryStore.getState(); + if (!hasCommittedCustomRange && st.selectedTimeRange !== 'custom') { + const nowMs = Date.now(); + draftStartMs = floorToStartOfMinuteMs(nowMs - 24 * 3600 * 1000); + draftEndMs = ceilToEndOfMinuteMs(nowMs); + hasUncommittedCustomDraft = false; + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + selectConsumptionTimeRange('custom', { + customStartMs: draftStartMs, + customEndMs: draftEndMs, + }); + return; + } draftStartMs = st.customStartMs; draftEndMs = st.customEndMs; hasUncommittedCustomDraft = false; @@ -21759,11 +21823,14 @@ const ConsumptionView = defineComponent({ onClick: () => { const sMs = Number(draftStartMs || 0); const eMs = Number(draftEndMs || 0); - const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; - const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + const rawMinMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; + const rawMaxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + const minMs = floorToStartOfMinuteMs(rawMinMs); + const maxMs = ceilToEndOfMinuteMs(rawMaxMs); draftStartMs = minMs; draftEndMs = maxMs; hasUncommittedCustomDraft = false; + hasCommittedCustomRange = true; startPicker.setValue(minMs); endPicker.setValue(maxMs); selectConsumptionTimeRange('custom', { @@ -24363,7 +24430,7 @@ const StepsDetailView = defineComponent({ st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, - experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), + experimentalModernUi: resolveSettingsModernUi(st.telemetry?.settings), }), (slice) => { latestSlice = slice; @@ -26265,7 +26332,7 @@ function mountWindowOverlay() { applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); const scaleKey = normalizeClientFontScale(settings?.fontScale); - const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const isModernUi = resolveSettingsModernUi(settings); const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { if (el.getAttribute?.('data-font-scale') !== scaleKey) { diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index b5c22df..bb233c0 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -30,6 +30,7 @@ import { lsRuntimeEndpoint, normalizeFullSettings, normalizeModelDisplayMode, + normalizeModernUi, normalizePluginUpdateMode, normalizeWindowMountMode, saveJson, @@ -333,9 +334,16 @@ export function executeSettingsAction(data) { ? 'upstream' : 'short' : normalizeModelDisplayMode(current.modelDisplayMode, current.showUpstreamModel); + const nextModernUi = + payload.modernUi !== undefined + ? normalizeModernUi(payload.modernUi) + : payload.experimentalModernUi !== undefined + ? normalizeModernUi(payload.experimentalModernUi) + : normalizeModernUi(current.modernUi); const updated = normalizeFullSettings({ ...current, ...payload, + modernUi: nextModernUi, modelContextWindows: current.modelContextWindows, weeklyTokenBudget: sanitizePositiveSettingNumber( payload.weeklyTokenBudget ?? payload.weeklyTokenLimit, diff --git a/sidecars/panel/backend/cli-statusline-config.mjs b/sidecars/panel/backend/cli-statusline-config.mjs index 3571cfd..d6fa436 100644 --- a/sidecars/panel/backend/cli-statusline-config.mjs +++ b/sidecars/panel/backend/cli-statusline-config.mjs @@ -749,11 +749,29 @@ function cliRenderSingleSlot(metricKey, slotCtx, { isEn = false, useColor = true * }} [options] * @returns {string} */ +function detectCliHostLanguageIsEn() { + const envLang = String( + process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '' + ).trim(); + if (envLang) { + return !envLang.toLowerCase().startsWith('zh'); + } + try { + const navLang = globalThis.navigator?.language; + if (navLang) { + return !String(navLang).toLowerCase().startsWith('zh'); + } + } catch { + // 忽略无 navigator 环境 + } + return false; +} + export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { const slots = normalizeTopbarCapsuleSlots(options.slots); const showMulti = options.showMultiSession !== false; const normLang = normalizeLanguageSetting(options.language); - const isEn = normLang === 'en-US'; + const isEn = normLang === 'auto' ? detectCliHostLanguageIsEn() : normLang === 'en-US'; const useColor = options.color !== false; const slotSet = new Set(slots); diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 8e8a430..f51465e 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -42,6 +42,7 @@ export { normalizeHoverModules, normalizeLanguageSetting, normalizeModelDisplayMode, + normalizeModernUi, normalizeOrchestratorIdMode, normalizeOverviewMetrics, normalizeOverviewModules, diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 45bf769..0ada7fa 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -1979,7 +1979,7 @@ export async function enumerateAndSyncConversations({ activeLiveActivityMemo.delete(cidLower); } - const entryAccountName = prev ? prev.accountName || '' : currentAccountName || ''; + const entryAccountName = prev?.accountName || currentAccountName || ''; const stepsWithOwners = attachStepAccountOwners( steps, prev, @@ -2085,9 +2085,8 @@ export async function enumerateAndSyncConversations({ Boolean(conv.parentConversationId) || Boolean(conv.rootConversationId && conv.rootConversationId !== cidLower); const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles); - const offlineAccountName = prev - ? prev.accountName || offlineFallback.accountName || '' - : offlineFallback.accountName || currentAccountName || ''; + const offlineAccountName = + prev?.accountName || offlineFallback.accountName || currentAccountName || ''; const offlineStepsWithOwners = attachStepAccountOwners( offlineFallback.steps, prev, diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 6500ce5..3942b69 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -31,6 +31,7 @@ import { normalizeHoverModules, normalizeLanguageSetting, normalizeModelDisplayMode, + normalizeModernUi, normalizeOrchestratorIdMode, normalizeOverviewMetrics, normalizeOverviewModules, @@ -73,6 +74,7 @@ export { normalizeHoverModules, normalizeLanguageSetting, normalizeModelDisplayMode, + normalizeModernUi, normalizeOrchestratorIdMode, normalizeOverviewMetrics, normalizeOverviewModules, @@ -107,10 +109,11 @@ export function normalizeModelContextWindows(value) { } export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ - language: 'zh-CN', + language: 'auto', themeAccent: 'host', fontScale: 'md', - experimentalModernUi: false, + modernUi: true, + experimentalModernUi: true, weeklyTokenBudget: 150000000, weeklyCostBudget: 100, weeklyLimitMode: 'official', @@ -173,11 +176,14 @@ export function normalizeFullSettings(rawInput) { safeRaw.modelDisplayMode, safeRaw.showUpstreamModel ); + const modernUi = + safeRaw.modernUi !== undefined ? normalizeModernUi(safeRaw.modernUi) : true; return { language: normalizeLanguageSetting(safeRaw.language), themeAccent: normalizeThemeAccent(safeRaw.themeAccent), fontScale: normalizeFontScale(safeRaw.fontScale), - experimentalModernUi: normalizeExperimentalModernUi(safeRaw.experimentalModernUi), + modernUi, + experimentalModernUi: modernUi, weeklyTokenBudget: schemaSanitizePositiveNum( safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit, DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 824f8b5..ad2a244 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -35,6 +35,29 @@ function normalizeOwnerAccount(val) { return typeof val === 'string' ? val.trim().toLowerCase() : ''; } +const COMPACTION_QUOTA_SETTLE_MAX_MS = 180_000; +const STEP_QUOTA_DURATION_CAP_SEC = 600; + +/** + * 解析单步用于官方配额周期窗口(`5h` / `weekly` / `cycle`)边界比对的结算时间戳: + * 服务端配额桶的 `resetTime` 锚定在周期内首笔请求完成扣费时刻(而非 `createdAt` 发起时刻), + * 使用完成时刻(无流式计时的自动压缩 `CHECKPOINT` 步按合理结算上限及下一步发起时刻封顶)避免漏计开启新周期的首步。 + */ +function resolveStepQuotaBillingMs(st, nextStep, nowMs) { + const tMs = Number(st?.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + if (!(tMs > 0) || tMs > nowMs) return tMs; + const durSec = Number(st?.totalDurationSec); + if (Number.isFinite(durSec) && durSec > 0) { + const endMs = tMs + Math.round(Math.min(durSec, STEP_QUOTA_DURATION_CAP_SEC) * 1000); + return Math.min(nowMs, endMs); + } + if (st?.isCompactionStep) { + const nextMs = Number(nextStep?.createdAtMs) > tMs ? Number(nextStep.createdAtMs) : Infinity; + return Math.min(nowMs, nextMs, tMs + COMPACTION_QUOTA_SETTLE_MAX_MS); + } + return tMs; +} + /** * 获取本地当日 00:00:00.000 的毫秒时间戳。 * @@ -900,13 +923,16 @@ function computeFamilySessionBuckets({ const cidLower = String(entry?.cascadeId || '').toLowerCase(); if (!cidLower || !familySet.has(cidLower)) continue; const entryOwner = normalizeOwnerAccount(entry.accountName); - for (const st of entry.steps || []) { + const entrySteps = entry.steps || []; + for (let sIdx = 0; sIdx < entrySteps.length; sIdx++) { + const st = entrySteps[sIdx]; if (!st || typeof st !== 'object') continue; + const nextSt = entrySteps[sIdx + 1] || null; const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; const includeInQuotaPools = normalizedQuotaAccount === null ? false - : normalizedQuotaAccount === '' + : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; const mInfo = resolveStepModel(st); @@ -923,6 +949,7 @@ function computeFamilySessionBuckets({ const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const unpriced = stepCost === null ? 1 : 0; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs); const savedCost = mInfo.pricing ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) : 0; @@ -951,39 +978,42 @@ function computeFamilySessionBuckets({ : null; let inCurrentCycle = false; - if (tMs > 0 && tMs <= nowMs) { + if (qMs > 0 && qMs <= nowMs) { if (isCustomWeeklyMode) { inCurrentCycle = tMs >= effectiveWeekStartMs; } else if (poolCycleBuckets.size > 0) { const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : cycleStartFallbackMs; - inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; + inCurrentCycle = includeInQuotaPools && qMs >= effCycleStartMs; } else { - inCurrentCycle = includeInQuotaPools && tMs >= cycleStartFallbackMs; + inCurrentCycle = includeInQuotaPools && qMs >= cycleStartFallbackMs; } } for (const k of presetKeys) { const w = presetWindows[k]; + const cmpMs = k === '5h' || k === 'week' ? qMs : tMs; const matchesPreset = k === 'all' ? true : k === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + : cmpMs > 0 && cmpMs >= w.startMs && cmpMs <= w.endMs; if (matchesPreset) { accumulateStepIntoBucket(sessionBuckets[k], stepUsage, entry.cascadeId); } } if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) { + const selCmpMs = + selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs; const inSelectedWindow = selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; + : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId); } @@ -1024,16 +1054,33 @@ function usageTimestampBoundary(dates, value, inclusive) { return start; } -function sameUsageWindows(previous, current, dates) { +function sortedQuotaBillingTimestamps(entries, nowMs) { + const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0)); + let count = 0; + for (const { steps } of entries) { + for (let i = 0; i < steps.length; i++) { + const qMs = resolveStepQuotaBillingMs(steps[i], steps[i + 1] || null, nowMs); + if (qMs > 0) dates[count++] = qMs; + } + } + return dates.subarray(0, count).sort(); +} + +function isQuotaAnchoredWindowKey(key) { + return key === '5h' || key === 'week' || key === 'cycle' || String(key || '').includes(':'); +} + +function sameUsageWindows(previous, current, dates, quotaDates = dates) { return previous.length === current.length && current.every((window, index) => { const before = previous[index]; + const refDates = isQuotaAnchoredWindowKey(window.key) ? quotaDates : dates; return before.key === window.key && before.label === window.label && (before.startMs === window.startMs || - usageTimestampBoundary(dates, before.startMs, false) === - usageTimestampBoundary(dates, window.startMs, false)) && + usageTimestampBoundary(refDates, before.startMs, false) === + usageTimestampBoundary(refDates, window.startMs, false)) && (before.endMs === window.endMs || - usageTimestampBoundary(dates, before.endMs, true) === - usageTimestampBoundary(dates, window.endMs, true)); + usageTimestampBoundary(refDates, before.endMs, true) === + usageTimestampBoundary(refDates, window.endMs, true)); }); } @@ -1157,8 +1204,12 @@ export function aggregateMultiWindowUsage({ if ( trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && trend.last === previous.trend.last && - sameUsageWindows(previous.windows, windows, - snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) + sameUsageWindows( + previous.windows, + windows, + (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)), + (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) + ) ) { snapshot.ranges.delete(selectedWindow.key); snapshot.ranges.set(selectedWindow.key, previous); @@ -1210,13 +1261,16 @@ export function aggregateMultiWindowUsage({ const srcKey = entry.appSource || 'standalone'; const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; - for (const st of entry.steps || []) { + const entrySteps = entry.steps || []; + for (let sIdx = 0; sIdx < entrySteps.length; sIdx++) { + const st = entrySteps[sIdx]; if (!st || typeof st !== 'object') continue; + const nextSt = entrySteps[sIdx + 1] || null; const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; const includeInQuotaPools = normalizedQuotaAccount === null ? false - : normalizedQuotaAccount === '' + : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; const mInfo = resolveStepModel(st); @@ -1233,6 +1287,7 @@ export function aggregateMultiWindowUsage({ const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const unpriced = stepCost === null ? 1 : 0; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; + const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs); const savedCost = mInfo.pricing ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) : 0; @@ -1270,37 +1325,38 @@ export function aggregateMultiWindowUsage({ hasDedicatedArgonPool ); - if (includeInQuotaPools && poolBucketEntry && tMs > 0 && tMs <= nowMs) { - if (tMs >= poolBucketEntry.start5hMs) { + if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) { + if (qMs >= poolBucketEntry.start5hMs) { accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); } - if (tMs >= poolBucketEntry.startWkMs) { + if (qMs >= poolBucketEntry.startWkMs) { accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); } } let inCurrentCycle = false; - if (tMs > 0 && tMs <= nowMs) { + if (qMs > 0 && qMs <= nowMs) { if (isCustomWeeklyMode) { inCurrentCycle = tMs >= presetWindows.week.startMs; } else if (poolCycleBuckets.size > 0) { const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : presetWindows.cycle.startMs; - inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs; + inCurrentCycle = includeInQuotaPools && qMs >= effCycleStartMs; } else { - inCurrentCycle = includeInQuotaPools && tMs >= presetWindows.cycle.startMs; + inCurrentCycle = includeInQuotaPools && qMs >= presetWindows.cycle.startMs; } } for (const k of presetKeys) { const w = presetWindows[k]; + const cmpMs = k === '5h' || k === 'week' ? qMs : tMs; const matchesPreset = k === 'all' ? true : k === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + : cmpMs > 0 && cmpMs >= w.startMs && cmpMs <= w.endMs; if (matchesPreset) { accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId); if (isCurrentConv) { @@ -1312,12 +1368,14 @@ export function aggregateMultiWindowUsage({ } } + const selCmpMs = + selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs; const inSelectedWindow = selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' ? inCurrentCycle - : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; + : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { if ( @@ -1626,7 +1684,8 @@ export function aggregateSelectedWindowUsage({ sameUsageWindows( [prevWin], [selectedWindow], - (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)) + (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)), + (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) ) ) { const res = candidate.result; @@ -1661,6 +1720,10 @@ export function aggregateSelectedWindowUsage({ } } + const maxSettlementSlackMs = Math.max( + COMPACTION_QUOTA_SETTLE_MAX_MS, + STEP_QUOTA_DURATION_CAP_SEC * 1000 + ); let minCutoffMs = 0; let maxCutoffMs = Infinity; let canPruneByTime = false; @@ -1674,9 +1737,14 @@ export function aggregateSelectedWindowUsage({ for (const entry of poolCycleBuckets.values()) { if (entry.startWkMs < minCutoffMs) minCutoffMs = entry.startWkMs; } + minCutoffMs = Math.max(0, minCutoffMs - maxSettlementSlackMs); } else { - minCutoffMs = selectedWindow.startMs; + minCutoffMs = Math.max(0, selectedWindow.startMs - maxSettlementSlackMs); } + } else if (selectedWindow.key === '5h' || selectedWindow.key === 'week') { + canPruneByTime = true; + minCutoffMs = Math.max(0, selectedWindow.startMs - maxSettlementSlackMs); + maxCutoffMs = selectedWindow.endMs; } else if (selectedWindow.key !== 'all') { canPruneByTime = true; minCutoffMs = selectedWindow.startMs; @@ -1706,10 +1774,24 @@ export function aggregateSelectedWindowUsage({ const srcKey = entry.appSource || 'standalone'; const srcName = USAGE_SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; - for (const st of steps) { + for (let sIdx = 0; sIdx < steps.length; sIdx++) { + const st = steps[sIdx]; if (!st || typeof st !== 'object') continue; + const nextSt = steps[sIdx + 1] || null; const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; - if (canPruneByTime && (tMs <= 0 || tMs < minCutoffMs || tMs > maxCutoffMs)) { + const qMs = resolveStepQuotaBillingMs(st, nextSt, nowMs); + const isQuotaWin = + selectedWindow.key === 'cycle' || + selectedWindow.key === '5h' || + selectedWindow.key === 'week'; + const effStepMs = isQuotaWin && !(selectedWindow.key === 'cycle' && isCustomWeeklyMode) ? qMs : tMs; + if (canPruneByTime && (effStepMs <= 0 || effStepMs < minCutoffMs || effStepMs > maxCutoffMs)) { + continue; + } + if ( + (selectedWindow.key === '5h' || selectedWindow.key === 'week') && + effStepMs < selectedWindow.startMs + ) { continue; } @@ -1720,7 +1802,7 @@ export function aggregateSelectedWindowUsage({ const includeInQuotaPools = normalizedQuotaAccount === null ? false - : normalizedQuotaAccount === '' + : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; let inCurrentCycle = false; @@ -1740,9 +1822,9 @@ export function aggregateSelectedWindowUsage({ const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : selectedWindow.startMs; - inCurrentCycle = tMs >= effCycleStartMs; + inCurrentCycle = qMs >= effCycleStartMs; } else { - inCurrentCycle = includeInQuotaPools && tMs >= selectedWindow.startMs; + inCurrentCycle = includeInQuotaPools && qMs >= selectedWindow.startMs; } if (!inCurrentCycle) continue; if ( diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index a9b704c..846e030 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@