diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 7102bb2..583283a 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 } = (() => { +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 } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -451,7 +451,21 @@ function normalizeStandalonePort(port) { if (num >= 1024 && num <= 65535) return num; return 0; } -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 }; + +/** + * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +function normalizeExperimentalModernUi(val) { + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + 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 }; })(); // --- shared/telemetry-display-rules.mjs --- @@ -1171,9 +1185,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ // Context Window Widget 'ctx.followActive': '跟随活跃 ({badge})', 'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口', - 'ctx.expandMore': '+{count} 展开 ▾', + 'ctx.expandMore': '+{count} 展开', 'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊', - 'ctx.collapse': '收起 ▴', + 'ctx.collapse': '收起', 'ctx.collapseTitle': '折叠多余子代理胶囊', 'ctx.ch.assistant': '模型回复', 'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参', @@ -1225,14 +1239,15 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.doneWithSteps': '已完成 ({steps} 步)', 'live.waitingWithSteps': '待命中 ({steps} 步)', 'live.killedWithSteps': '已终止 ({steps} 步)', - 'live.subToggleRunning': '子代理 {run}/{total} {arrow}', - 'live.subToggleIdle': '子代理 ({total}) {arrow}', - 'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}', - 'live.swarmToggleIdle': '蜂群 ({total}) {arrow}', + 'live.subToggleRunning': '子代理 {run}/{total}', + 'live.subToggleIdle': '子代理 ({total})', + 'live.swarmToggleRunning': '蜂群 {run}/{total}', + 'live.swarmToggleIdle': '蜂群 ({total})', 'live.subCollapseTitle': '点击收起子代理列表', 'live.subExpandTitle': '点击展开查看子代理缩略状态', // Consumption View + 'cons.rangeCycle': '周期', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', @@ -1432,6 +1447,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.gen.fontLg': '大', 'settings.gen.fontXl': '特大', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', + 'settings.gen.modernUi': '新 UI(实验性)', + 'settings.gen.modernUiOff': '关闭', + 'settings.gen.modernUiOn': '开启', + 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', 'settings.gen.updateTitle': '版本更新', 'settings.gen.updateMode': '更新方式', 'settings.gen.updateManual': '仅提示新版本,手动更新', @@ -1837,9 +1856,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({ // Context Window Widget 'ctx.followActive': 'Follow Active ({badge})', 'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window', - 'ctx.expandMore': '+{count} More ▾', + 'ctx.expandMore': '+{count} More', 'ctx.expandMoreTitle': 'Expand all {count} subagent context pills', - 'ctx.collapse': 'Less ▴', + 'ctx.collapse': 'Less', 'ctx.collapseTitle': 'Collapse extra subagent pills', 'ctx.ch.assistant': 'Assistant', 'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments', @@ -1891,14 +1910,15 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.doneWithSteps': 'Done ({steps} steps)', 'live.waitingWithSteps': 'Waiting ({steps} steps)', 'live.killedWithSteps': 'Killed ({steps} steps)', - 'live.subToggleRunning': 'Subagents {run}/{total} {arrow}', - 'live.subToggleIdle': 'Subagents ({total}) {arrow}', - 'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}', - 'live.swarmToggleIdle': 'Swarm ({total}) {arrow}', + 'live.subToggleRunning': 'Subagents {run}/{total}', + 'live.subToggleIdle': 'Subagents ({total})', + 'live.swarmToggleRunning': 'Swarm {run}/{total}', + 'live.swarmToggleIdle': 'Swarm ({total})', 'live.subCollapseTitle': 'Collapse subagent list', 'live.subExpandTitle': 'Expand subagent activity list', // Consumption View + 'cons.rangeCycle': 'Cycle', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', @@ -2098,6 +2118,10 @@ 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.modernUiOff': 'Off', + 'settings.gen.modernUiOn': 'On', + 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', 'settings.gen.updateTitle': 'Updates & Pricing', 'settings.gen.updateMode': 'Update Policy', 'settings.gen.updateManual': 'Notify only, update manually', @@ -2425,7 +2449,7 @@ return { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nS })(); // --- src/core/appearance.js --- -const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot } = (() => { +const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, 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, @@ -2466,23 +2490,342 @@ function normalizeClientFontScale(raw) { return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md'; } +function normalizeClientModernUi(raw) { + if (typeof raw === 'string') { + const lower = raw.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(raw); +} + +/** + * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. + * + * @param {Node | null | undefined} el + * @returns {boolean} + */ +function isModernUiActiveForElement(el) { + let cur = el || null; + while (cur) { + if (typeof cur.getAttribute === 'function' && cur.getAttribute('data-modern-ui') === 'true') { + return true; + } + if (cur.parentNode) { + cur = cur.parentNode; + } else if (cur.host) { + cur = cur.host; + } else { + break; + } + } + if (typeof document !== 'undefined' && document.documentElement) { + return document.documentElement.getAttribute?.('data-modern-ui') === 'true'; + } + return false; +} + +const LIGHT_THEME_CLASSES = new Set([ + 'light', + 'vs-light', + 'vscode-light', + 'hc-light', + 'vscode-high-contrast-light', +]); + +const DARK_THEME_CLASSES = new Set([ + 'dark', + 'vs-dark', + 'vscode-dark', + 'hc-black', + 'vscode-high-contrast', +]); + +function hslToRgb(hDeg, sPct, lPct) { + const h = (((hDeg % 360) + 360) % 360) / 360; + const s = Math.max(0, Math.min(1, sPct / 100)); + const l = Math.max(0, Math.min(1, lPct / 100)); + if (s === 0) { + const v = l * 255; + return [v, v, v]; + } + const hue2rgb = (p, q, t) => { + let tt = t; + if (tt < 0) tt += 1; + if (tt > 1) tt -= 1; + if (tt < 1 / 6) return p + (q - p) * 6 * tt; + if (tt < 1 / 2) return q; + if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6; + return p; + }; + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + return [ + hue2rgb(p, q, h + 1 / 3) * 255, + hue2rgb(p, q, h) * 255, + hue2rgb(p, q, h - 1 / 3) * 255, + ]; +} + +function parseAlphaToken(rawAlpha) { + if (rawAlpha == null || rawAlpha === '') return 1; + const str = String(rawAlpha).trim(); + if (!str) return 1; + if (str.endsWith('%')) { + const pct = parseFloat(str); + return Number.isFinite(pct) ? pct / 100 : 1; + } + const num = parseFloat(str); + return Number.isFinite(num) ? num : 1; +} + +/** + * Parse `#hex`, `rgb()/rgba()`, or `hsl()/hsla()` into perceptual luminance `[0, 1]`. + * Returns `null` when transparent (`alpha <= 0.15`) or unparseable. + * + * @param {string | null | undefined} rawColor + * @returns {number | null} + */ +function parseCssColorLuminance(rawColor) { + const str = String(rawColor ?? '').trim().toLowerCase(); + if (!str || str === 'transparent' || str === 'none' || str === 'inherit' || str === 'initial') { + return null; + } + + if (str.startsWith('#')) { + const hex = str.slice(1); + let r = 0; + let g = 0; + let b = 0; + let a = 1; + if (hex.length === 3 || hex.length === 4) { + r = parseInt(hex[0] + hex[0], 16); + g = parseInt(hex[1] + hex[1], 16); + b = parseInt(hex[2] + hex[2], 16); + if (hex.length === 4) a = parseInt(hex[3] + hex[3], 16) / 255; + } else if (hex.length === 6 || hex.length === 8) { + r = parseInt(hex.slice(0, 2), 16); + g = parseInt(hex.slice(2, 4), 16); + b = parseInt(hex.slice(4, 6), 16); + if (hex.length === 8) a = parseInt(hex.slice(6, 8), 16) / 255; + } else { + return null; + } + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const rgbMatch = str.match(/^rgba?\(([^)]+)\)$/); + if (rgbMatch) { + const body = rgbMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const parseChan = (tok) => + tok.endsWith('%') ? (parseFloat(tok) / 100) * 255 : parseFloat(tok); + const r = parseChan(parts[0]); + const g = parseChan(parts[1]); + const b = parseChan(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const hslMatch = str.match(/^hsla?\(([^)]+)\)$/); + if (hslMatch) { + const body = hslMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const h = parseFloat(parts[0]); + const s = parseFloat(parts[1]); + const l = parseFloat(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l) || a <= 0.15) { + return null; + } + const [r, g, b] = hslToRgb(h, s, l); + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + return null; +} + +function readStyleProp(el, cs, prop) { + if (prop.startsWith('--')) { + const inlineVal = + typeof el?.style?.getPropertyValue === 'function' + ? el.style.getPropertyValue(prop) + : el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.getPropertyValue?.(prop); + return compVal ? String(compVal).trim() : ''; + } + const inlineVal = el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.[prop]; + return compVal ? String(compVal).trim() : ''; +} + +/** + * Detect whether the active host surface is `'light'` or `'dark'`. + * Inspects explicit Antigravity / VS Code theme classes & attributes first, + * then actual computed surface/text luminance, then `prefers-color-scheme`. + * + * @param {HTMLElement | null | undefined} [targetEl] + * @returns {'light' | 'dark'} + */ +function detectHostColorScheme(targetEl = null) { + const doc = typeof document !== 'undefined' ? document : null; + const win = typeof window !== 'undefined' ? window : null; + let workbenchEl = null; + try { + workbenchEl = + typeof doc?.querySelector === 'function' ? doc.querySelector('.monaco-workbench') : null; + } catch { + workbenchEl = null; + } + + const candidates = []; + for (const el of [doc?.body, doc?.documentElement, workbenchEl, targetEl]) { + if (el && !candidates.includes(el)) { + candidates.push(el); + } + } + + // 1. Explicit host theme attributes & class tokens (never read our own data-color-scheme) + for (const el of candidates) { + const vscodeKind = String(el.getAttribute?.('data-vscode-theme-kind') || '') + .trim() + .toLowerCase(); + if (vscodeKind) { + if (vscodeKind.includes('light')) return 'light'; + if (vscodeKind.includes('dark') || vscodeKind.includes('high-contrast')) return 'dark'; + } + const dataTheme = String( + el.getAttribute?.('data-theme') || el.getAttribute?.('data-color-mode') || '' + ) + .trim() + .toLowerCase(); + if (dataTheme === 'light' || dataTheme.endsWith('-light')) return 'light'; + if (dataTheme === 'dark' || dataTheme.endsWith('-dark')) return 'dark'; + + const rawCls = typeof el.className === 'string' ? el.className : ''; + if (rawCls) { + const tokens = rawCls.trim().toLowerCase().split(/\s+/); + for (const tok of tokens) { + if (LIGHT_THEME_CLASSES.has(tok)) return 'light'; + if (DARK_THEME_CLASSES.has(tok)) return 'dark'; + } + } + } + + // 2. Computed / inline surface background luminance + const bgTargets = []; + for (const el of [targetEl, doc?.body, doc?.documentElement, workbenchEl]) { + if (el && !bgTargets.includes(el)) { + bgTargets.push(el); + } + } + const bgProps = [ + '--background', + '--card', + '--vscode-sideBar-background', + '--vscode-editor-background', + 'backgroundColor', + ]; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of bgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum > 0.52 ? 'light' : 'dark'; + } + } + } + + // 3. Computed / inline foreground text luminance + const fgProps = ['--foreground', '--vscode-foreground', '--vscode-editor-foreground', 'color']; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of fgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum < 0.48 ? 'light' : 'dark'; + } + } + } + + // 4. OS media query fallback + try { + if (win?.matchMedia?.('(prefers-color-scheme: dark)')?.matches) { + return 'dark'; + } + } catch { + // ignore matchMedia errors + } + + return 'light'; +} + +function setAttrIfChanged(el, name, value) { + if (!el || typeof el.setAttribute !== 'function') return; + if (typeof el.getAttribute === 'function' && el.getAttribute(name) === value) return; + el.setAttribute(name, value); +} + +function removeAttrIfPresent(el, name) { + if (!el || typeof el.removeAttribute !== 'function') return; + if (typeof el.hasAttribute === 'function' && !el.hasAttribute(name)) return; + el.removeAttribute(name); +} + function setOrClearStyleVar(el, propName, value) { if (!el || !el.style) return; + const cur = + typeof el.style.getPropertyValue === 'function' + ? el.style.getPropertyValue(propName) + : el.style[propName] || ''; if (value) { + if (cur === value) return; if (typeof el.style.setProperty === 'function') { el.style.setProperty(propName, value); } else { el.style[propName] = value; } - } else if (typeof el.style.removeProperty === 'function') { - el.style.removeProperty(propName); - } else if (typeof el.style.setProperty === 'function') { - el.style.setProperty(propName, ''); + } else if (cur) { + if (typeof el.style.removeProperty === 'function') { + el.style.removeProperty(propName); + } else if (typeof el.style.setProperty === 'function') { + el.style.setProperty(propName, ''); + } else { + el.style[propName] = ''; + } } } /** - * Synchronize theme accent and (optionally) font scale tokens onto a root/host element. + * Synchronize theme accent, host color scheme polarity, and (optionally) font scale tokens + * onto a root/host element. * * @param {HTMLElement | null | undefined} targetEl * @param {object | null | undefined} settings @@ -2500,7 +2843,17 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = setOrClearStyleVar(targetEl, '--user-accent-primary', ''); setOrClearStyleVar(targetEl, '--user-accent-contrast', ''); } - targetEl.setAttribute?.('data-accent', preset.key); + setAttrIfChanged(targetEl, 'data-accent', preset.key); + + const colorScheme = detectHostColorScheme(targetEl); + setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); + + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + if (isModernUi) { + setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); + } else { + removeAttrIfPresent(targetEl, 'data-modern-ui'); + } if (includeFontScale) { const scaleKey = normalizeClientFontScale(settings?.fontScale); @@ -2508,16 +2861,14 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1; setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor)); setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor)); - targetEl.setAttribute?.('data-font-scale', scaleKey); + setAttrIfChanged(targetEl, 'data-font-scale', scaleKey); } else { setOrClearStyleVar(targetEl, '--ui-font-scale', ''); setOrClearStyleVar(targetEl, '--ui-panel-scale', ''); - if (typeof targetEl.removeAttribute === 'function') { - targetEl.removeAttribute('data-font-scale'); - } + removeAttrIfPresent(targetEl, 'data-font-scale'); } } -return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot }; +return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot }; })(); // --- src/core/domPatch.js --- @@ -2655,7 +3006,11 @@ const keyedListState = new WeakMap(); * Keyed incremental list reconciler. * Reuses existing DOM nodes by key and patches only changed items in-place. */ -function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) { +function patchKeyedList( + container, + items, + { keyFn = (_, i) => i, sigFn, createRow, updateRow, destroyRow } = {} +) { if (!container) return; let map = keyedListState.get(container); if (!map) { @@ -2699,6 +3054,7 @@ function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow } if (record.el.parentNode === container) { container.removeChild(record.el); } + destroyRow?.(record.refs, record.el); map.delete(oldKey); } } @@ -4069,6 +4425,7 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) 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 ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; @@ -4769,6 +5126,9 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { + safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode); } @@ -6203,54 +6563,215 @@ return { CustomScrollbar }; // --- src/components/ui/SegmentedControl.js --- const { SegmentedControl } = (() => { /** - * @fileoverview Micro-bezel (2px radius) SegmentedControl switcher - * for time-range filtering, context limit selection, and sub-table switching. + * @fileoverview Sliding SegmentedControl switcher with variable-width GPU glider. + * Measures active button geometry via ResizeObserver so both inline variable-width + * segments (e.g. "今天 / 1天 / ... / 自定义", "按步查看 (1520) / 总汇总") and equal-width + * grid bars ("常规 / 结构 / 其他") glide smoothly without stretching from 0px on tab reveal. */ const SegmentedControl = defineComponent({ name: 'SegmentedControl', - setup({ getProps, setProps, emit }) { - const rootEl = h('div', { - className: 'segmented', - role: 'group', - 'aria-label': getProps().ariaLabel || '分段切换器', - }); + setup({ getProps, setProps, emit, onCleanup }) { + const gliderEl = h('div', { className: 'seg-glider', 'aria-hidden': 'true' }); + const rootEl = h( + 'div', + { + className: 'segmented', + role: 'group', + 'aria-label': getProps().ariaLabel || '分段切换器', + }, + [gliderEl] + ); + + const btnMap = new Map(); + let orderedBtns = []; + let activeBtnEl = null; + let observedBtnEl = null; + let hasMeasuredVisible = false; + let readyRafId = 0; + + function cancelReadyRaf() { + if (readyRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(readyRafId); + } + readyRafId = 0; + } + + function syncGliderGeometry() { + if (!activeBtnEl) { + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const w = Number(activeBtnEl.offsetWidth || 0); + const h = Number(activeBtnEl.offsetHeight || 0); + if (!(w > 0 && h > 0)) { + // Hidden parent tab or headless Mock DOM: keep .seg-btn.is-active fallback background + // and snap cleanly on first real paint when tab becomes visible. + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const x = Number(activeBtnEl.offsetLeft || 0); + const y = Number(activeBtnEl.offsetTop || 0); + patchStyleVar(gliderEl, '--glider-x', `${x}px`); + patchStyleVar(gliderEl, '--glider-y', `${y}px`); + patchStyleVar(gliderEl, '--glider-w', `${w}px`); + patchStyleVar(gliderEl, '--glider-h', `${h}px`); + patchClasses(rootEl, { 'has-glider': true }); + + if (!hasMeasuredVisible) { + hasMeasuredVisible = true; + patchClasses(gliderEl, { 'is-ready': false }); + void gliderEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + cancelReadyRaf(); + readyRafId = window.requestAnimationFrame(() => { + readyRafId = 0; + if (hasMeasuredVisible) { + patchClasses(gliderEl, { 'is-ready': true }); + } + }); + } else { + patchClasses(gliderEl, { 'is-ready': true }); + } + } + } + + let resizeObs = null; + if (typeof ResizeObserver === 'function') { + resizeObs = new ResizeObserver(() => { + syncGliderGeometry(); + }); + resizeObs.observe(rootEl); + } + + function updateObservedActiveButton(nextActiveBtn) { + if (!resizeObs || observedBtnEl === nextActiveBtn) return; + if (observedBtnEl) { + try { + resizeObs.unobserve(observedBtnEl); + } catch { + // ignore + } + } + observedBtnEl = nextActiveBtn || null; + if (observedBtnEl) { + try { + resizeObs.observe(observedBtnEl); + } catch { + // ignore + } + } + } + + function selectValue(nextVal) { + if (getProps().modelValue !== nextVal) { + setProps({ modelValue: nextVal }); + emit('update:modelValue', nextVal); + } + } function syncSegments() { - const { options = [], modelValue } = getProps(); - patchKeyedList(rootEl, options, { - keyFn: (opt) => opt.value, - sigFn: (opt) => `${opt.value}::${opt.label}::${opt.value === modelValue}`, - createRow: (opt) => { - const btn = h('button', { + const { options = [], modelValue, ariaLabel } = getProps(); + if (ariaLabel) { + patchAttr(rootEl, 'aria-label', ariaLabel); + } + + const validKeys = new Set(options.map((opt) => String(opt.value))); + for (const [key, btn] of btnMap.entries()) { + if (!validKeys.has(key)) { + if (btn.parentNode === rootEl) { + rootEl.removeChild(btn); + } + btnMap.delete(key); + } + } + + orderedBtns = []; + let nextActiveBtn = null; + + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + const key = String(opt.value); + let btn = btnMap.get(key); + if (!btn) { + btn = h('button', { type: 'button', className: 'seg-btn', onClick: (e) => { e.stopPropagation(); - if (getProps().modelValue !== opt.value) { - setProps({ modelValue: opt.value }); - emit('update:modelValue', opt.value); + selectValue(opt.value); + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curOpts = getProps().options || []; + if (!curOpts.length) return; + const curIdx = Math.max( + 0, + curOpts.findIndex((o) => String(o.value) === key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = (curIdx + delta + curOpts.length) % curOpts.length; + const targetOpt = curOpts[nextIdx]; + if (targetOpt) { + selectValue(targetOpt.value); + btnMap.get(String(targetOpt.value))?.focus?.(); + } } }, }); - return { el: btn, refs: {} }; - }, - updateRow: (_refs, opt, _idx, el) => { - const active = opt.value === modelValue; - patchText(el, opt.label); - patchClasses(el, { 'is-active': active }); - patchAttr(el, 'aria-pressed', active ? 'true' : 'false'); - patchAttr(el, 'data-seg-value', opt.value); - }, - }); + btnMap.set(key, btn); + } + + const active = opt.value === modelValue; + patchText(btn, opt.label); + patchClasses(btn, { 'is-active': active }); + patchAttr(btn, 'aria-pressed', active ? 'true' : 'false'); + patchAttr(btn, 'data-seg-value', opt.value); + orderedBtns.push(btn); + if (active) { + nextActiveBtn = btn; + } + } + + // Ensure gliderEl remains index 0 and buttons follow in exact option order + if (rootEl.firstChild !== gliderEl) { + rootEl.insertBefore(gliderEl, rootEl.firstChild); + } + for (let i = 0; i < orderedBtns.length; i++) { + const targetNode = orderedBtns[i]; + const currentAtSlot = rootEl.children[i + 1] || null; + if (currentAtSlot !== targetNode) { + rootEl.insertBefore(targetNode, currentAtSlot); + } + } + + activeBtnEl = nextActiveBtn || orderedBtns[0] || null; + updateObservedActiveButton(activeBtnEl); + syncGliderGeometry(); } syncSegments(); + onCleanup(() => { + cancelReadyRaf(); + resizeObs?.disconnect?.(); + resizeObs = null; + observedBtnEl = null; + }); + return { el: rootEl, - refs: {}, + refs: { gliderEl, refreshGlider: syncGliderGeometry }, onPropsChange: syncSegments, getValue: () => getProps().modelValue, }; @@ -6813,6 +7334,34 @@ function createTrendAreaChart() { let hoveredIdx = -1; let hoveredCellEl = null; let lastRenderSig = ''; + let tipTrackRaf = 0; + + function cancelTipTrackRaf() { + if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(tipTrackRaf); + } + tipTrackRaf = 0; + } + + function armTooltipTracking(wasHidden) { + if (!wasHidden) return; + patchClasses(tooltipEl, { 'is-tracking': false }); + patchClasses(hoverDot, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + cancelTipTrackRaf(); + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + tipTrackRaf = window.requestAnimationFrame(() => { + tipTrackRaf = 0; + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + } function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); @@ -6868,6 +7417,7 @@ function createTrendAreaChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const slot = currentSlots[idx]; const pt = currentPts[idx]; @@ -6880,19 +7430,31 @@ function createTrendAreaChart() { patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + const isLineLow = pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2); patchAttr(peakPill, 'hidden', true); patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, - 'is-line-low': pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2), + 'is-line-low': isLineLow, }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); + let tipY = 0; + if (isLineLow) { + const wrapH = Number(chartWrap.offsetHeight || 0); + const tipH = Number(tooltipEl.offsetHeight || 0); + if (wrapH > 0 && tipH > 0) { + tipY = Math.max(0, wrapH - tipH - 22); + } + } + const rawPct = (pt.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', `${Math.round(tipY)}px`); + armTooltipTracking(wasHidden); for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -6920,6 +7482,7 @@ function createTrendAreaChart() { const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); + const wasHidden = tooltipEl.hasAttribute('hidden'); // 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪 patchClasses(tooltipEl, { 'is-hm-bottom': row <= 3, @@ -6946,14 +7509,23 @@ function createTrendAreaChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + armTooltipTracking(wasHidden); } function clearHover() { + cancelTipTrackRaf(); hoveredIdx = -1; patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false }); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': false, + 'is-tracking': false, + }); + patchClasses(hoverDot, { 'is-tracking': false }); if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } @@ -7165,6 +7737,7 @@ function createTrendAreaChart() { } function destroy() { + cancelTipTrackRaf(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { @@ -8221,6 +8794,7 @@ function createSessionLineChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const pt = currentPoints[idx]; patchAttr(hoverLine, 'hidden', false); @@ -8251,6 +8825,20 @@ function createSessionLineChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -8262,6 +8850,7 @@ function createSessionLineChart() { patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); if (currentPoints.some((p) => p.valid)) { patchAttr(peakPill, 'hidden', false); } @@ -9015,6 +9604,7 @@ function createModelFitChart() { patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + const wasHidden = tooltipEl.hasAttribute('hidden'); patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); @@ -9050,6 +9640,20 @@ function createModelFitChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } } function clearHover() { @@ -9058,6 +9662,7 @@ function createModelFitChart() { patchAttr(hoverFitDot, 'hidden', true); patchAttr(hoverRawDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); } plotStage.addEventListener('mousemove', (e) => { @@ -10433,8 +11038,8 @@ const CTX_ASCII_CHAR_PX = 6.1; const CTX_PILL_GAP_PX = 4; const CTX_DEFAULT_BAR_WIDTH_PX = 310; -function estimateCtxPillWidth(text) { - let w = CTX_PILL_BASE_PAD_PX; +function estimateCtxPillWidth(text, withChevron = false) { + let w = CTX_PILL_BASE_PAD_PX + (withChevron ? 14 : 0); for (const ch of String(text || '')) { w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX; } @@ -10647,9 +11252,30 @@ const ContextWindowWidget = defineComponent({ let latestData = null; let ctxPillsExpanded = false; + let isCollapsingCtxPills = false; + let ctxCollapseTimer = null; let lastCascadeId = ''; let cachedBarWidth = 0; + function clearCtxExpandAnim() { + if (ctxCollapseTimer) { + clearTimeout(ctxCollapseTimer); + ctxCollapseTimer = null; + } + isCollapsingCtxPills = false; + ctxInspectorBar.ontransitionend = null; + ctxInspectorBar.style.height = ''; + ctxInspectorBar.style.overflow = ''; + ctxInspectorBar.style.transition = ''; + for (const child of ctxPillGroup.children) { + child.onanimationend = null; + patchClasses(child, { + 'is-pill-entering': false, + 'is-pill-collapsing': false, + }); + } + } + function update({ data } = {}) { latestData = data || null; const curLocale = getEffectiveLocale(); @@ -10680,6 +11306,7 @@ const ContextWindowWidget = defineComponent({ const currentCascadeId = data.activeConversation?.cascadeId || ''; if (currentCascadeId && currentCascadeId !== lastCascadeId) { if (lastCascadeId) { + clearCtxExpandAnim(); ctxPillsExpanded = false; } lastCascadeId = currentCascadeId; @@ -10711,7 +11338,10 @@ const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); - if (hasSubagents && ctxAgent) { + if (!hasSubagents && isCollapsingCtxPills) { + clearCtxExpandAnim(); + } + if (hasSubagents && ctxAgent && !isCollapsingCtxPills) { const activeBadgeText = formatAgentBadgeText({ agentKind: aggregated?.activeAgentKind || @@ -10758,7 +11388,7 @@ const ContextWindowWidget = defineComponent({ if (needsCollapse && !ctxPillsExpanded) { const toggleSample = t('ctx.expandMore', { count: allAgentPills.length }); - const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample); + const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample, true); let usedW = firstPillWidth; let fitCount = 0; for (let i = 0; i < allAgentPills.length; i += 1) { @@ -10789,6 +11419,7 @@ const ContextWindowWidget = defineComponent({ title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }), isActive: false, isMoreToggle: true, + isExpanded: false, mode: 'toggle-expand', }); } else { @@ -10800,6 +11431,7 @@ const ContextWindowWidget = defineComponent({ title: t('ctx.collapseTitle'), isActive: false, isMoreToggle: true, + isExpanded: true, mode: 'toggle-expand', }); } @@ -10808,22 +11440,117 @@ const ContextWindowWidget = defineComponent({ patchKeyedList(ctxPillGroup, pillItems, { keyFn: (item) => item.key, sigFn: (item) => - `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`, + `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${Boolean(item.isExpanded)}:${item.mode}:${item.title}`, createRow: () => { - const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }); - return { el: btn, refs: { btn } }; + const labelSpan = h('span', { className: 'ctx-pill-label' }); + const chevronEl = createSvgIcon('chevron-down', { + size: 11, + className: 'ctx-toggle-chevron', + }); + patchAttr(chevronEl, 'hidden', true); + const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }, [ + labelSpan, + chevronEl, + ]); + return { el: btn, refs: { btn, labelSpan, chevronEl } }; }, updateRow: (refs, item) => { - patchText(refs.btn, item.label); + patchText(refs.labelSpan, item.label); + patchAttr(refs.chevronEl, 'hidden', !item.isMoreToggle); patchAttr(refs.btn, 'title', item.title); + patchAttr(refs.btn, 'data-pill-key', item.key); patchClasses(refs.btn, { 'is-active': item.isActive, 'is-more-toggle': Boolean(item.isMoreToggle), + 'is-expanded': Boolean(item.isExpanded), + 'is-pill-collapsing': false, }); refs.btn.onclick = () => { if (item.mode === 'toggle-expand') { - ctxPillsExpanded = !ctxPillsExpanded; - if (latestData) update({ data: latestData }); + const modern = isModernUiActiveForElement(ctxPanel); + const startH = Number(ctxInspectorBar.offsetHeight || 0); + clearCtxExpandAnim(); + if (!modern || !(startH > 0)) { + ctxPillsExpanded = !ctxPillsExpanded; + if (latestData) update({ data: latestData }); + return; + } + + if (!ctxPillsExpanded) { + const prevKeys = new Set( + Array.from(ctxPillGroup.children, (el) => el.getAttribute?.('data-pill-key') || '') + ); + ctxPillsExpanded = true; + if (latestData) update({ data: latestData }); + const endH = Number(ctxPillGroup.offsetHeight || 0); + for (const child of ctxPillGroup.children) { + const k = child.getAttribute?.('data-pill-key') || ''; + if (k && k !== '__toggle_more__' && !prevKeys.has(k)) { + patchClasses(child, { 'is-pill-entering': true }); + child.onanimationend = () => { + child.onanimationend = null; + patchClasses(child, { 'is-pill-entering': false }); + }; + } + } + if (endH > startH + 1) { + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${endH}px`; + const finishExpand = () => clearCtxExpandAnim(); + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + ctxCollapseTimer = setTimeout(finishExpand, 260); + } + } else { + const firstPill = ctxPillGroup.children[0] || null; + const firstTop = Number(firstPill?.offsetTop || 0); + let firstRowH = Number(firstPill?.offsetHeight || 20); + for (const child of ctxPillGroup.children) { + const top = Number(child.offsetTop || 0); + if (top <= firstTop + 4) { + const bottom = top - firstTop + Number(child.offsetHeight || 0); + if (bottom > firstRowH) firstRowH = bottom; + } + } + const targetH = Math.max(18, firstRowH); + ctxPillsExpanded = false; + isCollapsingCtxPills = true; + patchClasses(refs.btn, { 'is-expanded': false }); + for (const child of ctxPillGroup.children) { + if (Number(child.offsetTop || 0) > firstTop + 4) { + patchClasses(child, { 'is-pill-collapsing': true }); + } + } + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${targetH}px`; + const finishCollapse = () => { + clearCtxExpandAnim(); + if (latestData) update({ data: latestData }); + }; + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + ctxCollapseTimer = setTimeout(finishCollapse, 240); + } } else { setCtxAgentId(item.key); } @@ -10902,6 +11629,7 @@ const ContextWindowWidget = defineComponent({ } onCleanup(() => { + clearCtxExpandAnim(); if (ro) ro.disconnect(); ctxSegmentBar.destroy(); }); @@ -11444,6 +12172,38 @@ const LiveActivityWidget = defineComponent({ } } + function readComputedPx(el, prop, fallback) { + if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') { + return fallback; + } + try { + const val = parseFloat(window.getComputedStyle(el)?.[prop]); + return Number.isFinite(val) ? val : fallback; + } catch { + return fallback; + } + } + + function clearSubExpandAnim(refs) { + if (!refs) return; + if (refs.subAnimTimer) { + clearTimeout(refs.subAnimTimer); + refs.subAnimTimer = null; + } + refs.isCollapsingSubs = false; + const host = refs.subScroll?.el; + if (host) { + host.ontransitionend = null; + patchClasses(host, { 'is-sub-animating': false }); + host.style.height = ''; + host.style.paddingTop = ''; + host.style.marginTop = ''; + host.style.opacity = ''; + host.style.overflow = ''; + host.style.transition = ''; + } + } + function createLiveTaskCard() { const dotIcon = createSvgIcon('dot', { size: 11 }); patchClasses(dotIcon, { 'is-pulsing': true }); @@ -11466,12 +12226,23 @@ const LiveActivityWidget = defineComponent({ text: '', }) : null; - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), + const subToggleLabel = h('span', { + className: 'live-sub-toggle-label', + text: t('live.subToggleIdle', { total: 0 }), }); + const subToggleChevron = createSvgIcon('chevron-down', { + size: 11, + className: 'live-sub-toggle-chevron', + }); + const subToggleBtn = h( + 'button', + { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + }, + [subToggleLabel, subToggleChevron] + ); const elapsedEl = h('span', { className: 'live-activity-elapsed text-mono', text: '0s', @@ -11520,7 +12291,16 @@ const LiveActivityWidget = defineComponent({ ]); const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + const subScroll = CustomScrollbar({ + contentEl: subListEl, + className: 'live-sub-scroll-host', + }); + patchAttr(subScroll.el, 'hidden', true); + const cardEl = h('div', { className: 'live-task-card' }, [ + headerEl, + mainRowEl, + subScroll.el, + ]); return { el: cardEl, @@ -11531,6 +12311,8 @@ const LiveActivityWidget = defineComponent({ hereTagEl, metricsEl, subToggleBtn, + subToggleLabel, + subToggleChevron, elapsedEl, mainBadge, mainPhase, @@ -11538,6 +12320,9 @@ const LiveActivityWidget = defineComponent({ mainSep, mainDetail, subListEl, + subScroll, + subAnimTimer: null, + isCollapsingSubs: false, }, }; } @@ -11599,7 +12384,12 @@ const LiveActivityWidget = defineComponent({ patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - patchKeyedList(liveActivityBar, [], {}); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); return; } @@ -11726,19 +12516,16 @@ const LiveActivityWidget = defineComponent({ patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; const toggleText = runSubCount > 0 ? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', { run: runSubCount, total: subCount, - arrow, }) : t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', { total: subCount, - arrow, }); - patchText(refs.subToggleBtn, toggleText); + patchText(refs.subToggleLabel, toggleText); patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); if (interactive) { patchAttr( @@ -11748,11 +12535,108 @@ const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - if (latestUpdateArgs) update(latestUpdateArgs); - onLayoutChange?.(); + const nextExpanded = !resolveIsExpanded(item); + const host = refs.subScroll.el; + const curH = Number(host.offsetHeight || 0); + const curPadTop = readComputedPx(host, 'paddingTop', 6); + const curMarginTop = readComputedPx(host, 'marginTop', 3); + const curOpacity = readComputedPx(host, 'opacity', 1); + const parentGap = readComputedPx(refs.cardEl, 'rowGap', 7); + const collapsedMarginTop = -Math.max(0, Math.round(parentGap)); + const wasMidAnim = Boolean(refs.subAnimTimer); + clearSubExpandAnim(refs); + manualSubExpandMap.set(item.cascadeId, nextExpanded); + + const modern = isModernUiActiveForElement(refs.cardEl); + if (!modern) { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + return; + } + + if (nextExpanded) { + if (latestUpdateArgs) update(latestUpdateArgs); + const endH = Number(host.offsetHeight || host.scrollHeight || 0); + const endPadTop = readComputedPx(host, 'paddingTop', 6); + const endMarginTop = readComputedPx(host, 'marginTop', 3); + const fromH = wasMidAnim && curH > 0 ? curH : 0; + const fromPadTop = wasMidAnim && curH > 0 ? curPadTop : 0; + const fromMarginTop = wasMidAnim && curH > 0 ? curMarginTop : collapsedMarginTop; + const fromOpacity = wasMidAnim && curH > 0 ? curOpacity : 0; + if (endH > 0) { + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${fromH}px`; + host.style.paddingTop = `${fromPadTop}px`; + host.style.marginTop = `${fromMarginTop}px`; + host.style.opacity = `${fromOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 220ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 220ms cubic-bezier(0.16, 1, 0.3, 1), opacity 180ms ease-out'; + host.style.height = `${endH}px`; + host.style.paddingTop = `${endPadTop}px`; + host.style.marginTop = `${endMarginTop}px`; + host.style.opacity = '1'; + const finishExpand = () => { + clearSubExpandAnim(refs); + refs.subScroll.refresh(); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + refs.subAnimTimer = setTimeout(finishExpand, 260); + } else { + onLayoutChange?.(); + } + } else { + patchClasses(refs.subToggleBtn, { 'is-expanded': false }); + patchAttr(refs.subToggleBtn, 'title', t('live.subExpandTitle')); + if (curH > 0) { + refs.isCollapsingSubs = true; + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${curH}px`; + host.style.paddingTop = `${curPadTop}px`; + host.style.marginTop = `${curMarginTop}px`; + host.style.opacity = `${curOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 200ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 200ms cubic-bezier(0.16, 1, 0.3, 1), opacity 150ms ease-out'; + host.style.height = '0px'; + host.style.paddingTop = '0px'; + host.style.marginTop = `${collapsedMarginTop}px`; + host.style.opacity = '0'; + const finishCollapse = () => { + clearSubExpandAnim(refs); + patchAttr(host, 'hidden', true); + patchAttr(refs.subListEl, 'hidden', true); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + refs.subAnimTimer = setTimeout(finishCollapse, 240); + } else { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + } + } }; } + } else if (refs.isCollapsingSubs) { + clearSubExpandAnim(refs); } const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); @@ -11783,7 +12667,10 @@ const LiveActivityWidget = defineComponent({ } const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); + if (!refs.isCollapsingSubs) { + patchAttr(refs.subScroll.el, 'hidden', !showSubs); + patchAttr(refs.subListEl, 'hidden', !showSubs); + } if (showSubs) { const rawSubItems = item.subagents || []; const getSubSortRank = (s) => { @@ -11898,8 +12785,13 @@ const LiveActivityWidget = defineComponent({ } }, }); + refs.subScroll.refresh(); } }, + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, }); for (const key of [...activityTimersMap.keys()]) { @@ -11913,6 +12805,12 @@ const LiveActivityWidget = defineComponent({ onCleanup(() => { stopLiveTicker(); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); }); return { @@ -13081,6 +13979,43 @@ const StepTableWidget = defineComponent({ const hoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; + let trackedCascadeId = null; + const seenStepKeys = new Set(); + const maxSeenStepByAgent = new Map(); + const activeEnterTimers = new Map(); + + function getStepRowIdentity(st, fallbackCascadeId) { + const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); + const stepNum = Number(st?.stepIndex); + const rowKey = `${agentKey}-${st?.stepIndex}`; + return { agentKey, stepNum, rowKey }; + } + + function absorbStepsIntoBaseline(stepList, fallbackCascadeId) { + if (!Array.isArray(stepList)) return; + for (const st of stepList) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, fallbackCascadeId); + seenStepKeys.add(rowKey); + if (Number.isFinite(stepNum)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || stepNum > prevMax) { + maxSeenStepByAgent.set(agentKey, stepNum); + } + } + } + } + + function clearRowEnterState(tr) { + if (!tr) return; + const timer = activeEnterTimers.get(tr); + if (timer) { + clearTimeout(timer); + activeEnterTimers.delete(tr); + } + tr.onanimationend = null; + patchClasses(tr, { 'is-step-entering': false }); + } function enterStepCell(event) { const { badge, prompt } = hoverRows.get(this); @@ -13121,8 +14056,37 @@ const StepTableWidget = defineComponent({ showStepSpeedColor = false, stepTokenComboFormat = undefined, displaySettings = {}, + allConversationSteps = null, + allowNewRowFade = false, } = {} ) { + const normCascadeId = String(cascadeId || ''); + let enteringRowKeys = null; + if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { + trackedCascadeId = normCascadeId || null; + seenStepKeys.clear(); + maxSeenStepByAgent.clear(); + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else if (!allowNewRowFade || standalone) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else { + for (const st of tableSteps) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); + if (!seenStepKeys.has(rowKey)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { + enteringRowKeys ??= new Set(); + enteringRowKeys.add(rowKey); + } + } + } + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } + const colOrderSig = colKeys.join(','); const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); const renderOptions = JSON.stringify([ @@ -13374,6 +14338,21 @@ const StepTableWidget = defineComponent({ hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail; hoverTd.onmouseleave = hideTurnTip; } + + if (enteringRowKeys?.has(item.rowKey)) { + clearRowEnterState(tr); + patchClasses(tr, { 'is-step-entering': true }); + tr.onanimationend = (ev) => { + if (!ev || !ev.target || ev.target === tr) { + clearRowEnterState(tr); + } + }; + const timer = setTimeout(() => clearRowEnterState(tr), 960); + activeEnterTimers.set(tr, timer); + } + }, + destroyRow: (_refs, tr) => { + clearRowEnterState(tr); }, }); lastRenderOptions = renderOptions; @@ -13383,6 +14362,9 @@ const StepTableWidget = defineComponent({ onCleanup(() => { stepsTablePane.removeEventListener('scroll', hideTurnTip); stepsTbody.removeEventListener('mouseleave', hideTurnTip); + for (const tr of [...activeEnterTimers.keys()]) { + clearRowEnterState(tr); + } }); return { @@ -14937,6 +15919,13 @@ function getFontScaleOptions() { ]; } +function getModernUiOptions() { + return [ + { value: 'off', label: t('settings.gen.modernUiOff') }, + { value: 'on', label: t('settings.gen.modernUiOn') }, + ]; +} + function getUpdateModeOptions() { return [ { value: 'manual', label: t('settings.gen.updateManual') }, @@ -14964,6 +15953,7 @@ const SettingsGeneralTab = defineComponent({ let draftLanguage = 'zh-CN'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; + let draftModernUi = false; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; @@ -15021,6 +16011,14 @@ const SettingsGeneralTab = defineComponent({ className: 'settings-hint-text', text: t('settings.gen.fontHint'), }); + const modernUiLabelEl = h('span', { + className: 'form-label', + text: t('settings.gen.modernUi'), + }); + const modernUiHintEl = h('span', { + className: 'settings-hint-text', + text: t('settings.gen.modernUiHint'), + }); const languageSwitch = SegmentedControl({ ariaLabel: t('settings.gen.language'), @@ -15079,6 +16077,38 @@ const SettingsGeneralTab = defineComponent({ }, }); + const modernUiSwitch = SegmentedControl({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: 'off', + options: getModernUiOptions(), + onUpdateModelValue: async (val) => { + const nextModernUi = val === 'on'; + draftModernUi = nextModernUi; + modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); + if (typeof document !== 'undefined' && document.documentElement) { + applyAppearanceToRoot( + document.documentElement, + { + ...(latestSettings || {}), + themeAccent: draftThemeAccent, + fontScale: draftFontScale, + experimentalModernUi: nextModernUi, + }, + { includeFontScale: true } + ); + } + showAppearanceFeedback(t('settings.saving'), 0); + try { + await saveSettingsPatch({ experimentalModernUi: nextModernUi }); + showAppearanceFeedback(t('settings.saved'), 1500); + props.onLayoutChange?.(); + } catch { + if (latestSettings) renderSettings(latestSettings); + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } + }, + }); + const appearancePanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -15090,6 +16120,7 @@ const SettingsGeneralTab = defineComponent({ h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]), h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]), h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]), + h('div', { className: 'form-row' }, [modernUiLabelEl, modernUiSwitch.el, modernUiHintEl]), ]); // --- Card 2: 版本更新 --- @@ -15248,6 +16279,7 @@ const SettingsGeneralTab = defineComponent({ draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); + draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin @@ -15262,6 +16294,10 @@ const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -15323,6 +16359,8 @@ const SettingsGeneralTab = defineComponent({ patchText(accentLabelEl, t('settings.gen.themeAccent')); patchText(fontLabelEl, t('settings.gen.fontScale')); patchText(fontHintEl, t('settings.gen.fontHint')); + patchText(modernUiLabelEl, t('settings.gen.modernUi')); + patchText(modernUiHintEl, t('settings.gen.modernUiHint')); patchText(updateTitleEl, t('settings.gen.updateTitle')); patchText(updateModeLabelEl, t('settings.gen.updateMode')); patchText(pricingCellLabelEl, t('settings.gen.pricingLabel')); @@ -15339,6 +16377,11 @@ const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -15356,6 +16399,7 @@ const SettingsGeneralTab = defineComponent({ languageSwitch.destroy(); themeColorPicker.destroy(); fontScaleSwitch.destroy(); + modernUiSwitch.destroy(); autoUpdateSelect.destroy(); }); @@ -15365,6 +16409,7 @@ const SettingsGeneralTab = defineComponent({ languageSwitch, themeColorPicker, fontScaleSwitch, + modernUiSwitch, autoUpdateSelect, syncPricingBtn, updatePluginBtn, @@ -15515,10 +16560,29 @@ const SettingsStructureTab = defineComponent({ 'aria-selected': item.key === activeThirdTab ? 'true' : 'false', 'data-structure-tab': item.key, onClick: () => { + applyActiveThirdTab(item.key); if (uiStore.getState().settingsStructureTab !== item.key) { uiStore.setState({ settingsStructureTab: item.key }); - } else { - applyActiveThirdTab(item.key); + } + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === item.key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = + (curIdx + delta + STRUCTURE_THIRD_TABS.length) % STRUCTURE_THIRD_TABS.length; + const nextItem = STRUCTURE_THIRD_TABS[nextIdx]; + if (nextItem) { + applyActiveThirdTab(nextItem.key); + if (uiStore.getState().settingsStructureTab !== nextItem.key) { + uiStore.setState({ settingsStructureTab: nextItem.key }); + } + thirdNavBtnMap.get(nextItem.key)?.btn?.focus?.(); + } } }, }, @@ -15528,6 +16592,7 @@ const SettingsStructureTab = defineComponent({ return btn; }); + const thirdNavGlider = h('div', { className: 'thirdnav-glider', 'aria-hidden': 'true' }); const thirdNavBar = h( 'div', { @@ -15535,7 +16600,15 @@ const SettingsStructureTab = defineComponent({ role: 'tablist', 'aria-label': t('settings.str.thirdTabAria'), }, - thirdNavBtns + [thirdNavGlider, ...thirdNavBtns] + ); + patchStyleVar( + thirdNavBar, + '--active-third-index', + Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === activeThirdTab) + ) ); // --- Pane 1: 挂载与胶囊栏 (`mount`) --- @@ -16311,6 +17384,11 @@ const SettingsStructureTab = defineComponent({ function applyActiveThirdTab(nextRawTab) { const nextTab = normalizeStructureTabKey(nextRawTab); activeThirdTab = nextTab; + const activeIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === nextTab) + ); + patchStyleVar(thirdNavBar, '--active-third-index', activeIdx); for (const [key, entry] of thirdNavBtnMap.entries()) { const isActive = key === nextTab; patchClasses(entry.btn, { 'is-active': isActive }); @@ -17595,6 +18673,7 @@ const { ConsumptionView } = (() => { /** 消耗统计顶栏支持的时间范围预设项 */ function getConsumptionTimeRangeOptions() { return [ + { value: 'cycle', label: t('cons.rangeCycle') }, { value: 'today', label: t('cons.rangeToday') }, { value: '24h', label: t('cons.range24h') }, { value: '7d', label: t('cons.range7d') }, @@ -17683,8 +18762,7 @@ const ConsumptionView = defineComponent({ const customRangeBar = h( 'div', { - style: - 'display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs);', + className: 'cons-custom-range-bar', hidden: true, }, [ @@ -17886,6 +18964,7 @@ const ConsumptionView = defineComponent({ activeHoverTargetEl = null; } patchAttr(breakdownPopoverEl, 'hidden', true); + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); } function positionBreakdownPopover(anchorEl, pointerClientX = null) { @@ -17961,8 +19040,22 @@ const ConsumptionView = defineComponent({ }, }); + const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); patchAttr(breakdownPopoverEl, 'hidden', false); positionBreakdownPopover(anchorEl, pointerClientX); + if (wasHidden) { + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); + void breakdownPopoverEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!breakdownPopoverEl.hasAttribute('hidden')) { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + } } function createMonthModelSegment() { @@ -19009,7 +20102,6 @@ const StepsDetailView = defineComponent({ collapseAll: true, multiUnit: t('steps.unitAgent'), modelValue: selectedAgentScopes, - icon: 'layers', placeholder: t('steps.allAgents'), className: 'steps-inline-scope-select', options: [{ value: 'all', label: t('steps.allAgents') }], @@ -19292,7 +20384,7 @@ const StepsDetailView = defineComponent({ } } - function renderStepsData(slice) { + function renderStepsData(slice, { allowNewRowFade = false } = {}) { if (!slice) return; const uiSt = uiStore.getState(); const locale = getEffectiveLocale(); @@ -19518,6 +20610,12 @@ const StepsDetailView = defineComponent({ ], }); + const allConversationSteps = hasSubagents + ? aggregated?.recentSteps || [] + : slice.recentSteps || []; + const shouldAnimateNewRows = Boolean( + allowNewRowFade && slice.experimentalModernUi && !showModels + ); if (!showModels) { const colKeys = normalizeClientStepColumns(slice.stepTableColumns); renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, { @@ -19529,6 +20627,8 @@ const StepsDetailView = defineComponent({ showStepSpeedColor: slice.showStepSpeedColor === true, stepTokenComboFormat: slice.stepTokenComboFormat, displaySettings, + allConversationSteps, + allowNewRowFade: shouldAnimateNewRows, }); stepsScroll.refresh(); } @@ -19859,6 +20959,7 @@ const StepsDetailView = defineComponent({ st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, + experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), }), (slice) => { latestSlice = slice; @@ -19870,7 +20971,9 @@ const StepsDetailView = defineComponent({ return; } isDirty = false; - renderStepsData(slice); + renderStepsData(slice, { + allowNewRowFade: uiStore.getState().stepsSubTab === 'steps', + }); } ); @@ -21686,6 +22789,7 @@ function mountWindowOverlay() { onSelectSession: inspectSessionInMonitor, onLayoutChange: () => { if (multiOpen) { + patchClasses(multiPanelEl, { 'is-instant': true }); positionFloatingElements(); } }, @@ -21743,9 +22847,23 @@ function mountWindowOverlay() { applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); const scaleKey = normalizeClientFontScale(settings?.fontScale); - popoverEl.setAttribute?.('data-font-scale', scaleKey); - hoverTipEl.setAttribute?.('data-font-scale', scaleKey); - multiPanelEl.setAttribute?.('data-font-scale', scaleKey); + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; + for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { + if (el.getAttribute?.('data-font-scale') !== scaleKey) { + el.setAttribute?.('data-font-scale', scaleKey); + } + if (el.getAttribute?.('data-color-scheme') !== colorScheme) { + el.setAttribute?.('data-color-scheme', colorScheme); + } + if (isModernUi) { + if (el.getAttribute?.('data-modern-ui') !== 'true') { + el.setAttribute?.('data-modern-ui', 'true'); + } + } else if (el.hasAttribute?.('data-modern-ui')) { + el.removeAttribute?.('data-modern-ui'); + } + } } portalShadow.appendChild(multiPanelEl); @@ -21880,6 +22998,7 @@ function mountWindowOverlay() { function ensureWorkbenchThemeObserved() { const wb = syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); if (wb && wb !== observedWorkbench && themeObserver) { observedWorkbench = wb; try { @@ -22909,6 +24028,7 @@ function mountWindowOverlay() { if (typeof MutationObserver !== 'undefined') { themeObserver = new MutationObserver(() => { syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); }); if (document.head) { themeObserver.observe(document.head, { @@ -22917,6 +24037,18 @@ function mountWindowOverlay() { subtree: true, }); } + if (document.documentElement) { + themeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + themeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } if (document.body) { hostDomObserver = new MutationObserver((records) => { if ( @@ -23155,10 +24287,48 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) { syncDocAppearance ); + let hostThemeObserver = null; + let colorSchemeMql = null; + const onHostThemeChange = () => { + syncDocAppearance(telemetryStore.getState().telemetry?.settings); + }; + try { + if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') { + hostThemeObserver = new MutationObserver(onHostThemeChange); + if (document.documentElement) { + hostThemeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + hostThemeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.head) { + hostThemeObserver.observe(document.head, { + childList: true, + characterData: true, + subtree: true, + }); + } + } + if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') { + colorSchemeMql = window.matchMedia('(prefers-color-scheme: dark)'); + colorSchemeMql?.addEventListener?.('change', onHostThemeChange); + } + } catch { + // ignore observer setup errors in constrained environments + } + const stopPolling = startAsyncTelemetryLoop(2000); return { appInstance, stopPolling: () => { + hostThemeObserver?.disconnect?.(); + colorSchemeMql?.removeEventListener?.('change', onHostThemeChange); unsubAppearance(); stopPolling(); }, diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 3c6fa79..6500ce5 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -26,6 +26,7 @@ import { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeExperimentalModernUi, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -67,6 +68,7 @@ export { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeExperimentalModernUi, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -108,6 +110,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ language: 'zh-CN', themeAccent: 'host', fontScale: 'md', + experimentalModernUi: false, weeklyTokenBudget: 150000000, weeklyCostBudget: 100, weeklyLimitMode: 'official', @@ -174,6 +177,7 @@ export function normalizeFullSettings(rawInput) { language: normalizeLanguageSetting(safeRaw.language), themeAccent: normalizeThemeAccent(safeRaw.themeAccent), fontScale: normalizeFontScale(safeRaw.fontScale), + experimentalModernUi: normalizeExperimentalModernUi(safeRaw.experimentalModernUi), weeklyTokenBudget: schemaSanitizePositiveNum( safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit, DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 4f948ae..0d6c5b3 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -1232,6 +1232,9 @@ export async function buildTelemetryPayloadInternal( weeklyResetMs: accountWeeklyResetMs || parseIsoMs(activeLiveWeekly?.resetTime), }; + const isCustomWeeklyMode = + settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost'; + // 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解 + 各配额池独立周期统计) const { selectedWindow, @@ -1252,6 +1255,7 @@ export async function buildTelemetryPayloadInternal( } = aggregateMultiWindowUsage({ filterOpts, cycleAnchors, + isCustomWeeklyMode, currentAccountName: accountScope, activeCascadeId, activeFamilyCascadeIds, @@ -1321,8 +1325,6 @@ export async function buildTelemetryPayloadInternal( +((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1) ); - const isCustomWeeklyMode = - settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost'; const useOfficialWeekly = Boolean(activeLiveWeekly) && !isCustomWeeklyMode; const weeklyUsedPct = useOfficialWeekly diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 308dd3f..d92bb8d 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -2,7 +2,7 @@ * @fileoverview 多时间窗口解析、用量桶累加、趋势序列、月度序列与分模型/分来源聚合引擎。 * * 负责将内存缓存 (`trajectoryCache`) 与外部深层统计缓存 (`loadExternalDeepStatsCache`) - * 中的所有步骤按预设窗口(`all`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口 + * 中的所有步骤按预设窗口(`all`, `cycle`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口 * 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。 */ @@ -98,10 +98,24 @@ function resolveTimeWindow( customStartMs = 0, customEndMs = 0, nowMs = Date.now(), - cycleAnchors = {} + cycleAnchors = {}, + isCustomWeeklyMode = false ) { const now = new Date(nowMs); switch (rangeKey) { + case 'cycle': { + const resetWkMs = !isCustomWeeklyMode ? cycleAnchors.weeklyResetMs || 0 : 0; + const startCycleMs = + resetWkMs > nowMs + ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) + : getStartOfCurrentWeekMs(now); + return { + key: 'cycle', + label: isCustomWeeklyMode ? '本周' : '当前周期', + startMs: startCycleMs, + endMs: nowMs, + }; + } case '5h': { const reset5hMs = cycleAnchors.fiveHourResetMs || 0; const start5hMs = @@ -460,6 +474,7 @@ function sameUsageWindows(previous, current, dates) { export function aggregateMultiWindowUsage({ filterOpts = {}, cycleAnchors = {}, + isCustomWeeklyMode = false, currentAccountName = '', activeCascadeId = null, activeFamilyCascadeIds = null, @@ -480,16 +495,17 @@ export function aggregateMultiWindowUsage({ filterOpts.startMs, filterOpts.endMs, nowMs, - cycleAnchors + cycleAnchors, + isCustomWeeklyMode ); - const presetKeys = ['all', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; + const presetKeys = ['all', 'cycle', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; const presetWindows = {}; const accountBuckets = {}; const sessionBuckets = {}; for (const k of presetKeys) { - presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors); + presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); accountBuckets[k] = createUsageBucket(); sessionBuckets[k] = createUsageBucket(); } @@ -529,6 +545,7 @@ export function aggregateMultiWindowUsage({ const selectedWindowSteps = []; let earliestSelectedStepMs = Infinity; let latestSelectedStepMs = 0; + let earliestActiveCyclePoolStartMs = Infinity; const currentYear = new Date(nowMs).getFullYear(); const monthBoundsMs = Array.from({ length: 13 }, (_, idx) => @@ -621,6 +638,7 @@ export function aggregateMultiWindowUsage({ const snapshot = lastUsageSnapshot; const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone && currentYear === snapshot.currentYear && + Boolean(isCustomWeeklyMode) === Boolean(snapshot.isCustomWeeklyMode) && normalizedQuotaAccount === snapshot.normalizedQuotaAccount && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && @@ -628,7 +646,11 @@ export function aggregateMultiWindowUsage({ const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; if (previous) { // 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。 - const trend = planUsageTrend(selectedWindow, nowMs, previous.earliest, previous.latest); + const effectivePrevWin = + selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow + ? { ...previous.effectiveSelectedWindow, endMs: nowMs } + : selectedWindow; + const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); if ( trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && trend.last === previous.trend.last && @@ -637,7 +659,12 @@ export function aggregateMultiWindowUsage({ ) { snapshot.ranges.delete(selectedWindow.key); snapshot.ranges.set(selectedWindow.key, previous); - return { ...previous.result, selectedWindow, trendStartMs: trend.start, trendEndMs: trend.end }; + return { + ...previous.result, + selectedWindow: effectivePrevWin, + trendStartMs: trend.start, + trendEndMs: trend.end, + }; } } @@ -698,9 +725,70 @@ export function aggregateMultiWindowUsage({ } } + let poolBucketEntry = null; + if (poolCycleBuckets.size > 0) { + let cachedPool = poolByModel.get(mInfo); + if ( + !cachedPool || + cachedPool.key !== st.modelKey || + cachedPool.response !== st.responseModel || + cachedPool.displayName !== st.modelDisplayName + ) { + const ids = [ + st.modelKey, + st.responseModel, + mInfo.modelId, + mInfo.label, + st.modelDisplayName, + ]; + let poolKey = null; + if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon'; + else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon'; + else if (mInfo.family === 'Gemini') poolKey = 'Gemini'; + else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT'; + cachedPool = { + key: st.modelKey, + response: st.responseModel, + displayName: st.modelDisplayName, + bucket: poolCycleBuckets.get(poolKey) || null, + }; + poolByModel.set(mInfo, cachedPool); + } + poolBucketEntry = cachedPool.bucket; + } + + if (includeInQuotaPools && poolBucketEntry && tMs > 0 && tMs <= nowMs) { + if (tMs >= poolBucketEntry.start5hMs) { + accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); + } + if (tMs >= poolBucketEntry.startWkMs) { + accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); + } + } + + let inCurrentCycle = false; + if (tMs > 0 && tMs <= 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; + } else { + inCurrentCycle = includeInQuotaPools && tMs >= presetWindows.cycle.startMs; + } + } + for (const k of presetKeys) { const w = presetWindows[k]; - if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) { + const matchesPreset = + k === 'all' + ? true + : k === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= w.startMs && tMs <= w.endMs; + if (matchesPreset) { accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId); if (isCurrentConv) { accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId); @@ -711,38 +799,22 @@ export function aggregateMultiWindowUsage({ } } - if (includeInQuotaPools && poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) { - let cachedPool = poolByModel.get(mInfo); - if (!cachedPool || cachedPool.key !== st.modelKey || - cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) { - const ids = [st.modelKey, st.responseModel, mInfo.modelId, mInfo.label, st.modelDisplayName]; - let poolKey = null; - if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon'; - else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon'; - else if (mInfo.family === 'Gemini') poolKey = 'Gemini'; - else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT'; - cachedPool = { - key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName, - bucket: poolCycleBuckets.get(poolKey), - }; - poolByModel.set(mInfo, cachedPool); - } - const poolBucketEntry = cachedPool.bucket; - if (poolBucketEntry) { - if (tMs >= poolBucketEntry.start5hMs) { - accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); - } - if (tMs >= poolBucketEntry.startWkMs) { - accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); - } - } - } - const inSelectedWindow = - selectedWindow.key === 'all' || - (tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs); + selectedWindow.key === 'all' + ? true + : selectedWindow.key === 'cycle' + ? inCurrentCycle + : tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs; if (inSelectedWindow) { + if ( + selectedWindow.key === 'cycle' && + !isCustomWeeklyMode && + poolBucketEntry && + poolBucketEntry.startWkMs < earliestActiveCyclePoolStartMs + ) { + earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; + } if (selectedWindow.key === 'custom') { accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); if (isCurrentConv) { @@ -803,7 +875,21 @@ export function aggregateMultiWindowUsage({ ); // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) - const trend = planUsageTrend(selectedWindow, nowMs, earliestSelectedStepMs, latestSelectedStepMs); + const effectiveSelectedWindow = + selectedWindow.key === 'cycle' && + Number.isFinite(earliestActiveCyclePoolStartMs) && + earliestActiveCyclePoolStartMs < Infinity + ? { + ...selectedWindow, + startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), + } + : selectedWindow; + const trend = planUsageTrend( + effectiveSelectedWindow, + nowMs, + earliestSelectedStepMs, + latestSelectedStepMs + ); const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend; const pad2 = (n) => String(n).padStart(2, '0'); const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; @@ -1075,7 +1161,7 @@ export function aggregateMultiWindowUsage({ : null; const result = { - selectedWindow, + selectedWindow: effectiveSelectedWindow, trendStartMs, trendEndMs, finalizedSelectedSession, @@ -1098,6 +1184,7 @@ export function aggregateMultiWindowUsage({ timeZone, modelInputs, currentYear, + isCustomWeeklyMode: Boolean(isCustomWeeklyMode), normalizedQuotaAccount, entries: allEntriesToAggregate, dates: null, @@ -1107,7 +1194,12 @@ export function aggregateMultiWindowUsage({ const { ranges } = lastUsageSnapshot; ranges.delete(selectedWindow.key); ranges.set(selectedWindow.key, { - windows, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs, + windows, + effectiveSelectedWindow, + trend, + result, + earliest: earliestSelectedStepMs, + latest: latestSelectedStepMs, }); // 侧栏和悬浮窗可同时查看不同范围,共用时间索引并最多保留两份聚合结果。 if (ranges.size > 2) ranges.delete(ranges.keys().next().value); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 0dffd36..0366f87 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index 09347dd..6c7ccef 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -504,6 +504,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/styles/views-tables.css', 'src/styles/views-settings.css', 'src/styles/overlay.css', + 'src/styles/modern-ui.css', ]; const cssBundle = diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs index f991242..07fdfde 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -446,3 +446,17 @@ export function normalizeStandalonePort(port) { if (num >= 1024 && num <= 65535) return num; return 0; } + +/** + * 归一化实验性现代化新 UI 开关(默认 `false`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +export function normalizeExperimentalModernUi(val) { + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(val); +} diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 359a92e..5739b74 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -783,6 +783,7 @@ export function createSessionLineChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const pt = currentPoints[idx]; patchAttr(hoverLine, 'hidden', false); @@ -813,6 +814,20 @@ export function createSessionLineChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -824,6 +839,7 @@ export function createSessionLineChart() { patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); if (currentPoints.some((p) => p.valid)) { patchAttr(peakPill, 'hidden', false); } @@ -1577,6 +1593,7 @@ export function createModelFitChart() { patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + const wasHidden = tooltipEl.hasAttribute('hidden'); patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); @@ -1612,6 +1629,20 @@ export function createModelFitChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + if (wasHidden) { + patchClasses(tooltipEl, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + } + } } function clearHover() { @@ -1620,6 +1651,7 @@ export function createModelFitChart() { patchAttr(hoverFitDot, 'hidden', true); patchAttr(hoverRawDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { 'is-tracking': false }); } plotStage.addEventListener('mousemove', (e) => { diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 6c46644..08f6191 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -403,6 +403,34 @@ export function createTrendAreaChart() { let hoveredIdx = -1; let hoveredCellEl = null; let lastRenderSig = ''; + let tipTrackRaf = 0; + + function cancelTipTrackRaf() { + if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(tipTrackRaf); + } + tipTrackRaf = 0; + } + + function armTooltipTracking(wasHidden) { + if (!wasHidden) return; + patchClasses(tooltipEl, { 'is-tracking': false }); + patchClasses(hoverDot, { 'is-tracking': false }); + void tooltipEl.offsetWidth; + cancelTipTrackRaf(); + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + tipTrackRaf = window.requestAnimationFrame(() => { + tipTrackRaf = 0; + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + patchClasses(hoverDot, { 'is-tracking': true }); + } + } function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); @@ -458,6 +486,7 @@ export function createTrendAreaChart() { clearHover(); return; } + const wasHidden = tooltipEl.hasAttribute('hidden'); hoveredIdx = idx; const slot = currentSlots[idx]; const pt = currentPts[idx]; @@ -470,19 +499,31 @@ export function createTrendAreaChart() { patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + const isLineLow = pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2); patchAttr(peakPill, 'hidden', true); patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, - 'is-line-low': pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2), + 'is-line-low': isLineLow, }); patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); + let tipY = 0; + if (isLineLow) { + const wrapH = Number(chartWrap.offsetHeight || 0); + const tipH = Number(tooltipEl.offsetHeight || 0); + if (wrapH > 0 && tipH > 0) { + tipY = Math.max(0, wrapH - tipH - 22); + } + } + const rawPct = (pt.x / viewW) * 100; const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', `${Math.round(tipY)}px`); + armTooltipTracking(wasHidden); for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); @@ -510,6 +551,7 @@ export function createTrendAreaChart() { const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); + const wasHidden = tooltipEl.hasAttribute('hidden'); // 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪 patchClasses(tooltipEl, { 'is-hm-bottom': row <= 3, @@ -536,14 +578,23 @@ export function createTrendAreaChart() { const clampedPct = Math.max(1, Math.min(99, rawPct)); patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-y', '0px'); + armTooltipTracking(wasHidden); } function clearHover() { + cancelTipTrackRaf(); hoveredIdx = -1; patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false }); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': false, + 'is-tracking': false, + }); + patchClasses(hoverDot, { 'is-tracking': false }); if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } @@ -755,6 +806,7 @@ export function createTrendAreaChart() { } function destroy() { + cancelTipTrackRaf(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index a5ac57f..f187404 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -19,6 +19,7 @@ import { PANEL_SCALE_FACTORS, applyAppearanceToRoot, normalizeClientFontScale, + normalizeClientModernUi, } from '../../core/appearance.js'; import { h, @@ -1397,6 +1398,7 @@ export function mountWindowOverlay() { onSelectSession: inspectSessionInMonitor, onLayoutChange: () => { if (multiOpen) { + patchClasses(multiPanelEl, { 'is-instant': true }); positionFloatingElements(); } }, @@ -1454,9 +1456,23 @@ export function mountWindowOverlay() { applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); const scaleKey = normalizeClientFontScale(settings?.fontScale); - popoverEl.setAttribute?.('data-font-scale', scaleKey); - hoverTipEl.setAttribute?.('data-font-scale', scaleKey); - multiPanelEl.setAttribute?.('data-font-scale', scaleKey); + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + const colorScheme = portalHost.getAttribute?.('data-color-scheme') || 'light'; + for (const el of [popoverEl, hoverTipEl, multiPanelEl]) { + if (el.getAttribute?.('data-font-scale') !== scaleKey) { + el.setAttribute?.('data-font-scale', scaleKey); + } + if (el.getAttribute?.('data-color-scheme') !== colorScheme) { + el.setAttribute?.('data-color-scheme', colorScheme); + } + if (isModernUi) { + if (el.getAttribute?.('data-modern-ui') !== 'true') { + el.setAttribute?.('data-modern-ui', 'true'); + } + } else if (el.hasAttribute?.('data-modern-ui')) { + el.removeAttribute?.('data-modern-ui'); + } + } } portalShadow.appendChild(multiPanelEl); @@ -1591,6 +1607,7 @@ export function mountWindowOverlay() { function ensureWorkbenchThemeObserved() { const wb = syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); if (wb && wb !== observedWorkbench && themeObserver) { observedWorkbench = wb; try { @@ -2620,6 +2637,7 @@ export function mountWindowOverlay() { if (typeof MutationObserver !== 'undefined') { themeObserver = new MutationObserver(() => { syncWorkbenchThemeVars(); + syncPortalAppearance(telemetryStore.getState().telemetry?.settings); }); if (document.head) { themeObserver.observe(document.head, { @@ -2628,6 +2646,18 @@ export function mountWindowOverlay() { subtree: true, }); } + if (document.documentElement) { + themeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + themeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } if (document.body) { hostDomObserver = new MutationObserver((records) => { if ( diff --git a/sidecars/panel/src/components/ui/SegmentedControl.js b/sidecars/panel/src/components/ui/SegmentedControl.js index 4c5670d..834c53f 100644 --- a/sidecars/panel/src/components/ui/SegmentedControl.js +++ b/sidecars/panel/src/components/ui/SegmentedControl.js @@ -1,54 +1,215 @@ /** - * @fileoverview Micro-bezel (2px radius) SegmentedControl switcher - * for time-range filtering, context limit selection, and sub-table switching. + * @fileoverview Sliding SegmentedControl switcher with variable-width GPU glider. + * Measures active button geometry via ResizeObserver so both inline variable-width + * segments (e.g. "今天 / 1天 / ... / 自定义", "按步查看 (1520) / 总汇总") and equal-width + * grid bars ("常规 / 结构 / 其他") glide smoothly without stretching from 0px on tab reveal. */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js'; +import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; export const SegmentedControl = defineComponent({ name: 'SegmentedControl', - setup({ getProps, setProps, emit }) { - const rootEl = h('div', { - className: 'segmented', - role: 'group', - 'aria-label': getProps().ariaLabel || '分段切换器', - }); + setup({ getProps, setProps, emit, onCleanup }) { + const gliderEl = h('div', { className: 'seg-glider', 'aria-hidden': 'true' }); + const rootEl = h( + 'div', + { + className: 'segmented', + role: 'group', + 'aria-label': getProps().ariaLabel || '分段切换器', + }, + [gliderEl] + ); + + const btnMap = new Map(); + let orderedBtns = []; + let activeBtnEl = null; + let observedBtnEl = null; + let hasMeasuredVisible = false; + let readyRafId = 0; + + function cancelReadyRaf() { + if (readyRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(readyRafId); + } + readyRafId = 0; + } + + function syncGliderGeometry() { + if (!activeBtnEl) { + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const w = Number(activeBtnEl.offsetWidth || 0); + const h = Number(activeBtnEl.offsetHeight || 0); + if (!(w > 0 && h > 0)) { + // Hidden parent tab or headless Mock DOM: keep .seg-btn.is-active fallback background + // and snap cleanly on first real paint when tab becomes visible. + cancelReadyRaf(); + hasMeasuredVisible = false; + patchClasses(rootEl, { 'has-glider': false }); + patchClasses(gliderEl, { 'is-ready': false }); + return; + } + + const x = Number(activeBtnEl.offsetLeft || 0); + const y = Number(activeBtnEl.offsetTop || 0); + patchStyleVar(gliderEl, '--glider-x', `${x}px`); + patchStyleVar(gliderEl, '--glider-y', `${y}px`); + patchStyleVar(gliderEl, '--glider-w', `${w}px`); + patchStyleVar(gliderEl, '--glider-h', `${h}px`); + patchClasses(rootEl, { 'has-glider': true }); + + if (!hasMeasuredVisible) { + hasMeasuredVisible = true; + patchClasses(gliderEl, { 'is-ready': false }); + void gliderEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + cancelReadyRaf(); + readyRafId = window.requestAnimationFrame(() => { + readyRafId = 0; + if (hasMeasuredVisible) { + patchClasses(gliderEl, { 'is-ready': true }); + } + }); + } else { + patchClasses(gliderEl, { 'is-ready': true }); + } + } + } + + let resizeObs = null; + if (typeof ResizeObserver === 'function') { + resizeObs = new ResizeObserver(() => { + syncGliderGeometry(); + }); + resizeObs.observe(rootEl); + } + + function updateObservedActiveButton(nextActiveBtn) { + if (!resizeObs || observedBtnEl === nextActiveBtn) return; + if (observedBtnEl) { + try { + resizeObs.unobserve(observedBtnEl); + } catch { + // ignore + } + } + observedBtnEl = nextActiveBtn || null; + if (observedBtnEl) { + try { + resizeObs.observe(observedBtnEl); + } catch { + // ignore + } + } + } + + function selectValue(nextVal) { + if (getProps().modelValue !== nextVal) { + setProps({ modelValue: nextVal }); + emit('update:modelValue', nextVal); + } + } function syncSegments() { - const { options = [], modelValue } = getProps(); - patchKeyedList(rootEl, options, { - keyFn: (opt) => opt.value, - sigFn: (opt) => `${opt.value}::${opt.label}::${opt.value === modelValue}`, - createRow: (opt) => { - const btn = h('button', { + const { options = [], modelValue, ariaLabel } = getProps(); + if (ariaLabel) { + patchAttr(rootEl, 'aria-label', ariaLabel); + } + + const validKeys = new Set(options.map((opt) => String(opt.value))); + for (const [key, btn] of btnMap.entries()) { + if (!validKeys.has(key)) { + if (btn.parentNode === rootEl) { + rootEl.removeChild(btn); + } + btnMap.delete(key); + } + } + + orderedBtns = []; + let nextActiveBtn = null; + + for (let i = 0; i < options.length; i++) { + const opt = options[i]; + const key = String(opt.value); + let btn = btnMap.get(key); + if (!btn) { + btn = h('button', { type: 'button', className: 'seg-btn', onClick: (e) => { e.stopPropagation(); - if (getProps().modelValue !== opt.value) { - setProps({ modelValue: opt.value }); - emit('update:modelValue', opt.value); + selectValue(opt.value); + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curOpts = getProps().options || []; + if (!curOpts.length) return; + const curIdx = Math.max( + 0, + curOpts.findIndex((o) => String(o.value) === key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = (curIdx + delta + curOpts.length) % curOpts.length; + const targetOpt = curOpts[nextIdx]; + if (targetOpt) { + selectValue(targetOpt.value); + btnMap.get(String(targetOpt.value))?.focus?.(); + } } }, }); - return { el: btn, refs: {} }; - }, - updateRow: (_refs, opt, _idx, el) => { - const active = opt.value === modelValue; - patchText(el, opt.label); - patchClasses(el, { 'is-active': active }); - patchAttr(el, 'aria-pressed', active ? 'true' : 'false'); - patchAttr(el, 'data-seg-value', opt.value); - }, - }); + btnMap.set(key, btn); + } + + const active = opt.value === modelValue; + patchText(btn, opt.label); + patchClasses(btn, { 'is-active': active }); + patchAttr(btn, 'aria-pressed', active ? 'true' : 'false'); + patchAttr(btn, 'data-seg-value', opt.value); + orderedBtns.push(btn); + if (active) { + nextActiveBtn = btn; + } + } + + // Ensure gliderEl remains index 0 and buttons follow in exact option order + if (rootEl.firstChild !== gliderEl) { + rootEl.insertBefore(gliderEl, rootEl.firstChild); + } + for (let i = 0; i < orderedBtns.length; i++) { + const targetNode = orderedBtns[i]; + const currentAtSlot = rootEl.children[i + 1] || null; + if (currentAtSlot !== targetNode) { + rootEl.insertBefore(targetNode, currentAtSlot); + } + } + + activeBtnEl = nextActiveBtn || orderedBtns[0] || null; + updateObservedActiveButton(activeBtnEl); + syncGliderGeometry(); } syncSegments(); + onCleanup(() => { + cancelReadyRaf(); + resizeObs?.disconnect?.(); + resizeObs = null; + observedBtnEl = null; + }); + return { el: rootEl, - refs: {}, + refs: { gliderEl, refreshGlider: syncGliderGeometry }, onPropsChange: syncSegments, getValue: () => getProps().modelValue, }; diff --git a/sidecars/panel/src/components/widgets/ContextWindowWidget.js b/sidecars/panel/src/components/widgets/ContextWindowWidget.js index 8540c5c..75d2426 100644 --- a/sidecars/panel/src/components/widgets/ContextWindowWidget.js +++ b/sidecars/panel/src/components/widgets/ContextWindowWidget.js @@ -5,6 +5,7 @@ */ import { defineComponent } from '../../core/component.js'; +import { isModernUiActiveForElement } from '../../core/appearance.js'; import { h, patchAttr, @@ -30,8 +31,8 @@ const CTX_ASCII_CHAR_PX = 6.1; const CTX_PILL_GAP_PX = 4; const CTX_DEFAULT_BAR_WIDTH_PX = 310; -function estimateCtxPillWidth(text) { - let w = CTX_PILL_BASE_PAD_PX; +function estimateCtxPillWidth(text, withChevron = false) { + let w = CTX_PILL_BASE_PAD_PX + (withChevron ? 14 : 0); for (const ch of String(text || '')) { w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX; } @@ -244,9 +245,30 @@ export const ContextWindowWidget = defineComponent({ let latestData = null; let ctxPillsExpanded = false; + let isCollapsingCtxPills = false; + let ctxCollapseTimer = null; let lastCascadeId = ''; let cachedBarWidth = 0; + function clearCtxExpandAnim() { + if (ctxCollapseTimer) { + clearTimeout(ctxCollapseTimer); + ctxCollapseTimer = null; + } + isCollapsingCtxPills = false; + ctxInspectorBar.ontransitionend = null; + ctxInspectorBar.style.height = ''; + ctxInspectorBar.style.overflow = ''; + ctxInspectorBar.style.transition = ''; + for (const child of ctxPillGroup.children) { + child.onanimationend = null; + patchClasses(child, { + 'is-pill-entering': false, + 'is-pill-collapsing': false, + }); + } + } + function update({ data } = {}) { latestData = data || null; const curLocale = getEffectiveLocale(); @@ -277,6 +299,7 @@ export const ContextWindowWidget = defineComponent({ const currentCascadeId = data.activeConversation?.cascadeId || ''; if (currentCascadeId && currentCascadeId !== lastCascadeId) { if (lastCascadeId) { + clearCtxExpandAnim(); ctxPillsExpanded = false; } lastCascadeId = currentCascadeId; @@ -308,7 +331,10 @@ export const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); - if (hasSubagents && ctxAgent) { + if (!hasSubagents && isCollapsingCtxPills) { + clearCtxExpandAnim(); + } + if (hasSubagents && ctxAgent && !isCollapsingCtxPills) { const activeBadgeText = formatAgentBadgeText({ agentKind: aggregated?.activeAgentKind || @@ -355,7 +381,7 @@ export const ContextWindowWidget = defineComponent({ if (needsCollapse && !ctxPillsExpanded) { const toggleSample = t('ctx.expandMore', { count: allAgentPills.length }); - const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample); + const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample, true); let usedW = firstPillWidth; let fitCount = 0; for (let i = 0; i < allAgentPills.length; i += 1) { @@ -386,6 +412,7 @@ export const ContextWindowWidget = defineComponent({ title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }), isActive: false, isMoreToggle: true, + isExpanded: false, mode: 'toggle-expand', }); } else { @@ -397,6 +424,7 @@ export const ContextWindowWidget = defineComponent({ title: t('ctx.collapseTitle'), isActive: false, isMoreToggle: true, + isExpanded: true, mode: 'toggle-expand', }); } @@ -405,22 +433,117 @@ export const ContextWindowWidget = defineComponent({ patchKeyedList(ctxPillGroup, pillItems, { keyFn: (item) => item.key, sigFn: (item) => - `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`, + `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${Boolean(item.isExpanded)}:${item.mode}:${item.title}`, createRow: () => { - const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }); - return { el: btn, refs: { btn } }; + const labelSpan = h('span', { className: 'ctx-pill-label' }); + const chevronEl = createSvgIcon('chevron-down', { + size: 11, + className: 'ctx-toggle-chevron', + }); + patchAttr(chevronEl, 'hidden', true); + const btn = h('button', { type: 'button', className: 'ctx-agent-pill' }, [ + labelSpan, + chevronEl, + ]); + return { el: btn, refs: { btn, labelSpan, chevronEl } }; }, updateRow: (refs, item) => { - patchText(refs.btn, item.label); + patchText(refs.labelSpan, item.label); + patchAttr(refs.chevronEl, 'hidden', !item.isMoreToggle); patchAttr(refs.btn, 'title', item.title); + patchAttr(refs.btn, 'data-pill-key', item.key); patchClasses(refs.btn, { 'is-active': item.isActive, 'is-more-toggle': Boolean(item.isMoreToggle), + 'is-expanded': Boolean(item.isExpanded), + 'is-pill-collapsing': false, }); refs.btn.onclick = () => { if (item.mode === 'toggle-expand') { - ctxPillsExpanded = !ctxPillsExpanded; - if (latestData) update({ data: latestData }); + const modern = isModernUiActiveForElement(ctxPanel); + const startH = Number(ctxInspectorBar.offsetHeight || 0); + clearCtxExpandAnim(); + if (!modern || !(startH > 0)) { + ctxPillsExpanded = !ctxPillsExpanded; + if (latestData) update({ data: latestData }); + return; + } + + if (!ctxPillsExpanded) { + const prevKeys = new Set( + Array.from(ctxPillGroup.children, (el) => el.getAttribute?.('data-pill-key') || '') + ); + ctxPillsExpanded = true; + if (latestData) update({ data: latestData }); + const endH = Number(ctxPillGroup.offsetHeight || 0); + for (const child of ctxPillGroup.children) { + const k = child.getAttribute?.('data-pill-key') || ''; + if (k && k !== '__toggle_more__' && !prevKeys.has(k)) { + patchClasses(child, { 'is-pill-entering': true }); + child.onanimationend = () => { + child.onanimationend = null; + patchClasses(child, { 'is-pill-entering': false }); + }; + } + } + if (endH > startH + 1) { + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${endH}px`; + const finishExpand = () => clearCtxExpandAnim(); + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + ctxCollapseTimer = setTimeout(finishExpand, 260); + } + } else { + const firstPill = ctxPillGroup.children[0] || null; + const firstTop = Number(firstPill?.offsetTop || 0); + let firstRowH = Number(firstPill?.offsetHeight || 20); + for (const child of ctxPillGroup.children) { + const top = Number(child.offsetTop || 0); + if (top <= firstTop + 4) { + const bottom = top - firstTop + Number(child.offsetHeight || 0); + if (bottom > firstRowH) firstRowH = bottom; + } + } + const targetH = Math.max(18, firstRowH); + ctxPillsExpanded = false; + isCollapsingCtxPills = true; + patchClasses(refs.btn, { 'is-expanded': false }); + for (const child of ctxPillGroup.children) { + if (Number(child.offsetTop || 0) > firstTop + 4) { + patchClasses(child, { 'is-pill-collapsing': true }); + } + } + ctxInspectorBar.style.height = `${startH}px`; + ctxInspectorBar.style.overflow = 'hidden'; + void ctxInspectorBar.offsetHeight; + ctxInspectorBar.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1)'; + ctxInspectorBar.style.height = `${targetH}px`; + const finishCollapse = () => { + clearCtxExpandAnim(); + if (latestData) update({ data: latestData }); + }; + ctxInspectorBar.ontransitionend = (ev) => { + if ( + ev?.target === ctxInspectorBar && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + ctxCollapseTimer = setTimeout(finishCollapse, 240); + } } else { setCtxAgentId(item.key); } @@ -499,6 +622,7 @@ export const ContextWindowWidget = defineComponent({ } onCleanup(() => { + clearCtxExpandAnim(); if (ro) ro.disconnect(); ctxSegmentBar.destroy(); }); diff --git a/sidecars/panel/src/components/widgets/LiveActivityWidget.js b/sidecars/panel/src/components/widgets/LiveActivityWidget.js index c65f761..6472bd9 100644 --- a/sidecars/panel/src/components/widgets/LiveActivityWidget.js +++ b/sidecars/panel/src/components/widgets/LiveActivityWidget.js @@ -6,6 +6,7 @@ */ import { defineComponent } from '../../core/component.js'; +import { isModernUiActiveForElement } from '../../core/appearance.js'; import { h, patchAttr, @@ -29,6 +30,7 @@ import { telemetryStore, } from '../../store/telemetryStore.js'; import { uiStore } from '../../store/uiStore.js'; +import { CustomScrollbar } from '../ui/CustomScrollbar.js'; export function buildFallbackRunningConversations( data, @@ -197,6 +199,38 @@ export const LiveActivityWidget = defineComponent({ } } + function readComputedPx(el, prop, fallback) { + if (!el || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') { + return fallback; + } + try { + const val = parseFloat(window.getComputedStyle(el)?.[prop]); + return Number.isFinite(val) ? val : fallback; + } catch { + return fallback; + } + } + + function clearSubExpandAnim(refs) { + if (!refs) return; + if (refs.subAnimTimer) { + clearTimeout(refs.subAnimTimer); + refs.subAnimTimer = null; + } + refs.isCollapsingSubs = false; + const host = refs.subScroll?.el; + if (host) { + host.ontransitionend = null; + patchClasses(host, { 'is-sub-animating': false }); + host.style.height = ''; + host.style.paddingTop = ''; + host.style.marginTop = ''; + host.style.opacity = ''; + host.style.overflow = ''; + host.style.transition = ''; + } + } + function createLiveTaskCard() { const dotIcon = createSvgIcon('dot', { size: 11 }); patchClasses(dotIcon, { 'is-pulsing': true }); @@ -219,12 +253,23 @@ export const LiveActivityWidget = defineComponent({ text: '', }) : null; - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), + const subToggleLabel = h('span', { + className: 'live-sub-toggle-label', + text: t('live.subToggleIdle', { total: 0 }), }); + const subToggleChevron = createSvgIcon('chevron-down', { + size: 11, + className: 'live-sub-toggle-chevron', + }); + const subToggleBtn = h( + 'button', + { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + }, + [subToggleLabel, subToggleChevron] + ); const elapsedEl = h('span', { className: 'live-activity-elapsed text-mono', text: '0s', @@ -273,7 +318,16 @@ export const LiveActivityWidget = defineComponent({ ]); const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + const subScroll = CustomScrollbar({ + contentEl: subListEl, + className: 'live-sub-scroll-host', + }); + patchAttr(subScroll.el, 'hidden', true); + const cardEl = h('div', { className: 'live-task-card' }, [ + headerEl, + mainRowEl, + subScroll.el, + ]); return { el: cardEl, @@ -284,6 +338,8 @@ export const LiveActivityWidget = defineComponent({ hereTagEl, metricsEl, subToggleBtn, + subToggleLabel, + subToggleChevron, elapsedEl, mainBadge, mainPhase, @@ -291,6 +347,9 @@ export const LiveActivityWidget = defineComponent({ mainSep, mainDetail, subListEl, + subScroll, + subAnimTimer: null, + isCollapsingSubs: false, }, }; } @@ -352,7 +411,12 @@ export const LiveActivityWidget = defineComponent({ patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - patchKeyedList(liveActivityBar, [], {}); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); return; } @@ -479,19 +543,16 @@ export const LiveActivityWidget = defineComponent({ patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; const toggleText = runSubCount > 0 ? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', { run: runSubCount, total: subCount, - arrow, }) : t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', { total: subCount, - arrow, }); - patchText(refs.subToggleBtn, toggleText); + patchText(refs.subToggleLabel, toggleText); patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); if (interactive) { patchAttr( @@ -501,11 +562,108 @@ export const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - if (latestUpdateArgs) update(latestUpdateArgs); - onLayoutChange?.(); + const nextExpanded = !resolveIsExpanded(item); + const host = refs.subScroll.el; + const curH = Number(host.offsetHeight || 0); + const curPadTop = readComputedPx(host, 'paddingTop', 6); + const curMarginTop = readComputedPx(host, 'marginTop', 3); + const curOpacity = readComputedPx(host, 'opacity', 1); + const parentGap = readComputedPx(refs.cardEl, 'rowGap', 7); + const collapsedMarginTop = -Math.max(0, Math.round(parentGap)); + const wasMidAnim = Boolean(refs.subAnimTimer); + clearSubExpandAnim(refs); + manualSubExpandMap.set(item.cascadeId, nextExpanded); + + const modern = isModernUiActiveForElement(refs.cardEl); + if (!modern) { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + return; + } + + if (nextExpanded) { + if (latestUpdateArgs) update(latestUpdateArgs); + const endH = Number(host.offsetHeight || host.scrollHeight || 0); + const endPadTop = readComputedPx(host, 'paddingTop', 6); + const endMarginTop = readComputedPx(host, 'marginTop', 3); + const fromH = wasMidAnim && curH > 0 ? curH : 0; + const fromPadTop = wasMidAnim && curH > 0 ? curPadTop : 0; + const fromMarginTop = wasMidAnim && curH > 0 ? curMarginTop : collapsedMarginTop; + const fromOpacity = wasMidAnim && curH > 0 ? curOpacity : 0; + if (endH > 0) { + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${fromH}px`; + host.style.paddingTop = `${fromPadTop}px`; + host.style.marginTop = `${fromMarginTop}px`; + host.style.opacity = `${fromOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 220ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 220ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 220ms cubic-bezier(0.16, 1, 0.3, 1), opacity 180ms ease-out'; + host.style.height = `${endH}px`; + host.style.paddingTop = `${endPadTop}px`; + host.style.marginTop = `${endMarginTop}px`; + host.style.opacity = '1'; + const finishExpand = () => { + clearSubExpandAnim(refs); + refs.subScroll.refresh(); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishExpand(); + } + }; + refs.subAnimTimer = setTimeout(finishExpand, 260); + } else { + onLayoutChange?.(); + } + } else { + patchClasses(refs.subToggleBtn, { 'is-expanded': false }); + patchAttr(refs.subToggleBtn, 'title', t('live.subExpandTitle')); + if (curH > 0) { + refs.isCollapsingSubs = true; + patchClasses(host, { 'is-sub-animating': true }); + host.style.height = `${curH}px`; + host.style.paddingTop = `${curPadTop}px`; + host.style.marginTop = `${curMarginTop}px`; + host.style.opacity = `${curOpacity}`; + host.style.overflow = 'hidden'; + void host.offsetHeight; + host.style.transition = + 'height 200ms cubic-bezier(0.16, 1, 0.3, 1), padding-top 200ms cubic-bezier(0.16, 1, 0.3, 1), margin-top 200ms cubic-bezier(0.16, 1, 0.3, 1), opacity 150ms ease-out'; + host.style.height = '0px'; + host.style.paddingTop = '0px'; + host.style.marginTop = `${collapsedMarginTop}px`; + host.style.opacity = '0'; + const finishCollapse = () => { + clearSubExpandAnim(refs); + patchAttr(host, 'hidden', true); + patchAttr(refs.subListEl, 'hidden', true); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + }; + host.ontransitionend = (ev) => { + if ( + ev?.target === host && + (!ev.propertyName || ev.propertyName === 'height') + ) { + finishCollapse(); + } + }; + refs.subAnimTimer = setTimeout(finishCollapse, 240); + } else { + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); + } + } }; } + } else if (refs.isCollapsingSubs) { + clearSubExpandAnim(refs); } const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); @@ -536,7 +694,10 @@ export const LiveActivityWidget = defineComponent({ } const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); + if (!refs.isCollapsingSubs) { + patchAttr(refs.subScroll.el, 'hidden', !showSubs); + patchAttr(refs.subListEl, 'hidden', !showSubs); + } if (showSubs) { const rawSubItems = item.subagents || []; const getSubSortRank = (s) => { @@ -651,8 +812,13 @@ export const LiveActivityWidget = defineComponent({ } }, }); + refs.subScroll.refresh(); } }, + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, }); for (const key of [...activityTimersMap.keys()]) { @@ -666,6 +832,12 @@ export const LiveActivityWidget = defineComponent({ onCleanup(() => { stopLiveTicker(); + patchKeyedList(liveActivityBar, [], { + destroyRow: (refs) => { + clearSubExpandAnim(refs); + refs?.subScroll?.destroy?.(); + }, + }); }); return { diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index c38ce47..e114a2b 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -131,6 +131,43 @@ export const StepTableWidget = defineComponent({ const hoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; + let trackedCascadeId = null; + const seenStepKeys = new Set(); + const maxSeenStepByAgent = new Map(); + const activeEnterTimers = new Map(); + + function getStepRowIdentity(st, fallbackCascadeId) { + const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); + const stepNum = Number(st?.stepIndex); + const rowKey = `${agentKey}-${st?.stepIndex}`; + return { agentKey, stepNum, rowKey }; + } + + function absorbStepsIntoBaseline(stepList, fallbackCascadeId) { + if (!Array.isArray(stepList)) return; + for (const st of stepList) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, fallbackCascadeId); + seenStepKeys.add(rowKey); + if (Number.isFinite(stepNum)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || stepNum > prevMax) { + maxSeenStepByAgent.set(agentKey, stepNum); + } + } + } + } + + function clearRowEnterState(tr) { + if (!tr) return; + const timer = activeEnterTimers.get(tr); + if (timer) { + clearTimeout(timer); + activeEnterTimers.delete(tr); + } + tr.onanimationend = null; + patchClasses(tr, { 'is-step-entering': false }); + } function enterStepCell(event) { const { badge, prompt } = hoverRows.get(this); @@ -171,8 +208,37 @@ export const StepTableWidget = defineComponent({ showStepSpeedColor = false, stepTokenComboFormat = undefined, displaySettings = {}, + allConversationSteps = null, + allowNewRowFade = false, } = {} ) { + const normCascadeId = String(cascadeId || ''); + let enteringRowKeys = null; + if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { + trackedCascadeId = normCascadeId || null; + seenStepKeys.clear(); + maxSeenStepByAgent.clear(); + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else if (!allowNewRowFade || standalone) { + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } else { + for (const st of tableSteps) { + if (!st || typeof st !== 'object') continue; + const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); + if (!seenStepKeys.has(rowKey)) { + const prevMax = maxSeenStepByAgent.get(agentKey); + if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { + enteringRowKeys ??= new Set(); + enteringRowKeys.add(rowKey); + } + } + } + absorbStepsIntoBaseline(allConversationSteps, normCascadeId); + absorbStepsIntoBaseline(tableSteps, normCascadeId); + } + const colOrderSig = colKeys.join(','); const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); const renderOptions = JSON.stringify([ @@ -424,6 +490,21 @@ export const StepTableWidget = defineComponent({ hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail; hoverTd.onmouseleave = hideTurnTip; } + + if (enteringRowKeys?.has(item.rowKey)) { + clearRowEnterState(tr); + patchClasses(tr, { 'is-step-entering': true }); + tr.onanimationend = (ev) => { + if (!ev || !ev.target || ev.target === tr) { + clearRowEnterState(tr); + } + }; + const timer = setTimeout(() => clearRowEnterState(tr), 960); + activeEnterTimers.set(tr, timer); + } + }, + destroyRow: (_refs, tr) => { + clearRowEnterState(tr); }, }); lastRenderOptions = renderOptions; @@ -433,6 +514,9 @@ export const StepTableWidget = defineComponent({ onCleanup(() => { stepsTablePane.removeEventListener('scroll', hideTurnTip); stepsTbody.removeEventListener('mouseleave', hideTurnTip); + for (const tr of [...activeEnterTimers.keys()]) { + clearRowEnterState(tr); + } }); return { diff --git a/sidecars/panel/src/core/appearance.js b/sidecars/panel/src/core/appearance.js index 2ff0a5e..4957014 100644 --- a/sidecars/panel/src/core/appearance.js +++ b/sidecars/panel/src/core/appearance.js @@ -38,23 +38,342 @@ export function normalizeClientFontScale(raw) { return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md'; } +export function normalizeClientModernUi(raw) { + if (typeof raw === 'string') { + const lower = raw.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(raw); +} + +/** + * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. + * + * @param {Node | null | undefined} el + * @returns {boolean} + */ +export function isModernUiActiveForElement(el) { + let cur = el || null; + while (cur) { + if (typeof cur.getAttribute === 'function' && cur.getAttribute('data-modern-ui') === 'true') { + return true; + } + if (cur.parentNode) { + cur = cur.parentNode; + } else if (cur.host) { + cur = cur.host; + } else { + break; + } + } + if (typeof document !== 'undefined' && document.documentElement) { + return document.documentElement.getAttribute?.('data-modern-ui') === 'true'; + } + return false; +} + +const LIGHT_THEME_CLASSES = new Set([ + 'light', + 'vs-light', + 'vscode-light', + 'hc-light', + 'vscode-high-contrast-light', +]); + +const DARK_THEME_CLASSES = new Set([ + 'dark', + 'vs-dark', + 'vscode-dark', + 'hc-black', + 'vscode-high-contrast', +]); + +function hslToRgb(hDeg, sPct, lPct) { + const h = (((hDeg % 360) + 360) % 360) / 360; + const s = Math.max(0, Math.min(1, sPct / 100)); + const l = Math.max(0, Math.min(1, lPct / 100)); + if (s === 0) { + const v = l * 255; + return [v, v, v]; + } + const hue2rgb = (p, q, t) => { + let tt = t; + if (tt < 0) tt += 1; + if (tt > 1) tt -= 1; + if (tt < 1 / 6) return p + (q - p) * 6 * tt; + if (tt < 1 / 2) return q; + if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6; + return p; + }; + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + return [ + hue2rgb(p, q, h + 1 / 3) * 255, + hue2rgb(p, q, h) * 255, + hue2rgb(p, q, h - 1 / 3) * 255, + ]; +} + +function parseAlphaToken(rawAlpha) { + if (rawAlpha == null || rawAlpha === '') return 1; + const str = String(rawAlpha).trim(); + if (!str) return 1; + if (str.endsWith('%')) { + const pct = parseFloat(str); + return Number.isFinite(pct) ? pct / 100 : 1; + } + const num = parseFloat(str); + return Number.isFinite(num) ? num : 1; +} + +/** + * Parse `#hex`, `rgb()/rgba()`, or `hsl()/hsla()` into perceptual luminance `[0, 1]`. + * Returns `null` when transparent (`alpha <= 0.15`) or unparseable. + * + * @param {string | null | undefined} rawColor + * @returns {number | null} + */ +export function parseCssColorLuminance(rawColor) { + const str = String(rawColor ?? '').trim().toLowerCase(); + if (!str || str === 'transparent' || str === 'none' || str === 'inherit' || str === 'initial') { + return null; + } + + if (str.startsWith('#')) { + const hex = str.slice(1); + let r = 0; + let g = 0; + let b = 0; + let a = 1; + if (hex.length === 3 || hex.length === 4) { + r = parseInt(hex[0] + hex[0], 16); + g = parseInt(hex[1] + hex[1], 16); + b = parseInt(hex[2] + hex[2], 16); + if (hex.length === 4) a = parseInt(hex[3] + hex[3], 16) / 255; + } else if (hex.length === 6 || hex.length === 8) { + r = parseInt(hex.slice(0, 2), 16); + g = parseInt(hex.slice(2, 4), 16); + b = parseInt(hex.slice(4, 6), 16); + if (hex.length === 8) a = parseInt(hex.slice(6, 8), 16) / 255; + } else { + return null; + } + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const rgbMatch = str.match(/^rgba?\(([^)]+)\)$/); + if (rgbMatch) { + const body = rgbMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const parseChan = (tok) => + tok.endsWith('%') ? (parseFloat(tok) / 100) * 255 : parseFloat(tok); + const r = parseChan(parts[0]); + const g = parseChan(parts[1]); + const b = parseChan(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) { + return null; + } + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + const hslMatch = str.match(/^hsla?\(([^)]+)\)$/); + if (hslMatch) { + const body = hslMatch[1].trim(); + const [channelsPart, slashAlpha] = body.split('/'); + const parts = channelsPart + .trim() + .split(/[\s,]+/) + .filter(Boolean); + if (parts.length < 3) return null; + const h = parseFloat(parts[0]); + const s = parseFloat(parts[1]); + const l = parseFloat(parts[2]); + const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]); + if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l) || a <= 0.15) { + return null; + } + const [r, g, b] = hslToRgb(h, s, l); + return (0.299 * r + 0.587 * g + 0.114 * b) / 255; + } + + return null; +} + +function readStyleProp(el, cs, prop) { + if (prop.startsWith('--')) { + const inlineVal = + typeof el?.style?.getPropertyValue === 'function' + ? el.style.getPropertyValue(prop) + : el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.getPropertyValue?.(prop); + return compVal ? String(compVal).trim() : ''; + } + const inlineVal = el?.style?.[prop]; + if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim(); + const compVal = cs?.[prop]; + return compVal ? String(compVal).trim() : ''; +} + +/** + * Detect whether the active host surface is `'light'` or `'dark'`. + * Inspects explicit Antigravity / VS Code theme classes & attributes first, + * then actual computed surface/text luminance, then `prefers-color-scheme`. + * + * @param {HTMLElement | null | undefined} [targetEl] + * @returns {'light' | 'dark'} + */ +export function detectHostColorScheme(targetEl = null) { + const doc = typeof document !== 'undefined' ? document : null; + const win = typeof window !== 'undefined' ? window : null; + let workbenchEl = null; + try { + workbenchEl = + typeof doc?.querySelector === 'function' ? doc.querySelector('.monaco-workbench') : null; + } catch { + workbenchEl = null; + } + + const candidates = []; + for (const el of [doc?.body, doc?.documentElement, workbenchEl, targetEl]) { + if (el && !candidates.includes(el)) { + candidates.push(el); + } + } + + // 1. Explicit host theme attributes & class tokens (never read our own data-color-scheme) + for (const el of candidates) { + const vscodeKind = String(el.getAttribute?.('data-vscode-theme-kind') || '') + .trim() + .toLowerCase(); + if (vscodeKind) { + if (vscodeKind.includes('light')) return 'light'; + if (vscodeKind.includes('dark') || vscodeKind.includes('high-contrast')) return 'dark'; + } + const dataTheme = String( + el.getAttribute?.('data-theme') || el.getAttribute?.('data-color-mode') || '' + ) + .trim() + .toLowerCase(); + if (dataTheme === 'light' || dataTheme.endsWith('-light')) return 'light'; + if (dataTheme === 'dark' || dataTheme.endsWith('-dark')) return 'dark'; + + const rawCls = typeof el.className === 'string' ? el.className : ''; + if (rawCls) { + const tokens = rawCls.trim().toLowerCase().split(/\s+/); + for (const tok of tokens) { + if (LIGHT_THEME_CLASSES.has(tok)) return 'light'; + if (DARK_THEME_CLASSES.has(tok)) return 'dark'; + } + } + } + + // 2. Computed / inline surface background luminance + const bgTargets = []; + for (const el of [targetEl, doc?.body, doc?.documentElement, workbenchEl]) { + if (el && !bgTargets.includes(el)) { + bgTargets.push(el); + } + } + const bgProps = [ + '--background', + '--card', + '--vscode-sideBar-background', + '--vscode-editor-background', + 'backgroundColor', + ]; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of bgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum > 0.52 ? 'light' : 'dark'; + } + } + } + + // 3. Computed / inline foreground text luminance + const fgProps = ['--foreground', '--vscode-foreground', '--vscode-editor-foreground', 'color']; + for (const el of bgTargets) { + let cs = null; + try { + cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null; + } catch { + cs = null; + } + for (const prop of fgProps) { + const lum = parseCssColorLuminance(readStyleProp(el, cs, prop)); + if (lum !== null) { + return lum < 0.48 ? 'light' : 'dark'; + } + } + } + + // 4. OS media query fallback + try { + if (win?.matchMedia?.('(prefers-color-scheme: dark)')?.matches) { + return 'dark'; + } + } catch { + // ignore matchMedia errors + } + + return 'light'; +} + +function setAttrIfChanged(el, name, value) { + if (!el || typeof el.setAttribute !== 'function') return; + if (typeof el.getAttribute === 'function' && el.getAttribute(name) === value) return; + el.setAttribute(name, value); +} + +function removeAttrIfPresent(el, name) { + if (!el || typeof el.removeAttribute !== 'function') return; + if (typeof el.hasAttribute === 'function' && !el.hasAttribute(name)) return; + el.removeAttribute(name); +} + function setOrClearStyleVar(el, propName, value) { if (!el || !el.style) return; + const cur = + typeof el.style.getPropertyValue === 'function' + ? el.style.getPropertyValue(propName) + : el.style[propName] || ''; if (value) { + if (cur === value) return; if (typeof el.style.setProperty === 'function') { el.style.setProperty(propName, value); } else { el.style[propName] = value; } - } else if (typeof el.style.removeProperty === 'function') { - el.style.removeProperty(propName); - } else if (typeof el.style.setProperty === 'function') { - el.style.setProperty(propName, ''); + } else if (cur) { + if (typeof el.style.removeProperty === 'function') { + el.style.removeProperty(propName); + } else if (typeof el.style.setProperty === 'function') { + el.style.setProperty(propName, ''); + } else { + el.style[propName] = ''; + } } } /** - * Synchronize theme accent and (optionally) font scale tokens onto a root/host element. + * Synchronize theme accent, host color scheme polarity, and (optionally) font scale tokens + * onto a root/host element. * * @param {HTMLElement | null | undefined} targetEl * @param {object | null | undefined} settings @@ -72,7 +391,17 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t setOrClearStyleVar(targetEl, '--user-accent-primary', ''); setOrClearStyleVar(targetEl, '--user-accent-contrast', ''); } - targetEl.setAttribute?.('data-accent', preset.key); + setAttrIfChanged(targetEl, 'data-accent', preset.key); + + const colorScheme = detectHostColorScheme(targetEl); + setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); + + const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi); + if (isModernUi) { + setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); + } else { + removeAttrIfPresent(targetEl, 'data-modern-ui'); + } if (includeFontScale) { const scaleKey = normalizeClientFontScale(settings?.fontScale); @@ -80,12 +409,10 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1; setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor)); setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor)); - targetEl.setAttribute?.('data-font-scale', scaleKey); + setAttrIfChanged(targetEl, 'data-font-scale', scaleKey); } else { setOrClearStyleVar(targetEl, '--ui-font-scale', ''); setOrClearStyleVar(targetEl, '--ui-panel-scale', ''); - if (typeof targetEl.removeAttribute === 'function') { - targetEl.removeAttribute('data-font-scale'); - } + removeAttrIfPresent(targetEl, 'data-font-scale'); } } diff --git a/sidecars/panel/src/core/domPatch.js b/sidecars/panel/src/core/domPatch.js index 1e40e46..d39900e 100644 --- a/sidecars/panel/src/core/domPatch.js +++ b/sidecars/panel/src/core/domPatch.js @@ -131,7 +131,11 @@ const keyedListState = new WeakMap(); * Keyed incremental list reconciler. * Reuses existing DOM nodes by key and patches only changed items in-place. */ -export function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) { +export function patchKeyedList( + container, + items, + { keyFn = (_, i) => i, sigFn, createRow, updateRow, destroyRow } = {} +) { if (!container) return; let map = keyedListState.get(container); if (!map) { @@ -175,6 +179,7 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda if (record.el.parentNode === container) { container.removeChild(record.el); } + destroyRow?.(record.refs, record.el); map.delete(oldKey); } } diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 9045460..2a61196 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -145,9 +145,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ // Context Window Widget 'ctx.followActive': 'Follow Active ({badge})', 'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window', - 'ctx.expandMore': '+{count} More ▾', + 'ctx.expandMore': '+{count} More', 'ctx.expandMoreTitle': 'Expand all {count} subagent context pills', - 'ctx.collapse': 'Less ▴', + 'ctx.collapse': 'Less', 'ctx.collapseTitle': 'Collapse extra subagent pills', 'ctx.ch.assistant': 'Assistant', 'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments', @@ -199,14 +199,15 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.doneWithSteps': 'Done ({steps} steps)', 'live.waitingWithSteps': 'Waiting ({steps} steps)', 'live.killedWithSteps': 'Killed ({steps} steps)', - 'live.subToggleRunning': 'Subagents {run}/{total} {arrow}', - 'live.subToggleIdle': 'Subagents ({total}) {arrow}', - 'live.swarmToggleRunning': 'Swarm {run}/{total} {arrow}', - 'live.swarmToggleIdle': 'Swarm ({total}) {arrow}', + 'live.subToggleRunning': 'Subagents {run}/{total}', + 'live.subToggleIdle': 'Subagents ({total})', + 'live.swarmToggleRunning': 'Swarm {run}/{total}', + 'live.swarmToggleIdle': 'Swarm ({total})', 'live.subCollapseTitle': 'Collapse subagent list', 'live.subExpandTitle': 'Expand subagent activity list', // Consumption View + 'cons.rangeCycle': 'Cycle', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', @@ -406,6 +407,10 @@ 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.modernUiOff': 'Off', + 'settings.gen.modernUiOn': 'On', + 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations', 'settings.gen.updateTitle': 'Updates & Pricing', 'settings.gen.updateMode': 'Update Policy', 'settings.gen.updateManual': 'Notify only, update manually', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 74346e1..38c3086 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -145,9 +145,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ // Context Window Widget 'ctx.followActive': '跟随活跃 ({badge})', 'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口', - 'ctx.expandMore': '+{count} 展开 ▾', + 'ctx.expandMore': '+{count} 展开', 'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊', - 'ctx.collapse': '收起 ▴', + 'ctx.collapse': '收起', 'ctx.collapseTitle': '折叠多余子代理胶囊', 'ctx.ch.assistant': '模型回复', 'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参', @@ -199,14 +199,15 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.doneWithSteps': '已完成 ({steps} 步)', 'live.waitingWithSteps': '待命中 ({steps} 步)', 'live.killedWithSteps': '已终止 ({steps} 步)', - 'live.subToggleRunning': '子代理 {run}/{total} {arrow}', - 'live.subToggleIdle': '子代理 ({total}) {arrow}', - 'live.swarmToggleRunning': '蜂群 {run}/{total} {arrow}', - 'live.swarmToggleIdle': '蜂群 ({total}) {arrow}', + 'live.subToggleRunning': '子代理 {run}/{total}', + 'live.subToggleIdle': '子代理 ({total})', + 'live.swarmToggleRunning': '蜂群 {run}/{total}', + 'live.swarmToggleIdle': '蜂群 ({total})', 'live.subCollapseTitle': '点击收起子代理列表', 'live.subExpandTitle': '点击展开查看子代理缩略状态', // Consumption View + 'cons.rangeCycle': '周期', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', @@ -406,6 +407,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.gen.fontLg': '大', 'settings.gen.fontXl': '特大', 'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高', + 'settings.gen.modernUi': '新 UI(实验性)', + 'settings.gen.modernUiOff': '关闭', + 'settings.gen.modernUiOn': '开启', + 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画', 'settings.gen.updateTitle': '版本更新', 'settings.gen.updateMode': '更新方式', 'settings.gen.updateManual': '仅提示新版本,手动更新', diff --git a/sidecars/panel/src/main.js b/sidecars/panel/src/main.js index a4dede6..90a7887 100644 --- a/sidecars/panel/src/main.js +++ b/sidecars/panel/src/main.js @@ -29,10 +29,48 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) { syncDocAppearance ); + let hostThemeObserver = null; + let colorSchemeMql = null; + const onHostThemeChange = () => { + syncDocAppearance(telemetryStore.getState().telemetry?.settings); + }; + try { + if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') { + hostThemeObserver = new MutationObserver(onHostThemeChange); + if (document.documentElement) { + hostThemeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.body) { + hostThemeObserver.observe(document.body, { + attributes: true, + attributeFilter: ['class', 'style', 'data-theme', 'data-vscode-theme-kind'], + }); + } + if (document.head) { + hostThemeObserver.observe(document.head, { + childList: true, + characterData: true, + subtree: true, + }); + } + } + if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') { + colorSchemeMql = window.matchMedia('(prefers-color-scheme: dark)'); + colorSchemeMql?.addEventListener?.('change', onHostThemeChange); + } + } catch { + // ignore observer setup errors in constrained environments + } + const stopPolling = startAsyncTelemetryLoop(2000); return { appInstance, stopPolling: () => { + hostThemeObserver?.disconnect?.(); + colorSchemeMql?.removeEventListener?.('change', onHostThemeChange); unsubAppearance(); stopPolling(); }, diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index df5612c..e984548 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -14,7 +14,11 @@ import { getAgentBadgeClass, } from '../core/formatters.js'; import { normalizeI18nLanguage, t } from '../i18n/index.js'; -import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js'; +import { + normalizeClientFontScale, + normalizeClientModernUi, + normalizeClientThemeAccent, +} from '../core/appearance.js'; import { DEFAULT_HOVER_MODULES, DEFAULT_OVERVIEW_METRICS, @@ -195,6 +199,7 @@ export function isEquivalentTelemetry(prev, next) { if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) 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 ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; @@ -895,6 +900,9 @@ export async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { + safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode); } diff --git a/sidecars/panel/src/styles/base.css b/sidecars/panel/src/styles/base.css index 8d4c8e7..7f487d2 100644 --- a/sidecars/panel/src/styles/base.css +++ b/sidecars/panel/src/styles/base.css @@ -54,6 +54,10 @@ td { color: inherit; } +button:focus:not(:focus-visible) { + outline: none; +} + input[type="number"] { appearance: textfield; -moz-appearance: textfield; diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index 96c2b09..c690472 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -95,6 +95,7 @@ color: var(--text-secondary); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; user-select: none; transition: @@ -104,6 +105,17 @@ transform var(--dur-instant) var(--ease-fast); } +.icon-btn:focus-visible, +.pill-tab:focus-visible, +.select-trigger:focus-visible, +.seg-btn:focus-visible, +.btn-primary:focus-visible, +.btn-secondary:focus-visible, +.btn-ghost-sm:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + .icon-btn:hover { background: var(--surface-hover); color: var(--text-primary); @@ -155,6 +167,7 @@ min-height: calc(26px * var(--ui-font-scale, 1)); padding: 2px var(--space-2); border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-base); @@ -569,17 +582,51 @@ color: var(--text-primary); } -/* --- 6. 微边框分段控制器 (Micro-Bezel Segmented Control) --- */ +/* --- 6. 微边框分段控制器 (Micro-Bezel Sliding Segmented Control) --- */ .segmented { + position: relative; display: inline-flex; + flex-wrap: wrap; align-items: center; + align-self: flex-start; + width: fit-content; gap: 2px; + max-width: 100%; padding: 0; background: transparent; border: none; + user-select: none; +} + +.seg-glider { + position: absolute; + top: 0; + left: 0; + width: var(--glider-w, 0px); + height: var(--glider-h, 0px); + border-radius: var(--radius-xs); + background: var(--accent-primary-soft); + transform: translate3d(var(--glider-x, 0px), var(--glider-y, 0px), 0); + opacity: 0; + pointer-events: none; + z-index: 0; + will-change: transform, width; +} + +.segmented.has-glider .seg-glider { + opacity: 1; +} + +.seg-glider.is-ready { + transition: + transform var(--dur-fast) var(--ease-fast), + width var(--dur-fast) var(--ease-fast), + height var(--dur-fast) var(--ease-fast); } .seg-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -587,6 +634,7 @@ min-height: calc(22px * var(--ui-font-scale, 1)); padding: 2px 7px; border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-md); @@ -608,6 +656,17 @@ font-weight: 600; } +.segmented.has-glider .seg-btn:hover { + background: transparent; + color: var(--text-primary); +} + +.segmented.has-glider .seg-btn.is-active { + background: transparent; + color: var(--accent-primary); + font-weight: 600; +} + /* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */ .custom-scroll-host { position: relative; diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css new file mode 100644 index 0000000..20acd1f --- /dev/null +++ b/sidecars/panel/src/styles/modern-ui.css @@ -0,0 +1,706 @@ +/* + * 实验性现代化无边框主题与流畅动画样式层 (modern-ui.css). + * 仅在根容器或 Shadow Host 携带 [data-modern-ui="true"] 时激活: + * 1. 移除绝大部分面板、矩阵、表格、徽章、按钮、输入框与悬浮窗的 1px 线框及分隔线; + * 2. 面板内部子数据块(如版本更新价格表/当前版本、消费矩阵指标格、汇总折线区)保持透明扁平,绝不套叠二层背景卡片; + * 3. 区分深色与浅色极性 ([data-color-scheme="light" | "dark"]): + * - 深色模式采用柔和提亮顶层卡片与轻薄半透雾面滑槽(绝不混入重黑色块); + * - 浅色模式采用微凉白瓷画布 (#f7f9fb) + 纯白悬浮顶层卡片 (#ffffff) + 纯白立体滑块; + * 4. 全局分段切换器 (.segmented / .long-pill-nav / .settings-thirdnav-bar) 按内容宽度贴合滑动。 + */ + +:root[data-modern-ui="true"], +:host([data-modern-ui="true"]), +[data-modern-ui="true"] { + --radius-sm: 10px; + --radius-xs: 7px; + --ease-modern: cubic-bezier(0.16, 1, 0.3, 1); + --dur-fast: 180ms; + --dur-normal: 240ms; + --modern-canvas-bg: var(--surface-bg); + --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); + --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); + --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-card-shadow: none; + --modern-nav-track-bg: var(--modern-surface-card); + --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); + --modern-glider-bg: color-mix(in srgb, var(--accent-primary) 17%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-glider-shadow: none; + --modern-progress-track: color-mix(in srgb, var(--text-primary) 8%, transparent); + --modern-stripe-bg: rgb(255 255 255 / 0.022); + --text-secondary: color-mix(in srgb, var(--text-primary) 80%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 62%, transparent); + --modern-active-accent: color-mix(in srgb, var(--accent-primary) 86%, var(--text-primary) 14%); + --shadow-popover: 0 10px 28px rgb(0 0 0 / 0.28), 0 2px 8px rgb(0 0 0 / 0.14); + --shadow-overlay: 0 22px 52px rgb(0 0 0 / 0.42), 0 4px 16px rgb(0 0 0 / 0.20); +} + +:root[data-modern-ui="true"][data-color-scheme="light"], +:host([data-modern-ui="true"][data-color-scheme="light"]), +[data-modern-ui="true"][data-color-scheme="light"] { + --modern-canvas-bg: color-mix(in srgb, var(--surface-bg) 95.5%, hsl(216 34% 48%) 4.5%); + --modern-surface-card: #ffffff; + --modern-surface-subtle: hsl(216 42% 97.2%); + --modern-surface-hover: hsl(216 56% 94.4%); + --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); + --modern-nav-track-bg: hsl(216 28% 94.2%); + --modern-inline-track-bg: hsl(216 32% 96.2%); + --modern-glider-bg: #ffffff; + --modern-glider-shadow: 0 1px 2px rgb(15 23 42 / 0.08), 0 1px 1px rgb(15 23 42 / 0.04); + --modern-progress-track: hsl(216 28% 93.4%); + --modern-stripe-bg: hsl(216 40% 97.8%); + --text-secondary: color-mix(in srgb, var(--text-primary) 72%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 58%, transparent); + --modern-active-accent: var(--accent-primary); + --shadow-popover: 0 10px 28px rgb(15 23 42 / 0.10), 0 2px 8px rgb(15 23 42 / 0.05); + --shadow-overlay: 0 20px 48px rgb(15 23 42 / 0.14), 0 4px 14px rgb(15 23 42 / 0.06); +} + +@keyframes anim-modern-view-in { + from { + opacity: 0; + transform: translate3d(0, 5px, 0); + } + to { + opacity: 1; + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pop-in { + from { + opacity: 0; + transform: translateY(-4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-pop-in-up { + from { + opacity: 0; + transform: translateY(4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-tip-fade { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes anim-modern-step-row-in { + 0% { + opacity: 0; + background-color: transparent; + animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1); + } + 20% { + opacity: 0.84; + background-color: color-mix(in srgb, var(--accent-primary) 7.5%, transparent); + animation-timing-function: ease-out; + } + 36% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 6%, transparent); + animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + } + 70% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 2%, transparent); + animation-timing-function: ease-out; + } + 100% { + opacity: 1; + background-color: transparent; + } +} + +@keyframes anim-modern-step-cell-in { + from { + transform: translate3d(0, -3px, 0); + } + to { + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pill-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +/* --- 1. 外壳画布、顶层卡片与按量贴合滑动轨道 (Canvas, Top-Level Cards & Fit-Content Sliding Tracks) --- */ +html[data-standalone="true"][data-modern-ui="true"] #app-root { + min-height: 100dvh; + background: var(--modern-canvas-bg); +} + +html[data-standalone="true"][data-modern-ui="true"] .app-shell { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .app-shell { + background: var(--modern-canvas-bg); +} + +[data-modern-ui="true"] .view-pane { + animation: anim-modern-view-in 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .panel, +[data-modern-ui="true"] .session-header { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); +} + +[data-modern-ui="true"] .panel .panel { + background: var(--modern-surface-subtle); + box-shadow: none; +} + +[data-modern-ui="true"] .long-pill-nav, +[data-modern-ui="true"] .settings-thirdnav-bar { + border: none; + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar { + padding: 0; + border: none; + background: transparent; +} + +[data-modern-ui="true"] .segmented { + padding: 2px; + border-radius: var(--radius-xs); + background: var(--modern-inline-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar .segmented { + padding: 3px; + border-radius: var(--radius-sm); + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .pill-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 230ms var(--ease-modern); +} + +[data-modern-ui="true"] .seg-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .seg-glider.is-ready { + transition: + transform 220ms var(--ease-modern), + width 220ms var(--ease-modern), + height 180ms var(--ease-modern); +} + +[data-modern-ui="true"] .segmented:not(.has-glider) .seg-btn.is-active { + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .thirdnav-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab, +[data-modern-ui="true"] .seg-btn, +[data-modern-ui="true"] .structure-thirdnav-btn { + transition: + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab:active, +[data-modern-ui="true"] .seg-btn:active, +[data-modern-ui="true"] .structure-thirdnav-btn:active { + transform: scale(0.97); +} + +/* --- 2. 按钮、状态标签、代理徽章与胶囊全面去边框 --- */ +[data-modern-ui="true"] .status-tag, +[data-modern-ui="true"] .status-tag.state-running, +[data-modern-ui="true"] .status-tag.state-synced, +[data-modern-ui="true"] .status-tag.state-warn, +[data-modern-ui="true"] .update-badge-btn, +[data-modern-ui="true"] .wm-update-btn, +[data-modern-ui="true"] .wm-hover-update-bar, +:host([data-modern-ui="true"]) .wm-update-btn { + border: none; +} + +[data-modern-ui="true"] .icon-btn, +[data-modern-ui="true"] .btn-secondary, +[data-modern-ui="true"] .btn-ghost-sm, +[data-modern-ui="true"] .live-sub-toggle, +[data-modern-ui="true"] .ctx-agent-pill, +[data-modern-ui="true"] .theme-host-chip, +[data-modern-ui="true"] .collapsible-badge { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 160ms var(--ease-modern), + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .session-header .icon-btn { + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .icon-btn:hover, +[data-modern-ui="true"] .btn-secondary:hover:not(:disabled), +[data-modern-ui="true"] .btn-ghost-sm:hover:not(:disabled), +[data-modern-ui="true"] .live-sub-toggle:hover, +[data-modern-ui="true"] .ctx-agent-pill:hover, +[data-modern-ui="true"] .theme-host-chip:hover { + border: none; + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .pill-tab.is-active, +[data-modern-ui="true"] .pill-tab.is-active .svg-icon, +[data-modern-ui="true"] .pill-tab.is-active .pill-tab-badge, +[data-modern-ui="true"] .seg-btn.is-active, +[data-modern-ui="true"] .structure-thirdnav-btn.is-active { + color: var(--modern-active-accent); +} + +[data-modern-ui="true"] .live-sub-toggle.is-expanded, +[data-modern-ui="true"] .ctx-agent-pill.is-active, +[data-modern-ui="true"] .theme-host-chip.is-active { + border: none; + color: var(--modern-active-accent); + background: var(--accent-primary-soft); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-more-toggle { + color: var(--text-secondary); +} + +[data-modern-ui="true"] .btn-ghost-sm:disabled { + opacity: 0.54; +} + +[data-modern-ui="true"] .live-sub-row.is-done { + opacity: 0.82; +} + +[data-modern-ui="true"] .live-sub-row.is-waiting-sub { + opacity: 0.92; +} + +[data-modern-ui="true"] .live-sub-row.is-killed-sub { + opacity: 0.68; +} + +[data-modern-ui="true"] .live-sub-toggle-chevron, +[data-modern-ui="true"] .ctx-toggle-chevron { + transition: transform 200ms var(--ease-modern); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-entering { + animation: anim-modern-pill-in 180ms ease-out both; +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-collapsing { + opacity: 0; + transition: opacity 150ms ease-out; +} + +[data-modern-ui="true"] .btn-primary { + border: none; + transition: + opacity 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .agent-badge, +[data-modern-ui="true"] .agent-badge.is-clickable:hover { + border: none; +} + +[data-modern-ui="true"] .agent-badge:not(.badge-main):not([class*="badge-sub-"]) { + background: var(--modern-surface-subtle); +} + +/* --- 3. 实时概览矩阵与任务卡片:顶层独立卡片,面板内子块绝不叠套背景 --- */ +[data-modern-ui="true"] .telemetry-matrix { + border: none; + background: transparent; + gap: 6px; + overflow: visible; +} + +[data-modern-ui="true"] .matrix-cell { + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); + padding: 8px 10px; + transition: background-color 160ms var(--ease-modern); +} + +/* 面板内的双栏信息项(如版本更新中的「价格表 / 当前版本」)不套二层背景 */ +[data-modern-ui="true"] .dual-grid > .matrix-cell { + background: transparent; + box-shadow: none; + border-radius: 0; + padding: 2px 0; +} + +/* 结构页预览画布内的测速卡与任务卡保持轻微层次以呈现真实预览布局 */ +[data-modern-ui="true"] .structure-preview-canvas .matrix-cell { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-task-card { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); +} + +[data-modern-ui="true"] .structure-preview-canvas .live-task-card { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-sub-scroll-host { + border-top: none; + padding-top: 6px; +} + +[data-modern-ui="true"] .live-sub-scroll-host.is-sub-animating > .scrollbar-rail { + opacity: 0 !important; + pointer-events: none; +} + +[data-modern-ui="true"] .progress-track { + border-radius: var(--radius-pill); + background: var(--modern-progress-track); +} + +/* --- 4. 用量统计矩阵、热力格与详情卡去边框且不叠内层背景 --- */ +[data-modern-ui="true"] .cons-box, +[data-modern-ui="true"] .cons-custom-range-bar { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn { + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .cons-unified-matrix { + border: none; + background: transparent; + gap: 10px 12px; + padding: 2px 0; + overflow: visible; +} + +[data-modern-ui="true"] .cons-split-3 { + gap: 12px; +} + +[data-modern-ui="true"] .cons-matrix-bottom { + border-top: none; +} + +[data-modern-ui="true"] .cons-col, +[data-modern-ui="true"] .cons-col.is-bordered-col { + border: none; + background: transparent; + border-radius: 0; + padding: 2px 0; +} + +[data-modern-ui="true"] .trend-peak-pill, +[data-modern-ui="true"] .trend-hm-cell.lv-0, +[data-modern-ui="true"] .trend-hm-swatch.lv-0 { + border: none; +} + +[data-modern-ui="true"] .trend-tip-sub, +[data-modern-ui="true"] .cons-pop-models { + border-top: none; + padding-top: 3px; +} + +[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, +[data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar, +[data-modern-ui="true"] .month-col.is-interactive:hover .month-stack, +[data-modern-ui="true"] .month-col.is-hovered .month-stack { + box-shadow: none; + filter: brightness(1.06); + transform: scaleY(1.06); +} + +[data-modern-ui="true"] .cons-source-model-bar, +[data-modern-ui="true"] .month-stack { + transition: + height var(--dur-normal) var(--ease-modern), + transform 150ms var(--ease-modern), + filter 150ms var(--ease-modern); +} + +/* --- 5. 调用记录表格与模型分析区去横线边框且不套内层背景 --- */ +[data-modern-ui="true"] .table-scroll-host { + border-top: none; + background: transparent; +} + +[data-modern-ui="true"] .table-viewport, +[data-modern-ui="true"] .data-table th { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"] .data-table th, +[data-modern-ui="true"] .data-table td { + border-bottom: none; +} + +[data-modern-ui="true"] .data-table tbody tr { + transition: background-color 130ms var(--ease-modern); +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering { + animation: anim-modern-step-row-in 850ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering > td { + animation: anim-modern-step-cell-in 300ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .data-table tbody tr:nth-child(even) { + background: var(--modern-stripe-bg); +} + +[data-modern-ui="true"] .data-table tbody tr:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .steps-inline-scope-select .select-trigger, +[data-modern-ui="true"] .steps-inline-model-select .select-trigger, +[data-modern-ui="true"] .sstep-fit-model-select .select-trigger { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .sstep-card, +[data-modern-ui="true"] .smodel-empty { + border: none; + background: transparent; + padding-left: 2px; + padding-right: 2px; +} + +[data-modern-ui="true"] .smodel-card { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .step-table-preview-host { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .smodel-card:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .smodel-card.is-fit-active { + border: none; + background: var(--accent-primary-soft); +} + +/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ +[data-modern-ui="true"] .collapsible-body, +[data-modern-ui="true"] .settings-action-block + .settings-action-block, +[data-modern-ui="true"] .settings-account-entry, +[data-modern-ui="true"] .dt-time-row { + border-top: none; +} + +[data-modern-ui="true"] .settings-divider { + display: none; +} + +[data-modern-ui="true"] .editable-slot-row, +[data-modern-ui="true"] .editable-slot-empty, +[data-modern-ui="true"] .structure-preview-empty, +[data-modern-ui="true"] .preview-sidebar-note, +[data-modern-ui="true"] .preview-capsule-bar, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-multi-btn, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-capsule-btn, +[data-modern-ui="true"] .preview-composer-chip { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .slot-add-btn, +[data-modern-ui="true"] .settings-bridge-relaunch-btn { + border: none; +} + +[data-modern-ui="true"] .ctx-risk-mask, +[data-modern-ui="true"] .settings-bridge-notice, +[data-modern-ui="true"] .settings-bridge-notice.is-restart { + border: none; +} + +[data-modern-ui="true"] .number-input, +[data-modern-ui="true"] .dt-trigger, +[data-modern-ui="true"] .dt-mini-step, +[data-modern-ui="true"] .settings-text-input, +[data-modern-ui="true"] .settings-account-form input { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 150ms var(--ease-modern), + box-shadow 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .num-step-btn { + background: transparent; +} + +[data-modern-ui="true"] .num-field { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .number-input:focus-within, +[data-modern-ui="true"] .settings-text-input:focus, +[data-modern-ui="true"] .settings-account-form input:focus { + border: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + +/* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */ +[data-modern-ui="true"] .select-menu, +[data-modern-ui="true"] .dt-popover, +[data-modern-ui="true"] .sstep-tooltip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-pop-in 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip, +[data-modern-ui="true"] .cons-breakdown-popover, +[data-modern-ui="true"] .turn-prompt-tip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-tip-fade 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) { + top: 2px; + bottom: auto; + transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0); +} + +[data-modern-ui="true"] .trend-tooltip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + bottom 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-hover-dot.is-tracking { + transition: + cx 150ms var(--ease-modern), + cy 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .cons-breakdown-popover.is-tracking, +[data-modern-ui="true"] .turn-prompt-tip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel, +[data-modern-ui="true"].wm-hover-tip, +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-popover-panel, +:host([data-modern-ui="true"]) .wm-hover-tip, +:host([data-modern-ui="true"]) .wm-multi-panel { + border: none; + border-radius: 12px; + background: var(--modern-canvas-bg); + box-shadow: var(--shadow-overlay); + animation: anim-modern-pop-in 200ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel.is-above, +[data-modern-ui="true"].wm-hover-tip.is-above, +[data-modern-ui="true"].wm-multi-panel.is-above, +:host([data-modern-ui="true"]) .wm-popover-panel.is-above, +:host([data-modern-ui="true"]) .wm-hover-tip.is-above, +:host([data-modern-ui="true"]) .wm-multi-panel.is-above { + animation-name: anim-modern-pop-in-up; +} + +[data-modern-ui="true"] .wm-multi-header, +:host([data-modern-ui="true"]) .wm-multi-header, +[data-modern-ui="true"].wm-multi-panel .live-task-card + .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card + .live-task-card { + border: none; +} + +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-multi-panel { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"].wm-multi-panel .live-activity-list, +:host([data-modern-ui="true"]) .wm-multi-panel .live-activity-list { + gap: 2px; +} + +[data-modern-ui="true"].wm-multi-panel .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card { + padding: 10px 2px; + border-radius: 0; + background: transparent; + box-shadow: none; +} diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index beef0b5..1da21cf 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -14,6 +14,25 @@ gap: 6px; } +.cons-overview-head .segmented { + gap: 1px; +} + +.cons-overview-head .seg-btn { + padding: 2px 6px; +} + +.cons-custom-range-bar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + padding: 2px 0 0; + background: transparent; + border: none; + border-radius: 0; +} + .cons-badge { font-size: var(--fs-md); font-weight: 500; diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 623d1e1..c81be2a 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -172,6 +172,7 @@ background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; white-space: nowrap; transition: @@ -180,6 +181,15 @@ background-color var(--dur-instant) var(--ease-fast); } +.live-sub-toggle-chevron { + flex-shrink: 0; + transform: rotate(-90deg); +} + +.live-sub-toggle.is-expanded .live-sub-toggle-chevron { + transform: rotate(0deg); +} + .live-sub-toggle:hover { border-color: var(--border-strong); color: var(--text-primary); @@ -260,34 +270,31 @@ flex-shrink: 0; } -.live-sub-list { - display: flex; - flex-direction: column; - gap: 8px; +.live-sub-scroll-host { padding-top: 9px; - padding-right: 4px; margin-top: 3px; margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; +} + +.live-sub-list { + display: flex; + flex-direction: column; + gap: 8px; + padding-right: 8px; + min-width: 0; max-height: 196px; overflow-y: auto; overscroll-behavior: contain; - scrollbar-width: thin; - scrollbar-color: var(--border-subtle) transparent; + scrollbar-width: none; + -ms-overflow-style: none; } .live-sub-list::-webkit-scrollbar { - width: 4px; -} - -.live-sub-list::-webkit-scrollbar-track { - background: transparent; -} - -.live-sub-list::-webkit-scrollbar-thumb { - background: var(--border-subtle); - border-radius: 999px; + width: 0 !important; + height: 0 !important; + display: none !important; } .live-sub-row { @@ -564,7 +571,7 @@ /* --- 6. 上下文窗口内联代理切换器与代理徽章 (Scheme B Context Inspector & Agent Badges) --- */ .ctx-inspector-bar { display: flex; - align-items: center; + align-items: flex-start; width: 100%; padding: 0; background: transparent; @@ -586,6 +593,7 @@ min-height: calc(20px * var(--ui-font-scale, 1)); padding: 1px 6px; border: 1px solid var(--border-hairline); + outline: none; background: var(--surface-panel); color: var(--text-secondary); font-size: var(--fs-md); @@ -620,6 +628,14 @@ color: var(--text-primary); } +.ctx-toggle-chevron { + flex-shrink: 0; +} + +.ctx-agent-pill.is-more-toggle.is-expanded .ctx-toggle-chevron { + transform: rotate(180deg); +} + .panel-title .agent-badge { flex: 0 1 auto; min-width: 0; diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 1c3d50a..171a05a 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -33,6 +33,7 @@ display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); + align-self: stretch; gap: 3px; } @@ -44,13 +45,37 @@ /* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */ .settings-thirdnav-bar { + position: relative; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 4px; + align-items: center; + padding: 3px; + gap: 0; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); flex-shrink: 0; + user-select: none; +} + +.thirdnav-glider { + position: absolute; + top: 3px; + bottom: 3px; + left: 3px; + width: calc((100% - 6px) / 4); + background: var(--accent-primary-soft); + border: 1px solid var(--accent-primary-border); + border-radius: var(--radius-xs); + transform: translate3d(calc(var(--active-third-index, 0) * 100%), 0, 0); + transition: transform var(--dur-fast) var(--ease-fast); + pointer-events: none; + z-index: 0; } .structure-thirdnav-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -58,29 +83,28 @@ min-height: calc(25px * var(--ui-font-scale, 1)); min-width: 0; padding: 2px 6px; - border: 1px solid var(--border-hairline); + border: none; + outline: none; border-radius: var(--radius-xs); - background: var(--surface-subtle); + background: transparent; color: var(--text-secondary); font-size: var(--fs-md); font-weight: 500; cursor: pointer; - transition: - background-color var(--dur-instant) var(--ease-fast), - color var(--dur-instant) var(--ease-fast), - border-color var(--dur-instant) var(--ease-fast); + transition: color var(--dur-instant) var(--ease-fast); +} + +.structure-thirdnav-btn:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); } .structure-thirdnav-btn:hover { color: var(--text-primary); - border-color: var(--border-strong); - background: var(--surface-hover); } .structure-thirdnav-btn.is-active { color: var(--accent-primary); - background: var(--accent-primary-soft); - border-color: var(--accent-primary-border); font-weight: 600; } diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 0ab0618..11e6a6e 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -47,6 +47,7 @@ import { SegmentedControl } from '../components/ui/SegmentedControl.js'; /** 消耗统计顶栏支持的时间范围预设项 */ function getConsumptionTimeRangeOptions() { return [ + { value: 'cycle', label: t('cons.rangeCycle') }, { value: 'today', label: t('cons.rangeToday') }, { value: '24h', label: t('cons.range24h') }, { value: '7d', label: t('cons.range7d') }, @@ -135,8 +136,7 @@ export const ConsumptionView = defineComponent({ const customRangeBar = h( 'div', { - style: - 'display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs);', + className: 'cons-custom-range-bar', hidden: true, }, [ @@ -338,6 +338,7 @@ export const ConsumptionView = defineComponent({ activeHoverTargetEl = null; } patchAttr(breakdownPopoverEl, 'hidden', true); + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); } function positionBreakdownPopover(anchorEl, pointerClientX = null) { @@ -413,8 +414,22 @@ export const ConsumptionView = defineComponent({ }, }); + const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); patchAttr(breakdownPopoverEl, 'hidden', false); positionBreakdownPopover(anchorEl, pointerClientX); + if (wasHidden) { + patchClasses(breakdownPopoverEl, { 'is-tracking': false }); + void breakdownPopoverEl.offsetWidth; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + if (!breakdownPopoverEl.hasAttribute('hidden')) { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + }); + } else { + patchClasses(breakdownPopoverEl, { 'is-tracking': true }); + } + } } function createMonthModelSegment() { diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index a3479fe..fe063ac 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -220,7 +220,6 @@ export const StepsDetailView = defineComponent({ collapseAll: true, multiUnit: t('steps.unitAgent'), modelValue: selectedAgentScopes, - icon: 'layers', placeholder: t('steps.allAgents'), className: 'steps-inline-scope-select', options: [{ value: 'all', label: t('steps.allAgents') }], @@ -503,7 +502,7 @@ export const StepsDetailView = defineComponent({ } } - function renderStepsData(slice) { + function renderStepsData(slice, { allowNewRowFade = false } = {}) { if (!slice) return; const uiSt = uiStore.getState(); const locale = getEffectiveLocale(); @@ -729,6 +728,12 @@ export const StepsDetailView = defineComponent({ ], }); + const allConversationSteps = hasSubagents + ? aggregated?.recentSteps || [] + : slice.recentSteps || []; + const shouldAnimateNewRows = Boolean( + allowNewRowFade && slice.experimentalModernUi && !showModels + ); if (!showModels) { const colKeys = normalizeClientStepColumns(slice.stepTableColumns); renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, { @@ -740,6 +745,8 @@ export const StepsDetailView = defineComponent({ showStepSpeedColor: slice.showStepSpeedColor === true, stepTokenComboFormat: slice.stepTokenComboFormat, displaySettings, + allConversationSteps, + allowNewRowFade: shouldAnimateNewRows, }); stepsScroll.refresh(); } @@ -1070,6 +1077,7 @@ export const StepsDetailView = defineComponent({ st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, + experimentalModernUi: Boolean(st.telemetry?.settings?.experimentalModernUi), }), (slice) => { latestSlice = slice; @@ -1081,7 +1089,9 @@ export const StepsDetailView = defineComponent({ return; } isDirty = false; - renderStepsData(slice); + renderStepsData(slice, { + allowNewRowFade: uiStore.getState().stepsSubTab === 'steps', + }); } ); diff --git a/sidecars/panel/src/views/settings/SettingsGeneralTab.js b/sidecars/panel/src/views/settings/SettingsGeneralTab.js index 138ade1..817bcb9 100644 --- a/sidecars/panel/src/views/settings/SettingsGeneralTab.js +++ b/sidecars/panel/src/views/settings/SettingsGeneralTab.js @@ -6,7 +6,9 @@ import { defineComponent } from '../../core/component.js'; import { + applyAppearanceToRoot, normalizeClientFontScale, + normalizeClientModernUi, normalizeClientThemeAccent, } from '../../core/appearance.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; @@ -39,6 +41,13 @@ function getFontScaleOptions() { ]; } +function getModernUiOptions() { + return [ + { value: 'off', label: t('settings.gen.modernUiOff') }, + { value: 'on', label: t('settings.gen.modernUiOn') }, + ]; +} + function getUpdateModeOptions() { return [ { value: 'manual', label: t('settings.gen.updateManual') }, @@ -66,6 +75,7 @@ export const SettingsGeneralTab = defineComponent({ let draftLanguage = 'zh-CN'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; + let draftModernUi = false; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; @@ -123,6 +133,14 @@ export const SettingsGeneralTab = defineComponent({ className: 'settings-hint-text', text: t('settings.gen.fontHint'), }); + const modernUiLabelEl = h('span', { + className: 'form-label', + text: t('settings.gen.modernUi'), + }); + const modernUiHintEl = h('span', { + className: 'settings-hint-text', + text: t('settings.gen.modernUiHint'), + }); const languageSwitch = SegmentedControl({ ariaLabel: t('settings.gen.language'), @@ -181,6 +199,38 @@ export const SettingsGeneralTab = defineComponent({ }, }); + const modernUiSwitch = SegmentedControl({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: 'off', + options: getModernUiOptions(), + onUpdateModelValue: async (val) => { + const nextModernUi = val === 'on'; + draftModernUi = nextModernUi; + modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); + if (typeof document !== 'undefined' && document.documentElement) { + applyAppearanceToRoot( + document.documentElement, + { + ...(latestSettings || {}), + themeAccent: draftThemeAccent, + fontScale: draftFontScale, + experimentalModernUi: nextModernUi, + }, + { includeFontScale: true } + ); + } + showAppearanceFeedback(t('settings.saving'), 0); + try { + await saveSettingsPatch({ experimentalModernUi: nextModernUi }); + showAppearanceFeedback(t('settings.saved'), 1500); + props.onLayoutChange?.(); + } catch { + if (latestSettings) renderSettings(latestSettings); + showAppearanceFeedback(t('settings.saveFailed'), 2500); + } + }, + }); + const appearancePanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -192,6 +242,7 @@ export const SettingsGeneralTab = defineComponent({ h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]), h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]), h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]), + h('div', { className: 'form-row' }, [modernUiLabelEl, modernUiSwitch.el, modernUiHintEl]), ]); // --- Card 2: 版本更新 --- @@ -350,6 +401,7 @@ export const SettingsGeneralTab = defineComponent({ draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); + draftModernUi = normalizeClientModernUi(settings.experimentalModernUi); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin @@ -364,6 +416,10 @@ export const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -425,6 +481,8 @@ export const SettingsGeneralTab = defineComponent({ patchText(accentLabelEl, t('settings.gen.themeAccent')); patchText(fontLabelEl, t('settings.gen.fontScale')); patchText(fontHintEl, t('settings.gen.fontHint')); + patchText(modernUiLabelEl, t('settings.gen.modernUi')); + patchText(modernUiHintEl, t('settings.gen.modernUiHint')); patchText(updateTitleEl, t('settings.gen.updateTitle')); patchText(updateModeLabelEl, t('settings.gen.updateMode')); patchText(pricingCellLabelEl, t('settings.gen.pricingLabel')); @@ -441,6 +499,11 @@ export const SettingsGeneralTab = defineComponent({ modelValue: draftFontScale, options: getFontScaleOptions(), }); + modernUiSwitch.setProps({ + ariaLabel: t('settings.gen.modernUi'), + modelValue: draftModernUi ? 'on' : 'off', + options: getModernUiOptions(), + }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), @@ -458,6 +521,7 @@ export const SettingsGeneralTab = defineComponent({ languageSwitch.destroy(); themeColorPicker.destroy(); fontScaleSwitch.destroy(); + modernUiSwitch.destroy(); autoUpdateSelect.destroy(); }); @@ -467,6 +531,7 @@ export const SettingsGeneralTab = defineComponent({ languageSwitch, themeColorPicker, fontScaleSwitch, + modernUiSwitch, autoUpdateSelect, syncPricingBtn, updatePluginBtn, diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index 2674351..4aaa801 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -7,7 +7,7 @@ */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; +import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; import { @@ -177,10 +177,29 @@ export const SettingsStructureTab = defineComponent({ 'aria-selected': item.key === activeThirdTab ? 'true' : 'false', 'data-structure-tab': item.key, onClick: () => { + applyActiveThirdTab(item.key); if (uiStore.getState().settingsStructureTab !== item.key) { uiStore.setState({ settingsStructureTab: item.key }); - } else { - applyActiveThirdTab(item.key); + } + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === item.key) + ); + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIdx = + (curIdx + delta + STRUCTURE_THIRD_TABS.length) % STRUCTURE_THIRD_TABS.length; + const nextItem = STRUCTURE_THIRD_TABS[nextIdx]; + if (nextItem) { + applyActiveThirdTab(nextItem.key); + if (uiStore.getState().settingsStructureTab !== nextItem.key) { + uiStore.setState({ settingsStructureTab: nextItem.key }); + } + thirdNavBtnMap.get(nextItem.key)?.btn?.focus?.(); + } } }, }, @@ -190,6 +209,7 @@ export const SettingsStructureTab = defineComponent({ return btn; }); + const thirdNavGlider = h('div', { className: 'thirdnav-glider', 'aria-hidden': 'true' }); const thirdNavBar = h( 'div', { @@ -197,7 +217,15 @@ export const SettingsStructureTab = defineComponent({ role: 'tablist', 'aria-label': t('settings.str.thirdTabAria'), }, - thirdNavBtns + [thirdNavGlider, ...thirdNavBtns] + ); + patchStyleVar( + thirdNavBar, + '--active-third-index', + Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === activeThirdTab) + ) ); // --- Pane 1: 挂载与胶囊栏 (`mount`) --- @@ -973,6 +1001,11 @@ export const SettingsStructureTab = defineComponent({ function applyActiveThirdTab(nextRawTab) { const nextTab = normalizeStructureTabKey(nextRawTab); activeThirdTab = nextTab; + const activeIdx = Math.max( + 0, + STRUCTURE_THIRD_TABS.findIndex((it) => it.key === nextTab) + ); + patchStyleVar(thirdNavBar, '--active-third-index', activeIdx); for (const [key, entry] of thirdNavBtnMap.entries()) { const isActive = key === nextTab; patchClasses(entry.btn, { 'is-active': isActive }); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index a215260..94699bb 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -233,6 +233,10 @@ td { color: inherit; } +button:focus:not(:focus-visible) { + outline: none; +} + input[type="number"] { appearance: textfield; -moz-appearance: textfield; @@ -466,6 +470,7 @@ html[data-standalone="true"] .app-shell { color: var(--text-secondary); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; user-select: none; transition: @@ -475,6 +480,17 @@ html[data-standalone="true"] .app-shell { transform var(--dur-instant) var(--ease-fast); } +.icon-btn:focus-visible, +.pill-tab:focus-visible, +.select-trigger:focus-visible, +.seg-btn:focus-visible, +.btn-primary:focus-visible, +.btn-secondary:focus-visible, +.btn-ghost-sm:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + .icon-btn:hover { background: var(--surface-hover); color: var(--text-primary); @@ -526,6 +542,7 @@ html[data-standalone="true"] .app-shell { min-height: calc(26px * var(--ui-font-scale, 1)); padding: 2px var(--space-2); border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-base); @@ -940,17 +957,51 @@ html[data-standalone="true"] .app-shell { color: var(--text-primary); } -/* --- 6. 微边框分段控制器 (Micro-Bezel Segmented Control) --- */ +/* --- 6. 微边框分段控制器 (Micro-Bezel Sliding Segmented Control) --- */ .segmented { + position: relative; display: inline-flex; + flex-wrap: wrap; align-items: center; + align-self: flex-start; + width: fit-content; gap: 2px; + max-width: 100%; padding: 0; background: transparent; border: none; + user-select: none; +} + +.seg-glider { + position: absolute; + top: 0; + left: 0; + width: var(--glider-w, 0px); + height: var(--glider-h, 0px); + border-radius: var(--radius-xs); + background: var(--accent-primary-soft); + transform: translate3d(var(--glider-x, 0px), var(--glider-y, 0px), 0); + opacity: 0; + pointer-events: none; + z-index: 0; + will-change: transform, width; +} + +.segmented.has-glider .seg-glider { + opacity: 1; +} + +.seg-glider.is-ready { + transition: + transform var(--dur-fast) var(--ease-fast), + width var(--dur-fast) var(--ease-fast), + height var(--dur-fast) var(--ease-fast); } .seg-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -958,6 +1009,7 @@ html[data-standalone="true"] .app-shell { min-height: calc(22px * var(--ui-font-scale, 1)); padding: 2px 7px; border: none; + outline: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-md); @@ -979,6 +1031,17 @@ html[data-standalone="true"] .app-shell { font-weight: 600; } +.segmented.has-glider .seg-btn:hover { + background: transparent; + color: var(--text-primary); +} + +.segmented.has-glider .seg-btn.is-active { + background: transparent; + color: var(--accent-primary); + font-weight: 600; +} + /* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */ .custom-scroll-host { position: relative; @@ -1419,6 +1482,7 @@ html[data-standalone="true"] .app-shell { background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + outline: none; cursor: pointer; white-space: nowrap; transition: @@ -1427,6 +1491,15 @@ html[data-standalone="true"] .app-shell { background-color var(--dur-instant) var(--ease-fast); } +.live-sub-toggle-chevron { + flex-shrink: 0; + transform: rotate(-90deg); +} + +.live-sub-toggle.is-expanded .live-sub-toggle-chevron { + transform: rotate(0deg); +} + .live-sub-toggle:hover { border-color: var(--border-strong); color: var(--text-primary); @@ -1507,34 +1580,31 @@ html[data-standalone="true"] .app-shell { flex-shrink: 0; } -.live-sub-list { - display: flex; - flex-direction: column; - gap: 8px; +.live-sub-scroll-host { padding-top: 9px; - padding-right: 4px; margin-top: 3px; margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; +} + +.live-sub-list { + display: flex; + flex-direction: column; + gap: 8px; + padding-right: 8px; + min-width: 0; max-height: 196px; overflow-y: auto; overscroll-behavior: contain; - scrollbar-width: thin; - scrollbar-color: var(--border-subtle) transparent; + scrollbar-width: none; + -ms-overflow-style: none; } .live-sub-list::-webkit-scrollbar { - width: 4px; -} - -.live-sub-list::-webkit-scrollbar-track { - background: transparent; -} - -.live-sub-list::-webkit-scrollbar-thumb { - background: var(--border-subtle); - border-radius: 999px; + width: 0 !important; + height: 0 !important; + display: none !important; } .live-sub-row { @@ -1811,7 +1881,7 @@ html[data-standalone="true"] .app-shell { /* --- 6. 上下文窗口内联代理切换器与代理徽章 (Scheme B Context Inspector & Agent Badges) --- */ .ctx-inspector-bar { display: flex; - align-items: center; + align-items: flex-start; width: 100%; padding: 0; background: transparent; @@ -1833,6 +1903,7 @@ html[data-standalone="true"] .app-shell { min-height: calc(20px * var(--ui-font-scale, 1)); padding: 1px 6px; border: 1px solid var(--border-hairline); + outline: none; background: var(--surface-panel); color: var(--text-secondary); font-size: var(--fs-md); @@ -1867,6 +1938,14 @@ html[data-standalone="true"] .app-shell { color: var(--text-primary); } +.ctx-toggle-chevron { + flex-shrink: 0; +} + +.ctx-agent-pill.is-more-toggle.is-expanded .ctx-toggle-chevron { + transform: rotate(180deg); +} + .panel-title .agent-badge { flex: 0 1 auto; min-width: 0; @@ -1949,6 +2028,25 @@ html[data-standalone="true"] .app-shell { gap: 6px; } +.cons-overview-head .segmented { + gap: 1px; +} + +.cons-overview-head .seg-btn { + padding: 2px 6px; +} + +.cons-custom-range-bar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + padding: 2px 0 0; + background: transparent; + border: none; + border-radius: 0; +} + .cons-badge { font-size: var(--fs-md); font-weight: 500; @@ -3571,6 +3669,7 @@ html[data-standalone="true"] .app-shell { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); + align-self: stretch; gap: 3px; } @@ -3582,13 +3681,37 @@ html[data-standalone="true"] .app-shell { /* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */ .settings-thirdnav-bar { + position: relative; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 4px; + align-items: center; + padding: 3px; + gap: 0; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); flex-shrink: 0; + user-select: none; +} + +.thirdnav-glider { + position: absolute; + top: 3px; + bottom: 3px; + left: 3px; + width: calc((100% - 6px) / 4); + background: var(--accent-primary-soft); + border: 1px solid var(--accent-primary-border); + border-radius: var(--radius-xs); + transform: translate3d(calc(var(--active-third-index, 0) * 100%), 0, 0); + transition: transform var(--dur-fast) var(--ease-fast); + pointer-events: none; + z-index: 0; } .structure-thirdnav-btn { + position: relative; + z-index: 1; display: inline-flex; align-items: center; justify-content: center; @@ -3596,29 +3719,28 @@ html[data-standalone="true"] .app-shell { min-height: calc(25px * var(--ui-font-scale, 1)); min-width: 0; padding: 2px 6px; - border: 1px solid var(--border-hairline); + border: none; + outline: none; border-radius: var(--radius-xs); - background: var(--surface-subtle); + background: transparent; color: var(--text-secondary); font-size: var(--fs-md); font-weight: 500; cursor: pointer; - transition: - background-color var(--dur-instant) var(--ease-fast), - color var(--dur-instant) var(--ease-fast), - border-color var(--dur-instant) var(--ease-fast); + transition: color var(--dur-instant) var(--ease-fast); +} + +.structure-thirdnav-btn:focus-visible { + outline: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); } .structure-thirdnav-btn:hover { color: var(--text-primary); - border-color: var(--border-strong); - background: var(--surface-hover); } .structure-thirdnav-btn.is-active { color: var(--accent-primary); - background: var(--accent-primary-soft); - border-color: var(--accent-primary-border); font-weight: 600; } @@ -5315,3 +5437,711 @@ html[data-standalone="true"] .app-shell { background: color-mix(in srgb, var(--text-secondary) 38%, transparent); flex-shrink: 0; } + +/* --- src/styles/modern-ui.css --- */ +/* + * 实验性现代化无边框主题与流畅动画样式层 (modern-ui.css). + * 仅在根容器或 Shadow Host 携带 [data-modern-ui="true"] 时激活: + * 1. 移除绝大部分面板、矩阵、表格、徽章、按钮、输入框与悬浮窗的 1px 线框及分隔线; + * 2. 面板内部子数据块(如版本更新价格表/当前版本、消费矩阵指标格、汇总折线区)保持透明扁平,绝不套叠二层背景卡片; + * 3. 区分深色与浅色极性 ([data-color-scheme="light" | "dark"]): + * - 深色模式采用柔和提亮顶层卡片与轻薄半透雾面滑槽(绝不混入重黑色块); + * - 浅色模式采用微凉白瓷画布 (#f7f9fb) + 纯白悬浮顶层卡片 (#ffffff) + 纯白立体滑块; + * 4. 全局分段切换器 (.segmented / .long-pill-nav / .settings-thirdnav-bar) 按内容宽度贴合滑动。 + */ + +:root[data-modern-ui="true"], +:host([data-modern-ui="true"]), +[data-modern-ui="true"] { + --radius-sm: 10px; + --radius-xs: 7px; + --ease-modern: cubic-bezier(0.16, 1, 0.3, 1); + --dur-fast: 180ms; + --dur-normal: 240ms; + --modern-canvas-bg: var(--surface-bg); + --modern-surface-card: color-mix(in srgb, var(--surface-panel) 95.2%, #ffffff 4.8%); + --modern-surface-subtle: color-mix(in srgb, var(--text-primary) 5.2%, transparent); + --modern-surface-hover: color-mix(in srgb, var(--accent-primary) 11%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-card-shadow: none; + --modern-nav-track-bg: var(--modern-surface-card); + --modern-inline-track-bg: color-mix(in srgb, var(--text-primary) 4.2%, transparent); + --modern-glider-bg: color-mix(in srgb, var(--accent-primary) 17%, color-mix(in srgb, var(--text-primary) 4%, transparent)); + --modern-glider-shadow: none; + --modern-progress-track: color-mix(in srgb, var(--text-primary) 8%, transparent); + --modern-stripe-bg: rgb(255 255 255 / 0.022); + --text-secondary: color-mix(in srgb, var(--text-primary) 80%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 62%, transparent); + --modern-active-accent: color-mix(in srgb, var(--accent-primary) 86%, var(--text-primary) 14%); + --shadow-popover: 0 10px 28px rgb(0 0 0 / 0.28), 0 2px 8px rgb(0 0 0 / 0.14); + --shadow-overlay: 0 22px 52px rgb(0 0 0 / 0.42), 0 4px 16px rgb(0 0 0 / 0.20); +} + +:root[data-modern-ui="true"][data-color-scheme="light"], +:host([data-modern-ui="true"][data-color-scheme="light"]), +[data-modern-ui="true"][data-color-scheme="light"] { + --modern-canvas-bg: color-mix(in srgb, var(--surface-bg) 95.5%, hsl(216 34% 48%) 4.5%); + --modern-surface-card: #ffffff; + --modern-surface-subtle: hsl(216 42% 97.2%); + --modern-surface-hover: hsl(216 56% 94.4%); + --modern-card-shadow: 0 1px 3px rgb(15 23 42 / 0.045), 0 4px 14px rgb(15 23 42 / 0.028); + --modern-nav-track-bg: hsl(216 28% 94.2%); + --modern-inline-track-bg: hsl(216 32% 96.2%); + --modern-glider-bg: #ffffff; + --modern-glider-shadow: 0 1px 2px rgb(15 23 42 / 0.08), 0 1px 1px rgb(15 23 42 / 0.04); + --modern-progress-track: hsl(216 28% 93.4%); + --modern-stripe-bg: hsl(216 40% 97.8%); + --text-secondary: color-mix(in srgb, var(--text-primary) 72%, transparent); + --text-muted: color-mix(in srgb, var(--text-primary) 58%, transparent); + --modern-active-accent: var(--accent-primary); + --shadow-popover: 0 10px 28px rgb(15 23 42 / 0.10), 0 2px 8px rgb(15 23 42 / 0.05); + --shadow-overlay: 0 20px 48px rgb(15 23 42 / 0.14), 0 4px 14px rgb(15 23 42 / 0.06); +} + +@keyframes anim-modern-view-in { + from { + opacity: 0; + transform: translate3d(0, 5px, 0); + } + to { + opacity: 1; + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pop-in { + from { + opacity: 0; + transform: translateY(-4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-pop-in-up { + from { + opacity: 0; + transform: translateY(4px) scale(0.975); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +@keyframes anim-modern-tip-fade { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes anim-modern-step-row-in { + 0% { + opacity: 0; + background-color: transparent; + animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1); + } + 20% { + opacity: 0.84; + background-color: color-mix(in srgb, var(--accent-primary) 7.5%, transparent); + animation-timing-function: ease-out; + } + 36% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 6%, transparent); + animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + } + 70% { + opacity: 1; + background-color: color-mix(in srgb, var(--accent-primary) 2%, transparent); + animation-timing-function: ease-out; + } + 100% { + opacity: 1; + background-color: transparent; + } +} + +@keyframes anim-modern-step-cell-in { + from { + transform: translate3d(0, -3px, 0); + } + to { + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-modern-pill-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +/* --- 1. 外壳画布、顶层卡片与按量贴合滑动轨道 (Canvas, Top-Level Cards & Fit-Content Sliding Tracks) --- */ +html[data-standalone="true"][data-modern-ui="true"] #app-root { + min-height: 100dvh; + background: var(--modern-canvas-bg); +} + +html[data-standalone="true"][data-modern-ui="true"] .app-shell { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .app-shell { + background: var(--modern-canvas-bg); +} + +[data-modern-ui="true"] .view-pane { + animation: anim-modern-view-in 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .panel, +[data-modern-ui="true"] .session-header { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); +} + +[data-modern-ui="true"] .panel .panel { + background: var(--modern-surface-subtle); + box-shadow: none; +} + +[data-modern-ui="true"] .long-pill-nav, +[data-modern-ui="true"] .settings-thirdnav-bar { + border: none; + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar { + padding: 0; + border: none; + background: transparent; +} + +[data-modern-ui="true"] .segmented { + padding: 2px; + border-radius: var(--radius-xs); + background: var(--modern-inline-track-bg); +} + +[data-modern-ui="true"] .settings-subnav-bar .segmented { + padding: 3px; + border-radius: var(--radius-sm); + background: var(--modern-nav-track-bg); +} + +[data-modern-ui="true"] .pill-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 230ms var(--ease-modern); +} + +[data-modern-ui="true"] .seg-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .seg-glider.is-ready { + transition: + transform 220ms var(--ease-modern), + width 220ms var(--ease-modern), + height 180ms var(--ease-modern); +} + +[data-modern-ui="true"] .segmented:not(.has-glider) .seg-btn.is-active { + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); +} + +[data-modern-ui="true"] .thirdnav-glider { + border: none; + background: var(--modern-glider-bg); + box-shadow: var(--modern-glider-shadow); + transition: transform 220ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab, +[data-modern-ui="true"] .seg-btn, +[data-modern-ui="true"] .structure-thirdnav-btn { + transition: + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .pill-tab:active, +[data-modern-ui="true"] .seg-btn:active, +[data-modern-ui="true"] .structure-thirdnav-btn:active { + transform: scale(0.97); +} + +/* --- 2. 按钮、状态标签、代理徽章与胶囊全面去边框 --- */ +[data-modern-ui="true"] .status-tag, +[data-modern-ui="true"] .status-tag.state-running, +[data-modern-ui="true"] .status-tag.state-synced, +[data-modern-ui="true"] .status-tag.state-warn, +[data-modern-ui="true"] .update-badge-btn, +[data-modern-ui="true"] .wm-update-btn, +[data-modern-ui="true"] .wm-hover-update-bar, +:host([data-modern-ui="true"]) .wm-update-btn { + border: none; +} + +[data-modern-ui="true"] .icon-btn, +[data-modern-ui="true"] .btn-secondary, +[data-modern-ui="true"] .btn-ghost-sm, +[data-modern-ui="true"] .live-sub-toggle, +[data-modern-ui="true"] .ctx-agent-pill, +[data-modern-ui="true"] .theme-host-chip, +[data-modern-ui="true"] .collapsible-badge { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 160ms var(--ease-modern), + color 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .session-header .icon-btn { + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .icon-btn:hover, +[data-modern-ui="true"] .btn-secondary:hover:not(:disabled), +[data-modern-ui="true"] .btn-ghost-sm:hover:not(:disabled), +[data-modern-ui="true"] .live-sub-toggle:hover, +[data-modern-ui="true"] .ctx-agent-pill:hover, +[data-modern-ui="true"] .theme-host-chip:hover { + border: none; + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .pill-tab.is-active, +[data-modern-ui="true"] .pill-tab.is-active .svg-icon, +[data-modern-ui="true"] .pill-tab.is-active .pill-tab-badge, +[data-modern-ui="true"] .seg-btn.is-active, +[data-modern-ui="true"] .structure-thirdnav-btn.is-active { + color: var(--modern-active-accent); +} + +[data-modern-ui="true"] .live-sub-toggle.is-expanded, +[data-modern-ui="true"] .ctx-agent-pill.is-active, +[data-modern-ui="true"] .theme-host-chip.is-active { + border: none; + color: var(--modern-active-accent); + background: var(--accent-primary-soft); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-more-toggle { + color: var(--text-secondary); +} + +[data-modern-ui="true"] .btn-ghost-sm:disabled { + opacity: 0.54; +} + +[data-modern-ui="true"] .live-sub-row.is-done { + opacity: 0.82; +} + +[data-modern-ui="true"] .live-sub-row.is-waiting-sub { + opacity: 0.92; +} + +[data-modern-ui="true"] .live-sub-row.is-killed-sub { + opacity: 0.68; +} + +[data-modern-ui="true"] .live-sub-toggle-chevron, +[data-modern-ui="true"] .ctx-toggle-chevron { + transition: transform 200ms var(--ease-modern); +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-entering { + animation: anim-modern-pill-in 180ms ease-out both; +} + +[data-modern-ui="true"] .ctx-agent-pill.is-pill-collapsing { + opacity: 0; + transition: opacity 150ms ease-out; +} + +[data-modern-ui="true"] .btn-primary { + border: none; + transition: + opacity 160ms var(--ease-modern), + transform 140ms var(--ease-modern); +} + +[data-modern-ui="true"] .agent-badge, +[data-modern-ui="true"] .agent-badge.is-clickable:hover { + border: none; +} + +[data-modern-ui="true"] .agent-badge:not(.badge-main):not([class*="badge-sub-"]) { + background: var(--modern-surface-subtle); +} + +/* --- 3. 实时概览矩阵与任务卡片:顶层独立卡片,面板内子块绝不叠套背景 --- */ +[data-modern-ui="true"] .telemetry-matrix { + border: none; + background: transparent; + gap: 6px; + overflow: visible; +} + +[data-modern-ui="true"] .matrix-cell { + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); + padding: 8px 10px; + transition: background-color 160ms var(--ease-modern); +} + +/* 面板内的双栏信息项(如版本更新中的「价格表 / 当前版本」)不套二层背景 */ +[data-modern-ui="true"] .dual-grid > .matrix-cell { + background: transparent; + box-shadow: none; + border-radius: 0; + padding: 2px 0; +} + +/* 结构页预览画布内的测速卡与任务卡保持轻微层次以呈现真实预览布局 */ +[data-modern-ui="true"] .structure-preview-canvas .matrix-cell { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-task-card { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--modern-card-shadow); + border-radius: var(--radius-sm); +} + +[data-modern-ui="true"] .structure-preview-canvas .live-task-card { + background: var(--modern-surface-subtle); + box-shadow: none; + border-radius: var(--radius-xs); +} + +[data-modern-ui="true"] .live-sub-scroll-host { + border-top: none; + padding-top: 6px; +} + +[data-modern-ui="true"] .live-sub-scroll-host.is-sub-animating > .scrollbar-rail { + opacity: 0 !important; + pointer-events: none; +} + +[data-modern-ui="true"] .progress-track { + border-radius: var(--radius-pill); + background: var(--modern-progress-track); +} + +/* --- 4. 用量统计矩阵、热力格与详情卡去边框且不叠内层背景 --- */ +[data-modern-ui="true"] .cons-box, +[data-modern-ui="true"] .cons-custom-range-bar { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn { + background: transparent; +} + +[data-modern-ui="true"] .dt-popover .icon-btn:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .cons-unified-matrix { + border: none; + background: transparent; + gap: 10px 12px; + padding: 2px 0; + overflow: visible; +} + +[data-modern-ui="true"] .cons-split-3 { + gap: 12px; +} + +[data-modern-ui="true"] .cons-matrix-bottom { + border-top: none; +} + +[data-modern-ui="true"] .cons-col, +[data-modern-ui="true"] .cons-col.is-bordered-col { + border: none; + background: transparent; + border-radius: 0; + padding: 2px 0; +} + +[data-modern-ui="true"] .trend-peak-pill, +[data-modern-ui="true"] .trend-hm-cell.lv-0, +[data-modern-ui="true"] .trend-hm-swatch.lv-0 { + border: none; +} + +[data-modern-ui="true"] .trend-tip-sub, +[data-modern-ui="true"] .cons-pop-models { + border-top: none; + padding-top: 3px; +} + +[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, +[data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar, +[data-modern-ui="true"] .month-col.is-interactive:hover .month-stack, +[data-modern-ui="true"] .month-col.is-hovered .month-stack { + box-shadow: none; + filter: brightness(1.06); + transform: scaleY(1.06); +} + +[data-modern-ui="true"] .cons-source-model-bar, +[data-modern-ui="true"] .month-stack { + transition: + height var(--dur-normal) var(--ease-modern), + transform 150ms var(--ease-modern), + filter 150ms var(--ease-modern); +} + +/* --- 5. 调用记录表格与模型分析区去横线边框且不套内层背景 --- */ +[data-modern-ui="true"] .table-scroll-host { + border-top: none; + background: transparent; +} + +[data-modern-ui="true"] .table-viewport, +[data-modern-ui="true"] .data-table th { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"] .data-table th, +[data-modern-ui="true"] .data-table td { + border-bottom: none; +} + +[data-modern-ui="true"] .data-table tbody tr { + transition: background-color 130ms var(--ease-modern); +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering { + animation: anim-modern-step-row-in 850ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .steps-data-table tbody tr.is-step-entering > td { + animation: anim-modern-step-cell-in 300ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +[data-modern-ui="true"] .data-table tbody tr:nth-child(even) { + background: var(--modern-stripe-bg); +} + +[data-modern-ui="true"] .data-table tbody tr:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .steps-inline-scope-select .select-trigger, +[data-modern-ui="true"] .steps-inline-model-select .select-trigger, +[data-modern-ui="true"] .sstep-fit-model-select .select-trigger { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .sstep-card, +[data-modern-ui="true"] .smodel-empty { + border: none; + background: transparent; + padding-left: 2px; + padding-right: 2px; +} + +[data-modern-ui="true"] .smodel-card { + border: none; + background: transparent; +} + +[data-modern-ui="true"] .step-table-preview-host { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .smodel-card:hover { + background: var(--modern-surface-hover); +} + +[data-modern-ui="true"] .smodel-card.is-fit-active { + border: none; + background: var(--accent-primary-soft); +} + +/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ +[data-modern-ui="true"] .collapsible-body, +[data-modern-ui="true"] .settings-action-block + .settings-action-block, +[data-modern-ui="true"] .settings-account-entry, +[data-modern-ui="true"] .dt-time-row { + border-top: none; +} + +[data-modern-ui="true"] .settings-divider { + display: none; +} + +[data-modern-ui="true"] .editable-slot-row, +[data-modern-ui="true"] .editable-slot-empty, +[data-modern-ui="true"] .structure-preview-empty, +[data-modern-ui="true"] .preview-sidebar-note, +[data-modern-ui="true"] .preview-capsule-bar, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-multi-btn, +[data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-capsule-btn, +[data-modern-ui="true"] .preview-composer-chip { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .slot-add-btn, +[data-modern-ui="true"] .settings-bridge-relaunch-btn { + border: none; +} + +[data-modern-ui="true"] .ctx-risk-mask, +[data-modern-ui="true"] .settings-bridge-notice, +[data-modern-ui="true"] .settings-bridge-notice.is-restart { + border: none; +} + +[data-modern-ui="true"] .number-input, +[data-modern-ui="true"] .dt-trigger, +[data-modern-ui="true"] .dt-mini-step, +[data-modern-ui="true"] .settings-text-input, +[data-modern-ui="true"] .settings-account-form input { + border: none; + background: var(--modern-surface-subtle); + transition: + background-color 150ms var(--ease-modern), + box-shadow 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .num-step-btn { + background: transparent; +} + +[data-modern-ui="true"] .num-field { + border-left: none; + border-right: none; +} + +[data-modern-ui="true"] .number-input:focus-within, +[data-modern-ui="true"] .settings-text-input:focus, +[data-modern-ui="true"] .settings-account-form input:focus { + border: none; + box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 55%, transparent); +} + +/* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */ +[data-modern-ui="true"] .select-menu, +[data-modern-ui="true"] .dt-popover, +[data-modern-ui="true"] .sstep-tooltip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-pop-in 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip, +[data-modern-ui="true"] .cons-breakdown-popover, +[data-modern-ui="true"] .turn-prompt-tip { + border: none; + background: var(--modern-surface-card); + box-shadow: var(--shadow-popover); + animation: anim-modern-tip-fade 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) { + top: 2px; + bottom: auto; + transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0); +} + +[data-modern-ui="true"] .trend-tooltip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + bottom 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-hover-dot.is-tracking { + transition: + cx 150ms var(--ease-modern), + cy 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .cons-breakdown-popover.is-tracking, +[data-modern-ui="true"] .turn-prompt-tip.is-tracking { + transition: + left 150ms var(--ease-modern), + top 150ms var(--ease-modern), + transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel, +[data-modern-ui="true"].wm-hover-tip, +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-popover-panel, +:host([data-modern-ui="true"]) .wm-hover-tip, +:host([data-modern-ui="true"]) .wm-multi-panel { + border: none; + border-radius: 12px; + background: var(--modern-canvas-bg); + box-shadow: var(--shadow-overlay); + animation: anim-modern-pop-in 200ms var(--ease-modern); +} + +[data-modern-ui="true"].wm-popover-panel.is-above, +[data-modern-ui="true"].wm-hover-tip.is-above, +[data-modern-ui="true"].wm-multi-panel.is-above, +:host([data-modern-ui="true"]) .wm-popover-panel.is-above, +:host([data-modern-ui="true"]) .wm-hover-tip.is-above, +:host([data-modern-ui="true"]) .wm-multi-panel.is-above { + animation-name: anim-modern-pop-in-up; +} + +[data-modern-ui="true"] .wm-multi-header, +:host([data-modern-ui="true"]) .wm-multi-header, +[data-modern-ui="true"].wm-multi-panel .live-task-card + .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card + .live-task-card { + border: none; +} + +[data-modern-ui="true"].wm-multi-panel, +:host([data-modern-ui="true"]) .wm-multi-panel { + background: var(--modern-surface-card); +} + +[data-modern-ui="true"].wm-multi-panel .live-activity-list, +:host([data-modern-ui="true"]) .wm-multi-panel .live-activity-list { + gap: 2px; +} + +[data-modern-ui="true"].wm-multi-panel .live-task-card, +:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card { + padding: 10px 2px; + border-radius: 0; + background: transparent; + box-shadow: none; +} diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs new file mode 100644 index 0000000..8e0357f --- /dev/null +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -0,0 +1,627 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { createMockDom } from './mock-dom.mjs'; +import { + DEFAULT_SETTINGS_SCHEMA, + normalizeExperimentalModernUi, + normalizeFullSettings, +} from '../backend/settings-schema.mjs'; +import { + applyAppearanceToRoot, + detectHostColorScheme, + normalizeClientModernUi, + parseCssColorLuminance, +} from '../src/core/appearance.js'; +import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js'; +import { SegmentedControl } from '../src/components/ui/SegmentedControl.js'; +import { ContextWindowWidget } from '../src/components/widgets/ContextWindowWidget.js'; +import { LiveActivityWidget } from '../src/components/widgets/LiveActivityWidget.js'; +import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js'; +import { isEquivalentTelemetry, telemetryStore } from '../src/store/telemetryStore.js'; +import { uiStore } from '../src/store/uiStore.js'; +import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; +import { ConsumptionView } from '../src/views/ConsumptionView.js'; +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); + 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('on'), true); + assert.equal(normalizeClientModernUi(false), false); + + assert.equal(normalizeFullSettings({}).experimentalModernUi, false); + assert.equal(normalizeFullSettings({ experimentalModernUi: true }).experimentalModernUi, true); + + assert.equal( + isEquivalentTelemetry( + { settings: { experimentalModernUi: false } }, + { settings: { experimentalModernUi: true } } + ), + false, + 'isEquivalentTelemetry must detect experimentalModernUi changes' + ); +}); + +test('detectHostColorScheme accurately distinguishes light vs dark host polarity across classes, CSS colors, and media queries', (t) => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + getComputedStyle: () => null, + matchMedia: () => ({ matches: false }), + }; + + t.after(() => { + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + assert.ok(parseCssColorLuminance('#ffffff') > 0.99); + assert.ok(parseCssColorLuminance('#18181b') < 0.15); + assert.ok(parseCssColorLuminance('rgb(255, 255, 255)') > 0.99); + assert.ok(parseCssColorLuminance('rgb(21, 24, 30)') < 0.15); + assert.equal(parseCssColorLuminance('rgba(0, 0, 0, 0)'), null); + + // 1. Light webview on a Dark OS: explicit vscode-light class wins over prefers-color-scheme: dark + globalThis.window.matchMedia = () => ({ matches: true }); + document.body.className = 'vscode-light'; + assert.equal(detectHostColorScheme(document.documentElement), 'light'); + + // 2. Dark class wins cleanly + document.body.className = 'vscode-dark'; + assert.equal(detectHostColorScheme(document.documentElement), 'dark'); + + // 3. Computed surface luminance when no explicit theme class is present + document.body.className = ''; + globalThis.window.getComputedStyle = (el) => { + if (el === document.body) { + return { + backgroundColor: 'rgb(255, 255, 255)', + color: 'rgb(24, 24, 27)', + getPropertyValue: () => '', + }; + } + return null; + }; + assert.equal(detectHostColorScheme(document.documentElement), 'light'); + + globalThis.window.getComputedStyle = (el) => { + if (el === document.body) { + return { + backgroundColor: 'rgb(24, 24, 27)', + color: 'rgb(244, 244, 245)', + getPropertyValue: () => '', + }; + } + return null; + }; + assert.equal(detectHostColorScheme(document.documentElement), 'dark'); +}); + +test('applyAppearanceToRoot and SettingsGeneralTab toggle data-modern-ui + data-color-scheme and bundle includes crisp light-mode rules', async (t) => { + const prevLocale = i18nStore.getState().locale; + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevTelState = { ...telemetryStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + document.body.className = 'vscode-light'; + const savedPatches = []; + globalThis.window = { + location: { pathname: '/' }, + sidecar: { + fetch: async (_url, opts) => { + if (opts?.method === 'POST' && opts?.body) { + const parsed = JSON.parse(opts.body); + savedPatches.push(parsed); + return { + ok: true, + status: 200, + json: async () => ({ + ok: true, + settings: { language: 'zh-CN', themeAccent: 'host', fontScale: 'md', ...parsed }, + }), + }; + } + return { ok: true, status: 200, json: async () => ({ ok: true }) }; + }, + }, + addEventListener() {}, + removeEventListener() {}, + }; + + let tab = null; + t.after(() => { + if (tab) tab.destroy(); + setI18nLanguage(prevLocale); + telemetryStore.setState(prevTelState, { sync: true }); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + setI18nLanguage('zh-CN'); + + // 1. Default off -> no data-modern-ui attribute, stamps data-color-scheme="light" + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: false }); + assert.equal(document.documentElement.hasAttribute('data-modern-ui'), false); + assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); + + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: true }); + assert.equal(document.documentElement.getAttribute('data-modern-ui'), 'true'); + assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'light'); + + document.body.className = 'vscode-dark'; + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: true }); + assert.equal(document.documentElement.getAttribute('data-color-scheme'), 'dark'); + + document.body.className = 'vscode-light'; + applyAppearanceToRoot(document.documentElement, { experimentalModernUi: false }); + 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 + tab = SettingsGeneralTab({}); + document.body.appendChild(tab.el); + tab.refs.renderSettings({ + language: 'zh-CN', + themeAccent: 'host', + fontScale: 'md', + 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); + + // Click '开启' (index 1) + modernBtns[1].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); + + // 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'); + assert.match(builtStyles, /\[data-modern-ui="true"\]\s+\.panel/); + assert.match(builtStyles, /\[data-modern-ui="true"\]\[data-color-scheme="light"\]/); + assert.match(builtStyles, /--modern-surface-card:\s*#ffffff;/); + assert.match(builtStyles, /--modern-glider-bg:\s*#ffffff;/); + assert.match( + builtStyles, + /--text-secondary:\s*color-mix\(in srgb,\s*var\(--text-primary\)\s*80%,\s*transparent\);/ + ); + assert.match( + builtStyles, + /--text-muted:\s*color-mix\(in srgb,\s*var\(--text-primary\)\s*62%,\s*transparent\);/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.ctx-agent-pill\.is-more-toggle\s*\{[^}]*color:\s*var\(--text-secondary\);/ + ); + assert.match(builtStyles, /\.seg-glider\.is-ready/); + assert.match(builtStyles, /\.thirdnav-glider/); + assert.match(builtStyles, /\.segmented\s*\{[^}]*width:\s*fit-content;[^}]*\}/); + assert.doesNotMatch(builtStyles, /#000000/); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.dual-grid\s*>\s*\.matrix-cell\s*\{[^}]*background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\.cons-custom-range-bar\s*\{[^}]*background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.steps-data-table\s+tbody\s+tr\.is-step-entering/ + ); + assert.doesNotMatch( + builtStyles, + /(?:^|\n)\.steps-data-table\s+tbody\s+tr\.is-step-entering/, + 'Step row enter animation must ONLY exist under [data-modern-ui="true"]' + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\s+\.trend-tooltip\.is-tracking\s*\{[^}]*150ms/ + ); + assert.match( + builtStyles, + /\[data-modern-ui="true"\]\.wm-multi-panel\s+\.live-task-card[\s\S]*?background:\s*transparent;/ + ); + assert.match( + builtStyles, + /\.ctx-inspector-bar\s*\{[^}]*align-items:\s*flex-start;/, + 'ctx-inspector-bar must top-align pills so height clip never hides row 1 during expand/collapse' + ); + assert.match( + builtStyles, + /@keyframes\s+anim-modern-step-row-in\s*\{\s*0%\s*\{[^}]*opacity:\s*0;[^}]*background-color:\s*transparent;[\s\S]*?100%\s*\{[^}]*opacity:\s*1;[^}]*background-color:\s*transparent;/, + 'Step row fade-in must start and end with transparent background to avoid abrupt flashes' + ); + assert.doesNotMatch( + builtStyles, + /scrollbar-width:\s*thin/, + 'No element may opt into Chromium native scrollbar-width: thin' + ); +}); + +test('SegmentedControl variable-width glider snaps cleanly on reveal and glides across variable-width buttons, plus SettingsStructureTab thirdnav glider slides', (t) => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevUiState = { ...uiStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + let queuedRaf = null; + globalThis.window = { + requestAnimationFrame: (cb) => { + queuedRaf = cb; + return 1; + }, + cancelAnimationFrame: () => { + queuedRaf = null; + }, + addEventListener() {}, + removeEventListener() {}, + }; + + let seg = null; + let structureTab = null; + t.after(() => { + seg?.destroy(); + structureTab?.destroy(); + uiStore.setState(prevUiState, { sync: true }); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + // 1. Hidden / 0x0 fallback -> no .has-glider, button fallback active + const picked = []; + seg = SegmentedControl({ + ariaLabel: '视图切换', + modelValue: 'steps', + options: [ + { value: 'steps', label: '按步查看 (1520)' }, + { value: 'models', label: '总汇总' }, + ], + onUpdateModelValue: (v) => picked.push(v), + }); + + const glider = seg.refs.gliderEl; + const btns = seg.el.querySelectorAll('.seg-btn'); + assert.equal(seg.el.children[0], glider, '.seg-glider stays at child index 0'); + assert.equal(seg.el.classList.contains('has-glider'), false); + assert.equal(glider.classList.contains('is-ready'), false); + + // 2. Simulate layout reveal with variable widths: btn0 = 114px @ x=3, btn1 = 56px @ x=119 + Object.assign(btns[0], { offsetLeft: 3, offsetTop: 3, offsetWidth: 114, offsetHeight: 22 }); + Object.assign(btns[1], { offsetLeft: 119, offsetTop: 3, offsetWidth: 56, offsetHeight: 22 }); + + seg.refs.refreshGlider(); + assert.equal(seg.el.classList.contains('has-glider'), true); + assert.equal(glider.style.getPropertyValue('--glider-x'), '3px'); + assert.equal(glider.style.getPropertyValue('--glider-w'), '114px'); + assert.equal( + glider.classList.contains('is-ready'), + false, + 'Initial visible snap must not animate from 0px' + ); + + assert.equal(typeof queuedRaf, 'function'); + queuedRaf(); + assert.equal(glider.classList.contains('is-ready'), true, 'Transition armed on next frame'); + + // 3. Click second segment ('总汇总') -> glider slides to x=119px, w=56px with .is-ready intact + btns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.deepEqual(picked, ['models']); + assert.equal(glider.style.getPropertyValue('--glider-x'), '119px'); + assert.equal(glider.style.getPropertyValue('--glider-w'), '56px'); + assert.equal(glider.classList.contains('is-ready'), true); + + // 4. ArrowLeft cycles back to 'steps' + btns[1].dispatchEvent({ type: 'keydown', key: 'ArrowLeft', preventDefault() {} }); + assert.deepEqual(picked, ['models', 'steps']); + assert.equal(glider.style.getPropertyValue('--glider-x'), '3px'); + assert.equal(glider.style.getPropertyValue('--glider-w'), '114px'); + + // 5. SettingsStructureTab 4-tab .settings-thirdnav-bar slides .thirdnav-glider via --active-third-index + uiStore.setState({ settingsStructureTab: 'mount' }, { sync: true }); + structureTab = SettingsStructureTab({}); + const thirdNavBar = structureTab.refs.thirdNavBar; + const thirdGlider = thirdNavBar.querySelector('.thirdnav-glider'); + const thirdBtns = thirdNavBar.querySelectorAll('.structure-thirdnav-btn'); + assert.ok(thirdGlider, 'thirdNavBar contains .thirdnav-glider'); + assert.equal(thirdNavBar.style.getPropertyValue('--active-third-index'), '0'); + + thirdBtns[2].dispatchEvent({ type: 'click' }); + uiStore.flushSync?.(); + assert.equal(thirdNavBar.style.getPropertyValue('--active-third-index'), '2'); + + thirdBtns[3].dispatchEvent({ type: 'click' }); + uiStore.flushSync?.(); + assert.equal(thirdNavBar.style.getPropertyValue('--active-third-index'), '3'); + + // 6. LiveActivityWidget wraps .live-sub-list inside CustomScrollbar (.live-sub-scroll-host) with zero native scrollbars + const liveWidget = LiveActivityWidget({ defaultExpandRunningSubs: true }); + liveWidget.refs.update({ + items: [ + { + cascadeId: 'conv-swarm-1', + title: 'Swarm Run', + isMainRunning: true, + subagentCount: 2, + runningSubagentCount: 1, + subagents: [ + { cascadeId: 'sub-1', index: 1, role: '@entry-runtime', isRunning: true, stepCount: 17 }, + { cascadeId: 'sub-2', index: 2, role: '@config-state', isRunning: false, stepCount: 7 }, + ], + }, + ], + }); + const scrollHost = liveWidget.el.querySelector('.live-sub-scroll-host'); + assert.ok(scrollHost, 'Subagent list is wrapped in CustomScrollbar .live-sub-scroll-host'); + assert.equal(scrollHost.hasAttribute('hidden'), false); + assert.ok(scrollHost.querySelector('.scrollbar-rail'), 'CustomScrollbar rail is mounted'); + assert.equal(liveWidget.el.querySelector('.live-sub-list').hasAttribute('hidden'), false); + liveWidget.destroy(); + + // 7. ConsumptionView places '周期' ('cycle') before '今天' ('today'), while defaulting active selection to 'today' + assert.equal(telemetryStore.getState().selectedTimeRange, 'today'); + setI18nLanguage('zh-CN'); + const consView = ConsumptionView({}); + const rangeBtns = consView.el.querySelector('.cons-overview-head').querySelectorAll('.seg-btn'); + assert.equal(rangeBtns[0].getAttribute('data-seg-value'), 'cycle'); + assert.equal(rangeBtns[0].textContent, '周期'); + assert.equal(rangeBtns[1].getAttribute('data-seg-value'), 'today'); + assert.equal(rangeBtns[1].textContent, '今天'); + assert.equal(rangeBtns[0].classList.contains('is-active'), false); + assert.equal(rangeBtns[1].classList.contains('is-active'), true, 'Default active range remains today'); + consView.destroy(); + + // 8. StepsDetailView inlineScopeSelect ('全部汇总') omits unnecessary leading SVG icon + const stepsView = StepsDetailView({}); + const scopeTriggerChildren = stepsView.refs.inlineScopeSelect.refs.triggerBtn.children; + assert.equal( + scopeTriggerChildren[0].hasAttribute('hidden'), + true, + 'inlineScopeSelect leading SVG icon is hidden' + ); + stepsView.destroy(); + + // 9. StepTableWidget animates ONLY genuinely newly added steps in Modern UI, never on initial load, filter change, classic UI, or conversation switch + const stepTable = StepTableWidget({}); + const cols = ['step', 'model', 'tokens_combo']; + const s1 = { stepIndex: 1, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 100 }; + const s2Sub = { + stepIndex: 1, + agentCascadeId: 'sub-1', + isSubagent: true, + agentId: 'sub-1', + modelShort: '4-carbon', + inputTokens: 80, + }; + const s2Main = { stepIndex: 2, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 200 }; + + // Initial load (conv-a, filtered to main only, while allConversationSteps has s2Sub too) -> 0 entering rows + stepTable.refs.renderStepTable([s2Main, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s2Main, s2Sub, s1], + allowNewRowFade: true, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Initial render must never animate existing rows' + ); + + // Filter change reveals existing s2Sub -> 0 entering rows ("而且不是查看其他记录") + stepTable.refs.renderStepTable([s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s2Main, s2Sub, s1], + allowNewRowFade: false, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Revealing existing subagent steps via filter must not animate' + ); + + // Classic UI (allowNewRowFade: false) when step #3 arrives -> 0 entering rows ("只有新ui才有这个动画") + const s3Classic = { stepIndex: 3, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 300 }; + stepTable.refs.renderStepTable([s3Classic, s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s3Classic, s2Main, s2Sub, s1], + allowNewRowFade: false, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Classic UI must not animate newly added step rows' + ); + + // Modern UI live update (allowNewRowFade: true) when step #4 arrives -> ONLY row 0 (#4) gets is-step-entering + const s4New = { stepIndex: 4, agentCascadeId: 'conv-a', modelShort: '4-carbon', inputTokens: 400 }; + stepTable.refs.renderStepTable([s4New, s3Classic, s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s4New, s3Classic, s2Main, s2Sub, s1], + allowNewRowFade: true, + }); + assert.equal(stepTable.refs.stepsTbody.children[0].classList.contains('is-step-entering'), true); + assert.equal(stepTable.refs.stepsTbody.children[1].classList.contains('is-step-entering'), false); + + // Bubbled animationend from a child must NOT cut off the highlight fade prematurely + const enteringRow = stepTable.refs.stepsTbody.children[0]; + enteringRow.onanimationend?.({ target: enteringRow.children[0] }); + assert.equal( + enteringRow.classList.contains('is-step-entering'), + true, + 'Child td animationend must not prematurely strip is-step-entering from tr' + ); + + // Clear animationend on row 0 itself, then streaming update to step #4 arrives -> must NOT re-trigger fade-in + enteringRow.onanimationend?.({ target: enteringRow }); + assert.equal(enteringRow.classList.contains('is-step-entering'), false); + const s4Updated = { ...s4New, outputTokens: 520 }; + stepTable.refs.renderStepTable([s4Updated, s3Classic, s2Main, s2Sub, s1], 'conv-a', cols, 'zh-CN', { + allConversationSteps: [s4Updated, s3Classic, s2Main, s2Sub, s1], + allowNewRowFade: true, + }); + assert.equal( + stepTable.refs.stepsTbody.children[0].classList.contains('is-step-entering'), + false, + 'In-place streaming update of an already seen step must not re-animate' + ); + + // Switching to another conversation ('conv-b') -> 0 entering rows + const otherConvStep = { stepIndex: 99, agentCascadeId: 'conv-b', modelShort: '4-carbon', inputTokens: 50 }; + stepTable.refs.renderStepTable([otherConvStep], 'conv-b', cols, 'zh-CN', { + allConversationSteps: [otherConvStep], + allowNewRowFade: true, + }); + assert.equal( + stepTable.refs.stepsTbody.children.some((tr) => tr.classList.contains('is-step-entering')), + false, + 'Switching conversation must not trigger row fade-in' + ); + stepTable.destroy(); + + // 10. TrendAreaChart tooltip arms 0.15s .is-tracking transition after initial snap and translates --tip-y smoothly + const trendChart = createTrendAreaChart(); + Object.assign(trendChart.el, { offsetHeight: 210 }); + const tipEl = trendChart.el.querySelector('.trend-tooltip'); + Object.assign(tipEl, { offsetHeight: 82 }); + trendChart.update([ + { index: 0, label: '00:00', fullLabel: '11月19日 00:00 - 01:00', tokens: 1000, calls: 2, costUsd: 0.1 }, + { index: 1, label: '10:00', fullLabel: '11月19日 10:00 - 11:00', tokens: 25_000_000, calls: 80, costUsd: 6.37 }, + ]); + const ticks = trendChart.el.querySelectorAll('.trend-x-tick'); + queuedRaf = null; + ticks[0].onclick(); // low valley -> --tip-y = 0px, initial snap has is-tracking = false + assert.equal(tipEl.style.getPropertyValue('--tip-y'), '0px'); + assert.equal(tipEl.classList.contains('is-tracking'), false); + queuedRaf?.(); + assert.equal(tipEl.classList.contains('is-tracking'), true); + + ticks[1].onclick(); // high peak -> --tip-y = 210 - 82 - 22 = 106px while is-tracking remains true + assert.equal(tipEl.style.getPropertyValue('--tip-y'), '106px'); + assert.equal(tipEl.classList.contains('is-tracking'), true); + trendChart.destroy(); + + // 11. ContextWindowWidget + LiveActivityWidget use pure SVG chevrons and animate expand/collapse under [data-modern-ui="true"] + document.documentElement.setAttribute('data-modern-ui', 'true'); + const ctxWidget = ContextWindowWidget({}); + document.body.appendChild(ctxWidget.el); + const subAgents = Array.from({ length: 8 }, (_, idx) => ({ + agentId: `sub-${idx + 1}`, + cascadeId: `sub-${idx + 1}`, + index: idx + 1, + agentKind: 'swarm_worker', + agentOrdinal: idx + 1, + isMain: false, + stepCount: 5, + context: { usedPct: 15 + idx }, + })); + ctxWidget.refs.update({ + data: { + settings: { language: 'zh-CN' }, + activeConversation: { + cascadeId: 'conv-ctx-anim', + hasSubagents: true, + agents: [ + { agentId: 'main', cascadeId: 'conv-ctx-anim', isMain: true, stepCount: 10, context: { usedPct: 40 } }, + ...subAgents, + ], + aggregated: { activeAgentId: 'main', activeAgentKind: 'main' }, + }, + }, + }); + + const moreBtn = ctxWidget.el.querySelector('.ctx-agent-pill.is-more-toggle'); + assert.ok(moreBtn, 'Overflowing agent pills render .is-more-toggle pill'); + assert.doesNotMatch(moreBtn.textContent, /[▾▴▸]/, 'Zero Unicode arrow characters in toggle text'); + assert.equal(moreBtn.querySelector('.ctx-toggle-chevron')?.hasAttribute('hidden'), false); + assert.equal(moreBtn.classList.contains('is-expanded'), false); + + const inspectorBar = ctxWidget.el.querySelector('.ctx-inspector-bar'); + const pillGroup = ctxWidget.el.querySelector('.ctx-pill-group'); + Object.assign(inspectorBar, { offsetHeight: 22 }); + Object.assign(pillGroup, { offsetHeight: 74 }); + + moreBtn.onclick(); // Expand + assert.equal(inspectorBar.style.height, '74px'); + const collapseBtn = ctxWidget.el.querySelector('.ctx-agent-pill.is-more-toggle'); + assert.equal(collapseBtn.textContent, '收起'); + assert.equal(collapseBtn.classList.contains('is-expanded'), true); + inspectorBar.ontransitionend?.({ target: inspectorBar }); + assert.equal(inspectorBar.style.height, ''); + + // Collapse back smoothly + Object.assign(inspectorBar, { offsetHeight: 74 }); + Object.assign(pillGroup.children[0], { offsetHeight: 22, offsetTop: 0 }); + collapseBtn.onclick(); + assert.equal(collapseBtn.classList.contains('is-expanded'), false); + assert.equal(inspectorBar.style.height, '22px'); + inspectorBar.ontransitionend?.({ target: inspectorBar }); + assert.equal(inspectorBar.style.height, ''); + ctxWidget.destroy(); + + // LiveActivityWidget SVG chevron + smooth collapse/expand under [data-modern-ui="true"] + const animLive = LiveActivityWidget({ defaultExpandRunningSubs: true }); + document.body.appendChild(animLive.el); + animLive.refs.update({ + items: [ + { + cascadeId: 'conv-live-anim', + title: 'Swarm Session', + isMainRunning: true, + subagentCount: 2, + swarmCount: 2, + runningSubagentCount: 0, + subagents: [ + { cascadeId: 'sw-1', index: 1, agentKind: 'swarm_worker', role: '@w1', isRunning: false, stepCount: 4 }, + { cascadeId: 'sw-2', index: 2, agentKind: 'swarm_worker', role: '@w2', isRunning: false, stepCount: 6 }, + ], + }, + ], + }); + const liveToggleBtn = animLive.el.querySelector('.live-sub-toggle'); + const liveScrollHost = animLive.el.querySelector('.live-sub-scroll-host'); + assert.equal(liveToggleBtn.textContent, '蜂群 (2)'); + assert.ok(liveToggleBtn.querySelector('.live-sub-toggle-chevron')); + assert.equal(liveToggleBtn.classList.contains('is-expanded'), false); + + Object.assign(liveScrollHost, { offsetHeight: 64, scrollHeight: 64 }); + liveToggleBtn.onclick({ stopPropagation() {} }); // Expand + assert.equal(liveToggleBtn.classList.contains('is-expanded'), true); + assert.equal(liveScrollHost.hasAttribute('hidden'), false); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), true); + assert.equal(liveScrollHost.style.height, '64px'); + // Opacity finishes earlier than height -> must NOT cut off height transition early + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'opacity' }); + assert.equal(liveScrollHost.style.height, '64px'); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), true); + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'height' }); + assert.equal(liveScrollHost.style.height, ''); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), false); + + liveToggleBtn.onclick({ stopPropagation() {} }); // Collapse + assert.equal(liveToggleBtn.classList.contains('is-expanded'), false); + assert.equal(liveScrollHost.style.height, '0px'); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), true); + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'opacity' }); + assert.equal(liveScrollHost.hasAttribute('hidden'), false); + liveScrollHost.ontransitionend?.({ target: liveScrollHost, propertyName: 'height' }); + assert.equal(liveScrollHost.hasAttribute('hidden'), true); + assert.equal(liveScrollHost.classList.contains('is-sub-animating'), false); + animLive.destroy(); + document.documentElement.removeAttribute('data-modern-ui'); +}); diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index 397536c..ea372dc 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -649,4 +649,17 @@ test('per-pool cycle5h and cycleWeekly isolate each pool by its own reset window p.quotas.weekly.costUsd, +(geminiPool.cycleWeekly.costUsd + argonPool.cycleWeekly.costUsd + claudePool.cycleWeekly.costUsd).toFixed(2) ); + + // Consumption preset 'cycle' and selected range 'cycle' match quotas.weekly across heterogeneous pool reset windows + assert.equal(p.consumption.presets.cycle.account.calls, 5); + assert.equal(p.consumption.presets.cycle.account.totalTokens, 155_000); + + const pCycle = await h.buildTelemetryPayloadInternal('multiCycleConv', false, { range: 'cycle' }); + assert.equal(pCycle.consumption.selectedRange.key, 'cycle'); + assert.equal(pCycle.consumption.account.calls, 5); + assert.equal(pCycle.consumption.account.totalTokens, 155_000); + const cycleModelsTok = pCycle.modelBreakdown.reduce((sum, m) => sum + m.totalTokens, 0); + assert.equal(cycleModelsTok, 155_000); + const cycleSourcesTok = pCycle.consumption.sourcesBreakdown.reduce((sum, s) => sum + s.totalTokens, 0); + assert.equal(cycleSourcesTok, 155_000); }); diff --git a/sidecars/panel/test/swarm-mode.test.mjs b/sidecars/panel/test/swarm-mode.test.mjs index 85c519e..9620ae1 100644 --- a/sidecars/panel/test/swarm-mode.test.mjs +++ b/sidecars/panel/test/swarm-mode.test.mjs @@ -1152,7 +1152,11 @@ test('Frontend Swarm formatters, bilingual i18n, LiveActivityWidget priority sor liveWidget.refs.pauseTicker(); const toggleBtn = liveWidget.el.querySelector('.live-sub-toggle'); - assert.equal(toggleBtn?.textContent, '蜂群 1/4 ▾'); + assert.equal(toggleBtn?.textContent, '蜂群 1/4'); + assert.ok( + toggleBtn?.querySelector('.live-sub-toggle-chevron'), + 'Swarm toggle button renders pure vector SVG chevron icon' + ); const hereTag = liveWidget.el.querySelector('.wm-session-tag.is-here'); assert.ok(hereTag && !hereTag.hasAttribute('hidden'), 'Child worker host route must light up is-here tag'); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 1ee6537..b4fe942 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -1370,11 +1370,29 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(structurePane.hasAttribute('hidden'), true); assert.equal(otherPane.hasAttribute('hidden'), true); - // --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, pluginUpdateMode) --- + // --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, modernUiSwitch, pluginUpdateMode) --- const generalSegControls = generalPane.querySelectorAll('.segmented'); - assert.equal(generalSegControls.length, 2, 'General tab has Language and FontScale segmented controls'); + assert.equal( + generalSegControls.length, + 3, + 'General tab has Language, FontScale, and Experimental Modern UI segmented controls' + ); 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 关闭 / 开启'); + + modernUiBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + 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'); @@ -2053,10 +2071,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro 'Heatmap palette uses unified project blue tokens instead of hardcoded green' ); - // Click '全部' (option index 5 in ConsumptionView timeFilterSwitch) to load 120-day series + // Click '全部' ('all' in ConsumptionView timeFilterSwitch) to load 120-day series const consPane = allPanes[1]; const consTimeSegBtns = consPane.querySelectorAll('.seg-btn'); - consTimeSegBtns[5].dispatchEvent({ type: 'click', stopPropagation() {} }); + const allRangeBtn = + consTimeSegBtns.find((btn) => btn.getAttribute('data-seg-value') === 'all') || + consTimeSegBtns[6]; + allRangeBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 35)); assert.equal(plotStageEl.hasAttribute('hidden'), true, 'Line chart hidden when trend exceeds 90 days');