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 @@ 用量监控 - +
- + diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs index 07fdfde..99d077f 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -142,19 +142,19 @@ export const MAX_POPOVER_WIDTH = 1080; export 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'} */ export 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'; } /** @@ -448,7 +448,24 @@ export function normalizeStandalonePort(port) { } /** - * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * 归一化现代化 UI 开关(默认 `true`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +export 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} diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index ff87b01..2abcbea 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -21,7 +21,7 @@ import { PANEL_SCALE_FACTORS, applyAppearanceToRoot, normalizeClientFontScale, - normalizeClientModernUi, + resolveSettingsModernUi, } from '../../core/appearance.js'; import { h, @@ -1468,7 +1468,7 @@ export 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/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index fe78488..e2eaf0d 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -98,6 +98,7 @@ export 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); @@ -114,6 +115,7 @@ export 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 { @@ -472,10 +474,6 @@ export 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 }), diff --git a/sidecars/panel/src/core/appearance.js b/sidecars/panel/src/core/appearance.js index 4957014..607e57e 100644 --- a/sidecars/panel/src/core/appearance.js +++ b/sidecars/panel/src/core/appearance.js @@ -39,13 +39,27 @@ export function normalizeClientFontScale(raw) { } export 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); } +export 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"]`. * @@ -396,7 +410,7 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t 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 { diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 822b2ac..8ce9b07 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -31,7 +31,7 @@ export 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', @@ -445,7 +445,7 @@ export 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', diff --git a/sidecars/panel/src/i18n/index.js b/sidecars/panel/src/i18n/index.js index b8088a7..c417110 100644 --- a/sidecars/panel/src/i18n/index.js +++ b/sidecars/panel/src/i18n/index.js @@ -29,8 +29,8 @@ export function detectHostSystemLocale() { } export const i18nStore = createReactiveStore({ - language: 'zh-CN', - locale: 'zh-CN', + language: 'auto', + locale: detectHostSystemLocale(), }); export function setI18nLanguage(rawLang) { diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index b2bcac0..5a40499 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -31,7 +31,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusGenerating': '生成中{suffix}', 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', - 'header.statusLive': '实时 2s', + 'header.statusLive': '监控中', // Formatters & Common Labels 'fmt.pending': '待定', @@ -445,10 +445,10 @@ export 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': '仅提示新版本,手动更新', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index e050d08..af21d05 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -23,6 +23,7 @@ import { normalizeClientFontScale, normalizeClientModernUi, normalizeClientThemeAccent, + resolveSettingsModernUi, } from '../core/appearance.js'; import { DEFAULT_HOVER_MODULES, @@ -478,10 +479,10 @@ export 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) || @@ -1645,7 +1646,11 @@ export 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')) { diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 3fee321..e3cbaf7 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -62,6 +62,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(); +} + export const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -69,6 +85,7 @@ export 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'), @@ -77,6 +94,19 @@ export 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; @@ -117,11 +147,14 @@ export 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', { diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index af2e2be..ae61f48 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -5,6 +5,7 @@ * - 总汇总视图提供会话线性走势图、多模型同图趋势拟合曲线与极简高密度模型总览卡片。 */ +import { resolveSettingsModernUi } from '../core/appearance.js'; import { defineComponent } from '../core/component.js'; import { h, @@ -1372,7 +1373,7 @@ export 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; diff --git a/sidecars/panel/src/views/settings/SettingsGeneralTab.js b/sidecars/panel/src/views/settings/SettingsGeneralTab.js index 2983f8c..ff88cda 100644 --- a/sidecars/panel/src/views/settings/SettingsGeneralTab.js +++ b/sidecars/panel/src/views/settings/SettingsGeneralTab.js @@ -8,8 +8,8 @@ import { defineComponent } from '../../core/component.js'; import { applyAppearanceToRoot, normalizeClientFontScale, - normalizeClientModernUi, normalizeClientThemeAccent, + resolveSettingsModernUi, } from '../../core/appearance.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; import { isWindowOverlayMode } from '../../core/httpClient.js'; @@ -27,9 +27,9 @@ import { SegmentedControl } from '../../components/ui/SegmentedControl.js'; 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') }, ]; } @@ -44,8 +44,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') }, ]; } @@ -73,10 +73,10 @@ function formatCloudSyncTimeText(tsMs, updatedAt) { export 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; @@ -218,10 +218,10 @@ export 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) { @@ -231,6 +231,7 @@ export const SettingsGeneralTab = defineComponent({ ...(latestSettings || {}), themeAccent: draftThemeAccent, fontScale: draftFontScale, + modernUi: nextModernUi, experimentalModernUi: nextModernUi, }, { includeFontScale: true } @@ -239,7 +240,7 @@ export 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); } @@ -423,7 +424,7 @@ export 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 diff --git a/sidecars/panel/src/views/settings/SettingsOtherTab.js b/sidecars/panel/src/views/settings/SettingsOtherTab.js index ca8c187..dbcbdc8 100644 --- a/sidecars/panel/src/views/settings/SettingsOtherTab.js +++ b/sidecars/panel/src/views/settings/SettingsOtherTab.js @@ -458,7 +458,7 @@ export 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); diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 1fde589..ee4f6cc 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -1054,12 +1054,24 @@ test('saving preferences sends the same legacy values normalized by the backend' }); test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => { - // 1. Default schema matches pre-refactor out-of-box UI 100% + // 1. Default schema matches v1.5.3 out-of-box UI (language='auto', modernUi=true) const hDefault = backendHarness({}); const def = hDefault.loadSettings(); - assert.equal(def.language, 'zh-CN'); + assert.equal(def.language, 'auto'); assert.equal(def.themeAccent, 'host'); assert.equal(def.fontScale, 'md'); + assert.equal(def.modernUi, true); + assert.equal(def.experimentalModernUi, true); + + // Upgrading from v1.5.2 settings.json (with experimentalModernUi: false and no modernUi key) enables modernUi=true + const hFrom152 = backendHarness({ settings: { language: 'zh-CN', experimentalModernUi: false } }); + const loadedFrom152 = hFrom152.loadSettings(); + assert.equal(loadedFrom152.modernUi, true); + assert.equal(loadedFrom152.experimentalModernUi, true); + const optOutRes = hFrom152.executeSettingsAction({ modernUi: false }); + assert.equal(optOutRes.ok, true); + assert.equal(optOutRes.updated.modernUi, false); + assert.equal(hFrom152.loadSettings().modernUi, false); assert.equal(def.pluginUpdateMode, 'manual'); assert.equal(def.windowMountMode, 'dual'); assert.equal(def.enableWindowOverlay, true); @@ -1147,7 +1159,8 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo // 6. executeResetSettingsAction restores full defaults cleanly const resetRes = hDefault.executeResetSettingsAction(); assert.equal(resetRes.ok, true); - assert.equal(resetRes.updated.language, 'zh-CN'); + assert.equal(resetRes.updated.language, 'auto'); + assert.equal(resetRes.updated.modernUi, true); assert.equal(resetRes.updated.themeAccent, 'host'); assert.equal(resetRes.updated.enableCliStatusLine, true); assert.equal(resetRes.updated.showStepTurnRail, false); diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index bca8187..62e5ee1 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1376,3 +1376,119 @@ test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveAc globalThis.window = prevWin; } }); + +test('5h quota cycle includes cycle-opening compaction CHECKPOINT and cross-boundary steps plus unattributed cold-boot cache entries', async () => { + const nowMs = Date.now(); + const start5hMs = nowMs - 2 * 3600_000; + const reset5hIso = new Date(start5hMs + 5 * 3600_000).toISOString(); + const resetWkIso = new Date(nowMs + 5 * 24 * 3600_000).toISOString(); + + // 1. Old step from expired previous cycle (2.5h before start5hMs) -> must be excluded from 5h + const oldCycleStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(start5hMs - 2.5 * 3600_000).toISOString(), + completedAt: new Date(start5hMs - 2.5 * 3600_000 + 8_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '100000', + cacheReadTokens: '0', + outputTokens: '5000', + }, + }, + }; + + // 2. Untimed /compact CHECKPOINT started 70s BEFORE start5hMs that settled & opened the 5h bucket -> must be included! + const compactOpeningStep = { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: new Date(start5hMs - 70_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '300000', + cacheReadTokens: '0', + outputTokens: '4000', + }, + }, + }; + + // 3. Normal step after compaction inside 5h window + const postCompactStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 3 }, + createdAt: new Date(start5hMs + 120_000).toISOString(), + completedAt: new Date(start5hMs + 135_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '6000', + cacheReadTokens: '80000', + outputTokens: '2000', + }, + }, + }; + + // 4. Cold-boot cached conversation initially saved with accountName: '' before email loaded -> included for Alice, while Bob stays excluded + const coldBootStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(start5hMs - 40_000).toISOString(), + completedAt: new Date(start5hMs + 10_000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '10000', + cacheReadTokens: '0', + outputTokens: '1000', + }, + }, + }; + + const h = backendHarness({ + userStatus: { email: 'alice@example.com', userTier: { name: 'Google AI Ultra' } }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.929, resetTime: reset5hIso }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.395, resetTime: resetWkIso }, + ], + }, + ], + }, + cache: { + 'cold-boot-conv': { + accountName: '', + signature: 'v10-model-identity:cold', + steps: extractModelSteps([coldBootStep]), + }, + 'bob-conv': { + accountName: 'bob@example.com', + signature: 'v10-model-identity:bob', + steps: extractModelSteps([postCompactStep]), + }, + }, + summaries: { + 'main-conv': { stepCount: 3, lastModifiedTime: new Date(nowMs - 10_000).toISOString(), status: 'IDLE' }, + }, + trajectories: { + 'main-conv': { trajectory: { steps: [oldCycleStep, compactOpeningStep, postCompactStep] } }, + }, + }); + + const payload = await h.buildTelemetryPayloadInternal('main-conv', false, { range: '5h' }); + const geminiPool = payload.quotas.pools.find((p) => p.poolKey === 'Gemini'); + // Includes compactOpeningStep (304,000) + postCompactStep (88,000) + coldBootStep (11,000) = 403,000 tokens (3 calls) + assert.equal(geminiPool.cycle5h.calls, 3); + assert.equal(geminiPool.cycle5h.tokens, 403_000); + // Preset 5h account bucket includes Alice's 3 calls (403k) + Bob's 1 call (88k), excluding oldCycleStep (105k) + assert.equal(payload.consumption.account.calls, 4); + assert.equal(payload.consumption.account.totalTokens, 491_000); +}); diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index 08dad6b..c33c520 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -6,6 +6,7 @@ import { DEFAULT_SETTINGS_SCHEMA, normalizeExperimentalModernUi, normalizeFullSettings, + normalizeModernUi, } from '../backend/settings-schema.mjs'; import { applyAppearanceToRoot, @@ -38,27 +39,44 @@ import { StepsDetailView } from '../src/views/StepsDetailView.js'; import { SettingsGeneralTab } from '../src/views/settings/SettingsGeneralTab.js'; import { SettingsStructureTab } from '../src/views/settings/SettingsStructureTab.js'; -test('experimentalModernUi schema normalization defaults to false and coerces boolean/string values cleanly', () => { - assert.equal(DEFAULT_SETTINGS_SCHEMA.experimentalModernUi, false); +test('modernUi schema normalization defaults to true, upgrades 1.5.2 settings without modernUi key to true, and respects explicit false', () => { + assert.equal(DEFAULT_SETTINGS_SCHEMA.language, 'auto'); + assert.equal(DEFAULT_SETTINGS_SCHEMA.modernUi, true); + assert.equal(DEFAULT_SETTINGS_SCHEMA.experimentalModernUi, true); + assert.equal(normalizeModernUi(undefined), true); + assert.equal(normalizeModernUi(false), false); + assert.equal(normalizeModernUi('off'), false); + assert.equal(normalizeModernUi(true), true); + assert.equal(normalizeModernUi('true'), true); + assert.equal(normalizeModernUi('on'), true); assert.equal(normalizeExperimentalModernUi(undefined), false); - assert.equal(normalizeExperimentalModernUi(false), false); - assert.equal(normalizeExperimentalModernUi('off'), false); - assert.equal(normalizeExperimentalModernUi(true), true); - assert.equal(normalizeExperimentalModernUi('true'), true); - assert.equal(normalizeExperimentalModernUi('on'), true); + assert.equal(normalizeClientModernUi(undefined), true); assert.equal(normalizeClientModernUi('on'), true); assert.equal(normalizeClientModernUi(false), false); + assert.equal(normalizeClientModernUi('off'), false); - assert.equal(normalizeFullSettings({}).experimentalModernUi, false); - assert.equal(normalizeFullSettings({ experimentalModernUi: true }).experimentalModernUi, true); + // Fresh 1.5.3 install -> language='auto', modernUi=true + assert.equal(normalizeFullSettings({}).language, 'auto'); + assert.equal(normalizeFullSettings({}).modernUi, true); + assert.equal(normalizeFullSettings({}).experimentalModernUi, true); + + // 1.5.2 persisted settings.json (where experimentalModernUi: false was written by default, no modernUi key) -> upgrades to true! + const upgradedFrom152 = normalizeFullSettings({ experimentalModernUi: false }); + assert.equal(upgradedFrom152.modernUi, true); + assert.equal(upgradedFrom152.experimentalModernUi, true); + + // Explicit 1.5.3 user opt-out (`modernUi: false`) -> stays false! + const explicitOff153 = normalizeFullSettings({ modernUi: false, experimentalModernUi: true }); + assert.equal(explicitOff153.modernUi, false); + assert.equal(explicitOff153.experimentalModernUi, false); assert.equal( isEquivalentTelemetry( - { settings: { experimentalModernUi: false } }, - { settings: { experimentalModernUi: true } } + { settings: { modernUi: false } }, + { settings: { modernUi: true } } ), false, - 'isEquivalentTelemetry must detect experimentalModernUi changes' + 'isEquivalentTelemetry must detect modernUi changes' ); }); @@ -182,29 +200,41 @@ test('applyAppearanceToRoot and SettingsGeneralTab toggle data-modern-ui + data- assert.equal(document.documentElement.hasAttribute('data-modern-ui'), false); assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); - // 2. SettingsGeneralTab renders '新 UI(实验性)' switch and toggles data-modern-ui immediately + // 2. SettingsGeneralTab renders '现代化 UI' (开启 / 关闭) and Language (跟随系统 / 简体中文 / English) tab = SettingsGeneralTab({}); document.body.appendChild(tab.el); tab.refs.renderSettings({ - language: 'zh-CN', + language: 'auto', themeAccent: 'host', fontScale: 'md', + modernUi: false, experimentalModernUi: false, pluginUpdateMode: 'manual', }); - assert.match(tab.el.textContent, /新 UI(实验性)/); - const modernBtns = tab.refs.modernUiSwitch.el.querySelectorAll('.seg-btn'); - assert.equal(modernBtns.length, 2); - assert.equal(modernBtns[0].classList.contains('is-active'), true); + assert.match(tab.el.textContent, /现代化 UI/); + assert.doesNotMatch(tab.el.textContent, /实验性/); + const langSegBtns = tab.refs.languageSwitch.el.querySelectorAll('.seg-btn'); + assert.deepEqual( + langSegBtns.map((b) => b.textContent), + ['跟随系统', '简体中文', 'English'] + ); + assert.equal(langSegBtns[0].classList.contains('is-active'), true); - // Click '开启' (index 1) - modernBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + const modernBtns = tab.refs.modernUiSwitch.el.querySelectorAll('.seg-btn'); + assert.deepEqual( + modernBtns.map((b) => b.textContent), + ['开启', '关闭'] + ); + assert.equal(modernBtns[1].classList.contains('is-active'), true); + + // Click '开启' (index 0) + modernBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 15)); assert.equal(document.documentElement.getAttribute('data-modern-ui'), 'true'); assert.equal(savedPatches.length, 1); - assert.equal(savedPatches[0].experimentalModernUi, true); + assert.equal(savedPatches[0].modernUi, true); // 3. Built styles.css contains modern-ui borderless, sliding glider, and crisp pure-white light-mode rules const builtStyles = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 764bee0..fc39f29 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -1234,10 +1234,12 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro capsuleHost.shadowRoot.children.indexOf(capsuleBtn), 'Multi-session button sits immediately to the left of telemetry capsule' ); + assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true', 'Modern UI enabled out-of-the-box'); + const readCapVal = (el) => el.getAttribute('data-od-value') ?? el.textContent; assert.equal(multiBtn.querySelector('.svg-icon'), null, 'Multi-session button has zero SVG clutter'); assert.equal(multiBtn.classList.contains('is-running'), true); const multiLabelEl = multiBtn.querySelector('.wm-multi-label'); - assert.equal(multiLabelEl.textContent, '2 运行 · 1 子'); + assert.equal(readCapVal(multiLabelEl), '2 运行 · 1 子'); // Verify capsule reactive text (default order: 92.4 t/s without bolt SVG, 0.85s TTFT, 50% context) const defaultCapSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot'); @@ -1248,9 +1250,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(defaultCapSlots[2].getAttribute('data-metric'), 'context'); assert.equal(speedSegEl.children.length, 1, 'Speed segment has no lightning bolt SVG'); assert.equal(speedSegEl.querySelector('.svg-icon'), null); - assert.ok(speedSegEl.children[0].textContent.includes('92.4 t/s')); - assert.equal(defaultCapSlots[1].children[0].textContent, '0.85s'); - assert.equal(ctxPctEl.textContent, '50%'); + assert.ok(readCapVal(speedSegEl.children[0]).includes('92.4 t/s')); + assert.equal(readCapVal(defaultCapSlots[1].children[0]), '0.85s'); + assert.equal(readCapVal(ctxPctEl), '50%'); // Verify hovering left multi-session button opens .wm-multi-panel with live tasks, subagents, and recent sessions const multiPanelEl = portalHost.shadowRoot.querySelector('.wm-multi-panel'); @@ -1411,22 +1413,28 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const langBtns = generalSegControls[0].querySelectorAll('.seg-btn'); const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn'); const modernUiBtns = generalSegControls[2].querySelectorAll('.seg-btn'); - assert.equal(modernUiBtns.length, 2, 'Experimental Modern UI switch has 关闭 / 开启'); + assert.equal(modernUiBtns.length, 2, 'Modern UI switch has 开启 / 关闭'); + assert.equal(modernUiBtns[0].textContent, '开启'); + assert.equal(modernUiBtns[1].textContent, '关闭'); modernUiBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.modernUi, false); + assert.equal(mockSettings.experimentalModernUi, false); + assert.equal(portalHost.hasAttribute('data-modern-ui'), false); + assert.equal(popoverEl.hasAttribute('data-modern-ui'), false); + modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.modernUi, true); assert.equal(mockSettings.experimentalModernUi, true); assert.equal(portalHost.getAttribute('data-modern-ui'), 'true'); assert.equal(capsuleHost.getAttribute('data-modern-ui'), 'true'); assert.equal(popoverEl.getAttribute('data-modern-ui'), 'true'); - modernUiBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); - await new Promise((r) => setTimeout(r, 30)); - assert.equal(mockSettings.experimentalModernUi, false); - assert.equal(portalHost.hasAttribute('data-modern-ui'), false); - assert.equal(popoverEl.hasAttribute('data-modern-ui'), false); - assert.equal(langBtns.length, 3, 'Language switch has 简体中文 / English / 跟随宿主'); - assert.equal(langBtns[0].textContent, '简体中文'); - assert.equal(langBtns[0].classList.contains('is-active'), true, 'Default language is zh-CN'); + assert.equal(langBtns.length, 3, 'Language switch has 跟随系统 / 简体中文 / English'); + assert.equal(langBtns[0].textContent, '跟随系统'); + assert.equal(langBtns[1].textContent, '简体中文'); + assert.equal(langBtns[2].textContent, 'English'); + assert.equal(langBtns[1].classList.contains('is-active'), true, 'mockSettings language zh-CN selects index 1'); const generalSelects = generalPane.querySelectorAll('.custom-select'); assert.equal(generalSelects.length, 1, 'General tab has Update Mode select'); const updateModeSelectEl = generalSelects[0]; @@ -1466,8 +1474,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(portalHost.getAttribute('data-font-scale'), 'md'); assert.equal(popoverEl.getAttribute('data-font-scale'), 'md'); - // Live i18n switch: zh-CN -> en-US -> zh-CN without page reload - langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + // Live i18n switch: zh-CN -> en-US (index 2) -> auto (index 0) -> zh-CN (index 1) without page reload + langBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.language, 'en-US'); assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, 'Live'); @@ -1477,6 +1485,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(subNavBtns[2].textContent, 'Other'); langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.language, 'auto'); + langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.language, 'zh-CN'); assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, '实时监控'); assert.equal(subNavBtns[0].textContent, '常规'); @@ -1570,10 +1581,15 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.ok(previewCapsuleBar, 'Pane 0 mounts real CapsuleBarWidget preview'); assert.equal(previewCapsuleBar.querySelector('.preview-win-controls'), null, 'No redundant 3 window dots after capsule'); assert.equal(previewCapsuleSlots.length, 5, 'Preview CapsuleBarWidget mounts real 5 capsule slots'); - assert.equal(previewCapsuleSlots[0].children[0].textContent, '68.4 t/s', 'Preview slot 0 renders simulated speed'); + assert.equal(readCapVal(previewCapsuleSlots[0].children[0]), '68.4 t/s', 'Preview slot 0 renders simulated speed'); assert.equal(previewCapsuleSlots[0].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards'); - assert.equal(previewCapsuleSlots[1].children[0].textContent, '1.1s', 'Preview slot 1 renders simulated TTFT'); - assert.equal(previewCapsuleSlots[2].querySelector('.wm-ctx-pct').textContent, '56%', 'Preview slot 2 renders simulated context %'); + assert.equal(readCapVal(previewCapsuleSlots[1].children[0]), '1.1s', 'Preview slot 1 renders simulated TTFT'); + assert.equal(readCapVal(previewCapsuleSlots[2].querySelector('.wm-ctx-pct')), '56%', 'Preview slot 2 renders simulated context %'); + assert.deepEqual( + previewCapsuleBar.querySelectorAll('.preview-composer-chip').map((c) => c.textContent.trim()), + ['Carbon (High)'], + 'Composer preview bar shows only Carbon (High) chip without Auto' + ); const mountSelectEl = sec0.querySelectorAll('.custom-select')[0]; // Toggle windowMountSelect: dual -> composer -> sidebar -> dual (updating both live host & preview bar) @@ -1664,26 +1680,26 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro capRowSelects[0].querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h'); - assert.equal(capSlots[0].children[0].textContent, '余 44%'); + assert.equal(readCapVal(capSlots[0].children[0]), '余 44%'); assert.equal(previewCapsuleSlots[0].getAttribute('data-metric'), 'gemini_5h', 'Preview slot 0 mirrors gemini_5h'); - assert.equal(previewCapsuleSlots[0].children[0].textContent, '余 64%', 'Preview slot 0 renders simulated gemini_5h'); + assert.equal(readCapVal(previewCapsuleSlots[0].children[0]), '余 64%', 'Preview slot 0 renders simulated gemini_5h'); assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); - assert.equal(capSlots[1].children[0].textContent, '0.85s'); + assert.equal(readCapVal(capSlots[1].children[0]), '0.85s'); capRowSelects[2].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); capRowSelects[2].querySelectorAll('.select-option')[4].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(capSlots[2].getAttribute('data-metric'), 'cost'); assert.equal(capSlots[2].children.length, 1, 'Ring SVG detached cleanly when slot leaves context'); - assert.equal(capSlots[2].children[0].textContent, '$0.040'); + assert.equal(readCapVal(capSlots[2].children[0]), '$0.040'); assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']); // Move Row 1 up (left): each row has [up, down, remove], so Row 1 up is index 3 capSlotWrap.querySelectorAll('.slot-move-btn')[3].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']); - assert.equal(capSlots[0].children[0].textContent, '0.85s'); - assert.equal(capSlots[1].children[0].textContent, '余 44%'); + assert.equal(readCapVal(capSlots[0].children[0]), '0.85s'); + assert.equal(readCapVal(capSlots[1].children[0]), '余 44%'); // Mouse drag-and-drop reorder: drag Row 0 ('ttft') down below Row 2 ('cost') -> ['gemini_5h', 'cost', 'ttft'] const capSlotListEl = capSlotWrap.querySelector('.editable-slot-list'); @@ -1755,7 +1771,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); assert.equal(capSlots[2].getAttribute('data-metric'), 'context'); assert.equal(capSlots[2].children.length, 2, 'Ring SVG re-attached on Slot 2'); - assert.equal(capSlots[2].querySelector('.wm-ctx-pct').textContent, '50%'); + assert.equal(readCapVal(capSlots[2].querySelector('.wm-ctx-pct')), '50%'); // Pane 1 (3rd-level tab 'hover'): Hover Popup Modules (0..4) + real hover UI preview const sec1 = accordionSections[1]; @@ -2644,13 +2660,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(delivered, 1); await new Promise((r) => setTimeout(r, 20)); assert.equal( - defaultCapSlots[2].querySelector('.wm-ctx-pct').textContent, + readCapVal(defaultCapSlots[2].querySelector('.wm-ctx-pct')), '25%', 'CDP relay delivered live telemetry without HTTP' ); - assert.equal(defaultCapSlots[0].children[0].textContent, '121 t/s'); + assert.equal(readCapVal(defaultCapSlots[0].children[0]), '121 t/s'); assert.equal(defaultCapSlots[1].hasAttribute('hidden'), false, 'TTFT slot stays pre-reserved even when latestTtftSec is absent'); - assert.equal(defaultCapSlots[1].children[0].textContent, '--s'); + assert.equal(readCapVal(defaultCapSlots[1].children[0]), '--s'); assert.equal( hoverLegendGrid.children[0], firstLegendSlotBefore,