(() => { '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, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, 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, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, ACCOUNT_QUOTA_REFRESH_MINUTES, DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, normalizeAccountQuotaRefreshMinutes, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']); const THEME_ACCENT_KEYS = Object.freeze([ 'host', 'blue', 'emerald', 'amber', 'violet', 'cyan', 'rose', ]); const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']); const TOPBAR_SLOT_KEYS = Object.freeze([ 'context', 'tps', 'ttft', 'avg_tps', 'cost', 'session_cost', 'cache_hit', 'session_tokens', 'quota_auto', 'gemini_5h', 'gemini_weekly', 'argon_weekly', 'claude_5h', 'claude_weekly', ]); const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); const MIN_TOPBAR_SLOTS = 1; const MAX_TOPBAR_SLOTS = 5; const DEFAULT_CLI_STATUSLINE_SLOTS = Object.freeze([ 'tps', 'ttft', 'session_cost', 'quota_auto', 'context', ]); const MIN_CLI_STATUSLINE_SLOTS = 1; const MAX_CLI_STATUSLINE_SLOTS = 6; const CLI_STATUSLINE_PRESETS = Object.freeze({ compact: Object.freeze(['tps', 'ttft', 'context']), balanced: DEFAULT_CLI_STATUSLINE_SLOTS, full: Object.freeze(['tps', 'ttft', 'cache_hit', 'session_cost', 'quota_auto', 'context']), }); const OVERVIEW_MODULE_KEYS = Object.freeze([ 'metrics', 'context', 'quotas', 'live_tasks', ]); const DEFAULT_OVERVIEW_MODULES = Object.freeze([ 'metrics', 'context', 'quotas', 'live_tasks', ]); const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']); const OVERVIEW_METRIC_KEYS = Object.freeze([ 'tps', 'ttft', 'avg_tps', 'step_cost', 'session_cost', 'cache_hit', 'session_tokens', 'context_usage', 'quota_tightest', ]); const DEFAULT_OVERVIEW_METRICS = Object.freeze([ 'tps', 'ttft', 'avg_tps', 'step_cost', ]); const STEP_TABLE_COLUMN_KEYS = Object.freeze([ 'step', 'time', 'model', 'tps', 'ttft', 'duration', 'tokens_combo', 'tokens_io_cache', 'tokens_custom', 'input_tokens', 'cache_tokens', 'output_tokens', 'cache', 'cost', ]); const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([ 'step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost', ]); const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache'; const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({ context: 'context', ctx: 'context', '上下文': 'context', in: 'in', new: 'in', input: 'in', '输入': 'in', '新输入': 'in', out: 'out', output: 'out', '输出': 'out', '总输出': 'out', cache: 'cache', cached: 'cache', cache_read: 'cache', cacheread: 'cache', '缓存': 'cache', '缓存读': 'cache', think: 'think', thinking: 'think', '思考': 'think', reply: 'reply', body: 'reply', resp: 'reply', response: 'reply', text: 'reply', '正文': 'reply', '回复': 'reply', total: 'total', all: 'total', sum: 'total', '总计': 'total', '总token': 'total', }); const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']); const MIN_POPOVER_WIDTH = 440; const MAX_POPOVER_WIDTH = 1080; const DEFAULT_POPOVER_WIDTH = 580; /** * 归一化界面语言枚举(默认 `'auto'`,支持 `'zh-CN'` 及 `'en-US'`)。 * * @param {unknown} lang * @returns {'auto'|'zh-CN'|'en-US'} */ function normalizeLanguageSetting(lang) { const raw = String(lang ?? '').trim(); if (!raw) return 'auto'; const lower = raw.toLowerCase(); if (lower === 'auto' || lower === 'system') return 'auto'; if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; return 'auto'; } /** * 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。 * * @param {unknown} accent * @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'} */ function normalizeThemeAccent(accent) { const clean = String(accent ?? '').trim().toLowerCase(); return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host'; } /** * 归一化面板字号档位(默认 `'md'` 标准 100%)。 * * @param {unknown} scale * @returns {'sm'|'md'|'lg'|'xl'} */ function normalizeFontScale(scale) { const clean = String(scale ?? '').trim().toLowerCase(); return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md'; } /** * 归一化模型名称展示模式(`'short'` | `'upstream_compact'` | `'upstream'`),兼容历史 `showUpstreamModel`。 * * @param {unknown} mode * @param {unknown} [legacyShowUpstream] * @returns {'short'|'upstream_compact'|'upstream'} */ function normalizeModelDisplayMode(mode, legacyShowUpstream) { const m = String(mode ?? '').trim().toLowerCase(); if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream'; if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') { return 'upstream_compact'; } if (m === 'short') return 'short'; if (legacyShowUpstream === true) return 'upstream'; return 'short'; } /** * 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` vs `'full'`,默认 `'compact'`)。 * * @param {unknown} mode * @returns {'compact'|'full'} */ function normalizeOrchestratorIdMode(mode) { return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact'; } /** * 归一化悬浮主面板宽度模式(`'auto'` | `'custom'`,默认 `'auto'`)。 * * @param {unknown} mode * @returns {'auto'|'custom'} */ function normalizePopoverWidthMode(mode) { const m = String(mode ?? '').trim().toLowerCase(); return m === 'custom' || m === 'fixed' ? 'custom' : 'auto'; } /** * 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。 * * @param {unknown} width * @returns {number} */ function normalizePopoverWidth(width) { const num = Number(width); if (!Number.isFinite(num) || num <= 0) return DEFAULT_POPOVER_WIDTH; return Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(num))); } /** * 解析步骤表自定义 Token 组合表达式,支持 `:`、`/`、`,`、`|` 分隔与中英文别名(1~4 项不重复)。 * * @param {unknown} raw * @returns {Array<'context'|'in'|'out'|'cache'|'think'|'reply'|'total'>} */ function parseStepTokenComboSegments(raw) { const str = String(raw ?? '').trim(); const out = []; const seen = new Set(); if (str) { for (const part of str.split(/[:/,|]+/)) { const key = part.trim().toLowerCase(); if (!key) continue; const mapped = Object.prototype.hasOwnProperty.call(STEP_TOKEN_SEGMENT_ALIASES, key) ? STEP_TOKEN_SEGMENT_ALIASES[key] : null; if (!mapped || seen.has(mapped)) continue; seen.add(mapped); out.push(/** @type {any} */ (mapped)); if (out.length >= 4) break; } } return out.length > 0 ? out : ['context', 'in', 'cache']; } /** * 归一化步骤表自定义 Token 组合格式字符串(如 `'context:new:cache'` -> `'context:in:cache'`)。 * * @param {unknown} raw * @returns {string} */ function normalizeStepTokenComboFormat(raw) { return parseStepTokenComboSegments(raw).join(':'); } /** * 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。 * * @param {unknown} mode * @param {unknown} [legacyAutoUpdate] * @returns {'off'|'manual'|'auto'} */ function normalizePluginUpdateMode(mode, legacyAutoUpdate) { const m = String(mode ?? '').trim().toLowerCase(); if (m === 'off' || m === 'manual' || m === 'auto') return m; if (legacyAutoUpdate === true) return 'auto'; return 'manual'; } /** * 归一化面板挂载方式枚举(`'dual'` | `'composer'` | `'sidebar'`),兼容历史 `enableWindowOverlay`。 * * @param {unknown} mode * @param {unknown} [legacyEnableOverlay] * @returns {'dual'|'composer'|'sidebar'} */ function normalizeWindowMountMode(mode, legacyEnableOverlay) { const m = String(mode ?? '').trim().toLowerCase(); if (m === 'composer' || m === 'input') return 'composer'; if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar'; if (m === 'dual' || m === 'topbar') return 'dual'; if (legacyEnableOverlay === false) return 'sidebar'; return 'dual'; } /** * 归一化每周额度统计模式枚举(`'official'` | `'custom_tokens'` | `'custom_cost'`)。 * * @param {unknown} mode * @returns {'official'|'custom_tokens'|'custom_cost'} */ function normalizeWeeklyLimitMode(mode) { const m = String(mode || '').trim().toLowerCase(); if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens'; if (m === 'custom_cost' || m === 'cost') return 'custom_cost'; return 'official'; } /** * 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。 * * @param {unknown} raw * @returns {string[]} */ function normalizeTopbarCapsuleSlots(raw) { if (!Array.isArray(raw)) { return [...DEFAULT_TOPBAR_SLOTS]; } const seen = new Set(); const out = []; for (const item of raw) { const val = String(item ?? '').trim(); if (!val || val === 'none') continue; const mapped = val === 'step_cost' ? 'cost' : val; if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue; seen.add(mapped); out.push(mapped); if (out.length >= MAX_TOPBAR_SLOTS) break; } if (out.length < MIN_TOPBAR_SLOTS) { return ['context']; } return out; } /** * 归一化 CLI 底部状态栏独立槽位配置(`null` 表示自动跟随宽屏默认或自定义顶栏槽位; * 支持预设名 `compact` / `balanced` / `full`、逗号分隔列表或数组,保留 1~6 个去重合法槽位)。 * * @param {unknown} raw * @returns {string[]|null} */ function normalizeCliStatusLineSlots(raw) { if (raw === undefined || raw === null) return null; let items = null; if (typeof raw === 'string') { const clean = raw.trim(); const lower = clean.toLowerCase(); if (!clean || lower === 'auto' || lower === 'default') { return null; } if (Object.prototype.hasOwnProperty.call(CLI_STATUSLINE_PRESETS, lower)) { return [...CLI_STATUSLINE_PRESETS[lower]]; } items = clean.split(/[\s,|:]+/); } else if (Array.isArray(raw)) { items = raw; } else { return null; } const seen = new Set(); const out = []; for (const item of items) { const val = String(item ?? '').trim(); if (!val || val === 'none') continue; const mapped = val === 'step_cost' ? 'cost' : val; if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue; seen.add(mapped); out.push(mapped); if (out.length >= MAX_CLI_STATUSLINE_SLOTS) break; } return out.length >= MIN_CLI_STATUSLINE_SLOTS ? out : null; } /** * 解析当前生效的 CLI 底栏槽位列表: * 1. 若用户显式设置了 `cliStatusLineSlots`,优先使用; * 2. 若用户自定义了非默认 `topbarCapsuleSlots`,沿用其自定义顺序保持兼容; * 3. 否则采用面向宽终端的 5 槽默认组合(速度 / 首字 / 费用 / 配额 / 上下文)。 * * @param {object|null|undefined} settings * @returns {string[]} */ function resolveEffectiveCliStatusLineSlots(settings) { const customCli = normalizeCliStatusLineSlots(settings?.cliStatusLineSlots); if (customCli && customCli.length > 0) { return customCli; } const topbar = normalizeTopbarCapsuleSlots(settings?.topbarCapsuleSlots); const isDefaultTopbar = topbar.length === DEFAULT_TOPBAR_SLOTS.length && topbar.every((k, i) => k === DEFAULT_TOPBAR_SLOTS[i]); if (!isDefaultTopbar) { return topbar; } return [...DEFAULT_CLI_STATUSLINE_SLOTS]; } /** * 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。 * * @param {unknown} raw * @returns {string[]} */ function normalizeOverviewMetrics(raw) { if (!Array.isArray(raw)) { return [...DEFAULT_OVERVIEW_METRICS]; } const seen = new Set(); const out = []; for (const item of raw) { const rawVal = String(item ?? '').trim(); const val = rawVal === 'cost' ? 'step_cost' : rawVal; if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue; seen.add(val); out.push(val); if (out.length >= 4) break; } return out.length > 0 ? out : ['tps']; } /** * 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。 * * @param {unknown} raw * @returns {string[]} */ function normalizeOverviewModules(raw) { if (!Array.isArray(raw)) { return [...DEFAULT_OVERVIEW_MODULES]; } const seen = new Set(); const out = []; for (const item of raw) { const val = String(item ?? '').trim(); if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; seen.add(val); out.push(val); if (out.length >= OVERVIEW_MODULE_KEYS.length) break; } return out.length > 0 ? out : ['metrics']; } /** * 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。 * * @param {unknown} raw * @returns {string[]} */ function normalizeHoverModules(raw) { if (!Array.isArray(raw)) { return [...DEFAULT_HOVER_MODULES]; } const seen = new Set(); const out = []; for (const item of raw) { const val = String(item ?? '').trim(); if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; seen.add(val); out.push(val); if (out.length >= OVERVIEW_MODULE_KEYS.length) break; } return out; } /** * 归一化调用明细「按步查看」表格列配置与左右顺序(2~14 列,默认保留现有 7 列)。 * * @param {unknown} raw * @returns {string[]} */ function normalizeStepTableColumns(raw) { if (!Array.isArray(raw)) { return [...DEFAULT_STEP_TABLE_COLUMNS]; } const seen = new Set(); const out = []; for (const item of raw) { const val = String(item ?? '').trim(); if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue; seen.add(val); out.push(val); if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break; } if (out.length < 2) { for (const fallbackCol of ['step', 'model', 'tps']) { if (!seen.has(fallbackCol)) { seen.add(fallbackCol); out.push(fallbackCol); } if (out.length >= 2) break; } } return out; } /** * 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。 * * @param {unknown} port * @returns {number} */ function normalizeStandalonePort(port) { const num = Number(port); if (!Number.isInteger(num) || num <= 0) return 0; if (num >= 1024 && num <= 65535) return num; return 0; } /** * 归一化现代化 UI 开关(默认 `true`)。 * * @param {unknown} val * @returns {boolean} */ function normalizeModernUi(val) { if (val === undefined || val === null || val === '') return true; if (typeof val === 'string') { const lower = val.trim().toLowerCase(); if (lower === 'false' || lower === '0' || lower === 'off') return false; if (lower === 'true' || lower === '1' || lower === 'on') return true; return true; } return Boolean(val); } const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']); const DEFAULT_CONTEXT_AGENT_MODE = 'main'; const ACCOUNT_QUOTA_REFRESH_MINUTES = Object.freeze([10, 30, 60, 180, 360, 720, 1440]); const DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES = 60; /** * 归一化非当前账号的后台配额刷新间隔(分钟,默认 `60` 即 1 小时)。 * * @param {unknown} raw * @returns {10|30|60|180|360|720|1440} */ function normalizeAccountQuotaRefreshMinutes(raw) { const num = Number(raw); return ACCOUNT_QUOTA_REFRESH_MINUTES.includes(num) ? /** @type {any} */ (num) : DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES; } /** * 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'main'` 锁定主代理,可选 `'auto'` 跟随活跃)。 * * @param {unknown} raw * @returns {'main'|'auto'} */ function normalizeContextAgentMode(raw) { const val = String(raw || '').trim().toLowerCase(); return val === 'auto' ? 'auto' : 'main'; } /** * 归一化配额预占估算开关(默认 `true`)。 * * @param {unknown} val * @returns {boolean} */ function normalizeExperimentalQuotaReservation(val) { if (val === undefined || val === null || val === '') return true; if (typeof val === 'string') { const lower = val.trim().toLowerCase(); if (lower === 'false' || lower === '0' || lower === 'off') return false; if (lower === 'true' || lower === '1' || lower === 'on') return true; return true; } return Boolean(val); } /** * 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。 * * @param {unknown} val * @returns {boolean} */ 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, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, 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, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, ACCOUNT_QUOTA_REFRESH_MINUTES, DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, normalizeAccountQuotaRefreshMinutes, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { /** * @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。 */ const THIRD_PARTY_POOL_RE = /3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i; /** * 判断模型或配额桶文本是否归属第三方模型池(Claude & GPT / OSS / 3P)。 * * @param {unknown} text * @returns {boolean} */ function isThirdPartyPoolText(text) { return THIRD_PARTY_POOL_RE.test(String(text || '')); } /** * 输出速度四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。 */ function classifySpeedTier(tokPerSec) { if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) { return 'muted'; } const v = Number(tokPerSec); if (v >= 60) return 'good'; if (v >= 35) return 'info'; if (v >= 20) return 'warn'; return 'danger'; } /** * 缓存命中率四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。 */ function classifyCacheTier(cacheHitPct, promptTokens = null) { if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) { return 'muted'; } const v = Number(cacheHitPct); if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) { return 'muted'; } if (v >= 85) return 'good'; if (v >= 65) return 'info'; if (v >= 30) return 'warn'; return 'danger'; } /** * 单步费用告警色阶分类(`''|'warn'|'danger'`)。 */ function classifyStepCostTier(costUsd) { if (costUsd == null || !Number.isFinite(Number(costUsd))) return ''; const v = Number(costUsd); if (v >= 0.3) return 'danger'; if (v >= 0.15) return 'warn'; return ''; } /** * 首字延迟告警色阶分类(`'muted'|''|'warn'|'danger'`)。 */ function classifyTtftTier(ttftSec) { if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) { return 'muted'; } const v = Number(ttftSec); if (v >= 30) return 'danger'; if (v >= 18) return 'warn'; return ''; } function formatCompactTokens(num) { const n = Number(num || 0); if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; return String(Math.round(n)); } function formatCompactCapsuleCost(costUsd) { if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--'; const val = Math.max(0, Number(costUsd)); if (val === 0) return '$0.00'; if (val < 0.001) return '<$0.001'; if (val < 1) return `$${val.toFixed(3)}`; if (val < 100) return `$${val.toFixed(2)}`; return `$${Math.round(val)}`; } function formatCompactCapsuleTtft(ttftSec) { if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; const val = Number(ttftSec); if (val < 1) return `${val.toFixed(2)}s`; if (val < 100) return `${val.toFixed(1)}s`; return `${Math.round(val)}s`; } function readPoolWeeklyRemainingPct(pool) { if (!pool || typeof pool !== 'object') return null; const raw = pool.weeklyRemainingPct ?? pool.remainingWeeklyPct; return raw != null && Number.isFinite(Number(raw)) ? Number(raw) : null; } function isArgonPoolObject(pool) { if (!pool || typeof pool !== 'object') return false; if (pool.poolKey === 'Argon' || pool.family === 'Argon') return true; return /\bargon\b/i.test(String(pool.poolKey || pool.poolLabel || pool.family || '')); } /** * 判断当前配额摘要中是否存在独立的 Argon 周限配额池(如 Google AI Pro 账号)。 * * @param {object|null|undefined} quotas * @returns {boolean} */ function hasArgonWeeklyQuotaPool(quotas) { if (!quotas || typeof quotas !== 'object') return false; const pools = Array.isArray(quotas.pools) ? quotas.pools : []; const argonPool = pools.find(isArgonPoolObject); if (argonPool && readPoolWeeklyRemainingPct(argonPool) != null) { return true; } const activePool = quotas.activePool; if (activePool && isArgonPoolObject(activePool) && readPoolWeeklyRemainingPct(activePool) != null) { return true; } return false; } /** * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `argon_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 * * @param {object|null|undefined} quotas * @param {string} slotKey * @returns {number|null} */ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (!quotas || typeof quotas !== 'object') return null; const pools = Array.isArray(quotas.pools) ? quotas.pools : []; const activePool = quotas.activePool || null; const weekly = quotas.weekly || null; if (slotKey === 'quota_auto') { const candidates = []; if (activePool && Number.isFinite(Number(activePool.remainingPct))) { candidates.push(Number(activePool.remainingPct)); } const activeWk = readPoolWeeklyRemainingPct(activePool); if (activeWk != null) { candidates.push(activeWk); } if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { candidates.push(Number(weekly.remainingPct)); } if (!candidates.length && pools.length > 0) { for (const p of pools) { if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); const pWk = readPoolWeeklyRemainingPct(p); if (pWk != null) candidates.push(pWk); } } if (!candidates.length) return null; return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); } if (slotKey === 'argon_weekly') { const argonPool = pools.find(isArgonPoolObject); let argonPct = readPoolWeeklyRemainingPct(argonPool); if (argonPct == null && isArgonPoolObject(activePool)) { argonPct = readPoolWeeklyRemainingPct(activePool); } if (argonPct == null || !Number.isFinite(argonPct)) return null; return Math.max(0, Math.min(100, Math.round(argonPct))); } const isClaude = slotKey.startsWith('claude_'); const isWeekly = slotKey.endsWith('_weekly'); let rawPct = null; if (isClaude) { const claudePool = pools.find((p) => p?.poolKey === 'Claude & GPT') || pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); const cand = isWeekly ? readPoolWeeklyRemainingPct(claudePool) : claudePool?.remainingPct; if (cand != null && Number.isFinite(Number(cand))) { rawPct = Number(cand); } else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) { const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } } else { const stdGemini = pools.find((p) => p?.poolKey === 'Gemini') || pools.find( (p) => /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && !/carbon|argon/i.test(String(p?.poolKey || '')) ); const geminiFamilyPools = pools.filter((p) => /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) ); const primaryCand = isWeekly ? readPoolWeeklyRemainingPct(stdGemini) : stdGemini?.remainingPct; if (primaryCand != null && Number.isFinite(Number(primaryCand))) { rawPct = Number(primaryCand); } else { const familyVals = geminiFamilyPools .map((p) => (isWeekly ? readPoolWeeklyRemainingPct(p) : p?.remainingPct)) .filter((v) => v != null && Number.isFinite(Number(v))) .map(Number); if (familyVals.length > 0) { rawPct = Math.min(...familyVals); } else if ( activePool && !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') ) { const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } if ( rawPct == null && isWeekly && weekly && !isThirdPartyPoolText(weekly.poolFamily || '') && weekly.remainingPct != null && Number.isFinite(Number(weekly.remainingPct)) ) { rawPct = Number(weekly.remainingPct); } } } if (rawPct == null || !Number.isFinite(rawPct)) return null; return Math.max(0, Math.min(100, Math.round(rawPct))); } /** * 使用最大余数法(Hamilton 方法)将各非零分桶等比缩放至目标整数总和, * 保证 0 值通道绝不被凭空分配余数,且缩放后各分桶之和精确等于 `targetTotal`。 * * @param {Record} buckets * @param {readonly string[]} keys * @param {number} targetTotal * @returns {Record} */ function scaleBucketsExact(buckets, keys, targetTotal) { const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0))); const out = {}; let currentSum = 0; for (const k of keys) { const val = Math.max(0, Number(buckets[k] || 0)); out[k] = val; currentSum += val; } if (safeTarget === 0 || currentSum <= 0) { for (const k of keys) out[k] = 0; return out; } if (currentSum === safeTarget) { for (const k of keys) out[k] = Math.round(out[k]); return out; } const remainders = []; let assigned = 0; for (const k of keys) { const rawVal = out[k]; if (rawVal <= 0) { out[k] = 0; continue; } const exact = (rawVal * safeTarget) / currentSum; const floored = Math.floor(exact); out[k] = floored; assigned += floored; remainders.push({ key: k, rem: exact - floored, orig: rawVal }); } const diff = safeTarget - assigned; if (diff > 0 && remainders.length > 0) { remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig); for (let i = 0; i < diff; i++) { out[remainders[i % remainders.length].key] += 1; } } return out; } return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; })(); // --- shared/window-bridge-protocol.mjs --- const { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_BRIDGE_ENDPOINT_KEY, WINDOW_BRIDGE_ENDPOINT_HEADER, LOCAL_ENDPOINT_ID, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge } = (() => { const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge'; const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId'; const WINDOW_BRIDGE_ENDPOINT_KEY = 'endpointId'; const WINDOW_BRIDGE_ENDPOINT_HEADER = 'X-Usage-Monitor-Endpoint'; const LOCAL_ENDPOINT_ID = 'local'; const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay'; const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows'; const WINDOW_OVERLAY_METHODS = Object.freeze({ ensureAlive: 'ensureAlive', getDockKind: 'getDockKind', getMountMode: 'getMountMode', updateBridge: 'updateBridge', applyMountMode: 'applyMountMode', syncHostRoute: 'syncHostRoute', deliverRpc: 'deliverRpc', dispose: 'dispose', }); const BRIDGE_API_ROUTE_DEFS = Object.freeze([ Object.freeze({ path: '/api/telemetry', method: 'GET', action: 'telemetry' }), Object.freeze({ path: '/api/settings', method: 'POST', action: 'settings' }), Object.freeze({ path: '/api/accounts', method: 'GET', action: 'accounts_get' }), Object.freeze({ path: '/api/accounts/update', method: 'POST', action: 'accounts_update' }), Object.freeze({ path: '/api/context-window', method: 'POST', action: 'context_window' }), Object.freeze({ path: '/api/settings/reset', method: 'POST', action: 'settings_reset' }), Object.freeze({ path: '/api/cache/rebuild', method: 'POST', action: 'cache_rebuild' }), Object.freeze({ path: '/api/cloud-sync', method: 'POST', action: 'cloud_sync' }), Object.freeze({ path: '/api/plugin-update', method: 'POST', action: 'plugin_update' }), Object.freeze({ path: '/api/bridge/relaunch', method: 'POST', action: 'bridge_relaunch' }), Object.freeze({ path: '/api/session-migration/catalog', method: 'GET', action: 'session_migration_catalog', }), Object.freeze({ path: '/api/session-migration/migrate', method: 'POST', action: 'session_migration_migrate', }), Object.freeze({ path: '/api/export-file', method: 'POST', action: 'export_file' }), Object.freeze({ path: '/api/reveal-file', method: 'POST', action: 'reveal_file' }), Object.freeze({ path: '/api/quota-reservation/log', method: 'GET', action: 'quota_reservation_log', }), Object.freeze({ path: '/api/host-i18n', method: 'GET', action: 'host_i18n_get' }), Object.freeze({ path: '/api/host-i18n', method: 'POST', action: 'host_i18n_action' }), ]); const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); function readInjectedWindowBridge() { return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY]; } return { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_BRIDGE_ENDPOINT_KEY, WINDOW_BRIDGE_ENDPOINT_HEADER, LOCAL_ENDPOINT_ID, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge }; })(); // --- shared/host-i18n-protocol.mjs --- const { HOST_I18N_GLOBAL_KEY, HOST_I18N_API_PATH, HOST_I18N_SCHEMA_VERSION, HOST_I18N_OFF_LOCALE, HOST_I18N_DEFAULT_DEPTH, HOST_I18N_DEPTHS, HOST_I18N_LOCALE_RE, normalizeHostI18nLocale, normalizeHostI18nDepth } = (() => { /** * @fileoverview Zero-dependency shared protocol constants and normalizers * for the decoupled Antigravity Host I18n subsystem. */ const HOST_I18N_GLOBAL_KEY = '__AGUsageMonitorHostI18n'; const HOST_I18N_API_PATH = '/api/host-i18n'; const HOST_I18N_SCHEMA_VERSION = 1; const HOST_I18N_OFF_LOCALE = 'off'; const HOST_I18N_DEFAULT_DEPTH = 'light'; const HOST_I18N_DEPTHS = Object.freeze(['light', 'deep']); const HOST_I18N_LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}$/; /** * Normalizes a host translation locale identifier (`'off'` or canonical BCP-47 tag). * * @param {unknown} value * @returns {string} */ function normalizeHostI18nLocale(value) { const raw = String(value || '').trim(); if (!raw) return HOST_I18N_OFF_LOCALE; const lower = raw.toLowerCase(); if ( lower === 'off' || lower === 'none' || lower === 'disabled' || lower === 'original' || lower === 'default' ) { return HOST_I18N_OFF_LOCALE; } const normalized = raw.replace(/_/g, '-'); if (!HOST_I18N_LOCALE_RE.test(normalized)) { return HOST_I18N_OFF_LOCALE; } const parts = normalized.split('-'); return parts .map((part, idx) => { if (idx === 0) return part.toLowerCase(); if (part.length === 2) return part.toUpperCase(); if (part.length === 4) return part[0].toUpperCase() + part.slice(1).toLowerCase(); return part; }) .join('-'); } /** * Normalizes translation depth (`'light'` or `'deep'`). * * @param {unknown} value * @returns {'light'|'deep'} */ function normalizeHostI18nDepth(value) { const lower = String(value || '').trim().toLowerCase(); if (lower === 'deep' || lower === 'full') return 'deep'; return HOST_I18N_DEFAULT_DEPTH; } return { HOST_I18N_GLOBAL_KEY, HOST_I18N_API_PATH, HOST_I18N_SCHEMA_VERSION, HOST_I18N_OFF_LOCALE, HOST_I18N_DEFAULT_DEPTH, HOST_I18N_DEPTHS, HOST_I18N_LOCALE_RE, normalizeHostI18nLocale, normalizeHostI18nDepth }; })(); // --- src/icons/svgRegistry.js --- const { SVG_ICON_DEFS } = (() => { /** * @fileoverview Pure vector SVG icon registry (16x16 grid). * Strictly zero emoji characters anywhere in the codebase. */ const SVG_ICON_DEFS = Object.freeze({ pulse: [ { tag: 'path', attrs: { d: 'M1.5 8h2.5l2.2-5.5 3.6 11 2.2-5.5h2.5' } }, ], bolt: [ { tag: 'path', attrs: { d: 'M9.2 1.5L3.5 9h4.2l-.9 5.5L12.5 7H8.3l.9-5.5z' } }, ], refresh: [ { tag: 'path', attrs: { d: 'M13.5 8a5.5 5.5 0 1 1-1.4-3.7' } }, { tag: 'path', attrs: { d: 'M13.5 2.2v2.6h-2.6' } }, ], check: [ { tag: 'path', attrs: { d: 'M3 8.5l3.2 3.2L13 4.8' } }, ], warning: [ { tag: 'path', attrs: { d: 'M8 2.2L1.8 13.2h12.4L8 2.2z' } }, { tag: 'path', attrs: { d: 'M8 6.2v3.4' } }, { tag: 'circle', attrs: { cx: '8', cy: '11.5', r: '0.6', fill: 'currentColor', stroke: 'none' } }, ], 'help-circle': [ { tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } }, { tag: 'path', attrs: { d: 'M6.2 6.3a1.9 1.9 0 0 1 3.6.7c0 1.15-1.8 1.35-1.8 2.5' } }, { tag: 'circle', attrs: { cx: '8', cy: '11.8', r: '0.65', fill: 'currentColor', stroke: 'none' } }, ], 'chevron-down': [ { tag: 'path', attrs: { d: 'M4 6.2l4 4 4-4' } }, ], 'chevron-up': [ { tag: 'path', attrs: { d: 'M4 9.8l4-4 4 4' } }, ], 'chevron-right': [ { tag: 'path', attrs: { d: 'M6.2 4l4 4-4 4' } }, ], 'chevron-left': [ { tag: 'path', attrs: { d: 'M9.8 4l-4 4 4 4' } }, ], layers: [ { tag: 'path', attrs: { d: 'M8 2L2 5.2 8 8.4l6-3.2L8 2z' } }, { tag: 'path', attrs: { d: 'M2 8.2L8 11.4l6-3.2' } }, { tag: 'path', attrs: { d: 'M2 11.2L8 14.4l6-3.2' } }, ], 'chart-bar': [ { tag: 'path', attrs: { d: 'M2 13.5h12' } }, { tag: 'path', attrs: { d: 'M4.5 13.5V7.5' } }, { tag: 'path', attrs: { d: 'M8 13.5V2.5' } }, { tag: 'path', attrs: { d: 'M11.5 13.5V5.2' } }, ], table: [ { tag: 'rect', attrs: { x: '2', y: '2.5', width: '12', height: '11', rx: '1.5' } }, { tag: 'path', attrs: { d: 'M2 6.2h12' } }, { tag: 'path', attrs: { d: 'M6.2 6.2v7.3' } }, ], sliders: [ { tag: 'path', attrs: { d: 'M2 3.5h2M7 3.5h7' } }, { tag: 'path', attrs: { d: 'M2 8h7M12 8h2' } }, { tag: 'path', attrs: { d: 'M2 12.5h3.3M8.3 12.5H14' } }, { tag: 'circle', attrs: { cx: '5.5', cy: '3.5', r: '1.5' } }, { tag: 'circle', attrs: { cx: '10.5', cy: '8', r: '1.5' } }, { tag: 'circle', attrs: { cx: '6.8', cy: '12.5', r: '1.5' } }, ], calendar: [ { tag: 'rect', attrs: { x: '2.2', y: '3.2', width: '11.6', height: '10.6', rx: '1' } }, { tag: 'path', attrs: { d: 'M5.2 1.8v2.4M10.8 1.8v2.4M2.2 6.5h11.6' } }, ], clock: [ { tag: 'circle', attrs: { cx: '8', cy: '8', r: '5.8' } }, { tag: 'path', attrs: { d: 'M8 4.8v3.5l2.4 1.5' } }, ], plus: [ { tag: 'path', attrs: { d: 'M8 3.5v9M3.5 8h9' } }, ], minus: [ { tag: 'path', attrs: { d: 'M3.5 8h9' } }, ], dot: [ { tag: 'circle', attrs: { cx: '8', cy: '8', r: '5', fill: 'currentColor', stroke: 'none' } }, ], 'arrow-down': [ { tag: 'path', attrs: { d: 'M8 2.8v10.4M4.2 9.4L8 13.2l3.8-3.8' } }, ], 'arrow-up': [ { tag: 'path', attrs: { d: 'M8 13.2V2.8M4.2 6.6L8 2.8l3.8 3.8' } }, ], dock: [ { tag: 'rect', attrs: { x: '1.8', y: '2.5', width: '12.4', height: '11', rx: '1.5' } }, { tag: 'path', attrs: { d: 'M1.8 6h12.4' } }, { tag: 'path', attrs: { d: 'M9.2 4.25h3.2' } }, ], close: [ { tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } }, ], copy: [ { tag: 'rect', attrs: { x: '5.2', y: '5.2', width: '8.3', height: '8.3', rx: '1.3' } }, { tag: 'path', attrs: { d: 'M3.5 10.8H2.8a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.8 2h6.2a1.3 1.3 0 0 1 1.3 1.3v.7' } }, ], search: [ { tag: 'circle', attrs: { cx: '7.2', cy: '7.2', r: '4.5' } }, { tag: 'path', attrs: { d: 'M10.6 10.6L14 14' } }, ], download: [ { tag: 'path', attrs: { d: 'M8 2.4v7.6M5 7.2L8 10.2l3-3' } }, { tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } }, ], upload: [ { tag: 'path', attrs: { d: 'M8 10.2V2.6M5 5.4L8 2.4l3 3' } }, { tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } }, ], 'more-vertical': [ { tag: 'circle', attrs: { cx: '8', cy: '3.6', r: '1.15', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '8', cy: '8', r: '1.15', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '8', cy: '12.4', r: '1.15', fill: 'currentColor', stroke: 'none' } }, ], folder: [ { tag: 'path', attrs: { d: 'M2.2 4.3a1.3 1.3 0 0 1 1.3-1.3h3l1.3 1.5h4.7a1.3 1.3 0 0 1 1.3 1.3v5.9a1.3 1.3 0 0 1-1.3 1.3H3.5a1.3 1.3 0 0 1-1.3-1.3V4.3z', }, }, ], grip: [ { tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '6', cy: '8', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '8', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '6', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } }, ], lock: [ { tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } }, { tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.6 0V7' } }, { tag: 'circle', attrs: { cx: '8', cy: '10.5', r: '0.9', fill: 'currentColor', stroke: 'none' } }, ], unlock: [ { tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } }, { tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.3-1.2' } }, ], globe: [ { tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } }, { tag: 'ellipse', attrs: { cx: '8', cy: '8', rx: '2.7', ry: '6' } }, { tag: 'path', attrs: { d: 'M2.3 6h11.4M2.3 10h11.4' } }, ], }); return { SVG_ICON_DEFS }; })(); // --- src/icons/SvgIcon.js --- const { SVG_NS, createSvgIcon, patchSvgIcon } = (() => { /** * @fileoverview Dynamic SVG icon component and incremental icon patcher. */ const SVG_NS = 'http://www.w3.org/2000/svg'; function createSvgIcon(name, { size = 14, className = '' } = {}) { const svg = document.createElementNS(SVG_NS, 'svg'); svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('width', String(size)); svg.setAttribute('height', String(size)); svg.setAttribute('fill', 'none'); svg.setAttribute('stroke', 'currentColor'); svg.setAttribute('stroke-width', '1.5'); svg.setAttribute('stroke-linecap', 'round'); svg.setAttribute('stroke-linejoin', 'round'); svg.setAttribute('aria-hidden', 'true'); if (className) { svg.setAttribute('class', `svg-icon ${className}`.trim()); } else { svg.setAttribute('class', 'svg-icon'); } patchSvgIcon(svg, name); return svg; } function patchSvgIcon(svgEl, name) { if (!svgEl || svgEl.dataset?.iconName === name) return false; if (svgEl.dataset) { svgEl.dataset.iconName = name; } while (svgEl.firstChild) { svgEl.removeChild(svgEl.firstChild); } const shapes = SVG_ICON_DEFS[name] || SVG_ICON_DEFS.dot; for (const shape of shapes) { const child = document.createElementNS(SVG_NS, shape.tag); for (const [k, v] of Object.entries(shape.attrs)) { child.setAttribute(k, v); } svgEl.appendChild(child); } return true; } return { SVG_NS, createSvgIcon, patchSvgIcon }; })(); // --- src/core/reactive.js --- const { createReactiveStore } = (() => { /** * @fileoverview Fine-grained reactive store with async microtask batching * and structural slice comparison to prevent full-page re-renders. */ const pendingJobs = new Set(); let isFlushPending = false; function scheduleAsyncJob(job) { pendingJobs.add(job); if (!isFlushPending) { isFlushPending = true; queueMicrotask(flushAsyncJobs); } } function flushAsyncJobs() { isFlushPending = false; const jobs = Array.from(pendingJobs); pendingJobs.clear(); for (const job of jobs) { job(); } } function isShallowEqual(a, b) { if (Object.is(a, b)) return true; if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) { return false; } if (Array.isArray(a) !== Array.isArray(b)) return false; if (Array.isArray(a)) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (!Object.is(a[i], b[i])) return false; } return true; } const keysA = Object.keys(a); const keysB = Object.keys(b); if (keysA.length !== keysB.length) return false; for (const k of keysA) { if (!Object.prototype.hasOwnProperty.call(b, k) || !Object.is(a[k], b[k])) { return false; } } return true; } function createReactiveStore(initialState) { let state = { ...initialState }; const subscribers = new Set(); function getState() { return state; } function notifyAll() { for (const sub of Array.from(subscribers)) { if (!subscribers.has(sub)) continue; const nextSlice = sub.selector(state); const equal = sub.compare(sub.lastSlice, nextSlice); if (!equal) { const prevSlice = sub.lastSlice; sub.lastSlice = nextSlice; sub.listener(nextSlice, prevSlice); } } } function setState(patchOrUpdater, { sync = false } = {}) { const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater; if (!patch || typeof patch !== 'object') return; let changed = false; const nextState = { ...state }; for (const [k, v] of Object.entries(patch)) { if (!Object.is(state[k], v)) { nextState[k] = v; changed = true; } } if (!changed) { return; } state = nextState; if (sync) { notifyAll(); } else { scheduleAsyncJob(notifyAll); } } function subscribe(selector, listener, { immediate = true, compare = isShallowEqual } = {}) { const initialSlice = selector(state); const sub = { selector, listener, compare, lastSlice: initialSlice, }; subscribers.add(sub); if (immediate) { listener(initialSlice, undefined); } return () => { subscribers.delete(sub); }; } return { getState, setState, subscribe, }; } return { createReactiveStore }; })(); // --- src/i18n/zh-CN.js --- const { I18N_MESSAGES_ZH_CN } = (() => { /** * @fileoverview Simplified Chinese (zh-CN) dictionary for Antigravity Usage & Speed Monitor. * Matches 100% of the existing out-of-the-box UI copy. Zero emoji characters. */ const I18N_MESSAGES_ZH_CN = Object.freeze({ // Top Navigation 'nav.overview': '实时监控', 'nav.consumption': '用量统计', 'nav.steps': '调用明细', 'nav.settings': '偏好设置', // Top Session Header 'header.followLatest': '跟随最新会话', 'header.followCurrentWindow': '跟随当前窗口会话', 'header.autoFollowBadge': '自动', 'header.currentWindowNamed': '当前窗口 ({title})', 'header.latestNamed': '最新 ({title})', 'header.lockedSession': '已锁定会话 ({id})', 'header.lockedMeta': '已锁定', 'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)', 'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)', 'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)', 'header.convCompactSubs': '{subs}子 · {total}步', 'header.convCompactSwarm': '{swarm}蜂 · {total}步', 'header.convCompactSwarmAndSubs': '{swarm}蜂{subs}子 · {total}步', 'header.convMetaSteps': '{count}步', 'header.hasUpdate': '有新版本', 'header.upgradeToVer': '升级 v{ver}', 'header.upgrading': '升级中…', 'header.ariaUpdate': '发现新版本,点击升级', 'header.ariaRefresh': '刷新数据', 'header.statusSyncing': '同步中', 'header.statusSynced': '已刷新', 'header.statusRetrying': '重试中', 'header.statusGenerating': '生成中{suffix}', 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', 'header.statusLive': '监控中', 'header.scopeAll': '全部代理', 'header.scopeAllShort': '全', 'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…', 'select.searchPlaceholder': '输入关键词筛选…', 'select.noMatches': '没有匹配的选项', 'select.clearSearch': '清空搜索', // Formatters & Common Labels 'fmt.pending': '待定', 'fmt.speedIncomplete': '计时不完整', 'fmt.speedCanceled': '已取消', 'fmt.speedError': '调用报错', 'fmt.speedInterrupted': '连接中断', 'fmt.speedCompactionTimingUnavailable': '压缩无计时', 'fmt.speedInvalidOutput': '无有效输出', 'fmt.speedInconsistent': '耗时数据异常', 'fmt.speedShort': '耗时过短 (<0.5s)', 'fmt.speedLegacy': '旧版缓存记录', 'fmt.sampleSteps': '{valid}/{total} 步', 'fmt.resetUnknown': '未知重置时间', 'fmt.resetSoon': '即将重置', 'fmt.resetUnder1m': '<1分钟后重置', 'fmt.resetDaysHours': '{d}天 {h}小时后重置', 'fmt.resetHoursMins': '{h}小时 {m}分后重置', 'fmt.resetMins': '{m}分钟后重置', 'fmt.selectTime': '选择时间', 'fmt.unknownModel': '模型未知', 'fmt.compactionSuffix': '·压缩', 'fmt.mainAgent': '主代理', 'fmt.mainBadge': '主', 'fmt.subAgent': '子代理', 'fmt.subBadge': '子{index}', 'fmt.subBadgeShort': '子', 'fmt.swarmAgent': '蜂群', 'fmt.swarmBadge': '蜂{index}', 'fmt.swarmBadgeShort': '蜂', 'fmt.swarmMonitorHint': '巡检', 'fmt.swarmNarratorHint': '旁白', 'fmt.sideQuestion': '旁路提问', 'fmt.sideBadge': '旁{index}', 'fmt.sideBadgeShort': '旁', 'fmt.selectedCount': '已选 {count} {unit}', 'fmt.selectedListTitle': '已选 ({count}):{names}', 'fmt.selectPlaceholder': '请选择', // Capsule & Multi-Session Overlay 'capsule.ariaMonitor': '用量与速度监控', 'capsule.ariaMulti': '多会话实时信息', 'capsule.multiZero': '0 运行中', 'capsule.multiRunning': '{count} 运行中', 'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子', 'capsule.multiRunningWithSwarm': '{count} 运行 · {subs} 蜂', 'capsule.tpsRunning': '生成中', 'capsule.tpsIdle': '待命', 'capsule.quotaLeft': '余 {pct}%', 'capsule.quotaUnknown': '余 --%', 'capsule.newVersion': '新版本', 'capsule.updating': '更新中…', 'capsule.ariaUpdateTitle': '发现新版本,点击立即更新', 'capsule.hoverNewVer': '发现新版本 v{ver}', 'capsule.hoverNewVerGeneric': '发现新版本可用', 'capsule.hoverUpdateHintTopbar': '点击顶栏 v{ver} 即可更新', 'capsule.hoverUpdateHintComposer': '点击版本胶囊 v{ver} 即可更新', 'capsule.hoverUpdateHintTopbarGeneric': '点击顶栏版本胶囊即可更新', 'capsule.hoverUpdateHintComposerGeneric': '点击版本胶囊即可更新', 'multi.title': '实时运行会话', 'multi.ariaDialog': '多会话实时信息面板', 'multi.pinned': '已固定', 'multi.loading': '读取中...', 'multi.empty': '当前暂无在线运行的会话', 'multi.allIdle': '全部待命', 'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中', 'multi.metaWithSwarm': '{main} 主会话 · {subs} 蜂群运行中', 'multi.metaMainOnly': '{main} 个会话运行中', 'multi.hereTag': '本窗', 'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}', // Live Overview & Widgets 'module.metrics': '实时指标', 'module.context': '上下文窗口', 'module.quotas': '可用额度', 'module.live_tasks': '实时运行任务', // Capsule Slot Metric Options 'capMetric.context': '上下文占用 (%)', 'capMetric.tps': '输出速度 (TPS)', 'capMetric.ttft': '首字延迟 (TTFT)', 'capMetric.avg_tps': '会话均速 (Avg TPS)', 'capMetric.cost': '本次费用 ($)', 'capMetric.session_cost': '会话累计费用 ($)', 'capMetric.cache_hit': '缓存命中率 (%)', 'capMetric.session_tokens': '会话总 Token', 'capMetric.quota_auto': '自动紧俏额度', 'capMetric.gemini_5h': 'Gemini 5h 额度', 'capMetric.gemini_weekly': 'Gemini 周额度', 'capMetric.argon_weekly': 'Argon 周额度', 'capMetric.claude_5h': 'Claude 5h 额度', 'capMetric.claude_weekly': 'Claude 周额度', // Overview Matrix Metric Options & Cells 'ovMetric.tps': '输出速度', 'ovMetric.ttft': '首字延迟', 'ovMetric.avg_tps': '平均速度', 'ovMetric.step_cost': '本次费用', 'ovMetric.session_cost': '累计费用', 'ovMetric.cache_hit': '缓存命中率', 'ovMetric.session_tokens': '会话 Token', 'ovMetric.context_usage': '上下文占用', 'ovMetric.quota_tightest': '紧俏额度', 'ovMetric.subAvgTtft': '均值 {val}', 'ovMetric.subAvgCache': '均值 {val}', 'ovMetric.subValidSamples': '有效 {samples}', 'ovMetric.subTotalCost': '累计 {cost}', 'ovMetric.subStepCost': '本次 {cost}', 'ovMetric.subInOutTokens': '入 {inTok} · 出 {outTok}', 'ovMetric.subCtxRatio': '{used} / {limit}', 'ovMetric.subQuotaPool': '{label}', 'ovMetric.subQuotaPending': '等待配额同步', // Context Window Widget 'ctx.followActive': '跟随活跃 ({badge})', 'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口', 'ctx.expandMore': '+{count} 展开', 'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊', 'ctx.collapse': '收起', 'ctx.collapseTitle': '折叠多余子代理胶囊', 'ctx.ch.assistant': '模型回复', 'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参', 'ctx.ch.toolResults': '工具结果', 'ctx.ch.toolResultsTitle': '文件读取、终端输出与工具执行返回内容', 'ctx.ch.userInput': '用户消息', 'ctx.ch.userInputTitle': '用户提问文本与上传附件', 'ctx.ch.subagent': '子代理通知', 'ctx.ch.subagentTitle': '子代理完成汇报与后台任务系统通知', 'ctx.ch.checkpoint': '压缩摘要', 'ctx.ch.checkpointTitle': '自动上下文压缩生成的历史摘要检查点', 'ctx.ch.systemPrompt': '系统提示词', 'ctx.ch.systemPromptTitle': '核心身份、终端沙箱、制品与环境提示词', 'ctx.ch.systemTools': '系统工具', 'ctx.ch.systemToolsTitle': '内置系统工具 Schema 定义', 'ctx.ch.mcpTools': 'MCP 工具', 'ctx.ch.mcpToolsTitle': 'MCP 外部服务工具与资源定义', 'ctx.ch.skills': 'Skill', 'ctx.ch.skillsTitle': '已挂载的 Skills 技能索引与说明', 'ctx.ch.userRules': '用户规则', 'ctx.ch.userRulesTitle': '全局与工作区自定义规则 (user_rules)', // Quota Pools Widget 'quota.weeklyShort': '周限', 'quota.weeklyPool': '周限 ({pool})', 'quota.loading': '读取中...', 'quota.failed': '获取失败 (--%)', 'quota.usedAndLeft': '{reset} · 已用 {used}%', 'quota.reservedTip': '预占估算(试验性):约 {rsv}%(实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.reservedTipMulti': '预占估算(试验性):约 {rsv}%(检测到 {leases} 笔叠加租约,实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.legendActual': '实占', 'quota.legendReserved': '预占', 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleFullSuffix': '满池约 {full}', 'quota.footTokensCustom': '本周累计: {tok} ({cost})', 'quota.footTokensCycle': '周期累计: {tok} ({cost})', 'quota.footCredits': 'AI 积分: {credits}', 'quota.footCallsCustom': '本周调用: {calls} 次', 'quota.footCallsCycle': '周期调用: {calls} 次', 'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计', 'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总', 'quota.rateHelpAria': '查看当前账号实测倍率预估', 'quota.ratePopTitle': '实测倍率预估', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': '当前账号', 'quota.ratePopPoolFallback': '池综合均值', 'quota.ratePopEq5hLabel': '5h 满池', 'quota.ratePopEqWkLabel': '周限满池', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} 样本', 'quota.ratePopPrelimSlope': '斜率初估', 'quota.ratePopPrelimCycle': '周期初估', 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。', 'quota.ratePopSharedBadge': '共享活跃', 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', 'quota.ratePopExternalBaseline': '检测到本周期存在家庭组 / 其他设备消耗,预占和费率仅按本机实测校准', 'quota.ratePopExt5h': '5h {pct}%', 'quota.ratePopExtWk': '周限 {pct}%', // Live Activity Widget 'live.currentSession': '当前会话', 'live.switchSessionTitle': '点击切换查看会话:{title}', 'live.thinking': '推理中', 'live.generating': '生成中', 'live.running': '运行中', 'live.waiting': '待命中', 'live.killed': '已终止', 'live.done': '已完成', 'live.doneWithSteps': '已完成 ({steps} 步)', 'live.waitingWithSteps': '待命中 ({steps} 步)', 'live.killedWithSteps': '已终止 ({steps} 步)', 'live.subToggleRunning': '子代理 {run}/{total}', 'live.subToggleIdle': '子代理 ({total})', 'live.swarmToggleRunning': '蜂群 {run}/{total}', 'live.swarmToggleIdle': '蜂群 ({total})', 'live.subCollapseTitle': '点击收起子代理列表', 'live.subExpandTitle': '点击展开查看子代理缩略状态', // Consumption View 'cons.rangeCycle': '周期', 'cons.cyclePoolAll': '全部池', 'cons.cyclePoolAllShort': '全部', 'cons.cyclePoolAria': '当前周期配额池筛选', 'cons.cyclePoolRemMeta': '剩 {pct}', 'cons.currentCycle': '当前周期', 'cons.cycleFallbackWeek': '本周', 'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', 'cons.range14d': '14天', 'cons.range30d': '30天', 'cons.rangeAll': '全部', 'cons.rangeCustom': '自定义', 'cons.rangeAria': '消耗统计时间范围', 'cons.applyFilter': '筛选', 'cons.rangeTo': '至', 'cons.overviewTitle': '用量总览', 'cons.totalTokens': '总 Token', 'cons.estCost': '预估费用', 'cons.cacheHitRate': '缓存命中率', 'cons.callsCount': '{calls} 次', 'cons.cacheHitTokens': '命中 {tokens}', 'cons.newInput': '新输入', 'cons.uncachedInput': '未命中缓存输入', 'cons.cacheRead': '缓存读取', 'cons.savedCost': '节省 {cost}', 'cons.outputUsage': '输出用量', 'cons.replyAndThink': '思考 {think} · 回复 {resp}', 'cons.trendTitle': '用量趋势', 'cons.allTime': '全部时间', 'cons.hmModeAria': '热力图查看维度', 'cons.hmModeDay': '日', 'cons.hmModeWeek': '周', 'cons.hmModeMonth': '月', 'cons.hmModeAll': '全部', 'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看', 'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看', 'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看', 'cons.topModels': '模型排行', 'cons.clientSources': '客户端来源', 'cons.monthlyTitle': '月度统计', 'cons.monthLabel': '{m}月', 'cons.monthFullLabel': '{year}年 {m}月', 'cons.hoverModelsHint': '悬停查看模型', 'cons.otherModelsCount': '其他 ({count})', 'cons.legInput': '输入', 'cons.legCache': '缓存', 'cons.legOutput': '输出', 'cons.legThinking': '思考', 'cons.footInput': '输入 ', 'cons.footCache': '缓存 ', 'cons.footOutput': '输出 ', 'cons.footThinking': '思考 ', 'cons.footCalls': '调用 ', 'cons.rankTabAria': '排行视图切换', 'cons.rankTabModelsCount': '模型排行 ({count})', 'cons.rankTabSessions': '会话排行', 'cons.rankTabSessionsCount': '会话排行 ({count})', 'cons.rankTabWorkspaces': '项目排行', 'cons.rankTabWorkspacesCount': '项目排行 ({count})', 'cons.workspaceUnbound': '未绑定工作区', 'cons.workspaceSessions': '{count} 会话', 'cons.exportMenuAria': '导出及报告选项', 'cons.exportXlsx': '导出 Excel (.xlsx)', 'cons.exportXlsxTip': '导出多工作表排版精美的 Excel 报表(自动列宽、千分位及对齐)', 'cons.exportCsv': '导出 CSV', 'cons.exportCsvTip': '导出当前统计区间用量明细为 CSV', 'cons.exportCsvDone': '已导出', 'cons.exportMd': '复制 Markdown 报告', 'cons.exportMdTip': '复制当前统计区间 Markdown 汇总报告', 'cons.exportMdDone': '已复制用量 Markdown 报告', 'cons.topConvsEmpty': '当前时间范围暂无会话消耗记录', 'cons.topConvsSortAria': '会话排行排序方式', 'cons.topConvsSortCost': '费用', 'cons.topConvsSortTokens': 'Token', 'cons.topConvCacheMeta': '缓存 {pct}%', 'cons.topConvJumpTip': '点击跳转到该会话调用记录', 'cons.modelsSortAria': '模型排行排序方式', 'cons.modelsSortTokens': 'Token', 'cons.modelsSortCost': '费用', 'cons.modelsSortSpeed': '均速', 'cons.modelsSortCalls': '调用', 'cons.modelUnitCost': '均价 {cost}/1M', 'cons.speedRelTip': '相对本时段最快模型的均速比例', 'cons.focusTtft': '首字 {ttft}', 'cons.focusSpeedMeta': '首字 {ttft} · 缓存 {cache}% · 输出 {out}', 'cons.focusCallsMeta': '单次均耗 {avgTok} · 费用 {cost}', // Steps Detail View & Step Column Registry 'steps.title': '调用记录', 'steps.tabSteps': '按步查看 ({count})', 'steps.tabStepsFiltered': '按步查看 ({filtered}/{total})', 'steps.tabModels': '总汇总', 'steps.allAgents': '全部汇总', 'steps.allModels': '全部模型', 'steps.selectModel': '选择模型', 'steps.unitAgent': '代理', 'steps.unitModel': '模型', 'steps.lineTitle': '会话走势', 'steps.fitTitle': '趋势拟合', 'steps.modelsTitle': '模型总览', 'steps.modelsEmpty': '当前范围暂无模型调用记录', 'steps.metricTotalTokens': '总Token', 'steps.metricContext': '上下文', 'steps.metricTps': 'TPS', 'steps.metricTtft': '首字', 'steps.metricCache': '缓存', 'steps.metricCost': '费用', 'steps.badgeBackAll': '点击切回全部汇总', 'steps.badgeFilterAgent': '点击仅过滤查看 {agent}(按住 Ctrl/Shift 可加减多选)', 'steps.ctxTitle': '上下文 {ctx} · 思考 {think} · 正文 {resp}', 'steps.ioCacheTitle': '新输入 {inPart} · 输出 {outPart} · 缓存读 {cachePart}', 'steps.tokSeg.context.th': '上下文', 'steps.tokSeg.context.tip': '上下文', 'steps.tokSeg.in.th': '输入', 'steps.tokSeg.in.tip': '新输入', 'steps.tokSeg.out.th': '输出', 'steps.tokSeg.out.tip': '输出', 'steps.tokSeg.cache.th': '缓存', 'steps.tokSeg.cache.tip': '缓存读', 'steps.tokSeg.think.th': '思考', 'steps.tokSeg.think.tip': '思考', 'steps.tokSeg.reply.th': '正文', 'steps.tokSeg.reply.tip': '正文', 'steps.tokSeg.total.th': '总计', 'steps.tokSeg.total.tip': '总计', 'steps.modelCallsShare': '{calls}次 · {pct}%', 'steps.modelCallsOnly': '{calls}次', 'steps.modelsSummaryPrefix': '{count} 模型 · ', 'steps.modelPerfFoot': '均速 {tps} · 首字 {ttft} · 缓存 {cache}%', 'steps.modelSplitFoot': '输入 {inTok} · 缓存 {cacheTok} · 思考 {thinkTok} · 输出 {respTok}', 'steps.fitActiveCardTitle': '{title}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)', 'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)', 'steps.turnMediaOnly': '[图片/附件提问]', 'steps.turnMediaSuffix': '[附图]', 'steps.anomalyTag.timeout': '超时{n}', 'steps.anomalyTag.rate_limit': '限流{n}', 'steps.anomalyTag.capacity': '503×{n}', 'steps.anomalyTag.capacitySingle': '503', 'steps.anomalyTag.disconnect': '断连{n}', 'steps.anomalyTag.upstream': '500×{n}', 'steps.anomalyTag.upstreamSingle': '500', 'steps.anomalyTag.model_output': '纠偏{n}', 'steps.anomalyTag.safety': '过滤{n}', 'steps.anomalyTag.auth_or_model': '受限{n}', 'steps.anomalyTag.error': '报错{n}', 'steps.anomalyTag.mixed': '异常{n}', 'steps.anomalyKind.timeout': '流空闲 / 连接超时', 'steps.anomalyKind.rate_limit': '429 限流 / 配额耗尽', 'steps.anomalyKind.capacity': '503 上游算力不足', 'steps.anomalyKind.disconnect': '连接中断 / 断流', 'steps.anomalyKind.upstream': '上游 5xx 内部错误', 'steps.anomalyKind.model_output': '模型输出 / 工具参数无效', 'steps.anomalyKind.safety': '内容安全过滤', 'steps.anomalyKind.auth_or_model': '请求受限 / 模型不可用', 'steps.anomalyKind.error': '调用异常', 'steps.anomalyKind.canceled': '用户取消', 'steps.anomalyStepTitle': '#{step} · 异常 {count} 次', 'steps.anomalyDelayPart': '退避 {sec}s', 'steps.compactionStepTitle': '#{step} · 自动压缩', 'steps.compactionSummaryRow': '输入 {input} → 摘要输出 {output}', 'steps.compactionDetailHint': '系统自动触发的上下文压缩步骤,用于折叠历史对话以释放窗口空间', 'steps.compactionAnomalyHint': '该步骤同时为系统自动压缩步骤', 'steps.timingStepTitle': '#{step} · 耗时拆解', 'steps.timingTotalSub': '总计 {sec}', 'steps.timingTtftLabel': '首字等待 (TTFT)', 'steps.timingStreamLabel': '流式返回', 'steps.timingAfterTtftLabel': '首字后耗时', 'steps.timingThinkLabel': '原生思考计时', 'steps.timingTotalLabel': '端到端总耗时', 'steps.timingOverlapHint': '原生思考计时可能重叠首字或流式阶段,不可直接相加', 'steps.timingToolBufferedHint': '含工具调用,缓冲返回时流式耗时较短', 'steps.timingAnomalyHint': '含 {count} 次异常', 'steps.timingAnomalyDelayHint': '含 {count} 次异常 · 退避 {sec}s', 'steps.anomalyTerminalTag': '中止', 'steps.anomalyModelTitle': '{model} · 异常 {count} 次', 'steps.anomalyModelSub': '涉及 {steps} 步', 'steps.anomalyModelKindRow': '{kind}:{count} 次', 'steps.anomalyModelClickHint': '点击前往「按步查看」筛选异常步', 'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)', 'steps.anomalyFilterLabel': '仅看异常 ({count})', 'steps.anomalyFilterAll': '返回全部步骤', 'steps.sortClickTip': '点击按「{col}」排序', 'steps.searchPlaceholder': '搜索 #步号、模型、提问或异常...', 'steps.searchClearAria': '清空步骤搜索', 'steps.chipAnomaly': '异常 {count}', 'steps.chipCompaction': '压缩 {count}', 'steps.chipLowCache': '低缓存 {count}', 'steps.chipLowCacheTip': '筛选缓存命中率低于 50% 的步骤', 'steps.chipSlowTtft': '慢首字 {count}', 'steps.chipSlowTtftTip': '筛选首字延迟 >= 30s 的严重卡顿步骤', 'steps.exportMenuAria': '导出及报告选项', 'steps.exportXlsx': '导出 Excel (.xlsx)', 'steps.exportXlsxTip': '导出排版精美的步骤明细及模型汇总 Excel 报表', 'steps.exportCsv': '导出 CSV', 'steps.exportCsvTip': '导出当前步骤明细为 CSV 文件', 'steps.exportCsvDone': '已导出', 'steps.exportMd': '复制 Markdown 报告', 'steps.exportMdTip': '复制当前步骤 Markdown 诊断报告', 'steps.exportMdDone': '已复制步骤 Markdown 报告', // Export & Toast Feedback 'export.savedLocal': '已导出 {file}', 'export.savedPicked': '已保存 {file}', 'export.savedBrowser': '已下载 {file}', 'export.savedBrowserHint': '文件已交给浏览器默认下载目录', 'export.openFolder': '打开位置', 'export.failed': '导出失败,请稍后重试', 'export.hostUnavailable': '本机导出通道暂未就绪,请重启 Antigravity 后重试', 'export.copied': '已复制到剪贴板', 'export.copyFailed': '复制失败,请检查剪贴板权限', 'export.closeToast': '关闭提示', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': '步序', 'stepCol.step.opt': '调用步序 (#)', 'stepCol.time.th': '时间', 'stepCol.time.opt': '调用时间 (HH:mm:ss)', 'stepCol.model.th': '模型', 'stepCol.model.opt': '调用模型', 'stepCol.tps.th': '速度', 'stepCol.tps.opt': '输出速度 (TPS)', 'stepCol.ttft.th': '首字', 'stepCol.ttft.opt': '首字延迟 (TTFT)', 'stepCol.duration.th': '耗时', 'stepCol.duration.opt': '端到端耗时 (s)', 'stepCol.tokens_combo.th': '上下文 / 思考 / 正文', 'stepCol.tokens_combo.opt': '上下文 / 思考 / 正文 (组合)', 'stepCol.tokens_io_cache.th': '输入 / 输出 / 缓存', 'stepCol.tokens_io_cache.opt': '输入 / 输出 / 缓存 (组合)', 'stepCol.tokens_custom.opt': '自定义组合 ({fmt})', 'stepCol.input_tokens.th': '新输入', 'stepCol.input_tokens.opt': '新输入 Token', 'stepCol.cache_tokens.th': '缓存读', 'stepCol.cache_tokens.opt': '缓存读取 Token', 'stepCol.output_tokens.th': '总输出', 'stepCol.output_tokens.opt': '总输出 Token', 'stepCol.cache.th': '缓存', 'stepCol.cache.opt': '缓存命中率 (%)', 'stepCol.cost.th': '费用', 'stepCol.cost.opt': '单步费用 ($)', // Preferences (3-Tab Modular Settings) 'settings.subTab.general': '常规', 'settings.subTab.structure': '结构', 'settings.subTab.account': '账号', 'settings.subTab.other': '其他', 'settings.subTab.aria': '偏好设置分类切换', 'settings.account.current': '当前账号', 'settings.account.signedOut': '未登录', 'settings.account.unknown': '暂未获取账号状态', 'settings.account.email': '账号邮箱', 'settings.account.googleLogin': '使用 Google 登录', 'settings.account.loginHint': '通过浏览器登录 Google,完成后账号会自动添加到列表。', 'settings.account.loginWaiting': '请在浏览器中选择 Google 账号并完成授权,完成后这里会自动更新。', 'settings.account.loginFinishing': '授权已收到,正在保存账号…', 'settings.account.loginSuccess': '登录成功,账号已添加。', 'settings.account.loginCancelled': '已取消本次登录。', 'settings.account.loginExpired': '登录已超时,请重新点击「使用 Google 登录」。', 'settings.account.loginDenied': 'Google 授权已取消,请重新登录。', 'settings.account.loginStartFailed': '未能开始登录,请重试。', 'settings.account.loginExchangeFailed': '未能完成登录,请检查网络后重新授权。', 'settings.account.openLoginPage': '重新打开 Google 授权页面', 'settings.account.cancelLogin': '取消登录', 'settings.account.importExisting': '导入已有凭证', 'settings.account.credential': 'OAuth 凭证', 'settings.account.credentialPlaceholder': '粘贴 1// 刷新令牌或 OAuth JSON…', 'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。', 'settings.account.save': '导入凭证', 'settings.account.capture': '保存当前凭证', 'settings.account.reload': '刷新列表', 'settings.account.switch': '切换并重启', 'settings.account.switchHint': '切换会关闭并重新打开 Antigravity App 和共享登录的 IDE,请先保存工作。', 'settings.account.restarting': '正在重启 Antigravity 并应用所选账号…', 'settings.account.switchStartFailed': '未能启动切号,请刷新列表后重试。', 'settings.account.clientCloseFailed': 'Antigravity 未能完全退出,切换未完成。', 'settings.account.clientRestartFailed': '凭证已更新,但自动重新打开失败,请手动打开 Antigravity。', 'settings.account.remove': '移除', 'settings.account.active': '当前使用', 'settings.account.savedBadge': '已备份', 'settings.account.written': '凭证已写入', 'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。', 'settings.account.savedCredentials': '已保存的账号', 'settings.account.empty': '暂无已保存的凭证。', 'settings.account.loading': '正在读取已保存的凭证…', 'settings.account.saved': '凭证已保存。', 'settings.account.removed': '已移除保存的凭证。', 'settings.account.switched': '已切换账号,正在刷新当前额度。', 'settings.account.switching': '正在验证凭证并准备重启…', 'settings.account.verifying': '正在验证凭证所属账号…', 'settings.account.loadQuota': '查额度', 'settings.account.loadingQuota': '查询中…', 'settings.account.refreshFreqAria': '非当前账号配额刷新间隔', 'settings.account.refresh10m': '10 分钟', 'settings.account.refresh30m': '30 分钟', 'settings.account.refresh1h': '1 小时', 'settings.account.refresh3h': '3 小时', 'settings.account.refresh6h': '6 小时', 'settings.account.refresh12h': '12 小时', 'settings.account.refresh24h': '24 小时', 'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。', 'settings.account.quota': '额度池剩余', 'settings.account.quota5h': '5 小时 {percent}%', 'settings.account.quotaWeekly': '每周 {percent}%', 'settings.account.noQuota': '暂未获取当前账号的额度池。', 'settings.account.quotaStale': '额度刷新失败,显示的是当前账号上次获取的数据。', 'settings.account.unsupported': '凭证切换目前支持 Windows 上的 Antigravity 共享登录。', 'settings.account.invalidEmail': '请先选择一个已保存的账号。', 'settings.account.invalidCredential': '请输入有效的 Antigravity 个人账号 OAuth 凭证。', 'settings.account.credentialTooLarge': '凭证超过 Windows 凭据管理器的 2560 字节上限。', 'settings.account.notFound': '该凭证已移除,请刷新列表。', 'settings.account.noCurrentCredential': '暂时无法读取当前账号的共享凭证。', 'settings.account.busy': '另一个窗口正在操作凭证,请稍后重试。', 'settings.account.storeFailed': '凭证操作失败,请重试。', 'settings.account.rollbackFailed': '凭证写入和回滚均失败。请在 Antigravity 中确认当前账号后再继续。', 'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。', 'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。', 'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。', 'settings.account.identityMismatch': '凭证所属账号跟宿主或保存的账号不一致,请重新导入该凭证。', 'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。', 'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。', 'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。', 'settings.account.switchConfirm': '确认切换', 'settings.account.removeConfirm': '确认移除', 'settings.account.pwdBtnSet': '二级密码', 'settings.account.pwdBtnManage': '密码设置', 'settings.account.lockNow': '锁定', 'settings.account.lockNowTip': '立即锁定凭证库', 'settings.account.unlockBtn': '解锁', 'settings.account.unlockPlaceholder': '输入二级密码解锁…', 'settings.account.vaultLockedHint': '凭证库已加密锁定,输入二级密码后可切换账号、管理凭证和刷新后台配额。', 'settings.account.forgotPwdToggle': '忘记密码?', 'settings.account.resetVaultHint': '二级密码采用真实密钥派生加密,遗忘后无法解密旧备份(不影响当前正在使用的账号),可清空凭证库后重新添加。', 'settings.account.resetVaultBtn': '清空凭证库', 'settings.account.resetVaultConfirm': '确认清空重置', 'settings.account.pwdTabChange': '修改密码', 'settings.account.pwdTabDisable': '关闭密码', 'settings.account.pwdCurrentPlaceholder': '当前二级密码…', 'settings.account.pwdNewPlaceholder': '设置二级密码(4~128 位)…', 'settings.account.pwdConfirmPlaceholder': '再次确认密码…', 'settings.account.pwdEnableSubmit': '启用加密', 'settings.account.pwdChangeSubmit': '更新密码', 'settings.account.pwdDisableSubmit': '关闭保护', 'settings.account.pwdSetHint': '使用二级密码对所有已存刷新令牌追加一层加密,每次启动首次操作时解锁一次;请牢记密码,遗忘后无法找回备份。', 'settings.account.pwdManageHint': '验证当前二级密码后可更换新密码,或退回系统默认加密。', 'settings.account.pwdEnabledToast': '已启用二级密码加密。', 'settings.account.pwdChangedToast': '二级密码已更新。', 'settings.account.pwdDisabledToast': '已关闭二级密码保护。', 'settings.account.vaultUnlockedToast': '凭证库已解锁。', 'settings.account.vaultLockedToast': '凭证库已锁定。', 'settings.account.vaultResetToast': '凭证库已清空重置。', 'settings.account.vaultLocked': '请先输入二级密码解锁凭证库。', 'settings.account.wrongPassword': '二级密码不正确,请核对后重试。', 'settings.account.invalidPassword': '密码长度需在 4 到 128 个字符之间且不能全为空格。', 'settings.account.passwordMismatch': '两次输入的密码不一致。', 'settings.account.passwordRateLimited': '密码连续输错次数过多,请稍候再试。', 'settings.account.vaultDecryptFailed': '凭证解密校验失败,请确认密码或重置凭证库。', 'settings.account.invalidActionNonce': '安全校验令牌已过期,请重试。', 'settings.account.riskNotAccepted': '请先确认并接受非官方能力风险提示。', 'settings.account.riskBody': 'Google 官方并未授权在 Antigravity App / IDE 中通过第三方插件导入、保存、切换账号凭证或后台查询多账号配额。擅自启用可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', 'settings.account.trendTitle': '额度变化', 'settings.account.trendWinAria': '配额窗口切换', 'settings.account.win5h': '5 小时', 'settings.account.winWeekly': '每周', 'settings.account.trendEmpty': '当前时间范围内暂无配额记录。', 'settings.saving': '保存中…', 'settings.saved': '已保存', 'settings.saveFailed': '保存失败', 'settings.resetDone': '已恢复默认', 'settings.resetBtn': '恢复默认', // Preferences -> General Tab 'settings.gen.appearanceTitle': '界面与外观', 'settings.gen.language': '界面语言', 'settings.gen.langZh': '简体中文', 'settings.gen.langEn': 'English', 'settings.gen.langAuto': '跟随系统', 'settings.gen.themeAccent': '主题色', 'settings.gen.accentHost': '跟随宿主', 'settings.gen.accentBlue': '经典蓝', 'settings.gen.accentEmerald': '翡翠绿', 'settings.gen.accentAmber': '琥珀橙', 'settings.gen.accentViolet': '鸢尾紫', 'settings.gen.accentCyan': '青碧色', 'settings.gen.accentRose': '玫瑰红', 'settings.gen.fontScale': '字体大小', 'settings.gen.fontSm': '小', 'settings.gen.fontMd': '标准', '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': '仅提示新版本,手动更新', 'settings.gen.updateAuto': '自动更新', 'settings.gen.updateOff': '关闭更新', 'settings.gen.pricingLabel': '价格表', 'settings.gen.versionLabel': '当前版本', 'settings.gen.modelCount': '{count} 个模型', 'settings.gen.srcRemote': '云端同步', 'settings.gen.srcLocal': '本地文件', 'settings.gen.srcDefault': '内置默认', 'settings.gen.syncAt': '更新于 {time}', 'settings.gen.pubAt': '发布于 {date}', 'settings.gen.defaultPricing': '默认价格', 'settings.gen.syncBtn': '更新价格表', 'settings.gen.syncingBtn': '更新中…', 'settings.gen.syncingMsg': '正在同步价格表…', 'settings.gen.syncedMsg': '价格表已更新 ({count} 个模型)', 'settings.gen.syncFallbackMsg': '连接超时,使用本地价格表', 'settings.gen.checkUpdateBtn': '检查更新', 'settings.gen.checkingBtn': '检查中…', 'settings.gen.checkingMsg': '正在检查新版本…', 'settings.gen.checkFailedMsg': '检查失败:{err}', 'settings.gen.upToDateMsg': '当前已是最新版本 (v{ver})', 'settings.gen.downloadingMsg': '正在下载更新…', 'settings.gen.updatedRestartMsg': '更新完成,正在重启面板…', 'settings.gen.updateSkippedMsg': '未执行更新', 'settings.gen.updateFailedMsg': '更新失败', 'settings.gen.canUpgradeSub': '可升级至 v{ver} ({mode})', 'settings.gen.upgradeToBtn': '升级至 v{ver}', 'settings.gen.manualUpgradeBtn': '手动升级 v{ver}', 'settings.gen.updateOffSub': '已关闭更新提醒 ({mode})', 'settings.gen.latestSub': '已是最新 ({mode})', // Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n) 'settings.hostI18n.title': 'Antigravity 界面语言', 'settings.hostI18n.langLabel': '目标语言', 'settings.hostI18n.langOff': '原始语言(不翻译)', 'settings.hostI18n.langHint': '从仓库按需独立下载语言包并在渲染层无损应用,不修改宿主安装包,不影响聊天内容与代码', 'settings.hostI18n.optInstalled': '已下载 v{ver}', 'settings.hostI18n.optRemote': '仓库拉取 · {size}', 'settings.hostI18n.refreshManifestTip': '刷新仓库语言包清单', 'settings.hostI18n.refreshingManifestMsg': '正在拉取语言清单…', 'settings.hostI18n.manifestSyncedMsg': '已更新清单({count} 个语言包)', 'settings.hostI18n.manifestFailedMsg': '拉取语言清单失败,请检查网络或代理', 'settings.hostI18n.depthLabel': '翻译深度', 'settings.hostI18n.depthLight': '浅度', 'settings.hostI18n.depthDeep': '深度', 'settings.hostI18n.depthLightHint': '浅度模式:保留 MCP、Skill、Workspace、Subagent、Swarm、Diff、Terminal 等高频英文术语及模型名称,仅翻译常规界面', 'settings.hostI18n.depthDeepHint': '深度模式:将常见工程术语一并译为目标语言(如工作区、子代理、蜂群、终端、沙箱),仅保留模型名与命令', 'settings.hostI18n.downloadingMsg': '正在下载 {locale} 语言包…', 'settings.hostI18n.downloadedAndAppliedMsg': '语言包已下载校验并生效', 'settings.hostI18n.appliedMsg': '已切换并即时生效', 'settings.hostI18n.disabledMsg': '已关闭翻译并还原原始界面', 'settings.hostI18n.depthSwitchedMsg': '已热切换翻译深度', 'settings.hostI18n.packUpdatedMsg': '语言包已更新并重新应用', 'settings.hostI18n.cacheRemovedMsg': '已删除本地语言包缓存', 'settings.hostI18n.actionFailed': '语言包操作失败,请重试', 'settings.hostI18n.entriesCount': '{count} 条词条', 'settings.hostI18n.appliedWindows': '已应用 {count} 窗口', 'settings.hostI18n.updatePackBtn': '更新至 v{ver}', 'settings.hostI18n.redownloadBtn': '检查更新', 'settings.hostI18n.removeCacheBtn': '删除缓存', 'settings.hostI18n.devToolsTitle': '词条采集与多语言扩展', 'settings.hostI18n.devToolsHint': '仅扫描当前打开的 Antigravity 界面控件中未命中的英文短语(自动排除聊天正文与代码),便于补全漏翻词条或制作新语言包', 'settings.hostI18n.collectBtn': '采集未翻译 UI 文案', 'settings.hostI18n.collectingBtn': '采集中…', 'settings.hostI18n.collectedResult': '共采集到 {count} 条待翻译 UI 文案(扫描 {targets} 个窗口)', 'settings.hostI18n.collectedEmpty': '当前页面未检测到待翻译的英文 UI 短语', 'settings.hostI18n.collectFailed': '采集失败,请确认已开启调试端口并打开主窗口', 'settings.hostI18n.copyJsonBtn': '复制 JSON', 'settings.hostI18n.exportJsonBtn': '导出 JSON', // Preferences -> Structure Tab 'settings.str.thirdTabAria': '结构子菜单切换', 'settings.str.tabMount': '挂载胶囊', 'settings.str.tabHover': '鼠标悬浮窗', 'settings.str.tabOverview': '实时监控布局', 'settings.str.tabSteps': '调用明细字段', 'settings.str.previewMountSidebarHint': '当前为仅侧边栏模式,主窗口不挂载胶囊;切回顶部栏或输入框挂载后将按上方样式呈现', 'settings.str.mountSection': '挂载胶囊', 'settings.str.mountBadge': '{count}/5 项', 'settings.str.mountMode': '面板挂载方式', 'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)', 'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)', 'settings.str.mountSidebar': '仅侧边栏', 'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊', 'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写', 'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。', 'settings.bridge.readOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可生效', 'settings.bridge.ctxReadOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可激活上下文覆写', 'settings.bridge.readOnlyBody': '个人启动项已配好,但公共桌面或开始菜单快捷方式需管理员权限修改。点击下方按钮并在系统弹窗中确认授权,即可一次性修补公共图标并带参重开(后续日常打开均自动生效)。', 'settings.bridge.macTitle': '当前会话未开启调试端口,一键重开即可启用挂载', 'settings.bridge.ctxMacTitle': '当前会话未开启调试端口,一键重开即可激活上下文覆写', 'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效', 'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效', 'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。', 'settings.bridge.guideMac': '受 macOS 应用签名限制,从 Dock 直接冷启动默认不带调试端口参数。点击下方按钮即可一键带参重开恢复(日常仅关窗不完全退出 Cmd+Q 则持续有效)。', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。', 'settings.bridge.relaunchBtn': '立即重启并启用挂载', 'settings.bridge.relaunchAuthBtn': '授权修补并立即重启', 'settings.bridge.relaunchingBtn': '正在重启客户端...', 'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试', 'settings.bridge.dismissAria': '暂时关闭提示', 'settings.bridge.copyFlagBtn': '复制 {cmd}', 'settings.bridge.copiedBtn': '已复制启动参数', 'settings.str.popoverWidthLabel': '悬浮面板宽度', 'settings.str.popoverWidthAuto': '自适应', 'settings.str.popoverWidthCustom': '指定宽度', 'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px', 'settings.str.multiToggle': '实时运行会话入口', 'settings.str.contextAgentModeLabel': '胶囊及悬浮上下文', 'settings.str.contextAgentMain': '锁定主代理', 'settings.str.contextAgentAuto': '跟随活跃', 'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊', 'settings.str.cliSlotsLabel': 'CLI 槽位顺序 (左 → 右,1~6 项,可拖拽)', 'settings.str.addCliSlot': '添加 CLI 槽位 ({count}/{max})', 'settings.str.cliCustomCmdHint': '检测到自定义 statusLine 命令,为避免误覆盖默认不会自动改写', 'settings.str.cliPausedHint': 'CLI 端当前已暂停或未写入 statusLine 配置', 'settings.str.cliFlagsOverrideHint': '检测到 CLI 启动参数包含显式槽位覆盖,命令行参数将优先于此处配置', 'settings.str.cliRestoreBtn': '一键接管并恢复', 'settings.str.cliEnableBtn': '重新写入并启用', 'settings.str.cliClearFlagsBtn': '清除命令行覆盖', 'settings.str.cliRestoringBtn': '正在写入...', 'settings.str.cliPreviewRunning': '{count} 运行中', 'settings.str.show': '显示', 'settings.str.hide': '隐藏', 'settings.str.on': '开启', 'settings.str.off': '关闭', 'settings.str.capsuleSlotsLabel': '胶囊数值与顺序 (左 → 右,1~5 项,可拖拽)', 'settings.str.addCapsuleSlot': '添加槽位 ({count}/{max})', 'settings.str.hoverSection': '鼠标悬浮窗', 'settings.str.hoverBadgeOff': '已关闭', 'settings.str.hoverBadgeCount': '{count} 模块', 'settings.str.hoverModulesLabel': '悬浮窗展示模块 (上 → 下,0~4 项,可拖拽)', 'settings.str.hoverEmptyHint': '已关闭悬浮速览窗(点击胶囊仍可展开完整面板)', 'settings.str.addHoverModule': '添加模块 ({count}/{max})', 'settings.str.overviewSection': '实时监控布局', 'settings.str.overviewBadge': '{modCount} 模块 · {metCount} 指标', 'settings.str.overviewModulesLabel': '监控模块与顺序 (上 → 下,至少 1 项,可拖拽)', 'settings.str.addOverviewModule': '添加模块 ({count}/{max})', 'settings.str.overviewMetricsLabel': '第一行实时指标 (左 → 右,1~4 项,可拖拽)', 'settings.str.overviewMetricsInactiveHint': '当前已移出「实时指标」模块,此配置将在悬浮窗启用或重新添加模块时生效', 'settings.str.addOverviewMetric': '添加指标 ({count}/{max})', 'settings.str.stepsSection': '调用明细字段', 'settings.str.stepsBadge': '{count} 列', 'settings.str.stepTurnRailToggle': '对话轮次导轨', 'settings.str.stepAgentBadgeToggle': '主/子代理标识', 'settings.str.stepSpeedColorToggle': '输出速度多色分级', 'settings.str.stepFilterToolbarToggle': '搜索及诊断筛选栏', 'settings.str.stepTokenComboLabel': '自定义 Token 组合格式', 'settings.str.stepTokenComboPlaceholder': '例如 context:new:cache 或 in:out:cache', 'settings.str.stepTokenComboHint': '可用字段:context(上下文)、in/new(新输入)、out(输出)、cache(缓存)、think(思考)、reply(正文)、total(总计),以 : 或 / 分隔(1~4 项)', 'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列,可拖拽)', 'settings.str.addStepCol': '添加字段 ({count}/{max})', 'settings.slot.dragHint': '按住上下拖动调整顺序', 'settings.slot.moveUp': '前移', 'settings.slot.moveDown': '后移', 'settings.slot.remove': '移除此项', 'settings.slot.minReached': '至少保留 {min} 项', 'settings.slot.alreadyAdded': '已添加', 'settings.mock.sessionTitle': '重构鉴权中间件与会话缓存', 'settings.mock.subRole': '接口审计', 'settings.mock.turnPromptLatest': '排查并发刷新令牌时的竞态问题,补齐单元测试', 'settings.mock.turnPromptPrev': '梳理路由守卫与过期会话清理逻辑', // Preferences -> Other Tab 'settings.oth.modelTitle': '模型标识显示', 'settings.oth.modelFormat': '模型名称格式', 'settings.oth.modelShort': '精简代号 (如 argon-4-high)', 'settings.oth.modelUpstream': '原始模型 ID (如 gemini-3.8-flash-n)', 'settings.oth.modelUpstreamCompact': '去前缀原始 ID (如 3.8-flash-n / sonnet-4-6 / 5.4-mini)', 'settings.oth.orchFormat': 'Orchestrator 系列 ID', 'settings.oth.orchCompact': '精简代号 (如 orchestrator-argon)', 'settings.oth.orchFull': '原始完整 ID (如 gemini-pro-orchestrator)', 'settings.oth.expTitle': '试验性功能', 'settings.oth.expBadge': '试验性', 'settings.oth.quotaReserveLabel': '配额预占估算', 'settings.oth.quotaReserveDesc': '在可用额度中估算 5h / 周限的 0.5% / 1% 租约预占,并用紫色标注占比及进度条段', 'settings.oth.quotaReserveLogLabel': '预占观测日志', 'settings.oth.quotaReserveLogDesc': '将配额跳变及退还观测记录复制到剪贴板,重启后自动保留,便于分析触发阈值', 'settings.oth.exportReserveLogBtn': '导出预占日志', 'settings.oth.exportReserveLogCopied': '已复制 {count} 条观测日志到剪贴板', 'settings.oth.exportReserveLogEmpty': '暂无跳变记录,已复制当前摘要到剪贴板', 'settings.oth.exportReserveLogFailed': '获取或复制预占日志失败', 'settings.oth.baselineTitle': '模型上下文设置', 'settings.oth.ctxRiskTitle': '非官方能力风险提示', 'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', 'settings.oth.ctxRiskAcceptBtn': '我已知晓风险,继续使用', 'settings.oth.ctxModel': '模型', 'settings.oth.ctxMainLabel': '主代理', 'settings.oth.ctxSwarmLabel': '子代理与蜂群', 'settings.oth.ctxSwarmError': '本地同步异常:{error}', 'settings.oth.ctxBaselineLabel': '上下文窗口上限', 'settings.oth.ctxChooseModel': '选择模型', 'settings.oth.ctxDefault': '跟随宿主设置', 'settings.oth.ctxExpensive': '{name}(消耗更多配额)', 'settings.oth.ctxTokens': '{count} token', 'settings.oth.ctxUnavailable': '{name}(当前不可用)', 'settings.oth.ctxConfigured': '{name} · 已设置', 'settings.oth.ctxConfiguredReported': '{name} · 已设置 / 最近 {reported}', 'settings.oth.ctxPendingBridge': '{name} · 待重启生效', 'settings.oth.ctxDefaultReported': '默认 · 最近 {name}', 'settings.oth.ctxReported': '最近一次请求由宿主报告为 {name}。', 'settings.oth.ctxMixed': '各推理档设置不同', 'settings.oth.ctxMixedHint': '该模型的推理档保留了不同的旧设置。选择一个上限即可统一。', 'settings.oth.ctxBaselineHint': '同一模型的推理档共享上限。插件会在启动后重新应用已保存的设置,用于之后发送的消息。', 'settings.oth.ctxNoModels': '宿主暂未返回可用模型。', 'settings.oth.ctxNoOptions': '宿主未提供此模型的上下文档位或容量,当前只能跟随宿主设置。', 'settings.oth.maintTitle': '缓存与重置', 'settings.oth.cacheLabel': '本地轨迹缓存', 'settings.oth.cacheDesc': '清空内存与磁盘步骤解析缓存并立即重扫全部会话', 'settings.oth.rebuildBtn': '重建本地轨迹缓存', 'settings.oth.rebuildingBtn': '重建中…', 'settings.oth.rebuildDone': '本地轨迹缓存已重建', 'settings.oth.rebuildFailed': '缓存重建失败', 'settings.oth.resetLabel': '恢复出厂偏好', 'settings.oth.resetDesc': '将常规、结构与其他分页中的所有偏好设置还原为初始默认状态', 'settings.oth.resetAllBtn': '恢复全部默认设置', 'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', 'settings.oth.backupLabel': '配置备份及恢复', 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON', 'settings.oth.exportJsonBtn': '导出 JSON', 'settings.oth.importJsonBtn': '导入 JSON', 'settings.oth.exportDone': '配置 JSON 已导出', 'settings.oth.importDone': '已恢复 {count} 项偏好设置', 'settings.oth.importInvalid': '导入失败:JSON 无效或未包含可识别的偏好项', 'settings.oth.migTitle': '跨端会话迁移', 'settings.oth.migDesc': '按需把选定会话迁往另一端,迁移前自动备份摘要库和源库', 'settings.oth.migRefreshBtn': '刷新列表', 'settings.oth.migSourceLabel': '来源端', 'settings.oth.migTargetLabel': '目标端', 'settings.oth.migModeLabel': '迁移方式', 'settings.oth.migModeMove': '完整迁移(推荐)', 'settings.oth.migModeClone': '克隆副本', 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端', 'settings.oth.migModeCloneHint': '保留源会话并生成新 ID,新副本仅统计迁入后的新步骤', 'settings.oth.migProjectLabel': '绑定目标项目', 'settings.oth.migProjectOutside': '独立会话(无所属项目)', 'settings.oth.migClientDesktop': '桌面端 App / 新版 IDE', 'settings.oth.migClientCli': 'Antigravity CLI', 'settings.oth.migClientIdeLegacy': '旧版 IDE (.db)', 'settings.oth.migSearchPlaceholder': '按标题或工作区筛选会话…', 'settings.oth.migSelectAll': '全选', 'settings.oth.migClearSel': '清空', 'settings.oth.migSelectedCount': '已选 {selected} / {total}', 'settings.oth.migRunningTag': '运行中', 'settings.oth.migStepsUnit': '{count} 步', 'settings.oth.migEmpty': '当前来源端暂无可迁移会话', 'settings.oth.migNoMatch': '没有匹配的会话', 'settings.oth.migActionBtn': '迁移选定会话 ({count})', 'settings.oth.migRunningBtn': '迁移中…', 'settings.oth.migDoneDesktop': '已成功迁移 {count} 条会话到「{project}」,在桌面端按 Ctrl+R 即可在左侧看到', 'settings.oth.migDoneCli': '已成功迁移 {count} 条会话到 CLI,可使用下方命令恢复对话', 'settings.oth.migPartialWarn': '(另有 {failed} 条跳过或失败)', 'settings.oth.migReloadBtn': '刷新窗口', 'settings.oth.migCopyCmd': '复制命令', 'settings.oth.migCopied': '已复制', 'settings.oth.migErrLocked': '源会话文件正被原端占用,请先关闭对应终端/窗口后重试,或切换为「克隆副本」', 'settings.oth.migErrExists': '目标端已存在同 ID 会话,无需重复移动(可切换为「克隆副本」)', 'settings.oth.migErrRunning': '该会话正在运行中,请待空闲后再迁移', 'settings.oth.migFailed': '迁移失败:{reason}', // Structured Live Activity Actions 'live.act.run_command': '执行命令', 'live.act.read_file': '读取文件', 'live.act.edit_file': '修改文件', 'live.act.write_file': '写入文件', 'live.act.grep_search': '搜索代码', 'live.act.find_file': '查找文件', 'live.act.read_url': '读取网页', 'live.act.search_web': '网页搜索', 'live.act.invoke_subagent': '调用子代理', 'live.act.send_message': '通信子代理', 'live.act.manage_subagents': '管理子代理', 'live.act.swarm_add': '派生工蜂', 'live.act.swarm_title': '命名蜂群', 'live.act.swarm_kill': '终止工蜂', 'live.act.swarm_model': '切换工蜂模型', 'live.act.swarm_channel': '蜂群频道', 'live.act.swarm_status': '巡检蜂群', 'live.act.post_message': '发布看板', 'live.act.read_board': '读取看板', 'live.act.swarm_wait': '看板待命', 'live.act.manage_task': '后台任务', 'live.act.schedule': '定时任务', 'live.act.ask_question': '等待用户选择', 'live.act.search_marketplace': '查询插件', 'live.act.generate_image': '生成图片', 'live.act.mcp_tool': '调用 MCP', 'live.act.tool_call': '调用工具', 'live.act.thinking': '推理中', 'live.act.compacting': '上下文压缩', 'live.act.responding': '正在输出回复', 'live.act.waiting_subagent': '等待子代理', 'live.act.waiting_swarm': '等待工蜂', 'live.act.swarm_waiting': '待命中', 'live.act.swarm_killed': '已终止', 'live.act.starting': '启动中', 'live.act.done': '已完成', 'live.act.awaitingApproval': '等待确认 · {label}', 'live.act.compactionResuming': '已完成压缩,正在恢复推理', // SVG Charts (SessionStepCharts & TrendAreaChart) 'chart.step.empty': '当前范围暂无可绘制的调用步骤', 'chart.step.excluded': '未纳入', 'chart.step.zeroSteps': '0 步', 'chart.step.stepAdd': '本步 +{tokens}', 'chart.step.ioSplit': '入 {inTok} · 缓 {cacheTok} · 出 {outTok}', 'chart.step.cacheShort': '缓存 {pct}%', 'chart.step.compactionCheckpoint': '上下文自动压缩检查点', 'chart.step.cacheHitOut': '缓存命中 {pct}% · 输出 +{outTok}', 'chart.step.ttftShort': '首字 {sec}s', 'chart.step.outAndCtx': '输出 {outTok} · 上下文 {ctxTok}', 'chart.step.compactionStep': '上下文压缩步', 'chart.step.noSpeedSample': '无测速样本', 'chart.step.ctxAndCache': '上下文 {ctxTok} · 缓存 {pct}%', 'chart.step.noTtftSample': '无首字计时样本', 'chart.step.cumCost': '累计 {cost}', 'chart.step.cacheAndStepTok': '缓存 {pct}% · 本步 {tokens}', 'chart.step.noSamples': '无样本', 'chart.step.peakShort': '峰 {val}', 'chart.step.peakPill': '峰值 {tag} · {val}', 'chart.step.stepsCount': '{count}步', 'chart.step.multiPrefix': '{count} 模型 · ', 'chart.step.sumTokens': '{prefix}累计 {tokens}', 'chart.step.peakTokens': '{prefix}峰值 {tokens}', 'chart.step.currentCtx': '当前 {tokens}', 'chart.step.meanTps': '{prefix}均值 {val} tok/s', 'chart.step.meanSec': '{prefix}均值 {val}s', 'chart.step.noValidSamples': '暂无有效样本', 'chart.step.sumCost': '{prefix}累计 {cost}', 'chart.fit.empty': '该模型暂无有效拟合样本', 'chart.fit.loess': 'LOESS 拟合', 'chart.fit.olsLinear': 'OLS 线性', 'chart.fit.olsReg': 'OLS 回归', 'chart.fit.observed': '观测值', 'chart.fit.tipFit': '拟合 {val}', 'chart.fit.tipObs': '观测 {val}', 'chart.fit.zeroSamples': '0 样本', 'chart.fit.peerMean': '{label} 均 {val}', 'chart.fit.peerCompare': '同图对比:{peers}', 'chart.fit.curvesCount': '{count} 条拟合线', 'chart.fit.multiBadge': '{steps}步 · {models} 模型对比', 'chart.fit.singleBadge': '{steps}步 · 均 {mean}', 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · 样本标准差 SD = ±{sd}', 'chart.trend.hmMonthYear': '{yy}年{month}月', 'chart.trend.hmMonthOnly': '{month}月', 'chart.trend.wdayMon': '一', 'chart.trend.wdayWed': '三', 'chart.trend.wdayFri': '五', 'chart.trend.wdaySun': '日', 'chart.trend.hmAria': '每日用量热力格子图', 'chart.trend.hmLess': '少', 'chart.trend.hmMore': '多', 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', 'chart.trend.hmActiveZero': '活跃 0/{total} 天', 'chart.trend.hmWeekPeak': '活跃 {active}/{total} 周 · 峰值 {label} · {tokens}', 'chart.trend.hmWeekZero': '活跃 0/{total} 周', 'chart.trend.hmMonthPeak': '活跃 {active}/{total} 月 · 峰值 {label} · {tokens}', 'chart.trend.hmMonthZero': '活跃 0/{total} 月', 'chart.trend.hmCumSummary': '累计 {days} 天 · 总计 {tokens} · {cost}', 'chart.trend.hmCumThrough': '截至 {date} 累计', 'chart.trend.peakPill': '峰值 {label} · {tokens}', // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) 'ui.dt.wdayMon': '一', 'ui.dt.wdayTue': '二', 'ui.dt.wdayWed': '三', 'ui.dt.wdayThu': '四', 'ui.dt.wdayFri': '五', 'ui.dt.wdaySat': '六', 'ui.dt.wdaySun': '日', 'ui.dt.prevMonth': '上个月', 'ui.dt.nextMonth': '下个月', 'ui.dt.hourMinute': '时 / 分', 'ui.num.decrease': '减少数值', 'ui.num.increase': '增加数值', 'ui.seg.defaultAria': '分段切换器', }); return { I18N_MESSAGES_ZH_CN }; })(); // --- src/i18n/en-US.js --- const { I18N_MESSAGES_EN_US } = (() => { /** * @fileoverview English (en-US) dictionary for Antigravity Usage & Speed Monitor. * Zero emoji characters. */ const I18N_MESSAGES_EN_US = Object.freeze({ // Top Navigation 'nav.overview': 'Live', 'nav.consumption': 'Usage', 'nav.steps': 'Steps', 'nav.settings': 'Settings', // Top Session Header 'header.followLatest': 'Follow Latest Session', 'header.followCurrentWindow': 'Follow Current Window', 'header.autoFollowBadge': 'Auto', 'header.currentWindowNamed': 'Current ({title})', 'header.latestNamed': 'Latest ({title})', 'header.lockedSession': 'Pinned Session ({id})', 'header.lockedMeta': 'Pinned', 'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)', 'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)', 'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)', 'header.convCompactSubs': '{subs} sub · {total} steps', 'header.convCompactSwarm': '{swarm} swm · {total} steps', 'header.convCompactSwarmAndSubs': '{swarm} swm {subs} sub · {total} steps', 'header.convMetaSteps': '{count} steps', 'header.hasUpdate': 'Update', 'header.upgradeToVer': 'Update v{ver}', 'header.upgrading': 'Updating…', 'header.ariaUpdate': 'New version available, click to update', 'header.ariaRefresh': 'Refresh telemetry', 'header.statusSyncing': 'Syncing', 'header.statusSynced': 'Synced', 'header.statusRetrying': 'Retrying', 'header.statusGenerating': 'Running{suffix}', 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', 'header.statusLive': 'Monitoring', 'header.scopeAll': 'All Agents', 'header.scopeAllShort': 'All', 'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…', 'select.searchPlaceholder': 'Filter options…', 'select.noMatches': 'No matching items', 'select.clearSearch': 'Clear search', // Formatters & Common Labels 'fmt.pending': 'N/A', 'fmt.speedIncomplete': 'Incomplete timing', 'fmt.speedCanceled': 'Canceled', 'fmt.speedError': 'Call error', 'fmt.speedInterrupted': 'Interrupted', 'fmt.speedCompactionTimingUnavailable': 'Untimed compaction', 'fmt.speedInvalidOutput': 'No valid output', 'fmt.speedInconsistent': 'Invalid timing', 'fmt.speedShort': 'Too brief (<0.5s)', 'fmt.speedLegacy': 'Legacy cached', 'fmt.sampleSteps': '{valid}/{total} steps', 'fmt.resetUnknown': 'Unknown reset', 'fmt.resetSoon': 'Resetting soon', 'fmt.resetUnder1m': 'Resets in <1m', 'fmt.resetDaysHours': 'Resets in {d}d {h}h', 'fmt.resetHoursMins': 'Resets in {h}h {m}m', 'fmt.resetMins': 'Resets in {m}m', 'fmt.selectTime': 'Select time', 'fmt.unknownModel': 'Unknown model', 'fmt.compactionSuffix': '·compact', 'fmt.mainAgent': 'Main Agent', 'fmt.mainBadge': 'Main', 'fmt.subAgent': 'Subagent', 'fmt.subBadge': 'S{index}', 'fmt.subBadgeShort': 'Sub', 'fmt.swarmAgent': 'Swarm', 'fmt.swarmBadge': 'W{index}', 'fmt.swarmBadgeShort': 'Swarm', 'fmt.swarmMonitorHint': 'Monitor', 'fmt.swarmNarratorHint': 'Narrator', 'fmt.sideQuestion': 'Side Question', 'fmt.sideBadge': 'Q{index}', 'fmt.sideBadgeShort': 'Q', 'fmt.selectedCount': '{count} {unit} selected', 'fmt.selectedListTitle': 'Selected ({count}): {names}', 'fmt.selectPlaceholder': 'Select', // Capsule & Multi-Session Overlay 'capsule.ariaMonitor': 'Usage & Speed Monitor', 'capsule.ariaMulti': 'Active Sessions Overview', 'capsule.multiZero': '0 active', 'capsule.multiRunning': '{count} active', 'capsule.multiRunningWithSubs': '{count} active · {subs} sub', 'capsule.multiRunningWithSwarm': '{count} active · {subs} swarm', 'capsule.tpsRunning': 'Running', 'capsule.tpsIdle': 'Idle', 'capsule.quotaLeft': '{pct}% left', 'capsule.quotaUnknown': '--% left', 'capsule.newVersion': 'Update', 'capsule.updating': 'Updating…', 'capsule.ariaUpdateTitle': 'New version available, click to update', 'capsule.hoverNewVer': 'Update v{ver} available', 'capsule.hoverNewVerGeneric': 'New version available', 'capsule.hoverUpdateHintTopbar': 'Click v{ver} in titlebar to update', 'capsule.hoverUpdateHintComposer': 'Click v{ver} badge to update', 'capsule.hoverUpdateHintTopbarGeneric': 'Click update badge in titlebar', 'capsule.hoverUpdateHintComposerGeneric': 'Click update badge to install', 'multi.title': 'Active Sessions', 'multi.ariaDialog': 'Active Sessions Panel', 'multi.pinned': 'Pinned', 'multi.loading': 'Loading...', 'multi.empty': 'No active running sessions', 'multi.allIdle': 'All idle', 'multi.metaWithSubs': '{main} main · {subs} subagents active', 'multi.metaWithSwarm': '{main} main · {subs} swarm active', 'multi.metaMainOnly': '{main} sessions active', 'multi.hereTag': 'Here', 'multi.inspectSessionTitle': 'Inspect session in monitor: {title}', // Live Overview & Widgets 'module.metrics': 'Live Metrics', 'module.context': 'Context Window', 'module.quotas': 'Available Quotas', 'module.live_tasks': 'Live Running Tasks', // Capsule Slot Metric Options 'capMetric.context': 'Context Usage (%)', 'capMetric.tps': 'Output Speed (TPS)', 'capMetric.ttft': 'First Token Latency (TTFT)', 'capMetric.avg_tps': 'Avg Speed (Avg TPS)', 'capMetric.cost': 'Step Cost ($)', 'capMetric.session_cost': 'Session Cost ($)', 'capMetric.cache_hit': 'Cache Hit Rate (%)', 'capMetric.session_tokens': 'Session Tokens', 'capMetric.quota_auto': 'Auto Tightest Quota', 'capMetric.gemini_5h': 'Gemini 5h Quota', 'capMetric.gemini_weekly': 'Gemini Weekly Quota', 'capMetric.argon_weekly': 'Argon Weekly Quota', 'capMetric.claude_5h': 'Claude 5h Quota', 'capMetric.claude_weekly': 'Claude Weekly Quota', // Overview Matrix Metric Options & Cells 'ovMetric.tps': 'Output Speed', 'ovMetric.ttft': 'First Token', 'ovMetric.avg_tps': 'Avg Speed', 'ovMetric.step_cost': 'Step Cost', 'ovMetric.session_cost': 'Session Cost', 'ovMetric.cache_hit': 'Cache Hit', 'ovMetric.session_tokens': 'Session Tokens', 'ovMetric.context_usage': 'Context Usage', 'ovMetric.quota_tightest': 'Tightest Quota', 'ovMetric.subAvgTtft': 'Avg {val}', 'ovMetric.subAvgCache': 'Avg {val}', 'ovMetric.subValidSamples': 'Valid {samples}', 'ovMetric.subTotalCost': 'Total {cost}', 'ovMetric.subStepCost': 'Step {cost}', 'ovMetric.subInOutTokens': 'In {inTok} · Out {outTok}', 'ovMetric.subCtxRatio': '{used} / {limit}', 'ovMetric.subQuotaPool': '{label}', 'ovMetric.subQuotaPending': 'Waiting for quota sync', // Context Window Widget 'ctx.followActive': 'Follow Active ({badge})', 'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window', 'ctx.expandMore': '+{count} More', 'ctx.expandMoreTitle': 'Expand all {count} subagent context pills', 'ctx.collapse': 'Less', 'ctx.collapseTitle': 'Collapse extra subagent pills', 'ctx.ch.assistant': 'Assistant', 'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments', 'ctx.ch.toolResults': 'Tool Results', 'ctx.ch.toolResultsTitle': 'File reads, terminal outputs, and tool execution results', 'ctx.ch.userInput': 'User Input', 'ctx.ch.userInputTitle': 'User messages and uploaded attachments', 'ctx.ch.subagent': 'Subagent', 'ctx.ch.subagentTitle': 'Subagent reports and background task notifications', 'ctx.ch.checkpoint': 'Checkpoint', 'ctx.ch.checkpointTitle': 'Compacted conversation checkpoint summaries', 'ctx.ch.systemPrompt': 'System Prompt', 'ctx.ch.systemPromptTitle': 'Core identity, sandbox, artifact, and environment prompts', 'ctx.ch.systemTools': 'System Tools', 'ctx.ch.systemToolsTitle': 'Built-in tool schema declarations', 'ctx.ch.mcpTools': 'MCP Tools', 'ctx.ch.mcpToolsTitle': 'MCP external server tool and resource schemas', 'ctx.ch.skills': 'Skills', 'ctx.ch.skillsTitle': 'Installed Skills index and instructions', 'ctx.ch.userRules': 'User Rules', 'ctx.ch.userRulesTitle': 'Global and workspace custom user_rules', // Quota Pools Widget 'quota.weeklyShort': 'Weekly', 'quota.weeklyPool': 'Weekly ({pool})', 'quota.loading': 'Loading...', 'quota.failed': 'Unavailable (--%)', 'quota.usedAndLeft': '{reset} · Used {used}%', 'quota.reservedTip': 'Estimated lease reservation (Experimental): ~{rsv}% (~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.reservedTipMulti': 'Estimated lease reservation (Experimental): ~{rsv}% ({leases} stacked leases, ~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.legendActual': 'Actual', 'quota.legendReserved': 'Reserved', 'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleFullSuffix': 'Full ~{full}', 'quota.footTokensCustom': 'Week Total: {tok} ({cost})', 'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})', 'quota.footCredits': 'AI Credits: {credits}', 'quota.footCallsCustom': 'Week Calls: {calls}', 'quota.footCallsCycle': 'Cycle Calls: {calls}', 'quota.footTipCustom': 'Counted since Monday 00:00 local time', 'quota.footTipCycle': 'Summed across each quota pool weekly reset window', 'quota.rateHelpAria': 'View empirical burn-rate estimates for this account', 'quota.ratePopTitle': 'Estimated Burn Rates', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': 'Current account', 'quota.ratePopPoolFallback': 'Pool average', 'quota.ratePopEq5hLabel': '5h full', 'quota.ratePopEqWkLabel': 'Weekly full', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} samples', 'quota.ratePopPrelimSlope': 'slope est.', 'quota.ratePopPrelimCycle': 'cycle est.', 'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).', 'quota.ratePopSharedBadge': 'Shared active', 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', 'quota.ratePopExternalBaseline': 'Family group / other-device usage detected this cycle; reservations & rates calibrate on local steps only', 'quota.ratePopExt5h': '5h {pct}%', 'quota.ratePopExtWk': 'Weekly {pct}%', // Live Activity Widget 'live.currentSession': 'Current Session', 'live.switchSessionTitle': 'Switch monitor to session: {title}', 'live.thinking': 'Thinking', 'live.generating': 'Generating', 'live.running': 'Running', 'live.waiting': 'Waiting', 'live.killed': 'Killed', 'live.done': 'Done', 'live.doneWithSteps': 'Done ({steps} steps)', 'live.waitingWithSteps': 'Waiting ({steps} steps)', 'live.killedWithSteps': 'Killed ({steps} steps)', '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.cyclePoolAll': 'All Pools', 'cons.cyclePoolAllShort': 'All', 'cons.cyclePoolAria': 'Filter current cycle by quota pool', 'cons.cyclePoolRemMeta': '{pct} left', 'cons.currentCycle': 'Current Cycle', 'cons.cycleFallbackWeek': 'This Week', 'cons.cycleFallbackWeekTip': 'Official weekly reset time unavailable; using calendar week from Monday', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', 'cons.range14d': '14d', 'cons.range30d': '30d', 'cons.rangeAll': 'All', 'cons.rangeCustom': 'Custom', 'cons.rangeAria': 'Usage statistics time range', 'cons.applyFilter': 'Apply', 'cons.rangeTo': 'to', 'cons.overviewTitle': 'Usage Overview', 'cons.totalTokens': 'Total Tokens', 'cons.estCost': 'Est. Cost', 'cons.cacheHitRate': 'Cache Hit Rate', 'cons.callsCount': '{calls} calls', 'cons.cacheHitTokens': 'Hit {tokens}', 'cons.newInput': 'New Input', 'cons.uncachedInput': 'Uncached input', 'cons.cacheRead': 'Cache Read', 'cons.savedCost': 'Saved {cost}', 'cons.outputUsage': 'Output', 'cons.replyAndThink': 'Think {think} · Reply {resp}', 'cons.trendTitle': 'Usage Trend', 'cons.allTime': 'All Time', 'cons.hmModeAria': 'Heatmap view mode', 'cons.hmModeDay': 'Day', 'cons.hmModeWeek': 'Week', 'cons.hmModeMonth': 'Month', 'cons.hmModeAll': 'Total', 'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details', 'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details', 'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details', 'cons.topModels': 'Top Models', 'cons.clientSources': 'Client Sources', 'cons.monthlyTitle': 'Monthly Breakdown', 'cons.monthLabel': 'M{m}', 'cons.monthFullLabel': 'M{m}, {year}', 'cons.hoverModelsHint': 'Hover for models', 'cons.otherModelsCount': 'Others ({count})', 'cons.legInput': 'Input', 'cons.legCache': 'Cache', 'cons.legOutput': 'Output', 'cons.legThinking': 'Think', 'cons.footInput': 'In ', 'cons.footCache': 'Cache ', 'cons.footOutput': 'Out ', 'cons.footThinking': 'Think ', 'cons.footCalls': 'Calls ', 'cons.rankTabAria': 'Switch ranking view', 'cons.rankTabModelsCount': 'Models ({count})', 'cons.rankTabSessions': 'Sessions', 'cons.rankTabSessionsCount': 'Sessions ({count})', 'cons.rankTabWorkspaces': 'Projects', 'cons.rankTabWorkspacesCount': 'Projects ({count})', 'cons.workspaceUnbound': 'Unbound Workspace', 'cons.workspaceSessions': '{count} sessions', 'cons.exportMenuAria': 'Export and report actions', 'cons.exportXlsx': 'Export Excel (.xlsx)', 'cons.exportXlsxTip': 'Export styled multi-sheet Excel workbook with auto column width and alignment', 'cons.exportCsv': 'Export CSV', 'cons.exportCsvTip': 'Export current usage range as CSV', 'cons.exportCsvDone': 'Exported', 'cons.exportMd': 'Copy Markdown Report', 'cons.exportMdTip': 'Copy Markdown summary report for current range', 'cons.exportMdDone': 'Usage Markdown report copied', 'cons.topConvsEmpty': 'No session usage in this range', 'cons.topConvsSortAria': 'Sort sessions ranking', 'cons.topConvsSortCost': 'Cost', 'cons.topConvsSortTokens': 'Tokens', 'cons.topConvCacheMeta': 'Cache {pct}%', 'cons.topConvJumpTip': 'Click to inspect this session in Steps', 'cons.modelsSortAria': 'Sort models ranking', 'cons.modelsSortTokens': 'Tokens', 'cons.modelsSortCost': 'Cost', 'cons.modelsSortSpeed': 'Speed', 'cons.modelsSortCalls': 'Calls', 'cons.modelUnitCost': 'Eff. {cost}/1M', 'cons.speedRelTip': 'Speed relative to fastest model in this range', 'cons.focusTtft': 'TTFT {ttft}', 'cons.focusSpeedMeta': 'TTFT {ttft} · Cache {cache}% · Out {out}', 'cons.focusCallsMeta': 'Avg {avgTok}/call · Cost {cost}', // Steps Detail View & Step Column Registry 'steps.title': 'Step Records', 'steps.tabSteps': 'Steps ({count})', 'steps.tabStepsFiltered': 'Steps ({filtered}/{total})', 'steps.tabModels': 'Analytics', 'steps.allAgents': 'All Agents', 'steps.allModels': 'All Models', 'steps.selectModel': 'Select Model', 'steps.unitAgent': 'agents', 'steps.unitModel': 'models', 'steps.lineTitle': 'Session Timeline', 'steps.fitTitle': 'Trend Fit', 'steps.modelsTitle': 'Model Summary', 'steps.modelsEmpty': 'No model calls in current scope', 'steps.metricTotalTokens': 'Tokens', 'steps.metricContext': 'Context', 'steps.metricTps': 'TPS', 'steps.metricTtft': 'TTFT', 'steps.metricCache': 'Cache', 'steps.metricCost': 'Cost', 'steps.badgeBackAll': 'Click to return to All Agents', 'steps.badgeFilterAgent': 'Click to filter {agent} (Ctrl/Shift-click to multi-select)', 'steps.ctxTitle': 'Context {ctx} · Thinking {think} · Reply {resp}', 'steps.ioCacheTitle': 'New In {inPart} · Out {outPart} · Cache Read {cachePart}', 'steps.tokSeg.context.th': 'Ctx', 'steps.tokSeg.context.tip': 'Context', 'steps.tokSeg.in.th': 'In', 'steps.tokSeg.in.tip': 'New In', 'steps.tokSeg.out.th': 'Out', 'steps.tokSeg.out.tip': 'Output', 'steps.tokSeg.cache.th': 'Cache', 'steps.tokSeg.cache.tip': 'Cache Read', 'steps.tokSeg.think.th': 'Think', 'steps.tokSeg.think.tip': 'Thinking', 'steps.tokSeg.reply.th': 'Reply', 'steps.tokSeg.reply.tip': 'Reply', 'steps.tokSeg.total.th': 'Total', 'steps.tokSeg.total.tip': 'Total', 'steps.modelCallsShare': '{calls} calls · {pct}%', 'steps.modelCallsOnly': '{calls} calls', 'steps.modelsSummaryPrefix': '{count} models · ', 'steps.modelPerfFoot': 'Avg {tps} · TTFT {ttft} · Cache {cache}%', 'steps.modelSplitFoot': 'In {inTok} · Cache {cacheTok} · Think {thinkTok} · Out {respTok}', 'steps.fitActiveCardTitle': '{title} (Active in Trend Fit; Ctrl/Shift-click to compare)', 'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)', 'steps.turnMediaOnly': '[Media Attachment]', 'steps.turnMediaSuffix': '[Media]', 'steps.anomalyTag.timeout': 'TO{n}', 'steps.anomalyTag.rate_limit': '429×{n}', 'steps.anomalyTag.capacity': '503×{n}', 'steps.anomalyTag.capacitySingle': '503', 'steps.anomalyTag.disconnect': 'Drop{n}', 'steps.anomalyTag.upstream': '500×{n}', 'steps.anomalyTag.upstreamSingle': '500', 'steps.anomalyTag.model_output': 'Fix{n}', 'steps.anomalyTag.safety': 'Safe{n}', 'steps.anomalyTag.auth_or_model': 'Err{n}', 'steps.anomalyTag.error': 'Err{n}', 'steps.anomalyTag.mixed': 'Warn{n}', 'steps.anomalyKind.timeout': 'Stream Idle / Connect Timeout', 'steps.anomalyKind.rate_limit': '429 Rate Limit / Quota Reached', 'steps.anomalyKind.capacity': '503 No Capacity Available', 'steps.anomalyKind.disconnect': 'Connection Reset / Stream Interrupted', 'steps.anomalyKind.upstream': 'Upstream 5xx Internal Error', 'steps.anomalyKind.model_output': 'Invalid Model Output / Tool Call', 'steps.anomalyKind.safety': 'Content Safety Filter', 'steps.anomalyKind.auth_or_model': 'Request / Model Rejected', 'steps.anomalyKind.error': 'Call Error', 'steps.anomalyKind.canceled': 'Canceled by User', 'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors', 'steps.anomalyDelayPart': 'Backoff {sec}s', 'steps.compactionStepTitle': '#{step} · Auto-Compaction', 'steps.compactionSummaryRow': 'Input {input} → Summary {output}', 'steps.compactionDetailHint': 'Automatic context compaction step triggered to summarize history and free window space', 'steps.compactionAnomalyHint': 'This step is also an auto-compaction step', 'steps.timingStepTitle': '#{step} · Timing Breakdown', 'steps.timingTotalSub': 'Total {sec}', 'steps.timingTtftLabel': 'First Token (TTFT)', 'steps.timingStreamLabel': 'Streaming', 'steps.timingAfterTtftLabel': 'After First Token', 'steps.timingThinkLabel': 'Native Thinking', 'steps.timingTotalLabel': 'Total Duration', 'steps.timingOverlapHint': 'Native thinking timing may overlap TTFT/streaming; not additive', 'steps.timingToolBufferedHint': 'Tool call step (buffered return yields short stream)', 'steps.timingAnomalyHint': '{count} retries/errors', 'steps.timingAnomalyDelayHint': '{count} retries/errors · backoff {sec}s', 'steps.anomalyTerminalTag': 'Stopped', 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', 'steps.anomalyModelSub': '{steps} steps affected', 'steps.anomalyModelKindRow': '{kind}: {count}', 'steps.anomalyModelClickHint': 'Click to filter anomalous steps', 'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)', 'steps.anomalyFilterLabel': 'Anomalies Only ({count})', 'steps.anomalyFilterAll': 'Show All Steps', 'steps.sortClickTip': 'Click to sort by {col}', 'steps.searchPlaceholder': 'Filter #step, model, prompt, or anomaly...', 'steps.searchClearAria': 'Clear step filter', 'steps.chipAnomaly': 'Anomaly {count}', 'steps.chipCompaction': 'Compact {count}', 'steps.chipLowCache': 'Low Cache {count}', 'steps.chipLowCacheTip': 'Filter steps with cache hit rate below 50%', 'steps.chipSlowTtft': 'Slow TTFT {count}', 'steps.chipSlowTtftTip': 'Filter severely delayed steps with TTFT >= 30s', 'steps.exportMenuAria': 'Export and report actions', 'steps.exportXlsx': 'Export Excel (.xlsx)', 'steps.exportXlsxTip': 'Export styled multi-sheet Excel workbook for steps and model summary', 'steps.exportCsv': 'Export CSV', 'steps.exportCsvTip': 'Export current steps table as CSV', 'steps.exportCsvDone': 'Exported', 'steps.exportMd': 'Copy Markdown Report', 'steps.exportMdTip': 'Copy Markdown diagnostic report for current steps', 'steps.exportMdDone': 'Steps Markdown report copied', // Export & Toast Feedback 'export.savedLocal': 'Exported {file}', 'export.savedPicked': 'Saved {file}', 'export.savedBrowser': 'Downloaded {file}', 'export.savedBrowserHint': 'Saved via browser default Downloads folder', 'export.openFolder': 'Show in Folder', 'export.failed': 'Export failed, please retry', 'export.hostUnavailable': 'Local export channel unavailable; please restart Antigravity and retry', 'export.copied': 'Copied to clipboard', 'export.copyFailed': 'Copy failed, check clipboard permissions', 'export.closeToast': 'Dismiss notification', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': 'Step', 'stepCol.step.opt': 'Step Number (#)', 'stepCol.time.th': 'Time', 'stepCol.time.opt': 'Timestamp (HH:mm:ss)', 'stepCol.model.th': 'Model', 'stepCol.model.opt': 'Model', 'stepCol.tps.th': 'Speed', 'stepCol.tps.opt': 'Output Speed (TPS)', 'stepCol.ttft.th': 'TTFT', 'stepCol.ttft.opt': 'First Token (TTFT)', 'stepCol.duration.th': 'Time(s)', 'stepCol.duration.opt': 'Total Duration (s)', 'stepCol.tokens_combo.th': 'Ctx / Think / Reply', 'stepCol.tokens_combo.opt': 'Ctx / Think / Reply (Combo)', 'stepCol.tokens_io_cache.th': 'In / Out / Cache', 'stepCol.tokens_io_cache.opt': 'In / Out / Cache (Combo)', 'stepCol.tokens_custom.opt': 'Custom Combo ({fmt})', 'stepCol.input_tokens.th': 'Input', 'stepCol.input_tokens.opt': 'New Input Tokens', 'stepCol.cache_tokens.th': 'CacheTok', 'stepCol.cache_tokens.opt': 'Cache Read Tokens', 'stepCol.output_tokens.th': 'Output', 'stepCol.output_tokens.opt': 'Total Output Tokens', 'stepCol.cache.th': 'Cache', 'stepCol.cache.opt': 'Cache Hit Rate (%)', 'stepCol.cost.th': 'Cost', 'stepCol.cost.opt': 'Step Cost ($)', // Preferences (3-Tab Modular Settings) 'settings.subTab.general': 'General', 'settings.subTab.structure': 'Structure', 'settings.subTab.account': 'Account', 'settings.subTab.other': 'Other', 'settings.account.current': 'Current account', 'settings.account.signedOut': 'Signed out', 'settings.account.unknown': 'Account status unavailable', 'settings.account.email': 'Account email', 'settings.account.googleLogin': 'Sign in with Google', 'settings.account.loginHint': 'Sign in with Google in your browser. The account will appear in this list automatically.', 'settings.account.loginWaiting': 'Choose a Google account and complete authorization in your browser. This list will update automatically.', 'settings.account.loginFinishing': 'Authorization received. Saving the account…', 'settings.account.loginSuccess': 'Signed in. The account has been added.', 'settings.account.loginCancelled': 'Sign-in cancelled.', 'settings.account.loginExpired': 'Sign-in expired. Click Sign in with Google to try again.', 'settings.account.loginDenied': 'Google authorization was cancelled. Try signing in again.', 'settings.account.loginStartFailed': 'Sign-in could not start. Try again.', 'settings.account.loginExchangeFailed': 'Sign-in could not finish. Check your connection and authorize again.', 'settings.account.openLoginPage': 'Reopen Google authorization', 'settings.account.cancelLogin': 'Cancel sign-in', 'settings.account.importExisting': 'Import existing credentials', 'settings.account.credential': 'OAuth credential', 'settings.account.credentialPlaceholder': 'Paste 1// refresh token or OAuth JSON…', 'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.', 'settings.account.save': 'Import credential', 'settings.account.capture': 'Save current credential', 'settings.account.reload': 'Refresh list', 'settings.account.switch': 'Switch and restart', 'settings.account.switchHint': 'Switching closes and reopens Antigravity App and the IDE sharing its sign-in. Save your work first.', 'settings.account.restarting': 'Restarting Antigravity with the selected account…', 'settings.account.switchStartFailed': 'The account switch could not start. Refresh the list and try again.', 'settings.account.clientCloseFailed': 'Antigravity could not fully exit. The switch is incomplete.', 'settings.account.clientRestartFailed': 'The credential was updated. Open Antigravity manually to finish switching.', 'settings.account.remove': 'Remove', 'settings.account.active': 'In use', 'settings.account.savedBadge': 'Backed up', 'settings.account.written': 'Credential written', 'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.', 'settings.account.savedCredentials': 'Saved accounts', 'settings.account.empty': 'No saved credentials.', 'settings.account.loading': 'Loading saved credentials…', 'settings.account.saved': 'Credential saved.', 'settings.account.removed': 'Saved credential removed.', 'settings.account.switched': 'Account switched. Refreshing the current quota.', 'settings.account.switching': 'Verifying the credential and preparing to restart…', 'settings.account.verifying': 'Verifying the credential owner…', 'settings.account.loadQuota': 'Check quota', 'settings.account.loadingQuota': 'Checking…', 'settings.account.refreshFreqAria': 'Background account quota refresh interval', 'settings.account.refresh10m': '10 min', 'settings.account.refresh30m': '30 min', 'settings.account.refresh1h': '1 hr', 'settings.account.refresh3h': '3 hr', 'settings.account.refresh6h': '6 hr', 'settings.account.refresh12h': '12 hr', 'settings.account.refresh24h': '24 hr', 'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.', 'settings.account.quota': 'Quota remaining by pool', 'settings.account.quota5h': '5 hours {percent}%', 'settings.account.quotaWeekly': 'Weekly {percent}%', 'settings.account.noQuota': 'Quota pools are unavailable for the current account.', 'settings.account.quotaStale': 'Quota refresh failed. Showing the last data for the current account.', 'settings.account.unsupported': 'Credential switching currently supports Antigravity shared sign-in on Windows.', 'settings.account.invalidEmail': 'Select a saved account first.', 'settings.account.invalidCredential': 'Enter a valid Antigravity OAuth credential for a personal account.', 'settings.account.credentialTooLarge': 'The credential exceeds the Windows Credential Manager limit of 2560 bytes.', 'settings.account.notFound': 'This credential was removed. Refresh the list.', 'settings.account.noCurrentCredential': 'The shared credential for the current account is unavailable.', 'settings.account.busy': 'Another window is updating credentials. Try again shortly.', 'settings.account.storeFailed': 'The credential operation failed. Try again.', 'settings.account.rollbackFailed': 'Writing and restoring the credential both failed. Check the active account in Antigravity before continuing.', 'settings.account.credentialAccessDenied': 'Windows denied access to Credential Manager. Open Antigravity in your Windows user session and try again.', 'settings.account.credentialChanged': 'This credential was updated in another window. Refresh the list and try again.', 'settings.account.credentialRejected': 'Google rejected this credential. Check that the Antigravity refresh token is still valid.', 'settings.account.identityMismatch': 'The credential belongs to a different account. Import the credential again.', 'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.', 'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.', 'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.', 'settings.account.switchConfirm': 'Confirm switch', 'settings.account.removeConfirm': 'Confirm remove', 'settings.account.pwdBtnSet': 'Passphrase', 'settings.account.pwdBtnManage': 'Passphrase', 'settings.account.lockNow': 'Lock', 'settings.account.lockNowTip': 'Lock credential vault now', 'settings.account.unlockBtn': 'Unlock', 'settings.account.unlockPlaceholder': 'Enter passphrase to unlock…', 'settings.account.vaultLockedHint': 'Credential vault is locked. Enter your passphrase to switch accounts, manage credentials, or refresh quotas.', 'settings.account.forgotPwdToggle': 'Forgot?', 'settings.account.resetVaultHint': 'Encrypted backups cannot be recovered without the passphrase (your active IDE sign-in is unaffected). You can clear and reset the vault.', 'settings.account.resetVaultBtn': 'Reset vault', 'settings.account.resetVaultConfirm': 'Confirm reset', 'settings.account.pwdTabChange': 'Change passphrase', 'settings.account.pwdTabDisable': 'Remove passphrase', 'settings.account.pwdCurrentPlaceholder': 'Current passphrase…', 'settings.account.pwdNewPlaceholder': 'New passphrase (4–128 chars)…', 'settings.account.pwdConfirmPlaceholder': 'Confirm passphrase…', 'settings.account.pwdEnableSubmit': 'Enable', 'settings.account.pwdChangeSubmit': 'Update', 'settings.account.pwdDisableSubmit': 'Disable', 'settings.account.pwdSetHint': 'Adds passphrase encryption to all saved refresh tokens. Asked once per session when managing accounts; cannot be recovered if forgotten.', 'settings.account.pwdManageHint': 'Verify your current passphrase to set a new one or return to default OS encryption.', 'settings.account.pwdEnabledToast': 'Passphrase encryption enabled.', 'settings.account.pwdChangedToast': 'Passphrase updated.', 'settings.account.pwdDisabledToast': 'Passphrase protection disabled.', 'settings.account.vaultUnlockedToast': 'Credential vault unlocked.', 'settings.account.vaultLockedToast': 'Credential vault locked.', 'settings.account.vaultResetToast': 'Credential vault cleared and reset.', 'settings.account.vaultLocked': 'Enter your passphrase to unlock the vault first.', 'settings.account.wrongPassword': 'Incorrect passphrase. Try again.', 'settings.account.invalidPassword': 'Passphrase must be 4–128 characters and not blank.', 'settings.account.passwordMismatch': 'Passphrases do not match.', 'settings.account.passwordRateLimited': 'Too many failed attempts. Wait a moment and try again.', 'settings.account.vaultDecryptFailed': 'Vault decryption check failed.', 'settings.account.invalidActionNonce': 'Security token expired. Please try again.', 'settings.account.riskNotAccepted': 'Acknowledge the unofficial feature risk warning first.', 'settings.account.riskBody': 'Google has not authorized importing, storing, or switching Antigravity credentials or polling multi-account quotas in Antigravity App / IDE. Enabling multi-account management may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', 'settings.account.trendTitle': 'Quota Trend', 'settings.account.trendWinAria': 'Quota window selector', 'settings.account.win5h': '5 Hours', 'settings.account.winWeekly': 'Weekly', 'settings.account.trendEmpty': 'No quota history recorded in the selected time range.', 'settings.subTab.aria': 'Preferences category tabs', 'settings.saving': 'Saving…', 'settings.saved': 'Saved', 'settings.saveFailed': 'Save failed', 'settings.resetDone': 'Reset to default', 'settings.resetBtn': 'Reset', // Preferences -> General Tab 'settings.gen.appearanceTitle': 'Interface & Appearance', 'settings.gen.language': 'Language', 'settings.gen.langZh': '简体中文', 'settings.gen.langEn': 'English', 'settings.gen.langAuto': 'Follow System', 'settings.gen.themeAccent': 'Accent Color', 'settings.gen.accentHost': 'Host', 'settings.gen.accentBlue': 'Blue', 'settings.gen.accentEmerald': 'Emerald', 'settings.gen.accentAmber': 'Amber', 'settings.gen.accentViolet': 'Violet', 'settings.gen.accentCyan': 'Cyan', 'settings.gen.accentRose': 'Rose', 'settings.gen.fontScale': 'Font Size', 'settings.gen.fontSm': 'Small', 'settings.gen.fontMd': 'Default', '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', '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', 'settings.gen.updateAuto': 'Auto update', 'settings.gen.updateOff': 'Disable updates', 'settings.gen.pricingLabel': 'Pricing Catalog', 'settings.gen.versionLabel': 'Current Version', 'settings.gen.modelCount': '{count} models', 'settings.gen.srcRemote': 'Cloud synced', 'settings.gen.srcLocal': 'Local file', 'settings.gen.srcDefault': 'Built-in', 'settings.gen.syncAt': 'Synced {time}', 'settings.gen.pubAt': 'Published {date}', 'settings.gen.defaultPricing': 'Default catalog', 'settings.gen.syncBtn': 'Sync Pricing', 'settings.gen.syncingBtn': 'Syncing…', 'settings.gen.syncingMsg': 'Syncing pricing catalog…', 'settings.gen.syncedMsg': 'Pricing updated ({count} models)', 'settings.gen.syncFallbackMsg': 'Timed out, using local catalog', 'settings.gen.checkUpdateBtn': 'Check Updates', 'settings.gen.checkingBtn': 'Checking…', 'settings.gen.checkingMsg': 'Checking for updates…', 'settings.gen.checkFailedMsg': 'Check failed: {err}', 'settings.gen.upToDateMsg': 'Already up to date (v{ver})', 'settings.gen.downloadingMsg': 'Downloading update…', 'settings.gen.updatedRestartMsg': 'Update complete, restarting panel…', 'settings.gen.updateSkippedMsg': 'Update not applied', 'settings.gen.updateFailedMsg': 'Update failed', 'settings.gen.canUpgradeSub': 'v{ver} available ({mode})', 'settings.gen.upgradeToBtn': 'Upgrade to v{ver}', 'settings.gen.manualUpgradeBtn': 'Upgrade v{ver}', 'settings.gen.updateOffSub': 'Notifications off ({mode})', 'settings.gen.latestSub': 'Up to date ({mode})', // Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n) 'settings.hostI18n.title': 'Antigravity UI Language', 'settings.hostI18n.langLabel': 'Host Language', 'settings.hostI18n.langOff': 'Original (Off)', 'settings.hostI18n.langHint': 'Downloads built language packs on demand from the repository and applies lossless runtime UI translation without patching app files or chat content', 'settings.hostI18n.optInstalled': 'Installed v{ver}', 'settings.hostI18n.optRemote': 'Download · {size}', 'settings.hostI18n.refreshManifestTip': 'Refresh repository language pack manifest', 'settings.hostI18n.refreshingManifestMsg': 'Refreshing language manifest…', 'settings.hostI18n.manifestSyncedMsg': 'Manifest updated ({count} packs)', 'settings.hostI18n.manifestFailedMsg': 'Failed to fetch language manifest', 'settings.hostI18n.depthLabel': 'Translation Depth', 'settings.hostI18n.depthLight': 'Light', 'settings.hostI18n.depthDeep': 'Deep', 'settings.hostI18n.depthLightHint': 'Light mode keeps common English engineering terms (MCP, Skill, Workspace, Subagent, Swarm, Diff, Terminal) and model names untranslated', 'settings.hostI18n.depthDeepHint': 'Deep mode localizes engineering terms alongside general UI copy while preserving model names and slash commands', 'settings.hostI18n.downloadingMsg': 'Downloading {locale} pack…', 'settings.hostI18n.downloadedAndAppliedMsg': 'Pack verified and applied', 'settings.hostI18n.appliedMsg': 'Language applied live', 'settings.hostI18n.disabledMsg': 'Translation disabled and UI restored', 'settings.hostI18n.depthSwitchedMsg': 'Translation depth switched', 'settings.hostI18n.packUpdatedMsg': 'Language pack updated and reapplied', 'settings.hostI18n.cacheRemovedMsg': 'Local pack cache removed', 'settings.hostI18n.actionFailed': 'Language pack operation failed', 'settings.hostI18n.entriesCount': '{count} entries', 'settings.hostI18n.appliedWindows': '{count} window(s) active', 'settings.hostI18n.updatePackBtn': 'Update to v{ver}', 'settings.hostI18n.redownloadBtn': 'Check Update', 'settings.hostI18n.removeCacheBtn': 'Remove Cache', 'settings.hostI18n.devToolsTitle': 'Missing UI String Collector', 'settings.hostI18n.devToolsHint': 'Scans visible Antigravity UI controls for untranslated English phrases (excluding chat content and code) to help complete packs or author new languages', 'settings.hostI18n.collectBtn': 'Collect Missing Strings', 'settings.hostI18n.collectingBtn': 'Collecting…', 'settings.hostI18n.collectedResult': 'Collected {count} untranslated UI strings across {targets} window(s)', 'settings.hostI18n.collectedEmpty': 'No untranslated English UI strings detected on active pages', 'settings.hostI18n.collectFailed': 'Collection failed — verify remote debugging bridge is active', 'settings.hostI18n.copyJsonBtn': 'Copy JSON', 'settings.hostI18n.exportJsonBtn': 'Export JSON', // Preferences -> Structure Tab 'settings.str.thirdTabAria': 'Structure section tabs', 'settings.str.tabMount': 'Mount & Bar', 'settings.str.tabHover': 'Hover View', 'settings.str.tabOverview': 'Overview', 'settings.str.tabSteps': 'Step Table', 'settings.str.previewMountSidebarHint': 'Window capsule is disabled in Sidebar Only mode; switching back to Titlebar or Composer applies the capsule above', 'settings.str.mountSection': 'Mount & Capsule Bar', 'settings.str.mountBadge': '{count}/5 slots', 'settings.str.mountMode': 'Panel Mount Mode', 'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)', 'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)', 'settings.str.mountSidebar': 'Sidebar Only', 'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate', 'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override', 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.', 'settings.bridge.readOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch to Activate', 'settings.bridge.ctxReadOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch for Context Override', 'settings.bridge.readOnlyBody': 'Personal launch entries are configured, but public shortcuts require administrator permission. Click below and approve the system prompt to patch public shortcuts once and relaunch.', 'settings.bridge.macTitle': 'Debug Port Inactive — One-Click Relaunch to Enable Mount', 'settings.bridge.ctxMacTitle': 'Debug Port Inactive — One-Click Relaunch for Context Override', 'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive', 'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive', 'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending', 'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.', 'settings.bridge.guideMac': 'Due to macOS app code signing, cold launches from Dock omit the debug port flag. Click below to relaunch with the flag in one click (stays active until you fully Quit via Cmd+Q).', 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.', 'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount', 'settings.bridge.relaunchAuthBtn': 'Authorize & Relaunch', 'settings.bridge.relaunchingBtn': 'Relaunching Host...', 'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry', 'settings.bridge.dismissAria': 'Dismiss notice for now', 'settings.bridge.copyFlagBtn': 'Copy {cmd}', 'settings.bridge.copiedBtn': 'Copied to Clipboard', 'settings.str.popoverWidthLabel': 'Popover Width', 'settings.str.popoverWidthAuto': 'Auto Fit', 'settings.str.popoverWidthCustom': 'Custom', 'settings.str.popoverWidthHint': 'Auto Fit widens wide tables like Step Records to avoid horizontal scroll; Custom accepts 440–1080 px', 'settings.str.multiToggle': 'Active Sessions Pill', 'settings.str.contextAgentModeLabel': 'Capsule & Hover Context', 'settings.str.contextAgentMain': 'Lock Main Agent', 'settings.str.contextAgentAuto': 'Follow Active', 'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule', 'settings.str.cliSlotsLabel': 'CLI Slot Order (Left → Right, 1–6, draggable)', 'settings.str.addCliSlot': 'Add CLI Slot ({count}/{max})', 'settings.str.cliCustomCmdHint': 'Custom statusLine command detected; preserved automatically unless you take over', 'settings.str.cliPausedHint': 'CLI statusLine is currently paused or not yet configured', 'settings.str.cliFlagsOverrideHint': 'Explicit CLI launch flags (--slots / --preset) detected and take precedence over these slots', 'settings.str.cliRestoreBtn': 'Take Over & Restore', 'settings.str.cliEnableBtn': 'Re-enable in CLI', 'settings.str.cliClearFlagsBtn': 'Clear Flag Override', 'settings.str.cliRestoringBtn': 'Applying...', 'settings.str.cliPreviewRunning': '{count} active', 'settings.str.show': 'Show', 'settings.str.hide': 'Hide', 'settings.str.on': 'On', 'settings.str.off': 'Off', 'settings.str.capsuleSlotsLabel': 'Capsule Metrics & Order (Left → Right, 1–5, draggable)', 'settings.str.addCapsuleSlot': 'Add Slot ({count}/{max})', 'settings.str.hoverSection': 'Hover Quick-View', 'settings.str.hoverBadgeOff': 'Off', 'settings.str.hoverBadgeCount': '{count} modules', 'settings.str.hoverModulesLabel': 'Hover Popup Modules (Top → Bottom, 0–4, draggable)', 'settings.str.hoverEmptyHint': 'Hover quick-view disabled (click capsule to open full panel)', 'settings.str.addHoverModule': 'Add Module ({count}/{max})', 'settings.str.overviewSection': 'Live Overview Layout', 'settings.str.overviewBadge': '{modCount} mod · {metCount} cells', 'settings.str.overviewModulesLabel': 'Overview Modules & Order (Top → Bottom, min 1, draggable)', 'settings.str.addOverviewModule': 'Add Module ({count}/{max})', 'settings.str.overviewMetricsLabel': 'First-Row Metrics (Left → Right, 1–4, draggable)', 'settings.str.overviewMetricsInactiveHint': '"Live Metrics" is hidden here; these cells still apply to Hover Quick-View or when re-added', 'settings.str.addOverviewMetric': 'Add Metric ({count}/{max})', 'settings.str.stepsSection': 'Step Table Columns', 'settings.str.stepsBadge': '{count} cols', 'settings.str.stepTurnRailToggle': 'Turn Rail & Preview', 'settings.str.stepAgentBadgeToggle': 'Main/Sub Agent Badge', 'settings.str.stepSpeedColorToggle': 'Speed Multi-Color', 'settings.str.stepFilterToolbarToggle': 'Search & Filter Bar', 'settings.str.stepTokenComboLabel': 'Custom Token Combo Format', 'settings.str.stepTokenComboPlaceholder': 'e.g. context:new:cache or in:out:cache', 'settings.str.stepTokenComboHint': 'Tokens: context, in/new, out, cache, think, reply, total — separated by : or / (1–4 items)', 'settings.str.stepsColsLabel': '"Steps" Visible Columns (Left → Right, min 2, draggable)', 'settings.str.addStepCol': 'Add Column ({count}/{max})', 'settings.slot.dragHint': 'Drag up or down to reorder', 'settings.slot.moveUp': 'Move earlier', 'settings.slot.moveDown': 'Move later', 'settings.slot.remove': 'Remove item', 'settings.slot.minReached': 'Keep at least {min}', 'settings.slot.alreadyAdded': 'Added', 'settings.mock.sessionTitle': 'Refactor Auth Middleware & Session Cache', 'settings.mock.subRole': 'API Audit', 'settings.mock.turnPromptLatest': 'Fix token refresh race condition under concurrent requests and add tests', 'settings.mock.turnPromptPrev': 'Audit route guards and expired session cleanup logic', // Preferences -> Other Tab 'settings.oth.modelTitle': 'Model Identity Display', 'settings.oth.modelFormat': 'Model Name Format', 'settings.oth.modelShort': 'Short Alias (e.g. argon-4-high)', 'settings.oth.modelUpstream': 'Raw Upstream ID (e.g. gemini-3.8-flash-n)', 'settings.oth.modelUpstreamCompact': 'Trimmed Raw ID (hide gemini- / claude- / gpt-)', 'settings.oth.orchFormat': 'Orchestrator Series ID', 'settings.oth.orchCompact': 'Compact Alias (e.g. orchestrator-argon)', 'settings.oth.orchFull': 'Full Upstream ID (e.g. gemini-pro-orchestrator)', 'settings.oth.expTitle': 'Experimental', 'settings.oth.expBadge': 'Experimental', 'settings.oth.quotaReserveLabel': 'Quota Reservation Estimate', 'settings.oth.quotaReserveDesc': 'Estimate 0.5% / 1% 5h & weekly lease holds in Available Quotas and highlight the reserved share in violet', 'settings.oth.quotaReserveLogLabel': 'Reservation Observation Log', 'settings.oth.quotaReserveLogDesc': 'Copy persisted quota jump & refund observations to clipboard (retained across restarts)', 'settings.oth.exportReserveLogBtn': 'Export Reserve Log', 'settings.oth.exportReserveLogCopied': 'Copied {count} log entries to clipboard', 'settings.oth.exportReserveLogEmpty': 'No events yet; copied current summary to clipboard', 'settings.oth.exportReserveLogFailed': 'Failed to copy reservation log', 'settings.oth.baselineTitle': 'Model Context Settings', 'settings.oth.ctxRiskTitle': 'Unofficial Override Risk Warning', 'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', 'settings.oth.ctxRiskAcceptBtn': 'I Understand the Risk, Unlock', 'settings.oth.ctxModel': 'Model', 'settings.oth.ctxMainLabel': 'Main Agent', 'settings.oth.ctxSwarmLabel': 'Subagents & Swarm', 'settings.oth.ctxSwarmError': 'Local sync failed: {error}', 'settings.oth.ctxBaselineLabel': 'Context Window Limit', 'settings.oth.ctxChooseModel': 'Choose a model', 'settings.oth.ctxDefault': 'Follow host settings', 'settings.oth.ctxExpensive': '{name} (uses more quota)', 'settings.oth.ctxTokens': '{count} tokens', 'settings.oth.ctxUnavailable': '{name} (currently unavailable)', 'settings.oth.ctxConfigured': '{name} · Set', 'settings.oth.ctxConfiguredReported': '{name} · Set / Last seen {reported}', 'settings.oth.ctxPendingBridge': '{name} · Pending Restart', 'settings.oth.ctxDefaultReported': 'Default · Last seen {name}', 'settings.oth.ctxReported': 'The host reported {name} on the latest request.', 'settings.oth.ctxMixed': 'Different limits by thinking level', 'settings.oth.ctxMixedHint': 'Thinking levels for this model have different saved limits. Choose a limit to apply it to all levels.', 'settings.oth.ctxBaselineHint': 'Thinking levels for the same model share a limit. Saved limits are reapplied at plugin startup and used for future messages.', 'settings.oth.ctxNoModels': 'The host has not returned any available models.', 'settings.oth.ctxNoOptions': 'The host has not provided context options or a capacity for this model. Follow host settings is the only available option.', 'settings.oth.maintTitle': 'Cache & Reset', 'settings.oth.cacheLabel': 'Local Trajectory Cache', 'settings.oth.cacheDesc': 'Clear cached step records and rescan all conversation transcripts immediately', 'settings.oth.rebuildBtn': 'Rebuild Trajectory Cache', 'settings.oth.rebuildingBtn': 'Rebuilding…', 'settings.oth.rebuildDone': 'Trajectory cache rebuilt', 'settings.oth.rebuildFailed': 'Failed to rebuild cache', 'settings.oth.resetLabel': 'Factory Defaults', 'settings.oth.resetDesc': 'Restore all preferences across General, Structure, and Other tabs to default values', 'settings.oth.resetAllBtn': 'Reset All Defaults', 'settings.oth.resetConfirmBtn': 'Click Again to Confirm', 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', 'settings.oth.backupLabel': 'Preferences Backup & Restore', 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON', 'settings.oth.exportJsonBtn': 'Export JSON', 'settings.oth.importJsonBtn': 'Import JSON', 'settings.oth.exportDone': 'Preferences JSON exported', 'settings.oth.importDone': 'Restored {count} preference settings', 'settings.oth.importInvalid': 'Import failed: invalid JSON or no recognized settings', 'settings.oth.migTitle': 'Cross-Client Session Migration', 'settings.oth.migDesc': 'Migrate selected sessions on demand with automatic source and summary backups', 'settings.oth.migRefreshBtn': 'Refresh', 'settings.oth.migSourceLabel': 'Source Client', 'settings.oth.migTargetLabel': 'Target Client', 'settings.oth.migModeLabel': 'Migration Mode', 'settings.oth.migModeMove': 'Full Move (Recommended)', 'settings.oth.migModeClone': 'Clone Copy', 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving', 'settings.oth.migModeCloneHint': 'Keeps source intact with a fresh UUID; only counts new steps generated after cloning', 'settings.oth.migProjectLabel': 'Target Project', 'settings.oth.migProjectOutside': 'Standalone (No Project)', 'settings.oth.migClientDesktop': 'Desktop App / Modern IDE', 'settings.oth.migClientCli': 'Antigravity CLI', 'settings.oth.migClientIdeLegacy': 'Legacy IDE (.db)', 'settings.oth.migSearchPlaceholder': 'Filter sessions by title or workspace…', 'settings.oth.migSelectAll': 'Select all', 'settings.oth.migClearSel': 'Clear', 'settings.oth.migSelectedCount': '{selected} / {total} selected', 'settings.oth.migRunningTag': 'Running', 'settings.oth.migStepsUnit': '{count} steps', 'settings.oth.migEmpty': 'No migratable sessions in this source client', 'settings.oth.migNoMatch': 'No matching sessions', 'settings.oth.migActionBtn': 'Migrate Selected ({count})', 'settings.oth.migRunningBtn': 'Migrating…', 'settings.oth.migDoneDesktop': 'Migrated {count} session(s) to "{project}". Press Ctrl+R in Desktop App to refresh the sidebar', 'settings.oth.migDoneCli': 'Migrated {count} session(s) to CLI. Use the command below to resume', 'settings.oth.migPartialWarn': ' ({failed} skipped or failed)', 'settings.oth.migReloadBtn': 'Reload Window', 'settings.oth.migCopyCmd': 'Copy', 'settings.oth.migCopied': 'Copied', 'settings.oth.migErrLocked': 'Source database is locked by its open client. Close that terminal/window first, or switch to Clone Copy', 'settings.oth.migErrExists': 'A session with the same ID already exists in target (switch to Clone Copy if you want a duplicate)', 'settings.oth.migErrRunning': 'Session is currently running; wait until idle before migrating', 'settings.oth.migFailed': 'Migration failed: {reason}', // Structured Live Activity Actions 'live.act.run_command': 'Run Command', 'live.act.read_file': 'Read File', 'live.act.edit_file': 'Edit File', 'live.act.write_file': 'Write File', 'live.act.grep_search': 'Search Code', 'live.act.find_file': 'Find Files', 'live.act.read_url': 'Read Web Page', 'live.act.search_web': 'Search Web', 'live.act.invoke_subagent': 'Invoke Subagent', 'live.act.send_message': 'Message Subagent', 'live.act.manage_subagents': 'Manage Subagents', 'live.act.swarm_add': 'Spawn Worker', 'live.act.swarm_title': 'Name Swarm', 'live.act.swarm_kill': 'Kill Worker', 'live.act.swarm_model': 'Switch Worker Model', 'live.act.swarm_channel': 'Swarm Channel', 'live.act.swarm_status': 'Check Swarm', 'live.act.post_message': 'Post to Board', 'live.act.read_board': 'Read Board', 'live.act.swarm_wait': 'Parked on Board', 'live.act.manage_task': 'Manage Task', 'live.act.schedule': 'Schedule Task', 'live.act.ask_question': 'Waiting for User Choice', 'live.act.search_marketplace': 'Search Plugins', 'live.act.generate_image': 'Generate Image', 'live.act.mcp_tool': 'Call MCP Tool', 'live.act.tool_call': 'Call Tool', 'live.act.thinking': 'Thinking', 'live.act.compacting': 'Compacting Context', 'live.act.responding': 'Responding', 'live.act.waiting_subagent': 'Waiting for Subagent', 'live.act.waiting_swarm': 'Waiting for Swarm', 'live.act.swarm_waiting': 'Waiting', 'live.act.swarm_killed': 'Killed', 'live.act.starting': 'Starting', 'live.act.done': 'Completed', 'live.act.awaitingApproval': 'Awaiting Approval · {label}', 'live.act.compactionResuming': 'Compaction finished, resuming reasoning', // SVG Charts (SessionStepCharts & TrendAreaChart) 'chart.step.empty': 'No plottable steps in current scope', 'chart.step.excluded': 'Excluded', 'chart.step.zeroSteps': '0 steps', 'chart.step.stepAdd': 'Step +{tokens}', 'chart.step.ioSplit': 'In {inTok} · Cache {cacheTok} · Out {outTok}', 'chart.step.cacheShort': 'Cache {pct}%', 'chart.step.compactionCheckpoint': 'Auto-compaction checkpoint', 'chart.step.cacheHitOut': 'Cache hit {pct}% · Out +{outTok}', 'chart.step.ttftShort': 'TTFT {sec}s', 'chart.step.outAndCtx': 'Out {outTok} · Context {ctxTok}', 'chart.step.compactionStep': 'Compaction step', 'chart.step.noSpeedSample': 'No speed sample', 'chart.step.ctxAndCache': 'Context {ctxTok} · Cache {pct}%', 'chart.step.noTtftSample': 'No TTFT sample', 'chart.step.cumCost': 'Total {cost}', 'chart.step.cacheAndStepTok': 'Cache {pct}% · Step {tokens}', 'chart.step.noSamples': 'No samples', 'chart.step.peakShort': 'Peak {val}', 'chart.step.peakPill': 'Peak {tag} · {val}', 'chart.step.stepsCount': '{count} steps', 'chart.step.multiPrefix': '{count} models · ', 'chart.step.sumTokens': '{prefix}Total {tokens}', 'chart.step.peakTokens': '{prefix}Peak {tokens}', 'chart.step.currentCtx': 'Current {tokens}', 'chart.step.meanTps': '{prefix}Avg {val} tok/s', 'chart.step.meanSec': '{prefix}Avg {val}s', 'chart.step.noValidSamples': 'No valid samples', 'chart.step.sumCost': '{prefix}Total {cost}', 'chart.fit.empty': 'No valid regression samples for this model', 'chart.fit.loess': 'LOESS Fit', 'chart.fit.olsLinear': 'OLS Linear', 'chart.fit.olsReg': 'OLS Reg', 'chart.fit.observed': 'Observed', 'chart.fit.tipFit': 'Fit {val}', 'chart.fit.tipObs': 'Obs {val}', 'chart.fit.zeroSamples': '0 samples', 'chart.fit.peerMean': '{label} Avg {val}', 'chart.fit.peerCompare': 'Compare: {peers}', 'chart.fit.curvesCount': '{count} fit curves', 'chart.fit.multiBadge': '{steps} steps · {models} models', 'chart.fit.singleBadge': '{steps} steps · Avg {mean}', 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · Sample SD = ±{sd}', 'chart.trend.hmMonthYear': "{month}/{yy}", 'chart.trend.hmMonthOnly': 'M{month}', 'chart.trend.wdayMon': 'M', 'chart.trend.wdayWed': 'W', 'chart.trend.wdayFri': 'F', 'chart.trend.wdaySun': 'S', 'chart.trend.hmAria': 'Daily usage heatmap', 'chart.trend.hmLess': 'Less', 'chart.trend.hmMore': 'More', 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', 'chart.trend.hmActiveZero': 'Active 0/{total}d', 'chart.trend.hmWeekPeak': 'Active {active}/{total}w · Peak {label} · {tokens}', 'chart.trend.hmWeekZero': 'Active 0/{total}w', 'chart.trend.hmMonthPeak': 'Active {active}/{total}m · Peak {label} · {tokens}', 'chart.trend.hmMonthZero': 'Active 0/{total}m', 'chart.trend.hmCumSummary': 'Cumulative {days}d · Total {tokens} · {cost}', 'chart.trend.hmCumThrough': 'Cumulative through {date}', 'chart.trend.peakPill': 'Peak {label} · {tokens}', // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) 'ui.dt.wdayMon': 'Mo', 'ui.dt.wdayTue': 'Tu', 'ui.dt.wdayWed': 'We', 'ui.dt.wdayThu': 'Th', 'ui.dt.wdayFri': 'Fr', 'ui.dt.wdaySat': 'Sa', 'ui.dt.wdaySun': 'Su', 'ui.dt.prevMonth': 'Previous month', 'ui.dt.nextMonth': 'Next month', 'ui.dt.hourMinute': 'Hr / Min', 'ui.num.decrease': 'Decrease value', 'ui.num.increase': 'Increase value', 'ui.seg.defaultAria': 'Segmented switcher', }); return { I18N_MESSAGES_EN_US }; })(); // --- src/i18n/index.js --- const { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nStore, setI18nLanguage, getEffectiveLocale, isEnglishLocale, t } = (() => { /** * @fileoverview Reactive lightweight i18n engine (`zh-CN` / `en-US` / `auto`). * Default language is `'zh-CN'` so out-of-the-box UI matches existing behavior 100%. */ const I18N_DICTIONARIES = Object.freeze({ 'zh-CN': I18N_MESSAGES_ZH_CN, 'en-US': I18N_MESSAGES_EN_US, }); function normalizeI18nLanguage(raw) { return normalizeLanguageSetting(raw); } function detectHostSystemLocale() { try { if (typeof navigator !== 'undefined' && navigator.language) { return String(navigator.language).toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US'; } } catch { // Ignore environment navigator read errors } return 'zh-CN'; } const i18nStore = createReactiveStore({ language: 'auto', locale: detectHostSystemLocale(), }); function setI18nLanguage(rawLang) { const language = normalizeI18nLanguage(rawLang); const locale = language === 'auto' ? detectHostSystemLocale() : language; const cur = i18nStore.getState(); if (cur.language !== language || cur.locale !== locale) { i18nStore.setState({ language, locale }); } return locale; } function getEffectiveLocale() { return i18nStore.getState().locale || 'zh-CN'; } function isEnglishLocale() { return getEffectiveLocale() === 'en-US'; } /** * Translate a message key with optional `{name}` variable interpolation. * * @param {string} key * @param {Record} [vars] * @returns {string} */ function t(key, vars = undefined) { const locale = getEffectiveLocale(); const dict = I18N_DICTIONARIES[locale] || I18N_MESSAGES_ZH_CN; const template = dict[key] ?? I18N_MESSAGES_ZH_CN[key] ?? key; if (!vars || typeof template !== 'string') return template; return template.replace(/\{(\w+)\}/g, (_, k) => vars[k] !== undefined && vars[k] !== null ? String(vars[k]) : '' ); } return { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nStore, setI18nLanguage, getEffectiveLocale, isEnglishLocale, t }; })(); // --- src/core/appearance.js --- const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, resolveSettingsModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot } = (() => { /** * @fileoverview Theme accent palette & panel font-scale appearance engine. * Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts, * while strictly isolating `#ag-usage-monitor-capsule` from font scaling. */ const THEME_ACCENT_PRESETS = Object.freeze([ { key: 'host', labelKey: 'settings.gen.accentHost', cssColor: '' }, { key: 'blue', labelKey: 'settings.gen.accentBlue', cssColor: 'hsl(217 84% 53%)' }, { key: 'emerald', labelKey: 'settings.gen.accentEmerald', cssColor: 'hsl(152 66% 39%)' }, { key: 'amber', labelKey: 'settings.gen.accentAmber', cssColor: 'hsl(34 88% 46%)' }, { key: 'violet', labelKey: 'settings.gen.accentViolet', cssColor: 'hsl(262 76% 58%)' }, { key: 'cyan', labelKey: 'settings.gen.accentCyan', cssColor: 'hsl(191 82% 41%)' }, { key: 'rose', labelKey: 'settings.gen.accentRose', cssColor: 'hsl(346 78% 54%)' }, ]); const FONT_SCALE_FACTORS = Object.freeze({ sm: 0.92, md: 1, lg: 1.14, xl: 1.28, }); const PANEL_SCALE_FACTORS = Object.freeze({ sm: 1, md: 1, lg: 1.09, xl: 1.18, }); function normalizeClientThemeAccent(raw) { const val = String(raw ?? '').trim().toLowerCase(); return THEME_ACCENT_PRESETS.some((p) => p.key === val) ? val : 'host'; } function normalizeClientFontScale(raw) { const val = String(raw ?? '').trim().toLowerCase(); return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md'; } function normalizeClientModernUi(raw) { if (raw === undefined || raw === null || raw === '') return true; if (typeof raw === 'string') { const lower = raw.trim().toLowerCase(); if (lower === 'false' || lower === '0' || lower === 'off') return false; if (lower === 'true' || lower === '1' || lower === 'on') return true; return true; } return Boolean(raw); } function resolveSettingsModernUi(settings) { if (!settings || typeof settings !== 'object') return true; if (settings.modernUi !== undefined) { return normalizeClientModernUi(settings.modernUi); } if (settings.experimentalModernUi !== undefined) { return normalizeClientModernUi(settings.experimentalModernUi); } return true; } /** * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`. * * @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 (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, host color scheme polarity, and (optionally) font scale tokens * onto a root/host element. * * @param {HTMLElement | null | undefined} targetEl * @param {object | null | undefined} settings * @param {{ includeFontScale?: boolean }} [options] */ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = {}) { if (!targetEl || !targetEl.style) return; const accentKey = normalizeClientThemeAccent(settings?.themeAccent); const preset = THEME_ACCENT_PRESETS.find((p) => p.key === accentKey) || THEME_ACCENT_PRESETS[0]; if (preset.key !== 'host' && preset.cssColor) { setOrClearStyleVar(targetEl, '--user-accent-primary', preset.cssColor); setOrClearStyleVar(targetEl, '--user-accent-contrast', '#ffffff'); } else { setOrClearStyleVar(targetEl, '--user-accent-primary', ''); setOrClearStyleVar(targetEl, '--user-accent-contrast', ''); } setAttrIfChanged(targetEl, 'data-accent', preset.key); const colorScheme = detectHostColorScheme(targetEl); setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme); const isModernUi = resolveSettingsModernUi(settings); if (isModernUi) { setAttrIfChanged(targetEl, 'data-modern-ui', 'true'); } else { removeAttrIfPresent(targetEl, 'data-modern-ui'); } if (includeFontScale) { const scaleKey = normalizeClientFontScale(settings?.fontScale); const factor = FONT_SCALE_FACTORS[scaleKey] ?? 1; 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)); setAttrIfChanged(targetEl, 'data-font-scale', scaleKey); } else { setOrClearStyleVar(targetEl, '--ui-font-scale', ''); setOrClearStyleVar(targetEl, '--ui-panel-scale', ''); removeAttrIfPresent(targetEl, 'data-font-scale'); } } return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, resolveSettingsModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot }; })(); // --- src/core/domPatch.js --- const { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList, positionAnchoredPopup } = (() => { /** * @fileoverview Incremental DOM patching utilities and keyed list reconciler. * Prevents full innerHTML replacements and preserves active DOM element state. */ function h(tag, props = {}, children = []) { const el = document.createElement(tag); if (props) { for (const [key, val] of Object.entries(props)) { if (val === undefined || val === null || val === false) continue; if (key === 'className' || key === 'class') { el.className = String(val); } else if (key === 'dataset' && typeof val === 'object') { for (const [dk, dv] of Object.entries(val)) { if (dv !== undefined && dv !== null) { el.dataset[dk] = String(dv); } } } else if (key.startsWith('on') && typeof val === 'function') { const evt = key.slice(2).toLowerCase(); el.addEventListener(evt, val); } else if (key === 'text') { el.textContent = String(val); } else if (val === true) { el.setAttribute(key, ''); } else { el.setAttribute(key, String(val)); } } } const childArray = Array.isArray(children) ? children : [children]; for (const child of childArray) { if (child === null || child === undefined || child === false) continue; if (typeof child === 'string' || typeof child === 'number') { el.appendChild(document.createTextNode(String(child))); } else { el.appendChild(child); } } return el; } function patchText(el, nextValue) { if (!el) return false; const nextStr = String(nextValue ?? ''); if (el.textContent === nextStr) { return false; } el.textContent = nextStr; return true; } function patchAttr(el, attrName, nextValue) { if (!el) return false; if (nextValue === null || nextValue === undefined || nextValue === false) { let mutated = false; if (el.hasAttribute(attrName)) { el.removeAttribute(attrName); mutated = true; } if (attrName === 'value' && 'value' in el && el.value !== '') { el.value = ''; mutated = true; } return mutated; } const strVal = nextValue === true ? '' : String(nextValue); let mutated = false; if (el.getAttribute(attrName) !== strVal) { el.setAttribute(attrName, strVal); mutated = true; } if (attrName === 'value' && 'value' in el && el.value !== strVal) { el.value = strVal; mutated = true; } return mutated; } function patchClasses(el, classMap) { if (!el || !classMap) return false; let mutated = false; for (const [cls, active] of Object.entries(classMap)) { if (!cls) continue; const shouldHave = Boolean(active); const tokens = String(cls).split(/\s+/).filter(Boolean); for (const tok of tokens) { const has = el.classList.contains(tok); if (has !== shouldHave) { el.classList.toggle(tok, shouldHave); mutated = true; } } } return mutated; } function patchStyleVar(el, varName, nextValue) { if (!el) return false; const strVal = String(nextValue ?? ''); const prev = el.style.getPropertyValue(varName); if (prev === strVal) { return false; } el.style.setProperty(varName, strVal); return true; } /** * 判断事件是否发生在目标节点内部(兼容 Shadow DOM 的 `composedPath()` 穿透)。 * * @param {Event|null|undefined} event * @param {Node|null|undefined} element * @returns {boolean} */ function isEventInside(event, element) { if (!event || !element) return false; if (typeof event.composedPath === 'function') { const path = event.composedPath(); if (Array.isArray(path) && path.includes(element)) { return true; } } const target = event.target; return Boolean(target && typeof element.contains === 'function' && element.contains(target)); } 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 = (_, i) => i, sigFn, createRow, updateRow, destroyRow } = {} ) { if (!container) return; let map = keyedListState.get(container); if (!map) { map = new Map(); keyedListState.set(container, map); } const nextKeys = new Set(); const seenInPass = new Map(); const orderedNodes = []; for (let i = 0; i < items.length; i++) { const item = items[i]; const rawKey = String(keyFn(item, i)); const dupIdx = seenInPass.get(rawKey) || 0; seenInPass.set(rawKey, dupIdx + 1); const key = dupIdx === 0 ? rawKey : `${rawKey}__dup_${dupIdx}`; const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item); nextKeys.add(key); let record = map.get(key); if (!record) { const created = createRow(item, i); record = { el: created.el, refs: created.refs, sig, }; updateRow(record.refs, item, i, record.el); map.set(key, record); } else if (record.sig !== sig) { record.sig = sig; updateRow(record.refs, item, i, record.el); } orderedNodes.push(record.el); } // Remove stale keys for (const [oldKey, record] of map.entries()) { if (!nextKeys.has(oldKey)) { if (record.el.parentNode === container) { container.removeChild(record.el); } destroyRow?.(record.refs, record.el); map.delete(oldKey); } } if (!container.firstChild && orderedNodes.length > 1 && typeof document.createDocumentFragment === 'function') { const fragment = document.createDocumentFragment(); for (const node of orderedNodes) { fragment.appendChild(node); } container.appendChild(fragment); return; } // Reorder or insert nodes with minimal DOM moves for (let i = 0; i < orderedNodes.length; i++) { const targetNode = orderedNodes[i]; const currentNode = container.children[i] || null; if (currentNode !== targetNode) { container.insertBefore(targetNode, currentNode); } } } const CLIPPING_OVERFLOW_RE = /(?:hidden|clip|auto|scroll)/i; /** * 解析浮层所在的可视裁剪边界(兼容 Shadow DOM 悬浮窗 `.wm-popover-panel`、 * 侧栏 `.app-shell`、自定义滚动容器 `.custom-scroll-content` 与窗口视口)。 * * @param {HTMLElement} anchorRootEl * @returns {{ left: number, top: number, right: number, bottom: number, width: number, height: number } | null} */ function resolvePopupBoundaryRect(anchorRootEl) { if (!anchorRootEl) return null; const winW = typeof window !== 'undefined' ? Number(window.innerWidth || 0) : 0; const winH = typeof window !== 'undefined' ? Number(window.innerHeight || 0) : 0; let boundLeft = 0; let boundTop = 0; let boundRight = winW > 0 ? winW : Infinity; let boundBottom = winH > 0 ? winH : Infinity; let hasBoundary = winW > 0 && winH > 0; const getStyle = typeof window !== 'undefined' && typeof window.getComputedStyle === 'function' ? window.getComputedStyle : null; let cur = anchorRootEl.parentNode || null; while (cur) { if (cur.nodeType === 1 || typeof cur.getBoundingClientRect === 'function') { const cls = cur.classList; const isShell = Boolean( cls?.contains?.('wm-popover-panel') || cls?.contains?.('wm-multi-panel') || cls?.contains?.('app-shell') || cls?.contains?.('custom-scroll-host') || cls?.contains?.('custom-scroll-content') ); let clipsX = isShell; let clipsY = isShell; if (!isShell && getStyle) { try { const cs = getStyle(cur); if (cs) { clipsX = CLIPPING_OVERFLOW_RE.test(cs.overflowX || cs.overflow || ''); clipsY = CLIPPING_OVERFLOW_RE.test(cs.overflowY || cs.overflow || ''); } } catch { // 忽略 Mock DOM 样式查询异常 } } if (clipsX || clipsY) { const r = cur.getBoundingClientRect?.(); if (r && r.width > 0 && r.height > 0) { hasBoundary = true; if (clipsX) { boundLeft = Math.max(boundLeft, r.left); boundRight = Math.min(boundRight, r.right); } if (clipsY) { boundTop = Math.max(boundTop, r.top); boundBottom = Math.min(boundBottom, r.bottom); } } } } // 到达 ShadowRoot 或文档顶层后停止,避免误受宿主页面外层容器干扰 if (!cur.parentNode) break; cur = cur.parentNode; } if (!hasBoundary || !Number.isFinite(boundRight) || !Number.isFinite(boundBottom)) { return null; } const width = Math.max(0, boundRight - boundLeft); const height = Math.max(0, boundBottom - boundTop); if (width <= 0 || height <= 0) return null; return { left: boundLeft, top: boundTop, right: boundRight, bottom: boundBottom, width, height }; } /** * 为锚定在触发器上的绝对定位下拉浮层执行水平/垂直碰撞检测与边界夹紧: * - 水平方向优先左对齐,右侧溢出时切右对齐,仍越界则直接夹紧在容器可视安全区内; * - 垂直方向底部空间不足且上方更宽裕时自动向上翻转(追加 `.is-above`),并按可用空间收紧 `max-height`。 * * @param {HTMLElement} rootEl 定位基准容器 (`position: relative`) * @param {HTMLElement} triggerEl 触发按钮 * @param {HTMLElement} popupEl 下拉浮层 (`position: absolute`) * @param {{ margin?: number, gap?: number, maxHeight?: number, minFlipSpace?: number }} [opts] */ function positionAnchoredPopup( rootEl, triggerEl, popupEl, { margin = 6, gap = 4, maxHeight = 220, minFlipSpace = 140 } = {} ) { if (!rootEl || !triggerEl || !popupEl || !popupEl.style) return; if (popupEl.hasAttribute?.('hidden')) return; const rootRect = rootEl.getBoundingClientRect?.(); const triggerRect = triggerEl.getBoundingClientRect?.(); if ( !rootRect || !triggerRect || !(triggerRect.width > 0 && triggerRect.height > 0) ) { return; } const bound = resolvePopupBoundaryRect(rootEl); if (!bound) return; // 清除旧的动态夹紧值以便读取自然布局宽度 popupEl.style.left = ''; popupEl.style.right = ''; popupEl.style.top = ''; popupEl.style.bottom = ''; popupEl.style.minWidth = ''; popupEl.style.maxWidth = ''; popupEl.style.maxHeight = ''; const availWidth = Math.max(120, Math.floor(bound.width - margin * 2)); let cssMaxW = NaN; if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { try { const rawMaxW = window.getComputedStyle(popupEl)?.maxWidth; if (rawMaxW && rawMaxW !== 'none') { cssMaxW = Number.parseFloat(rawMaxW); } } catch { // 忽略 Mock DOM 样式查询异常 } } const effectiveMaxW = Number.isFinite(cssMaxW) && cssMaxW > 0 ? Math.max(120, Math.min(availWidth, Math.floor(cssMaxW))) : availWidth; popupEl.style.maxWidth = `${effectiveMaxW}px`; const rawRect = popupEl.getBoundingClientRect?.(); // 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小 const naturalW = Math.max( Number(popupEl.offsetWidth || 0), Math.ceil(Number(rawRect?.width || 0)) ); if (naturalW > effectiveMaxW) { popupEl.style.minWidth = '0px'; } const popupW = Math.min( effectiveMaxW, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210) ); const safeLeft = bound.left + margin; const safeRight = bound.right - margin; const rawLeft = Number(rawRect?.left); const rawRight = Number(rawRect?.right); const hasRawBox = Number.isFinite(rawLeft) && Number.isFinite(rawRight) && rawRight > rawLeft; // 若入场缩放动画(如 scale(0.975))正在首帧生效,按对称补偿还原终态边界再判断是否越界 const scalePadX = hasRawBox ? Math.max(0, (popupW - (rawRight - rawLeft)) / 2) : 0; const naturalLeft = hasRawBox ? rawLeft - scalePadX : triggerRect.left; const naturalRight = hasRawBox ? Math.max(rawRight + scalePadX, naturalLeft + popupW) : naturalLeft + popupW; const fitsAsDefault = hasRawBox && naturalLeft >= safeLeft && naturalRight <= safeRight; if (!fitsAsDefault) { let targetLeft = triggerRect.left; if (targetLeft + popupW > safeRight) { const rightAlignedLeft = triggerRect.right - popupW; if (rightAlignedLeft >= safeLeft) { targetLeft = rightAlignedLeft; } else { targetLeft = Math.max(safeLeft, safeRight - popupW); } } if (targetLeft < safeLeft) { targetLeft = safeLeft; } const offsetLeft = Math.round(targetLeft - rootRect.left); popupEl.style.left = `${offsetLeft}px`; popupEl.style.right = 'auto'; } const spaceBelow = Math.max(0, bound.bottom - triggerRect.bottom - gap - margin); const spaceAbove = Math.max(0, triggerRect.top - bound.top - gap - margin); const naturalH = Math.max( Number(popupEl.scrollHeight || 0), Number(popupEl.offsetHeight || 0), Math.ceil(Number(rawRect?.height || 0)) ); const desiredH = maxHeight > 0 ? Math.min(maxHeight, naturalH || maxHeight) : naturalH || 240; const shouldOpenAbove = spaceBelow < Math.min(desiredH, minFlipSpace) && spaceAbove > spaceBelow; patchClasses(popupEl, { 'is-above': shouldOpenAbove }); if (shouldOpenAbove) { popupEl.style.top = 'auto'; popupEl.style.bottom = `calc(100% + ${gap}px)`; if (maxHeight > 0) { popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceAbove)))}px`; } } else { popupEl.style.top = `calc(100% + ${gap}px)`; popupEl.style.bottom = 'auto'; if (maxHeight > 0) { popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceBelow)))}px`; } } } return { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList, positionAnchoredPopup }; })(); // --- src/core/component.js --- const { defineComponent } = (() => { /** * @fileoverview Vue-inspired lightweight component kernel supporting * props, custom v-model value transmission (emit('update:modelValue', val)), * reactive subscriptions, and lifecycle cleanup. */ function defineComponent({ name, setup }) { return function createInstance(initialProps = {}) { const props = { ...initialProps }; const cleanups = []; function emit(event, payload) { // Support Vue-style onUpdateModelValue / onChange prop callbacks if (event === 'update:modelValue') { if (typeof props.onUpdateModelValue === 'function') { props.onUpdateModelValue(payload); } if (typeof props.onChange === 'function') { props.onChange(payload); } } } function onCleanup(fn) { if (typeof fn === 'function') { cleanups.push(fn); } } let setupResult = null; function setProps(nextProps = {}) { Object.assign(props, nextProps); if (setupResult && typeof setupResult.onPropsChange === 'function') { setupResult.onPropsChange(props); } } function setValue(nextValue) { setProps({ modelValue: nextValue }); } setupResult = setup({ props, getProps: () => props, setProps, emit, onCleanup, }); function destroy() { for (const fn of cleanups.splice(0)) { try { fn(); } catch (err) { console.error(`[${name}] cleanup error:`, err); } } if (setupResult.el?.parentNode) { setupResult.el.parentNode.removeChild(setupResult.el); } } return { name, el: setupResult.el, refs: setupResult.refs || {}, setProps, setValue, destroy, ...setupResult.methods, }; }; } return { defineComponent }; })(); // --- src/core/formatters.js --- const { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatTrendSlotFullLabel, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. */ const EN_MONTH_SHORT = Object.freeze([ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]); const ZH_WEEKDAY_SHORT = Object.freeze([ '周日', '周一', '周二', '周三', '周四', '周五', '周六', ]); const EN_WEEKDAY_SHORT = Object.freeze([ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', ]); function formatMetric(value, unit = '') { if (!Number.isFinite(value)) return '—'; const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1); return `${numStr}${unit}`; } function formatSpeedMetric(value, unit = ' tok/s') { return formatMetric(value, unit); } function formatCachePct(value) { if (value == null || !Number.isFinite(Number(value))) return '—'; const num = Math.max(0, Math.min(100, +Number(value).toFixed(1))); return `${num}%`; } /** * 格式化百分比数值文本:常规值保留 1 位小数,将边界值 `0.0` / `100.0` 收口为整数 `0` / `100`。 * * @param {number|string|null|undefined} value * @param {{ withSymbol?: boolean }} [options] * @returns {string} */ function formatPctNumber(value, { withSymbol = false } = {}) { const num = Number(value); if (!Number.isFinite(num)) return withSymbol ? '0%' : '0'; const rounded = Math.round(num * 10) / 10; const str = Math.abs(rounded) < 1e-9 ? '0' : Math.abs(rounded - 100) < 1e-9 ? '100' : rounded.toFixed(1); return withSymbol ? `${str}%` : str; } function getSpeedToneClass(tokPerSec) { return `tone-${classifySpeedTier(tokPerSec)}`; } function getCacheToneClass(cacheHitPct, promptTokens = null) { return `tone-${classifyCacheTier(cacheHitPct, promptTokens)}`; } function getStepCostToneClass(costUsd) { const tier = classifyStepCostTier(costUsd); return tier ? `tone-${tier}` : ''; } function getTtftToneClass(ttftSec) { const tier = classifyTtftTier(ttftSec); return tier === 'warn' || tier === 'danger' ? `tone-${tier}` : ''; } const formatTokens = formatCompactTokens; function formatTokensPrecise(num) { const n = Number(num || 0); if (n <= 0) return '0'; if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`; if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; return String(Math.round(n)); } function formatCnyApprox(usdAmount, rate = 7.2) { const rmb = Number(usdAmount || 0) * rate; if (rmb <= 0) return '≈ ¥0'; if (rmb >= 10) return `≈ ¥${Math.round(rmb)}`; return `≈ ¥${rmb.toFixed(1)}`; } function formatDateSpanBadge(startMs, endMs) { const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date(); const sameYear = s.getFullYear() === e.getFullYear(); const sameMonth = sameYear && s.getMonth() === e.getMonth(); const sameDay = sameMonth && s.getDate() === e.getDate(); if (isEnglishLocale()) { const sMon = EN_MONTH_SHORT[s.getMonth()] || ''; const eMon = EN_MONTH_SHORT[e.getMonth()] || ''; if (!sameYear) { return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`; } if (sameDay) { return `${sMon} ${s.getDate()}`; } if (sameMonth) { return `${sMon} ${s.getDate()} ~ ${e.getDate()}`; } return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`; } if (!sameYear) { return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`; } if (sameDay) { return `${s.getMonth() + 1}月${s.getDate()}日`; } if (sameMonth) { return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getDate()}日`; } return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } function formatTrendSlotFullLabel(slot, { locale, showFullYear = false } = {}) { const en = typeof locale === 'string' && locale.trim() ? locale.trim().toLowerCase().startsWith('en') : isEnglishLocale(); const sMs = Number(slot?.startMs); if (Number.isFinite(sMs) && sMs > 0) { const sd = new Date(sMs); const pad2 = (n) => String(n).padStart(2, '0'); const rawFull = String(slot?.fullLabel || ''); const includeYear = Boolean( showFullYear || /^\d{4}年/.test(rawFull) || sd.getFullYear() !== new Date().getFullYear() ); const gran = String(slot?.granularity || '').toLowerCase(); const isSubDay = gran === 'minute' || gran === 'hour' || (!gran && Number(slot?.endMs) > sMs && Number(slot.endMs) - sMs <= 3600_000 * 2); if (isSubDay) { const eMs = Number(slot?.endMs); const ed = Number.isFinite(eMs) && eMs > 0 ? new Date(eMs) : new Date(sMs + 3600_000); const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; if (en) { const mon = EN_MONTH_SHORT[sd.getMonth()] || ''; return includeYear ? `${mon} ${sd.getDate()}, ${sd.getFullYear()}, ${hh} - ${endHh}` : `${mon} ${sd.getDate()}, ${hh} - ${endHh}`; } const yearPrefix = includeYear ? `${sd.getFullYear()}年` : ''; return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`; } if (en) { const mon = EN_MONTH_SHORT[sd.getMonth()] || ''; const wday = EN_WEEKDAY_SHORT[sd.getDay()] || ''; return includeYear ? `${mon} ${sd.getDate()}, ${sd.getFullYear()} (${wday})` : `${mon} ${sd.getDate()} (${wday})`; } const yearPrefix = includeYear ? `${sd.getFullYear()}年` : ''; return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${ZH_WEEKDAY_SHORT[sd.getDay()] || ''})`; } const rawFull = String(slot?.fullLabel || '').trim(); const rawShort = String(slot?.label || '').trim(); if (en && rawFull && /[\u4e00-\u9fff]/.test(rawFull)) { return rawShort || rawFull; } return rawFull || rawShort; } function formatUsd(amount, { precise = false } = {}) { if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending'); const val = Number(amount || 0); if (precise) { if (val > 0 && val < 0.001) return '<$0.001'; return val >= 1 ? `$${val.toFixed(2)}` : `$${val.toFixed(3)}`; } return `$${val.toFixed(2)}`; } const SPEED_REASON_LABELS = { __proto__: null, incomplete_or_invalid_timing: 'fmt.speedIncomplete', canceled: 'fmt.speedCanceled', error: 'fmt.speedError', interrupted: 'fmt.speedInterrupted', compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable', invalid_output_tokens: 'fmt.speedInvalidOutput', inconsistent_timing: 'fmt.speedInconsistent', short_timing: 'fmt.speedShort', legacy_cache: 'fmt.speedLegacy', }; function speedReasonText(reason) { const label = SPEED_REASON_LABELS[reason]; return label ? t(label) : ''; } const ANOMALY_KIND_ORDER = Object.freeze([ 'rate_limit', 'timeout', 'capacity', 'disconnect', 'upstream', 'model_output', 'safety', 'auth_or_model', 'error', ]); function formatAnomalyKindLabel(kind) { const k = String(kind || 'error'); const key = `steps.anomalyKind.${k}`; const text = t(key); return text === key ? t('steps.anomalyKind.error') : text; } function formatAnomalyTagText(primaryKind, count = 1) { const n = Math.max(1, Math.floor(Number(count) || 1)); const k = String(primaryKind || 'error'); if (k === 'capacity' && n === 1) return t('steps.anomalyTag.capacitySingle'); if (k === 'upstream' && n === 1) return t('steps.anomalyTag.upstreamSingle'); const key = `steps.anomalyTag.${k}`; const formatted = t(key, { n }); return formatted === key ? t('steps.anomalyTag.error', { n }) : formatted; } function resolveModelAnomalySummary(m) { const count = Math.max(0, Number(m?.anomalyCount || 0)); const steps = Math.max(0, Number(m?.anomalySteps || 0)); if (count <= 0 && steps <= 0) return null; const byKind = m?.anomalyByKind && typeof m.anomalyByKind === 'object' ? m.anomalyByKind : {}; const entries = Object.entries(byKind) .map(([k, v]) => [k, Math.max(0, Number(v || 0))]) .filter(([, v]) => v > 0) .sort((a, b) => { if (b[1] !== a[1]) return b[1] - a[1]; const pa = ANOMALY_KIND_ORDER.indexOf(a[0]); const pb = ANOMALY_KIND_ORDER.indexOf(b[0]); return (pa < 0 ? 99 : pa) - (pb < 0 ? 99 : pb); }); const totalCount = count || entries.reduce((sum, [, v]) => sum + v, 0) || steps; const primaryKind = entries.length === 1 ? entries[0][0] : entries.length > 1 ? 'mixed' : 'error'; const severity = Number(m?.anomalyDangerCount || 0) > 0 || entries.some(([k]) => k === 'rate_limit' || k === 'auth_or_model') ? 'danger' : 'warn'; return { count: totalCount, steps: steps || totalCount, totalDelaySec: Math.max(0, Number(m?.anomalyTotalDelaySec || 0)), primaryKind, severity, entries, tagText: formatAnomalyTagText(primaryKind, totalCount), }; } function formatStepAnomalyInlineSummary(anomaly) { if (!anomaly || !(Number(anomaly.count) > 0)) return ''; const tag = formatAnomalyTagText(anomaly.primaryKind, anomaly.count); const label = formatAnomalyKindLabel(anomaly.primaryKind); const delaySec = Number(anomaly.totalDelaySec || 0); const delayPart = delaySec > 0 ? ` · ${t('steps.anomalyDelayPart', { sec: delaySec })}` : ''; return `${tag} · ${label}${delayPart}`; } function buildStepAnomalyDiagnostic(st) { const a = st?.anomaly; if (!a || !(Number(a.count) > 0)) return null; const title = t('steps.anomalyStepTitle', { step: Number(st.stepIndex ?? 0), count: Number(a.count), }); const delaySec = Number(a.totalDelaySec || 0); const sub = delaySec > 0 ? t('steps.anomalyDelayPart', { sec: delaySec }) : ''; const events = Array.isArray(a.events) ? a.events : []; const rows = events.map((ev, idx) => { const label = formatAnomalyKindLabel(ev.kind); const parts = [`#${ev.attempt || idx + 1} ${label}`]; if (Number(ev.delaySec) > 0) { parts.push(t('steps.anomalyDelayPart', { sec: ev.delaySec })); } if (ev.terminal) { parts.push(t('steps.anomalyTerminalTag')); } return { text: parts.join(' · '), detail: ev.message || '', danger: Boolean(ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model'), }; }); return { title, sub, rows, hint: '', severity: a.severity === 'danger' ? 'danger' : 'warn', }; } function buildStepCompactionDiagnostic(st, displaySettings = {}) { if (!st || typeof st !== 'object') return null; const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '' }); const promptTok = Math.max(0, Number(st.inputTokens || 0)) + Math.max(0, Number(st.cacheReadTokens || 0)); const outTok = Math.max(0, Number(st.outputTokens || 0)); const title = t('steps.compactionStepTitle', { step: Number(st.stepIndex ?? 0) }); const rows = promptTok > 0 || outTok > 0 ? [ { text: t('steps.compactionSummaryRow', { input: formatTokens(promptTok), output: formatTokens(outTok), }), detail: t('steps.compactionDetailHint'), mono: false, danger: false, }, ] : [ { text: t('steps.compactionDetailHint'), detail: '', danger: false, }, ]; return { title, sub: disp.baseText || '', rows, hint: '', severity: 'compaction', }; } function finiteNonNegativeSec(val) { if (val === null || val === undefined || val === '') return null; const num = Number(val); return Number.isFinite(num) && num >= 0 ? num : null; } function formatTimingDetailSec(sec) { const num = finiteNonNegativeSec(sec); if (num === null) return '—'; if (num > 0 && num < 0.01) return '<0.01s'; if (num >= 10) return `${num.toFixed(1)}s`; return `${num.toFixed(2)}s`; } function hasStepTimingData(st) { if (!st || typeof st !== 'object') return false; return ( finiteNonNegativeSec(st.nativeTtftSec ?? st.ttftSec) !== null || finiteNonNegativeSec(st.totalDurationSec ?? st.streamDurationSec) !== null || finiteNonNegativeSec(st.nativeStreamSec) !== null || finiteNonNegativeSec(st.thinkingDurationSec) !== null ); } function buildStepTimingDiagnostic(st) { if (!st || typeof st !== 'object') return null; const ttft = finiteNonNegativeSec(st.nativeTtftSec ?? st.ttftSec); const total = finiteNonNegativeSec(st.totalDurationSec ?? st.streamDurationSec); const nativeStream = finiteNonNegativeSec(st.nativeStreamSec); const think = finiteNonNegativeSec(st.thinkingDurationSec); if (ttft === null && total === null && nativeStream === null && think === null) { return null; } const afterTtft = nativeStream === null && total !== null && ttft !== null && total >= ttft ? +(total - ttft).toFixed(6) : null; const rows = []; if (ttft !== null) { let valText = formatTimingDetailSec(ttft); if (total !== null && total > 0 && ttft <= total + 0.01) { const pct = Math.min(100, Math.max(0, Math.round((ttft / total) * 100))); valText = `${valText} (${pct}%)`; } rows.push({ text: t('steps.timingTtftLabel'), value: valText, toneClass: getTtftToneClass(ttft), }); } if (nativeStream !== null) { rows.push({ text: t('steps.timingStreamLabel'), value: formatTimingDetailSec(nativeStream), }); } else if (afterTtft !== null) { rows.push({ text: t('steps.timingAfterTtftLabel'), value: formatTimingDetailSec(afterTtft), }); } if (think !== null) { rows.push({ text: t('steps.timingThinkLabel'), value: formatTimingDetailSec(think), }); } const showTotalInSub = total !== null && rows.length > 0; if (total !== null && !showTotalInSub) { rows.push({ text: t('steps.timingTotalLabel'), value: formatTimingDetailSec(total), }); } const hints = []; const hasOverlap = think !== null && total !== null && ((ttft !== null && ttft + think > total + 0.05) || (nativeStream !== null && ttft !== null && ttft + nativeStream + think > total + 0.05) || think > total + 0.05); if (hasOverlap) { hints.push(t('steps.timingOverlapHint')); } const streamForToolCheck = nativeStream ?? afterTtft; if ( st.hasToolCalls && streamForToolCheck !== null && streamForToolCheck < 0.5 && ttft !== null && ttft >= 2 ) { hints.push(t('steps.timingToolBufferedHint')); } const anomalyCount = Math.max(0, Number(st.anomaly?.count || 0)); if (anomalyCount > 0) { const delaySec = Number(st.anomaly?.totalDelaySec || 0); hints.push( delaySec > 0 ? t('steps.timingAnomalyDelayHint', { count: anomalyCount, sec: delaySec }) : t('steps.timingAnomalyHint', { count: anomalyCount }) ); } return { title: t('steps.timingStepTitle', { step: Number(st.stepIndex ?? 0) }), sub: showTotalInSub ? t('steps.timingTotalSub', { sec: formatTimingDetailSec(total) }) : '', rows, hint: hints.join(' · '), severity: 'timing', }; } function buildModelAnomalyDiagnostic(m) { const sum = resolveModelAnomalySummary(m); if (!sum) return null; const title = t('steps.anomalyModelTitle', { model: m?.displayText || m?.shortName || m?.label || '—', count: sum.count, }); const subParts = [t('steps.anomalyModelSub', { steps: sum.steps })]; if (sum.totalDelaySec > 0) { subParts.push(t('steps.anomalyDelayPart', { sec: sum.totalDelaySec })); } const rows = sum.entries.map(([k, v]) => ({ text: t('steps.anomalyModelKindRow', { kind: formatAnomalyKindLabel(k), count: v }), detail: '', danger: k === 'rate_limit' || k === 'auth_or_model', })); return { title, sub: subParts.join(' · '), rows, hint: t('steps.anomalyModelClickHint'), severity: sum.severity, }; } function sampleSummary(summary) { const valid = summary?.sampleCount || 0; const excluded = summary?.excludedCount || 0; return t('fmt.sampleSteps', { valid, total: valid + excluded }); } function formatCountdown(isoTime, nowMs = Date.now()) { if (!isoTime) return t('fmt.resetUnknown'); const targetMs = Date.parse(isoTime); if (!Number.isFinite(targetMs) || targetMs <= 0) return t('fmt.resetUnknown'); const diffMs = targetMs - nowMs; if (diffMs <= 0) return t('fmt.resetSoon'); if (diffMs < 60_000) return t('fmt.resetUnder1m'); const totalMinutes = Math.floor(diffMs / 60000); const days = Math.floor(totalMinutes / (60 * 24)); const hours = Math.floor((totalMinutes % (60 * 24)) / 60); const minutes = totalMinutes % 60; if (days > 0) return t('fmt.resetDaysHours', { d: days, h: hours }); if (hours > 0) return t('fmt.resetHoursMins', { h: hours, m: minutes }); return t('fmt.resetMins', { m: minutes }); } function formatCompactDateTime(ms) { if (!ms || !Number.isFinite(ms)) return t('fmt.selectTime'); const d = new Date(ms); const pad = (n) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; } function formatElapsedSec(seconds) { const s = Math.max(0, Math.floor(Number(seconds) || 0)); if (s < 60) return `${s}s`; const m = Math.floor(s / 60); const remS = s % 60; if (m < 60) { return `${m}m ${String(remS).padStart(2, '0')}s`; } const h = Math.floor(m / 60); const remM = m % 60; return `${h}h ${remM}m`; } /** * 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。 * * @param {string} rawText * @returns {string} */ function stripVendorModelPrefix(rawText) { return String(rawText || '') .trim() .replace(/^(?:gemini|claude|gpt)-(?=.+)/i, ''); } function stripCompactionMarker(rawText) { return String(rawText || '') .replace(/(?:·(?:压缩|compact)|\[自动压缩\]|\[auto[- ]?compact\])\s*$/iu, '') .trim(); } const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode; function normalizeOrchVariantToken(raw = '') { let s = String(raw || '') .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^a-z0-9.-]+/g, '-') .replace(/-+/g, '-') .replace(/^-+|-+$/g, ''); if (!s || /^worker(?:$|-)/.test(s)) return ''; s = s.replace(/([a-z]-)(\d+)-(\d+)(?=$|-)/g, '$1$2.$3'); s = s .replace(/^(?:claude|anthropic|openai)-(?=.+)/, '') .replace(/^gemini-(?:4-)?(?=(?:carbon|argon|neon|hydrogen|helix)(?:$|-))/, ''); return s; } function extractOrchWorkerVariant(fields = [], combinedText = '') { for (const rawField of fields) { const field = String(rawField || '').trim(); if (!field) continue; const parenMatch = field.match(/\bOrchestrator\s+Worker\s*\(\s*([^)]+?)\s*\)/i); if (parenMatch) { const v = normalizeOrchVariantToken(parenMatch[1]); if (v) return v; } const compactMatch = field.match(/\bworker-agy-([a-z0-9]+(?:[.-][a-z0-9]+)*)(?=·|\s|$)/i); if (compactMatch) { const v = normalizeOrchVariantToken(compactMatch[1]); if (v) return v; } } if (/\bMODEL_PLACEHOLDER_M669\b|\bgemini-flash-worker-agy\b/i.test(combinedText)) { return 'hydrogen'; } const upstreamMatch = combinedText.match(/\b([a-z0-9][a-z0-9.-]*?)-worker-agy\b/i); if (upstreamMatch) { const rawPrefix = upstreamMatch[1].toLowerCase(); if (rawPrefix === 'gemini-flash') return 'hydrogen'; if (/^gemini-(?:4-)?neon$/i.test(rawPrefix)) return 'neon'; if (/^gemini-(?:4-)?argon$/i.test(rawPrefix)) return 'argon'; if (/^gemini-(?:4-)?carbon$/i.test(rawPrefix)) return 'carbon'; const v = normalizeOrchVariantToken(rawPrefix); if (v && v !== 'gemini-pro') return v; } if (/\bneon\b/i.test(combinedText)) return 'neon'; if (/\bhydrogen\b/i.test(combinedText)) return 'hydrogen'; if (/\bargon\b/i.test(combinedText)) return 'argon'; if (/\bcarbon\b/i.test(combinedText)) return 'carbon'; return ''; } function extractDynamicOrchVariant(fields = []) { for (const rawField of fields) { const field = String(rawField || '').trim(); if (!field) continue; const parenAfter = field.match(/\bOrchestrator\s*\(\s*([^)]+?)\s*\)/i); if (parenAfter) { const v = normalizeOrchVariantToken(parenAfter[1]); if (v) return v; } const parenBefore = field.match( /^([a-z0-9][a-z0-9.\s-]{0,40}?)\s*\(\s*Orchestrator\s*\)(?:\s*\[[^\]]+\])?$/i ); if (parenBefore) { const v = normalizeOrchVariantToken(parenBefore[1]); if (v) return v; } const geminiProSlug = field.match( /\bgemini-pro-orchestrator-([a-z0-9]+(?:[.-][a-z0-9]+)*)(?=·|\s|$)/i ); if (geminiProSlug) { const v = normalizeOrchVariantToken(geminiProSlug[1]); if (v) return v; } const prefixSlug = field.match( /\b(?:orchestrator|orch)-([a-z0-9]+(?:[.-][a-z0-9]+)*)(?=·|\s|$)/i ); if (prefixSlug) { const v = normalizeOrchVariantToken(prefixSlug[1]); if (v) return v; } const suffixSlug = field.match(/\b([a-z0-9]+(?:[.-][a-z0-9]+)*)-orchestrator(?=·|\s|$)/i); if (suffixSlug && !/^gemini-pro$/i.test(suffixSlug[1])) { const v = normalizeOrchVariantToken(suffixSlug[1]); if (v) return v; } } return ''; } /** * 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本及悬停提示。 * * 规则: * - Orchestrator 系列(如 `Orchestrator (Carbon / Argon / Neon / Opus 5.5)`、`Orchestrator Worker (Hydrogen / Neon / ...)`) * 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-` / `worker-agy-`; * `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响; * - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`); * - 独立拆分 `baseText` 及 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。 * * @param {object|null|undefined} target * @param {{ modelDisplayMode?: string, showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings] * @param {{ preferLabelInShort?: boolean, fallback?: string }} [options] * @returns {{ text: string, baseText: string, compactionSuffix: string, isCompaction: boolean, title: string, isOrchestratorSeries: boolean }} */ function resolveModelDisplayInfo(target, settings = {}, options = {}) { const modelDisplayMode = typeof settings === 'boolean' ? settings ? 'upstream' : 'short' : normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel); const showUpstream = modelDisplayMode !== 'short'; const orchestratorMode = normalizeOrchestratorIdDisplayMode( typeof settings === 'object' && settings ? settings.orchestratorIdMode : 'compact' ); const preferLabelInShort = Boolean(options?.preferLabelInShort); const fallback = options?.fallback ?? t('fmt.unknownModel'); if (!target || typeof target !== 'object') { return { text: fallback, baseText: fallback, compactionSuffix: '', isCompaction: false, title: fallback, isOrchestratorSeries: false, }; } const shortText = String( target.activeBaseModelShort ?? target.baseModelShort ?? target.activeModelShort ?? target.modelShort ?? target.shortName ?? '' ).trim(); const labelText = String( target.activeBaseModelLabel ?? target.baseModelLabel ?? target.activeModelLabel ?? target.modelLabel ?? target.label ?? '' ).trim(); const upstreamText = String( target.baseModelUpstream ?? target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamModel ?? target.upstreamName ?? '' ).trim(); const rawCompactionText = `${target.activeModelShort ?? target.modelShort ?? ''} ${target.activeModelLabel ?? target.modelLabel ?? ''} ${target.activeModelUpstream ?? target.modelUpstream ?? ''}`; const responseText = String(target.responseModel ?? '').trim(); const modelKeyText = String(target.modelKey ?? '').trim(); const isCompaction = Boolean(target.isCompactionStep) || /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(rawCompactionText); const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : ''; const fields = [labelText, shortText, upstreamText, responseText, modelKeyText]; const combined = `${modelKeyText} ${shortText} ${labelText} ${upstreamText} ${responseText}`; const isOrchWorker = /\bMODEL_PLACEHOLDER_M669\b|\b[a-z0-9.-]*worker-agy\b|\bworker-agy-[a-z0-9.-]+\b|\bOrchestrator\s+Worker\b/i.test( combined ); const isKnownOrchCarbonPh = /\bMODEL_PLACEHOLDER_M667\b/i.test(combined); const isKnownOrchArgonPh = /\bMODEL_PLACEHOLDER_M681\b/i.test(combined); const isKnownOrchNeonPh = /\bMODEL_PLACEHOLDER_M537\b/i.test(combined); const dynamicOrchVariant = isOrchWorker ? '' : extractDynamicOrchVariant(fields); const hasBareProOrch = /\bgemini-pro-orchestrator\b(?![-_][a-z0-9])/i.test(combined); const isOrchSeries = isOrchWorker || Boolean(dynamicOrchVariant) || isKnownOrchNeonPh || isKnownOrchArgonPh || isKnownOrchCarbonPh || hasBareProOrch; if (isOrchSeries) { let compactId = ''; let fullId = ''; if (isOrchWorker) { const workerVariant = extractOrchWorkerVariant(fields, combined); const cleanUpstream = stripCompactionMarker(upstreamText || responseText || '').trim(); if (workerVariant === 'hydrogen') { compactId = 'worker-agy-hydrogen'; fullId = 'gemini-flash-worker-agy (hydrogen-4)'; } else if (workerVariant === 'neon') { compactId = 'worker-agy-neon'; if (cleanUpstream) { if (/\([^)]+\)\s*$/.test(cleanUpstream)) { fullId = cleanUpstream; } else if (/(?:worker-agy)/i.test(cleanUpstream)) { fullId = `${cleanUpstream} (neon-4)`; } else if (/\bneon\b/i.test(cleanUpstream)) { fullId = cleanUpstream; } else { fullId = `${cleanUpstream} (neon-4)`; } } else { fullId = 'gemini-neon-worker-agy (neon-4)'; } } else if (workerVariant) { compactId = `worker-agy-${workerVariant}`; const variantDashed = workerVariant.replace(/\./g, '-'); const upstreamLower = cleanUpstream.toLowerCase(); const mentionsVariant = upstreamLower.includes(workerVariant) || upstreamLower.includes(variantDashed); fullId = cleanUpstream ? mentionsVariant || /\([^)]+\)\s*$/.test(cleanUpstream) ? cleanUpstream : `${cleanUpstream} (${workerVariant})` : `worker-agy-${workerVariant}`; } else { compactId = 'worker-agy'; fullId = cleanUpstream || 'worker-agy'; } } else if (isKnownOrchNeonPh || dynamicOrchVariant === 'neon') { compactId = 'orchestrator-neon'; fullId = 'gemini-pro-orchestrator-neon (neon-4)'; } else if (isKnownOrchArgonPh || dynamicOrchVariant === 'argon') { compactId = 'orchestrator-argon'; fullId = 'gemini-pro-orchestrator-argon (argon-4)'; } else if ( isKnownOrchCarbonPh || dynamicOrchVariant === 'carbon' || (hasBareProOrch && !dynamicOrchVariant) ) { compactId = 'orchestrator-carbon'; fullId = 'gemini-pro-orchestrator (carbon-4)'; } else if (dynamicOrchVariant) { compactId = `orchestrator-${dynamicOrchVariant}`; const cleanUpstream = stripCompactionMarker(upstreamText || responseText || '').trim(); const variantDashed = dynamicOrchVariant.replace(/\./g, '-'); const upstreamLower = cleanUpstream.toLowerCase(); const mentionsVariant = upstreamLower.includes(dynamicOrchVariant) || upstreamLower.includes(variantDashed); if (cleanUpstream) { fullId = mentionsVariant || /\([^)]+\)\s*$/.test(cleanUpstream) ? cleanUpstream : `${cleanUpstream} (${dynamicOrchVariant})`; } else { const isNonGeminiOrch = /\b(?:claude|anthropic|opus|sonnet|haiku|fable|gpt|openai)\b/i.test( `${combined} ${dynamicOrchVariant}` ); fullId = isNonGeminiOrch ? `orchestrator-${dynamicOrchVariant}` : `gemini-pro-orchestrator-${dynamicOrchVariant}`; } } if (compactId) { const baseText = orchestratorMode === 'full' ? fullId : compactId; const text = `${baseText}${compactionSuffix}`; const multiUpstream = Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1 ? target.upstreamModels.join(' / ') : ''; const title = multiUpstream || `${fullId}${compactionSuffix}`; return { text, baseText, compactionSuffix, isCompaction, title, isOrchestratorSeries: true, }; } } const rawSelected = (showUpstream ? upstreamText || responseText || shortText || labelText : preferLabelInShort ? labelText || shortText : shortText || labelText) || fallback; const cleanRawBase = stripCompactionMarker(rawSelected) || fallback; const baseText = modelDisplayMode === 'upstream_compact' ? stripVendorModelPrefix(cleanRawBase) || cleanRawBase : cleanRawBase; const text = `${baseText}${compactionSuffix}`; const fullUpstreamWithSuffix = `${cleanRawBase}${compactionSuffix}`; const standardTitle = showUpstream && Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1 ? target.upstreamModels.join(' / ') : showUpstream ? fullUpstreamWithSuffix : text; return { text, baseText, compactionSuffix, isCompaction, title: standardTitle, isOrchestratorSeries: false, }; } /** * 按当前显示策略 (`resolveModelDisplayInfo`) 解析出的最终展示名称对模型统计列表执行二次去重归并, * 确保当多个外层模型槽位映射到同一展示名(例如切换至“原始模型 ID”后共享同一 `upstreamName`)时, * 不会在排行榜或总览中出现重复同名行,同时完整累加 Token、调用次数、未定价计数与速度/首字加权均值。 * * @param {object[]} [models=[]] * @param {object|boolean} [settings={}] * @param {{ preferLabelInShort?: boolean, fallback?: string }} [options={}] * @returns {object[]} */ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { if (!Array.isArray(models) || models.length === 0) return []; const showUpstream = typeof settings === 'boolean' ? settings : normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel) !== 'short'; const byDisplay = new Map(); for (const m of models) { if (!m || typeof m !== 'object') continue; const disp = resolveModelDisplayInfo(m, settings, options); const key = String(disp.text || options?.fallback || '—').trim() || '—'; const calls = Math.max(0, Number(m.calls || 0)); const inTok = Math.max(0, Number(m.inputTokens || 0)); const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0)); const outTok = Math.max(0, Number(m.outputTokens || 0)); const thinkTok = Math.max(0, Number(m.thinkingTokens || 0)); const respTok = m.responseTokens != null ? Math.max(0, Number(m.responseTokens)) : Math.max(0, outTok - thinkTok); const totTok = Math.max(0, Number(m.totalTokens ?? inTok + cacheTok + outTok)); const costUsd = Number.isFinite(Number(m.costUsd)) ? Math.max(0, Number(m.costUsd)) : 0; const unpricedCalls = Math.max(0, Number(m.unpricedCalls || 0)); const speedSampleCount = Math.max(0, Number(m.speedSummary?.sampleCount || 0)); const speedExcludedCount = Math.max(0, Number(m.speedSummary?.excludedCount || 0)); const speedWeight = speedSampleCount > 0 ? speedSampleCount : Math.max(1, outTok || calls || 1); const hasSpeed = m.avgTokPerSec != null && Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0; const rawSpeedTokens = Number(m.speedSummary?.tokens); const rawSpeedSeconds = Number(m.speedSummary?.seconds); const hasExactSpeedSummary = Number.isFinite(rawSpeedTokens) && Number.isFinite(rawSpeedSeconds) && rawSpeedSeconds > 0 && rawSpeedTokens >= 0; const ttftSampleCount = Math.max(0, Number(m.ttftSampleCount || 0)); const ttftWeight = ttftSampleCount > 0 ? ttftSampleCount : Math.max(1, calls || 1); const hasTtft = m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0; let acc = byDisplay.get(key); if (!acc) { const initExcludedReasons = {}; if (m.speedSummary?.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { const cnt = Math.max(0, Number(rv || 0)); if (cnt > 0) initExcludedReasons[rk] = cnt; } } acc = { baseItem: m, mergedCount: 1, displayText: key, firstTitle: disp.title || key, titleSet: new Set(disp.title ? [disp.title] : []), upstreamSet: new Set( Array.isArray(m.upstreamModels) ? m.upstreamModels.filter(Boolean) : [] ), sourceLabels: m.label ? [m.label] : [], calls, inputTokens: inTok, cacheReadTokens: cacheTok, outputTokens: outTok, thinkingTokens: thinkTok, responseTokens: respTok, totalTokens: totTok, costUsd, unpricedCalls, hasAnySpeedSummary: Boolean(m.speedSummary), allSpeedExact: !hasSpeed || hasExactSpeedSummary, speedTokens: hasExactSpeedSummary ? rawSpeedTokens : 0, speedSeconds: hasExactSpeedSummary ? rawSpeedSeconds : 0, speedWeightedSum: hasSpeed ? Number(m.avgTokPerSec) * speedWeight : 0, speedWeight: hasSpeed ? speedWeight : 0, speedSampleCount, speedExcludedCount, speedExcludedReasons: initExcludedReasons, ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0, ttftWeight: hasTtft ? ttftWeight : 0, ttftSampleCount, anomalySteps: Math.max(0, Number(m.anomalySteps || 0)), anomalyCount: Math.max(0, Number(m.anomalyCount || 0)), anomalyDangerCount: Math.max(0, Number(m.anomalyDangerCount || 0)), anomalyTotalDelaySec: Math.max(0, Number(m.anomalyTotalDelaySec || 0)), anomalyByKind: m.anomalyByKind && typeof m.anomalyByKind === 'object' ? { ...m.anomalyByKind } : {}, }; if (m.upstreamName) acc.upstreamSet.add(m.upstreamName); byDisplay.set(key, acc); continue; } acc.mergedCount += 1; if (disp.title) acc.titleSet.add(disp.title); if (Array.isArray(m.upstreamModels)) { for (const u of m.upstreamModels) { if (u) acc.upstreamSet.add(u); } } if (m.upstreamName) acc.upstreamSet.add(m.upstreamName); if (m.label && !acc.sourceLabels.includes(m.label)) { acc.sourceLabels.push(m.label); } acc.calls += calls; acc.inputTokens += inTok; acc.cacheReadTokens += cacheTok; acc.outputTokens += outTok; acc.thinkingTokens += thinkTok; acc.responseTokens += respTok; acc.totalTokens += totTok; acc.costUsd += costUsd; acc.unpricedCalls += unpricedCalls; acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0)); acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0)); acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0)); acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0)); if (m.anomalyByKind && typeof m.anomalyByKind === 'object') { for (const [ak, av] of Object.entries(m.anomalyByKind)) { const cnt = Math.max(0, Number(av || 0)); if (cnt > 0) acc.anomalyByKind[ak] = (acc.anomalyByKind[ak] || 0) + cnt; } } if (m.speedSummary) acc.hasAnySpeedSummary = true; if (hasSpeed && !hasExactSpeedSummary) acc.allSpeedExact = false; if (hasExactSpeedSummary) { acc.speedTokens += rawSpeedTokens; acc.speedSeconds += rawSpeedSeconds; } if (hasSpeed) { acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight; acc.speedWeight += speedWeight; } acc.speedSampleCount += speedSampleCount; acc.speedExcludedCount += speedExcludedCount; if (m.speedSummary?.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { const cnt = Math.max(0, Number(rv || 0)); if (cnt > 0) acc.speedExcludedReasons[rk] = (acc.speedExcludedReasons[rk] || 0) + cnt; } } if (hasTtft) { acc.ttftWeightedSum += Number(m.avgTtftSec) * ttftWeight; acc.ttftWeight += ttftWeight; } acc.ttftSampleCount += ttftSampleCount; } return Array.from(byDisplay.values()).map((acc) => { if (acc.mergedCount === 1) { return { ...acc.baseItem, displayText: acc.displayText, displayTitle: acc.firstTitle, sourceLabels: acc.sourceLabels, }; } const promptTok = acc.inputTokens + acc.cacheReadTokens; const cacheHitPct = promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0; const rawAvgTps = acc.allSpeedExact && acc.speedSeconds > 0 ? acc.speedTokens / acc.speedSeconds : acc.speedWeight > 0 ? acc.speedWeightedSum / acc.speedWeight : null; const avgTokPerSec = rawAvgTps !== null ? +rawAvgTps.toFixed(1) : null; const avgTtftSec = acc.ttftWeight > 0 ? +(acc.ttftWeightedSum / acc.ttftWeight).toFixed(1) : null; const upstreamModels = Array.from(acc.upstreamSet); const displayTitle = showUpstream && upstreamModels.length > 1 ? upstreamModels.join(' / ') : Array.from(acc.titleSet).join(' / ') || acc.displayText; return { ...acc.baseItem, calls: acc.calls, inputTokens: acc.inputTokens, cacheReadTokens: acc.cacheReadTokens, outputTokens: acc.outputTokens, thinkingTokens: acc.thinkingTokens, responseTokens: acc.responseTokens, totalTokens: acc.totalTokens, costUsd: +acc.costUsd.toFixed(6), unpricedCalls: acc.unpricedCalls, cacheHitPct, avgTokPerSec, avgTtftSec, ttftSampleCount: acc.ttftSampleCount, ...(acc.anomalyCount > 0 ? { anomalySteps: acc.anomalySteps, anomalyCount: acc.anomalyCount, anomalyDangerCount: acc.anomalyDangerCount, anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1), anomalyByKind: acc.anomalyByKind, } : {}), speedSummary: acc.hasAnySpeedSummary ? { ...(acc.baseItem.speedSummary || {}), tokens: acc.speedTokens, seconds: +acc.speedSeconds.toFixed(6), sampleCount: acc.speedSampleCount, excludedCount: acc.speedExcludedCount, excludedReasons: acc.speedExcludedReasons, avgTokPerSec: rawAvgTps, } : undefined, upstreamModels, displayText: acc.displayText, displayTitle, sourceLabels: acc.sourceLabels, }; }); } /** * 根据代理索引返回对应的微边框语义徽章样式类名。 * * @param {number} [index=0] * @param {boolean} [isMain=false] * @returns {string} */ function getAgentBadgeClass(index = 0, isMain = false) { if (isMain || index <= 0) return 'badge-main'; const slot = ((index - 1) % 3) + 1; return `badge-sub-${slot}`; } function resolveStructuredAgentKind(agent) { if (!agent) return 'main'; if (agent.agentKind) return agent.agentKind; if (agent.isMain) return 'main'; if (agent.isSideQuestion || agent.typeName === 'side_question') return 'side_question'; if ( agent.typeName === 'worker' || agent.typeName === 'swarm_worker' || /^Swarm\s+Worker\s*\(/i.test(String(agent.role || '')) ) { return 'swarm_worker'; } return 'subagent'; } function normalizeSwarmMemberHandle(rawText) { const trimmed = String(rawText || '').trim(); if (!trimmed) return ''; const wrapper = trimmed.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i); const inner = (wrapper ? wrapper[1] : trimmed).replace(/^@+/, '').trim(); if ( !inner || inner === '蜂群' || inner === '工蜂' || inner.toLowerCase() === 'swarm' || inner.toLowerCase() === 'worker' || inner.toLowerCase() === 'swarm worker' ) { return ''; } return `@${inner}`; } /** * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理、蜂群节点或旁路提问的紧凑徽章文本(零正则反拆中文)。 * * @param {object|null|undefined} agent * @returns {string} */ function formatAgentBadgeText(agent) { if (!agent) return t('fmt.mainBadge'); const kind = resolveStructuredAgentKind(agent); if (kind === 'all') return t('header.scopeAllShort'); if (kind === 'main') return t('fmt.mainBadge'); if (kind === 'side_question') { const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); if (ord > 0) return t('fmt.sideBadge', { index: ord }); if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); return t('fmt.sideBadgeShort'); } if (kind === 'swarm_worker') { const ord = Number(agent.agentOrdinal || agent.index || 0); if (ord > 0) return t('fmt.swarmBadge', { index: ord }); if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); return t('fmt.swarmBadgeShort'); } const ord = Number(agent.agentOrdinal || agent.index || 0); if (ord > 0) return t('fmt.subBadge', { index: ord }); if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); return t('fmt.subBadgeShort'); } /** * 基于结构化 `agentKind` / `agentOrdinal` / `customRole` 格式化代理完整显示名称(零正则反拆中文)。 * * @param {object|null|undefined} agent * @returns {string} */ function formatAgentLabel(agent) { if (!agent) return t('fmt.mainAgent'); const kind = resolveStructuredAgentKind(agent); if (kind === 'all') return t('header.scopeAll'); if (kind === 'main') return t('fmt.mainAgent'); const rawCustom = agent.customRole !== undefined ? String(agent.customRole || '').trim() : String(agent.role || '').trim(); if (kind === 'side_question') { const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); const baseLabel = ord > 0 ? `${t('fmt.sideQuestion')} #${ord}` : t('fmt.sideQuestion'); const isGeneric = !rawCustom || rawCustom === baseLabel || rawCustom === agent.shortLabel || rawCustom === t('fmt.sideQuestion') || rawCustom === 'Side Question' || rawCustom === 'side_question'; return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; } if (kind === 'swarm_worker') { const ord = Number(agent.agentOrdinal || agent.index || 0); const baseLabel = ord > 0 ? `${t('fmt.swarmAgent')} #${ord}` : t('fmt.swarmAgent'); const handle = normalizeSwarmMemberHandle(rawCustom || agent.role || ''); if (!handle) return baseLabel; let auxSuffix = ''; if (/^@monitor(?:-\d+)?$/i.test(handle)) { auxSuffix = ` (${t('fmt.swarmMonitorHint')})`; } else if (/^@narrator(?:-\d+)?$/i.test(handle)) { auxSuffix = ` (${t('fmt.swarmNarratorHint')})`; } return `${baseLabel} · ${handle}${auxSuffix}`; } const ord = Number(agent.agentOrdinal || agent.index || 0); const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent'); const isGeneric = !rawCustom || rawCustom === baseLabel || rawCustom === agent.shortLabel || rawCustom === t('fmt.subAgent') || rawCustom === 'Subagent'; return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; } /** * 格式化会话选项右侧元信息(自适应区分纯蜂群、蜂群+子代理混合、常规子代理与单会话步数)。 * * @param {object|null|undefined} conv * @returns {string} */ function formatConversationMeta(conv) { if (!conv) return ''; const main = Number(conv.stepCount || 0); const totalSubs = Number(conv.subagentCount || 0); const swarm = Number(conv.swarmCount || 0); const otherSubs = Math.max(0, totalSubs - swarm); const total = Number(conv.totalStepCount ?? conv.totalStepsAllAgents ?? main); if (swarm > 0 && otherSubs > 0) { return t('header.convMetaWithSwarmAndSubs', { main, swarm, subs: otherSubs, total }); } if (swarm > 0) { return t('header.convMetaWithSwarm', { main, swarm, total }); } if (totalSubs > 0) { return t('header.convMetaWithSubs', { main, subs: totalSubs, total }); } return t('header.convMetaSteps', { count: main }); } /** * 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。 * * @param {object|null|undefined} act * @param {string} [fallbackKey='live.thinking'] * @returns {string} */ function formatLiveActivityLabel(act, fallbackKey = 'live.thinking') { if (!act || typeof act !== 'object') return t(fallbackKey); let baseLabel = ''; if (act.actionKey) { const i18nKey = `live.act.${act.actionKey}`; const translated = t(i18nKey); if (translated && translated !== i18nKey) { baseLabel = translated; } } if (!baseLabel) { baseLabel = String(act.label || '').trim() || t(fallbackKey); } if (act.waitingApproval) { return t('live.act.awaitingApproval', { label: baseLabel }); } return baseLabel; } /** * 基于后端结构化 `detailKey` 渲染实时动作补充说明(兼容自由文本 `detail`)。 * * @param {object|null|undefined} act * @returns {string} */ function formatLiveActivityDetail(act) { if (!act || typeof act !== 'object') return ''; if (act.detailKey === 'compaction_resuming') { return t('live.act.compactionResuming'); } return String(act.detail || ''); } /** * 20 色感知均匀色环(无特定模型绑定,兼顾亮/暗背景可读性,彻底消除标准 HSL 绿色/暗红区过度聚集撞色)。 * 每项为 `[hue, saturationPct, lightnessPct]`。 */ const PERCEPTUAL_MODEL_COLOR_RING = [ [217, 82, 53], // Royal Blue [14, 80, 52], // Coral / Vermilion [162, 74, 41], // Teal / Jade [272, 74, 58], // Vivid Violet [36, 88, 47], // Rich Amber [336, 78, 53], // Rose / Raspberry [193, 84, 43], // Cerulean / Cyan [138, 66, 41], // Emerald Green [246, 74, 60], // Indigo [25, 86, 50], // Tangerine Orange [306, 70, 52], // Magenta / Orchid [177, 76, 39], // Deep Seafoam [355, 76, 54], // Crimson Red [205, 80, 48], // Ocean Blue [45, 88, 44], // Warm Gold [288, 68, 55], // Amethyst Purple [102, 60, 42], // Leaf Green [230, 76, 57], // Cobalt Blue [322, 74, 51], // Berry Pink [185, 72, 46], // Turquoise ]; /** * 提取跨平台、跨语言、同屏三栏(模型排行 / 客户端来源 / 月度统计)严格一致的模型颜色种子字符串。 * * 优先取单模型稳定 `sourceLabels[0]`;若多个外层槽位已在当前显示策略下合并(如 `4-argon`), * 则以规范化 `displayText` 为种子,确保跨客户端与跨月份聚合子集不同时依然映射至完全相同的颜色。 * * @param {object|string|null|undefined} model * @returns {string} */ function getCanonicalModelColorSeed(model) { if (typeof model === 'string') { return model.trim().toLowerCase().replace(/\s+/g, ' '); } if (!model || typeof model !== 'object') return ''; if ( Number(model.mergedCount || 0) <= 1 && Array.isArray(model.sourceLabels) && model.sourceLabels.length === 1 && model.sourceLabels[0] ) { return String(model.sourceLabels[0]).trim().toLowerCase().replace(/\s+/g, ' '); } const raw = model.displayText || model.label || model.modelId || model.baseItem?.modelId || model.shortName || model.name || ''; return String(raw).trim().toLowerCase().replace(/\s+/g, ' '); } function hashModelSeed32(str) { let h = 0x811c9dc5; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193); } h ^= h >>> 16; h = Math.imul(h, 0x85ebca6b); h ^= h >>> 13; h = Math.imul(h, 0xc2b2ae35); h ^= h >>> 16; return h >>> 0; } function formatRingSlotHsl(slotIdx, shiftLight = 0) { const [hue, sat, light] = PERCEPTUAL_MODEL_COLOR_RING[slotIdx % PERCEPTUAL_MODEL_COLOR_RING.length]; const clampedLight = Math.min(66, Math.max(34, light + shiftLight)); return `hsl(${hue} ${sat}% ${clampedLight}%)`; } /** * 基于模型标识通过 32 位雪崩哈希映射至 20 色感知均匀色环,确保跨电脑同模型同色且无需硬编码颜色表。 * * @param {object|string|null|undefined} seedOrModel * @returns {string} */ function resolveDeterministicModelColor(seedOrModel) { const seed = getCanonicalModelColorSeed(seedOrModel); if (!seed) return 'var(--accent-primary)'; const h = hashModelSeed32(seed); return formatRingSlotHsl(h % PERCEPTUAL_MODEL_COLOR_RING.length); } /** * 为一组模型构建确定性颜色映射表(双遍固有槽位保护): * 1. 所有无槽位冲突的模型 100% 保持其纯哈希固有色,不受长尾模型增减影响; * 2. 仅当同屏两个模型恰好落入同一色环槽位时,按严格字典序以互质步长 `+7` 优先探查未被任何模型占用的空闲槽位。 * * @param {Array} [models=[]] * @returns {Map} `canonicalSeed -> hsl(...)` */ function buildDeterministicModelColorMap(models = []) { const ringLen = PERCEPTUAL_MODEL_COLOR_RING.length; const uniqueSeeds = Array.from( new Set( (Array.isArray(models) ? models : []) .map((m) => getCanonicalModelColorSeed(m)) .filter(Boolean) ) ).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); const naturalSlotCounts = new Map(); for (const seed of uniqueSeeds) { const nat = hashModelSeed32(seed) % ringLen; naturalSlotCounts.set(nat, (naturalSlotCounts.get(nat) || 0) + 1); } const usedSlots = new Set(); const colorMap = new Map(); for (const seed of uniqueSeeds) { const h = hashModelSeed32(seed); const nat = h % ringLen; if (!usedSlots.has(nat)) { usedSlots.add(nat); colorMap.set(seed, formatRingSlotHsl(nat)); continue; } let picked = -1; for (let k = 1; k < ringLen; k++) { const cand = (nat + k * 7) % ringLen; if (!usedSlots.has(cand) && !naturalSlotCounts.has(cand)) { picked = cand; break; } } if (picked < 0) { for (let k = 1; k < ringLen; k++) { const cand = (nat + k * 7) % ringLen; if (!usedSlots.has(cand)) { picked = cand; break; } } } if (picked >= 0) { usedSlots.add(picked); colorMap.set(seed, formatRingSlotHsl(picked)); } else { const shift = (h >>> 8) & 1 ? 9 : -8; colorMap.set(seed, formatRingSlotHsl(nat, shift)); } } return colorMap; } return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatTrendSlotFullLabel, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); // --- src/core/stepInspector.js --- const { STEP_LOW_CACHE_MIN_PROMPT_TOKENS, STEP_LOW_CACHE_MAX_PCT, STEP_SLOW_TTFT_MIN_SEC, getStepSelectionKey, isLowCacheStep, isSlowTtftStep, computeStepQuickChipCounts, filterStepsBySearchAndChip, findPrevAgentContextTokens, computeStepTimingWaterfall, buildStepDiagnosticMarkdown, copyPlainTextToClipboard, createCopiedFeedbackController } = (() => { /** * @fileoverview 步骤搜索筛选、快捷诊断统计、耗时瀑布计算及单步诊断 Markdown 导出纯函数模块 (`stepInspector.js`)。 * 保持零 DOM 耦合和单遍 O(N) 高性能,供 `StepsDetailView` 及单元测试直接复用。 */ const STEP_LOW_CACHE_MIN_PROMPT_TOKENS = 2000; const STEP_LOW_CACHE_MAX_PCT = 50; const STEP_SLOW_TTFT_MIN_SEC = 30; /** * 同 `StepTableWidget` 保持一致的单步稳定选择键。 * * @param {object|null|undefined} st * @param {string} [fallbackCascadeId=''] * @returns {string} */ function getStepSelectionKey(st, fallbackCascadeId = '') { if (!st || typeof st !== 'object') return ''; const agentKey = st.agentCascadeId || st.agentId || st.cascadeId || fallbackCascadeId || 'conv'; return `${agentKey}-${st.stepIndex}`; } function isLowCacheStep(st) { if (!st || st.isCompactionStep) return false; const promptTok = Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0); if (promptTok < STEP_LOW_CACHE_MIN_PROMPT_TOKENS) return false; const pct = st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct)) ? Number(st.cacheHitPct) : promptTok > 0 ? (Number(st.cacheReadTokens || 0) / promptTok) * 100 : 0; return pct < STEP_LOW_CACHE_MAX_PCT; } function isSlowTtftStep(st) { if (!st || st.isCompactionStep) return false; return classifyTtftTier(st.ttftSec) === 'danger'; } /** * 单遍 O(N) 统计当前步骤集中各诊断快捷筛选芯片的命中数量。 * * @param {Array} steps * @returns {{ anomaly: number, compaction: number, low_cache: number, slow_ttft: number }} */ function computeStepQuickChipCounts(steps) { let anomaly = 0; let compaction = 0; let lowCache = 0; let slowTtft = 0; if (Array.isArray(steps)) { for (let i = 0; i < steps.length; i += 1) { const st = steps[i]; if (!st) continue; if (st.anomaly && Number(st.anomaly.count) > 0) anomaly += 1; if (st.isCompactionStep) compaction += 1; if (isLowCacheStep(st)) lowCache += 1; if (isSlowTtftStep(st)) slowTtft += 1; } } return { anomaly, compaction, low_cache: lowCache, slow_ttft: slowTtft, }; } /** * 按快捷诊断芯片、异常类型及多词关键字过滤步骤列表(纯函数 O(N))。 * * @param {Array} steps * @param {{ query?: string, quickChip?: string, anomalyKindFilter?: string, displaySettings?: object }} [opts] * @returns {Array} */ function filterStepsBySearchAndChip( steps, { query = '', quickChip = '', anomalyKindFilter = '', displaySettings = {} } = {} ) { if (!Array.isArray(steps) || steps.length === 0) return []; const rawTerms = String(query || '') .trim() .toLowerCase() .split(/\s+/) .filter(Boolean); const chip = String(quickChip || '').trim(); const kind = String(anomalyKindFilter || '').trim(); if (!chip && !kind && rawTerms.length === 0) { return steps; } const out = []; for (let i = 0; i < steps.length; i += 1) { const st = steps[i]; if (!st) continue; if (chip === 'anomaly' || kind) { const a = st.anomaly; if (!a || !(Number(a.count) > 0)) continue; if (kind && !(Number(a.kinds?.[kind] || 0) > 0)) continue; } else if (chip === 'compaction') { if (!st.isCompactionStep) continue; } else if (chip === 'low_cache') { if (!isLowCacheStep(st)) continue; } else if (chip === 'slow_ttft') { if (!isSlowTtftStep(st)) continue; } if (rawTerms.length > 0) { const modelInfo = resolveModelDisplayInfo(st, displaySettings); const anomalyKinds = st.anomaly?.kinds ? Object.keys(st.anomaly.kinds).join(' ') : ''; const anomalyEventsText = Array.isArray(st.anomaly?.events) ? st.anomaly.events .map((ev) => `${ev?.kind || ''} ${ev?.attempt ?? ''} ${ev?.message || ''}`) .join(' ') : ''; const anomalyItemsText = Array.isArray(st.anomaly?.items) ? st.anomaly.items .map((it) => `${it?.kind || ''} ${it?.httpStatus || ''} ${it?.detail || ''}`) .join(' ') : ''; const haystack = [ `#${st.stepIndex ?? ''}`, String(st.stepIndex ?? ''), modelInfo.text, modelInfo.title, st.modelLabel || '', st.modelShort || '', st.modelKey || '', st.modelUpstream || '', st.responseModel || '', st.rawModelId || '', st.upstreamName || '', st.turnPrompt || '', st.rootTurnPrompt || '', st.agentLabel || '', st.agentRole || '', st.agentBadge || '', st.isCompactionStep ? 'compaction 压缩' : '', anomalyKinds, anomalyEventsText, anomalyItemsText, ] .join(' ') .toLowerCase(); let matchedAll = true; for (let tIdx = 0; tIdx < rawTerms.length; tIdx += 1) { if (!haystack.includes(rawTerms[tIdx])) { matchedAll = false; break; } } if (!matchedAll) continue; } out.push(st); } return out; } /** * 在同代理步骤集合中定位目标步骤之前最近一步的上下文 Token 数,用于展示单步上下文增量。 * * @param {Array} allSteps * @param {object|null|undefined} targetStep * @returns {number|null} */ function findPrevAgentContextTokens(allSteps, targetStep) { if (!Array.isArray(allSteps) || !targetStep || targetStep.stepIndex == null) return null; const targetIdx = Number(targetStep.stepIndex); const targetAgent = targetStep.agentId || 'main'; if (!Number.isFinite(targetIdx)) return null; let bestIdx = -Infinity; let bestCtx = null; for (let i = 0; i < allSteps.length; i += 1) { const st = allSteps[i]; if (!st) continue; if ((st.agentId || 'main') !== targetAgent) continue; const idx = Number(st.stepIndex); if (Number.isFinite(idx) && idx < targetIdx && idx > bestIdx) { const ctxVal = Number( st.contextTokens || Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0) + Number(st.outputTokens || 0) ); if (ctxVal > 0) { bestIdx = idx; bestCtx = ctxVal; } } } return bestCtx; } /** * 计算单步耗时瀑布分段比例(TTFT 首字等待 / 流式输出 / 工具及尾部阶段)。 * * @param {object|null|undefined} st * @returns {{ totalSec: number, ttftSec: number, streamSec: number, otherSec: number, thinkingSec: number, ttftPct: number, streamPct: number, otherPct: number }|null} */ function computeStepTimingWaterfall(st) { if (!st || typeof st !== 'object') return null; const rawTtft = st.ttftSec ?? st.nativeTtftSec; const ttft = rawTtft != null && Number.isFinite(Number(rawTtft)) && Number(rawTtft) >= 0 ? Number(rawTtft) : 0; const rawStream = st.nativeStreamSec ?? st.streamDurationSec; const stream = rawStream != null && Number.isFinite(Number(rawStream)) && Number(rawStream) >= 0 ? Number(rawStream) : 0; const thinking = st.thinkingDurationSec != null && Number.isFinite(Number(st.thinkingDurationSec)) && Number(st.thinkingDurationSec) >= 0 ? Number(st.thinkingDurationSec) : 0; const rawDur = st.totalDurationSec ?? st.durationSec; const rawTotal = rawDur != null && Number.isFinite(Number(rawDur)) && Number(rawDur) > 0 ? Number(rawDur) : ttft + stream; const totalSec = Math.max(rawTotal, ttft + stream); if (!(totalSec > 0)) return null; const effStream = Math.min(stream, Math.max(0, totalSec - ttft)); const otherSec = Math.max(0, +(totalSec - ttft - effStream).toFixed(3)); const ttftPct = +((ttft / totalSec) * 100).toFixed(2); const streamPct = +((effStream / totalSec) * 100).toFixed(2); const otherPct = Math.max(0, +(100 - ttftPct - streamPct).toFixed(2)); return { totalSec: +totalSec.toFixed(3), ttftSec: +ttft.toFixed(3), streamSec: +effStream.toFixed(3), otherSec, thinkingSec: +thinking.toFixed(3), ttftPct, streamPct, otherPct, }; } /** * 生成结构化的单步诊断 Markdown 文本,便于直接复制到工单、讨论或性能复盘中。 * * @param {object} st * @param {{ prevContextTokens?: number|null, displaySettings?: object }} [opts] * @returns {string} */ function buildStepDiagnosticMarkdown( st, { prevContextTokens = null, displaySettings = {} } = {} ) { if (!st || typeof st !== 'object') return ''; const modelInfo = resolveModelDisplayInfo(st, displaySettings); const timeStr = st.createdAtMs ? formatCompactDateTime(st.createdAtMs) : '—'; const promptTok = Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0); const cachePct = st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct)) ? formatPctNumber(st.cacheHitPct, { withSymbol: true }) : promptTok > 0 ? formatPctNumber((Number(st.cacheReadTokens || 0) / promptTok) * 100, { withSymbol: true, }) : '0%'; const ctxTok = Number(st.contextTokens || promptTok + Number(st.outputTokens || 0)); const ctxDelta = prevContextTokens != null && ctxTok > 0 ? ` (${ctxTok >= prevContextTokens ? '+' : '-'}${formatTokensPrecise(Math.abs(ctxTok - prevContextTokens))})` : ''; const wf = computeStepTimingWaterfall(st); const lines = [ `### Step #${st.stepIndex ?? '—'} · ${modelInfo.text}${st.isCompactionStep ? ' [Compaction]' : ''}`, `- **Time**: ${timeStr}`, ...(modelInfo.title && modelInfo.title !== modelInfo.text ? [`- **Model ID**: \`${modelInfo.title}\``] : []), `- **Speed / Timing**: ${formatSpeedMetric(st.tokPerSec, ' tok/s')} | TTFT ${formatMetric(st.ttftSec, 's')} | Total ${wf ? formatTimingDetailSec(wf.totalSec) : '—'}${st.selectedSpeedReason ? ` (${speedReasonText(st.selectedSpeedReason) || st.selectedSpeedReason})` : ''}`, `- **Tokens**: Input ${formatTokensPrecise(st.inputTokens || 0)} | Cache ${formatTokensPrecise(st.cacheReadTokens || 0)} (${cachePct}) | Output ${formatTokensPrecise(st.outputTokens || 0)} (Think ${formatTokensPrecise(st.thinkingTokens || 0)} / Reply ${formatTokensPrecise(st.responseTokens || 0)})`, `- **Context / Cost**: ${formatTokensPrecise(ctxTok)}${ctxDelta} | ${formatUsd(st.costUsd, { precise: true })}`, ]; if (st.anomaly && Number(st.anomaly.count) > 0) { const kinds = Object.entries(st.anomaly.kinds || {}) .map(([k, v]) => `${formatAnomalyKindLabel(k)}×${v}`) .join(', '); lines.push(`- **Anomalies (${st.anomaly.count})**: ${kinds || st.anomaly.primaryKind || 'error'}`); } const promptText = String(st.turnPrompt || st.rootTurnPrompt || '').trim(); if (promptText) { lines.push('', '> ' + promptText.replace(/\r?\n/g, '\n> ')); } return lines.join('\n'); } /** * 轻量剪贴板复制工具(优先 Clipboard API,降级至隐藏 textarea execCommand)。 * * @param {string} text * @returns {Promise} */ async function copyPlainTextToClipboard(text) { const str = String(text ?? ''); try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(str); return true; } } catch { // 降级到 DOM 复制 } try { if (typeof document !== 'undefined' && document.body && typeof document.execCommand === 'function') { const ta = document.createElement('textarea'); ta.value = str; ta.setAttribute('readonly', ''); ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select?.(); const ok = document.execCommand('copy'); if (typeof ta.remove === 'function') { ta.remove(); } else { document.body.removeChild?.(ta); } return Boolean(ok); } } catch { // 忽略非浏览器环境异常 } return false; } /** * 统一的「已复制」临时反馈计时器控制器(自动重置定时器并在组件销毁时清理)。 * * @param {{ * durationMs?: number, * onChange?: (copiedKey: any) => void, * onCleanup?: (cleanupFn: () => void) => void, * }} [options={}] */ function createCopiedFeedbackController({ durationMs = 1800, onChange = null, onCleanup = null, } = {}) { let activeKey = null; let timer = null; let disposed = false; function clear() { if (timer) { clearTimeout(timer); timer = null; } if (activeKey !== null) { activeKey = null; if (!disposed) onChange?.(null); } } function trigger(key = true) { if (disposed) return; if (timer) clearTimeout(timer); activeKey = key; onChange?.(activeKey); timer = setTimeout(() => { timer = null; if (disposed) return; activeKey = null; onChange?.(null); }, durationMs); timer?.unref?.(); } onCleanup?.(() => { disposed = true; if (timer) { clearTimeout(timer); timer = null; } activeKey = null; }); return { isCopied: (key = true) => activeKey === key, getActiveKey: () => activeKey, trigger, clear, }; } return { STEP_LOW_CACHE_MIN_PROMPT_TOKENS, STEP_LOW_CACHE_MAX_PCT, STEP_SLOW_TTFT_MIN_SEC, getStepSelectionKey, isLowCacheStep, isSlowTtftStep, computeStepQuickChipCounts, filterStepsBySearchAndChip, findPrevAgentContextTokens, computeStepTimingWaterfall, buildStepDiagnosticMarkdown, copyPlainTextToClipboard, createCopiedFeedbackController }; })(); // --- src/core/settingsBackup.js --- const { triggerBlobDownload, triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson } = (() => { /** * @fileoverview 偏好设置便携 JSON 备份及恢复工具 (`settingsBackup.js`). * 通过单一声明式字段描述符表同时驱动导出与导入归一化,消除双遍手写 30 个键的漏同步风险。 */ const SETTINGS_BACKUP_SCHEMA = 'antigravity-usage-monitor.settings'; const MAX_SETTINGS_IMPORT_BYTES = 128 * 1024; function sanitizePositiveBudgetNum(val) { const num = Number(val); return Number.isFinite(num) && num > 0 ? num : null; } /** * 在浏览器端通过内存 Blob 触发文件下载(统一承载文本与二进制载荷)。 * * @param {string} filename * @param {BlobPart} blobPart * @param {string} [mimeType] * @returns {boolean} */ function triggerBlobDownload( filename, blobPart, mimeType = 'application/octet-stream' ) { try { if ( typeof Blob === 'undefined' || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function' || typeof document === 'undefined' ) { return false; } const blob = new Blob([blobPart], { type: mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', String(filename || 'export.dat')); a.style.display = 'none'; document.body?.appendChild?.(a); a.click?.(); a.remove?.(); setTimeout(() => { try { URL.revokeObjectURL(url); } catch {} }, 1000); return true; } catch { return false; } } /** * 在浏览器端通过内存 Blob 触发文本文件下载。 * * @param {string} filename * @param {string} content * @param {string} [mimeType] * @returns {boolean} */ function triggerTextFileDownload( filename, content, mimeType = 'application/json;charset=utf-8' ) { return triggerBlobDownload( String(filename || 'export.json'), String(content ?? ''), mimeType ); } const normField = (key, normalizeFn) => ({ exportTo: (src, out) => { out[key] = normalizeFn(src[key]); }, importTo: (src, hasKey, patch) => { if (hasKey(key)) patch[key] = normalizeFn(src[key]); }, }); const boolField = (key, defaultVal) => ({ exportTo: (src, out) => { out[key] = defaultVal ? src[key] !== false : src[key] === true; }, importTo: (src, hasKey, patch) => { if (hasKey(key) && typeof src[key] === 'boolean') patch[key] = src[key]; }, }); const arrayField = (key, normalizeFn) => ({ exportTo: (src, out) => { out[key] = normalizeFn(src[key]); }, importTo: (src, hasKey, patch) => { if (hasKey(key) && Array.isArray(src[key])) patch[key] = normalizeFn(src[key]); }, }); const positiveBudgetField = (key, fallbackVal) => ({ exportTo: (src, out) => { out[key] = sanitizePositiveBudgetNum(src[key]) ?? fallbackVal; }, importTo: (src, hasKey, patch) => { if (hasKey(key)) { const num = sanitizePositiveBudgetNum(src[key]); if (num !== null) patch[key] = num; } }, }); const PORTABLE_SETTING_DESCRIPTORS = Object.freeze([ normField('language', normalizeLanguageSetting), normField('themeAccent', normalizeThemeAccent), normField('fontScale', normalizeFontScale), { exportTo: (src, out) => { out.modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true; }, importTo: (src, hasKey, patch) => { if (hasKey('modernUi')) { const val = normalizeModernUi(src.modernUi); patch.modernUi = val; patch.experimentalModernUi = val; } }, }, normField('weeklyLimitMode', normalizeWeeklyLimitMode), positiveBudgetField('weeklyTokenBudget', 150000000), positiveBudgetField('weeklyCostBudget', 100), { exportTo: (src, out) => { const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); out.modelDisplayMode = mode; out.showUpstreamModel = mode !== 'short'; }, importTo: (src, hasKey, patch) => { if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) { const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); patch.modelDisplayMode = mode; patch.showUpstreamModel = mode !== 'short'; } }, }, normField('orchestratorIdMode', normalizeOrchestratorIdMode), { exportTo: (src, out) => { out.pluginUpdateMode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin); }, importTo: (src, hasKey, patch) => { if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) { const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin); patch.pluginUpdateMode = mode; patch.autoUpdatePlugin = mode === 'auto'; } }, }, { exportTo: (src, out) => { out.windowMountMode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay); }, importTo: (src, hasKey, patch) => { if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) { const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay); patch.windowMountMode = mode; patch.enableWindowOverlay = mode !== 'sidebar'; } }, }, normField('popoverWidthMode', normalizePopoverWidthMode), normField('popoverWidth', normalizePopoverWidth), boolField('enableCliStatusLine', true), normField('cliStatusLineSlots', normalizeCliStatusLineSlots), normField('standalonePort', normalizeStandalonePort), boolField('showTopbarMultiSession', true), normField('contextAgentMode', normalizeContextAgentMode), arrayField('topbarCapsuleSlots', normalizeTopbarCapsuleSlots), arrayField('hoverModules', normalizeHoverModules), arrayField('overviewModules', normalizeOverviewModules), arrayField('overviewMetrics', normalizeOverviewMetrics), boolField('showStepTurnRail', false), boolField('showStepAgentBadge', true), boolField('showStepSpeedColor', false), boolField('showStepFilterToolbar', false), normField('stepTokenComboFormat', normalizeStepTokenComboFormat), arrayField('stepTableColumns', normalizeStepTableColumns), normField('experimentalQuotaReservation', normalizeExperimentalQuotaReservation), normField('accountQuotaRefreshMinutes', normalizeAccountQuotaRefreshMinutes), ]); /** * 将当前用户偏好设置序列化为跨设备可迁移的安全 JSON 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。 * * @param {object} [settings={}] * @returns {string} */ function buildExportableSettingsJson(settings = {}) { const src = settings && typeof settings === 'object' ? settings : {}; const outSettings = {}; for (const desc of PORTABLE_SETTING_DESCRIPTORS) { desc.exportTo(src, outSettings); } const payload = { schema: SETTINGS_BACKUP_SCHEMA, version: 1, exportedAt: new Date().toISOString(), settings: outSettings, }; return `${JSON.stringify(payload, null, 2)}\n`; } /** * 校验并解析导入的偏好设置 JSON,仅提取并归一化白名单内的便携配置项。 * * @param {string} rawText * @returns {{ ok: true, patch: object, appliedCount: number } | { ok: false, errorCode: string }} */ function parseImportedSettingsJson(rawText) { if (typeof rawText !== 'string' || !rawText.trim() || rawText.length > MAX_SETTINGS_IMPORT_BYTES) { return { ok: false, errorCode: 'invalid_json' }; } let parsed; try { parsed = JSON.parse(rawText); } catch { return { ok: false, errorCode: 'invalid_json' }; } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return { ok: false, errorCode: 'invalid_json' }; } const hasWrappedSettings = parsed.settings && typeof parsed.settings === 'object' && !Array.isArray(parsed.settings); if (parsed.schema !== undefined && parsed.schema !== SETTINGS_BACKUP_SCHEMA) { return { ok: false, errorCode: 'invalid_schema' }; } const src = hasWrappedSettings ? parsed.settings : parsed; const hasKey = (k) => Object.prototype.hasOwnProperty.call(src, k); const patch = {}; for (const desc of PORTABLE_SETTING_DESCRIPTORS) { desc.importTo(src, hasKey, patch); } const appliedCount = Object.keys(patch).length; if (appliedCount === 0) { return { ok: false, errorCode: 'empty_patch' }; } return { ok: true, patch, appliedCount }; } return { triggerBlobDownload, triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson }; })(); // --- src/core/xlsxBuilder.js --- const { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { /** * @fileoverview 零外部依赖原生 Excel (`.xlsx` / ECMA-376 OOXML) 多工作表构建器 (`xlsxBuilder.js`)。 * 内置标准 IEEE 802.3 CRC-32 及 ZIP STORE 封装,支持: * - 多 Sheet 分页、冻结首行表头、自动筛选下拉箭头; * - 按中英文混合视觉宽度精确自动计算最佳列宽(彻底消除截断及 `###` / `1E+08` 科学计数法); * - 原生数字格式(整数千分位 `#,##0`、货币 `$#,##0.00` / `$#,##0.0000`、原生百分比 `0.0%`、小数 `#,##0.0`); * - 专业视觉样式(深石板蓝表头、斑马纹、汇总高亮、异常红底警示、压缩蓝底提示); * - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。 */ const MAX_EXCEL_CELL_CHARS = 32767; const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g; const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { const tbl = new Uint32Array(256); for (let i = 0; i < 256; i += 1) { let c = i; for (let k = 0; k < 8; k += 1) { c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; } tbl[i] = c >>> 0; } return tbl; })(); function computeCrc32(bytes) { let crc = 0xffffffff; for (let i = 0; i < bytes.length; i += 1) { crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8); } return (crc ^ 0xffffffff) >>> 0; } function encodeUtf8Bytes(str) { if (typeof TextEncoder !== 'undefined') { return new TextEncoder().encode(String(str ?? '')); } if (typeof Buffer !== 'undefined') { return new Uint8Array(Buffer.from(String(str ?? ''), 'utf8')); } const s = unescape(encodeURIComponent(String(str ?? ''))); const out = new Uint8Array(s.length); for (let i = 0; i < s.length; i += 1) out[i] = s.charCodeAt(i); return out; } /** * 将 `Uint8Array` 编码为标准 Base64 字符串(兼容浏览器及 Node 环境)。 * * @param {Uint8Array} bytes * @returns {string} */ function uint8ArrayToBase64(bytes) { if (!(bytes instanceof Uint8Array)) return ''; if (typeof Buffer !== 'undefined') { return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64'); } let binary = ''; const chunkSize = 0x8000; for (let i = 0; i < bytes.length; i += chunkSize) { const slice = bytes.subarray(i, i + chunkSize); binary += String.fromCharCode.apply(null, slice); } return btoa(binary); } /** * 标准零依赖 ZIP STORE 打包器(用于生成严格合规的 `.xlsx` OOXML 容器)。 * * @param {Array<{ name: string, data: Uint8Array | string }>} entries * @returns {Uint8Array} */ function buildZipStoreArchive(entries) { const localParts = []; const centralParts = []; let offset = 0; for (let i = 0; i < entries.length; i += 1) { const nameBytes = encodeUtf8Bytes(entries[i].name); const dataBytes = entries[i].data instanceof Uint8Array ? entries[i].data : encodeUtf8Bytes(entries[i].data); const crc = computeCrc32(dataBytes); const size = dataBytes.length; // Local File Header (30 bytes + filename + data) const lh = new Uint8Array(30 + nameBytes.length); const lv = new DataView(lh.buffer); lv.setUint32(0, 0x04034b50, true); lv.setUint16(4, 20, true); // version needed: 2.0 lv.setUint16(6, 0x0800, true); // UTF-8 filename flag lv.setUint16(8, 0, true); // compression: STORE lv.setUint16(10, 0, true); // mod time lv.setUint16(12, 0x5821, true); // mod date lv.setUint32(14, crc, true); lv.setUint32(18, size, true); lv.setUint32(22, size, true); lv.setUint16(26, nameBytes.length, true); lv.setUint16(28, 0, true); lh.set(nameBytes, 30); localParts.push(lh, dataBytes); // Central Directory Header (46 bytes + filename) const ch = new Uint8Array(46 + nameBytes.length); const cv = new DataView(ch.buffer); cv.setUint32(0, 0x02014b50, true); cv.setUint16(4, 20, true); cv.setUint16(6, 20, true); cv.setUint16(8, 0x0800, true); cv.setUint16(10, 0, true); cv.setUint16(12, 0, true); cv.setUint16(14, 0x5821, true); cv.setUint32(16, crc, true); cv.setUint32(20, size, true); cv.setUint32(24, size, true); cv.setUint16(28, nameBytes.length, true); cv.setUint16(30, 0, true); cv.setUint16(32, 0, true); cv.setUint16(34, 0, true); cv.setUint16(36, 0, true); cv.setUint32(38, 0, true); cv.setUint32(42, offset, true); ch.set(nameBytes, 46); centralParts.push(ch); offset += lh.length + dataBytes.length; } let cdSize = 0; for (let i = 0; i < centralParts.length; i += 1) cdSize += centralParts[i].length; // End of Central Directory Record (22 bytes) const eocd = new Uint8Array(22); const ev = new DataView(eocd.buffer); ev.setUint32(0, 0x06054b50, true); ev.setUint16(4, 0, true); ev.setUint16(6, 0, true); ev.setUint16(8, entries.length, true); ev.setUint16(10, entries.length, true); ev.setUint32(12, cdSize, true); ev.setUint32(16, offset, true); ev.setUint16(20, 0, true); const totalLen = offset + cdSize + eocd.length; const archive = new Uint8Array(totalLen); let pos = 0; for (let i = 0; i < localParts.length; i += 1) { archive.set(localParts[i], pos); pos += localParts[i].length; } for (let i = 0; i < centralParts.length; i += 1) { archive.set(centralParts[i], pos); pos += centralParts[i].length; } archive.set(eocd, pos); return archive; } function sanitizeExcelCellText(val) { const clean = String(val ?? '') .replace(INVALID_XML_CTRL_RE, '') .replace(LONE_SURROGATE_RE, '\uFFFD'); if (clean.length <= MAX_EXCEL_CELL_CHARS) { return clean; } // 桌面版 Excel 单格文本硬上限为 32,767 UTF-16 码元;预留 1 位给省略号并避免劈断代理对 let cut = MAX_EXCEL_CELL_CHARS - 1; const prevCode = clean.charCodeAt(cut - 1); if (prevCode >= 0xd800 && prevCode <= 0xdbff) { cut -= 1; } return `${clean.slice(0, cut)}…`; } function escapeXmlText(val) { return sanitizeExcelCellText(val) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function columnIndexToLetter(index) { let n = index + 1; let out = ''; while (n > 0) { const rem = (n - 1) % 26; out = String.fromCharCode(65 + rem) + out; n = Math.floor((n - 1) / 26); } return out; } /** * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽; * 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。 */ function measureExcelVisualWidth(str) { const raw = String(str ?? ''); const s = (raw.length > 128 ? raw.slice(0, 128) : raw).replace(/\r?\n/g, ' '); let w = 0; for (let i = 0; i < s.length; i += 1) { const code = s.charCodeAt(i); if ( (code >= 0x2e80 && code <= 0x9fff) || (code >= 0xac00 && code <= 0xd7af) || (code >= 0xf900 && code <= 0xfaff) || (code >= 0xff00 && code <= 0xffef) ) { w += 2.05; } else { w += 1.05; } } return w; } function estimateFormattedValueWidth(val, colType) { if (val === null || val === undefined || val === '') return 0; if (typeof val === 'number' && Number.isFinite(val)) { if (colType === 'int') { return Math.round(val).toLocaleString('en-US').length * 1.1; } if (colType === 'usd2') { return (`$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`).length * 1.1; } if (colType === 'usd4') { return (`$${val.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 })}`).length * 1.1; } if (colType === 'pct') { return (`${(val * 100).toFixed(1)}%`).length * 1.1; } if (colType === 'dec1') { return (`${val.toFixed(1)}`).length * 1.1; } if (colType === 'dec2') { return (`${val.toFixed(2)}`).length * 1.1; } } return measureExcelVisualWidth(String(val)); } function sanitizeSheetName(rawName, usedNames) { const base = String(rawName || 'Sheet') .replace(INVALID_XML_CTRL_RE, '') .replace(INVALID_SHEET_NAME_RE, ' ') .replace(/^'+|'+$/g, '') .trim() .slice(0, 31) || 'Sheet'; let name = base; let seq = 2; while (usedNames.has(name.toLowerCase())) { const suffix = ` ${seq}`; name = `${base.slice(0, Math.max(1, 31 - suffix.length))}${suffix}`; seq += 1; } usedNames.add(name.toLowerCase()); return name; } function resolveHeaderStyle(col) { const align = col.align || (col.type === 'center' ? 'center' : col.type && col.type !== 'text' ? 'right' : 'left'); if (align === 'center') return STYLE_HEADER_CENTER; if (align === 'right') return STYLE_HEADER_RIGHT; return STYLE_HEADER_LEFT; } function resolveCellStyle(col, isAlt, rowTone) { const colType = col.type || 'text'; if (rowTone === 'summary') { if (colType === 'center') return STYLE_SUMMARY_CENTER; if (colType === 'int') return STYLE_SUMMARY_INT; if (colType === 'dec1') return STYLE_SUMMARY_DEC1; if (colType === 'dec2') return STYLE_SUMMARY_DEC2; if (colType === 'pct') return STYLE_SUMMARY_PCT; if (colType === 'usd2') return STYLE_SUMMARY_USD2; if (colType === 'usd4') return STYLE_SUMMARY_USD4; if (colType === 'text_right' || col.align === 'right') return STYLE_SUMMARY_TEXT_RIGHT; return STYLE_SUMMARY_LABEL; } if (rowTone === 'danger') { if (colType === 'center') return STYLE_DANGER_CENTER; if (colType === 'int') return STYLE_DANGER_INT; if (colType === 'dec1') return STYLE_DANGER_DEC1; if (colType === 'dec2') return STYLE_DANGER_DEC2; if (colType === 'pct') return STYLE_DANGER_PCT; if (colType === 'usd2' || colType === 'usd4') return STYLE_DANGER_USD4; return STYLE_DANGER_TEXT; } if (rowTone === 'info') { if (colType === 'center') return STYLE_INFO_CENTER; if (colType === 'int') return STYLE_INFO_INT; if (colType === 'dec1') return STYLE_INFO_DEC1; if (colType === 'dec2') return STYLE_INFO_DEC2; if (colType === 'pct') return STYLE_INFO_PCT; if (colType === 'usd2' || colType === 'usd4') return STYLE_INFO_USD4; return STYLE_INFO_TEXT; } if (colType === 'center') return isAlt ? STYLE_TEXT_CENTER_ALT : STYLE_TEXT_CENTER; if (colType === 'text_right') return isAlt ? STYLE_TEXT_RIGHT_ALT : STYLE_TEXT_RIGHT; if (colType === 'int') return isAlt ? STYLE_INT_ALT : STYLE_INT; if (colType === 'dec1') return isAlt ? STYLE_DEC1_ALT : STYLE_DEC1; if (colType === 'dec2') return isAlt ? STYLE_DEC2_ALT : STYLE_DEC2; if (colType === 'pct') return isAlt ? STYLE_PCT_ALT : STYLE_PCT; if (colType === 'usd2') return isAlt ? STYLE_USD2_ALT : STYLE_USD2; if (colType === 'usd4') return isAlt ? STYLE_USD4_ALT : STYLE_USD4; return isAlt ? STYLE_TEXT_LEFT_ALT : STYLE_TEXT_LEFT; } function buildStylesXml() { return ` `; } function buildWorksheetXml(sheet, isFirstSheet) { const columns = Array.isArray(sheet.columns) ? sheet.columns : []; const rows = Array.isArray(sheet.rows) ? sheet.rows : []; const hasAutoFilter = sheet.autoFilter !== false; const headerPad = hasAutoFilter ? 5.5 : 3.8; const colWidths = columns.map((col) => { const headerW = measureExcelVisualWidth(col.header || '') + headerPad; return Math.max(Number(col.minWidth || 9), headerW); }); const rowXmls = []; // Row 1: Header const headerCells = []; for (let c = 0; c < columns.length; c += 1) { const ref = `${columnIndexToLetter(c)}1`; const styleId = resolveHeaderStyle(columns[c]); headerCells.push( `${escapeXmlText(columns[c].header || '')}` ); } rowXmls.push(`${headerCells.join('')}`); // Data Rows for (let r = 0; r < rows.length; r += 1) { const rowObj = rows[r]; const rowValues = Array.isArray(rowObj) ? rowObj : Array.isArray(rowObj?.values) ? rowObj.values : []; const rowTone = !Array.isArray(rowObj) && rowObj?.tone ? rowObj.tone : ''; const isAlt = r % 2 === 1; const excelRowIdx = r + 2; const cellXmls = []; for (let c = 0; c < columns.length; c += 1) { const col = columns[c]; const rawVal = rowValues[c]; const ref = `${columnIndexToLetter(c)}${excelRowIdx}`; const isCellObj = rawVal && typeof rawVal === 'object' && !Array.isArray(rawVal); const val = isCellObj ? rawVal.value : rawVal; const cellCol = isCellObj && rawVal.type ? { ...col, type: rawVal.type } : col; const styleId = resolveCellStyle(cellCol, isAlt, rowTone); const estW = estimateFormattedValueWidth(val, cellCol.type) + 3.8; const maxW = Number(col.maxWidth || 52); if (estW > colWidths[c]) { colWidths[c] = Math.min(maxW, estW); } if (val === null || val === undefined || val === '') { cellXmls.push(``); } else if (typeof val === 'number' && Number.isFinite(val)) { cellXmls.push(`${val}`); } else { const textVal = String(val); cellXmls.push( `${escapeXmlText(textVal)}` ); } } const rowHeight = rowTone === 'summary' ? 24 : 21; rowXmls.push(`${cellXmls.join('')}`); } const colsXml = columns .map((_, idx) => { const w = Math.max(8, Math.min(64, +colWidths[idx].toFixed(1))); return ``; }) .join(''); const lastCol = columnIndexToLetter(Math.max(0, columns.length - 1)); const lastRow = Math.max(1, rows.length + 1); // 若末尾包含合计行,自动筛选区自动排除合计行,避免按列排序时把合计行混入明细 let filterEndRow = lastRow; while (filterEndRow > 1) { const tailRow = rows[filterEndRow - 2]; if (tailRow && !Array.isArray(tailRow) && tailRow.tone === 'summary') { filterEndRow -= 1; } else { break; } } const autoFilterXml = hasAutoFilter && columns.length > 0 && filterEndRow > 1 ? `` : ''; const tabSel = isFirstSheet ? ' tabSelected="1"' : ''; const freezeXml = sheet.freezeHeader !== false ? '' : ''; return ` ${freezeXml} ${colsXml} ${rowXmls.join('')} ${autoFilterXml} `; } /** * 将结构化多工作表数据编译为标准 `.xlsx` 二进制字节流 (`Uint8Array`)。 * * @param {Array<{ * name: string, * columns: Array<{ header: string, type?: 'text'|'center'|'int'|'dec1'|'dec2'|'pct'|'usd2'|'usd4', align?: 'left'|'center'|'right', minWidth?: number, maxWidth?: number }>, * rows: Array | { values: Array, tone?: ''|'danger'|'info'|'summary' }>, * autoFilter?: boolean, * freezeHeader?: boolean, * }>} sheets * @returns {Uint8Array} */ function buildXlsxWorkbookBytes(sheets) { const validSheets = (Array.isArray(sheets) ? sheets : []).filter( (s) => s && Array.isArray(s.columns) && s.columns.length > 0 ); if (validSheets.length === 0) { validSheets.push({ name: 'Sheet1', columns: [{ header: 'Empty', type: 'text', minWidth: 14 }], rows: [], }); } const usedNames = new Set(); const normalizedSheets = validSheets.map((s) => ({ ...s, safeName: sanitizeSheetName(s.name, usedNames), })); const contentOverrides = [ '', '', ...normalizedSheets.map( (_, idx) => `` ), ].join(''); const contentTypesXml = ` ${contentOverrides} `; const rootRelsXml = ` `; const wbSheetsXml = normalizedSheets .map( (s, idx) => `` ) .join(''); const workbookXml = ` ${wbSheetsXml} `; const wbRelsList = [ ...normalizedSheets.map( (_, idx) => `` ), ``, ].join(''); const wbRelsXml = ` ${wbRelsList} `; const archiveEntries = [ { name: '[Content_Types].xml', data: contentTypesXml }, { name: '_rels/.rels', data: rootRelsXml }, { name: 'xl/workbook.xml', data: workbookXml }, { name: 'xl/_rels/workbook.xml.rels', data: wbRelsXml }, { name: 'xl/styles.xml', data: buildStylesXml() }, ...normalizedSheets.map((s, idx) => ({ name: `xl/worksheets/sheet${idx + 1}.xml`, data: buildWorksheetXml(s, idx === 0), })), ]; return buildZipStoreArchive(archiveEntries); } return { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes }; })(); // --- src/core/reportExporter.js --- const { escapeCsvCell, sanitizeExportFilename, buildConsumptionExportBaseName, buildStepsExportBaseName, buildStepsCsv, buildStepsXlsx, buildStepsMarkdownReport, buildConsumptionCsv, buildConsumptionXlsx, buildConsumptionMarkdownReport } = (() => { /** * @fileoverview 原生多工作表 Excel (`.xlsx`)、RFC-4180 防公式注入 CSV 及双语 Markdown 诊断报告生成纯函数模块 (`reportExporter.js`)。 * 零外部依赖、单遍 O(N) 聚合,供「按步查看」和「用量统计」视图复用。 */ const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/; const RANGE_LABELS_ZH = Object.freeze({ '5h': '近5小时', today: '今日', '24h': '近24小时', week: '本周', '7d': '近7天', '14d': '近14天', '30d': '近30天', all: '全部时间', cycle: '当前周期', custom: '自定义区间', }); const RANGE_LABELS_EN = Object.freeze({ '5h': 'Last 5 Hours', today: 'Today', '24h': 'Last 24 Hours', week: 'This Week', '7d': 'Last 7 Days', '14d': 'Last 14 Days', '30d': 'Last 30 Days', all: 'All Time', cycle: 'Current Cycle', custom: 'Custom Range', }); const ANOMALY_LABELS_ZH = Object.freeze({ timeout: '流空闲 / 连接超时', rate_limit: '429 限流 / 配额耗尽', capacity: '503 上游算力不足', disconnect: '连接中断 / 断流', upstream: '上游 5xx 内部错误', model_output: '模型输出 / 工具参数无效', safety: '内容安全过滤', auth_or_model: '请求受限 / 模型不可用', error: '调用异常', canceled: '用户取消', }); const ANOMALY_LABELS_EN = Object.freeze({ timeout: 'Stream Idle / Connect Timeout', rate_limit: '429 Rate Limit / Quota Reached', capacity: '503 No Capacity Available', disconnect: 'Connection Reset / Stream Interrupted', upstream: 'Upstream 5xx Internal Error', model_output: 'Invalid Model Output / Tool Call', safety: 'Content Safety Filter', auth_or_model: 'Request / Model Rejected', error: 'Call Error', canceled: 'Canceled by User', }); function resolveExportEnglish(locale) { if (typeof locale === 'string' && locale.trim()) { return locale.trim().toLowerCase().startsWith('en'); } return isEnglishLocale(); } function formatExportDateTime(ms, includeSeconds = true) { const n = Number(ms); if (!(n > 0) || !Number.isFinite(n)) return ''; const d = new Date(n); const pad = (v) => String(v).padStart(2, '0'); const base = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; return includeSeconds ? `${base}:${pad(d.getSeconds())}` : base; } function formatExportDate(ms) { const n = Number(ms); if (!(n > 0) || !Number.isFinite(n)) return ''; const d = new Date(n); const pad = (v) => String(v).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; } function resolveLocalizedRangeLabel(range, en) { const r = range || {}; const key = String(r.key || '').trim().toLowerCase(); const poolSuffix = key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : ''; if (en) { const baseEn = key === 'cycle' && r.isFallbackWeek ? 'This Week' : RANGE_LABELS_EN[key] || r.label || key || 'All Time'; return `${baseEn}${poolSuffix}`; } if (r.label) return r.label; const baseZh = RANGE_LABELS_ZH[key] || key || '全部时间'; return `${baseZh}${poolSuffix}`; } function resolveRangeSpanNote(range) { const startMs = Number(range?.startMs || 0); const endMs = Number(range?.endMs || 0); if (startMs > 0 && endMs > 0) { return `${formatExportDate(startMs)} ~ ${formatExportDate(endMs)}`; } return ''; } function computeCacheHitRatio(inTok, cacheTok, fallbackPct = null) { const safeIn = Math.max(0, Number(inTok || 0)); const safeCache = Math.max(0, Number(cacheTok || 0)); const promptTok = safeIn + safeCache; if (promptTok > 0) { return Math.max(0, Math.min(1, safeCache / promptTok)); } if (fallbackPct != null && Number.isFinite(Number(fallbackPct))) { return Math.max(0, Math.min(1, Number(fallbackPct) / 100)); } return 0; } function formatLocalizedAnomalyKind(kind, en, explicitLocale) { const k = String(kind || 'error').trim(); if (explicitLocale) { const dict = en ? ANOMALY_LABELS_EN : ANOMALY_LABELS_ZH; if (dict[k]) return dict[k]; } return formatAnomalyKindLabel(k); } function formatStepAnomaliesText(st, en, explicitLocale) { const anom = st?.anomaly; const count = Number(anom?.count || 0); if (!(count > 0)) return ''; const kinds = anom?.kinds && typeof anom.kinds === 'object' ? Object.entries(anom.kinds) : []; if (kinds.length > 0) { return kinds .filter(([, v]) => Number(v || 0) > 0) .map(([k, v]) => `${formatLocalizedAnomalyKind(k, en, explicitLocale)} ×${Number(v)}`) .join(';'); } return formatLocalizedAnomalyKind(anom?.primaryKind || 'error', en, explicitLocale); } function formatStepAgentLabel(st, en) { const explicit = String(st?.agentLabel || st?.agentBadge || '').trim(); if (explicit) return explicit; if (st?.isSubagent) { return st?.agentId ? String(st.agentId) : en ? 'Subagent' : '子代理'; } return en ? 'Main' : '主会话'; } function formatTrendWindowLabel(slot, isHourly) { if (Number(slot?.startMs) > 0) { return isHourly ? formatExportDateTime(slot.startMs, false) : formatExportDate(slot.startMs); } return String(slot?.fullLabel || slot?.label || ''); } function summarizeStepsForExport(list, displaySettings) { let sumIn = 0; let sumCache = 0; let sumOut = 0; let sumThink = 0; let sumReply = 0; let sumCost = 0; let sumDuration = 0; let maxContext = 0; let tpsTokSum = 0; let tpsSecSum = 0; let tpsCnt = 0; let ttftSum = 0; let ttftCnt = 0; let anomSteps = 0; let anomTotal = 0; let compactionCount = 0; const byModel = new Map(); for (let i = 0; i < list.length; i += 1) { const st = list[i]; if (!st) continue; const inTok = Math.max(0, Number(st.inputTokens || 0)); const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); const outTok = Math.max(0, Number(st.outputTokens || 0)); const thinkTok = Math.max(0, Number(st.thinkingTokens || 0)); const replyTok = st.responseTokens != null ? Math.max(0, Number(st.responseTokens)) : Math.max(0, outTok - thinkTok); const ctxTok = Math.max(0, Number(st.contextTokens || inTok + cacheTok + outTok)); const cost = Number(st.costUsd || 0); const rawDur = st.totalDurationSec ?? st.durationSec; const dur = rawDur != null && Number.isFinite(Number(rawDur)) ? Number(rawDur) : 0; sumIn += inTok; sumCache += cacheTok; sumOut += outTok; sumThink += thinkTok; sumReply += replyTok; if (ctxTok > maxContext) maxContext = ctxTok; if (Number.isFinite(cost) && cost > 0) sumCost += cost; if (Number.isFinite(dur) && dur > 0) sumDuration += dur; const validTps = !st.isCompactionStep && !st.isImageGenStep && outTok >= 50 && !st.selectedSpeedReason && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0; const stepSpeedSec = validTps ? st.totalDurationSec != null && Number(st.totalDurationSec) >= 0.5 ? Number(st.totalDurationSec) : outTok / Number(st.tokPerSec) : 0; const validTtft = !st.isCompactionStep && !st.isImageGenStep && st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0; if (validTps && stepSpeedSec > 0) { tpsTokSum += outTok; tpsSecSum += stepSpeedSec; tpsCnt += 1; } if (validTtft) { ttftSum += Number(st.ttftSec); ttftCnt += 1; } if (st.isCompactionStep) compactionCount += 1; const ac = Number(st.anomaly?.count || 0); if (ac > 0) { anomSteps += 1; anomTotal += ac; } const mInfo = resolveModelDisplayInfo(st, displaySettings); const mKey = mInfo.text || 'Unknown'; let mAcc = byModel.get(mKey); if (!mAcc) { mAcc = { label: mKey, calls: 0, inTok: 0, cacheTok: 0, outTok: 0, cost: 0, tpsTokSum: 0, tpsSecSum: 0, tpsCnt: 0, ttftSum: 0, ttftCnt: 0, }; byModel.set(mKey, mAcc); } mAcc.calls += 1; mAcc.inTok += inTok; mAcc.cacheTok += cacheTok; mAcc.outTok += outTok; if (Number.isFinite(cost) && cost > 0) mAcc.cost += cost; if (validTps && stepSpeedSec > 0) { mAcc.tpsTokSum += outTok; mAcc.tpsSecSum += stepSpeedSec; mAcc.tpsCnt += 1; } if (validTtft) { mAcc.ttftSum += Number(st.ttftSec); mAcc.ttftCnt += 1; } } const sortedModels = Array.from(byModel.values()).sort( (a, b) => b.cost - a.cost || b.inTok + b.cacheTok + b.outTok - (a.inTok + a.cacheTok + a.outTok) ); return { sumIn, sumCache, sumOut, sumThink, sumReply, sumCost, sumDuration, maxContext, tpsTokSum, tpsSecSum, tpsCnt, ttftSum, ttftCnt, anomSteps, anomTotal, compactionCount, sortedModels, }; } /** * RFC-4180 安全转义单个 CSV 单元格,并防御电子表格公式注入(`=`, `+`, `-`, `@`, `\t`, `\r`)。 * * @param {unknown} value * @returns {string} */ function escapeCsvCell(value) { if (value === null || value === undefined) return ''; let str = String(value); if (str.length > 0) { const first = str[0]; if ( first === '=' || first === '@' || first === '\t' || first === '\r' || ((first === '+' || first === '-') && !PLAIN_SIGNED_NUMBER_RE.test(str.trim())) ) { str = `'${str}`; } } if (/[",\r\n]/.test(str)) { return `"${str.replace(/"/g, '""')}"`; } return str; } function csvRow(cells) { return cells.map(escapeCsvCell).join(','); } /** * 生成安全跨平台导出文件名(剔除非法路径字符并附加 `YYYYMMDD-HHmm` 时间戳)。 * * @param {string} baseName * @param {string} ext * @param {number} [nowMs] * @returns {string} */ function sanitizeExportFilename(baseName, ext = 'xlsx', nowMs = Date.now()) { const cleanBase = String(baseName || 'usage-report') .replace(/[\\/:*?"<>|\r\n\t]+/g, '-') .replace(/\s+/g, '-') .replace(/-+/g, '-') .replace(/^-|-$/g, '') .slice(0, 48) || 'usage-report'; const d = new Date(Number.isFinite(nowMs) ? nowMs : Date.now()); const pad = (n) => String(n).padStart(2, '0'); const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`; const cleanExt = String(ext || 'xlsx').replace(/^\.+/, ''); return `${cleanBase}-${stamp}.${cleanExt}`; } /** * 生成按当前界面语言本地化的用量统计导出文件前缀。 * * @param {object} consumption * @param {string} [fallbackRange='all'] * @param {{ locale?: string }} [opts] * @returns {string} */ function buildConsumptionExportBaseName( consumption, fallbackRange = 'all', { locale } = {} ) { const en = resolveExportEnglish(locale); const range = consumption?.selectedRange || { key: fallbackRange }; const rKey = range.key || fallbackRange || 'all'; if (en) { return `usage-${rKey}`; } const zhLabel = resolveLocalizedRangeLabel(range, false); return `用量统计-${zhLabel}`; } /** * 生成按当前界面语言本地化的调用明细导出文件前缀。 * * @param {string} [title=''] * @param {string} [cascadeId=''] * @param {{ locale?: string }} [opts] * @returns {string} */ function buildStepsExportBaseName(title = '', cascadeId = '', { locale } = {}) { const en = resolveExportEnglish(locale); const name = String(title || cascadeId || '').trim(); if (en) { return `steps-${name || 'session'}`; } return `调用明细-${name || '当前会话'}`; } function escapeMdCell(value) { return String(value ?? '—') .replace(/\r?\n/g, ' ') .replace(/\|/g, '\\|') .trim(); } /** * 将当前步骤列表导出为带 UTF-8 BOM 的 RFC-4180 安全 CSV 字符串(向后兼容保留)。 * * @param {Array} steps * @param {{ displaySettings?: object, includeBom?: boolean }} [opts] * @returns {string} */ function buildStepsCsv(steps, { displaySettings = {}, includeBom = true } = {}) { const list = Array.isArray(steps) ? steps : []; const header = csvRow([ 'step', 'timestamp', 'agent', 'model', 'raw_model_id', 'tok_per_sec', 'ttft_sec', 'duration_sec', 'input_tokens', 'cache_read_tokens', 'output_tokens', 'thinking_tokens', 'response_tokens', 'context_tokens', 'cache_hit_pct', 'cost_usd', 'compaction', 'anomaly_count', 'anomalies', 'prompt', ]); const rows = [header]; for (let i = 0; i < list.length; i += 1) { const st = list[i]; if (!st) continue; const mInfo = resolveModelDisplayInfo(st, displaySettings); const inTok = Number(st.inputTokens || 0); const cacheTok = Number(st.cacheReadTokens || 0); const outTok = Number(st.outputTokens || 0); const thinkTok = Number(st.thinkingTokens || 0); const replyTok = st.responseTokens != null ? Number(st.responseTokens) : Math.max(0, outTok - thinkTok); const promptTok = inTok + cacheTok; const cachePct = st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct)) ? formatPctNumber(st.cacheHitPct) : promptTok > 0 ? formatPctNumber((cacheTok / promptTok) * 100) : '0'; const ctxTok = Number(st.contextTokens || promptTok + outTok); const anomCount = Number(st.anomaly?.count || 0); const anomDesc = anomCount > 0 ? Object.entries(st.anomaly?.kinds || {}) .map(([k, v]) => `${k}:${v}`) .join(';') || String(st.anomaly?.primaryKind || 'error') : ''; rows.push( csvRow([ st.stepIndex ?? '', st.createdAtMs ? new Date(st.createdAtMs).toISOString() : '', st.agentLabel || st.agentBadge || (st.isSubagent ? st.agentId || 'subagent' : 'main'), mInfo.text, st.rawModelId || st.modelKey || '', st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) ? Number(st.tokPerSec).toFixed(2) : '', st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) ? Number(st.ttftSec).toFixed(3) : '', (st.totalDurationSec ?? st.durationSec) != null && Number.isFinite(Number(st.totalDurationSec ?? st.durationSec)) ? Number(st.totalDurationSec ?? st.durationSec).toFixed(3) : '', inTok, cacheTok, outTok, thinkTok, replyTok, ctxTok, cachePct, st.costUsd != null && Number.isFinite(Number(st.costUsd)) ? Number(st.costUsd).toFixed(6) : '', st.isCompactionStep ? 'true' : 'false', anomCount, anomDesc, String(st.turnPrompt || st.rootTurnPrompt || '').replace(/\r?\n/g, ' ').trim(), ]) ); } return `${includeBom ? '\uFEFF' : ''}${rows.join('\r\n')}\r\n`; } /** * 将当前步骤列表导出为精排版、多工作表、双语本地化原生 Excel (`.xlsx`) 二进制工作簿。 * 包含「步骤明细 / Steps」(带异常红底标亮、压缩蓝底提示、自动列宽及数字格式)和「模型汇总 / Model Summary」。 * * @param {Array} steps * @param {{ title?: string, cascadeId?: string, displaySettings?: object, locale?: string }} [opts] * @returns {Uint8Array} */ function buildStepsXlsx( steps, { displaySettings = {}, locale } = {} ) { const en = resolveExportEnglish(locale); const explicitLocale = typeof locale === 'string' && locale.trim().length > 0; const list = Array.isArray(steps) ? steps.filter(Boolean) : []; const agg = summarizeStepsForExport(list, displaySettings); const stepRows = []; for (let i = 0; i < list.length; i += 1) { const st = list[i]; const mInfo = resolveModelDisplayInfo(st, displaySettings); const inTok = Math.max(0, Number(st.inputTokens || 0)); const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); const outTok = Math.max(0, Number(st.outputTokens || 0)); const thinkTok = Math.max(0, Number(st.thinkingTokens || 0)); const replyTok = st.responseTokens != null ? Math.max(0, Number(st.responseTokens)) : Math.max(0, outTok - thinkTok); const ctxTok = Math.max(0, Number(st.contextTokens || inTok + cacheTok + outTok)); const cacheRatio = computeCacheHitRatio(inTok, cacheTok, st.cacheHitPct); const anomCount = Number(st.anomaly?.count || 0); const anomText = formatStepAnomaliesText(st, en, explicitLocale); const promptText = String(st.turnPrompt || st.rootTurnPrompt || '') .replace(/\r?\n/g, ' ') .trim(); const stepNum = Number.isFinite(Number(st.stepIndex)) ? Number(st.stepIndex) : i + 1; const tpsVal = !st.isCompactionStep && st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) ? Number(st.tokPerSec) : null; const ttftVal = !st.isCompactionStep && st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) ? Number(st.ttftSec) : null; const rawDurVal = st.totalDurationSec ?? st.durationSec; const durVal = rawDurVal != null && Number.isFinite(Number(rawDurVal)) ? Number(rawDurVal) : null; const costVal = st.costUsd != null && Number.isFinite(Number(st.costUsd)) ? Number(st.costUsd) : null; const typeLabel = st.isCompactionStep ? en ? 'Compaction' : '自动压缩' : st.isImageGenStep ? en ? 'Image Gen' : '生成图片' : en ? 'Normal' : '常规'; const tone = anomCount > 0 ? 'danger' : st.isCompactionStep ? 'info' : ''; stepRows.push({ tone, values: [ stepNum, formatExportDateTime(st.createdAtMs, true), formatStepAgentLabel(st, en), mInfo.text || '—', typeLabel, tpsVal, ttftVal, durVal, inTok, cacheTok, thinkTok, replyTok, outTok, ctxTok, cacheRatio, costVal, anomText, promptText, ], }); } if (list.length > 0) { const overallCacheRatio = computeCacheHitRatio(agg.sumIn, agg.sumCache); stepRows.push({ tone: 'summary', values: [ '', '', '', en ? `Total (${list.length} steps)` : `合计(共 ${list.length} 步)`, agg.compactionCount > 0 ? en ? `${agg.compactionCount} compact` : `含 ${agg.compactionCount} 次压缩` : '', agg.tpsSecSum > 0 ? +(agg.tpsTokSum / agg.tpsSecSum).toFixed(1) : null, agg.ttftCnt > 0 ? +(agg.ttftSum / agg.ttftCnt).toFixed(2) : null, agg.sumDuration > 0 ? +agg.sumDuration.toFixed(2) : null, agg.sumIn, agg.sumCache, agg.sumThink, agg.sumReply, agg.sumOut, agg.maxContext, overallCacheRatio, agg.sumCost, agg.anomTotal > 0 ? en ? `${agg.anomTotal} events (${agg.anomSteps} steps)` : `共 ${agg.anomTotal} 次(${agg.anomSteps} 步)` : '', '', ], }); } const sheets = [ { name: en ? 'Steps' : '步骤明细', columns: [ { header: en ? 'Step' : '步骤', type: 'int', minWidth: 9 }, { header: en ? 'Time' : '时间', type: 'center', minWidth: 21 }, { header: en ? 'Agent' : '执行体', type: 'center', minWidth: 11 }, { header: en ? 'Model' : '模型', type: 'text', minWidth: 18, maxWidth: 38 }, { header: en ? 'Type' : '类型', type: 'center', minWidth: 11 }, { header: en ? 'Speed (tok/s)' : '速率 (tok/s)', type: 'dec1', minWidth: 14 }, { header: en ? 'TTFT (s)' : '首字延迟 (s)', type: 'dec2', minWidth: 13 }, { header: en ? 'Duration (s)' : '总耗时 (s)', type: 'dec2', minWidth: 13 }, { header: en ? 'Fresh Input' : '新输入', type: 'int', minWidth: 13 }, { header: en ? 'Cache Read' : '缓存读取', type: 'int', minWidth: 14 }, { header: en ? 'Thinking' : '思考', type: 'int', minWidth: 11 }, { header: en ? 'Reply' : '回复', type: 'int', minWidth: 11 }, { header: en ? 'Output' : '总输出', type: 'int', minWidth: 12 }, { header: en ? 'Context' : '上下文', type: 'int', minWidth: 14 }, { header: en ? 'Cache Hit %' : '缓存命中率', type: 'pct', minWidth: 13 }, { header: en ? 'Cost (USD)' : '费用 (USD)', type: 'usd4', minWidth: 14 }, { header: en ? 'Anomalies' : '异常诊断', type: 'text', minWidth: 14, maxWidth: 38 }, { header: en ? 'Turn Prompt' : '用户指令', type: 'text', minWidth: 24, maxWidth: 52 }, ], rows: stepRows, }, ]; if (agg.sortedModels.length > 0) { const modelRows = agg.sortedModels.map((m) => { const mTotal = m.inTok + m.cacheTok + m.outTok; return [ m.label, m.calls, m.inTok, m.cacheTok, m.outTok, mTotal, computeCacheHitRatio(m.inTok, m.cacheTok), m.tpsSecSum > 0 ? +(m.tpsTokSum / m.tpsSecSum).toFixed(1) : null, m.ttftCnt > 0 ? +(m.ttftSum / m.ttftCnt).toFixed(2) : null, m.cost, ]; }); modelRows.push({ tone: 'summary', values: [ en ? 'Total' : '合计', list.length, agg.sumIn, agg.sumCache, agg.sumOut, agg.sumIn + agg.sumCache + agg.sumOut, computeCacheHitRatio(agg.sumIn, agg.sumCache), agg.tpsSecSum > 0 ? +(agg.tpsTokSum / agg.tpsSecSum).toFixed(1) : null, agg.ttftCnt > 0 ? +(agg.ttftSum / agg.ttftCnt).toFixed(2) : null, agg.sumCost, ], }); sheets.push({ name: en ? 'Model Summary' : '模型汇总', columns: [ { header: en ? 'Model' : '模型', type: 'text', minWidth: 20, maxWidth: 42 }, { header: en ? 'Steps' : '步数', type: 'int', minWidth: 10 }, { header: en ? 'Fresh Input' : '新输入', type: 'int', minWidth: 14 }, { header: en ? 'Cache Read' : '缓存读取', type: 'int', minWidth: 15 }, { header: en ? 'Output' : '总输出', type: 'int', minWidth: 13 }, { header: en ? 'Total Tokens' : '总 Token', type: 'int', minWidth: 15 }, { header: en ? 'Cache Hit %' : '缓存命中率', type: 'pct', minWidth: 13 }, { header: en ? 'Avg Speed (tok/s)' : '平均速率 (tok/s)', type: 'dec1', minWidth: 16 }, { header: en ? 'Avg TTFT (s)' : '平均首字 (s)', type: 'dec2', minWidth: 14 }, { header: en ? 'Est. Cost (USD)' : '预估费用 (USD)', type: 'usd4', minWidth: 16 }, ], rows: modelRows, }); } return buildXlsxWorkbookBytes(sheets); } /** * 生成当前会话(或筛选后步骤子集)的可分享双语 Markdown 诊断报告。 * * @param {Array} steps * @param {{ title?: string, cascadeId?: string, displaySettings?: object, filterNote?: string, locale?: string }} [opts] * @returns {string} */ function buildStepsMarkdownReport( steps, { title = '', cascadeId = '', displaySettings = {}, filterNote = '', locale } = {} ) { const en = resolveExportEnglish(locale); const explicitLocale = typeof locale === 'string' && locale.trim().length > 0; const list = Array.isArray(steps) ? steps.filter(Boolean) : []; const agg = summarizeStepsForExport(list, displaySettings); const totalTok = agg.sumIn + agg.sumCache + agg.sumOut; const cacheHitPct = formatPctNumber(computeCacheHitRatio(agg.sumIn, agg.sumCache) * 100); const avgTps = agg.tpsSecSum > 0 ? formatSpeedMetric(agg.tpsTokSum / agg.tpsSecSum, ' tok/s') : '—'; const avgTtft = agg.ttftCnt > 0 ? formatMetric(agg.ttftSum / agg.ttftCnt, 's') : '—'; const heading = title ? `# ${title}` : en ? '# Session Telemetry Report' : '# 会话遥测诊断报告'; const lines = en ? [ heading, '', ...(cascadeId ? [`- **Session ID**: \`${cascadeId}\``] : []), ...(filterNote ? [`- **Scope**: ${filterNote}`] : []), `- **Steps**: ${list.length}${agg.compactionCount > 0 ? ` (${agg.compactionCount} compaction)` : ''}${agg.anomTotal > 0 ? ` · **Anomalies**: ${agg.anomTotal} across ${agg.anomSteps} steps` : ''}`, `- **Total Tokens**: ${formatTokensPrecise(totalTok)} (Input ${formatTokensPrecise(agg.sumIn)} / Cache ${formatTokensPrecise(agg.sumCache)} · ${cacheHitPct}% / Output ${formatTokensPrecise(agg.sumOut)})`, `- **Est. Cost**: ${formatUsd(agg.sumCost, { precise: agg.sumCost > 0 && agg.sumCost < 0.1 })} · **Avg Speed**: ${avgTps} · **Avg TTFT**: ${avgTtft}`, ] : [ heading, '', ...(cascadeId ? [`- **会话 ID**: \`${cascadeId}\``] : []), ...(filterNote ? [`- **筛选范围**: ${filterNote}`] : []), `- **调用步数**: ${list.length}${agg.compactionCount > 0 ? `(含 ${agg.compactionCount} 次自动压缩)` : ''}${agg.anomTotal > 0 ? ` · **异常事件**: ${agg.anomTotal} 次(涉及 ${agg.anomSteps} 步)` : ''}`, `- **总 Token**: ${formatTokensPrecise(totalTok)}(新输入 ${formatTokensPrecise(agg.sumIn)} / 缓存读取 ${formatTokensPrecise(agg.sumCache)} · ${cacheHitPct}% / 输出 ${formatTokensPrecise(agg.sumOut)})`, `- **预估费用**: ${formatUsd(agg.sumCost, { precise: agg.sumCost > 0 && agg.sumCost < 0.1 })} · **平均速率**: ${avgTps} · **平均首字**: ${avgTtft}`, ]; if (agg.sortedModels.length > 0) { lines.push( '', en ? '## Model Breakdown' : '## 模型分布', '', en ? '| Model | Calls | Total Tokens | Cache Hit | Avg Speed | Est. Cost |' : '| 模型 | 调用次数 | 总 Token | 缓存命中率 | 平均速率 | 预估费用 |', '| --- | ---: | ---: | ---: | ---: | ---: |' ); for (const m of agg.sortedModels) { const mTotal = m.inTok + m.cacheTok + m.outTok; const mCache = formatPctNumber(computeCacheHitRatio(m.inTok, m.cacheTok) * 100, { withSymbol: true, }); const mTps = m.tpsSecSum > 0 ? formatSpeedMetric(m.tpsTokSum / m.tpsSecSum, ' tok/s') : '—'; lines.push( `| ${escapeMdCell(m.label)} | ${m.calls} | ${formatTokensPrecise(mTotal)} | ${mCache} | ${mTps} | ${formatUsd(m.cost, { precise: m.cost > 0 && m.cost < 0.1 })} |` ); } } const topCostly = list .filter((st) => Number(st?.costUsd || 0) > 0) .slice() .sort((a, b) => Number(b.costUsd || 0) - Number(a.costUsd || 0)) .slice(0, 5); if (topCostly.length > 0) { lines.push( '', en ? '## Top Costliest Steps' : '## 高成本步骤 Top 5', '', en ? '| Step | Time | Model | Speed | TTFT | Context | Cost |' : '| 步骤 | 时间 | 模型 | 速率 | 首字延迟 | 上下文 | 费用 |', '| ---: | --- | --- | ---: | ---: | ---: | ---: |' ); for (const st of topCostly) { const mInfo = resolveModelDisplayInfo(st, displaySettings); const timeStr = st.createdAtMs ? formatCompactDateTime(st.createdAtMs) : '—'; const ctxTok = Number( st.contextTokens || Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0) + Number(st.outputTokens || 0) ); lines.push( `| #${st.stepIndex ?? '—'} | ${timeStr} | ${escapeMdCell(mInfo.text)} | ${formatSpeedMetric(st.tokPerSec, ' tok/s')} | ${formatMetric(st.ttftSec, 's')} | ${formatTokensPrecise(ctxTok)} | ${formatUsd(st.costUsd, { precise: true })} |` ); } } if (agg.anomTotal > 0) { const anomKindTotals = new Map(); for (const st of list) { if (!st?.anomaly?.kinds) continue; for (const [k, v] of Object.entries(st.anomaly.kinds)) { const n = Number(v || 0); if (n > 0) anomKindTotals.set(k, (anomKindTotals.get(k) || 0) + n); } } if (anomKindTotals.size > 0) { const summary = Array.from(anomKindTotals.entries()) .sort((a, b) => b[1] - a[1]) .map(([k, v]) => `${formatLocalizedAnomalyKind(k, en, explicitLocale)} ×${v}`) .join(en ? ', ' : '、'); lines.push('', en ? `**Anomaly Summary**: ${summary}` : `**异常汇总**: ${summary}`); } } return `${lines.join('\n')}\n`; } /** * 将历史用量统计视图当前区间数据导出为结构化 CSV(向后兼容保留)。 * * @param {object} consumption * @param {Array} modelBreakdown * @param {{ displaySettings?: object, includeBom?: boolean }} [opts] * @returns {string} */ function buildConsumptionCsv( consumption, modelBreakdown = [], { displaySettings = {}, includeBom = true, locale } = {} ) { const en = resolveExportEnglish(locale); const effectiveLocale = en ? 'en-US' : 'zh-CN'; const cons = consumption || {}; const acc = cons.account || {}; const range = cons.selectedRange || {}; const models = mergeModelsByDisplayName(modelBreakdown || [], displaySettings, { preferLabelInShort: true, }); const workspaces = Array.isArray(cons.topWorkspaces) ? cons.topWorkspaces : []; const sessions = Array.isArray(cons.topConversations) ? cons.topConversations : []; const trend = Array.isArray(cons.trendSeries) ? cons.trendSeries : []; const rows = [ csvRow([ 'section', 'name', 'calls', 'input_tokens', 'cache_read_tokens', 'output_tokens', 'total_tokens', 'cache_hit_pct', 'cost_usd', 'extra', ]), csvRow([ 'summary', resolveLocalizedRangeLabel(range, en), Number(acc.calls || 0), Number(acc.inputTokens || 0), Number(acc.cacheReadTokens || 0), Number(acc.outputTokens || 0), Number(acc.totalTokens || 0), formatPctNumber(acc.cacheHitPct || 0), Number(acc.costUsd || 0).toFixed(4), `saved_usd=${Number(acc.savedCostUsd || 0).toFixed(4)}`, ]), ]; for (const m of models) { rows.push( csvRow([ 'model', m.displayText || m.label || m.shortName || '—', Number(m.calls || 0), Number(m.inputTokens || 0), Number(m.cacheReadTokens || 0), Number(m.outputTokens || 0), Number(m.totalTokens || 0), formatPctNumber(m.cacheHitPct || 0), Number(m.costUsd || 0).toFixed(4), m.avgTokPerSec != null ? `avg_tps=${Number(m.avgTokPerSec).toFixed(1)}` : '', ]) ); } for (const w of workspaces) { rows.push( csvRow([ 'project', w.label || w.workspacePath || 'unbound', Number(w.calls || 0), Number(w.inputTokens || 0), Number(w.cacheReadTokens || 0), Number(w.responseTokens || 0) + Number(w.thinkingTokens || 0), Number(w.totalTokens || 0), formatPctNumber(w.cacheHitPct || 0), Number(w.costUsd || 0).toFixed(4), `sessions=${Number(w.sessionCount || 0)}`, ]) ); } for (const c of sessions) { rows.push( csvRow([ 'session', c.title || c.cascadeId || '—', Number(c.calls || 0), Number(c.inputTokens || 0), Number(c.cacheReadTokens || 0), Number(c.responseTokens || 0) + Number(c.thinkingTokens || 0), Number(c.totalTokens || 0), formatPctNumber(c.cacheHitPct || 0), Number(c.costUsd || 0).toFixed(4), c.sourceName || c.appSource || '', ]) ); } for (const slot of trend) { if (!slot || !(Number(slot.tokens || 0) > 0 || Number(slot.calls || 0) > 0)) continue; rows.push( csvRow([ 'trend', formatTrendSlotFullLabel(slot, { locale: effectiveLocale }) || slot.label || '', Number(slot.calls || 0), Number(slot.inputTokens || 0), Number(slot.cacheReadTokens || 0), Number(slot.outputTokens || 0), Number(slot.tokens || 0), '', Number(slot.costUsd || 0).toFixed(4), slot.granularity || '', ]) ); } return `${includeBom ? '\uFEFF' : ''}${rows.join('\r\n')}\r\n`; } /** * 将历史用量统计视图当前区间数据导出为多工作表、全自动列宽及双语本地化原生 Excel (`.xlsx`) 工作簿。 * 自动拆分为「用量总览 / 模型排行 / 项目排行 / 会话排行 / 时间趋势 / 客户端来源」独立分页。 * * @param {object} consumption * @param {Array} modelBreakdown * @param {{ displaySettings?: object, locale?: string, nowMs?: number }} [opts] * @returns {Uint8Array} */ function buildConsumptionXlsx( consumption, modelBreakdown = [], { displaySettings = {}, locale, nowMs = Date.now() } = {} ) { const en = resolveExportEnglish(locale); const cons = consumption || {}; const acc = cons.account || {}; const range = cons.selectedRange || {}; const models = mergeModelsByDisplayName(modelBreakdown || [], displaySettings, { preferLabelInShort: true, }); const workspaces = Array.isArray(cons.topWorkspaces) ? cons.topWorkspaces : []; const sessions = Array.isArray(cons.topConversations) ? cons.topConversations : []; const sources = Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : []; const trend = (Array.isArray(cons.trendSeries) ? cons.trendSeries : []).filter( (slot) => slot && (Number(slot.tokens || 0) > 0 || Number(slot.calls || 0) > 0) ); const rangeLabel = resolveLocalizedRangeLabel(range, en); const spanNote = resolveRangeSpanNote(range); const accIn = Math.max(0, Number(acc.inputTokens || 0)); const accCache = Math.max(0, Number(acc.cacheReadTokens || 0)); const accOut = Math.max(0, Number(acc.outputTokens || 0)); const accThink = Math.max(0, Number(acc.thinkingTokens || 0)); const accReply = acc.responseTokens != null ? Math.max(0, Number(acc.responseTokens)) : Math.max(0, accOut - accThink); const accTotal = Math.max(0, Number(acc.totalTokens ?? accIn + accCache + accOut)); const accCalls = Math.max(0, Number(acc.calls || 0)); const accCacheRatio = computeCacheHitRatio(accIn, accCache, acc.cacheHitPct); const accCost = Math.max(0, Number(acc.costUsd || 0)); const accSaved = Math.max(0, Number(acc.savedCostUsd || 0)); const overviewRows = [ [en ? 'Time Range' : '统计周期', { value: rangeLabel, type: 'text_right' }, spanNote], [en ? 'Exported At' : '导出时间', { value: formatExportDateTime(nowMs, true), type: 'text_right' }, ''], [ en ? 'Total Calls' : '调用次数', { value: accCalls, type: 'int' }, en ? 'Completed model requests' : '有效模型请求步数', ], [ en ? 'Total Tokens' : '总 Token', { value: accTotal, type: 'int' }, en ? 'Fresh input + Cache read + Output' : '新输入 + 缓存读取 + 总输出', ], [ en ? 'Fresh Input Tokens' : '新输入 Token', { value: accIn, type: 'int' }, en ? 'Uncached prompt tokens' : '未命中缓存的新增提示词', ], [ en ? 'Cache Read Tokens' : '缓存读取 Token', { value: accCache, type: 'int' }, en ? 'Prompt cache hit tokens' : '命中 Prompt Cache 的复用输入', ], [ en ? 'Total Output Tokens' : '总输出 Token', { value: accOut, type: 'int' }, accThink > 0 ? en ? `Thinking ${accThink.toLocaleString('en-US')} / Reply ${accReply.toLocaleString('en-US')}` : `思考 ${accThink.toLocaleString('en-US')} / 回复 ${accReply.toLocaleString('en-US')}` : en ? 'Generated completion tokens' : '模型生成输出总量', ], ]; if (accThink > 0 || accReply > 0) { overviewRows.push( [ en ? 'Thinking Tokens' : '思考 Token', { value: accThink, type: 'int' }, en ? 'Reasoning output tokens' : '内部推理过程消耗', ], [ en ? 'Reply Tokens' : '回复 Token', { value: accReply, type: 'int' }, en ? 'Visible response tokens' : '正文可见回复消耗', ] ); } overviewRows.push( [ en ? 'Cache Hit Rate' : '缓存命中率', { value: accCacheRatio, type: 'pct' }, en ? 'Cache read / (Fresh input + Cache read)' : '缓存读取 / (新输入 + 缓存读取)', ], [ en ? 'Cache Saved (USD)' : '缓存节省 (USD)', { value: accSaved, type: 'usd2' }, en ? 'Estimated savings from prompt caching' : '相比全量未缓存输入估算节省的费用', ], { tone: 'summary', values: [ en ? 'Est. Cost (USD)' : '预估费用 (USD)', { value: accCost, type: 'usd2' }, en ? 'Estimated from official model list pricing' : '按模型官方阶梯定价汇总估算', ], } ); const sheets = [ { name: en ? 'Overview' : '用量总览', autoFilter: false, columns: [ { header: en ? 'Metric' : '指标项', type: 'text', minWidth: 20 }, { header: en ? 'Value' : '数值', type: 'text_right', align: 'right', minWidth: 22 }, { header: en ? 'Notes' : '说明', type: 'text', minWidth: 32, maxWidth: 56 }, ], rows: overviewRows, }, ]; // Sheet 2: Models if (models.length > 0) { let mCalls = 0; let mIn = 0; let mCache = 0; let mOut = 0; let mTot = 0; let mCost = 0; let tpsTokSum = 0; let tpsSecSum = 0; const modelRows = models.map((m, idx) => { const calls = Math.max(0, Number(m.calls || 0)); const inTok = Math.max(0, Number(m.inputTokens || 0)); const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0)); const outTok = Math.max(0, Number(m.outputTokens || 0)); const totTok = Math.max(0, Number(m.totalTokens ?? inTok + cacheTok + outTok)); const cost = Math.max(0, Number(m.costUsd || 0)); const tps = m.avgTokPerSec != null && Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0 ? Number(m.avgTokPerSec) : null; mCalls += calls; mIn += inTok; mCache += cacheTok; mOut += outTok; mTot += totTok; mCost += cost; const rawSpeedTok = Number(m.speedSummary?.tokens); const rawSpeedSec = Number(m.speedSummary?.seconds); if ( Number.isFinite(rawSpeedTok) && Number.isFinite(rawSpeedSec) && rawSpeedSec > 0 && rawSpeedTok >= 0 ) { tpsTokSum += rawSpeedTok; tpsSecSum += rawSpeedSec; } else if (tps != null) { const fallbackTok = outTok > 0 ? outTok : Math.max(1, calls); tpsTokSum += fallbackTok; tpsSecSum += fallbackTok / tps; } return [ idx + 1, m.displayText || m.label || m.shortName || '—', calls, inTok, cacheTok, outTok, totTok, computeCacheHitRatio(inTok, cacheTok, m.cacheHitPct), tps, cost, ]; }); modelRows.push({ tone: 'summary', values: [ '', en ? 'Total' : '合计', mCalls, mIn, mCache, mOut, mTot, computeCacheHitRatio(mIn, mCache), tpsSecSum > 0 ? +(tpsTokSum / tpsSecSum).toFixed(1) : null, mCost, ], }); sheets.push({ name: en ? 'Models' : '模型排行', columns: [ { header: en ? 'Rank' : '排名', type: 'center', minWidth: 8 }, { header: en ? 'Model' : '模型', type: 'text', minWidth: 20, maxWidth: 42 }, { header: en ? 'Calls' : '调用次数', type: 'int', minWidth: 11 }, { header: en ? 'Fresh Input' : '新输入', type: 'int', minWidth: 14 }, { header: en ? 'Cache Read' : '缓存读取', type: 'int', minWidth: 15 }, { header: en ? 'Output' : '输出', type: 'int', minWidth: 13 }, { header: en ? 'Total Tokens' : '总 Token', type: 'int', minWidth: 15 }, { header: en ? 'Cache Hit %' : '缓存命中率', type: 'pct', minWidth: 13 }, { header: en ? 'Avg Speed (tok/s)' : '平均速率 (tok/s)', type: 'dec1', minWidth: 17 }, { header: en ? 'Est. Cost (USD)' : '预估费用 (USD)', type: 'usd2', minWidth: 16 }, ], rows: modelRows, }); } // Sheet 3: Projects if (workspaces.length > 0) { let wSess = 0; let wCalls = 0; let wIn = 0; let wCache = 0; let wOut = 0; let wTot = 0; let wCost = 0; const wsRows = workspaces.map((w, idx) => { const sess = Math.max(0, Number(w.sessionCount || 0)); const calls = Math.max(0, Number(w.calls || 0)); const inTok = Math.max(0, Number(w.inputTokens || 0)); const cacheTok = Math.max(0, Number(w.cacheReadTokens || 0)); const outTok = w.outputTokens != null ? Math.max(0, Number(w.outputTokens)) : Math.max(0, Number(w.responseTokens || 0)) + Math.max(0, Number(w.thinkingTokens || 0)); const totTok = Math.max(0, Number(w.totalTokens ?? inTok + cacheTok + outTok)); const cost = Math.max(0, Number(w.costUsd || 0)); wSess += sess; wCalls += calls; wIn += inTok; wCache += cacheTok; wOut += outTok; wTot += totTok; wCost += cost; return [ idx + 1, w.label || w.workspacePath || (en ? 'Unbound' : '未绑定工作区'), w.workspacePath || '', sess, calls, inTok, cacheTok, outTok, totTok, computeCacheHitRatio(inTok, cacheTok, w.cacheHitPct), cost, ]; }); wsRows.push({ tone: 'summary', values: [ '', en ? 'Total' : '合计', '', wSess, wCalls, wIn, wCache, wOut, wTot, computeCacheHitRatio(wIn, wCache), wCost, ], }); sheets.push({ name: en ? 'Projects' : '项目排行', columns: [ { header: en ? 'Rank' : '排名', type: 'center', minWidth: 8 }, { header: en ? 'Project' : '项目名称', type: 'text', minWidth: 18, maxWidth: 36 }, { header: en ? 'Workspace Path' : '工作区路径', type: 'text', minWidth: 22, maxWidth: 52 }, { header: en ? 'Sessions' : '会话数', type: 'int', minWidth: 10 }, { header: en ? 'Calls' : '调用次数', type: 'int', minWidth: 11 }, { header: en ? 'Fresh Input' : '新输入', type: 'int', minWidth: 14 }, { header: en ? 'Cache Read' : '缓存读取', type: 'int', minWidth: 15 }, { header: en ? 'Output' : '输出', type: 'int', minWidth: 13 }, { header: en ? 'Total Tokens' : '总 Token', type: 'int', minWidth: 15 }, { header: en ? 'Cache Hit %' : '缓存命中率', type: 'pct', minWidth: 13 }, { header: en ? 'Est. Cost (USD)' : '预估费用 (USD)', type: 'usd2', minWidth: 16 }, ], rows: wsRows, }); } // Sheet 4: Sessions if (sessions.length > 0) { let sCalls = 0; let sIn = 0; let sCache = 0; let sOut = 0; let sTot = 0; let sCost = 0; const sessRows = sessions.map((c, idx) => { const calls = Math.max(0, Number(c.calls || 0)); const inTok = Math.max(0, Number(c.inputTokens || 0)); const cacheTok = Math.max(0, Number(c.cacheReadTokens || 0)); const outTok = c.outputTokens != null ? Math.max(0, Number(c.outputTokens)) : Math.max(0, Number(c.responseTokens || 0)) + Math.max(0, Number(c.thinkingTokens || 0)); const totTok = Math.max(0, Number(c.totalTokens ?? inTok + cacheTok + outTok)); const cost = Math.max(0, Number(c.costUsd || 0)); sCalls += calls; sIn += inTok; sCache += cacheTok; sOut += outTok; sTot += totTok; sCost += cost; return [ idx + 1, c.title || c.cascadeId || '—', c.sourceName || c.appSource || '', calls, inTok, cacheTok, outTok, totTok, computeCacheHitRatio(inTok, cacheTok, c.cacheHitPct), cost, ]; }); sessRows.push({ tone: 'summary', values: [ '', en ? 'Total' : '合计', '', sCalls, sIn, sCache, sOut, sTot, computeCacheHitRatio(sIn, sCache), sCost, ], }); sheets.push({ name: en ? 'Sessions' : '会话排行', columns: [ { header: en ? 'Rank' : '排名', type: 'center', minWidth: 8 }, { header: en ? 'Session Title' : '会话标题', type: 'text', minWidth: 24, maxWidth: 48 }, { header: en ? 'Client Source' : '客户端来源', type: 'text', minWidth: 16 }, { header: en ? 'Calls' : '调用次数', type: 'int', minWidth: 11 }, { header: en ? 'Fresh Input' : '新输入', type: 'int', minWidth: 14 }, { header: en ? 'Cache Read' : '缓存读取', type: 'int', minWidth: 15 }, { header: en ? 'Output' : '输出', type: 'int', minWidth: 13 }, { header: en ? 'Total Tokens' : '总 Token', type: 'int', minWidth: 15 }, { header: en ? 'Cache Hit %' : '缓存命中率', type: 'pct', minWidth: 13 }, { header: en ? 'Est. Cost (USD)' : '预估费用 (USD)', type: 'usd2', minWidth: 16 }, ], rows: sessRows, }); } // Sheet 5: Trend if (trend.length > 0) { let tCalls = 0; let tIn = 0; let tCache = 0; let tOut = 0; let tTot = 0; let tCost = 0; const trendRows = trend.map((slot) => { const isMinute = slot.granularity === 'minute'; const isHourly = isMinute || slot.granularity === 'hour' || String(slot.label || '').includes(':'); const calls = Math.max(0, Number(slot.calls || 0)); const inTok = Math.max(0, Number(slot.inputTokens || 0)); const cacheTok = Math.max(0, Number(slot.cacheReadTokens || 0)); const outTok = Math.max(0, Number(slot.outputTokens || 0)); const totTok = Math.max(0, Number(slot.tokens ?? inTok + cacheTok + outTok)); const cost = Math.max(0, Number(slot.costUsd || 0)); tCalls += calls; tIn += inTok; tCache += cacheTok; tOut += outTok; tTot += totTok; tCost += cost; const stepMins = Math.max(1, Number(slot.stepMinutes) || 5); const granLabel = isMinute ? en ? `${stepMins}m` : `按 ${stepMins} 分钟` : isHourly ? en ? 'Hourly' : '按小时' : en ? 'Daily' : '按天'; return [ formatTrendWindowLabel(slot, isHourly), granLabel, calls, inTok, cacheTok, outTok, totTok, cost, ]; }); trendRows.push({ tone: 'summary', values: [ en ? 'Total' : '合计', '', tCalls, tIn, tCache, tOut, tTot, tCost, ], }); sheets.push({ name: en ? 'Trend' : '时间趋势', columns: [ { header: en ? 'Time Window' : '时间段', type: 'text', minWidth: 19 }, { header: en ? 'Granularity' : '粒度', type: 'center', minWidth: 11 }, { header: en ? 'Calls' : '调用次数', type: 'int', minWidth: 11 }, { header: en ? 'Fresh Input' : '新输入', type: 'int', minWidth: 14 }, { header: en ? 'Cache Read' : '缓存读取', type: 'int', minWidth: 15 }, { header: en ? 'Output' : '输出', type: 'int', minWidth: 13 }, { header: en ? 'Total Tokens' : '总 Token', type: 'int', minWidth: 15 }, { header: en ? 'Est. Cost (USD)' : '预估费用 (USD)', type: 'usd2', minWidth: 16 }, ], rows: trendRows, }); } // Sheet 6: Client Sources if (sources.length > 0) { let srcCalls = 0; let srcIn = 0; let srcCache = 0; let srcOut = 0; let srcTot = 0; let srcCost = 0; const srcRows = sources.map((s) => { const calls = Math.max(0, Number(s.calls || 0)); const inTok = Math.max(0, Number(s.inputTokens || 0)); const cacheTok = Math.max(0, Number(s.cacheReadTokens || 0)); const outTok = s.outputTokens != null ? Math.max(0, Number(s.outputTokens)) : Math.max(0, Number(s.responseTokens || 0)) + Math.max(0, Number(s.thinkingTokens || 0)); const totTok = Math.max(0, Number(s.totalTokens ?? inTok + cacheTok + outTok)); const cost = Math.max(0, Number(s.costUsd || 0)); srcCalls += calls; srcIn += inTok; srcCache += cacheTok; srcOut += outTok; srcTot += totTok; srcCost += cost; return [ s.name || '—', calls, inTok, cacheTok, outTok, totTok, computeCacheHitRatio(inTok, cacheTok, s.cacheHitPct), cost, ]; }); srcRows.push({ tone: 'summary', values: [ en ? 'Total' : '合计', srcCalls, srcIn, srcCache, srcOut, srcTot, computeCacheHitRatio(srcIn, srcCache), srcCost, ], }); sheets.push({ name: en ? 'Client Sources' : '客户端来源', columns: [ { header: en ? 'Client Source' : '客户端来源', type: 'text', minWidth: 18 }, { header: en ? 'Calls' : '调用次数', type: 'int', minWidth: 11 }, { header: en ? 'Fresh Input' : '新输入', type: 'int', minWidth: 14 }, { header: en ? 'Cache Read' : '缓存读取', type: 'int', minWidth: 15 }, { header: en ? 'Output' : '输出', type: 'int', minWidth: 13 }, { header: en ? 'Total Tokens' : '总 Token', type: 'int', minWidth: 15 }, { header: en ? 'Cache Hit %' : '缓存命中率', type: 'pct', minWidth: 13 }, { header: en ? 'Est. Cost (USD)' : '预估费用 (USD)', type: 'usd2', minWidth: 16 }, ], rows: srcRows, }); } return buildXlsxWorkbookBytes(sheets); } /** * 生成历史用量统计当前区间的双语 Markdown 汇总报告。 * * @param {object} consumption * @param {Array} modelBreakdown * @param {{ displaySettings?: object, locale?: string }} [opts] * @returns {string} */ function buildConsumptionMarkdownReport( consumption, modelBreakdown = [], { displaySettings = {}, locale } = {} ) { const en = resolveExportEnglish(locale); const cons = consumption || {}; const acc = cons.account || {}; const range = cons.selectedRange || {}; const models = mergeModelsByDisplayName(modelBreakdown || [], displaySettings, { preferLabelInShort: true, }); const workspaces = Array.isArray(cons.topWorkspaces) ? cons.topWorkspaces : []; const sessions = Array.isArray(cons.topConversations) ? cons.topConversations : []; const rangeLabel = resolveLocalizedRangeLabel(range, en); const lines = en ? [ `# Usage Report · ${rangeLabel}`, '', `- **Total Tokens**: ${formatTokensPrecise(acc.totalTokens || 0)} (${Number(acc.calls || 0)} calls)`, `- **Est. Cost**: ${formatUsd(acc.costUsd || 0)} (Cache Saved ${formatUsd(acc.savedCostUsd || 0)})`, `- **Cache Hit Rate**: ${formatPctNumber(acc.cacheHitPct || 0, { withSymbol: true })} (Input ${formatTokensPrecise(acc.inputTokens || 0)} / Cache ${formatTokensPrecise(acc.cacheReadTokens || 0)} / Output ${formatTokensPrecise(acc.outputTokens || 0)})`, ] : [ `# 用量统计报告 · ${rangeLabel}`, '', `- **总 Token**: ${formatTokensPrecise(acc.totalTokens || 0)}(共 ${Number(acc.calls || 0)} 次调用)`, `- **预估费用**: ${formatUsd(acc.costUsd || 0)}(缓存节省 ${formatUsd(acc.savedCostUsd || 0)})`, `- **缓存命中率**: ${formatPctNumber(acc.cacheHitPct || 0, { withSymbol: true })}(新输入 ${formatTokensPrecise(acc.inputTokens || 0)} / 缓存读取 ${formatTokensPrecise(acc.cacheReadTokens || 0)} / 输出 ${formatTokensPrecise(acc.outputTokens || 0)})`, ]; if (models.length > 0) { lines.push( '', en ? '## Models' : '## 模型排行', '', en ? '| Model | Calls | Tokens | Cache Hit | Avg Speed | Est. Cost |' : '| 模型 | 调用次数 | 总 Token | 缓存命中率 | 平均速率 | 预估费用 |', '| --- | ---: | ---: | ---: | ---: | ---: |' ); for (const m of models) { lines.push( `| ${escapeMdCell(m.displayText || m.label || m.shortName)} | ${Number(m.calls || 0)} | ${formatTokensPrecise(m.totalTokens || 0)} | ${formatPctNumber(m.cacheHitPct || 0, { withSymbol: true })} | ${m.avgTokPerSec != null ? formatSpeedMetric(m.avgTokPerSec, ' tok/s') : '—'} | ${formatUsd(m.costUsd || 0)} |` ); } } if (workspaces.length > 0) { lines.push( '', en ? '## Projects' : '## 项目排行', '', en ? '| Project | Sessions | Calls | Tokens | Cache Hit | Est. Cost |' : '| 项目 | 会话数 | 调用次数 | 总 Token | 缓存命中率 | 预估费用 |', '| --- | ---: | ---: | ---: | ---: | ---: |' ); for (const w of workspaces) { lines.push( `| ${escapeMdCell(w.label || w.workspacePath || (en ? 'Unbound' : '未绑定工作区'))} | ${Number(w.sessionCount || 0)} | ${Number(w.calls || 0)} | ${formatTokensPrecise(w.totalTokens || 0)} | ${formatPctNumber(w.cacheHitPct || 0, { withSymbol: true })} | ${formatUsd(w.costUsd || 0)} |` ); } } if (sessions.length > 0) { lines.push( '', en ? '## Top Sessions' : '## 热门会话', '', en ? '| Session | Calls | Tokens | Cache Hit | Est. Cost |' : '| 会话 | 调用次数 | 总 Token | 缓存命中率 | 预估费用 |', '| --- | ---: | ---: | ---: | ---: |' ); for (const c of sessions.slice(0, 8)) { lines.push( `| ${escapeMdCell(c.title || c.cascadeId)} | ${Number(c.calls || 0)} | ${formatTokensPrecise(c.totalTokens || 0)} | ${formatPctNumber(c.cacheHitPct || 0, { withSymbol: true })} | ${formatUsd(c.costUsd || 0)} |` ); } } return `${lines.join('\n')}\n`; } return { escapeCsvCell, sanitizeExportFilename, buildConsumptionExportBaseName, buildStepsExportBaseName, buildStepsCsv, buildStepsXlsx, buildStepsMarkdownReport, buildConsumptionCsv, buildConsumptionXlsx, buildConsumptionMarkdownReport }; })(); // --- src/core/httpClient.js --- const { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => { /** * @fileoverview Async HTTP client with AbortController cancellation for stale * polling requests, concurrent GET deduplication, and dual-mode transport * (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge). */ const inFlightGets = new Map(); const activeControllers = new Map(); function abortSidecarApiKey(abortKey) { if (!abortKey) return; const prev = activeControllers.get(abortKey); if (prev) { activeControllers.delete(abortKey); prev.abort(); } } /** * 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。 * * @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null} */ function getWindowBridgeConfig() { const br = readInjectedWindowBridge(); const port = Number(br?.port || 0); if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) { return br; } return null; } /** * 判断当前脚本是否以双栖悬浮模式运行在宿主主聊天窗口内(而非右侧辅助栏 Webview)。 * * @returns {boolean} */ function isWindowOverlayMode() { if (typeof window === 'undefined') return false; if (window.sidecar?.fetch) return false; return Boolean(getWindowBridgeConfig()); } /** * 接收 Sidecar 通过 CDP `Runtime.evaluate` 批量投递的 RPC 响应,完成因 CSP/代理解除 HTTP 直连时的兜底请求。 * * @param {Array<{ id: string, ok: boolean, status?: number, data?: any, error?: string }>} responses * @returns {number} */ function deliverCdpBridgeResponses(responses) { const br = getWindowBridgeConfig(); if (!br || !(br.rpcPending instanceof Map) || !Array.isArray(responses)) return 0; let delivered = 0; for (const item of responses) { const entry = br.rpcPending.get(item?.id); if (!entry) continue; br.rpcPending.delete(item.id); delivered += 1; if (item.ok) { entry.resolve(item.data); } else { entry.reject(new Error(item.error || `HTTP ${item.status || 500}`)); } } return delivered; } function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs }) { return new Promise((resolve, reject) => { if (signal?.aborted) { const abortErr = new Error('Request aborted'); abortErr.name = 'AbortError'; reject(abortErr); return; } if (!Array.isArray(bridge.rpcQueue)) bridge.rpcQueue = []; if (!(bridge.rpcPending instanceof Map)) bridge.rpcPending = new Map(); const reqId = `rpc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; const cleanupQueueItem = () => { if (!Array.isArray(bridge.rpcQueue)) return; const idx = bridge.rpcQueue.findIndex((item) => item?.id === reqId); if (idx >= 0) bridge.rpcQueue.splice(idx, 1); }; const timeoutId = setTimeout(() => { bridge.rpcPending.delete(reqId); cleanupQueueItem(); reject(new Error('CDP bridge timeout')); }, cdpTimeoutMs); const onAbort = () => { clearTimeout(timeoutId); bridge.rpcPending.delete(reqId); cleanupQueueItem(); const abortErr = new Error('Request aborted'); abortErr.name = 'AbortError'; reject(abortErr); }; if (signal) { signal.addEventListener('abort', onAbort, { once: true }); } bridge.rpcPending.set(reqId, { resolve: (data) => { clearTimeout(timeoutId); if (signal) signal.removeEventListener('abort', onAbort); resolve(data); }, reject: (err) => { clearTimeout(timeoutId); if (signal) signal.removeEventListener('abort', onAbort); reject(err); }, }); if (bridge.rpcQueue.length >= 16) { const dropped = bridge.rpcQueue.shift(); if (dropped?.id) { const stale = bridge.rpcPending.get(dropped.id); bridge.rpcPending.delete(dropped.id); stale?.reject(new Error('CDP queue superseded')); } } bridge.rpcQueue.push({ id: reqId, path, method, body }); }); } async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) { const upperMethod = method.toUpperCase(); const activeEndpointId = String(getWindowBridgeConfig()?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() || LOCAL_ENDPOINT_ID; const dedupKey = upperMethod === 'GET' && !abortKey ? `${activeEndpointId}::${path}` : ''; if (dedupKey && inFlightGets.has(dedupKey)) { return inFlightGets.get(dedupKey); } let signal; let requestController = null; if (abortKey && typeof AbortController !== 'undefined') { const prev = activeControllers.get(abortKey); if (prev) { prev.abort(); } requestController = new AbortController(); activeControllers.set(abortKey, requestController); signal = requestController.signal; } const ensureEndpointUnchanged = (targetBridge) => { if (!targetBridge) return; const currentEndpointId = String(targetBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID).trim() || LOCAL_ENDPOINT_ID; if (currentEndpointId !== activeEndpointId) { const switchErr = new Error('Bridge endpoint switched'); switchErr.name = 'AbortError'; throw switchErr; } }; const execHttpOnce = async (activeBridge) => { ensureEndpointUnchanged(activeBridge); const sidecar = typeof window !== 'undefined' ? window.sidecar : null; const fetchFn = sidecar?.fetch ? sidecar.fetch.bind(sidecar) : typeof window !== 'undefined' && typeof window.fetch === 'function' ? window.fetch.bind(window) : globalThis.fetch.bind(globalThis); const requestUrl = activeBridge ? `http://127.0.0.1:${activeBridge.port}${path}` : path; const headers = {}; if (body !== undefined || !activeBridge) { headers['Content-Type'] = 'application/json'; } if (activeBridge) { headers['X-Usage-Monitor-Token'] = activeBridge.token; const epId = String(activeBridge[WINDOW_BRIDGE_ENDPOINT_KEY] || '').trim(); if (epId && epId !== LOCAL_ENDPOINT_ID) { headers[WINDOW_BRIDGE_ENDPOINT_HEADER] = epId; } } const res = await fetchFn(requestUrl, { method: upperMethod, headers, body: body === undefined ? undefined : JSON.stringify(body), signal, }); if (signal?.aborted) { const abortErr = new Error('Request aborted'); abortErr.name = 'AbortError'; throw abortErr; } const data = await res.json().catch(() => ({})); if (signal?.aborted) { const abortErr = new Error('Request aborted'); abortErr.name = 'AbortError'; throw abortErr; } if (!res.ok) { const httpErr = new Error(data.error || `HTTP ${res.status}`); httpErr.httpStatus = res.status; httpErr.retryable = Boolean(data?.retryable); throw httpErr; } if (activeBridge) { activeBridge.transportMode = 'http'; } return data; }; const fallbackViaCdpWithRecovery = async (initialBridge) => { initialBridge.transportMode = 'cdp'; try { return await callViaCdpBridge(initialBridge, path, { method: upperMethod, body, signal, cdpTimeoutMs, }); } catch (cdpErr) { if (signal?.aborted || cdpErr?.name === 'AbortError') { throw cdpErr; } // 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次; // 但若端点已切换(例如本地 <-> SSH),绝不将旧端点请求重放至新端点 const latestBridge = getWindowBridgeConfig() || initialBridge; ensureEndpointUnchanged(latestBridge); latestBridge.transportMode = 'http'; return execHttpOnce(latestBridge); } }; const runRequest = async () => { const sidecar = typeof window !== 'undefined' ? window.sidecar : null; const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null; if (bridge && bridge.transportMode === 'cdp') { return fallbackViaCdpWithRecovery(bridge); } try { return await execHttpOnce(bridge); } catch (fetchErr) { if (signal?.aborted || fetchErr?.name === 'AbortError') { throw fetchErr; } if (!bridge) { // 辅助栏 Webview 在 Worker 热替换瞬间若有极短暂波动,延迟 180ms 自动无感重试一次 if (upperMethod === 'GET') { await new Promise((r) => setTimeout(r, 180)); if (!signal?.aborted) { return execHttpOnce(null); } } throw fetchErr; } // 仅在网络/CORS 阻断(无 HTTP 状态码)或桥接令牌失配(403)时切换至 CDP 兜底; // 业务/初始化状态码(如 503 Remote endpoint initializing、400、500)保持 HTTP 通道等待正常重试。 if (fetchErr?.httpStatus && fetchErr.httpStatus !== 403) { throw fetchErr; } return fallbackViaCdpWithRecovery(bridge); } }; const promise = runRequest().finally(() => { if (dedupKey) { inFlightGets.delete(dedupKey); } if (abortKey && requestController && activeControllers.get(abortKey) === requestController) { activeControllers.delete(abortKey); } }); if (dedupKey) { inFlightGets.set(dedupKey, promise); } return promise; } return { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi }; })(); // --- src/store/uiStore.js --- const { getViewTabs, uiStore, showUiToast, dismissUiToast, getVisibleMonitorView } = (() => { /** * @fileoverview UI navigation and view state store. */ function getViewTabs() { return [ { value: 'overview', label: t('nav.overview'), icon: 'pulse' }, { value: 'consumption', label: t('nav.consumption'), icon: 'chart-bar' }, { value: 'steps', label: t('nav.steps'), icon: 'table' }, { value: 'settings', label: t('nav.settings'), icon: 'sliders' }, ]; } const uiStore = createReactiveStore({ activeView: 'overview', monitorVisible: true, stepsSubTab: 'steps', // 'steps' | 'models' settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other' settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps' selectedAgentScope: 'all', // 'all' | 'main' | ctxInspectorAgentId: 'main', // 'main' | 'auto' | toast: null, // { id, message, detail, actionLabel, onAction, tone, durationMs } }); let toastSeq = 0; /** * 触发全局底部轻量通知条(用于文件导出路径提示、一键定位文件夹及剪贴板复制反馈)。 * * @param {{ message: string, detail?: string, actionLabel?: string, onAction?: (() => void) | null, tone?: 'ok' | 'info' | 'warn', durationMs?: number }} toastConfig * @returns {number} */ function showUiToast(toastConfig) { if (!toastConfig || !toastConfig.message) return 0; toastSeq += 1; uiStore.setState({ toast: { id: toastSeq, message: String(toastConfig.message), detail: toastConfig.detail ? String(toastConfig.detail) : '', actionLabel: toastConfig.actionLabel ? String(toastConfig.actionLabel) : '', onAction: typeof toastConfig.onAction === 'function' ? toastConfig.onAction : null, tone: toastConfig.tone || 'ok', durationMs: Number(toastConfig.durationMs) >= 0 ? Number(toastConfig.durationMs) : 5200, }, }); return toastSeq; } function dismissUiToast(toastId = 0) { const cur = uiStore.getState().toast; if (!cur) return; if (toastId && cur.id !== toastId) return; uiStore.setState({ toast: null }); } function getVisibleMonitorView(state = uiStore.getState()) { return state.monitorVisible ? state.activeView : null; } return { getViewTabs, uiStore, showUiToast, dismissUiToast, getVisibleMonitorView }; })(); // --- src/core/fileExportClient.js --- const { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFeedback, copyTextWithFeedback } = (() => { /** * @fileoverview 统一文本/二进制文件导出及剪贴板复制客户端 (`fileExportClient.js`)。 * 优先调用本机后端 `/api/export-file` 落盘到用户 Downloads(或插件 `.data/exports`)并返回真实绝对路径, * 同时通过全局 Toast 清晰展示保存位置并提供「打开位置」快捷按钮; * 当后端不可达或处于远程浏览器访问时,自动平滑降级到 `showSaveFilePicker` 或浏览器 Blob 下载并给出明确提示。 */ function isHostEmbeddedWebview() { if (typeof window === 'undefined') return false; return Boolean(window.sidecar?.fetch) || isWindowOverlayMode(); } function getPickerTypesForFilename(filename, mimeType) { const lower = String(filename || '').toLowerCase(); if (lower.endsWith('.xlsx') || String(mimeType || '').includes('spreadsheetml')) { return [ { description: 'Excel Workbook', accept: { 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'], }, }, ]; } if (lower.endsWith('.csv') || String(mimeType || '').includes('csv')) { return [{ description: 'CSV', accept: { 'text/csv': ['.csv'] } }]; } if (lower.endsWith('.md') || String(mimeType || '').includes('markdown')) { return [{ description: 'Markdown', accept: { 'text/markdown': ['.md'] } }]; } return [{ description: 'JSON', accept: { 'application/json': ['.json'] } }]; } /** * 调用本机后端在系统文件管理器中打开并高亮选中已导出的文件。 * 兼容热更新后常驻父进程 `main.mjs` 尚未注册新路由的场景,自动回退至 `POST /api/settings` 穿透转发至最新 Worker。 * * @param {string} filePath * @returns {Promise} */ async function revealExportedFile(filePath) { if (!filePath || !isHostEmbeddedWebview()) return false; try { const res = await callSidecarApi('/api/reveal-file', { method: 'POST', body: { filePath }, cdpTimeoutMs: 4000, }); if (res?.ok) return true; } catch (err) { if (err?.httpStatus === 403) return false; } try { const fallbackRes = await callSidecarApi('/api/settings', { method: 'POST', body: { __exportFileAction: 'reveal', payload: { filePath } }, cdpTimeoutMs: 4000, }); return Boolean(fallbackRes?.ok); } catch { return false; } } async function requestLocalBackendExport(payload) { let remoteForbidden = false; try { const res = await callSidecarApi('/api/export-file', { method: 'POST', body: payload, cdpTimeoutMs: 6000, }); if (res && res.ok && res.filePath) { return { res, remoteForbidden: false }; } if (res && res.fallbackBrowser) { return { res: null, remoteForbidden: true }; } } catch (err) { if (err?.httpStatus === 403) { remoteForbidden = true; } } if (remoteForbidden) { return { res: null, remoteForbidden: true }; } // 兼容热更新后常驻父进程 main.mjs 尚未重注册 /api/export-file 的场景,回退经 POST /api/settings 穿透至最新 Worker try { const fallbackRes = await callSidecarApi('/api/settings', { method: 'POST', body: { __exportFileAction: 'save', payload }, cdpTimeoutMs: 6000, }); if (fallbackRes && fallbackRes.ok && fallbackRes.filePath) { return { res: fallbackRes, remoteForbidden: false }; } } catch { // 忽略回退异常,交由下方分环境处理 } return { res: null, remoteForbidden: false }; } /** * 共享多阶段导出与 Toast 反馈骨架(本机落盘 -> 宿主拦截保护 -> File System Access Picker -> Blob 下载)。 */ async function runExportPipelineWithFeedback({ safeName, mimeType, backendPayload, writablePayload, }) { if (isHostEmbeddedWebview()) { const { res: localRes } = await requestLocalBackendExport(backendPayload); if (localRes && localRes.ok && localRes.filePath) { const savedPath = String(localRes.filePath); const savedName = String(localRes.fileName || safeName); showUiToast({ message: t('export.savedLocal', { file: savedName }), detail: savedPath, actionLabel: t('export.openFolder'), onAction: () => { void revealExportedFile(savedPath); }, tone: 'ok', durationMs: 7000, }); return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName }; } // 在 Antigravity Sidecar / 双栖 Electron 宿主内, 会被静默吞掉,绝不误报“已下载到浏览器” showUiToast({ message: t('export.failed'), detail: t('export.hostUnavailable'), tone: 'warn', durationMs: 5200, }); return { ok: false, mode: 'failed' }; } if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') { try { const handle = await window.showSaveFilePicker({ suggestedName: safeName, types: getPickerTypesForFilename(safeName, mimeType), }); const writable = await handle.createWritable(); await writable.write(writablePayload); await writable.close(); const pickedName = handle.name || safeName; showUiToast({ message: t('export.savedPicked', { file: pickedName }), tone: 'ok', durationMs: 4200, }); return { ok: true, mode: 'picker', fileName: pickedName }; } catch (err) { if (err && err.name === 'AbortError') { return { ok: false, mode: 'cancelled' }; } } } const ok = triggerBlobDownload(safeName, writablePayload, mimeType); if (ok) { showUiToast({ message: t('export.savedBrowser', { file: safeName }), detail: t('export.savedBrowserHint'), tone: 'info', durationMs: 5000, }); return { ok: true, mode: 'browser', fileName: safeName }; } showUiToast({ message: t('export.failed'), tone: 'warn', durationMs: 3600, }); return { ok: false, mode: 'failed' }; } /** * 统一文本导出入口:优先本机后端落盘(返回精确路径 + 支持一键打开所在目录), * 仅在真正独立浏览器上下文下降级为浏览器保存。 * * @param {string} filename * @param {string} content * @param {string} [mimeType='application/json;charset=utf-8'] * @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>} */ async function exportTextFileWithFeedback( filename, content, mimeType = 'application/json;charset=utf-8' ) { const safeName = String(filename || 'export.txt'); const text = String(content ?? ''); return runExportPipelineWithFeedback({ safeName, mimeType, backendPayload: { filename: safeName, content: text, mimeType, }, writablePayload: text, }); } /** * 统一二进制文件导出入口(用于原生 `.xlsx` Excel 工作簿)。 * * @param {string} filename * @param {Uint8Array} bytes * @param {string} [mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'] * @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>} */ async function exportBinaryFileWithFeedback( filename, bytes, mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) { const safeName = String(filename || 'export.xlsx'); if (!(bytes instanceof Uint8Array) || bytes.length === 0) { showUiToast({ message: t('export.failed'), tone: 'warn', durationMs: 3600 }); return { ok: false, mode: 'failed' }; } return runExportPipelineWithFeedback({ safeName, mimeType, backendPayload: { filename: safeName, content: uint8ArrayToBase64(bytes), encoding: 'base64', mimeType, }, writablePayload: bytes, }); } /** * 复制文本到剪贴板并弹出轻量提示条。 * * @param {string} text * @param {string} successMessage * @returns {Promise} */ async function copyTextWithFeedback(text, successMessage) { const ok = await copyPlainTextToClipboard(text); if (ok) { showUiToast({ message: successMessage || t('export.copied'), tone: 'ok', durationMs: 2400, }); } else { showUiToast({ message: t('export.copyFailed'), tone: 'warn', durationMs: 3200, }); } return ok; } return { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFeedback, copyTextWithFeedback }; })(); // --- src/core/hostI18nClient.js --- const { fetchHostI18nStatus, refreshHostI18nManifest, selectHostI18nLanguage, updateHostI18nDepth, installOrUpdateHostI18nPack, removeHostI18nPack, collectHostI18nUntranslated } = (() => { /** * @fileoverview Decoupled HTTP/CDP client for `/api/host-i18n`. * Completely independent from `telemetryStore.js`. */ async function fetchHostI18nStatus() { return callSidecarApi(HOST_I18N_API_PATH, { method: 'GET', abortKey: 'host-i18n-get', cdpTimeoutMs: 12000, }); } async function refreshHostI18nManifest() { return callSidecarApi(HOST_I18N_API_PATH, { method: 'POST', body: { action: 'refresh_manifest' }, cdpTimeoutMs: 18000, }); } async function selectHostI18nLanguage(locale, depth) { return callSidecarApi(HOST_I18N_API_PATH, { method: 'POST', body: { action: 'select', locale: normalizeHostI18nLocale(locale), ...(depth !== undefined ? { depth: normalizeHostI18nDepth(depth) } : {}), }, cdpTimeoutMs: 22000, }); } async function updateHostI18nDepth(depth) { return callSidecarApi(HOST_I18N_API_PATH, { method: 'POST', body: { action: 'set_depth', depth: normalizeHostI18nDepth(depth), }, cdpTimeoutMs: 10000, }); } async function installOrUpdateHostI18nPack(locale) { return callSidecarApi(HOST_I18N_API_PATH, { method: 'POST', body: { action: 'update', locale: normalizeHostI18nLocale(locale), }, cdpTimeoutMs: 22000, }); } async function removeHostI18nPack(locale) { return callSidecarApi(HOST_I18N_API_PATH, { method: 'POST', body: { action: 'remove', locale: normalizeHostI18nLocale(locale), }, cdpTimeoutMs: 10000, }); } async function collectHostI18nUntranslated() { return callSidecarApi(HOST_I18N_API_PATH, { method: 'POST', body: { action: 'collect_untranslated' }, cdpTimeoutMs: 15000, }); } return { fetchHostI18nStatus, refreshHostI18nManifest, selectHostI18nLanguage, updateHostI18nDepth, installOrUpdateHostI18nPack, removeHostI18nPack, collectHostI18nUntranslated }; })(); // --- src/store/telemetryStore.js --- const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientAccountQuotaRefreshMinutes, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. */ const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** * 在主窗口双栖模式下,提取当前正在浏览的会话 ID: * 1. 优先解析 Antigravity 2.0 路由路径 `/c/`; * 2. 在 Antigravity IDE (`workbench.html`) 无路径路由时,回退读取活跃对话视图 * `[data-testid="conversation-view"][data-cascade-id]` 或侧栏选中项。 * * @returns {string} */ function extractHostRouteCascadeId() { if (typeof window === 'undefined' || !isWindowOverlayMode()) return ''; const pathname = String(window.location?.pathname || ''); const m = pathname.match(/^\/c\/([a-f0-9-]{36})(?:\/|$)/i); if (m && CASCADE_UUID_RE.test(m[1])) { return m[1]; } const extBridgeRouteId = String(readInjectedWindowBridge()?.[WINDOW_BRIDGE_ROUTE_KEY] || '').trim(); if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) { return extBridgeRouteId; } try { if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { return ''; } const selectedRow = document.querySelector( '[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]' ); const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim(); if (typeof document.querySelectorAll === 'function') { const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]'); const visibleIds = []; let focusedId = ''; const activeEl = document.activeElement || null; for (const viewEl of views) { const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim(); if (!CASCADE_UUID_RE.test(cid)) continue; if (viewEl.hasAttribute?.('hidden')) continue; if (viewEl.getBoundingClientRect) { const r = viewEl.getBoundingClientRect(); if (r.width <= 0 && r.height <= 0) continue; } visibleIds.push(cid); if (activeEl && viewEl.contains?.(activeEl)) { focusedId = cid; } } if (focusedId) return focusedId; if ( selectedRowId && CASCADE_UUID_RE.test(selectedRowId) && visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase()) ) { return selectedRowId; } if (visibleIds.length > 0) return visibleIds[0]; } const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]'); const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim(); if (CASCADE_UUID_RE.test(singleViewId)) { return singleViewId; } if (CASCADE_UUID_RE.test(selectedRowId)) { return selectedRowId; } } catch { // 忽略宿主 DOM 查询异常 } return ''; } const initialConversationId = (typeof window !== 'undefined' && window.sidecar?.conversationId) || ''; const telemetryStore = createReactiveStore({ selectedConversationId: initialConversationId, hostRouteConversationId: extractHostRouteCascadeId(), selectedTimeRange: 'today', selectedCyclePool: 'all', customStartMs: Date.now() - 24 * 3600 * 1000, customEndMs: Date.now(), syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' minuteTick: 0, telemetry: null, }); let pollTimer = null; let feedbackTimer = null; let deferredConvSyncTimer = null; let activeBundleVersion = 0; let latestRequestSeq = 0; let latestConsumptionReqSeq = 0; let latestConversationSwitchSeq = 0; let endpointSwitchEpoch = 0; let activeForceCount = 0; let consecutivePollFailures = 0; let inFlightTelemetryPoll = null; let inFlightPresetsPrefetch = null; let lastPrefetchedUsageRevision = 0; let consumptionCacheScopeSig = ''; const MAX_CONSUMPTION_RANGE_CACHE = 24; const MAX_CONVERSATION_VIEW_CACHE = 12; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const consumptionRangeCache = new Map(); const conversationViewCache = new Map(); let lastReceivedSteps = null; let loopActive = false; let loopIntervalMs = 2000; let loopTickFn = null; let settingsRevision = 0; let settingsWriteChain = Promise.resolve(); const pendingSettingsMutations = new Map(); const recentCommittedSettings = new Map(); const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ 'weeklyLimitMode', 'weeklyTokenBudget', 'weeklyCostBudget', 'windowMountMode', 'enableWindowOverlay', ]); function makeConsumptionRangeCacheKey( range, customStartMs = 0, customEndMs = 0, cyclePool = 'all' ) { const key = String(range || 'all'); if (key === 'custom') { return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; } if (key === 'cycle' && cyclePool && cyclePool !== 'all') { return `cycle:${String(cyclePool)}`; } return key; } function clearConsumptionRangeCache() { consumptionRangeCache.clear(); lastPrefetchedUsageRevision = 0; inFlightPresetsPrefetch = null; } function clearConversationViewCache() { conversationViewCache.clear(); if (deferredConvSyncTimer) { clearTimeout(deferredConvSyncTimer); deferredConvSyncTimer = null; } } function buildConsumptionScopeSig(payload) { if (!payload || typeof payload !== 'object') return ''; const ep = payload.endpoint || {}; const acct = payload.account || {}; const set = payload.settings || {}; const cloud = payload.cloudStatus || {}; return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; } function reconcileSelectedCyclePool(payload) { const curPool = telemetryStore.getState().selectedCyclePool || 'all'; if (curPool === 'all') return; const pools = payload?.quotas?.pools; if (!Array.isArray(pools) || pools.length === 0) return; const exists = pools.some((p) => String(p?.poolKey || p?.family || '') === curPool); if (!exists) { telemetryStore.setState({ selectedCyclePool: 'all' }); } } function syncConsumptionCacheScope(payload) { const nextSig = buildConsumptionScopeSig(payload); if (!nextSig) return; if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) { clearConsumptionRangeCache(); clearConversationViewCache(); } consumptionCacheScopeSig = nextSig; reconcileSelectedCyclePool(payload); } function recordConversationViewToCache(payload) { const active = payload?.activeConversation; const cidLower = String(active?.cascadeId || '').trim().toLowerCase(); if (!cidLower || !Array.isArray(active?.recentSteps)) return; const entry = { cascadeId: active.cascadeId, activeConversation: active, activePool: payload.quotas?.activePool || null, weekly: payload.quotas?.weekly || null, sessionConsumption: payload.consumption?.session || null, sessionPresets: payload.consumption?.sessionPresets || (payload.consumption?.presets ? Object.fromEntries( Object.entries(payload.consumption.presets).map(([k, v]) => [k, v?.session || null]) ) : null), stepRevision: String(payload.stepRevision || ''), cachedAtMs: Date.now(), }; conversationViewCache.delete(cidLower); conversationViewCache.set(cidLower, entry); while (conversationViewCache.size > MAX_CONVERSATION_VIEW_CACHE) { conversationViewCache.delete(conversationViewCache.keys().next().value); } } function resolveCachedConversationRootId(telemetry, effectiveConvId) { const target = String(effectiveConvId || '').trim(); const convs = Array.isArray(telemetry?.conversations) ? telemetry.conversations : []; if (!target) { return String(convs[0]?.cascadeId || '').trim().toLowerCase(); } const lower = target.toLowerCase(); if (conversationViewCache.has(lower)) return lower; const matchedRoot = convs.find( (c) => String(c?.cascadeId || '').toLowerCase() === lower || (Array.isArray(c?.memberCascadeIds) && c.memberCascadeIds.some((m) => String(m || '').toLowerCase() === lower)) ); return String(matchedRoot?.cascadeId || lower).trim().toLowerCase(); } function applyConversationSliceToTelemetry(baseTelemetry, slice) { if (!baseTelemetry || !slice?.activeConversation) return baseTelemetry; const activeCidLower = String(slice.activeConversation.cascadeId || '').toLowerCase(); const prevQuotas = baseTelemetry.quotas || {}; const nextQuotas = slice.activePool || slice.weekly ? { ...prevQuotas, ...(slice.activePool ? { activePool: slice.activePool } : {}), ...(slice.weekly ? { weekly: slice.weekly } : {}), } : prevQuotas; const prevCons = baseTelemetry.consumption || {}; let nextPresets = prevCons.presets; if (slice.sessionPresets && prevCons.presets && typeof prevCons.presets === 'object') { nextPresets = { ...prevCons.presets }; for (const [k, sBucket] of Object.entries(slice.sessionPresets)) { if (sBucket && nextPresets[k]) { nextPresets[k] = { ...nextPresets[k], session: sBucket }; } } } const nextCons = slice.sessionConsumption || nextPresets !== prevCons.presets ? { ...prevCons, ...(slice.sessionConsumption ? { session: slice.sessionConsumption } : {}), ...(nextPresets !== prevCons.presets ? { presets: nextPresets } : {}), } : prevCons; const prevRunning = Array.isArray(baseTelemetry.runningConversations) ? baseTelemetry.runningConversations : null; let nextRunning = prevRunning; if (prevRunning && prevRunning.length > 0 && activeCidLower) { let anyChanged = false; const mapped = prevRunning.map((item) => { const shouldSelect = String(item?.cascadeId || '').toLowerCase() === activeCidLower; if (Boolean(item?.isCurrentSelected) === shouldSelect) return item; anyChanged = true; return { ...item, isCurrentSelected: shouldSelect }; }); if (anyChanged) nextRunning = mapped; } return { ...baseTelemetry, ...(slice.stepRevision ? { stepRevision: slice.stepRevision } : {}), activeConversation: slice.activeConversation, quotas: nextQuotas, consumption: nextCons, ...(nextRunning ? { runningConversations: nextRunning } : {}), }; } function putConsumptionRangeCacheEntry(cacheKey, entry) { if (!cacheKey || !entry) return; consumptionRangeCache.delete(cacheKey); consumptionRangeCache.set(cacheKey, entry); while (consumptionRangeCache.size > MAX_CONSUMPTION_RANGE_CACHE) { consumptionRangeCache.delete(consumptionRangeCache.keys().next().value); } } function recordConsumptionSliceToCache( cons, modelBreakdown, { customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {} ) { const rangeKey = String(cons?.selectedRange?.key || ''); if (!rangeKey) return; const resolvedPool = rangeKey === 'cycle' ? String(cons?.selectedRange?.pool || cyclePool || 'all') : 'all'; const cacheKey = makeConsumptionRangeCacheKey( rangeKey, rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0, resolvedPool ); putConsumptionRangeCacheEntry(cacheKey, { revision: Number(cons.revision ?? usageRevision ?? 0), selectedRange: cons.selectedRange, session: cons.session, account: cons.account, trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [], sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [], topConversations: Array.isArray(cons.topConversations) ? cons.topConversations : [], topWorkspaces: Array.isArray(cons.topWorkspaces) ? cons.topWorkspaces : [], modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [], }); } function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision = 0) { if (!baseTelemetry || !cachedEntry) return baseTelemetry; const prevCons = baseTelemetry.consumption || {}; return { ...baseTelemetry, consumption: { ...prevCons, ...(targetRevision > 0 ? { revision: targetRevision } : {}), selectedRange: cachedEntry.selectedRange, session: cachedEntry.session ?? prevCons.session, account: cachedEntry.account ?? prevCons.account, trendSeries: cachedEntry.trendSeries, sourcesBreakdown: cachedEntry.sourcesBreakdown, topConversations: Array.isArray(cachedEntry.topConversations) ? cachedEntry.topConversations : [], topWorkspaces: Array.isArray(cachedEntry.topWorkspaces) ? cachedEntry.topWorkspaces : [], }, modelBreakdown: cachedEntry.modelBreakdown, }; } function hasAllPresetRangesCached(expectedRevision) { for (const key of CONSUMPTION_PRESET_KEYS) { const entry = consumptionRangeCache.get(key); if (!entry) return false; if (expectedRevision > 0 && entry.revision !== expectedRevision) return false; } return true; } function enqueueSettingsWrite(task) { const run = settingsWriteChain.then(task, task); settingsWriteChain = run.catch(() => {}); return run; } function extractReturnedSettings(res) { if (!res || typeof res !== 'object') return null; if (res.settings && typeof res.settings === 'object' && !Array.isArray(res.settings)) { return res.settings; } if ( typeof res.language === 'string' || typeof res.themeAccent === 'string' || typeof res.windowMountMode === 'string' ) { return res; } return null; } function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) { if (!payload?.settings || typeof payload.settings !== 'object') { return payload; } for (const [k, entry] of [...recentCommittedSettings.entries()]) { if (reqSettingsRev >= entry.rev) { recentCommittedSettings.delete(k); } } if (pendingSettingsMutations.size === 0 && recentCommittedSettings.size === 0) { return payload; } let merged = null; for (const [k, entry] of recentCommittedSettings.entries()) { if (reqSettingsRev < entry.rev) { merged ??= { ...payload.settings }; merged[k] = entry.value; } } for (const [k, entry] of pendingSettingsMutations.entries()) { merged ??= { ...payload.settings }; merged[k] = entry.value; } return merged ? { ...payload, settings: merged } : payload; } const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS; const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS; const DEFAULT_CLIENT_CONTEXT_AGENT_MODE = DEFAULT_CONTEXT_AGENT_MODE; const CLIENT_CLI_STATUSLINE_PRESETS = CLI_STATUSLINE_PRESETS; const DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS = DEFAULT_CLI_STATUSLINE_SLOTS; const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS; const DEFAULT_CLIENT_OVERVIEW_MODULES = DEFAULT_OVERVIEW_MODULES; const DEFAULT_CLIENT_HOVER_MODULES = DEFAULT_HOVER_MODULES; const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS; const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS; const CLIENT_STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS; const DEFAULT_CLIENT_STEP_COLUMNS = DEFAULT_STEP_TABLE_COLUMNS; const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT; const MIN_CLIENT_POPOVER_WIDTH = MIN_POPOVER_WIDTH; const MAX_CLIENT_POPOVER_WIDTH = MAX_POPOVER_WIDTH; const DEFAULT_CLIENT_POPOVER_WIDTH = DEFAULT_POPOVER_WIDTH; const parseClientStepTokenComboSegments = parseStepTokenComboSegments; const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat; const normalizeClientPopoverWidthMode = normalizePopoverWidthMode; const normalizeClientPopoverWidth = normalizePopoverWidth; const normalizeClientModelDisplayMode = normalizeModelDisplayMode; const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; const normalizeClientContextAgentMode = normalizeContextAgentMode; const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation; const normalizeClientAccountQuotaRefreshMinutes = normalizeAccountQuotaRefreshMinutes; const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots; /** * 根据偏好设置返回默认上下文代理目标(`'main'` 锁定主代理,`'auto'` 跟随活跃)。 * * @param {Record|null|undefined} settings * @returns {'main'|'auto'} */ function getDefaultCtxInspectorAgentId(settings) { return normalizeContextAgentMode(settings?.contextAgentMode) === 'auto' ? 'auto' : 'main'; } /** * 计算顶栏挂载胶囊及悬停速览浮窗应使用的上下文代理目标: * - 当 `contextAgentMode === 'main'`(默认)时始终锁定 `'main'`,不被后台子代理或面板临时点选带偏; * - 当 `contextAgentMode === 'auto'` 时跟随面板当前 `ctxInspectorAgentId`(含手动点选 `主`)。 * * @param {Record|null|undefined} telemetry * @param {string} [ctxInspectorAgentId='auto'] * @returns {string} */ function resolveOverlayCtxInspectorAgentId(telemetry, ctxInspectorAgentId = 'auto') { if (normalizeContextAgentMode(telemetry?.settings?.contextAgentMode) === 'main') { return 'main'; } return ctxInspectorAgentId || 'auto'; } const resolveEffectiveClientCliStatusLineSlots = resolveEffectiveCliStatusLineSlots; const normalizeClientHoverModules = normalizeHoverModules; const normalizeClientOverviewModules = normalizeOverviewModules; const normalizeClientOverviewMetrics = normalizeOverviewMetrics; const normalizeClientStepColumns = normalizeStepTableColumns; const normalizeClientUpdateMode = normalizePluginUpdateMode; const normalizeClientOrchestratorIdMode = normalizeOrchestratorIdMode; const normalizeClientWindowMountMode = normalizeWindowMountMode; function isEquivalentTelemetry(prev, next) { if (!prev || !next) return false; if (prev === next) return true; const sameArr = (a, b) => { if (a === b) return true; if (!Array.isArray(a) || !Array.isArray(b)) return false; if (a.length !== b.length) return false; for (let i = 0; i < a.length; i += 1) { if (a[i] !== b[i]) return false; } return true; }; // 1. 比对系统设置项(外观语言/主题/字号、模型显示策略、更新策略、挂载与结构布局配置) const pAct = prev.activeConversation; const nAct = next.activeConversation; const pSet = prev.settings; const nSet = next.settings; if ((pSet?.language ?? 'auto') !== (nSet?.language ?? 'auto')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; if (resolveSettingsModernUi(pSet) !== resolveSettingsModernUi(nSet)) return false; if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if ( (prev.endpoint?.id || LOCAL_ENDPOINT_ID) !== (next.endpoint?.id || LOCAL_ENDPOINT_ID) || Boolean(prev.endpoint?.isRemote) !== Boolean(next.endpoint?.isRemote) || (prev.endpoint?.label || '') !== (next.endpoint?.label || '') ) { return false; } if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; } if ( (pSet?.contextWindowMainEnabled !== false) !== (nSet?.contextWindowMainEnabled !== false) || Boolean(pSet?.contextWindowSwarmEnabled) !== Boolean(nSet?.contextWindowSwarmEnabled) ) { return false; } if ( (prev.cloudCodeProxy?.state || 'disabled') !== (next.cloudCodeProxy?.state || 'disabled') || Number(prev.cloudCodeProxy?.ruleCount || 0) !== Number(next.cloudCodeProxy?.ruleCount || 0) || String(prev.cloudCodeProxy?.error || '') !== String(next.cloudCodeProxy?.error || '') || Number(prev.cloudCodeProxy?.syncedAtMs || 0) !== Number(next.cloudCodeProxy?.syncedAtMs || 0) ) { return false; } if ( JSON.stringify(pSet?.modelContextWindows) !== JSON.stringify(nSet?.modelContextWindows) || JSON.stringify(prev.contextWindowModels) !== JSON.stringify(next.contextWindowModels) ) { return false; } if ( normalizeModelDisplayMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !== normalizeModelDisplayMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel) ) { return false; } if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false; if (normalizePopoverWidthMode(pSet?.popoverWidthMode) !== normalizePopoverWidthMode(nSet?.popoverWidthMode)) { return false; } if (normalizePopoverWidth(pSet?.popoverWidth) !== normalizePopoverWidth(nSet?.popoverWidth)) { return false; } if ( String(pSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() !== String(nSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() ) { return false; } if ( normalizeOrchestratorIdMode(pSet?.orchestratorIdMode) !== normalizeOrchestratorIdMode(nSet?.orchestratorIdMode) ) { return false; } if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false; if (pSet?.weeklyTokenBudget !== nSet?.weeklyTokenBudget) return false; if (pSet?.weeklyCostBudget !== nSet?.weeklyCostBudget) return false; if ((pSet?.pluginUpdateMode ?? '') !== (nSet?.pluginUpdateMode ?? '')) return false; if (pSet?.autoUpdatePlugin !== nSet?.autoUpdatePlugin) return false; if ( normalizeClientWindowMountMode(pSet?.windowMountMode, pSet?.enableWindowOverlay) !== normalizeClientWindowMountMode(nSet?.windowMountMode, nSet?.enableWindowOverlay) ) { return false; } if (pSet?.enableWindowOverlay !== nSet?.enableWindowOverlay) return false; if ((pSet?.enableCliStatusLine !== false) !== (nSet?.enableCliStatusLine !== false)) { return false; } if (!sameArr(pSet?.cliStatusLineSlots, nSet?.cliStatusLineSlots)) return false; if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) { return false; } if ( normalizeClientContextAgentMode(pSet?.contextAgentMode) !== normalizeClientContextAgentMode(nSet?.contextAgentMode) ) { return false; } if (Boolean(pSet?.showStepTurnRail) !== Boolean(nSet?.showStepTurnRail)) { return false; } if ((pSet?.showStepAgentBadge !== false) !== (nSet?.showStepAgentBadge !== false)) { return false; } if (Boolean(pSet?.showStepSpeedColor) !== Boolean(nSet?.showStepSpeedColor)) { return false; } if (Boolean(pSet?.showStepFilterToolbar) !== Boolean(nSet?.showStepFilterToolbar)) { return false; } if ( normalizeClientExperimentalQuotaReservation(pSet?.experimentalQuotaReservation) !== normalizeClientExperimentalQuotaReservation(nSet?.experimentalQuotaReservation) ) { return false; } if ( normalizeClientAccountQuotaRefreshMinutes(pSet?.accountQuotaRefreshMinutes) !== normalizeClientAccountQuotaRefreshMinutes(nSet?.accountQuotaRefreshMinutes) ) { return false; } if (Boolean(pSet?.accountSwitchRiskAccepted) !== Boolean(nSet?.accountSwitchRiskAccepted)) { return false; } if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false; if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false; if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false; if (!sameArr(pSet?.overviewMetrics, nSet?.overviewMetrics)) return false; if (!sameArr(pSet?.stepTableColumns, nSet?.stepTableColumns)) return false; // 2. 比对云端状态与桥接健康度 const pWb = prev.windowBridge; const nWb = next.windowBridge; if ( (pWb?.state || '') !== (nWb?.state || '') || Boolean(pWb?.argvUpdatedThisBoot) !== Boolean(nWb?.argvUpdatedThisBoot) || Boolean(pWb?.argvConfigured) !== Boolean(nWb?.argvConfigured) || Boolean(pWb?.launcherConfigured) !== Boolean(nWb?.launcherConfigured) || Boolean(pWb?.canRelaunch) !== Boolean(nWb?.canRelaunch) || Number(pWb?.aliveCount || 0) !== Number(nWb?.aliveCount || 0) ) { return false; } const pCli = prev.cliStatusLine; const nCli = next.cliStatusLine; if ( Boolean(pCli?.installed) !== Boolean(nCli?.installed) || Boolean(pCli?.configured) !== Boolean(nCli?.configured) || Boolean(pCli?.preservedCustom) !== Boolean(nCli?.preservedCustom) || String(pCli?.managedFlags || '') !== String(nCli?.managedFlags || '') ) { return false; } const pCloud = prev.cloudStatus; const nCloud = next.cloudStatus; if ( pCloud?.currentPluginVersion !== nCloud?.currentPluginVersion || pCloud?.latestPluginVersion !== nCloud?.latestPluginVersion || pCloud?.updateAvailable !== nCloud?.updateAvailable || pCloud?.installMode !== nCloud?.installMode || pCloud?.catalogVersion !== nCloud?.catalogVersion || pCloud?.source !== nCloud?.source || pCloud?.lastSyncedAtMs !== nCloud?.lastSyncedAtMs || pCloud?.modelCount !== nCloud?.modelCount || pCloud?.isSyncing !== nCloud?.isSyncing || pCloud?.isUpdating !== nCloud?.isUpdating || pCloud?.lastSyncError !== nCloud?.lastSyncError || pCloud?.lastUpdateError !== nCloud?.lastUpdateError || pCloud?.lastUpdateResult?.updatedAtMs !== nCloud?.lastUpdateResult?.updatedAtMs ) { return false; } // 3. 比对活跃会话的实时测速指标 if (pAct?.cascadeId !== nAct?.cascadeId) return false; if (pAct?.stepCount !== nAct?.stepCount) return false; if (pAct?.subagentCount !== nAct?.subagentCount) return false; if ((pAct?.swarmCount || 0) !== (nAct?.swarmCount || 0)) return false; if ((pAct?.swarmTitle || '') !== (nAct?.swarmTitle || '')) return false; if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false; if (pAct?.isRunning !== nAct?.isRunning) return false; if ( pAct?.inputTokens !== nAct?.inputTokens || pAct?.cacheReadTokens !== nAct?.cacheReadTokens || pAct?.outputTokens !== nAct?.outputTokens || pAct?.totalTokens !== nAct?.totalTokens ) { return false; } if ( pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature || pAct?.liveActivity?.startedAtMs !== nAct?.liveActivity?.startedAtMs ) { return false; } if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false; if ( pAct?.aggregated?.inputTokens !== nAct?.aggregated?.inputTokens || pAct?.aggregated?.cacheReadTokens !== nAct?.aggregated?.cacheReadTokens || pAct?.aggregated?.outputTokens !== nAct?.aggregated?.outputTokens || pAct?.aggregated?.totalTokens !== nAct?.aggregated?.totalTokens ) { return false; } if ( pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature || pAct?.aggregated?.liveActivity?.startedAtMs !== nAct?.aggregated?.liveActivity?.startedAtMs ) { return false; } if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false; if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false; if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false; if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false; if (pAct?.aggregated?.latestTtftSec !== nAct?.aggregated?.latestTtftSec) return false; if (pAct?.aggregated?.lastKnownTtftSec !== nAct?.aggregated?.lastKnownTtftSec) return false; if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false; if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false; if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false; if (pAct?.aggregated?.sessionUnpricedCalls !== nAct?.aggregated?.sessionUnpricedCalls) return false; if (pAct?.aggregated?.sessionCacheHitPct !== nAct?.aggregated?.sessionCacheHitPct) return false; if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false; if (pAct?.aggregated?.activeModelUpstream !== nAct?.aggregated?.activeModelUpstream) return false; if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false; if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; if (pAct?.lastKnownTtftSec !== nAct?.lastKnownTtftSec) return false; if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false; if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false; if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false; if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false; if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false; if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false; if ( pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel || pAct?.activeModelUpstream !== nAct?.activeModelUpstream ) { return false; } if ( pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionCostUsd !== nAct?.sessionCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls ) { return false; } const pAgents = pAct?.agents || []; const nAgents = nAct?.agents || []; if (pAgents.length !== nAgents.length) return false; for (let i = 0; i < pAgents.length; i++) { const pa = pAgents[i]; const na = nAgents[i]; if ( pa?.agentId !== na?.agentId || pa?.agentKind !== na?.agentKind || pa?.agentOrdinal !== na?.agentOrdinal || (pa?.swarmState || '') !== (na?.swarmState || '') || pa?.role !== na?.role || pa?.stepCount !== na?.stepCount || pa?.isRunning !== na?.isRunning || pa?.liveActivity?.signature !== na?.liveActivity?.signature || pa?.latestTokPerSec !== na?.latestTokPerSec || pa?.latestTtftSec !== na?.latestTtftSec || pa?.lastKnownTtftSec !== na?.lastKnownTtftSec || pa?.avgTokPerSec !== na?.avgTokPerSec || pa?.latestCacheHitPct !== na?.latestCacheHitPct || pa?.sessionCacheHitPct !== na?.sessionCacheHitPct || pa?.latestSpeedReason !== na?.latestSpeedReason || pa?.latestStepCostUsd !== na?.latestStepCostUsd || pa?.sessionCostUsd !== na?.sessionCostUsd || pa?.sessionUnpricedCalls !== na?.sessionUnpricedCalls || pa?.activeModelShort !== na?.activeModelShort || pa?.activeModelUpstream !== na?.activeModelUpstream || pa?.context?.totalTokens !== na?.context?.totalTokens || pa?.context?.compactionLimitTokens !== na?.context?.compactionLimitTokens || pa?.context?.limitTokens !== na?.context?.limitTokens || pa?.context?.messagesTokens !== na?.context?.messagesTokens || pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens || pa?.context?.assistantTokens !== na?.context?.assistantTokens || pa?.context?.userInputTokens !== na?.context?.userInputTokens || pa?.context?.subagentTokens !== na?.context?.subagentTokens || pa?.context?.checkpointTokens !== na?.context?.checkpointTokens || pa?.context?.systemToolsTokens !== na?.context?.systemToolsTokens || pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens || pa?.context?.skillsTokens !== na?.context?.skillsTokens || pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens || pa?.context?.userRulesTokens !== na?.context?.userRulesTokens ) { return false; } // 主代理步骤由根会话统一比对,避免明细视图组装后的引用造成重复比对。 const paSteps = pa?.isMain && pAct?.recentSteps ? [] : pa?.recentSteps || []; const naSteps = na?.isMain && nAct?.recentSteps ? [] : na?.recentSteps || []; if (paSteps.length !== naSteps.length) return false; for (let j = 0; paSteps !== naSteps && j < paSteps.length; j++) { const bs = paSteps[j]; const as = naSteps[j]; if ( bs?.stepIndex !== as?.stepIndex || bs?.createdAtMs !== as?.createdAtMs || bs?.totalDurationSec !== as?.totalDurationSec || bs?.streamDurationSec !== as?.streamDurationSec || bs?.nativeStreamSec !== as?.nativeStreamSec || bs?.thinkingDurationSec !== as?.thinkingDurationSec || Boolean(bs?.hasToolCalls) !== Boolean(as?.hasToolCalls) || bs?.modelKey !== as?.modelKey || bs?.modelShort !== as?.modelShort || bs?.modelLabel !== as?.modelLabel || bs?.modelUpstream !== as?.modelUpstream || bs?.responseModel !== as?.responseModel || bs?.modelSource !== as?.modelSource || bs?.costUsd !== as?.costUsd || bs?.tokPerSec !== as?.tokPerSec || bs?.ttftSec !== as?.ttftSec || bs?.outputTokens !== as?.outputTokens || bs?.thinkingTokens !== as?.thinkingTokens || bs?.responseTokens !== as?.responseTokens || bs?.inputTokens !== as?.inputTokens || bs?.cacheReadTokens !== as?.cacheReadTokens || bs?.contextTokens !== as?.contextTokens || bs?.cacheHitPct !== as?.cacheHitPct || bs?.selectedSpeedReason !== as?.selectedSpeedReason || bs?.anomalySig !== as?.anomalySig || bs?.turnIndex !== as?.turnIndex || bs?.rootTurnIndex !== as?.rootTurnIndex || bs?.isTurnStart !== as?.isTurnStart || bs?.isRootTurnStart !== as?.isRootTurnStart || bs?.isLatestTurn !== as?.isLatestTurn || bs?.isRootLatestTurn !== as?.isRootLatestTurn || bs?.turnPrompt !== as?.turnPrompt || bs?.rootTurnPrompt !== as?.rootTurnPrompt ) { return false; } } } // 4. 比对 10 通道上下文窗口构成及近期步骤明细 const pCtx = pAct?.context; const nCtx = nAct?.context; if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; if (pCtx?.compactionLimitTokens !== nCtx?.compactionLimitTokens) return false; if (pCtx?.limitTokens !== nCtx?.limitTokens) return false; if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false; if (pCtx?.assistantTokens !== nCtx?.assistantTokens) return false; if (pCtx?.toolResultsTokens !== nCtx?.toolResultsTokens) return false; if (pCtx?.userInputTokens !== nCtx?.userInputTokens) return false; if (pCtx?.subagentTokens !== nCtx?.subagentTokens) return false; if (pCtx?.checkpointTokens !== nCtx?.checkpointTokens) return false; if (pCtx?.systemToolsTokens !== nCtx?.systemToolsTokens) return false; if (pCtx?.mcpToolsTokens !== nCtx?.mcpToolsTokens) return false; if (pCtx?.skillsTokens !== nCtx?.skillsTokens) return false; if (pCtx?.systemPromptTokens !== nCtx?.systemPromptTokens) return false; if (pCtx?.userRulesTokens !== nCtx?.userRulesTokens) return false; if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false; for (let i = 0; pAct?.recentSteps !== nAct?.recentSteps && i < (pAct?.recentSteps?.length || 0); i++) { const before = pAct.recentSteps[i], after = nAct.recentSteps[i]; if ( before.stepIndex !== after.stepIndex || before.createdAtMs !== after.createdAtMs || before.totalDurationSec !== after.totalDurationSec || before.streamDurationSec !== after.streamDurationSec || before.nativeStreamSec !== after.nativeStreamSec || before.thinkingDurationSec !== after.thinkingDurationSec || Boolean(before.hasToolCalls) !== Boolean(after.hasToolCalls) || before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || before.modelLabel !== after.modelLabel || before.modelUpstream !== after.modelUpstream || before.responseModel !== after.responseModel || before.modelSource !== after.modelSource || before.costUsd !== after.costUsd || before.tokPerSec !== after.tokPerSec || before.ttftSec !== after.ttftSec || before.outputTokens !== after.outputTokens || before.thinkingTokens !== after.thinkingTokens || before.responseTokens !== after.responseTokens || before.inputTokens !== after.inputTokens || before.cacheReadTokens !== after.cacheReadTokens || before.contextTokens !== after.contextTokens || before.cacheHitPct !== after.cacheHitPct || before.selectedSpeedReason !== after.selectedSpeedReason || before.anomalySig !== after.anomalySig || before.turnIndex !== after.turnIndex || before.rootTurnIndex !== after.rootTurnIndex || before.isTurnStart !== after.isTurnStart || before.isRootTurnStart !== after.isRootTurnStart || before.isLatestTurn !== after.isLatestTurn || before.isRootLatestTurn !== after.isRootLatestTurn || before.turnPrompt !== after.turnPrompt || before.rootTurnPrompt !== after.rootTurnPrompt ) { return false; } } // 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费 const pRange = prev.consumption?.selectedRange; const nRange = next.consumption?.selectedRange; if (pRange?.key !== nRange?.key) return false; if ((pRange?.pool || 'all') !== (nRange?.pool || 'all')) return false; if ((pRange?.label || '') !== (nRange?.label || '')) return false; if (Boolean(pRange?.isFallbackWeek) !== Boolean(nRange?.isFallbackWeek)) return false; if (nRange?.key === 'custom' || nRange?.key === 'cycle') { if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false; } const pCons = prev.consumption?.session; const nCons = next.consumption?.session; if (pCons?.totalTokens !== nCons?.totalTokens) return false; if (pCons?.costUsd !== nCons?.costUsd) return false; if (pCons?.unpricedCalls !== nCons?.unpricedCalls) return false; const pAcct = prev.consumption?.account; const nAcct = next.consumption?.account; if (pAcct?.totalTokens !== nAcct?.totalTokens) return false; if (pAcct?.inputTokens !== nAcct?.inputTokens) return false; if (pAcct?.cacheReadTokens !== nAcct?.cacheReadTokens) return false; if (pAcct?.outputTokens !== nAcct?.outputTokens) return false; if (pAcct?.calls !== nAcct?.calls) return false; if (pAcct?.costUsd !== nAcct?.costUsd) return false; if (pAcct?.savedCostUsd !== nAcct?.savedCostUsd) return false; if (pAcct?.cacheHitPct !== nAcct?.cacheHitPct) return false; if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; // 6. 比对历史趋势时间分桶序列与年度分月序列 const areModelSlicesEqual = (pList, nList) => { const a = pList || []; const b = nList || []; if (a.length !== b.length) return false; for (let k = 0; k < a.length; k++) { if ( a[k]?.label !== b[k]?.label || a[k]?.shortName !== b[k]?.shortName || a[k]?.upstreamName !== b[k]?.upstreamName || a[k]?.costUsd !== b[k]?.costUsd || a[k]?.unpricedCalls !== b[k]?.unpricedCalls || a[k]?.totalTokens !== b[k]?.totalTokens || a[k]?.inputTokens !== b[k]?.inputTokens || a[k]?.cacheReadTokens !== b[k]?.cacheReadTokens || a[k]?.thinkingTokens !== b[k]?.thinkingTokens || a[k]?.responseTokens !== b[k]?.responseTokens || a[k]?.calls !== b[k]?.calls || (a[k]?.avgTokPerSec ?? null) !== (b[k]?.avgTokPerSec ?? null) || (a[k]?.avgTtftSec ?? null) !== (b[k]?.avgTtftSec ?? null) || (a[k]?.cacheHitPct ?? null) !== (b[k]?.cacheHitPct ?? null) || Number(a[k]?.anomalyCount || 0) !== Number(b[k]?.anomalyCount || 0) || Number(a[k]?.anomalySteps || 0) !== Number(b[k]?.anomalySteps || 0) ) { return false; } } return true; }; const pTrend = prev.consumption?.trendSeries || []; const nTrend = next.consumption?.trendSeries || []; if (pTrend.length !== nTrend.length) return false; for (let i = 0; i < pTrend.length; i++) { if ( pTrend[i]?.tokens !== nTrend[i]?.tokens || pTrend[i]?.inputTokens !== nTrend[i]?.inputTokens || pTrend[i]?.cacheReadTokens !== nTrend[i]?.cacheReadTokens || pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens || pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens || pTrend[i]?.calls !== nTrend[i]?.calls || pTrend[i]?.granularity !== nTrend[i]?.granularity || pTrend[i]?.stepMinutes !== nTrend[i]?.stepMinutes || pTrend[i]?.label !== nTrend[i]?.label || pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || !areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models) ) { return false; } } if (prev.consumption?.monthlyYear !== next.consumption?.monthlyYear) return false; const pMonthly = prev.consumption?.monthlySeries || []; const nMonthly = next.consumption?.monthlySeries || []; if (pMonthly.length !== nMonthly.length) return false; for (let i = 0; i < pMonthly.length; i++) { if ( pMonthly[i]?.totalTokens !== nMonthly[i]?.totalTokens || pMonthly[i]?.costUsd !== nMonthly[i]?.costUsd || pMonthly[i]?.calls !== nMonthly[i]?.calls || !areModelSlicesEqual(pMonthly[i]?.models, nMonthly[i]?.models) ) { return false; } } // 7. 比对按模型汇总明细与数据来源汇总明细 if (!areModelSlicesEqual(pAct?.modelBreakdown, nAct?.modelBreakdown)) { return false; } if (!areModelSlicesEqual(prev.modelBreakdown, next.modelBreakdown)) { return false; } const pSources = prev.consumption?.sourcesBreakdown || []; const nSources = next.consumption?.sourcesBreakdown || []; if (pSources.length !== nSources.length) return false; for (let i = 0; i < pSources.length; i++) { if ( pSources[i]?.name !== nSources[i]?.name || pSources[i]?.costUsd !== nSources[i]?.costUsd || pSources[i]?.unpricedCalls !== nSources[i]?.unpricedCalls || pSources[i]?.totalTokens !== nSources[i]?.totalTokens || pSources[i]?.calls !== nSources[i]?.calls || !areModelSlicesEqual(pSources[i]?.models, nSources[i]?.models) ) { return false; } } const pTopConvs = prev.consumption?.topConversations || []; const nTopConvs = next.consumption?.topConversations || []; if (pTopConvs.length !== nTopConvs.length) return false; for (let i = 0; i < pTopConvs.length; i++) { if ( pTopConvs[i]?.cascadeId !== nTopConvs[i]?.cascadeId || pTopConvs[i]?.title !== nTopConvs[i]?.title || pTopConvs[i]?.totalTokens !== nTopConvs[i]?.totalTokens || pTopConvs[i]?.costUsd !== nTopConvs[i]?.costUsd || pTopConvs[i]?.calls !== nTopConvs[i]?.calls || !areModelSlicesEqual(pTopConvs[i]?.models, nTopConvs[i]?.models) ) { return false; } } const pTopWs = prev.consumption?.topWorkspaces || []; const nTopWs = next.consumption?.topWorkspaces || []; if (pTopWs.length !== nTopWs.length) return false; for (let i = 0; i < pTopWs.length; i++) { if ( pTopWs[i]?.workspaceKey !== nTopWs[i]?.workspaceKey || pTopWs[i]?.label !== nTopWs[i]?.label || pTopWs[i]?.sessionCount !== nTopWs[i]?.sessionCount || pTopWs[i]?.totalTokens !== nTopWs[i]?.totalTokens || pTopWs[i]?.costUsd !== nTopWs[i]?.costUsd || pTopWs[i]?.calls !== nTopWs[i]?.calls || !areModelSlicesEqual(pTopWs[i]?.models, nTopWs[i]?.models) ) { return false; } } // 8. 比对账号订阅档位与动态多配额池 if ( prev.account?.email !== next.account?.email || prev.account?.name !== next.account?.name || prev.account?.status !== next.account?.status || prev.account?.tierId !== next.account?.tierId || prev.account?.tierName !== next.account?.tierName || prev.account?.tierMultiplier !== next.account?.tierMultiplier || prev.account?.planName !== next.account?.planName || prev.account?.aiCredits !== next.account?.aiCredits ) { return false; } if ( prev.quotas?.meta?.refreshFailed !== next.quotas?.meta?.refreshFailed || prev.quotas?.meta?.isStale !== next.quotas?.meta?.isStale ) { return false; } const pQuot = prev.quotas?.activePool; const nQuot = next.quotas?.activePool; if (pQuot?.family !== nQuot?.family) return false; if (pQuot?.usedPct !== nQuot?.usedPct) return false; if (pQuot?.remainingPct !== nQuot?.remainingPct) return false; if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false; if (pQuot?.weeklyRemainingPct !== nQuot?.weeklyRemainingPct) return false; if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false; if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false; if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false; if (prev.quotas?.weekly?.costUsd !== next.quotas?.weekly?.costUsd) return false; if (prev.quotas?.weekly?.calls !== next.quotas?.weekly?.calls) return false; if (prev.quotas?.weekly?.unpricedCalls !== next.quotas?.weekly?.unpricedCalls) return false; if (prev.quotas?.weekly?.resetTime !== next.quotas?.weekly?.resetTime) return false; const pPools = prev.quotas?.pools || []; const nPools = next.quotas?.pools || []; if (pPools.length !== nPools.length) return false; for (let i = 0; i < pPools.length; i++) { if ( pPools[i]?.poolKey !== nPools[i]?.poolKey || pPools[i]?.poolLabel !== nPools[i]?.poolLabel || pPools[i]?.usedPct !== nPools[i]?.usedPct || pPools[i]?.remainingPct !== nPools[i]?.remainingPct || pPools[i]?.reservedPct !== nPools[i]?.reservedPct || pPools[i]?.reservedLeaseCount !== nPools[i]?.reservedLeaseCount || pPools[i]?.resetTime !== nPools[i]?.resetTime || pPools[i]?.weeklyUsedPct !== nPools[i]?.weeklyUsedPct || pPools[i]?.weeklyRemainingPct !== nPools[i]?.weeklyRemainingPct || pPools[i]?.weeklyReservedPct !== nPools[i]?.weeklyReservedPct || pPools[i]?.weeklyReservedLeaseCount !== nPools[i]?.weeklyReservedLeaseCount || pPools[i]?.weeklyResetTime !== nPools[i]?.weeklyResetTime || pPools[i]?.cycle5h?.tokens !== nPools[i]?.cycle5h?.tokens || pPools[i]?.cycle5h?.costUsd !== nPools[i]?.cycle5h?.costUsd || pPools[i]?.cycle5h?.calls !== nPools[i]?.cycle5h?.calls || pPools[i]?.cycleWeekly?.tokens !== nPools[i]?.cycleWeekly?.tokens || pPools[i]?.cycleWeekly?.costUsd !== nPools[i]?.cycleWeekly?.costUsd || pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls || JSON.stringify(pPools[i]?.rateEstimate || null) !== JSON.stringify(nPools[i]?.rateEstimate || null) ) { return false; } } if ( JSON.stringify(prev.quotas?.weeklyCapacityEstimate || null) !== JSON.stringify(next.quotas?.weeklyCapacityEstimate || null) ) { return false; } const pConvs = prev.conversations || []; const nConvs = next.conversations || []; if (pConvs.length !== nConvs.length) return false; for (let i = 0; i < pConvs.length; i++) { if ( pConvs[i]?.cascadeId !== nConvs[i]?.cascadeId || pConvs[i]?.title !== nConvs[i]?.title || pConvs[i]?.status !== nConvs[i]?.status || pConvs[i]?.stepCount !== nConvs[i]?.stepCount || pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount || (pConvs[i]?.swarmCount || 0) !== (nConvs[i]?.swarmCount || 0) || (pConvs[i]?.swarmTitle || '') !== (nConvs[i]?.swarmTitle || '') || (pConvs[i]?.workspaceName || '') !== (nConvs[i]?.workspaceName || '') || pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount ) { return false; } } const pRunning = prev.runningConversations || []; const nRunning = next.runningConversations || []; if (pRunning.length !== nRunning.length) return false; for (let i = 0; i < pRunning.length; i++) { const pr = pRunning[i]; const nr = nRunning[i]; if ( pr?.cascadeId !== nr?.cascadeId || pr?.title !== nr?.title || pr?.isCurrentSelected !== nr?.isCurrentSelected || pr?.isMainRunning !== nr?.isMainRunning || pr?.subagentCount !== nr?.subagentCount || (pr?.swarmCount || 0) !== (nr?.swarmCount || 0) || pr?.runningSubagentCount !== nr?.runningSubagentCount || (pr?.runningSwarmCount || 0) !== (nr?.runningSwarmCount || 0) || pr?.mainActivity?.signature !== nr?.mainActivity?.signature || pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs ) { return false; } const pSubs = pr?.subagents || []; const nSubs = nr?.subagents || []; if (pSubs.length !== nSubs.length) return false; for (let j = 0; j < pSubs.length; j++) { if ( pSubs[j]?.cascadeId !== nSubs[j]?.cascadeId || pSubs[j]?.agentKind !== nSubs[j]?.agentKind || (pSubs[j]?.swarmState || '') !== (nSubs[j]?.swarmState || '') || pSubs[j]?.role !== nSubs[j]?.role || pSubs[j]?.isRunning !== nSubs[j]?.isRunning || pSubs[j]?.stepCount !== nSubs[j]?.stepCount || pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature || pSubs[j]?.liveActivity?.startedAtMs !== nSubs[j]?.liveActivity?.startedAtMs ) { return false; } } } return true; } function resetTelemetryForEndpointSwitch() { endpointSwitchEpoch += 1; latestRequestSeq += 1; latestConsumptionReqSeq += 1; latestConversationSwitchSeq += 1; lastReceivedSteps = null; inFlightTelemetryPoll = null; consecutivePollFailures = 0; consumptionCacheScopeSig = ''; abortSidecarApiKey('telemetry-poll'); abortSidecarApiKey('telemetry-force'); abortSidecarApiKey('consumption-range'); abortSidecarApiKey('consumption-presets'); abortSidecarApiKey('conversation-switch'); clearConsumptionRangeCache(); clearConversationViewCache(); if (feedbackTimer) { clearTimeout(feedbackTimer); feedbackTimer = null; } telemetryStore.setState({ selectedConversationId: '', telemetry: null, syncState: 'idle', }); } async function fetchTelemetry({ force = false } = {}) { if (!force && activeForceCount > 0) { return telemetryStore.getState().telemetry; } const overlay = isWindowOverlayMode(); if (overlay) { const st = telemetryStore.getState(); const liveRouteId = extractHostRouteCascadeId(); if (liveRouteId !== st.hostRouteConversationId) { const patch = { hostRouteConversationId: liveRouteId }; if (liveRouteId && st.selectedConversationId && st.selectedConversationId !== liveRouteId) { patch.selectedConversationId = ''; } telemetryStore.setState(patch); } } const current = telemetryStore.getState(); const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); if ( current.selectedTimeRange === 'cycle' && current.selectedCyclePool && current.selectedCyclePool !== 'all' ) { params.set('pool', current.selectedCyclePool); } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); } if (force) params.set('force', '1'); params.set('stepDetails', 'display'); if (force) { inFlightTelemetryPoll = null; return requestTelemetry(params, true); } const query = params.toString(); const bridge = overlay ? getWindowBridgeConfig() : null; const endpointId = bridge?.[WINDOW_BRIDGE_ENDPOINT_KEY] || LOCAL_ENDPOINT_ID; const existing = inFlightTelemetryPoll; if ( existing?.query === query && existing.port === bridge?.port && existing.token === bridge?.token && existing.endpointId === endpointId ) { return existing.promise; } const poll = { query, port: bridge?.port, token: bridge?.token, endpointId, promise: null }; poll.promise = requestTelemetry(params, false).finally(() => { if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null; }); inFlightTelemetryPoll = poll; return poll.promise; } function readDisplaySteps(payload) { const active = payload?.activeConversation; if (!payload?.stepRevision || !Array.isArray(active?.recentSteps)) return null; return { revision: payload.stepRevision, recentSteps: active.recentSteps, agentSteps: active.agents.map((agent) => agent.recentSteps === active.recentSteps ? undefined : agent.recentSteps), }; } async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; const reqSettingsRev = settingsRevision; const reqRange = String(params.get('range') || ''); const reqPool = String(params.get('pool') || 'all'); const reqStartMs = Number(params.get('startMs') || 0); const reqEndMs = Number(params.get('endMs') || 0); const startMs = Date.now(); if (force) { activeForceCount += 1; if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; } telemetryStore.setState({ syncState: 'syncing' }); } try { const previousSteps = lastReceivedSteps || readDisplaySteps(telemetryStore.getState().telemetry); params.set('stepRevision', previousSteps?.revision || ''); const payload = await callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: force ? 'telemetry-force' : 'telemetry-poll', }); const active = payload?.activeConversation; if (payload?.stepsUnchanged) { if (!active || !previousSteps || payload.stepRevision !== previousSteps.revision) { throw new Error('Telemetry step revision mismatch'); } active.recentSteps = previousSteps.recentSteps; active.agents.forEach((agent, index) => { const steps = previousSteps.agentSteps[index]; if (steps) agent.recentSteps = steps; }); } if (reqSeq !== latestRequestSeq) { return payload; } lastReceivedSteps = readDisplaySteps(payload); if (payload?.uiBundleVersion) { if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) { if ( !isWindowOverlayMode() && typeof window !== 'undefined' && typeof window.location?.reload === 'function' ) { window.location.reload(); return payload; } } activeBundleVersion = payload.uiBundleVersion; } consecutivePollFailures = 0; let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); syncConsumptionCacheScope(resolvedPayload); recordConversationViewToCache(resolvedPayload); if (resolvedPayload?.consumption) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: reqStartMs, customEndMs: reqEndMs, cyclePool: reqPool, }); } const latestSt = telemetryStore.getState(); const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); const activePoolPref = latestSt.selectedCyclePool || 'all'; const matchesCurrentRange = !reqRange || (reqRange === latestSt.selectedTimeRange && (reqRange !== 'cycle' || reqPool === activePoolPref) && (reqRange !== 'custom' || (reqStartMs === Number(latestSt.customStartMs || 0) && reqEndMs === Number(latestSt.customEndMs || 0)))); // 常规 2 秒轮询在途期间若用户已通过前端缓存瞬切到其他时间段,保留用户当前选中的范围不回跳, // 若后端 usageRevision 已推进则静默补发一次轻量范围校准。 let needsSilentRangeRevalidate = false; if (!force && !matchesCurrentRange && resolvedPayload?.consumption) { const activeKey = makeConsumptionRangeCacheKey( latestSt.selectedTimeRange, latestSt.customStartMs, latestSt.customEndMs, activePoolPref ); const cachedActive = consumptionRangeCache.get(activeKey); if (cachedActive) { resolvedPayload = applyCachedConsumptionSlice(resolvedPayload, cachedActive, incomingRev); if (incomingRev > 0 && cachedActive.revision !== incomingRev) { needsSilentRangeRevalidate = true; } } else if ( latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange && (latestSt.selectedTimeRange !== 'cycle' || (latestSt.telemetry?.consumption?.selectedRange?.pool || 'all') === activePoolPref) ) { resolvedPayload = { ...resolvedPayload, consumption: { ...resolvedPayload.consumption, selectedRange: latestSt.telemetry.consumption.selectedRange, session: latestSt.telemetry.consumption.session, account: latestSt.telemetry.consumption.account, trendSeries: latestSt.telemetry.consumption.trendSeries, sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown, topConversations: latestSt.telemetry.consumption.topConversations, topWorkspaces: latestSt.telemetry.consumption.topWorkspaces, }, modelBreakdown: latestSt.telemetry.modelBreakdown, }; } } if (force) { const elapsed = Date.now() - startMs; if (elapsed < 220) { await new Promise((r) => setTimeout(r, 220 - elapsed)); } if (reqSeq !== latestRequestSeq) { return resolvedPayload; } const finalForcePayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ telemetry: finalForcePayload, minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', }); feedbackTimer = setTimeout(() => { feedbackTimer = null; telemetryStore.setState({ syncState: 'idle' }); }, 1100); return finalForcePayload; } else { const isSame = isEquivalentTelemetry(latestSt.telemetry, resolvedPayload); const nextTelemetry = isSame ? latestSt.telemetry : resolvedPayload; telemetryStore.setState({ telemetry: nextTelemetry, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); if (needsSilentRangeRevalidate) { void fetchConsumptionRangeSlice({ range: latestSt.selectedTimeRange, customStartMs: latestSt.customStartMs, customEndMs: latestSt.customEndMs, cyclePool: latestSt.selectedCyclePool || 'all', }); } return resolvedPayload; } } catch (err) { if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null; consecutivePollFailures += 1; if (force || consecutivePollFailures >= 2 || !telemetryStore.getState().telemetry) { telemetryStore.setState({ syncState: 'error' }); } return null; } finally { if (force) { activeForceCount = Math.max(0, activeForceCount - 1); if (activeForceCount === 0 && loopActive && loopTickFn && !pollTimer) { pollTimer = setTimeout(loopTickFn, loopIntervalMs); } } } } async function fetchConsumptionRangeSlice({ range, customStartMs = 0, customEndMs = 0, cyclePool = 'all', } = {}) { const reqEpoch = endpointSwitchEpoch; const reqSeq = ++latestConsumptionReqSeq; const targetRange = String(range || 'today'); const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all'; const current = telemetryStore.getState(); const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('range', targetRange); if (targetRange === 'cycle' && targetPool !== 'all') { params.set('pool', targetPool); } if (targetRange === 'custom') { if (customStartMs > 0) params.set('startMs', String(customStartMs)); if (customEndMs > 0) params.set('endMs', String(customEndMs)); } params.set('scope', 'consumption'); try { const payload = await callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: 'consumption-range', }); if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null; if (payload.scope === 'consumption' && payload.consumption) { const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0); recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { customStartMs, customEndMs, cyclePool: targetPool, usageRevision: usageRev, }); if (reqSeq !== latestConsumptionReqSeq) return payload; const latestSt = telemetryStore.getState(); const stillMatches = latestSt.selectedTimeRange === targetRange && (targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) && (targetRange !== 'custom' || (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); if (!stillMatches) return payload; const prevTelemetry = latestSt.telemetry; if (prevTelemetry) { const nextTelemetry = { ...prevTelemetry, consumption: { ...(prevTelemetry.consumption || {}), ...payload.consumption, ...(usageRev > 0 ? { revision: usageRev } : {}), }, modelBreakdown: Array.isArray(payload.modelBreakdown) ? payload.modelBreakdown : prevTelemetry.modelBreakdown, }; if (!isEquivalentTelemetry(prevTelemetry, nextTelemetry)) { telemetryStore.setState({ telemetry: nextTelemetry }); } } return payload; } // 冷启动阶段后端尚无基础快照时会回退返回完整 telemetry,直接平滑复用现有状态合并 if (payload.consumption) { syncConsumptionCacheScope(payload); recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { customStartMs, customEndMs, }); if (reqSeq === latestConsumptionReqSeq) { const latestSt = telemetryStore.getState(); if (!isEquivalentTelemetry(latestSt.telemetry, payload)) { telemetryStore.setState({ telemetry: payload }); } } } return payload; } catch (err) { if (err?.name === 'AbortError') return null; return null; } } /** * 快速切换当前查看的会话: * - 命中前端 `conversationViewCache` 时,0ms 原子切换当前会话快照,并静默走轻量 `scope=conversation` 校准; * - 未命中缓存时直接走零 LS RPC、零全盘扫描的 `scope=conversation` 通道; * - 若后端提示该会话需要补读最新运行态或懒迁移字段(`needsBackgroundSync`),展示后再在后台静默补齐。 */ async function selectConversation( nextConvId, { hostRouteConversationId = undefined } = {} ) { const switchSeq = ++latestConversationSwitchSeq; latestRequestSeq += 1; inFlightTelemetryPoll = null; abortSidecarApiKey('telemetry-poll'); if (deferredConvSyncTimer) { clearTimeout(deferredConvSyncTimer); deferredConvSyncTimer = null; } const targetSelectedId = String(nextConvId || '').trim(); const prevSt = telemetryStore.getState(); const nextHostRouteId = hostRouteConversationId !== undefined ? String(hostRouteConversationId || '').trim() : prevSt.hostRouteConversationId; const effectiveConvId = targetSelectedId || nextHostRouteId || ''; const statePatch = { selectedConversationId: targetSelectedId, ...(hostRouteConversationId !== undefined ? { hostRouteConversationId: nextHostRouteId } : {}), }; const prevTelemetry = prevSt.telemetry; const lookupRootId = resolveCachedConversationRootId(prevTelemetry, effectiveConvId); const cachedEntry = lookupRootId ? conversationViewCache.get(lookupRootId) : null; const cachedSteps = cachedEntry && cachedEntry.stepRevision ? readDisplaySteps({ stepRevision: cachedEntry.stepRevision, activeConversation: cachedEntry.activeConversation, }) : null; if (cachedEntry && prevTelemetry) { const optimisticTelemetry = applyConversationSliceToTelemetry(prevTelemetry, cachedEntry); if (cachedSteps) { lastReceivedSteps = cachedSteps; } telemetryStore.setState({ ...statePatch, telemetry: optimisticTelemetry, }); } else { telemetryStore.setState(statePatch); } const current = telemetryStore.getState(); const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); if ( current.selectedTimeRange === 'cycle' && current.selectedCyclePool && current.selectedCyclePool !== 'all' ) { params.set('pool', current.selectedCyclePool); } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); } params.set('stepDetails', 'display'); params.set('stepRevision', cachedSteps?.revision || ''); params.set('scope', 'conversation'); const reqEpoch = endpointSwitchEpoch; const reqSettingsRev = settingsRevision; try { const payload = await callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: 'conversation-switch', }); if (!payload || typeof payload !== 'object' || reqEpoch !== endpointSwitchEpoch) return null; if (switchSeq !== latestConversationSwitchSeq) return payload; const latestSt = telemetryStore.getState(); const latestEffectiveId = String(latestSt.selectedConversationId || latestSt.hostRouteConversationId || '').trim(); if (latestEffectiveId !== effectiveConvId) return payload; const active = payload.activeConversation; if (payload.stepsUnchanged) { const stepsSource = (cachedSteps && payload.stepRevision === cachedSteps.revision ? cachedSteps : null) || (lastReceivedSteps && payload.stepRevision === lastReceivedSteps.revision ? lastReceivedSteps : null); if (!active || !stepsSource) { return fetchTelemetry({ force: false }); } active.recentSteps = stepsSource.recentSteps; active.agents.forEach((agent, index) => { const steps = stepsSource.agentSteps[index]; if (steps) agent.recentSteps = steps; }); } if (payload.scope === 'conversation' && active) { lastReceivedSteps = readDisplaySteps(payload) || lastReceivedSteps; recordConversationViewToCache(payload); const baseTelemetry = latestSt.telemetry; if (baseTelemetry) { const mergedTelemetry = applyConversationSliceToTelemetry(baseTelemetry, { activeConversation: active, activePool: payload.quotas?.activePool || null, weekly: payload.quotas?.weekly || null, sessionConsumption: payload.consumption?.session || null, sessionPresets: payload.consumption?.sessionPresets || null, stepRevision: payload.stepRevision || '', }); if (!isEquivalentTelemetry(baseTelemetry, mergedTelemetry)) { telemetryStore.setState({ telemetry: mergedTelemetry, minuteTick: Math.floor(Date.now() / 30000), }); } } else { return fetchTelemetry({ force: false }); } if (payload.needsBackgroundSync && loopActive && typeof setTimeout === 'function') { deferredConvSyncTimer = setTimeout(() => { deferredConvSyncTimer = null; if (switchSeq === latestConversationSwitchSeq && loopActive) { void fetchTelemetry({ force: false }); } }, 35); } return payload; } // 冷启动或全新未入缓存会话回退至完整载荷 const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev); syncConsumptionCacheScope(resolvedPayload); lastReceivedSteps = readDisplaySteps(resolvedPayload) || lastReceivedSteps; recordConversationViewToCache(resolvedPayload); if (resolvedPayload?.consumption) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: Number(current.customStartMs || 0), customEndMs: Number(current.customEndMs || 0), }); } if (!isEquivalentTelemetry(latestSt.telemetry, resolvedPayload)) { telemetryStore.setState({ telemetry: resolvedPayload, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); } return resolvedPayload; } catch (err) { if (err?.name === 'AbortError' || switchSeq !== latestConversationSwitchSeq) return null; return null; } } /** * 切换「用量统计」时间范围: * - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求); * - 若后台数据已更新则先 0ms 展示缓存,再静默发起轻量 `scope=consumption` 校准; * - 未命中缓存(如自定义时段或进页首 20ms 抢点)则直接走 `<5ms` 的 `scope=consumption` 通道。 */ function selectConsumptionTimeRange( nextRange, { customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {} ) { const targetRange = String(nextRange || 'today'); const prevSt = telemetryStore.getState(); const nextStartMs = targetRange === 'custom' ? Number(customStartMs !== undefined ? customStartMs : prevSt.customStartMs || 0) : prevSt.customStartMs; const nextEndMs = targetRange === 'custom' ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) : prevSt.customEndMs; const nextCyclePool = targetRange === 'cycle' ? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all') : prevSt.selectedCyclePool || 'all'; const statePatch = { selectedTimeRange: targetRange }; if (cyclePool !== undefined) { statePatch.selectedCyclePool = nextCyclePool; } if (targetRange === 'custom') { statePatch.customStartMs = nextStartMs; statePatch.customEndMs = nextEndMs; } const cacheKey = makeConsumptionRangeCacheKey( targetRange, nextStartMs, nextEndMs, targetRange === 'cycle' ? nextCyclePool : 'all' ); const cached = consumptionRangeCache.get(cacheKey); const prevTelemetry = prevSt.telemetry; if (cached && prevTelemetry) { const currentRev = Number(prevTelemetry.consumption?.revision || 0); const nextTelemetry = applyCachedConsumptionSlice( prevTelemetry, cached, currentRev > 0 ? currentRev : cached.revision ); telemetryStore.setState({ ...statePatch, telemetry: nextTelemetry }); if (currentRev > 0 && cached.revision === currentRev) { return Promise.resolve(nextTelemetry); } return fetchConsumptionRangeSlice({ range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, cyclePool: nextCyclePool, }); } telemetryStore.setState(statePatch); return fetchConsumptionRangeSlice({ range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, cyclePool: nextCyclePool, }); } function selectConsumptionCyclePool(nextPool = 'all') { return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') }); } /** * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 */ function prefetchConsumptionPresets() { const prevTelemetry = telemetryStore.getState().telemetry; const currentRev = Number(prevTelemetry?.consumption?.revision || 0); if (currentRev > 0 && lastPrefetchedUsageRevision === currentRev && hasAllPresetRangesCached(currentRev)) { return Promise.resolve(true); } if (inFlightPresetsPrefetch) { return inFlightPresetsPrefetch; } const current = telemetryStore.getState(); const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('scope', 'consumption-presets'); const reqEpoch = endpointSwitchEpoch; const task = callSidecarApi(`/api/telemetry?${params}`, { method: 'GET', abortKey: 'consumption-presets', }) .then((payload) => { if (reqEpoch !== endpointSwitchEpoch) return false; if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') { const rev = Number(payload.usageRevision || currentRev || 0); for (const [rangeKey, entry] of Object.entries(payload.ranges)) { if (!entry || typeof entry !== 'object') continue; recordConsumptionSliceToCache( { ...entry, revision: rev }, entry.modelBreakdown, { usageRevision: rev } ); } if (rev > 0) { lastPrefetchedUsageRevision = rev; } return true; } return false; }) .catch(() => false) .finally(() => { if (inFlightPresetsPrefetch === task) { inFlightPresetsPrefetch = null; } }); inFlightPresetsPrefetch = task; return task; } async function saveSettingsPatch(patch) { const safePatch = patch && typeof patch === 'object' ? { ...patch } : {}; if (Object.prototype.hasOwnProperty.call(safePatch, 'language')) { safePatch.language = normalizeI18nLanguage(safePatch.language); } if (Object.prototype.hasOwnProperty.call(safePatch, 'themeAccent')) { safePatch.themeAccent = normalizeClientThemeAccent(safePatch.themeAccent); } if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } if (Object.prototype.hasOwnProperty.call(safePatch, 'modernUi')) { const normModern = normalizeClientModernUi(safePatch.modernUi); safePatch.modernUi = normModern; safePatch.experimentalModernUi = normModern; } else if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalModernUi')) { safePatch.experimentalModernUi = normalizeClientModernUi(safePatch.experimentalModernUi); } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode); } if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) { safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine); } if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) { safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession); } if (Object.prototype.hasOwnProperty.call(safePatch, 'contextAgentMode')) { safePatch.contextAgentMode = normalizeClientContextAgentMode(safePatch.contextAgentMode); } if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepTurnRail')) { safePatch.showStepTurnRail = Boolean(safePatch.showStepTurnRail); } if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepAgentBadge')) { safePatch.showStepAgentBadge = Boolean(safePatch.showStepAgentBadge); } if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepSpeedColor')) { safePatch.showStepSpeedColor = Boolean(safePatch.showStepSpeedColor); } if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepFilterToolbar')) { safePatch.showStepFilterToolbar = Boolean(safePatch.showStepFilterToolbar); } if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalQuotaReservation')) { safePatch.experimentalQuotaReservation = normalizeClientExperimentalQuotaReservation( safePatch.experimentalQuotaReservation ); } if (Object.prototype.hasOwnProperty.call(safePatch, 'accountQuotaRefreshMinutes')) { safePatch.accountQuotaRefreshMinutes = normalizeClientAccountQuotaRefreshMinutes( safePatch.accountQuotaRefreshMinutes ); } if (Object.prototype.hasOwnProperty.call(safePatch, 'accountSwitchRiskAccepted')) { safePatch.accountSwitchRiskAccepted = Boolean(safePatch.accountSwitchRiskAccepted); } if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } if (Object.prototype.hasOwnProperty.call(safePatch, 'cliStatusLineSlots')) { safePatch.cliStatusLineSlots = normalizeClientCliStatusLineSlots(safePatch.cliStatusLineSlots); } if (Object.prototype.hasOwnProperty.call(safePatch, 'hoverModules')) { safePatch.hoverModules = normalizeClientHoverModules(safePatch.hoverModules); } if (Object.prototype.hasOwnProperty.call(safePatch, 'overviewModules')) { safePatch.overviewModules = normalizeClientOverviewModules(safePatch.overviewModules); } if (Object.prototype.hasOwnProperty.call(safePatch, 'overviewMetrics')) { safePatch.overviewMetrics = normalizeClientOverviewMetrics(safePatch.overviewMetrics); } if (Object.prototype.hasOwnProperty.call(safePatch, 'stepTableColumns')) { safePatch.stepTableColumns = normalizeClientStepColumns(safePatch.stepTableColumns); } if (Object.prototype.hasOwnProperty.call(safePatch, 'stepTokenComboFormat')) { safePatch.stepTokenComboFormat = normalizeClientStepTokenComboFormat( safePatch.stepTokenComboFormat ); } if (Object.prototype.hasOwnProperty.call(safePatch, 'modelDisplayMode')) { const normDisp = normalizeClientModelDisplayMode( safePatch.modelDisplayMode, safePatch.showUpstreamModel ); safePatch.modelDisplayMode = normDisp; safePatch.showUpstreamModel = normDisp !== 'short'; } else if (Object.prototype.hasOwnProperty.call(safePatch, 'showUpstreamModel')) { safePatch.showUpstreamModel = Boolean(safePatch.showUpstreamModel); safePatch.modelDisplayMode = safePatch.showUpstreamModel ? 'upstream' : 'short'; } if (Object.prototype.hasOwnProperty.call(safePatch, 'popoverWidthMode')) { safePatch.popoverWidthMode = normalizeClientPopoverWidthMode(safePatch.popoverWidthMode); } if (Object.prototype.hasOwnProperty.call(safePatch, 'popoverWidth')) { safePatch.popoverWidth = normalizeClientPopoverWidth(safePatch.popoverWidth); } if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowRiskAccepted')) { safePatch.contextWindowRiskAccepted = Boolean(safePatch.contextWindowRiskAccepted); } if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowMainEnabled')) { safePatch.contextWindowMainEnabled = Boolean(safePatch.contextWindowMainEnabled); } if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowSwarmEnabled')) { safePatch.contextWindowSwarmEnabled = Boolean(safePatch.contextWindowSwarmEnabled); } if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) { safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode); } if (Object.prototype.hasOwnProperty.call(safePatch, 'standalonePort')) { const numPort = Number(safePatch.standalonePort); safePatch.standalonePort = Number.isInteger(numPort) && numPort >= 1024 && numPort <= 65535 ? numPort : 0; } if (Object.prototype.hasOwnProperty.call(safePatch, 'windowMountMode')) { const normMount = normalizeClientWindowMountMode( safePatch.windowMountMode, safePatch.enableWindowOverlay ); safePatch.windowMountMode = normMount; safePatch.enableWindowOverlay = normMount !== 'sidebar'; } else if (Object.prototype.hasOwnProperty.call(safePatch, 'enableWindowOverlay')) { safePatch.enableWindowOverlay = Boolean(safePatch.enableWindowOverlay); safePatch.windowMountMode = safePatch.enableWindowOverlay ? 'dual' : 'sidebar'; } const myRev = ++settingsRevision; const prevTelemetry = telemetryStore.getState().telemetry; const patchKeys = Object.keys(safePatch); const prevKeyValues = new Map(); for (const key of patchKeys) { prevKeyValues.set(key, prevTelemetry?.settings?.[key]); pendingSettingsMutations.set(key, { rev: myRev, value: safePatch[key] }); } let optimisticTelemetry = null; if (prevTelemetry?.settings) { optimisticTelemetry = { ...prevTelemetry, settings: { ...prevTelemetry.settings, ...safePatch }, }; telemetryStore.setState({ telemetry: optimisticTelemetry }); } let res = null; try { res = await enqueueSettingsWrite(() => callSidecarApi('/api/settings', { method: 'POST', body: safePatch }) ); } catch (err) { const rollbackKeys = []; for (const key of patchKeys) { const activeEntry = pendingSettingsMutations.get(key); if (activeEntry?.rev === myRev) { pendingSettingsMutations.delete(key); rollbackKeys.push(key); } } if (rollbackKeys.length > 0) { const curTelemetry = telemetryStore.getState().telemetry; if (prevTelemetry && optimisticTelemetry && curTelemetry === optimisticTelemetry) { telemetryStore.setState({ telemetry: prevTelemetry }); } else if (curTelemetry?.settings) { const rolledBackSettings = { ...curTelemetry.settings }; for (const key of rollbackKeys) { if (recentCommittedSettings.has(key)) { rolledBackSettings[key] = recentCommittedSettings.get(key).value; } else { rolledBackSettings[key] = prevKeyValues.get(key); } } telemetryStore.setState({ telemetry: { ...curTelemetry, settings: rolledBackSettings }, }); } } throw err; } const serverSettings = extractReturnedSettings(res); const committedRev = ++settingsRevision; for (const key of patchKeys) { const activeEntry = pendingSettingsMutations.get(key); const committedVal = serverSettings && Object.prototype.hasOwnProperty.call(serverSettings, key) ? serverSettings[key] : safePatch[key]; if (activeEntry?.rev === myRev) { pendingSettingsMutations.delete(key); recentCommittedSettings.set(key, { rev: committedRev, value: committedVal }); } } const curTelemetry = telemetryStore.getState().telemetry; if (curTelemetry?.settings) { const nextSettings = serverSettings ? { ...curTelemetry.settings, ...serverSettings } : { ...curTelemetry.settings }; for (const [k, entry] of recentCommittedSettings.entries()) { if (entry.rev > committedRev) { nextSettings[k] = entry.value; } } for (const [k, entry] of pendingSettingsMutations.entries()) { nextSettings[k] = entry.value; } telemetryStore.setState({ telemetry: { ...curTelemetry, settings: nextSettings }, }); } const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k)); if ( Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode') || Object.prototype.hasOwnProperty.call(safePatch, 'weeklyTokenBudget') || Object.prototype.hasOwnProperty.call(safePatch, 'weeklyCostBudget') ) { clearConsumptionRangeCache(); clearConversationViewCache(); } if (needsTelemetryRecompute) { inFlightTelemetryPoll = null; void fetchTelemetry({ force: false }); } } async function saveModelContextWindow(modelId, option) { const myRev = ++settingsRevision; const result = await enqueueSettingsWrite(() => callSidecarApi('/api/context-window', { method: 'POST', body: { modelId, option }, }) ); const committedRev = ++settingsRevision; if (result?.modelContextWindows) { recentCommittedSettings.set('modelContextWindows', { rev: Math.max(myRev, committedRev), value: result.modelContextWindows, }); } const telemetry = telemetryStore.getState().telemetry; if (telemetry?.settings) { telemetryStore.setState({ telemetry: { ...telemetry, settings: { ...telemetry.settings, modelContextWindows: result.modelContextWindows }, }, }); } return result.modelContextWindows; } async function resetAllSettings() { const myRev = ++settingsRevision; const res = await enqueueSettingsWrite(() => callSidecarApi('/api/settings/reset', { method: 'POST', body: {} }) ); const committedRev = ++settingsRevision; const serverSettings = extractReturnedSettings(res); if (serverSettings) { for (const [key, val] of Object.entries(serverSettings)) { const pending = pendingSettingsMutations.get(key); if (!pending || pending.rev <= myRev) { pendingSettingsMutations.delete(key); recentCommittedSettings.set(key, { rev: committedRev, value: val }); } } } const prevTelemetry = telemetryStore.getState().telemetry; if (serverSettings && prevTelemetry) { const mergedSettings = { ...serverSettings }; for (const [k, entry] of pendingSettingsMutations.entries()) { mergedSettings[k] = entry.value; } telemetryStore.setState({ telemetry: { ...prevTelemetry, settings: mergedSettings, }, }); } inFlightTelemetryPoll = null; clearConsumptionRangeCache(); clearConversationViewCache(); void fetchTelemetry({ force: false }); return res; } async function rebuildTrajectoryCache() { const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} }); clearConsumptionRangeCache(); clearConversationViewCache(); await fetchTelemetry({ force: true }); return res; } async function triggerCloudSync() { const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} }); clearConsumptionRangeCache(); clearConversationViewCache(); await fetchTelemetry({ force: true }); return res; } async function triggerBridgeHostRelaunch() { try { return await callSidecarApi('/api/bridge/relaunch', { method: 'POST', body: {} }); } catch { // 兼容热更新后常驻父进程 main.mjs 尚未重注册新路由的场景,平滑回退至既有 POST /api/settings 通道转发至最新 Worker return callSidecarApi('/api/settings', { method: 'POST', body: { __bridgeAction: 'relaunch' }, }); } } async function triggerCliStatusLineAction(action) { const res = await callSidecarApi('/api/settings', { method: 'POST', body: { __cliStatusLineAction: String(action || 'force_install') }, }); const cur = telemetryStore.getState().telemetry; if (cur && res && typeof res === 'object') { const nextTelemetry = { ...cur, ...(res.cliStatusLine ? { cliStatusLine: res.cliStatusLine } : {}), ...(res.settings ? { settings: { ...cur.settings, ...res.settings } } : {}), }; telemetryStore.setState({ telemetry: nextTelemetry }); } void fetchTelemetry({ force: true }).catch(() => {}); return res; } async function fetchSessionMigrationCatalog() { try { return await callSidecarApi('/api/session-migration/catalog', { method: 'GET' }); } catch { return callSidecarApi('/api/settings', { method: 'POST', body: { __sessionMigrationAction: 'catalog' }, }); } } async function fetchQuotaReservationLog() { try { return await callSidecarApi('/api/quota-reservation/log', { method: 'GET' }); } catch { return callSidecarApi('/api/settings', { method: 'POST', body: { __quotaReservationAction: 'log' }, }); } } async function executeSessionMigration(payload) { let res; try { res = await callSidecarApi('/api/session-migration/migrate', { method: 'POST', body: payload || {}, }); } catch { res = await callSidecarApi('/api/settings', { method: 'POST', body: { __sessionMigrationAction: 'migrate', payload: payload || {} }, }); } if (res?.migratedCount > 0) { void fetchTelemetry({ force: true }).catch(() => {}); } return res; } async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { await new Promise((r) => setTimeout(r, 1100)); if ( !isWindowOverlayMode() && typeof window !== 'undefined' && typeof window.location?.reload === 'function' ) { window.location.reload(); return res; } } await fetchTelemetry({ force: true }); return res; } function startAsyncTelemetryLoop(intervalMs = 2000) { stopAsyncTelemetryLoop(); loopActive = true; loopIntervalMs = intervalMs; const resolveNextDelay = () => { if (isWindowOverlayMode() && typeof document !== 'undefined' && document.hidden) { return Math.max(loopIntervalMs, 8000); } return loopIntervalMs; }; const tick = async () => { pollTimer = null; if (!loopActive) return; await fetchTelemetry({ force: false }); if (!loopActive || activeForceCount > 0) return; if (!pollTimer) { pollTimer = setTimeout(tick, resolveNextDelay()); } }; loopTickFn = tick; tick(); return () => { stopAsyncTelemetryLoop(); }; } function stopAsyncTelemetryLoop() { loopActive = false; loopTickFn = null; if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; } if (feedbackTimer) { clearTimeout(feedbackTimer); feedbackTimer = null; } if (deferredConvSyncTimer) { clearTimeout(deferredConvSyncTimer); deferredConvSyncTimer = null; } } /** * 在遥测快照中解析宿主当前路由会话 ID(兼容顶层主会话 ID 与子代理/蜂群工蜂 ID)。 * * @param {object|null|undefined} telemetry * @param {string} rawRouteId * @returns {{ rootConv: object|null, childAgent: object|null, isChildRoute: boolean } | null} */ function resolveHostRouteMatch(telemetry, rawRouteId) { const routeLower = String(rawRouteId || '').trim().toLowerCase(); if (!routeLower || !telemetry) return null; const convs = Array.isArray(telemetry.conversations) ? telemetry.conversations : []; const actConv = telemetry.activeConversation || null; const directRoot = convs.find((c) => String(c?.cascadeId || '').toLowerCase() === routeLower) || (String(actConv?.cascadeId || '').toLowerCase() === routeLower ? actConv : null); if (directRoot) { return { rootConv: directRoot, childAgent: null, isChildRoute: false }; } const activeChild = (actConv?.agents || []).find( (a) => !a?.isMain && (String(a?.cascadeId || '').toLowerCase() === routeLower || String(a?.agentId || '').toLowerCase() === routeLower) ); if (activeChild) { const parentInList = convs.find( (c) => String(c?.cascadeId || '').toLowerCase() === String(actConv?.cascadeId || '').toLowerCase() ); return { rootConv: parentInList || actConv, childAgent: activeChild, isChildRoute: true, }; } const memberParent = convs.find( (c) => Array.isArray(c?.memberCascadeIds) && c.memberCascadeIds.some((id) => String(id || '').toLowerCase() === routeLower) ); if (memberParent) { return { rootConv: memberParent, childAgent: null, isChildRoute: true }; } return null; } /** * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 * 同时在客户端按需组装主代理与全部汇总的 `recentSteps`,避免后端 JSON 载荷重复序列化 2-3 倍步骤列表。 * * @param {object|null} telemetry * @param {string} [selectedAgentScope='all'] * @param {string} [ctxInspectorAgentId='auto'] * @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表 */ const scopedStepProjectionMemo = new WeakMap(); function resolveScopedConversation( telemetry, selectedAgentScope = 'all', ctxInspectorAgentId = 'auto', includeSteps = false ) { const rawActive = telemetry?.activeConversation; const active = rawActive || {}; const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : []; const hasSubagents = Boolean(active.hasSubagents && agents.length > 1); const subagents = agents.filter((a) => !a.isMain); let mainAgent = agents.find((a) => a.isMain) || active; let aggregated = active.aggregated || active; let resolvedAgents = agents; if (includeSteps) { let cached = rawActive && typeof rawActive === 'object' ? scopedStepProjectionMemo.get(rawActive) : null; if (!cached) { let nextMain = mainAgent; let nextAgents = agents; if (!Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) { nextMain = { ...mainAgent, recentSteps: active.recentSteps }; if (agents.includes(mainAgent)) { nextAgents = agents.map((ag) => (ag === mainAgent ? nextMain : ag)); } } let nextAgg = aggregated; if (hasSubagents && !Array.isArray(aggregated.recentSteps)) { const combined = []; for (const ag of nextAgents) { const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || []; for (const step of steps) combined.push(step); } combined.sort( (a, b) => (b.createdAtMs || 0) - (a.createdAtMs || 0) || (b.agentIndex || 0) - (a.agentIndex || 0) || (b.stepIndex || 0) - (a.stepIndex || 0) ); nextAgg = { ...aggregated, recentSteps: combined }; } cached = { mainAgent: nextMain, aggregated: nextAgg, agents: nextAgents }; if (rawActive && typeof rawActive === 'object') { scopedStepProjectionMemo.set(rawActive, cached); } } mainAgent = cached.mainAgent; aggregated = cached.aggregated; resolvedAgents = cached.agents; } if (!hasSubagents) { const singleScoped = includeSteps && !Array.isArray(active.recentSteps) && Array.isArray(mainAgent.recentSteps) ? { ...active, recentSteps: mainAgent.recentSteps } : active; return { hasSubagents: false, effectiveScope: 'main', effectiveCtxScope: 'main', agents: resolvedAgents, subagents: [], mainAgent, aggregated, scopedConv: singleScoped, ctxAgent: mainAgent, }; } const isValidSub = subagents.some((s) => s.agentId === selectedAgentScope); const effectiveScope = selectedAgentScope === 'main' ? 'main' : isValidSub ? selectedAgentScope : 'all'; const scopedConv = effectiveScope === 'all' ? aggregated : resolvedAgents.find((a) => a.agentId === effectiveScope) || mainAgent; let ctxAgent = scopedConv; let effectiveCtxScope = effectiveScope; if (effectiveScope === 'all') { if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') { const matched = resolvedAgents.find((a) => a.agentId === ctxInspectorAgentId); if (matched) { ctxAgent = matched; effectiveCtxScope = matched.agentId; } else { effectiveCtxScope = 'auto'; } } else { effectiveCtxScope = 'auto'; } if (effectiveCtxScope === 'auto') { ctxAgent = resolvedAgents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) || resolvedAgents.find((a) => !a.isSideQuestion && a.isRunning) || mainAgent; } } return { hasSubagents: true, effectiveScope, effectiveCtxScope, agents: resolvedAgents, subagents, mainAgent, aggregated, scopedConv, ctxAgent, }; } /** * 判断宿主系统是否为 macOS (`darwin`):优先读取后端遥测或双栖桥接注入的 `platform`,首帧缺省时回退 UA/平台标识。 * * @param {Record|null|undefined} telemetry * @returns {boolean} */ function isMacHostPlatform(telemetry) { const p = String(telemetry?.hostPlatform || readInjectedWindowBridge()?.platform || '') .trim() .toLowerCase(); if (p) return p === 'darwin'; if (typeof navigator !== 'undefined') { const ua = String(navigator.platform || navigator.userAgent || ''); return /\b(?:mac|darwin)\b|macintosh|mac\s*os/i.test(ua); } return false; } return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientAccountQuotaRefreshMinutes, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- const { TopLongPillNav } = (() => { /** * @fileoverview Top Long-Pill Navigation Bar (顶部唯一长药丸功能分割栏). * Splits the application into focused single-viewport views and animates * the active glider using GPU-accelerated translate3d. */ const TopLongPillNav = defineComponent({ name: 'TopLongPillNav', setup({ getProps, emit }) { const glider = h('div', { className: 'pill-glider', 'aria-hidden': 'true' }); const navEl = h( 'nav', { className: 'long-pill-nav', role: 'tablist', 'aria-label': '主功能视图分割导航', }, [glider] ); const tabButtons = new Map(); function selectValue(nextVal) { const current = getProps().modelValue; if (nextVal !== current) { emit('update:modelValue', nextVal); } } function syncTabs() { const { items = [], modelValue } = getProps(); patchStyleVar(navEl, '--pill-count', Math.max(1, items.length)); const validValues = new Set(items.map((it) => it.value)); for (const [val, entry] of tabButtons.entries()) { if (!validValues.has(val)) { if (entry.btn?.parentNode === navEl) { navEl.removeChild(entry.btn); } tabButtons.delete(val); } } let activeIdx = 0; items.forEach((item, index) => { if (item.value === modelValue) { activeIdx = index; } let entry = tabButtons.get(item.value); if (!entry) { const iconEl = item.icon ? createSvgIcon(item.icon, { size: 14 }) : null; const labelEl = h('span', { className: 'pill-tab-label', text: item.label }); const badgeEl = h('span', { className: 'pill-tab-badge', hidden: true }); const btn = h( 'button', { type: 'button', role: 'tab', className: 'pill-tab', dataset: { pillValue: item.value }, onClick: () => selectValue(item.value), onKeydown: (e) => { if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { e.preventDefault(); const curItems = getProps().items || []; if (!curItems.length) return; const curIndex = Math.max( 0, curItems.findIndex((it) => it.value === item.value) ); const delta = e.key === 'ArrowRight' ? 1 : -1; const nextIndex = (curIndex + delta + curItems.length) % curItems.length; const target = curItems[nextIndex]; if (target) { selectValue(target.value); tabButtons.get(target.value)?.btn?.focus(); } } }, }, [iconEl, labelEl, badgeEl] ); entry = { btn, labelEl, badgeEl }; tabButtons.set(item.value, entry); navEl.appendChild(btn); } patchText(entry.labelEl, item.label); const hasBadge = item.badge !== undefined && item.badge !== null && item.badge !== ''; if (hasBadge) { patchAttr(entry.badgeEl, 'hidden', false); patchText(entry.badgeEl, `(${item.badge})`); } else { patchAttr(entry.badgeEl, 'hidden', true); } patchAttr(entry.btn, 'title', hasBadge ? `${item.label} (${item.badge})` : item.label); const isActive = item.value === modelValue; patchClasses(entry.btn, { 'is-active': isActive }); patchAttr(entry.btn, 'aria-selected', isActive ? 'true' : 'false'); patchAttr(entry.btn, 'tabindex', isActive ? '0' : '-1'); }); patchStyleVar(navEl, '--active-index', activeIdx); } syncTabs(); return { el: navEl, refs: { glider, tabButtons }, onPropsChange: syncTabs, getValue: () => getProps().modelValue, }; }, }); return { TopLongPillNav }; })(); // --- src/components/ui/SearchInput.js --- const { createSearchInput } = (() => { /** * @fileoverview Shared compact search input bar (`SearchInput.js`) with leading search icon * and conditional clear button, reused across `CustomSelect`, `StepsDetailView`, and `SessionMigrationCard`. */ /** * Creates a unified search input box while preserving caller-specific modifier classes. * * @param {{ * wrapClassName?: string, * iconClassName?: string, * inputClassName?: string, * clearClassName?: string, * placeholder?: string, * ariaLabel?: string, * clearAriaLabel?: string, * hidden?: boolean, * stopClickPropagation?: boolean, * closeIconSize?: number, * onInput?: (value: string, event: any) => void, * onClear?: (event: any) => void, * onKeydown?: (event: any) => void, * }} [options={}] */ function createSearchInput({ wrapClassName = '', iconClassName = '', inputClassName = '', clearClassName = '', placeholder = '', ariaLabel = '', clearAriaLabel = '', hidden = false, stopClickPropagation = false, closeIconSize = 10, onInput = null, onClear = null, onKeydown = null, } = {}) { const iconEl = createSvgIcon('search', { size: 12, className: ['ui-search-icon', iconClassName].filter(Boolean).join(' '), }); const inputEl = h('input', { type: 'text', className: ['ui-search-input', inputClassName].filter(Boolean).join(' '), autocomplete: 'off', spellcheck: 'false', placeholder, ...(ariaLabel ? { 'aria-label': ariaLabel } : {}), ...(stopClickPropagation ? { onClick: (e) => e.stopPropagation?.() } : {}), onInput: (e) => { const val = String(e?.target?.value ?? inputEl.value ?? ''); patchAttr(clearBtnEl, 'hidden', !val.trim()); onInput?.(val, e); }, ...(onKeydown ? { onKeydown } : {}), }); const clearBtnEl = h( 'button', { type: 'button', className: ['ui-search-clear', clearClassName].filter(Boolean).join(' '), hidden: true, ...(clearAriaLabel ? { 'aria-label': clearAriaLabel } : {}), onClick: (e) => { if (stopClickPropagation) e?.stopPropagation?.(); inputEl.value = ''; patchAttr(clearBtnEl, 'hidden', true); if (onClear) { onClear(e); } else { onInput?.('', e); inputEl.focus?.(); } }, }, [createSvgIcon('close', { size: closeIconSize })] ); const wrapEl = h( 'div', { className: ['ui-search-wrap', wrapClassName].filter(Boolean).join(' '), ...(hidden ? { hidden: true } : {}), ...(stopClickPropagation ? { onClick: (e) => e.stopPropagation?.() } : {}), }, [iconEl, inputEl, clearBtnEl] ); return { el: wrapEl, iconEl, inputEl, clearBtnEl, getValue() { return String(inputEl.value || ''); }, setValue(nextVal) { const str = String(nextVal ?? ''); inputEl.value = str; patchAttr(clearBtnEl, 'hidden', !str.trim()); }, syncLabels({ placeholder: nextPlaceholder, ariaLabel: nextAria, clearAriaLabel: nextClearAria } = {}) { if (nextPlaceholder !== undefined) patchAttr(inputEl, 'placeholder', nextPlaceholder); if (nextAria !== undefined) patchAttr(inputEl, 'aria-label', nextAria); if (nextClearAria !== undefined) patchAttr(clearBtnEl, 'aria-label', nextClearAria); }, focus() { inputEl.focus?.(); }, }; } return { createSearchInput }; })(); // --- src/components/ui/CustomSelect.js --- const { filterSelectOptionsByQuery, CustomSelect } = (() => { /** * @fileoverview Bespoke CustomSelect dropdown component replacing native with custom SVG step controls, * keyboard ArrowUp/ArrowDown (+Shift 10x), and min/max clamping. */ const CustomNumberInput = defineComponent({ name: 'CustomNumberInput', setup({ getProps, setProps, emit, onCleanup }) { function clampValue(raw) { const { min = -Infinity, max = Infinity, precision = 0 } = getProps(); const num = Number(raw); if (!Number.isFinite(num)) { return Number(getProps().modelValue ?? (Number.isFinite(min) ? min : 0)); } const clamped = Math.min(max, Math.max(min, num)); return precision > 0 ? Number(clamped.toFixed(precision)) : Math.round(clamped); } function applyStep(direction, multiplier = 1) { const { step = 1, modelValue = 0 } = getProps(); const current = Number(modelValue) || 0; const next = clampValue(current + direction * step * multiplier); syncFieldDisplay(next); if (next !== current) { setProps({ modelValue: next }); emit('update:modelValue', next); } } const decBtn = h( 'button', { type: 'button', className: 'num-step-btn', 'aria-label': t('ui.num.decrease'), onClick: (e) => { e.preventDefault(); applyStep(-1, e.shiftKey ? 10 : 1); }, }, [createSvgIcon('minus', { size: 12 })] ); const incBtn = h( 'button', { type: 'button', className: 'num-step-btn', 'aria-label': t('ui.num.increase'), onClick: (e) => { e.preventDefault(); applyStep(1, e.shiftKey ? 10 : 1); }, }, [createSvgIcon('plus', { size: 12 })] ); const textField = h('input', { type: 'text', inputmode: 'decimal', role: 'spinbutton', className: 'num-field', onKeydown: (e) => { if (e.key === 'ArrowUp') { e.preventDefault(); applyStep(1, e.shiftKey ? 10 : 1); } else if (e.key === 'ArrowDown') { e.preventDefault(); applyStep(-1, e.shiftKey ? 10 : 1); } else if (e.key === 'Enter') { e.preventDefault(); commitManualInput(); } }, onChange: () => commitManualInput(), onBlur: () => commitManualInput(), }); function commitManualInput() { const raw = String(textField.value ?? '').trim(); if (!raw || !/\d/.test(raw)) { syncFieldDisplay(getProps().modelValue); return; } const cleaned = raw.replace(/[^0-9.-]/g, ''); const parsed = Number(cleaned); if (!Number.isFinite(parsed)) { syncFieldDisplay(getProps().modelValue); return; } const next = clampValue(parsed); const prev = Number(getProps().modelValue); syncFieldDisplay(next); if (next !== prev) { setProps({ modelValue: next }); emit('update:modelValue', next); } } function syncFieldDisplay(val = getProps().modelValue) { const { min, max, ariaLabel } = getProps(); const normalized = clampValue(val); if (textField.value !== String(normalized)) { textField.value = String(normalized); } patchAttr(textField, 'aria-valuenow', normalized); if (ariaLabel) patchAttr(textField, 'aria-label', ariaLabel); if (Number.isFinite(min)) patchAttr(textField, 'aria-valuemin', min); if (Number.isFinite(max)) patchAttr(textField, 'aria-valuemax', max); } const rootEl = h('div', { className: 'number-input' }, [decBtn, textField, incBtn]); const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { patchAttr(decBtn, 'aria-label', t('ui.num.decrease')); patchAttr(incBtn, 'aria-label', t('ui.num.increase')); }, { immediate: false } ); onCleanup(unsubI18n); syncFieldDisplay(); return { el: rootEl, refs: { decBtn, incBtn, textField }, onPropsChange: () => syncFieldDisplay(), methods: { commit: () => commitManualInput(), }, }; }, }); return { CustomNumberInput }; })(); // --- src/components/ui/CustomDateTimePicker.js --- const { CustomDateTimePicker } = (() => { /** * @fileoverview Bespoke CustomDateTimePicker calendar matrix and hour/minute stepper. * Replaces native and emits Unix epoch ms. */ const WEEKDAY_KEYS = [ 'ui.dt.wdayMon', 'ui.dt.wdayTue', 'ui.dt.wdayWed', 'ui.dt.wdayThu', 'ui.dt.wdayFri', 'ui.dt.wdaySat', 'ui.dt.wdaySun', ]; function buildCalendarDays(viewYear, viewMonth, selectedDate) { const firstDay = new Date(viewYear, viewMonth, 1); // Convert Sunday=0..Saturday=6 into Monday=0..Sunday=6 const startOffset = (firstDay.getDay() + 6) % 7; const cells = []; for (let i = 0; i < 42; i++) { const cellDate = new Date(viewYear, viewMonth, 1 - startOffset + i); const y = cellDate.getFullYear(); const m = cellDate.getMonth(); const d = cellDate.getDate(); const isCurrentMonth = m === viewMonth; const isSelected = selectedDate && selectedDate.getFullYear() === y && selectedDate.getMonth() === m && selectedDate.getDate() === d; cells.push({ key: `${y}-${m}-${d}`, year: y, month: m, day: d, isCurrentMonth, isSelected, }); } return cells; } const CustomDateTimePicker = defineComponent({ name: 'CustomDateTimePicker', setup({ getProps, emit, onCleanup }) { let isOpen = false; const initialDate = new Date(getProps().modelValue || Date.now()); let viewYear = initialDate.getFullYear(); let viewMonth = initialDate.getMonth(); const triggerText = h('span', { className: 'text-mono' }); const triggerBtn = h( 'button', { type: 'button', className: 'dt-trigger', 'aria-expanded': 'false', onClick: (e) => { e.stopPropagation(); togglePopover(!isOpen); }, }, [createSvgIcon('calendar', { size: 13 }), triggerText] ); const monthTitle = h('span', { className: 'text-mono' }); const prevMonthBtn = h( 'button', { type: 'button', className: 'icon-btn', 'aria-label': t('ui.dt.prevMonth'), onClick: (e) => { e.stopPropagation(); viewMonth -= 1; if (viewMonth < 0) { viewMonth = 11; viewYear -= 1; } renderCalendar(); }, }, [createSvgIcon('chevron-left', { size: 12 })] ); const nextMonthBtn = h( 'button', { type: 'button', className: 'icon-btn', 'aria-label': t('ui.dt.nextMonth'), onClick: (e) => { e.stopPropagation(); viewMonth += 1; if (viewMonth > 11) { viewMonth = 0; viewYear += 1; } renderCalendar(); }, }, [createSvgIcon('chevron-right', { size: 12 })] ); const navBar = h('div', { className: 'dt-nav' }, [prevMonthBtn, monthTitle, nextMonthBtn]); const weekdaySpans = WEEKDAY_KEYS.map((key) => h('span', { className: 'dt-weekday', text: t(key) }) ); const weekdayRow = h('div', { className: 'dt-weekdays' }, weekdaySpans); const daysGrid = h('div', { className: 'dt-days' }); const hourValSpan = h('strong', { className: 'text-mono', text: '00' }); const minValSpan = h('strong', { className: 'text-mono', text: '00' }); function adjustTime(part, delta) { const cur = new Date(getProps().modelValue || Date.now()); if (part === 'hour') { cur.setHours(cur.getHours() + delta); } else { cur.setMinutes(cur.getMinutes() + delta); } const nextMs = cur.getTime(); viewYear = cur.getFullYear(); viewMonth = cur.getMonth(); emit('update:modelValue', nextMs); } const hourMinLabelEl = h('span', { className: 'text-muted', text: t('ui.dt.hourMinute') }); const timeRow = h('div', { className: 'dt-time-row' }, [ hourMinLabelEl, h('div', { className: 'dt-time-controls' }, [ h('div', { className: 'dt-mini-step' }, [ h('button', { type: 'button', className: 'dt-mini-btn', text: '-', onClick: (e) => { e.stopPropagation(); adjustTime('hour', -1); }, }), hourValSpan, h('button', { type: 'button', className: 'dt-mini-btn', text: '+', onClick: (e) => { e.stopPropagation(); adjustTime('hour', 1); }, }), ]), h('span', { text: ':' }), h('div', { className: 'dt-mini-step' }, [ h('button', { type: 'button', className: 'dt-mini-btn', text: '-', onClick: (e) => { e.stopPropagation(); adjustTime('minute', -5); }, }), minValSpan, h('button', { type: 'button', className: 'dt-mini-btn', text: '+', onClick: (e) => { e.stopPropagation(); adjustTime('minute', 5); }, }), ]), ]), ]); const popoverEl = h( 'div', { className: 'dt-popover', hidden: true, }, [navBar, weekdayRow, daysGrid, timeRow] ); const rootEl = h('div', { className: 'datetime-picker' }, [triggerBtn, popoverEl]); function positionPopover() { if (!isOpen) return; positionAnchoredPopup(rootEl, triggerBtn, popoverEl, { margin: 6, gap: 4, maxHeight: 0, minFlipSpace: 260, }); } let boundReposition = false; function handleViewportChange() { if (!isOpen) return; positionPopover(); } function setRepositionListeners(active) { if (active === boundReposition) return; boundReposition = active; if (typeof window !== 'undefined' && window.addEventListener) { if (active) { window.addEventListener('resize', handleViewportChange, { passive: true }); window.addEventListener('scroll', handleViewportChange, true); } else { window.removeEventListener('resize', handleViewportChange); window.removeEventListener('scroll', handleViewportChange, true); } } } function togglePopover(nextOpen) { isOpen = Boolean(nextOpen); patchAttr(popoverEl, 'hidden', !isOpen); patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); setRepositionListeners(isOpen); if (isOpen) { const cur = new Date(getProps().modelValue || Date.now()); viewYear = cur.getFullYear(); viewMonth = cur.getMonth(); renderCalendar(); positionPopover(); } } function selectDay(cell) { const cur = new Date(getProps().modelValue || Date.now()); cur.setFullYear(cell.year, cell.month, cell.day); const nextMs = cur.getTime(); viewYear = cell.year; viewMonth = cell.month; emit('update:modelValue', nextMs); } function renderCalendar() { const cur = new Date(getProps().modelValue || Date.now()); const pad = (n) => String(n).padStart(2, '0'); patchText(monthTitle, `${viewYear}-${pad(viewMonth + 1)}`); patchText(hourValSpan, pad(cur.getHours())); patchText(minValSpan, pad(cur.getMinutes())); const cells = buildCalendarDays(viewYear, viewMonth, cur); patchKeyedList(daysGrid, cells, { keyFn: (c) => c.key, sigFn: (c) => `${c.key}:${c.isCurrentMonth}:${c.isSelected}`, createRow: (cell) => { const btn = h('button', { type: 'button', className: 'dt-day', onClick: (e) => { e.stopPropagation(); selectDay(cell); }, }); return { el: btn, refs: {} }; }, updateRow: (_refs, cell, _idx, el) => { patchText(el, cell.day); patchClasses(el, { 'is-selected': cell.isSelected, 'is-outside': !cell.isCurrentMonth, }); patchAttr(el, 'data-date-key', cell.key); }, }); } function syncDisplay() { const ms = Number(getProps().modelValue || Date.now()); patchText(triggerText, formatCompactDateTime(ms)); if (isOpen) { renderCalendar(); } } const handleDocClick = (e) => { if (isOpen && !isEventInside(e, rootEl)) { togglePopover(false); } }; if (typeof document !== 'undefined' && document.addEventListener) { document.addEventListener('click', handleDocClick, true); onCleanup(() => { setRepositionListeners(false); document.removeEventListener('click', handleDocClick, true); }); } else { onCleanup(() => setRepositionListeners(false)); } function syncI18nLabels() { patchAttr(prevMonthBtn, 'aria-label', t('ui.dt.prevMonth')); patchAttr(nextMonthBtn, 'aria-label', t('ui.dt.nextMonth')); patchText(hourMinLabelEl, t('ui.dt.hourMinute')); for (let i = 0; i < WEEKDAY_KEYS.length; i += 1) { patchText(weekdaySpans[i], t(WEEKDAY_KEYS[i])); } } const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { syncI18nLabels(); syncDisplay(); }, { immediate: false } ); onCleanup(unsubI18n); syncDisplay(); return { el: rootEl, refs: { triggerBtn, triggerText, popoverEl, daysGrid, hourValSpan, minValSpan }, onPropsChange: syncDisplay, }; }, }); return { CustomDateTimePicker }; })(); // --- src/components/ui/CustomScrollbar.js --- const { CustomScrollbar } = (() => { /** * @fileoverview Bespoke custom scrollbar component (零原生滚动条). * Hides native OS scrollbars completely and renders a precision 4px floating * rail + GPU-translated thumb with drag and track-jump support. */ const CustomScrollbar = defineComponent({ name: 'CustomScrollbar', setup({ getProps, onCleanup }) { const contentEl = getProps().contentEl || h('div'); contentEl.classList.add('custom-scroll-content'); const thumbEl = h('div', { className: 'scrollbar-thumb' }); const railEl = h( 'div', { className: 'scrollbar-rail is-inactive', 'aria-hidden': 'true', }, [thumbEl] ); const hostEl = h( 'div', { className: `custom-scroll-host ${getProps().className || ''}`.trim(), }, [contentEl, railEl] ); let isDragging = false; let dragStartY = 0; let dragStartScrollTop = 0; let scrollRafId = 0; function syncThumb() { const scrollHeight = Number(contentEl.scrollHeight || 0); const clientHeight = Number(contentEl.clientHeight || 0); const scrollTop = Number(contentEl.scrollTop || 0); const overflow = scrollHeight - clientHeight; if (overflow <= 1 || clientHeight <= 0) { patchClasses(railEl, { 'is-inactive': true }); patchStyleVar(thumbEl, '--thumb-h', '0px'); patchStyleVar(thumbEl, '--thumb-y', '0px'); return; } patchClasses(railEl, { 'is-inactive': false }); const railHeight = Math.max(24, clientHeight - 4); const thumbHeight = Math.max(24, Math.round((clientHeight / scrollHeight) * railHeight)); const maxThumbTop = Math.max(0, railHeight - thumbHeight); const ratio = Math.max(0, Math.min(1, scrollTop / overflow)); const thumbTop = Math.round(ratio * maxThumbTop); patchStyleVar(thumbEl, '--thumb-h', `${thumbHeight}px`); patchStyleVar(thumbEl, '--thumb-y', `${thumbTop}px`); } function onContentScroll() { if (isDragging || typeof requestAnimationFrame !== 'function') { syncThumb(); return; } if (scrollRafId) return; scrollRafId = requestAnimationFrame(() => { scrollRafId = 0; syncThumb(); }); } function onDocMouseMove(e) { if (!isDragging) return; const clientHeight = Number(contentEl.clientHeight || 0); const scrollHeight = Number(contentEl.scrollHeight || 0); const overflow = scrollHeight - clientHeight; if (overflow <= 1) return; const railHeight = Math.max(24, clientHeight - 4); const thumbHeight = Math.max(24, Math.round((clientHeight / scrollHeight) * railHeight)); const maxThumbTop = Math.max(1, railHeight - thumbHeight); const deltaY = (e.clientY || 0) - dragStartY; const scrollDelta = (deltaY / maxThumbTop) * overflow; contentEl.scrollTop = Math.max(0, Math.min(overflow, dragStartScrollTop + scrollDelta)); syncThumb(); } function onDocMouseUp() { if (!isDragging) return; isDragging = false; patchClasses(railEl, { 'is-dragging': false }); if (typeof document !== 'undefined') { document.removeEventListener('mousemove', onDocMouseMove); document.removeEventListener('mouseup', onDocMouseUp); } } thumbEl.addEventListener('mousedown', (e) => { e.preventDefault(); e.stopPropagation(); isDragging = true; dragStartY = e.clientY || 0; dragStartScrollTop = Number(contentEl.scrollTop || 0); patchClasses(railEl, { 'is-dragging': true }); if (typeof document !== 'undefined') { document.addEventListener('mousemove', onDocMouseMove); document.addEventListener('mouseup', onDocMouseUp); } }); railEl.addEventListener('mousedown', (e) => { if (e.target === thumbEl) return; e.preventDefault(); const rect = railEl.getBoundingClientRect ? railEl.getBoundingClientRect() : null; if (!rect || rect.height <= 0) return; const clickOffset = (e.clientY || 0) - rect.top; const ratio = Math.max(0, Math.min(1, clickOffset / rect.height)); const overflow = Math.max(0, (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0)); contentEl.scrollTop = Math.round(ratio * overflow); syncThumb(); }); contentEl.addEventListener('scroll', onContentScroll, { passive: true }); hostEl.addEventListener('mouseenter', syncThumb); let resizeObserver = null; if (typeof ResizeObserver !== 'undefined') { resizeObserver = new ResizeObserver(() => syncThumb()); resizeObserver.observe(hostEl); resizeObserver.observe(contentEl); } syncThumb(); onCleanup(() => { onDocMouseUp(); if (scrollRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(scrollRafId); scrollRafId = 0; } contentEl.removeEventListener('scroll', onContentScroll); hostEl.removeEventListener('mouseenter', syncThumb); if (resizeObserver) { resizeObserver.disconnect(); } }); let pendingSync = false; function scheduleSyncThumb() { if (typeof queueMicrotask === 'function') { if (pendingSync) return; pendingSync = true; queueMicrotask(() => { pendingSync = false; syncThumb(); }); } else { syncThumb(); } } return { el: hostEl, refs: { contentEl, railEl, thumbEl }, onPropsChange: scheduleSyncThumb, methods: { refresh() { scheduleSyncThumb(); }, }, }; }, }); return { CustomScrollbar }; })(); // --- src/components/ui/SegmentedControl.js --- const { SegmentedControl } = (() => { /** * @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, onCleanup }) { const gliderEl = h('div', { className: 'seg-glider', 'aria-hidden': 'true' }); const rootEl = h( 'div', { className: 'segmented', role: 'group', 'aria-label': getProps().ariaLabel || t('ui.seg.defaultAria'), }, [gliderEl] ); const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { patchAttr(rootEl, 'aria-label', getProps().ariaLabel || t('ui.seg.defaultAria')); }, { immediate: false } ); onCleanup(unsubI18n); 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, 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(); 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?.(); } } }, }); 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: { gliderEl, refreshGlider: syncGliderGeometry }, onPropsChange: syncSegments, getValue: () => getProps().modelValue, }; }, }); return { SegmentedControl }; })(); // --- src/components/ui/ToggleSwitch.js --- const { ToggleSwitch } = (() => { /** * @fileoverview Zero-ResizeObserver binary toggle switch (`ToggleSwitch.js`). * Uses a pure-CSS 2-column grid glider (`--seg-active-idx`) so Settings tabs do not * instantiate 10+ ResizeObservers or force synchronous layout measurements for simple * on/off or show/hide switches, while preserving `.segmented` / `.seg-btn` semantics. */ const TOGGLE_PRESET_DEFS = Object.freeze({ enable: Object.freeze([ { value: 'on', labelKey: 'settings.str.on' }, { value: 'off', labelKey: 'settings.str.off' }, ]), visibility: Object.freeze([ { value: 'show', labelKey: 'settings.str.show' }, { value: 'hide', labelKey: 'settings.str.hide' }, ]), modernUi: Object.freeze([ { value: 'on', labelKey: 'settings.gen.modernUiOn' }, { value: 'off', labelKey: 'settings.gen.modernUiOff' }, ]), }); function resolveToggleOptions(props) { if (Array.isArray(props.options) && props.options.length === 2) { return props.options; } const defs = TOGGLE_PRESET_DEFS[props.preset] || TOGGLE_PRESET_DEFS.enable; return [ { value: defs[0].value, label: t(defs[0].labelKey) }, { value: defs[1].value, label: t(defs[1].labelKey) }, ]; } const ToggleSwitch = defineComponent({ name: 'ToggleSwitch', setup({ getProps, setProps, emit, onCleanup }) { const gliderEl = h('div', { className: 'seg-glider is-ready', 'aria-hidden': 'true' }); const btns = [0, 1].map((slotIdx) => h('button', { type: 'button', className: 'seg-btn', onClick: (e) => { e.stopPropagation(); const opts = resolveToggleOptions(getProps()); const opt = opts[slotIdx]; if (opt) selectValue(opt.value); }, onKeydown: (e) => { if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { e.preventDefault(); const opts = resolveToggleOptions(getProps()); const nextIdx = slotIdx === 0 ? 1 : 0; const targetOpt = opts[nextIdx]; if (targetOpt) { selectValue(targetOpt.value); btns[nextIdx]?.focus?.(); } } }, }) ); const rootEl = h( 'div', { className: 'segmented segmented--binary has-glider toggle-switch', role: 'group', 'aria-label': getProps().ariaLabel || t('ui.seg.defaultAria'), }, [gliderEl, btns[0], btns[1]] ); function selectValue(nextVal) { if (getProps().modelValue !== nextVal) { setProps({ modelValue: nextVal }); emit('update:modelValue', nextVal); } } function syncToggle() { const props = getProps(); const opts = resolveToggleOptions(props); const aria = props.ariaLabelKey ? t(props.ariaLabelKey) : props.ariaLabel || t('ui.seg.defaultAria'); patchAttr(rootEl, 'aria-label', aria); let activeIdx = 0; for (let i = 0; i < 2; i += 1) { const opt = opts[i]; const btn = btns[i]; const active = opt.value === props.modelValue; if (active) activeIdx = i; patchText(btn, opt.label); patchClasses(btn, { 'is-active': active }); patchAttr(btn, 'aria-pressed', active ? 'true' : 'false'); patchAttr(btn, 'data-seg-value', opt.value); } patchStyleVar(rootEl, '--seg-active-idx', String(activeIdx)); } const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { syncToggle(); }, { immediate: false } ); onCleanup(unsubI18n); syncToggle(); return { el: rootEl, onPropsChange: syncToggle, methods: { setValue(val) { setProps({ modelValue: val }); }, setOptions(options) { setProps({ options }); }, refreshGeometry() {}, }, }; }, }); return { ToggleSwitch }; })(); // --- src/components/ui/ContextSegmentMeter.js --- const { ContextSegmentMeter } = (() => { /** * @fileoverview 10-channel segmented context window progress bar updated via * CSS custom variables against the current model's automatic compaction baseline, * dynamically ordered from largest to smallest segment. */ const SEGMENT_DEFS = [ { key: 'assistant', labelKey: 'ctx.ch.assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) }, { key: 'toolResults', labelKey: 'ctx.ch.toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) }, { key: 'userInput', labelKey: 'ctx.ch.userInput', cls: 'seg-user-input', getVal: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), }, { key: 'subagent', labelKey: 'ctx.ch.subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) }, { key: 'checkpoint', labelKey: 'ctx.ch.checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) }, { key: 'systemPrompt', labelKey: 'ctx.ch.systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) }, { key: 'systemTools', labelKey: 'ctx.ch.systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) }, { key: 'mcpTools', labelKey: 'ctx.ch.mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) }, { key: 'skills', labelKey: 'ctx.ch.skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) }, { key: 'userRules', labelKey: 'ctx.ch.userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) }, ]; const ContextSegmentMeter = defineComponent({ name: 'ContextSegmentMeter', setup({ getProps }) { // 固定 10 个位置槽位节点,不通过 appendChild 移动 DOM,防止浏览器中断 CSS transition 动画 const slotEls = SEGMENT_DEFS.map((def) => h('div', { className: `progress-seg ${def.cls}` }) ); const trackEl = h( 'div', { className: 'progress-track ctx-segment-meter', role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', }, slotEls ); let lastOrderSig = ''; function syncMeter() { const ctx = getProps().context || {}; const limit = Math.max(1, Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000)); const scored = SEGMENT_DEFS.map((def, defaultOrder) => { const val = def.getVal(ctx); const pct = Math.min(100, (val / limit) * 100); return { def, defaultOrder, val, pct }; }); scored.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder); // 仅关注非零通道的相对顺序变化,决定是否启用 0.05s 先变色再伸缩的衔接延迟 const activeOrderSig = scored .filter((x) => x.val > 0) .map((x) => x.def.key) .join(','); const orderChanged = Boolean(lastOrderSig && activeOrderSig && activeOrderSig !== lastOrderSig); if (activeOrderSig) { lastOrderSig = activeOrderSig; } patchClasses(trackEl, { 'is-reordering': orderChanged }); let seenActive = false; for (let i = 0; i < slotEls.length; i++) { const slotEl = slotEls[i]; const item = scored[i]; const isActive = item.val > 0 && item.pct > 0; const hasSep = isActive && seenActive; if (isActive) seenActive = true; const cls = `progress-seg ${item.def.cls}${isActive ? ' is-active' : ''}${hasSep ? ' has-sep' : ''}`; patchAttr(slotEl, 'class', cls); patchStyleVar(slotEl, '--seg-w', isActive ? `${item.pct.toFixed(2)}%` : '0%'); patchAttr( slotEl, 'title', isActive ? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${formatPctNumber(item.pct, { withSymbol: true })})` : null ); } patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0)); } syncMeter(); return { el: trackEl, refs: { segments: slotEls }, onPropsChange: syncMeter, }; }, }); return { ContextSegmentMeter }; })(); // --- src/components/ui/FourSegmentBar.js --- const { createFourSegmentBar } = (() => { /** * @fileoverview 通用 4 段式 Token 构成比例条组件 (FourSegmentBar). * 用于在消费概览、热门模型明细及模型总览卡片中直观展示: * 直接输入 (Input)、缓存读取 (Cached)、思考推理 (Thinking)、内容生成 (Output) 的 Token 占比。 */ /** * 创建 4 段式水平比例进度条实例。 * 通过动态更新各分段节点的 `--seg-w` CSS 变量实现零重排平滑过渡。 * * @returns {{ * el: HTMLElement, * update: (metrics: { * inputTokens?: number, * cacheReadTokens?: number, * responseTokens?: number, * thinkingTokens?: number * }) => void * }} 组件根元素及增量更新方法 */ function createFourSegmentBar() { const segInput = h('div', { className: 'progress-seg seg-input' }); const segCached = h('div', { className: 'progress-seg seg-cached' }); const segThinking = h('div', { className: 'progress-seg seg-thinking' }); const segOutput = h('div', { className: 'progress-seg seg-output' }); const el = h('div', { className: 'progress-track cons-seg-bar' }, [ segInput, segCached, segThinking, segOutput, ]); /** * 根据四类 Token 数量与整体行宽占比系数 (`scaleRatio`,默认 `1` 占满 100%) 重新计算并写入各分段百分比宽度。 */ function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0, scaleRatio = 1, }) { const sum = inputTokens + cacheReadTokens + responseTokens + thinkingTokens; const clampedRatio = Number.isFinite(Number(scaleRatio)) ? Math.min(1, Math.max(0, Number(scaleRatio))) : 1; if (sum <= 0 || clampedRatio <= 0) { patchStyleVar(segInput, '--seg-w', '0%'); patchStyleVar(segCached, '--seg-w', '0%'); patchStyleVar(segOutput, '--seg-w', '0%'); patchStyleVar(segThinking, '--seg-w', '0%'); return; } patchStyleVar(segInput, '--seg-w', `${((inputTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); patchStyleVar(segOutput, '--seg-w', `${((responseTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / sum) * 100 * clampedRatio).toFixed(2)}%`); } return { el, update }; } return { createFourSegmentBar }; })(); // --- src/components/ui/ConsumptionTooltipContent.js --- const { createConsumptionBreakdownContent } = (() => { /** * @fileoverview 消耗统计统一悬浮详情内容组件 (ConsumptionTooltipContent). * 供历史趋势(折线/热力图)、客户端来源、会话排行及月度统计悬浮卡片复用: * 1. 顶部标题/日期行 + 右侧调用次数; * 2. 核心大字总量 (`TOKEN`) + 右侧预估费用; * 3. 分模型明细行(模型名/Token/占比 + 同「模型排行」Token 模式一致的四段构成进度条,不显示多余分组标题); * 4. 底部四通道汇总(输入 / 缓存 / 思考 / 输出)。 */ function safeNonNeg(val) { const n = Number(val); return Number.isFinite(n) && n > 0 ? n : 0; } function resolveSegmentChannels(seg) { const inputTokens = safeNonNeg(seg?.inputTokens); const cacheReadTokens = safeNonNeg(seg?.cacheReadTokens); const thinkingTokens = safeNonNeg(seg?.thinkingTokens); const responseTokens = seg?.responseTokens != null ? safeNonNeg(seg.responseTokens) : Math.max(0, safeNonNeg(seg?.outputTokens) - thinkingTokens); return { inputTokens, cacheReadTokens, thinkingTokens, responseTokens }; } /** * 创建可增量更新的消耗统计悬浮详情内容结构。 * * @param {{ showModelDot?: boolean, monoTitle?: boolean }} [options] * @returns {{ * children: HTMLElement[], * update: (payload: { * title?: string, * calls?: number, * totalTokens?: number, * costText?: string, * inputTokens?: number, * cacheReadTokens?: number, * thinkingTokens?: number, * responseTokens?: number, * outputTokens?: number, * segments?: Array, * }) => void, * }} */ function createConsumptionBreakdownContent({ showModelDot = false, monoTitle = false, } = {}) { const titleEl = h('span', { className: monoTitle ? 'trend-tip-time text-mono' : 'trend-tip-time', }); const callsEl = h('span', { className: 'trend-tip-calls text-mono' }); const headEl = h('div', { className: 'trend-tip-head cons-tip-head' }, [titleEl, callsEl]); const heroNumEl = h('span', { className: 'cons-tip-hero-num', text: '0' }); const heroUnitEl = h('span', { className: 'cons-tip-hero-unit', text: ' TOKEN' }); const tokensEl = h('strong', { className: 'trend-tip-tokens cons-tip-hero text-mono' }, [ heroNumEl, heroUnitEl, ]); const costEl = h('span', { className: 'trend-tip-cost text-mono' }); const mainEl = h('div', { className: 'trend-tip-main cons-tip-main' }, [tokensEl, costEl]); function createModelRow() { const dotEl = h('span', { className: 'dot-swatch cons-model-dot', hidden: !showModelDot, }); const nameEl = h('span', { className: 'cons-pop-model-name' }); const tokEl = h('span', { className: 'cons-pop-model-tok' }); const pctEl = h('strong', { className: 'cons-pop-model-pct' }); const segBar = createFourSegmentBar(); const rowEl = h('div', { className: 'cons-pop-model-row' }, [ h('div', { className: 'cons-pop-model-head' }, [ h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]), h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]), ]), segBar.el, ]); return { el: rowEl, refs: { rowEl, dotEl, nameEl, tokEl, pctEl, segBar }, }; } const modelsEl = h('div', { className: 'cons-pop-models', hidden: true }); const inLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legInput') }); const inValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' }); const cacheLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legCache') }); const cacheValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' }); const thinkLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legThinking') }); const thinkValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' }); const outLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legOutput') }); const outValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' }); const channelsEl = h('div', { className: 'cons-pop-channels', hidden: true }, [ h('div', { className: 'cons-pop-chan' }, [ h('span', { className: 'cons-pop-chan-head' }, [ h('span', { className: 'dot-swatch seg-input' }), inLabelEl, ]), inValEl, ]), h('div', { className: 'cons-pop-chan' }, [ h('span', { className: 'cons-pop-chan-head' }, [ h('span', { className: 'dot-swatch seg-cached' }), cacheLabelEl, ]), cacheValEl, ]), h('div', { className: 'cons-pop-chan' }, [ h('span', { className: 'cons-pop-chan-head' }, [ h('span', { className: 'dot-swatch seg-thinking' }), thinkLabelEl, ]), thinkValEl, ]), h('div', { className: 'cons-pop-chan' }, [ h('span', { className: 'cons-pop-chan-head' }, [ h('span', { className: 'dot-swatch seg-output' }), outLabelEl, ]), outValEl, ]), ]); function update(payload = {}) { patchText(titleEl, payload.title || '--'); patchText( callsEl, t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(payload.calls) || 0)) }) ); const totalTokens = safeNonNeg(payload.totalTokens); patchText(heroNumEl, formatTokensPrecise(totalTokens)); patchText(heroUnitEl, ' TOKEN'); patchText(costEl, payload.costText || ''); const rows = Array.isArray(payload.segments) ? payload.segments : []; patchAttr(modelsEl, 'hidden', rows.length === 0); patchKeyedList(modelsEl, rows, { keyFn: (r) => r.key, sigFn: (r) => `${showModelDot ? 1 : 0}:${r.key}:${r.label}:${r.color || ''}:${r.tokText}:${r.pctText}:${r.isOther ? 1 : 0}:${r.tok || 0}:${r.inputTokens || 0}:${r.cacheReadTokens || 0}:${r.thinkingTokens || 0}:${r.responseTokens ?? ''}:${r.outputTokens ?? ''}`, createRow: createModelRow, updateRow: (rRefs, r) => { patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) }); patchAttr(rRefs.dotEl, 'hidden', !showModelDot); if (showModelDot) { patchStyleVar(rRefs.dotEl, '--dot-color', r.color); } patchText(rRefs.nameEl, r.label); patchText(rRefs.tokEl, r.tokText); patchText(rRefs.pctEl, r.pctText); const segTok = safeNonNeg(r.tok); const pct = Math.max(0, Math.min(100, Number(r.pct) || 0)); const scaleRatio = segTok > 0 ? Math.min(1, Math.max(0.008, pct / 100)) : 0; const ch = resolveSegmentChannels(r); const chSum = ch.inputTokens + ch.cacheReadTokens + ch.thinkingTokens + ch.responseTokens; if (chSum > 0) { rRefs.segBar.update({ inputTokens: ch.inputTokens, cacheReadTokens: ch.cacheReadTokens, thinkingTokens: ch.thinkingTokens, responseTokens: ch.responseTokens, scaleRatio, }); } else if (segTok > 0) { rRefs.segBar.update({ inputTokens: 0, cacheReadTokens: segTok, thinkingTokens: 0, responseTokens: 0, scaleRatio, }); } else { rRefs.segBar.update({ inputTokens: 0, cacheReadTokens: 0, thinkingTokens: 0, responseTokens: 0, scaleRatio: 0, }); } }, }); const hasExplicitChannels = payload.inputTokens !== undefined || payload.cacheReadTokens !== undefined || payload.thinkingTokens !== undefined || payload.responseTokens !== undefined || payload.outputTokens !== undefined; let inTok = safeNonNeg(payload.inputTokens); let cacheTok = safeNonNeg(payload.cacheReadTokens); let thinkTok = safeNonNeg(payload.thinkingTokens); let respTok = payload.responseTokens != null ? safeNonNeg(payload.responseTokens) : Math.max(0, safeNonNeg(payload.outputTokens) - thinkTok); let hasChannels = hasExplicitChannels; if (!hasChannels && rows.length > 0) { let segIn = 0; let segCache = 0; let segThink = 0; let segResp = 0; for (const seg of rows) { const ch = resolveSegmentChannels(seg); segIn += ch.inputTokens; segCache += ch.cacheReadTokens; segThink += ch.thinkingTokens; segResp += ch.responseTokens; } if (segIn + segCache + segThink + segResp > 0) { inTok = segIn; cacheTok = segCache; thinkTok = segThink; respTok = segResp; hasChannels = true; } } const showChannels = totalTokens > 0 && hasChannels; patchAttr(channelsEl, 'hidden', !showChannels); if (showChannels) { patchText(inLabelEl, t('cons.legInput')); patchText(cacheLabelEl, t('cons.legCache')); patchText(thinkLabelEl, t('cons.legThinking')); patchText(outLabelEl, t('cons.legOutput')); patchText(inValEl, formatTokensPrecise(inTok)); patchText(cacheValEl, formatTokensPrecise(cacheTok)); patchText(thinkValEl, formatTokensPrecise(thinkTok)); patchText(outValEl, formatTokensPrecise(respTok)); } } return { children: [headEl, mainEl, modelsEl, channelsEl], update, }; } return { createConsumptionBreakdownContent }; })(); // --- src/components/charts/chartMotion.js --- const { CHART_CURVE_MORPH_MS, canAnimateChartInBrowser, evalCubicBezier, createReadyClassArmer, pointsToNormalizedCubicSegs, buildPathFromNormalizedSegs, createCubicCurveMorphController, createMultiSeriesCurveMorphController, createFitGridMorphController, createFloatingChartTooltipController } = (() => { /** * @fileoverview Shared interactive chart motion & 2D mouse-following tooltip primitives (`chartMotion.js`). * * Reused across: * 1. `TrendAreaChart.js` (ConsumptionView usage trend & heatmap); * 2. `SessionStepCharts.js` (StepsDetailView summary step line chart & LOESS model fit chart); * 3. `AccountQuotaTrendCard.js` (SettingsAccountTab per-account quota trajectory chart). * * Provides: * - GPU-composited 2D pointer-following floating tooltip (`translate3d`) with 4-way collision * avoidance, viewport clipping, cached layout rects, and `150ms` `.is-tracking` arming * synchronized with SVG focus dots (`.trend-hover-dot` / `.sstep-hover-raw-dot`); * - Exact CSS `cubic-bezier` solver (`evalCubicBezier`) and `240ms` normalized cubic-Bezier * chain subdivision morphing for single-series and multi-series curves + area fills; * - Smooth `240ms` LOESS curve, `95% CI` confidence band, and OLS line morphing; * - Next-frame `.is-ready` transition arming for sliding peak badges (`.trend-peak-pill`). */ const CHART_CURVE_MORPH_MS = 240; /** * Checks whether smooth `requestAnimationFrame` chart animations should run in the current * environment (browser runtime with `prefers-reduced-motion` not enabled). */ function canAnimateChartInBrowser() { if ( typeof window === 'undefined' || typeof window.requestAnimationFrame !== 'function' || typeof window.getComputedStyle !== 'function' || typeof performance === 'undefined' || typeof performance.now !== 'function' ) { return false; } if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) { return false; } return true; } /** * Solves standard CSS `cubic-bezier(x1, y1, x2, y2)` at progress `t` (`0..1`) * so JS path morphing, peak-pill gliding, and CSS bar transitions stay in lockstep. */ function evalCubicBezier(x1, y1, x2, y2, t) { if (t <= 0) return 0; if (t >= 1) return 1; let lo = 0; let hi = 1; for (let i = 0; i < 16; i++) { const s = (lo + hi) * 0.5; const inv = 1 - s; const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s; if (bx < t) lo = s; else hi = s; } const s = (lo + hi) * 0.5; const inv = 1 - s; return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s; } /** * Arms a CSS transition readiness class (e.g. `.is-ready` on `.trend-peak-pill`) on the next * animation frame so initial placement snaps cleanly without sliding in from `50%`. */ function createReadyClassArmer(el, readyClass = 'is-ready') { let armed = false; let rafId = 0; function cancel() { if (rafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { window.cancelAnimationFrame(rafId); } rafId = 0; } function arm() { if (armed) return; armed = true; if (canAnimateChartInBrowser()) { rafId = window.requestAnimationFrame(() => { rafId = 0; patchClasses(el, { [readyClass]: true }); }); } else { patchClasses(el, { [readyClass]: true }); } } return { arm, cancel }; } /** * Converts 2D SVG points into a normalized horizontal (`u` in `0..1`) cubic-Bezier chain * with horizontal endpoint tangents (`0.42` tension by default, zero vertical overshoot). * Supports both uniform slot spacing and arbitrary timestamp/x coordinates via `leftX` + `spanX`. * * @param {Array<{ x?: number, y: number }>} pts * @param {number} bottomY * @param {{ leftX?: number, spanX?: number, tension?: number }} [opts] */ function pointsToNormalizedCubicSegs( pts, bottomY, { leftX = 0, spanX = 0, tension = 0.42 } = {} ) { const n = Array.isArray(pts) ? pts.length : 0; const invT = 1 - tension; if (n === 0) { return [ { u0: 0, y0: bottomY, cu1: tension, cy1: bottomY, cu2: invT, cy2: bottomY, u3: 1, y3: bottomY, }, ]; } if (n === 1) { const py = pts[0].y; const uMid = spanX > 0 && Number.isFinite(pts[0].x) ? Math.max(0, Math.min(1, (pts[0].x - leftX) / spanX)) : 0.5; if (Math.abs(py - bottomY) < 0.01) { return [ { u0: 0, y0: bottomY, cu1: tension, cy1: bottomY, cu2: invT, cy2: bottomY, u3: 1, y3: bottomY, }, ]; } return [ { u0: 0, y0: bottomY, cu1: uMid * tension, cy1: bottomY, cu2: uMid * invT, cy2: py, u3: uMid, y3: py, }, { u0: uMid, y0: py, cu1: uMid + (1 - uMid) * tension, cy1: py, cu2: uMid + (1 - uMid) * invT, cy2: bottomY, u3: 1, y3: bottomY, }, ]; } const useCoordU = spanX > 0 && Number.isFinite(pts[0].x); const segs = []; let prevU = useCoordU ? Math.max(0, Math.min(1, (pts[0].x - leftX) / spanX)) : 0; let prevY = pts[0].y; for (let i = 1; i < n; i++) { const rawU = useCoordU ? Math.max(0, Math.min(1, (pts[i].x - leftX) / spanX)) : i / (n - 1); const u3 = Math.max(prevU, rawU); const y3 = pts[i].y; if (u3 - prevU <= 1e-6 && i < n - 1 && Math.abs(y3 - prevY) < 0.05) { continue; } const safeU3 = u3 - prevU <= 1e-6 ? Math.min(1, prevU + 1e-5) : u3; const du = safeU3 - prevU; segs.push({ u0: prevU, y0: prevY, cu1: prevU + du * tension, cy1: prevY, cu2: safeU3 - du * tension, cy2: y3, u3: safeU3, y3, }); prevU = safeU3; prevY = y3; } if (segs.length === 0) { return [ { u0: prevU, y0: prevY, cu1: prevU, cy1: prevY, cu2: prevU, cy2: prevY, u3: prevU, y3: prevY, }, ]; } return segs; } function solveCubicParamForU(seg, targetU) { if (targetU <= seg.u0) return 0; if (targetU >= seg.u3) return 1; let lo = 0; let hi = 1; for (let it = 0; it < 20; it++) { const s = (lo + hi) * 0.5; const inv = 1 - s; const u = inv * inv * inv * seg.u0 + 3 * inv * inv * s * seg.cu1 + 3 * inv * s * s * seg.cu2 + s * s * s * seg.u3; if (u < targetU) lo = s; else hi = s; } return (lo + hi) * 0.5; } function splitCubicAt(seg, s) { const u01 = seg.u0 + (seg.cu1 - seg.u0) * s; const y01 = seg.y0 + (seg.cy1 - seg.y0) * s; const u12 = seg.cu1 + (seg.cu2 - seg.cu1) * s; const y12 = seg.cy1 + (seg.cy2 - seg.cy1) * s; const u23 = seg.cu2 + (seg.u3 - seg.cu2) * s; const y23 = seg.cy2 + (seg.y3 - seg.cy2) * s; const u012 = u01 + (u12 - u01) * s; const y012 = y01 + (y12 - y01) * s; const u123 = u12 + (u23 - u12) * s; const y123 = y12 + (y23 - y12) * s; const u0123 = u012 + (u123 - u012) * s; const y0123 = y012 + (y123 - y012) * s; return [ { u0: seg.u0, y0: seg.y0, cu1: u01, cy1: y01, cu2: u012, cy2: y012, u3: u0123, y3: y0123 }, { u0: u0123, y0: y0123, cu1: u123, cy1: y123, cu2: u23, cy2: y23, u3: seg.u3, y3: seg.y3 }, ]; } function extractCubicSubsegment(seg, uStart, uEnd) { const s0 = solveCubicParamForU(seg, uStart); const s1 = solveCubicParamForU(seg, uEnd); if (s0 <= 1e-7 && s1 >= 1 - 1e-7) return { ...seg }; const [, right] = s0 <= 1e-7 ? [null, seg] : splitCubicAt(seg, s0); const remSpan = 1 - s0; const localS1 = remSpan > 1e-9 ? Math.min(1, Math.max(0, (s1 - s0) / remSpan)) : 1; const [sub] = localS1 >= 1 - 1e-7 ? [right] : splitCubicAt(right, localS1); sub.u0 = uStart; sub.u3 = uEnd; return sub; } /** * Aligns two cubic-Bezier chains (`fromSegs` and `toSegs`, even when their horizontal `[uStart, uEnd]` * spans differ) onto a shared normalized `[0..1]` knot partition so every segment pair interpolates * smoothly without endpoint snapping. */ function alignCubicChainsForMorph(fromSegs, toSegs) { const fStart = fromSegs[0].u0; const fEnd = fromSegs[fromSegs.length - 1].u3; const fSpan = fEnd - fStart; const tStart = toSegs[0].u0; const tEnd = toSegs[toSegs.length - 1].u3; const tSpan = tEnd - tStart; const rawTau = [0, 1]; const pushChainKnots = (segs, start, span) => { if (!(span > 1e-6)) return; for (let i = 0; i < segs.length; i++) { rawTau.push(Math.max(0, Math.min(1, (segs[i].u0 - start) / span))); rawTau.push(Math.max(0, Math.min(1, (segs[i].u3 - start) / span))); } }; pushChainKnots(toSegs, tStart, tSpan); pushChainKnots(fromSegs, fStart, fSpan); rawTau.sort((a, b) => a - b); const tauKnots = [0]; for (let i = 1; i < rawTau.length; i++) { if (rawTau[i] - tauKnots[tauKnots.length - 1] > 1e-5) { tauKnots.push(rawTau[i]); } } if (tauKnots.length === 1) tauKnots.push(1); else tauKnots[tauKnots.length - 1] = 1; const subdivideOnTau = (segs, start, span) => { const out = new Array(tauKnots.length - 1); let j = 0; for (let k = 0; k < tauKnots.length - 1; k++) { const ta = tauKnots[k]; const tb = tauKnots[k + 1]; if (!(span > 1e-6)) { const s0 = segs[0]; out[k] = { u0: start, y0: s0.y0, cu1: start, cy1: s0.y0, cu2: start, cy2: s0.y3, u3: start, y3: s0.y3, }; continue; } const ua = start + ta * span; const ub = start + tb * span; const umid = (ua + ub) * 0.5; while (j < segs.length - 1 && segs[j].u3 < umid) j++; out[k] = extractCubicSubsegment(segs[j], ua, ub); } return out; }; return { alignedFrom: subdivideOnTau(fromSegs, fStart, fSpan), alignedTo: subdivideOnTau(toSegs, tStart, tSpan), }; } function buildPathFromNormalizedSegs(segs, leftX, spanX) { const xAt = (u) => (leftX + u * spanX).toFixed(1); let d = `M ${xAt(segs[0].u0)} ${segs[0].y0.toFixed(1)}`; for (let i = 0; i < segs.length; i++) { const s = segs[i]; d += ` C ${xAt(s.cu1)} ${s.cy1.toFixed(1)}, ${xAt(s.cu2)} ${s.cy2.toFixed(1)}, ${xAt(s.u3)} ${s.y3.toFixed(1)}`; } return d; } /** * Single-series cubic-Bezier curve + area fill morph controller (used by `TrendAreaChart` and * single-series `SessionStepCharts`). */ function createCubicCurveMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { let morphRafId = 0; let committedSegs = []; let liveMorphSegs = null; let hasRenderedOnce = false; function cancel() { if ( morphRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function' ) { window.cancelAnimationFrame(morphRafId); } morphRafId = 0; } function reset() { cancel(); committedSegs = []; liveMorphSegs = null; hasRenderedOnce = false; } function getCurrentSegs() { const src = liveMorphSegs || committedSegs; return hasRenderedOnce && src.length > 0 ? src.map((s) => ({ ...s })) : []; } function seedSegs(segs) { cancel(); if (Array.isArray(segs) && segs.length > 0) { committedSegs = segs.map((s) => ({ ...s })); liveMorphSegs = null; hasRenderedOnce = true; } } function morphTo({ nextSegs, leftX, spanX, bottomY, linePath, areaPath = null, finalLineD, finalAreaD = '', skipMorph = false, }) { const prevSegs = liveMorphSegs || committedSegs; committedSegs = nextSegs; if ( skipMorph || !hasRenderedOnce || !canAnimateChartInBrowser() || prevSegs.length === 0 || nextSegs.length === 0 ) { hasRenderedOnce = true; cancel(); liveMorphSegs = null; patchAttr(linePath, 'd', finalLineD); if (areaPath) patchAttr(areaPath, 'd', finalAreaD); return; } hasRenderedOnce = true; cancel(); const { alignedFrom, alignedTo } = alignCubicChainsForMorph(prevSegs, nextSegs); const segCount = alignedTo.length; let maxDelta = 0; for (let i = 0; i < segCount; i++) { const a = alignedFrom[i]; const b = alignedTo[i]; maxDelta = Math.max( maxDelta, Math.abs(b.y0 - a.y0), Math.abs(b.cy1 - a.cy1), Math.abs(b.cy2 - a.cy2), Math.abs(b.y3 - a.y3), Math.abs(b.u0 - a.u0) * spanX, Math.abs(b.u3 - a.u3) * spanX ); } if (maxDelta < 0.25) { liveMorphSegs = null; patchAttr(linePath, 'd', finalLineD); if (areaPath) patchAttr(areaPath, 'd', finalAreaD); return; } const activeLive = alignedFrom.map((s) => ({ ...s })); liveMorphSegs = activeLive; const initialLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); patchAttr(linePath, 'd', initialLineD); if (areaPath) { if (finalAreaD) { const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); patchAttr(areaPath, 'd', `${initialLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); } else { patchAttr(areaPath, 'd', ''); } } const startTs = performance.now(); const step = (nowTs) => { const elapsed = Math.max(0, nowTs - startTs); const rawT = Math.min(1, elapsed / durationMs); if (rawT >= 1) { morphRafId = 0; liveMorphSegs = null; patchAttr(linePath, 'd', finalLineD); if (areaPath) patchAttr(areaPath, 'd', finalAreaD); return; } const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); for (let i = 0; i < segCount; i++) { const a = alignedFrom[i]; const b = alignedTo[i]; const cur = activeLive[i]; cur.u0 = a.u0 + (b.u0 - a.u0) * ease; cur.y0 = a.y0 + (b.y0 - a.y0) * ease; cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; cur.u3 = a.u3 + (b.u3 - a.u3) * ease; cur.y3 = a.y3 + (b.y3 - a.y3) * ease; } const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); patchAttr(linePath, 'd', morphLineD); if (areaPath) { const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); patchAttr(areaPath, 'd', `${morphLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); } morphRafId = window.requestAnimationFrame(step); }; morphRafId = window.requestAnimationFrame(step); } return { morphTo, cancel, reset, getCurrentSegs, seedSegs }; } /** * Coalesced multi-series cubic-Bezier curve, area fill, and endpoint dot morph controller * (used by `AccountQuotaTrendCard` and multi-model `SessionStepCharts`). */ function createMultiSeriesCurveMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { let morphRafId = 0; let hasRenderedOnce = false; const stateByKey = new Map(); function cancel() { if ( morphRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function' ) { window.cancelAnimationFrame(morphRafId); } morphRafId = 0; } function reset() { cancel(); hasRenderedOnce = false; stateByKey.clear(); } function getSeriesSegs(key) { const rec = stateByKey.get(key); const src = rec ? rec.liveSegs || rec.committedSegs : null; return src && src.length > 0 ? src.map((s) => ({ ...s })) : null; } function getFirstSegs() { for (const rec of stateByKey.values()) { const src = rec.liveSegs || rec.committedSegs; if (src && src.length > 0) return src.map((s) => ({ ...s })); } return null; } function seedSeries(key, segs) { if (!key || !Array.isArray(segs) || segs.length === 0) return; stateByKey.set(key, { committedSegs: segs.map((s) => ({ ...s })), liveSegs: null, endX: NaN, endY: NaN, }); hasRenderedOnce = true; } function morphSeries({ items, leftX, spanX, bottomY, skipMorph = false, allowBaselineEntry = false, }) { cancel(); const canAnim = !skipMorph && canAnimateChartInBrowser(); const wasRenderedBefore = hasRenderedOnce; hasRenderedOnce = items.length > 0; const activeSet = new Set(); const jobs = []; for (let idx = 0; idx < items.length; idx++) { const it = items[idx]; activeSet.add(it.key); const prevEntry = stateByKey.get(it.key); let prevSegs = prevEntry ? prevEntry.liveSegs || prevEntry.committedSegs : null; if ( (!prevSegs || prevSegs.length === 0) && canAnim && allowBaselineEntry && wasRenderedBefore && it.nextSegs.length > 0 && Number.isFinite(bottomY) ) { prevSegs = it.nextSegs.map((s) => ({ u0: s.u0, y0: bottomY, cu1: s.cu1, cy1: bottomY, cu2: s.cu2, cy2: bottomY, u3: s.u3, y3: bottomY, })); } if (!canAnim || !prevSegs || prevSegs.length === 0 || it.nextSegs.length === 0) { stateByKey.set(it.key, { committedSegs: it.nextSegs, liveSegs: null, endX: it.endX, endY: it.endY, }); patchAttr(it.lineEl, 'd', it.finalLineD); if (it.areaEl) patchAttr(it.areaEl, 'd', it.finalAreaD || ''); if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { patchAttr(it.endDotEl, 'cx', it.endX.toFixed(1)); patchAttr(it.endDotEl, 'cy', it.endY.toFixed(1)); } continue; } const { alignedFrom, alignedTo } = alignCubicChainsForMorph(prevSegs, it.nextSegs); const segCount = alignedTo.length; let maxDelta = 0; for (let i = 0; i < segCount; i++) { const a = alignedFrom[i]; const b = alignedTo[i]; maxDelta = Math.max( maxDelta, Math.abs(b.y0 - a.y0), Math.abs(b.cy1 - a.cy1), Math.abs(b.cy2 - a.cy2), Math.abs(b.y3 - a.y3), Math.abs(b.u0 - a.u0) * spanX, Math.abs(b.u3 - a.u3) * spanX ); } if (maxDelta < 0.25) { stateByKey.set(it.key, { committedSegs: it.nextSegs, liveSegs: null, endX: it.endX, endY: it.endY, }); patchAttr(it.lineEl, 'd', it.finalLineD); if (it.areaEl) patchAttr(it.areaEl, 'd', it.finalAreaD || ''); if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { patchAttr(it.endDotEl, 'cx', it.endX.toFixed(1)); patchAttr(it.endDotEl, 'cy', it.endY.toFixed(1)); } continue; } const activeLive = alignedFrom.map((s) => ({ ...s })); const fromEndX = Number.isFinite(prevEntry?.endX) ? prevEntry.endX : leftX + alignedFrom[segCount - 1].u3 * spanX; const fromEndY = Number.isFinite(prevEntry?.endY) ? prevEntry.endY : alignedFrom[segCount - 1].y3; const stateRec = { committedSegs: it.nextSegs, liveSegs: activeLive, endX: fromEndX, endY: fromEndY, }; stateByKey.set(it.key, stateRec); const initLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); patchAttr(it.lineEl, 'd', initLineD); if (it.areaEl) { if (it.finalAreaD) { const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); patchAttr(it.areaEl, 'd', `${initLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); } else { patchAttr(it.areaEl, 'd', ''); } } jobs.push({ it, alignedFrom, alignedTo, activeLive, segCount, fromEndX, fromEndY, stateRec, }); } for (const k of Array.from(stateByKey.keys())) { if (!activeSet.has(k)) stateByKey.delete(k); } if (jobs.length === 0) return; const startTs = performance.now(); const step = (nowTs) => { const elapsed = Math.max(0, nowTs - startTs); const rawT = Math.min(1, elapsed / durationMs); if (rawT >= 1) { morphRafId = 0; for (let j = 0; j < jobs.length; j++) { const jb = jobs[j]; jb.stateRec.liveSegs = null; jb.stateRec.endX = jb.it.endX; jb.stateRec.endY = jb.it.endY; patchAttr(jb.it.lineEl, 'd', jb.it.finalLineD); if (jb.it.areaEl) patchAttr(jb.it.areaEl, 'd', jb.it.finalAreaD || ''); if (jb.it.endDotEl && Number.isFinite(jb.it.endX) && Number.isFinite(jb.it.endY)) { patchAttr(jb.it.endDotEl, 'cx', jb.it.endX.toFixed(1)); patchAttr(jb.it.endDotEl, 'cy', jb.it.endY.toFixed(1)); } } return; } const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); for (let j = 0; j < jobs.length; j++) { const jb = jobs[j]; const { alignedFrom, alignedTo, activeLive, segCount, it } = jb; for (let i = 0; i < segCount; i++) { const a = alignedFrom[i]; const b = alignedTo[i]; const cur = activeLive[i]; cur.u0 = a.u0 + (b.u0 - a.u0) * ease; cur.y0 = a.y0 + (b.y0 - a.y0) * ease; cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; cur.u3 = a.u3 + (b.u3 - a.u3) * ease; cur.y3 = a.y3 + (b.y3 - a.y3) * ease; } const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); patchAttr(it.lineEl, 'd', morphLineD); if (it.areaEl && it.finalAreaD) { const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); patchAttr(it.areaEl, 'd', `${morphLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); } if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { const cx = jb.fromEndX + (it.endX - jb.fromEndX) * ease; const cy = jb.fromEndY + (it.endY - jb.fromEndY) * ease; jb.stateRec.endX = cx; jb.stateRec.endY = cy; patchAttr(it.endDotEl, 'cx', cx.toFixed(1)); patchAttr(it.endDotEl, 'cy', cy.toFixed(1)); } } morphRafId = window.requestAnimationFrame(step); }; morphRafId = window.requestAnimationFrame(step); } return { morphSeries, cancel, reset, getSeriesSegs, getFirstSegs, seedSeries }; } function buildGridFitPolylineD(grid) { if (!grid.length) return ''; let d = `M ${grid[0].x.toFixed(1)} ${grid[0].fitY.toFixed(1)}`; for (let i = 1; i < grid.length; i++) { d += ` L ${grid[i].x.toFixed(1)} ${grid[i].fitY.toFixed(1)}`; } return d; } function buildGridCiBandD(grid) { if (grid.length < 2) return ''; let d = `M ${grid[0].x.toFixed(1)} ${grid[0].highY.toFixed(1)}`; for (let i = 1; i < grid.length; i++) { d += ` L ${grid[i].x.toFixed(1)} ${grid[i].highY.toFixed(1)}`; } for (let i = grid.length - 1; i >= 0; i--) { d += ` L ${grid[i].x.toFixed(1)} ${grid[i].lowY.toFixed(1)}`; } return `${d} Z`; } function resampleFitGridToTargetXs(sourceGrid, targetGrid) { if (!Array.isArray(sourceGrid) || sourceGrid.length === 0) return null; const sLen = sourceGrid.length; const sFirst = sourceGrid[0]; const sLast = sourceGrid[sLen - 1]; let j = 0; return targetGrid.map((tg) => { const x = tg.x; if (sLen === 1 || x <= sFirst.x) { return { x, fitY: sFirst.fitY, lowY: sFirst.lowY, highY: sFirst.highY }; } if (x >= sLast.x) { return { x, fitY: sLast.fitY, lowY: sLast.lowY, highY: sLast.highY }; } while (j < sLen - 2 && sourceGrid[j + 1].x < x) j += 1; const a = sourceGrid[j]; const b = sourceGrid[j + 1]; const span = b.x - a.x; const r = span > 1e-6 ? Math.max(0, Math.min(1, (x - a.x) / span)) : 0; return { x, fitY: a.fitY + (b.fitY - a.fitY) * r, lowY: a.lowY + (b.lowY - a.lowY) * r, highY: a.highY + (b.highY - a.highY) * r, }; }); } /** * Smoothly morphs LOESS fit polylines, `95% CI` confidence bands, and optional OLS lines * across metric/model switches in `createModelFitChart`. */ function createFitGridMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { let morphRafId = 0; let hasRenderedOnce = false; const stateByKey = new Map(); function cancel() { if ( morphRafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function' ) { window.cancelAnimationFrame(morphRafId); } morphRafId = 0; } function reset() { cancel(); hasRenderedOnce = false; stateByKey.clear(); } function getGrid(key) { const rec = stateByKey.get(key); const src = rec ? rec.liveGrid || rec.committedGrid : null; return src && src.length > 0 ? src.map((g) => ({ ...g })) : null; } function getFirstGrid() { for (const rec of stateByKey.values()) { const src = rec.liveGrid || rec.committedGrid; if (src && src.length > 0) return src.map((g) => ({ ...g })); } return null; } function seedGrid(key, gridPts) { if (!key || !Array.isArray(gridPts) || gridPts.length === 0) return; stateByKey.set(key, { committedGrid: gridPts.map((g) => ({ ...g })), liveGrid: null, ols: null, }); hasRenderedOnce = true; } function morphFits({ items, skipMorph = false, allowBaselineEntry = false, bottomY = NaN }) { cancel(); const canAnim = !skipMorph && canAnimateChartInBrowser(); const wasRenderedBefore = hasRenderedOnce; hasRenderedOnce = items.length > 0; const activeSet = new Set(); const jobs = []; for (let idx = 0; idx < items.length; idx++) { const it = items[idx]; activeSet.add(it.key); const prevEntry = stateByKey.get(it.key); const rawPrevGrid = prevEntry ? prevEntry.liveGrid || prevEntry.committedGrid : null; let prevGrid = rawPrevGrid && rawPrevGrid.length > 0 && it.gridPts.length >= 2 ? rawPrevGrid.length === it.gridPts.length && Math.abs(rawPrevGrid[0].x - it.gridPts[0].x) < 0.5 && Math.abs( rawPrevGrid[rawPrevGrid.length - 1].x - it.gridPts[it.gridPts.length - 1].x ) < 0.5 ? rawPrevGrid : resampleFitGridToTargetXs(rawPrevGrid, it.gridPts) : null; if ( !prevGrid && canAnim && allowBaselineEntry && wasRenderedBefore && it.gridPts.length >= 2 && Number.isFinite(bottomY) ) { prevGrid = it.gridPts.map((g) => ({ x: g.x, fitY: bottomY, lowY: bottomY, highY: bottomY, })); } if ( !canAnim || !prevGrid || prevGrid.length !== it.gridPts.length || it.gridPts.length < 2 ) { stateByKey.set(it.key, { committedGrid: it.gridPts, liveGrid: null, ols: it.olsCoords || null, }); patchAttr(it.curveEl, 'd', it.finalCurveD); if (it.bandEl) patchAttr(it.bandEl, 'd', it.finalBandD || ''); if (it.olsEl && it.olsCoords) { patchAttr(it.olsEl, 'x1', it.olsCoords.x1.toFixed(1)); patchAttr(it.olsEl, 'y1', it.olsCoords.y1.toFixed(1)); patchAttr(it.olsEl, 'x2', it.olsCoords.x2.toFixed(1)); patchAttr(it.olsEl, 'y2', it.olsCoords.y2.toFixed(1)); } continue; } let maxDelta = 0; for (let i = 0; i < it.gridPts.length; i++) { const a = prevGrid[i]; const b = it.gridPts[i]; maxDelta = Math.max( maxDelta, Math.abs(b.fitY - a.fitY), Math.abs(b.highY - a.highY), Math.abs(b.lowY - a.lowY), Math.abs(b.x - a.x) ); } if (maxDelta < 0.25) { stateByKey.set(it.key, { committedGrid: it.gridPts, liveGrid: null, ols: it.olsCoords || null, }); patchAttr(it.curveEl, 'd', it.finalCurveD); if (it.bandEl) patchAttr(it.bandEl, 'd', it.finalBandD || ''); if (it.olsEl && it.olsCoords) { patchAttr(it.olsEl, 'x1', it.olsCoords.x1.toFixed(1)); patchAttr(it.olsEl, 'y1', it.olsCoords.y1.toFixed(1)); patchAttr(it.olsEl, 'x2', it.olsCoords.x2.toFixed(1)); patchAttr(it.olsEl, 'y2', it.olsCoords.y2.toFixed(1)); } continue; } const activeLive = prevGrid.map((g) => ({ ...g })); const fromOls = prevEntry?.ols || it.olsCoords || null; const stateRec = { committedGrid: it.gridPts, liveGrid: activeLive, ols: fromOls ? { ...fromOls } : null, }; stateByKey.set(it.key, stateRec); patchAttr(it.curveEl, 'd', buildGridFitPolylineD(activeLive)); if (it.bandEl) { patchAttr(it.bandEl, 'd', it.finalBandD ? buildGridCiBandD(activeLive) : ''); } if (it.olsEl && fromOls) { patchAttr(it.olsEl, 'x1', fromOls.x1.toFixed(1)); patchAttr(it.olsEl, 'y1', fromOls.y1.toFixed(1)); patchAttr(it.olsEl, 'x2', fromOls.x2.toFixed(1)); patchAttr(it.olsEl, 'y2', fromOls.y2.toFixed(1)); } jobs.push({ it, fromGrid: prevGrid, activeLive, fromOls, stateRec }); } for (const k of Array.from(stateByKey.keys())) { if (!activeSet.has(k)) stateByKey.delete(k); } if (jobs.length === 0) return; const startTs = performance.now(); const step = (nowTs) => { const elapsed = Math.max(0, nowTs - startTs); const rawT = Math.min(1, elapsed / durationMs); if (rawT >= 1) { morphRafId = 0; for (let j = 0; j < jobs.length; j++) { const jb = jobs[j]; jb.stateRec.liveGrid = null; jb.stateRec.ols = jb.it.olsCoords || null; patchAttr(jb.it.curveEl, 'd', jb.it.finalCurveD); if (jb.it.bandEl) patchAttr(jb.it.bandEl, 'd', jb.it.finalBandD || ''); if (jb.it.olsEl && jb.it.olsCoords) { patchAttr(jb.it.olsEl, 'x1', jb.it.olsCoords.x1.toFixed(1)); patchAttr(jb.it.olsEl, 'y1', jb.it.olsCoords.y1.toFixed(1)); patchAttr(jb.it.olsEl, 'x2', jb.it.olsCoords.x2.toFixed(1)); patchAttr(jb.it.olsEl, 'y2', jb.it.olsCoords.y2.toFixed(1)); } } return; } const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); for (let j = 0; j < jobs.length; j++) { const jb = jobs[j]; const { fromGrid, activeLive, it } = jb; for (let i = 0; i < activeLive.length; i++) { const a = fromGrid[i]; const b = it.gridPts[i]; const cur = activeLive[i]; cur.x = a.x + (b.x - a.x) * ease; cur.fitY = a.fitY + (b.fitY - a.fitY) * ease; cur.highY = a.highY + (b.highY - a.highY) * ease; cur.lowY = a.lowY + (b.lowY - a.lowY) * ease; } patchAttr(it.curveEl, 'd', buildGridFitPolylineD(activeLive)); if (it.bandEl && it.finalBandD) { patchAttr(it.bandEl, 'd', buildGridCiBandD(activeLive)); } if (it.olsEl && it.olsCoords && jb.fromOls) { const ox1 = jb.fromOls.x1 + (it.olsCoords.x1 - jb.fromOls.x1) * ease; const oy1 = jb.fromOls.y1 + (it.olsCoords.y1 - jb.fromOls.y1) * ease; const ox2 = jb.fromOls.x2 + (it.olsCoords.x2 - jb.fromOls.x2) * ease; const oy2 = jb.fromOls.y2 + (it.olsCoords.y2 - jb.fromOls.y2) * ease; jb.stateRec.ols = { x1: ox1, y1: oy1, x2: ox2, y2: oy2 }; patchAttr(it.olsEl, 'x1', ox1.toFixed(1)); patchAttr(it.olsEl, 'y1', oy1.toFixed(1)); patchAttr(it.olsEl, 'x2', ox2.toFixed(1)); patchAttr(it.olsEl, 'y2', oy2.toFixed(1)); } } morphRafId = window.requestAnimationFrame(step); }; morphRafId = window.requestAnimationFrame(step); } return { morphFits, cancel, reset, getGrid, getFirstGrid, seedGrid }; } /** * Shared 2D pointer-following floating tooltip & focus-dot tracking controller. * Positions `.trend-tooltip` smoothly around the pointer (`above -> right -> left -> below`), * clamps inside the nearest scrollable viewport container, and arms `.is-tracking` (`150ms`) * on both the tooltip and active SVG focus dots after the initial reveal frame. */ function createFloatingChartTooltipController({ containerEl, tooltipEl, defaultTipWidth = 216, defaultTipHeight = 96, defaultViewWidth = 460, defaultViewHeight = 184, clipSelector = '.view-pane, .cons-view-stage, .models-analytics-pane, .table-viewport', useFloatingClass = true, }) { if (useFloatingClass) { tooltipEl.classList.add('is-floating-tip'); } let cachedWrapRect = null; let cachedClipRect = undefined; let cachedTipW = 0; let cachedTipH = 0; let lastSizeKey = null; let tipTrackRaf = 0; let activeTrackedDots = []; function cancelTrackRaf() { if ( tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function' ) { window.cancelAnimationFrame(tipTrackRaf); } tipTrackRaf = 0; } function invalidateRects() { cachedWrapRect = null; cachedClipRect = undefined; cachedTipW = 0; cachedTipH = 0; lastSizeKey = null; } function getWrapRect() { if (!cachedWrapRect) { cachedWrapRect = containerEl.getBoundingClientRect?.() || null; } return cachedWrapRect; } function syncTrackedDots(nextDots, isTrackingActive) { const nextList = Array.isArray(nextDots) ? nextDots.filter(Boolean) : []; for (let i = 0; i < activeTrackedDots.length; i++) { const prevDot = activeTrackedDots[i]; if (!nextList.includes(prevDot)) { patchClasses(prevDot, { 'is-tracking': false }); } } if (isTrackingActive) { for (let i = 0; i < nextList.length; i++) { patchClasses(nextList[i], { 'is-tracking': true }); } } activeTrackedDots = nextList; } function armTracking(wasHidden, nextDots) { if (!wasHidden) { syncTrackedDots(nextDots, tooltipEl.classList.contains('is-tracking')); return; } patchClasses(tooltipEl, { 'is-tracking': false }); const dotList = Array.isArray(nextDots) ? nextDots.filter(Boolean) : []; for (let i = 0; i < dotList.length; i++) { patchClasses(dotList[i], { 'is-tracking': false }); } activeTrackedDots = dotList; void tooltipEl.offsetWidth; cancelTrackRaf(); if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { tipTrackRaf = window.requestAnimationFrame(() => { tipTrackRaf = 0; if (!tooltipEl.hasAttribute('hidden')) { patchClasses(tooltipEl, { 'is-tracking': true }); for (let i = 0; i < activeTrackedDots.length; i++) { patchClasses(activeTrackedDots[i], { 'is-tracking': true }); } } }); } else { patchClasses(tooltipEl, { 'is-tracking': true }); for (let i = 0; i < activeTrackedDots.length; i++) { patchClasses(activeTrackedDots[i], { 'is-tracking': true }); } } } function positionNearAnchor({ fallbackX, fallbackY, pointer = null, viewWidth = defaultViewWidth, viewHeight = defaultViewHeight, remeasureTip = false, }) { const wrapRect = getWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(containerEl.clientWidth || viewWidth || defaultViewWidth); const wrapH = wrapRect && wrapRect.height > 0 ? wrapRect.height : Number(containerEl.offsetHeight || viewHeight || defaultViewHeight); if (remeasureTip || !(cachedTipW > 0) || !(cachedTipH > 0)) { cachedTipW = Number(tooltipEl.offsetWidth || 0) || defaultTipWidth; cachedTipH = Number(tooltipEl.offsetHeight || 0) || defaultTipHeight; } const tipW = cachedTipW; const tipH = cachedTipH; const hasPointer = pointer && Number.isFinite(Number(pointer.clientX)) && Number.isFinite(Number(pointer.clientY)) && wrapRect && wrapRect.width > 0 && wrapRect.height > 0; const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX; const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY; if (cachedClipRect === undefined) { const clipEl = containerEl.closest?.(clipSelector) || null; cachedClipRect = clipEl?.getBoundingClientRect?.() || null; } const clipRect = cachedClipRect; const hasClip = Boolean( clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0 ); const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16; const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16; const maxLeft = Math.max(4, wrapW - tipW - 4); let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2)); const aboveY = anchorY - tipH - 14; let topPx; if (aboveY >= minY) { topPx = Math.min(maxY, aboveY); } else if (anchorX + 16 + tipW <= wrapW - 4) { leftPx = anchorX + 16; topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); } else if (anchorX - 16 - tipW >= 4) { leftPx = anchorX - 16 - tipW; topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); } else { topPx = Math.max(minY, Math.min(maxY, anchorY + 18)); } patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`); patchStyleVar(tooltipEl, '--tip-shift', '0px'); patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`); } function show({ fallbackX, fallbackY, pointer = null, trackedDots = [], viewWidth = defaultViewWidth, viewHeight = defaultViewHeight, sizeKey = '', }) { const wasHidden = tooltipEl.hasAttribute('hidden'); if (wasHidden) { patchAttr(tooltipEl, 'hidden', false); } const normalizedKey = String(sizeKey || ''); const shouldRemeasure = wasHidden || normalizedKey !== lastSizeKey; lastSizeKey = normalizedKey; positionNearAnchor({ fallbackX, fallbackY, pointer, viewWidth, viewHeight, remeasureTip: shouldRemeasure, }); armTracking(wasHidden, trackedDots); } function hide() { invalidateRects(); cancelTrackRaf(); patchAttr(tooltipEl, 'hidden', true); patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false, 'is-tracking': false, }); for (let i = 0; i < activeTrackedDots.length; i++) { patchClasses(activeTrackedDots[i], { 'is-tracking': false }); } activeTrackedDots = []; } function destroy() { cancelTrackRaf(); invalidateRects(); activeTrackedDots = []; } return { show, hide, getWrapRect, invalidateRects, destroy, }; } return { CHART_CURVE_MORPH_MS, canAnimateChartInBrowser, evalCubicBezier, createReadyClassArmer, pointsToNormalizedCubicSegs, buildPathFromNormalizedSegs, createCubicCurveMorphController, createMultiSeriesCurveMorphController, createFitGridMorphController, createFloatingChartTooltipController }; })(); // --- src/components/charts/TrendAreaChart.js --- const { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart } = (() => { /** * @fileoverview 交互式历史用量趋势图组件 (TrendAreaChart). * 支持双模式自适应切换: * 1. <= 90 天(或整点小时分桶):渲染三次贝塞尔平滑曲线面积图、峰值气泡与对齐多刻度时间轴; * 2. > 90 天(自然日分桶):自动切换为类 GitHub 贡献日历的小格子热力排列(一格一天,7 行星期 × 周列、月份刻度、分位数 5 档热力色阶与底部图例); * 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。 */ /** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ const HEATMAP_DAYS_THRESHOLD = 90; let chartUidCounter = 0; function safeSlotTokens(v) { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; } /** * 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。 * 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平, * 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。 * * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组(长度 >= 2) * @returns {string} SVG `` 的 `d` 属性字符串 */ function buildSmoothSplinePath(points) { let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; for (let i = 0; i < points.length - 1; i++) { const p0 = points[i]; const p1 = points[i + 1]; const cpx1 = p0.x + (p1.x - p0.x) * 0.42; const cpx2 = p1.x - (p1.x - p0.x) * 0.42; d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; } return d; } /** * 根据分桶总数及标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 * * @param {Array<{ label?: string }>} slots * @returns {number[]} */ function computeTickIndices(slots) { const n = slots.length; if (n <= 1) return [0]; const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || ''); const maxDirectTicks = sampleLabel.length > 6 ? 5 : 8; if (n <= maxDirectTicks) { return Array.from({ length: n }, (_, i) => i); } const maxTicks = sampleLabel.length > 6 ? 5 : 6; const set = new Set(); for (let k = 0; k < maxTicks; k++) { const idx = Math.round((k / (maxTicks - 1)) * (n - 1)); set.add(idx); } return Array.from(set).sort((a, b) => a - b); } /** * 基于非零活跃日的分位数阈值计算热力图 5 档色阶(0 ~ 4),避免单日极端峰值压缩其余活跃日的层次对比。 * * @param {number[]} nonZeroValues 已升序排列的正数 Token 列表 * @param {number} maxTokens * @returns {{ q1: number, q2: number, q3: number, maxTokens: number, count: number }} */ function computeHeatmapThresholds(nonZeroValues, maxTokens) { const n = nonZeroValues.length; if (n === 0 || maxTokens <= 0) { return { q1: 0, q2: 0, q3: 0, maxTokens: 0, count: 0 }; } if (n < 4) { return { q1: maxTokens * 0.25, q2: maxTokens * 0.5, q3: maxTokens * 0.75, maxTokens, count: n, }; } return { q1: nonZeroValues[Math.floor((n - 1) * 0.25)], q2: nonZeroValues[Math.floor((n - 1) * 0.5)], q3: nonZeroValues[Math.floor((n - 1) * 0.75)], maxTokens, count: n, }; } function resolveHeatmapLevel(tokens, thresholds) { if (tokens <= 0 || thresholds.maxTokens <= 0) return 0; if (tokens >= thresholds.maxTokens || tokens > thresholds.q3) return 4; if (tokens > thresholds.q2) return 3; if (tokens > thresholds.q1) return 2; return 1; } /** * 解析日期槽位的年份与月份信息(兼容真实时间戳 `startMs` 与测试简写 `label`)。 * * @param {object} slot * @returns {{ year: number, month: number, day: number }} */ function parseSlotCalendarParts(slot) { const sMs = Number(slot?.startMs); if (Number.isFinite(sMs) && sMs > 0) { const d = new Date(sMs); return { year: d.getFullYear(), month: d.getMonth() + 1, day: d.getDate() }; } const m = String(slot?.label || '').match(/^(\d{1,2})\/(\d{1,2})$/); if (m) { return { year: new Date().getFullYear(), month: Number(m[1]), day: Number(m[2]) }; } return { year: new Date().getFullYear(), month: 0, day: 0 }; } /** * 构建热力图顶部与周列对齐的月份刻度标签(自动跳过首尾过窄残月,防止相邻月份文字重叠)。 * * @param {Array} slots * @param {number} firstDow 首日对应的星期行索引(0 = 周一 .. 6 = 周日) * @param {number} totalWeeks 总周列数 * @returns {Array<{ col: number, text: string }>} */ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { if (!slots.length || totalWeeks <= 0) return []; const firstParts = parseSlotCalendarParts(slots[0]); const lastParts = parseSlotCalendarParts(slots[slots.length - 1]); const crossYear = firstParts.year !== lastParts.year; const candidates = []; let prevMonthKey = ''; for (let col = 0; col < totalWeeks; col++) { let chosenParts = null; for (let row = 0; row < 7; row++) { const idx = col * 7 + row - firstDow; if (idx < 0 || idx >= slots.length) continue; const parts = parseSlotCalendarParts(slots[idx]); if (!parts.month) continue; const mKey = `${parts.year}-${parts.month}`; if (col === 0 && !chosenParts) { chosenParts = parts; prevMonthKey = mKey; break; } if (mKey !== prevMonthKey) { chosenParts = parts; prevMonthKey = mKey; break; } } if (chosenParts && chosenParts.month > 0) { candidates.push({ col, year: chosenParts.year, month: chosenParts.month }); } } const baseMinGap = totalWeeks > 40 ? 4 : 3; if ( candidates.length >= 2 && candidates[0].col === 0 && candidates[1].col - candidates[0].col < baseMinGap ) { candidates.shift(); } const ticks = []; let nextAllowedCol = 0; for (let i = 0; i < candidates.length; i++) { const c = candidates[i]; if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue; if (ticks.length > 0 && c.col < nextAllowedCol) continue; const showYear = crossYear && (c.month === 1 || ticks.length === 0); const text = showYear ? t('chart.trend.hmMonthYear', { yy: String(c.year).slice(-2), month: c.month }) : t('chart.trend.hmMonthOnly', { month: c.month }); ticks.push({ col: c.col, text }); nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap); } return ticks; } const EN_SHORT_MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; function normalizeHeatmapMode(mode) { return mode === 'week' || mode === 'month' || mode === 'all' ? mode : 'day'; } function createHeatmapAggAcc(extra = {}) { return { tokens: 0, inputTokens: 0, cacheReadTokens: 0, thinkingTokens: 0, responseTokens: 0, outputTokens: 0, costUsd: 0, calls: 0, minStartMs: Infinity, maxEndMs: 0, firstLabel: '', lastLabel: '', modelMap: new Map(), ...extra, }; } function mergeSlotIntoHeatmapAcc(acc, slot) { if (!slot) return; const tok = safeSlotTokens(slot.tokens); const inTok = safeSlotTokens(slot.inputTokens); const cacheTok = safeSlotTokens(slot.cacheReadTokens); const thinkTok = safeSlotTokens(slot.thinkingTokens); const respTok = safeSlotTokens(slot.responseTokens); const outTok = slot.outputTokens !== undefined && slot.outputTokens !== null ? safeSlotTokens(slot.outputTokens) : thinkTok + respTok; acc.tokens += tok; acc.inputTokens += inTok; acc.cacheReadTokens += cacheTok; acc.thinkingTokens += thinkTok; acc.responseTokens += respTok; acc.outputTokens += outTok; acc.costUsd += Math.max(0, Number(slot.costUsd || 0)); acc.calls += Math.max(0, Number(slot.calls || 0)); const sMs = Number(slot.startMs); const eMs = Number(slot.endMs); if (Number.isFinite(sMs) && sMs > 0 && sMs < acc.minStartMs) { acc.minStartMs = sMs; } if (Number.isFinite(eMs) && eMs > acc.maxEndMs) { acc.maxEndMs = eMs; } else if (Number.isFinite(sMs) && sMs > 0 && sMs + 86_400_000 > acc.maxEndMs) { acc.maxEndMs = sMs + 86_400_000; } const lbl = String(slot.label || ''); if (!acc.firstLabel && lbl) acc.firstLabel = lbl; if (lbl) acc.lastLabel = lbl; const srcModels = Array.isArray(slot.mergedModels) ? slot.mergedModels : Array.isArray(slot.models) ? slot.models : null; if (srcModels) { for (let i = 0; i < srcModels.length; i++) { const m = srcModels[i]; if (!m) continue; const key = String(m.displayText || m.label || m.shortName || ''); if (!key) continue; let cur = acc.modelMap.get(key); if (!cur) { cur = { ...m, calls: 0, inputTokens: 0, cacheReadTokens: 0, thinkingTokens: 0, responseTokens: 0, outputTokens: 0, totalTokens: 0, costUsd: 0, }; acc.modelMap.set(key, cur); } cur.calls += Math.max(0, Number(m.calls || 0)); cur.inputTokens += safeSlotTokens(m.inputTokens); cur.cacheReadTokens += safeSlotTokens(m.cacheReadTokens); cur.thinkingTokens += safeSlotTokens(m.thinkingTokens); cur.responseTokens += safeSlotTokens(m.responseTokens); cur.outputTokens += safeSlotTokens(m.outputTokens); cur.totalTokens += safeSlotTokens(m.totalTokens); cur.costUsd += Math.max(0, Number(m.costUsd || 0)); } } } function finalizeHeatmapBucket(acc, customTitle, shortLabel, buildSegmentsFn) { const hasStart = Number.isFinite(acc.minStartMs) && acc.minStartMs < Infinity && acc.minStartMs > 0; const startMs = hasStart ? acc.minStartMs : 0; const endMs = hasStart && acc.maxEndMs > startMs ? Math.max(startMs + 60_000, acc.maxEndMs - 1) : 0; let modelSegments = []; if (typeof buildSegmentsFn === 'function' && acc.modelMap.size > 0) { const mergedList = Array.from(acc.modelMap.values(), (m) => ({ ...m })).sort( (a, b) => (b.totalTokens || 0) - (a.totalTokens || 0) || (b.calls || 0) - (a.calls || 0) ); modelSegments = buildSegmentsFn(mergedList) || []; } return { startMs, endMs, label: shortLabel || customTitle, fullLabel: customTitle, customTitle, tokens: acc.tokens, inputTokens: acc.inputTokens, cacheReadTokens: acc.cacheReadTokens, thinkingTokens: acc.thinkingTokens, responseTokens: acc.responseTokens, outputTokens: acc.outputTokens, costUsd: +acc.costUsd.toFixed(4), calls: acc.calls, modelSegments, }; } function buildHeatmapBarView(slots, firstDow, totalWeeks, mode, buildSegmentsFn) { if (mode === 'week') { const weekAccs = Array.from({ length: totalWeeks }, () => createHeatmapAggAcc()); for (let i = 0; i < slots.length; i++) { const col = Math.floor((firstDow + i) / 7); if (col >= 0 && col < totalWeeks) { mergeSlotIntoHeatmapAcc(weekAccs[col], slots[i]); } } let maxTok = 0; let peakIdx = 0; let activeWeeks = 0; const nonZero = []; const buckets = weekAccs.map((acc, idx) => { if (acc.tokens > 0) { activeWeeks++; nonZero.push(acc.tokens); } if (acc.tokens >= maxTok) { maxTok = acc.tokens; peakIdx = idx; } const hasValidRange = Number.isFinite(acc.minStartMs) && acc.minStartMs < Infinity && acc.minStartMs > 0; const spanTitle = hasValidRange ? formatDateSpanBadge(acc.minStartMs, Math.max(acc.minStartMs, acc.maxEndMs - 1)) : acc.firstLabel && acc.lastLabel && acc.firstLabel !== acc.lastLabel ? `${acc.firstLabel} ~ ${acc.lastLabel}` : acc.firstLabel || '--'; const shortLbl = acc.firstLabel && acc.lastLabel && acc.firstLabel !== acc.lastLabel ? `${acc.firstLabel}~${acc.lastLabel.split('/').pop()}` : acc.firstLabel || spanTitle; return finalizeHeatmapBucket(acc, spanTitle, shortLbl, buildSegmentsFn); }); nonZero.sort((a, b) => a - b); const thresholds = computeHeatmapThresholds(nonZero, maxTok); const colSpecs = buckets.map((b, col) => { const litRows = b.tokens > 0 && maxTok > 0 ? Math.max(1, Math.min(7, Math.ceil((b.tokens / maxTok) * 7))) : 0; return { bucketIdx: col, litRows, lv: litRows > 0 ? resolveHeatmapLevel(b.tokens, thresholds) : 0, isMonthEdge: false, }; }); const peakB = buckets[peakIdx]; const summaryText = maxTok > 0 && peakB ? t('chart.trend.hmWeekPeak', { active: activeWeeks, total: totalWeeks, label: peakB.label, tokens: formatTokensPrecise(maxTok), }) : t('chart.trend.hmWeekZero', { total: totalWeeks }); return { buckets, colSpecs, summaryText }; } if (mode === 'month') { const monthIndexByKey = new Map(); const monthAccs = []; const colMonthCounts = Array.from({ length: totalWeeks }, () => new Map()); for (let i = 0; i < slots.length; i++) { const slot = slots[i]; const parts = parseSlotCalendarParts(slot); const mKey = `${parts.year}-${parts.month}`; let mIdx = monthIndexByKey.get(mKey); if (mIdx === undefined) { mIdx = monthAccs.length; monthIndexByKey.set(mKey, mIdx); monthAccs.push(createHeatmapAggAcc({ year: parts.year, month: parts.month })); } mergeSlotIntoHeatmapAcc(monthAccs[mIdx], slot); const col = Math.floor((firstDow + i) / 7); if (col >= 0 && col < totalWeeks) { colMonthCounts[col].set(mIdx, (colMonthCounts[col].get(mIdx) || 0) + 1); } } const colMonthIdx = new Array(totalWeeks).fill(0); for (let col = 0; col < totalWeeks; col++) { let bestM = col > 0 ? colMonthIdx[col - 1] : 0; let bestCnt = -1; for (const [mIdx, cnt] of colMonthCounts[col].entries()) { if (cnt >= bestCnt) { bestCnt = cnt; bestM = mIdx; } } colMonthIdx[col] = bestM; } if (monthAccs.length > 0 && totalWeeks >= monthAccs.length) { colMonthIdx[0] = 0; colMonthIdx[totalWeeks - 1] = monthAccs.length - 1; } let maxTok = 0; let peakIdx = 0; let activeMonths = 0; const nonZero = []; const en = isEnglishLocale(); const buckets = monthAccs.map((acc, idx) => { if (acc.tokens > 0) { activeMonths++; nonZero.push(acc.tokens); } if (acc.tokens >= maxTok) { maxTok = acc.tokens; peakIdx = idx; } const mNum = acc.month || 1; const enShort = EN_SHORT_MONTHS[mNum - 1] || `M${mNum}`; const fullTitle = en ? `${enShort} ${acc.year}` : t('cons.monthFullLabel', { year: acc.year, m: mNum }); const shortLbl = en ? enShort : t('cons.monthLabel', { m: mNum }); return finalizeHeatmapBucket(acc, fullTitle, shortLbl, buildSegmentsFn); }); nonZero.sort((a, b) => a - b); const thresholds = computeHeatmapThresholds(nonZero, maxTok); const colSpecs = colMonthIdx.map((mIdx, col) => { const b = buckets[mIdx] || { tokens: 0 }; const litRows = b.tokens > 0 && maxTok > 0 ? Math.max(1, Math.min(7, Math.ceil((b.tokens / maxTok) * 7))) : 0; return { bucketIdx: mIdx, litRows, lv: litRows > 0 ? resolveHeatmapLevel(b.tokens, thresholds) : 0, isMonthEdge: col > 0 && mIdx !== colMonthIdx[col - 1], }; }); const peakB = buckets[peakIdx]; const summaryText = maxTok > 0 && peakB ? t('chart.trend.hmMonthPeak', { active: activeMonths, total: buckets.length, label: peakB.label, tokens: formatTokensPrecise(maxTok), }) : t('chart.trend.hmMonthZero', { total: Math.max(1, buckets.length) }); return { buckets, colSpecs, summaryText }; } // mode === 'all' (累计总量爬升柱阵) const runAcc = createHeatmapAggAcc(); const buckets = new Array(totalWeeks); for (let col = 0; col < totalWeeks; col++) { for (let row = 0; row < 7; row++) { const sIdx = col * 7 + row - firstDow; if (sIdx >= 0 && sIdx < slots.length) { mergeSlotIntoHeatmapAcc(runAcc, slots[sIdx]); } } const hasEnd = Number.isFinite(runAcc.minStartMs) && runAcc.minStartMs < Infinity && runAcc.maxEndMs > 0; const endDayMs = hasEnd ? Math.max(runAcc.minStartMs, runAcc.maxEndMs - 1) : 0; const endDateStr = endDayMs > 0 ? formatDateSpanBadge(endDayMs, endDayMs) : runAcc.lastLabel || '--'; const cumTitle = t('chart.trend.hmCumThrough', { date: endDateStr }); buckets[col] = finalizeHeatmapBucket(runAcc, cumTitle, endDateStr, buildSegmentsFn); } const grandTotal = buckets[totalWeeks - 1]?.tokens || 0; const grandCost = buckets[totalWeeks - 1]?.costUsd || 0; const colSpecs = buckets.map((b, col) => { const litRows = b.tokens > 0 && grandTotal > 0 ? Math.max(1, Math.min(7, Math.ceil((b.tokens / grandTotal) * 7))) : 0; const ratio = grandTotal > 0 ? b.tokens / grandTotal : 0; const lv = litRows === 0 ? 0 : ratio > 0.75 ? 4 : ratio > 0.5 ? 3 : ratio > 0.25 ? 2 : 1; return { bucketIdx: col, litRows, lv, isMonthEdge: false, }; }); const summaryText = t('chart.trend.hmCumSummary', { days: slots.length, tokens: formatTokensPrecise(grandTotal), cost: formatUsd(grandCost), }); return { buckets, colSpecs, summaryText }; } /** * 创建交互式历史趋势组件(<=90 天为 SVG 平滑曲线图,>90 天自动切换为类 GitHub 每日小格子热力图)。 * * @param {{ onSelectSlot?: (slot: object) => void }} [options] * @returns {{ * el: HTMLElement, * update: (series?: Array) => void, * destroy: () => void * }} */ function createTrendAreaChart({ onSelectSlot = null } = {}) { const DEFAULT_VIEW_W = 460; const VIEW_H = 184; const TOP_Y = 26; const BOTTOM_Y = 164; const SPAN_Y = BOTTOM_Y - TOP_Y; let viewW = DEFAULT_VIEW_W; function resolvePlotBounds(w) { const leftX = 1; const rightX = Math.max(leftX + 20, w - 1); return { leftX, rightX, spanX: rightX - leftX }; } const svg = document.createElementNS(SVG_NS, 'svg'); svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); svg.setAttribute('class', 'trend-svg'); svg.setAttribute('aria-hidden', 'true'); // 垂直线性渐变(每实例独立 ID,避免多图表挂载时 SVG url(#...) 冲突) const gradId = `trend-area-grad-${++chartUidCounter}`; const defs = document.createElementNS(SVG_NS, 'defs'); const grad = document.createElementNS(SVG_NS, 'linearGradient'); grad.setAttribute('id', gradId); grad.setAttribute('x1', '0'); grad.setAttribute('y1', '0'); grad.setAttribute('x2', '0'); grad.setAttribute('y2', '1'); const stop1 = document.createElementNS(SVG_NS, 'stop'); stop1.setAttribute('offset', '0%'); stop1.setAttribute('stop-color', 'var(--ctx-cached)'); stop1.setAttribute('stop-opacity', '0.34'); const stop2 = document.createElementNS(SVG_NS, 'stop'); stop2.setAttribute('offset', '100%'); stop2.setAttribute('stop-color', 'var(--ctx-cached)'); stop2.setAttribute('stop-opacity', '0.0'); grad.appendChild(stop1); grad.appendChild(stop2); defs.appendChild(grad); svg.appendChild(defs); // 背景水平与垂直参考网格线(水平网格全宽贴边铺满 0..viewW) const hGridGroup = document.createElementNS(SVG_NS, 'g'); hGridGroup.setAttribute('class', 'trend-grid'); const hGridLines = []; for (const y of [ TOP_Y, Math.round(TOP_Y + SPAN_Y / 3), Math.round(TOP_Y + (SPAN_Y * 2) / 3), BOTTOM_Y, ]) { const line = document.createElementNS(SVG_NS, 'line'); line.setAttribute('x1', '0'); line.setAttribute('y1', String(y)); line.setAttribute('x2', String(viewW)); line.setAttribute('y2', String(y)); hGridGroup.appendChild(line); hGridLines.push(line); } svg.appendChild(hGridGroup); const vGridGroup = document.createElementNS(SVG_NS, 'g'); vGridGroup.setAttribute('class', 'trend-grid trend-v-grid'); svg.appendChild(vGridGroup); const areaPath = document.createElementNS(SVG_NS, 'path'); areaPath.setAttribute('fill', `url(#${gradId})`); svg.appendChild(areaPath); const linePath = document.createElementNS(SVG_NS, 'path'); linePath.setAttribute('class', 'trend-line'); linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); // 悬停十字准星及焦点圆点 const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '12'); hoverLine.setAttribute('y2', String(BOTTOM_Y)); hoverLine.setAttribute('hidden', 'true'); svg.appendChild(hoverLine); const hoverDot = document.createElementNS(SVG_NS, 'circle'); hoverDot.setAttribute('r', '3.2'); hoverDot.setAttribute('class', 'trend-hover-dot'); hoverDot.setAttribute('hidden', 'true'); svg.appendChild(hoverDot); const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0', hidden: true }); // 共享悬停详情浮层卡片(曲线图和热力格子图共用,含分模型四段进度条及底部四通道明细) const tooltipContent = createConsumptionBreakdownContent({ showModelDot: false, monoTitle: true, }); const tooltipEl = h( 'div', { className: 'trend-tooltip is-rich-breakdown', hidden: true }, tooltipContent.children ); // 底部对齐刻度轴(曲线模式) const xAxisEl = h('div', { className: 'trend-x-axis' }); const plotStage = h( 'div', { className: `trend-plot-stage${typeof onSelectSlot === 'function' ? ' is-clickable' : ''}` }, [peakPill, svg] ); // 类 GitHub 每日小格子热力图容器(> 90 天模式) const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') }); const wdayWedEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayWed') }); const wdayFriEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayFri') }); const wdaySunEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdaySun') }); const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [ h('span', { className: 'trend-hm-month-spacer' }), wdayMonEl, h('span', { className: 'trend-hm-wday', text: '' }), wdayWedEl, h('span', { className: 'trend-hm-wday', text: '' }), wdayFriEl, h('span', { className: 'trend-hm-wday', text: '' }), wdaySunEl, ]); const hmMonthsEl = h('div', { className: 'trend-hm-months' }); const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': t('chart.trend.hmAria'), }); const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]); const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]); const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]); const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' }); const hmLessEl = h('span', { text: t('chart.trend.hmLess') }); const hmMoreEl = h('span', { text: t('chart.trend.hmMore') }); const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [ hmLessEl, h('span', { className: 'trend-hm-swatch lv-0' }), h('span', { className: 'trend-hm-swatch lv-1' }), h('span', { className: 'trend-hm-swatch lv-2' }), h('span', { className: 'trend-hm-swatch lv-3' }), h('span', { className: 'trend-hm-swatch lv-4' }), hmMoreEl, ]); const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]); const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [ hmBodyEl, hmFooterEl, ]); const chartWrap = h('div', { className: 'trend-chart-wrap' }, [ plotStage, xAxisEl, heatmapStage, tooltipEl, ]); let currentSlots = []; let currentPts = []; let currentMaxTokens = 0; let currentIsHeatmap = false; let currentHmMode = 'day'; let lastBuildSegmentsFn = null; let currentHeatmapWeeks = 0; let currentHeatmapFirstDow = 0; let currentHeatmapGapPx = 2; let currentCellEls = []; let currentHmBuckets = []; let currentHmBucketCells = []; let currentHmAnchorCells = []; let currentColBucketIdx = []; let hoveredHighlightEls = []; let lastHeatmapSummaryText = ''; let tickElsByIdx = new Map(); let hoveredIdx = -1; let hoveredCellEl = null; let lastPointer = null; let lastRenderSig = ''; const vGridLinePool = []; const xAxisTickPool = []; const hmMonthPool = []; const hmCellPool = []; const curveMorphCtrl = createCubicCurveMorphController(); const peakReadyArmer = createReadyClassArmer(peakPill, 'is-ready'); const tooltipCtrl = createFloatingChartTooltipController({ containerEl: chartWrap, tooltipEl, defaultTipWidth: 216, defaultTipHeight: 104, defaultViewWidth: DEFAULT_VIEW_W, defaultViewHeight: VIEW_H, useFloatingClass: false, }); function populateTooltipContent(slot) { const slotTok = safeSlotTokens(slot.tokens); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; tooltipContent.update({ title: slot.customTitle || formatTrendSlotFullLabel(slot) || slot.label || '--', calls: slot.calls, totalTokens: slotTok, costText: formatUsd(slotCost, { precise: slotCost > 0 && slotCost < 0.1, }), inputTokens: slot.inputTokens, cacheReadTokens: slot.cacheReadTokens, thinkingTokens: slot.thinkingTokens, responseTokens: slot.responseTokens, outputTokens: slot.outputTokens, segments: Array.isArray(slot.modelSegments) ? slot.modelSegments : [], }); } let cachedSvgRect = null; let cachedHmGridRect = null; function invalidateHoverRects() { tooltipCtrl.invalidateRects(); cachedSvgRect = null; cachedHmGridRect = null; } function showLineHoverAtIndex(idx, pointer = null) { if (currentIsHeatmap || idx < 0 || idx >= currentSlots.length || !currentPts[idx]) { clearHover(); return; } const wasHidden = tooltipEl.hasAttribute('hidden'); const changedIdx = idx !== hoveredIdx; hoveredIdx = idx; if (pointer) { lastPointer = pointer; } const slot = currentSlots[idx]; const pt = currentPts[idx]; if (wasHidden || changedIdx) { patchAttr(hoverLine, 'hidden', false); patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); patchAttr(hoverDot, 'hidden', false); patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); patchAttr(peakPill, 'hidden', true); patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false, }); populateTooltipContent(slot); for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); } } const wrapRect = tooltipCtrl.getWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W); const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW; const fallbackY = pt.y + 6; tooltipCtrl.show({ fallbackX, fallbackY, pointer: pointer || lastPointer, trackedDots: [hoverDot], viewWidth: viewW, viewHeight: VIEW_H, }); } function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) { if (!currentIsHeatmap || idx < 0 || idx >= currentHmBuckets.length) { clearHover(); return; } const isBarMode = currentHmMode !== 'day'; const targetCell = isBarMode ? currentHmAnchorCells[idx] || cellEl || null : cellEl || currentHmAnchorCells[idx] || currentCellEls[idx] || null; if (!targetCell) { clearHover(); return; } const wasHidden = tooltipEl.hasAttribute('hidden'); const changedCell = idx !== hoveredIdx || hoveredCellEl !== targetCell; hoveredIdx = idx; if (pointer) { lastPointer = pointer; } if (changedCell || hoveredHighlightEls.length === 0) { for (let i = 0; i < hoveredHighlightEls.length; i++) { patchClasses(hoveredHighlightEls[i], { 'is-hovered': false, 'is-bar-hovered': false, }); } const nextHighlight = currentHmBucketCells[idx] && currentHmBucketCells[idx].length > 0 ? currentHmBucketCells[idx] : [targetCell]; for (let i = 0; i < nextHighlight.length; i++) { patchClasses(nextHighlight[i], { 'is-hovered': !isBarMode, 'is-bar-hovered': isBarMode, }); } hoveredHighlightEls = nextHighlight; hoveredCellEl = targetCell; } const slot = currentHmBuckets[idx]; const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); if (wasHidden || changedCell) { patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false, 'is-line-low': false, }); populateTooltipContent(slot); } const wrapRect = tooltipCtrl.getWrapRect(); const cellRect = targetCell.getBoundingClientRect?.() || null; const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W); let fallbackX = currentHeatmapWeeks > 0 ? ((col + 0.5) / currentHeatmapWeeks) * wrapW : wrapW / 2; let fallbackY = 20 + row * 14; const hasValidCellRect = Boolean( wrapRect && wrapRect.width > 0 && cellRect && cellRect.width > 0 && cellRect.width < wrapRect.width ); if (hasValidCellRect) { fallbackX = cellRect.left + cellRect.width / 2 - wrapRect.left; fallbackY = cellRect.top + cellRect.height / 2 - wrapRect.top; } const rawPtr = pointer || lastPointer; const effectivePtr = isBarMode && rawPtr && hasValidCellRect && Number.isFinite(Number(rawPtr.clientX)) && Number.isFinite(Number(rawPtr.clientY)) ? { clientX: Number(rawPtr.clientX), clientY: Math.min(Number(rawPtr.clientY), cellRect.top + 2), } : rawPtr; tooltipCtrl.show({ fallbackX, fallbackY, pointer: effectivePtr, trackedDots: [], viewWidth: viewW, viewHeight: VIEW_H, }); } function clearHover() { invalidateHoverRects(); tooltipCtrl.hide(); hoveredIdx = -1; lastPointer = null; patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchClasses(hoverDot, { 'is-tracking': false }); if (!currentIsHeatmap && currentMaxTokens > 0) { patchAttr(peakPill, 'hidden', false); } if (hoveredHighlightEls.length > 0) { for (let i = 0; i < hoveredHighlightEls.length; i++) { patchClasses(hoveredHighlightEls[i], { 'is-hovered': false, 'is-bar-hovered': false, }); } hoveredHighlightEls = []; } if (hoveredCellEl) { patchClasses(hoveredCellEl, { 'is-hovered': false, 'is-bar-hovered': false }); hoveredCellEl = null; } for (const el of tickElsByIdx.values()) { patchClasses(el, { 'is-hovered': false }); } } function syncViewWidth() { const measured = Math.round( plotStage.clientWidth || svg.clientWidth || plotStage.getBoundingClientRect?.()?.width || 0 ); if (measured >= 160 && measured !== viewW) { viewW = measured; svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); for (const line of hGridLines) { line.setAttribute('x1', '0'); line.setAttribute('x2', String(viewW)); } return true; } return false; } function handlePointerMove(e) { if (currentIsHeatmap || !currentSlots.length) return; if (!cachedSvgRect) { cachedSvgRect = svg.getBoundingClientRect(); } const rect = cachedSvgRect; if (!rect || rect.width <= 0) { cachedSvgRect = null; return; } const relX = ((e.clientX - rect.left) / rect.width) * viewW; const { leftX, spanX } = resolvePlotBounds(viewW); const ratio = (relX - leftX) / Math.max(1, spanX); const idx = Math.max( 0, Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1))) ); const pointer = Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } : null; showLineHoverAtIndex(idx, pointer); } function findDirectHeatmapCell(e) { let cur = e?.target || null; while (cur && cur !== hmGridEl) { const idxAttr = cur.getAttribute?.('data-slot-idx'); if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') { const idx = Number(idxAttr); if (Number.isFinite(idx) && idx >= 0 && idx < currentHmBuckets.length) { const cellEl = currentHmMode !== 'day' ? currentHmAnchorCells[idx] || cur : cur; return { idx, cellEl }; } } cur = cur.parentNode || null; } return null; } function resolveHeatmapCellFromPointer(e) { const directHit = findDirectHeatmapCell(e); if (directHit) return directHit; const clientX = Number(e?.clientX); const clientY = Number(e?.clientY); if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) { if ( hoveredIdx >= 0 && hoveredIdx < currentHmBuckets.length && currentHmAnchorCells[hoveredIdx] ) { return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; } return null; } if (!cachedHmGridRect) { cachedHmGridRect = hmGridEl.getBoundingClientRect?.() || null; } const rect = cachedHmGridRect; if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) { cachedHmGridRect = null; if ( hoveredIdx >= 0 && hoveredIdx < currentHmBuckets.length && currentHmAnchorCells[hoveredIdx] ) { return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; } return null; } const W = currentHeatmapWeeks; const G = currentHeatmapGapPx; const relX = clientX - rect.left; const relY = clientY - rect.top; if ( relX < -(G + 1) || relX > rect.width + G + 1 || relY < -(G + 1) || relY > rect.height + G + 1 ) { return null; } const pitchX = (rect.width + G) / W; const pitchY = (rect.height + G) / 7; const cellW = Math.max(1, pitchX - G); const cellH = Math.max(1, pitchY - G); // 柱阵模式下按列定位分桶,并在列间隙保持原高亮防闪烁 if (currentHmMode !== 'day') { const approxCol = Math.max(0, Math.min(W - 1, Math.floor((relX + G * 0.5) / pitchX))); if ( hoveredIdx >= 0 && hoveredIdx < currentHmBuckets.length && currentColBucketIdx[approxCol] !== hoveredIdx ) { for (const dc of [-1, 1]) { const nc = approxCol + dc; if (nc < 0 || nc >= W || currentColBucketIdx[nc] !== hoveredIdx) continue; const x0 = nc * pitchX; const dx = relX < x0 ? x0 - relX : relX > x0 + cellW ? relX - (x0 + cellW) : 0; if (dx <= G + 0.75 && currentHmAnchorCells[hoveredIdx]) { return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; } } } const bIdx = currentColBucketIdx[approxCol]; if ( Number.isFinite(bIdx) && bIdx >= 0 && bIdx < currentHmBuckets.length && currentHmAnchorCells[bIdx] ) { return { idx: bIdx, cellEl: currentHmAnchorCells[bIdx] }; } return null; } function distanceToCell(c, r) { const x0 = c * pitchX; const y0 = r * pitchY; const dx = relX < x0 ? x0 - relX : relX > x0 + cellW ? relX - (x0 + cellW) : 0; const dy = relY < y0 ? y0 - relY : relY > y0 + cellH ? relY - (y0 + cellH) : 0; return { chebyshev: Math.max(dx, dy), distSq: dx * dx + dy * dy }; } // 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁和边缘微抖 if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { const curGridPos = currentHeatmapFirstDow + hoveredIdx; const curCol = Math.floor(curGridPos / 7); const curRow = curGridPos % 7; if (distanceToCell(curCol, curRow).chebyshev <= G + 0.75) { return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; } } // 快速扫过或初始落入格子间隙时,按网格步距吸附到最近的有效日期格 const approxCol = Math.max(0, Math.min(W - 1, Math.floor((relX + G * 0.5) / pitchX))); const approxRow = Math.max(0, Math.min(6, Math.floor((relY + G * 0.5) / pitchY))); const directSlotIdx = approxCol * 7 + approxRow - currentHeatmapFirstDow; if ( directSlotIdx >= 0 && directSlotIdx < currentSlots.length && currentCellEls[directSlotIdx] ) { return { idx: directSlotIdx, cellEl: currentCellEls[directSlotIdx] }; } // 首周补位或末周未来空白边缘:仅当仍在相邻有效格的间隙光晕内才吸附,深入纯空白角则清空 let bestIdx = -1; let bestDistSq = Infinity; for (let dc = -1; dc <= 1; dc++) { const c = approxCol + dc; if (c < 0 || c >= W) continue; for (let dr = -1; dr <= 1; dr++) { const r = approxRow + dr; if (r < 0 || r > 6) continue; const sIdx = c * 7 + r - currentHeatmapFirstDow; if (sIdx < 0 || sIdx >= currentSlots.length || !currentCellEls[sIdx]) continue; const d = distanceToCell(c, r); if (d.chebyshev <= G + 1.5 && d.distSq < bestDistSq) { bestDistSq = d.distSq; bestIdx = sIdx; } } } if (bestIdx >= 0) { return { idx: bestIdx, cellEl: currentCellEls[bestIdx] }; } return null; } function handleHeatmapPointer(e) { if (!currentIsHeatmap || !currentHmBuckets.length) return; const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) { clearHover(); return; } const pointer = Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } : null; if (hit.idx !== hoveredIdx || hit.cellEl !== hoveredCellEl || pointer) { showHeatmapHoverAtIndex(hit.idx, hit.cellEl, pointer); } } function handleHeatmapWheel(e) { if (!currentIsHeatmap) return; const maxScrollLeft = (hmScrollEl.scrollWidth || 0) - (hmScrollEl.clientWidth || 0); if (maxScrollLeft <= 2) return; const dy = Number(e.deltaY || 0); const dx = Number(e.deltaX || 0); if (Math.abs(dy) > Math.abs(dx) && dy !== 0) { const prev = hmScrollEl.scrollLeft || 0; const next = Math.max(0, Math.min(maxScrollLeft, prev + dy)); if (next !== prev) { hmScrollEl.scrollLeft = next; e.preventDefault?.(); } } } function handleLineClick(e) { if (currentIsHeatmap || !currentSlots.length || typeof onSelectSlot !== 'function') return; let idx = hoveredIdx; const rect = svg.getBoundingClientRect?.(); if (rect && rect.width > 0 && Number.isFinite(Number(e?.clientX))) { const relX = ((e.clientX - rect.left) / rect.width) * viewW; const { leftX, spanX } = resolvePlotBounds(viewW); const ratio = (relX - leftX) / Math.max(1, spanX); idx = Math.max( 0, Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1))) ); } const slot = currentSlots[idx]; if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) { onSelectSlot(slot); } } function handleHeatmapClick(e) { handleHeatmapPointer(e); if (!currentIsHeatmap || !currentHmBuckets.length || typeof onSelectSlot !== 'function') return; const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) return; const slot = currentHmBuckets[hit.idx]; if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) { onSelectSlot(slot); } } plotStage.addEventListener('mousemove', handlePointerMove); plotStage.addEventListener('click', handleLineClick); plotStage.addEventListener('mouseleave', clearHover); hmGridEl.addEventListener('mouseover', handleHeatmapPointer); hmGridEl.addEventListener('mousemove', handleHeatmapPointer); hmGridEl.addEventListener('click', handleHeatmapClick); hmGridEl.addEventListener('mouseleave', clearHover); hmScrollEl.addEventListener('wheel', handleHeatmapWheel); let resizeObs = null; let onWinResize = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { invalidateHoverRects(); if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) { lastRenderSig = ''; update(currentSlots); } }); resizeObs.observe(plotStage); } else if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') { onWinResize = () => { if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) { lastRenderSig = ''; update(currentSlots); } }; window.addEventListener('resize', onWinResize); } function destroy() { tooltipCtrl.destroy(); curveMorphCtrl.cancel(); peakReadyArmer.cancel(); plotStage.removeEventListener('mousemove', handlePointerMove); plotStage.removeEventListener('click', handleLineClick); plotStage.removeEventListener('mouseleave', clearHover); hmGridEl.removeEventListener('mouseover', handleHeatmapPointer); hmGridEl.removeEventListener('mousemove', handleHeatmapPointer); hmGridEl.removeEventListener('click', handleHeatmapClick); hmGridEl.removeEventListener('mouseleave', clearHover); hmScrollEl.removeEventListener('wheel', handleHeatmapWheel); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { window.removeEventListener('resize', onWinResize); onWinResize = null; } } /** * 根据最新时间分桶序列重绘平滑曲线(<=90天/小时级)或 7×W 矩阵热力图(>90天,支持日/周/月/全部四档)。 */ function update(series = [], opts = {}) { if (opts && opts.heatmapMode !== undefined) { const nextHmMode = normalizeHeatmapMode(opts.heatmapMode); if (nextHmMode !== currentHmMode) { clearHover(); currentHmMode = nextHmMode; } } if (opts && typeof opts.buildModelSegments === 'function') { lastBuildSegmentsFn = opts.buildModelSegments; } const slots = Array.isArray(series) && series.length >= 1 ? series : [ { label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 }, { label: '06:00', fullLabel: '06:00 - 07:00', tokens: 0, calls: 0, costUsd: 0 }, { label: '12:00', fullLabel: '12:00 - 13:00', tokens: 0, calls: 0, costUsd: 0 }, { label: '18:00', fullLabel: '18:00 - 19:00', tokens: 0, calls: 0, costUsd: 0 }, ]; currentSlots = slots; const isHourly = slots[0]?.granularity === 'hour' || slots[0]?.granularity === 'minute' || String(slots[0]?.label || '').includes(':'); const useHeatmap = !isHourly && slots.length > HEATMAP_DAYS_THRESHOLD; const modeChanged = useHeatmap !== currentIsHeatmap; currentIsHeatmap = useHeatmap; if (modeChanged) { clearHover(); curveMorphCtrl.cancel(); } patchClasses(chartWrap, { 'is-heatmap': useHeatmap }); patchAttr(plotStage, 'hidden', useHeatmap); patchAttr(xAxisEl, 'hidden', useHeatmap); patchAttr(heatmapStage, 'hidden', !useHeatmap); if (!useHeatmap) { syncViewWidth(); } let maxTokens = 0; let peakIdx = 0; let activeDays = 0; const nonZeroVals = []; for (let i = 0; i < slots.length; i++) { const tokVal = safeSlotTokens(slots[i]?.tokens); if (tokVal > 0) { activeDays++; nonZeroVals.push(tokVal); } if (tokVal >= maxTokens) { maxTokens = tokVal; peakIdx = i; } } currentMaxTokens = maxTokens; const locale = getEffectiveLocale(); patchText(wdayMonEl, t('chart.trend.wdayMon')); patchText(wdayWedEl, t('chart.trend.wdayWed')); patchText(wdayFriEl, t('chart.trend.wdayFri')); patchText(wdaySunEl, t('chart.trend.wdaySun')); patchAttr(hmGridEl, 'aria-label', t('chart.trend.hmAria')); patchText(hmLessEl, t('chart.trend.hmLess')); patchText(hmMoreEl, t('chart.trend.hmMore')); const sig = `${locale}|${useHeatmap ? `hm:${currentHmMode}` : `line:${viewW}`}|` + slots .map((s) => { const mSig = Array.isArray(s?.modelSegments) ? s.modelSegments .map( (m) => `${m.key}:${m.color}:${m.pctText}:${m.inputTokens || 0}:${m.cacheReadTokens || 0}:${m.thinkingTokens || 0}:${m.responseTokens || 0}` ) .join(',') : ''; const mergedCnt = Array.isArray(s?.mergedModels) ? s.mergedModels.length : 0; return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${safeSlotTokens(s?.inputTokens)}:${safeSlotTokens(s?.cacheReadTokens)}:${safeSlotTokens(s?.thinkingTokens)}:${safeSlotTokens(s?.responseTokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mergedCnt}:${mSig}`; }) .join('|'); if (useHeatmap) { currentPts = []; const isBarMode = currentHmMode !== 'day'; hmWeekdaysEl.style.visibility = isBarMode ? 'hidden' : ''; patchClasses(heatmapStage, { 'is-bar-mode': isBarMode }); if (sig !== lastRenderSig) { lastRenderSig = sig; const firstStartMs = Number(slots[0]?.startMs); const firstDow = Number.isFinite(firstStartMs) && firstStartMs > 0 ? (new Date(firstStartMs).getDay() + 6) % 7 : 0; const totalCells = firstDow + slots.length; const totalWeeks = Math.max(1, Math.ceil(totalCells / 7)); const gapPx = totalWeeks > 42 ? 1.5 : 2; const shouldAutoScrollRight = modeChanged || currentHeatmapWeeks !== totalWeeks; currentHeatmapWeeks = totalWeeks; currentHeatmapFirstDow = firstDow; currentHeatmapGapPx = gapPx; patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks)); patchStyleVar(hmBodyEl, '--hm-gap', `${gapPx}px`); // 就地增量补丁顶部对齐月份标签,避免文字节点销毁重建 const monthTicks = buildHeatmapMonthTicks(slots, firstDow, totalWeeks); for (let i = 0; i < monthTicks.length; i++) { const mt = monthTicks[i]; let mEl = hmMonthPool[i]; if (!mEl) { mEl = h('span', { className: 'trend-hm-month text-mono' }); hmMonthPool.push(mEl); } patchText(mEl, mt.text); patchStyleVar(mEl, '--hm-col', String(mt.col)); if (hmMonthsEl.children[i] !== mEl) { hmMonthsEl.insertBefore(mEl, hmMonthsEl.children[i] || null); } } while (hmMonthsEl.children.length > monthTicks.length) { hmMonthsEl.removeChild(hmMonthsEl.lastChild); } const prevMountedCount = hmGridEl.children.length; if (!isBarMode) { nonZeroVals.sort((a, b) => a - b); const thresholds = computeHeatmapThresholds(nonZeroVals, maxTokens); // 就地增量复用 7 行 × N 周列的每日小格子,首次批量新增节点使用 DocumentFragment 挂载 currentCellEls = new Array(slots.length); const newCellsFrag = totalCells > prevMountedCount && typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : null; for (let nodeIdx = 0; nodeIdx < totalCells; nodeIdx++) { let cellEl = hmCellPool[nodeIdx]; if (!cellEl) { cellEl = h('span', { className: 'trend-hm-cell' }); hmCellPool.push(cellEl); } if (nodeIdx < firstDow) { patchClasses(cellEl, { 'is-pad': true, 'is-hovered': false, 'is-bar-hovered': false, 'is-month-edge': false, 'lv-0': false, 'lv-1': false, 'lv-2': false, 'lv-3': false, 'lv-4': false, }); patchAttr(cellEl, 'aria-hidden', 'true'); patchAttr(cellEl, 'role', null); patchAttr(cellEl, 'data-slot-idx', null); patchAttr(cellEl, 'data-hm-col', null); patchAttr(cellEl, 'data-hm-row', null); } else { const i = nodeIdx - firstDow; const slot = slots[i]; const tok = safeSlotTokens(slot?.tokens); const lv = resolveHeatmapLevel(tok, thresholds); const col = Math.floor(nodeIdx / 7); const row = nodeIdx % 7; patchClasses(cellEl, { 'is-pad': false, 'is-hovered': hoveredIdx === i, 'is-bar-hovered': false, 'is-month-edge': false, 'lv-0': lv === 0, 'lv-1': lv === 1, 'lv-2': lv === 2, 'lv-3': lv === 3, 'lv-4': lv === 4, }); patchAttr(cellEl, 'aria-hidden', null); patchAttr(cellEl, 'role', 'gridcell'); patchAttr(cellEl, 'data-slot-idx', String(i)); patchAttr(cellEl, 'data-hm-col', String(col)); patchAttr(cellEl, 'data-hm-row', String(row)); currentCellEls[i] = cellEl; } if (nodeIdx < prevMountedCount) { if (hmGridEl.children[nodeIdx] !== cellEl) { hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); } } else if (newCellsFrag) { newCellsFrag.appendChild(cellEl); } else { hmGridEl.appendChild(cellEl); } } if (newCellsFrag) { hmGridEl.appendChild(newCellsFrag); } while (hmGridEl.children.length > totalCells) { hmGridEl.removeChild(hmGridEl.lastChild); } currentHmBuckets = slots; currentHmBucketCells = currentCellEls.map((el) => (el ? [el] : [])); currentHmAnchorCells = currentCellEls.slice(); currentColBucketIdx = []; hoveredCellEl = hoveredIdx >= 0 && hoveredIdx < slots.length ? currentCellEls[hoveredIdx] || null : null; hoveredHighlightEls = hoveredCellEl ? [hoveredCellEl] : []; const peakSlot = slots[peakIdx]; lastHeatmapSummaryText = maxTokens > 0 && peakSlot?.label ? t('chart.trend.hmActivePeak', { active: activeDays, total: slots.length, label: peakSlot.label, tokens: formatTokensPrecise(maxTokens), }) : t('chart.trend.hmActiveZero', { total: slots.length }); } else { // 周 / 月 / 全部柱阵模式:保持 7 行 × N 周列点阵几何不变,自底向上点亮对应格数 const barView = buildHeatmapBarView( slots, firstDow, totalWeeks, currentHmMode, lastBuildSegmentsFn ); const totalGridCells = totalWeeks * 7; currentCellEls = []; currentHmBuckets = barView.buckets; currentColBucketIdx = barView.colSpecs.map((s) => s.bucketIdx); const bucketCount = barView.buckets.length; const bucketLitCells = Array.from({ length: bucketCount }, () => []); const bucketBottomCells = Array.from({ length: bucketCount }, () => []); const bucketTopRowCells = Array.from({ length: bucketCount }, () => []); const newCellsFrag = totalGridCells > prevMountedCount && typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : null; for (let nodeIdx = 0; nodeIdx < totalGridCells; nodeIdx++) { let cellEl = hmCellPool[nodeIdx]; if (!cellEl) { cellEl = h('span', { className: 'trend-hm-cell' }); hmCellPool.push(cellEl); } const col = Math.floor(nodeIdx / 7); const row = nodeIdx % 7; const spec = barView.colSpecs[col] || { bucketIdx: 0, litRows: 0, lv: 0, isMonthEdge: false, }; const bIdx = spec.bucketIdx; const topLitRow = spec.litRows > 0 ? 7 - spec.litRows : 6; const isLit = spec.litRows > 0 && row >= topLitRow; const lv = isLit ? spec.lv : 0; const isBarHovered = hoveredIdx === bIdx && (isLit || (spec.litRows === 0 && row === 6)); patchClasses(cellEl, { 'is-pad': false, 'is-hovered': false, 'is-bar-hovered': isBarHovered, 'is-month-edge': Boolean(spec.isMonthEdge), 'lv-0': lv === 0, 'lv-1': lv === 1, 'lv-2': lv === 2, 'lv-3': lv === 3, 'lv-4': lv === 4, }); patchAttr(cellEl, 'aria-hidden', null); patchAttr(cellEl, 'role', 'gridcell'); patchAttr(cellEl, 'data-slot-idx', String(bIdx)); patchAttr(cellEl, 'data-hm-col', String(col)); patchAttr(cellEl, 'data-hm-row', String(row)); if (bIdx >= 0 && bIdx < bucketCount) { if (isLit) bucketLitCells[bIdx].push(cellEl); if (row === 6) bucketBottomCells[bIdx].push(cellEl); if (row === topLitRow) bucketTopRowCells[bIdx].push(cellEl); } if (nodeIdx < prevMountedCount) { if (hmGridEl.children[nodeIdx] !== cellEl) { hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); } } else if (newCellsFrag) { newCellsFrag.appendChild(cellEl); } else { hmGridEl.appendChild(cellEl); } } if (newCellsFrag) { hmGridEl.appendChild(newCellsFrag); } while (hmGridEl.children.length > totalGridCells) { hmGridEl.removeChild(hmGridEl.lastChild); } currentHmBucketCells = barView.buckets.map((_, bIdx) => bucketLitCells[bIdx].length > 0 ? bucketLitCells[bIdx] : bucketBottomCells[bIdx] ); currentHmAnchorCells = barView.buckets.map((_, bIdx) => { const tops = bucketTopRowCells[bIdx]; return tops.length > 0 ? tops[Math.floor(tops.length / 2)] : null; }); hoveredCellEl = hoveredIdx >= 0 && hoveredIdx < bucketCount ? currentHmAnchorCells[hoveredIdx] || null : null; hoveredHighlightEls = hoveredIdx >= 0 && hoveredIdx < bucketCount ? currentHmBucketCells[hoveredIdx] || [] : []; lastHeatmapSummaryText = barView.summaryText; } if (shouldAutoScrollRight && typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => { if (hmScrollEl.scrollWidth > hmScrollEl.clientWidth) { hmScrollEl.scrollLeft = hmScrollEl.scrollWidth; } }); } } else if (currentHmMode === 'day') { const peakSlot = slots[peakIdx]; lastHeatmapSummaryText = maxTokens > 0 && peakSlot?.label ? t('chart.trend.hmActivePeak', { active: activeDays, total: slots.length, label: peakSlot.label, tokens: formatTokensPrecise(maxTokens), }) : t('chart.trend.hmActiveZero', { total: slots.length }); } patchText(hmSummaryEl, lastHeatmapSummaryText); if (hoveredIdx >= currentHmBuckets.length) { clearHover(); } else if (hoveredIdx >= 0) { if (!tooltipEl.hasAttribute('hidden') && currentHmBuckets[hoveredIdx]) { populateTooltipContent(currentHmBuckets[hoveredIdx]); } showHeatmapHoverAtIndex(hoveredIdx, currentHmAnchorCells[hoveredIdx], lastPointer); } return; } if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) { populateTooltipContent(slots[hoveredIdx]); } // --- <= 90 天(或整点/分钟级):渲染平滑面积曲线图(1:1 贴边对齐 + 连续插值形变过渡) --- currentCellEls = []; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); const denom = Math.max(1, maxTokens); const isSingle = slots.length === 1; const pts = slots.map((s, idx) => { const tok = safeSlotTokens(s?.tokens); const x = isSingle ? (leftX + rightX) / 2 : leftX + (idx / Math.max(1, slots.length - 1)) * spanX; const ratio = maxTokens > 0 ? tok / denom : 0; const y = BOTTOM_Y - ratio * SPAN_Y; return { x, y, tokens: tok }; }); currentPts = pts; const nextSegs = pointsToNormalizedCubicSegs(pts, BOTTOM_Y); if (sig !== lastRenderSig) { lastRenderSig = sig; let lineD; let areaD; if (isSingle) { if (maxTokens > 0) { lineD = buildSmoothSplinePath([ { x: leftX, y: BOTTOM_Y }, pts[0], { x: rightX, y: BOTTOM_Y }, ]); } else { const yStr = pts[0].y.toFixed(1); lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; } areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`; } else { lineD = buildSmoothSplinePath(pts); areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; } curveMorphCtrl.morphTo({ nextSegs, leftX, spanX, bottomY: BOTTOM_Y, linePath, areaPath, finalLineD: lineD, finalAreaD: areaD, skipMorph: modeChanged, }); // 就地增量补丁垂直参考网格线及底部 X 轴标签,保持文字常驻不重排不闪烁 const tickIndices = computeTickIndices(slots); tickElsByIdx = new Map(); let vLineCount = 0; let tickCount = 0; for (let i = 0; i < tickIndices.length; i++) { const tIdx = tickIndices[i]; const pt = pts[tIdx]; const slot = slots[tIdx]; if (!pt || !slot) continue; if (i > 0 && i < tickIndices.length - 1) { let vLine = vGridLinePool[vLineCount]; if (!vLine) { vLine = document.createElementNS(SVG_NS, 'line'); vLine.setAttribute('y1', '16'); vLine.setAttribute('y2', String(BOTTOM_Y)); vGridLinePool.push(vLine); } const xFixed = pt.x.toFixed(1); patchAttr(vLine, 'x1', xFixed); patchAttr(vLine, 'x2', xFixed); if (vGridGroup.children[vLineCount] !== vLine) { vGridGroup.insertBefore(vLine, vGridGroup.children[vLineCount] || null); } vLineCount++; } const isFirst = !isSingle && i === 0; const isLast = !isSingle && i === tickIndices.length - 1; const pct = isFirst ? 0 : isLast ? 100 : (pt.x / viewW) * 100; let tickRec = xAxisTickPool[tickCount]; if (!tickRec) { const el = h('span', { className: 'trend-x-tick text-mono' }); const rec = { el, slotIdx: tIdx }; el.onclick = () => { lastPointer = null; showLineHoverAtIndex(rec.slotIdx); }; tickRec = rec; xAxisTickPool.push(tickRec); } tickRec.slotIdx = tIdx; patchClasses(tickRec.el, { 'is-start': isFirst, 'is-end': isLast, 'is-hovered': hoveredIdx === tIdx, }); patchText(tickRec.el, slot.label || ''); patchAttr(tickRec.el, 'title', formatTrendSlotFullLabel(slot) || slot.label || ''); patchStyleVar(tickRec.el, '--tick-x', `${pct.toFixed(2)}%`); if (xAxisEl.children[tickCount] !== tickRec.el) { xAxisEl.insertBefore(tickRec.el, xAxisEl.children[tickCount] || null); } tickElsByIdx.set(tIdx, tickRec.el); tickCount++; } while (vGridGroup.children.length > vLineCount) { vGridGroup.removeChild(vGridGroup.lastChild); } while (xAxisEl.children.length > tickCount) { xAxisEl.removeChild(xAxisEl.lastChild); } } if (maxTokens > 0) { const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; const peakSlot = slots[peakIdx]; const peakText = peakSlot?.label ? t('chart.trend.peakPill', { label: peakSlot.label, tokens: formatTokensPrecise(maxTokens), }) : formatTokensPrecise(maxTokens); patchText(peakPill, peakText); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); peakReadyArmer.arm(); if (hoveredIdx < 0) { patchAttr(peakPill, 'hidden', false); } } else { patchAttr(peakPill, 'hidden', true); } if (hoveredIdx >= slots.length) { clearHover(); } else if (hoveredIdx >= 0) { showLineHoverAtIndex(hoveredIdx, lastPointer); } } function setHeatmapMode(nextMode) { const norm = normalizeHeatmapMode(nextMode); if (norm === currentHmMode) return; clearHover(); currentHmMode = norm; if (currentSlots.length > 0) { update(currentSlots); } } return { el: chartWrap, update, setHeatmapMode, getHeatmapMode: () => currentHmMode, destroy, }; } return { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart }; })(); // --- src/components/charts/stepChartMath.js --- const { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, clampValue, computeLinearFit, computePublicationFit, niceStepNumber, computeNiceYScale, computeNiceXStepTicks, formatYAxisTick, buildPolylinePath, buildSplinePath, computeStepTickIndices, formatStepAxisTag, formatChartMetricValue, formatChartMetricCompact, downsampleStepPointsForPlot, evalStepSplineYAtX } = (() => { /** * @fileoverview Pure regression math (OLS + IRLS-LOESS), nice axis tick generators, * SVG spline/polyline path builders, and step metric formatters extracted from SessionStepCharts.js. */ /** 多模型节点和多曲线对比语义调色板(全部取自 tokens.css 语义变量,兼顾设计一致性和交叉曲线区分度) */ const MODEL_COLOR_VARS = Object.freeze([ 'var(--ctx-cached)', 'var(--ctx-skills)', 'var(--ctx-user-input)', 'var(--ctx-checkpoint)', 'var(--ctx-tool-results)', 'var(--ctx-subagent-msg)', ]); /** * 提取步骤所属的基础模型分组键(和后端 `usage-aggregator.mjs` 中 `modelBreakdown[].label` 严格一致), * 且不受“精简代号 / 原始模型 ID”或“自动压缩”后缀切换影响。 * * @param {object|null|undefined} step * @returns {string} */ function getStepModelGroupKey(step) { if (!step || typeof step !== 'object') return t('fmt.unknownModel'); const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '') .replace(/\s*\[自动压缩\]\s*$/u, '') .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') .trim(); if (rawLabel) return rawLabel; const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '') .replace(/·(?:压缩|Compact)\s*$/iu, '') .trim(); return rawShort || t('fmt.unknownModel'); } /** * 将逆序或混合代理的步骤列表归一化为严格时间升序序列(最旧 -> 最新)。 * * @param {Array} steps * @param {boolean} isMergedAllAgents * @returns {Array} */ function toChronologicalSteps(steps, isMergedAllAgents = false) { if (!Array.isArray(steps) || steps.length === 0) return []; const copy = steps.slice(); if (isMergedAllAgents) { copy.sort( (a, b) => (Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) || (Number(a?.agentIndex) || 0) - (Number(b?.agentIndex) || 0) || (Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) ); return copy; } copy.sort( (a, b) => (Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) || (Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) ); return copy; } function clampValue(v, minVal = 0, maxVal = Infinity) { if (!Number.isFinite(v)) return minVal; return Math.max(minVal, Math.min(maxVal, v)); } /** * 双侧 95% 置信区间对应的 Student-t 临界值近似表(t_{0.975, df})。 * * @param {number} df 残差自由度 * @returns {number} */ function tCritical95(df) { if (!Number.isFinite(df) || df <= 1.5) return 3.182; if (df <= 2.5) return 3.182 + (2.5 - df) * 0.9; if (df <= 3.5) return 2.776 + (3.5 - df) * 0.406; if (df <= 4.5) return 2.571 + (4.5 - df) * 0.205; if (df <= 6) return 2.447; if (df <= 8) return 2.306; if (df <= 10) return 2.228; if (df <= 15) return 2.131; if (df <= 20) return 2.086; if (df <= 30) return 2.042; if (df <= 60) return 2.0; if (df <= 120) return 1.98; return 1.96; } /** * 计算普通最小二乘线性回归(OLS: y = intercept + slope * x)。 * * @param {number[]} ys 样本纵坐标序列 * @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [options] * @returns {{ values: number[], slope: number, intercept: number, mean: number, r: number, r2: number }} */ function computeLinearFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) { const n = Array.isArray(ys) ? ys.length : 0; if (n === 0) { return { values: [], slope: 0, intercept: 0, mean: 0, r: 0, r2: 0 }; } const xArr = Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx); const meanY = ys.reduce((acc, v) => acc + v, 0) / n; if (n === 1) { const c = clampValue(ys[0], minVal, maxVal); return { values: [c], slope: 0, intercept: c, mean: c, r: 0, r2: 0 }; } const meanX = xArr.reduce((acc, v) => acc + v, 0) / n; let sxx = 0; let sxy = 0; let syy = 0; for (let i = 0; i < n; i++) { const dx = xArr[i] - meanX; const dy = ys[i] - meanY; sxx += dx * dx; sxy += dx * dy; syy += dy * dy; } const slope = sxx > 1e-12 ? sxy / sxx : 0; const intercept = meanY - slope * meanX; const r = sxx > 1e-12 && syy > 1e-12 ? clampValue(sxy / Math.sqrt(sxx * syy), -1, 1) : 0; const values = xArr.map((x) => clampValue(intercept + slope * x, minVal, maxVal)); return { values, slope, intercept, mean: meanY, r, r2: r * r }; } /** * 学术论文级回归和 95% 置信带计算引擎(Cleveland & Devlin 高斯局部加权线性回归 LOESS + 精确帽子矩阵标准误, * 小样本 n <= 5 时自动采用精确 OLS 线性回归和双曲 t 分布 95% 置信区间,等同于 R `ggplot2::geom_smooth(se = TRUE)`)。 * * @param {number[]} xs 严格递增或单调的样本横坐标序列 * @param {number[]} ys 样本纵坐标序列 * @param {{ minVal?: number, maxVal?: number, gridSize?: number, span?: number }} [options] */ function computePublicationFit( xs, ys, { minVal = 0, maxVal = Infinity, gridSize = 64, span = 0.5 } = {} ) { const n = Math.min(Array.isArray(xs) ? xs.length : 0, Array.isArray(ys) ? ys.length : 0); if (n === 0) { return { method: 'OLS', mean: 0, sd: 0, slope: 0, intercept: 0, r: 0, r2: 0, sampleFits: [], sampleCiLow: [], sampleCiHigh: [], sampleCiHalf: [], grid: [], }; } const ols = computeLinearFit(ys, { minVal, maxVal, xs }); let syy = 0; for (let i = 0; i < n; i++) { const dy = ys[i] - ols.mean; syy += dy * dy; } const sd = n > 1 ? Math.sqrt(syy / (n - 1)) : 0; if (n === 1) { const val = clampValue(ys[0], minVal, maxVal); return { method: 'OLS', mean: val, sd: 0, slope: 0, intercept: val, r: 0, r2: 0, sampleFits: [val], sampleCiLow: [val], sampleCiHigh: [val], sampleCiHalf: [0], grid: [{ x: xs[0], fit: val, ciLow: val, ciHigh: val }], }; } const xMin = xs[0]; const xMax = xs[n - 1]; const xSpan = Math.max(1e-9, xMax - xMin); const M = Math.max(2, gridSize); const gridXs = Array.from({ length: M }, (_, k) => xMin + (k / (M - 1)) * xSpan); // 小样本(n <= 5):采用精确 OLS 线性回归和 Student-t 双曲 95% CI 置信带 if (n <= 5) { const meanX = xs.reduce((a, b) => a + b, 0) / n; let sxx = 0; let sse = 0; for (let i = 0; i < n; i++) { const dx = xs[i] - meanX; sxx += dx * dx; const resid = ys[i] - (ols.intercept + ols.slope * xs[i]); sse += resid * resid; } const df = n - 2; const seResid = df >= 1 ? Math.sqrt(sse / df) : 0; const tCrit = df >= 1 ? tCritical95(df) : 0; const evalOlsAt = (x0) => { const rawFit = ols.intercept + ols.slope * x0; const sePred = seResid > 0 ? seResid * Math.sqrt(1 / n + (sxx > 1e-12 ? ((x0 - meanX) * (x0 - meanX)) / sxx : 0)) : 0; const half = tCrit * sePred; return { fit: clampValue(rawFit, minVal, maxVal), ciLow: clampValue(rawFit - half, minVal, maxVal), ciHigh: clampValue(rawFit + half, minVal, maxVal), half, }; }; const sampleEval = xs.map(evalOlsAt); const grid = gridXs.map((gx) => { const g = evalOlsAt(gx); return { x: gx, fit: g.fit, ciLow: g.ciLow, ciHigh: g.ciHigh }; }); return { method: 'OLS', mean: ols.mean, sd, slope: ols.slope, intercept: ols.intercept, r: ols.r, r2: ols.r2, sampleFits: sampleEval.map((e) => e.fit), sampleCiLow: sampleEval.map((e) => e.ciLow), sampleCiHigh: sampleEval.map((e) => e.ciHigh), sampleCiHalf: sampleEval.map((e) => e.half), grid, }; } // n >= 6:Cleveland 高斯局部加权一阶线性回归(LOESS)+ 精确帽子矩阵杠杆度 95% CI 置信带 const q = Math.max(5, Math.min(n, Math.ceil(span * n))); const wBuf = new Float64Array(n); const sortedXs = q <= n && xs.slice(0, n).every( (x, i) => Number.isFinite(x) && (i === 0 || xs[i - 1] <= x) ); function loessBandwidth(x0) { // 有序 x 上的 q 个最近样本可取连续区间;二分比较两端,避免每个拟合点都排序。 let left = 0; let right = n - q; while (left < right) { const mid = (left + right) >>> 1; if (x0 - xs[mid] > xs[mid + q] - x0) { left = mid + 1; } else { right = mid; } } return Math.max(Math.abs(xs[left] - x0), Math.abs(xs[left + q - 1] - x0)); } function evalLoessPoint(x0, diagIdx = -1) { let h; if (sortedXs) { h = loessBandwidth(x0); if (h <= 1e-9) { h = Math.max(Math.abs(xs[0] - x0), Math.abs(xs[n - 1] - x0), xSpan * 0.05, 1e-6); } } else { const sortedDists = Array.from({ length: n }, (_, j) => Math.abs(xs[j] - x0)).sort((a, b) => a - b); h = sortedDists[q - 1]; if (h <= 1e-9) { h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6); } } const maxDist = h * 1.0001; let start = 0; let end = n; if (sortedXs) { // 三次权重的支持区间之外权重为零,保留区间内样本原来的累加顺序。 let right = n; while (start < right) { const mid = (start + right) >>> 1; if (x0 - xs[mid] >= maxDist) start = mid + 1; else right = mid; } let left = start; while (left < end) { const mid = (left + end) >>> 1; if (xs[mid] - x0 < maxDist) left = mid + 1; else end = mid; } } let sw = 0; let swx = 0; for (let j = start; j < end; j++) { const u = Math.abs(xs[j] - x0) / maxDist; const base = 1 - u * u * u; const w = u >= 1 ? 0 : base * base * base; wBuf[j] = w; sw += w; swx += w * xs[j]; } if (sw <= 1e-12) { const fallbackVal = ols.intercept + ols.slope * x0; return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n }; } const mx = swx / sw; let sxxW = 0; for (let j = start; j < end; j++) { const w = wBuf[j]; if (w <= 0) continue; const dx = xs[j] - mx; sxxW += w * dx * dx; } const dx0 = x0 - mx; const useSlope = sxxW > 1e-12; const inverseWeightSum = 1 / sw; const slopeScale = useSlope ? dx0 / sxxW : 0; const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0); let rawFit = 0; let leverageNormSq = 0; let diagHat = 0; for (let j = start; j < end; j++) { const w = wBuf[j]; if (w <= 0) continue; const lj = w * inverseWeightSum + (useSlope ? w * (xs[j] - mx) * slopeScale : 0); rawFit += lj * ys[j]; leverageNormSq += lj * lj; if (j === diagIdx) diagHat = lj; } return { rawFit, leverageNormSq, diagHat, localHatDiag }; } const rawSampleFits = new Float64Array(n); const sampleLevSq = new Float64Array(n); let sse = 0; let traceL = 0; let precomputedGridEval = null; // 大样本(n > 200 且 x 单调有序)采用和 R `stats::loess(surface = "interpolate")` 一致的网格插值加速: // 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值和杠杆度,避免 O(N²) 阻塞主线程。 if (n > 200 && sortedXs && M >= 2) { const gridRawFit = new Float64Array(M); const gridLevSq = new Float64Array(M); const gridHatDiag = new Float64Array(M); for (let k = 0; k < M; k++) { const res = evalLoessPoint(gridXs[k], -1); gridRawFit[k] = res.rawFit; gridLevSq[k] = res.leverageNormSq; gridHatDiag[k] = res.localHatDiag; } precomputedGridEval = { gridRawFit, gridLevSq }; const invSpan = (M - 1) / xSpan; const maxK0 = M - 2; for (let i = 0; i < n; i++) { const u = (xs[i] - xMin) * invSpan; const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u); const frac = Math.max(0, Math.min(1, u - k0)); const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]); const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0])); const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]); rawSampleFits[i] = rf; sampleLevSq[i] = ls; traceL += hd; const diff = ys[i] - rf; sse += diff * diff; } } else { for (let i = 0; i < n; i++) { const res = evalLoessPoint(xs[i], i); rawSampleFits[i] = res.rawFit; sampleLevSq[i] = res.leverageNormSq; traceL += res.diagHat; const diff = ys[i] - res.rawFit; sse += diff * diff; } } const dfRes = Math.max(1, n - traceL); const sigmaHat = Math.sqrt(sse / dfRes); const tCrit = tCritical95(dfRes); const sampleFits = new Array(n); const sampleCiLow = new Array(n); const sampleCiHigh = new Array(n); const sampleCiHalf = new Array(n); let clampedSse = 0; for (let i = 0; i < n; i++) { const fitVal = clampValue(rawSampleFits[i], minVal, maxVal); const half = tCrit * sigmaHat * Math.sqrt(sampleLevSq[i]); sampleFits[i] = fitVal; sampleCiLow[i] = clampValue(rawSampleFits[i] - half, minVal, maxVal); sampleCiHigh[i] = clampValue(rawSampleFits[i] + half, minVal, maxVal); sampleCiHalf[i] = half; const d = ys[i] - fitVal; clampedSse += d * d; } const grid = precomputedGridEval ? gridXs.map((gx, k) => { const rf = precomputedGridEval.gridRawFit[k]; const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k])); return { x: gx, fit: clampValue(rf, minVal, maxVal), ciLow: clampValue(rf - half, minVal, maxVal), ciHigh: clampValue(rf + half, minVal, maxVal), }; }) : gridXs.map((gx) => { const res = evalLoessPoint(gx, -1); const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq); return { x: gx, fit: clampValue(res.rawFit, minVal, maxVal), ciLow: clampValue(res.rawFit - half, minVal, maxVal), ciHigh: clampValue(res.rawFit + half, minVal, maxVal), }; }); const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1; return { method: 'LOESS', mean: ols.mean, sd, slope: ols.slope, intercept: ols.intercept, r: ols.r, r2: r2Loess, sampleFits, sampleCiLow, sampleCiHigh, sampleCiHalf, grid, }; } /** * Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。 */ function niceStepNumber(range, round) { if (!Number.isFinite(range) || range <= 0) return 1; const exponent = Math.floor(Math.log10(range)); const fraction = range / 10 ** exponent; let niceFraction; if (round) { if (fraction < 1.5) niceFraction = 1; else if (fraction < 3) niceFraction = 2; else if (fraction < 7) niceFraction = 5; else niceFraction = 10; } else if (fraction <= 1) niceFraction = 1; else if (fraction <= 2) niceFraction = 2; else if (fraction <= 5) niceFraction = 5; else niceFraction = 10; return niceFraction * 10 ** exponent; } function computeNiceYScale(dataMin, dataMax, { minBound = 0, maxBound = Infinity, tickCount = 4 } = {}) { let lo = Number.isFinite(dataMin) ? dataMin : 0; let hi = Number.isFinite(dataMax) ? dataMax : 1; if (minBound === 0 && lo >= 0 && hi > 0 && lo <= hi * 0.32) { lo = 0; } if (hi - lo <= 1e-9) { const pad = lo > 0 ? lo * 0.15 : 1; lo = Math.max(minBound, lo - pad); hi = Math.min(maxBound, hi + pad); if (hi - lo <= 1e-9) { lo = Math.max(minBound, hi - 1); } } else { const pad = (hi - lo) * 0.05; lo = Math.max(minBound, lo - (lo === 0 ? 0 : pad)); hi = Math.min(maxBound, hi + pad); } const rawRange = niceStepNumber(hi - lo, false); const step = niceStepNumber(rawRange / Math.max(2, tickCount - 1), true); let graphMin = Math.max(minBound, Math.floor(lo / step) * step); let graphMax = Math.min(maxBound, Math.ceil(hi / step) * step); if (graphMax - graphMin <= 1e-9) { graphMax = graphMin + step; } const ticks = []; for (let v = graphMin; v <= graphMax + step * 0.25; v += step) { const clamped = clampValue(+v.toPrecision(10), minBound, maxBound); if (ticks.length === 0 || Math.abs(clamped - ticks[ticks.length - 1]) > step * 1e-4) { ticks.push(clamped); } if (ticks.length >= 8) break; } return { min: ticks[0] ?? graphMin, max: ticks[ticks.length - 1] ?? graphMax, step, ticks, }; } function computeNiceXStepTicks(xs) { const n = xs.length; if (n === 0) return []; if (n <= 5) { return Array.from(new Set(xs.map((x) => Math.round(x)))); } const xMin = xs[0]; const xMax = xs[n - 1]; const span = xMax - xMin; if (span <= 5) { return Array.from(new Set(xs.map((x) => Math.round(x)))); } const step = Math.max(1, Math.round(niceStepNumber(span / 4.5, true))); const firstTick = Math.ceil(xMin / step) * step; const ticks = []; if (firstTick - xMin > step * 0.45) { ticks.push(Math.round(xMin)); } for (let v = firstTick; v <= xMax + 1e-6; v += step) { ticks.push(Math.round(v)); if (ticks.length >= 7) break; } if (ticks.length === 0) { return [Math.round(xMin), Math.round(xMax)]; } return ticks; } function formatYAxisTick(metric, val, step) { if (!Number.isFinite(val)) return ''; if (Math.abs(val) < 1e-9) { return metric === 'cost' ? '$0' : metric === 'cache' ? '0%' : metric === 'ttft' ? '0s' : '0'; } if (metric === 'tps') { return step >= 1 ? `${Math.round(val)}` : val.toFixed(1); } if (metric === 'ttft') { return step >= 1 ? `${Math.round(val)}s` : `${val.toFixed(1)}s`; } if (metric === 'cache') { return step >= 1 ? `${Math.round(val)}%` : formatPctNumber(val, { withSymbol: true }); } if (metric === 'cost') { if (step >= 1) return `$${Math.round(val)}`; if (step >= 0.1) return `$${val.toFixed(1)}`; if (step >= 0.01) return `$${val.toFixed(2)}`; return `$${val.toFixed(3)}`; } return String(val); } function buildPolylinePath(points) { if (!points.length) return ''; let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; for (let i = 1; i < points.length; i++) { d += ` L ${points[i].x.toFixed(1)} ${points[i].y.toFixed(1)}`; } return d; } function buildSplinePath(points) { if (!points.length) return ''; if (points.length === 1) { return `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; } let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; for (let i = 0; i < points.length - 1; i++) { const p0 = points[i]; const p1 = points[i + 1]; const cpx1 = p0.x + (p1.x - p0.x) * 0.38; const cpx2 = p1.x - (p1.x - p0.x) * 0.38; d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; } return d; } function computeStepTickIndices(count) { if (count <= 0) return []; if (count <= 6) return Array.from({ length: count }, (_, i) => i); const maxTicks = 6; const set = new Set(); for (let k = 0; k < maxTicks; k++) { set.add(Math.round((k / (maxTicks - 1)) * (count - 1))); } return Array.from(set).sort((a, b) => a - b); } function formatStepAxisTag(st, showAgentPrefix) { const num = `#${Number(st?.stepIndex ?? 0)}`; if (!showAgentPrefix) return num; const badge = formatAgentBadgeText({ agentKind: st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), agentOrdinal: st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), isMain: !st?.isSubagent, isSideQuestion: Boolean(st?.isSideQuestion), sideIndex: st?.sideIndex || 0, index: st?.agentIndex || 0, badgeText: st?.agentBadge, }); return `${badge}${num}`; } function formatChartMetricValue(metric, val) { if (!Number.isFinite(val)) return '—'; switch (metric) { case 'totalTokens': case 'context': return `${formatTokensPrecise(val)} tok`; case 'tps': return formatSpeedMetric(val, ' tok/s'); case 'ttft': return formatMetric(val, 's'); case 'cache': return formatPctNumber(val, { withSymbol: true }); case 'cost': return formatUsd(val, { precise: true }); default: return String(val); } } function formatChartMetricCompact(metric, val) { if (!Number.isFinite(val)) return '—'; switch (metric) { case 'totalTokens': case 'context': return formatTokens(val); case 'tps': return formatSpeedMetric(val, ' tok/s'); case 'ttft': return formatMetric(val, 's'); case 'cache': return formatPctNumber(val, { withSymbol: true }); case 'cost': return formatUsd(val, { precise: true }); default: return String(val); } } /** * Downsamples dense chronological step series (`> maxPoints`, e.g. 1,500–5,000 steps) to an * adaptive visual vertex budget (`~2.1px` per segment) so cubic splines never overplot into an * opaque solid wall while strictly preserving the start step, end step, and exact global peak step. * * @template {{ value?: number }} T * @param {T[]} points * @param {number} [maxPoints=208] * @returns {T[]} */ function downsampleStepPointsForPlot(points, maxPoints = 208) { if (!Array.isArray(points) || points.length <= maxPoints || maxPoints < 8) { return points; } const n = points.length; let globalPeakIdx = -1; let globalPeakVal = -Infinity; for (let i = 0; i < n; i += 1) { const v = Number(points[i]?.value); if (Number.isFinite(v) && v >= globalPeakVal) { globalPeakVal = v; globalPeakIdx = i; } } const out = [points[0]]; const bucketCount = maxPoints - 2; const interiorLen = n - 2; for (let b = 0; b < bucketCount; b += 1) { const bStart = 1 + Math.floor((b * interiorLen) / bucketCount); const bEnd = Math.max(bStart + 1, 1 + Math.floor(((b + 1) * interiorLen) / bucketCount)); let pickIdx = -1; if (globalPeakIdx >= bStart && globalPeakIdx < bEnd) { pickIdx = globalPeakIdx; } else { for (let k = bStart; k < bEnd; k += 1) { if (points[k]?.anomalySummary) { if (pickIdx < 0 || points[k]?.anomalySeverity === 'danger') { pickIdx = k; if (points[k]?.anomalySeverity === 'danger') break; } } } if (pickIdx < 0) { pickIdx = bStart + Math.floor((bEnd - bStart) / 2); } } const picked = points[pickIdx]; if (picked && picked !== out[out.length - 1]) { out.push(picked); } } const lastPt = points[n - 1]; if (lastPt && lastPt !== out[out.length - 1]) { out.push(lastPt); } return out; } /** * Evaluates the exact `y` coordinate on `buildSplinePath(plotPoints)` at horizontal coordinate `targetX` * so overlay markers (such as anomaly dots) sit flush on the rendered curve even between downsampled knots. * * @param {Array<{ x: number, y: number }>} plotPoints * @param {number} targetX * @returns {number} */ function evalStepSplineYAtX(plotPoints, targetX) { if (!Array.isArray(plotPoints) || plotPoints.length === 0) return 0; if (plotPoints.length === 1 || targetX <= plotPoints[0].x) return plotPoints[0].y; const last = plotPoints[plotPoints.length - 1]; if (targetX >= last.x) return last.y; let loIdx = 0; let hiIdx = plotPoints.length - 1; while (loIdx + 1 < hiIdx) { const mid = (loIdx + hiIdx) >>> 1; if (plotPoints[mid].x <= targetX) loIdx = mid; else hiIdx = mid; } const p0 = plotPoints[loIdx]; const p1 = plotPoints[hiIdx]; const dx = p1.x - p0.x; if (!(dx > 1e-6)) return p0.y; const uTarget = Math.max(0, Math.min(1, (targetX - p0.x) / dx)); let sLo = 0; let sHi = 1; for (let it = 0; it < 14; it += 1) { const s = (sLo + sHi) * 0.5; const inv = 1 - s; const u = 3 * inv * inv * s * 0.38 + 3 * inv * s * s * 0.62 + s * s * s; if (u < uTarget) sLo = s; else sHi = s; } const s = (sLo + sHi) * 0.5; return p0.y + (p1.y - p0.y) * s * s * (3 - 2 * s); } return { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, clampValue, computeLinearFit, computePublicationFit, niceStepNumber, computeNiceYScale, computeNiceXStepTicks, formatYAxisTick, buildPolylinePath, buildSplinePath, computeStepTickIndices, formatStepAxisTag, formatChartMetricValue, formatChartMetricCompact, downsampleStepPointsForPlot, evalStepSplineYAtX }; })(); // --- src/components/charts/SessionStepCharts.js --- const { createSessionLineChart, createModelFitChart } = (() => { /** * @fileoverview 当前会话步骤级线性走势图与模型趋势拟合图组件 (SessionStepCharts). * * 包含两部分能力: * 1. `createSessionLineChart`:查看当前会话(支持主代理 / 子代理 / 全部汇总)所有模型的步进变化, * 支持切换 `总Token`(累计调用总量)、`上下文`(单步上下文体积)、`TPS`、`首字`、`费用` 五大维度; * 2. `createModelFitChart`:查看指定模型或全部模型的 `TPS`、`首字`、`缓存`、`费用` 散点与鲁棒局部加权线性回归(LOWESS + OLS 基准)拟合曲线, * 内置视图级模型锁定状态机,进入视图时自动锚定当前调用模型,停留在视图期间绝不随轮询跳变。 */ let sessionChartUid = 0; /** * 创建会话全模型线性走势图(支持 `totalTokens` | `context` | `tps` | `ttft` | `cost`,全宽 1:1 贴边对齐)。 */ function createSessionLineChart() { const DEFAULT_VIEW_W = 460; const VIEW_H = 106; const TOP_Y = 18; const BOTTOM_Y = 94; const SPAN_Y = BOTTOM_Y - TOP_Y; let viewW = DEFAULT_VIEW_W; function resolvePlotBounds(w) { const leftX = 1; const rightX = Math.max(leftX + 20, w - 1); return { leftX, rightX, spanX: rightX - leftX }; } const svg = document.createElementNS(SVG_NS, 'svg'); svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); svg.setAttribute('class', 'sstep-svg'); svg.setAttribute('aria-hidden', 'true'); const gradId = `sstep-line-grad-${++sessionChartUid}`; const defs = document.createElementNS(SVG_NS, 'defs'); const grad = document.createElementNS(SVG_NS, 'linearGradient'); grad.setAttribute('id', gradId); grad.setAttribute('x1', '0'); grad.setAttribute('y1', '0'); grad.setAttribute('x2', '0'); grad.setAttribute('y2', '1'); const stop1 = document.createElementNS(SVG_NS, 'stop'); stop1.setAttribute('offset', '0%'); stop1.setAttribute('stop-color', 'var(--ctx-cached)'); stop1.setAttribute('stop-opacity', '0.28'); const stop2 = document.createElementNS(SVG_NS, 'stop'); stop2.setAttribute('offset', '100%'); stop2.setAttribute('stop-color', 'var(--ctx-cached)'); stop2.setAttribute('stop-opacity', '0.0'); grad.appendChild(stop1); grad.appendChild(stop2); defs.appendChild(grad); svg.appendChild(defs); const gridGroup = document.createElementNS(SVG_NS, 'g'); gridGroup.setAttribute('class', 'trend-grid'); const gridLines = []; for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) { const line = document.createElementNS(SVG_NS, 'line'); line.setAttribute('x1', '0'); line.setAttribute('y1', String(y)); line.setAttribute('x2', String(viewW)); line.setAttribute('y2', String(y)); gridGroup.appendChild(line); gridLines.push(line); } svg.appendChild(gridGroup); const areaPath = document.createElementNS(SVG_NS, 'path'); areaPath.setAttribute('fill', `url(#${gradId})`); svg.appendChild(areaPath); const multiAreaGroup = document.createElementNS(SVG_NS, 'g'); multiAreaGroup.setAttribute('class', 'sstep-multi-area-group'); svg.appendChild(multiAreaGroup); const linePath = document.createElementNS(SVG_NS, 'path'); linePath.setAttribute('class', 'trend-line'); linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); const multiLineGroup = document.createElementNS(SVG_NS, 'g'); multiLineGroup.setAttribute('class', 'sstep-multi-line-group'); svg.appendChild(multiLineGroup); const dotsGroup = document.createElementNS(SVG_NS, 'g'); svg.appendChild(dotsGroup); const anomalyDotsGroup = document.createElementNS(SVG_NS, 'g'); anomalyDotsGroup.setAttribute('class', 'sstep-anomaly-dots'); svg.appendChild(anomalyDotsGroup); const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '10'); hoverLine.setAttribute('y2', String(BOTTOM_Y)); hoverLine.setAttribute('hidden', 'true'); svg.appendChild(hoverLine); const hoverDot = document.createElementNS(SVG_NS, 'circle'); hoverDot.setAttribute('r', '3.4'); hoverDot.setAttribute('class', 'trend-hover-dot'); hoverDot.setAttribute('hidden', 'true'); svg.appendChild(hoverDot); const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', text: t('chart.step.empty'), hidden: true, }); const peakPill = h('span', { className: 'trend-peak-pill text-mono', hidden: true }); const tipHeadLeft = h('span', { className: 'trend-tip-time text-mono' }); const tipHeadRight = h('span', { className: 'trend-tip-calls text-mono' }); const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') }); const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') }); const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') }); const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' }); const tipIoGrid = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [ h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]), h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]), h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]), ]); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), tipIoGrid, tipSub, tipAnomaly, ]); const xAxisEl = h('div', { className: 'trend-x-axis' }); const modelLegendEl = h('div', { className: 'sstep-model-legend', hidden: true }); const plotStage = h('div', { className: 'sstep-plot-stage' }, [ peakPill, emptyHintEl, svg, ]); const rootEl = h('div', { className: 'sstep-chart-wrap' }, [ plotStage, xAxisEl, modelLegendEl, tooltipEl, ]); let currentPoints = []; let currentMaxVal = 0; let currentMetric = 'totalTokens'; let hoveredIdx = -1; let lastPointer = null; let tickElsByIdx = new Map(); let lastSig = ''; let lastPreSig = ''; let lastSummaryBadge = ''; let lastUpdateParams = null; let cachedPlotSvgRect = null; let lastLineMode = ''; let lastSingleLineKey = ''; const multiSeriesNodesByKey = new Map(); const anomalyDotElsByKey = new Map(); const singleCurveMorphCtrl = createCubicCurveMorphController(); const multiCurveMorphCtrl = createMultiSeriesCurveMorphController(); const peakReadyArmer = createReadyClassArmer(peakPill, 'is-ready'); const lineTooltipCtrl = createFloatingChartTooltipController({ containerEl: rootEl, tooltipEl, defaultTipWidth: 212, defaultTipHeight: 86, defaultViewWidth: DEFAULT_VIEW_W, defaultViewHeight: VIEW_H, }); function invalidatePlotSvgRect() { cachedPlotSvgRect = null; lineTooltipCtrl.invalidateRects(); } function syncViewWidth() { const measured = Math.round( plotStage.clientWidth || svg.clientWidth || plotStage.getBoundingClientRect?.()?.width || 0 ); if (measured >= 160 && measured !== viewW) { viewW = measured; svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); for (const line of gridLines) { line.setAttribute('x1', '0'); line.setAttribute('x2', String(viewW)); } return true; } return false; } function showHoverAt(idx, pointer = null, { forceRefresh = false } = {}) { if (idx < 0 || idx >= currentPoints.length) { clearHover(); return; } const wasHidden = tooltipEl.hasAttribute('hidden'); const changedIdx = forceRefresh || wasHidden || idx !== hoveredIdx; hoveredIdx = idx; if (pointer) { lastPointer = pointer; } const pt = currentPoints[idx]; const hasIoParts = Boolean(pt.ioParts); if (changedIdx) { patchAttr(hoverLine, 'hidden', false); patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); patchAttr(hoverDot, 'hidden', false); patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); const hoverAccent = pt.anomalySummary ? pt.anomalySeverity === 'danger' ? 'var(--metric-danger)' : 'var(--metric-warn)' : pt.hoverColor || 'var(--ctx-cached)'; patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent); patchAttr(peakPill, 'hidden', true); patchText(tipHeadLeft, pt.stepTag); patchText(tipHeadRight, pt.modelText); patchText( tipMainLeft, pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') ); patchText(tipMainRight, pt.secondaryRight || ''); patchAttr(tipIoGrid, 'hidden', !hasIoParts); if (hasIoParts) { patchText(tipInLabelEl, t('cons.legInput')); patchText(tipCacheLabelEl, t('cons.legCache')); patchText(tipOutLabelEl, t('cons.legOutput')); patchText(tipInValEl, pt.ioParts.inTok); patchText(tipCacheValEl, pt.ioParts.cacheTok); patchText(tipOutValEl, pt.ioParts.outTok); } patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail); if (!hasIoParts && pt.subDetail) { patchText(tipSub, pt.subDetail); } patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); if (pt.anomalySummary) { patchText(tipAnomaly, pt.anomalySummary); patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' }); } for (const [tIdx, el] of tickElsByIdx.entries()) { patchClasses(el, { 'is-hovered': tIdx === idx }); } } const wrapRect = lineTooltipCtrl.getWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(rootEl.clientWidth || viewW || DEFAULT_VIEW_W); const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW; const fallbackY = pt.y + 4; lineTooltipCtrl.show({ fallbackX, fallbackY, pointer: pointer || lastPointer, trackedDots: [hoverDot], viewWidth: viewW, viewHeight: VIEW_H, sizeKey: `${hasIoParts ? 'io' : pt.subDetail ? 'sub' : 'min'}:${pt.anomalySummary ? 'a' : '0'}`, }); } function clearHover() { hoveredIdx = -1; lastPointer = null; lineTooltipCtrl.hide(); patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); patchClasses(hoverDot, { 'is-tracking': false }); if (currentMaxVal > 0 && currentPoints.some((p) => p.valid)) { patchAttr(peakPill, 'hidden', false); } for (const el of tickElsByIdx.values()) { patchClasses(el, { 'is-hovered': false }); } } plotStage.addEventListener('mousemove', (e) => { if (!currentPoints.length) return; if (!cachedPlotSvgRect) { cachedPlotSvgRect = svg.getBoundingClientRect(); } const rect = cachedPlotSvgRect; if (!rect || rect.width <= 0) { cachedPlotSvgRect = null; return; } const relX = ((e.clientX - rect.left) / rect.width) * viewW; const { leftX, spanX } = resolvePlotBounds(viewW); const ratio = (relX - leftX) / Math.max(1, spanX); const idx = Math.max( 0, Math.min(currentPoints.length - 1, Math.round(ratio * (currentPoints.length - 1))) ); const pointer = Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } : null; showHoverAt(idx, pointer); }); plotStage.addEventListener('mouseleave', () => { invalidatePlotSvgRect(); clearHover(); }); let resizeObs = null; let onWinResize = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { invalidatePlotSvgRect(); if (syncViewWidth() && lastUpdateParams) { lastSig = ''; lastPreSig = ''; update({ ...lastUpdateParams, _skipMorph: true }); } }); resizeObs.observe(plotStage); } else if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') { onWinResize = () => { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; update({ ...lastUpdateParams, _skipMorph: true }); } }; window.addEventListener('resize', onWinResize); } function destroy() { singleCurveMorphCtrl.cancel(); multiCurveMorphCtrl.cancel(); peakReadyArmer.cancel(); lineTooltipCtrl.destroy(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { window.removeEventListener('resize', onWinResize); onWinResize = null; } } /** * @param {{ * steps: Array, * modelGroupKey?: string, * modelGroupKeys?: string[]|null, * modelColorByGroup?: Map|null, * metric: 'totalTokens'|'context'|'tps'|'ttft'|'cost', * showAgentPrefix?: boolean, * displaySettings?: object, * }} params * @returns {{ summaryBadge: string }} */ function update({ steps = [], modelGroupKey = '__all__', modelGroupKeys = null, modelColorByGroup = null, metric = 'totalTokens', showAgentPrefix = false, displaySettings = {}, _skipMorph = false, } = {}) { lastUpdateParams = { steps, modelGroupKey, modelGroupKeys, modelColorByGroup, metric, showAgentPrefix, displaySettings, }; currentMetric = metric; syncViewWidth(); const accentColor = 'var(--ctx-cached)'; patchAttr(stop1, 'stop-color', accentColor); patchAttr(stop2, 'stop-color', accentColor); patchStyleVar(rootEl, '--sstep-accent', accentColor); const rawKeys = Array.isArray(modelGroupKeys) && modelGroupKeys.length > 0 ? modelGroupKeys : [modelGroupKey || '__all__']; const isPooledAll = rawKeys.includes('__all__'); const targetKeys = isPooledAll ? ['__all__'] : Array.from(new Set(rawKeys.map((k) => String(k || '')).filter(Boolean))); const targetKeySet = new Set(targetKeys); const isMultiCompare = !isPooledAll && targetKeys.length >= 2; const matchedSteps = isPooledAll ? steps : steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st))); patchText(emptyHintEl, t('chart.step.empty')); if (!matchedSteps.length) { currentPoints = []; patchClasses(rootEl, { 'is-dense': false }); lastSig = 'empty'; lastPreSig = ''; lastLineMode = ''; lastSingleLineKey = ''; singleCurveMorphCtrl.reset(); multiCurveMorphCtrl.reset(); lastSummaryBadge = t('chart.step.zeroSteps'); invalidatePlotSvgRect(); patchAttr(areaPath, 'd', ''); patchAttr(linePath, 'd', ''); while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild); while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild); anomalyDotElsByKey.clear(); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); patchAttr(modelLegendEl, 'hidden', true); patchAttr(peakPill, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); clearHover(); return { summaryBadge: lastSummaryBadge }; } const locale = getEffectiveLocale(); const extColorSig = modelColorByGroup ? Array.from(modelColorByGroup.entries()) .map(([k, v]) => `${k}=${v}`) .join(',') : ''; let preStepParts = `${matchedSteps.length}:`; for (let i = 0; i < matchedSteps.length; i += 1) { const s = matchedSteps[i]; preStepParts += `${s.stepIndex ?? i},${s.agentIndex ?? 0},${s.modelKey || s.modelShort || ''},${s.inputTokens || 0},${s.cacheReadTokens || 0},${s.outputTokens || 0},${s.contextTokens || 0},${s.tokPerSec ?? ''},${s.ttftSec ?? ''},${s.costUsd ?? ''},${s.anomalySig || ''};`; } const preSig = `${locale}|${viewW}|${metric}|${showAgentPrefix}|${displaySettings?.modelDisplayMode || ''}|${Boolean(displaySettings?.showUpstreamModel)}|${displaySettings?.orchestratorIdMode || ''}|${targetKeys.join(',')}|${extColorSig}|${preStepParts}`; if (preSig === lastPreSig && lastSummaryBadge) { return { summaryBadge: lastSummaryBadge }; } const modelColorMap = new Map(); const modelLabelByGroup = new Map(); if (isMultiCompare) { for (let i = 0; i < targetKeys.length; i++) { const gk = targetKeys[i]; const colorVar = modelColorByGroup?.get(gk) || MODEL_COLOR_VARS[i % MODEL_COLOR_VARS.length]; modelColorMap.set(gk, colorVar); const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, { fallback: gk, }); modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } for (const st of matchedSteps) { const gk = getStepModelGroupKey(st); if (!modelColorMap.has(gk)) { const colorVar = modelColorByGroup?.get(gk) || MODEL_COLOR_VARS[modelColorMap.size % MODEL_COLOR_VARS.length]; modelColorMap.set(gk, colorVar); } if (!modelLabelByGroup.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } let runningTokens = 0; let runningCost = 0; let validSum = 0; let validCount = 0; const perModelRunningTokens = new Map(); const perModelRunningCost = new Map(); const perModelPrevCtx = new Map(); const perModelStats = new Map(); const rawItems = matchedSteps.map((st, idx) => { const gk = getStepModelGroupKey(st); const inTok = Math.max(0, Number(st.inputTokens || 0)); const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); const outTok = Math.max(0, Number(st.outputTokens || 0)); const stepTotalTok = inTok + cacheTok + outTok; runningTokens += stepTotalTok; const modelCumTok = (perModelRunningTokens.get(gk) || 0) + stepTotalTok; perModelRunningTokens.set(gk, modelCumTok); const stepCost = Number.isFinite(Number(st.costUsd)) ? Math.max(0, Number(st.costUsd)) : null; if (stepCost !== null) { runningCost += stepCost; perModelRunningCost.set(gk, (perModelRunningCost.get(gk) || 0) + stepCost); } const modelCumCost = perModelRunningCost.get(gk) || 0; const ctxTok = Math.max(0, Number(st.contextTokens ?? stepTotalTok)); const hasPrevModelCtx = perModelPrevCtx.has(gk); const prevSameModelCtx = hasPrevModelCtx ? perModelPrevCtx.get(gk) : ctxTok; perModelPrevCtx.set(gk, ctxTok); const prevGlobalCtx = idx > 0 ? Math.max( 0, Number( matchedSteps[idx - 1].contextTokens ?? Number(matchedSteps[idx - 1].inputTokens || 0) + Number(matchedSteps[idx - 1].cacheReadTokens || 0) + Number(matchedSteps[idx - 1].outputTokens || 0) ) ) : ctxTok; const hasPrevCtx = isMultiCompare ? hasPrevModelCtx : idx > 0; const ctxDelta = isMultiCompare ? ctxTok - prevSameModelCtx : idx > 0 ? ctxTok - prevGlobalCtx : 0; const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '—' }); const stepTag = formatStepAxisTag(st, showAgentPrefix); let valid = true; let value = 0; let secondaryRight = ''; let subDetail = ''; let ioParts = null; if (metric === 'totalTokens') { value = isMultiCompare ? modelCumTok : runningTokens; secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); ioParts = { inTok: formatTokens(inTok), cacheTok: formatTokens(cacheTok), outTok: formatTokens(outTok), }; subDetail = t('chart.step.ioSplit', ioParts); } else if (metric === 'context') { value = ctxTok; if (hasPrevCtx) { const sign = ctxDelta >= 0 ? '+' : '-'; secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`; } else { secondaryRight = t('chart.step.cacheShort', { pct: Number(st.cacheHitPct ?? 0) }); } subDetail = st.isCompactionStep ? t('chart.step.compactionCheckpoint') : t('chart.step.cacheHitOut', { pct: Number(st.cacheHitPct ?? 0), outTok: formatTokens(outTok), }); } else if (metric === 'tps') { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; value = valid ? Number(st.tokPerSec) : 0; secondaryRight = Number.isFinite(st.ttftSec) ? t('chart.step.ttftShort', { sec: formatMetric(st.ttftSec, '') }) : ''; subDetail = valid ? t('chart.step.outAndCtx', { outTok: formatTokens(outTok), ctxTok: formatTokens(ctxTok), }) : speedReasonText(st.selectedSpeedReason) || (st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noSpeedSample')); } else if (metric === 'ttft') { valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0; value = valid ? Number(st.ttftSec) : 0; secondaryRight = Number.isFinite(st.tokPerSec) ? formatSpeedMetric(st.tokPerSec, ' tok/s') : ''; subDetail = valid ? t('chart.step.ctxAndCache', { ctxTok: formatTokens(ctxTok), pct: Number(st.cacheHitPct ?? 0), }) : st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noTtftSample'); } else if (metric === 'cost') { valid = stepCost !== null; value = valid ? stepCost : 0; const shownCumCost = isMultiCompare ? modelCumCost : runningCost; secondaryRight = t('chart.step.cumCost', { cost: formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 }), }); subDetail = t('chart.step.cacheAndStepTok', { pct: Number(st.cacheHitPct ?? 0), tokens: formatTokens(stepTotalTok), }); } if (valid) { validSum += value; validCount += 1; let stStat = perModelStats.get(gk); if (!stStat) { stStat = { count: 0, sum: 0, max: 0, last: 0, cumTok: 0, cumCost: 0 }; perModelStats.set(gk, stStat); } stStat.count += 1; stStat.sum += value; if (value > stStat.max) stStat.max = value; stStat.last = value; stStat.cumTok = modelCumTok; stStat.cumCost = modelCumCost; } const dotColor = modelColorMap.get(gk) || accentColor; const anomalySummary = formatStepAnomalyInlineSummary(st.anomaly); return { idx, st, stepTag, modelGroupKey: gk, modelText: disp.text, dotColor, hoverColor: isMultiCompare ? dotColor : accentColor, valid, value, secondaryRight, subDetail, ioParts, anomalySummary, anomalySeverity: st.anomaly?.severity || '', }; }); let maxVal = 0; let peakIdx = -1; for (let i = 0; i < rawItems.length; i++) { if (rawItems[i].valid && rawItems[i].value >= maxVal) { maxVal = rawItems[i].value; peakIdx = i; } } currentMaxVal = maxVal; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); const maxPlotPoints = Math.max(128, Math.min(256, Math.floor(spanX / 2.1))); const denom = maxVal > 0 ? maxVal : 1; const isSingle = rawItems.length === 1; const points = rawItems.map((item, i) => { const x = isSingle ? (leftX + rightX) / 2 : leftX + (i / Math.max(1, rawItems.length - 1)) * spanX; const ratio = item.valid && maxVal > 0 ? item.value / denom : 0; const y = item.valid ? BOTTOM_Y - ratio * SPAN_Y : BOTTOM_Y; return { ...item, x, y }; }); const validPoints = points.filter((p) => p.valid); let hoverPoints = points; if (isMultiCompare) { if (points.length > maxPlotPoints * targetKeys.length) { const merged = []; for (const gk of targetKeys) { const rawSeries = points.filter((p) => p.modelGroupKey === gk && p.valid); merged.push(...downsampleStepPointsForPlot(rawSeries, maxPlotPoints)); } merged.sort((a, b) => a.idx - b.idx); if (merged.length > 0) hoverPoints = merged; } } else if (validPoints.length > maxPlotPoints) { hoverPoints = downsampleStepPointsForPlot(validPoints, maxPlotPoints); } currentPoints = hoverPoints; patchClasses(rootEl, { 'is-dense': isMultiCompare ? hoverPoints.length > 120 * targetKeys.length : hoverPoints.length > 120, }); patchAttr(emptyHintEl, 'hidden', validPoints.length > 0); const colorSig = Array.from(modelColorMap.entries()) .map(([k, v]) => `${k}=${v}`) .join(','); const sig = `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + points .map( (p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}:${p.st?.anomalySig || ''}` ) .join('|'); if (sig !== lastSig) { lastSig = sig; while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); const plottedSeriesByKey = new Map(); let singlePlottedPts = null; if (isMultiCompare) { if (lastLineMode === 'single') { const prevSingleSegs = singleCurveMorphCtrl.getCurrentSegs(); if (prevSingleSegs.length > 0) { if (lastSingleLineKey && lastSingleLineKey !== '__all__') { multiCurveMorphCtrl.seedSeries(lastSingleLineKey, prevSingleSegs); } else { for (const gk of targetKeys) { multiCurveMorphCtrl.seedSeries(gk, prevSingleSegs); } } } } singleCurveMorphCtrl.reset(); lastLineMode = 'multi'; lastSingleLineKey = ''; patchAttr(linePath, 'd', ''); patchAttr(areaPath, 'd', ''); for (let ci = multiLineGroup.children.length - 1; ci >= 0; ci--) { const ch = multiLineGroup.children[ci]; if (ch.getAttribute?.('class') === 'sstep-series-single-dot') { ch.remove(); } } const activeGks = new Set(); const morphItems = []; for (const gk of targetKeys) { const seriesColor = modelColorMap.get(gk) || accentColor; const rawSeriesPts = points.filter((p) => p.modelGroupKey === gk && p.valid); const seriesPts = downsampleStepPointsForPlot(rawSeriesPts, maxPlotPoints); if (seriesPts.length === 0) continue; plottedSeriesByKey.set(gk, seriesPts); if (seriesPts.length === 1) { const singleDot = document.createElementNS(SVG_NS, 'circle'); singleDot.setAttribute('cx', seriesPts[0].x.toFixed(1)); singleDot.setAttribute('cy', seriesPts[0].y.toFixed(1)); singleDot.setAttribute('r', '3.1'); singleDot.setAttribute('class', 'sstep-series-single-dot'); patchStyleVar(singleDot, '--sstep-series-color', seriesColor); multiLineGroup.appendChild(singleDot); } else { activeGks.add(gk); let nodes = multiSeriesNodesByKey.get(gk); if (!nodes) { const mArea = document.createElementNS(SVG_NS, 'path'); mArea.setAttribute('class', 'sstep-multi-area'); const mLine = document.createElementNS(SVG_NS, 'path'); mLine.setAttribute('class', 'sstep-fit-line'); mLine.setAttribute('fill', 'none'); nodes = { mArea, mLine }; multiSeriesNodesByKey.set(gk, nodes); } patchStyleVar(nodes.mArea, '--sstep-series-color', seriesColor); patchStyleVar(nodes.mLine, '--sstep-fit-accent', seriesColor); multiAreaGroup.appendChild(nodes.mArea); multiLineGroup.appendChild(nodes.mLine); const seriesLineD = buildSplinePath(seriesPts); const firstX = seriesPts[0].x.toFixed(1); const lastX = seriesPts[seriesPts.length - 1].x.toFixed(1); const seriesAreaD = `${seriesLineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`; morphItems.push({ key: gk, nextSegs: pointsToNormalizedCubicSegs(seriesPts, BOTTOM_Y, { leftX, spanX, }), lineEl: nodes.mLine, areaEl: nodes.mArea, endDotEl: null, endX: NaN, endY: NaN, finalLineD: seriesLineD, finalAreaD: seriesAreaD, }); } } for (const [gk, nodes] of multiSeriesNodesByKey.entries()) { if (!activeGks.has(gk)) { nodes.mArea.remove(); nodes.mLine.remove(); } } multiCurveMorphCtrl.morphSeries({ items: morphItems, leftX, spanX, bottomY: BOTTOM_Y, skipMorph: _skipMorph, allowBaselineEntry: true, }); } else { const nextSingleKey = isPooledAll ? '__all__' : targetKeys[0] || '__all__'; if (lastLineMode === 'multi') { const seedSegs = multiCurveMorphCtrl.getSeriesSegs(nextSingleKey) || multiCurveMorphCtrl.getFirstSegs(); if (seedSegs && seedSegs.length > 0) { singleCurveMorphCtrl.seedSegs(seedSegs); } } multiCurveMorphCtrl.reset(); lastLineMode = 'single'; lastSingleLineKey = nextSingleKey; for (const nodes of multiSeriesNodesByKey.values()) { nodes.mArea.remove(); nodes.mLine.remove(); } const plotValidPoints = downsampleStepPointsForPlot(validPoints, maxPlotPoints); singlePlottedPts = plotValidPoints; if (plotValidPoints.length === 0) { singleCurveMorphCtrl.reset(); patchAttr(linePath, 'd', ''); patchAttr(areaPath, 'd', ''); } else if (plotValidPoints.length === 1) { const yVal = plotValidPoints[0].y; const yStr = yVal.toFixed(1); const lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; const areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`; const flatPts = [ { x: leftX, y: yVal }, { x: rightX, y: yVal }, ]; singleCurveMorphCtrl.morphTo({ nextSegs: pointsToNormalizedCubicSegs(flatPts, BOTTOM_Y, { leftX, spanX }), leftX, spanX, bottomY: BOTTOM_Y, linePath, areaPath, finalLineD: lineD, finalAreaD: areaD, skipMorph: _skipMorph, }); } else { const lineD = buildSplinePath(plotValidPoints); const firstX = plotValidPoints[0].x.toFixed(1); const lastX = plotValidPoints[plotValidPoints.length - 1].x.toFixed(1); const areaD = `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`; singleCurveMorphCtrl.morphTo({ nextSegs: pointsToNormalizedCubicSegs(plotValidPoints, BOTTOM_Y, { leftX, spanX }), leftX, spanX, bottomY: BOTTOM_Y, linePath, areaPath, finalLineD: lineD, finalAreaD: areaD, skipMorph: _skipMorph, }); } } const clusteredAnomalies = []; for (const pt of points) { if (!pt.valid || !pt.anomalySummary) continue; const curvePts = isMultiCompare ? plottedSeriesByKey.get(pt.modelGroupKey) : singlePlottedPts; if (!curvePts || curvePts.length === 0) continue; const onCurveY = curvePts.length === 1 ? curvePts[0].y : evalStepSplineYAtX(curvePts, pt.x); const prevCluster = clusteredAnomalies[clusteredAnomalies.length - 1]; if ( prevCluster && (!isMultiCompare || prevCluster.modelGroupKey === pt.modelGroupKey) && Math.abs(pt.x - prevCluster.x) < 3.0 ) { if (pt.anomalySeverity === 'danger' && prevCluster.severity !== 'danger') { prevCluster.key = `${pt.stepTag}:${pt.modelGroupKey}`; prevCluster.x = pt.x; prevCluster.y = onCurveY; prevCluster.severity = 'danger'; } continue; } clusteredAnomalies.push({ key: `${pt.stepTag}:${pt.modelGroupKey}`, modelGroupKey: pt.modelGroupKey, x: pt.x, y: onCurveY, severity: pt.anomalySeverity === 'danger' ? 'danger' : 'warn', }); } clusteredAnomalies.sort((a, b) => a.severity === 'danger' ? 1 : b.severity === 'danger' ? -1 : 0 ); const activeAnomalyKeys = new Set(); for (const item of clusteredAnomalies) { activeAnomalyKeys.add(item.key); let dotEl = anomalyDotElsByKey.get(item.key); if (!dotEl) { dotEl = document.createElementNS(SVG_NS, 'circle'); dotEl.setAttribute('r', '2.1'); anomalyDotElsByKey.set(item.key, dotEl); } patchAttr(dotEl, 'cx', item.x.toFixed(1)); patchAttr(dotEl, 'cy', item.y.toFixed(1)); patchAttr( dotEl, 'class', `sstep-anomaly-dot${item.severity === 'danger' ? ' is-danger' : ''}` ); anomalyDotsGroup.appendChild(dotEl); } for (const [k, el] of anomalyDotElsByKey.entries()) { if (!activeAnomalyKeys.has(k)) { el.remove(); anomalyDotElsByKey.delete(k); } } const tickIndices = computeStepTickIndices(currentPoints.length); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); tickElsByIdx = new Map(); for (let i = 0; i < tickIndices.length; i++) { const tIdx = tickIndices[i]; const pt = currentPoints[tIdx]; if (!pt) continue; const isFirst = !isSingle && i === 0; const isLast = !isSingle && i === tickIndices.length - 1; const pct = isFirst ? 0 : isLast ? 100 : (pt.x / viewW) * 100; const tickEl = h('span', { className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, text: pt.stepTag, title: `${pt.stepTag} · ${pt.modelText}`, }); patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); tickEl.onclick = () => { lastPointer = null; showHoverAt(tIdx, null); }; xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } while (modelLegendEl.firstChild) modelLegendEl.removeChild(modelLegendEl.firstChild); if (isMultiCompare) { patchAttr(modelLegendEl, 'hidden', false); for (const gk of targetKeys) { const colorVar = modelColorMap.get(gk) || accentColor; const swatch = h('span', { className: 'sstep-legend-line' }); patchStyleVar(swatch, '--swatch-bg', colorVar); const stStat = perModelStats.get(gk); const baseLabel = modelLabelByGroup.get(gk) || gk; let summarySuffix = t('chart.step.noSamples'); if (stStat && stStat.count > 0) { if (metric === 'totalTokens') { summarySuffix = formatTokens(stStat.cumTok); } else if (metric === 'context') { summarySuffix = t('chart.step.peakShort', { val: formatTokens(stStat.max) }); } else if (metric === 'tps' || metric === 'ttft') { summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count); } else if (metric === 'cost') { summarySuffix = formatUsd(stStat.cumCost, { precise: stStat.cumCost > 0 && stStat.cumCost < 0.1, }); } } modelLegendEl.appendChild( h('span', { className: 'sstep-legend-item' }, [ swatch, h('span', { text: `${baseLabel} (${summarySuffix})` }), ]) ); } } else { const showPooledDotLegend = points.length <= 64 && modelColorMap.size > 1; patchAttr(modelLegendEl, 'hidden', !showPooledDotLegend); if (showPooledDotLegend) { for (const [gk, colorVar] of modelColorMap.entries()) { const swatch = h('span', { className: 'sstep-legend-dot' }); patchStyleVar(swatch, '--swatch-bg', colorVar); modelLegendEl.appendChild( h('span', { className: 'sstep-legend-item' }, [ swatch, h('span', { text: modelLabelByGroup.get(gk) || gk }), ]) ); } } } } if (peakIdx >= 0 && validPoints.length > 0 && maxVal > 0) { const peakPt = points[peakIdx]; patchText( peakPill, t('chart.step.peakPill', { tag: peakPt.stepTag, val: formatChartMetricCompact(metric, peakPt.value), }) ); patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); peakReadyArmer.arm(); if (hoveredIdx < 0) patchAttr(peakPill, 'hidden', false); } else { patchAttr(peakPill, 'hidden', true); } if (hoveredIdx >= currentPoints.length) { clearHover(); } else if (hoveredIdx >= 0) { showHoverAt(hoveredIdx, lastPointer, { forceRefresh: true }); } let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length }); const activeCompareCount = isMultiCompare ? targetKeys.length : 1; const multiPrefix = isMultiCompare ? t('chart.step.multiPrefix', { count: activeCompareCount }) : ''; if (metric === 'totalTokens') { summaryBadge = t('chart.step.sumTokens', { prefix: multiPrefix, tokens: formatTokens(runningTokens), }); } else if (metric === 'context') { const lastCtx = points[points.length - 1]?.value || 0; summaryBadge = isMultiCompare ? t('chart.step.peakTokens', { prefix: multiPrefix, tokens: formatTokens(maxVal) }) : t('chart.step.currentCtx', { tokens: formatTokens(lastCtx) }); } else if (metric === 'tps') { summaryBadge = validCount > 0 ? t('chart.step.meanTps', { prefix: multiPrefix, val: (validSum / validCount).toFixed(1), }) : t('chart.step.noValidSamples'); } else if (metric === 'ttft') { summaryBadge = validCount > 0 ? t('chart.step.meanSec', { prefix: multiPrefix, val: (validSum / validCount).toFixed(1), }) : t('chart.step.noValidSamples'); } else if (metric === 'cost') { summaryBadge = t('chart.step.sumCost', { prefix: multiPrefix, cost: formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 }), }); } lastPreSig = preSig; lastSummaryBadge = summaryBadge; return { summaryBadge }; } return { el: rootEl, update, destroy }; } /** * 创建学术论文风格散点回归与 95% 置信带拟合图(全宽 1:1 贴边对齐 + 项目统一冷蓝灰设计语言): * - 全宽水平参考网格与底部线性步序刻度轴(内嵌左对齐 Y 轴刻度标签,零左右缩进留白); * - 半透明冷蓝灰实心观测散点(自然呈现重叠密度); * - 围绕回归曲线的 95% CI 置信区间阴影带(绝不向 y=0 做面积图填充); * - 高斯局部线性回归曲线(LOESS, n >= 6)或精确线性回归(OLS, n <= 5),配相关系数 r 与拟合优度 R²。 */ function createModelFitChart() { const DEFAULT_VIEW_W = 460; const VIEW_H = 136; const TOP_Y = 16; const BOTTOM_Y = 116; const SPAN_Y = BOTTOM_Y - TOP_Y; let viewW = DEFAULT_VIEW_W; function resolveFitBounds(w) { const plotLeft = 2; const plotRight = Math.max(plotLeft + 20, w - 2); return { plotLeft, plotRight, plotSpanX: plotRight - plotLeft }; } const svg = document.createElementNS(SVG_NS, 'svg'); svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); svg.setAttribute('class', 'sstep-svg sstep-fit-svg'); svg.setAttribute('aria-hidden', 'true'); const gridGroup = document.createElementNS(SVG_NS, 'g'); gridGroup.setAttribute('class', 'sstep-sci-grid'); svg.appendChild(gridGroup); const axesGroup = document.createElementNS(SVG_NS, 'g'); axesGroup.setAttribute('class', 'sstep-sci-axes'); svg.appendChild(axesGroup); const multiBandGroup = document.createElementNS(SVG_NS, 'g'); multiBandGroup.setAttribute('class', 'sstep-multi-band-group'); svg.appendChild(multiBandGroup); const scatterGroup = document.createElementNS(SVG_NS, 'g'); scatterGroup.setAttribute('class', 'sstep-scatter-group'); svg.appendChild(scatterGroup); const multiCurveGroup = document.createElementNS(SVG_NS, 'g'); multiCurveGroup.setAttribute('class', 'sstep-multi-curve-group'); svg.appendChild(multiCurveGroup); const ciBandPath = document.createElementNS(SVG_NS, 'path'); ciBandPath.setAttribute('class', 'sstep-ci-band'); svg.appendChild(ciBandPath); const olsLine = document.createElementNS(SVG_NS, 'line'); olsLine.setAttribute('class', 'sstep-ols-line'); olsLine.setAttribute('hidden', 'true'); svg.appendChild(olsLine); const fitPath = document.createElementNS(SVG_NS, 'path'); fitPath.setAttribute('class', 'sstep-fit-line'); fitPath.setAttribute('fill', 'none'); svg.appendChild(fitPath); const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', String(TOP_Y)); hoverLine.setAttribute('y2', String(BOTTOM_Y)); hoverLine.setAttribute('hidden', 'true'); svg.appendChild(hoverLine); const hoverRawDot = document.createElementNS(SVG_NS, 'circle'); hoverRawDot.setAttribute('r', '3.0'); hoverRawDot.setAttribute('class', 'sstep-hover-raw-dot'); hoverRawDot.setAttribute('hidden', 'true'); svg.appendChild(hoverRawDot); const hoverFitDot = document.createElementNS(SVG_NS, 'circle'); hoverFitDot.setAttribute('r', '3.1'); hoverFitDot.setAttribute('class', 'trend-hover-dot'); hoverFitDot.setAttribute('hidden', 'true'); svg.appendChild(hoverFitDot); const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', text: t('chart.fit.empty'), hidden: true, }); const tipHeadLeft = h('span', { className: 'trend-tip-time text-mono' }); const tipHeadRight = h('span', { className: 'trend-tip-calls text-mono' }); const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' }); const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' }); const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]), h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]), tipSub, tipAnomaly, ]); const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') }); const olsLegendTextEl = h('span', { text: t('chart.fit.olsLinear') }); const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [ h('span', { className: 'sstep-fit-swatch is-ols' }), olsLegendTextEl, ]); const obsLegendTextEl = h('span', { text: t('chart.fit.observed') }); const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [ h('span', { className: 'sstep-fit-swatch is-scatter' }), obsLegendTextEl, h('span', { className: 'sstep-fit-swatch is-curve' }), fitMethodLabelEl, h('span', { className: 'sstep-fit-swatch is-ci' }), h('span', { text: '95% CI' }), olsLegendWrapEl, ]); const multiLegendEl = h('div', { className: 'sstep-model-legend', hidden: true }); const fitStatsEl = h('span', { className: 'sstep-fit-delta text-mono text-muted' }); const fitLegendFoot = h('div', { className: 'sstep-fit-foot' }, [ singleLegendEl, multiLegendEl, fitStatsEl, ]); const plotStage = h('div', { className: 'sstep-plot-stage' }, [emptyHintEl, svg]); const rootEl = h('div', { className: 'sstep-chart-wrap' }, [plotStage, fitLegendFoot, tooltipEl]); let currentSamples = []; let currentMetric = 'tps'; let hoveredIdx = -1; let lastFitPointer = null; let lastSig = ''; let lastUpdateParams = null; let fitCacheMetric = ''; const fitCache = new Map(); const multiFitNodesByKey = new Map(); const fitMorphCtrl = createFitGridMorphController(); let lastFitMode = ''; let lastSingleFitKey = ''; const fitTooltipCtrl = createFloatingChartTooltipController({ containerEl: rootEl, tooltipEl, defaultTipWidth: 216, defaultTipHeight: 82, defaultViewWidth: DEFAULT_VIEW_W, defaultViewHeight: VIEW_H, }); function reusePublicationFit(key, xs, ys, maxVal, isMultiCompare) { const previous = fitCache.get(key); if ( previous && previous.xs.length === xs.length && xs.every((x, i) => x === previous.xs[i] && ys[i] === previous.ys[i]) ) { return previous.result; } const result = computePublicationFit(xs, ys, { minVal: 0, maxVal, gridSize: isMultiCompare ? 56 : 64, span: 0.5, }); fitCache.set(key, { xs, ys, result }); return result; } function syncViewWidth() { const measured = Math.round( plotStage.clientWidth || svg.clientWidth || plotStage.getBoundingClientRect?.()?.width || 0 ); if (measured >= 160 && measured !== viewW) { viewW = measured; svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); return true; } return false; } function showHoverAt(idx, pointer = null, { forceRefresh = false } = {}) { if (idx < 0 || idx >= currentSamples.length) { clearHover(); return; } const wasHidden = tooltipEl.hasAttribute('hidden'); const changedIdx = forceRefresh || wasHidden || idx !== hoveredIdx; hoveredIdx = idx; if (pointer) { lastFitPointer = pointer; } const sp = currentSamples[idx]; if (changedIdx) { patchAttr(hoverLine, 'hidden', false); patchAttr(hoverLine, 'x1', sp.x.toFixed(1)); patchAttr(hoverLine, 'x2', sp.x.toFixed(1)); patchAttr(hoverFitDot, 'hidden', false); patchAttr(hoverFitDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverFitDot, 'cy', sp.fitY.toFixed(1)); patchStyleVar(hoverFitDot, '--hover-dot-color', sp.seriesColor || 'var(--accent-primary)'); patchAttr(hoverRawDot, 'hidden', false); patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); patchClasses(hoverRawDot, { 'is-anomaly': Boolean(sp.anomalySummary), 'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'), }); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); patchText( tipMainLeft, t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) ); patchText( tipMainRight, t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) ); patchAttr(tipSub, 'hidden', false); if (sp.compareHint) { patchText(tipSub, sp.compareHint); } else if (currentSamples.length >= 3 && sp.ciHalf > 0) { patchText( tipSub, `95% CI [${formatChartMetricCompact(currentMetric, sp.ciLow)}, ${formatChartMetricCompact(currentMetric, sp.ciHigh)}]` ); } else { const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); patchText( tipSub, t('chart.step.ctxAndCache', { ctxTok: formatTokens(ctxTok), pct: Number(sp.st?.cacheHitPct ?? 0), }) ); } patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary); if (sp.anomalySummary) { patchText(tipAnomaly, sp.anomalySummary); patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' }); } } const wrapRect = fitTooltipCtrl.getWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(rootEl.clientWidth || viewW || DEFAULT_VIEW_W); const fallbackX = (sp.x / Math.max(1, viewW)) * wrapW; const fallbackY = sp.fitY + 4; fitTooltipCtrl.show({ fallbackX, fallbackY, pointer: pointer || lastFitPointer, trackedDots: [hoverFitDot, hoverRawDot], viewWidth: viewW, viewHeight: VIEW_H, sizeKey: sp.anomalySummary ? 'fit:a' : 'fit:0', }); } function clearHover() { hoveredIdx = -1; lastFitPointer = null; fitTooltipCtrl.hide(); patchAttr(hoverLine, 'hidden', true); patchAttr(hoverFitDot, 'hidden', true); patchAttr(hoverRawDot, 'hidden', true); patchClasses(hoverFitDot, { 'is-tracking': false }); patchClasses(hoverRawDot, { 'is-tracking': false }); } let cachedFitSvgRect = null; plotStage.addEventListener('mousemove', (e) => { if (!currentSamples.length) return; if (!cachedFitSvgRect) { cachedFitSvgRect = svg.getBoundingClientRect(); } const rect = cachedFitSvgRect; if (!rect || rect.width <= 0) { cachedFitSvgRect = null; return; } const relX = ((e.clientX - rect.left) / rect.width) * viewW; let lo = 0; let hi = currentSamples.length - 1; while (lo < hi) { const mid = (lo + hi) >>> 1; if (currentSamples[mid].x < relX) lo = mid + 1; else hi = mid; } let bestIdx = lo; if ( lo > 0 && Math.abs(currentSamples[lo - 1].x - relX) <= Math.abs(currentSamples[lo].x - relX) ) { bestIdx = lo - 1; } const pointer = Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } : null; showHoverAt(bestIdx, pointer); }); plotStage.addEventListener('mouseleave', () => { cachedFitSvgRect = null; fitTooltipCtrl.invalidateRects(); clearHover(); }); let resizeObs = null; let onWinResize = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { cachedFitSvgRect = null; fitTooltipCtrl.invalidateRects(); if (syncViewWidth() && lastUpdateParams) { lastSig = ''; update({ ...lastUpdateParams, _skipMorph: true }); } }); resizeObs.observe(plotStage); } else if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') { onWinResize = () => { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; update({ ...lastUpdateParams, _skipMorph: true }); } }; window.addEventListener('resize', onWinResize); } function destroy() { fitMorphCtrl.cancel(); fitTooltipCtrl.destroy(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { window.removeEventListener('resize', onWinResize); onWinResize = null; } } /** * 在给定横坐标 x0 处对某模型的回归网格做线性插值(仅当 x0 位于该模型观测区间内时返回拟合值)。 */ function interpolateSeriesGridFit(grid, x0) { if (!Array.isArray(grid) || grid.length === 0) return null; if (grid.length === 1) { return Math.abs(grid[0].x - x0) < 1e-6 ? grid[0].fit : null; } const gMin = grid[0].x; const gMax = grid[grid.length - 1].x; if (x0 < gMin - 1e-6 || x0 > gMax + 1e-6) return null; if (x0 <= gMin) return grid[0].fit; if (x0 >= gMax) return grid[grid.length - 1].fit; for (let i = 0; i < grid.length - 1; i++) { const a = grid[i]; const b = grid[i + 1]; if (x0 >= a.x && x0 <= b.x) { const span = b.x - a.x; const t = span > 1e-9 ? (x0 - a.x) / span : 0; return a.fit + t * (b.fit - a.fit); } } return grid[grid.length - 1].fit; } /** * 绘制共享的水平网格线、底部步序坐标轴及左对齐内联 Y 轴刻度标签。 */ function renderFitAxesAndGrid({ yScale, mapY, mapX, xs, isSingle, plotLeft, plotRight, metric, showAgentPrefix }) { while (gridGroup.firstChild) gridGroup.removeChild(gridGroup.firstChild); while (axesGroup.firstChild) axesGroup.removeChild(axesGroup.firstChild); const xMin = xs[0]; const xMax = xs[xs.length - 1]; const xSpine = document.createElementNS(SVG_NS, 'line'); xSpine.setAttribute('x1', '0'); xSpine.setAttribute('y1', String(BOTTOM_Y)); xSpine.setAttribute('x2', String(viewW)); xSpine.setAttribute('y2', String(BOTTOM_Y)); xSpine.setAttribute('class', 'sstep-axis-spine'); axesGroup.appendChild(xSpine); for (const tv of yScale.ticks) { const ty = mapY(tv); if (Math.abs(ty - BOTTOM_Y) > 1.5) { const gLine = document.createElementNS(SVG_NS, 'line'); gLine.setAttribute('x1', '0'); gLine.setAttribute('y1', ty.toFixed(1)); gLine.setAttribute('x2', String(viewW)); gLine.setAttribute('y2', ty.toFixed(1)); gridGroup.appendChild(gLine); } const labelEl = document.createElementNS(SVG_NS, 'text'); labelEl.setAttribute('x', '0'); labelEl.setAttribute('y', (ty - 3.5).toFixed(1)); labelEl.setAttribute('text-anchor', 'start'); labelEl.setAttribute('class', 'sstep-axis-label is-y-inline'); labelEl.textContent = formatYAxisTick(metric, tv, yScale.step); axesGroup.appendChild(labelEl); } const xTickEntries = []; if (isSingle) { xTickEntries.push({ xv: Math.round(xMin), tickX: mapX(xMin), labelX: mapX(xMin), anchor: 'middle', }); } else { xTickEntries.push({ xv: Math.round(xMin), tickX: plotLeft, labelX: 0, anchor: 'start', }); const interiorTicks = computeNiceXStepTicks(xs); for (const xv of interiorTicks) { if (xv <= xMin || xv >= xMax) continue; const tx = mapX(xv); if (tx < plotLeft + 38 || tx > plotRight - 38) continue; xTickEntries.push({ xv, tickX: tx, labelX: tx, anchor: 'middle', }); } xTickEntries.push({ xv: Math.round(xMax), tickX: plotRight, labelX: viewW, anchor: 'end', }); } for (const xt of xTickEntries) { const tickMark = document.createElementNS(SVG_NS, 'line'); tickMark.setAttribute('x1', xt.tickX.toFixed(1)); tickMark.setAttribute('y1', String(BOTTOM_Y)); tickMark.setAttribute('x2', xt.tickX.toFixed(1)); tickMark.setAttribute('y2', (BOTTOM_Y + 3.2).toFixed(1)); tickMark.setAttribute('class', 'sstep-axis-tick'); axesGroup.appendChild(tickMark); const labelEl = document.createElementNS(SVG_NS, 'text'); labelEl.setAttribute('x', xt.labelX.toFixed(1)); labelEl.setAttribute('y', (BOTTOM_Y + 13.5).toFixed(1)); labelEl.setAttribute('text-anchor', xt.anchor); labelEl.setAttribute('class', 'sstep-axis-label'); labelEl.textContent = showAgentPrefix ? `${xt.xv}` : `#${xt.xv}`; axesGroup.appendChild(labelEl); } } /** * @param {{ * steps: Array, * modelGroupKey?: string, * modelGroupKeys?: string[]|null, * modelColorByGroup?: Map|null, * metric: 'tps'|'ttft'|'cache'|'cost', * showAgentPrefix?: boolean, * displaySettings?: object, * }} params * @returns {{ sampleCount: number, summaryBadge: string }} */ function update({ steps = [], modelGroupKey = '__all__', modelGroupKeys = null, modelColorByGroup = null, metric = 'tps', showAgentPrefix = false, displaySettings = {}, _skipMorph = false, } = {}) { lastUpdateParams = { steps, modelGroupKey, modelGroupKeys, modelColorByGroup, metric, showAgentPrefix, displaySettings, }; currentMetric = metric; syncViewWidth(); patchStyleVar(rootEl, '--sstep-fit-accent', 'var(--ctx-cached)'); const rawKeys = Array.isArray(modelGroupKeys) && modelGroupKeys.length > 0 ? modelGroupKeys : [modelGroupKey || '__all__']; const isPooledAll = rawKeys.includes('__all__'); const targetKeys = isPooledAll ? ['__all__'] : Array.from(new Set(rawKeys.map((k) => String(k || '')).filter(Boolean))); const targetKeySet = new Set(targetKeys); const isMultiCompare = !isPooledAll && targetKeys.length >= 2; const matchedItems = []; let prevXVal = -Infinity; for (let idx = 0; idx < steps.length; idx++) { const st = steps[idx]; if (!st || typeof st !== 'object') continue; let globalX = showAgentPrefix ? idx + 1 : Number(st.stepIndex ?? idx + 1); if (!Number.isFinite(globalX) || globalX <= prevXVal) { globalX = prevXVal === -Infinity ? idx + 1 : prevXVal + 1; } prevXVal = globalX; const gk = getStepModelGroupKey(st); if (!isPooledAll && !targetKeySet.has(gk)) { continue; } let valid = false; let rawVal = 0; if (metric === 'tps') { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; rawVal = valid ? Number(st.tokPerSec) : 0; } else if (metric === 'ttft') { valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0; rawVal = valid ? Number(st.ttftSec) : 0; } else if (metric === 'cache') { valid = !st.isCompactionStep && Number.isFinite(st.cacheHitPct) && st.cacheHitPct >= 0; rawVal = valid ? Number(st.cacheHitPct) : 0; } else if (metric === 'cost') { valid = Number.isFinite(Number(st.costUsd)) && Number(st.costUsd) >= 0; rawVal = valid ? Number(st.costUsd) : 0; } if (valid) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '—' }); matchedItems.push({ st, gk, xVal: globalX, rawVal, stepTag: formatStepAxisTag(st, showAgentPrefix), modelText: disp.baseText || disp.text, anomalySummary: formatStepAnomalyInlineSummary(st.anomaly), anomalySeverity: st.anomaly?.severity || '', }); } } const locale = getEffectiveLocale(); patchText(emptyHintEl, t('chart.fit.empty')); patchText(obsLegendTextEl, t('chart.fit.observed')); patchText(olsLegendTextEl, t('chart.fit.olsLinear')); if (fitCacheMetric !== metric) { fitCache.clear(); fitCacheMetric = metric; } for (const key of fitCache.keys()) { if (isMultiCompare ? !targetKeySet.has(key) : key !== null) fitCache.delete(key); } if (matchedItems.length === 0) { fitCache.clear(); fitMorphCtrl.reset(); lastFitMode = ''; lastSingleFitKey = ''; currentSamples = []; lastSig = 'empty'; patchAttr(ciBandPath, 'd', ''); patchAttr(fitPath, 'd', ''); patchAttr(olsLine, 'hidden', true); for (const nodes of multiFitNodesByKey.values()) { nodes.bandEl.remove(); nodes.curveEl.remove(); } while (gridGroup.firstChild) gridGroup.removeChild(gridGroup.firstChild); while (axesGroup.firstChild) axesGroup.removeChild(axesGroup.firstChild); while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); patchText(fitMethodLabelEl, t('chart.fit.loess')); patchText(fitStatsEl, 'n = 0'); clearHover(); return { sampleCount: 0, summaryBadge: t('chart.fit.zeroSamples') }; } patchAttr(emptyHintEl, 'hidden', true); const minBound = 0; const maxBound = metric === 'cache' ? 100 : Infinity; // 分支 A:多模型同图独立拟合曲线对比模式(勾选 >= 2 个模型) if (isMultiCompare) { const seriesList = []; for (let kIdx = 0; kIdx < targetKeys.length; kIdx++) { const key = targetKeys[kIdx]; const items = matchedItems.filter((it) => it.gk === key); if (items.length === 0) continue; const xs = items.map((d) => d.xVal); const rawYs = items.map((d) => d.rawVal); const pubFit = reusePublicationFit(key, xs, rawYs, maxBound, true); const colorVar = modelColorByGroup?.get(key) || MODEL_COLOR_VARS[kIdx % MODEL_COLOR_VARS.length]; seriesList.push({ key, label: items[0].modelText || key, colorVar, items, xs, rawYs, pubFit, }); } patchAttr(singleLegendEl, 'hidden', true); patchAttr(multiLegendEl, 'hidden', false); patchAttr(ciBandPath, 'd', ''); patchAttr(fitPath, 'd', ''); patchAttr(olsLine, 'hidden', true); const allXs = matchedItems.map((d) => d.xVal); let dataMin = Infinity; let dataMax = -Infinity; for (const s of seriesList) { for (const v of s.rawYs) { if (v < dataMin) dataMin = v; if (v > dataMax) dataMax = v; } for (const g of s.pubFit.grid) { if (g.ciLow < dataMin) dataMin = g.ciLow; if (g.ciHigh > dataMax) dataMax = g.ciHigh; } } const yScale = computeNiceYScale(dataMin, dataMax, { minBound, maxBound, tickCount: 4, }); const yRange = Math.max(1e-9, yScale.max - yScale.min); const mapY = (v) => BOTTOM_Y - ((clampValue(v, yScale.min, yScale.max) - yScale.min) / yRange) * SPAN_Y; const { plotLeft, plotRight, plotSpanX } = resolveFitBounds(viewW); const xMin = allXs[0]; const xMax = allXs[allXs.length - 1]; const isSingle = matchedItems.length === 1 || xMax - xMin <= 1e-9; const mapX = (xv) => isSingle ? (plotLeft + plotRight) / 2 : plotLeft + ((xv - xMin) / (xMax - xMin)) * plotSpanX; const combinedSamples = []; for (const s of seriesList) { const sSamples = s.items.map((item, i) => { const x = mapX(item.xVal); const rawY = mapY(item.rawVal); const fitVal = s.pubFit.sampleFits[i]; const fitY = mapY(fitVal); const peerParts = []; for (const other of seriesList) { if (other.key === s.key) continue; const interp = interpolateSeriesGridFit(other.pubFit.grid, item.xVal); if (interp !== null) { peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`); } else { peerParts.push( t('chart.fit.peerMean', { label: other.label, val: formatChartMetricCompact(metric, other.pubFit.mean), }) ); } } return { ...item, x, rawY, fitVal, fitY, ciLow: s.pubFit.sampleCiLow[i], ciHigh: s.pubFit.sampleCiHigh[i], ciHalf: s.pubFit.sampleCiHalf[i], seriesColor: s.colorVar, compareHint: peerParts.length > 0 ? t('chart.fit.peerCompare', { peers: peerParts.join(' · ') }) : '', }; }); s.samples = sSamples; combinedSamples.push(...sSamples); } combinedSamples.sort((a, b) => a.x - b.x || a.xVal - b.xVal); currentSamples = combinedSamples; const sig = `multi|${locale}|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + seriesList .map( (s) => `${s.key}:${s.colorVar}:` + s.samples .map( (p) => `${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}:${p.st?.anomalySig || ''}` ) .join(',') ) .join('||'); if (sig !== lastSig) { lastSig = sig; renderFitAxesAndGrid({ yScale, mapY, mapX, xs: allXs, isSingle, plotLeft, plotRight, metric, showAgentPrefix, }); while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); const dotRadius = combinedSamples.length > 80 ? '1.8' : combinedSamples.length > 36 ? '2.1' : '2.4'; const dedupOverdraw = combinedSamples.length > 200; const scatterTarget = typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : scatterGroup; const anomalyOverlayDots = []; const activeFitKeys = new Set(); const fitMorphItems = []; for (const s of seriesList) { const binCounts = dedupOverdraw ? new Map() : null; for (const sp of s.samples) { if (sp.anomalySummary) { anomalyOverlayDots.push(sp); continue; } if (binCounts) { const binKey = (Math.round(sp.x * 2) << 11) ^ Math.round(sp.rawY * 2); const prevCnt = binCounts.get(binKey) || 0; if (prevCnt >= 6) continue; binCounts.set(binKey, prevCnt + 1); } const dot = document.createElementNS(SVG_NS, 'circle'); dot.setAttribute('cx', sp.x.toFixed(1)); dot.setAttribute('cy', sp.rawY.toFixed(1)); dot.setAttribute('r', dotRadius); dot.setAttribute('class', 'sstep-scatter-dot is-multi'); patchStyleVar(dot, '--sstep-fit-accent', s.colorVar); scatterTarget.appendChild(dot); } activeFitKeys.add(s.key); let nodes = multiFitNodesByKey.get(s.key); if (!nodes) { const bandEl = document.createElementNS(SVG_NS, 'path'); bandEl.setAttribute('class', 'sstep-ci-band is-multi'); const curveEl = document.createElementNS(SVG_NS, 'path'); curveEl.setAttribute('class', 'sstep-fit-line'); curveEl.setAttribute('fill', 'none'); nodes = { bandEl, curveEl }; multiFitNodesByKey.set(s.key, nodes); } patchStyleVar(nodes.bandEl, '--sstep-fit-accent', s.colorVar); patchStyleVar(nodes.curveEl, '--sstep-fit-accent', s.colorVar); if (s.samples.length === 1) { const sp = s.samples[0]; const segHalf = Math.min(12, plotSpanX * 0.04); const x1 = Math.max(plotLeft, sp.x - segHalf); const x2 = Math.min(plotRight, sp.x + segHalf); const yStr = sp.fitY.toFixed(1); const flatCurveD = `M ${x1.toFixed(1)} ${yStr} L ${x2.toFixed(1)} ${yStr}`; nodes.bandEl.setAttribute('d', ''); nodes.bandEl.remove(); multiCurveGroup.appendChild(nodes.curveEl); fitMorphItems.push({ key: `multi:${s.key}`, gridPts: [ { x: x1, fitY: sp.fitY, lowY: sp.fitY, highY: sp.fitY }, { x: x2, fitY: sp.fitY, lowY: sp.fitY, highY: sp.fitY }, ], curveEl: nodes.curveEl, bandEl: null, olsEl: null, olsCoords: null, finalCurveD: flatCurveD, finalBandD: '', }); } else { const gridPts = s.pubFit.grid.map((g) => ({ x: mapX(g.x), fitY: mapY(g.fit), lowY: mapY(g.ciLow), highY: mapY(g.ciHigh), })); let bandD = ''; if (s.samples.length >= 3) { bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; for (let i = 1; i < gridPts.length; i++) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].highY.toFixed(1)}`; } for (let i = gridPts.length - 1; i >= 0; i--) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].lowY.toFixed(1)}`; } bandD += ' Z'; multiBandGroup.appendChild(nodes.bandEl); } else { nodes.bandEl.setAttribute('d', ''); nodes.bandEl.remove(); } const curveD = buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))); multiCurveGroup.appendChild(nodes.curveEl); fitMorphItems.push({ key: `multi:${s.key}`, gridPts, curveEl: nodes.curveEl, bandEl: bandD ? nodes.bandEl : null, olsEl: null, olsCoords: null, finalCurveD: curveD, finalBandD: bandD, }); } } for (const [k, nodes] of multiFitNodesByKey.entries()) { if (!activeFitKeys.has(k)) { nodes.bandEl.remove(); nodes.curveEl.remove(); } } if (lastFitMode === 'single') { const prevSingleGrid = fitMorphCtrl.getGrid('single'); if (prevSingleGrid && prevSingleGrid.length > 0) { if (lastSingleFitKey && lastSingleFitKey !== '__all__') { fitMorphCtrl.seedGrid(`multi:${lastSingleFitKey}`, prevSingleGrid); } else { for (const s of seriesList) { fitMorphCtrl.seedGrid(`multi:${s.key}`, prevSingleGrid); } } } } lastFitMode = 'multi'; lastSingleFitKey = ''; fitMorphCtrl.morphFits({ items: fitMorphItems, skipMorph: _skipMorph, allowBaselineEntry: true, bottomY: BOTTOM_Y, }); anomalyOverlayDots.sort((a, b) => a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 ); for (const sp of anomalyOverlayDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', sp.x.toFixed(1)); aDot.setAttribute('cy', sp.rawY.toFixed(1)); aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}` ); scatterTarget.appendChild(aDot); } if (scatterTarget !== scatterGroup) { scatterGroup.appendChild(scatterTarget); } while (multiLegendEl.firstChild) multiLegendEl.removeChild(multiLegendEl.firstChild); for (const s of seriesList) { const swatch = h('span', { className: 'sstep-legend-line' }); patchStyleVar(swatch, '--swatch-bg', s.colorVar); multiLegendEl.appendChild( h('span', { className: 'sstep-legend-item' }, [ swatch, h('span', { text: `${s.label} (${formatChartMetricCompact(metric, s.pubFit.mean)})`, }), ]) ); } } const r2SummaryTitle = seriesList .map((s) => { const rSign = s.pubFit.r >= 0 ? '+' : ''; return `${s.label}: n=${s.samples.length}, r=${rSign}${s.pubFit.r.toFixed(2)}, R²=${s.pubFit.r2.toFixed(2)}`; }) .join(' | '); patchText( fitStatsEl, seriesList.length <= 2 ? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ') : t('chart.fit.curvesCount', { count: seriesList.length }) ); patchAttr(fitStatsEl, 'title', r2SummaryTitle); if (hoveredIdx >= currentSamples.length) { clearHover(); } else if (hoveredIdx >= 0) { showHoverAt(hoveredIdx, lastFitPointer, { forceRefresh: true }); } return { sampleCount: combinedSamples.length, summaryBadge: t('chart.fit.multiBadge', { steps: combinedSamples.length, models: seriesList.length, }), }; } // 分支 B:单模型或整体合并单曲线模式 const nextSingleFitKey = isPooledAll ? '__all__' : targetKeys[0] || '__all__'; if (lastFitMode === 'multi') { const seedGrid = fitMorphCtrl.getGrid(`multi:${nextSingleFitKey}`) || fitMorphCtrl.getFirstGrid(); if (seedGrid && seedGrid.length > 0) { fitMorphCtrl.seedGrid('single', seedGrid); } } lastFitMode = 'single'; lastSingleFitKey = nextSingleFitKey; for (const nodes of multiFitNodesByKey.values()) { nodes.bandEl.remove(); nodes.curveEl.remove(); } patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); const filtered = matchedItems; const xs = filtered.map((d) => d.xVal); const rawYs = filtered.map((d) => d.rawVal); const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false); patchText( fitMethodLabelEl, pubFit.method === 'LOESS' ? t('chart.fit.loess') : t('chart.fit.olsReg') ); patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6); let dataMin = Infinity; let dataMax = -Infinity; for (let i = 0; i < filtered.length; i++) { if (rawYs[i] < dataMin) dataMin = rawYs[i]; if (rawYs[i] > dataMax) dataMax = rawYs[i]; } for (const g of pubFit.grid) { if (g.ciLow < dataMin) dataMin = g.ciLow; if (g.ciHigh > dataMax) dataMax = g.ciHigh; } const yScale = computeNiceYScale(dataMin, dataMax, { minBound, maxBound, tickCount: 4, }); const yRange = Math.max(1e-9, yScale.max - yScale.min); const mapY = (v) => BOTTOM_Y - ((clampValue(v, yScale.min, yScale.max) - yScale.min) / yRange) * SPAN_Y; const { plotLeft, plotRight, plotSpanX } = resolveFitBounds(viewW); const xMin = xs[0]; const xMax = xs[xs.length - 1]; const isSingle = filtered.length === 1 || xMax - xMin <= 1e-9; const mapX = (xv) => isSingle ? (plotLeft + plotRight) / 2 : plotLeft + ((xv - xMin) / (xMax - xMin)) * plotSpanX; const samples = filtered.map((item, i) => { const x = mapX(item.xVal); const rawY = mapY(item.rawVal); const fitVal = pubFit.sampleFits[i]; const fitY = mapY(fitVal); return { ...item, x, rawY, fitVal, fitY, ciLow: pubFit.sampleCiLow[i], ciHigh: pubFit.sampleCiHigh[i], ciHalf: pubFit.sampleCiHalf[i], seriesColor: 'var(--accent-primary)', compareHint: '', }; }); currentSamples = samples; const sig = `single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + samples .map( (s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}:${s.st?.anomalySig || ''}` ) .join('|'); if (sig !== lastSig) { lastSig = sig; renderFitAxesAndGrid({ yScale, mapY, mapX, xs, isSingle, plotLeft, plotRight, metric, showAgentPrefix, }); // 2. 绘制半透明冷蓝灰实心观测散点(自然呈现局部密度,不抢夺拟合曲线焦点) while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); const dotRadius = samples.length > 80 ? '1.8' : samples.length > 36 ? '2.1' : '2.4'; const binCounts = samples.length > 200 ? new Map() : null; const scatterTarget = typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : scatterGroup; const singleAnomalyDots = []; for (const s of samples) { if (s.anomalySummary) { singleAnomalyDots.push(s); continue; } if (binCounts) { const binKey = (Math.round(s.x * 2) << 11) ^ Math.round(s.rawY * 2); const prevCnt = binCounts.get(binKey) || 0; if (prevCnt >= 6) continue; binCounts.set(binKey, prevCnt + 1); } const dot = document.createElementNS(SVG_NS, 'circle'); dot.setAttribute('cx', s.x.toFixed(1)); dot.setAttribute('cy', s.rawY.toFixed(1)); dot.setAttribute('r', dotRadius); dot.setAttribute('class', 'sstep-scatter-dot'); scatterTarget.appendChild(dot); } singleAnomalyDots.sort((a, b) => a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 ); for (const s of singleAnomalyDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', s.x.toFixed(1)); aDot.setAttribute('cy', s.rawY.toFixed(1)); aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}` ); scatterTarget.appendChild(aDot); } if (scatterTarget !== scatterGroup) { scatterGroup.appendChild(scatterTarget); } // 3. 绘制 95% CI 置信带闭合多边形和回归拟合曲线(支持 240ms 平滑连续形变,绝不向底部 X 轴填充面积) if (isSingle) { const yVal = samples[0].fitY; const yStr = yVal.toFixed(1); const flatCurveD = `M ${plotLeft.toFixed(1)} ${yStr} L ${plotRight.toFixed(1)} ${yStr}`; patchAttr(ciBandPath, 'd', ''); patchAttr(olsLine, 'hidden', true); const flatGrid = Array.from({ length: 64 }, (_, gi) => ({ x: plotLeft + (gi / 63) * plotSpanX, fitY: yVal, lowY: yVal, highY: yVal, })); fitMorphCtrl.morphFits({ items: [ { key: 'single', gridPts: flatGrid, curveEl: fitPath, bandEl: null, olsEl: null, olsCoords: null, finalCurveD: flatCurveD, finalBandD: '', }, ], skipMorph: _skipMorph, }); } else { const gridPts = pubFit.grid.map((g) => ({ x: mapX(g.x), fitY: mapY(g.fit), lowY: mapY(g.ciLow), highY: mapY(g.ciHigh), })); const curveD = buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))); let bandD = ''; if (samples.length >= 3) { bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; for (let i = 1; i < gridPts.length; i++) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].highY.toFixed(1)}`; } for (let i = gridPts.length - 1; i >= 0; i--) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].lowY.toFixed(1)}`; } bandD += ' Z'; } else { patchAttr(ciBandPath, 'd', ''); } const showOlsRef = samples.length >= 6; patchAttr(olsLine, 'hidden', !showOlsRef); let olsCoords = null; if (showOlsRef) { const olsStartVal = clampValue(pubFit.intercept + pubFit.slope * xMin, minBound, maxBound); const olsEndVal = clampValue(pubFit.intercept + pubFit.slope * xMax, minBound, maxBound); olsCoords = { x1: plotLeft, y1: mapY(olsStartVal), x2: plotRight, y2: mapY(olsEndVal), }; } fitMorphCtrl.morphFits({ items: [ { key: 'single', gridPts, curveEl: fitPath, bandEl: bandD ? ciBandPath : null, olsEl: showOlsRef ? olsLine : null, olsCoords, finalCurveD: curveD, finalBandD: bandD, }, ], skipMorph: _skipMorph, }); } } const summaryBadge = t('chart.fit.singleBadge', { steps: samples.length, mean: formatChartMetricCompact(metric, pubFit.mean), }); if (samples.length >= 2) { const rSign = pubFit.r >= 0 ? '+' : ''; const slopeSign = pubFit.slope >= 0 ? '+' : ''; patchText(fitStatsEl, `r = ${rSign}${pubFit.r.toFixed(2)} · R² = ${pubFit.r2.toFixed(2)}`); patchAttr( fitStatsEl, 'title', t('chart.fit.olsTitle', { slope: `${slopeSign}${pubFit.slope.toFixed(3)}`, intercept: pubFit.intercept.toFixed(2), sd: pubFit.sd.toFixed(2), }) ); } else { patchText(fitStatsEl, `n = ${samples.length}`); patchAttr(fitStatsEl, 'title', ''); } if (hoveredIdx >= samples.length) { clearHover(); } else if (hoveredIdx >= 0) { showHoverAt(hoveredIdx, lastFitPointer, { forceRefresh: true }); } return { sampleCount: samples.length, summaryBadge }; } return { el: rootEl, update, destroy }; } return { createSessionLineChart, createModelFitChart }; })(); // --- src/registries/metricRegistry.js --- const { CAPSULE_METRIC_KEYS, getCapsuleMetricOptions, getOverviewMetricOptions, resolveQuotaCapsuleSummary, resolveSpecificQuotaSlotSummary, resolveCapsuleMetricPresentation, resolveOverviewMetricCell } = (() => { /** * @fileoverview Decoupled Metric Registry (`metricRegistry.js`). * Centralizes presentation & option metadata for: * 1. Topbar / Composer Capsule Slots (1..5 items out of 13 metrics) * 2. Live Overview / Hover First-Row Metric Matrix (1..4 items out of 9 metrics) */ const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS; function getCapsuleMetricOptions({ quotas = null, selectedSlots = [] } = {}) { const showArgonWeekly = hasArgonWeeklyQuotaPool(quotas) || (Array.isArray(selectedSlots) && selectedSlots.includes('argon_weekly')); return CAPSULE_METRIC_KEYS.filter((key) => key !== 'argon_weekly' || showArgonWeekly).map( (key) => ({ value: key, label: t(`capMetric.${key}`), }) ); } function getOverviewMetricOptions() { return OVERVIEW_METRIC_KEYS.map((key) => ({ value: key, label: t(`ovMetric.${key}`), })); } function resolveQuotaCapsuleSummary(quotas) { if (!quotas) return null; const activePool = quotas.activePool; const weekly = quotas.weekly; const pools = Array.isArray(quotas.pools) ? quotas.pools : []; const candidates = []; const defaultPoolName = isEnglishLocale() ? 'Active Pool' : '当前池'; const wkTag = isEnglishLocale() ? 'Wk' : '周'; if (activePool && Number.isFinite(Number(activePool.remainingPct))) { candidates.push({ pct: Number(activePool.remainingPct), label: activePool.poolLabel || activePool.family || defaultPoolName, windowTag: '5h', }); } if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { candidates.push({ pct: Number(activePool.weeklyRemainingPct), label: activePool.poolLabel || activePool.family || defaultPoolName, windowTag: wkTag, }); } if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { candidates.push({ pct: Number(weekly.remainingPct), label: weekly.poolFamily || (isEnglishLocale() ? 'Weekly' : '周限额'), windowTag: wkTag, }); } if (!candidates.length && pools.length > 0) { for (const p of pools) { const pLabel = p?.poolLabel || p?.family || defaultPoolName; if (p && Number.isFinite(Number(p.remainingPct))) { candidates.push({ pct: Number(p.remainingPct), label: pLabel, windowTag: '5h' }); } if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { candidates.push({ pct: Number(p.weeklyRemainingPct), label: pLabel, windowTag: wkTag }); } } } if (!candidates.length) return null; candidates.sort((a, b) => a.pct - b.pct); const tightest = candidates[0]; const runnerUp = candidates.length > 1 ? candidates[1] : null; const rounded = Math.max(0, Math.min(100, Math.round(tightest.pct))); const runnerPct = runnerUp ? Math.max(0, Math.min(100, Math.round(runnerUp.pct))) : null; const subLabelText = runnerUp ? runnerUp.label === tightest.label ? `${tightest.label} ${tightest.windowTag} · ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} · ${tightest.windowTag}`; const tightestIsClaude = /claude|gpt|fable|oss|third/i.test(String(tightest.label || '')); const tightestIsArgon = !tightestIsClaude && /\bargon\b/i.test(String(tightest.label || '')); const tightestIsGemini = !tightestIsClaude && !tightestIsArgon && /gemini|carbon|neon|flash|pro/i.test(String(tightest.label || '')); const tightestWinShort = tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'w' : '周'; const poolPrefix = tightestIsClaude ? `C${tightestWinShort}` : tightestIsArgon ? `A${tightestWinShort}` : tightestIsGemini ? `G${tightestWinShort}` : tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'Wk' : '周'; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), poolPrefix, subLabelText, detailText: candidates .map((c) => { const cPct = Math.max(0, Math.min(100, Math.round(c.pct))); return `${c.label} ${c.windowTag} ${t('capsule.quotaLeft', { pct: cPct })}`; }) .join(' · '), }; } function resolveQuotaCapsulePrefix(metricKey, quotaSum) { const isEn = isEnglishLocale(); if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; if (metricKey === 'argon_weekly') return isEn ? 'Aw' : 'A周'; if (metricKey === 'claude_5h') return 'C5h'; if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; if (quotaSum?.poolPrefix) return quotaSum.poolPrefix; return isEn ? 'Q' : '余'; } /** * 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。 * * @param {object|null|undefined} quotas * @param {'gemini_5h'|'gemini_weekly'|'claude_5h'|'claude_weekly'} slotKey * @returns {{ roundedPct: number, shortText: string } | null} */ function resolveSpecificQuotaSlotSummary(quotas, slotKey) { const rounded = resolveCapsuleQuotaSlotPct(quotas, slotKey); if (rounded == null) return null; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), }; } /** * 解析顶栏/输入框精简胶囊单槽位展示结构。 * * @param {string} metricKey * @param {object} slotCtx * @param {number} ringCircumference */ function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) { if (!metricKey || metricKey === 'none') { return { hidden: true, metric: 'none', segClass: 'wm-cap-slot', textClass: 'wm-slot-text', showRing: false, dashOffset: ringCircumference, text: '', toneClass: '', running: false, warn: false, danger: false, }; } if (metricKey === 'context') { if (!slotCtx.hasTelemetry) { return { hidden: false, metric: 'context', segClass: 'wm-cap-slot wm-ctx-seg', textClass: 'wm-slot-text wm-ctx-pct', showRing: true, dashOffset: ringCircumference, text: '--%', toneClass: '', running: false, warn: false, danger: false, }; } const isDanger = slotCtx.usedPct >= 88; const isWarn = !isDanger && slotCtx.usedPct >= 70; const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : ''; return { hidden: false, metric: 'context', segClass: 'wm-cap-slot wm-ctx-seg', textClass: 'wm-slot-text wm-ctx-pct', showRing: true, dashOffset: slotCtx.dashOffset, text: `${Math.round(slotCtx.usedPct)}%`, toneClass, running: false, warn: isWarn, danger: isDanger, }; } if (metricKey === 'tps') { if (!slotCtx.hasTelemetry) { return { hidden: false, metric: 'tps', segClass: 'wm-cap-slot wm-seg-speed', textClass: 'wm-slot-text wm-speed-text', showRing: false, dashOffset: ringCircumference, text: '-- t/s', toneClass: '', running: false, warn: false, danger: false, }; } const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0; const toneClass = hasValidTps ? getSpeedToneClass(slotCtx.tps) : ''; const tpsText = hasValidTps ? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s` : slotCtx.isRunning ? t('capsule.tpsRunning') : t('capsule.tpsIdle'); return { hidden: false, metric: 'tps', segClass: 'wm-cap-slot wm-seg-speed', textClass: 'wm-slot-text wm-speed-text', showRing: false, dashOffset: ringCircumference, text: tpsText, toneClass, running: Boolean(slotCtx.isRunning), warn: toneClass === 'tone-warn', danger: toneClass === 'tone-danger', }; } if (metricKey === 'avg_tps') { const avgVal = slotCtx.hasTelemetry ? slotCtx.avgTps : null; const valid = Number.isFinite(avgVal) && avgVal > 0; const toneClass = valid ? getSpeedToneClass(avgVal) : ''; return { hidden: false, metric: 'avg_tps', segClass: 'wm-cap-slot wm-seg-speed', textClass: 'wm-slot-text wm-speed-text', showRing: false, dashOffset: ringCircumference, text: valid ? `${avgVal >= 100 ? Math.round(avgVal) : avgVal.toFixed(1)} t/s` : '-- t/s', toneClass, running: false, warn: toneClass === 'tone-warn', danger: toneClass === 'tone-danger', }; } if (metricKey === 'ttft') { const val = slotCtx.hasTelemetry ? slotCtx.ttft : null; const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0; const numVal = valid ? Number(val) : 0; const toneClass = valid ? getTtftToneClass(numVal) : ''; return { hidden: false, metric: 'ttft', segClass: 'wm-cap-slot wm-seg-ttft', textClass: 'wm-slot-text wm-ttft-text', showRing: false, dashOffset: ringCircumference, text: valid ? formatCompactCapsuleTtft(numVal) : '--s', toneClass, running: false, warn: toneClass === 'tone-warn', danger: toneClass === 'tone-danger', }; } if (metricKey === 'cost' || metricKey === 'session_cost') { const costVal = !slotCtx.hasTelemetry ? null : metricKey === 'session_cost' ? slotCtx.sessionCost : slotCtx.stepCost; const toneClass = metricKey === 'cost' && slotCtx.hasTelemetry && costVal != null ? getStepCostToneClass(costVal) : ''; return { hidden: false, metric: metricKey, segClass: 'wm-cap-slot wm-seg-cost', textClass: 'wm-slot-text wm-cost-text', showRing: false, dashOffset: ringCircumference, text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--', toneClass, running: false, warn: toneClass === 'tone-warn', danger: toneClass === 'tone-danger', }; } if (metricKey === 'cache_hit') { const cachePct = slotCtx.hasTelemetry ? slotCtx.cacheHitPct : null; const valid = cachePct != null && Number.isFinite(Number(cachePct)); const numVal = valid ? Number(cachePct) : 0; const toneClass = valid ? getCacheToneClass(numVal, slotCtx.latestPromptTokens) : ''; return { hidden: false, metric: 'cache_hit', segClass: 'wm-cap-slot wm-seg-cache', textClass: 'wm-slot-text wm-cache-text', showRing: false, dashOffset: ringCircumference, text: valid ? `${Math.round(numVal)}%` : '--%', toneClass, running: false, warn: toneClass === 'tone-warn', danger: toneClass === 'tone-danger', }; } if (metricKey === 'session_tokens') { const tokVal = slotCtx.hasTelemetry ? slotCtx.sessionTokens : null; const valid = tokVal != null && Number.isFinite(Number(tokVal)) && Number(tokVal) >= 0; return { hidden: false, metric: 'session_tokens', segClass: 'wm-cap-slot wm-seg-tokens', textClass: 'wm-slot-text wm-tokens-text', showRing: false, dashOffset: ringCircumference, text: valid ? formatTokens(Number(tokVal)) : '--', toneClass: '', running: false, warn: false, danger: false, }; } if (metricKey === 'argon_weekly' && slotCtx.hasTelemetry && !hasArgonWeeklyQuotaPool(slotCtx.quotas)) { return { hidden: true, metric: 'none', segClass: 'wm-cap-slot', textClass: 'wm-slot-text', showRing: false, dashOffset: ringCircumference, text: '', toneClass: '', running: false, warn: false, danger: false, }; } const quotaSum = !slotCtx.hasTelemetry ? null : metricKey === 'quota_auto' ? resolveQuotaCapsuleSummary(slotCtx.quotas) : resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey); const hasQuotaPct = Boolean(quotaSum && Number.isFinite(quotaSum.roundedPct)); const clampedPct = hasQuotaPct ? Math.max(0, Math.min(100, quotaSum.roundedPct)) : 0; const quotaDashOffset = hasQuotaPct ? +(ringCircumference * (1 - clampedPct / 100)).toFixed(2) : ringCircumference; const isDanger = Boolean(hasQuotaPct && clampedPct <= 15); const isWarn = Boolean(hasQuotaPct && !isDanger && clampedPct <= 30); const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : ''; return { hidden: false, metric: metricKey, segClass: 'wm-cap-slot wm-seg-quota', textClass: 'wm-slot-text wm-quota-text', showRing: true, ringKind: 'quota', ringEmpty: !hasQuotaPct, dashOffset: quotaDashOffset, prefix: resolveQuotaCapsulePrefix(metricKey, quotaSum), text: hasQuotaPct ? `${clampedPct}%` : '--%', toneClass, running: false, warn: isWarn, danger: isDanger, }; } function resolveActiveBadgeText(active) { if (!active?.activeAgentBadge && !active?.activeAgentKind) return ''; return formatAgentBadgeText({ agentKind: active.activeAgentKind || (!active.activeAgentId || active.activeAgentId === 'main' ? 'main' : 'subagent'), agentOrdinal: Number(active.activeAgentOrdinal || 0), isMain: !active.activeAgentId || active.activeAgentId === 'main', badgeText: active.activeAgentBadge, }); } /** * 解析实时监控第一行矩阵单个单元格的展示数据。 * * @param {string} metricKey * @param {{ active?: object, ctx?: object, quotas?: object, settings?: object, hasSubagents?: boolean }} cellCtx */ function resolveOverviewMetricCell(metricKey, cellCtx = {}) { const active = cellCtx.active || {}; const ctx = cellCtx.ctx || active.context || {}; const quotas = cellCtx.quotas || {}; const settings = cellCtx.settings || {}; const hasSubagents = Boolean(cellCtx.hasSubagents); const hasAnySteps = Number(active.stepCount || 0) > 0; if (metricKey === 'tps') { const activeModelDisplay = resolveModelDisplayInfo(active, settings, { fallback: t('fmt.unknownModel'), }).text; const reason = speedReasonText(active.latestSpeedReason); const badgeStr = resolveActiveBadgeText(active); const modelAndAgent = hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay; const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0; const speedTone = hasAnySteps && hasSpeed ? getSpeedToneClass(active.latestTokPerSec) : ''; return { key: 'tps', label: t('ovMetric.tps'), icon: 'dot', iconSize: 10, isPulsing: Boolean(active.isRunning), valueText: formatMetric(active.latestTokPerSec, ' tok/s'), valueClass: speedTone ? `cell-value ${speedTone}` : 'cell-value', subText: reason ? !hasSpeed ? `${reason} · ${modelAndAgent}` : `${modelAndAgent} · ${reason}` : modelAndAgent, subClass: 'cell-sub', }; } if (metricKey === 'ttft') { const ttftTone = hasAnySteps ? getTtftToneClass(active.latestTtftSec) : ''; return { key: 'ttft', label: t('ovMetric.ttft'), icon: 'clock', iconSize: 11, isPulsing: false, valueText: formatMetric(active.latestTtftSec, 's'), valueClass: ttftTone ? `cell-value ${ttftTone}` : 'cell-value', subText: t('ovMetric.subAvgTtft', { val: formatMetric(active.ttftSummary?.avgSec, 's'), }), subClass: 'cell-sub', }; } if (metricKey === 'avg_tps') { const hasAvgSpeed = Number.isFinite(active.avgTokPerSec) && Number(active.avgTokPerSec) > 0; const avgSpeedTone = hasAnySteps && hasAvgSpeed ? getSpeedToneClass(active.avgTokPerSec) : ''; return { key: 'avg_tps', label: t('ovMetric.avg_tps'), icon: 'pulse', iconSize: 11, isPulsing: false, valueText: formatMetric(active.avgTokPerSec, ' tok/s'), valueClass: avgSpeedTone ? `cell-value ${avgSpeedTone}` : 'cell-value', subText: t('ovMetric.subValidSamples', { samples: sampleSummary(active.speedSummary), }), subClass: 'cell-sub', }; } if (metricKey === 'step_cost' || metricKey === 'session_cost') { const stepCost = active.latestStepCostUsd; const sessCost = Number(active.sessionCostUsd || 0); const stepCnt = Number(active.stepCount || 0); const isAllUnpriced = stepCnt > 0 && Number(active.sessionUnpricedCalls || 0) >= stepCnt && !(sessCost > 0); const stepCostText = !hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true }); const totalCostText = !hasAnySteps && active.sessionCostUsd == null ? '—' : formatUsd(isAllUnpriced ? null : sessCost, { precise: sessCost > 0 && sessCost < 0.1, }); if (metricKey === 'step_cost') { const costTone = hasAnySteps ? getStepCostToneClass(stepCost) : ''; return { key: 'step_cost', label: t('ovMetric.step_cost'), icon: 'bolt', iconSize: 11, isPulsing: false, valueText: stepCostText, valueClass: costTone ? `cell-value ${costTone}` : 'cell-value', subText: t('ovMetric.subTotalCost', { cost: totalCostText }), subClass: 'cell-sub', }; } return { key: 'session_cost', label: t('ovMetric.session_cost'), icon: 'bolt', iconSize: 11, isPulsing: false, valueText: totalCostText, valueClass: 'cell-value', subText: t('ovMetric.subStepCost', { cost: stepCostText }), subClass: 'cell-sub', }; } if (metricKey === 'cache_hit') { const latestCache = active.latestCacheHitPct; const avgCache = active.sessionCacheHitPct ?? active.latestCacheHitPct; const hasLatest = hasAnySteps && latestCache != null && Number.isFinite(Number(latestCache)); const hasAvg = hasAnySteps && avgCache != null && Number.isFinite(Number(avgCache)); const cacheTone = hasLatest ? getCacheToneClass(latestCache, active.latestPromptTokens) : ''; return { key: 'cache_hit', label: t('ovMetric.cache_hit'), icon: 'layers', iconSize: 11, isPulsing: false, valueText: hasLatest ? formatCachePct(latestCache) : '—', valueClass: cacheTone ? `cell-value ${cacheTone}` : 'cell-value', subText: t('ovMetric.subAvgCache', { val: hasAvg ? formatCachePct(avgCache) : '—', }), subClass: 'cell-sub', }; } if (metricKey === 'session_tokens') { const inTok = Math.max(0, Number(active.inputTokens || 0)); const cacheTok = Math.max(0, Number(active.cacheReadTokens || 0)); const outTok = Math.max(0, Number(active.outputTokens || 0)); const totalTok = Math.max(0, Number(active.totalTokens ?? inTok + cacheTok + outTok)); return { key: 'session_tokens', label: t('ovMetric.session_tokens'), icon: 'chart-bar', iconSize: 11, isPulsing: false, valueText: !hasAnySteps && !totalTok ? '—' : formatTokens(totalTok), valueClass: 'cell-value', subText: t('ovMetric.subInOutTokens', { inTok: formatTokens(inTok + cacheTok), outTok: formatTokens(outTok), }), subClass: 'cell-sub', }; } if (metricKey === 'context_usage') { const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); const totalTokens = Number(ctx.totalTokens || 0); const usedPct = limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; const toneCls = usedPct >= 88 ? 'cell-value tone-danger' : usedPct >= 70 ? 'cell-value tone-warn' : 'cell-value'; return { key: 'context_usage', label: t('ovMetric.context_usage'), icon: 'layers', iconSize: 11, isPulsing: false, valueText: `${usedPct}%`, valueClass: toneCls, subText: t('ovMetric.subCtxRatio', { used: formatTokens(totalTokens), limit: formatTokens(limitTokens), }), subClass: 'cell-sub', }; } const quotaSum = resolveQuotaCapsuleSummary(quotas); const quotaToneCls = quotaSum && quotaSum.roundedPct <= 15 ? 'cell-value tone-danger' : quotaSum && quotaSum.roundedPct <= 30 ? 'cell-value tone-warn' : 'cell-value'; return { key: 'quota_tightest', label: t('ovMetric.quota_tightest'), icon: 'pulse', iconSize: 11, isPulsing: false, valueText: quotaSum ? quotaSum.shortText : '—', valueClass: quotaToneCls, subText: quotaSum ? t('ovMetric.subQuotaPool', { label: quotaSum.subLabelText }) : t('ovMetric.subQuotaPending'), subClass: 'cell-sub', }; } return { CAPSULE_METRIC_KEYS, getCapsuleMetricOptions, getOverviewMetricOptions, resolveQuotaCapsuleSummary, resolveSpecificQuotaSlotSummary, resolveCapsuleMetricPresentation, resolveOverviewMetricCell }; })(); // --- src/components/widgets/MetricMatrixWidget.js --- const { MetricMatrixWidget } = (() => { /** * @fileoverview Standalone decoupled Metric Matrix Widget (`MetricMatrixWidget.js`). * Renders 1..4 user-selected telemetry cells dynamically via `metricRegistry.js`. */ const MetricMatrixWidget = defineComponent({ name: 'MetricMatrixWidget', setup({ props }) { const getCtxAgentId = typeof props?.getCtxAgentId === 'function' ? props.getCtxAgentId : () => uiStore.getState().ctxInspectorAgentId; const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': t('module.metrics'), 'data-cols': '4', }); patchStyleVar(matrixEl, '--matrix-cols', '4'); function createMetricCellNode() { const labelSpan = h('span', { text: '—' }); const iconSvg = createSvgIcon('pulse', { size: 11 }); const valueEl = h('strong', { className: 'cell-value', text: '—' }); const subEl = h('span', { className: 'cell-sub', text: '—' }); const el = h('div', { className: 'matrix-cell' }, [ h('div', { className: 'cell-label' }, [labelSpan, iconSvg]), valueEl, subEl, ]); return { el, refs: { labelSpan, iconSvg, valueEl, subEl }, }; } function update({ data } = {}) { patchAttr(matrixEl, 'aria-label', t('module.metrics')); const metricKeys = normalizeClientOverviewMetrics(data?.settings?.overviewMetrics); const colCount = Math.max(1, Math.min(4, metricKeys.length)); patchAttr(matrixEl, 'data-cols', String(colCount)); patchStyleVar(matrixEl, '--matrix-cols', String(colCount)); const { hasSubagents, scopedConv, ctxAgent } = resolveScopedConversation( data, 'all', getCtxAgentId() ); const active = scopedConv || data?.activeConversation || {}; const ctx = ctxAgent?.context || active.context || {}; const quotas = data?.quotas || {}; const settings = data?.settings || {}; const locale = getEffectiveLocale(); const cells = metricKeys.map((key) => resolveOverviewMetricCell(key, { active, ctx, quotas, settings, hasSubagents, }) ); patchKeyedList(matrixEl, cells, { keyFn: (cell) => cell.key, sigFn: (cell) => `${locale}:${cell.key}:${cell.label}:${cell.icon}:${cell.isPulsing}:${cell.valueClass}:${cell.valueText}:${cell.subClass}:${cell.subText}`, createRow: createMetricCellNode, updateRow: (refs, cell) => { patchText(refs.labelSpan, cell.label); patchSvgIcon(refs.iconSvg, cell.icon); refs.iconSvg.setAttribute('width', String(cell.iconSize)); refs.iconSvg.setAttribute('height', String(cell.iconSize)); patchClasses(refs.iconSvg, { 'is-pulsing': Boolean(cell.isPulsing) }); patchAttr(refs.valueEl, 'class', cell.valueClass); patchText(refs.valueEl, cell.valueText); patchAttr(refs.subEl, 'class', cell.subClass); patchText(refs.subEl, cell.subText); }, }); } // Initialize default 4-cell skeleton so hover/overview has zero initial height jump update({ data: null }); return { el: matrixEl, refs: { update }, }; }, }); return { MetricMatrixWidget }; })(); // --- src/components/widgets/ContextWindowWidget.js --- const { CTX_CHANNEL_DEFS, ContextWindowWidget } = (() => { /** * @fileoverview Standalone decoupled Context Window Widget (`ContextWindowWidget.js`). * Supports both interactive multi-agent inspector mode (`LiveOverviewView`) * and pointer-events-none in-place pre-allocated mode (`WindowOverlayShell` hover popup). */ const CTX_PILL_BASE_PAD_PX = 14; const CTX_CJK_CHAR_PX = 11; const CTX_ASCII_CHAR_PX = 6.1; const CTX_PILL_GAP_PX = 4; const CTX_DEFAULT_BAR_WIDTH_PX = 310; 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; } return Math.ceil(w); } /** * 10 通道上下文窗口构成定义(通过动态 getter 自动跟随当前激活语言)。 */ const CTX_CHANNEL_DEFS = [ { key: 'assistant', labelKey: 'ctx.ch.assistant', titleKey: 'ctx.ch.assistantTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-assistant', getValue: (c) => Number(c.assistantTokens || 0), }, { key: 'toolResults', labelKey: 'ctx.ch.toolResults', titleKey: 'ctx.ch.toolResultsTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-tool-results', getValue: (c) => Number(c.toolResultsTokens || 0), }, { key: 'userInput', labelKey: 'ctx.ch.userInput', titleKey: 'ctx.ch.userInputTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-user-input', getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), }, { key: 'subagent', labelKey: 'ctx.ch.subagent', titleKey: 'ctx.ch.subagentTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-subagent-msg', getValue: (c) => Number(c.subagentTokens || 0), }, { key: 'checkpoint', labelKey: 'ctx.ch.checkpoint', titleKey: 'ctx.ch.checkpointTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-checkpoint', getValue: (c) => Number(c.checkpointTokens || 0), }, { key: 'systemPrompt', labelKey: 'ctx.ch.systemPrompt', titleKey: 'ctx.ch.systemPromptTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-system-prompt', getValue: (c) => Number(c.systemPromptTokens || 0), }, { key: 'systemTools', labelKey: 'ctx.ch.systemTools', titleKey: 'ctx.ch.systemToolsTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-system-tools', getValue: (c) => Number(c.systemToolsTokens || 0), }, { key: 'mcpTools', labelKey: 'ctx.ch.mcpTools', titleKey: 'ctx.ch.mcpToolsTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-mcp-tools', getValue: (c) => Number(c.mcpToolsTokens || 0), }, { key: 'skills', labelKey: 'ctx.ch.skills', titleKey: 'ctx.ch.skillsTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-skills', getValue: (c) => Number(c.skillsTokens || 0), }, { key: 'userRules', labelKey: 'ctx.ch.userRules', titleKey: 'ctx.ch.userRulesTitle', get label() { return t(this.labelKey); }, get title() { return t(this.titleKey); }, segClass: 'seg-user-rules', getValue: (c) => Number(c.userRulesTokens || 0), }, ]; const ContextWindowWidget = defineComponent({ name: 'ContextWindowWidget', setup({ props, onCleanup }) { const interactiveInspector = props.interactiveInspector !== false; const getCtxAgentId = typeof props.getCtxAgentId === 'function' ? props.getCtxAgentId : () => uiStore.getState().ctxInspectorAgentId; const setCtxAgentId = typeof props.setCtxAgentId === 'function' ? props.setCtxAgentId : (nextId) => uiStore.setState({ ctxInspectorAgentId: nextId }); const isVisibleFn = typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true; const titleTextEl = h('span', { text: t('module.context') }); const ctxAgentBadge = h('span', { className: 'agent-badge badge-main', hidden: true, text: t('fmt.mainAgent'), }); const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' }); const ctxSegmentBar = ContextSegmentMeter({ context: {} }); const ctxPillGroup = h('div', { className: 'ctx-pill-group' }); const ctxInspectorBar = h( 'div', { className: 'ctx-inspector-bar', hidden: true }, [ctxPillGroup] ); const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => { const swatchEl = h('span', { className: `swatch ${ch.segClass}` }); const labelEl = h('span', { text: ch.label }); const valEl = h('strong', { className: 'text-mono', text: '0' }); const itemEl = h( 'div', { className: 'legend-item', ...(interactiveInspector ? { title: ch.title } : {}) }, [h('span', { className: 'legend-left' }, [swatchEl, labelEl]), valEl] ); return { ch, defaultOrder: idx, swatchEl, labelEl, valEl, itemEl }; }); const ctxLegendGrid = h( 'div', { className: 'ctx-legend-grid' }, ctxChannels.map((entry) => entry.itemEl) ); let lastLegendOrderSig = ctxChannels.map((entry) => entry.ch.key).join(','); let lastLocale = getEffectiveLocale(); const children = [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('layers', { size: 13 }), titleTextEl, ctxAgentBadge, ]), h('span', { className: 'panel-meta' }, [ctxSummaryText]), ]), ]; if (interactiveInspector) { children.push(ctxInspectorBar); } children.push(ctxSegmentBar.el, ctxLegendGrid); const ctxPanel = h('section', { className: 'panel' }, children); 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(); patchText(titleTextEl, t('module.context')); if (!data) { if (curLocale !== lastLocale) { lastLocale = curLocale; for (const entry of ctxChannels) { patchText(entry.labelEl, entry.ch.label); if (interactiveInspector) { patchAttr(entry.itemEl, 'title', entry.ch.title); } } } return; } let availRowWidth = CTX_DEFAULT_BAR_WIDTH_PX; if (interactiveInspector) { const measuredWidth = ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0); if (measuredWidth > 160) { cachedBarWidth = measuredWidth; } availRowWidth = cachedBarWidth > 160 ? cachedBarWidth : CTX_DEFAULT_BAR_WIDTH_PX; const currentCascadeId = data.activeConversation?.cascadeId || ''; if (currentCascadeId && currentCascadeId !== lastCascadeId) { if (lastCascadeId) { clearCtxExpandAnim(); ctxPillsExpanded = false; } lastCascadeId = currentCascadeId; } } const { hasSubagents, effectiveCtxScope, agents, aggregated, scopedConv, ctxAgent, } = resolveScopedConversation(data, 'all', getCtxAgentId()); const active = scopedConv || data.activeConversation || {}; const ctx = ctxAgent?.context || active.context || {}; patchAttr(ctxAgentBadge, 'hidden', !(hasSubagents && ctxAgent)); if (hasSubagents && ctxAgent) { const badgeCls = getAgentBadgeClass(ctxAgent.index || 0, Boolean(ctxAgent.isMain)); patchAttr(ctxAgentBadge, 'class', `agent-badge ${badgeCls}`); const badgeFullText = formatAgentLabel(ctxAgent); patchText(ctxAgentBadge, badgeFullText); if (interactiveInspector) { patchAttr(ctxAgentBadge, 'title', badgeFullText); } } if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); if (!hasSubagents && isCollapsingCtxPills) { clearCtxExpandAnim(); } if (hasSubagents && ctxAgent && !isCollapsingCtxPills) { const activeBadgeText = formatAgentBadgeText({ agentKind: aggregated?.activeAgentKind || (!aggregated?.activeAgentId || aggregated.activeAgentId === 'main' ? 'main' : 'subagent'), agentOrdinal: Number(aggregated?.activeAgentOrdinal || 0), isMain: !aggregated?.activeAgentId || aggregated.activeAgentId === 'main', badgeText: aggregated?.activeAgentBadge, }); const pillItems = [ { key: 'auto', label: t('ctx.followActive', { badge: activeBadgeText }), title: t('ctx.followActiveTitle'), isActive: effectiveCtxScope === 'auto', mode: 'ctx-only', }, ]; const allAgentPills = agents.map((ag) => { const agPct = ag.context?.usedPct ?? 0; const agModelDisplay = resolveModelDisplayInfo(ag, data.settings, { fallback: t('fmt.unknownModel'), }).text; const badgeLabel = formatAgentBadgeText(ag); return { key: ag.agentId, label: `${badgeLabel} ${agPct}%`, title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${t('header.convMetaSteps', { count: ag.stepCount || 0 })})`, isActive: effectiveCtxScope === ag.agentId, mode: 'ctx-only', }; }); const firstPillWidth = pillItems.length > 0 ? estimateCtxPillWidth(pillItems[0].label) : 0; const totalAllWidth = allAgentPills.reduce( (sum, p) => sum + CTX_PILL_GAP_PX + estimateCtxPillWidth(p.label), firstPillWidth ); const needsCollapse = totalAllWidth > availRowWidth && allAgentPills.length > 2; if (needsCollapse && !ctxPillsExpanded) { const toggleSample = t('ctx.expandMore', { count: allAgentPills.length }); const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample, true); let usedW = firstPillWidth; let fitCount = 0; for (let i = 0; i < allAgentPills.length; i += 1) { const pw = CTX_PILL_GAP_PX + estimateCtxPillWidth(allAgentPills[i].label); if (fitCount >= 1 && usedW + pw + toggleReservePx > availRowWidth) { break; } usedW += pw; fitCount += 1; } const maxKeep = Math.max(1, allAgentPills.length - 2); const maxCollapsedCount = Math.max(1, Math.min(maxKeep, fitCount)); const visibleAgentPills = allAgentPills.slice(0, maxCollapsedCount); const activeHiddenPill = allAgentPills .slice(maxCollapsedCount) .find((p) => p.isActive); if (activeHiddenPill) { if (visibleAgentPills.length >= 2) { visibleAgentPills[visibleAgentPills.length - 1] = activeHiddenPill; } else { visibleAgentPills.push(activeHiddenPill); } } const hiddenCount = allAgentPills.length - visibleAgentPills.length; pillItems.push(...visibleAgentPills, { key: '__toggle_more__', label: t('ctx.expandMore', { count: hiddenCount }), title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }), isActive: false, isMoreToggle: true, isExpanded: false, mode: 'toggle-expand', }); } else { pillItems.push(...allAgentPills); if (needsCollapse) { pillItems.push({ key: '__toggle_more__', label: t('ctx.collapse'), title: t('ctx.collapseTitle'), isActive: false, isMoreToggle: true, isExpanded: true, mode: 'toggle-expand', }); } } patchKeyedList(ctxPillGroup, pillItems, { keyFn: (item) => item.key, sigFn: (item) => `${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${Boolean(item.isExpanded)}:${item.mode}:${item.title}`, createRow: () => { 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.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') { 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); } }; }, }); } } const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); const totalTokens = Number(ctx.totalTokens || 0); const usedPct = limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; const ctxToneCls = usedPct >= 88 ? 'tone-danger' : usedPct >= 70 ? 'tone-warn' : ''; patchAttr(ctxSummaryText, 'class', ctxToneCls ? `text-mono ${ctxToneCls}` : 'text-mono'); patchText( ctxSummaryText, `${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)` ); ctxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } }); if (interactiveInspector) { const localeChanged = curLocale !== lastLocale; lastLocale = curLocale; const scored = ctxChannels.map((entry) => { const val = entry.ch.getValue(ctx); if (localeChanged) { patchText(entry.labelEl, entry.ch.label); patchAttr(entry.itemEl, 'title', entry.ch.title); } patchText(entry.valEl, formatTokens(val)); return { entry, val }; }); scored.sort((a, b) => b.val - a.val || a.entry.defaultOrder - b.entry.defaultOrder); const nextLegendOrderSig = scored.map((x) => x.entry.ch.key).join(','); if (nextLegendOrderSig !== lastLegendOrderSig) { lastLegendOrderSig = nextLegendOrderSig; for (const { entry } of scored) { ctxLegendGrid.appendChild(entry.itemEl); } } } else { lastLocale = curLocale; const scoredChannels = CTX_CHANNEL_DEFS.map((ch, defaultOrder) => ({ ch, defaultOrder, val: ch.getValue(ctx), })); scoredChannels.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder); for (let i = 0; i < ctxChannels.length; i += 1) { const slot = ctxChannels[i]; const item = scoredChannels[i]; if (!slot || !item) continue; patchAttr(slot.swatchEl, 'class', `swatch ${item.ch.segClass}`); patchText(slot.labelEl, item.ch.label); patchText(slot.valEl, formatTokens(item.val)); } } } let ro = null; if (interactiveInspector && typeof ResizeObserver !== 'undefined') { ro = new ResizeObserver(() => { if (!isVisibleFn()) return; const nextW = ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0); if (nextW > 160 && Math.abs(nextW - cachedBarWidth) >= 6) { cachedBarWidth = nextW; if (latestData?.activeConversation?.hasSubagents) { update({ data: latestData }); } } }); ro.observe(ctxPanel); } onCleanup(() => { clearCtxExpandAnim(); if (ro) ro.disconnect(); ctxSegmentBar.destroy(); }); return { el: ctxPanel, refs: { update, ctxSegmentBar }, }; }, }); return { CTX_CHANNEL_DEFS, ContextWindowWidget }; })(); // --- src/components/widgets/QuotaPoolsWidget.js --- const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, maskAccountLabel, QuotaPoolsWidget } = (() => { /** * @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`). * Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT) * and weekly summary footer for both `LiveOverviewView` and `WindowOverlayShell`. */ /** * 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。 * * @param {object|null|undefined} quotas * @param {number} minuteTick * @param {{ isPending?: boolean }} [options] * @returns {Array} */ function buildQuotaPoolItems( quotas, minuteTick = 0, { isPending = false, showReserved = false } = {} ) { const safeQuotas = quotas || {}; const activePool = safeQuotas.activePool || {}; const rawPools = Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0 ? safeQuotas.pools : [ { poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' }, { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' }, ]; const weekly = safeQuotas.weekly || {}; const poolItems = rawPools.map((p) => { const key = p.poolKey || p.family || p.poolLabel || 'Other'; const poolLabel = p.poolLabel || p.family || key; const isActivePool = Boolean(activePool.family) && (activePool.poolKey === key || activePool.family === p.family || (key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family))); return { key, poolLabel, poolData: p, fallbackWeekly: weekly, isActivePool, minuteTick, isPending, showReserved: Boolean(showReserved), }; }); if ( weekly?.isOfficial === false && poolItems.length > 0 && !poolItems.some((item) => item.isActivePool) ) { poolItems[0].isActivePool = true; } return poolItems; } /** * 创建单个配额池的 DOM 行结构,内含 5h 限额及每周限额两个可独立显隐的子窗口进度条。 */ function createPoolQuotaRow() { const title5h = h('span', { className: 'quota-win-title', text: '5h' }); const usage5h = h('span', { className: 'quota-win-usage', hidden: true, text: '' }); const left5h = h('span', { className: 'quota-win-left' }, [title5h, usage5h]); const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' }); const fill5h = h('div', { className: 'progress-fill' }); const fillReserved5h = h('div', { className: 'progress-fill-reserved' }); const track5h = h('div', { className: 'progress-track' }, [fill5h, fillReserved5h]); const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ h('div', { className: 'panel-header quota-win-head' }, [left5h, meta5h]), track5h, ]); const titleWk = h('span', { className: 'quota-win-title', text: t('quota.weeklyShort') }); const usageWk = h('span', { className: 'quota-win-usage', hidden: true, text: '' }); const leftWk = h('span', { className: 'quota-win-left' }, [titleWk, usageWk]); const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' }); const fillWk = h('div', { className: 'progress-fill' }); const fillReservedWk = h('div', { className: 'progress-fill-reserved' }); const trackWk = h('div', { className: 'progress-track' }, [fillWk, fillReservedWk]); const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ h('div', { className: 'panel-header quota-win-head' }, [leftWk, metaWk]), trackWk, ]); const el = h('div', { className: 'quota-pool-row' }, [ row5h, rowWk, ]); return { el, refs: { row5h, left5h, title5h, usage5h, meta5h, track5h, fill5h, fillReserved5h, rowWk, leftWk, titleWk, usageWk, metaWk, trackWk, fillWk, fillReservedWk, }, }; } /** * 格式化可用额度面板底部的汇总行文案(官方配额模式下展示各池周期合计,自定义预算模式下展示自然周累计)。 */ function formatQuotaSummaryFooter(quotas, account) { const weekly = quotas?.weekly || {}; const isCustomLocal = weekly.isOfficial === false; const tokStr = formatTokens(weekly.tokens || 0); const costStr = formatUsd(weekly.costUsd || 0); const leftText = isCustomLocal ? t('quota.footTokensCustom', { tok: tokStr, cost: costStr }) : t('quota.footTokensCycle', { tok: tokStr, cost: costStr }); const rightText = Number(account?.aiCredits) > 0 ? t('quota.footCredits', { credits: account.aiCredits }) : isCustomLocal ? t('quota.footCallsCustom', { calls: weekly.calls || 0 }) : t('quota.footCallsCycle', { calls: weekly.calls || 0 }); const tooltip = isCustomLocal ? t('quota.footTipCustom') : t('quota.footTipCycle'); return { leftText, rightText, tooltip }; } function syncQuotaWindowMeter({ hasData, usedVal, resetTime, fallbackMetaText, showReserved, rawReservedPct, leaseCount, metaEl, trackEl, fillEl, fillReservedEl, }) { const numReserved = showReserved && hasData ? Number(rawReservedPct || 0) : 0; const rsvVal = Number.isFinite(numReserved) && numReserved >= 0.05 ? Math.min(usedVal, numReserved) : 0; const actualVal = Math.max(0, usedVal - rsvVal); const resetStr = hasData ? formatCountdown(resetTime) : ''; patchText( metaEl, hasData ? t('quota.usedAndLeft', { reset: resetStr, used: formatPctNumber(usedVal), }) : fallbackMetaText ); if (hasData && rsvVal > 0) { const rsvStr = formatPctNumber(rsvVal); const actualStr = formatPctNumber(actualVal); const leases = Math.max(1, Number(leaseCount) || 1); const tipText = leases >= 2 ? t('quota.reservedTipMulti', { rsv: rsvStr, leases, actual: actualStr }) : t('quota.reservedTip', { rsv: rsvStr, actual: actualStr }); patchAttr(metaEl, 'title', tipText); patchAttr(trackEl, 'title', tipText); const actualWidth = +Math.min(100, actualVal).toFixed(2); const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); patchStyleVar(fillEl, '--fill-w', `${actualWidth}%`); patchStyleVar(fillReservedEl, '--reserved-w', `${rsvWidth}%`); patchClasses(fillReservedEl, { 'is-active': true, 'has-sep': actualWidth > 0 }); } else { patchAttr(metaEl, 'title', null); patchAttr(trackEl, 'title', null); patchStyleVar(fillEl, '--fill-w', `${Math.min(100, usedVal)}%`); patchStyleVar(fillReservedEl, '--reserved-w', '0%'); patchClasses(fillReservedEl, { 'is-active': false, 'has-sep': false }); } patchClasses(fillEl, { 'tone-warn': usedVal >= 70 && usedVal < 85, 'tone-danger': usedVal >= 85, }); } /** * 同步单个配额池行的 5h 及每周窗口状态。 */ function syncPoolQuotaRow(refs, item, idx, rowEl) { const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending, showReserved } = item; patchClasses(rowEl, { 'quota-pool-row': true, 'has-divider': idx > 0 }); const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; const used5hVal = has5h ? Number(poolData.usedPct) : 0; const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false); const wkUsedRaw = useCustomWeekly ? fallbackWeekly?.usedPct : poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null); const wkRemRaw = useCustomWeekly ? fallbackWeekly?.remainingPct : poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null); const wkResetRaw = useCustomWeekly ? fallbackWeekly?.resetTime || poolData?.weeklyResetTime : poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null); const hasWk = wkUsedRaw != null && wkRemRaw != null; const usedWkVal = hasWk ? Number(wkUsedRaw) : 0; const hide5h = !has5h && hasWk; const hideWk = !hasWk && has5h; refs.row5h.hidden = hide5h; refs.row5h.style.display = hide5h ? 'none' : 'flex'; refs.rowWk.hidden = hideWk; refs.rowWk.style.display = hideWk ? 'none' : 'flex'; const fallbackMetaText = isPending ? t('quota.loading') : t('quota.failed'); const allowReserved = Boolean(showReserved && !isPending); patchText(refs.title5h, `5h (${poolLabel})`); const c5h = poolData?.cycle5h; const est = poolData?.rateEstimate; if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) { const tok5h = formatTokens(c5h.tokens || 0); const cost5h = formatUsd(c5h.costUsd || 0); const calls5h = Number(c5h.calls || 0); const full5hRef = formatPoolFullCapRef(est?.eqFull5hUsd, est?.eqFull5hTokens); const baseTip5h = t('quota.cycle5hTitle', { pool: poolLabel, tok: tok5h, cost: cost5h, calls: calls5h, }); refs.usage5h.hidden = false; patchText(refs.usage5h, `· ${tok5h} (${cost5h})`); patchAttr( refs.left5h, 'title', full5hRef ? `${baseTip5h} · ${t('quota.cycleFullSuffix', { full: full5hRef })}` : baseTip5h ); } else { refs.usage5h.hidden = true; patchText(refs.usage5h, ''); patchAttr(refs.left5h, 'title', null); } syncQuotaWindowMeter({ hasData: has5h, usedVal: used5hVal, resetTime: poolData?.resetTime, fallbackMetaText, showReserved: allowReserved, rawReservedPct: poolData?.reservedPct, leaseCount: poolData?.reservedLeaseCount, metaEl: refs.meta5h, trackEl: refs.track5h, fillEl: refs.fill5h, fillReservedEl: refs.fillReserved5h, }); const customTitle = useCustomWeekly && fallbackWeekly?.title ? fallbackWeekly.title : t('quota.weeklyPool', { pool: poolLabel }); patchText(refs.titleWk, customTitle); const cWk = useCustomWeekly ? fallbackWeekly : poolData?.cycleWeekly || (isActivePool ? fallbackWeekly : null); if (!isPending && hasWk && cWk && (cWk.tokens != null || cWk.costUsd != null)) { const tokWk = formatTokens(cWk.tokens || 0); const costWk = formatUsd(cWk.costUsd || 0); const callsWk = Number(cWk.calls || 0); const fullWkRef = !useCustomWeekly ? formatPoolFullCapRef(est?.eqFullWeeklyUsd, est?.eqFullWeeklyTokens) : ''; const baseTipWk = useCustomWeekly ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) : t('quota.cycleWkPoolTitle', { pool: poolLabel, tok: tokWk, cost: costWk, calls: callsWk, }); refs.usageWk.hidden = false; patchText(refs.usageWk, `· ${tokWk} (${costWk})`); patchAttr( refs.leftWk, 'title', fullWkRef ? `${baseTipWk} · ${t('quota.cycleFullSuffix', { full: fullWkRef })}` : baseTipWk ); } else { refs.usageWk.hidden = true; patchText(refs.usageWk, ''); patchAttr(refs.leftWk, 'title', null); } syncQuotaWindowMeter({ hasData: hasWk, usedVal: usedWkVal, resetTime: wkResetRaw, fallbackMetaText, showReserved: allowReserved && !useCustomWeekly, rawReservedPct: poolData?.weeklyReservedPct, leaseCount: poolData?.weeklyReservedLeaseCount, metaEl: refs.metaWk, trackEl: refs.trackWk, fillEl: refs.fillWk, fillReservedEl: refs.fillReservedWk, }); } function quotaPoolRowSig(item, idx) { const c5h = item.poolData?.cycle5h; const cWk = item.poolData?.cycleWeekly; const est = item.poolData?.rateEstimate; const fw = item.fallbackWeekly; return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${est?.eqFull5hUsd}:${est?.eqFull5hTokens}:${est?.eqFullWeeklyUsd}:${est?.eqFullWeeklyTokens}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } /** * 格式化可用额度面板右上角的账号订阅徽章(区分 Ultra 5x / 20x,并对 Pro / Free 去重)。 * * @param {object|null|undefined} account * @returns {string} */ function formatAccountTierBadge(account) { const tierName = String(account?.tierName || '').trim() || 'Google AI'; const tierId = String(account?.tierId || '').trim().toLowerCase(); const explicitMult = String(account?.tierMultiplier || '').trim(); const inferredMult = explicitMult || (/(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(`${tierId} ${tierName}`) ? '5x' : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(`${tierId} ${tierName}`) || tierId === 'g1-ultra-tier' ? '20x' : ''); const rawPlan = String(account?.planName || '').trim(); const isUltra = /\bultra\b/i.test(tierName) || /ultra/i.test(tierId); if (isUltra) { if (inferredMult) { const hasMultInTier = new RegExp(`(?:^|\\s|·)${inferredMult}(?:$|\\s)`, 'i').test(tierName); return hasMultInTier ? tierName : `${tierName} · ${inferredMult}`; } if (rawPlan && !/^(?:pro|ultra)$/i.test(rawPlan)) { return `${tierName} · ${rawPlan}`; } return tierName; } if (!rawPlan) return tierName; const escapedPlan = rawPlan.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); if (new RegExp(`(?:^|\\s|·)${escapedPlan}(?:$|\\s)`, 'i').test(tierName)) { return tierName; } return `${tierName} · ${rawPlan}`; } /** * 对账号邮箱或名称做轻量隐私脱敏(如 `sjee80343@gmail.com` -> `sj***43@gmail.com`), * 兼顾多账号辨识度及截图分享隐私安全。 * * @param {string|null|undefined} raw * @returns {string} */ function maskAccountLabel(raw) { const str = String(raw || '').trim(); if (!str) return ''; const atIdx = str.indexOf('@'); if (atIdx > 0 && atIdx < str.length - 1) { const local = str.slice(0, atIdx); const domain = str.slice(atIdx); const chars = Array.from(local); if (chars.length <= 1) return `*${domain}`; if (chars.length === 2) return `${chars[0]}*${domain}`; if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}${domain}`; return `${chars.slice(0, 2).join('')}***${chars.slice(-2).join('')}${domain}`; } const chars = Array.from(str); if (chars.length <= 1) return '*'; if (chars.length === 2) return `${chars[0]}*`; if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}`; return `${chars.slice(0, 2).join('')}***${chars[chars.length - 1]}`; } function formatRateEqUsd(val) { const num = Number(val); if (!Number.isFinite(num) || num <= 0) return '--'; if (num >= 10) return `$${Math.round(num)}`; return `$${Number(num.toFixed(1))}`; } function formatPoolFullCapRef(eqUsd, eqTok) { const usdNum = Number(eqUsd); if (!Number.isFinite(usdNum) || usdNum <= 0) return ''; const usdStr = formatRateEqUsd(usdNum); const tokNum = Number(eqTok); if (Number.isFinite(tokNum) && tokNum > 0) { return `${usdStr} (${formatTokens(tokNum)})`; } return usdStr; } function formatRatePerUsdValue(rate) { const num = Number(rate); if (!Number.isFinite(num) || num <= 0) return '--'; return String(Number(num.toFixed(2))); } function formatRateMultiplier(mult) { const num = Number(mult); if (!Number.isFinite(num) || num <= 0) return ''; return `${Number(num.toFixed(1))}x`; } function createRateModelCard({ name, isMutedName = false, isFallback = false, multiplier = null, rate5hPctPerUsd = null, rateWeeklyPctPerUsd = null, eqFull5hUsd = null, eqFullWeeklyUsd = null, eqFull5hTokens = null, eqFullWeeklyTokens = null, samples = 0, source = null, isPreliminary = false, }) { const leftNodes = [ h('span', { className: `quota-rate-model-name${isMutedName ? ' is-muted' : ''}`, text: name, }), ]; const multText = formatRateMultiplier(multiplier); if (multText) { leftNodes.push( h('span', { className: `quota-rate-mult-badge${Number(multiplier) >= 1.5 ? ' is-high' : ''}`, text: multText, }) ); } const has5hRate = rate5hPctPerUsd != null; const primaryRate = has5hRate ? rate5hPctPerUsd : rateWeeklyPctPerUsd; const subParts = []; if (primaryRate != null) { subParts.push( t('quota.ratePopPerUsd', { win: has5hRate ? '5h' : t('quota.weeklyShort'), rate: formatRatePerUsdValue(primaryRate), }) ); } if (isPreliminary) { subParts.push( source === 'anchor_slope' ? t('quota.ratePopPrelimSlope') : t('quota.ratePopPrelimCycle') ); } else if (Number(samples) > 0) { subParts.push(t('quota.ratePopSamples', { n: Number(samples) })); } const eqCells = []; if (eqFull5hUsd != null) { const cell5hChildren = [ h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), h('span', { className: 'quota-rate-eq-v text-mono', text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, }), ]; if (Number.isFinite(Number(eqFull5hTokens)) && Number(eqFull5hTokens) > 0) { cell5hChildren.push( h('span', { className: 'quota-rate-eq-tok text-mono', text: `· ${formatTokens(Number(eqFull5hTokens))}`, }) ); } eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cell5hChildren)); } if (eqFullWeeklyUsd != null) { const cellWkChildren = [ h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), h('span', { className: 'quota-rate-eq-v text-mono', text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, }), ]; if (Number.isFinite(Number(eqFullWeeklyTokens)) && Number(eqFullWeeklyTokens) > 0) { cellWkChildren.push( h('span', { className: 'quota-rate-eq-tok text-mono', text: `· ${formatTokens(Number(eqFullWeeklyTokens))}`, }) ); } eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cellWkChildren)); } const cardChildren = [ h('div', { className: 'quota-rate-row-top' }, [ h('div', { className: 'quota-rate-model-left' }, leftNodes), ...(subParts.length > 0 ? [h('span', { className: 'quota-rate-meta text-mono', text: subParts.join(' · ') })] : []), ]), ]; if (eqCells.length > 0) { cardChildren.push( h( 'div', { className: `quota-rate-eq-grid${eqCells.length === 1 ? ' is-single' : ''}` }, eqCells ) ); } return h('div', { className: `quota-rate-model-row${isFallback ? ' is-fallback' : ''}` }, cardChildren); } function buildRatePopoverSig(data) { const locale = getEffectiveLocale(); const acct = String(data?.account?.email || data?.account?.name || '').trim(); const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; const poolSig = pools .map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`) .join('|'); return `${locale}|${acct}|${poolSig}`; } const QuotaPoolsWidget = defineComponent({ name: 'QuotaPoolsWidget', setup({ props, onCleanup }) { const compactHover = Boolean(props.compactHover); const titleTextEl = h('span', { text: t('module.quotas') }); const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); const ratePopTitleEl = h('span', { className: 'quota-rate-pop-title', text: t('quota.ratePopTitle'), }); const ratePopAccountEl = h('span', { className: 'quota-rate-pop-account', text: t('quota.ratePopAccountCurrent'), }); const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); const ratePopoverEl = h( 'div', { className: 'quota-rate-popover', role: 'tooltip', hidden: true, }, [ h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), ratePopBodyEl, ] ); ratePopoverEl.hidden = true; let ratePopOpen = false; let ratePopCloseTimer = null; let lastRatePopSig = ''; const cancelRatePopClose = () => { if (ratePopCloseTimer) { clearTimeout(ratePopCloseTimer); ratePopCloseTimer = null; } }; const setRatePopOpen = (open) => { const next = Boolean(open); ratePopOpen = next; ratePopoverEl.hidden = !next; patchAttr(ratePopoverEl, 'hidden', !next); patchAttr(rateHelpBtn, 'aria-expanded', next ? 'true' : 'false'); patchClasses(rateHelpBtn, { 'is-open': next }); }; const openRatePop = () => { cancelRatePopClose(); if (!ratePopOpen) setRatePopOpen(true); }; const scheduleRatePopClose = () => { cancelRatePopClose(); ratePopCloseTimer = setTimeout(() => { ratePopCloseTimer = null; setRatePopOpen(false); }, 130); }; const rateHelpBtn = h( 'button', { type: 'button', className: 'quota-rate-help-btn', 'aria-label': t('quota.rateHelpAria'), 'aria-haspopup': 'true', 'aria-expanded': 'false', onMouseenter: openRatePop, onMouseleave: scheduleRatePopClose, onFocus: openRatePop, onBlur: scheduleRatePopClose, onClick: (ev) => { ev?.stopPropagation?.(); cancelRatePopClose(); setRatePopOpen(!ratePopOpen); }, onKeydown: (ev) => { if (ev?.key === 'Escape' && ratePopOpen) { ev.stopPropagation?.(); cancelRatePopClose(); setRatePopOpen(false); } }, }, [createSvgIcon('help-circle', { size: 13 })] ); ratePopoverEl.addEventListener?.('mouseenter', openRatePop); ratePopoverEl.addEventListener?.('mouseleave', scheduleRatePopClose); onCleanup?.(() => { cancelRatePopClose(); }); function syncRatePopoverContent(data) { const sig = buildRatePopoverSig(data); if (sig === lastRatePopSig) return; lastRatePopSig = sig; patchText(ratePopTitleEl, t('quota.ratePopTitle')); patchAttr(rateHelpBtn, 'aria-label', t('quota.rateHelpAria')); const acctMasked = maskAccountLabel(data?.account?.email || data?.account?.name || ''); patchText( ratePopAccountEl, acctMasked ? t('quota.ratePopAccountScope', { account: acctMasked }) : t('quota.ratePopAccountCurrent') ); patchAttr(ratePopAccountEl, 'title', acctMasked || null); while (ratePopBodyEl.firstChild) { ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); } const rawPools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; const populatedGroups = []; for (const p of rawPools) { const est = p?.rateEstimate; if (!est || typeof est !== 'object') continue; const models = Array.isArray(est.models) ? est.models : []; const hasPoolFallback = models.length === 0 && (Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd)); const ext = est.externalUsage && est.externalUsage.detected ? est.externalUsage : null; if (models.length === 0 && !hasPoolFallback && !ext) continue; const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; const fallbackPrimaryIs5h = est.rate5hPctPerUsd != null; const anyModelHasWeekly = models.some((m) => m?.eqFullWeeklyUsd != null); const needsWeeklyFallbackRow = models.length > 0 && !anyModelHasWeekly && Number.isFinite(est.rateWeeklyPctPerUsd) && est.eqFullWeeklyUsd != null; const rows = models.length > 0 ? [ ...models.map((item) => createRateModelCard({ name: item.model, multiplier: item.multiplier, rate5hPctPerUsd: item.rate5hPctPerUsd, rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, eqFull5hUsd: item.eqFull5hUsd, eqFullWeeklyUsd: item.eqFullWeeklyUsd, eqFull5hTokens: item.eqFull5hTokens, eqFullWeeklyTokens: item.eqFullWeeklyTokens, samples: item.samples, }) ), ...(needsWeeklyFallbackRow ? [ createRateModelCard({ name: t('quota.ratePopPoolFallback'), isMutedName: true, isFallback: true, rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, eqFullWeeklyUsd: est.eqFullWeeklyUsd, eqFullWeeklyTokens: est.eqFullWeeklyTokens, samples: Number(est.samplesWeekly) || 0, source: est.sourceWeekly || null, isPreliminary: Boolean(est.isPreliminaryWeekly), }), ] : []), ] : hasPoolFallback ? [ createRateModelCard({ name: t('quota.ratePopPoolFallback'), isMutedName: true, isFallback: true, rate5hPctPerUsd: est.rate5hPctPerUsd, rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, eqFull5hUsd: est.eqFull5hUsd, eqFullWeeklyUsd: est.eqFullWeeklyUsd, eqFull5hTokens: est.eqFull5hTokens, eqFullWeeklyTokens: est.eqFullWeeklyTokens, samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), source: fallbackPrimaryIs5h ? est.source5h || null : est.sourceWeekly || null, isPreliminary: fallbackPrimaryIs5h ? Boolean(est.isPreliminary5h) : Boolean(est.isPreliminaryWeekly), }), ] : []; const headChildren = [h('div', { className: 'quota-rate-pool-label', text: poolLabel })]; if (ext?.activeRecently) { headChildren.push( h('span', { className: 'quota-rate-shared-badge', text: t('quota.ratePopSharedBadge'), title: t('quota.ratePopSharedBadgeTip'), }) ); } const groupChildren = [h('div', { className: 'quota-rate-pool-head' }, headChildren)]; if (rows.length > 0) { groupChildren.push(h('div', { className: 'quota-rate-model-list' }, rows)); } else { groupChildren.push( h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') }) ); } if (ext) { const extParts = []; if (Number(ext.used5hPct) >= 0.1) { extParts.push( t('quota.ratePopExt5h', { pct: formatPctNumber(Number(ext.used5hPct)) }) ); } if (Number(ext.usedWeeklyPct) >= 0.1) { extParts.push( t('quota.ratePopExtWk', { pct: formatPctNumber(Number(ext.usedWeeklyPct)) }) ); } const extText = extParts.length > 0 ? t('quota.ratePopExternalDetail', { detail: extParts.join(' · ') }) : t('quota.ratePopExternalBaseline'); groupChildren.push( h('div', { className: `quota-rate-ext-banner${ext.activeRecently ? ' is-active' : ''}`, text: extText, }) ); } populatedGroups.push(h('div', { className: 'quota-rate-pool-group' }, groupChildren)); } if (populatedGroups.length === 0) { ratePopBodyEl.appendChild( h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') }) ); } else { for (const grp of populatedGroups) { ratePopBodyEl.appendChild(grp); } } } const poolsListEl = h( 'div', compactHover ? { className: 'wm-hover-quota-pools' } : { style: 'display: flex; flex-direction: column; gap: 0;' } ); if (compactHover) { patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); } const legendActualTextEl = h('span', { text: t('quota.legendActual') }); const legendReservedTextEl = h('span', { text: t('quota.legendReserved') }); const reserveLegendEl = h( 'div', { className: 'quota-reserve-legend', hidden: true }, [ h('span', { className: 'quota-legend-item' }, [ h('span', { className: 'quota-legend-line is-actual', 'aria-hidden': 'true' }), legendActualTextEl, ]), h('span', { className: 'quota-legend-item' }, [ h('span', { className: 'quota-legend-line is-reserved', 'aria-hidden': 'true' }), legendReservedTextEl, ]), ] ); const quotaPanel = h('section', { className: 'panel quota-panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('pulse', { size: 13 }), titleTextEl, rateHelpBtn, ]), tierBadge, ]), poolsListEl, reserveLegendEl, ratePopoverEl, ]); syncRatePopoverContent(null); function update({ data, minuteTick } = {}) { patchText(titleTextEl, t('module.quotas')); patchText(legendActualTextEl, t('quota.legendActual')); patchText(legendReservedTextEl, t('quota.legendReserved')); syncRatePopoverContent(data); if (!data) { reserveLegendEl.hidden = true; if (compactHover) { patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); } return; } const quotas = data.quotas || {}; const showReserved = data.settings?.experimentalQuotaReservation !== false; reserveLegendEl.hidden = !showReserved; const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000); patchText(tierBadge, formatAccountTierBadge(data.account)); patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick, { showReserved }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); } return { el: quotaPanel, refs: { update, poolsListEl, rateHelpBtn, ratePopoverEl }, }; }, }); return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, maskAccountLabel, QuotaPoolsWidget }; })(); // --- src/components/widgets/AccountQuotaTrendCard.js --- const { resolveQuotaWindowBounds, buildQuotaWindowSeries, AccountQuotaTrendCard } = (() => { /** * @fileoverview Per-account quota remaining-% trajectory chart (`AccountQuotaTrendCard.js`). * Full-bleed edge-to-edge plot (`x = 1 .. viewW - 1`), X-axis clamped to earliest recorded * sample when history is shorter than the selected preset, and adaptive integer Y-scale so * real quota movements never compress into a tiny corner with wasted whitespace. */ const POOL_COLORS = Object.freeze({ Gemini: 'var(--accent-primary)', 'Claude & GPT': 'var(--metric-ok)', Argon: 'var(--ctx-thinking)', Carbon: 'var(--metric-warn)', }); const POOL_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; let quotaChartUid = 0; function floorMinute(ms) { const n = Number(ms); if (!(n > 0)) return 0; const d = new Date(n); d.setSeconds(0, 0); return d.getTime(); } function ceilMinute(ms) { const n = Number(ms); if (!(n > 0)) return 0; const d = new Date(n); d.setSeconds(59, 999); return d.getTime(); } function pad2(n) { return String(n).padStart(2, '0'); } function formatAxisTickTime(ms, spanMs) { const d = new Date(ms); const hm = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; if (spanMs <= 36 * 3600_000) { return hm; } const md = `${d.getMonth() + 1}/${pad2(d.getDate())}`; if (spanMs <= 7 * 86400_000) { return `${md} ${pad2(d.getHours())}h`; } return md; } function formatHoverTimestamp(ms) { const d = new Date(ms); return `${d.getMonth() + 1}/${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; } function buildHorizontalTangentSpline(pts) { if (pts.length === 0) return ''; if (pts.length === 1) return `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`; let d = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`; for (let i = 0; i < pts.length - 1; i++) { const p0 = pts[i]; const p1 = pts[i + 1]; const dx = (p1.x - p0.x) * 0.38; d += ` C ${(p0.x + dx).toFixed(1)} ${p0.y.toFixed(1)}, ${(p1.x - dx).toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; } return d; } const HOVER_SLOT_COUNT = 96; const MAX_SVG_COLUMN_BUCKETS = 96; /** * Downsamples dense sub-pixel SVG points (e.g. 12s poll bursts) into `<= maxCols` * min/max-preserving visual knots so curve rasterization and morphing stay crisp and fast, * while `rawPoints` remain intact for exact timestamp interpolation. */ function simplifySvgPointsForRender(svgPts, leftX, plotW, maxCols = MAX_SVG_COLUMN_BUCKETS) { if (svgPts.length <= maxCols) return svgPts; const colW = Math.max(1, plotW) / maxCols; const out = [svgPts[0]]; let idx = 1; const endIdx = svgPts.length - 1; while (idx < endIdx) { const col = Math.floor((svgPts[idx].x - leftX) / colW); let minPt = svgPts[idx]; let maxPt = svgPts[idx]; let j = idx + 1; while (j < endIdx && Math.floor((svgPts[j].x - leftX) / colW) === col) { const cand = svgPts[j]; if (cand.y < minPt.y) minPt = cand; if (cand.y > maxPt.y) maxPt = cand; j += 1; } if (minPt === maxPt) { out.push(minPt); } else if (minPt.x <= maxPt.x) { out.push(minPt, maxPt); } else { out.push(maxPt, minPt); } idx = j; } out.push(svgPts[endIdx]); return out; } /** * Computes tight, integer-aligned `[yMin, yMid, yMax]` bounds (`0..100%`) around * observed `[dataMin, dataMax]` so small-to-moderate quota changes use the full * vertical canvas instead of leaving 80%+ empty bottom space. */ function computeAdaptiveQuotaScale(dataMin, dataMax) { const lo = Math.max(0, Math.min(100, Number.isFinite(dataMin) ? dataMin : 0)); const hi = Math.max(lo, Math.min(100, Number.isFinite(dataMax) ? dataMax : 100)); const rawSpan = hi - lo; const pad = Math.max(1.5, rawSpan * 0.14); let yMax = hi >= 98.5 ? 100 : Math.min(100, Math.ceil((hi + pad) / 10) * 10); let yMin = lo <= 2 ? 0 : Math.max(0, Math.floor((lo - pad) / 10) * 10); if (yMax - yMin < 10) { if (yMax >= 100) { yMax = 100; yMin = 90; } else if (yMin <= 0) { yMin = 0; yMax = 10; } else { yMin = Math.max(0, yMax - 10); } } // Ensure `(yMax - yMin)` is even so midpoint tick is always an exact integer if ((yMax - yMin) % 2 !== 0) { if (yMin > 0) yMin -= 1; else if (yMax < 100) yMax += 1; } const yMid = Math.round((yMin + yMax) / 2); return { yMin, yMid, yMax, span: Math.max(1, yMax - yMin) }; } const IMPULSE_GLITCH_MAX_SPAN_MS = 20 * 60_000; const IMPULSE_GLITCH_MIN_JUMP_PCT = 3; const IMPULSE_GLITCH_MAX_NEIGHBOR_DIFF_PCT = 1.2; const CYCLE_RESET_JUMP_MIN_PCT = 3.5; function stripIsolatedImpulseSpikes(pts) { if (pts.length < 3) return pts; const out = pts.slice(); let i = 1; while (i < out.length - 1) { const prev = out[i - 1]; const cur = out[i]; const next = out[i + 1]; const spanMs = next.ts - prev.ts; if ( spanMs >= 0 && spanMs <= IMPULSE_GLITCH_MAX_SPAN_MS && cur.val - prev.val >= IMPULSE_GLITCH_MIN_JUMP_PCT && cur.val - next.val >= IMPULSE_GLITCH_MIN_JUMP_PCT && Math.abs(next.val - prev.val) <= IMPULSE_GLITCH_MAX_NEIGHBOR_DIFF_PCT ) { out.splice(i, 1); if (i > 1) i -= 1; continue; } i += 1; } return out; } function resolveQuotaWindowBounds({ pools, selectedRange, selectedWin, selectedPool, customStartMs = 0, customEndMs = 0, nowMs = Date.now(), }) { if (selectedRange === 'custom') { return { startMs: Math.min(customStartMs, customEndMs), endMs: Math.max(customStartMs, customEndMs), }; } if (selectedRange === 'today') { const d = new Date(nowMs); d.setHours(0, 0, 0, 0); return { startMs: d.getTime(), endMs: nowMs }; } if (selectedRange === '24h') return { startMs: nowMs - 24 * 3600_000, endMs: nowMs }; if (selectedRange === '7d') return { startMs: nowMs - 7 * 86400_000, endMs: nowMs }; if (selectedRange === '14d') return { startMs: nowMs - 14 * 86400_000, endMs: nowMs }; if (selectedRange === '30d') return { startMs: nowMs - 30 * 86400_000, endMs: nowMs }; if (selectedRange === 'all') { let minTs = Infinity; for (const p of pools) { for (const pt of p.points) { if (pt[0] > 0 && pt[0] < minTs) minTs = pt[0]; } } const safeStart = Number.isFinite(minTs) && minTs < nowMs - 60_000 ? minTs : nowMs - 5 * 3600_000; return { startMs: safeStart, endMs: nowMs }; } const targetPools = selectedPool !== 'all' ? pools.filter((p) => p.poolKey === selectedPool) : pools; const refPools = targetPools.length ? targetPools : pools; const isWeekly = selectedWin === 'weekly'; const winDurationMs = isWeekly ? 7 * 86400_000 : 5 * 3600_000; let activeMinResetMs = Infinity; let anyMinResetMs = Infinity; for (const p of refPools) { const rMs = isWeekly ? p.resetWeeklyMs : p.reset5hMs; const liveVal = isWeekly ? p.liveWk : p.live5h; if (!(rMs > nowMs)) continue; if (rMs < anyMinResetMs) anyMinResetMs = rMs; if (liveVal !== null && liveVal !== undefined && liveVal < 99.95 && rMs < activeMinResetMs) { activeMinResetMs = rMs; } } const chosenResetMs = Number.isFinite(activeMinResetMs) ? activeMinResetMs : Number.isFinite(anyMinResetMs) ? anyMinResetMs : 0; const startMs = chosenResetMs > nowMs ? chosenResetMs - winDurationMs : nowMs - winDurationMs; return { startMs: Math.min(startMs, nowMs - 60_000), endMs: nowMs }; } /** * Extracts per-pool trajectories for the requested window, ensuring `'cycle'` mode * strictly excludes pre-reset points from any previous expired cycle (eliminating * artificial `84% -> 100%` vertical reset spikes at cycle start). */ function buildQuotaWindowSeries({ visiblePools, rawBounds, selectedRange, selectedWin, nowMs = Date.now(), }) { const isCycleMode = selectedRange === 'cycle'; const isWeekly = selectedWin === 'weekly'; const valIdx = isWeekly ? 2 : 1; const winDurationMs = isWeekly ? 7 * 86400_000 : 5 * 3600_000; const staged = []; let hasStartAnchor = false; let earliestInWinTs = Infinity; for (const p of visiblePools) { const cleanedAll = []; for (let i = 0; i < p.points.length; i++) { const pt = p.points[i]; const v = pt[valIdx]; if (v === null || v === undefined || !Number.isFinite(Number(v))) continue; cleanedAll.push({ ts: pt[0], val: Math.max(0, Math.min(100, Number(v))), }); } const sanitized = stripIsolatedImpulseSpikes(cleanedAll); if (sanitized.length === 0) continue; const pResetMs = isWeekly ? p.resetWeeklyMs : p.reset5hMs; const pLiveVal = isWeekly ? p.liveWk : p.live5h; const poolCutoffMs = isCycleMode && pResetMs > nowMs && pLiveVal !== null && pLiveVal < 99.95 ? Math.max(rawBounds.startMs, pResetMs - winDurationMs) : rawBounds.startMs; let carryBefore = null; let inWinPts = []; for (let i = 0; i < sanitized.length; i++) { const sp = sanitized[i]; if (sp.ts <= poolCutoffMs) { carryBefore = sp; } else if (sp.ts <= rawBounds.endMs) { inWinPts.push(sp); } } // In `'cycle'` mode, `< 99.95%` observations at or before `poolCutoffMs` belong // to the previous expired cycle and must never carry forward into the new cycle. if (isCycleMode && carryBefore && carryBefore.val < 99.95) { carryBefore = null; } let hadResetInWindow = false; if (isCycleMode && inWinPts.length >= 2) { let lastResetIdx = 0; for (let k = 1; k < inWinPts.length; k++) { const prev = inWinPts[k - 1].val; const cur = inWinPts[k].val; if (cur - prev >= CYCLE_RESET_JUMP_MIN_PCT || (cur >= 99.5 && prev <= 98.5)) { lastResetIdx = k; } } if (lastResetIdx > 0) { inWinPts = inWinPts.slice(lastResetIdx); carryBefore = null; hadResetInWindow = true; } } const isMidWindowReset = hadResetInWindow && inWinPts[0].ts - poolCutoffMs > 5 * 60_000; const anchorsCycleOrigin = isCycleMode && !isMidWindowReset && !carryBefore && inWinPts.length > 0 && inWinPts[0].ts - poolCutoffMs <= 3 * 60_000; if (carryBefore || (anchorsCycleOrigin && poolCutoffMs <= rawBounds.startMs + 5000)) { hasStartAnchor = true; } if (inWinPts.length > 0 && inWinPts[0].ts < earliestInWinTs) { earliestInWinTs = inWinPts[0].ts; } staged.push({ pool: p, poolCutoffMs, carryBefore, inWinPts, isMidWindowReset, anchorsCycleOrigin, }); } let plottedStartMs = rawBounds.startMs; if ( !hasStartAnchor && selectedRange !== 'custom' && Number.isFinite(earliestInWinTs) && earliestInWinTs > rawBounds.startMs ) { plottedStartMs = rawBounds.endMs - earliestInWinTs >= 60_000 ? earliestInWinTs : Math.max(rawBounds.startMs, rawBounds.endMs - 5 * 60_000); } const plottedEndMs = Math.max(plottedStartMs + 60_000, rawBounds.endMs); const rawBuilt = []; let dataMin = Infinity; let dataMax = -Infinity; for (const item of staged) { const { pool, poolCutoffMs, carryBefore, inWinPts, isMidWindowReset, anchorsCycleOrigin } = item; const seriesPts = []; const anchorStartTs = Math.max(plottedStartMs, poolCutoffMs); if (carryBefore) { seriesPts.push({ ts: anchorStartTs, val: carryBefore.val }); } else if (anchorsCycleOrigin) { const originVal = Math.max(100, inWinPts[0].val); if (inWinPts[0].ts > anchorStartTs) { seriesPts.push({ ts: anchorStartTs, val: Math.min(100, originVal) }); } } else if ( !isMidWindowReset && inWinPts.length > 0 && inWinPts[0].ts > plottedStartMs && (inWinPts.length === 1 || inWinPts[0].val >= 99.95) ) { seriesPts.push({ ts: plottedStartMs, val: inWinPts[0].val }); } for (let i = 0; i < inWinPts.length; i++) { const vp = inWinPts[i]; if (vp.ts >= plottedStartMs) { seriesPts.push(vp); } } if (seriesPts.length > 0 && plottedEndMs <= nowMs + 60_000) { const tail = seriesPts[seriesPts.length - 1]; const tailEnd = Math.min(plottedEndMs, nowMs); if (tailEnd > tail.ts + 1000) { seriesPts.push({ ts: tailEnd, val: tail.val }); } } if (seriesPts.length === 0) continue; for (let i = 0; i < seriesPts.length; i++) { const v = seriesPts[i].val; if (v < dataMin) dataMin = v; if (v > dataMax) dataMax = v; } rawBuilt.push({ poolKey: pool.poolKey, label: pool.label, color: POOL_COLORS[pool.poolKey] || 'var(--accent-primary)', rawPoints: seriesPts, latestVal: seriesPts[seriesPts.length - 1].val, }); } return { plottedStartMs, plottedEndMs, rawBuilt, yScale: rawBuilt.length > 0 ? computeAdaptiveQuotaScale(dataMin, dataMax) : null, }; } function getTimeRangeOptions() { 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') }, { value: '14d', label: t('cons.range14d') }, { value: '30d', label: t('cons.range30d') }, { value: 'all', label: t('cons.rangeAll') }, { value: 'custom', label: t('cons.rangeCustom') }, ]; } function getQuotaWindowOptions() { return [ { value: '5h', label: t('settings.account.win5h') }, { value: 'weekly', label: t('settings.account.winWeekly') }, ]; } const AccountQuotaTrendCard = defineComponent({ name: 'AccountQuotaTrendCard', setup({ onCleanup }) { const VIEW_H = 184; const TOP_Y = 18; const BOTTOM_Y = 166; const SPAN_Y = BOTTOM_Y - TOP_Y; const LEFT_X = 1; const RIGHT_PAD = 1; let viewW = 460; let selectedRange = 'cycle'; let selectedWin = '5h'; let selectedPool = 'all'; let selectedAccountEmail = ''; const initNow = Date.now(); let customStartMs = floorMinute(initNow - 24 * 3600_000); let customEndMs = ceilMinute(initNow); let draftStartMs = customStartMs; let draftEndMs = customEndMs; let latestState = { activeEmail: '', activePools: [], riskAccepted: false, accounts: [], savedQuotas: new Map(), quotaHistory: {}, }; let plottedSeries = []; let plottedStartMs = 0; let plottedEndMs = 0; let plottedYScale = { yMin: 0, yMid: 50, yMax: 100, span: 100 }; const cardTitleText = h('span', { text: t('settings.account.trendTitle') }); const spanBadgeEl = h('span', { className: 'cons-badge text-mono', text: '' }); const accountSelect = CustomSelect({ className: 'cons-cycle-pool-select account-trend-email-select', modelValue: '', options: [], onUpdateModelValue: (val) => { selectedAccountEmail = String(val || '').trim().toLowerCase(); hideHover(); renderChart(); }, }); patchAttr(accountSelect.el, 'hidden', true); const poolSelect = CustomSelect({ className: 'cons-cycle-pool-select', modelValue: 'all', options: [{ value: 'all', label: t('cons.cyclePoolAll') }], onUpdateModelValue: (val) => { selectedPool = val || 'all'; hideHover(); renderChart(); }, }); const winSwitch = SegmentedControl({ ariaLabel: t('settings.account.trendWinAria'), modelValue: selectedWin, options: getQuotaWindowOptions(), onUpdateModelValue: (val) => { selectedWin = val === 'weekly' ? 'weekly' : '5h'; winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); hideHover(); renderChart(); }, }); const rangeSwitch = SegmentedControl({ ariaLabel: t('cons.rangeAria'), modelValue: selectedRange, options: getTimeRangeOptions(), onUpdateModelValue: (nextRange) => { selectedRange = nextRange || 'cycle'; if (selectedRange === 'custom') { startPicker.setValue(draftStartMs); endPicker.setValue(draftEndMs); } rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); hideHover(); renderChart(); }, }); const startPicker = CustomDateTimePicker({ modelValue: draftStartMs, onUpdateModelValue: (ms) => { draftStartMs = ms; startPicker.setValue(ms); }, }); const endPicker = CustomDateTimePicker({ modelValue: draftEndMs, onUpdateModelValue: (ms) => { draftEndMs = ms; endPicker.setValue(ms); }, }); const applyCustomLabel = h('span', { text: t('cons.applyFilter') }); const applyCustomBtn = h( 'button', { type: 'button', className: 'btn-primary', onClick: () => { const s = Number(draftStartMs || 0); const e = Number(draftEndMs || 0); const lo = floorMinute(s > 0 && e > 0 ? Math.min(s, e) : s); const hi = ceilMinute(s > 0 && e > 0 ? Math.max(s, e) : e); if (lo > 0 && hi > lo) { customStartMs = lo; customEndMs = hi; draftStartMs = lo; draftEndMs = hi; startPicker.setValue(lo); endPicker.setValue(hi); renderChart(); } }, }, [createSvgIcon('check', { size: 12 }), applyCustomLabel] ); const rangeToEl = h('span', { className: 'text-muted', text: t('cons.rangeTo') }); const customRangeBar = h('div', { className: 'cons-custom-range-bar', hidden: true }, [ startPicker.el, rangeToEl, endPicker.el, applyCustomBtn, ]); // --- Full-Bleed Edge-to-Edge 184px SVG Stage (reusing TrendAreaChart `.trend-svg`) --- const uid = ++quotaChartUid; const gradId = `acct-quota-grad-${uid}`; const svg = document.createElementNS(SVG_NS, 'svg'); svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); svg.setAttribute('class', 'trend-svg'); svg.setAttribute('aria-hidden', 'true'); const defs = document.createElementNS(SVG_NS, 'defs'); const grad = document.createElementNS(SVG_NS, 'linearGradient'); grad.setAttribute('id', gradId); grad.setAttribute('x1', '0'); grad.setAttribute('y1', '0'); grad.setAttribute('x2', '0'); grad.setAttribute('y2', '1'); const stopTop = document.createElementNS(SVG_NS, 'stop'); stopTop.setAttribute('offset', '0%'); stopTop.setAttribute('stop-color', 'var(--accent-primary)'); stopTop.setAttribute('stop-opacity', '0.24'); const stopBot = document.createElementNS(SVG_NS, 'stop'); stopBot.setAttribute('offset', '100%'); stopBot.setAttribute('stop-color', 'var(--accent-primary)'); stopBot.setAttribute('stop-opacity', '0.0'); grad.appendChild(stopTop); grad.appendChild(stopBot); defs.appendChild(grad); svg.appendChild(defs); const gridGroup = document.createElementNS(SVG_NS, 'g'); gridGroup.setAttribute('class', 'trend-grid'); const gridRowSpecs = [ { y: TOP_Y, dy: 3, labeled: true }, { y: Math.round(TOP_Y + SPAN_Y * 0.25), dy: 0, labeled: false }, { y: Math.round(TOP_Y + SPAN_Y * 0.5), dy: 3, labeled: true }, { y: Math.round(TOP_Y + SPAN_Y * 0.75), dy: 0, labeled: false }, { y: BOTTOM_Y, dy: -3, labeled: true }, ]; const gridLines = []; const yLabels = []; for (const row of gridRowSpecs) { const line = document.createElementNS(SVG_NS, 'line'); line.setAttribute('x1', '0'); line.setAttribute('y1', String(row.y)); line.setAttribute('x2', String(viewW)); line.setAttribute('y2', String(row.y)); gridGroup.appendChild(line); gridLines.push(line); if (row.labeled) { const lbl = document.createElementNS(SVG_NS, 'text'); lbl.setAttribute('class', 'sstep-axis-label is-y-inline'); lbl.setAttribute('x', '3'); lbl.setAttribute('y', String(row.y + row.dy)); lbl.setAttribute('text-anchor', 'start'); yLabels.push(lbl); } } svg.appendChild(gridGroup); const seriesGroup = document.createElementNS(SVG_NS, 'g'); svg.appendChild(seriesGroup); // Append inline Y labels above series fills so halo stroke keeps text crisp const yLabelOverlay = document.createElementNS(SVG_NS, 'g'); for (const lbl of yLabels) { yLabelOverlay.appendChild(lbl); } svg.appendChild(yLabelOverlay); const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', String(TOP_Y)); hoverLine.setAttribute('y2', String(BOTTOM_Y)); hoverLine.setAttribute('hidden', ''); svg.appendChild(hoverLine); const hoverDotsGroup = document.createElementNS(SVG_NS, 'g'); hoverDotsGroup.setAttribute('hidden', ''); svg.appendChild(hoverDotsGroup); const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' }); const tipWinEl = h('span', { className: 'trend-tip-calls' }); const tipRowsHost = h('div', { className: 'account-trend-tip-rows' }); const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipWinEl]), tipRowsHost, ]); const xAxisEl = h('div', { className: 'trend-x-axis' }); const legendRowEl = h('div', { className: 'account-trend-legend' }); const emptyStateEl = h('div', { className: 'smodel-empty settings-action-desc', hidden: true }); const plotStage = h( 'div', { className: 'trend-plot-stage', onMousemove: handlePointerMove, onMouseleave: hideHover, }, [svg] ); const chartWrap = h('div', { className: 'trend-chart-wrap' }, [ plotStage, xAxisEl, legendRowEl, tooltipEl, ]); const tooltipCtrl = createFloatingChartTooltipController({ containerEl: chartWrap, tooltipEl, defaultTipWidth: 204, defaultTipHeight: 78, defaultViewWidth: 460, defaultViewHeight: VIEW_H, }); const seriesMorphCtrl = createMultiSeriesCurveMorphController(); const seriesNodePoolByKey = new Map(); const hoverDotPoolByKey = new Map(); let xTickElements = []; let hoveredSlotIdx = -1; let lastActiveDots = []; let lastFallbackX = 0; let lastFallbackY = 0; let lastSizeKey = ''; let lastTipTimeStr = ''; let lastTipWinStr = ''; let lastHoveredTickIdx = -1; let lastPointer = null; let cachedSvgRect = null; let lastPlotSig = ''; const rootEl = h('section', { className: 'panel account-quota-trend-panel' }, [ h('div', { className: 'panel-header account-trend-toprow' }, [ h('span', { className: 'panel-title cons-overview-title' }, [ createSvgIcon('pulse', { size: 13 }), cardTitleText, accountSelect.el, poolSelect.el, ]), winSwitch.el, ]), h('div', { className: 'panel-header cons-overview-head account-trend-subbar' }, [ spanBadgeEl, h('div', { className: 'cons-overview-controls' }, [rangeSwitch.el]), ]), customRangeBar, chartWrap, emptyStateEl, ]); function valueToSvgY(val) { const clamped = Math.max(plottedYScale.yMin, Math.min(plottedYScale.yMax, val)); return BOTTOM_Y - ((clamped - plottedYScale.yMin) / plottedYScale.span) * SPAN_Y; } function syncHoveredTickClass(activeTickIdx) { if (activeTickIdx === lastHoveredTickIdx) return; lastHoveredTickIdx = activeTickIdx; for (let i = 0; i < xTickElements.length; i++) { patchClasses(xTickElements[i], { 'is-hovered': i === activeTickIdx }); } } function hideHover() { cachedSvgRect = null; hoveredSlotIdx = -1; lastActiveDots = []; lastTipTimeStr = ''; lastTipWinStr = ''; lastPointer = null; tooltipCtrl.hide(); hoverLine.setAttribute('hidden', ''); hoverDotsGroup.setAttribute('hidden', ''); for (const dot of hoverDotPoolByKey.values()) { dot.setAttribute('hidden', ''); patchClasses(dot, { 'is-tracking': false }); } syncHoveredTickClass(-1); } function sampleSeriesValueAt(points, targetMs) { if (!points.length) return null; if (targetMs < points[0].ts - 1000) return null; if (targetMs <= points[0].ts) return points[0].val; const last = points[points.length - 1]; if (targetMs > last.ts + 60_000) return null; if (targetMs >= last.ts) return last.val; let lo = 0; let hi = points.length - 1; while (lo + 1 < hi) { const mid = (lo + hi) >> 1; if (points[mid].ts <= targetMs) lo = mid; else hi = mid; } const a = points[lo]; const b = points[hi]; const span = b.ts - a.ts; if (span <= 0) return b.val; return a.val + (b.val - a.val) * ((targetMs - a.ts) / span); } function showHoverAtSlot(slotIdx, pointer = null, { forceRefresh = false } = {}) { if (!plottedSeries.length || !(plottedEndMs > plottedStartMs) || slotIdx < 0) { hideHover(); return; } const clampedSlot = Math.max(0, Math.min(HOVER_SLOT_COUNT, slotIdx)); const wasHidden = tooltipEl.hasAttribute('hidden'); const changedSlot = forceRefresh || wasHidden || clampedSlot !== hoveredSlotIdx; hoveredSlotIdx = clampedSlot; if (pointer) lastPointer = pointer; if (changedSlot) { const u = clampedSlot / HOVER_SLOT_COUNT; const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); const clampedX = LEFT_X + u * plotW; const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs)); hoverLine.setAttribute('x1', clampedX.toFixed(1)); hoverLine.setAttribute('x2', clampedX.toFixed(1)); const tipItems = []; const activeDots = []; let sumY = 0; const usedKeys = new Set(); for (let i = 0; i < plottedSeries.length; i++) { const s = plottedSeries[i]; const val = sampleSeriesValueAt(s.rawPoints, targetMs); if (val === null) continue; usedKeys.add(s.poolKey); const y = valueToSvgY(val); sumY += y; let dot = hoverDotPoolByKey.get(s.poolKey); if (!dot) { dot = document.createElementNS(SVG_NS, 'circle'); dot.setAttribute('class', 'trend-hover-dot'); dot.setAttribute('r', '3.2'); dot.style.fill = 'var(--surface-panel)'; hoverDotPoolByKey.set(s.poolKey, dot); hoverDotsGroup.appendChild(dot); } if (dot._lastColor !== s.color) { dot._lastColor = s.color; dot.style.stroke = s.color; } dot.setAttribute('cx', clampedX.toFixed(1)); dot.setAttribute('cy', y.toFixed(1)); if (dot.hasAttribute('hidden')) dot.removeAttribute('hidden'); activeDots.push(dot); tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val }); } for (const [k, dot] of hoverDotPoolByKey.entries()) { if (!usedKeys.has(k) && !dot.hasAttribute('hidden')) { dot.setAttribute('hidden', ''); patchClasses(dot, { 'is-tracking': false }); } } if (tipItems.length === 0) { hideHover(); return; } if (hoverLine.hasAttribute('hidden')) hoverLine.removeAttribute('hidden'); if (hoverDotsGroup.hasAttribute('hidden')) hoverDotsGroup.removeAttribute('hidden'); if (xTickElements.length > 1) { syncHoveredTickClass(Math.round(u * (xTickElements.length - 1))); } const nextTimeStr = formatHoverTimestamp(targetMs); if (nextTimeStr !== lastTipTimeStr) { lastTipTimeStr = nextTimeStr; patchText(tipTimeEl, nextTimeStr); } const nextWinStr = t( selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h' ); if (nextWinStr !== lastTipWinStr) { lastTipWinStr = nextWinStr; patchText(tipWinEl, nextWinStr); } patchKeyedList(tipRowsHost, tipItems, { keyFn: (it) => it.key, sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`, createRow: () => { const sw = h('span', { className: 'dot-swatch' }); const nm = h('span', { className: 'account-trend-tip-name' }); const vl = h('strong', { className: 'text-mono' }); const row = h('div', { className: 'account-trend-tip-row' }, [ h('span', { className: 'legend-left' }, [sw, nm]), vl, ]); return { el: row, refs: { sw, nm, vl } }; }, updateRow: (r, it) => { if (r.sw._lastBg !== it.color) { r.sw._lastBg = it.color; r.sw.style.background = it.color; } patchText(r.nm, it.label); patchText(r.vl, `${+it.val.toFixed(1)}%`); }, }); const wrapRect = tooltipCtrl.getWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(chartWrap.clientWidth || viewW || 460); lastFallbackX = (clampedX / Math.max(1, viewW)) * wrapW; lastFallbackY = sumY / activeDots.length + 6; lastActiveDots = activeDots; lastSizeKey = `rows:${tipItems.length}`; } tooltipCtrl.show({ fallbackX: lastFallbackX, fallbackY: lastFallbackY, pointer: pointer || lastPointer, trackedDots: lastActiveDots, viewWidth: viewW, viewHeight: VIEW_H, sizeKey: lastSizeKey, }); } function handlePointerMove(ev) { if (!plottedSeries.length || !(plottedEndMs > plottedStartMs)) { hideHover(); return; } if (!cachedSvgRect) { cachedSvgRect = svg.getBoundingClientRect?.() || null; } const rect = cachedSvgRect; const widthPx = Number(rect?.width || viewW); if (!(widthPx > 0)) { cachedSvgRect = null; return; } const offsetX = Number(ev.clientX || 0) - Number(rect?.left || 0); const svgX = (offsetX / widthPx) * viewW; const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); const u = Math.max(0, Math.min(1, (svgX - LEFT_X) / plotW)); const slotIdx = Math.round(u * HOVER_SLOT_COUNT); const pointer = Number.isFinite(Number(ev?.clientX)) && Number.isFinite(Number(ev?.clientY)) ? { clientX: Number(ev.clientX), clientY: Number(ev.clientY) } : null; showHoverAtSlot(slotIdx, pointer); } function resolveTargetAccountEmail() { const { activeEmail, riskAccepted, accounts } = latestState; if (!riskAccepted) { return activeEmail || ''; } const candidates = []; if (activeEmail) candidates.push(activeEmail); for (const addr of accounts) { if (addr && !candidates.includes(addr)) candidates.push(addr); } if (selectedAccountEmail && candidates.includes(selectedAccountEmail)) { return selectedAccountEmail; } selectedAccountEmail = candidates[0] || ''; return selectedAccountEmail; } function buildMergedPoolsForEmail(email, nowMs) { const histPools = latestState.quotaHistory?.[email]?.pools || {}; const livePools = email && email === latestState.activeEmail ? latestState.activePools || [] : latestState.savedQuotas.get(email)?.pools || []; const merged = new Map(); for (const [pk, hEntry] of Object.entries(histPools)) { merged.set(pk, { poolKey: pk, label: hEntry.label || pk, reset5hMs: Number(hEntry.reset5hMs) || 0, resetWeeklyMs: Number(hEntry.resetWeeklyMs) || 0, points: Array.isArray(hEntry.points) ? hEntry.points.slice() : [], live5h: null, liveWk: null, }); } for (const lp of livePools) { const pk = String(lp?.poolKey || lp?.family || lp?.poolLabel || '').trim(); if (!pk || pk === 'Unknown') continue; let item = merged.get(pk); if (!item) { item = { poolKey: pk, label: String(lp?.poolLabel || pk), reset5hMs: 0, resetWeeklyMs: 0, points: [], live5h: null, liveWk: null, }; merged.set(pk, item); } if (lp?.poolLabel) item.label = String(lp.poolLabel); const r5Ms = Date.parse(lp?.resetTime || ''); const rWMs = Date.parse(lp?.weeklyResetTime || ''); if (Number.isFinite(r5Ms) && r5Ms > 0) item.reset5hMs = r5Ms; if (Number.isFinite(rWMs) && rWMs > 0) item.resetWeeklyMs = rWMs; if (Number.isFinite(lp?.remainingPct)) item.live5h = +Number(lp.remainingPct).toFixed(1); if (Number.isFinite(lp?.weeklyRemainingPct)) { item.liveWk = +Number(lp.weeklyRemainingPct).toFixed(1); } if (item.live5h !== null || item.liveWk !== null) { const last = item.points[item.points.length - 1]; if (!last || nowMs >= last[0]) { item.points.push([ nowMs, item.live5h ?? (last ? last[1] : null), item.liveWk ?? (last ? last[2] : null), ]); } } } return Array.from(merged.values()).sort( (a, b) => (POOL_ORDER.indexOf(a.poolKey) === -1 ? 99 : POOL_ORDER.indexOf(a.poolKey)) - (POOL_ORDER.indexOf(b.poolKey) === -1 ? 99 : POOL_ORDER.indexOf(b.poolKey)) ); } function renderChart({ skipMorph = false } = {}) { const nowMs = Date.now(); const locale = getEffectiveLocale(); patchText(cardTitleText, t('settings.account.trendTitle')); patchText(rangeToEl, t('cons.rangeTo')); patchText(applyCustomLabel, t('cons.applyFilter')); winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); patchAttr(customRangeBar, 'hidden', selectedRange !== 'custom'); const targetEmail = resolveTargetAccountEmail(); const candidateEmails = []; if (latestState.activeEmail) candidateEmails.push(latestState.activeEmail); if (latestState.riskAccepted) { for (const addr of latestState.accounts) { if (addr && !candidateEmails.includes(addr)) candidateEmails.push(addr); } } const showAccountPicker = latestState.riskAccepted && candidateEmails.length > 1; patchAttr(accountSelect.el, 'hidden', !showAccountPicker); if (showAccountPicker) { accountSelect.setProps({ modelValue: targetEmail, options: candidateEmails.map((addr) => ({ value: addr, label: addr.split('@')[0] || addr, title: addr, })), }); } const mergedPools = targetEmail ? buildMergedPoolsForEmail(targetEmail, nowMs) : []; if (selectedPool !== 'all' && !mergedPools.some((p) => p.poolKey === selectedPool)) { selectedPool = 'all'; } const poolOpts = [ { value: 'all', label: t('cons.cyclePoolAll'), }, ...mergedPools.map((p) => ({ value: p.poolKey, label: p.poolKey === 'Claude & GPT' ? 'Claude/GPT' : p.label, title: p.label, })), ]; poolSelect.setProps({ modelValue: selectedPool, options: poolOpts }); patchAttr(poolSelect.el, 'hidden', mergedPools.length <= 1); const rawBounds = resolveQuotaWindowBounds({ pools: mergedPools, selectedRange, selectedWin, selectedPool, customStartMs, customEndMs, nowMs, }); const visiblePools = selectedPool === 'all' ? mergedPools : mergedPools.filter((p) => p.poolKey === selectedPool); const built = buildQuotaWindowSeries({ visiblePools, rawBounds, selectedRange, selectedWin, nowMs, }); plottedStartMs = built.plottedStartMs; plottedEndMs = built.plottedEndMs; const spanMs = plottedEndMs - plottedStartMs; patchText(spanBadgeEl, formatDateSpanBadge(plottedStartMs, plottedEndMs)); const rawBuilt = built.rawBuilt; const hasPlot = rawBuilt.length > 0; patchAttr(chartWrap, 'hidden', !hasPlot); patchAttr(emptyStateEl, 'hidden', hasPlot); if (!hasPlot) { plottedSeries = []; lastPlotSig = ''; seriesMorphCtrl.reset(); hideHover(); patchText(emptyStateEl, t('settings.account.trendEmpty')); return; } plottedYScale = built.yScale; yLabels[0].textContent = `${plottedYScale.yMax}%`; yLabels[1].textContent = `${plottedYScale.yMid}%`; yLabels[2].textContent = `${plottedYScale.yMin}%`; const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); for (const gl of gridLines) { gl.setAttribute('x2', String(viewW)); } plottedSeries = rawBuilt.map((rb) => { const fullSvgPts = rb.rawPoints.map((sp) => { const u = Math.max(0, Math.min(1, (sp.ts - plottedStartMs) / spanMs)); return { x: LEFT_X + u * plotW, y: valueToSvgY(sp.val), val: sp.val, ts: sp.ts, }; }); return { ...rb, svgPts: simplifySvgPointsForRender(fullSvgPts, LEFT_X, plotW), }; }); const plotSig = `${locale}|${viewW}|${targetEmail}|${selectedWin}|${selectedRange}|${selectedPool}|${plottedYScale.yMin}-${plottedYScale.yMax}|` + plottedSeries .map( (s) => `${s.poolKey}:${s.svgPts.length}:${s.svgPts[0]?.x.toFixed(1)}:${s.svgPts[0]?.y.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.x.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.y.toFixed(1)}` ) .join('|'); if (plotSig !== lastPlotSig) { lastPlotSig = plotSig; const activePoolKeys = new Set(); const morphItems = []; for (let i = 0; i < plottedSeries.length; i++) { const s = plottedSeries[i]; activePoolKeys.add(s.poolKey); let nodes = seriesNodePoolByKey.get(s.poolKey); if (!nodes) { const areaEl = document.createElementNS(SVG_NS, 'path'); const lineEl = document.createElementNS(SVG_NS, 'path'); lineEl.setAttribute('fill', 'none'); lineEl.setAttribute('stroke-width', '1.9'); lineEl.setAttribute('stroke-linecap', 'round'); const endDotEl = document.createElementNS(SVG_NS, 'circle'); endDotEl.setAttribute('r', '2.7'); nodes = { areaEl, lineEl, endDotEl }; seriesNodePoolByKey.set(s.poolKey, nodes); } const lineD = buildHorizontalTangentSpline(s.svgPts); let areaD = ''; if (s.svgPts.length >= 2) { const first = s.svgPts[0]; const last = s.svgPts[s.svgPts.length - 1]; areaD = `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z`; if (plottedSeries.length === 1) { stopTop.setAttribute('stop-color', s.color); stopBot.setAttribute('stop-color', s.color); nodes.areaEl.removeAttribute('class'); nodes.areaEl.style.removeProperty('--sstep-series-color'); nodes.areaEl.setAttribute('fill', `url(#${gradId})`); } else { nodes.areaEl.removeAttribute('fill'); nodes.areaEl.setAttribute('class', 'sstep-multi-area'); nodes.areaEl.style.setProperty('--sstep-series-color', s.color); } nodes.areaEl.removeAttribute('hidden'); } else { nodes.areaEl.setAttribute('d', ''); nodes.areaEl.setAttribute('hidden', ''); } nodes.lineEl.setAttribute('stroke', s.color); nodes.endDotEl.setAttribute('fill', s.color); seriesGroup.appendChild(nodes.areaEl); seriesGroup.appendChild(nodes.lineEl); seriesGroup.appendChild(nodes.endDotEl); const endPt = s.svgPts[s.svgPts.length - 1]; morphItems.push({ key: s.poolKey, nextSegs: pointsToNormalizedCubicSegs(s.svgPts, BOTTOM_Y, { leftX: LEFT_X, spanX: plotW, tension: 0.38, }), lineEl: nodes.lineEl, areaEl: areaD ? nodes.areaEl : null, endDotEl: nodes.endDotEl, endX: endPt.x, endY: endPt.y, finalLineD: lineD, finalAreaD: areaD, }); } for (const [k, nodes] of seriesNodePoolByKey.entries()) { if (!activePoolKeys.has(k)) { nodes.areaEl.remove(); nodes.lineEl.remove(); nodes.endDotEl.remove(); } } seriesMorphCtrl.morphSeries({ items: morphItems, leftX: LEFT_X, spanX: plotW, bottomY: BOTTOM_Y, skipMorph, }); } // Edge-to-edge X-axis ticks (`0% .. 100%`) with active hover highlight & click-to-inspect const tickCount = 5; const activeTickIdx = hoveredSlotIdx >= 0 ? Math.round((hoveredSlotIdx / HOVER_SLOT_COUNT) * (tickCount - 1)) : -1; const ticks = []; for (let k = 0; k < tickCount; k++) { const ratio = k / (tickCount - 1); const tickMs = Math.round(plottedStartMs + ratio * spanMs); const leftPct = ratio * 100; ticks.push({ idx: k, slotIdx: Math.round(ratio * HOVER_SLOT_COUNT), leftPct, label: formatAxisTickTime(tickMs, spanMs), fullTitle: formatHoverTimestamp(tickMs), edge: k === 0 ? 'start' : k === tickCount - 1 ? 'end' : '', isHovered: k === activeTickIdx, }); } xTickElements = []; lastHoveredTickIdx = activeTickIdx; patchKeyedList(xAxisEl, ticks, { keyFn: (tk) => tk.idx, sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}:${tk.isHovered}`, createRow: () => { const el = h('span', { className: 'trend-x-tick text-mono' }); return { el, refs: { el } }; }, updateRow: (r, tk) => { patchText(r.el, tk.label); patchAttr(r.el, 'title', tk.fullTitle); patchStyleVar(r.el, '--tick-x', `${tk.leftPct.toFixed(2)}%`); patchClasses(r.el, { 'is-start': tk.edge === 'start', 'is-end': tk.edge === 'end', 'is-hovered': tk.isHovered, }); r.el.onclick = () => { lastPointer = null; showHoverAtSlot(tk.slotIdx, null, { forceRefresh: true }); }; xTickElements[tk.idx] = r.el; }, }); patchKeyedList(legendRowEl, plottedSeries, { keyFn: (s) => s.poolKey, sigFn: (s) => `${s.label}:${s.latestVal.toFixed(1)}:${s.color}`, createRow: () => { const sw = h('span', { className: 'dot-swatch' }); const nm = h('span', { className: 'account-trend-leg-name' }); const vl = h('strong', { className: 'text-mono' }); const el = h('span', { className: 'account-trend-leg-item' }, [sw, nm, vl]); return { el, refs: { sw, nm, vl } }; }, updateRow: (r, s) => { r.sw.style.background = s.color; patchText(r.nm, s.label); patchText(r.vl, `${+s.latestVal.toFixed(1)}%`); }, }); if (hoveredSlotIdx >= 0) { showHoverAtSlot(hoveredSlotIdx, lastPointer, { forceRefresh: true }); } } let resizeObs = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver((entries) => { cachedSvgRect = null; tooltipCtrl.invalidateRects(); const w = Math.floor(Number(entries?.[0]?.contentRect?.width || 0)); if (w >= 180 && Math.abs(w - viewW) >= 2) { viewW = w; renderChart({ skipMorph: true }); } }); resizeObs.observe(plotStage); } onCleanup(() => { seriesMorphCtrl.cancel(); tooltipCtrl.destroy(); resizeObs?.disconnect(); accountSelect.destroy(); poolSelect.destroy(); winSwitch.destroy(); rangeSwitch.destroy(); startPicker.destroy(); endPicker.destroy(); }); function update(nextState) { latestState = { ...latestState, ...nextState }; renderChart(); } renderChart(); return { el: rootEl, refs: { update, refreshLabels: () => renderChart() }, }; }, }); return { resolveQuotaWindowBounds, buildQuotaWindowSeries, AccountQuotaTrendCard }; })(); // --- src/components/widgets/LiveActivityWidget.js --- const { buildFallbackRunningConversations, LiveActivityWidget } = (() => { /** * @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`). * Displays active multi-session running conversations & collapsible subagent activity * with an isolated 1s elapsed timer lifecycle. Supports both Overview/Hover widget mode * and controlled Multi-Session Floating Panel mode (`WindowOverlayShell.js`). */ function buildFallbackRunningConversations( data, { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} ) { if (!data) return []; if (Array.isArray(data.runningConversations) && data.runningConversations.length > 0) { return data.runningConversations; } const activeConv = data.activeConversation || {}; if (!activeConv.isRunning && !aggregated?.isRunning) return []; const childAgents = (agents || []).filter((a) => !a.isMain); const swarmChildren = childAgents.filter((a) => a.agentKind === 'swarm_worker'); return [ { cascadeId: activeConv.cascadeId || 'current', title: activeConv.title || t('live.currentSession'), ...(activeConv.swarmTitle ? { swarmTitle: activeConv.swarmTitle } : {}), isCurrentSelected: true, isMainRunning: Boolean(activeConv.isRunning), isRunning: true, mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, subagentCount: childAgents.length, swarmCount: swarmChildren.length, runningSubagentCount: childAgents.filter((a) => a.isRunning).length, runningSwarmCount: swarmChildren.filter((a) => a.isRunning).length, ...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}), ...(contextUsedPct !== undefined ? { contextUsedPct } : {}), subagents: childAgents.map((s, idx) => { const isSwarmW = s.agentKind === 'swarm_worker'; const isKilled = Boolean(s.swarmState === 'killed'); return { cascadeId: s.cascadeId || s.agentId, index: s.index || idx + 1, agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'), agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1), customRole: s.customRole, ...(s.swarmState ? { swarmState: s.swarmState } : {}), ...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}), badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), shortLabel: s.shortLabel || `${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`, role: s.role || `${isSwarmW ? t('fmt.swarmAgent') : t('fmt.subAgent')} #${s.agentOrdinal || idx + 1}`, isRunning: Boolean(s.isRunning), stepCount: Number(s.stepCount || 0), lastModifiedMs: s.lastModifiedMs || 0, liveActivity: s.liveActivity || { phase: s.isRunning ? 'thinking' : isSwarmW && !isKilled ? 'waiting' : 'done', actionKey: s.isRunning ? 'thinking' : isSwarmW ? isKilled ? 'swarm_killed' : 'swarm_waiting' : 'done', label: s.isRunning ? t('live.thinking') : isSwarmW ? isKilled ? t('live.killed') : t('live.waiting') : t('live.done'), detail: '', stepProgress: '', startedAtMs: s.lastModifiedMs || 0, signature: `${s.agentId}:${s.swarmState || ''}:${s.stepCount || 0}`, }, }; }), }, ]; } const LiveActivityWidget = defineComponent({ name: 'LiveActivityWidget', setup({ props, onCleanup }) { const interactive = props.interactive !== false; const preview = Boolean(props.preview); const defaultExpandRunningSubs = Boolean(props.defaultExpandRunningSubs); const showSessionExtras = Boolean(props.showSessionExtras); const onSelectSession = typeof props.onSelectSession === 'function' ? props.onSelectSession : null; const onLayoutChange = typeof props.onLayoutChange === 'function' ? props.onLayoutChange : null; const getCtxAgentId = typeof props.getCtxAgentId === 'function' ? props.getCtxAgentId : () => uiStore.getState().ctxInspectorAgentId; const isVisibleFn = typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true; const liveActivityBar = h('div', { className: 'live-activity-list', hidden: true, 'aria-live': 'polite', }); const manualSubExpandMap = new Map(); const activityTimersMap = new Map(); let liveTickTimer = null; let latestUpdateArgs = null; function resolveIsExpanded(item) { const runSubCount = Number(item?.runningSubagentCount || 0); if (!interactive) return runSubCount > 0; if (manualSubExpandMap.has(item.cascadeId)) { return Boolean(manualSubExpandMap.get(item.cascadeId)); } return defaultExpandRunningSubs ? runSubCount > 0 : false; } function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { const now = Date.now(); const prev = activityTimersMap.get(timerKey); let startMs = prev?.startMs || 0; if (!prev || prev.sig !== sig) { const validRaw = Number(rawStartMs || 0); startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { startMs = Number(rawStartMs); } activityTimersMap.set(timerKey, { sig, startMs, el: targetEl }); const elapsedSec = Math.max(0, (now - startMs) / 1000); patchText(targetEl, formatElapsedSec(elapsedSec)); } function updateLiveElapsedDisplay() { const now = Date.now(); for (const entry of activityTimersMap.values()) { if (!entry?.el) continue; const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; patchText(entry.el, formatElapsedSec(elapsedSec)); } } function pauseTicker() { if (liveTickTimer) { clearInterval(liveTickTimer); liveTickTimer = null; } } function stopLiveTicker() { pauseTicker(); activityTimersMap.clear(); } function ensureLiveTicker() { if (!isVisibleFn() || activityTimersMap.size === 0) { pauseTicker(); return; } if (!liveTickTimer) { liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000); } } function resumeTicker() { if (activityTimersMap.size > 0) { updateLiveElapsedDisplay(); ensureLiveTicker(); } } 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 }); const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); const titleEl = h('strong', { className: 'live-task-title', text: t('live.currentSession'), }); const hereTagEl = showSessionExtras ? h('span', { className: 'wm-session-tag is-here', hidden: true, text: t('multi.hereTag'), }) : null; const metricsEl = showSessionExtras ? h('span', { className: 'wm-task-metrics text-mono', hidden: true, text: '', }) : null; 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', }); const headerEl = h('div', { className: 'live-task-header' }, [ h('div', { className: 'live-task-title-wrap' }, [ dotWrap, titleEl, ...(hereTagEl ? [hereTagEl] : []), ]), h('div', { className: 'live-task-header-right' }, [ ...(metricsEl ? [metricsEl] : []), subToggleBtn, elapsedEl, ]), ]); const mainBadge = h('span', { className: 'agent-badge badge-main', hidden: true, text: t('fmt.mainBadge'), }); const mainPhase = h('strong', { className: 'live-activity-phase', text: t('live.thinking'), }); const mainProgress = h('span', { className: 'live-activity-progress text-mono', hidden: true, text: '', }); const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); const mainDetail = h('span', { className: 'live-activity-detail', hidden: true, text: '', }); const mainRowEl = h('div', { className: 'live-task-main-row' }, [ mainBadge, mainPhase, mainProgress, mainSep, mainDetail, ]); const subListEl = h('div', { className: 'live-sub-list', hidden: true }); 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, refs: { cardEl, dotIcon, titleEl, hereTagEl, metricsEl, subToggleBtn, subToggleLabel, subToggleChevron, elapsedEl, mainBadge, mainPhase, mainProgress, mainSep, mainDetail, subListEl, subScroll, subAnimTimer: null, isCollapsingSubs: false, }, }; } function createLiveSubRow() { const subBadge = h('span', { className: 'agent-badge badge-sub-1', text: t('fmt.subBadge', { index: 1 }), }); const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') }); const subSummary = h('span', { className: 'live-sub-summary', text: '' }); const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' }); const rowEl = h('div', { className: 'live-sub-row' }, [ h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]), subElapsed, ]); return { el: rowEl, refs: { rowEl, subBadge, subRole, subSummary, subElapsed, }, }; } function update({ data = null, items = null, hostRouteConversationId = '' } = {}) { latestUpdateArgs = { data, items, hostRouteConversationId }; if (!data && !Array.isArray(items)) { patchAttr(liveActivityBar, 'hidden', true); stopLiveTicker(); return; } let rawRunningList = Array.isArray(items) ? items : null; if (!rawRunningList) { const { agents, aggregated } = resolveScopedConversation( data, 'all', getCtxAgentId() ); rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated }); } if (manualSubExpandMap.size > 0) { const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); for (const id of [...manualSubExpandMap.keys()]) { if (!runningIdsSet.has(id)) { manualSubExpandMap.delete(id); } } } const hasRunningTasks = rawRunningList.length > 0; patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); patchKeyedList(liveActivityBar, [], { destroyRow: (refs) => { clearSubExpandAnim(refs); refs?.subScroll?.destroy?.(); }, }); return; } if (!isVisibleFn()) { pauseTicker(); return; } const locale = getEffectiveLocale(); const hostRouteLower = showSessionExtras ? String(hostRouteConversationId || extractHostRouteCascadeId() || '').toLowerCase() : ''; const activeTimerKeys = new Set(); for (const item of rawRunningList) { activeTimerKeys.add(`main:${item.cascadeId}`); const subCount = Number(item.subagentCount || item.subagents?.length || 0); const isExp = resolveIsExpanded(item); if (subCount > 0 && isExp) { for (const sub of item.subagents || []) { if (sub?.isRunning) { activeTimerKeys.add(`sub:${sub.cascadeId}`); } } } } patchKeyedList(liveActivityBar, rawRunningList, { keyFn: (item) => item.cascadeId, sigFn: (item) => { const isExp = resolveIsExpanded(item); const isHere = showSessionExtras && Boolean(hostRouteLower) && (String(item.cascadeId || '').toLowerCase() === hostRouteLower || (item.subagents || []).some( (s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower )); const subSig = (item.subagents || []) .map( (s) => `${s.cascadeId}:${s.isRunning}:${s.swarmState || ''}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.swarmCount || 0}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { const act = item.mainActivity || { phase: 'thinking', actionKey: 'thinking', label: t('live.thinking'), detail: '', stepProgress: '', startedAtMs: item.lastModifiedMs || 0, signature: `fallback:${item.lastModifiedMs || 0}`, }; const isWaiting = act.phase === 'waiting'; const isCompacting = act.phase === 'compacting'; patchClasses(refs.cardEl, { 'is-waiting': isWaiting, 'is-compacting': isCompacting, }); patchClasses(refs.dotIcon, { 'is-pulsing': true }); const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); patchText(refs.titleEl, convTitle); if (interactive && !preview) { patchAttr( refs.titleEl, 'title', onSelectSession ? t('multi.inspectSessionTitle', { title: convTitle }) : t('live.switchSessionTitle', { title: convTitle }) ); refs.titleEl.onclick = (e) => { e?.stopPropagation?.(); if (onSelectSession) { onSelectSession(item.cascadeId); } else if (item.cascadeId && item.cascadeId !== 'current') { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); void selectConversation(item.cascadeId); } }; } if (showSessionExtras && refs.hereTagEl && refs.metricsEl) { const isHere = Boolean(hostRouteLower) && (String(item.cascadeId || '').toLowerCase() === hostRouteLower || (item.subagents || []).some( (s) => String(s?.cascadeId || '').toLowerCase() === hostRouteLower )); patchText(refs.hereTagEl, t('multi.hereTag')); patchAttr(refs.hereTagEl, 'hidden', !isHere); const metricParts = []; if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { metricParts.push( `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` ); } if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); } const metricsStr = metricParts.join(' · '); patchAttr(refs.metricsEl, 'hidden', !metricsStr); if (metricsStr) { patchText(refs.metricsEl, metricsStr); } } const subCount = Number(item.subagentCount || item.subagents?.length || 0); const swarmCount = Number( item.swarmCount ?? (item.subagents || []).filter((s) => s?.agentKind === 'swarm_worker').length ); const isPureSwarm = subCount > 0 && swarmCount === subCount; const runSubCount = Number(item.runningSubagentCount || 0); const isExpanded = resolveIsExpanded(item); patchText(refs.mainBadge, t('fmt.mainBadge')); patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); if (subCount > 0) { const toggleText = runSubCount > 0 ? t(isPureSwarm ? 'live.swarmToggleRunning' : 'live.subToggleRunning', { run: runSubCount, total: subCount, }) : t(isPureSwarm ? 'live.swarmToggleIdle' : 'live.subToggleIdle', { total: subCount, }); patchText(refs.subToggleLabel, toggleText); patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); if (interactive) { patchAttr( refs.subToggleBtn, 'title', isExpanded ? t('live.subCollapseTitle') : t('live.subExpandTitle') ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); 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'); const detailStr = formatLiveActivityDetail(act); const mainTimerKey = `main:${item.cascadeId}`; activeTimerKeys.add(mainTimerKey); bindLiveElapsedTimer( mainTimerKey, `${item.cascadeId}:${act.signature || mainLabel}`, act.startedAtMs, refs.elapsedEl ); patchText(refs.mainPhase, mainLabel); const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; patchAttr(refs.mainProgress, 'hidden', !progText); if (progText) { patchText(refs.mainProgress, progText); } patchAttr(refs.mainSep, 'hidden', !detailStr); patchAttr(refs.mainDetail, 'hidden', !detailStr); patchText(refs.mainDetail, detailStr); if (interactive && !showSessionExtras) { const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${mainLabel}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; patchAttr(refs.cardEl, 'title', fullTooltip); } const showSubs = subCount > 0 && isExpanded; if (!refs.isCollapsingSubs) { patchAttr(refs.subScroll.el, 'hidden', !showSubs); patchAttr(refs.subListEl, 'hidden', !showSubs); } if (showSubs) { const rawSubItems = item.subagents || []; const getSubSortRank = (s) => { if (s?.isRunning) return 0; if (s?.swarmState === 'waiting' || s?.liveActivity?.actionKey === 'swarm_waiting') { return 1; } return 2; }; const subItems = rawSubItems.length > 1 ? rawSubItems .slice() .sort( (a, b) => getSubSortRank(a) - getSubSortRank(b) || Number(a?.index || 0) - Number(b?.index || 0) ) : rawSubItems; patchKeyedList(refs.subListEl, subItems, { keyFn: (sub) => sub.cascadeId, sigFn: (sub) => `${locale}:${sub.cascadeId}:${sub.agentKind || ''}:${sub.swarmState || ''}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`, createRow: createLiveSubRow, updateRow: (subRefs, sub) => { const subAct = sub.liveActivity || { phase: sub.isRunning ? 'thinking' : 'done', actionKey: sub.isRunning ? 'thinking' : 'done', label: sub.isRunning ? t('live.thinking') : t('live.done'), detail: '', stepProgress: '', startedAtMs: sub.lastModifiedMs || 0, }; const isWaitingSub = !sub.isRunning && (sub.swarmState === 'waiting' || subAct.actionKey === 'swarm_waiting'); const isKilledSub = !sub.isRunning && (sub.swarmState === 'killed' || subAct.actionKey === 'swarm_killed'); patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning && !isWaitingSub, 'is-waiting-sub': isWaitingSub, 'is-killed-sub': isKilledSub, }); const badgeCls = getAgentBadgeClass(sub.index || 1, false); const subBadgeText = formatAgentBadgeText({ ...sub, isMain: false, index: sub.index || 1, }); patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); patchText(subRefs.subBadge, subBadgeText); const fallbackRole = sub.agentKind === 'side_question' || sub.isSideQuestion ? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}` : sub.agentKind === 'swarm_worker' ? `${t('fmt.swarmAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}` : `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`; const roleText = sub.customRole !== undefined ? sub.customRole || fallbackRole : sub.role || sub.shortLabel || fallbackRole; patchText(subRefs.subRole, roleText); const idleFallbackKey = isKilledSub ? 'live.killed' : isWaitingSub ? 'live.waiting' : 'live.done'; const subLabel = sub.isRunning ? formatLiveActivityLabel(subAct, 'live.running') : formatLiveActivityLabel(subAct, idleFallbackKey); const subDetail = formatLiveActivityDetail(subAct); const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; const summaryStr = showSessionExtras ? sub.isRunning ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}` : isKilledSub ? t('live.killedWithSteps', { steps: sub.stepCount || 0 }) : isWaitingSub ? t('live.waitingWithSteps', { steps: sub.stepCount || 0 }) : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) : [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' '); patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchText(subRefs.subSummary, summaryStr); if (interactive && !showSessionExtras) { patchAttr( subRefs.rowEl, 'title', `[${subBadgeText}] ${roleText}${summaryStr ? ` ${summaryStr}` : ''}` ); } if (sub.isRunning) { const subTimerKey = `sub:${sub.cascadeId}`; activeTimerKeys.add(subTimerKey); bindLiveElapsedTimer( subTimerKey, `${sub.cascadeId}:${subAct.signature || subLabel}`, subAct.startedAtMs || sub.lastModifiedMs, subRefs.subElapsed ); } else { activityTimersMap.delete(`sub:${sub.cascadeId}`); patchText( subRefs.subElapsed, t('header.convMetaSteps', { count: sub.stepCount || 0 }) ); } }, }); refs.subScroll.refresh(); } }, destroyRow: (refs) => { clearSubExpandAnim(refs); refs?.subScroll?.destroy?.(); }, }); for (const key of [...activityTimersMap.keys()]) { if (!activeTimerKeys.has(key)) { activityTimersMap.delete(key); } } updateLiveElapsedDisplay(); ensureLiveTicker(); } onCleanup(() => { stopLiveTicker(); patchKeyedList(liveActivityBar, [], { destroyRow: (refs) => { clearSubExpandAnim(refs); refs?.subScroll?.destroy?.(); }, }); }); return { el: liveActivityBar, refs: { update, pauseTicker, resumeTicker, stopLiveTicker, }, }; }, }); return { buildFallbackRunningConversations, LiveActivityWidget }; })(); // --- src/registries/widgetRegistry.js --- const { OVERVIEW_WIDGET_KEYS, OVERVIEW_WIDGET_REGISTRY, getOverviewModuleOptions, createDynamicWidgetHost } = (() => { /** * @fileoverview Decoupled Overview & Hover Widget Registry (`widgetRegistry.js`). * Maps module keys (`metrics`, `context`, `quotas`, `live_tasks`) to standalone * widget components and provides `createDynamicWidgetHost` for zero-hardcode mounting, * live reordering, and clean instance disposal. */ const OVERVIEW_WIDGET_KEYS = OVERVIEW_MODULE_KEYS; const OVERVIEW_WIDGET_REGISTRY = Object.freeze({ metrics: { key: 'metrics', labelKey: 'module.metrics', create: ({ mode, isVisibleFn, preview, getCtxAgentId }) => MetricMatrixWidget({ mode, isVisibleFn, preview, getCtxAgentId }), }, context: { key: 'context', labelKey: 'module.context', create: ({ mode, isVisibleFn, preview, getCtxAgentId, setCtxAgentId }) => ContextWindowWidget({ interactiveInspector: mode !== 'hover', isVisibleFn, preview, getCtxAgentId, setCtxAgentId, }), }, quotas: { key: 'quotas', labelKey: 'module.quotas', create: ({ mode }) => QuotaPoolsWidget({ compactHover: mode === 'hover', }), }, live_tasks: { key: 'live_tasks', labelKey: 'module.live_tasks', create: ({ mode, isVisibleFn, preview, getCtxAgentId }) => LiveActivityWidget({ interactive: mode !== 'hover', isVisibleFn, preview, getCtxAgentId, }), }, }); function getOverviewModuleOptions() { return OVERVIEW_WIDGET_KEYS.map((key) => ({ value: key, label: t(`module.${key}`), })); } /** * Create a dynamic container host that mounts, reorders, updates, and disposes * standalone telemetry widgets based on user-configured module keys. * * @param {{ * containerEl: HTMLElement, * mode?: 'overview' | 'hover', * isVisibleFn?: () => boolean, * initialModuleKeys?: string[] * }} options */ function createDynamicWidgetHost({ containerEl, mode = 'overview', preview = false, isVisibleFn = () => true, initialModuleKeys = [], getCtxAgentId: customGetCtxAgentId = undefined, setCtxAgentId: customSetCtxAgentId = undefined, }) { const instances = new Map(); let currentKeys = []; let previewCtxAgentId = 'main'; let latestUpdatePayload = null; const getCtxAgentId = typeof customGetCtxAgentId === 'function' ? customGetCtxAgentId : preview ? () => previewCtxAgentId : undefined; const setCtxAgentId = typeof customSetCtxAgentId === 'function' ? customSetCtxAgentId : preview ? (nextId) => { previewCtxAgentId = String(nextId || 'main'); if (latestUpdatePayload) { for (const key of currentKeys) { instances.get(key)?.refs?.update?.(latestUpdatePayload); } } } : undefined; function syncModules(nextKeys) { const validKeys = []; const seen = new Set(); for (const rawKey of Array.isArray(nextKeys) ? nextKeys : []) { const k = String(rawKey || '').trim(); if (!k || seen.has(k) || !OVERVIEW_WIDGET_REGISTRY[k]) continue; seen.add(k); validKeys.push(k); } // Remove and destroy widgets no longer present for (const [existingKey, inst] of [...instances.entries()]) { if (!seen.has(existingKey)) { try { inst.el?.remove?.(); } catch {} try { inst.destroy?.(); } catch {} instances.delete(existingKey); } } // Instantiate newly added widgets for (const key of validKeys) { if (!instances.has(key)) { const inst = OVERVIEW_WIDGET_REGISTRY[key].create({ mode, preview, isVisibleFn, getCtxAgentId, setCtxAgentId, }); instances.set(key, inst); } } // Reorder DOM nodes in containerEl only where needed const orderChanged = validKeys.length !== currentKeys.length || validKeys.some((k, idx) => currentKeys[idx] !== k) || (containerEl.children && containerEl.children.length !== validKeys.length); if (orderChanged) { for (let i = 0; i < validKeys.length; i += 1) { const targetEl = instances.get(validKeys[i]).el; const curChild = containerEl.children ? containerEl.children[i] : null; if (curChild !== targetEl) { if (curChild && typeof containerEl.insertBefore === 'function') { containerEl.insertBefore(targetEl, curChild); } else { containerEl.appendChild(targetEl); } } } currentKeys = [...validKeys]; } return validKeys; } function update({ moduleKeys = [], data = null, minuteTick = undefined } = {}) { latestUpdatePayload = { data, minuteTick }; const validKeys = syncModules(moduleKeys); for (const key of validKeys) { const inst = instances.get(key); inst?.refs?.update?.({ data, minuteTick }); } } function pauseTickers() { for (const inst of instances.values()) { inst?.refs?.pauseTicker?.(); } } function resumeTickers() { for (const inst of instances.values()) { inst?.refs?.resumeTicker?.(); } } function getInstance(key) { return instances.get(key) || null; } function destroy() { for (const inst of instances.values()) { try { inst.el?.remove?.(); } catch {} try { inst.destroy?.(); } catch {} } instances.clear(); currentKeys = []; } if (Array.isArray(initialModuleKeys) && initialModuleKeys.length > 0) { syncModules(initialModuleKeys); } return { update, pauseTickers, resumeTickers, getInstance, getActiveKeys: () => [...currentKeys], destroy, }; } return { OVERVIEW_WIDGET_KEYS, OVERVIEW_WIDGET_REGISTRY, getOverviewModuleOptions, createDynamicWidgetHost }; })(); // --- src/registries/stepColumnRegistry.js --- const { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, resolveStepTokenParts, formatCustomTokenComboHeader, isCompactionStepItem, STEP_COLUMN_REGISTRY, getStepColumnOptions, sortStepsByColumn } = (() => { /** * @fileoverview Decoupled Step Table Column Registry (`stepColumnRegistry.js`). * Defines all 12 customizable columns for `StepsDetailView` ("按步查看"), * preserving 100% of the 7 out-of-the-box default columns, clickable agent filter badges, * speed reason sub-lines, token combo tooltips, and high-cost highlights. */ const STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS; const DEFAULT_STEP_COLUMN_KEYS = DEFAULT_STEP_TABLE_COLUMNS; const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT; const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat; const parseClientStepTokenComboSegments = parseStepTokenComboSegments; function resolveStepTokenParts(st) { const inTok = Math.max(0, Number(st?.inputTokens || 0)); const cacheTok = Math.max(0, Number(st?.cacheReadTokens || 0)); const outTok = Math.max(0, Number(st?.outputTokens || 0)); const thinkTok = Math.max(0, Number(st?.thinkingTokens || 0)); const respTok = st?.responseTokens != null ? Math.max(0, Number(st.responseTokens)) : Math.max(0, outTok - thinkTok); const totalTok = inTok + cacheTok + outTok; const ctxTok = Math.max(0, Number(st?.contextTokens ?? totalTok)); return { inTok, cacheTok, outTok, thinkTok, respTok, totalTok, ctxTok }; } function finiteSortNum(val, { allowZero = true } = {}) { if (val == null || val === '') return null; const num = Number(val); if (!Number.isFinite(num)) return null; if (!allowZero && !(num > 0)) return null; return num; } function formatPartWithOptionalCost(tokCount, costVal) { const countStr = Math.round(Number(tokCount || 0)).toLocaleString(); if (costVal != null && Number.isFinite(Number(costVal))) { return `${countStr} (${formatUsd(Number(costVal), { precise: true })})`; } return countStr; } function formatCustomTokenComboHeader(rawFormat) { const segs = parseClientStepTokenComboSegments(rawFormat); return segs.map((seg) => t(`steps.tokSeg.${seg}.th`)).join(' / '); } function resolveSegmentDisplay(seg, parts, st) { switch (seg) { case 'context': return { short: formatTokens(parts.ctxTok), tip: `${t('steps.tokSeg.context.tip')} ${Math.round(parts.ctxTok).toLocaleString()}`, }; case 'in': return { short: formatTokens(parts.inTok), tip: `${t('steps.tokSeg.in.tip')} ${formatPartWithOptionalCost(parts.inTok, st?.inCostUsd)}`, }; case 'out': return { short: formatTokens(parts.outTok), tip: `${t('steps.tokSeg.out.tip')} ${formatPartWithOptionalCost(parts.outTok, st?.outCostUsd)}`, }; case 'cache': return { short: formatTokens(parts.cacheTok), tip: `${t('steps.tokSeg.cache.tip')} ${formatPartWithOptionalCost(parts.cacheTok, st?.cacheCostUsd)}`, }; case 'think': return { short: formatTokens(parts.thinkTok), tip: `${t('steps.tokSeg.think.tip')} ${Math.round(parts.thinkTok).toLocaleString()}`, }; case 'reply': return { short: formatTokens(parts.respTok), tip: `${t('steps.tokSeg.reply.tip')} ${Math.round(parts.respTok).toLocaleString()}`, }; case 'total': default: return { short: formatTokens(parts.totalTok), tip: `${t('steps.tokSeg.total.tip')} ${formatPartWithOptionalCost(parts.totalTok, st?.costUsd)}`, }; } } function formatStepClockTime(createdAtMs) { const ms = Number(createdAtMs || 0); if (!(ms > 0) || !Number.isFinite(ms)) { return { text: '—', title: '' }; } const d = new Date(ms); const pad = (n) => String(n).padStart(2, '0'); const hhmmss = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; const full = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hhmmss}`; return { text: hhmmss, title: full }; } function isCompactionStepItem(st) { if (!st || typeof st !== 'object') return false; if (st.isCompactionStep) return true; const raw = `${st.activeModelShort ?? st.modelShort ?? ''} ${st.activeModelLabel ?? st.modelLabel ?? ''} ${st.activeModelUpstream ?? st.modelUpstream ?? ''}`; return /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(raw); } const STEP_COLUMN_REGISTRY = Object.freeze({ step: { key: 'step', thLabel: () => t('stepCol.step.th'), optLabel: () => t('stepCol.step.opt'), sigPart: (st) => `${st.stepIndex}`, sortValue: (st) => finiteSortNum(st?.stepIndex), createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { patchText(refs.valEl, `#${Number(st.stepIndex)}`); }, }, time: { key: 'time', thLabel: () => t('stepCol.time.th'), optLabel: () => t('stepCol.time.opt'), sigPart: (st) => `${st.createdAtMs || 0}`, sortValue: (st) => finiteSortNum(st?.createdAtMs, { allowZero: false }), createCell: () => { const valEl = h('span'); const td = h('td', { className: 'text-muted' }, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const { text, title } = formatStepClockTime(st.createdAtMs); patchText(refs.valEl, text); patchAttr(refs.td, 'title', title || null); }, }, model: { key: 'model', thLabel: () => t('stepCol.model.th'), optLabel: () => t('stepCol.model.opt'), defaultSortDir: 'asc', sigPart: (st, ctx) => { const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); return `${disp.baseText}:${disp.title}`; }, sortValue: (st, ctx) => { const disp = resolveModelDisplayInfo(st, ctx?.displaySettings, { fallback: '' }); return String(disp.baseText || '').toLowerCase() || null; }, createCell: () => { const nameEl = h('span', { className: 'step-model-name' }); const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl]); const td = h('td', {}, [wrapEl]); return { td, refs: { td, wrapEl, nameEl } }; }, updateCell: (refs, st, ctx) => { const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); patchText(refs.nameEl, modelDisplay.baseText); patchAttr(refs.td, 'title', modelDisplay.title); }, }, tps: { key: 'tps', thLabel: () => t('stepCol.tps.th'), optLabel: () => t('stepCol.tps.opt'), sigPart: (st, ctx) => `${st.tokPerSec}:${st.selectedSpeedReason || ''}:${ctx?.showStepSpeedColor === true ? 1 : 0}`, sortValue: (st) => finiteSortNum(st?.tokPerSec, { allowZero: false }), createCell: () => { const speedMain = h('strong', { className: 'cell-value tone-muted', style: 'font-size: var(--fs-base-sm);', }); const wrapEl = h( 'span', { style: 'display: inline-block; vertical-align: middle;' }, [speedMain] ); const td = h('td', {}, [wrapEl]); return { td, refs: { wrapEl, speedMain, speedReason: null } }; }, updateCell: (refs, st, ctx) => { patchText(refs.speedMain, formatSpeedMetric(st.tokPerSec, ' tok/s')); const hasValidSpeed = st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0; const toneCls = ctx?.showStepSpeedColor === true ? getSpeedToneClass(st.tokPerSec) : hasValidSpeed ? '' : 'tone-muted'; patchAttr(refs.speedMain, 'class', toneCls ? `cell-value ${toneCls}` : 'cell-value'); const reason = speedReasonText(st.selectedSpeedReason); if (reason && !refs.speedReason) { refs.speedReason = h('div', { className: 'text-muted', style: 'font-size: var(--fs-xs);', }); refs.wrapEl.appendChild(refs.speedReason); } if (refs.speedReason) { patchText(refs.speedReason, reason); patchAttr(refs.speedReason, 'hidden', !reason); } }, }, ttft: { key: 'ttft', thLabel: () => t('stepCol.ttft.th'), optLabel: () => t('stepCol.ttft.opt'), sigPart: (st) => `${st.ttftSec ?? ''}:${st.totalDurationSec ?? ''}:${st.nativeStreamSec ?? ''}:${st.thinkingDurationSec ?? ''}:${st.hasToolCalls ? 1 : 0}`, sortValue: (st) => finiteSortNum(st?.ttftSec), createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { patchText(refs.valEl, formatMetric(st.ttftSec, 's')); const tone = getTtftToneClass(st.ttftSec); patchAttr(refs.valEl, 'class', tone || null); }, }, duration: { key: 'duration', thLabel: () => t('stepCol.duration.th'), optLabel: () => t('stepCol.duration.opt'), sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}:${st.ttftSec ?? ''}:${st.nativeStreamSec ?? ''}:${st.thinkingDurationSec ?? ''}:${st.hasToolCalls ? 1 : 0}`, sortValue: (st) => finiteSortNum(st?.totalDurationSec ?? st?.streamDurationSec), createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const dur = st.totalDurationSec ?? st.streamDurationSec ?? null; patchText(refs.valEl, formatMetric(dur, 's')); }, }, tokens_combo: { key: 'tokens_combo', thLabel: () => t('stepCol.tokens_combo.th'), optLabel: () => t('stepCol.tokens_combo.opt'), sigPart: (st) => `${st.contextTokens}:${st.outputTokens}:${st.thinkingTokens}:${st.responseTokens}`, sortValue: (st) => resolveStepTokenParts(st).ctxTok, createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const parts = resolveStepTokenParts(st); patchText( refs.valEl, `${formatTokens(parts.ctxTok)} / ${formatTokens(parts.thinkTok)} / ${formatTokens(parts.respTok)}` ); patchAttr( refs.td, 'title', t('steps.ctxTitle', { ctx: Math.round(parts.ctxTok), think: Math.round(parts.thinkTok), resp: Math.round(parts.respTok), }) ); }, }, tokens_io_cache: { key: 'tokens_io_cache', thLabel: () => t('stepCol.tokens_io_cache.th'), optLabel: () => t('stepCol.tokens_io_cache.opt'), sigPart: (st) => `${st.inputTokens || 0}:${st.outputTokens || 0}:${st.cacheReadTokens || 0}:${st.inCostUsd ?? ''}:${st.outCostUsd ?? ''}:${st.cacheCostUsd ?? ''}`, sortValue: (st) => resolveStepTokenParts(st).totalTok, createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const parts = resolveStepTokenParts(st); patchText( refs.valEl, `${formatTokens(parts.inTok)} / ${formatTokens(parts.outTok)} / ${formatTokens(parts.cacheTok)}` ); patchAttr( refs.td, 'title', t('steps.ioCacheTitle', { inPart: formatPartWithOptionalCost(parts.inTok, st?.inCostUsd), outPart: formatPartWithOptionalCost(parts.outTok, st?.outCostUsd), cachePart: formatPartWithOptionalCost(parts.cacheTok, st?.cacheCostUsd), }) ); }, }, tokens_custom: { key: 'tokens_custom', thLabel: (ctx) => formatCustomTokenComboHeader(ctx?.stepTokenComboFormat), optLabel: (ctx) => t('stepCol.tokens_custom.opt', { fmt: formatCustomTokenComboHeader(ctx?.stepTokenComboFormat), }), sigPart: (st, ctx) => `${normalizeClientStepTokenComboFormat(ctx?.stepTokenComboFormat)}:${st.contextTokens || 0}:${st.inputTokens || 0}:${st.cacheReadTokens || 0}:${st.outputTokens || 0}:${st.thinkingTokens || 0}:${st.responseTokens ?? ''}:${st.costUsd ?? ''}`, sortValue: (st, ctx) => { const firstSeg = parseClientStepTokenComboSegments(ctx?.stepTokenComboFormat)[0] || 'total'; const parts = resolveStepTokenParts(st); switch (firstSeg) { case 'context': return parts.ctxTok; case 'in': return parts.inTok; case 'out': return parts.outTok; case 'cache': return parts.cacheTok; case 'think': return parts.thinkTok; case 'reply': return parts.respTok; default: return parts.totalTok; } }, createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st, ctx) => { const segs = parseClientStepTokenComboSegments(ctx?.stepTokenComboFormat); const parts = resolveStepTokenParts(st); const rendered = segs.map((seg) => resolveSegmentDisplay(seg, parts, st)); patchText( refs.valEl, rendered.map((r) => r.short).join(' / ') ); patchAttr( refs.td, 'title', rendered.map((r) => r.tip).join(' · ') ); }, }, input_tokens: { key: 'input_tokens', thLabel: () => t('stepCol.input_tokens.th'), optLabel: () => t('stepCol.input_tokens.opt'), sigPart: (st) => `${st.inputTokens || 0}`, sortValue: (st) => finiteSortNum(st?.inputTokens ?? 0), createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { patchText(refs.valEl, formatTokens(st.inputTokens || 0)); }, }, cache_tokens: { key: 'cache_tokens', thLabel: () => t('stepCol.cache_tokens.th'), optLabel: () => t('stepCol.cache_tokens.opt'), sigPart: (st) => `${st.cacheReadTokens || 0}`, sortValue: (st) => finiteSortNum(st?.cacheReadTokens ?? 0), createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { patchText(refs.valEl, formatTokens(st.cacheReadTokens || 0)); }, }, output_tokens: { key: 'output_tokens', thLabel: () => t('stepCol.output_tokens.th'), optLabel: () => t('stepCol.output_tokens.opt'), sigPart: (st) => `${st.outputTokens || 0}`, sortValue: (st) => finiteSortNum(st?.outputTokens ?? 0), createCell: () => { const valEl = h('span'); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { patchText(refs.valEl, formatTokens(st.outputTokens || 0)); }, }, cache: { key: 'cache', thLabel: () => t('stepCol.cache.th'), optLabel: () => t('stepCol.cache.opt'), sigPart: (st) => `${st.cacheHitPct ?? 0}:${(st.inputTokens || 0) + (st.cacheReadTokens || 0) > 0 ? 1 : 0}`, sortValue: (st) => { const prompt = Number(st?.inputTokens || 0) + Number(st?.cacheReadTokens || 0); return prompt > 0 ? finiteSortNum(st?.cacheHitPct ?? 0) : null; }, createCell: () => { const valEl = h('span', { className: 'cell-value tone-muted', style: 'font-size: var(--fs-base-sm);', }); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const promptTokens = Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0); patchText(refs.valEl, formatCachePct(st.cacheHitPct ?? 0)); patchAttr( refs.valEl, 'class', `cell-value ${getCacheToneClass(st.cacheHitPct ?? 0, promptTokens)}` ); }, }, cost: { key: 'cost', thLabel: () => t('stepCol.cost.th'), optLabel: () => t('stepCol.cost.opt'), sigPart: (st) => `${st.costUsd}`, sortValue: (st) => finiteSortNum(st?.costUsd), createCell: () => { const valEl = h('span', { style: 'font-weight: 600;' }); const td = h('td', {}, [valEl]); return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const costVal = st.costUsd; patchText(refs.valEl, formatUsd(costVal, { precise: true })); const tone = getStepCostToneClass(costVal); patchAttr(refs.valEl, 'class', tone || null); }, }, }); function getStepColumnOptions( stepTokenComboFormat = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT ) { const ctx = { stepTokenComboFormat }; return STEP_COLUMN_KEYS.map((key) => ({ value: key, label: STEP_COLUMN_REGISTRY[key].optLabel(ctx), })); } /** * 按指定列对步骤数组进行稳定排序(空值/不可用测速值始终置底)。 * * @param {Array} steps * @param {string} sortKey * @param {'asc'|'desc'|''} sortDir * @param {object} [ctx] * @returns {Array} */ function sortStepsByColumn(steps, sortKey, sortDir, ctx = {}) { if (!Array.isArray(steps) || steps.length <= 1 || !sortKey || !sortDir) { return Array.isArray(steps) ? steps : []; } const col = STEP_COLUMN_REGISTRY[sortKey]; if (!col || typeof col.sortValue !== 'function') return steps; const mul = sortDir === 'asc' ? 1 : -1; const decorated = steps.map((st, origIdx) => ({ st, origIdx, val: col.sortValue(st, ctx), })); decorated.sort((a, b) => { const aNull = a.val === null || a.val === undefined; const bNull = b.val === null || b.val === undefined; if (aNull && bNull) return a.origIdx - b.origIdx; if (aNull) return 1; if (bNull) return -1; let cmp = 0; if (typeof a.val === 'string' || typeof b.val === 'string') { cmp = String(a.val).localeCompare(String(b.val)); } else { cmp = Number(a.val) - Number(b.val); } if (cmp !== 0) return cmp * mul; return a.origIdx - b.origIdx; }); return decorated.map((d) => d.st); } return { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, resolveStepTokenParts, formatCustomTokenComboHeader, isCompactionStepItem, STEP_COLUMN_REGISTRY, getStepColumnOptions, sortStepsByColumn }; })(); // --- src/components/widgets/CapsuleBarWidget.js --- const { RING_RADIUS, RING_CIRCUMFERENCE, tokenizeCapsuleOdometerText, patchCapsuleOdometerText, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget } = (() => { /** * @fileoverview Shared Decoupled Capsule Bar Primitives & Widget (`CapsuleBarWidget.js`). * Powers both the live host window capsule (`WindowOverlayShell.js`) and the * real-UI structure preview (`SettingsStructureTab.js`), ensuring 100% DOM/CSS parity. */ const RING_RADIUS = 5.2; const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); const ODOMETER_DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const capsuleOdometerState = new WeakMap(); /** * 将胶囊指标文本拆分为「按数位对齐的数字滚轮 + 静态字符片段」: * - 整数部分从右向左按位次键控(个位 `i:0`、十位 `i:1`...),小数部分从左向右键控(`f:0`...); * - 位数增减时既有数位节点原地复用,仅发生变化的数字位执行 0.15s 老虎机垂直滚动,未变位与单位纹丝不动。 * * @param {string} rawText * @returns {Array<{ key: string, kind: 'digit' | 'static', digit?: number, text?: string }>} */ function tokenizeCapsuleOdometerText(rawText) { const str = String(rawText ?? ''); if (!str) return []; const parts = str.split(/(\d+(?:\.\d+)?)/g); const tokens = []; let numIdx = 0; let staticIdx = 0; for (let p = 0; p < parts.length; p += 1) { const seg = parts[p]; if (!seg) continue; if (/^\d+(?:\.\d+)?$/.test(seg)) { const dotPos = seg.indexOf('.'); const intPart = dotPos >= 0 ? seg.slice(0, dotPos) : seg; const fracPart = dotPos >= 0 ? seg.slice(dotPos + 1) : ''; const intLen = intPart.length; for (let i = 0; i < intLen; i += 1) { const place = intLen - 1 - i; tokens.push({ key: `n:${numIdx}:i:${place}`, kind: 'digit', digit: Number(intPart[i]), }); } if (dotPos >= 0) { tokens.push({ key: `n:${numIdx}:dot`, kind: 'static', text: '.' }); for (let j = 0; j < fracPart.length; j += 1) { tokens.push({ key: `n:${numIdx}:f:${j}`, kind: 'digit', digit: Number(fracPart[j]), }); } } numIdx += 1; } else { tokens.push({ key: `s:${staticIdx}`, kind: 'static', text: seg }); staticIdx += 1; } } return tokens; } function createOdometerDigitReel(initialDigit) { const cells = ODOMETER_DIGITS.map((d) => h('span', { className: 'wm-od-cell', text: d })); const trackEl = h('span', { className: 'wm-od-track' }, cells); patchStyleVar(trackEl, '--od-val', String(initialDigit)); const digitEl = h('span', { className: 'wm-od-digit', 'aria-hidden': 'true' }, [trackEl]); return { el: digitEl, trackEl, kind: 'digit', digit: initialDigit }; } /** * 在实验性新 UI (`[data-modern-ui="true"]`) 下将胶囊数字渲染为 0.15s 老虎机垂直滚轮; * 经典 UI 或无数字占位文本(如 `-- t/s`)严格退回原生纯文本 `patchText`,零多余 DOM 与动画。 */ function patchCapsuleOdometerText( el, nextValue, { resetKey = '', modernUi = undefined } = {} ) { if (!el) return false; const nextStr = String(nextValue ?? ''); const isModern = typeof modernUi === 'boolean' ? modernUi : isModernUiActiveForElement(el); const prev = capsuleOdometerState.get(el); if (!isModern || !/\d/.test(nextStr)) { if (prev?.active) { el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); patchAttr(el, 'data-od-active', null); patchAttr(el, 'data-od-value', null); patchAttr(el, 'aria-label', null); } const changed = patchText(el, nextStr); capsuleOdometerState.set(el, { active: false, text: nextStr, resetKey, nodes: null }); return changed; } if (prev?.active && prev.text === nextStr && prev.resetKey === resetKey) { return false; } let nodes; if (!prev?.active || prev.resetKey !== resetKey || !(prev.nodes instanceof Map)) { el.textContent = ''; while (el.firstChild) el.removeChild(el.firstChild); nodes = new Map(); } else { nodes = prev.nodes; } const tokens = tokenizeCapsuleOdometerText(nextStr); const nextKeys = new Set(); const orderedEls = []; for (let i = 0; i < tokens.length; i += 1) { const tok = tokens[i]; nextKeys.add(tok.key); let rec = nodes.get(tok.key); if (!rec || rec.kind !== tok.kind) { if (rec?.el?.parentNode === el) { el.removeChild(rec.el); } if (tok.kind === 'digit') { rec = createOdometerDigitReel(tok.digit); } else { rec = { el: h('span', { className: 'wm-od-static', 'aria-hidden': 'true', text: tok.text }), trackEl: null, kind: 'static', text: tok.text, }; } nodes.set(tok.key, rec); } else if (tok.kind === 'digit') { if (rec.digit !== tok.digit) { patchStyleVar(rec.trackEl, '--od-val', String(tok.digit)); rec.digit = tok.digit; } } else if (rec.text !== tok.text) { patchText(rec.el, tok.text); rec.text = tok.text; } orderedEls.push(rec.el); } for (const [oldKey, rec] of nodes.entries()) { if (!nextKeys.has(oldKey)) { if (rec.el?.parentNode === el) { el.removeChild(rec.el); } nodes.delete(oldKey); } } for (let i = 0; i < orderedEls.length; i += 1) { const targetNode = orderedEls[i]; const currentNode = el.children[i] || null; if (currentNode !== targetNode) { el.insertBefore(targetNode, currentNode); } } patchAttr(el, 'data-od-active', '1'); patchAttr(el, 'data-od-value', nextStr); patchAttr(el, 'aria-label', nextStr); capsuleOdometerState.set(el, { active: true, text: nextStr, resetKey, nodes }); return true; } function isValidTtftSec(val) { return val != null && Number.isFinite(Number(val)) && Number(val) >= 0; } function findFallbackRecentStepTtft(steps) { if (!Array.isArray(steps) || steps.length === 0) return null; const firstIdx = Number(steps[0]?.stepIndex ?? 0); const lastIdx = Number(steps[steps.length - 1]?.stepIndex ?? 0); if (firstIdx >= lastIdx) { for (let i = 0; i < steps.length; i += 1) { const candidate = steps[i]?.ttftSec; if (isValidTtftSec(candidate)) return Number(candidate); } return null; } for (let i = steps.length - 1; i >= 0; i -= 1) { const candidate = steps[i]?.ttftSec; if (isValidTtftSec(candidate)) return Number(candidate); } return null; } /** * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. */ function buildCapsuleSlotContext( data, { scopedConv = null, overviewConv = null, ctxAgent = null, aggregated = null } = {} ) { if (!data) return { hasTelemetry: false }; const activeConv = data.activeConversation || {}; const overviewActive = overviewConv || scopedConv || aggregated || activeConv; const capActive = scopedConv || aggregated || activeConv || {}; const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); const totalTokens = Number(ctx.totalTokens || 0); const usedPct = limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; const dashOffset = +( RING_CIRCUMFERENCE * (1 - Math.max(0, Math.min(100, usedPct)) / 100) ).toFixed(2); const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); const convId = String(capActive.cascadeId || activeConv.cascadeId || '') .trim() .toLowerCase(); const scopeId = String(scopedConv?.agentId || aggregated?.agentId || 'main'); const conversationKey = convId ? `${convId}::${scopeId}` : ''; const stepCount = Math.max(0, Number(capActive.stepCount ?? activeConv.stepCount ?? 0)); const rawTtft = scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null; const fallbackTtft = isValidTtftSec(rawTtft) ? Number(rawTtft) : scopedConv?.lastKnownTtftSec ?? findFallbackRecentStepTtft(scopedConv?.recentSteps) ?? aggregated?.lastKnownTtftSec ?? activeConv.lastKnownTtftSec ?? findFallbackRecentStepTtft(activeConv.recentSteps); const resolvedTtft = isValidTtftSec(fallbackTtft) ? Number(fallbackTtft) : null; const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); const sessionTokens = stepCount > 0 || capActive.totalTokens != null || capInTok + capCacheTok + capOutTok > 0 ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) : null; return { hasTelemetry: true, conversationKey, stepCount, usedPct, dashOffset, isRunning, tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null, avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null, ttft: resolvedTtft, stepCost: scopedConv?.latestStepCostUsd ?? aggregated?.latestStepCostUsd ?? activeConv.latestStepCostUsd ?? null, sessionCost: scopedConv?.sessionCostUsd ?? aggregated?.sessionCostUsd ?? activeConv.sessionCostUsd ?? null, cacheHitPct: Number(capActive.stepCount || 0) > 0 ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null : null, latestPromptTokens: capActive.latestPromptTokens ?? null, sessionTokens, quotas: data.quotas, }; } /** * Compute multi-session button state & normalized running conversation list. */ function resolveMultiSessionCapsuleState( data, { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} ) { const rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated, latestTokPerSec, contextUsedPct, }); const runningCount = rawRunningList.length; const runningSubCount = rawRunningList.reduce( (acc, item) => acc + Number(item.runningSubagentCount || 0), 0 ); const runningSwarmCount = rawRunningList.reduce( (acc, item) => acc + Number(item.runningSwarmCount || 0), 0 ); const isPureSwarmSubs = runningSubCount > 0 && runningSwarmCount === runningSubCount; const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); const multiBtnText = runningCount > 0 ? runningSubCount > 0 ? t(isPureSwarmSubs ? 'capsule.multiRunningWithSwarm' : 'capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount, }) : t('capsule.multiRunning', { count: runningCount }) : t('capsule.multiZero'); return { rawRunningList, runningCount, runningSubCount, runningSwarmCount, hasWaiting, multiBtnText, }; } /** * Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring. */ function createCapsuleSlotNode(slotIndex, initialMetric) { const ringSvg = document.createElementNS(SVG_NS, 'svg'); ringSvg.setAttribute('viewBox', '0 0 14 14'); ringSvg.setAttribute('class', 'wm-ring-svg'); ringSvg.setAttribute('aria-hidden', 'true'); const ringTrack = document.createElementNS(SVG_NS, 'circle'); ringTrack.setAttribute('cx', '7'); ringTrack.setAttribute('cy', '7'); ringTrack.setAttribute('r', String(RING_RADIUS)); ringTrack.setAttribute('class', 'wm-ring-track'); const ringFill = document.createElementNS(SVG_NS, 'circle'); ringFill.setAttribute('cx', '7'); ringFill.setAttribute('cy', '7'); ringFill.setAttribute('r', String(RING_RADIUS)); ringFill.setAttribute('class', 'wm-ring-fill'); ringFill.setAttribute('stroke-dasharray', String(RING_CIRCUMFERENCE)); ringFill.setAttribute('stroke-dashoffset', String(RING_CIRCUMFERENCE)); ringSvg.appendChild(ringTrack); ringSvg.appendChild(ringFill); const isNone = initialMetric === 'none'; const isCtx = initialMetric === 'context'; const prefixSpan = h('span', { className: 'wm-slot-prefix' }); const textSpan = h('span', { className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text', text: isNone ? '' : isCtx ? '--%' : initialMetric === 'tps' ? '-- t/s' : initialMetric === 'ttft' ? '--s' : '--%', }); const el = h( 'span', { className: isNone ? 'wm-cap-slot' : isCtx ? 'wm-cap-slot wm-ctx-seg' : initialMetric === 'tps' ? 'wm-cap-slot wm-seg-speed' : initialMetric === 'ttft' ? 'wm-cap-slot wm-seg-metric' : 'wm-cap-slot wm-seg-quota', hidden: isNone, 'data-slot-idx': String(slotIndex), 'data-metric': initialMetric, 'data-vis-rank': isNone ? '' : String(slotIndex + 1), }, isCtx ? [ringSvg, textSpan] : [textSpan] ); return { el, ringSvg, ringFill, prefixSpan, textSpan, ringMounted: isCtx, prefixMounted: false, heldTtft: null, }; } /** * Patch 5 pre-allocated capsule slots and 4 separators in-place via `metricRegistry`. */ function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx) { let visRank = 0; const visRanks = [0, 0, 0, 0, 0]; for (let i = 0; i < capsuleSlots.length; i += 1) { const slot = capsuleSlots[i]; const metricKey = i < slotKeys.length ? slotKeys[i] : 'none'; if (!slotCtx?.hasTelemetry || metricKey !== 'ttft') { slot.heldTtft = null; } let pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE); if (metricKey === 'ttft' && slotCtx?.hasTelemetry) { const convKey = String(slotCtx.conversationKey || ''); if (isValidTtftSec(slotCtx.ttft)) { slot.heldTtft = convKey ? { conversationKey: convKey, pres } : null; } else if ( convKey && slot.heldTtft && slot.heldTtft.conversationKey === convKey && (slotCtx.isRunning || Number(slotCtx.stepCount) > 0) ) { pres = { ...slot.heldTtft.pres, running: Boolean(slotCtx.isRunning) }; } else { slot.heldTtft = null; } } if (pres.hidden) { patchAttr(slot.el, 'hidden', true); patchAttr(slot.el, 'data-metric', 'none'); patchAttr(slot.el, 'data-vis-rank', ''); continue; } visRank += 1; visRanks[i] = visRank; patchAttr(slot.el, 'hidden', false); patchAttr(slot.el, 'data-metric', pres.metric); patchAttr(slot.el, 'data-vis-rank', String(visRank)); if (pres.showRing && !slot.ringMounted) { slot.el.insertBefore(slot.ringSvg, slot.el.firstChild || slot.textSpan); slot.ringMounted = true; } else if (!pres.showRing && slot.ringMounted) { slot.ringSvg.remove(); slot.ringMounted = false; } const prefixText = String(pres.prefix || ''); if (prefixText) { patchText(slot.prefixSpan, prefixText); if (!slot.prefixMounted) { slot.el.insertBefore(slot.prefixSpan, slot.textSpan); slot.prefixMounted = true; } } else if (slot.prefixMounted) { slot.prefixSpan.remove(); slot.prefixMounted = false; } const toneCls = pres.toneClass || (pres.danger ? 'tone-danger' : pres.warn ? 'tone-warn' : ''); const fullSegClass = `${pres.segClass}${pres.running ? ' state-running' : ''}${toneCls ? ` ${toneCls}` : ''}`; patchAttr(slot.el, 'class', fullSegClass); const fullTextClass = `${pres.textClass}${toneCls ? ` ${toneCls}` : ''}`; patchAttr(slot.textSpan, 'class', fullTextClass); patchCapsuleOdometerText(slot.textSpan, pres.text, { resetKey: pres.metric }); if (pres.showRing) { slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset)); patchClasses(slot.ringFill, { 'is-quota': pres.ringKind === 'quota', 'is-empty': pres.ringEmpty === true, 'tone-warn': pres.warn, 'tone-danger': pres.danger, }); } } for (let s = 0; s < capsuleSeps.length; s += 1) { const sepEl = capsuleSeps[s]; const nextRank = visRanks[s + 1] || 0; const showSep = nextRank >= 2; patchAttr(sepEl, 'hidden', !showSep); patchAttr(sepEl, 'data-sep-for-rank', showSep ? String(nextRank) : ''); } } /** * Standalone Capsule Bar Preview Widget mounting the real `.wm-multi-btn` and `.wm-capsule-btn` * inside a contextual host bar (`dual` titlebar, `composer` toolbar, or `sidebar` disabled state). */ const CapsuleBarWidget = defineComponent({ name: 'CapsuleBarWidget', setup() { const multiDot = h('span', { className: 'wm-multi-dot' }); const multiLabel = h('span', { className: 'wm-multi-label', text: t('capsule.multiZero'), }); const multiBtn = h( 'button', { type: 'button', className: 'wm-multi-btn', tabindex: '-1', 'aria-hidden': 'true', }, [multiDot, multiLabel] ); const capsuleSlots = [ createCapsuleSlotNode(0, 'tps'), createCapsuleSlotNode(1, 'ttft'), createCapsuleSlotNode(2, 'context'), createCapsuleSlotNode(3, 'none'), createCapsuleSlotNode(4, 'none'), ]; const capsuleSeps = [ h('span', { className: 'wm-sep wm-sep-speed', 'data-sep-for-rank': '2' }), h('span', { className: 'wm-sep wm-sep-quota', 'data-sep-for-rank': '3' }), h('span', { className: 'wm-sep', 'data-sep-for-rank': '', hidden: true }), h('span', { className: 'wm-sep', 'data-sep-for-rank': '', hidden: true }), ]; const capsuleBtn = h( 'button', { type: 'button', className: 'wm-capsule-btn', tabindex: '-1', 'aria-hidden': 'true', }, [ capsuleSlots[0].el, capsuleSeps[0], capsuleSlots[1].el, capsuleSeps[1], capsuleSlots[2].el, capsuleSeps[2], capsuleSlots[3].el, capsuleSeps[3], capsuleSlots[4].el, ] ); const capsuleCluster = h('div', { className: 'preview-capsule-cluster' }, [ multiBtn, capsuleBtn, ]); // Contextual host chrome affordances for Titlebar vs Composer vs Sidebar-only const titlebarLeftMock = h('div', { className: 'preview-host-left is-titlebar' }, [ h('span', { className: 'preview-win-title', text: 'Antigravity' }), ]); const composerLeftMock = h( 'div', { className: 'preview-host-left is-composer', hidden: true }, [ h('span', { className: 'preview-composer-chip' }, [ h('span', { text: 'Carbon (High)' }), createSvgIcon('chevron-down', { size: 10 }), ]), ] ); const composerSendMock = h( 'span', { className: 'preview-composer-send', 'aria-hidden': 'true', hidden: true }, [createSvgIcon('arrow-up', { size: 11 })] ); const hostBarEl = h( 'div', { className: 'preview-capsule-bar', 'data-mount-mode': 'dual' }, [titlebarLeftMock, composerLeftMock, capsuleCluster, composerSendMock] ); const sidebarHintEl = h('div', { className: 'preview-sidebar-note', hidden: true, text: t('settings.str.previewMountSidebarHint'), }); const rootEl = h('div', { className: 'capsule-preview-widget' }, [hostBarEl, sidebarHintEl]); function update({ data } = {}) { const settings = data?.settings || {}; const mountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay ); const showMulti = settings.showTopbarMultiSession !== false; const slotKeys = normalizeClientTopbarSlots(settings.topbarCapsuleSlots); const isComposer = mountMode === 'composer'; const isSidebar = mountMode === 'sidebar'; patchAttr(hostBarEl, 'data-mount-mode', mountMode); patchClasses(hostBarEl, { 'is-composer': isComposer, 'is-sidebar-only': isSidebar, }); patchAttr(titlebarLeftMock, 'hidden', isComposer); patchAttr(composerLeftMock, 'hidden', !isComposer); patchAttr(composerSendMock, 'hidden', !isComposer); patchAttr(sidebarHintEl, 'hidden', !isSidebar); patchText(sidebarHintEl, t('settings.str.previewMountSidebarHint')); patchAttr(multiBtn, 'hidden', !showMulti); if (!data) { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); patchCapsuleOdometerText(multiLabel, t('capsule.multiZero'), { resetKey: 'multi' }); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { hasTelemetry: false }); return; } const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation( data, 'all', resolveOverlayCtxInspectorAgentId(data, 'auto') ); const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated }); const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, { agents, aggregated, contextUsedPct: slotCtx.usedPct, }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); patchCapsuleOdometerText(multiLabel, multiBtnText, { resetKey: 'multi' }); patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); } return { el: rootEl, refs: { update, multiBtn, capsuleBtn, capsuleSlots, capsuleSeps, hostBarEl, }, }; }, }); return { RING_RADIUS, RING_CIRCUMFERENCE, tokenizeCapsuleOdometerText, patchCapsuleOdometerText, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget }; })(); // --- src/components/widgets/StepTableWidget.js --- const { formatTurnPromptText, StepTableWidget } = (() => { /** * @fileoverview Reusable Decoupled Step Table Widget (`StepTableWidget.js`). * Powers both `StepsDetailView` ("按步查看") and `SettingsStructureTab` live preview, * dynamically rendering 2..12 columns via `stepColumnRegistry.js`, turn rail + prompt * preview tooltips, and independent Main/Sub agent badges. */ function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) { const text = String(rawPrompt || '').trim(); if (mediaOnly || (!text && hasMedia)) return t('steps.turnMediaOnly'); if (!text) return ''; return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text; } const VIRTUAL_ROW_THRESHOLD = 80; const VIRTUAL_OVERSCAN_ROWS = 16; const VIRTUAL_REFILL_MARGIN = 6; const MAX_ROW_POOL_SIZE = 96; const FALLBACK_VIEWPORT_H = 560; const BASE_SINGLE_ROW_H = 28; const BASE_REASON_ROW_H = 42; const SIZER_ROW_KEY = '__vsizer__'; const SPACER_TOP_KEY = '__vspacer_top__'; const SPACER_BOTTOM_KEY = '__vspacer_bottom__'; function estProportionalTextWidth(text) { const s = String(text || ''); let w = 0; for (let i = 0; i < s.length; i++) { const code = s.charCodeAt(i); if (code > 0x2e7f) { w += 1.8; } else if ( code === 105 || code === 108 || code === 73 || code === 116 || code === 102 || code === 114 || code === 46 || code === 44 || code === 58 || code === 59 || code === 45 || code === 47 || code === 32 ) { w += 0.55; } else if ( code === 109 || code === 119 || code === 77 || code === 87 || code === 71 || code === 79 || code === 81 || code === 67 ) { w += 1.32; } else { w += 1.0; } } return w; } function estTokenChars(val) { const n = Math.max(0, Number(val || 0)); if (n >= 1_000_000) return n >= 10_000_000 ? 6.4 : 5.6; if (n >= 100_000) return 6.0; if (n >= 10_000) return 5.0; if (n >= 1_000) return 4.1; if (n >= 100) return 3.0; if (n >= 10) return 2.0; return 1.0; } function estCostWidth(st) { return estProportionalTextWidth(formatUsd(st?.costUsd, { precise: true })); } function estSegmentChars(seg, st) { const inTok = Math.max(0, Number(st?.inputTokens || 0)); const cacheTok = Math.max(0, Number(st?.cacheReadTokens || 0)); const outTok = Math.max(0, Number(st?.outputTokens || 0)); const thinkTok = Math.max(0, Number(st?.thinkingTokens || 0)); const respTok = st?.responseTokens != null ? Math.max(0, Number(st.responseTokens)) : Math.max(0, outTok - thinkTok); switch (seg) { case 'context': return estTokenChars(st?.contextTokens ?? inTok + cacheTok + outTok); case 'in': return estTokenChars(inTok); case 'out': return estTokenChars(outTok); case 'cache': return estTokenChars(cacheTok); case 'think': return estTokenChars(thinkTok); case 'reply': return estTokenChars(respTok); case 'total': default: return estTokenChars(inTok + cacheTok + outTok); } } function resolveBadgeTextForStep(st) { return formatAgentBadgeText({ agentKind: st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), agentOrdinal: st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), isMain: !st?.isSubagent, isSideQuestion: Boolean(st?.isSideQuestion), sideIndex: st?.sideIndex || 0, index: st?.agentIndex || 0, badgeText: st?.agentBadge, }); } function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { const firstStep = tableSteps[0] || {}; const colSteps = {}; const needStep = wantedSet.has('step'); const needTime = wantedSet.has('time'); const needModel = wantedSet.has('model'); const needTps = wantedSet.has('tps'); const needTtft = wantedSet.has('ttft'); const needDuration = wantedSet.has('duration'); const needTokensCombo = wantedSet.has('tokens_combo'); const needTokensIoCache = wantedSet.has('tokens_io_cache'); const needTokensCustom = wantedSet.has('tokens_custom'); const needInput = wantedSet.has('input_tokens'); const needCacheTok = wantedSet.has('cache_tokens'); const needOutput = wantedSet.has('output_tokens'); const needCachePct = wantedSet.has('cache'); const needCost = wantedSet.has('cost'); const customSegs = needTokensCustom ? parseStepTokenComboSegments(cellCtx?.stepTokenComboFormat) : null; let bestStepNum = -1; let bestStepObj = firstStep; let bestTimeObj = null; const modelCandidates = needModel ? new Map() : null; let maxTpsVal = -1; let maxTpsObj = null; const reasonCandidates = needTps ? new Set() : null; let maxTtftVal = -1; let bestTtftObj = firstStep; let maxDurVal = -1; let bestDurObj = firstStep; let bestComboScore = -1; let bestComboObj = firstStep; let bestIoCacheScore = -1; let bestIoCacheObj = firstStep; let bestCustomScore = -1; let bestCustomObj = firstStep; let maxInputVal = -1; let bestInputObj = firstStep; let maxCacheTokVal = -1; let bestCacheTokObj = firstStep; let maxOutputVal = -1; let bestOutputObj = firstStep; let bestCachePctScore = -1; let bestCachePctObj = firstStep; let bestCostScore = -1; let bestCostObj = firstStep; let bestBadgeText = ''; let bestBadgeWidth = -1; let bestBadgeClass = ''; let hasBoldFirstCol = false; const badgeCandidates = cellCtx?.showAgentBadge ? new Set() : null; for (let i = 0; i < tableSteps.length; i++) { const st = tableSteps[i]; if (!st || typeof st !== 'object') continue; if (!hasBoldFirstCol && (isCompactionStepItem(st) || Number(st?.anomaly?.count) > 0)) { hasBoldFirstCol = true; } if (badgeCandidates) { const bKey = `${st.agentKind || ''}|${st.isSubagent ? 1 : 0}|${st.isSideQuestion ? 1 : 0}|${st.agentOrdinal || 0}|${st.sideIndex || 0}|${st.agentIndex || 0}|${st.agentBadge || ''}`; if (!badgeCandidates.has(bKey)) { badgeCandidates.add(bKey); const text = resolveBadgeTextForStep(st); const bw = estProportionalTextWidth(text); if (bw > bestBadgeWidth) { bestBadgeWidth = bw; bestBadgeText = text; bestBadgeClass = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); } } } if (needStep) { const idxNum = Number(st.stepIndex) || 0; if (idxNum > bestStepNum) { bestStepNum = idxNum; bestStepObj = st; } } if (needTime && !bestTimeObj && Number(st.createdAtMs || 0) > 0) { bestTimeObj = st; } if (modelCandidates) { const mKey = `${st.baseModelShort || st.modelShort || ''}|${st.baseModelLabel || st.modelLabel || ''}|${st.rawModel || ''}|${st.isCompactionStep ? 1 : 0}`; if (!modelCandidates.has(mKey)) { modelCandidates.set(mKey, st); } } if (needTps) { const tpsVal = Number(st.tokPerSec); if (Number.isFinite(tpsVal) && tpsVal >= 0) { const tpsScore = (tpsVal >= 100 ? String(Math.round(tpsVal)).length : tpsVal.toFixed(1).length) * 1e6 + tpsVal; if (tpsScore > maxTpsVal) { maxTpsVal = tpsScore; maxTpsObj = st; } } if (st.selectedSpeedReason) { reasonCandidates.add(st.selectedSpeedReason); } } if (needTtft) { const v = Number(st.ttftSec); if (Number.isFinite(v) && v >= 0) { const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v; if (score > maxTtftVal) { maxTtftVal = score; bestTtftObj = st; } } } if (needDuration) { const v = Number(st.totalDurationSec ?? st.streamDurationSec); if (Number.isFinite(v) && v >= 0) { const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v; if (score > maxDurVal) { maxDurVal = score; bestDurObj = st; } } } if (needTokensCombo) { const inTok = Math.max(0, Number(st.inputTokens || 0)); const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); const outTok = Math.max(0, Number(st.outputTokens || 0)); const thinkTok = Math.max(0, Number(st.thinkingTokens || 0)); const respTok = st.responseTokens != null ? Math.max(0, Number(st.responseTokens)) : Math.max(0, outTok - thinkTok); const ctxTok = Math.max(0, Number(st.contextTokens ?? inTok + cacheTok + outTok)); const score = (estTokenChars(ctxTok) + estTokenChars(thinkTok) + estTokenChars(respTok)) * 1e9 + ctxTok; if (score > bestComboScore) { bestComboScore = score; bestComboObj = st; } } if (needTokensIoCache) { const inTok = Math.max(0, Number(st.inputTokens || 0)); const outTok = Math.max(0, Number(st.outputTokens || 0)); const cacheTok = Math.max(0, Number(st.cacheReadTokens || 0)); const score = (estTokenChars(inTok) + estTokenChars(outTok) + estTokenChars(cacheTok)) * 1e9 + cacheTok; if (score > bestIoCacheScore) { bestIoCacheScore = score; bestIoCacheObj = st; } } if (needTokensCustom && customSegs) { let chars = 0; for (let s = 0; s < customSegs.length; s++) { chars += estSegmentChars(customSegs[s], st); } if (chars > bestCustomScore) { bestCustomScore = chars; bestCustomObj = st; } } if (needInput) { const v = Math.max(0, Number(st.inputTokens || 0)); const score = estTokenChars(v) * 1e9 + v; if (score > maxInputVal) { maxInputVal = score; bestInputObj = st; } } if (needCacheTok) { const v = Math.max(0, Number(st.cacheReadTokens || 0)); const score = estTokenChars(v) * 1e9 + v; if (score > maxCacheTokVal) { maxCacheTokVal = score; bestCacheTokObj = st; } } if (needOutput) { const v = Math.max(0, Number(st.outputTokens || 0)); const score = estTokenChars(v) * 1e9 + v; if (score > maxOutputVal) { maxOutputVal = score; bestOutputObj = st; } } if (needCachePct) { const pct = Number(st.cacheHitPct ?? 0); const hasDec = pct > 0 && pct < 100 && Math.abs(pct - Math.round(pct)) > 1e-6; const score = pct >= 100 ? 4 : hasDec ? (pct >= 10 ? 5 : 4) : pct >= 10 ? 3 : 2; if (score > bestCachePctScore) { bestCachePctScore = score; bestCachePctObj = st; } } if (needCost) { const c = Number(st.costUsd); const score = estCostWidth(st) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0); if (score > bestCostScore) { bestCostScore = score; bestCostObj = st; } } } if (needStep) colSteps.step = bestStepObj; if (needTime) colSteps.time = bestTimeObj || firstStep; if (needModel && modelCandidates) { let bestModelWidth = -1; let bestModelObj = firstStep; for (const cand of modelCandidates.values()) { const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); const w = estProportionalTextWidth(disp.baseText || ''); if (w > bestModelWidth) { bestModelWidth = w; bestModelObj = cand; } } colSteps.model = bestModelObj; } if (needTps) { let longestReasonKey = null; let longestReasonWidth = 0; if (reasonCandidates) { for (const rk of reasonCandidates) { const txt = speedReasonText(rk); const w = txt ? estProportionalTextWidth(txt) : 0; if (w > longestReasonWidth) { longestReasonWidth = w; longestReasonKey = rk; } } } colSteps.tps = { ...(maxTpsObj || firstStep), tokPerSec: maxTpsObj ? maxTpsObj.tokPerSec : firstStep.tokPerSec, selectedSpeedReason: longestReasonKey, }; } if (needTtft) colSteps.ttft = bestTtftObj; if (needDuration) colSteps.duration = bestDurObj; if (needTokensCombo) colSteps.tokens_combo = bestComboObj; if (needTokensIoCache) colSteps.tokens_io_cache = bestIoCacheObj; if (needTokensCustom) colSteps.tokens_custom = bestCustomObj; if (needInput) colSteps.input_tokens = bestInputObj; if (needCacheTok) colSteps.cache_tokens = bestCacheTokObj; if (needOutput) colSteps.output_tokens = bestOutputObj; if (needCachePct) colSteps.cache = bestCachePctObj; if (needCost) colSteps.cost = bestCostObj; const sigParts = colKeys.map((colKey) => { const st = colSteps[colKey] || firstStep; return `${colKey}=${STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)}`; }); return { colSteps, badgeText: bestBadgeText, badgeClass: bestBadgeClass, hasBoldFirstCol, sig: `sizer:${bestBadgeText}:${hasBoldFirstCol ? 1 : 0}:${sigParts.join('|')}`, }; } const StepTableWidget = defineComponent({ name: 'StepTableWidget', setup({ props, onCleanup }) { const standalone = Boolean(props.standalone); const interactiveBadges = props.interactiveBadges !== false; const onSelectAgentScopes = typeof props.onSelectAgentScopes === 'function' ? props.onSelectAgentScopes : null; const onVirtualHeightChange = typeof props.onVirtualHeightChange === 'function' ? props.onVirtualHeightChange : null; const onSortChange = typeof props.onSortChange === 'function' ? props.onSortChange : null; const stepsTheadRow = h('tr'); const stepsThead = h('thead', {}, [stepsTheadRow]); const stepsTbody = h('tbody'); function syncTableHeaderColumns(colKeys, headerCtx = {}) { const locale = getEffectiveLocale(); const fmtKey = normalizeClientStepTokenComboFormat(headerCtx?.stepTokenComboFormat); const activeSortKey = String(headerCtx?.sortKey || ''); const activeSortDir = headerCtx?.sortDir === 'asc' || headerCtx?.sortDir === 'desc' ? headerCtx.sortDir : ''; const ctx = { stepTokenComboFormat: fmtKey }; patchKeyedList(stepsTheadRow, colKeys, { keyFn: (colKey) => colKey, sigFn: (colKey) => { const isSorted = activeSortKey === colKey && Boolean(activeSortDir); return `${locale}:${colKey}:${fmtKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel(ctx)}:${onSortChange ? 1 : 0}:${isSorted ? activeSortDir : ''}`; }, createRow: (colKey) => { const labelSpan = h('span', { className: 'step-th-label', text: STEP_COLUMN_REGISTRY[colKey].thLabel(ctx), }); const sortIcon = createSvgIcon('chevron-down', { size: 10, className: 'step-sort-icon', }); patchAttr(sortIcon, 'hidden', true); const innerWrap = h('span', { className: 'step-th-inner' }, [labelSpan, sortIcon]); const th = h('th', {}, [innerWrap]); return { el: th, refs: { th, labelSpan, sortIcon } }; }, updateRow: (refs, colKey) => { const labelText = STEP_COLUMN_REGISTRY[colKey].thLabel(ctx); patchText(refs.labelSpan, labelText); const sortable = Boolean( onSortChange && typeof STEP_COLUMN_REGISTRY[colKey]?.sortValue === 'function' ); const isSorted = sortable && activeSortKey === colKey && Boolean(activeSortDir); patchClasses(refs.th, { 'is-sortable': sortable, 'is-sorted': isSorted, }); patchAttr( refs.th, 'aria-sort', isSorted ? (activeSortDir === 'asc' ? 'ascending' : 'descending') : sortable ? 'none' : null ); patchAttr( refs.th, 'title', sortable ? t('steps.sortClickTip', { col: labelText }) : null ); patchAttr(refs.sortIcon, 'hidden', !isSorted); if (isSorted) { patchSvgIcon(refs.sortIcon, activeSortDir === 'asc' ? 'chevron-up' : 'chevron-down'); } refs.th.onclick = sortable ? () => { const defaultDir = STEP_COLUMN_REGISTRY[colKey]?.defaultSortDir || 'desc'; let nextKey = colKey; let nextDir = defaultDir; if (activeSortKey === colKey) { if (activeSortDir === defaultDir) { nextDir = defaultDir === 'desc' ? 'asc' : 'desc'; } else { nextKey = ''; nextDir = ''; } } onSortChange(nextKey, nextDir); } : null; }, }); } syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS); const stepsTableEl = h('table', { className: 'data-table steps-data-table' }, [ stepsThead, stepsTbody, ]); const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [stepsTableEl]); const turnTipEl = h('div', { className: 'turn-prompt-tip', role: 'tooltip', hidden: true, }); const hideTurnTip = () => patchAttr(turnTipEl, 'hidden', true); const anomalyTipTitleEl = h('div', { className: 'step-anomaly-tip-title' }); const anomalyTipSubEl = h('div', { className: 'step-anomaly-tip-sub text-mono', hidden: true }); const anomalyTipHeadEl = h('div', { className: 'step-anomaly-tip-head' }, [ anomalyTipTitleEl, anomalyTipSubEl, ]); const anomalyTipListEl = h('div', { className: 'step-anomaly-tip-list' }); const anomalyTipHintEl = h('div', { className: 'step-anomaly-tip-hint', hidden: true }); const anomalyTipEl = h( 'div', { className: 'step-anomaly-tip', role: 'tooltip', hidden: true, }, [anomalyTipHeadEl, anomalyTipListEl, anomalyTipHintEl] ); const hideAnomalyTip = () => patchAttr(anomalyTipEl, 'hidden', true); const standaloneHostEl = standalone ? h('div', { className: 'step-table-preview-host' }, [ stepsTablePane, turnTipEl, anomalyTipEl, ]) : null; let boundsContainerGetter = typeof props.getBoundsEl === 'function' ? props.getBoundsEl : () => standaloneHostEl || stepsTablePane; function setBoundsElGetter(fn) { if (typeof fn === 'function') { boundsContainerGetter = fn; } } function positionFloatingTip(tipEl, anchorEl) { const boundsEl = boundsContainerGetter?.(); if ( !boundsEl || typeof boundsEl.getBoundingClientRect !== 'function' || typeof anchorEl?.getBoundingClientRect !== 'function' ) { return; } const panelRect = boundsEl.getBoundingClientRect(); const anchorRect = anchorEl.getBoundingClientRect(); if (!(panelRect.width > 0 && panelRect.height > 0)) return; const tipH = tipEl.offsetHeight || 56; const tipW = tipEl.offsetWidth || 220; const placeAbove = panelRect.bottom - anchorRect.bottom < tipH + 10 && anchorRect.top - panelRect.top > tipH + 6; const topPx = placeAbove ? Math.max(4, Math.round(anchorRect.top - panelRect.top - tipH - 5)) : Math.round(anchorRect.bottom - panelRect.top + 5); const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8)); const leftPx = Math.min( maxLeft, Math.max(6, Math.round(anchorRect.left - panelRect.left)) ); tipEl.style.top = `${topPx}px`; tipEl.style.left = `${leftPx}px`; } function showTurnTip(anchorCell, promptText) { const text = String(promptText || '').trim(); if (!anchorCell || !text) { hideTurnTip(); return; } hideAnomalyTip(); patchText(turnTipEl, text); patchAttr(turnTipEl, 'hidden', false); positionFloatingTip(turnTipEl, anchorCell); } function showAnomalyTip(anchorEl, diag) { if (!anchorEl || !diag || !diag.title) { hideAnomalyTip(); return; } hideTurnTip(); patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger', 'is-compaction': diag.severity === 'compaction', 'is-timing': diag.severity === 'timing', }); patchText(anomalyTipTitleEl, diag.title); patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); if (diag.sub) patchText(anomalyTipSubEl, diag.sub); while (anomalyTipListEl.firstChild) { anomalyTipListEl.removeChild(anomalyTipListEl.firstChild); } const rows = Array.isArray(diag.rows) ? diag.rows : []; for (const row of rows) { const hasKvValue = row.value !== undefined && row.value !== null && row.value !== ''; const lineEl = hasKvValue ? h( 'div', { className: `step-anomaly-tip-row is-kv${row.danger ? ' is-danger' : ''}` }, [ h('span', { className: 'step-anomaly-tip-k', text: row.text }), h('span', { className: `step-anomaly-tip-v text-mono${row.toneClass ? ` ${row.toneClass}` : ''}`, text: row.value, }), ] ) : h('div', { className: `step-anomaly-tip-row${row.danger ? ' is-danger' : ''}`, text: row.text, }); const itemChildren = [lineEl]; if (row.detail) { itemChildren.push( h('div', { className: row.mono === false ? 'step-anomaly-tip-detail' : 'step-anomaly-tip-detail text-mono', text: row.detail, }) ); } anomalyTipListEl.appendChild(h('div', { className: 'step-anomaly-tip-item' }, itemChildren)); } patchAttr(anomalyTipListEl, 'hidden', rows.length === 0); patchAttr(anomalyTipHintEl, 'hidden', !diag.hint); if (diag.hint) patchText(anomalyTipHintEl, diag.hint); patchAttr(anomalyTipEl, 'hidden', false); positionFloatingTip(anomalyTipEl, anchorEl); } const hoverRows = new WeakMap(); const timingHoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; let trackedCascadeId = null; let lastAbsorbedAllSteps = null; const seenStepKeys = new Set(); const maxSeenStepByAgent = new Map(); const activeEnterTimers = new Map(); // Virtualization state (activates transparently only when !standalone && rowCount > 80) let activeDataset = null; let renderedSliceStart = -1; let renderedSliceEnd = -1; let renderedTopSpacerH = -1; let renderedBottomSpacerH = -1; let scrollRafId = 0; let calibrateRafId = 0; let lastFontScale = 1; let calibratedSingleRowH = 0; let calibratedReasonRowH = 0; let lockedColKey = ''; let lockedPaneWidth = 0; const rowPool = []; function computeColLockKey(ds) { if (!ds?.isVirtualized) return ''; return `${ds.locale}:${ds.colOrderSig}:${lastFontScale}:${ds.showAgentBadge ? 1 : 0}:${ds.railActive ? 1 : 0}:${ds.sortKey || ''}:${ds.sortDir || ''}:${ds.sizerSpec?.sig || ''}`; } function unlockColumnWidths() { lockedColKey = ''; lockedPaneWidth = 0; patchClasses(stepsTableEl, { 'is-cols-locked': false }); if (stepsTableEl.style) { stepsTableEl.style.minWidth = ''; } const ths = stepsTheadRow.children || []; for (let i = 0; i < ths.length; i++) { if (ths[i]?.style) ths[i].style.width = ''; } } function lockColumnWidthsIfNeeded() { if (!activeDataset?.isVirtualized) return; const paneW = Number(stepsTablePane.clientWidth || 0); if (paneW <= 0) return; const nextKey = computeColLockKey(activeDataset); if (lockedColKey === nextKey && Math.abs(paneW - lockedPaneWidth) < 1) return; const ths = stepsTheadRow.children || []; const colCount = activeDataset.colKeys.length; if (ths.length !== colCount) return; // Release fixed layout momentarily if stale so browser resolves natural widths from sizer + header if (stepsTableEl.classList?.contains('is-cols-locked')) { unlockColumnWidths(); } const widths = []; for (let i = 0; i < colCount; i++) { const w = Number(ths[i]?.getBoundingClientRect?.()?.width || 0); if (!Number.isFinite(w) || w <= 0) return; widths.push(w); } const tableW = Number(stepsTableEl.getBoundingClientRect?.()?.width || 0); if (!Number.isFinite(tableW) || tableW <= 0) return; for (let i = 0; i < colCount; i++) { if (ths[i]?.style) { ths[i].style.width = `${widths[i].toFixed(2)}px`; } } if (stepsTableEl.style) { stepsTableEl.style.minWidth = tableW > paneW + 0.5 ? `${tableW.toFixed(2)}px` : ''; } patchClasses(stepsTableEl, { 'is-cols-locked': true }); lockedColKey = nextKey; lockedPaneWidth = paneW; } function readUiFontScale() { try { if (typeof getComputedStyle === 'function') { const target = stepsTableEl || (typeof document !== 'undefined' ? document.documentElement : null); if (target) { const raw = getComputedStyle(target)?.getPropertyValue?.('--ui-font-scale'); const parsed = Number.parseFloat(raw); if (Number.isFinite(parsed) && parsed >= 0.5 && parsed <= 2.5) { return parsed; } } } } catch { // Fallback to default scale in headless/mock environments. } return 1; } function getEstRowHeights() { const single = calibratedSingleRowH > 0 ? calibratedSingleRowH : Math.round(BASE_SINGLE_ROW_H * lastFontScale); const reason = calibratedReasonRowH > 0 ? calibratedReasonRowH : Math.round(BASE_REASON_ROW_H * lastFontScale); return { single, reason }; } function buildRowTops(n, hasReasonFlags) { const { single, reason } = getEstRowHeights(); const tops = new Float64Array(n + 1); let acc = 0; for (let i = 0; i < n; i++) { tops[i] = acc; acc += hasReasonFlags && hasReasonFlags[i] ? reason : single; } tops[n] = acc; return { rowTops: tops, totalBodyH: acc }; } function findRowIndexAtOffset(rowTops, n, offset) { if (n <= 0 || offset <= 0) return 0; if (offset >= rowTops[n - 1]) return n - 1; let lo = 0; let hi = n - 1; while (lo < hi) { const mid = (lo + hi + 1) >>> 1; if (rowTops[mid] <= offset) lo = mid; else hi = mid - 1; } return lo; } function syncFontScaleIfChanged() { const nextScale = readUiFontScale(); if (Math.abs(nextScale - lastFontScale) < 0.005) return false; lastFontScale = nextScale; calibratedSingleRowH = 0; calibratedReasonRowH = 0; unlockColumnWidths(); if (activeDataset?.isVirtualized) { const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); activeDataset.rowTops = rebuilt.rowTops; activeDataset.totalBodyH = rebuilt.totalBodyH; } return true; } function getStepRowIdentity(st, fallbackCascadeId) { const agentKey = String( st?.agentCascadeId || st?.agentId || st?.cascadeId || fallbackCascadeId || 'conv' ); const stepNum = Number(st?.stepIndex); const rowKey = getStepSelectionKey(st, fallbackCascadeId); 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); if (event?.target === badge) hideTurnTip(); else showTurnTip(this, prompt); } function moveInStepCell(event) { const { badge } = hoverRows.get(this); if (event?.target === badge) hideTurnTip(); } function buildStepRowDiagnostic(st, displaySettings, hasStepAnomaly, isCompactionRow) { if (hasStepAnomaly) { const diag = buildStepAnomalyDiagnostic(st); if (diag && isCompactionRow) { return { ...diag, hint: diag.hint ? `${diag.hint} · ${t('steps.compactionAnomalyHint')}` : t('steps.compactionAnomalyHint'), }; } return diag; } if (isCompactionRow) { return buildStepCompactionDiagnostic(st, displaySettings); } return null; } function moveAlongTurnRail(event) { const { badge, prompt, rowDiagGetter, timingDiagGetter } = hoverRows.get(this); const rect = this.getBoundingClientRect?.(); const relX = rect ? (event?.clientX ?? 0) - rect.left : 0; if (event?.target !== badge && relX <= 18) { showTurnTip(this, prompt); } else { hideTurnTip(); const diag = timingDiagGetter?.() || rowDiagGetter?.(); if (diag) { showAnomalyTip(this, diag); } else { hideAnomalyTip(); } } } function leaveStepCell(event) { const entry = hoverRows.get(this); hideTurnTip(); if (entry?.rowDiagGetter && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { showAnomalyTip(entry.rowAnchorEl || this, entry.rowDiagGetter()); } else if (entry?.timingDiagGetter) { hideAnomalyTip(); } } function clearCellHover(cell) { if (!cell || !hoverRows.delete(cell)) return; cell.onmouseenter = null; cell.onmousemove = null; cell.onmouseleave = null; } function enterTimingCell() { const entry = timingHoverRows.get(this); if (!entry) return; const diag = entry.timingDiagGetter?.(); if (diag) { showAnomalyTip(this, diag); } } function leaveTimingCell(event) { const entry = timingHoverRows.get(this); if ( entry?.rowDiagGetter && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget) ) { showAnomalyTip(entry.rowAnchorEl || entry.tr, entry.rowDiagGetter()); return; } hideAnomalyTip(); } function clearTimingCellHover(cell) { if (!cell || !timingHoverRows.delete(cell)) return; cell.onmouseenter = null; cell.onmouseleave = null; } function clearRowTimingHovers(refs) { if (!refs?.timingHoverTds) return; for (const td of refs.timingHoverTds) { clearTimingCellHover(td); } refs.timingHoverTds.clear(); } function calibrateRowHeights() { calibrateRafId = 0; if (!activeDataset?.isVirtualized) return; if (Number(stepsTablePane.clientHeight || 0) <= 0) return; lockColumnWidthsIfNeeded(); const needSingle = calibratedSingleRowH <= 0; const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; if (!needSingle && !needReason) return; let measuredSingle = 0; let measuredReason = 0; // Measure contiguous run of normal rows to eliminate single-row subpixel/border-collapse drift. let runStartTop = 0; let runEndBottom = 0; let runCount = 0; let bestRunStride = 0; let bestRunCount = 0; const children = stepsTbody.children || []; for (let i = 0; i < children.length; i++) { const tr = children[i]; if (!tr || tr.classList?.contains('step-vspacer') || tr.classList?.contains('step-vsizer')) { runCount = 0; continue; } const isReason = tr.dataset?.hasReason === '1'; if (!isReason && needSingle) { const rect = tr.getBoundingClientRect?.(); const hVal = Number(rect?.height || tr.offsetHeight || 0); if (hVal >= 14 && hVal <= 120) { if (!measuredSingle) measuredSingle = hVal; if (rect && Number.isFinite(rect.top) && Number.isFinite(rect.bottom) && rect.bottom > rect.top) { if (runCount === 0) { runStartTop = rect.top; } runEndBottom = rect.bottom; runCount += 1; if (runCount > bestRunCount && runCount >= 2) { const stride = (runEndBottom - runStartTop) / runCount; if (stride >= 14 && stride <= 120) { bestRunCount = runCount; bestRunStride = stride; } } } } } else { runCount = 0; if (isReason && needReason && !measuredReason) { const hVal = Number(tr.getBoundingClientRect?.()?.height || tr.offsetHeight || 0); if (hVal >= 18 && hVal <= 160) measuredReason = hVal; } } if ((!needSingle || bestRunCount >= 12) && (!needReason || measuredReason > 0)) { break; } } if (bestRunStride > 0) { measuredSingle = bestRunStride; } let changed = false; if (measuredSingle > 0) { const prev = getEstRowHeights().single; calibratedSingleRowH = measuredSingle; if (Math.abs(measuredSingle - prev) >= 0.25) changed = true; } if (measuredReason > 0) { const prev = getEstRowHeights().reason; calibratedReasonRowH = measuredReason; if (Math.abs(measuredReason - prev) >= 0.25) changed = true; } if (changed && activeDataset) { const prevTops = activeDataset.rowTops; const anchorIdx = renderedSliceStart > 0 ? renderedSliceStart : 0; const prevAnchorTop = prevTops ? prevTops[anchorIdx] : 0; const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); activeDataset.rowTops = rebuilt.rowTops; activeDataset.totalBodyH = rebuilt.totalBodyH; const curScrollTop = Number(stepsTablePane.scrollTop || 0); if (anchorIdx > 0 && curScrollTop > 0) { const delta = rebuilt.rowTops[anchorIdx] - prevAnchorTop; if (Math.abs(delta) >= 0.5) { stepsTablePane.scrollTop = Math.max(0, curScrollTop + delta); } } renderCurrentWindow({ force: true, enteringRowKeys: null }); onVirtualHeightChange?.(); } } function scheduleCalibrateRowHeights() { if (!activeDataset?.isVirtualized) return; const needSingle = calibratedSingleRowH <= 0; const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; const paneW = Number(stepsTablePane.clientWidth || 0); const needColLock = !lockedColKey || lockedColKey !== computeColLockKey(activeDataset) || (paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1); if (!needSingle && !needReason && !needColLock) return; if (calibrateRafId) return; if (typeof requestAnimationFrame === 'function') { calibrateRafId = requestAnimationFrame(calibrateRowHeights); } else { calibrateRowHeights(); } } function renderCurrentWindow({ force = false, enteringRowKeys = null } = {}) { const ds = activeDataset; if (!ds) return; const { tableSteps, cascadeId, colKeys, wantedSet, colOrderSig, locale, cellCtx, railActive, showAgentBadge, showStepTurnRail, useRootTurn, isVirtualized, hasReasonFlags, rowTops, totalBodyH, sizerSpec, effectiveScopes, formattedPrompts, } = ds; const n = tableSteps.length; let startIdx = 0; let endIdx = n; let topSpacerH = 0; let bottomSpacerH = 0; if (isVirtualized) { const scrollTop = Math.max(0, Number(stepsTablePane.scrollTop || 0)); const rawClientH = Number(stepsTablePane.clientHeight || 0); const viewportH = rawClientH > 0 ? rawClientH : FALLBACK_VIEWPORT_H; const rawTheadH = Number( stepsThead.offsetHeight || stepsThead.getBoundingClientRect?.()?.height || 0 ); const theadH = rawTheadH > 0 ? rawTheadH : getEstRowHeights().single; const viewTop = Math.max(0, scrollTop - theadH); const viewBottom = viewTop + viewportH; const firstVis = findRowIndexAtOffset(rowTops, n, viewTop); const lastVis = findRowIndexAtOffset(rowTops, n, viewBottom); if ( !force && renderedSliceStart >= 0 && renderedSliceEnd > renderedSliceStart && renderedSliceEnd <= n ) { const topSafe = renderedSliceStart === 0 || firstVis - renderedSliceStart >= VIRTUAL_REFILL_MARGIN; const bottomSafe = renderedSliceEnd === n || renderedSliceEnd - 1 - lastVis >= VIRTUAL_REFILL_MARGIN; if (topSafe && bottomSafe) { return; } } startIdx = Math.max(0, firstVis - VIRTUAL_OVERSCAN_ROWS); endIdx = Math.min(n, lastVis + 1 + VIRTUAL_OVERSCAN_ROWS); topSpacerH = +rowTops[startIdx].toFixed(2); bottomSpacerH = +Math.max(0, totalBodyH - rowTops[endIdx]).toFixed(2); if ( !force && startIdx === renderedSliceStart && endIdx === renderedSliceEnd && topSpacerH === renderedTopSpacerH && bottomSpacerH === renderedBottomSpacerH ) { return; } } const getStepTurnIdx = (st) => useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex; const getStepIsStart = (st) => Boolean(useRootTurn ? (st?.isRootTurnStart ?? st?.isTurnStart) : st?.isTurnStart); const getStepIsLatest = (st) => Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn); const getStepPrompt = (st) => (useRootTurn ? (st?.rootTurnPromptClean ?? st?.rootTurnPrompt ?? st?.turnPromptClean ?? st?.turnPrompt) : (st?.turnPromptClean ?? st?.turnPrompt)) || ''; const getStepHasMedia = (st) => Boolean(useRootTurn ? (st?.rootTurnHasMedia ?? st?.turnHasMedia) : st?.turnHasMedia); const getStepMediaOnly = (st) => Boolean(useRootTurn ? (st?.rootTurnMediaOnly ?? st?.turnMediaOnly) : st?.turnMediaOnly); function getTurnKeyAt(idx) { if (!showStepTurnRail || idx < 0 || idx >= n) return ''; const st = tableSteps[idx]; const tIdx = getStepTurnIdx(st); if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`; } function formattedTurnPrompt(st) { const raw = getStepPrompt(st); const hasMedia = getStepHasMedia(st); const mediaOnly = getStepMediaOnly(st); const cacheKey = `${mediaOnly ? 2 : hasMedia ? 1 : 0}:${raw}`; if (!formattedPrompts.has(cacheKey)) { formattedPrompts.set(cacheKey, formatTurnPromptText(raw, { hasMedia, mediaOnly })); } return formattedPrompts.get(cacheKey); } const windowItems = []; if (isVirtualized && sizerSpec) { windowItems.push({ isSizer: true, isSpacer: false, rowKey: SIZER_ROW_KEY, sizerSpec, }); } if (isVirtualized && topSpacerH > 0) { windowItems.push({ isSizer: false, isSpacer: true, rowKey: SPACER_TOP_KEY, height: topSpacerH, colSpan: colKeys.length, }); } for (let idx = startIdx; idx < endIdx; idx++) { const st = tableSteps[idx]; const tKey = getTurnKeyAt(idx); const hasTurn = Boolean(tKey); const hasUp = hasTurn && getTurnKeyAt(idx - 1) === tKey; const hasDown = hasTurn && getTurnKeyAt(idx + 1) === tKey; windowItems.push({ isSizer: false, isSpacer: false, st, logicalIdx: idx, isStripeEven: (idx & 1) === 1, hasReason: Boolean(hasReasonFlags && hasReasonFlags[idx]), rowKey: getStepSelectionKey(st, cascadeId), hasTurn, hasUp, hasDown, isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)), isLatest: hasTurn && getStepIsLatest(st), prompt: hasTurn ? formattedTurnPrompt(st) : '', }); } if (isVirtualized && bottomSpacerH > 0) { windowItems.push({ isSizer: false, isSpacer: true, rowKey: SPACER_BOTTOM_KEY, height: bottomSpacerH, colSpan: colKeys.length, }); } patchKeyedList(stepsTbody, windowItems, { keyFn: (item) => item.rowKey, sigFn: (item) => { if (item.isSizer) { return `${locale}:${colOrderSig}:${showAgentBadge ? 1 : 0}:${railActive ? 1 : 0}:${item.sizerSpec.sig}`; } if (item.isSpacer) { return `spacer:${item.colSpan}:${item.height}`; } const { st } = item; const parts = colKeys .map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)) .join('|'); const badgeSig = showAgentBadge ? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}` : ''; const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N'; const anomalySig = st.anomalySig || ''; const compactSig = isCompactionStepItem(st) ? 'C' : ''; return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${compactSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, createRow: (item) => { if (item.isSizer) { const tr = h('tr', { className: 'step-vsizer', 'aria-hidden': 'true' }); return { el: tr, refs: { isSizer: true, isSpacer: false, cellMap: new Map(), colOrderSig: '', agentBadgeEl: null, }, }; } if (item.isSpacer) { const td = h('td', { className: 'step-vspacer-cell', colspan: String(item.colSpan), }); const tr = h('tr', { className: 'step-vspacer', 'aria-hidden': 'true' }, [td]); return { el: tr, refs: { isSizer: false, isSpacer: true, td } }; } if (rowPool.length > 0) { return rowPool.pop(); } const tr = h('tr'); return { el: tr, refs: { isSizer: false, isSpacer: false, cellMap: new Map(), colOrderSig: '', railEl: null, agentBadgeEl: null, hoverTd: null, timingHoverTds: new Set(), }, }; }, updateRow: (refs, item, _idx, tr) => { if (item.isSizer) { const spec = item.sizerSpec; patchClasses(tr, { 'has-bold-first': Boolean(spec.hasBoldFirstCol) }); if (refs.colOrderSig !== colOrderSig) { for (const [oldColKey, entry] of refs.cellMap) { if (!wantedSet.has(oldColKey)) { if (refs.agentBadgeEl?.parentNode === entry.innerEl) { entry.innerEl.removeChild(refs.agentBadgeEl); } tr.removeChild(entry.td); refs.cellMap.delete(oldColKey); } } const isNewSizer = refs.colOrderSig === ''; for (let i = 0; i < colKeys.length; i++) { const colKey = colKeys[i]; let entry = refs.cellMap.get(colKey); if (!entry) { const created = STEP_COLUMN_REGISTRY[colKey].createCell(); const innerEl = h('div', { className: 'step-vsizer-inner' }); while (created.td.firstChild) { innerEl.appendChild(created.td.firstChild); } created.td.appendChild(innerEl); entry = { td: created.td, refs: created.refs, innerEl }; refs.cellMap.set(colKey, entry); } if (isNewSizer) { tr.appendChild(entry.td); } else { const currentTd = tr.children[i] || null; if (currentTd !== entry.td) tr.insertBefore(entry.td, currentTd); } } refs.colOrderSig = colOrderSig; } for (const colKey of colKeys) { const entry = refs.cellMap.get(colKey); const probeStep = spec.colSteps[colKey] || tableSteps[0]; if (entry && probeStep) { STEP_COLUMN_REGISTRY[colKey].updateCell(entry.refs, probeStep, cellCtx); } } const firstColKey = colKeys[0]; const firstInner = firstColKey ? refs.cellMap.get(firstColKey)?.innerEl || null : null; const showSizerBadge = Boolean(showAgentBadge && firstInner && spec.badgeText); if (showSizerBadge && !refs.agentBadgeEl) { refs.agentBadgeEl = h('span', { className: 'agent-badge', style: 'margin-right: 4px;' }); } if (firstInner && refs.agentBadgeEl) { if (refs.agentBadgeEl.parentNode !== firstInner || firstInner.firstChild !== refs.agentBadgeEl) { firstInner.insertBefore(refs.agentBadgeEl, firstInner.firstChild); } patchAttr(refs.agentBadgeEl, 'hidden', !showSizerBadge); if (showSizerBadge) { patchAttr(refs.agentBadgeEl, 'class', `agent-badge ${spec.badgeClass || ''}`.trim()); patchText(refs.agentBadgeEl, spec.badgeText); } } return; } if (item.isSpacer) { patchAttr(refs.td, 'colspan', String(item.colSpan)); if (refs.td?.style) { refs.td.style.height = `${item.height}px`; } return; } const { st, hasTurn, hasUp, hasDown, isStart, isLatest, prompt } = item; patchClasses(tr, { 'is-stripe-even': Boolean(isVirtualized && item.isStripeEven) }); if (tr.dataset) { tr.dataset.hasReason = item.hasReason ? '1' : '0'; } if (refs.colOrderSig !== colOrderSig) { if (refs.hoverTd) { clearCellHover(refs.hoverTd); refs.hoverTd = null; } clearRowTimingHovers(refs); for (const [oldColKey, entry] of refs.cellMap) { if (!wantedSet.has(oldColKey)) { if (refs.railEl?.parentNode === entry.td) { entry.td.removeChild(refs.railEl); } if (refs.agentBadgeEl?.parentNode === entry.td) { entry.td.removeChild(refs.agentBadgeEl); } tr.removeChild(entry.td); refs.cellMap.delete(oldColKey); } } const isNewRow = refs.colOrderSig === ''; for (let i = 0; i < colKeys.length; i++) { const colKey = colKeys[i]; let cell = refs.cellMap.get(colKey); if (!cell) { cell = STEP_COLUMN_REGISTRY[colKey].createCell(); refs.cellMap.set(colKey, cell); } if (isNewRow) { tr.appendChild(cell.td); } else { const currentTd = tr.children[i] || null; if (currentTd !== cell.td) tr.insertBefore(cell.td, currentTd); } } refs.colOrderSig = colOrderSig; } for (const colKey of colKeys) { const cellEntry = refs.cellMap.get(colKey); STEP_COLUMN_REGISTRY[colKey].updateCell(cellEntry.refs, st, cellCtx); } const firstColKey = colKeys[0]; const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null; const showRowRail = Boolean(hasTurn && firstTd); if (showRowRail && !refs.railEl) { refs.railEl = h('span', { className: 'turn-rail', 'aria-hidden': 'true' }); } if (showAgentBadge && firstTd && !refs.agentBadgeEl) { refs.agentBadgeEl = h('span', { className: 'agent-badge', style: 'margin-right: 4px;' }); } if (firstTd) { if (refs.railEl && (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl)) { firstTd.insertBefore(refs.railEl, firstTd.firstChild); } const afterRail = refs.railEl ? refs.railEl.nextSibling ?? firstTd.children[1] ?? null : firstTd.firstChild; if ( refs.agentBadgeEl && (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) ) { firstTd.insertBefore(refs.agentBadgeEl, afterRail); } } patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge || !firstTd); if (showAgentBadge && firstTd) { const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : ''; patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`); const badgeText = formatAgentBadgeText({ agentKind: st.agentKind || (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), agentOrdinal: st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), isMain: !st.isSubagent, isSideQuestion: Boolean(st.isSideQuestion), sideIndex: st.sideIndex || 0, index: st.agentIndex || 0, badgeText: st.agentBadge, }); patchText(refs.agentBadgeEl, badgeText); if (interactiveBadges && onSelectAgentScopes) { const targetScope = st.agentId || 'main'; const isSoleTarget = effectiveScopes.length === 1 && effectiveScopes[0] === targetScope; const agentName = formatAgentLabel({ agentKind: st.agentKind || (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), agentOrdinal: st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), customRole: st.agentCustomRole, isMain: !st.isSubagent, isSideQuestion: Boolean(st.isSideQuestion), sideIndex: st.sideIndex || 0, index: st.agentIndex || 0, role: st.agentRole || '', shortLabel: st.agentLabel || '', }); patchAttr( refs.agentBadgeEl, 'title', isSoleTarget ? t('steps.badgeBackAll') : t('steps.badgeFilterAgent', { agent: agentName }) ); refs.agentBadgeEl.onclick = (e) => { e?.stopPropagation?.(); if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') { const next = effectiveScopes.includes(targetScope) ? effectiveScopes.filter((id) => id !== targetScope) : [...effectiveScopes, targetScope]; onSelectAgentScopes(next.length > 0 ? next : ['all']); } else { onSelectAgentScopes(isSoleTarget ? ['all'] : [targetScope]); } }; } else { patchAttr(refs.agentBadgeEl, 'title', null); refs.agentBadgeEl.onclick = null; } } else if (refs.agentBadgeEl) { refs.agentBadgeEl.onclick = null; } const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0); const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger'); const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger); const isCompactionRow = isCompactionStepItem(st); const hasRowTip = hasStepAnomaly || isCompactionRow; const rowDiagGetter = hasRowTip ? () => buildStepRowDiagnostic(st, cellCtx.displaySettings, hasStepAnomaly, isCompactionRow) : null; patchClasses(tr, { 'is-compaction': isCompactionRow, 'is-anomaly-warn': isAnomalyWarn, 'is-anomaly-danger': isAnomalyDanger, }); if (hasRowTip) { const anchorEl = firstTd || tr; tr.onmouseenter = () => { showAnomalyTip(anchorEl, rowDiagGetter()); }; tr.onmouseleave = hideAnomalyTip; } else { tr.onmouseenter = null; tr.onmouseleave = null; } patchAttr(refs.railEl, 'hidden', !showRowRail); if (showRowRail) { const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : ''; patchAttr( refs.railEl, 'class', `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}` ); } const hasTimingTip = hasStepTimingData(st); const timingDiagGetter = hasTimingTip ? () => buildStepTimingDiagnostic(st) : null; const isFirstTimingCol = firstColKey === 'ttft' || firstColKey === 'duration'; const hoverTd = showRowRail && prompt ? firstTd : null; if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd); refs.hoverTd = hoverTd; if (hoverTd) { hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt, rowAnchorEl: firstTd || tr, rowDiagGetter, timingDiagGetter: isFirstTimingCol ? timingDiagGetter : null, tr, }); const useWholeCellTurnTip = firstColKey === 'step' && !hasRowTip; hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null; hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail; hoverTd.onmouseleave = leaveStepCell; } if (!refs.timingHoverTds) refs.timingHoverTds = new Set(); const nextTimingTds = new Set(); if (timingDiagGetter) { for (const timingColKey of ['ttft', 'duration']) { const timingTd = refs.cellMap.get(timingColKey)?.td || null; if (!timingTd || timingTd === hoverTd) continue; nextTimingTds.add(timingTd); timingHoverRows.set(timingTd, { tr, rowAnchorEl: firstTd || tr, rowDiagGetter, timingDiagGetter, }); timingTd.onmouseenter = enterTimingCell; timingTd.onmouseleave = leaveTimingCell; } } for (const prevTd of refs.timingHoverTds) { if (!nextTimingTds.has(prevTd)) { clearTimingCellHover(prevTd); } } refs.timingHoverTds = nextTimingTds; 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) => { if (refs?.hoverTd) { clearCellHover(refs.hoverTd); refs.hoverTd = null; } clearRowTimingHovers(refs); clearRowEnterState(tr); if (!refs?.isSpacer && !refs?.isSizer && tr) { patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false, 'is-compaction': false, 'is-anomaly-warn': false, 'is-anomaly-danger': false, }); tr.onmouseenter = null; tr.onmouseleave = null; if (refs.agentBadgeEl) { refs.agentBadgeEl.onclick = null; } if (rowPool.length < MAX_ROW_POOL_SIZE) { rowPool.push({ el: tr, refs }); } } }, }); renderedSliceStart = startIdx; renderedSliceEnd = endIdx; renderedTopSpacerH = topSpacerH; renderedBottomSpacerH = bottomSpacerH; if (isVirtualized) { scheduleCalibrateRowHeights(); } } function refreshViewport() { if (!activeDataset?.isVirtualized) return; const scaleChanged = syncFontScaleIfChanged(); const paneW = Number(stepsTablePane.clientWidth || 0); if (lockedColKey && paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1) { unlockColumnWidths(); } renderCurrentWindow({ force: scaleChanged, enteringRowKeys: null }); scheduleCalibrateRowHeights(); } function onPaneScroll() { hideTurnTip(); hideAnomalyTip(); if (!activeDataset?.isVirtualized) return; if (typeof requestAnimationFrame === 'function') { if (scrollRafId) return; scrollRafId = requestAnimationFrame(() => { scrollRafId = 0; renderCurrentWindow({ force: false, enteringRowKeys: null }); }); } else { renderCurrentWindow({ force: false, enteringRowKeys: null }); } } function onTbodyLeave() { hideTurnTip(); hideAnomalyTip(); } stepsTablePane.addEventListener('scroll', onPaneScroll, { passive: true }); stepsTbody.addEventListener('mouseleave', onTbodyLeave); let paneResizeObs = null; if (typeof ResizeObserver === 'function') { paneResizeObs = new ResizeObserver(() => { if (!activeDataset?.isVirtualized) return; refreshViewport(); }); paneResizeObs.observe(stepsTablePane); } function renderStepTable( tableSteps, cascadeId, colKeys, locale, { effectiveScopes = ['all'], hasSubagents = false, isMergedMultiAgents = false, showStepTurnRail = false, showStepAgentBadge = true, showStepSpeedColor = false, stepTokenComboFormat = undefined, displaySettings = {}, allConversationSteps = null, allowNewRowFade = false, sortKey = '', sortDir = '', } = {} ) { const normCascadeId = String(cascadeId || ''); let enteringRowKeys = null; if (!normCascadeId || trackedCascadeId === null || normCascadeId !== trackedCascadeId) { trackedCascadeId = normCascadeId || null; lastAbsorbedAllSteps = null; seenStepKeys.clear(); maxSeenStepByAgent.clear(); if (allConversationSteps && allConversationSteps !== tableSteps) { absorbStepsIntoBaseline(allConversationSteps, normCascadeId); lastAbsorbedAllSteps = allConversationSteps; } absorbStepsIntoBaseline(tableSteps, normCascadeId); } else if (!allowNewRowFade || standalone) { if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { absorbStepsIntoBaseline(allConversationSteps, normCascadeId); lastAbsorbedAllSteps = allConversationSteps; } if (tableSteps !== lastRenderedRows) { absorbStepsIntoBaseline(tableSteps, normCascadeId); } } else if (tableSteps !== lastRenderedRows) { let pendingMaxByAgent = null; for (const st of tableSteps) { if (!st || typeof st !== 'object') continue; const { agentKey, stepNum, rowKey } = getStepRowIdentity(st, normCascadeId); if (!seenStepKeys.has(rowKey)) { seenStepKeys.add(rowKey); const prevMax = maxSeenStepByAgent.get(agentKey); if (prevMax === undefined || !Number.isFinite(stepNum) || stepNum > prevMax) { enteringRowKeys ??= new Set(); enteringRowKeys.add(rowKey); } if (Number.isFinite(stepNum)) { const curPending = pendingMaxByAgent?.get(agentKey); if (curPending === undefined || stepNum > curPending) { pendingMaxByAgent ??= new Map(); pendingMaxByAgent.set(agentKey, stepNum); } } } } if (pendingMaxByAgent) { for (const [agentKey, maxStep] of pendingMaxByAgent) { const prevMax = maxSeenStepByAgent.get(agentKey); if (prevMax === undefined || maxStep > prevMax) { maxSeenStepByAgent.set(agentKey, maxStep); } } } if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { absorbStepsIntoBaseline(allConversationSteps, normCascadeId); lastAbsorbedAllSteps = allConversationSteps; } } else if (allConversationSteps && allConversationSteps !== lastAbsorbedAllSteps && allConversationSteps !== tableSteps) { absorbStepsIntoBaseline(allConversationSteps, normCascadeId); lastAbsorbedAllSteps = allConversationSteps; } const colOrderSig = colKeys.join(','); const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat); const normSortKey = String(sortKey || ''); const normSortDir = sortDir === 'asc' || sortDir === 'desc' ? sortDir : ''; const isCustomSorted = Boolean(normSortKey && normSortDir); const effectiveTurnRail = Boolean(showStepTurnRail && !isCustomSorted); const renderOptions = JSON.stringify([ cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents, effectiveTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt, displaySettings.modelDisplayMode, displaySettings.showUpstreamModel, displaySettings.orchestratorIdMode, normSortKey, normSortDir, ]); if ( lastRenderOptions === renderOptions && lastRenderedRows && (lastRenderedRows === tableSteps || (lastRenderedRows.length === tableSteps.length && tableSteps.every((step, i) => step === lastRenderedRows[i]))) ) { if (activeDataset?.isVirtualized) { refreshViewport(); } return; } syncFontScaleIfChanged(); const wantedSet = new Set(colKeys); syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt, sortKey: normSortKey, sortDir: normSortDir, }); const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge); const cellCtx = { hasSubagents, showAgentBadge, showStepSpeedColor, stepTokenComboFormat: normTokenFmt, effectiveScopes, scopeSigKey: effectiveScopes.join(','), displaySettings, onSelectAgentScopes, }; const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents); let railActive = false; if (effectiveTurnRail) { for (let i = 0; i < tableSteps.length; i++) { const st = tableSteps[i]; const tIdx = useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex; if (Number.isInteger(tIdx) && tIdx > 0) { railActive = true; break; } } } if (!railActive) { hideTurnTip(); } const isVirtualized = !standalone && tableSteps.length > VIRTUAL_ROW_THRESHOLD; patchClasses(stepsTableEl, { 'has-turn-rail': railActive, 'is-virtualized': isVirtualized, }); let hasReasonFlags = null; let hasAnyReason = false; let rowTops = null; let totalBodyH = 0; let sizerSpec = null; if (isVirtualized) { const hasTpsCol = wantedSet.has('tps'); if (hasTpsCol) { hasReasonFlags = new Uint8Array(tableSteps.length); for (let i = 0; i < tableSteps.length; i++) { const rawReason = tableSteps[i]?.selectedSpeedReason; if (rawReason && speedReasonText(rawReason)) { hasReasonFlags[i] = 1; hasAnyReason = true; } } } const built = buildRowTops(tableSteps.length, hasReasonFlags); rowTops = built.rowTops; totalBodyH = built.totalBodyH; sizerSpec = buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx); } activeDataset = { tableSteps, cascadeId, colKeys, wantedSet, colOrderSig, locale, cellCtx, railActive, showAgentBadge, showStepTurnRail: effectiveTurnRail, useRootTurn, isVirtualized, hasReasonFlags, hasAnyReason, rowTops, totalBodyH, sizerSpec, effectiveScopes, sortKey: normSortKey, sortDir: normSortDir, formattedPrompts: new Map(), }; if (!isVirtualized || computeColLockKey(activeDataset) !== lockedColKey) { unlockColumnWidths(); } renderedSliceStart = -1; renderedSliceEnd = -1; renderedTopSpacerH = -1; renderedBottomSpacerH = -1; renderCurrentWindow({ force: true, enteringRowKeys }); lastRenderOptions = renderOptions; lastRenderedRows = tableSteps; } onCleanup(() => { stepsTablePane.removeEventListener('scroll', onPaneScroll); stepsTbody.removeEventListener('mouseleave', onTbodyLeave); if (scrollRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(scrollRafId); scrollRafId = 0; } if (calibrateRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(calibrateRafId); calibrateRafId = 0; } paneResizeObs?.disconnect(); paneResizeObs = null; rowPool.length = 0; for (const tr of [...activeEnterTimers.keys()]) { clearRowEnterState(tr); } }); return { el: standaloneHostEl || stepsTablePane, refs: { stepsTablePane, stepsTableEl, stepsTheadRow, stepsTbody, turnTipEl, anomalyTipEl, syncTableHeaderColumns, renderStepTable, refreshViewport, hideTurnTip, showAnomalyTip, hideAnomalyTip, setBoundsElGetter, }, }; }, }); return { formatTurnPromptText, StepTableWidget }; })(); // --- src/components/widgets/ConsumptionBreakdownRows.js --- const { partitionModelSegments, createBreakdownItemRow, updateBreakdownItemRow, createConsumptionBreakdownRowBuilders } = (() => { /** * @fileoverview Reusable model, client-source, workspace, and top-conversation breakdown * row builders (`ConsumptionBreakdownRows.js`) extracted from `ConsumptionView.js`. * Consolidates shared long-tail model partitioning, hover-popover event binding, and top-model pill rendering. */ function createSourceModelSegment() { const segEl = h('div', { className: 'progress-seg cons-model-seg' }); return { el: segEl, refs: { segEl } }; } function createSourceTopModelItem() { const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' }); const nameEl = h('span', { className: 'cons-source-top-name' }); const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' }); const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]); return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } }; } function formatCompactSourceSharePct(pct) { const num = Number(pct || 0); if (!Number.isFinite(num) || num <= 0) return '0%'; if (num >= 10) return `${Math.round(num)}%`; return `${num.toFixed(1)}%`; } function renderSegmentedModelBarAndTopPills( trackEl, topModelsEl, partitioned, scaleRatio, fallbackKey ) { const barItems = partitioned.length > 0 ? partitioned.map((seg) => ({ key: seg.key, segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, color: seg.color, })) : scaleRatio > 0 ? [ { key: fallbackKey, segPct: scaleRatio * 100, color: 'var(--accent-primary)', }, ] : []; patchKeyedList(trackEl, barItems, { keyFn: (seg) => seg.key, sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, createRow: createSourceModelSegment, updateRow: (segRefs, seg) => { patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); patchStyleVar(segRefs.segEl, '--seg-color', seg.color); }, }); const topModels = partitioned .filter((seg) => !seg.isOther) .slice(0, 3) .map((seg) => ({ key: seg.key, label: seg.label, pctText: formatCompactSourceSharePct(seg.pct), color: seg.color, })); patchAttr(topModelsEl, 'hidden', topModels.length === 0); patchKeyedList(topModelsEl, topModels, { keyFn: (m) => m.key, sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, createRow: createSourceTopModelItem, updateRow: (mRefs, m) => { patchStyleVar(mRefs.dotEl, '--dot-color', m.color); patchText(mRefs.nameEl, m.label); patchText(mRefs.pctEl, m.pctText); patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); }, }); return topModels; } /** * Collapses long-tail model entries into primary segments + an aggregated "Other (N)" tail. */ function partitionModelSegments( mergedModels, modelColorMap, { maxMain = 5, minSharePct = 1.5 } = {} ) { if (!Array.isArray(mergedModels) || mergedModels.length === 0) return []; const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); const mainModels = []; const tailModels = []; for (let i = 0; i < mergedModels.length; i += 1) { const m = mergedModels[i]; const mTok = Number(m.totalTokens || 0); const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0; if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) { mainModels.push(m); } else { tailModels.push(m); } } if (tailModels.length === 1) { mainModels.push(tailModels.pop()); } const out = mainModels.map((m) => { const seed = getCanonicalModelColorSeed(m); const color = modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText); const tok = Number(m.totalTokens || 0); const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0; const label = m.displayText || m.label || m.shortName || '—'; const inputTokens = Math.max(0, Number(m.inputTokens || 0)); const cacheReadTokens = Math.max(0, Number(m.cacheReadTokens || 0)); const thinkingTokens = Math.max(0, Number(m.thinkingTokens || 0)); const responseTokens = m.responseTokens != null ? Math.max(0, Number(m.responseTokens)) : Math.max(0, Number(m.outputTokens || 0) - thinkingTokens); return { key: label, label, tok, pct, inputTokens, cacheReadTokens, thinkingTokens, responseTokens, outputTokens: responseTokens + thinkingTokens, tokText: formatTokensPrecise(tok), pctText: formatPctNumber(pct, { withSymbol: true }), color, isOther: false, }; }); if (tailModels.length >= 2) { let otherTok = 0; let otherIn = 0; let otherCache = 0; let otherThink = 0; let otherResp = 0; for (const m of tailModels) { const mt = Math.max(0, Number(m.thinkingTokens || 0)); const mr = m.responseTokens != null ? Math.max(0, Number(m.responseTokens)) : Math.max(0, Number(m.outputTokens || 0) - mt); otherTok += Number(m.totalTokens || 0); otherIn += Math.max(0, Number(m.inputTokens || 0)); otherCache += Math.max(0, Number(m.cacheReadTokens || 0)); otherThink += mt; otherResp += mr; } const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0; const otherLabel = t('cons.otherModelsCount', { count: tailModels.length }); out.push({ key: '__other__', label: otherLabel, tok: otherTok, pct: otherPct, inputTokens: otherIn, cacheReadTokens: otherCache, thinkingTokens: otherThink, responseTokens: otherResp, outputTokens: otherResp + otherThink, tokText: formatTokensPrecise(otherTok), pctText: formatPctNumber(otherPct, { withSymbol: true }), color: 'var(--cons-other-seg)', isOther: true, }); } return out; } /** * Creates a model ranking row (`tokens` | `cost` | `speed` | `calls` sort modes). */ function createBreakdownItemRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const segBar = createFourSegmentBar(); const inLbl = h('span', { text: t('cons.footInput') }); const cacheLbl = h('span', { text: t('cons.footCache') }); const outLbl = h('span', { text: t('cons.footOutput') }); const thinkLbl = h('span', { text: t('cons.footThinking') }); const callsLbl = h('span', { text: t('cons.footCalls') }); const inVal = h('strong', { className: 'text-mono' }); const cacheVal = h('strong', { className: 'text-mono' }); const outVal = h('strong', { className: 'text-mono' }); const thinkVal = h('strong', { className: 'text-mono' }); const callsVal = h('strong', { className: 'text-mono' }); const metricBarFillEl = h('div', { className: 'progress-seg cons-metric-fill' }); const metricBarEl = h( 'div', { className: 'progress-track cons-seg-bar cons-metric-bar', hidden: true }, [metricBarFillEl] ); const tokenFootEl = h('div', { className: 'cons-item-foot' }, [ h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-input' }), inLbl, inVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-cached' }), cacheLbl, cacheVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-thinking' }), thinkLbl, thinkVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-output' }), outLbl, outVal, ]), h('span', { className: 'legend-left' }, [callsLbl, callsVal]), ]); const perfMainEl = h('span', { className: 'cons-model-perf-main text-mono' }); const perfUnitCostEl = h('span', { className: 'cons-model-unit-cost text-mono', hidden: true }); const perfFootEl = h('div', { className: 'cons-model-perf-foot', hidden: true }, [ perfMainEl, perfUnitCostEl, ]); const focusLeftEl = h('span', { className: 'cons-model-focus-left text-mono' }); const focusRightEl = h('span', { className: 'cons-model-focus-right text-mono' }); const focusFootEl = h( 'div', { className: 'cons-item-foot cons-model-focus-foot', hidden: true }, [focusLeftEl, focusRightEl] ); const rowEl = h('div', { className: 'cons-item-row' }, [ h('div', { className: 'panel-header' }, [ nameEl, h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), ]), segBar.el, metricBarEl, tokenFootEl, perfFootEl, focusFootEl, ]); return { el: rowEl, refs: { nameEl, nameTextEl, pctBadge, totalTokEl, costEl, segBar, metricBarEl, metricBarFillEl, tokenFootEl, inLbl, cacheLbl, outLbl, thinkLbl, callsLbl, inVal, cacheVal, outVal, thinkVal, callsVal, perfFootEl, perfMainEl, perfUnitCostEl, focusFootEl, focusLeftEl, focusRightEl, }, }; } /** * Incrementally patches a model ranking row. */ function updateBreakdownItemRow(refs, item, totalsCtx, sortMode = 'tokens') { const displayLabel = item.label || item.name || item.shortName || '—'; patchText(refs.nameTextEl, displayLabel); patchAttr(refs.nameEl, 'title', item.title || displayLabel); const total = Number(item.totalTokens || 0); const costVal = Number(item.costUsd || 0); const callsCount = Number(item.calls || 0); const isAllUnpriced = callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); const costText = formatUsd(isAllUnpriced ? null : costVal, { precise: costVal > 0 && costVal < 0.1, }); const avgTps = item.avgTokPerSec != null && Number.isFinite(Number(item.avgTokPerSec)) && Number(item.avgTokPerSec) > 0 ? Number(item.avgTokPerSec) : null; const avgTtft = item.avgTtftSec != null && Number.isFinite(Number(item.avgTtftSec)) && Number(item.avgTtftSec) >= 0 ? Number(item.avgTtftSec) : null; const hasExplicitCachePct = item.cacheHitPct != null && Number.isFinite(Number(item.cacheHitPct)); const promptTok = Number(item.inputTokens || 0) + Number(item.cacheReadTokens || 0); const cachePctVal = hasExplicitCachePct ? Number(item.cacheHitPct) : promptTok > 0 && Number(item.cacheReadTokens || 0) > 0 ? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1) : 0; const cachePctStr = formatPctNumber(cachePctVal); const effCostPer1M = !isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null; const outTok = Number( item.outputTokens ?? Number(item.responseTokens || 0) + Number(item.thinkingTokens || 0) ); if (sortMode === 'cost') { const costBase = Number(totalsCtx?.totalCost || 0); const costShare = costBase > 0 ? +((costVal / costBase) * 100).toFixed(1) : 0; const barPct = costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true })); patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal)); patchText(refs.costEl, costText); patchAttr(refs.segBar.el, 'hidden', true); patchAttr(refs.metricBarEl, 'hidden', false); patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); patchClasses(refs.metricBarFillEl, { 'tone-cost': true, 'tone-speed': false, 'tone-calls': false, }); patchAttr(refs.tokenFootEl, 'hidden', true); patchAttr(refs.perfFootEl, 'hidden', true); patchAttr(refs.focusFootEl, 'hidden', false); const unitPart = effCostPer1M !== null ? t('cons.modelUnitCost', { cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), }) : ''; const cachePart = t('cons.topConvCacheMeta', { pct: cachePctStr }); patchText(refs.focusLeftEl, unitPart ? `${unitPart} · ${cachePart}` : cachePart); patchText( refs.focusRightEl, `${formatTokensPrecise(total)} · ${t('cons.callsCount', { calls: callsCount })}` ); return; } if (sortMode === 'speed') { const maxTps = Number(totalsCtx?.maxAvgTps || 0); const speedPct = maxTps > 0 && avgTps !== null ? Math.min(100, Math.max(2, (avgTps / maxTps) * 100)) : 0; patchAttr(refs.pctBadge, 'hidden', avgTps === null); patchAttr(refs.pctBadge, 'title', avgTps !== null ? t('cons.speedRelTip') : null); patchText(refs.pctBadge, avgTps !== null ? `${Math.round(speedPct)}%` : ''); patchText( refs.totalTokEl, avgTtft !== null ? t('cons.focusTtft', { ttft: formatMetric(avgTtft, 's') }) : '' ); patchText(refs.costEl, formatSpeedMetric(avgTps, ' tok/s')); patchAttr(refs.segBar.el, 'hidden', true); patchAttr(refs.metricBarEl, 'hidden', false); patchStyleVar(refs.metricBarFillEl, '--seg-w', `${speedPct.toFixed(2)}%`); patchClasses(refs.metricBarFillEl, { 'tone-cost': false, 'tone-speed': true, 'tone-calls': false, }); patchAttr(refs.tokenFootEl, 'hidden', true); patchAttr(refs.perfFootEl, 'hidden', true); patchAttr(refs.focusFootEl, 'hidden', false); patchText( refs.focusLeftEl, t('cons.focusSpeedMeta', { ttft: formatMetric(avgTtft, 's'), cache: cachePctStr, out: formatTokensPrecise(outTok), }) ); patchText(refs.focusRightEl, t('cons.callsCount', { calls: callsCount })); return; } if (sortMode === 'calls') { const callsBase = Number(totalsCtx?.totalCalls || 0); const callsShare = callsBase > 0 ? +((callsCount / callsBase) * 100).toFixed(1) : 0; const barPct = callsBase > 0 && callsCount > 0 ? Math.min(100, Math.max(1, (callsCount / callsBase) * 100)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); patchText(refs.costEl, t('cons.callsCount', { calls: callsCount })); patchAttr(refs.segBar.el, 'hidden', true); patchAttr(refs.metricBarEl, 'hidden', false); patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); patchClasses(refs.metricBarFillEl, { 'tone-cost': false, 'tone-speed': false, 'tone-calls': true, }); patchAttr(refs.tokenFootEl, 'hidden', true); patchAttr(refs.perfFootEl, 'hidden', true); patchAttr(refs.focusFootEl, 'hidden', false); const avgPerCall = callsCount > 0 ? total / callsCount : 0; patchText( refs.focusLeftEl, t('cons.focusCallsMeta', { avgTok: formatTokensPrecise(avgPerCall), cost: costText, }) ); patchText(refs.focusRightEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); return; } patchText(refs.inLbl, t('cons.footInput')); patchText(refs.cacheLbl, t('cons.footCache')); patchText(refs.outLbl, t('cons.footOutput')); patchText(refs.thinkLbl, t('cons.footThinking')); patchText(refs.callsLbl, t('cons.footCalls')); const grandTotalTokens = Number(totalsCtx?.totalTokens || 0); const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; const scaleRatio = grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); patchText(refs.costEl, costText); const responseTok = item.responseTokens != null ? Number(item.responseTokens) : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); const thinkingTok = Number(item.thinkingTokens || 0); patchAttr(refs.segBar.el, 'hidden', false); patchAttr(refs.metricBarEl, 'hidden', true); refs.segBar.update({ inputTokens: Number(item.inputTokens || 0), cacheReadTokens: Number(item.cacheReadTokens || 0), responseTokens: responseTok, thinkingTokens: thinkingTok, scaleRatio, }); patchAttr(refs.tokenFootEl, 'hidden', false); patchAttr(refs.focusFootEl, 'hidden', true); patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); patchText(refs.outVal, formatTokensPrecise(responseTok)); patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); patchText(refs.callsVal, String(callsCount)); const hasPerfMeta = avgTps !== null || avgTtft !== null || effCostPer1M !== null; patchAttr(refs.perfFootEl, 'hidden', !hasPerfMeta); if (hasPerfMeta) { if (avgTps !== null || avgTtft !== null) { patchText( refs.perfMainEl, t('steps.modelPerfFoot', { tps: formatSpeedMetric(avgTps, ' tok/s'), ttft: formatMetric(avgTtft, 's'), cache: cachePctStr, }) ); } else { patchText(refs.perfMainEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); } patchAttr(refs.perfUnitCostEl, 'hidden', effCostPer1M === null); patchText( refs.perfUnitCostEl, effCostPer1M !== null ? t('cons.modelUnitCost', { cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), }) : '' ); } } /** * Binds shared popover hover callbacks to build source-breakdown and workspace/conversation rows. */ function createConsumptionBreakdownRowBuilders({ showPopover, movePopover, hidePopover, isHoveredTarget, onSelectConversation, }) { function isNodeInside(root, node) { if (!root || !node) return false; if (typeof root.contains === 'function') return root.contains(node); let cur = node; while (cur) { if (cur === root) return true; cur = cur.parentNode || null; } return false; } function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) { zoneEl.addEventListener('mouseenter', (e) => { if (rowState.hoverPayload) { showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); } }); zoneEl.addEventListener('mousemove', (e) => { if (rowState.hoverPayload && isHoveredTarget(zoneEl)) { movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); } }); zoneEl.addEventListener('mouseleave', () => { if (isHoveredTarget(zoneEl)) hidePopover(); }); for (const childEl of compatTargets) { if (!childEl) continue; childEl.addEventListener('mouseenter', (e) => { if (rowState.hoverPayload) { showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); } }); childEl.addEventListener('mousemove', (e) => { if (rowState.hoverPayload && isHoveredTarget(zoneEl)) { movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); } }); childEl.addEventListener('mouseleave', (e) => { const nextEl = e?.relatedTarget || null; if (isNodeInside(zoneEl, nextEl)) { return; } if (isHoveredTarget(zoneEl)) hidePopover(); }); } } function createSourceBreakdownRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { hoverPayload: null }; const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ barHitEl, h('div', { className: 'cons-item-foot cons-source-foot' }, [ topModelsEl, h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]), ]), ]); attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ h('div', { className: 'panel-header' }, [ nameEl, h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), ]), hoverZoneEl, ]); return { el: rowEl, refs: { nameEl, nameTextEl, pctBadge, totalTokEl, costEl, hoverZoneEl, barHitEl, trackEl, topModelsEl, callsLbl, callsVal, rowState, }, }; } function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) { patchText(refs.callsLbl, t('cons.footCalls')); const displayLabel = item.label || item.name || '—'; patchText(refs.nameTextEl, displayLabel); patchAttr(refs.nameEl, 'title', item.title || displayLabel); const total = Number(item.totalTokens || 0); const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; const scaleRatio = grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); const costVal = Number(item.costUsd || 0); const callsCount = Number(item.calls || 0); const isAllUnpriced = callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); const costText = formatUsd(isAllUnpriced ? null : costVal, { precise: costVal > 0 && costVal < 0.1, }); patchText(refs.costEl, costText); patchText(refs.callsVal, String(callsCount)); const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; const partitioned = partitionModelSegments(sourceModels, modelColorMap, { maxMain: 5, minSharePct: 1.5, }); renderSegmentedModelBarAndTopPills( refs.trackEl, refs.topModelsEl, partitioned, total > 0 ? scaleRatio : 0, '__source_fallback__' ); refs.rowState.hoverPayload = total > 0 || callsCount > 0 ? { title: displayLabel, calls: callsCount, totalTokens: total, costText, inputTokens: item.inputTokens, cacheReadTokens: item.cacheReadTokens, thinkingTokens: item.thinkingTokens, responseTokens: item.responseTokens, outputTokens: item.outputTokens, segments: partitioned, } : null; patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); } function createTopConversationRow() { const titleTextEl = h('span', { className: 'cons-row-title-text' }); const wsBadgeEl = h('span', { className: 'cons-ws-sessions-tag text-mono', hidden: true }); const titleEl = h('strong', { className: 'cons-row-title cons-top-conv-title' }, [ titleTextEl, wsBadgeEl, ]); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { cascadeId: '', canJump: false, hoverPayload: null }; const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true }); const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ barHitEl, h('div', { className: 'cons-item-foot cons-source-foot' }, [ topModelsEl, fallbackMetaEl, h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]), ]), ]); attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); const rowEl = h( 'div', { className: 'cons-top-conv-row', onClick: () => { if (!rowState.canJump || !rowState.cascadeId) return; hidePopover(); onSelectConversation?.(rowState.cascadeId); }, }, [ h('div', { className: 'panel-header' }, [ titleEl, h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), ]), hoverZoneEl, ] ); return { el: rowEl, refs: { rowEl, titleEl, titleTextEl, wsBadgeEl, pctBadge, totalTokEl, costEl, hoverZoneEl, barHitEl, trackEl, topModelsEl, fallbackMetaEl, callsLbl, callsVal, rowState, }, }; } function updateTopConversationRow(refs, item, bases, modelColorMap, sortMode = 'cost') { patchText(refs.callsLbl, t('cons.footCalls')); const isWorkspaceRow = Boolean(item.isWorkspaceRow); const title = isWorkspaceRow ? item.isUnbound ? t('cons.workspaceUnbound') : String(item.label || item.workspacePath || '—').trim() : String(item.title || item.cascadeId || '—').trim(); refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || ''); refs.rowState.canJump = !isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId); patchClasses(refs.rowEl, { 'is-jumpable': refs.rowState.canJump, 'cons-workspace-row': isWorkspaceRow, }); const baseTip = isWorkspaceRow && item.workspacePath && item.workspacePath !== title ? `${title} (${item.workspacePath})` : title; patchAttr( refs.rowEl, 'title', refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip ); patchText(refs.titleTextEl, title); if (refs.wsBadgeEl) { const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0; patchAttr(refs.wsBadgeEl, 'hidden', !showWsBadge); if (showWsBadge) { patchText(refs.wsBadgeEl, t('cons.workspaceSessions', { count: item.sessionCount })); } } const total = Number(item.totalTokens || 0); const costVal = Number(item.costUsd || 0); const callsCount = Number(item.calls || 0); const isAllUnpriced = callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); const costText = formatUsd(isAllUnpriced ? null : costVal, { precise: costVal > 0 && costVal < 0.1, }); const tokBase = Number(bases?.tokens || 0); const costBase = Number(bases?.cost || 0); const useCostBasis = sortMode === 'cost' && costBase > 0; const share = useCostBasis ? +((costVal / costBase) * 100).toFixed(1) : tokBase > 0 ? +((total / tokBase) * 100).toFixed(1) : 0; const scaleRatio = useCostBasis ? costVal > 0 ? Math.min(1, Math.max(0.01, costVal / costBase)) : 0 : tokBase > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / tokBase)) : 0; patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); if (sortMode === 'tokens') { patchText(refs.totalTokEl, costText); patchText(refs.costEl, formatTokensPrecise(total)); } else { patchText(refs.totalTokEl, formatTokensPrecise(total)); patchText(refs.costEl, costText); } patchText(refs.callsVal, String(callsCount)); const convModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; const partitioned = partitionModelSegments(convModels, modelColorMap, { maxMain: 5, minSharePct: 1.5, }); const topModels = renderSegmentedModelBarAndTopPills( refs.trackEl, refs.topModelsEl, partitioned, scaleRatio, '__conv_fallback__' ); const showFallbackMeta = topModels.length === 0; patchAttr(refs.fallbackMetaEl, 'hidden', !showFallbackMeta); if (showFallbackMeta) { const srcLabel = item.sourceName || item.appSource || ''; const cacheLabel = t('cons.topConvCacheMeta', { pct: formatPctNumber(item.cacheHitPct ?? 0), }); patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel); } refs.rowState.hoverPayload = partitioned.length > 0 && (total > 0 || callsCount > 0) ? { title, calls: callsCount, totalTokens: total, costText, inputTokens: item.inputTokens, cacheReadTokens: item.cacheReadTokens, thinkingTokens: item.thinkingTokens, responseTokens: item.responseTokens, outputTokens: item.outputTokens, segments: partitioned, } : null; patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); } return { createSourceBreakdownRow, updateSourceBreakdownRow, createTopConversationRow, updateTopConversationRow, }; } return { partitionModelSegments, createBreakdownItemRow, updateBreakdownItemRow, createConsumptionBreakdownRowBuilders }; })(); // --- src/components/settings/structurePreviewMock.js --- const { buildStructurePreviewTelemetry } = (() => { /** * @fileoverview Realistic Simulated Telemetry Builder (`structurePreviewMock.js`) * for `SettingsStructureTab` real-UI live previews. * Exercises all 13 capsule metrics, 8 overview metrics, 10 context channels + subagents, * multi-pool quotas, live running task + subagent, and 12 step table columns. */ function buildStructurePreviewTelemetry( baseSettings = {}, draftOverrides = {}, { includeArgonPool = false } = {} ) { const anchorMinMs = Math.floor(Date.now() / 60000) * 60000; const reset5hIso = new Date(anchorMinMs + (2 * 60 + 42) * 60000).toISOString(); const resetWkIso = new Date(anchorMinMs + (4 * 24 * 60 + 180) * 60000).toISOString(); const resetClaude5hIso = new Date(anchorMinMs + (1 * 60 + 18) * 60000).toISOString(); const mergedSettings = { ...(baseSettings && typeof baseSettings === 'object' ? baseSettings : {}), ...draftOverrides, }; const sessionTitle = t('settings.mock.sessionTitle'); const subRole = t('settings.mock.subRole'); const promptLatest = t('settings.mock.turnPromptLatest'); const promptPrev = t('settings.mock.turnPromptPrev'); const mainContext = { totalTokens: 142800, limitTokens: 256000, compactionLimitTokens: 256000, compactionUsedTokens: 142800, usedPct: 55.8, messagesTokens: 119660, toolResultsTokens: 86400, assistantTokens: 24200, systemToolsTokens: 11800, checkpointTokens: 7600, systemPromptTokens: 5800, skillsTokens: 3100, userRulesTokens: 1900, userInputTokens: 1120, mcpToolsTokens: 540, subagentTokens: 340, }; const subContext = { totalTokens: 72704, limitTokens: 256000, compactionLimitTokens: 256000, compactionUsedTokens: 72704, usedPct: 28.4, messagesTokens: 63704, toolResultsTokens: 51200, assistantTokens: 11400, systemToolsTokens: 5600, systemPromptTokens: 3400, userInputTokens: 1104, checkpointTokens: 0, skillsTokens: 0, userRulesTokens: 0, mcpToolsTokens: 0, subagentTokens: 0, }; const mockSteps = [ { stepIndex: 24, agentCascadeId: 'mock-main', agentId: 'main', agentIndex: 0, isSubagent: false, agentBadge: '主', agentLabel: t('fmt.mainAgent'), modelLabel: 'Gemini 4 Carbon (High)', modelShort: 'carbon-4-high', rawModel: 'MODEL_PLACEHOLDER_M37', modelUpstream: 'gemini-4-carbon-high', upstreamModel: 'gemini-4-carbon-high', tokPerSec: 68.4, ttftSec: 1.15, totalDurationSec: 12.6, streamDurationSec: 11.45, contextTokens: 142800, inputTokens: 7800, cacheReadTokens: 133580, outputTokens: 1420, thinkingTokens: 860, responseTokens: 560, cacheHitPct: 94.5, costUsd: 0.042, inCostUsd: 0.0156, cacheCostUsd: 0.0134, outCostUsd: 0.0142, createdAtMs: anchorMinMs - 14_000, turnIndex: 2, rootTurnIndex: 2, isTurnStart: false, isRootTurnStart: false, isLatestTurn: true, isRootLatestTurn: true, turnPrompt: promptLatest, rootTurnPrompt: promptLatest, }, { stepIndex: 8, agentCascadeId: 'mock-sub-1', agentId: 'sub-1', agentIndex: 1, isSubagent: true, agentBadge: '子1', agentRole: subRole, agentLabel: subRole, modelLabel: 'Gemini 3.8 Flash', modelShort: 'flash-3.8', rawModel: 'MODEL_PLACEHOLDER_M42', modelUpstream: 'gemini-3.8-flash-n', upstreamModel: 'gemini-3.8-flash-n', tokPerSec: 96.2, ttftSec: 0.68, totalDurationSec: 5.4, streamDurationSec: 4.72, contextTokens: 72704, inputTokens: 8600, cacheReadTokens: 63400, outputTokens: 704, thinkingTokens: 240, responseTokens: 464, cacheHitPct: 88.1, costUsd: 0.009, inCostUsd: 0.0065, cacheCostUsd: 0.0005, outCostUsd: 0.0026, createdAtMs: anchorMinMs - 42_000, turnIndex: 1, rootTurnIndex: 2, isTurnStart: true, isRootTurnStart: false, isLatestTurn: true, isRootLatestTurn: true, turnPrompt: promptLatest, rootTurnPrompt: promptLatest, }, { stepIndex: 22, agentCascadeId: 'mock-main', agentId: 'main', agentIndex: 0, isSubagent: false, agentBadge: '主', agentLabel: t('fmt.mainAgent'), isCompactionStep: true, modelLabel: 'Gemini 4 Carbon (High) [自动压缩]', modelShort: 'carbon-4-high·压缩', rawModel: 'MODEL_PLACEHOLDER_M37', modelUpstream: 'gemini-4-carbon-high·压缩', upstreamModel: 'gemini-4-carbon-high', tokPerSec: 46.5, ttftSec: 3.4, totalDurationSec: 15.8, streamDurationSec: 12.4, contextTokens: 128400, inputTokens: 49200, cacheReadTokens: 78100, outputTokens: 1100, thinkingTokens: 720, responseTokens: 380, cacheHitPct: 61.4, costUsd: 0.068, inCostUsd: 0.0492, cacheCostUsd: 0.0078, outCostUsd: 0.011, createdAtMs: anchorMinMs - 88_000, turnIndex: 2, rootTurnIndex: 2, isTurnStart: true, isRootTurnStart: true, isLatestTurn: true, isRootLatestTurn: true, turnPrompt: promptLatest, rootTurnPrompt: promptLatest, }, { stepIndex: 19, agentCascadeId: 'mock-main', agentId: 'main', agentIndex: 0, isSubagent: false, agentBadge: '主', agentLabel: t('fmt.mainAgent'), modelKey: 'MODEL_PLACEHOLDER_M667', modelLabel: 'Gemini Pro Orchestrator (Carbon)', modelShort: 'orchestrator-carbon', rawModel: 'MODEL_PLACEHOLDER_M667', modelUpstream: 'gemini-pro-orchestrator', upstreamModel: 'gemini-pro-orchestrator', tokPerSec: 17.8, ttftSec: 19.4, totalDurationSec: 31.2, streamDurationSec: 11.8, contextTokens: 96200, inputTokens: 95400, cacheReadTokens: 0, outputTokens: 800, thinkingTokens: 540, responseTokens: 260, cacheHitPct: 0, costUsd: 0.198, inCostUsd: 0.19, cacheCostUsd: 0, outCostUsd: 0.008, createdAtMs: anchorMinMs - 215_000, turnIndex: 1, rootTurnIndex: 1, isTurnStart: true, isRootTurnStart: true, isLatestTurn: false, isRootLatestTurn: false, turnPrompt: promptPrev, rootTurnPrompt: promptPrev, }, ]; const mainAgent = { agentId: 'main', cascadeId: 'mock-main', isMain: true, index: 0, badgeText: '主', role: t('fmt.mainAgent'), isRunning: true, stepCount: 16, speedSampleCount: 15, speedSummary: { sampleCount: 15, excludedCount: 1 }, latestTokPerSec: 68.4, avgTokPerSec: 54.8, latestTtftSec: 1.15, avgTtftSec: 1.62, ttftSummary: { avgSec: 1.62, sampleCount: 15 }, latestStepCostUsd: 0.042, sessionCostUsd: 1.16, latestCacheHitPct: 94.5, sessionCacheHitPct: 89.2, latestPromptTokens: 141380, inputTokens: 152400, cacheReadTokens: 1260000, outputTokens: 22100, totalTokens: 1434500, latestModelLabel: 'Gemini 4 Carbon (High)', latestModelShort: 'carbon-4-high', latestRawModel: 'MODEL_PLACEHOLDER_M37', latestUpstreamModel: 'gemini-4-carbon-high', activeModelLabel: 'Gemini 4 Carbon (High)', activeModelShort: 'carbon-4-high', activeModelUpstream: 'gemini-4-carbon-high', sessionUnpricedCalls: 0, modelBreakdown: [ { modelKey: 'MODEL_PLACEHOLDER_M37', modelShort: 'carbon-4-high', modelLabel: 'Gemini 4 Carbon (High)', modelUpstream: 'gemini-4-carbon-high', upstreamModel: 'gemini-4-carbon-high', calls: 16, inputTokens: 152400, cacheReadTokens: 1260000, outputTokens: 22100, thinkingTokens: 14200, totalTokens: 1434500, costUsd: 1.16, sharePct: 100, }, ], context: mainContext, recentSteps: mockSteps.filter((s) => !s.isSubagent), }; const subAgent1 = { agentId: 'sub-1', cascadeId: 'mock-sub-1', isMain: false, agentKind: 'subagent', agentOrdinal: 1, index: 1, badgeText: '子1', shortLabel: `${t('fmt.subAgent')} #1`, role: subRole, isRunning: false, stepCount: 8, speedSampleCount: 8, speedSummary: { sampleCount: 8, excludedCount: 0 }, latestTokPerSec: 96.2, avgTokPerSec: 88.5, latestTtftSec: 0.68, avgTtftSec: 0.82, ttftSummary: { avgSec: 0.82, sampleCount: 8 }, latestStepCostUsd: 0.009, sessionCostUsd: 0.12, latestCacheHitPct: 88.1, sessionCacheHitPct: 86.4, latestPromptTokens: 72000, inputTokens: 34000, cacheReadTokens: 280000, outputTokens: 6300, totalTokens: 320300, latestModelLabel: 'Gemini 3.8 Flash', latestModelShort: 'flash-3.8', latestRawModel: 'MODEL_PLACEHOLDER_M42', latestUpstreamModel: 'gemini-3.8-flash-n', activeModelLabel: 'Gemini 3.8 Flash', activeModelShort: 'flash-3.8', activeModelUpstream: 'gemini-3.8-flash-n', sessionUnpricedCalls: 0, modelBreakdown: [ { modelKey: 'MODEL_PLACEHOLDER_M42', modelShort: 'flash-3.8', modelLabel: 'Gemini 3.8 Flash', modelUpstream: 'gemini-3.8-flash-n', upstreamModel: 'gemini-3.8-flash-n', calls: 8, inputTokens: 34000, cacheReadTokens: 280000, outputTokens: 6300, thinkingTokens: 2100, totalTokens: 320300, costUsd: 0.12, sharePct: 100, }, ], context: subContext, recentSteps: mockSteps.filter((s) => s.isSubagent), }; const aggregated = { ...mainAgent, agentId: 'all', isMain: false, agentKind: 'all', agentOrdinal: 0, badgeText: t('header.scopeAllShort'), activeAgentId: 'sub-1', activeAgentKind: 'subagent', activeAgentOrdinal: 1, stepCount: 24, speedSampleCount: 23, speedSummary: { sampleCount: 23, excludedCount: 1 }, avgTokPerSec: 59.6, avgTtftSec: 1.38, ttftSummary: { avgSec: 1.38, sampleCount: 23 }, sessionCostUsd: 1.28, sessionUnpricedCalls: 0, sessionCacheHitPct: 88.9, inputTokens: 186400, cacheReadTokens: 1540000, outputTokens: 28400, totalTokens: 1754800, activeAgentBadge: '子1', modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], recentSteps: mockSteps, }; return { settings: mergedSettings, account: { tierId: 'g1-ultra-lite-tier', tierName: 'Google AI Ultra', tierMultiplier: '5x', planName: '5x', aiCredits: 0, }, quotas: { meta: { hasOfficialData: true, isStale: false, refreshFailed: false, }, activePool: { family: 'Gemini', poolKey: 'Gemini', poolLabel: 'Gemini', usedPct: 36, remainingPct: 64, resetTime: reset5hIso, weeklyUsedPct: 48, weeklyRemainingPct: 52, weeklyResetTime: resetWkIso, }, pools: [ { poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini', usedPct: 36, remainingPct: 64, reservedPct: 1.0, reservedLeaseCount: 1, resetTime: reset5hIso, weeklyUsedPct: 48, weeklyRemainingPct: 52, weeklyReservedPct: 0.5, weeklyReservedLeaseCount: 1, weeklyResetTime: resetWkIso, cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 }, cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 }, }, ...(includeArgonPool ? [ { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', family: 'Argon', has5h: false, hasWeekly: true, weeklyUsedPct: 58, weeklyRemainingPct: 42, weeklyResetTime: resetWkIso, cycleWeekly: { tokens: 4200000, costUsd: 6.4, calls: 48 }, }, ] : []), { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT', usedPct: 68, remainingPct: 32, resetTime: resetClaude5hIso, weeklyUsedPct: 41, weeklyRemainingPct: 59, weeklyResetTime: resetWkIso, cycle5h: { tokens: 620000, costUsd: 2.15, calls: 11 }, cycleWeekly: { tokens: 5800000, costUsd: 18.6, calls: 92 }, }, ], weekly: { isOfficial: true, usedPct: 48, remainingPct: 52, resetTime: resetWkIso, tokens: 20000000, costUsd: 30.0, calls: 278, }, }, runningConversations: [ { cascadeId: 'mock-preview-conv', title: sessionTitle, isCurrentSelected: true, isMainRunning: true, isRunning: true, subagentCount: 1, runningSubagentCount: 0, latestTokPerSec: 68.4, contextUsedPct: 55.8, mainActivity: { phase: 'generating', label: t('live.generating'), stepProgress: '#24', detail: 'src/auth/tokenRefresh.ts', startedAtMs: Date.now() - 8000, signature: 'mock-preview:24', }, subagents: [ { cascadeId: 'mock-sub-1', index: 1, badgeText: '子1', shortLabel: `${t('fmt.subAgent')} #1`, role: subRole, isRunning: false, stepCount: 8, lastModifiedMs: anchorMinMs - 42_000, liveActivity: { phase: 'done', label: t('live.done'), detail: '', stepProgress: '', startedAtMs: anchorMinMs - 42_000, signature: 'mock-sub-1:8', }, }, ], }, ], activeConversation: { ...mainAgent, cascadeId: 'mock-preview-conv', title: sessionTitle, hasSubagents: true, agents: [mainAgent, subAgent1], aggregated, recentSteps: mockSteps, }, }; } return { buildStructurePreviewTelemetry }; })(); // --- src/components/settings/CollapsibleSection.js --- const { CollapsibleSection } = (() => { /** * @fileoverview Reusable Section Card (`CollapsibleSection.js`) * for `SettingsStructureTab` — supports both accordion mode (`collapsible: true`) * and static 3rd-level pane card mode (`collapsible: false`). */ const CollapsibleSection = defineComponent({ name: 'CollapsibleSection', setup({ props, onCleanup }) { const isCollapsible = props.collapsible !== false; let expanded = isCollapsible ? Boolean(props.defaultExpanded) : true; let statusTimer = null; const chevronIcon = isCollapsible ? createSvgIcon('chevron-right', { size: 12, className: 'collapsible-chevron', }) : null; const sectionIcon = props.icon ? createSvgIcon(props.icon, { size: 13 }) : null; const titleTextEl = h('span', { className: 'collapsible-title-text', text: props.title || '', }); const triggerChildren = []; if (chevronIcon) triggerChildren.push(chevronIcon); if (sectionIcon) triggerChildren.push(sectionIcon); triggerChildren.push(titleTextEl); const triggerBtn = isCollapsible ? h( 'button', { type: 'button', className: 'collapsible-trigger', 'aria-expanded': expanded ? 'true' : 'false', onClick: () => { setExpanded(!expanded); if (typeof props.onToggle === 'function') { props.onToggle(expanded); } }, }, triggerChildren ) : h('div', { className: 'collapsible-title-static' }, triggerChildren); const statusTextEl = h('span', { className: 'collapsible-status', text: '' }); const badgeEl = h('span', { className: 'collapsible-badge text-mono', hidden: !props.badgeText, text: props.badgeText || '', }); const resetBtnText = h('span', { text: props.resetLabel || t('settings.resetBtn') }); const resetBtn = typeof props.onReset === 'function' ? h( 'button', { type: 'button', className: 'btn-ghost-sm', disabled: props.resetDisabled !== false, onClick: (e) => { e.stopPropagation(); props.onReset(); }, }, [resetBtnText] ) : null; const rightChildren = [statusTextEl, badgeEl]; if (resetBtn) rightChildren.push(resetBtn); const headerRow = h('div', { className: 'collapsible-header-row' }, [ triggerBtn, h('span', { className: 'collapsible-right' }, rightChildren), ]); const bodyEl = h( 'div', { className: 'collapsible-body', hidden: !expanded, }, Array.isArray(props.children) ? props.children : [] ); const sectionEl = h( 'section', { className: `panel collapsible-section${expanded ? ' is-expanded' : ''}${isCollapsible ? '' : ' is-static-pane'}`, }, [headerRow, bodyEl] ); function setExpanded(next) { if (!isCollapsible) return; expanded = Boolean(next); patchClasses(sectionEl, { 'is-expanded': expanded }); patchAttr(triggerBtn, 'aria-expanded', expanded ? 'true' : 'false'); patchAttr(bodyEl, 'hidden', !expanded); } function setTitle(text) { patchText(titleTextEl, text || ''); } function setBadge(text) { patchAttr(badgeEl, 'hidden', !text); patchText(badgeEl, text || ''); } function setResetLabel(text) { if (resetBtn) { patchText(resetBtnText, text || t('settings.resetBtn')); } } function setResetDisabled(disabled) { if (resetBtn) { patchAttr(resetBtn, 'disabled', Boolean(disabled)); } } function showStatus(text, autoClearMs = 1500) { if (statusTimer) { clearTimeout(statusTimer); statusTimer = null; } patchText(statusTextEl, text || ''); if (text && autoClearMs > 0) { statusTimer = setTimeout(() => { statusTimer = null; patchText(statusTextEl, ''); }, autoClearMs); } } onCleanup(() => { if (statusTimer) { clearTimeout(statusTimer); statusTimer = null; } }); return { el: sectionEl, refs: { triggerBtn, bodyEl, resetBtn, badgeEl, statusTextEl, setExpanded, setTitle, setBadge, setResetLabel, setResetDisabled, showStatus, isExpanded: () => expanded, }, }; }, }); return { CollapsibleSection }; })(); // --- src/components/settings/EditableSlotList.js --- const { EditableSlotList } = (() => { /** * @fileoverview Reusable Drag-Sortable & `+` / `-` / `↑` / `↓` Dynamic Slot List (`EditableSlotList.js`). * Powers Topbar Capsule Slots (1..5), Hover Popup Modules (0..4), * Live Overview Modules (1..4), First-Row Metrics (1..4), and Step Table Columns (2..12). * Supports smooth pointer-based drag reordering with live preview callbacks (`onPreview`) * and single-commit persistence on drop (`onChange`). */ function isNodeWithin(target, container) { let cur = target; while (cur) { if (cur === container) return true; cur = cur.parentNode || cur.host || null; } return false; } function areSlotListsEqual(a, b) { if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false; for (let i = 0; i < a.length; i += 1) { if (a[i] !== b[i]) return false; } return true; } const EditableSlotList = defineComponent({ name: 'EditableSlotList', setup({ props, onCleanup }) { const minItems = Math.max(0, Number(props.minItems ?? 1)); const maxItems = Math.max(minItems, Number(props.maxItems ?? 5)); let currentItems = Array.isArray(props.items) ? [...props.items] : []; let currentOptions = Array.isArray(props.options) ? [...props.options] : []; let emptyHintText = String(props.emptyHintText || ''); let addBtnTextFn = typeof props.addBtnTextFn === 'function' ? props.addBtnTextFn : null; let activeDrag = null; const listEl = h('div', { className: 'editable-slot-list' }); const emptyEl = h('div', { className: 'editable-slot-empty', hidden: true, text: emptyHintText, }); const addBtnLabel = h('span', { text: '' }); const addBtn = h( 'button', { type: 'button', className: 'slot-add-btn', onClick: () => { if (currentItems.length >= maxItems) return; const usedSet = new Set(currentItems); const nextOpt = currentOptions.find((opt) => !usedSet.has(opt.value)); if (!nextOpt) return; emitChange([...currentItems, nextOpt.value]); }, }, [createSvgIcon('plus', { size: 11 }), addBtnLabel] ); const footerEl = h('div', { className: 'editable-slot-footer' }, [addBtn]); const rootEl = h('div', { className: 'editable-slot-wrap' }, [emptyEl, listEl, footerEl]); const rowPool = []; function emitChange(nextItems) { currentItems = [...nextItems]; syncRows(); if (typeof props.onPreview === 'function') { props.onPreview([...currentItems]); } if (typeof props.onChange === 'function') { props.onChange([...currentItems]); } } function teardownActiveDrag({ revert = false } = {}) { if (!activeDrag) return; const { startItems, hasMoved, cleanupListeners } = activeDrag; activeDrag = null; cleanupListeners(); patchClasses(listEl, { 'is-dragging-list': false }); for (const r of rowPool) { patchClasses(r.rowEl, { 'is-dragging': false }); } if (revert && hasMoved && !areSlotListsEqual(startItems, currentItems)) { currentItems = [...startItems]; syncRows(); if (typeof props.onPreview === 'function') { props.onPreview([...currentItems]); } } } function startPointerDrag(e, initialRowIdx) { if (e && e.button != null && e.button !== 0) return; if (currentItems.length <= 1) return; if (activeDrag) { teardownActiveDrag({ revert: false }); } const startY = Number(e?.clientY ?? 0); const startItems = [...currentItems]; let dragIdx = initialRowIdx; let hasMoved = false; const onPointerMove = (ev) => { if (!activeDrag) return; const clientY = Number(ev?.clientY ?? startY); if (!hasMoved) { if (Math.abs(clientY - startY) < 4) return; hasMoved = true; activeDrag.hasMoved = true; for (let k = 0; k < currentItems.length; k += 1) { rowPool[k]?.selectComp?.close?.(); } patchClasses(listEl, { 'is-dragging-list': true }); if (rowPool[dragIdx]) { patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': true }); } } ev?.preventDefault?.(); let targetIdx = dragIdx; const count = currentItems.length; for (let i = 0; i < dragIdx; i += 1) { const rect = rowPool[i]?.rowEl?.getBoundingClientRect?.(); if (rect && rect.height > 0 && clientY < rect.top + rect.height * 0.5) { targetIdx = i; break; } } if (targetIdx === dragIdx) { for (let i = count - 1; i > dragIdx; i -= 1) { const rect = rowPool[i]?.rowEl?.getBoundingClientRect?.(); if (rect && rect.height > 0 && clientY > rect.top + rect.height * 0.5) { targetIdx = i; break; } } } if (targetIdx !== dragIdx) { if (rowPool[dragIdx]) { patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': false }); } const next = [...currentItems]; const [moved] = next.splice(dragIdx, 1); next.splice(targetIdx, 0, moved); dragIdx = targetIdx; activeDrag.dragIdx = dragIdx; currentItems = next; syncRows(); if (rowPool[dragIdx]) { patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': true }); } if (typeof props.onPreview === 'function') { props.onPreview([...currentItems]); } } }; const onPointerUp = () => { if (!activeDrag) return; const moved = activeDrag.hasMoved; const changed = !areSlotListsEqual(startItems, currentItems); teardownActiveDrag({ revert: false }); if (moved && changed) { emitChange([...currentItems]); } }; const onPointerCancel = () => { teardownActiveDrag({ revert: true }); }; const onKeyDown = (ev) => { if (ev?.key === 'Escape') { teardownActiveDrag({ revert: true }); } }; const docTarget = typeof document !== 'undefined' && typeof document.addEventListener === 'function' ? document : null; if (docTarget) { docTarget.addEventListener('pointermove', onPointerMove); docTarget.addEventListener('pointerup', onPointerUp); docTarget.addEventListener('pointercancel', onPointerCancel); docTarget.addEventListener('keydown', onKeyDown); } activeDrag = { startItems, dragIdx, hasMoved: false, cleanupListeners: () => { if (docTarget && typeof docTarget.removeEventListener === 'function') { docTarget.removeEventListener('pointermove', onPointerMove); docTarget.removeEventListener('pointerup', onPointerUp); docTarget.removeEventListener('pointercancel', onPointerCancel); docTarget.removeEventListener('keydown', onKeyDown); } }, }; } function createSlotRow() { let rowIndex = 0; const dragHandle = h( 'span', { className: 'slot-drag-handle', 'aria-hidden': 'true', onPointerdown: (e) => { e.preventDefault?.(); e.stopPropagation?.(); startPointerDrag(e, rowIndex); }, }, [createSvgIcon('grip', { size: 12 })] ); const indexBadge = h('span', { className: 'slot-index-badge text-mono', text: '1' }); const selectComp = CustomSelect({ modelValue: '', options: [], onUpdateModelValue: (nextVal) => { if (!nextVal || currentItems[rowIndex] === nextVal) return; if (currentItems.some((v, idx) => idx !== rowIndex && v === nextVal)) return; const next = [...currentItems]; next[rowIndex] = nextVal; emitChange(next); }, }); const upBtn = h( 'button', { type: 'button', className: 'slot-move-btn', onClick: (e) => { e.stopPropagation(); if (rowIndex <= 0) return; const next = [...currentItems]; const tmp = next[rowIndex - 1]; next[rowIndex - 1] = next[rowIndex]; next[rowIndex] = tmp; emitChange(next); }, }, [createSvgIcon('chevron-up', { size: 12 })] ); const downBtn = h( 'button', { type: 'button', className: 'slot-move-btn', onClick: (e) => { e.stopPropagation(); if (rowIndex >= currentItems.length - 1) return; const next = [...currentItems]; const tmp = next[rowIndex + 1]; next[rowIndex + 1] = next[rowIndex]; next[rowIndex] = tmp; emitChange(next); }, }, [createSvgIcon('chevron-down', { size: 12 })] ); const removeBtn = h( 'button', { type: 'button', className: 'slot-move-btn slot-remove-btn', onClick: (e) => { e.stopPropagation(); if (currentItems.length <= minItems) return; const next = currentItems.filter((_, idx) => idx !== rowIndex); emitChange(next); }, }, [createSvgIcon('minus', { size: 12 })] ); const orderBtnsEl = h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]); const rowEl = h( 'div', { className: 'editable-slot-row', onPointerdown: (e) => { if (isNodeWithin(e?.target, selectComp.el) || isNodeWithin(e?.target, orderBtnsEl)) { return; } startPointerDrag(e, rowIndex); }, }, [dragHandle, indexBadge, selectComp.el, orderBtnsEl] ); return { rowEl, dragHandle, indexBadge, selectComp, upBtn, downBtn, removeBtn, setIndex(idx) { rowIndex = idx; }, }; } function syncRows() { const count = currentItems.length; patchAttr(emptyEl, 'hidden', count > 0 || !emptyHintText); if (emptyHintText) { patchText(emptyEl, emptyHintText); } patchAttr(listEl, 'hidden', count === 0); while (rowPool.length < count) { rowPool.push(createSlotRow()); } while (listEl.children && listEl.children.length > count) { const tailIdx = listEl.children.length - 1; const tailChild = listEl.children[tailIdx]; tailChild?.remove?.(); } const canDrag = count > 1; const dragTitle = canDrag ? t('settings.slot.dragHint') : ''; const canRemove = count > minItems; const removeTitle = canRemove ? t('settings.slot.remove') : t('settings.slot.minReached', { min: minItems }); for (let i = 0; i < count; i += 1) { const entry = rowPool[i]; const itemVal = currentItems[i]; entry.setIndex(i); patchAttr(entry.rowEl, 'data-slot-row', String(i)); patchText(entry.indexBadge, String(i + 1)); patchClasses(entry.dragHandle, { 'is-disabled': !canDrag }); patchAttr(entry.dragHandle, 'title', dragTitle || null); const otherUsed = new Set(currentItems.filter((_, idx) => idx !== i)); const rowOpts = currentOptions.map((opt) => { const isTaken = otherUsed.has(opt.value); return isTaken ? { ...opt, disabled: true, meta: t('settings.slot.alreadyAdded'), } : opt; }); entry.selectComp.setProps({ modelValue: itemVal, options: rowOpts, }); patchAttr(entry.upBtn, 'disabled', i === 0); patchAttr(entry.upBtn, 'title', t('settings.slot.moveUp')); patchAttr(entry.upBtn, 'aria-label', t('settings.slot.moveUp')); patchAttr(entry.downBtn, 'disabled', i === count - 1); patchAttr(entry.downBtn, 'title', t('settings.slot.moveDown')); patchAttr(entry.downBtn, 'aria-label', t('settings.slot.moveDown')); patchAttr(entry.removeBtn, 'disabled', !canRemove); patchAttr(entry.removeBtn, 'title', removeTitle); patchAttr(entry.removeBtn, 'aria-label', removeTitle); if (!listEl.children || listEl.children[i] !== entry.rowEl) { listEl.appendChild(entry.rowEl); } } // Close any hidden pooled selects for (let j = count; j < rowPool.length; j += 1) { rowPool[j].selectComp.close(); } const usedAll = new Set(currentItems); const hasAvailableOption = currentOptions.some((opt) => !usedAll.has(opt.value)); const disableAdd = count >= maxItems || !hasAvailableOption; patchAttr(addBtn, 'disabled', disableAdd); const addLabel = addBtnTextFn ? addBtnTextFn(count, maxItems) : `+ (${count}/${maxItems})`; patchText(addBtnLabel, addLabel); } function setProps(next = {}) { if (!activeDrag && Array.isArray(next.items)) { currentItems = [...next.items]; } if (Array.isArray(next.options)) { currentOptions = [...next.options]; } if (next.emptyHintText !== undefined) { emptyHintText = String(next.emptyHintText || ''); } if (typeof next.addBtnTextFn === 'function') { addBtnTextFn = next.addBtnTextFn; } syncRows(); } syncRows(); onCleanup(() => { teardownActiveDrag({ revert: false }); for (const entry of rowPool) { entry.selectComp.destroy(); } rowPool.length = 0; }); return { el: rootEl, refs: { listEl, addBtn, emptyEl, setProps, getItems: () => [...currentItems], getSelects: () => rowPool.slice(0, currentItems.length).map((r) => r.selectComp), }, }; }, }); return { EditableSlotList }; })(); // --- src/components/settings/ThemeColorPicker.js --- const { ThemeColorPicker } = (() => { /** * @fileoverview Host-aware Theme Accent Swatch Picker (`ThemeColorPicker.js`). * Provides the default "跟随宿主" (`host`) pill plus 6 curated color swatches. */ const ThemeColorPicker = defineComponent({ name: 'ThemeColorPicker', setup({ props }) { let currentKey = normalizeClientThemeAccent(props.modelValue); const hostLabelEl = h('span', { text: t('settings.gen.accentHost') }); const hostBtn = h( 'button', { type: 'button', className: 'theme-host-chip', 'data-accent-key': 'host', onClick: () => selectAccent('host'), }, [hostLabelEl] ); const swatchPresets = THEME_ACCENT_PRESETS.filter((p) => p.key !== 'host'); const swatchEntries = swatchPresets.map((preset) => { const checkIcon = createSvgIcon('check', { size: 11 }); const btn = h( 'button', { type: 'button', className: 'theme-swatch-btn', 'data-accent-key': preset.key, title: t(preset.labelKey), 'aria-label': t(preset.labelKey), onClick: () => selectAccent(preset.key), }, [checkIcon] ); patchStyleVar(btn, '--swatch-color', preset.cssColor); return { preset, btn, checkIcon }; }); const swatchGroup = h( 'span', { className: 'theme-swatch-group' }, swatchEntries.map((s) => s.btn) ); const rootEl = h('div', { className: 'theme-color-picker' }, [hostBtn, swatchGroup]); function syncVisuals() { const isHost = currentKey === 'host'; patchClasses(hostBtn, { 'is-active': isHost }); patchAttr(hostBtn, 'aria-pressed', isHost ? 'true' : 'false'); for (const entry of swatchEntries) { const active = entry.preset.key === currentKey; patchClasses(entry.btn, { 'is-active': active }); patchAttr(entry.btn, 'aria-pressed', active ? 'true' : 'false'); patchAttr(entry.checkIcon, 'hidden', !active); } } function refreshLabels() { patchText(hostLabelEl, t('settings.gen.accentHost')); for (const entry of swatchEntries) { const label = t(entry.preset.labelKey); patchAttr(entry.btn, 'title', label); patchAttr(entry.btn, 'aria-label', label); } } function selectAccent(nextRaw) { const normalized = normalizeClientThemeAccent(nextRaw); if (normalized === currentKey) return; currentKey = normalized; syncVisuals(); if (typeof props.onUpdateModelValue === 'function') { props.onUpdateModelValue(currentKey); } } function setValue(nextRaw) { currentKey = normalizeClientThemeAccent(nextRaw); syncVisuals(); } syncVisuals(); return { el: rootEl, refs: { hostBtn, swatchEntries, setValue, refreshLabels, getValue: () => currentKey, }, }; }, }); return { ThemeColorPicker }; })(); // --- src/components/settings/BridgeStatusNotice.js --- const { BridgeStatusNotice } = (() => { /** * @fileoverview Shared CDP / Window Bridge diagnostic & one-click relaunch card (`BridgeStatusNotice.js`). * Surfaces automatic shortcut provisioning status and a one-click host relaunch button when * Antigravity 2.33.0+ runs without an active `DevToolsActivePort` (`no_devtools_port` / `cdp_unreachable`). */ const LAUNCH_FLAG_TEXT = '--remote-debugging-port=0'; const BridgeStatusNotice = defineComponent({ name: 'BridgeStatusNotice', setup({ props, onCleanup }) { let contextMode = Boolean(props?.contextMode); const dismissible = Boolean(props?.dismissible); let lastPayload = { visible: false, windowBridge: null, hostPlatform: 'win32', }; let dismissed = false; let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed' let relaunchResetTimer = null; let destroyed = false; const copyFeedback = createCopiedFeedbackController({ durationMs: 1800, onCleanup, onChange: () => { if (!destroyed) syncActionButtons(); }, }); const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' }); const titleEl = h('strong', { className: 'settings-bridge-title', text: '' }); const bodyEl = h('p', { className: 'settings-bridge-desc', text: '' }); const dismissBtnEl = dismissible ? h( 'button', { type: 'button', className: 'btn-ghost-sm settings-bridge-dismiss-btn', 'aria-label': t('settings.bridge.dismissAria'), title: t('settings.bridge.dismissAria'), onClick: () => { dismissed = true; render(); props?.onDismiss?.(); }, }, [createSvgIcon('close', { size: 11 })] ) : null; const relaunchBtnIconEl = createSvgIcon('refresh', { size: 11 }); const relaunchBtnTextEl = h('span', { className: 'settings-bridge-relaunch-text', text: t('settings.bridge.relaunchBtn'), }); const relaunchBtnEl = h( 'button', { type: 'button', className: 'settings-bridge-relaunch-btn', onClick: async () => { if (relaunchState === 'relaunching' || destroyed) return; relaunchState = 'relaunching'; if (relaunchResetTimer) { clearTimeout(relaunchResetTimer); relaunchResetTimer = null; } syncActionButtons(); try { const res = await triggerBridgeHostRelaunch(); if (destroyed) return; if (!res || res.ok === false) { relaunchState = 'failed'; syncActionButtons(); relaunchResetTimer = setTimeout(() => { relaunchResetTimer = null; if (destroyed) return; relaunchState = 'idle'; syncActionButtons(); }, 3500); relaunchResetTimer?.unref?.(); return; } // Reset button if host is still open after 9s (e.g. cancelled close prompt) relaunchResetTimer = setTimeout(() => { relaunchResetTimer = null; if (destroyed) return; relaunchState = 'idle'; syncActionButtons(); }, 9000); relaunchResetTimer?.unref?.(); } catch { if (destroyed) return; relaunchState = 'failed'; syncActionButtons(); relaunchResetTimer = setTimeout(() => { relaunchResetTimer = null; if (destroyed) return; relaunchState = 'idle'; syncActionButtons(); }, 3500); relaunchResetTimer?.unref?.(); } }, }, [relaunchBtnIconEl, relaunchBtnTextEl] ); const copyBtnIconEl = createSvgIcon('copy', { size: 11 }); const copyBtnTextEl = h('span', { className: 'settings-bridge-copy-text', text: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }), }); const copyBtnEl = h( 'button', { type: 'button', className: 'btn-ghost-sm settings-bridge-copy-btn', onClick: async () => { await copyPlainTextToClipboard(LAUNCH_FLAG_TEXT); if (destroyed) return; copyFeedback.trigger(true); }, }, [copyBtnIconEl, copyBtnTextEl] ); const headLeftEl = h('div', { className: 'settings-bridge-head-main' }, [headIconEl, titleEl]); const headRowEl = h( 'div', { className: 'settings-bridge-head' }, dismissBtnEl ? [headLeftEl, dismissBtnEl] : [headLeftEl] ); const actionsRowEl = h('div', { className: 'settings-bridge-actions' }, [ relaunchBtnEl, copyBtnEl, ]); const rootEl = h( 'div', { className: 'settings-bridge-notice', role: 'status', hidden: true, }, [headRowEl, bodyEl, actionsRowEl] ); function syncActionButtons() { const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false; const needsAuth = Boolean(lastPayload.windowBridge?.hasReadOnlyShortcuts); patchAttr(relaunchBtnEl, 'hidden', !canRelaunch); patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching'); patchText( relaunchBtnTextEl, relaunchState === 'relaunching' ? t('settings.bridge.relaunchingBtn') : relaunchState === 'failed' ? t('settings.bridge.relaunchFailed') : needsAuth ? t('settings.bridge.relaunchAuthBtn') : t('settings.bridge.relaunchBtn') ); const isCopied = copyFeedback.isCopied(true); patchSvgIcon(copyBtnIconEl, isCopied ? 'check' : 'copy'); patchText( copyBtnTextEl, isCopied ? t('settings.bridge.copiedBtn') : t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }) ); if (dismissBtnEl) { const aria = t('settings.bridge.dismissAria'); patchAttr(dismissBtnEl, 'aria-label', aria); patchAttr(dismissBtnEl, 'title', aria); } } function render() { const wb = lastPayload.windowBridge; const state = String(wb?.state || '').trim(); if (state === 'active') { dismissed = false; } const shouldShow = !dismissed && Boolean(lastPayload.visible) && !isWindowOverlayMode() && (state === 'no_devtools_port' || state === 'cdp_unreachable'); patchAttr(rootEl, 'hidden', !shouldShow); if (!shouldShow) return; const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); const hasReadOnlyShortcuts = Boolean(wb?.hasReadOnlyShortcuts); const isMacDesktop = plat === 'darwin' && !wb?.argvConfigured; const isAutoConfigured = Boolean( wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured ); const useRestartTheme = !hasReadOnlyShortcuts && (isAutoConfigured || isMacDesktop); patchClasses(rootEl, { 'is-restart': useRestartTheme, 'is-warn': !useRestartTheme, }); patchSvgIcon(headIconEl, useRestartTheme ? 'refresh' : 'warning'); let titleText = ''; let bodyText = ''; if (hasReadOnlyShortcuts) { titleText = contextMode ? t('settings.bridge.ctxReadOnlyTitle') : t('settings.bridge.readOnlyTitle'); bodyText = t('settings.bridge.readOnlyBody'); } else if (isMacDesktop) { titleText = contextMode ? t('settings.bridge.ctxMacTitle') : t('settings.bridge.macTitle'); bodyText = t('settings.bridge.guideMac'); } else if (isAutoConfigured) { titleText = contextMode ? t('settings.bridge.ctxRestartTitle') : t('settings.bridge.restartTitle'); bodyText = t('settings.bridge.restartBody'); } else { titleText = contextMode ? t('settings.bridge.ctxTitle') : state === 'cdp_unreachable' ? t('settings.bridge.unreachableTitle') : t('settings.bridge.noPortTitle'); bodyText = plat === 'linux' ? t('settings.bridge.guideLinux') : t('settings.bridge.guideWin'); } patchText(titleEl, titleText); patchText(bodyEl, bodyText); syncActionButtons(); } function update(next = {}) { if (typeof next.contextMode === 'boolean') { contextMode = next.contextMode; } lastPayload = { ...lastPayload, ...next, }; render(); } onCleanup(() => { destroyed = true; if (relaunchResetTimer) { clearTimeout(relaunchResetTimer); relaunchResetTimer = null; } }); return { el: rootEl, refs: { update, refreshLabels: render, relaunchBtnEl, copyBtnEl, dismissBtnEl, }, }; }, }); return { BridgeStatusNotice }; })(); // --- src/components/settings/SessionMigrationCard.js --- const { SessionMigrationCard } = (() => { /** * @fileoverview 跨端会话按需迁移设置卡片 (`SessionMigrationCard.js`)。 * 仅当本机检测到 ≥2 个 Antigravity 客户端目录时展示,支持自由勾选根会话以完整迁移或克隆副本到目标端。 */ const SMIG_OUTSIDE_PROJECT_ID = 'outside-of-project'; function smigGetClientLabel(clientId) { if (clientId === 'cli') return t('settings.oth.migClientCli'); if (clientId === 'ide_legacy') return t('settings.oth.migClientIdeLegacy'); return t('settings.oth.migClientDesktop'); } function smigGetModeOptions() { return [ { value: 'move', label: t('settings.oth.migModeMove') }, { value: 'clone', label: t('settings.oth.migModeClone') }, ]; } function smigFormatAge(epochMs) { const ts = Number(epochMs || 0); if (!Number.isFinite(ts) || ts <= 0) return ''; const diffSec = Math.max(0, Math.floor((Date.now() - ts) / 1000)); const isEn = isEnglishLocale(); if (diffSec < 60) return isEn ? 'just now' : '刚刚'; const diffMin = Math.floor(diffSec / 60); if (diffMin < 60) return isEn ? `${diffMin}m ago` : `${diffMin}分钟前`; const diffHr = Math.floor(diffMin / 60); if (diffHr < 24) return isEn ? `${diffHr}h ago` : `${diffHr}小时前`; const diffDay = Math.floor(diffHr / 24); return isEn ? `${diffDay}d ago` : `${diffDay}天前`; } const SessionMigrationCard = defineComponent({ name: 'SessionMigrationCard', setup({ props, onCleanup }) { const loadCatalogFn = typeof props?.loadCatalog === 'function' ? props.loadCatalog : fetchSessionMigrationCatalog; const runMigrateFn = typeof props?.runMigrate === 'function' ? props.runMigrate : executeSessionMigration; let catalog = null; let hasLoadedOnce = false; let isLoading = false; let isMigrating = false; let destroyed = false; let bodyMounted = false; let sourceClient = ''; let targetClient = ''; let migrationMode = 'move'; let targetProjectId = ''; let searchQuery = ''; const selectedIds = new Set(); let lastResult = null; let copiedCmdId = ''; let copiedTimer = null; let titleEl = null; let descEl = null; let refreshBtnText = null; let refreshBtn = null; let sourceLabelEl = null; let targetLabelEl = null; let modeLabelEl = null; let modeSeg = null; let modeHintEl = null; let projectLabelEl = null; let sourceSelect = null; let targetSelect = null; let projectSelect = null; let projectFieldWrap = null; let searchInput = null; let searchClearBtn = null; let toggleAllBtn = null; let selectedCountEl = null; let listEl = null; let listScrollbar = null; let migrateBtnText = null; let migrateBtn = null; let resultBoxEl = null; const rootEl = h('section', { className: 'panel smig-panel', hidden: true }); function ensureBodyMounted() { if (bodyMounted) return; bodyMounted = true; titleEl = h('span', { text: t('settings.oth.migTitle') }); descEl = h('p', { className: 'settings-hint-text smig-desc', text: t('settings.oth.migDesc') }); refreshBtnText = h('span', { text: t('settings.oth.migRefreshBtn') }); refreshBtn = h( 'button', { type: 'button', className: 'btn-ghost-sm smig-refresh-btn', onClick: () => { void loadCatalog(true); }, }, [createSvgIcon('refresh', { size: 12 }), refreshBtnText] ); sourceLabelEl = h('span', { className: 'form-label', text: t('settings.oth.migSourceLabel') }); targetLabelEl = h('span', { className: 'form-label', text: t('settings.oth.migTargetLabel') }); modeLabelEl = h('span', { className: 'form-label', text: t('settings.oth.migModeLabel') }); modeSeg = SegmentedControl({ ariaLabel: t('settings.oth.migModeLabel'), modelValue: migrationMode, options: smigGetModeOptions(), onUpdateModelValue: (val) => { if (!val || val === migrationMode) return; migrationMode = val; lastResult = null; syncModeControls(); renderResultBox(); }, }); modeSeg.el.classList?.add('smig-mode-seg'); modeHintEl = h('span', { className: 'settings-hint-text smig-mode-hint', text: t('settings.oth.migModeMoveHint'), }); projectLabelEl = h('span', { className: 'form-label', text: t('settings.oth.migProjectLabel') }); sourceSelect = CustomSelect({ ariaLabel: t('settings.oth.migSourceLabel'), modelValue: '', options: [], onUpdateModelValue: (val) => { if (!val || val === sourceClient) return; sourceClient = val; selectedIds.clear(); lastResult = null; ensureValidTarget(); syncControlsAndList(); }, }); targetSelect = CustomSelect({ ariaLabel: t('settings.oth.migTargetLabel'), modelValue: '', options: [], onUpdateModelValue: (val) => { if (!val || val === targetClient) return; targetClient = val; lastResult = null; syncControlsAndList(); }, }); projectSelect = CustomSelect({ ariaLabel: t('settings.oth.migProjectLabel'), modelValue: '', options: [], className: 'smig-project-select', onUpdateModelValue: (val) => { targetProjectId = String(val || ''); }, }); projectFieldWrap = h('div', { className: 'form-row smig-field' }, [ projectLabelEl, projectSelect.el, ]); const searchBox = createSearchInput({ wrapClassName: 'smig-search-wrap', iconClassName: 'smig-search-icon', inputClassName: 'smig-search-input', clearClassName: 'smig-search-clear', placeholder: t('settings.oth.migSearchPlaceholder'), clearAriaLabel: t('select.clearSearch'), closeIconSize: 10, onInput: (val) => { searchQuery = String(val || '').trim(); renderSessionList(); }, onClear: () => { searchQuery = ''; renderSessionList(); searchInput.focus?.(); }, }); searchInput = searchBox.inputEl; searchClearBtn = searchBox.clearBtnEl; const searchWrap = searchBox.el; toggleAllBtn = h('button', { type: 'button', className: 'btn-ghost-sm smig-toggle-all-btn', text: t('settings.oth.migSelectAll'), onClick: () => { const selectable = getFilteredSessions().filter((s) => !s.isRunning); if (selectable.length === 0) return; const allSelected = selectable.every((s) => selectedIds.has(s.cascadeId)); if (allSelected) { for (const s of selectable) selectedIds.delete(s.cascadeId); } else { for (const s of selectable) selectedIds.add(s.cascadeId); } renderSessionList(); }, }); selectedCountEl = h('span', { className: 'smig-count-meta', text: '' }); listEl = h('div', { className: 'smig-list', role: 'list' }); listScrollbar = CustomScrollbar({ className: 'smig-scroll-host', contentEl: listEl, }); migrateBtnText = h('span', { text: t('settings.oth.migActionBtn', { count: 0 }), }); migrateBtn = h( 'button', { type: 'button', className: 'btn-primary smig-migrate-btn', disabled: true, onClick: () => { void handleMigrate(); }, }, [createSvgIcon('copy', { size: 12 }), migrateBtnText] ); resultBoxEl = h('div', { className: 'smig-result', hidden: true }); const children = [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('layers', { size: 13 }), titleEl, ]), refreshBtn, ]), descEl, h('div', { className: 'smig-direction-grid' }, [ h('div', { className: 'form-row smig-field' }, [sourceLabelEl, sourceSelect.el]), h('div', { className: 'form-row smig-field' }, [targetLabelEl, targetSelect.el]), ]), h('div', { className: 'smig-mode-block' }, [ h('div', { className: 'settings-inline-row smig-mode-row' }, [ modeLabelEl, modeSeg.el, ]), modeHintEl, ]), projectFieldWrap, h('div', { className: 'smig-toolbar' }, [ searchWrap, toggleAllBtn, selectedCountEl, ]), listScrollbar.el, h('div', { className: 'smig-footer' }, [migrateBtn]), resultBoxEl, ]; for (const child of children) { rootEl.appendChild(child); } } function getDetectedClients() { return Array.isArray(catalog?.clients) ? catalog.clients.filter((c) => c.exists) : []; } function getTargetClientsFor(srcId) { return getDetectedClients().filter((c) => c.canBeTarget && c.id !== srcId); } function ensureValidSelectionDefaults() { const detected = getDetectedClients(); if (detected.length < 2) { sourceClient = ''; targetClient = ''; return; } const validSources = detected.filter((c) => getTargetClientsFor(c.id).length > 0); if (!validSources.some((c) => c.id === sourceClient)) { const cliClient = validSources.find((c) => c.id === 'cli' && c.sessionCount > 0); const firstWithSessions = validSources.find((c) => c.sessionCount > 0); sourceClient = (cliClient || firstWithSessions || validSources[0])?.id || ''; } ensureValidTarget(); const projects = Array.isArray(catalog?.desktopProjects) ? catalog.desktopProjects : []; if (!projects.some((p) => p.projectId === targetProjectId)) { const preferred = projects.find((p) => !p.isOutsideProject) || projects[0]; targetProjectId = preferred?.projectId || SMIG_OUTSIDE_PROJECT_ID; } } function ensureValidTarget() { const targets = getTargetClientsFor(sourceClient); if (!targets.some((c) => c.id === targetClient)) { const preferDesktop = targets.find((c) => c.id === 'desktop'); targetClient = (preferDesktop || targets[0])?.id || ''; } } function getCurrentSourceSessions() { const list = catalog?.sessionsByClient?.[sourceClient]; return Array.isArray(list) ? list : []; } function getFilteredSessions() { const all = getCurrentSourceSessions(); if (!searchQuery) return all; const needle = searchQuery.toLowerCase(); return all.filter((item) => { const haystack = [ item.title, item.workspaceName, item.workspacePath, item.cascadeId, ] .filter(Boolean) .join(' ') .toLowerCase(); return haystack.includes(needle); }); } function resolveProjectDisplayLabel(projectId) { if (!projectId || projectId === SMIG_OUTSIDE_PROJECT_ID) { return t('settings.oth.migProjectOutside'); } const projects = Array.isArray(catalog?.desktopProjects) ? catalog.desktopProjects : []; const found = projects.find((p) => p.projectId === projectId); return found?.name || projectId.slice(0, 8); } function syncModeControls() { if (!bodyMounted) return; modeSeg?.setProps({ ariaLabel: t('settings.oth.migModeLabel'), modelValue: migrationMode, options: smigGetModeOptions(), }); patchText( modeHintEl, migrationMode === 'clone' ? t('settings.oth.migModeCloneHint') : t('settings.oth.migModeMoveHint') ); } function formatMigrationError(code) { if (code === 'source_locked') return t('settings.oth.migErrLocked'); if (code === 'target_already_exists') return t('settings.oth.migErrExists'); if (code === 'session_running') return t('settings.oth.migErrRunning'); return t('settings.oth.migFailed', { reason: code || 'unknown_error' }); } function syncControlsAndList() { const visible = Boolean(catalog?.available); patchAttr(rootEl, 'hidden', !visible); if (!visible) { props?.onLayoutChange?.(); return; } ensureBodyMounted(); syncModeControls(); const detected = getDetectedClients(); const sourceOptions = detected .filter((c) => getTargetClientsFor(c.id).length > 0) .map((c) => ({ value: c.id, label: smigGetClientLabel(c.id), meta: String(c.sessionCount), })); const targetOptions = getTargetClientsFor(sourceClient).map((c) => ({ value: c.id, label: smigGetClientLabel(c.id), })); const projectOptions = (catalog?.desktopProjects || []).map((p) => p.isOutsideProject ? { value: p.projectId, label: t('settings.oth.migProjectOutside') } : { value: p.projectId, label: p.name || p.projectId.slice(0, 8), meta: p.workspacePath || '', } ); sourceSelect.setProps({ ariaLabel: t('settings.oth.migSourceLabel'), modelValue: sourceClient, options: sourceOptions, }); targetSelect.setProps({ ariaLabel: t('settings.oth.migTargetLabel'), modelValue: targetClient, options: targetOptions, }); projectSelect.setProps({ ariaLabel: t('settings.oth.migProjectLabel'), modelValue: targetProjectId, options: projectOptions, }); patchAttr(projectFieldWrap, 'hidden', targetClient !== 'desktop'); renderSessionList(); renderResultBox(); props?.onLayoutChange?.(); } function renderSessionList() { const all = getCurrentSourceSessions(); const filtered = getFilteredSessions(); // 清理已不在当前来源中的选中 ID const validSet = new Set(all.filter((s) => !s.isRunning).map((s) => s.cascadeId)); for (const id of [...selectedIds]) { if (!validSet.has(id)) selectedIds.delete(id); } const selectableFiltered = filtered.filter((s) => !s.isRunning); const allSelected = selectableFiltered.length > 0 && selectableFiltered.every((s) => selectedIds.has(s.cascadeId)); patchText( toggleAllBtn, allSelected ? t('settings.oth.migClearSel') : t('settings.oth.migSelectAll') ); patchAttr(toggleAllBtn, 'disabled', selectableFiltered.length === 0 || isMigrating); patchText( selectedCountEl, t('settings.oth.migSelectedCount', { selected: selectedIds.size, total: filtered.length, }) ); while (listEl.firstChild) { listEl.removeChild(listEl.firstChild); } if (all.length === 0) { listEl.appendChild(h('div', { className: 'smig-empty', text: t('settings.oth.migEmpty') })); } else if (filtered.length === 0) { listEl.appendChild( h('div', { className: 'smig-empty', text: t('settings.oth.migNoMatch') }) ); } else { for (const item of filtered) { const checked = selectedIds.has(item.cascadeId); const disabled = Boolean(item.isRunning || isMigrating); const checkIcon = createSvgIcon('check', { size: 10 }); patchAttr(checkIcon, 'hidden', !checked); const checkboxEl = h( 'span', { className: `select-checkbox smig-checkbox${checked ? ' is-checked' : ''}`, 'aria-hidden': 'true', }, [checkIcon] ); const toggleItem = () => { if (item.isRunning || isMigrating) return; if (selectedIds.has(item.cascadeId)) { selectedIds.delete(item.cascadeId); } else { selectedIds.add(item.cascadeId); } renderSessionList(); }; const metaParts = [t('settings.oth.migStepsUnit', { count: item.stepCount })]; const age = smigFormatAge(item.lastModifiedMs); if (age) metaParts.push(age); const subChildren = []; if (item.workspacePath || item.workspaceName) { subChildren.push( h('span', { className: 'smig-item-ws', text: item.workspacePath || item.workspaceName, title: item.workspacePath || item.workspaceName, }) ); } if (item.isRunning) { subChildren.push( h('span', { className: 'smig-item-running', text: t('settings.oth.migRunningTag'), }) ); } const rowEl = h( 'button', { type: 'button', role: 'checkbox', 'aria-checked': checked ? 'true' : 'false', disabled, className: `smig-item${checked ? ' is-selected' : ''}${item.isRunning ? ' is-running' : ''}`, onClick: toggleItem, }, [ checkboxEl, h('span', { className: 'smig-item-body' }, [ h('span', { className: 'smig-item-top' }, [ h('span', { className: 'smig-item-title', text: item.title || item.cascadeId.slice(0, 8), title: item.title || item.cascadeId, }), h('span', { className: 'smig-item-meta', text: metaParts.join(' · ') }), ]), ...(subChildren.length > 0 ? [h('span', { className: 'smig-item-sub' }, subChildren)] : []), ]), ] ); listEl.appendChild(rowEl); } } listScrollbar?.refresh?.(); patchAttr(migrateBtn, 'disabled', isMigrating || selectedIds.size === 0 || !targetClient); patchText( migrateBtnText, isMigrating ? t('settings.oth.migRunningBtn') : t('settings.oth.migActionBtn', { count: selectedIds.size }) ); } function renderResultBox() { if (!lastResult) { patchAttr(resultBoxEl, 'hidden', true); return; } patchAttr(resultBoxEl, 'hidden', false); patchClasses(resultBoxEl, { 'is-ok': Boolean(lastResult.ok), 'is-err': !lastResult.ok, }); while (resultBoxEl.firstChild) { resultBoxEl.removeChild(resultBoxEl.firstChild); } if (!lastResult.ok) { resultBoxEl.appendChild( h('div', { className: 'smig-result-msg', text: formatMigrationError(lastResult.error), }) ); return; } const partialSuffix = lastResult.failedCount > 0 ? t('settings.oth.migPartialWarn', { failed: lastResult.failedCount }) : ''; const baseMsg = lastResult.targetClient === 'cli' ? t('settings.oth.migDoneCli', { count: lastResult.migratedCount }) : t('settings.oth.migDoneDesktop', { count: lastResult.migratedCount, project: resolveProjectDisplayLabel(lastResult.targetProjectId), }); resultBoxEl.appendChild( h('div', { className: 'smig-result-msg', text: `${baseMsg}${partialSuffix}` }) ); if (lastResult.targetClient === 'desktop' && isWindowOverlayMode()) { resultBoxEl.appendChild( h('div', { className: 'smig-result-actions' }, [ h( 'button', { type: 'button', className: 'btn-secondary smig-result-btn', onClick: () => { if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { window.location.reload(); } }, }, [createSvgIcon('refresh', { size: 11 }), h('span', { text: t('settings.oth.migReloadBtn') })] ), ]) ); } if (lastResult.targetClient === 'cli') { const okItems = (lastResult.results || []).filter((r) => r.ok && r.resumeCommand); if (okItems.length > 0) { const cmdWrap = h('div', { className: 'smig-cmd-list' }); for (const item of okItems.slice(0, 6)) { const isCopied = copiedCmdId === item.newCascadeId; const copyBtn = h( 'button', { type: 'button', className: 'btn-ghost-sm smig-cmd-copy', text: isCopied ? t('settings.oth.migCopied') : t('settings.oth.migCopyCmd'), onClick: async () => { const ok = await copyPlainTextToClipboard(item.resumeCommand); if (!ok || destroyed) return; copiedCmdId = item.newCascadeId; renderResultBox(); if (copiedTimer) clearTimeout(copiedTimer); copiedTimer = setTimeout(() => { copiedTimer = null; if (!destroyed && copiedCmdId === item.newCascadeId) { copiedCmdId = ''; renderResultBox(); } }, 2000); }, } ); cmdWrap.appendChild( h('div', { className: 'smig-cmd-row' }, [ h('code', { className: 'smig-cmd-code', text: item.resumeCommand }), copyBtn, ]) ); } resultBoxEl.appendChild(cmdWrap); } } } async function loadCatalog(force = false) { if (isLoading || (hasLoadedOnce && !force)) return; isLoading = true; if (refreshBtn) patchAttr(refreshBtn, 'disabled', true); try { const res = await loadCatalogFn(); if (destroyed) return; hasLoadedOnce = true; if (res && typeof res === 'object') { catalog = res; ensureValidSelectionDefaults(); syncControlsAndList(); } } catch { // 本地目录或 API 暂不可用时静默隐藏卡片,避免干扰其他设置项 if (!destroyed && !catalog) { patchAttr(rootEl, 'hidden', true); } } finally { isLoading = false; if (refreshBtn) patchAttr(refreshBtn, 'disabled', false); } } async function handleMigrate() { if (isMigrating || selectedIds.size === 0 || !sourceClient || !targetClient) return; isMigrating = true; lastResult = null; renderSessionList(); renderResultBox(); try { const payload = { sourceClient, targetClient, mode: migrationMode, cascadeIds: [...selectedIds], ...(targetClient === 'desktop' ? { targetProjectId } : {}), }; const res = await runMigrateFn(payload); if (destroyed) return; lastResult = res || { ok: false, error: 'empty_response' }; if (res?.ok) { selectedIds.clear(); void loadCatalog(true); } } catch (err) { if (!destroyed) { lastResult = { ok: false, error: err?.message || 'request_failed' }; } } finally { isMigrating = false; if (!destroyed) { renderSessionList(); renderResultBox(); props?.onLayoutChange?.(); } } } function refreshLabels() { if (!bodyMounted) return; patchText(titleEl, t('settings.oth.migTitle')); patchText(descEl, t('settings.oth.migDesc')); patchText(refreshBtnText, t('settings.oth.migRefreshBtn')); patchText(sourceLabelEl, t('settings.oth.migSourceLabel')); patchText(targetLabelEl, t('settings.oth.migTargetLabel')); patchText(modeLabelEl, t('settings.oth.migModeLabel')); syncModeControls(); patchText(projectLabelEl, t('settings.oth.migProjectLabel')); patchAttr(searchInput, 'placeholder', t('settings.oth.migSearchPlaceholder')); patchAttr(searchClearBtn, 'aria-label', t('select.clearSearch')); if (catalog?.available) { syncControlsAndList(); } } onCleanup(() => { destroyed = true; if (copiedTimer) { clearTimeout(copiedTimer); copiedTimer = null; } modeSeg?.destroy?.(); listScrollbar?.destroy?.(); sourceSelect?.destroy?.(); targetSelect?.destroy?.(); projectSelect?.destroy?.(); }); return { el: rootEl, refs: { ensureLoaded: () => loadCatalog(false), reload: () => loadCatalog(true), refreshLabels, }, }; }, }); return { SessionMigrationCard }; })(); // --- src/components/settings/HostI18nCard.js --- const { HostI18nCard } = (() => { /** * @fileoverview Self-contained Antigravity Host UI Language card (`HostI18nCard.js`). * * Mounted inside `SettingsGeneralTab` with minimal glue; manages: * - Language selection (`off` or any pack listed in repository `manifest.json`), * - Conditional Light / Deep translation depth switching (0-network hot switch), * - On-demand repository pack download, update, and local cache removal, * - CDP bridge notice when DevTools port is unavailable, * - Optional collapsed developer drawer to collect untranslated UI strings. */ function formatHostI18nBytes(bytes) { const num = Number(bytes || 0); if (!Number.isFinite(num) || num <= 0) return ''; if (num < 1024) return `${num} B`; return `${(num / 1024).toFixed(1)} KB`; } function getHostI18nDepthOptions() { return [ { value: 'light', label: t('settings.hostI18n.depthLight') }, { value: 'deep', label: t('settings.hostI18n.depthDeep') }, ]; } const HostI18nCard = defineComponent({ name: 'HostI18nCard', setup({ props, onCleanup }) { let status = null; let draftLocale = HOST_I18N_OFF_LOCALE; let draftDepth = 'light'; let latestWindowBridge = null; let latestHostPlatform = 'win32'; let lastBridgeRenderSig = ''; let hasLoadedOnce = false; let isBusy = false; let isCollecting = false; let destroyed = false; let feedbackTimer = null; let devExpanded = false; let lastCollected = null; const titleEl = h('span', { text: t('settings.hostI18n.title') }); const statusMsgEl = h('span', { className: 'text-muted host-i18n-status-msg', text: '', }); function showFeedback(text, { isError = false, autoClearMs = 2800 } = {}) { if (feedbackTimer) { clearTimeout(feedbackTimer); feedbackTimer = null; } patchText(statusMsgEl, text || ''); patchClasses(statusMsgEl, { 'is-error': Boolean(isError && text) }); if (text && autoClearMs > 0) { feedbackTimer = setTimeout(() => { feedbackTimer = null; if (!destroyed) { patchText(statusMsgEl, ''); patchClasses(statusMsgEl, { 'is-error': false }); } }, autoClearMs); } } function getPackList() { return Array.isArray(status?.packs) ? status.packs : []; } function findPackByLocale(locale) { return getPackList().find((p) => p.locale === locale) || null; } function buildLocaleOptions() { const opts = [{ value: HOST_I18N_OFF_LOCALE, label: t('settings.hostI18n.langOff') }]; for (const pack of getPackList()) { const displayName = pack.nativeName && pack.nativeName !== pack.name ? `${pack.nativeName} (${pack.locale})` : `${pack.name || pack.locale} (${pack.locale})`; const tag = pack.installed ? t('settings.hostI18n.optInstalled', { ver: pack.installedVersion || pack.remoteVersion || '1.0.0' }) : t('settings.hostI18n.optRemote', { size: formatHostI18nBytes(pack.remoteBytes) || 'pack', }); opts.push({ value: pack.locale, label: `${displayName} · ${tag}`, }); } if ( draftLocale !== HOST_I18N_OFF_LOCALE && !opts.some((o) => o.value === draftLocale) ) { opts.push({ value: draftLocale, label: draftLocale }); } return opts; } const langLabelEl = h('span', { className: 'form-label', text: t('settings.hostI18n.langLabel'), }); const langSelect = CustomSelect({ ariaLabel: t('settings.hostI18n.langLabel'), icon: 'globe', modelValue: draftLocale, options: buildLocaleOptions(), onUpdateModelValue: async (val) => { if (isBusy || destroyed) return; const nextLocale = normalizeHostI18nLocale(val); const targetPack = findPackByLocale(nextLocale); const needsDownload = nextLocale !== HOST_I18N_OFF_LOCALE && !targetPack?.installed; isBusy = true; draftLocale = nextLocale; syncControls(); showFeedback( needsDownload ? t('settings.hostI18n.downloadingMsg', { locale: nextLocale }) : t('settings.saving'), { autoClearMs: 0 } ); try { const res = await selectHostI18nLanguage(nextLocale, draftDepth); if (destroyed) return; applyStatusPayload(res); if (res?.ok === false) { showFeedback(res.error || t('settings.hostI18n.actionFailed'), { isError: true, autoClearMs: 5000, }); } else if (nextLocale === HOST_I18N_OFF_LOCALE) { showFeedback(t('settings.hostI18n.disabledMsg'), { autoClearMs: 2500 }); } else if (res?.downloaded) { showFeedback(t('settings.hostI18n.downloadedAndAppliedMsg'), { autoClearMs: 3200 }); } else { showFeedback(t('settings.hostI18n.appliedMsg'), { autoClearMs: 2200 }); } } catch (err) { if (!destroyed) { if (status) applyStatusPayload(status); showFeedback(err?.message || t('settings.hostI18n.actionFailed'), { isError: true, autoClearMs: 5000, }); } } finally { isBusy = false; if (!destroyed) { syncControls(); props.onLayoutChange?.(); } } }, }); const refreshManifestBtn = h( 'button', { type: 'button', className: 'btn-ghost-sm host-i18n-icon-btn', title: t('settings.hostI18n.refreshManifestTip'), 'aria-label': t('settings.hostI18n.refreshManifestTip'), onClick: async () => { if (isBusy || destroyed) return; isBusy = true; syncControls(); showFeedback(t('settings.hostI18n.refreshingManifestMsg'), { autoClearMs: 0 }); try { const res = await refreshHostI18nManifest(); if (destroyed) return; applyStatusPayload(res); if (res?.ok === false) { showFeedback(res.error || t('settings.hostI18n.manifestFailedMsg'), { isError: true, autoClearMs: 4500, }); } else { showFeedback( t('settings.hostI18n.manifestSyncedMsg', { count: getPackList().length }), { autoClearMs: 2600 } ); } } catch (err) { if (!destroyed) { showFeedback(err?.message || t('settings.hostI18n.manifestFailedMsg'), { isError: true, autoClearMs: 4500, }); } } finally { isBusy = false; if (!destroyed) { syncControls(); props.onLayoutChange?.(); } } }, }, [createSvgIcon('refresh', { size: 12 })] ); const langHintEl = h('span', { className: 'settings-hint-text', text: t('settings.hostI18n.langHint'), }); // --- Conditional Depth Row (visible only when locale !== 'off') --- const depthLabelEl = h('span', { className: 'form-label', text: t('settings.hostI18n.depthLabel'), }); const depthSwitch = SegmentedControl({ ariaLabel: t('settings.hostI18n.depthLabel'), modelValue: draftDepth, options: getHostI18nDepthOptions(), onUpdateModelValue: async (val) => { if (isBusy || destroyed) return; const nextDepth = normalizeHostI18nDepth(val); if (nextDepth === draftDepth) return; isBusy = true; draftDepth = nextDepth; syncControls(); showFeedback(t('settings.saving'), { autoClearMs: 0 }); try { const res = await updateHostI18nDepth(nextDepth); if (destroyed) return; applyStatusPayload(res); showFeedback(t('settings.hostI18n.depthSwitchedMsg'), { autoClearMs: 2000 }); } catch (err) { if (!destroyed) { if (status) applyStatusPayload(status); showFeedback(err?.message || t('settings.saveFailed'), { isError: true, autoClearMs: 3500, }); } } finally { isBusy = false; if (!destroyed) syncControls(); } }, }); const depthHintEl = h('span', { className: 'settings-hint-text', text: t('settings.hostI18n.depthLightHint'), }); const depthRowEl = h('div', { className: 'form-row', hidden: true }, [ depthLabelEl, depthSwitch.el, depthHintEl, ]); // --- Pack Meta & Actions Bar (visible only when locale !== 'off') --- const packMetaTextEl = h('span', { className: 'host-i18n-pack-meta text-muted', text: '' }); const updatePackBtnText = h('span', { text: t('settings.hostI18n.redownloadBtn') }); const updatePackBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return; isBusy = true; syncControls(); showFeedback(t('settings.hostI18n.downloadingMsg', { locale: draftLocale }), { autoClearMs: 0, }); try { const res = await installOrUpdateHostI18nPack(draftLocale); if (destroyed) return; applyStatusPayload(res); if (res?.ok === false) { showFeedback(res.error || t('settings.hostI18n.actionFailed'), { isError: true, autoClearMs: 5000, }); } else { showFeedback(t('settings.hostI18n.packUpdatedMsg'), { autoClearMs: 3000 }); } } catch (err) { if (!destroyed) { showFeedback(err?.message || t('settings.hostI18n.actionFailed'), { isError: true, autoClearMs: 5000, }); } } finally { isBusy = false; if (!destroyed) syncControls(); } }, }, [createSvgIcon('download', { size: 12 }), updatePackBtnText] ); const removePackBtnText = h('span', { text: t('settings.hostI18n.removeCacheBtn') }); const removePackBtn = h( 'button', { type: 'button', className: 'btn-ghost-sm', onClick: async () => { if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return; isBusy = true; syncControls(); showFeedback(t('settings.saving'), { autoClearMs: 0 }); try { const res = await removeHostI18nPack(draftLocale); if (destroyed) return; applyStatusPayload(res); showFeedback(t('settings.hostI18n.cacheRemovedMsg'), { autoClearMs: 2800 }); } catch (err) { if (!destroyed) { showFeedback(err?.message || t('settings.hostI18n.actionFailed'), { isError: true, autoClearMs: 4500, }); } } finally { isBusy = false; if (!destroyed) { syncControls(); props.onLayoutChange?.(); } } }, }, [removePackBtnText] ); const packBarEl = h('div', { className: 'host-i18n-pack-bar', hidden: true }, [ packMetaTextEl, h('div', { className: 'host-i18n-pack-actions' }, [updatePackBtn, removePackBtn]), ]); // --- CDP Bridge Diagnostic Notice (shown only when active locale cannot reach CDP) --- const bridgeNotice = BridgeStatusNotice({ contextMode: true }); // --- Collapsed Developer Drawer: Untranslated UI String Collector --- const devChevron = createSvgIcon('chevron-right', { size: 11, className: 'host-i18n-dev-chevron', }); const devToggleText = h('span', { text: t('settings.hostI18n.devToolsTitle') }); const devToggleBtn = h( 'button', { type: 'button', className: 'host-i18n-dev-toggle', 'aria-expanded': 'false', onClick: () => { devExpanded = !devExpanded; patchAttr(devToggleBtn, 'aria-expanded', devExpanded ? 'true' : 'false'); patchClasses(devDrawerEl, { 'is-expanded': devExpanded }); patchAttr(devBodyEl, 'hidden', !devExpanded); props.onLayoutChange?.(); }, }, [devChevron, devToggleText] ); const devHintEl = h('span', { className: 'settings-hint-text', text: t('settings.hostI18n.devToolsHint'), }); const collectBtnText = h('span', { text: t('settings.hostI18n.collectBtn') }); const collectResultEl = h('span', { className: 'settings-hint-text', text: '' }); const copyCollectedBtnText = h('span', { text: t('settings.hostI18n.copyJsonBtn') }); const copyCollectedBtn = h( 'button', { type: 'button', className: 'btn-ghost-sm', hidden: true, onClick: async () => { if (!lastCollected?.template) return; await copyTextWithFeedback(JSON.stringify(lastCollected.template, null, 2), { onFeedback: (msg) => showFeedback(msg, { autoClearMs: 2400 }), }); }, }, [createSvgIcon('copy', { size: 11 }), copyCollectedBtnText] ); const exportCollectedBtnText = h('span', { text: t('settings.hostI18n.exportJsonBtn') }); const exportCollectedBtn = h( 'button', { type: 'button', className: 'btn-ghost-sm', hidden: true, onClick: async () => { if (!lastCollected?.template) return; const fileLocale = draftLocale === HOST_I18N_OFF_LOCALE ? 'en-source' : draftLocale; await exportTextFileWithFeedback({ filename: `host-i18n-missing-${fileLocale}.json`, content: JSON.stringify(lastCollected.template, null, 2) + '\n', mimeType: 'application/json', onFeedback: (msg) => showFeedback(msg, { autoClearMs: 3200 }), }); }, }, [createSvgIcon('download', { size: 11 }), exportCollectedBtnText] ); const collectBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { if (isCollecting || destroyed) return; isCollecting = true; patchAttr(collectBtn, 'disabled', true); patchText(collectBtnText, t('settings.hostI18n.collectingBtn')); try { const res = await collectHostI18nUntranslated(); if (destroyed) return; if (res?.ok) { lastCollected = res; patchText( collectResultEl, res.count > 0 ? t('settings.hostI18n.collectedResult', { count: res.count, targets: res.targets || 1, }) : t('settings.hostI18n.collectedEmpty') ); patchAttr(copyCollectedBtn, 'hidden', !(res.count > 0)); patchAttr(exportCollectedBtn, 'hidden', !(res.count > 0)); } else { patchText(collectResultEl, res?.error || t('settings.hostI18n.collectFailed')); } } catch (err) { if (!destroyed) { patchText(collectResultEl, err?.message || t('settings.hostI18n.collectFailed')); } } finally { isCollecting = false; if (!destroyed) { patchAttr(collectBtn, 'disabled', false); patchText(collectBtnText, t('settings.hostI18n.collectBtn')); props.onLayoutChange?.(); } } }, }, [createSvgIcon('search', { size: 12 }), collectBtnText] ); const devBodyEl = h('div', { className: 'host-i18n-dev-body', hidden: true }, [ devHintEl, h('div', { className: 'host-i18n-dev-actions' }, [ collectBtn, copyCollectedBtn, exportCollectedBtn, ]), collectResultEl, ]); const devDrawerEl = h('div', { className: 'host-i18n-dev-drawer' }, [ devToggleBtn, devBodyEl, ]); const rootEl = h('section', { className: 'panel host-i18n-panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('globe', { size: 13 }), titleEl, ]), statusMsgEl, ]), h('div', { className: 'form-row' }, [ langLabelEl, h('div', { className: 'host-i18n-select-row' }, [langSelect.el, refreshManifestBtn]), langHintEl, ]), depthRowEl, packBarEl, bridgeNotice.el, devDrawerEl, ]); function applyStatusPayload(payload) { if (!payload || typeof payload !== 'object') return; status = payload; draftLocale = normalizeHostI18nLocale(payload.locale); draftDepth = normalizeHostI18nDepth(payload.depth); if (payload.bridgeStatus) { latestWindowBridge = payload.bridgeStatus; } syncControls(); } function syncControls() { const enabled = draftLocale !== HOST_I18N_OFF_LOCALE; const activePack = enabled ? findPackByLocale(draftLocale) : null; langSelect.setProps({ modelValue: draftLocale, options: buildLocaleOptions(), disabled: isBusy, }); patchAttr(refreshManifestBtn, 'disabled', isBusy); patchAttr(depthRowEl, 'hidden', !enabled); depthSwitch.setProps({ modelValue: draftDepth, options: getHostI18nDepthOptions(), }); patchText( depthHintEl, draftDepth === 'deep' ? t('settings.hostI18n.depthDeepHint') : t('settings.hostI18n.depthLightHint') ); patchAttr(packBarEl, 'hidden', !enabled); if (enabled) { const ver = activePack?.installedVersion || activePack?.remoteVersion || '1.0.0'; const stats = activePack?.stats; const entryCount = stats ? Number(stats.baseExact || 0) + Number(draftDepth === 'deep' ? stats.deepExact || 0 : stats.lightExact || 0) + Number(stats.basePatterns || 0) + Number(draftDepth === 'deep' ? stats.deepPatterns || 0 : stats.lightPatterns || 0) : 0; const sizeStr = formatHostI18nBytes( activePack?.installedBytes || activePack?.remoteBytes || 0 ); const appliedCount = Number(latestWindowBridge?.hostI18nAppliedCount || 0); const metaParts = [`v${ver}`]; if (entryCount > 0) { metaParts.push(t('settings.hostI18n.entriesCount', { count: entryCount })); } if (sizeStr) metaParts.push(sizeStr); if (appliedCount > 0) { metaParts.push(t('settings.hostI18n.appliedWindows', { count: appliedCount })); } patchText(packMetaTextEl, metaParts.join(' · ')); const hasUpdate = Boolean(activePack?.updateAvailable); patchText( updatePackBtnText, hasUpdate ? t('settings.hostI18n.updatePackBtn', { ver: activePack.remoteVersion }) : t('settings.hostI18n.redownloadBtn') ); patchClasses(updatePackBtn, { 'btn-primary': hasUpdate, 'btn-secondary': !hasUpdate, }); patchAttr(updatePackBtn, 'disabled', isBusy); patchAttr(removePackBtn, 'disabled', isBusy || !activePack?.installed); } bridgeNotice.refs.update({ visible: enabled, windowBridge: latestWindowBridge, hostPlatform: latestHostPlatform, contextMode: true, }); } async function load(force = false) { if (destroyed) return; if (hasLoadedOnce && !force) return; hasLoadedOnce = true; try { const res = await fetchHostI18nStatus(); if (destroyed) return; applyStatusPayload(res); props.onLayoutChange?.(); } catch { // 静默兜底,保留手动刷新入口 } } function renderBridgeStatus(windowBridge, hostPlatform) { if (windowBridge) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; const sig = [ Number(latestWindowBridge?.hostI18nAppliedCount || 0), Boolean(latestWindowBridge?.connected), Boolean(latestWindowBridge?.available), String(latestWindowBridge?.reason || ''), String(latestWindowBridge?.ideStatus?.reason || ''), String(latestHostPlatform || ''), ].join('|'); if (sig === lastBridgeRenderSig) return; lastBridgeRenderSig = sig; syncControls(); } function refreshLabels() { patchText(titleEl, t('settings.hostI18n.title')); patchText(langLabelEl, t('settings.hostI18n.langLabel')); patchText(langHintEl, t('settings.hostI18n.langHint')); patchText(depthLabelEl, t('settings.hostI18n.depthLabel')); patchText(removePackBtnText, t('settings.hostI18n.removeCacheBtn')); patchText(devToggleText, t('settings.hostI18n.devToolsTitle')); patchText(devHintEl, t('settings.hostI18n.devToolsHint')); if (!isCollecting) patchText(collectBtnText, t('settings.hostI18n.collectBtn')); patchText(copyCollectedBtnText, t('settings.hostI18n.copyJsonBtn')); patchText(exportCollectedBtnText, t('settings.hostI18n.exportJsonBtn')); patchAttr(refreshManifestBtn, 'title', t('settings.hostI18n.refreshManifestTip')); patchAttr(refreshManifestBtn, 'aria-label', t('settings.hostI18n.refreshManifestTip')); bridgeNotice.refs.refreshLabels(); syncControls(); } onCleanup(() => { destroyed = true; abortSidecarApiKey('host-i18n-get'); if (feedbackTimer) { clearTimeout(feedbackTimer); feedbackTimer = null; } langSelect.destroy(); depthSwitch.destroy(); bridgeNotice.destroy(); }); return { el: rootEl, refs: { langSelect, depthSwitch, load, renderBridgeStatus, refreshLabels, }, }; }, }); return { HostI18nCard }; })(); // --- src/views/settings/SettingsGeneralTab.js --- const { SettingsGeneralTab } = (() => { /** * @fileoverview Preferences Tab 1: `SettingsGeneralTab.js` ("常规"). * Manages UI Language (`zh-CN` / `en-US` / `auto`), Theme Accent (`host` + 6 swatches), * Panel Font Scale (`sm` / `md` / `lg` / `xl`), Pricing Sync, and Plugin Updates. */ function getLanguageOptions() { return [ { value: 'auto', label: t('settings.gen.langAuto') }, { value: 'zh-CN', label: t('settings.gen.langZh') }, { value: 'en-US', label: t('settings.gen.langEn') }, ]; } function getFontScaleOptions() { return [ { value: 'sm', label: t('settings.gen.fontSm') }, { value: 'md', label: t('settings.gen.fontMd') }, { value: 'lg', label: t('settings.gen.fontLg') }, { value: 'xl', label: t('settings.gen.fontXl') }, ]; } function getUpdateModeOptions() { return [ { value: 'manual', label: t('settings.gen.updateManual') }, { value: 'auto', label: t('settings.gen.updateAuto') }, { value: 'off', label: t('settings.gen.updateOff') }, ]; } function formatCloudSyncTimeText(tsMs, updatedAt) { if (Number(tsMs) > 0) { const d = new Date(Number(tsMs)); const pad = (n) => String(n).padStart(2, '0'); const timeStr = `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; return t('settings.gen.syncAt', { time: timeStr }); } if (updatedAt) { return t('settings.gen.pubAt', { date: String(updatedAt).slice(0, 10) }); } return t('settings.gen.defaultPricing'); } const SettingsGeneralTab = defineComponent({ name: 'SettingsGeneralTab', setup({ props, onCleanup }) { let draftLanguage = 'auto'; let draftThemeAccent = 'host'; let draftFontScale = 'md'; let draftModernUi = true; let draftPluginUpdateMode = 'manual'; let latestSettings = null; let latestCloudStatus = null; let appearanceTimer = null; let appearanceSaveSeq = 0; let cloudTimer = null; const appearanceStatusText = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: '', }); const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: '', }); function showAppearanceFeedback(text, autoClearMs = 1500) { if (appearanceTimer) { clearTimeout(appearanceTimer); appearanceTimer = null; } patchText(appearanceStatusText, text); if (text && autoClearMs > 0) { appearanceTimer = setTimeout(() => { appearanceTimer = null; patchText(appearanceStatusText, ''); }, autoClearMs); } } function showCloudFeedback(text, autoClearMs = 3500) { if (cloudTimer) { clearTimeout(cloudTimer); cloudTimer = null; } patchText(cloudStatusMsg, text); if (text && autoClearMs > 0) { cloudTimer = setTimeout(() => { cloudTimer = null; patchText(cloudStatusMsg, ''); }, autoClearMs); } } // --- Card 1: 界面与外观 --- const appearanceTitleEl = h('span', { text: t('settings.gen.appearanceTitle') }); const langLabelEl = h('span', { className: 'form-label', text: t('settings.gen.language') }); const accentLabelEl = h('span', { className: 'form-label', text: t('settings.gen.themeAccent'), }); const fontLabelEl = h('span', { className: 'form-label', text: t('settings.gen.fontScale') }); const fontHintEl = h('span', { 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'), modelValue: draftLanguage, options: getLanguageOptions(), onUpdateModelValue: async (val) => { const nextLang = normalizeI18nLanguage(val); draftLanguage = nextLang; setI18nLanguage(nextLang); languageSwitch.setValue(nextLang); const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ language: nextLang }); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saved'), 1500); } } catch { if (latestSettings) renderSettings(latestSettings); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saveFailed'), 2500); } } }, }); const themeColorPicker = ThemeColorPicker({ modelValue: draftThemeAccent, onUpdateModelValue: async (val) => { const nextAccent = normalizeClientThemeAccent(val); draftThemeAccent = nextAccent; themeColorPicker.refs.setValue(nextAccent); const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ themeAccent: nextAccent }); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saved'), 1500); } } catch { if (latestSettings) renderSettings(latestSettings); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saveFailed'), 2500); } } }, }); const fontScaleSwitch = SegmentedControl({ ariaLabel: t('settings.gen.fontScale'), modelValue: draftFontScale, options: getFontScaleOptions(), onUpdateModelValue: async (val) => { const nextScale = normalizeClientFontScale(val); draftFontScale = nextScale; fontScaleSwitch.setValue(nextScale); const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ fontScale: nextScale }); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saved'), 1500); } props.onLayoutChange?.(); } catch { if (latestSettings) renderSettings(latestSettings); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saveFailed'), 2500); } } }, }); const modernUiSwitch = ToggleSwitch({ ariaLabelKey: 'settings.gen.modernUi', preset: 'modernUi', modelValue: 'on', onUpdateModelValue: async (val) => { const nextModernUi = val !== 'off'; draftModernUi = nextModernUi; modernUiSwitch.setValue(nextModernUi ? 'on' : 'off'); if (!isWindowOverlayMode() && typeof document !== 'undefined' && document.documentElement) { applyAppearanceToRoot( document.documentElement, { ...(latestSettings || {}), themeAccent: draftThemeAccent, fontScale: draftFontScale, modernUi: nextModernUi, experimentalModernUi: nextModernUi, }, { includeFontScale: true } ); } const saveToken = ++appearanceSaveSeq; showAppearanceFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ modernUi: nextModernUi }); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saved'), 1500); } props.onLayoutChange?.(); } catch { if (latestSettings) renderSettings(latestSettings); if (saveToken === appearanceSaveSeq) { showAppearanceFeedback(t('settings.saveFailed'), 2500); } } }, }); const appearancePanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('sliders', { size: 13 }), appearanceTitleEl, ]), appearanceStatusText, ]), 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: 版本更新 --- const updateTitleEl = h('span', { text: t('settings.gen.updateTitle') }); const updateModeLabelEl = h('span', { className: 'form-label', text: t('settings.gen.updateMode'), }); const pricingCellLabelEl = h('span', { className: 'cell-label', text: t('settings.gen.pricingLabel'), }); const versionCellLabelEl = h('span', { className: 'cell-label', text: t('settings.gen.versionLabel'), }); const autoUpdateSelect = CustomSelect({ modelValue: 'manual', icon: 'refresh', options: getUpdateModeOptions(), onUpdateModelValue: async (val) => { const nextMode = normalizeClientUpdateMode(val); draftPluginUpdateMode = nextMode; autoUpdateSelect.setValue(nextMode); if (latestCloudStatus) { renderCloudStatus(latestCloudStatus); } showCloudFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ pluginUpdateMode: nextMode, autoUpdatePlugin: nextMode === 'auto', }); showCloudFeedback(t('settings.saved'), 1800); } catch { if (latestSettings) renderSettings(latestSettings); if (latestCloudStatus) renderCloudStatus(latestCloudStatus); showCloudFeedback(t('settings.saveFailed'), 2500); } }, }); const pricingCountVal = h('strong', { className: 'cell-value', text: '—' }); const pricingSyncSub = h('span', { className: 'cell-sub', text: t('quota.loading') }); const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.4' }); const versionSub = h('span', { className: 'cell-sub', text: t('settings.gen.checkingBtn') }); const syncPricingBtnText = h('span', { text: t('settings.gen.syncBtn') }); const syncPricingBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { patchAttr(syncPricingBtn, 'disabled', true); patchText(syncPricingBtnText, t('settings.gen.syncingBtn')); showCloudFeedback(t('settings.gen.syncingMsg'), 0); try { const res = await triggerCloudSync(); const cs = res?.cloudStatus; if (res?.ok && cs) { showCloudFeedback(t('settings.gen.syncedMsg', { count: cs.modelCount }), 3500); } else { showCloudFeedback(cs?.lastSyncError || t('settings.gen.syncFallbackMsg'), 4500); } } catch (err) { showCloudFeedback(err?.message || t('settings.gen.syncFallbackMsg'), 4500); } finally { patchAttr(syncPricingBtn, 'disabled', false); patchText(syncPricingBtnText, t('settings.gen.syncBtn')); } }, }, [createSvgIcon('refresh', { size: 12 }), syncPricingBtnText] ); const updatePluginBtnText = h('span', { text: t('settings.gen.checkUpdateBtn') }); const updatePluginBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { patchAttr(updatePluginBtn, 'disabled', true); try { if (!latestCloudStatus?.updateAvailable) { patchText(updatePluginBtnText, t('settings.gen.checkingBtn')); showCloudFeedback(t('settings.gen.checkingMsg'), 0); const syncRes = await triggerCloudSync(); const cs = syncRes?.cloudStatus || latestCloudStatus; if (cs) { latestCloudStatus = cs; renderCloudStatus(cs); } if (!syncRes?.ok && cs?.lastSyncError) { showCloudFeedback( t('settings.gen.checkFailedMsg', { err: cs.lastSyncError }), 5000 ); return; } if (!cs?.updateAvailable) { const curVer = cs?.currentPluginVersion || '1.4.4'; showCloudFeedback(t('settings.gen.upToDateMsg', { ver: curVer }), 4500); return; } } patchText(updatePluginBtnText, t('capsule.updating')); showCloudFeedback(t('settings.gen.downloadingMsg'), 0); const res = await triggerPluginUpdate(); if (res?.cloudStatus) { latestCloudStatus = res.cloudStatus; } if (res?.ok) { showCloudFeedback(res.message || t('settings.gen.updatedRestartMsg'), 5000); } else { showCloudFeedback(res?.message || t('settings.gen.updateSkippedMsg'), 5500); } } catch (err) { showCloudFeedback(err?.message || t('settings.gen.updateFailedMsg'), 5000); } finally { patchAttr(updatePluginBtn, 'disabled', false); renderCloudStatus(latestCloudStatus); } }, }, [createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText] ); const cloudPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('bolt', { size: 13 }), updateTitleEl, ]), cloudStatusMsg, ]), h('div', { className: 'form-row' }, [updateModeLabelEl, autoUpdateSelect.el]), h('div', { className: 'dual-grid' }, [ h('div', { className: 'matrix-cell' }, [ pricingCellLabelEl, pricingCountVal, pricingSyncSub, ]), h('div', { className: 'matrix-cell' }, [versionCellLabelEl, versionVal, versionSub]), ]), h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]), ]); const hostI18nCard = HostI18nCard({ onLayoutChange: () => props.onLayoutChange?.(), }); const rootEl = h('div', { className: 'settings-tab-stack' }, [ appearancePanel, hostI18nCard.el, cloudPanel, ]); function renderSettings(settings, windowBridge = null, hostPlatform = 'win32') { if (windowBridge || hostPlatform) { hostI18nCard.refs.renderBridgeStatus(windowBridge, hostPlatform); } if (!settings) return; latestSettings = settings; draftLanguage = normalizeI18nLanguage(settings.language); draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent); draftFontScale = normalizeClientFontScale(settings.fontScale); draftModernUi = resolveSettingsModernUi(settings); draftPluginUpdateMode = normalizeClientUpdateMode( settings.pluginUpdateMode, settings.autoUpdatePlugin ); languageSwitch.setProps({ modelValue: draftLanguage, options: getLanguageOptions(), }); themeColorPicker.refs.setValue(draftThemeAccent); fontScaleSwitch.setProps({ modelValue: draftFontScale, options: getFontScaleOptions(), }); modernUiSwitch.setProps({ modelValue: draftModernUi ? 'on' : 'off', }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), }); } function renderCloudStatus(cs) { if (!cs) return; latestCloudStatus = cs; const srcLabel = cs.source === 'remote' ? t('settings.gen.srcRemote') : cs.source === 'local' ? t('settings.gen.srcLocal') : t('settings.gen.srcDefault'); patchText(pricingCountVal, t('settings.gen.modelCount', { count: cs.modelCount || 0 })); patchText( pricingSyncSub, `${srcLabel} · ${formatCloudSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}` ); const curVer = cs.currentPluginVersion || '1.4.4'; const latVer = cs.latestPluginVersion || curVer; const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP'; patchText(versionVal, `v${curVer}`); if (cs.updateAvailable && draftPluginUpdateMode !== 'off') { patchText(versionSub, t('settings.gen.canUpgradeSub', { ver: latVer, mode: modeTag })); patchClasses(versionSub, { 'accent-ok': true }); patchText(updatePluginBtnText, t('settings.gen.upgradeToBtn', { ver: latVer })); patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false }); } else if (draftPluginUpdateMode === 'off') { patchText(versionSub, t('settings.gen.updateOffSub', { mode: modeTag })); patchClasses(versionSub, { 'accent-ok': false }); patchText( updatePluginBtnText, cs.updateAvailable ? t('settings.gen.manualUpgradeBtn', { ver: latVer }) : t('settings.gen.checkUpdateBtn') ); patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true }); } else { patchText(versionSub, t('settings.gen.latestSub', { mode: modeTag })); patchClasses(versionSub, { 'accent-ok': false }); patchText(updatePluginBtnText, t('settings.gen.checkUpdateBtn')); patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true }); } if ( !cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message)) ) { showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500); } } function refreshLabels() { patchText(appearanceTitleEl, t('settings.gen.appearanceTitle')); patchText(langLabelEl, t('settings.gen.language')); 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')); patchText(versionCellLabelEl, t('settings.gen.versionLabel')); if (!syncPricingBtn.hasAttribute('disabled')) { patchText(syncPricingBtnText, t('settings.gen.syncBtn')); } languageSwitch.setProps({ modelValue: draftLanguage, options: getLanguageOptions(), }); themeColorPicker.refs.refreshLabels(); fontScaleSwitch.setProps({ modelValue: draftFontScale, options: getFontScaleOptions(), }); modernUiSwitch.setProps({ modelValue: draftModernUi ? 'on' : 'off', }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, options: getUpdateModeOptions(), }); if (latestCloudStatus) { renderCloudStatus(latestCloudStatus); } else { patchText(pricingSyncSub, t('quota.loading')); } hostI18nCard.refs.refreshLabels(); } onCleanup(() => { if (appearanceTimer) clearTimeout(appearanceTimer); if (cloudTimer) clearTimeout(cloudTimer); languageSwitch.destroy(); themeColorPicker.destroy(); fontScaleSwitch.destroy(); modernUiSwitch.destroy(); autoUpdateSelect.destroy(); hostI18nCard.destroy(); }); return { el: rootEl, refs: { languageSwitch, themeColorPicker, fontScaleSwitch, modernUiSwitch, autoUpdateSelect, syncPricingBtn, updatePluginBtn, hostI18nCard, loadHostI18n: (force = false) => hostI18nCard.refs.load(force), renderSettings, renderCloudStatus, refreshLabels, }, }; }, }); return { SettingsGeneralTab }; })(); // --- src/views/settings/SettingsStructureTab.js --- const { SettingsStructureTab } = (() => { /** * @fileoverview Preferences Tab 2: `SettingsStructureTab.js` ("结构"). * Organizes the 4 structure settings panes under a dedicated 3rd-level menu bar, * renders live previews powered by the decoupled real UI components (`CapsuleBarWidget`, * `createDynamicWidgetHost` in `hover` / `overview` modes, and `StepTableWidget`) * with simulated telemetry, and supports smooth mouse drag-and-drop reordering. */ const STRUCTURE_THIRD_TABS = Object.freeze([ { key: 'mount', icon: 'dock', labelKey: 'settings.str.tabMount' }, { key: 'hover', icon: 'layers', labelKey: 'settings.str.tabHover' }, { key: 'overview', icon: 'pulse', labelKey: 'settings.str.tabOverview' }, { key: 'steps', icon: 'table', labelKey: 'settings.str.tabSteps' }, ]); function normalizeStructureTabKey(raw) { const k = String(raw || '').trim(); return k === 'hover' || k === 'overview' || k === 'steps' ? k : 'mount'; } function getMountModeOptions() { return [ { value: 'dual', label: t('settings.str.mountDual') }, { value: 'composer', label: t('settings.str.mountComposer') }, { value: 'sidebar', label: t('settings.str.mountSidebar') }, ]; } function getPopoverWidthModeOptions() { return [ { value: 'auto', label: t('settings.str.popoverWidthAuto') }, { value: 'custom', label: t('settings.str.popoverWidthCustom') }, ]; } function getContextAgentModeOptions() { return [ { value: 'main', label: t('settings.str.contextAgentMain') }, { value: 'auto', label: t('settings.str.contextAgentAuto') }, ]; } function isSameList(a, b) { if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false; for (let i = 0; i < a.length; i += 1) { if (a[i] !== b[i]) return false; } return true; } function formatCliPreviewSlot(slotKey, slotCtx, isEn) { const safeCtx = slotCtx || {}; const quotas = safeCtx.quotas || {}; const quotaPct = (key, fallback) => { const summary = resolveSpecificQuotaSlotSummary(quotas, key); return summary && Number.isFinite(summary.roundedPct) ? summary.roundedPct : fallback; }; switch (slotKey) { case 'tps': { const val = Number.isFinite(Number(safeCtx.tps)) ? Number(safeCtx.tps).toFixed(1) : '68.4'; return { prefix: '', text: `${val} t/s`, tone: 'good', pillPct: null }; } case 'avg_tps': { const val = Number.isFinite(Number(safeCtx.avgTps)) ? Number(safeCtx.avgTps).toFixed(1) : '59.6'; return { prefix: '', text: isEn ? `avg ${val}` : `均 ${val}`, tone: 'info', pillPct: null, }; } case 'ttft': { const val = Number.isFinite(Number(safeCtx.ttft)) ? formatMetric(Number(safeCtx.ttft), 's') : '1.1s'; return { prefix: '', text: val, tone: 'good', pillPct: null }; } case 'cost': { const num = Number.isFinite(Number(safeCtx.stepCost)) ? Number(safeCtx.stepCost) : 0.042; return { prefix: '', text: `$${num.toFixed(3)}`, tone: 'normal', pillPct: null }; } case 'session_cost': { const num = Number.isFinite(Number(safeCtx.sessionCost)) ? Number(safeCtx.sessionCost) : 1.28; return { prefix: '', text: formatUsd(num), tone: 'normal', pillPct: null }; } case 'cache_hit': { const pct = Number.isFinite(Number(safeCtx.cacheHitPct)) ? Math.round(Number(safeCtx.cacheHitPct)) : 95; return { prefix: '', text: isEn ? `cache ${pct}%` : `缓 ${pct}%`, tone: 'good', pillPct: null, }; } case 'session_tokens': { const tokStr = Number.isFinite(Number(safeCtx.sessionTokens)) ? formatTokens(Number(safeCtx.sessionTokens)) : '1.8M'; return { prefix: '', text: `${tokStr} tok`, tone: 'muted', pillPct: null }; } case 'quota_auto': { const pct = quotaPct('quota_auto', 64); return { prefix: isEn ? '5h ' : '余 ', text: `${pct}%`, tone: 'good', pillPct: pct, }; } case 'gemini_5h': { const pct = quotaPct('gemini_5h', 64); return { prefix: 'G5h ', text: `${pct}%`, tone: 'good', pillPct: pct, }; } case 'gemini_weekly': { const pct = quotaPct('gemini_weekly', 52); return { prefix: isEn ? 'Gw ' : 'G周 ', text: `${pct}%`, tone: 'good', pillPct: pct, }; } case 'argon_weekly': { const pct = quotaPct('argon_weekly', 42); return { prefix: isEn ? 'Aw ' : 'A周 ', text: `${pct}%`, tone: 'good', pillPct: pct, }; } case 'claude_5h': { const pct = quotaPct('claude_5h', 32); return { prefix: 'C5h ', text: `${pct}%`, tone: 'good', pillPct: pct, }; } case 'claude_weekly': { const pct = quotaPct('claude_weekly', 59); return { prefix: isEn ? 'Cw ' : 'C周 ', text: `${pct}%`, tone: 'good', pillPct: pct, }; } case 'context': default: { const pct = Number.isFinite(Number(safeCtx.usedPct)) ? Math.round(Number(safeCtx.usedPct)) : 56; return { prefix: isEn ? 'Ctx ' : '上下文 ', text: `${pct}%`, tone: 'accent', pillPct: pct, }; } } } const SettingsStructureTab = defineComponent({ name: 'SettingsStructureTab', setup({ props, onCleanup }) { let activeThirdTab = normalizeStructureTabKey(uiStore.getState().settingsStructureTab); let draftWindowMountMode = 'dual'; let draftPopoverWidthMode = 'auto'; let draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH; let draftEnableCliStatusLine = true; let draftCliStatusLineSlots = null; let draftShowTopbarMulti = true; let draftContextAgentMode = DEFAULT_CLIENT_CONTEXT_AGENT_MODE; let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES]; let draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES]; let draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS]; let draftShowStepTurnRail = false; let draftShowStepAgentBadge = true; let draftShowStepSpeedColor = false; let draftShowStepFilterToolbar = false; let draftStepTokenComboFormat = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT; let rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT; let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS]; let latestSettings = null; let latestWindowBridge = null; let latestCliStatusLine = null; let latestHostPlatform = 'win32'; let latestQuotas = null; function getEffectiveDraftCliSlots() { return resolveEffectiveClientCliStatusLineSlots({ cliStatusLineSlots: draftCliStatusLineSlots, topbarCapsuleSlots: draftTopbarSlots, }); } function isStructureVisible() { const st = uiStore.getState(); return getVisibleMonitorView(st) === 'settings' && st.settingsSubTab === 'structure'; } function buildDraftTelemetry() { const effectiveCliSlots = getEffectiveDraftCliSlots(); const includeArgonPool = hasArgonWeeklyQuotaPool(latestQuotas) || draftTopbarSlots.includes('argon_weekly') || effectiveCliSlots.includes('argon_weekly'); return buildStructurePreviewTelemetry( latestSettings, { windowMountMode: draftWindowMountMode, enableWindowOverlay: draftWindowMountMode !== 'sidebar', popoverWidthMode: draftPopoverWidthMode, popoverWidth: draftPopoverWidth, enableCliStatusLine: draftEnableCliStatusLine, showTopbarMultiSession: draftShowTopbarMulti, contextAgentMode: draftContextAgentMode, topbarCapsuleSlots: draftTopbarSlots, hoverModules: draftHoverModules, overviewModules: draftOverviewModules, overviewMetrics: draftOverviewMetrics, showStepTurnRail: draftShowStepTurnRail, showStepAgentBadge: draftShowStepAgentBadge, showStepSpeedColor: draftShowStepSpeedColor, showStepFilterToolbar: draftShowStepFilterToolbar, stepTokenComboFormat: draftStepTokenComboFormat, stepTableColumns: draftStepColumns, }, { includeArgonPool } ); } async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') { sectionComp.refs.showStatus(t('settings.saving'), 0); try { await saveSettingsPatch(patchObj); sectionComp.refs.showStatus(t(successKey), 1500); } catch { if (latestSettings) { renderSettings(latestSettings); } sectionComp.refs.showStatus(t('settings.saveFailed'), 2500); } } // --- 3rd-Level Navigation Bar --- const thirdNavBtnMap = new Map(); const thirdNavBtns = STRUCTURE_THIRD_TABS.map((item) => { const labelEl = h('span', { className: 'structure-thirdnav-label', text: t(item.labelKey), }); const btn = h( 'button', { type: 'button', className: `structure-thirdnav-btn${item.key === activeThirdTab ? ' is-active' : ''}`, role: 'tab', '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 }); } }, 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?.(); } } }, }, [createSvgIcon(item.icon, { size: 12 }), labelEl] ); thirdNavBtnMap.set(item.key, { btn, labelEl, labelKey: item.labelKey }); return btn; }); const thirdNavGlider = h('div', { className: 'thirdnav-glider', 'aria-hidden': 'true' }); const thirdNavBar = h( 'div', { className: 'settings-thirdnav-bar', role: 'tablist', 'aria-label': t('settings.str.thirdTabAria'), }, [thirdNavGlider, ...thirdNavBtns] ); patchStyleVar( thirdNavBar, '--active-third-index', Math.max( 0, STRUCTURE_THIRD_TABS.findIndex((it) => it.key === activeThirdTab) ) ); // --- Pane 1: 挂载与胶囊栏 (`mount`) --- const capsulePreviewWidget = CapsuleBarWidget({}); const mountPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ capsulePreviewWidget.el, ]); const mountModeLabelEl = h('span', { className: 'form-label', text: t('settings.str.mountMode'), }); const popoverWidthLabelEl = h('span', { className: 'form-label', text: t('settings.str.popoverWidthLabel'), }); const multiToggleLabelEl = h('span', { className: 'form-label', text: t('settings.str.multiToggle'), }); const contextAgentModeLabelEl = h('span', { className: 'form-label', text: t('settings.str.contextAgentModeLabel'), }); const cliCapsuleLabelEl = h('span', { className: 'form-label', text: t('settings.str.cliCapsuleToggle'), }); const cliSlotsLabelEl = h('span', { className: 'form-label', text: t('settings.str.cliSlotsLabel'), }); const cliStatusHintEl = h('span', { className: 'settings-hint-text cli-status-hint', }); let cliActionBusy = false; let activeCliStatusAction = ''; const cliStatusActionBtn = h('button', { type: 'button', className: 'cli-status-action-btn', hidden: true, text: t('settings.str.cliRestoreBtn'), onClick: async () => { if (cliActionBusy || !activeCliStatusAction) return; cliActionBusy = true; const actionToRun = activeCliStatusAction; patchAttr(cliStatusActionBtn, 'disabled', true); patchText(cliStatusActionBtn, t('settings.str.cliRestoringBtn')); mountSection.refs.showStatus(t('settings.saving'), 0); try { const res = await triggerCliStatusLineAction(actionToRun); if (res?.cliStatusLine) { latestCliStatusLine = res.cliStatusLine; } if (res?.settings && typeof res.settings === 'object') { latestSettings = { ...(latestSettings || {}), ...res.settings }; draftEnableCliStatusLine = latestSettings.enableCliStatusLine !== false; } mountSection.refs.showStatus( res?.ok === false ? t('settings.saveFailed') : t('settings.saved'), 1800 ); } catch { mountSection.refs.showStatus(t('settings.saveFailed'), 2500); } finally { cliActionBusy = false; patchAttr(cliStatusActionBtn, 'disabled', false); syncMountSectionMeta(); props.onLayoutChange?.(); } }, }); const capsuleSlotsLabelEl = h('span', { className: 'form-label', text: t('settings.str.capsuleSlotsLabel'), }); const windowMountSelect = CustomSelect({ modelValue: draftWindowMountMode, icon: 'dock', options: getMountModeOptions(), onUpdateModelValue: (val) => { const nextMode = normalizeClientWindowMountMode(val); draftWindowMountMode = nextMode; syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(mountSection, { windowMountMode: nextMode, enableWindowOverlay: nextMode !== 'sidebar', }); }, }); const popoverWidthStepper = CustomNumberInput({ modelValue: draftPopoverWidth, min: MIN_CLIENT_POPOVER_WIDTH, max: MAX_CLIENT_POPOVER_WIDTH, step: 10, ariaLabel: t('settings.str.popoverWidthLabel'), onUpdateModelValue: (val) => { const nextWidth = normalizeClientPopoverWidth(val); draftPopoverWidth = nextWidth; syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(mountSection, { popoverWidthMode: draftPopoverWidthMode, popoverWidth: draftPopoverWidth, }); }, }); const popoverWidthNumWrap = h( 'span', { className: 'settings-number-wrap', hidden: draftPopoverWidthMode !== 'custom' }, [popoverWidthStepper.el, h('span', { className: 'settings-number-unit', text: 'px' })] ); const popoverWidthModeToggle = SegmentedControl({ ariaLabel: t('settings.str.popoverWidthLabel'), modelValue: draftPopoverWidthMode, options: getPopoverWidthModeOptions(), onUpdateModelValue: (val) => { draftPopoverWidthMode = normalizeClientPopoverWidthMode(val); syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(mountSection, { popoverWidthMode: draftPopoverWidthMode, popoverWidth: draftPopoverWidth, }); }, }); const multiSessionToggle = ToggleSwitch({ ariaLabelKey: 'settings.str.multiToggle', preset: 'visibility', modelValue: 'show', onUpdateModelValue: (val) => { draftShowTopbarMulti = val !== 'hide'; syncMountSectionMeta(); void persistStructurePatch(mountSection, { showTopbarMultiSession: draftShowTopbarMulti, }); }, }); const contextAgentModeToggle = SegmentedControl({ ariaLabel: t('settings.str.contextAgentModeLabel'), modelValue: draftContextAgentMode, options: getContextAgentModeOptions(), onUpdateModelValue: (val) => { const nextMode = normalizeClientContextAgentMode(val); draftContextAgentMode = nextMode; uiStore.setState({ ctxInspectorAgentId: nextMode }); syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(mountSection, { contextAgentMode: nextMode, }); }, }); const cliCapsuleToggle = ToggleSwitch({ ariaLabelKey: 'settings.str.cliCapsuleToggle', preset: 'enable', modelValue: 'on', onUpdateModelValue: (val) => { draftEnableCliStatusLine = val !== 'off'; syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(mountSection, { enableCliStatusLine: draftEnableCliStatusLine, }); }, }); const cliPreviewMultiTextEl = h('span', { text: t('settings.str.cliPreviewRunning', { count: 1 }), }); const cliPreviewMultiEl = h('span', { className: 'cli-preview-multi' }, [ h('span', { className: 'cli-preview-dot', 'aria-hidden': 'true', text: '●' }), cliPreviewMultiTextEl, ]); const cliPreviewSlotParts = []; const cliPreviewSepEls = []; const cliPreviewChildren = [cliPreviewMultiEl]; for (let i = 0; i < 6; i += 1) { if (i > 0) { const sepEl = h('span', { className: 'cli-preview-sep', 'aria-hidden': 'true', text: '|', }); cliPreviewSepEls.push(sepEl); cliPreviewChildren.push(sepEl); } const prefixEl = h('span', { className: 'cli-preview-prefix' }); const valueEl = h('span', { className: 'cli-preview-val' }); const slotEl = h('span', { className: 'cli-preview-slot' }, [ prefixEl, valueEl, ]); cliPreviewSlotParts.push({ slotEl, prefixEl, valueEl }); cliPreviewChildren.push(slotEl); } const cliPreviewEl = h('div', { className: 'cli-status-preview' }, cliPreviewChildren); const cliSlotsList = EditableSlotList({ items: getEffectiveDraftCliSlots(), options: getCapsuleMetricOptions(), minItems: 1, maxItems: 6, addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), onPreview: (previewItems) => { draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(previewItems); refreshCliPreview(); }, onChange: (nextItems) => { draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(nextItems); syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(mountSection, { cliStatusLineSlots: draftCliStatusLineSlots, }); }, }); const cliStatusFooterEl = h('div', { className: 'cli-status-footer', hidden: true }, [ cliStatusHintEl, cliStatusActionBtn, ]); const cliStatusDetailEl = h('div', { className: 'cli-statusline-detail' }, [ cliPreviewEl, h('div', { className: 'form-row' }, [cliSlotsLabelEl, cliSlotsList.el]), cliStatusFooterEl, ]); const cliStatusGroupEl = h('div', { className: 'cli-statusline-group', hidden: true }, [ h('div', { className: 'settings-divider' }), h('div', { className: 'settings-inline-row' }, [cliCapsuleLabelEl, cliCapsuleToggle.el]), cliStatusDetailEl, ]); const topbarSlotsList = EditableSlotList({ items: draftTopbarSlots, options: getCapsuleMetricOptions(), minItems: 1, maxItems: 5, addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }), onPreview: (previewItems) => { draftTopbarSlots = normalizeClientTopbarSlots(previewItems); refreshMountPreview(); }, onChange: (nextItems) => { draftTopbarSlots = normalizeClientTopbarSlots(nextItems); syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(mountSection, { topbarCapsuleSlots: draftTopbarSlots, }); }, }); const mountBridgeNotice = BridgeStatusNotice({}); const mountSection = CollapsibleSection({ collapsible: false, icon: 'dock', title: t('settings.str.mountSection'), badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }), onReset: () => { draftWindowMountMode = 'dual'; draftPopoverWidthMode = 'auto'; draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH; popoverWidthStepper.setProps({ modelValue: DEFAULT_CLIENT_POPOVER_WIDTH }); draftEnableCliStatusLine = true; draftCliStatusLineSlots = null; draftShowTopbarMulti = true; draftContextAgentMode = DEFAULT_CLIENT_CONTEXT_AGENT_MODE; draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; uiStore.setState({ ctxInspectorAgentId: DEFAULT_CLIENT_CONTEXT_AGENT_MODE }); syncMountSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch( mountSection, { windowMountMode: 'dual', enableWindowOverlay: true, popoverWidthMode: 'auto', popoverWidth: DEFAULT_CLIENT_POPOVER_WIDTH, enableCliStatusLine: true, cliStatusLineSlots: null, showTopbarMultiSession: true, contextAgentMode: DEFAULT_CLIENT_CONTEXT_AGENT_MODE, topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS], }, 'settings.resetDone' ); }, children: [ mountPreviewCanvas, h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]), mountBridgeNotice.el, h('div', { className: 'settings-inline-row' }, [ popoverWidthLabelEl, h('div', { className: 'settings-inline-controls' }, [ popoverWidthModeToggle.el, popoverWidthNumWrap, ]), ]), h('div', { className: 'settings-inline-row' }, [ multiToggleLabelEl, multiSessionToggle.el, ]), h('div', { className: 'settings-inline-row' }, [ contextAgentModeLabelEl, contextAgentModeToggle.el, ]), h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]), cliStatusGroupEl, ], }); function refreshCliPreview(previewData = null) { const effectiveSlots = getEffectiveDraftCliSlots(); const isEn = getEffectiveLocale() === 'en-US'; const mockData = previewData || buildDraftTelemetry(); const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( mockData, 'all', resolveOverlayCtxInspectorAgentId(mockData, 'auto') ); const slotCtx = buildCapsuleSlotContext(mockData, { scopedConv, ctxAgent, aggregated }); const runningCount = Math.max( 1, Array.isArray(mockData?.runningConversations) ? mockData.runningConversations.length : 1 ); patchAttr(cliPreviewMultiEl, 'hidden', !draftShowTopbarMulti); patchText(cliPreviewMultiTextEl, t('settings.str.cliPreviewRunning', { count: runningCount })); for (let i = 0; i < cliPreviewSlotParts.length; i += 1) { const parts = cliPreviewSlotParts[i]; const sepEl = i > 0 ? cliPreviewSepEls[i - 1] : null; const key = effectiveSlots[i]; const visible = Boolean(key); patchAttr(parts.slotEl, 'hidden', !visible); if (sepEl) patchAttr(sepEl, 'hidden', !visible); if (visible) { const item = formatCliPreviewSlot(key, slotCtx, isEn); const isPill = Number.isFinite(item.pillPct); patchAttr(parts.slotEl, 'data-metric', key); patchText(parts.prefixEl, item.prefix || ''); patchText(parts.valueEl, item.text || ''); patchStyleVar(parts.slotEl, '--cli-pill-pct', isPill ? `${item.pillPct}%` : ''); patchClasses(parts.slotEl, { 'is-pill': isPill, 'tone-good': item.tone === 'good', 'tone-info': item.tone === 'info', 'tone-accent': item.tone === 'accent', 'tone-muted': item.tone === 'muted', }); } } } function refreshMountPreview() { if (!isStructureVisible() || activeThirdTab !== 'mount') return; const mockData = buildDraftTelemetry(); capsulePreviewWidget.refs.update({ data: mockData }); refreshCliPreview(mockData); } function syncMountSectionMeta() { windowMountSelect.setProps({ modelValue: draftWindowMountMode, options: getMountModeOptions(), }); mountBridgeNotice.refs.update({ visible: draftWindowMountMode !== 'sidebar', windowBridge: latestWindowBridge, hostPlatform: latestHostPlatform, }); popoverWidthModeToggle.setProps({ modelValue: draftPopoverWidthMode, options: getPopoverWidthModeOptions(), }); patchAttr(popoverWidthNumWrap, 'hidden', draftPopoverWidthMode !== 'custom'); if (document?.activeElement !== popoverWidthStepper.refs.textField) { popoverWidthStepper.setProps({ modelValue: draftPopoverWidth, ariaLabel: t('settings.str.popoverWidthLabel'), }); } multiSessionToggle.setProps({ modelValue: draftShowTopbarMulti ? 'show' : 'hide', }); contextAgentModeToggle.setProps({ modelValue: draftContextAgentMode, options: getContextAgentModeOptions(), ariaLabel: t('settings.str.contextAgentModeLabel'), }); const cliInstalled = Boolean(latestCliStatusLine?.installed); patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled); cliCapsuleToggle.setProps({ modelValue: draftEnableCliStatusLine ? 'on' : 'off', }); patchAttr(cliStatusDetailEl, 'hidden', !draftEnableCliStatusLine); const effectiveCliSlots = getEffectiveDraftCliSlots(); cliSlotsList.refs.setProps({ items: effectiveCliSlots, options: getCapsuleMetricOptions({ quotas: latestQuotas, selectedSlots: effectiveCliSlots, }), addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), }); const preservedCustom = Boolean(latestCliStatusLine?.preservedCustom); const isConfigured = Boolean(latestCliStatusLine?.configured); const hasInlineSlotFlags = /(?:^|\s)--(?:slots|preset)(?:=|\s|$)/i.test( String(latestCliStatusLine?.managedFlags || '') ); const isPausedInCli = cliInstalled && !preservedCustom && !isConfigured && draftEnableCliStatusLine; const cliHintText = preservedCustom ? t('settings.str.cliCustomCmdHint') : isPausedInCli ? t('settings.str.cliPausedHint') : hasInlineSlotFlags ? t('settings.str.cliFlagsOverrideHint') : ''; patchAttr(cliStatusFooterEl, 'hidden', !cliHintText); patchClasses(cliStatusHintEl, { 'is-warn': preservedCustom || isPausedInCli }); patchText(cliStatusHintEl, cliHintText); activeCliStatusAction = preservedCustom || isPausedInCli ? 'force_install' : hasInlineSlotFlags ? 'clear_flags' : ''; patchAttr(cliStatusActionBtn, 'hidden', !activeCliStatusAction); patchClasses(cliStatusActionBtn, { 'is-warn': preservedCustom }); if (!cliActionBusy && activeCliStatusAction) { patchText( cliStatusActionBtn, preservedCustom ? t('settings.str.cliRestoreBtn') : isPausedInCli ? t('settings.str.cliEnableBtn') : t('settings.str.cliClearFlagsBtn') ); } refreshCliPreview(); topbarSlotsList.refs.setProps({ items: draftTopbarSlots, options: getCapsuleMetricOptions({ quotas: latestQuotas, selectedSlots: draftTopbarSlots, }), addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }), }); mountSection.refs.setBadge( t('settings.str.mountBadge', { count: draftTopbarSlots.length }) ); const isDefault = draftWindowMountMode === 'dual' && draftPopoverWidthMode === 'auto' && draftPopoverWidth === DEFAULT_CLIENT_POPOVER_WIDTH && draftEnableCliStatusLine === true && draftCliStatusLineSlots === null && draftShowTopbarMulti === true && draftContextAgentMode === DEFAULT_CLIENT_CONTEXT_AGENT_MODE && isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS); mountSection.refs.setResetDisabled(isDefault); refreshMountPreview(); } // --- Pane 2: 鼠标悬浮窗 (`hover`) --- const hoverWidgetsContainerEl = h('div', { className: 'wm-hover-widgets' }); const hoverPreviewTipEl = h('div', { className: 'wm-hover-tip is-preview' }, [ hoverWidgetsContainerEl, ]); const hoverPreviewEmptyEl = h('div', { className: 'structure-preview-empty', hidden: true, text: t('settings.str.hoverEmptyHint'), }); const hoverPreviewHost = createDynamicWidgetHost({ containerEl: hoverWidgetsContainerEl, mode: 'hover', preview: true, isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover', initialModuleKeys: [], getCtxAgentId: () => resolveOverlayCtxInspectorAgentId( { settings: { contextAgentMode: draftContextAgentMode } }, 'auto' ), }); const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ hoverPreviewTipEl, hoverPreviewEmptyEl, ]); const hoverModulesLabelEl = h('span', { className: 'form-label', text: t('settings.str.hoverModulesLabel'), }); const hoverModulesList = EditableSlotList({ items: draftHoverModules, options: getOverviewModuleOptions(), minItems: 0, maxItems: 4, emptyHintText: t('settings.str.hoverEmptyHint'), addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }), onPreview: (previewItems) => { draftHoverModules = normalizeClientHoverModules(previewItems); refreshHoverPreview(); }, onChange: (nextItems) => { draftHoverModules = normalizeClientHoverModules(nextItems); syncHoverSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(hoverSection, { hoverModules: draftHoverModules, }); }, }); const hoverSection = CollapsibleSection({ collapsible: false, icon: 'layers', title: t('settings.str.hoverSection'), badgeText: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length }), onReset: () => { draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES]; syncHoverSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch( hoverSection, { hoverModules: [...DEFAULT_CLIENT_HOVER_MODULES] }, 'settings.resetDone' ); }, children: [ hoverPreviewCanvas, h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [hoverModulesLabelEl, hoverModulesList.el]), ], }); function refreshHoverPreview() { if (!isStructureVisible() || activeThirdTab !== 'hover') return; const hasModules = draftHoverModules.length > 0; patchAttr(hoverPreviewTipEl, 'hidden', !hasModules); patchAttr(hoverPreviewEmptyEl, 'hidden', hasModules); patchText(hoverPreviewEmptyEl, t('settings.str.hoverEmptyHint')); hoverPreviewHost.update({ moduleKeys: draftHoverModules, data: buildDraftTelemetry(), }); } function syncHoverSectionMeta() { hoverModulesList.refs.setProps({ items: draftHoverModules, options: getOverviewModuleOptions(), emptyHintText: t('settings.str.hoverEmptyHint'), addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }), }); hoverSection.refs.setBadge( draftHoverModules.length === 0 ? t('settings.str.hoverBadgeOff') : t('settings.str.hoverBadgeCount', { count: draftHoverModules.length }) ); hoverSection.refs.setResetDisabled( isSameList(draftHoverModules, DEFAULT_CLIENT_HOVER_MODULES) ); refreshHoverPreview(); } // --- Pane 3: 实时监控布局 (`overview`) --- const overviewPreviewContainerEl = h('div', { className: 'overview-modules-host is-preview' }); const overviewPreviewHost = createDynamicWidgetHost({ containerEl: overviewPreviewContainerEl, mode: 'overview', preview: true, isVisibleFn: () => isStructureVisible() && activeThirdTab === 'overview', initialModuleKeys: [], }); const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ overviewPreviewContainerEl, ]); const overviewModulesLabelEl = h('span', { className: 'form-label', text: t('settings.str.overviewModulesLabel'), }); const overviewMetricsLabelEl = h('span', { className: 'form-label', text: t('settings.str.overviewMetricsLabel'), }); const overviewMetricsHintEl = h('span', { className: 'settings-hint-text', hidden: true, text: t('settings.str.overviewMetricsInactiveHint'), }); const overviewModulesList = EditableSlotList({ items: draftOverviewModules, options: getOverviewModuleOptions(), minItems: 1, maxItems: 4, addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }), onPreview: (previewItems) => { draftOverviewModules = normalizeClientOverviewModules(previewItems); patchAttr(overviewMetricsHintEl, 'hidden', draftOverviewModules.includes('metrics')); refreshOverviewPreview(); }, onChange: (nextItems) => { draftOverviewModules = normalizeClientOverviewModules(nextItems); syncOverviewSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(overviewSection, { overviewModules: draftOverviewModules, }); }, }); const overviewMetricsList = EditableSlotList({ items: draftOverviewMetrics, options: getOverviewMetricOptions(), minItems: 1, maxItems: 4, addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }), onPreview: (previewItems) => { draftOverviewMetrics = normalizeClientOverviewMetrics(previewItems); refreshOverviewPreview(); }, onChange: (nextItems) => { draftOverviewMetrics = normalizeClientOverviewMetrics(nextItems); syncOverviewSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(overviewSection, { overviewMetrics: draftOverviewMetrics, }); }, }); const overviewSection = CollapsibleSection({ collapsible: false, icon: 'pulse', title: t('settings.str.overviewSection'), badgeText: t('settings.str.overviewBadge', { modCount: draftOverviewModules.length, metCount: draftOverviewMetrics.length, }), onReset: () => { draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES]; draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS]; syncOverviewSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch( overviewSection, { overviewModules: [...DEFAULT_CLIENT_OVERVIEW_MODULES], overviewMetrics: [...DEFAULT_CLIENT_OVERVIEW_METRICS], }, 'settings.resetDone' ); }, children: [ overviewPreviewCanvas, h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [overviewModulesLabelEl, overviewModulesList.el]), h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [ overviewMetricsLabelEl, overviewMetricsHintEl, overviewMetricsList.el, ]), ], }); function refreshOverviewPreview() { if (!isStructureVisible() || activeThirdTab !== 'overview') return; overviewPreviewHost.update({ moduleKeys: draftOverviewModules, data: buildDraftTelemetry(), }); } function syncOverviewSectionMeta() { overviewModulesList.refs.setProps({ items: draftOverviewModules, options: getOverviewModuleOptions(), addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }), }); overviewMetricsList.refs.setProps({ items: draftOverviewMetrics, options: getOverviewMetricOptions(), addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }), }); const metricsModuleActive = draftOverviewModules.includes('metrics'); patchAttr(overviewMetricsHintEl, 'hidden', metricsModuleActive); overviewSection.refs.setBadge( t('settings.str.overviewBadge', { modCount: draftOverviewModules.length, metCount: draftOverviewMetrics.length, }) ); const isDefault = isSameList(draftOverviewModules, DEFAULT_CLIENT_OVERVIEW_MODULES) && isSameList(draftOverviewMetrics, DEFAULT_CLIENT_OVERVIEW_METRICS); overviewSection.refs.setResetDisabled(isDefault); refreshOverviewPreview(); } // --- Pane 4: 调用明细字段 (`steps`) --- const stepTablePreview = StepTableWidget({ standalone: true, interactiveBadges: false, }); const stepsPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ stepTablePreview.el, ]); const stepTurnRailLabelEl = h('span', { className: 'form-label', text: t('settings.str.stepTurnRailToggle'), }); const stepAgentBadgeLabelEl = h('span', { className: 'form-label', text: t('settings.str.stepAgentBadgeToggle'), }); const stepSpeedColorLabelEl = h('span', { className: 'form-label', text: t('settings.str.stepSpeedColorToggle'), }); const stepFilterToolbarLabelEl = h('span', { className: 'form-label', text: t('settings.str.stepFilterToolbarToggle'), }); const stepTokenComboLabelEl = h('span', { className: 'form-label', text: t('settings.str.stepTokenComboLabel'), }); const stepTokenComboHintEl = h('span', { className: 'settings-hint-text', text: t('settings.str.stepTokenComboHint'), }); const stepColsLabelEl = h('span', { className: 'form-label', text: t('settings.str.stepsColsLabel'), }); const stepTurnRailToggle = ToggleSwitch({ ariaLabelKey: 'settings.str.stepTurnRailToggle', preset: 'visibility', modelValue: 'hide', onUpdateModelValue: (val) => { draftShowStepTurnRail = val !== 'hide'; syncStepsSectionMeta(); void persistStructurePatch(stepsSection, { showStepTurnRail: draftShowStepTurnRail, }); }, }); const stepAgentBadgeToggle = ToggleSwitch({ ariaLabelKey: 'settings.str.stepAgentBadgeToggle', preset: 'visibility', modelValue: 'show', onUpdateModelValue: (val) => { draftShowStepAgentBadge = val !== 'hide'; syncStepsSectionMeta(); void persistStructurePatch(stepsSection, { showStepAgentBadge: draftShowStepAgentBadge, }); }, }); const stepSpeedColorToggle = ToggleSwitch({ ariaLabelKey: 'settings.str.stepSpeedColorToggle', preset: 'enable', modelValue: 'off', onUpdateModelValue: (val) => { draftShowStepSpeedColor = val !== 'off'; syncStepsSectionMeta(); void persistStructurePatch(stepsSection, { showStepSpeedColor: draftShowStepSpeedColor, }); }, }); const stepFilterToolbarToggle = ToggleSwitch({ ariaLabelKey: 'settings.str.stepFilterToolbarToggle', preset: 'enable', modelValue: 'off', onUpdateModelValue: (val) => { draftShowStepFilterToolbar = val !== 'off'; syncStepsSectionMeta(); void persistStructurePatch(stepsSection, { showStepFilterToolbar: draftShowStepFilterToolbar, }); }, }); function commitStepTokenComboInput() { const rawTrimmed = String(stepTokenComboInput.value || '').trim(); const normFmt = normalizeClientStepTokenComboFormat(rawTrimmed); rawStepTokenComboText = normFmt; draftStepTokenComboFormat = normFmt; stepTokenComboInput.value = normFmt; if (rawTrimmed && !draftStepColumns.includes('tokens_custom')) { const comboIdx = draftStepColumns.findIndex( (k) => k === 'tokens_combo' || k === 'tokens_io_cache' ); if (comboIdx >= 0) { const nextCols = [...draftStepColumns]; nextCols[comboIdx] = 'tokens_custom'; draftStepColumns = normalizeClientStepColumns(nextCols); } else { draftStepColumns = normalizeClientStepColumns([...draftStepColumns, 'tokens_custom']); } } syncStepsSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(stepsSection, { stepTokenComboFormat: draftStepTokenComboFormat, stepTableColumns: draftStepColumns, }); } const stepTokenComboInput = h('input', { type: 'text', className: 'settings-text-input', spellcheck: 'false', value: rawStepTokenComboText, placeholder: t('settings.str.stepTokenComboPlaceholder'), 'aria-label': t('settings.str.stepTokenComboLabel'), onInput: () => { rawStepTokenComboText = stepTokenComboInput.value; draftStepTokenComboFormat = normalizeClientStepTokenComboFormat(rawStepTokenComboText); stepColumnsList.refs.setProps({ items: draftStepColumns, options: getStepColumnOptions(draftStepTokenComboFormat), addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }), }); refreshStepsPreview(); }, onChange: () => { commitStepTokenComboInput(); }, onKeydown: (e) => { if (e?.key === 'Enter') { e.preventDefault(); stepTokenComboInput.blur(); } }, }); const stepColumnsList = EditableSlotList({ items: draftStepColumns, options: getStepColumnOptions(draftStepTokenComboFormat), minItems: 2, maxItems: 14, addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }), onPreview: (previewItems) => { draftStepColumns = normalizeClientStepColumns(previewItems); refreshStepsPreview(); }, onChange: (nextItems) => { draftStepColumns = normalizeClientStepColumns(nextItems); syncStepsSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch(stepsSection, { stepTableColumns: draftStepColumns, }); }, }); const stepsSection = CollapsibleSection({ collapsible: false, icon: 'table', title: t('settings.str.stepsSection'), badgeText: t('settings.str.stepsBadge', { count: draftStepColumns.length }), onReset: () => { draftShowStepTurnRail = false; draftShowStepAgentBadge = true; draftShowStepSpeedColor = false; draftShowStepFilterToolbar = false; draftStepTokenComboFormat = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT; rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT; stepTokenComboInput.value = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT; draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS]; syncStepsSectionMeta(); props.onLayoutChange?.(); void persistStructurePatch( stepsSection, { showStepTurnRail: false, showStepAgentBadge: true, showStepSpeedColor: false, showStepFilterToolbar: false, stepTokenComboFormat: DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, stepTableColumns: [...DEFAULT_CLIENT_STEP_COLUMNS], }, 'settings.resetDone' ); }, children: [ stepsPreviewCanvas, h('div', { className: 'settings-divider' }), h('div', { className: 'settings-inline-row' }, [ stepTurnRailLabelEl, stepTurnRailToggle.el, ]), h('div', { className: 'settings-inline-row' }, [ stepAgentBadgeLabelEl, stepAgentBadgeToggle.el, ]), h('div', { className: 'settings-inline-row' }, [ stepSpeedColorLabelEl, stepSpeedColorToggle.el, ]), h('div', { className: 'settings-inline-row' }, [ stepFilterToolbarLabelEl, stepFilterToolbarToggle.el, ]), h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [ stepTokenComboLabelEl, stepTokenComboInput, stepTokenComboHintEl, ]), h('div', { className: 'form-row' }, [stepColsLabelEl, stepColumnsList.el]), ], }); function refreshStepsPreview() { if (!isStructureVisible() || activeThirdTab !== 'steps') return; const mockData = buildDraftTelemetry(); const mockSteps = mockData.activeConversation?.recentSteps || []; const previewCols = document?.activeElement === stepTokenComboInput && String(rawStepTokenComboText || '').trim() && !draftStepColumns.includes('tokens_custom') ? normalizeClientStepColumns( draftStepColumns.some((k) => k === 'tokens_combo' || k === 'tokens_io_cache') ? draftStepColumns.map((k) => k === 'tokens_combo' || k === 'tokens_io_cache' ? 'tokens_custom' : k ) : [...draftStepColumns, 'tokens_custom'] ) : draftStepColumns; stepTablePreview.refs.renderStepTable( mockSteps, 'mock-preview-conv', previewCols, getEffectiveLocale(), { effectiveScopes: ['all'], hasSubagents: true, isMergedMultiAgents: true, showStepTurnRail: draftShowStepTurnRail, showStepAgentBadge: draftShowStepAgentBadge, showStepSpeedColor: draftShowStepSpeedColor, stepTokenComboFormat: draftStepTokenComboFormat, displaySettings: mockData.settings, } ); } function syncStepsSectionMeta() { stepTurnRailToggle.setProps({ modelValue: draftShowStepTurnRail ? 'show' : 'hide', }); stepAgentBadgeToggle.setProps({ modelValue: draftShowStepAgentBadge ? 'show' : 'hide', }); stepSpeedColorToggle.setProps({ modelValue: draftShowStepSpeedColor ? 'on' : 'off', }); stepFilterToolbarToggle.setProps({ modelValue: draftShowStepFilterToolbar ? 'on' : 'off', }); if (document?.activeElement !== stepTokenComboInput) { stepTokenComboInput.value = rawStepTokenComboText; } stepColumnsList.refs.setProps({ items: draftStepColumns, options: getStepColumnOptions(draftStepTokenComboFormat), addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }), }); stepsSection.refs.setBadge(t('settings.str.stepsBadge', { count: draftStepColumns.length })); const isDefault = draftShowStepTurnRail === false && draftShowStepAgentBadge === true && draftShowStepSpeedColor === false && draftShowStepFilterToolbar === false && draftStepTokenComboFormat === DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT && isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS); stepsSection.refs.setResetDisabled(isDefault); refreshStepsPreview(); } function syncPreviewTickers() { const visible = isStructureVisible(); if (visible && activeThirdTab === 'hover') { hoverPreviewHost.resumeTickers(); } else { hoverPreviewHost.pauseTickers(); } if (visible && activeThirdTab === 'overview') { overviewPreviewHost.resumeTickers(); } else { overviewPreviewHost.pauseTickers(); } if (!visible || activeThirdTab !== 'steps') { stepTablePreview.refs.hideTurnTip(); } } function refreshActivePreview() { if (!isStructureVisible()) return; if (activeThirdTab === 'mount') refreshMountPreview(); else if (activeThirdTab === 'hover') refreshHoverPreview(); else if (activeThirdTab === 'overview') refreshOverviewPreview(); else if (activeThirdTab === 'steps') refreshStepsPreview(); } 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 }); patchAttr(entry.btn, 'aria-selected', isActive ? 'true' : 'false'); } patchAttr(mountSection.el, 'hidden', nextTab !== 'mount'); patchAttr(hoverSection.el, 'hidden', nextTab !== 'hover'); patchAttr(overviewSection.el, 'hidden', nextTab !== 'overview'); patchAttr(stepsSection.el, 'hidden', nextTab !== 'steps'); refreshActivePreview(); syncPreviewTickers(); props.onLayoutChange?.(); } const rootEl = h('div', { className: 'settings-tab-stack' }, [ mountSection.el, hoverSection.el, overviewSection.el, stepsSection.el, ]); function renderSettings( settings, windowBridge = latestWindowBridge, hostPlatform = latestHostPlatform, cliStatusLine = latestCliStatusLine, quotas = latestQuotas ) { if (!settings) return; latestSettings = settings; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine; if (quotas !== undefined) latestQuotas = quotas; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay ); draftPopoverWidthMode = normalizeClientPopoverWidthMode(settings.popoverWidthMode); draftPopoverWidth = normalizeClientPopoverWidth(settings.popoverWidth); draftEnableCliStatusLine = settings.enableCliStatusLine !== false; draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(settings.cliStatusLineSlots); draftShowTopbarMulti = settings.showTopbarMultiSession !== false; draftContextAgentMode = normalizeClientContextAgentMode(settings.contextAgentMode); draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots); draftHoverModules = normalizeClientHoverModules(settings.hoverModules); draftOverviewModules = normalizeClientOverviewModules(settings.overviewModules); draftOverviewMetrics = normalizeClientOverviewMetrics(settings.overviewMetrics); draftShowStepTurnRail = settings.showStepTurnRail === true; draftShowStepAgentBadge = settings.showStepAgentBadge !== false; draftShowStepSpeedColor = settings.showStepSpeedColor === true; draftShowStepFilterToolbar = settings.showStepFilterToolbar === true; draftStepTokenComboFormat = normalizeClientStepTokenComboFormat( settings.stepTokenComboFormat ); rawStepTokenComboText = draftStepTokenComboFormat; draftStepColumns = normalizeClientStepColumns(settings.stepTableColumns); syncMountSectionMeta(); syncHoverSectionMeta(); syncOverviewSectionMeta(); syncStepsSectionMeta(); } function refreshLabels() { patchAttr(thirdNavBar, 'aria-label', t('settings.str.thirdTabAria')); for (const entry of thirdNavBtnMap.values()) { patchText(entry.labelEl, t(entry.labelKey)); } mountSection.refs.setTitle(t('settings.str.mountSection')); mountSection.refs.setResetLabel(t('settings.resetBtn')); patchText(mountModeLabelEl, t('settings.str.mountMode')); patchText(popoverWidthLabelEl, t('settings.str.popoverWidthLabel')); popoverWidthStepper.setProps({ ariaLabel: t('settings.str.popoverWidthLabel') }); patchText(multiToggleLabelEl, t('settings.str.multiToggle')); patchText(contextAgentModeLabelEl, t('settings.str.contextAgentModeLabel')); patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle')); patchText(cliSlotsLabelEl, t('settings.str.cliSlotsLabel')); patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel')); hoverSection.refs.setTitle(t('settings.str.hoverSection')); hoverSection.refs.setResetLabel(t('settings.resetBtn')); patchText(hoverModulesLabelEl, t('settings.str.hoverModulesLabel')); overviewSection.refs.setTitle(t('settings.str.overviewSection')); overviewSection.refs.setResetLabel(t('settings.resetBtn')); patchText(overviewModulesLabelEl, t('settings.str.overviewModulesLabel')); patchText(overviewMetricsLabelEl, t('settings.str.overviewMetricsLabel')); patchText(overviewMetricsHintEl, t('settings.str.overviewMetricsInactiveHint')); stepsSection.refs.setTitle(t('settings.str.stepsSection')); stepsSection.refs.setResetLabel(t('settings.resetBtn')); patchText(stepTurnRailLabelEl, t('settings.str.stepTurnRailToggle')); patchText(stepAgentBadgeLabelEl, t('settings.str.stepAgentBadgeToggle')); patchText(stepSpeedColorLabelEl, t('settings.str.stepSpeedColorToggle')); patchText(stepFilterToolbarLabelEl, t('settings.str.stepFilterToolbarToggle')); stepFilterToolbarToggle.setProps({ ariaLabel: t('settings.str.stepFilterToolbarToggle') }); patchText(stepTokenComboLabelEl, t('settings.str.stepTokenComboLabel')); patchText(stepTokenComboHintEl, t('settings.str.stepTokenComboHint')); patchAttr(stepTokenComboInput, 'placeholder', t('settings.str.stepTokenComboPlaceholder')); patchAttr(stepTokenComboInput, 'aria-label', t('settings.str.stepTokenComboLabel')); patchText(stepColsLabelEl, t('settings.str.stepsColsLabel')); syncMountSectionMeta(); syncHoverSectionMeta(); syncOverviewSectionMeta(); syncStepsSectionMeta(); } let wasStructureVisible = isStructureVisible(); const unsubUi = uiStore.subscribe( (st) => ({ activeView: getVisibleMonitorView(st), settingsSubTab: st.settingsSubTab, settingsStructureTab: st.settingsStructureTab, }), (slice) => { const nowVisible = slice.activeView === 'settings' && slice.settingsSubTab === 'structure'; const enteredStructure = nowVisible && !wasStructureVisible; wasStructureVisible = nowVisible; if (normalizeStructureTabKey(slice.settingsStructureTab) !== activeThirdTab) { applyActiveThirdTab(slice.settingsStructureTab); } else { if (enteredStructure) { refreshActivePreview(); } syncPreviewTickers(); } } ); syncMountSectionMeta(); syncHoverSectionMeta(); syncOverviewSectionMeta(); syncStepsSectionMeta(); applyActiveThirdTab(activeThirdTab); onCleanup(() => { unsubUi(); mountBridgeNotice.destroy(); capsulePreviewWidget.destroy(); hoverPreviewHost.destroy(); overviewPreviewHost.destroy(); stepTablePreview.destroy(); windowMountSelect.destroy(); popoverWidthStepper.destroy(); popoverWidthModeToggle.destroy(); multiSessionToggle.destroy(); contextAgentModeToggle.destroy(); cliCapsuleToggle.destroy(); cliSlotsList.destroy(); topbarSlotsList.destroy(); hoverModulesList.destroy(); overviewModulesList.destroy(); overviewMetricsList.destroy(); stepTurnRailToggle.destroy(); stepAgentBadgeToggle.destroy(); stepSpeedColorToggle.destroy(); stepFilterToolbarToggle.destroy(); stepColumnsList.destroy(); mountSection.destroy(); hoverSection.destroy(); overviewSection.destroy(); stepsSection.destroy(); }); return { el: rootEl, refs: { thirdNavBar, capsulePreviewWidget, mountBridgeNotice, hoverPreviewHost, overviewPreviewHost, stepTablePreview, windowMountSelect, multiSessionToggle, contextAgentModeToggle, cliCapsuleToggle, cliStatusGroupEl, cliStatusDetailEl, cliPreviewEl, cliSlotsList, cliStatusFooterEl, cliStatusHintEl, cliStatusActionBtn, topbarSlotsList, hoverModulesList, overviewModulesList, overviewMetricsList, stepTurnRailToggle, stepAgentBadgeToggle, stepSpeedColorToggle, stepFilterToolbarToggle, stepColumnsList, mountSection, hoverSection, overviewSection, stepsSection, renderSettings, refreshLabels, }, }; }, }); return { SettingsStructureTab }; })(); // --- src/views/settings/SettingsAccountTab.js --- const { SettingsAccountTab } = (() => { /** * @fileoverview Multi-account switcher, quota trajectory chart, risk gate, and passphrase vault UI. * Reuses `SegmentedControl`, `CustomSelect`, `AccountQuotaTrendCard`, `.ctx-risk-mask`, * `.settings-bridge-notice`, `.status-tag`, `.btn-ghost-sm`, `.btn-danger-confirm`, and `.quota-pool-row`. */ const key = (name) => `settings.account.${name}`; const fmtPct = (v) => String(+Number(v).toFixed(1)); let warmAccountCache = null; const errors = new Set([ 'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound', 'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied', 'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable', 'oauthUnavailable', 'quotaUnavailable', 'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed', 'loginStartFailed', 'loginExchangeFailed', 'loginExpired', 'loginDenied', 'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordMismatch', 'passwordRateLimited', 'vaultDecryptFailed', 'invalidActionNonce', 'riskNotAccepted', ]); const okToastKeys = new Set([ 'saved', 'removed', 'switched', 'pwdEnabledToast', 'pwdChangedToast', 'pwdDisabledToast', 'vaultUnlockedToast', 'vaultLockedToast', 'vaultResetToast', ]); function getAccountRefreshOptions() { return [ { value: 10, label: t(key('refresh10m')) }, { value: 30, label: t(key('refresh30m')) }, { value: 60, label: t(key('refresh1h')) }, { value: 180, label: t(key('refresh3h')) }, { value: 360, label: t(key('refresh6h')) }, { value: 720, label: t(key('refresh12h')) }, { value: 1440, label: t(key('refresh24h')) }, ]; } function getPwdModeOptions() { return [ { value: 'change', label: t(key('pwdTabChange')) }, { value: 'disable', label: t(key('pwdTabDisable')) }, ]; } function formatValidCountdown(isoTime) { if (!isoTime) return ''; const ms = Date.parse(isoTime); if (!Number.isFinite(ms) || ms <= Date.now()) return ''; return formatCountdown(isoTime); } function syncRemainingMeter(wrapEl, quotaLabelEl, resetEl, fillEl, hasData, labelText, remVal, resetTime) { patchAttr(wrapEl, 'hidden', !hasData); if (!hasData) return; const clamped = Math.max(0, Math.min(100, Number(remVal) || 0)); patchText(quotaLabelEl, labelText); const cd = formatValidCountdown(resetTime); patchText(resetEl, cd); patchAttr(resetEl, 'hidden', !cd); patchStyleVar(fillEl, '--fill-w', `${+clamped.toFixed(1)}%`); patchClasses(fillEl, { 'tone-warn': clamped > 15 && clamped <= 30, 'tone-danger': clamped <= 15, }); } function renderQuotaRows(container, quotaPools) { const locale = getEffectiveLocale(); const pools = (Array.isArray(quotaPools) ? quotaPools : []).filter( (pool) => Number.isFinite(pool?.remainingPct) || Number.isFinite(pool?.weeklyRemainingPct) ); patchKeyedList(container, pools, { keyFn: (pool) => pool.poolKey || pool.poolLabel, sigFn: (pool, idx) => JSON.stringify([ idx > 0, locale, pool.poolLabel, pool.remainingPct, pool.weeklyRemainingPct, pool.resetTime, pool.weeklyResetTime, ]), createRow: () => { const poolTitle = h('div', { className: 'account-pool-label' }); const label5h = h('span', { className: 'quota-win-title settings-account-quota text-mono' }); const reset5h = h('span', { className: 'panel-meta quota-win-meta text-mono', hidden: true }); const fill5h = h('div', { className: 'progress-fill' }); const meter5h = h('div', { className: 'account-meter-col' }, [ h('div', { className: 'panel-header quota-win-head' }, [ h('span', { className: 'quota-win-left' }, [label5h]), reset5h, ]), h('div', { className: 'progress-track' }, [fill5h]), ]); const labelWk = h('span', { className: 'quota-win-title settings-account-quota text-mono' }); const resetWk = h('span', { className: 'panel-meta quota-win-meta text-mono', hidden: true }); const fillWk = h('div', { className: 'progress-fill' }); const meterWk = h('div', { className: 'account-meter-col' }, [ h('div', { className: 'panel-header quota-win-head' }, [ h('span', { className: 'quota-win-left' }, [labelWk]), resetWk, ]), h('div', { className: 'progress-track' }, [fillWk]), ]); const gridEl = h('div', { className: 'account-pool-meters' }, [meter5h, meterWk]); const el = h('div', { className: 'quota-pool-row' }, [poolTitle, gridEl]); return { el, refs: { el, poolTitle, gridEl, meter5h, label5h, reset5h, fill5h, meterWk, labelWk, resetWk, fillWk }, }; }, updateRow: (refs, pool, idx) => { patchClasses(refs.el, { 'has-divider': idx > 0 }); patchText(refs.poolTitle, pool.poolLabel || pool.poolKey); const has5h = Number.isFinite(pool.remainingPct); const hasWk = Number.isFinite(pool.weeklyRemainingPct); patchClasses(refs.gridEl, { 'is-single': (has5h ? 1 : 0) + (hasWk ? 1 : 0) <= 1 }); syncRemainingMeter( refs.meter5h, refs.label5h, refs.reset5h, refs.fill5h, has5h, has5h ? t(key('quota5h'), { percent: fmtPct(pool.remainingPct) }) : '', pool.remainingPct, pool.resetTime ); syncRemainingMeter( refs.meterWk, refs.labelWk, refs.resetWk, refs.fillWk, hasWk, hasWk ? t(key('quotaWeekly'), { percent: fmtPct(pool.weeklyRemainingPct) }) : '', pool.weeklyRemainingPct, pool.weeklyResetTime ); }, }); patchAttr(container, 'hidden', pools.length === 0); return pools.length; } function needsLegacyUltraTierRefresh(cached) { if (!cached || cached.tierId || cached.tierMultiplier) return false; const name = String(cached.tierName || ''); return /\bultra\b/i.test(name) && !/\b(?:5x|20x)\b/i.test(name); } function isValidVaultPassphrase(raw) { return typeof raw === 'string' && raw.length >= 4 && raw.length <= 128 && Boolean(raw.trim()); } const SettingsAccountTab = defineComponent({ name: 'SettingsAccountTab', setup({ props, onCleanup }) { const initialSettings = telemetryStore.getState().telemetry?.settings; let account = null; let quotas = null; let refreshMinutes = normalizeAccountQuotaRefreshMinutes( initialSettings?.accountQuotaRefreshMinutes ?? DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES ); let draftRiskAccepted = Boolean(initialSettings?.accountSwitchRiskAccepted); let acceptingRisk = false; let riskLockedFromServer = warmAccountCache ? Boolean(warmAccountCache.riskLocked) : true; let accounts = warmAccountCache ? [...warmAccountCache.accounts] : []; let selectedEmail = warmAccountCache ? warmAccountCache.selectedEmail : ''; let supported = warmAccountCache ? warmAccountCache.supported : null; let vaultSecurity = warmAccountCache?.vaultSecurity ? { ...warmAccountCache.vaultSecurity } : { enabled: false, unlocked: true }; let quotaHistory = warmAccountCache?.quotaHistory ? { ...warmAccountCache.quotaHistory } : {}; let actionNonce = warmAccountCache?.actionNonce || ''; let operation = ''; let status = ''; let statusClearTimer = null; let confirmTarget = null; let confirmClearTimer = null; let switchState = null; let importOpen = false; let pwdDrawerOpen = false; let pwdManageMode = 'change'; let forgotResetOpen = false; let refreshingSavedQuotas = false; let disposed = false; let loginSession = null; let loginTimer; let loginGeneration = 0; let loginRefreshEmail = ''; const savedQuotas = new Map(warmAccountCache ? warmAccountCache.savedQuotasEntries : []); const quotaInFlight = new Set(); const quotaVisibleLoading = new Set(); const quotaErrors = new Map(); function isVaultLocked() { return Boolean(vaultSecurity?.enabled && !vaultSecurity?.unlocked); } function syncWarmCache() { if (supported !== true) return; warmAccountCache = { supported, riskLocked: riskLockedFromServer, accounts: [...accounts], selectedEmail, savedQuotasEntries: [...savedQuotas.entries()], vaultSecurity: { ...vaultSecurity }, quotaHistory: { ...quotaHistory }, actionNonce, }; } function clearConfirmTarget(shouldRender = false) { if (confirmClearTimer) { clearTimeout(confirmClearTimer); confirmClearTimer = null; } if (!confirmTarget) return; confirmTarget = null; if (shouldRender && !disposed) render(); } function armOrRunConfirm(type, targetKey, runFn) { if (confirmTarget && confirmTarget.type === type && confirmTarget.key === targetKey) { clearConfirmTarget(false); runFn(); return; } if (confirmClearTimer) clearTimeout(confirmClearTimer); confirmTarget = { type, key: targetKey }; confirmClearTimer = setTimeout(() => clearConfirmTarget(true), 4500); render(); } function setTransientStatus(nextStatus, autoClearMs = 0) { if (statusClearTimer) { clearTimeout(statusClearTimer); statusClearTimer = null; } status = nextStatus; if (nextStatus && autoClearMs > 0) { statusClearTimer = setTimeout(() => { statusClearTimer = null; if (!disposed && status === nextStatus) { status = ''; render(); } }, autoClearMs); } } function clearPasswordInputs() { unlockInput.value = ''; pwdCurrentInput.value = ''; pwdNewInput.value = ''; pwdConfirmInput.value = ''; } // --- Section 1: Active Account Card Host --- const activeCardHost = h('div', { className: 'account-cards-stack' }); // --- Section 2: Quota Trend Line Chart Card --- const quotaTrendCard = AccountQuotaTrendCard(); // --- Section 3: Multi-Account Toolbar, Drawers, Backup Cards & Risk Gate --- const loginBtnLabel = h('span'); const loginButton = h( 'button', { type: 'button', className: 'btn-primary settings-account-login', onClick: () => { clearConfirmTarget(false); void request('loginStart', { language: getEffectiveLocale() }); }, }, [createSvgIcon('plus', { size: 12 }), loginBtnLabel] ); const cancelLogin = h('button', { type: 'button', className: 'btn-secondary settings-account-login-cancel', hidden: true, onClick: () => request('loginCancel', { id: loginSession?.id }), }); const importToggleLabel = h('span'); const importToggleBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: () => { clearConfirmTarget(false); importOpen = !importOpen; if (importOpen) { pwdDrawerOpen = false; clearPasswordInputs(); } render(); if (importOpen) credential.focus?.(); }, }, [importToggleLabel] ); const pwdToggleIcon = createSvgIcon('lock', { size: 12 }); const pwdToggleLabel = h('span'); const pwdToggleBtn = h( 'button', { type: 'button', className: 'btn-secondary settings-account-pwd-toggle', onClick: () => { clearConfirmTarget(false); pwdDrawerOpen = !pwdDrawerOpen; if (pwdDrawerOpen) { importOpen = false; pwdManageMode = 'change'; pwdModeSegment.setProps({ modelValue: 'change', options: getPwdModeOptions() }); } clearPasswordInputs(); render(); if (pwdDrawerOpen) { (vaultSecurity.enabled ? pwdCurrentInput : pwdNewInput).focus?.(); } }, }, [pwdToggleIcon, pwdToggleLabel] ); const lockNowLabel = h('span'); const lockNowBtn = h( 'button', { type: 'button', className: 'btn-secondary settings-account-lock-now', hidden: true, onClick: () => { clearConfirmTarget(false); pwdDrawerOpen = false; importOpen = false; clearPasswordInputs(); void request('lockVault'); }, }, [createSvgIcon('lock', { size: 12 }), lockNowLabel] ); const feedback = h('span', { className: 'settings-action-desc account-status-inline', role: 'status', hidden: true, }); const refreshIntervalSelect = CustomSelect({ className: 'account-refresh-select', icon: 'clock', modelValue: refreshMinutes, options: getAccountRefreshOptions(), onUpdateModelValue: async (nextVal) => { const nextMins = normalizeAccountQuotaRefreshMinutes(nextVal); refreshMinutes = nextMins; refreshIntervalSelect.setValue(nextMins); void refreshSavedQuotas(); try { await saveSettingsPatch({ accountQuotaRefreshMinutes: nextMins }); } catch { // Keep selected interval locally if save fails transiently } }, }); patchAttr(refreshIntervalSelect.refs.triggerBtn, 'aria-label', t(key('refreshFreqAria'))); patchAttr(refreshIntervalSelect.refs.triggerBtn, 'title', t(key('refreshFreqAria'))); const reload = h( 'button', { type: 'button', className: 'icon-btn', onClick: () => request('list'), }, [createSvgIcon('refresh', { size: 13 })] ); // Locked Vault Notice (reusing `.settings-bridge-notice`) const unlockHintLabel = h('span', { className: 'settings-bridge-title' }); const forgotToggleBtn = h('button', { type: 'button', className: 'btn-ghost-sm settings-account-forgot-btn', onClick: () => { forgotResetOpen = !forgotResetOpen; clearConfirmTarget(false); render(); }, }); const unlockInput = h('input', { type: 'password', className: 'settings-text-input account-import-input settings-account-unlock-input', autocomplete: 'off', spellcheck: 'false', maxlength: 128, }); const unlockSubmitBtn = h('button', { type: 'submit', className: 'btn-primary settings-account-unlock-submit', }); const unlockForm = h( 'form', { className: 'account-import-row', autocomplete: 'off', onSubmit: submitUnlock, }, [unlockInput, unlockSubmitBtn] ); const resetHintEl = h('p', { className: 'settings-bridge-desc', hidden: true }); const resetVaultBtn = h('button', { type: 'button', className: 'btn-secondary btn-danger-confirm settings-account-reset-vault', hidden: true, onClick: () => { armOrRunConfirm('resetVault', 'vault', () => { void request('resetVault', { confirmReset: 'RESET' }); }); }, }); const unlockBox = h( 'div', { className: 'settings-bridge-notice settings-account-unlock-box', hidden: true }, [ h('div', { className: 'settings-bridge-head' }, [ h('span', { className: 'settings-bridge-head-main' }, [ createSvgIcon('lock', { size: 13, className: 'settings-bridge-icon' }), unlockHintLabel, ]), forgotToggleBtn, ]), unlockForm, resetHintEl, h('div', { className: 'settings-bridge-actions', hidden: true }, [resetVaultBtn]), ] ); const resetActionsWrap = resetVaultBtn.parentElement; // Passphrase Setup / Manage Drawer (reusing `SegmentedControl`!) const pwdModeSegment = SegmentedControl({ ariaLabel: t(key('pwdBtnManage')), modelValue: pwdManageMode, options: getPwdModeOptions(), onUpdateModelValue: (val) => { pwdManageMode = val === 'disable' ? 'disable' : 'change'; pwdModeSegment.setProps({ modelValue: pwdManageMode, options: getPwdModeOptions() }); clearPasswordInputs(); render(); }, }); const pwdCurrentInput = h('input', { type: 'password', className: 'settings-text-input account-import-input settings-account-pwd-current', autocomplete: 'off', spellcheck: 'false', maxlength: 128, hidden: true, }); const pwdNewInput = h('input', { type: 'password', className: 'settings-text-input account-import-input settings-account-pwd-new', autocomplete: 'off', spellcheck: 'false', maxlength: 128, }); const pwdConfirmInput = h('input', { type: 'password', className: 'settings-text-input account-import-input settings-account-pwd-confirm', autocomplete: 'off', spellcheck: 'false', maxlength: 128, }); const pwdSubmitBtn = h('button', { type: 'submit', className: 'btn-primary settings-account-pwd-submit', }); const pwdHint = h('div', { className: 'settings-action-desc' }); const pwdForm = h( 'form', { className: 'account-import-drawer settings-account-pwd-form', autocomplete: 'off', hidden: true, onSubmit: submitPasswordDrawer, }, [ pwdModeSegment.el, h('div', { className: 'account-import-row' }, [ pwdCurrentInput, pwdNewInput, pwdConfirmInput, pwdSubmitBtn, ]), pwdHint, ] ); // Credential Import Drawer const credential = h('input', { type: 'password', className: 'settings-text-input account-import-input', required: true, autocomplete: 'off', spellcheck: 'false', maxlength: 16384, }); const save = h('button', { type: 'submit', className: 'btn-primary', }); const importHint = h('div', { className: 'settings-action-desc' }); const form = h( 'form', { className: 'settings-account-form account-import-drawer', autocomplete: 'off', hidden: true, onSubmit: importCredential, }, [ h('div', { className: 'account-import-row' }, [credential, save]), importHint, ] ); // OAuth Browser Login & Switch Notices (reusing `.settings-bridge-notice`) const loginMessage = h('p', { className: 'settings-bridge-desc settings-action-desc', role: 'status', hidden: true, }); const loginLink = h('a', { className: 'settings-bridge-relaunch-btn', target: '_blank', rel: 'noopener noreferrer', hidden: true, }); const loginStrip = h( 'div', { className: 'settings-bridge-notice is-restart', hidden: true }, [loginMessage, h('div', { className: 'settings-bridge-actions' }, [loginLink])] ); const loginLinkWrap = loginLink.parentElement; const pendingDesc = h('p', { className: 'settings-bridge-desc', role: 'status' }); const pending = h('div', { className: 'settings-bridge-notice', hidden: true }, [pendingDesc]); const toolbarPanel = h('section', { className: 'panel account-toolbar-panel' }, [ h('div', { className: 'account-toolbar-row' }, [ h('div', { className: 'account-toolbar-left' }, [ loginButton, cancelLogin, importToggleBtn, pwdToggleBtn, lockNowBtn, ]), h('div', { className: 'account-toolbar-right' }, [ feedback, refreshIntervalSelect.el, reload, ]), ]), unlockBox, pwdForm, form, loginStrip, pending, ]); const backupCardsHost = h('div', { className: 'account-cards-stack' }); const emptyPanel = h('section', { className: 'panel account-empty-panel', hidden: true }, [ h('div', { className: 'settings-action-desc account-empty-text' }), ]); const emptyTextEl = emptyPanel.firstChild; // Risk Gate Stage (100% shared `.ctx-risk-stage` / `.ctx-risk-mask` with `SettingsOtherTab`) const riskTitleEl = h('strong', { className: 'ctx-risk-title', text: t('settings.oth.ctxRiskTitle'), }); const riskBodyEl = h('p', { className: 'ctx-risk-desc', text: t(key('riskBody')), }); const riskAcceptBtnText = h('span', { text: t('settings.oth.ctxRiskAcceptBtn') }); const riskAcceptBtn = h( 'button', { type: 'button', className: 'btn-secondary btn-danger-confirm ctx-risk-accept-btn settings-account-risk-accept', onClick: async () => { if (acceptingRisk || draftRiskAccepted) return; acceptingRisk = true; draftRiskAccepted = true; render(); try { await saveSettingsPatch({ accountSwitchRiskAccepted: true }); await request('list'); } catch { draftRiskAccepted = false; setTransientStatus('storeFailed', 2800); } finally { acceptingRisk = false; if (!disposed) render(); } }, }, [createSvgIcon('warning', { size: 12 }), riskAcceptBtnText] ); const riskMask = h( 'div', { className: 'ctx-risk-mask settings-account-risk-mask', role: 'region', 'aria-label': t('settings.oth.ctxRiskTitle'), }, [ h('div', { className: 'ctx-risk-head' }, [ createSvgIcon('warning', { size: 14, className: 'ctx-risk-icon' }), riskTitleEl, ]), riskBodyEl, riskAcceptBtn, ] ); const managedControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ toolbarPanel, backupCardsHost, ]); const riskStage = h('div', { className: 'ctx-risk-stage' }, [managedControlsBody, riskMask]); function resolveActiveEmail() { return account?.status === 'signedIn' ? (account.email || '').trim().toLowerCase() : ''; } function createAccountCardDom(entry) { const emailEl = h('span', { className: 'settings-account-identity account-card-email', text: entry.email, title: entry.email, }); const tierPill = h('span', { className: 'status-tag state-synced', hidden: true }); const statePill = h('span', { className: 'status-tag', hidden: true }); const captureBtn = h('button', { type: 'button', className: 'btn-ghost-sm', hidden: true, onClick: () => { clearConfirmTarget(false); void request('capture'); }, }); const selectBtn = h('button', { type: 'button', className: 'btn-ghost-sm', hidden: true, onClick: () => { armOrRunConfirm('switch', entry.email, () => { const curActive = resolveActiveEmail(); void request('switch', { email: entry.email, ...(curActive ? { activeEmail: curActive } : {}), }); }); }, }); const loadQuotaBtn = h( 'button', { type: 'button', className: 'icon-btn settings-account-load-quota', hidden: true, onClick: () => { clearConfirmTarget(false); void request('quota', { email: entry.email, manual: true }); }, }, [createSvgIcon('refresh', { size: 12 })] ); const removeBtn = h( 'button', { type: 'button', className: 'icon-btn slot-remove-btn settings-account-remove', hidden: true, onClick: () => { armOrRunConfirm('remove', entry.email, () => { void request('remove', { email: entry.email }); }); }, }, [createSvgIcon('close', { size: 12 })] ); const removeConfirmBtn = h('button', { type: 'button', className: 'btn-ghost-sm btn-danger-confirm settings-account-remove-confirm', hidden: true, onClick: () => { armOrRunConfirm('remove', entry.email, () => { void request('remove', { email: entry.email }); }); }, }); const actionsWrap = h('div', { className: 'account-card-actions' }, [ captureBtn, selectBtn, loadQuotaBtn, removeBtn, removeConfirmBtn, ]); const poolsWrap = h('div', { className: 'account-pools-stack' }); const noteEl = h('div', { className: 'settings-action-desc account-card-note', hidden: true }); const cardEl = h('section', { className: 'panel account-card' }, [ h('div', { className: 'panel-header account-card-head' }, [ h('div', { className: 'account-card-meta' }, [emailEl, tierPill, statePill]), actionsWrap, ]), poolsWrap, noteEl, ]); return { el: cardEl, refs: { cardEl, emailEl, tierPill, statePill, actionsWrap, captureBtn, selectBtn, loadQuotaBtn, removeBtn, removeConfirmBtn, poolsWrap, noteEl, }, }; } function updateAccountCardDom(row, entry, ctx) { const addr = entry.email; const active = entry.isActive; const isSaved = entry.isSaved; const written = addr === selectedEmail && !active && switchState?.state === 'written'; const cached = active ? null : savedQuotas.get(addr); const tierText = active ? ctx.activeTierBadge : cached?.tierName || cached?.tierId ? formatAccountTierBadge({ tierId: cached.tierId, tierName: cached.tierName, tierMultiplier: cached.tierMultiplier, }) : ''; const isSpinning = !active && quotaVisibleLoading.has(addr); const canSwitch = !active && isSaved && ctx.riskAccepted; const armedSwitch = confirmTarget?.type === 'switch' && confirmTarget.key === addr; const armedRemove = confirmTarget?.type === 'remove' && confirmTarget.key === addr; patchClasses(row.cardEl, { 'is-active-account': active }); patchText(row.emailEl, addr); patchAttr(row.emailEl, 'title', addr); patchText(row.tierPill, tierText); patchAttr(row.tierPill, 'hidden', !tierText); patchText(row.statePill, active ? t(key('active')) : written ? t(key('written')) : ''); patchClasses(row.statePill, { 'state-warn': written && !active }); patchAttr(row.statePill, 'hidden', !active && !written); const showCapture = active && !isSaved && ctx.riskAccepted && supported !== false; const showRemove = isSaved && ctx.riskAccepted; const showQuotaRefresh = !active && isSaved && ctx.riskAccepted; const hasAnyAction = showCapture || canSwitch || showQuotaRefresh || showRemove; patchAttr(row.actionsWrap, 'hidden', !hasAnyAction); patchText(row.captureBtn, t(key('capture'))); patchAttr(row.captureBtn, 'hidden', !showCapture); patchAttr(row.captureBtn, 'disabled', !ctx.canWrite); patchText(row.selectBtn, t(key(armedSwitch ? 'switchConfirm' : 'switch'))); patchAttr(row.selectBtn, 'title', t(key('switchHint'))); patchClasses(row.selectBtn, { 'settings-account-switch': canSwitch, 'btn-danger-confirm': armedSwitch, }); patchAttr(row.selectBtn, 'hidden', !canSwitch); patchAttr(row.selectBtn, 'disabled', !ctx.canWrite); patchAttr(row.loadQuotaBtn, 'title', t(key(isSpinning ? 'loadingQuota' : 'loadQuota'))); patchAttr(row.loadQuotaBtn, 'aria-label', t(key('loadQuota'))); patchClasses(row.loadQuotaBtn, { 'is-spinning': isSpinning }); patchAttr(row.loadQuotaBtn, 'hidden', !showQuotaRefresh); patchAttr(row.loadQuotaBtn, 'disabled', !ctx.canWrite || isSpinning); patchAttr(row.removeBtn, 'title', t(key('remove'))); patchAttr(row.removeBtn, 'aria-label', t(key('remove'))); patchAttr(row.removeBtn, 'hidden', !showRemove || armedRemove); patchAttr(row.removeBtn, 'disabled', !ctx.canWrite); patchText(row.removeConfirmBtn, t(key('removeConfirm'))); patchAttr(row.removeConfirmBtn, 'hidden', !showRemove || !armedRemove); patchAttr(row.removeConfirmBtn, 'disabled', !ctx.canWrite); const displayedPools = active ? quotas?.pools || [] : cached?.pools || []; const poolCount = renderQuotaRows(row.poolsWrap, displayedPools); const quotaError = active ? '' : quotaErrors.get(addr); let noteText = ''; if (quotaError) { noteText = t(key(quotaError)); } else if (active && poolCount > 0 && quotas?.meta?.isStale) { noteText = t(key('quotaStale')); } else if (active && poolCount === 0) { noteText = t(key('noQuota')); } else if (!active && cached && poolCount === 0) { noteText = t(key('emptyCredentialQuota')); } patchText(row.noteEl, noteText); patchClasses(row.noteEl, { 'is-error': Boolean(quotaError) }); patchAttr(row.noteEl, 'hidden', !noteText); } function render() { const signedIn = account?.status === 'signedIn'; const activeEmail = resolveActiveEmail(); if (activeEmail && selectedEmail === activeEmail && switchState?.state !== 'starting') { selectedEmail = ''; } const riskAccepted = Boolean(draftRiskAccepted); if (!riskAccepted) { refreshIntervalSelect.close?.(); } const vaultLocked = isVaultLocked(); const canOperateVault = riskAccepted && supported === true && !operation && status !== 'restarting' && switchState?.state !== 'starting'; const canWrite = canOperateVault && !vaultLocked; const locale = getEffectiveLocale(); const activeTierBadge = signedIn && (account?.tierName || account?.planName) ? formatAccountTierBadge(account) : ''; const cardCtx = { riskAccepted, canWrite, activeTierBadge }; // 1. Active Logged-in Account Card const activeEntries = activeEmail ? [ { email: activeEmail, isActive: true, isSaved: riskAccepted && accounts.includes(activeEmail), }, ] : []; patchAttr(activeCardHost, 'hidden', activeEntries.length === 0); patchKeyedList(activeCardHost, activeEntries, { keyFn: (entry) => entry.email, sigFn: (entry) => JSON.stringify([ locale, entry.isSaved, riskAccepted, canWrite, confirmTarget?.key === entry.email ? confirmTarget.type : '', quotas, activeTierBadge, ]), createRow: createAccountCardDom, updateRow: (row, entry) => updateAccountCardDom(row, entry, cardCtx), }); // 2. Quota Trend Line Chart Card (always visible; locked to activeEmail when !riskAccepted) quotaTrendCard.refs.update({ activeEmail, activePools: quotas?.pools || [], riskAccepted, accounts, savedQuotas, quotaHistory, }); // 3. Risk Gate Stage & Multi-Account Controls patchClasses(managedControlsBody, { 'is-locked': !riskAccepted }); patchAttr(managedControlsBody, 'inert', !riskAccepted); patchAttr(managedControlsBody, 'aria-hidden', riskAccepted ? null : 'true'); patchAttr(riskMask, 'hidden', riskAccepted); patchAttr(riskMask, 'aria-label', t('settings.oth.ctxRiskTitle')); patchText(riskTitleEl, t('settings.oth.ctxRiskTitle')); patchText(riskBodyEl, t(key('riskBody'))); patchText(riskAcceptBtnText, t('settings.oth.ctxRiskAcceptBtn')); patchAttr(riskAcceptBtn, 'disabled', acceptingRisk); const loginActive = ['waiting', 'exchanging', 'saving'].includes(loginSession?.status); patchText(loginBtnLabel, t(key('googleLogin'))); patchAttr(loginButton, 'disabled', !canWrite || loginActive); patchText(cancelLogin, t(key('cancelLogin'))); patchAttr(cancelLogin, 'hidden', !loginActive); patchAttr(cancelLogin, 'disabled', Boolean(operation) || loginSession?.status === 'saving'); patchText(importToggleLabel, t(key('importExisting'))); patchClasses(importToggleBtn, { 'is-open': importOpen }); patchAttr(importToggleBtn, 'hidden', supported === false); patchAttr(importToggleBtn, 'disabled', !canWrite); patchSvgIcon(pwdToggleIcon, vaultSecurity.enabled ? 'unlock' : 'lock'); patchText(pwdToggleLabel, t(key(vaultSecurity.enabled ? 'pwdBtnManage' : 'pwdBtnSet'))); patchClasses(pwdToggleBtn, { 'is-open': pwdDrawerOpen }); patchAttr(pwdToggleBtn, 'hidden', supported === false || vaultLocked); patchAttr(pwdToggleBtn, 'disabled', !canOperateVault); patchText(lockNowLabel, t(key('lockNow'))); patchAttr(lockNowBtn, 'title', t(key('lockNowTip'))); patchAttr(lockNowBtn, 'hidden', !vaultSecurity.enabled || vaultLocked || supported === false); patchAttr(lockNowBtn, 'disabled', !canOperateVault); // Unlock Notice patchAttr(unlockBox, 'hidden', !riskAccepted || supported !== true || !vaultLocked); patchText(unlockHintLabel, t(key('vaultLockedHint'))); patchText(forgotToggleBtn, t(key('forgotPwdToggle'))); patchAttr(unlockInput, 'placeholder', t(key('unlockPlaceholder'))); patchAttr(unlockInput, 'disabled', !canOperateVault); patchText(unlockSubmitBtn, t(key('unlockBtn'))); patchAttr(unlockSubmitBtn, 'disabled', !canOperateVault); const showResetSection = forgotResetOpen && vaultLocked; patchAttr(resetHintEl, 'hidden', !showResetSection); patchAttr(resetActionsWrap, 'hidden', !showResetSection); patchAttr(resetVaultBtn, 'hidden', !showResetSection); patchText(resetHintEl, t(key('resetVaultHint'))); const armedVaultReset = confirmTarget?.type === 'resetVault' && confirmTarget.key === 'vault'; patchText(resetVaultBtn, t(key(armedVaultReset ? 'resetVaultConfirm' : 'resetVaultBtn'))); patchAttr(resetVaultBtn, 'disabled', !canOperateVault); // Passphrase Drawer (`SegmentedControl` for Change / Disable) const showPwdDrawer = riskAccepted && pwdDrawerOpen && !vaultLocked && supported === true; patchAttr(pwdForm, 'hidden', !showPwdDrawer); if (showPwdDrawer) { const isSetNew = !vaultSecurity.enabled; const isDisableMode = !isSetNew && pwdManageMode === 'disable'; patchAttr(pwdModeSegment.el, 'hidden', isSetNew); if (!isSetNew) { pwdModeSegment.setProps({ modelValue: pwdManageMode, options: getPwdModeOptions() }); } patchAttr(pwdCurrentInput, 'hidden', isSetNew); patchAttr(pwdCurrentInput, 'placeholder', t(key('pwdCurrentPlaceholder'))); patchAttr(pwdCurrentInput, 'disabled', !canOperateVault); patchAttr(pwdNewInput, 'hidden', isDisableMode); patchAttr(pwdNewInput, 'placeholder', t(key('pwdNewPlaceholder'))); patchAttr(pwdNewInput, 'disabled', !canOperateVault); patchAttr(pwdConfirmInput, 'hidden', isDisableMode); patchAttr(pwdConfirmInput, 'placeholder', t(key('pwdConfirmPlaceholder'))); patchAttr(pwdConfirmInput, 'disabled', !canOperateVault); patchText( pwdSubmitBtn, t(key(isSetNew ? 'pwdEnableSubmit' : isDisableMode ? 'pwdDisableSubmit' : 'pwdChangeSubmit')) ); patchClasses(pwdSubmitBtn, { 'btn-primary': !isDisableMode, 'btn-secondary': isDisableMode, 'btn-danger-confirm': isDisableMode, }); patchAttr(pwdSubmitBtn, 'disabled', !canOperateVault); patchText(pwdHint, t(key(isSetNew ? 'pwdSetHint' : 'pwdManageHint'))); } refreshIntervalSelect.setProps({ modelValue: refreshMinutes, options: getAccountRefreshOptions(), }); patchAttr(refreshIntervalSelect.refs.triggerBtn, 'aria-label', t(key('refreshFreqAria'))); patchAttr(refreshIntervalSelect.refs.triggerBtn, 'title', t(key('refreshFreqAria'))); patchAttr(refreshIntervalSelect.el, 'hidden', supported === false); patchAttr(reload, 'title', t(key('reload'))); patchAttr(reload, 'aria-label', t(key('reload'))); patchAttr(reload, 'disabled', Boolean(operation)); patchClasses(reload, { 'is-spinning': operation === 'list' }); patchAttr(form, 'hidden', !riskAccepted || !importOpen || vaultLocked || supported === false); patchAttr(credential, 'placeholder', t(key('credentialPlaceholder'))); patchAttr(credential, 'disabled', !canWrite); patchText(save, t(key('save'))); patchAttr(save, 'disabled', !canWrite); patchText(importHint, t(key('importHint'))); const loginStatusKeys = { waiting: 'loginWaiting', exchanging: 'loginFinishing', saving: 'loginFinishing', success: 'loginSuccess', cancelled: 'loginCancelled', expired: 'loginExpired', }; const hasLoginSession = Boolean(loginSession?.status); const loginIsError = loginSession?.status === 'error' || loginSession?.status === 'expired' || loginSession?.error === 'loginDenied'; const loginMessageKey = loginSession?.status === 'error' ? errors.has(loginSession.error) ? loginSession.error : 'loginExchangeFailed' : loginSession?.error === 'loginDenied' ? 'loginDenied' : loginStatusKeys[loginSession?.status] || ''; patchText(loginMessage, loginMessageKey ? t(key(loginMessageKey)) : ''); patchAttr(loginMessage, 'hidden', !loginMessageKey); const authUrl = loginSession?.status === 'waiting' && loginSession.url?.startsWith('https://accounts.google.com/o/oauth2/v2/auth?') ? loginSession.url : ''; patchText(loginLink, t(key('openLoginPage'))); patchAttr(loginLink, 'href', authUrl || null); patchAttr(loginLink, 'hidden', !authUrl); patchAttr(loginLinkWrap, 'hidden', !authUrl); patchClasses(loginStrip, { 'is-restart': !loginIsError }); patchAttr(loginStrip, 'hidden', !hasLoginSession || !loginMessageKey); const failedSwitch = switchState?.state === 'failed' && errors.has(switchState.error) ? switchState.error : ''; const message = status || failedSwitch || (operation === 'switch' ? 'switching' : operation === 'save' || operation === 'capture' ? 'verifying' : ''); const isFeedbackError = Boolean(errors.has(message)); const isFeedbackOk = okToastKeys.has(message); patchText(feedback, message ? t(key(message)) : ''); patchAttr(feedback, 'title', message ? t(key(message)) : null); patchClasses(feedback, { 'is-error': isFeedbackError, 'is-ok': isFeedbackOk, }); patchAttr(feedback, 'hidden', !message); const waiting = Boolean(selectedEmail) && activeEmail !== selectedEmail && switchState?.state === 'written' && status !== 'restarting'; patchText(pendingDesc, waiting ? t(key('pending'), { email: selectedEmail }) : ''); patchAttr(pending, 'hidden', !waiting); const backupEntries = riskAccepted ? accounts .filter((addr) => addr && addr !== activeEmail) .map((addr) => ({ email: addr, isActive: false, isSaved: true })) : []; patchAttr(backupCardsHost, 'hidden', backupEntries.length === 0); patchKeyedList(backupCardsHost, backupEntries, { keyFn: (entry) => entry.email, sigFn: (entry) => JSON.stringify([ locale, selectedEmail, switchState?.state || '', canWrite, confirmTarget?.key === entry.email ? confirmTarget.type : '', savedQuotas.get(entry.email), quotaVisibleLoading.has(entry.email), quotaErrors.get(entry.email), ]), createRow: createAccountCardDom, updateRow: (row, entry) => updateAccountCardDom(row, entry, cardCtx), }); const showEmpty = !activeEmail && (!riskAccepted || backupEntries.length === 0); patchText( emptyTextEl, t( key( supported === null && !activeEmail ? 'loading' : account?.status === 'signedOut' ? 'signedOut' : 'empty' ) ) ); patchAttr(emptyPanel, 'hidden', !showEmpty); props.onLayoutChange?.(); } async function dispatchAccountPost(action, fields) { let res = await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields, ...(actionNonce ? { actionNonce } : {}), }, cdpTimeoutMs: 40000, }); if (res?.actionNonce) { actionNonce = res.actionNonce; } if (res?.error === 'invalidActionNonce' && actionNonce) { res = await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields, actionNonce, }, cdpTimeoutMs: 40000, }); if (res?.actionNonce) { actionNonce = res.actionNonce; } } return res; } async function request(action, fields = {}) { if (action !== 'list' && !draftRiskAccepted) return; if (action === 'quota') return refreshQuota(fields.email, Boolean(fields.manual)); if (operation) return; operation = action; if (action === 'loginStart' || action === 'loginCancel') { clearTimeout(loginTimer); loginGeneration += 1; } setTransientStatus(''); render(); try { const result = action === 'list' ? await callSidecarApi('/api/accounts') : await dispatchAccountPost(action, fields); if (disposed) return; if (typeof result?.actionNonce === 'string' && result.actionNonce) { actionNonce = result.actionNonce; } if (result?.quotaHistory && typeof result.quotaHistory === 'object') { quotaHistory = { ...quotaHistory, ...result.quotaHistory }; } if (result?.error) { if (result.error === 'unsupported') supported = false; if (result.error === 'vaultLocked') { vaultSecurity = { enabled: true, unlocked: false }; syncWarmCache(); } setTransientStatus(errors.has(result.error) ? result.error : 'storeFailed', 3600); return; } if (action === 'loginStart' || action === 'loginCancel') { applyLogin(result.login); if (result.login?.status === 'success') loginRefreshEmail = result.login.email; return; } supported = result?.supported === true; riskLockedFromServer = Boolean(result?.riskLocked); accounts = result?.accounts || []; selectedEmail = result?.selectedEmail || ''; switchState = result?.switchState || null; if (result?.security) { vaultSecurity = { enabled: Boolean(result.security.enabled), unlocked: result.security.unlocked !== false, }; } else { vaultSecurity = { enabled: false, unlocked: true }; } if (result.login) applyLogin(result.login); if (action === 'resetVault') { savedQuotas.clear(); quotaErrors.clear(); } for (const [addr, snapshot] of Object.entries(result?.quotas || {})) { savedQuotas.set(addr, snapshot); } syncWarmCache(); if (action !== 'switch' && draftRiskAccepted && !riskLockedFromServer && !isVaultLocked()) { void refreshSavedQuotas(); } if (action === 'save' || action === 'capture') { importOpen = false; setTransientStatus('saved', 2600); } else if (action === 'remove') { savedQuotas.delete(fields.email); quotaErrors.delete(fields.email); syncWarmCache(); setTransientStatus('removed', 2600); } else if (action === 'switch') { setTransientStatus(result.restarting ? 'restarting' : 'switchStartFailed'); } else if (action === 'setPassword') { pwdDrawerOpen = false; setTransientStatus('pwdEnabledToast', 2600); } else if (action === 'changePassword') { pwdDrawerOpen = false; setTransientStatus('pwdChangedToast', 2600); } else if (action === 'disablePassword') { pwdDrawerOpen = false; setTransientStatus('pwdDisabledToast', 2600); } else if (action === 'unlockVault') { forgotResetOpen = false; quotaErrors.clear(); setTransientStatus('vaultUnlockedToast', 2200); } else if (action === 'lockVault') { pwdDrawerOpen = false; importOpen = false; setTransientStatus('vaultLockedToast', 2200); } else if (action === 'resetVault') { forgotResetOpen = false; setTransientStatus('vaultResetToast', 2600); } } catch { setTransientStatus('storeFailed', 3200); } finally { operation = ''; if (!disposed) { render(); if (loginRefreshEmail) { const email = loginRefreshEmail; loginRefreshEmail = ''; void refreshLoginAccount(email); } } } } async function refreshLoginAccount(email) { if (disposed || !email) return; if (operation) { loginRefreshEmail = email; return; } await request('list'); if (!disposed && draftRiskAccepted && !isVaultLocked() && email !== resolveActiveEmail()) { void refreshQuota(email, false); } } function applyLogin(session) { loginSession = session; clearTimeout(loginTimer); if (['waiting', 'exchanging', 'saving'].includes(session?.status)) { loginTimer = setTimeout(() => pollLogin(session.id, loginGeneration), 1000); } } async function pollLogin(id, generation) { try { const result = await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action: 'loginStatus', id, ...(actionNonce ? { actionNonce } : {}) }, cdpTimeoutMs: 10000, }); if (disposed || generation !== loginGeneration) return; if (typeof result?.actionNonce === 'string' && result.actionNonce) { actionNonce = result.actionNonce; } if (result.error) throw new Error(result.error); applyLogin(result.login); if (loginSession?.status === 'success') await refreshLoginAccount(loginSession.email); } catch { if (disposed || generation !== loginGeneration) return; loginSession = { id, status: 'error', error: 'loginStartFailed' }; } if (!disposed) render(); } async function refreshSavedQuotas() { if (refreshingSavedQuotas || !draftRiskAccepted || isVaultLocked()) return; refreshingSavedQuotas = true; try { const activeEmail = resolveActiveEmail(); const ttlMs = refreshMinutes * 60_000; const staleTargets = accounts.filter((addr) => { if (!addr || addr === activeEmail) return false; const cached = savedQuotas.get(addr); if (needsLegacyUltraTierRefresh(cached)) return true; return Date.now() - (cached?.fetchedAt || 0) >= ttlMs; }); const BATCH_SIZE = 3; for (let i = 0; i < staleTargets.length; i += BATCH_SIZE) { if (disposed || operation === 'switch' || !draftRiskAccepted || isVaultLocked()) break; const batch = staleTargets.slice(i, i + BATCH_SIZE); await Promise.all(batch.map((addr) => refreshQuota(addr, false))); } } finally { refreshingSavedQuotas = false; } } async function refreshQuota(addr, manual = false) { const activeEmail = resolveActiveEmail(); if ( !addr || addr === activeEmail || !draftRiskAccepted || isVaultLocked() || quotaInFlight.has(addr) || disposed ) { return; } const hasCachedPools = Boolean(savedQuotas.get(addr)?.pools?.length); const showSpinner = manual || !hasCachedPools; quotaInFlight.add(addr); if (showSpinner) quotaVisibleLoading.add(addr); quotaErrors.delete(addr); if (showSpinner || quotaErrors.size > 0) render(); try { const result = await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action: 'quota', email: addr, ...(actionNonce ? { actionNonce } : {}) }, cdpTimeoutMs: 40000, }); if (typeof result?.actionNonce === 'string' && result.actionNonce) { actionNonce = result.actionNonce; } if (result?.error === 'vaultLocked') { vaultSecurity = { enabled: true, unlocked: false }; syncWarmCache(); return; } if (result?.error) { if (manual || !hasCachedPools) { quotaErrors.set(addr, errors.has(result.error) ? result.error : 'quotaUnavailable'); } } else { const prev = savedQuotas.get(addr) || {}; const nextTierId = result.tierId || prev.tierId || ''; const nextTierName = result.tierName || prev.tierName || ''; const nextTierMult = result.tierMultiplier || prev.tierMultiplier || ''; const fetchedAt = result.fetchedAt || Date.now(); savedQuotas.set(addr, { pools: result.pools, fetchedAt, ...(nextTierId ? { tierId: nextTierId } : {}), ...(nextTierName ? { tierName: nextTierName } : {}), ...(nextTierMult ? { tierMultiplier: nextTierMult } : {}), }); syncWarmCache(); } } catch { if (manual || !hasCachedPools) { quotaErrors.set(addr, 'quotaUnavailable'); } } finally { quotaInFlight.delete(addr); quotaVisibleLoading.delete(addr); if (!disposed) render(); } } function submitUnlock(event) { event.preventDefault(); if (operation) return; const pwd = unlockInput.value; unlockInput.value = ''; if (!isValidVaultPassphrase(pwd)) { setTransientStatus('wrongPassword', 3000); render(); return; } void request('unlockVault', { password: pwd }); } function submitPasswordDrawer(event) { event.preventDefault(); if (operation) return; const curPwd = pwdCurrentInput.value; const nextPwd = pwdNewInput.value; const confirmPwd = pwdConfirmInput.value; clearPasswordInputs(); if (!vaultSecurity.enabled) { if (!isValidVaultPassphrase(nextPwd)) { setTransientStatus('invalidPassword', 3200); render(); return; } if (nextPwd !== confirmPwd) { setTransientStatus('passwordMismatch', 3200); render(); return; } void request('setPassword', { newPassword: nextPwd }); return; } if (!isValidVaultPassphrase(curPwd)) { setTransientStatus('wrongPassword', 3000); render(); return; } if (pwdManageMode === 'disable') { void request('disablePassword', { currentPassword: curPwd }); return; } if (!isValidVaultPassphrase(nextPwd)) { setTransientStatus('invalidPassword', 3200); render(); return; } if (nextPwd !== confirmPwd) { setTransientStatus('passwordMismatch', 3200); render(); return; } void request('changePassword', { currentPassword: curPwd, newPassword: nextPwd }); } function importCredential(event) { event.preventDefault(); if (operation) return; const input = credential.value; credential.value = ''; void request('save', { credential: input }); } function renderAccount(value, quotaData, settingsData) { const nextRefreshMins = settingsData?.accountQuotaRefreshMinutes !== undefined ? normalizeAccountQuotaRefreshMinutes(settingsData.accountQuotaRefreshMinutes) : refreshMinutes; const nextRiskAccepted = acceptingRisk || settingsData?.accountSwitchRiskAccepted === undefined ? draftRiskAccepted : Boolean(settingsData.accountSwitchRiskAccepted); if ( account === value && quotas === quotaData && refreshMinutes === nextRefreshMins && draftRiskAccepted === nextRiskAccepted ) { return; } const becameRiskUnlocked = !draftRiskAccepted && nextRiskAccepted; account = value; quotas = quotaData; refreshMinutes = nextRefreshMins; draftRiskAccepted = nextRiskAccepted; render(); if (becameRiskUnlocked && riskLockedFromServer && !operation) { void request('list'); } } const quotaScheduleTimer = setInterval(() => { if (!disposed && draftRiskAccepted && accounts.length > 0 && !operation && !isVaultLocked()) { void refreshSavedQuotas(); } }, 60_000); quotaScheduleTimer.unref?.(); const root = h('div', { className: 'settings-tab-stack settings-account-root' }, [ quotaTrendCard.el, activeCardHost, emptyPanel, riskStage, ]); render(); onCleanup(() => { disposed = true; clearTimeout(loginTimer); clearInterval(quotaScheduleTimer); if (statusClearTimer) clearTimeout(statusClearTimer); if (confirmClearTimer) clearTimeout(confirmClearTimer); refreshIntervalSelect.destroy(); pwdModeSegment.destroy(); quotaTrendCard.destroy(); loginGeneration += 1; credential.value = ''; clearPasswordInputs(); }); return { el: root, refs: { renderAccount, refreshLabels: () => { quotaTrendCard.refs.refreshLabels(); render(); }, preload: () => (supported === null ? request('list') : Promise.resolve()), load: () => supported === null || (draftRiskAccepted && riskLockedFromServer) ? request('list') : draftRiskAccepted ? refreshSavedQuotas() : Promise.resolve(), }, }; }, }); return { SettingsAccountTab }; })(); // --- src/views/settings/SettingsOtherTab.js --- const { SettingsOtherTab } = (() => { /** * @fileoverview Preferences Tab 3: `SettingsOtherTab.js` ("其他"). * Houses Model Identifier Formatting, Per-Model Context Windows, * Local Trajectory Cache Rebuild, and Two-Step Factory Preference Reset. */ function formatQuotaReservationLogForClipboard(snapshot) { const safe = snapshot && typeof snapshot === 'object' ? snapshot : {}; const buckets = Array.isArray(safe.buckets) ? safe.buckets : []; const events = Array.isArray(safe.events) ? safe.events : []; const bucketLines = buckets.map((b) => ` ${JSON.stringify(b)}`).join(',\n'); const eventLines = events.map((e) => ` ${JSON.stringify(e)}`).join(',\n'); return [ '{', ` "generatedAt": ${JSON.stringify(safe.generatedAt || new Date().toISOString())},`, ` "count": ${events.length},`, ` "buckets": [${bucketLines ? `\n${bucketLines}\n ` : ''}],`, ` "events": [${eventLines ? `\n${eventLines}\n ` : ''}]`, '}', ].join('\n'); } function getStepModelDisplayOptions() { return [ { value: 'short', label: t('settings.oth.modelShort') }, { value: 'upstream', label: t('settings.oth.modelUpstream') }, { value: 'upstream_compact', label: t('settings.oth.modelUpstreamCompact') }, ]; } function getOrchestratorIdDisplayOptions() { return [ { value: 'compact', label: t('settings.oth.orchCompact') }, { value: 'full', label: t('settings.oth.orchFull') }, ]; } const SettingsOtherTab = defineComponent({ name: 'SettingsOtherTab', setup({ onCleanup, getProps }) { let draftModelDisplayMode = 'short'; let draftOrchestratorIdMode = 'compact'; let draftExperimentalQuotaReservation = true; let draftContextRiskAccepted = false; let acceptingContextRisk = false; let draftContextMainEnabled = true; let draftContextSwarmEnabled = false; let savingContextScope = false; let latestSettings = null; let latestWindowBridge = null; let latestCloudCodeProxy = null; let latestHostPlatform = 'win32'; let contextWindowModels = []; let contextModelId = ''; let savingContextWindow = false; let contextFeedback = ''; let modelTimer = null; let expTimer = null; let maintTimer = null; let resetConfirmTimer = null; let resetConfirmArmed = false; let isRebuilding = false; let isResetting = false; const modelStatusText = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: '', }); const expStatusText = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: '', }); const maintStatusText = h('span', { className: 'text-muted settings-panel-status', text: '', }); function showExpFeedback(text, autoClearMs = 1500) { if (expTimer) { clearTimeout(expTimer); expTimer = null; } patchText(expStatusText, text); if (text && autoClearMs > 0) { expTimer = setTimeout(() => { expTimer = null; patchText(expStatusText, ''); }, autoClearMs); } } function showModelFeedback(text, autoClearMs = 1500) { if (modelTimer) { clearTimeout(modelTimer); modelTimer = null; } patchText(modelStatusText, text); if (text && autoClearMs > 0) { modelTimer = setTimeout(() => { modelTimer = null; patchText(modelStatusText, ''); }, autoClearMs); } } function showMaintFeedback(text, autoClearMs = 2500) { if (maintTimer) { clearTimeout(maintTimer); maintTimer = null; } patchText(maintStatusText, text); patchAttr(maintStatusText, 'title', text || null); if (text && autoClearMs > 0) { maintTimer = setTimeout(() => { maintTimer = null; patchText(maintStatusText, ''); patchAttr(maintStatusText, 'title', null); }, autoClearMs); } } // --- Card 1: 模型标识显示 --- const modelCardTitleEl = h('span', { text: t('settings.oth.modelTitle') }); const modelFormatLabelEl = h('span', { className: 'form-label', text: t('settings.oth.modelFormat'), }); const orchFormatLabelEl = h('span', { className: 'form-label', text: t('settings.oth.orchFormat'), }); const stepModelSelect = CustomSelect({ modelValue: 'short', icon: 'table', options: getStepModelDisplayOptions(), onUpdateModelValue: async (val) => { const nextMode = normalizeClientModelDisplayMode(val); draftModelDisplayMode = nextMode; stepModelSelect.setValue(nextMode); showModelFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ modelDisplayMode: nextMode, showUpstreamModel: nextMode !== 'short', }); showModelFeedback(t('settings.saved'), 1500); } catch { if (latestSettings) renderSettings(latestSettings); showModelFeedback(t('settings.saveFailed'), 2500); } }, }); const orchestratorIdSelect = CustomSelect({ modelValue: 'compact', icon: 'layers', options: getOrchestratorIdDisplayOptions(), onUpdateModelValue: async (val) => { const nextMode = normalizeClientOrchestratorIdMode(val); draftOrchestratorIdMode = nextMode; orchestratorIdSelect.setValue(nextMode); showModelFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ orchestratorIdMode: nextMode }); showModelFeedback(t('settings.saved'), 1500); } catch { if (latestSettings) renderSettings(latestSettings); showModelFeedback(t('settings.saveFailed'), 2500); } }, }); const modelPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('sliders', { size: 13 }), modelCardTitleEl, ]), modelStatusText, ]), h('div', { className: 'form-row' }, [modelFormatLabelEl, stepModelSelect.el]), h('div', { className: 'form-row' }, [orchFormatLabelEl, orchestratorIdSelect.el]), ]); // --- Card 2: 试验性功能 --- const expTitleEl = h('span', { text: t('settings.oth.expTitle') }); const quotaReserveLabelEl = h('span', { className: 'settings-action-title', text: t('settings.oth.quotaReserveLabel'), }); const quotaReserveBadgeEl = h('span', { className: 'settings-experimental-badge', text: t('settings.oth.expBadge'), }); const quotaReserveDescEl = h('span', { className: 'settings-action-desc', text: t('settings.oth.quotaReserveDesc'), }); const quotaReserveLogLabelEl = h('span', { className: 'settings-action-title', text: t('settings.oth.quotaReserveLogLabel'), }); const quotaReserveLogDescEl = h('span', { className: 'settings-action-desc', text: t('settings.oth.quotaReserveLogDesc'), }); const exportReserveLogBtnText = h('span', { text: t('settings.oth.exportReserveLogBtn'), }); let isExportingReserveLog = false; const exportReserveLogBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { if (isExportingReserveLog) return; isExportingReserveLog = true; patchAttr(exportReserveLogBtn, 'disabled', true); try { const snapshot = await fetchQuotaReservationLog(); const text = formatQuotaReservationLogForClipboard(snapshot); const count = Array.isArray(snapshot?.events) ? snapshot.events.length : 0; const successMsg = count > 0 ? t('settings.oth.exportReserveLogCopied', { count }) : t('settings.oth.exportReserveLogEmpty'); const ok = await copyTextWithFeedback(text, successMsg); showExpFeedback(ok ? successMsg : t('settings.oth.exportReserveLogFailed'), 2800); } catch { showExpFeedback(t('settings.oth.exportReserveLogFailed'), 2800); } finally { isExportingReserveLog = false; patchAttr(exportReserveLogBtn, 'disabled', false); } }, }, [createSvgIcon('copy', { size: 12 }), exportReserveLogBtnText] ); const quotaReserveToggle = ToggleSwitch({ modelValue: 'on', ariaLabelKey: 'settings.oth.quotaReserveLabel', preset: 'enable', onUpdateModelValue: async (val) => { const nextEnabled = val === 'on'; draftExperimentalQuotaReservation = nextEnabled; quotaReserveToggle.setProps({ modelValue: nextEnabled ? 'on' : 'off', }); showExpFeedback(t('settings.saving'), 0); try { await saveSettingsPatch({ experimentalQuotaReservation: nextEnabled }); showExpFeedback(t('settings.saved'), 1500); } catch { if (latestSettings) renderSettings(latestSettings); showExpFeedback(t('settings.saveFailed'), 2500); } }, }); const experimentalPanel = h('section', { className: 'panel', hidden: true }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('pulse', { size: 13 }), expTitleEl, ]), expStatusText, ]), h('div', { className: 'settings-action-block' }, [ h('div', { className: 'settings-action-info' }, [ h('div', { className: 'settings-experimental-label-group' }, [ quotaReserveLabelEl, quotaReserveBadgeEl, ]), quotaReserveDescEl, ]), quotaReserveToggle.el, ]), h('div', { className: 'settings-action-block' }, [ h('div', { className: 'settings-action-info' }, [ quotaReserveLogLabelEl, quotaReserveLogDescEl, ]), exportReserveLogBtn, ]), ]); // --- Card 2: 按模型设置上下文窗口 --- const baselineTitleEl = h('span', { text: t('settings.oth.baselineTitle') }); const ctxModelLabel = h('span', { className: 'form-label' }); const ctxWindowLabel = h('span', { className: 'form-label' }); const ctxHint = h('span', { className: 'settings-hint-text' }); const ctxStatus = h('span', { className: 'text-muted settings-panel-status', role: 'status', }); const ctxModelSelect = CustomSelect({ className: 'settings-context-model', searchable: true, searchThreshold: 8, options: [], onUpdateModelValue: (id) => { if (!draftContextRiskAccepted || savingContextWindow) return; contextModelId = id; contextFeedback = ''; renderContextWindows(); }, }); const ctxWindowSelect = CustomSelect({ options: [], onUpdateModelValue: async (value) => { if (!draftContextRiskAccepted || savingContextWindow || !contextModelId) return; savingContextWindow = true; contextFeedback = 'settings.saving'; renderContextWindows(); try { const modelContextWindows = await saveModelContextWindow(contextModelId, value || null); latestSettings = { ...latestSettings, modelContextWindows }; contextFeedback = 'settings.saved'; } catch { contextFeedback = 'settings.saveFailed'; } finally { savingContextWindow = false; renderContextWindows(); } }, }); const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true }); const ctxMainLabelEl = h('span', { className: 'form-label', text: t('settings.oth.ctxMainLabel'), }); const ctxMainToggle = ToggleSwitch({ modelValue: 'on', ariaLabelKey: 'settings.oth.ctxMainLabel', preset: 'enable', onUpdateModelValue: async (val) => { if (!draftContextRiskAccepted || savingContextScope) return; const nextEnabled = val === 'on'; const prevEnabled = draftContextMainEnabled; savingContextScope = true; draftContextMainEnabled = nextEnabled; latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: nextEnabled }; contextFeedback = 'settings.saving'; renderContextWindows(); try { await saveSettingsPatch({ contextWindowMainEnabled: nextEnabled }); contextFeedback = 'settings.saved'; } catch { draftContextMainEnabled = prevEnabled; latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: prevEnabled }; contextFeedback = 'settings.saveFailed'; } finally { savingContextScope = false; renderContextWindows(); } }, }); const ctxSwarmLabelEl = h('span', { className: 'form-label', text: t('settings.oth.ctxSwarmLabel'), }); const ctxSwarmToggle = ToggleSwitch({ modelValue: 'off', ariaLabelKey: 'settings.oth.ctxSwarmLabel', preset: 'enable', onUpdateModelValue: async (val) => { if (!draftContextRiskAccepted || savingContextScope) return; const nextEnabled = val === 'on'; const prevEnabled = draftContextSwarmEnabled; savingContextScope = true; draftContextSwarmEnabled = nextEnabled; latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: nextEnabled }; contextFeedback = 'settings.saving'; renderContextWindows(); try { await saveSettingsPatch({ contextWindowSwarmEnabled: nextEnabled }); contextFeedback = 'settings.saved'; } catch { draftContextSwarmEnabled = prevEnabled; latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: prevEnabled }; contextFeedback = 'settings.saveFailed'; } finally { savingContextScope = false; renderContextWindows(); } }, }); const ctxMainRow = h('div', { className: 'form-row' }, [ctxMainLabelEl, ctxMainToggle.el]); const ctxSwarmRow = h('div', { className: 'form-row' }, [ctxSwarmLabelEl, ctxSwarmToggle.el]); const ctxSyncStatusEl = h('span', { className: 'settings-hint-text ctx-sync-status is-error', hidden: true, }); const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]); const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]); const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ ctxBridgeNotice.el, ctxMainRow, ctxSwarmRow, ctxSyncStatusEl, ctxModelRow, ctxWindowRow, h('div', { className: 'form-row' }, [ctxHint]), ]); const ctxRiskTitleEl = h('strong', { className: 'ctx-risk-title', text: t('settings.oth.ctxRiskTitle'), }); const ctxRiskBodyEl = h('p', { className: 'ctx-risk-desc', text: t('settings.oth.ctxRiskBody'), }); const ctxRiskAcceptBtnText = h('span', { text: t('settings.oth.ctxRiskAcceptBtn') }); const ctxRiskAcceptBtn = h( 'button', { type: 'button', className: 'btn-secondary btn-danger-confirm ctx-risk-accept-btn', onClick: async () => { if (acceptingContextRisk || draftContextRiskAccepted) return; acceptingContextRisk = true; draftContextRiskAccepted = true; latestSettings = { ...(latestSettings || {}), contextWindowRiskAccepted: true }; contextFeedback = 'settings.saving'; renderContextWindows(); try { await saveSettingsPatch({ contextWindowRiskAccepted: true }); contextFeedback = 'settings.saved'; } catch { draftContextRiskAccepted = false; latestSettings = { ...(latestSettings || {}), contextWindowRiskAccepted: false }; contextFeedback = 'settings.saveFailed'; } finally { acceptingContextRisk = false; renderContextWindows(); } }, }, [createSvgIcon('warning', { size: 12 }), ctxRiskAcceptBtnText] ); const ctxRiskMask = h( 'div', { className: 'ctx-risk-mask', role: 'region', 'aria-label': t('settings.oth.ctxRiskTitle'), }, [ h('div', { className: 'ctx-risk-head' }, [ createSvgIcon('warning', { size: 14, className: 'ctx-risk-icon' }), ctxRiskTitleEl, ]), ctxRiskBodyEl, ctxRiskAcceptBtn, ] ); const ctxRiskStage = h('div', { className: 'ctx-risk-stage' }, [ctxControlsBody, ctxRiskMask]); function renderContextWindows() { const unlocked = Boolean(draftContextRiskAccepted); if (!unlocked) { ctxModelSelect.close(); ctxWindowSelect.close(); } patchClasses(ctxControlsBody, { 'is-locked': !unlocked }); patchAttr(ctxControlsBody, 'inert', !unlocked); patchAttr(ctxControlsBody, 'aria-hidden', unlocked ? null : 'true'); patchAttr(ctxRiskMask, 'hidden', unlocked); patchAttr(ctxRiskMask, 'aria-label', t('settings.oth.ctxRiskTitle')); patchText(ctxRiskTitleEl, t('settings.oth.ctxRiskTitle')); patchText(ctxRiskBodyEl, t('settings.oth.ctxRiskBody')); patchText(ctxRiskAcceptBtnText, t('settings.oth.ctxRiskAcceptBtn')); patchAttr(ctxRiskAcceptBtn, 'disabled', acceptingContextRisk); const saved = latestSettings?.modelContextWindows || {}; const wbState = String(latestWindowBridge?.state || '').trim(); const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable'; const proxyState = String(latestCloudCodeProxy?.state || 'disabled'); const isProxyActive = Boolean(latestCloudCodeProxy?.active && proxyState === 'active'); patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel')); ctxMainToggle.setProps({ modelValue: draftContextMainEnabled ? 'on' : 'off', }); patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel')); ctxSwarmToggle.setProps({ modelValue: draftContextSwarmEnabled ? 'on' : 'off', }); const syncErrorText = draftContextSwarmEnabled && proxyState === 'error' && latestCloudCodeProxy?.error ? t('settings.oth.ctxSwarmError', { error: latestCloudCodeProxy.error }) : ''; patchAttr(ctxSyncStatusEl, 'hidden', !syncErrorText); patchText(ctxSyncStatusEl, syncErrorText); ctxBridgeNotice.refs.update({ visible: unlocked && draftContextMainEnabled, windowBridge: latestWindowBridge, hostPlatform: latestHostPlatform, }); const models = new Map(contextWindowModels.map((model) => [model.id, model])); const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members])); for (const id of Object.keys(saved)) { if (!knownIds.has(id)) models.set(id, { id, label: id.replace(/^model:/, ''), options: [] }); } if (!models.has(contextModelId)) contextModelId = ''; const mixed = '\u0000mixed'; const getSelection = ({ id, members = [] }) => { const legacy = new Set(members.map((member) => saved[member]).filter(Boolean)); return saved[id] || (legacy.size > 1 ? mixed : legacy.values().next().value) || ''; }; const formatLimit = (value) => /^\d+$/.test(value) ? t('settings.oth.ctxTokens', { count: Number(value).toLocaleString() }) : value; const isAvailable = (model, value) => model.options.some(({ name }) => name === value) || (/^[1-9]\d*$/.test(value) && Number(value) <= model.capacity); const current = models.get(contextModelId); const options = current?.options || []; const selected = current ? getSelection(current) : ''; const choices = [ { value: '', label: t('settings.oth.ctxDefault') }, ...options.map(({ name, expensive, tokens }) => ({ value: name, label: tokens ? formatLimit(name) : (expensive ? t('settings.oth.ctxExpensive', { name }) : name), })), ]; if (selected && !choices.some((item) => item.value === selected)) { let label = t('settings.oth.ctxMixed'); if (selected !== mixed) { const name = formatLimit(selected); label = isAvailable(current, selected) ? name : t('settings.oth.ctxUnavailable', { name }); } choices.push({ value: selected, label, disabled: true }); } ctxModelSelect.setProps({ modelValue: contextModelId, options: [ { value: '', label: t('settings.oth.ctxChooseModel') }, ...[...models.values()].map((model) => { const value = getSelection(model); let meta = t('settings.oth.ctxDefault'); if (value === mixed) meta = t('settings.oth.ctxMixed'); else if (value) { const name = formatLimit(value); if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name }); else if ( isBridgeMissing && draftContextMainEnabled && !(draftContextSwarmEnabled && isProxyActive) ) { meta = t('settings.oth.ctxPendingBridge', { name }); } else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) { meta = t('settings.oth.ctxConfiguredReported', { name, reported: formatLimit(String(model.reportedLimitTokens)), }); } else meta = t('settings.oth.ctxConfigured', { name }); } else if (model.reportedLimitTokens) meta = t('settings.oth.ctxDefaultReported', { name: formatLimit(String(model.reportedLimitTokens)) }); return { value: model.id, label: model.label, meta }; }), ], }); ctxWindowSelect.setProps({ modelValue: selected, options: choices }); patchAttr(ctxModelSelect.refs.triggerBtn, 'disabled', !unlocked || savingContextWindow); patchAttr(ctxWindowSelect.refs.triggerBtn, 'disabled', !unlocked || savingContextWindow || (!options.length && !selected)); patchAttr(ctxModelSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxModel')); patchAttr(ctxWindowSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxBaselineLabel')); patchAttr(ctxModelRow, 'hidden', !models.size); patchAttr(ctxWindowRow, 'hidden', !contextModelId); patchText(ctxModelLabel, t('settings.oth.ctxModel')); patchText(ctxWindowLabel, t('settings.oth.ctxBaselineLabel')); const hint = !models.size ? 'ctxNoModels' : selected === mixed ? 'ctxMixedHint' : contextModelId && !options.length ? 'ctxNoOptions' : 'ctxBaselineHint'; const reported = current?.reportedLimitTokens; patchText(ctxHint, [t(`settings.oth.${hint}`), reported && t('settings.oth.ctxReported', { name: formatLimit(String(reported)) })].filter(Boolean).join(' ')); patchText(ctxStatus, contextFeedback ? t(contextFeedback) : ''); getProps().onLayoutChange?.(); } const baselinePanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header settings-panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('layers', { size: 13 }), baselineTitleEl, ]), ctxStatus, ]), ctxRiskStage, ]); renderContextWindows(); // --- Card 3: 缓存与重置 --- const maintTitleEl = h('span', { text: t('settings.oth.maintTitle') }); const cacheLabelEl = h('span', { className: 'settings-action-title', text: t('settings.oth.cacheLabel'), }); const cacheDescEl = h('span', { className: 'settings-action-desc', text: t('settings.oth.cacheDesc'), }); const rebuildBtnText = h('span', { text: t('settings.oth.rebuildBtn') }); const rebuildCacheBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { if (isRebuilding) return; isRebuilding = true; patchAttr(rebuildCacheBtn, 'disabled', true); patchText(rebuildBtnText, t('settings.oth.rebuildingBtn')); showMaintFeedback(t('settings.oth.rebuildingBtn'), 0); try { const res = await rebuildTrajectoryCache(); if (res?.ok !== false) { showMaintFeedback(t('settings.oth.rebuildDone'), 2800); } else { showMaintFeedback(t('settings.oth.rebuildFailed'), 3000); } } catch { showMaintFeedback(t('settings.oth.rebuildFailed'), 3000); } finally { isRebuilding = false; patchAttr(rebuildCacheBtn, 'disabled', false); patchText(rebuildBtnText, t('settings.oth.rebuildBtn')); } }, }, [createSvgIcon('refresh', { size: 12 }), rebuildBtnText] ); const resetLabelEl = h('span', { className: 'settings-action-title', text: t('settings.oth.resetLabel'), }); const resetDescEl = h('span', { className: 'settings-action-desc', text: t('settings.oth.resetDesc'), }); const resetBtnText = h('span', { text: t('settings.oth.resetAllBtn') }); function disarmResetConfirm() { resetConfirmArmed = false; if (resetConfirmTimer) { clearTimeout(resetConfirmTimer); resetConfirmTimer = null; } patchClasses(resetAllBtn, { 'btn-danger-confirm': false }); if (!isResetting) { patchText(resetBtnText, t('settings.oth.resetAllBtn')); } } const resetAllBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { if (isResetting) return; if (!resetConfirmArmed) { resetConfirmArmed = true; patchClasses(resetAllBtn, { 'btn-danger-confirm': true }); patchText(resetBtnText, t('settings.oth.resetConfirmBtn')); if (resetConfirmTimer) clearTimeout(resetConfirmTimer); resetConfirmTimer = setTimeout(() => { disarmResetConfirm(); }, 3000); return; } disarmResetConfirm(); isResetting = true; patchAttr(resetAllBtn, 'disabled', true); patchText(resetBtnText, t('settings.oth.resettingBtn')); showMaintFeedback(t('settings.oth.resettingBtn'), 0); try { const res = await resetAllSettings(); setI18nLanguage(res?.settings?.language || 'auto'); showMaintFeedback(t('settings.oth.resetAllDone'), 2800); } catch { showMaintFeedback(t('settings.saveFailed'), 2800); } finally { isResetting = false; patchAttr(resetAllBtn, 'disabled', false); patchText(resetBtnText, t('settings.oth.resetAllBtn')); } }, }, [resetBtnText] ); const backupLabelEl = h('span', { className: 'settings-action-title', text: t('settings.oth.backupLabel'), }); const backupDescEl = h('span', { className: 'settings-action-desc', text: t('settings.oth.backupDesc'), }); const exportJsonBtnText = h('span', { text: t('settings.oth.exportJsonBtn') }); const importJsonBtnText = h('span', { text: t('settings.oth.importJsonBtn') }); let isImportingSettings = false; async function applyImportedSettingsText(rawText) { const parsed = parseImportedSettingsJson(rawText); if (!parsed.ok) { showMaintFeedback(t('settings.oth.importInvalid'), 3200); return false; } isImportingSettings = true; patchAttr(importJsonBtn, 'disabled', true); showMaintFeedback(t('settings.saving'), 0); try { await saveSettingsPatch(parsed.patch); if (parsed.patch.language) { setI18nLanguage(parsed.patch.language); } showMaintFeedback( t('settings.oth.importDone', { count: parsed.appliedCount }), 2800 ); return true; } catch { showMaintFeedback(t('settings.saveFailed'), 2800); return false; } finally { isImportingSettings = false; patchAttr(importJsonBtn, 'disabled', false); } } const importFileInput = h('input', { type: 'file', accept: '.json,application/json', className: 'settings-hidden-file-input', hidden: true, }); importFileInput.addEventListener?.('change', async () => { const file = importFileInput.files?.[0]; importFileInput.value = ''; if (!file || isImportingSettings) return; try { const text = typeof file.text === 'function' ? await file.text() : String(file.content || ''); await applyImportedSettingsText(text); } catch { showMaintFeedback(t('settings.oth.importInvalid'), 3200); } }); const exportJsonBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: async () => { const json = buildExportableSettingsJson(latestSettings || {}); const res = await exportTextFileWithFeedback( 'antigravity-usage-monitor-settings.json', json, 'application/json;charset=utf-8' ); if (res?.ok) { showMaintFeedback( res.filePath ? `${t('settings.oth.exportDone')} · ${res.filePath}` : t('settings.oth.exportDone'), 4200 ); } }, }, [createSvgIcon('download', { size: 12 }), exportJsonBtnText] ); const importJsonBtn = h( 'button', { type: 'button', className: 'btn-secondary', onClick: () => { if (isImportingSettings) return; importFileInput.click?.(); }, }, [createSvgIcon('upload', { size: 12 }), importJsonBtnText] ); const backupActionsWrap = h('div', { className: 'settings-backup-actions' }, [ exportJsonBtn, importJsonBtn, importFileInput, ]); const maintPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header settings-panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('refresh', { size: 13 }), maintTitleEl, ]), maintStatusText, ]), h('div', { className: 'settings-action-block' }, [ h('div', { className: 'settings-action-info' }, [cacheLabelEl, cacheDescEl]), rebuildCacheBtn, ]), h('div', { className: 'settings-action-block' }, [ h('div', { className: 'settings-action-info' }, [resetLabelEl, resetDescEl]), resetAllBtn, ]), h('div', { className: 'settings-action-block' }, [ h('div', { className: 'settings-action-info' }, [backupLabelEl, backupDescEl]), backupActionsWrap, ]), ]); const sessionMigrationCard = SessionMigrationCard({ onLayoutChange: () => { getProps()?.onLayoutChange?.(); }, }); const rootEl = h('div', { className: 'settings-tab-stack' }, [ modelPanel, experimentalPanel, baselinePanel, maintPanel, sessionMigrationCard.el, ]); function renderSettings( settings, models = contextWindowModels, windowBridge = latestWindowBridge, hostPlatform = latestHostPlatform, cloudCodeProxy = latestCloudCodeProxy ) { if (!settings) return; latestSettings = settings; contextWindowModels = models; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; if (cloudCodeProxy !== undefined) latestCloudCodeProxy = cloudCodeProxy; draftModelDisplayMode = normalizeClientModelDisplayMode( settings.modelDisplayMode, settings.showUpstreamModel ); draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode); draftExperimentalQuotaReservation = normalizeClientExperimentalQuotaReservation( settings.experimentalQuotaReservation ); if (!acceptingContextRisk) { draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted); } if (!savingContextScope) { draftContextMainEnabled = settings.contextWindowMainEnabled !== false; draftContextSwarmEnabled = settings.contextWindowSwarmEnabled === true; } stepModelSelect.setProps({ modelValue: draftModelDisplayMode, options: getStepModelDisplayOptions(), }); orchestratorIdSelect.setProps({ modelValue: draftOrchestratorIdMode, options: getOrchestratorIdDisplayOptions(), }); quotaReserveToggle.setProps({ modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', }); renderContextWindows(); void sessionMigrationCard.refs.ensureLoaded(); } function refreshLabels() { patchText(modelCardTitleEl, t('settings.oth.modelTitle')); patchText(modelFormatLabelEl, t('settings.oth.modelFormat')); patchText(orchFormatLabelEl, t('settings.oth.orchFormat')); patchText(expTitleEl, t('settings.oth.expTitle')); patchText(quotaReserveLabelEl, t('settings.oth.quotaReserveLabel')); patchText(quotaReserveBadgeEl, t('settings.oth.expBadge')); patchText(quotaReserveDescEl, t('settings.oth.quotaReserveDesc')); patchText(quotaReserveLogLabelEl, t('settings.oth.quotaReserveLogLabel')); patchText(quotaReserveLogDescEl, t('settings.oth.quotaReserveLogDesc')); patchText(exportReserveLogBtnText, t('settings.oth.exportReserveLogBtn')); quotaReserveToggle.setProps({ modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', }); patchText(baselineTitleEl, t('settings.oth.baselineTitle')); renderContextWindows(); patchText(maintTitleEl, t('settings.oth.maintTitle')); patchText(backupLabelEl, t('settings.oth.backupLabel')); patchText(backupDescEl, t('settings.oth.backupDesc')); patchText(exportJsonBtnText, t('settings.oth.exportJsonBtn')); patchText(importJsonBtnText, t('settings.oth.importJsonBtn')); patchText(cacheLabelEl, t('settings.oth.cacheLabel')); patchText(cacheDescEl, t('settings.oth.cacheDesc')); patchText(resetLabelEl, t('settings.oth.resetLabel')); patchText(resetDescEl, t('settings.oth.resetDesc')); if (!isRebuilding) { patchText(rebuildBtnText, t('settings.oth.rebuildBtn')); } if (!isResetting) { patchText( resetBtnText, resetConfirmArmed ? t('settings.oth.resetConfirmBtn') : t('settings.oth.resetAllBtn') ); } stepModelSelect.setProps({ modelValue: draftModelDisplayMode, options: getStepModelDisplayOptions(), }); orchestratorIdSelect.setProps({ modelValue: draftOrchestratorIdMode, options: getOrchestratorIdDisplayOptions(), }); sessionMigrationCard.refs.refreshLabels(); } onCleanup(() => { if (modelTimer) clearTimeout(modelTimer); if (expTimer) clearTimeout(expTimer); if (maintTimer) clearTimeout(maintTimer); if (resetConfirmTimer) clearTimeout(resetConfirmTimer); stepModelSelect.destroy(); orchestratorIdSelect.destroy(); quotaReserveToggle.destroy(); ctxBridgeNotice.destroy(); ctxMainToggle.destroy(); ctxSwarmToggle.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); sessionMigrationCard.destroy(); }); return { el: rootEl, refs: { stepModelSelect, orchestratorIdSelect, quotaReserveToggle, exportReserveLogBtn, ctxBridgeNotice, ctxMainToggle, ctxSwarmToggle, ctxModelSelect, ctxWindowSelect, sessionMigrationCard, rebuildCacheBtn, resetAllBtn, exportJsonBtn, importJsonBtn, importFileInput, applyImportedSettingsText, renderSettings, refreshLabels, }, }; }, }); return { SettingsOtherTab }; })(); // --- src/components/layout/TopSessionHeader.js --- const { TopSessionHeader } = (() => { /** * @fileoverview Row 1 of the compact top bar: * Bespoke CustomSelect for session switching, SVG live status indicator, * and async force-refresh button. */ const INLINE_UUID_RE = /(? 0 && otherSubs > 0) { return t('header.convCompactSwarmAndSubs', { swarm, subs: otherSubs, total }); } if (swarm > 0) { return t('header.convCompactSwarm', { swarm, total }); } if (totalSubs > 0) { return t('header.convCompactSubs', { subs: totalSubs, total }); } return t('header.convMetaSteps', { count: main }); } function resolveConvTotalSteps(c) { if (!c) return 0; const main = Number(c.stepCount || 0); return Number(c.totalStepCount ?? c.totalStepsAllAgents ?? main); } function formatConvOptionTitle(c) { const parts = []; const label = String(c?.title || c?.cascadeId?.slice?.(0, 8) || '').trim(); if (label) { parts.push(c?.swarmTitle && c.swarmTitle !== c.title ? `${label} · ${c.swarmTitle}` : label); } const fullMeta = formatConversationMeta(c); if (fullMeta) { parts.push(fullMeta); } const wsPath = String(c?.workspacePath || c?.workspaceName || '').trim(); if (wsPath) { parts.push(wsPath); } return parts.length > 0 ? parts.join(' · ') : ''; } const TopSessionHeader = defineComponent({ name: 'TopSessionHeader', setup({ onCleanup }) { const convSelect = CustomSelect({ className: 'session-select', modelValue: telemetryStore.getState().selectedConversationId, placeholder: t('header.followLatest'), searchable: true, searchThreshold: 6, searchPlaceholder: t('header.searchSessionPlaceholder'), options: [{ value: '', label: t('header.followLatest') }], onUpdateModelValue: (nextConvId) => { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); void selectConversation(nextConvId); }, }); const updateBtnIcon = createSvgIcon('arrow-down', { size: 11 }); const updateBtnText = h('span', { text: t('header.hasUpdate') }); let isHeaderUpdating = false; const updateBtn = h( 'button', { type: 'button', className: 'update-badge-btn', hidden: true, 'aria-label': t('header.ariaUpdate'), onClick: async () => { if (isHeaderUpdating) return; isHeaderUpdating = true; patchText(updateBtnText, t('header.upgrading')); patchAttr(updateBtn, 'disabled', true); try { const res = await triggerPluginUpdate(); if (!res?.ok) { uiStore.setState({ activeView: 'settings' }); } } catch { uiStore.setState({ activeView: 'settings' }); } finally { isHeaderUpdating = false; patchAttr(updateBtn, 'disabled', false); const cs = telemetryStore.getState().telemetry?.cloudStatus; patchText( updateBtnText, cs?.latestPluginVersion ? t('header.upgradeToVer', { ver: cs.latestPluginVersion }) : t('header.hasUpdate') ); } }, }, [updateBtnIcon, updateBtnText] ); const sshBadge = h('span', { className: 'endpoint-ssh-badge', hidden: true, text: 'SSH', }); const statusIcon = createSvgIcon('pulse', { size: 12 }); const statusText = h('span', { text: t('header.statusLive') }); const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]); const refreshBtn = h( 'button', { type: 'button', className: 'icon-btn', 'aria-label': t('header.ariaRefresh'), onClick: () => fetchTelemetry({ force: true }), }, [createSvgIcon('refresh', { size: 13 })] ); const headerRowEl = h('div', { className: 'session-header' }, [ h('div', { className: 'session-left' }, [convSelect.el]), h('div', { className: 'session-right' }, [sshBadge, updateBtn, statusTag, refreshBtn]), ]); const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); let lastActiveCascadeId = ''; let lastAppliedHostChildRouteId = ''; let preChildCtxInspectorAgentId = ''; function syncSessionScopeOnCascadeChange(telemetry, telSlice = telemetryStore.getState()) { const currentCascadeId = telemetry?.activeConversation?.cascadeId || ''; if (!currentCascadeId) return; const selectedId = String(telSlice?.selectedConversationId || '').trim(); const hostRouteId = String(telSlice?.hostRouteConversationId || '').trim(); const hostRouteLower = hostRouteId.toLowerCase(); const defaultCtxId = getDefaultCtxInspectorAgentId(telemetry?.settings); if (!selectedId && hostRouteLower) { const routeMatch = resolveHostRouteMatch(telemetry, hostRouteId); if (routeMatch?.isChildRoute && routeMatch.childAgent?.agentId) { lastActiveCascadeId = currentCascadeId; if (lastAppliedHostChildRouteId !== hostRouteLower) { const uiSt = uiStore.getState(); if (!lastAppliedHostChildRouteId) { preChildCtxInspectorAgentId = uiSt.ctxInspectorAgentId === 'main' || uiSt.ctxInspectorAgentId === 'auto' ? uiSt.ctxInspectorAgentId : defaultCtxId; } lastAppliedHostChildRouteId = hostRouteLower; const targetAgentId = routeMatch.childAgent.agentId; if ( uiSt.selectedAgentScope !== targetAgentId || uiSt.ctxInspectorAgentId !== targetAgentId ) { uiStore.setState({ selectedAgentScope: targetAgentId, ctxInspectorAgentId: targetAgentId, }); } } return; } if (lastAppliedHostChildRouteId && !routeMatch?.isChildRoute) { const restoreCtxId = preChildCtxInspectorAgentId === 'main' || preChildCtxInspectorAgentId === 'auto' ? preChildCtxInspectorAgentId : defaultCtxId; lastAppliedHostChildRouteId = ''; preChildCtxInspectorAgentId = ''; const uiSt = uiStore.getState(); if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== restoreCtxId) { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: restoreCtxId }); } lastActiveCascadeId = currentCascadeId; return; } } else if (lastAppliedHostChildRouteId) { lastAppliedHostChildRouteId = ''; preChildCtxInspectorAgentId = ''; } if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) { lastActiveCascadeId = currentCascadeId; preChildCtxInspectorAgentId = ''; const uiSt = uiStore.getState(); if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== defaultCtxId) { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: defaultCtxId }); } } else { lastActiveCascadeId = currentCascadeId; } } function renderHeaderState() { const telSt = telemetryStore.getState(); const uiSt = uiStore.getState(); const telemetry = telSt.telemetry; if (!uiSt.monitorVisible) return; patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate')); patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh')); const ep = telemetry?.endpoint; const isRemoteEndpoint = Boolean(ep?.isRemote); patchAttr(sshBadge, 'hidden', !isRemoteEndpoint); if (isRemoteEndpoint) { const epLabel = String(ep?.label || 'SSH').trim(); patchAttr(sshBadge, 'title', epLabel && epLabel !== 'SSH' ? `SSH · ${epLabel}` : 'SSH'); } const actConv = telemetry?.activeConversation; const convs = telemetry?.conversations || []; const hostRouteId = telSt.hostRouteConversationId || ''; const routeMatch = hostRouteId ? resolveHostRouteMatch(telemetry, hostRouteId) : null; const hostMatchedConv = routeMatch?.rootConv || null; const childRouteBadge = routeMatch?.isChildRoute && routeMatch.childAgent ? formatAgentBadgeText(routeMatch.childAgent) : ''; const hostBaseTitle = compactInlineUuids( hostMatchedConv?.title || hostRouteId.slice(0, 8) ); const hostDisplayTitle = childRouteBadge ? `${hostBaseTitle} · ${childRouteBadge}` : hostBaseTitle; const defaultTriggerLabel = hostRouteId ? t('header.currentWindowNamed', { title: hostDisplayTitle, }) : convs[0]?.title ? t('header.latestNamed', { title: compactInlineUuids(convs[0].title) }) : t('header.followLatest'); const lockedId = telSt.selectedConversationId; const defaultMenuLabel = hostRouteId ? t('header.followCurrentWindow') : t('header.followLatest'); const options = [ { value: '', label: defaultMenuLabel, shortLabel: defaultTriggerLabel, meta: t('header.autoFollowBadge'), dividerAfter: convs.length > 0 || Boolean(lockedId), ...(hostMatchedConv?.swarmTitle ? { title: hostMatchedConv.swarmTitle } : {}), }, ...convs.map((c) => { const rawTitle = c.title || c.cascadeId.slice(0, 8); const cleanLabel = compactInlineUuids(rawTitle); const wsName = String(c?.workspaceName || '').trim(); const optTitle = formatConvOptionTitle(c); return { value: c.cascadeId, label: cleanLabel, meta: formatCompactConvStepsMeta(c), dimMeta: resolveConvTotalSteps(c) === 0, searchText: `${rawTitle} ${wsName} ${c.workspacePath || ''} ${c.swarmTitle || ''}`, ...(optTitle ? { title: optTitle } : {}), }; }), ]; if (lockedId && !convs.some((c) => c.cascadeId === lockedId)) { const isLoadedLocked = actConv?.cascadeId === lockedId; const rawLockedTitle = isLoadedLocked && actConv?.title ? actConv.title : t('header.lockedSession', { id: String(lockedId).slice(0, 8) }); const lockedLabel = compactInlineUuids(rawLockedTitle); const lockedWs = isLoadedLocked ? String(actConv?.workspaceName || '').trim() : ''; const lockedMeta = isLoadedLocked ? formatCompactConvStepsMeta(actConv) : t('header.lockedMeta'); options.splice(1, 0, { value: lockedId, label: lockedLabel, meta: lockedMeta, searchText: `${rawLockedTitle} ${lockedWs}`, }); } convSelect.setProps({ modelValue: telSt.selectedConversationId, placeholder: t('header.followLatest'), searchPlaceholder: t('header.searchSessionPlaceholder'), options, }); const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0); const aggregated = actConv?.aggregated; const cloudStatus = telemetry?.cloudStatus; const updateMode = normalizeClientUpdateMode( telemetry?.settings?.pluginUpdateMode, telemetry?.settings?.autoUpdatePlugin ); const showUpdate = Boolean(cloudStatus?.updateAvailable) && updateMode !== 'off'; patchAttr(updateBtn, 'hidden', !showUpdate); if (showUpdate && !isHeaderUpdating) { patchText( updateBtnText, cloudStatus?.latestPluginVersion ? t('header.upgradeToVer', { ver: cloudStatus.latestPluginVersion }) : t('header.hasUpdate') ); } const isSyncing = telSt.syncState === 'syncing'; const isSynced = telSt.syncState === 'synced'; const isError = telSt.syncState === 'error'; const isRunning = Boolean(aggregated?.isRunning || telemetry?.activeConversation?.isRunning); const quotaMeta = telemetry?.quotas?.meta; const quotaStale = Boolean(quotaMeta?.refreshFailed || quotaMeta?.isStale); patchClasses(refreshBtn, { 'is-spinning': isSyncing }); patchAttr(refreshBtn, 'disabled', isSyncing); if (isSyncing) { patchSvgIcon(statusIcon, 'refresh'); patchText(statusText, t('header.statusSyncing')); patchClasses(statusTag, { 'state-running': false, 'state-synced': true, 'state-warn': false, }); } else if (isSynced) { patchSvgIcon(statusIcon, 'check'); patchText(statusText, t('header.statusSynced')); patchClasses(statusTag, { 'state-running': false, 'state-synced': true, 'state-warn': false, }); } else if (isError) { patchSvgIcon(statusIcon, 'warning'); patchText(statusText, t('header.statusRetrying')); patchClasses(statusTag, { 'state-running': false, 'state-synced': false, 'state-warn': true, }); } else if (isRunning) { const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning); const runSuffix = hasSubagents && runningAgent ? ` · ${formatAgentBadgeText(runningAgent)}` : ''; patchSvgIcon(statusIcon, 'bolt'); patchText(statusText, t('header.statusGenerating', { suffix: runSuffix })); patchClasses(statusTag, { 'state-running': true, 'state-synced': false, 'state-warn': false, }); } else if (quotaStale) { patchSvgIcon(statusIcon, 'warning'); patchText( statusText, quotaMeta?.hasOfficialData ? t('header.statusQuotaCached') : t('header.statusQuotaOffline') ); patchClasses(statusTag, { 'state-running': false, 'state-synced': false, 'state-warn': true, }); } else { patchSvgIcon(statusIcon, 'pulse'); patchText(statusText, t('header.statusLive')); patchClasses(statusTag, { 'state-running': false, 'state-synced': false, 'state-warn': false, }); } } const unsubTelemetry = telemetryStore.subscribe( (st) => ({ selectedConversationId: st.selectedConversationId, hostRouteConversationId: st.hostRouteConversationId, syncState: st.syncState, telemetry: st.telemetry, }), (slice) => { syncSessionScopeOnCascadeChange(slice.telemetry, slice); renderHeaderState(); } ); const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => renderHeaderState() ); const unsubVisibility = uiStore.subscribe( (st) => st.monitorVisible, (visible) => { if (visible) renderHeaderState(); }, { immediate: false } ); onCleanup(() => { unsubTelemetry(); unsubI18n(); unsubVisibility(); convSelect.destroy(); }); return { el: headerEl, refs: { convSelect, statusTag, refreshBtn }, }; }, }); return { TopSessionHeader }; })(); // --- src/views/LiveOverviewView.js --- const { LiveOverviewView } = (() => { /** * @fileoverview View 1: Decoupled `LiveOverviewView.js` (实时监控视图). * Acts as a lightweight host container delegating all telemetry cards * (`metrics`, `context`, `quotas`, `live_tasks`) to `widgetRegistry.js` (`a` calls `b`), * allowing users to freely reorder or remove any module down to 1 item. */ const LiveOverviewView = defineComponent({ name: 'LiveOverviewView', setup({ onCleanup }) { const overviewInner = h('div', { className: 'overview-modules-host', }); const widgetHost = createDynamicWidgetHost({ containerEl: overviewInner, mode: 'overview', isVisibleFn: () => getVisibleMonitorView() === 'overview', initialModuleKeys: DEFAULT_CLIENT_OVERVIEW_MODULES, }); const viewScrollbar = CustomScrollbar({ contentEl: overviewInner, className: 'view-pane', }); let latestData = null; let isDirty = false; let countdownTickTimer = null; function stopCountdownTicker() { if (countdownTickTimer) { clearInterval(countdownTickTimer); countdownTickTimer = null; } } function ensureCountdownTicker() { if (getVisibleMonitorView() !== 'overview') { stopCountdownTicker(); return; } if (!countdownTickTimer) { countdownTickTimer = setInterval(() => { if (getVisibleMonitorView() === 'overview' && latestData) { renderData(latestData); } }, 30_000); } } function renderData(data) { if (!data) return; const moduleKeys = normalizeClientOverviewModules(data.settings?.overviewModules); const minuteTick = Math.floor(Date.now() / 30000); widgetHost.update({ moduleKeys, data, minuteTick, }); ensureCountdownTicker(); viewScrollbar.refresh(); } const unsubTelemetry = telemetryStore.subscribe( (st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }), ({ telemetry: data }) => { latestData = data; if (getVisibleMonitorView() !== 'overview') { const stillRunning = (Array.isArray(data?.runningConversations) && data.runningConversations.length > 0) || Boolean( data?.activeConversation?.isRunning || data?.activeConversation?.aggregated?.isRunning ); if (!stillRunning) { widgetHost.pauseTickers(); } isDirty = true; return; } isDirty = false; renderData(data); } ); let prevCtxTarget = uiStore.getState().ctxInspectorAgentId; const unsubView = uiStore.subscribe( (st) => ({ activeView: getVisibleMonitorView(st), ctxInspectorAgentId: st.ctxInspectorAgentId, }), (slice) => { const scopeChanged = slice.ctxInspectorAgentId !== prevCtxTarget; prevCtxTarget = slice.ctxInspectorAgentId; if (slice.activeView !== 'overview') { widgetHost.pauseTickers(); stopCountdownTicker(); if (scopeChanged) isDirty = true; return; } ensureCountdownTicker(); if ((isDirty || scopeChanged) && latestData) { isDirty = false; renderData(latestData); } else { widgetHost.resumeTickers(); } } ); const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { if (getVisibleMonitorView() !== 'overview') { isDirty = true; // Refresh initial skeleton labels even before telemetry arrives if (!latestData) { widgetHost.update({ moduleKeys: DEFAULT_CLIENT_OVERVIEW_MODULES, data: null, }); } return; } if (latestData) { renderData(latestData); } else { widgetHost.update({ moduleKeys: DEFAULT_CLIENT_OVERVIEW_MODULES, data: null, }); } } ); onCleanup(() => { stopCountdownTicker(); unsubTelemetry(); unsubView(); unsubI18n(); widgetHost.destroy(); viewScrollbar.destroy(); }); return { el: viewScrollbar.el, refs: { viewScrollbar, widgetHost }, }; }, }); return { LiveOverviewView }; })(); // --- src/views/ConsumptionView.js --- const { ConsumptionView } = (() => { /** * @fileoverview View 2: ConsumptionView (全景消耗统计视图). * 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗: * 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+3 组合矩阵展示总 Token/调用次数、 * USD/CNY 预估费用、缓存命中率与命中量、新输入/缓存读取(含节省费用)/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。 * 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡、对齐多刻度时间轴与悬停详情浮层。 * 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。 * 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。 * 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。 */ /** 消耗统计顶栏支持的时间范围预设项 */ 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') }, { value: '14d', label: t('cons.range14d') }, { value: '30d', label: t('cons.range30d') }, { value: 'all', label: t('cons.rangeAll') }, { value: 'custom', label: t('cons.rangeCustom') }, ]; } /** 热力图顶栏支持的四档聚合视图选项 */ function getHeatmapModeOptions() { return [ { value: 'day', label: t('cons.hmModeDay') }, { value: 'week', label: t('cons.hmModeWeek') }, { value: 'month', label: t('cons.hmModeMonth') }, { value: 'all', label: t('cons.hmModeAll') }, ]; } function floorToStartOfMinuteMs(ms) { const n = Number(ms); if (!(n > 0)) return 0; const d = new Date(n); d.setSeconds(0, 0); return d.getTime(); } function ceilToEndOfMinuteMs(ms) { const n = Number(ms); if (!(n > 0)) return 0; const d = new Date(n); d.setSeconds(59, 999); return d.getTime(); } function formatCyclePoolShortLabel(poolKey, poolLabel) { if (poolKey === 'Argon') return 'Argon'; if (poolKey === 'Carbon') return 'Carbon'; if (poolKey === 'Claude & GPT') return 'Claude/GPT'; return poolLabel || poolKey; } function buildCyclePoolSelectOptions(pools, isCustomWeeklyMode = false) { const list = Array.isArray(pools) ? pools : []; let sumCycleCost = 0; let hasAnyCycleCost = false; for (let i = 0; i < list.length; i++) { const c = Number(list[i]?.cycleWeekly?.costUsd); if (Number.isFinite(c) && c >= 0 && list[i]?.cycleWeekly) { sumCycleCost += c; hasAnyCycleCost = true; } } const allLabel = t('cons.cyclePoolAll'); const opts = [ { value: 'all', label: allLabel, shortLabel: t('cons.cyclePoolAllShort'), meta: !isCustomWeeklyMode && hasAnyCycleCost ? formatUsd(sumCycleCost) : '', title: allLabel, }, ]; for (let i = 0; i < list.length; i++) { const p = list[i]; const key = String(p?.poolKey || p?.family || '').trim(); if (!key || key === 'Unknown') continue; const label = String(p?.poolLabel || key).trim(); const shortLabel = formatCyclePoolShortLabel(key, label); const metaParts = []; if ( !isCustomWeeklyMode && p?.weeklyRemainingPct != null && Number.isFinite(Number(p.weeklyRemainingPct)) ) { metaParts.push( t('cons.cyclePoolRemMeta', { pct: formatPctNumber(p.weeklyRemainingPct, { withSymbol: true }), }) ); } if (!isCustomWeeklyMode && p?.cycleWeekly && Number.isFinite(Number(p.cycleWeekly.costUsd))) { metaParts.push(formatUsd(p.cycleWeekly.costUsd)); } const meta = metaParts.join(' · '); opts.push({ value: key, label, shortLabel, meta, title: meta ? `${label} (${meta})` : label, }); } return opts; } function formatCycleMinuteSpanTip(startMs, endMs, isFallbackWeek = false) { const s = Number(startMs); const e = Number(endMs); if (!(s > 0 && e > 0 && Number.isFinite(s) && Number.isFinite(e))) return null; const sd = new Date(s); const ed = new Date(e); const pad2 = (n) => String(n).padStart(2, '0'); const sTime = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; const eTime = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; const sameDay = sd.getFullYear() === ed.getFullYear() && sd.getMonth() === ed.getMonth() && sd.getDate() === ed.getDate(); const sDate = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; const eDate = `${ed.getMonth() + 1}/${pad2(ed.getDate())}`; const base = sameDay ? `${sDate} ${sTime} ~ ${eTime}` : `${sDate} ${sTime} ~ ${eDate} ${eTime}`; return isFallbackWeek ? `${base} · ${t('cons.cycleFallbackWeekTip')}` : base; } const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { // --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 --- let draftStartMs = telemetryStore.getState().customStartMs; let draftEndMs = telemetryStore.getState().customEndMs; let hasUncommittedCustomDraft = false; let hasCommittedCustomRange = false; const timeFilterSwitch = SegmentedControl({ ariaLabel: t('cons.rangeAria'), modelValue: telemetryStore.getState().selectedTimeRange, options: getConsumptionTimeRangeOptions(), onUpdateModelValue: (nextRange) => { if (nextRange === 'custom') { const st = telemetryStore.getState(); if (!hasCommittedCustomRange && st.selectedTimeRange !== 'custom') { const nowMs = Date.now(); draftStartMs = floorToStartOfMinuteMs(nowMs - 24 * 3600 * 1000); draftEndMs = ceilToEndOfMinuteMs(nowMs); hasUncommittedCustomDraft = false; startPicker.setValue(draftStartMs); endPicker.setValue(draftEndMs); selectConsumptionTimeRange('custom', { customStartMs: draftStartMs, customEndMs: draftEndMs, }); return; } draftStartMs = st.customStartMs; draftEndMs = st.customEndMs; hasUncommittedCustomDraft = false; startPicker.setValue(draftStartMs); endPicker.setValue(draftEndMs); } else { hasUncommittedCustomDraft = false; } selectConsumptionTimeRange(nextRange); }, }); const startPicker = CustomDateTimePicker({ modelValue: draftStartMs, onUpdateModelValue: (ms) => { draftStartMs = ms; hasUncommittedCustomDraft = true; startPicker.setValue(ms); }, }); const endPicker = CustomDateTimePicker({ modelValue: draftEndMs, onUpdateModelValue: (ms) => { draftEndMs = ms; hasUncommittedCustomDraft = true; endPicker.setValue(ms); }, }); const applyCustomBtnLabel = h('span', { text: t('cons.applyFilter') }); const applyCustomBtn = h( 'button', { type: 'button', className: 'btn-primary', style: 'height: 26px; padding: 0 10px;', onClick: () => { const sMs = Number(draftStartMs || 0); const eMs = Number(draftEndMs || 0); const rawMinMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; const rawMaxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; const minMs = floorToStartOfMinuteMs(rawMinMs); const maxMs = ceilToEndOfMinuteMs(rawMaxMs); draftStartMs = minMs; draftEndMs = maxMs; hasUncommittedCustomDraft = false; hasCommittedCustomRange = true; startPicker.setValue(minMs); endPicker.setValue(maxMs); selectConsumptionTimeRange('custom', { customStartMs: minMs, customEndMs: maxMs, }); }, }, [createSvgIcon('check', { size: 12 }), applyCustomBtnLabel] ); const rangeToSpan = h('span', { className: 'text-muted', text: t('cons.rangeTo') }); const customRangeBar = h( 'div', { className: 'cons-custom-range-bar', hidden: true, }, [ startPicker.el, rangeToSpan, endPicker.el, applyCustomBtn, ] ); // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); const cyclePoolSelect = CustomSelect({ className: 'cons-cycle-pool-select', modelValue: telemetryStore.getState().selectedCyclePool || 'all', options: buildCyclePoolSelectOptions([]), onUpdateModelValue: (nextPool) => { selectConsumptionCyclePool(nextPool || 'all'); }, }); patchAttr(cyclePoolSelect.el, 'hidden', true); patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) }); const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: '≈ ¥0' }); const cacheHitPctEl = h('strong', { className: 'cons-hero-cache text-mono', text: '0%' }); const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.cacheHitTokens', { tokens: 0 }) }); const inputSharePct = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: '0%' }); const inputMainTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const cacheSharePct = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: '0%' }); const cacheMainTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const outputSharePct = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: '0%' }); const outputMainTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const overviewSegBar = createFourSegmentBar(); const consExportMenu = ActionMenu({ ariaLabel: t('cons.exportMenuAria'), className: 'cons-export-menu', items: [ { key: 'xlsx', icon: 'download', label: t('cons.exportXlsx'), title: t('cons.exportXlsxTip'), onSelect: () => { const cons = latestSlice?.consumption; if (!cons) return; const displaySettings = { modelDisplayMode: latestSlice?.modelDisplayMode, showUpstreamModel: latestSlice?.showUpstreamModel, orchestratorIdMode: latestSlice?.orchestratorIdMode, }; const bytes = buildConsumptionXlsx(cons, latestSlice?.modelBreakdown || [], { displaySettings, }); const baseName = buildConsumptionExportBaseName( cons, latestSlice?.range || 'all' ); void exportBinaryFileWithFeedback( sanitizeExportFilename(baseName, 'xlsx'), bytes ); }, }, { key: 'md', icon: 'copy', label: t('cons.exportMd'), title: t('cons.exportMdTip'), onSelect: () => { const cons = latestSlice?.consumption; if (!cons) return; const displaySettings = { modelDisplayMode: latestSlice?.modelDisplayMode, showUpstreamModel: latestSlice?.showUpstreamModel, orchestratorIdMode: latestSlice?.orchestratorIdMode, }; const md = buildConsumptionMarkdownReport(cons, latestSlice?.modelBreakdown || [], { displaySettings, }); void copyTextWithFeedback(md, t('cons.exportMdDone')); }, }, ], }); consExportMenu.refs.setHidden(true); const totalTokensLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.totalTokens') }); const estCostLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.estCost') }); const cacheHitRateLabel = h('span', { text: t('cons.cacheHitRate') }); const newInputLabel = h('span', { text: t('cons.newInput') }); const cacheReadLabel = h('span', { text: t('cons.cacheRead') }); const outputUsageLabel = h('span', { text: t('cons.outputUsage') }); const unifiedMatrixEl = h('div', { className: 'cons-box cons-unified-matrix' }, [ h('div', { className: 'cons-split-3' }, [ h('div', { className: 'cons-col' }, [ totalTokensLabel, h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), ]), h('div', { className: 'cons-col is-bordered-col' }, [ estCostLabel, h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), ]), h('div', { className: 'cons-col is-bordered-col' }, [ h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [ h('span', { className: 'dot-swatch seg-cached' }), cacheHitRateLabel, ]), h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), ]), ]), h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ h('div', { className: 'cons-col' }, [ h('span', { className: 'legend-left text-muted', style: 'font-size: var(--fs-md);' }, [ h('span', { className: 'dot-swatch seg-input' }), newInputLabel, ]), h('div', { className: 'cons-baseline' }, [inputMainTokens, inputSharePct]), ]), h('div', { className: 'cons-col is-bordered-col' }, [ h('span', { className: 'legend-left text-muted', style: 'font-size: var(--fs-md);' }, [ h('span', { className: 'dot-swatch seg-cached' }), cacheReadLabel, ]), h('div', { className: 'cons-baseline' }, [cacheMainTokens, cacheSharePct]), ]), h('div', { className: 'cons-col is-bordered-col' }, [ h('span', { className: 'legend-left text-muted', style: 'font-size: var(--fs-md);' }, [ h('span', { className: 'dot-swatch seg-output' }), outputUsageLabel, ]), h('div', { className: 'cons-baseline' }, [outputMainTokens, outputSharePct]), ]), ]), ]); const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ h('span', { className: 'panel-title cons-overview-title' }, [ dateSpanBadge, cyclePoolSelect.el, ]), h('div', { className: 'cons-overview-controls' }, [ timeFilterSwitch.el, consExportMenu.el, ]), ]), customRangeBar, unifiedMatrixEl, overviewSegBar.el, ]); function drillDownToTimeRange(startMs, endMs) { const minMs = floorToStartOfMinuteMs(startMs); const maxMs = ceilToEndOfMinuteMs(endMs); if (!(minMs > 0) || !(maxMs > minMs)) return; hideBreakdownPopover(); draftStartMs = minMs; draftEndMs = maxMs; hasUncommittedCustomDraft = false; hasCommittedCustomRange = true; startPicker.setValue(minMs); endPicker.setValue(maxMs); selectConsumptionTimeRange('custom', { customStartMs: minMs, customEndMs: maxMs, }); } // --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 / 7×W 四态热力格子图 + 悬停明细浮层 + 点击时段下钻) --- let heatmapViewMode = 'day'; const trendTitleSpan = h('span', { text: t('cons.trendTitle') }); const trendRangeBadge = h('span', { className: 'cons-badge', text: t('cons.allTime') }); const trendGranularityHint = h('span', { className: 'cons-trend-hint text-muted text-mono', style: 'font-size: var(--fs-sm);', text: t('cons.trendPointsHintHourly', { points: 0 }), }); const heatmapModeSwitch = SegmentedControl({ ariaLabel: t('cons.hmModeAria'), modelValue: heatmapViewMode, options: getHeatmapModeOptions(), onUpdateModelValue: (nextMode) => { if (!['day', 'week', 'month', 'all'].includes(nextMode)) return; heatmapViewMode = nextMode; heatmapModeSwitch.setValue(nextMode); trendChart.setHeatmapMode(nextMode); }, }); heatmapModeSwitch.el.classList.add('cons-hm-mode-switch'); patchAttr(heatmapModeSwitch.el, 'hidden', true); const trendChart = createTrendAreaChart({ onSelectSlot: (slot) => { if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) { drillDownToTimeRange(slot.startMs, slot.endMs); } }, }); const trendPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-trend-head' }, [ h('span', { className: 'panel-title' }, [ trendTitleSpan, trendRangeBadge, ]), h('div', { className: 'cons-trend-head-right' }, [ trendGranularityHint, heatmapModeSwitch.el, ]), ]), trendChart.el, ]); // --- Section 3: 统一排行卡片(分段切换「模型排行 | 项目排行 | 会话排行」,右侧联动对应排序切换) --- let activeRankingTab = 'models'; let modelsSortBy = 'tokens'; let topConvsSortBy = 'cost'; let lastModelsCount = 0; let lastWorkspacesCount = 0; let lastConvsCount = 0; let hasCompletedInitialDraw = false; let lastAnimatedRangeSig = ''; let lastAnimatedRankingKey = ''; let lastAnimatedSortSig = ''; const consAnimTimers = new Map(); const TRANSIENT_CONS_CLASSES = ['is-bars-revealing']; function cleanupConsAnim(el) { const rec = consAnimTimers.get(el); if (!rec) return; clearTimeout(rec.tid); el?.removeEventListener?.('animationend', rec.onEnd); el?.classList?.remove(...TRANSIENT_CONS_CLASSES); consAnimTimers.delete(el); } function triggerConsAnim(el, cls, fallbackMs = 650) { if ( !el || !el.classList || typeof window === 'undefined' || typeof window.getComputedStyle !== 'function' || window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ) { return; } cleanupConsAnim(el); el.classList.remove(...TRANSIENT_CONS_CLASSES); void el.offsetWidth; const onEnd = (ev) => { if (ev && ev.target && ev.target !== el) return; cleanupConsAnim(el); }; const tid = setTimeout(() => cleanupConsAnim(el), fallbackMs); consAnimTimers.set(el, { cls, tid, onEnd }); el.addEventListener?.('animationend', onEnd); el.classList.add(cls); } function clearConsAnimTimers() { for (const el of Array.from(consAnimTimers.keys())) { cleanupConsAnim(el); } } function getRankingTabOptions( modelsCount = lastModelsCount, convsCount = lastConvsCount, workspacesCount = lastWorkspacesCount ) { const opts = [ { value: 'models', label: modelsCount > 0 ? t('cons.rankTabModelsCount', { count: modelsCount }) : t('cons.topModels'), }, ]; if (workspacesCount > 0) { opts.push({ value: 'workspaces', label: t('cons.rankTabWorkspacesCount', { count: workspacesCount }), }); } opts.push({ value: 'sessions', label: convsCount > 0 ? t('cons.rankTabSessionsCount', { count: convsCount }) : t('cons.rankTabSessions'), }); return opts; } function getModelsSortOptions() { return [ { value: 'tokens', label: t('cons.modelsSortTokens') }, { value: 'cost', label: t('cons.modelsSortCost') }, { value: 'speed', label: t('cons.modelsSortSpeed') }, { value: 'calls', label: t('cons.modelsSortCalls') }, ]; } function getTopConvsSortOptions() { return [ { value: 'cost', label: t('cons.topConvsSortCost') }, { value: 'tokens', label: t('cons.topConvsSortTokens') }, ]; } const rankingTabSwitch = SegmentedControl({ ariaLabel: t('cons.rankTabAria'), modelValue: activeRankingTab, options: getRankingTabOptions(0, 0, 0), onUpdateModelValue: (nextTab) => { if (nextTab !== 'models' && nextTab !== 'sessions' && nextTab !== 'workspaces') return; activeRankingTab = nextTab; rankingTabSwitch.setValue(nextTab); if (latestSlice) { renderConsumptionData(latestSlice); } }, }); const modelsSortSwitch = SegmentedControl({ ariaLabel: t('cons.modelsSortAria'), modelValue: modelsSortBy, options: getModelsSortOptions(), onUpdateModelValue: (nextSort) => { if (!['tokens', 'cost', 'speed', 'calls'].includes(nextSort)) return; modelsSortBy = nextSort; modelsSortSwitch.setValue(nextSort); if (latestSlice) { renderConsumptionData(latestSlice); } }, }); const topConvsSortSwitch = SegmentedControl({ ariaLabel: t('cons.topConvsSortAria'), modelValue: topConvsSortBy, options: getTopConvsSortOptions(), onUpdateModelValue: (nextSort) => { if (nextSort !== 'cost' && nextSort !== 'tokens') return; topConvsSortBy = nextSort; topConvsSortSwitch.setValue(nextSort); if (latestSlice) { renderConsumptionData(latestSlice); } }, }); patchAttr(topConvsSortSwitch.el, 'hidden', true); const rankingSortWrap = h('div', { className: 'cons-ranking-sort-wrap' }, [ modelsSortSwitch.el, topConvsSortSwitch.el, ]); const modelsListEl = h('div', { className: 'cons-item-list' }); const topConvsListEl = h('div', { className: 'cons-item-list', hidden: true }); const workspacesListEl = h('div', { className: 'cons-item-list', hidden: true }); const topConvsEmptyEl = h('div', { className: 'cons-ranking-empty text-muted', hidden: true, text: t('cons.topConvsEmpty'), }); const rankingPanel = h('section', { className: 'panel cons-ranking-panel' }, [ h('div', { className: 'panel-header cons-ranking-head' }, [ rankingTabSwitch.el, rankingSortWrap, ]), modelsListEl, topConvsListEl, workspacesListEl, topConvsEmptyEl, ]); // --- Section 4: 客户端来源列表 --- const sourcesTitleSpan = h('span', { className: 'panel-title', text: t('cons.clientSources') }); const sourcesHoverHint = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-sm);', text: t('cons.hoverModelsHint'), }); const sourcesListEl = h('div', { className: 'cons-item-list' }); const sourcesPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ sourcesTitleSpan, sourcesHoverHint, ]), sourcesListEl, ]); // --- Section 5: 按月细分 (12 个月垂直按模型配色堆叠柱状图 + 悬停明细浮层) --- const monthlyTitleSpan = h('span', { text: t('cons.monthlyTitle') }); const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' }); const monthlyHoverHint = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-sm);', text: t('cons.hoverModelsHint'), }); let activeHoverTargetEl = null; let activeHoverPayload = null; let cachedBreakdownRootRect = null; let cachedBreakdownAnchorRect = null; const popoverContent = createConsumptionBreakdownContent({ showModelDot: true, monoTitle: false, }); const breakdownPopoverEl = h( 'div', { className: 'cons-breakdown-popover is-rich-breakdown', hidden: true }, popoverContent.children ); function hideBreakdownPopover() { cachedBreakdownRootRect = null; cachedBreakdownAnchorRect = null; activeHoverPayload = null; if (activeHoverTargetEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); activeHoverTargetEl = null; } patchAttr(breakdownPopoverEl, 'hidden', true); patchClasses(breakdownPopoverEl, { 'is-tracking': false }); } function positionBreakdownPopover(anchorEl, pointerClientX = null, pointerClientY = null) { if (!cachedBreakdownRootRect) { cachedBreakdownRootRect = rootEl.getBoundingClientRect?.() || { left: 0, top: 0, width: 360, height: 600, }; } const rootRect = cachedBreakdownRootRect; if (!cachedBreakdownAnchorRect) { cachedBreakdownAnchorRect = anchorEl?.getBoundingClientRect?.() || { left: 0, top: 0, bottom: 0, width: 0, height: 0, }; } const anchorRect = cachedBreakdownAnchorRect; const tipW = Number(breakdownPopoverEl.offsetWidth || 0) || 216; const tipH = Number(breakdownPopoverEl.offsetHeight || 0) || 108; const rootW = rootRect.width > 0 ? rootRect.width : 360; const rootH = rootRect.height > 0 ? rootRect.height : 600; const hasPointerX = Number.isFinite(pointerClientX) && pointerClientX > 0 && rootRect.width > 0; const hasPointerY = Number.isFinite(pointerClientY) && pointerClientY > 0 && rootRect.height > 0; const centerX = hasPointerX ? pointerClientX - rootRect.left : anchorRect.left - rootRect.left + anchorRect.width / 2; const anchorY = hasPointerY ? pointerClientY - rootRect.top : anchorRect.top - rootRect.top; const maxLeft = Math.max(8, rootW - tipW - 8); let leftPx = Math.max(8, Math.min(maxLeft, centerX - tipW / 2)); const aboveTop = anchorY - tipH - (hasPointerY ? 14 : 8); const belowTop = hasPointerY ? anchorY + 18 : anchorRect.bottom - rootRect.top + 8; let topPx; if (aboveTop >= 6) { topPx = Math.min(Math.max(6, rootH - tipH - 6), aboveTop); } else if (hasPointerX && centerX + 16 + tipW <= rootW - 8) { leftPx = centerX + 16; topPx = Math.max(6, Math.min(Math.max(6, rootH - tipH - 6), anchorY - tipH / 2)); } else if (hasPointerX && centerX - 16 - tipW >= 8) { leftPx = centerX - 16 - tipW; topPx = Math.max(6, Math.min(Math.max(6, rootH - tipH - 6), anchorY - tipH / 2)); } else { topPx = Math.min(Math.max(6, rootH - tipH - 6), Math.max(6, belowTop)); } patchStyleVar(breakdownPopoverEl, '--pop-x', `${Math.round(leftPx)}px`); patchStyleVar(breakdownPopoverEl, '--pop-y', `${Math.round(topPx)}px`); } function showBreakdownPopover( anchorEl, payload, pointerClientX = null, pointerClientY = null ) { if (!payload || !(payload.totalTokens > 0 || payload.calls > 0)) { hideBreakdownPopover(); return; } const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); const sameTargetAndPayload = !wasHidden && activeHoverTargetEl === anchorEl && activeHoverPayload === payload; if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); cachedBreakdownAnchorRect = null; } else if (!activeHoverTargetEl) { cachedBreakdownRootRect = null; cachedBreakdownAnchorRect = null; } activeHoverTargetEl = anchorEl; activeHoverPayload = payload; patchClasses(anchorEl, { 'is-hovered': true }); if (!sameTargetAndPayload) { popoverContent.update({ title: payload.title || '—', calls: payload.calls || 0, totalTokens: payload.totalTokens || 0, costText: payload.costText || '$0.00', inputTokens: payload.inputTokens, cacheReadTokens: payload.cacheReadTokens, thinkingTokens: payload.thinkingTokens, responseTokens: payload.responseTokens, outputTokens: payload.outputTokens, segments: Array.isArray(payload.segments) ? payload.segments : [], }); } patchAttr(breakdownPopoverEl, 'hidden', false); positionBreakdownPopover(anchorEl, pointerClientX, pointerClientY); 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() { const segEl = h('div', { className: 'month-seg cons-model-seg' }); return { el: segEl, refs: { segEl } }; } let monthlyGridEl = null; const monthlyColByEl = new Map(); function findMonthlyColForNode(node) { let cur = node; while (cur && cur !== monthlyGridEl) { const hit = monthlyColByEl.get(cur); if (hit) return hit; cur = cur.parentNode || null; } return null; } const monthlyCols = Array.from({ length: 12 }, (_, idx) => { const costText = h('span', { className: 'month-cost text-mono', text: '' }); const stackWrap = h('div', { className: 'month-stack' }); const zeroDot = h('span', { className: 'month-zero-dot' }); const monthLabel = h('span', { className: 'month-label', text: t('cons.monthLabel', { m: idx + 1 }) }); const tokText = h('span', { className: 'month-tok text-mono', text: '' }); const colState = { hoverPayload: null, monthRange: null }; const colEl = h( 'div', { className: 'month-col', onClick: () => { if (colState.monthRange) { drillDownToTimeRange(colState.monthRange.startMs, colState.monthRange.endMs); } }, onMouseEnter: (e) => { if (colState.hoverPayload) { showBreakdownPopover( colEl, colState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null ); } else { if (activeHoverTargetEl && monthlyColByEl.has(activeHoverTargetEl)) { hideBreakdownPopover(); } e?.stopPropagation?.(); } }, onMouseMove: (e) => { if (colState.hoverPayload && activeHoverTargetEl === colEl) { positionBreakdownPopover(colEl, e?.clientX ?? null, e?.clientY ?? null); } }, onMouseLeave: (e) => { if (activeHoverTargetEl !== colEl) return; const nextEl = e?.relatedTarget || null; if (nextEl) { const nextCol = findMonthlyColForNode(nextEl); if ((nextCol && nextCol.colState.hoverPayload) || nextEl === monthlyGridEl) { return; } } hideBreakdownPopover(); }, }, [ costText, h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), monthLabel, tokText, ] ); const colRec = { el: colEl, costText, stackWrap, zeroDot, monthLabel, tokText, colState, }; monthlyColByEl.set(colEl, colRec); return colRec; }); monthlyGridEl = h( 'div', { className: 'monthly-grid', onMouseLeave: () => { if (activeHoverTargetEl && monthlyColByEl.has(activeHoverTargetEl)) { hideBreakdownPopover(); } }, }, monthlyCols.map((c) => c.el) ); const monthlyPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ monthlyTitleSpan, monthlyYearBadge, ]), monthlyHoverHint, ]), monthlyGridEl, ]); const scrollInner = h( 'div', { style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: var(--space-3);', }, [ overviewPanel, trendPanel, rankingPanel, sourcesPanel, monthlyPanel, ] ); const viewScrollbar = CustomScrollbar({ contentEl: scrollInner, className: 'view-pane', }); viewScrollbar.el.addEventListener?.('scroll', hideBreakdownPopover, { passive: true }); const rootEl = h('div', { className: 'cons-view-stage' }, [ viewScrollbar.el, breakdownPopoverEl, ]); const { createSourceBreakdownRow, updateSourceBreakdownRow, createTopConversationRow, updateTopConversationRow, } = createConsumptionBreakdownRowBuilders({ showPopover: showBreakdownPopover, movePopover: positionBreakdownPopover, hidePopover: hideBreakdownPopover, isHoveredTarget: (targetEl) => activeHoverTargetEl === targetEl, onSelectConversation: (cascadeId) => { selectConversation(cascadeId); uiStore.setState({ activeView: 'steps', stepsSubTab: 'steps', selectedAgentScope: 'all', ctxInspectorAgentId: getDefaultCtxInspectorAgentId( telemetryStore.getState().telemetry?.settings ), }); }, }); let latestSlice = null; let isDirty = false; let prefetchedOnCurrentVisit = false; let lastRenderedTuple = null; let cachedMonthlySeriesRef = null; let cachedMonthlyDisplayKey = ''; let cachedMonthsMergedModels = null; let cachedAllMonthMergedModels = null; function isSameRenderTuple(prev, next) { if (!prev || prev.length !== next.length) return false; for (let i = 0; i < prev.length; i++) { if (!Object.is(prev[i], next[i])) return false; } return true; } /** * 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。 */ function renderConsumptionData(slice) { if (!slice) return; const cons = slice.consumption || {}; const rangeInfo = cons.selectedRange || {}; // 始终在 0ms 同步顶部时间段滑块、周期池选择器及自定义日期条显隐,给予即刻交互反馈 timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); if (!hasUncommittedCustomDraft) { draftStartMs = slice.customStartMs; draftEndMs = slice.customEndMs; startPicker.setValue(draftStartMs); endPicker.setValue(draftEndMs); } const isCustomWeeklyMode = slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost'; const cyclePoolOptions = slice.range === 'cycle' ? buildCyclePoolSelectOptions(slice.quotaPools, isCustomWeeklyMode) : []; const activePoolFilter = slice.range === 'cycle' ? slice.cyclePool || 'all' : 'all'; const showCyclePoolSelect = slice.range === 'cycle' && cyclePoolOptions.length > 2; if (!showCyclePoolSelect) { cyclePoolSelect.close?.(); patchAttr(cyclePoolSelect.el, 'hidden', true); } else { cyclePoolSelect.setProps({ modelValue: activePoolFilter, options: cyclePoolOptions, }); patchAttr(cyclePoolSelect.el, 'hidden', false); } // 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制 const payloadPool = rangeInfo.key === 'cycle' ? rangeInfo.pool || 'all' : 'all'; if ( (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) || (slice.range === 'cycle' && rangeInfo.pool && payloadPool !== activePoolFilter) ) { return; } const preset = slice.range !== 'custom' && !(slice.range === 'cycle' && activePoolFilter !== 'all') && cons.presets?.[slice.range] ? cons.presets[slice.range] : null; const acct = cons.account || preset?.account || {}; const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); const cycleOptionsSig = showCyclePoolSelect ? cyclePoolOptions.map((o) => `${o.value}:${o.label}:${o.meta || ''}`).join('|') : ''; const now = new Date(); const currentMonthIdx = now.getMonth(); const monthlyYear = cons.monthlyYear || now.getFullYear(); const locale = i18nStore.getState().locale; const renderTuple = [ locale, slice.range, activePoolFilter, cycleOptionsSig, Boolean(rangeInfo.isFallbackWeek), slice.customStartMs, slice.customEndMs, slice.modelDisplayMode, slice.showUpstreamModel, slice.orchestratorIdMode, dateSpan, preset?.label || rangeInfo.label, acct, cons.trendSeries, slice.modelBreakdown, activeRankingTab, modelsSortBy, cons.topConversations, topConvsSortBy, cons.sourcesBreakdown, monthlyYear, currentMonthIdx, cons.monthlySeries, ]; if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; drawConsumptionData(slice, { cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear, }); lastRenderedTuple = renderTuple; } function drawConsumptionData( slice, { cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear } ) { // 1. 同步用量概览矩阵及顶部 4 段比例条 patchText(dateSpanBadge, dateSpan); patchAttr( dateSpanBadge, 'title', slice.range === 'cycle' ? formatCycleMinuteSpanTip( rangeInfo.startMs, rangeInfo.endMs, Boolean(rangeInfo.isFallbackWeek) ) : null ); const totalTokens = Number(acct.totalTokens || 0); const inputTokens = Number(acct.inputTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0); const outputTokens = Number(acct.outputTokens || 0); const responseTokens = Number(acct.responseTokens || 0); const thinkingTokens = Number(acct.thinkingTokens || 0); const costUsd = Number(acct.costUsd || 0); patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); patchText(heroTotalCalls, t('cons.callsCount', { calls: acct.calls || 0 })); patchText(heroCostUsd, formatUsd(costUsd)); patchText(heroCostCny, formatCnyApprox(costUsd)); patchText(cacheHitPctEl, formatPctNumber(acct.cacheHitPct ?? 0, { withSymbol: true })); patchText(cacheTokensEl, t('cons.cacheHitTokens', { tokens: formatTokensPrecise(cacheTokens) })); let inPct = 0; let cachePct = 0; let outPct = 0; if (totalTokens > 0) { const scaled = scaleBucketsExact( { in: inputTokens, cache: cacheTokens, out: outputTokens }, ['in', 'cache', 'out'], 1000 ); inPct = +(scaled.in / 10).toFixed(1); cachePct = +(scaled.cache / 10).toFixed(1); outPct = +(scaled.out / 10).toFixed(1); } patchText(inputSharePct, `${inPct}%`); patchText(inputMainTokens, formatTokensPrecise(inputTokens)); patchText(cacheSharePct, `${cachePct}%`); patchText(cacheMainTokens, formatTokensPrecise(cacheTokens)); patchText(outputSharePct, `${outPct}%`); patchText(outputMainTokens, formatTokensPrecise(outputTokens)); consExportMenu.refs.setHidden(!(totalTokens > 0 || Number(acct.calls || 0) > 0)); overviewSegBar.update({ inputTokens, cacheReadTokens: cacheTokens, responseTokens, thinkingTokens, }); // 2-5. 统一解析展示模式与全局确定性模型配色映射(确保趋势浮层、模型排行圆点、客户端来源条、月度堆叠柱四处完全同色) const localeSig = i18nStore.getState().locale; const displaySettings = { modelDisplayMode: normalizeModelDisplayMode( slice.modelDisplayMode, slice.showUpstreamModel ), showUpstreamModel: Boolean(slice.showUpstreamModel), orchestratorIdMode: slice.orchestratorIdMode, }; const mergeAndSortBucketModels = (rawList) => mergeModelsByDisplayName(rawList || [], displaySettings, { preferLabelInShort: true, }) .filter((m) => Number(m.totalTokens || 0) > 0 || Number(m.calls || 0) > 0) .sort( (a, b) => (b.totalTokens || 0) - (a.totalTokens || 0) || (b.calls || 0) - (a.calls || 0) ); const models = mergeModelsByDisplayName(slice.modelBreakdown || [], displaySettings, { preferLabelInShort: true, }).sort((a, b) => { if (modelsSortBy === 'cost') { return (b.costUsd || 0) - (a.costUsd || 0) || (b.totalTokens || 0) - (a.totalTokens || 0); } if (modelsSortBy === 'speed') { const sa = Number(a.avgTokPerSec) > 0 ? Number(a.avgTokPerSec) : -1; const sb = Number(b.avgTokPerSec) > 0 ? Number(b.avgTokPerSec) : -1; return sb - sa || (b.totalTokens || 0) - (a.totalTokens || 0); } if (modelsSortBy === 'calls') { return (b.calls || 0) - (a.calls || 0) || (b.totalTokens || 0) - (a.totalTokens || 0); } return (b.totalTokens || 0) - (a.totalTokens || 0) || (b.calls || 0) - (a.calls || 0); }); const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0); const modelsTotalCost = models.reduce((s, m) => s + Math.max(0, Number(m.costUsd || 0)), 0); const modelsTotalCalls = models.reduce((s, m) => s + Math.max(0, Number(m.calls || 0)), 0); const modelsMaxAvgTps = models.reduce((mx, m) => { const v = Number(m.avgTokPerSec || 0); return Number.isFinite(v) && v > mx ? v : mx; }, 0); const modelsTotalsCtx = { totalTokens: modelsTotalTok, totalCost: modelsTotalCost, totalCalls: modelsTotalCalls, maxAvgTps: modelsMaxAvgTps, }; const rawTopConvs = Array.isArray(cons.topConversations) ? cons.topConversations : []; const allTopConvMergedModels = []; const topConvsWithModels = rawTopConvs.map((c) => { const mergedModels = mergeAndSortBucketModels(c.models); for (const m of mergedModels) { allTopConvMergedModels.push(m); } return { ...c, mergedModels }; }); const rawTopWorkspaces = Array.isArray(cons.topWorkspaces) ? cons.topWorkspaces : []; const allWorkspaceMergedModels = []; const topWorkspacesWithModels = rawTopWorkspaces.map((w) => { const mergedModels = mergeAndSortBucketModels(w.models); for (const m of mergedModels) { allWorkspaceMergedModels.push(m); } return { ...w, isWorkspaceRow: true, mergedModels }; }); const rawSources = cons.sourcesBreakdown || []; const sourcesTotalTok = rawSources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); const allSourceMergedModels = []; const sourcesWithModels = rawSources.map((s) => { const mergedModels = mergeAndSortBucketModels(s.models); for (const m of mergedModels) { allSourceMergedModels.push(m); } return { ...s, mergedModels }; }); const monthlySeries = cons.monthlySeries || []; const monthlyDisplayKey = `${displaySettings.modelDisplayMode}|${displaySettings.showUpstreamModel ? 1 : 0}|${displaySettings.orchestratorIdMode}`; let monthsMergedModels; let allMonthMergedModels; if ( cachedMonthlySeriesRef === monthlySeries && cachedMonthlyDisplayKey === monthlyDisplayKey && cachedMonthsMergedModels && cachedAllMonthMergedModels ) { monthsMergedModels = cachedMonthsMergedModels; allMonthMergedModels = cachedAllMonthMergedModels; } else { allMonthMergedModels = []; monthsMergedModels = Array.from({ length: 12 }, (_, idx) => { const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models); for (const m of merged) { allMonthMergedModels.push(m); } return merged; }); cachedMonthlySeriesRef = monthlySeries; cachedMonthlyDisplayKey = monthlyDisplayKey; cachedMonthsMergedModels = monthsMergedModels; cachedAllMonthMergedModels = allMonthMergedModels; } const rawTrendSeries = cons.trendSeries || []; const allTrendMergedModels = []; const trendMergedByIdx = rawTrendSeries.map((slot) => { if (!Array.isArray(slot?.models) || slot.models.length === 0) return null; const merged = mergeAndSortBucketModels(slot.models); for (const m of merged) { allTrendMergedModels.push(m); } return merged; }); const modelColorMap = buildDeterministicModelColorMap([ ...models, ...allSourceMergedModels, ...allTopConvMergedModels, ...allWorkspaceMergedModels, ...allMonthMergedModels, ...allTrendMergedModels, ]); // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)及悬停分模型浮层 const rangeBadgeText = slice.range === 'cycle' ? `${rangeInfo.isFallbackWeek || slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost' ? t('cons.cycleFallbackWeek') : t('cons.currentCycle')}${ activePoolFilter && activePoolFilter !== 'all' ? ` · ${rangeInfo.poolLabel || activePoolFilter}` : '' }` : isEnglishLocale() ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || t('cons.allTime') : preset?.label || rangeInfo.label || t('cons.allTime'); patchText(trendRangeBadge, rangeBadgeText); const firstTrendSlot = rawTrendSeries[0] || null; const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; const isHourlyTrend = !isMinuteTrend && (firstTrendSlot?.granularity === 'hour' || (firstTrendSlot?.label || '').includes(':')); const isHeatmapTrend = !isMinuteTrend && !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; patchAttr(trendGranularityHint, 'hidden', isHeatmapTrend); patchAttr(heatmapModeSwitch.el, 'hidden', !isHeatmapTrend); if (!isHeatmapTrend) { patchText( trendGranularityHint, isMinuteTrend ? t('cons.trendPointsHintMinute', { minutes: Math.max(1, Number(firstTrendSlot?.stepMinutes) || 5), points: rawTrendSeries.length || 0, }) : isHourlyTrend ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) ); } else { heatmapModeSwitch.setValue(heatmapViewMode); } const buildTrendModelSegments = (mergedSlotModels) => partitionModelSegments(mergedSlotModels, modelColorMap, { maxMain: 5, minSharePct: 1.5, }); const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { const mergedSlotModels = trendMergedByIdx[idx]; if (!mergedSlotModels || mergedSlotModels.length === 0) return slot; return { ...slot, mergedModels: mergedSlotModels, modelSegments: buildTrendModelSegments(mergedSlotModels), }; }); trendChart.update(enrichedTrendSeries, { heatmapMode: heatmapViewMode, buildModelSegments: buildTrendModelSegments, }); // 3. 同步统一排行卡片(分段切换「模型排行 | 项目排行 | 会话排行」及对应排序控制) const sortedTopConvs = [...topConvsWithModels].sort((a, b) => topConvsSortBy === 'tokens' ? (b.totalTokens || 0) - (a.totalTokens || 0) || (b.costUsd || 0) - (a.costUsd || 0) : (b.costUsd || 0) - (a.costUsd || 0) || (b.totalTokens || 0) - (a.totalTokens || 0) ); const sortedTopWorkspaces = [...topWorkspacesWithModels].sort((a, b) => topConvsSortBy === 'tokens' ? (b.totalTokens || 0) - (a.totalTokens || 0) || (b.costUsd || 0) - (a.costUsd || 0) : (b.costUsd || 0) - (a.costUsd || 0) || (b.totalTokens || 0) - (a.totalTokens || 0) ); if (activeRankingTab === 'workspaces' && sortedTopWorkspaces.length === 0) { activeRankingTab = 'models'; } lastModelsCount = models.length; lastWorkspacesCount = sortedTopWorkspaces.length; lastConvsCount = sortedTopConvs.length; rankingTabSwitch.setProps({ ariaLabel: t('cons.rankTabAria'), modelValue: activeRankingTab, options: getRankingTabOptions( models.length, sortedTopConvs.length, sortedTopWorkspaces.length ), }); const showSessionsTab = activeRankingTab === 'sessions'; const showWorkspacesTab = activeRankingTab === 'workspaces' && sortedTopWorkspaces.length > 0; const showModelsTab = !showSessionsTab && !showWorkspacesTab; patchAttr(modelsSortSwitch.el, 'hidden', !showModelsTab); patchAttr( topConvsSortSwitch.el, 'hidden', showModelsTab || (showSessionsTab && sortedTopConvs.length === 0) || (showWorkspacesTab && sortedTopWorkspaces.length === 0) ); patchAttr(modelsListEl, 'hidden', !showModelsTab); patchAttr(topConvsListEl, 'hidden', !showSessionsTab || sortedTopConvs.length === 0); patchAttr(workspacesListEl, 'hidden', !showWorkspacesTab); patchAttr(topConvsEmptyEl, 'hidden', !showSessionsTab || sortedTopConvs.length > 0); patchText(topConvsEmptyEl, t('cons.topConvsEmpty')); const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; const nextRankingKey = showWorkspacesTab ? 'workspaces' : showSessionsTab ? 'sessions' : 'models'; const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`; const activeRankingEl = showWorkspacesTab ? workspacesListEl : showSessionsTab ? sortedTopConvs.length > 0 ? topConvsListEl : topConvsEmptyEl : modelsListEl; const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig; const tabSwitched = hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey; const sortSwitched = hasCompletedInitialDraw && !rangeSwitched && !tabSwitched && nextSortSig !== lastAnimatedSortSig; patchKeyedList(modelsListEl, models, { keyFn: (m) => m.displayText || m.label || m.shortName, sigFn: (m) => `${localeSig}:${modelsSortBy}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.inputTokens}:${m.cacheReadTokens}:${m.responseTokens}:${m.thinkingTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${m.avgTokPerSec ?? ''}:${m.avgTtftSec ?? ''}:${m.cacheHitPct ?? ''}:${modelsTotalTok}:${modelsTotalCost.toFixed(4)}:${modelsTotalCalls}:${modelsMaxAvgTps}`, createRow: createBreakdownItemRow, updateRow: (refs, m) => { updateBreakdownItemRow( refs, { ...m, label: m.displayText, title: m.displayTitle }, modelsTotalsCtx, modelsSortBy ); }, }); const topConvsBaseTokens = totalTokens > 0 ? totalTokens : sortedTopConvs.reduce((s, c) => s + Number(c.totalTokens || 0), 0); const topConvsBaseCost = costUsd > 0 ? costUsd : sortedTopConvs.reduce((s, c) => s + Math.max(0, Number(c.costUsd || 0)), 0); const topConvsBases = { tokens: topConvsBaseTokens, cost: topConvsBaseCost }; patchKeyedList(topConvsListEl, sortedTopConvs, { keyFn: (c) => c.cascadeId, sigFn: (c) => { const modelsSig = c.mergedModels .map((m) => { const seed = getCanonicalModelColorSeed(m); return `${m.displayText}:${m.totalTokens}:${m.inputTokens || 0}:${m.cacheReadTokens || 0}:${m.thinkingTokens || 0}:${m.responseTokens || 0}:${m.calls}:${modelColorMap.get(seed) || ''}`; }) .join('|'); return `${localeSig}:${topConvsSortBy}:${c.cascadeId}:${c.title}:${c.totalTokens}:${c.inputTokens || 0}:${c.cacheReadTokens || 0}:${c.thinkingTokens || 0}:${c.responseTokens || 0}:${c.costUsd}:${c.unpricedCalls}:${c.calls}:${c.cacheHitPct}:${c.sourceName}:${c.canJump ? 1 : 0}:${topConvsBaseTokens}:${topConvsBaseCost.toFixed(4)}:${modelsSig}`; }, createRow: createTopConversationRow, updateRow: (refs, c) => updateTopConversationRow(refs, c, topConvsBases, modelColorMap, topConvsSortBy), }); const topWsBaseTokens = totalTokens > 0 ? totalTokens : sortedTopWorkspaces.reduce((s, w) => s + Number(w.totalTokens || 0), 0); const topWsBaseCost = costUsd > 0 ? costUsd : sortedTopWorkspaces.reduce((s, w) => s + Math.max(0, Number(w.costUsd || 0)), 0); const topWsBases = { tokens: topWsBaseTokens, cost: topWsBaseCost }; patchKeyedList(workspacesListEl, sortedTopWorkspaces, { keyFn: (w) => w.workspaceKey, sigFn: (w) => { const modelsSig = w.mergedModels .map((m) => { const seed = getCanonicalModelColorSeed(m); return `${m.displayText}:${m.totalTokens}:${m.inputTokens || 0}:${m.cacheReadTokens || 0}:${m.thinkingTokens || 0}:${m.responseTokens || 0}:${m.calls}:${modelColorMap.get(seed) || ''}`; }) .join('|'); return `${localeSig}:${topConvsSortBy}:${w.workspaceKey}:${w.label}:${w.sessionCount}:${w.totalTokens}:${w.inputTokens || 0}:${w.cacheReadTokens || 0}:${w.thinkingTokens || 0}:${w.responseTokens || 0}:${w.costUsd}:${w.unpricedCalls}:${w.calls}:${w.cacheHitPct}:${w.latestCascadeId}:${w.canJump ? 1 : 0}:${topWsBaseTokens}:${topWsBaseCost.toFixed(4)}:${modelsSig}`; }, createRow: createTopConversationRow, updateRow: (refs, w) => updateTopConversationRow(refs, w, topWsBases, modelColorMap, topConvsSortBy), }); // 4. 同步客户端来源列表(长尾合并分段配色 + 右侧总调用数 + 悬停进度条弹出明细浮层) patchKeyedList(sourcesListEl, sourcesWithModels, { keyFn: (s) => s.name, sigFn: (s) => { const modelsSig = s.mergedModels .map((m) => { const seed = getCanonicalModelColorSeed(m); return `${m.displayText}:${m.totalTokens}:${m.inputTokens || 0}:${m.cacheReadTokens || 0}:${m.thinkingTokens || 0}:${m.responseTokens || 0}:${m.calls}:${modelColorMap.get(seed) || ''}`; }) .join('|'); return `${localeSig}:${s.name}:${s.totalTokens}:${s.inputTokens || 0}:${s.cacheReadTokens || 0}:${s.thinkingTokens || 0}:${s.responseTokens || 0}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}:${modelsSig}`; }, createRow: createSourceBreakdownRow, updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); if (tabSwitched || sortSwitched) { triggerConsAnim(activeRankingEl, 'is-bars-revealing'); } if (!hasCompletedInitialDraw) { hasCompletedInitialDraw = true; if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { window.requestAnimationFrame(() => { rootEl.classList?.add('is-ready'); }); } else { rootEl.classList?.add('is-ready'); } } lastAnimatedRangeSig = nextRangeSig; lastAnimatedRankingKey = nextRankingKey; lastAnimatedSortSig = nextSortSig; // 5. 同步 12 个月垂直堆叠柱状图(按模型配色堆叠 + 长尾合并 + 悬停弹出明细浮层) patchText(monthlyYearBadge, String(monthlyYear)); const maxMonthTokens = Math.max( 1, ...monthlySeries.map((m) => Number(m.totalTokens || 0)) ); for (let i = 0; i < 12; i++) { const col = monthlyCols[i]; const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0, calls: 0 }; const mTot = Number(m.totalTokens || 0); const mCalls = Number(m.calls || 0); const hasData = mTot > 0; patchClasses(col.el, { 'is-interactive': hasData || mCalls > 0 }); patchClasses(col.monthLabel, { 'is-current': i === currentMonthIdx }); patchAttr(col.stackWrap, 'hidden', !hasData); patchAttr(col.zeroDot, 'hidden', hasData); if (!hasData) { patchText(col.costText, ''); patchText(col.tokText, ''); col.colState.hoverPayload = null; col.colState.monthRange = null; patchKeyedList(col.stackWrap, [], { keyFn: (x) => x.key, sigFn: (x) => x.key, createRow: createMonthModelSegment, updateRow: () => {}, }); } else { const cVal = Number(m.costUsd || 0); const isMonthUnpriced = mCalls > 0 && Number(m.unpricedCalls || 0) >= mCalls && !(cVal > 0); patchText( col.costText, isMonthUnpriced ? '—' : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}` ); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); patchStyleVar(col.stackWrap, '--bar-h', `${totalHeightPct.toFixed(1)}%`); const monthModels = monthsMergedModels[i] || []; const barPartitioned = partitionModelSegments(monthModels, modelColorMap, { maxMain: 5, minSharePct: 1.5, }); // 垂直柱状图底端放主力模型、顶端叠放小占比及「其他」,视觉重心稳定 const verticalSegments = barPartitioned.length > 0 ? [...barPartitioned].reverse() : [{ key: '__month_fallback__', pct: 100, color: 'var(--accent-primary)' }]; patchKeyedList(col.stackWrap, verticalSegments, { keyFn: (seg) => seg.key, sigFn: (seg) => `${seg.key}:${seg.pct.toFixed(2)}:${seg.color}`, createRow: createMonthModelSegment, updateRow: (segRefs, seg) => { patchStyleVar(segRefs.segEl, '--seg-h', `${seg.pct.toFixed(2)}%`); patchStyleVar(segRefs.segEl, '--seg-color', seg.color); }, }); col.colState.monthRange = { startMs: new Date(monthlyYear, i, 1, 0, 0, 0, 0).getTime(), endMs: new Date(monthlyYear, i + 1, 0, 23, 59, 59, 999).getTime(), }; col.colState.hoverPayload = { title: t('cons.monthFullLabel', { year: monthlyYear, m: i + 1 }), calls: mCalls, totalTokens: mTot, costText: formatUsd(isMonthUnpriced ? null : cVal, { precise: cVal > 0 && cVal < 0.1, }), inputTokens: m.inputTokens, cacheReadTokens: m.cacheReadTokens, thinkingTokens: m.thinkingTokens, responseTokens: m.responseTokens, outputTokens: m.outputTokens, segments: barPartitioned, }; } } if (activeHoverTargetEl && activeHoverTargetEl.isConnected === false) { hideBreakdownPopover(); } viewScrollbar.refresh(); } const unsub = telemetryStore.subscribe( (st) => ({ range: st.selectedTimeRange, cyclePool: st.selectedCyclePool || 'all', customStartMs: st.customStartMs, customEndMs: st.customEndMs, quotaPools: st.telemetry?.quotas?.pools, weeklyLimitMode: st.telemetry?.settings?.weeklyLimitMode, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, modelDisplayMode: normalizeModelDisplayMode( st.telemetry?.settings?.modelDisplayMode, st.telemetry?.settings?.showUpstreamModel ), showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), orchestratorIdMode: normalizeOrchestratorIdDisplayMode( st.telemetry?.settings?.orchestratorIdMode ), }), (slice) => { latestSlice = slice; if (getVisibleMonitorView() !== 'consumption') { hideBreakdownPopover(); isDirty = true; return; } isDirty = false; renderConsumptionData(slice); if (!prefetchedOnCurrentVisit && Number(slice?.consumption?.revision || 0) > 0) { prefetchedOnCurrentVisit = true; void prefetchConsumptionPresets(); } } ); const unsubView = uiStore.subscribe( getVisibleMonitorView, (activeView) => { if (activeView !== 'consumption') { prefetchedOnCurrentVisit = false; hideBreakdownPopover(); return; } if (isDirty) { isDirty = false; if (latestSlice) { renderConsumptionData(latestSlice); } } if (!prefetchedOnCurrentVisit && Number(latestSlice?.consumption?.revision || 0) > 0) { prefetchedOnCurrentVisit = true; void prefetchConsumptionPresets(); } } ); function syncStaticLocaleLabels() { timeFilterSwitch.setProps({ ariaLabel: t('cons.rangeAria'), options: getConsumptionTimeRangeOptions(), }); patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); patchText(applyCustomBtnLabel, t('cons.applyFilter')); patchText(rangeToSpan, t('cons.rangeTo')); patchText(totalTokensLabel, t('cons.totalTokens')); patchText(estCostLabel, t('cons.estCost')); patchText(cacheHitRateLabel, t('cons.cacheHitRate')); patchText(newInputLabel, t('cons.newInput')); patchText(cacheReadLabel, t('cons.cacheRead')); patchText(outputUsageLabel, t('cons.outputUsage')); consExportMenu.refs.setAriaLabel(t('cons.exportMenuAria')); consExportMenu.refs.updateItemLabels({ xlsx: { label: t('cons.exportXlsx'), title: t('cons.exportXlsxTip') }, md: { label: t('cons.exportMd'), title: t('cons.exportMdTip') }, }); patchText(trendTitleSpan, t('cons.trendTitle')); heatmapModeSwitch.setProps({ ariaLabel: t('cons.hmModeAria'), modelValue: heatmapViewMode, options: getHeatmapModeOptions(), }); rankingTabSwitch.setProps({ ariaLabel: t('cons.rankTabAria'), modelValue: activeRankingTab, options: getRankingTabOptions(), }); modelsSortSwitch.setProps({ ariaLabel: t('cons.modelsSortAria'), options: getModelsSortOptions(), }); topConvsSortSwitch.setProps({ ariaLabel: t('cons.topConvsSortAria'), options: getTopConvsSortOptions(), }); patchText(topConvsEmptyEl, t('cons.topConvsEmpty')); patchText(sourcesTitleSpan, t('cons.clientSources')); patchText(sourcesHoverHint, t('cons.hoverModelsHint')); patchText(monthlyTitleSpan, t('cons.monthlyTitle')); patchText(monthlyHoverHint, t('cons.hoverModelsHint')); for (let i = 0; i < 12; i++) { patchText(monthlyCols[i].monthLabel, t('cons.monthLabel', { m: i + 1 })); } } const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { syncStaticLocaleLabels(); if (getVisibleMonitorView() === 'consumption' && latestSlice) { isDirty = false; renderConsumptionData(latestSlice); } else { isDirty = true; } } ); onCleanup(() => { clearConsAnimTimers(); hideBreakdownPopover(); unsub(); unsubView(); unsubI18n(); consExportMenu.destroy(); cyclePoolSelect.destroy(); heatmapModeSwitch.destroy(); trendChart.destroy?.(); rankingTabSwitch.destroy(); modelsSortSwitch.destroy(); topConvsSortSwitch.destroy(); timeFilterSwitch.destroy(); startPicker.destroy(); endPicker.destroy(); viewScrollbar.destroy(); }); return { el: rootEl, refs: { timeFilterSwitch, cyclePoolSelect, heatmapModeSwitch, trendChart, startPicker, endPicker, viewScrollbar, breakdownPopoverEl, consExportMenu, }, }; }, }); return { ConsumptionView }; })(); // --- src/views/StepsDetailView.js --- const { mergeSelectedAgentUnits, StepsDetailView } = (() => { /** * @fileoverview View 3: StepsDetailView (步骤明细与总汇总分析视图). * 提供“按步查看”与“总汇总”双子视图切换: * - 单步测速表通过 `stepColumnRegistry.js` 动态渲染用户自选的 2..12 个字段列,并支持行级增量对账; * - 总汇总视图提供会话线性走势图、多模型同图趋势拟合曲线与极简高密度模型总览卡片。 */ function mergeSelectedAgentUnits(units) { const combinedSteps = []; const modelMap = new Map(); for (const ag of units) { if (!ag || typeof ag !== 'object') continue; if (Array.isArray(ag.recentSteps)) { for (const step of ag.recentSteps) combinedSteps.push(step); } const breakdown = Array.isArray(ag.modelBreakdown) ? ag.modelBreakdown : []; for (const m of breakdown) { if (!m || typeof m !== 'object') continue; const gk = getStepModelGroupKey(m); let acc = modelMap.get(gk); if (!acc) { acc = { label: m.label || gk, shortName: m.shortName || gk, rawModel: m.rawModel || '', upstreamName: m.upstreamName || m.upstreamModel || '', upstreamSet: new Set( Array.isArray(m.upstreamModels) ? m.upstreamModels.filter(Boolean) : [] ), calls: 0, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0, thinkingTokens: 0, responseTokens: 0, totalTokens: 0, costUsd: 0, unpricedCalls: 0, anomalySteps: 0, anomalyCount: 0, anomalyDangerCount: 0, anomalyTotalDelaySec: 0, anomalyByKind: {}, _hasAnySpeedSummary: false, _speedTokens: 0, _speedSeconds: 0, _speedSampleCount: 0, _speedExcludedCount: 0, _speedExcludedReasons: {}, _ttftWeightedSum: 0, _ttftWeight: 0, _ttftSampleCount: 0, }; if (acc.upstreamName) acc.upstreamSet.add(acc.upstreamName); modelMap.set(gk, acc); } if (!acc.upstreamName && (m.upstreamName || m.upstreamModel)) { acc.upstreamName = m.upstreamName || m.upstreamModel; } if (m.upstreamName) acc.upstreamSet.add(m.upstreamName); if (Array.isArray(m.upstreamModels)) { for (const u of m.upstreamModels) { if (u) acc.upstreamSet.add(u); } } const calls = Math.max(0, Number(m.calls || 0)); const inTok = Math.max(0, Number(m.inputTokens || 0)); const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0)); const outTok = Math.max(0, Number(m.outputTokens || 0)); const thinkTok = Math.max(0, Number(m.thinkingTokens || 0)); const respTok = m.responseTokens != null ? Math.max(0, Number(m.responseTokens)) : Math.max(0, outTok - thinkTok); const totTok = Math.max(0, Number(m.totalTokens ?? inTok + cacheTok + outTok)); const costUsd = Number.isFinite(Number(m.costUsd)) ? Math.max(0, Number(m.costUsd)) : 0; const unpricedCalls = Math.max(0, Number(m.unpricedCalls || 0)); acc.calls += calls; acc.inputTokens += inTok; acc.cacheReadTokens += cacheTok; acc.outputTokens += outTok; acc.thinkingTokens += thinkTok; acc.responseTokens += respTok; acc.totalTokens += totTok; acc.costUsd += costUsd; acc.unpricedCalls += unpricedCalls; acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0)); acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0)); acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0)); acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0)); if (m.anomalyByKind && typeof m.anomalyByKind === 'object') { for (const [kind, cnt] of Object.entries(m.anomalyByKind)) { const n = Math.max(0, Number(cnt || 0)); if (n > 0) acc.anomalyByKind[kind] = (acc.anomalyByKind[kind] || 0) + n; } } const rawSpeedTok = Number(m.speedSummary?.tokens); const rawSpeedSec = Number(m.speedSummary?.seconds); if ( Number.isFinite(rawSpeedTok) && Number.isFinite(rawSpeedSec) && rawSpeedSec > 0 && rawSpeedTok >= 0 ) { acc._hasAnySpeedSummary = true; acc._speedTokens += rawSpeedTok; acc._speedSeconds += rawSpeedSec; } else if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) { const fallbackTok = outTok > 0 ? outTok : Math.max(1, calls || 1); acc._speedTokens += fallbackTok; acc._speedSeconds += fallbackTok / Number(m.avgTokPerSec); } if (m.speedSummary) { acc._hasAnySpeedSummary = true; acc._speedSampleCount += Math.max(0, Number(m.speedSummary.sampleCount || 0)); acc._speedExcludedCount += Math.max(0, Number(m.speedSummary.excludedCount || 0)); if (m.speedSummary.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { const cnt = Math.max(0, Number(rv || 0)); if (cnt > 0) acc._speedExcludedReasons[rk] = (acc._speedExcludedReasons[rk] || 0) + cnt; } } } if ( m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0 ) { const ttftSamples = Math.max(0, Number(m.ttftSampleCount || 0)); const w = ttftSamples > 0 ? ttftSamples : Math.max(1, calls || 1); acc._ttftWeightedSum += Number(m.avgTtftSec) * w; acc._ttftWeight += w; acc._ttftSampleCount += ttftSamples; } } } combinedSteps.sort( (a, b) => (Number(b?.createdAtMs) || 0) - (Number(a?.createdAtMs) || 0) || (Number(b?.agentIndex) || 0) - (Number(a?.agentIndex) || 0) || (Number(b?.stepIndex) || 0) - (Number(a?.stepIndex) || 0) ); const mergedModels = Array.from(modelMap.values()) .map((acc) => { const promptTok = acc.inputTokens + acc.cacheReadTokens; const rawAvgTps = acc._speedSeconds > 0 ? acc._speedTokens / acc._speedSeconds : null; return { label: acc.label, shortName: acc.shortName, rawModel: acc.rawModel, upstreamName: acc.upstreamName, upstreamModels: Array.from(acc.upstreamSet), calls: acc.calls, inputTokens: acc.inputTokens, cacheReadTokens: acc.cacheReadTokens, outputTokens: acc.outputTokens, thinkingTokens: acc.thinkingTokens, responseTokens: acc.responseTokens, totalTokens: acc.totalTokens, costUsd: +acc.costUsd.toFixed(6), unpricedCalls: acc.unpricedCalls, avgTokPerSec: rawAvgTps !== null ? +rawAvgTps.toFixed(1) : null, avgTtftSec: acc._ttftWeight > 0 ? +(acc._ttftWeightedSum / acc._ttftWeight).toFixed(1) : null, ttftSampleCount: acc._ttftSampleCount, ...(acc._hasAnySpeedSummary ? { speedSummary: { tokens: acc._speedTokens, seconds: +acc._speedSeconds.toFixed(6), sampleCount: acc._speedSampleCount, excludedCount: acc._speedExcludedCount, excludedReasons: acc._speedExcludedReasons, avgTokPerSec: rawAvgTps, }, } : {}), cacheHitPct: promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0, ...(acc.anomalyCount > 0 ? { anomalySteps: acc.anomalySteps, anomalyCount: acc.anomalyCount, anomalyDangerCount: acc.anomalyDangerCount, anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1), anomalyByKind: acc.anomalyByKind, } : {}), }; }) .sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls); return { steps: combinedSteps, models: mergedModels }; } function getLineMetricSwitchOptions() { return [ { value: 'totalTokens', label: t('steps.metricTotalTokens') }, { value: 'context', label: t('steps.metricContext') }, { value: 'tps', label: t('steps.metricTps') }, { value: 'ttft', label: t('steps.metricTtft') }, { value: 'cost', label: t('steps.metricCost') }, ]; } function getFitMetricSwitchOptions() { return [ { value: 'tps', label: t('steps.metricTps') }, { value: 'ttft', label: t('steps.metricTtft') }, { value: 'cache', label: t('steps.metricCache') }, { value: 'cost', label: t('steps.metricCost') }, ]; } const StepsDetailView = defineComponent({ name: 'StepsDetailView', setup({ onCleanup }) { let selectedAgentScopes = [uiStore.getState().selectedAgentScope || 'all']; let lastSyncedUiScope = uiStore.getState().selectedAgentScope || 'all'; let selectedTableModels = ['__all__']; let selectedLineModels = ['__all__']; let onlyAnomalies = false; let anomalyKindFilter = ''; let stepSearchQuery = ''; let stepQuickChip = ''; let currentTableSteps = []; let currentAllConvSteps = []; let currentDisplaySettings = {}; let sortKey = ''; let sortDir = ''; let cachedSortSrc = null; let cachedSortSig = ''; let cachedSortedOut = []; function applyAgentScopesSelection(nextScopes) { selectedAgentScopes = nextScopes; const mappedSingle = nextScopes.length === 1 && nextScopes[0] !== 'all' ? nextScopes[0] : 'all'; const prevUiScope = uiStore.getState().selectedAgentScope; lastSyncedUiScope = mappedSingle; if (prevUiScope !== mappedSingle) { const curCtxId = uiStore.getState().ctxInspectorAgentId; const shouldResetSubCtx = mappedSingle === 'all' && curCtxId && curCtxId !== 'main' && curCtxId !== 'auto'; uiStore.setState({ selectedAgentScope: mappedSingle, ...(shouldResetSubCtx ? { ctxInspectorAgentId: getDefaultCtxInspectorAgentId( telemetryStore.getState().telemetry?.settings ), } : {}), }); } else if (latestSlice) { renderStepsData(latestSlice); } } const inlineScopeSelect = CustomSelect({ multiple: true, allValue: 'all', collapseAll: true, multiUnit: t('steps.unitAgent'), modelValue: selectedAgentScopes, placeholder: t('steps.allAgents'), className: 'steps-inline-scope-select', options: [{ value: 'all', label: t('steps.allAgents') }], onUpdateModelValue: (nextScopes) => { if (!Array.isArray(nextScopes) || nextScopes.length === 0) return; applyAgentScopesSelection(nextScopes); }, }); inlineScopeSelect.el.setAttribute('hidden', ''); const stepsModelSelect = CustomSelect({ multiple: true, allValue: '__all__', collapseAll: false, multiUnit: t('steps.unitModel'), modelValue: selectedTableModels, placeholder: t('steps.allModels'), className: 'steps-inline-model-select', options: [{ value: '__all__', label: t('steps.allModels') }], onUpdateModelValue: (nextModels) => { if (!Array.isArray(nextModels) || nextModels.length === 0) return; selectedTableModels = nextModels; if (latestSlice) renderStepsData(latestSlice); }, }); stepsModelSelect.el.setAttribute('hidden', ''); const subTabSwitch = SegmentedControl({ ariaLabel: t('steps.title'), modelValue: uiStore.getState().stepsSubTab, options: [ { value: 'steps', label: t('steps.tabSteps', { count: 0 }) }, { value: 'models', label: t('steps.tabModels') }, ], onUpdateModelValue: (nextTab) => { uiStore.setState({ stepsSubTab: nextTab }); }, }); // --- 子视图 1:单步明细表(委托给可复用的 `StepTableWidget` 解耦组件) --- let stepsScroll = null; const stepTableWidget = StepTableWidget({ onSelectAgentScopes: applyAgentScopesSelection, onVirtualHeightChange: () => stepsScroll?.refresh(), onSortChange: (nextKey, nextDir) => { sortKey = nextKey || ''; sortDir = nextDir || ''; if (latestSlice) renderStepsData(latestSlice); }, }); const { stepsTablePane, stepsTableEl, stepsTheadRow, stepsTbody, turnTipEl, anomalyTipEl, hideTurnTip, showAnomalyTip, hideAnomalyTip, syncTableHeaderColumns, renderStepTable, refreshViewport: refreshStepTableViewport, } = stepTableWidget.refs; stepsScroll = CustomScrollbar({ contentEl: stepsTablePane, className: 'table-scroll-host', }); const anomalyFilterLabelEl = h('span', { className: 'steps-anomaly-filter-label text-mono' }); const anomalyFilterClearBtn = h('button', { type: 'button', className: 'btn-ghost-sm steps-anomaly-filter-clear', text: t('steps.anomalyFilterAll'), onclick: () => { onlyAnomalies = false; anomalyKindFilter = ''; if (stepQuickChip === 'anomaly') stepQuickChip = ''; if (latestSlice) renderStepsData(latestSlice); }, }); const anomalyFilterBarEl = h( 'div', { className: 'steps-anomaly-filterbar', hidden: true }, [anomalyFilterLabelEl, anomalyFilterClearBtn] ); // --- 步骤搜索栏及快捷诊断芯片 --- const stepSearchBox = createSearchInput({ wrapClassName: 'steps-search-wrap', iconClassName: 'steps-search-icon', inputClassName: 'steps-search-input', clearClassName: 'steps-search-clear', placeholder: t('steps.searchPlaceholder'), ariaLabel: t('steps.searchPlaceholder'), clearAriaLabel: t('steps.searchClearAria'), closeIconSize: 11, onInput: (val) => { stepSearchQuery = String(val ?? ''); if (latestSlice) renderStepsData(latestSlice); }, onClear: () => { stepSearchQuery = ''; if (latestSlice) renderStepsData(latestSlice); stepSearchInput.focus?.(); }, onKeydown: (e) => { if (e?.key === 'Escape') { e.stopPropagation?.(); if (stepSearchQuery) { stepSearchQuery = ''; stepSearchBox.setValue(''); if (latestSlice) renderStepsData(latestSlice); } else { stepSearchInput.blur?.(); } } }, }); const stepSearchWrapEl = stepSearchBox.el; const stepSearchInput = stepSearchBox.inputEl; const stepSearchClearBtn = stepSearchBox.clearBtnEl; const QUICK_CHIP_DEFS = [ { key: 'anomaly', i18nKey: 'steps.chipAnomaly', tone: 'is-warn' }, { key: 'compaction', i18nKey: 'steps.chipCompaction', tone: 'is-info' }, { key: 'low_cache', i18nKey: 'steps.chipLowCache', tipKey: 'steps.chipLowCacheTip', tone: 'is-warn' }, { key: 'slow_ttft', i18nKey: 'steps.chipSlowTtft', tipKey: 'steps.chipSlowTtftTip', tone: 'is-danger' }, ]; const quickChipBtns = QUICK_CHIP_DEFS.map((def) => { const btn = h('button', { type: 'button', className: `steps-chip-btn ${def.tone}`, 'data-chip': def.key, hidden: true, onclick: () => { if (def.key === 'anomaly') { const nextOn = !(onlyAnomalies || stepQuickChip === 'anomaly'); onlyAnomalies = nextOn; anomalyKindFilter = ''; stepQuickChip = nextOn ? 'anomaly' : ''; } else { const nextKey = stepQuickChip === def.key ? '' : def.key; stepQuickChip = nextKey; if (nextKey) { onlyAnomalies = false; anomalyKindFilter = ''; } } if (latestSlice) renderStepsData(latestSlice); }, }); return { def, btn }; }); const stepQuickChipsEl = h( 'div', { className: 'steps-quick-chips', hidden: true }, quickChipBtns.map((c) => c.btn) ); const stepsExportMenu = ActionMenu({ ariaLabel: t('steps.exportMenuAria'), className: 'steps-export-menu', items: [ { key: 'xlsx', icon: 'download', label: t('steps.exportXlsx'), title: t('steps.exportXlsxTip'), onSelect: () => { if (currentTableSteps.length === 0) return; const bytes = buildStepsXlsx(currentTableSteps, { title: latestSlice?.activeConversation?.title || '', cascadeId: latestSlice?.cascadeId || latestSlice?.activeConversation?.cascadeId || '', displaySettings: currentDisplaySettings, }); const baseName = buildStepsExportBaseName( latestSlice?.activeConversation?.title || '', latestSlice?.cascadeId || latestSlice?.activeConversation?.cascadeId || '' ); void exportBinaryFileWithFeedback( sanitizeExportFilename(baseName, 'xlsx'), bytes ); }, }, { key: 'md', icon: 'copy', label: t('steps.exportMd'), title: t('steps.exportMdTip'), onSelect: () => { if (currentTableSteps.length === 0) return; const md = buildStepsMarkdownReport(currentTableSteps, { title: latestSlice?.activeConversation?.title || '', cascadeId: latestSlice?.cascadeId || latestSlice?.activeConversation?.cascadeId || '', displaySettings: currentDisplaySettings, }); void copyTextWithFeedback(md, t('steps.exportMdDone')); }, }, ], }); stepsExportMenu.refs.setHidden(true); const stepsFilterToolbarEl = h( 'div', { className: 'steps-filter-toolbar', hidden: true }, [stepSearchWrapEl, stepQuickChipsEl] ); // --- 子视图 2:总汇总分析面板 --- let selectedLineMetric = 'totalTokens'; let selectedFitMetric = 'tps'; let fitLockedCascadeId = null; let fitLockedModelKeys = []; let fitPinnedWhileVisible = false; let fitUserPicked = false; const lineTitleEl = h('span', { className: 'sstep-card-title', text: t('steps.lineTitle') }); const lineSummaryBadge = h('span', { className: 'cons-badge text-mono', text: t('header.convMetaSteps', { count: 0 }), }); const lineModelSelect = CustomSelect({ multiple: true, allValue: '__all__', collapseAll: false, multiUnit: t('steps.unitModel'), modelValue: selectedLineModels, placeholder: t('steps.allModels'), className: 'sstep-fit-model-select sstep-line-model-select', options: [{ value: '__all__', label: t('steps.allModels') }], onUpdateModelValue: (nextModels) => { if (!Array.isArray(nextModels) || nextModels.length === 0) return; selectedLineModels = nextModels; if (latestSlice) renderStepsData(latestSlice); }, }); lineModelSelect.el.setAttribute('hidden', ''); const lineMetricSwitch = SegmentedControl({ ariaLabel: t('steps.lineTitle'), modelValue: selectedLineMetric, options: getLineMetricSwitchOptions(), onUpdateModelValue: (nextMetric) => { selectedLineMetric = nextMetric; if (latestSlice) renderStepsData(latestSlice); }, }); const sessionLineChart = createSessionLineChart(); const sessionLineCard = h('div', { className: 'sstep-card sstep-line-card' }, [ h('div', { className: 'sstep-card-head' }, [ h('div', { className: 'sstep-card-title-group' }, [lineTitleEl, lineSummaryBadge]), h('div', { className: 'sstep-fit-controls' }, [ lineModelSelect.el, lineMetricSwitch.el, ]), ]), sessionLineChart.el, ]); const fitTitleEl = h('span', { className: 'sstep-card-title', text: t('steps.fitTitle') }); const fitSummaryBadge = h('span', { className: 'cons-badge text-mono', text: t('header.convMetaSteps', { count: 0 }), }); const fitModelSelect = CustomSelect({ multiple: true, allValue: '__all__', collapseAll: false, multiUnit: t('steps.unitModel'), modelValue: ['__all__'], placeholder: t('steps.selectModel'), className: 'sstep-fit-model-select', options: [{ value: '__all__', label: t('steps.allModels') }], onUpdateModelValue: (nextModelKeys) => { if (!Array.isArray(nextModelKeys) || nextModelKeys.length === 0) return; fitLockedModelKeys = nextModelKeys; fitUserPicked = true; fitPinnedWhileVisible = true; if (latestSlice) renderStepsData(latestSlice); }, }); fitModelSelect.el.setAttribute('hidden', ''); const fitMetricSwitch = SegmentedControl({ ariaLabel: t('steps.fitTitle'), modelValue: selectedFitMetric, options: getFitMetricSwitchOptions(), onUpdateModelValue: (nextMetric) => { selectedFitMetric = nextMetric; if (latestSlice) renderStepsData(latestSlice); }, }); const modelFitChart = createModelFitChart(); const modelFitCard = h('div', { className: 'sstep-card sstep-fit-card' }, [ h('div', { className: 'sstep-card-head' }, [ h('div', { className: 'sstep-card-title-group' }, [fitTitleEl, fitSummaryBadge]), h('div', { className: 'sstep-fit-controls' }, [fitModelSelect.el, fitMetricSwitch.el]), ]), modelFitChart.el, ]); const modelsSectionTitleEl = h('span', { className: 'sstep-card-title', text: t('steps.modelsTitle'), }); const modelsSummaryMeta = h('span', { className: 'cons-badge text-mono', text: t('cons.callsCount', { calls: 0 }), }); const modelsAnomalyMetaEl = h('button', { type: 'button', className: 'steps-anomaly-strip-meta text-mono', onclick: () => { hideAnomalyTip(); selectedTableModels = ['__all__']; onlyAnomalies = true; anomalyKindFilter = ''; uiStore.setState({ stepsSubTab: 'steps' }); }, }); const modelsAnomalyTagsEl = h('div', { className: 'steps-anomaly-strip-tags' }); const modelsAnomalyStripEl = h( 'div', { className: 'steps-anomaly-strip', hidden: true }, [modelsAnomalyMetaEl, modelsAnomalyTagsEl] ); let lastAnomalyStripSig = ''; const modelsEmptyEl = h('div', { className: 'smodel-empty text-muted', text: t('steps.modelsEmpty'), }); const modelsListEl = h('div', { className: 'smodel-list' }); const modelsSummarySection = h('div', { className: 'smodel-section' }, [ h('div', { className: 'smodel-section-head' }, [modelsSectionTitleEl, modelsSummaryMeta]), modelsAnomalyStripEl, modelsEmptyEl, modelsListEl, ]); const modelsAnalyticsPane = h('div', { className: 'table-viewport models-analytics-pane' }, [ sessionLineCard, modelFitCard, modelsSummarySection, ]); const onModelsPaneScroll = () => hideAnomalyTip(); modelsAnalyticsPane.addEventListener('scroll', onModelsPaneScroll, { passive: true }); const modelsScroll = CustomScrollbar({ contentEl: modelsAnalyticsPane, className: 'table-scroll-host', }); modelsScroll.el.setAttribute('hidden', ''); const headerFiltersEl = h('div', { className: 'steps-header-filters', hidden: true }, [ inlineScopeSelect.el, stepsModelSelect.el, ]); const panelEl = h( 'section', { className: 'panel', style: 'flex: 1; min-height: 0; display: flex; flex-direction: column; position: relative;', }, [ h('div', { className: 'panel-header steps-panel-header' }, [ h('div', { className: 'steps-header-controls' }, [ subTabSwitch.el, h('div', { className: 'steps-header-right' }, [ headerFiltersEl, stepsExportMenu.el, ]), ]), ]), stepsFilterToolbarEl, anomalyFilterBarEl, stepsScroll.el, modelsScroll.el, turnTipEl, anomalyTipEl, ] ); stepTableWidget.refs.setBoundsElGetter(() => panelEl); const rootEl = h('div', { className: 'view-pane' }, [panelEl]); let latestSlice = null; let isDirty = false; let cachedChronoSrc = null; let cachedChronoMerged = false; let cachedChronoOut = []; function getMemoizedChronoSteps(steps, isMergedMultiAgents) { if (cachedChronoSrc === steps && cachedChronoMerged === isMergedMultiAgents) { return cachedChronoOut; } cachedChronoSrc = steps; cachedChronoMerged = isMergedMultiAgents; cachedChronoOut = toChronologicalSteps(steps, isMergedMultiAgents); return cachedChronoOut; } function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { if (scopedConv?.hasKnownModel !== false) { const activeCand = getStepModelGroupKey({ baseModelLabel: scopedConv?.activeBaseModelLabel, baseModelShort: scopedConv?.activeBaseModelShort, modelLabel: scopedConv?.activeModelLabel, modelShort: scopedConv?.activeModelShort, }); if ( activeCand && activeCand !== t('fmt.unknownModel') && availableModelKeys.has(activeCand) ) { return activeCand; } } for (let i = chronoSteps.length - 1; i >= 0; i--) { const st = chronoSteps[i]; if (!st || st.isCompactionStep) continue; const gk = getStepModelGroupKey(st); if (gk && availableModelKeys.has(gk)) return gk; } if (chronoSteps.length > 0) { const gk = getStepModelGroupKey(chronoSteps[chronoSteps.length - 1]); if (gk && availableModelKeys.has(gk)) return gk; } if (models.length > 0) { const firstKey = getStepModelGroupKey(models[0]); if (firstKey && availableModelKeys.has(firstKey)) return firstKey; } return '__all__'; } function normalizeMultiModelSelection(rawSelection, availableModelKeys) { if (availableModelKeys.size <= 1) return ['__all__']; const arr = Array.isArray(rawSelection) ? rawSelection : []; if (arr.length === 0 || arr.includes('__all__')) return ['__all__']; const valid = Array.from(new Set(arr.filter((k) => availableModelKeys.has(k)))); if (valid.length === 0) return ['__all__']; return valid; } function refreshStaticLocaleLabels() { patchText(lineTitleEl, t('steps.lineTitle')); patchText(fitTitleEl, t('steps.fitTitle')); patchText(modelsSectionTitleEl, t('steps.modelsTitle')); patchText(modelsEmptyEl, t('steps.modelsEmpty')); patchText(anomalyFilterClearBtn, t('steps.anomalyFilterAll')); patchAttr(stepSearchInput, 'placeholder', t('steps.searchPlaceholder')); patchAttr(stepSearchInput, 'aria-label', t('steps.searchPlaceholder')); patchAttr(stepSearchClearBtn, 'aria-label', t('steps.searchClearAria')); stepsExportMenu.refs.setAriaLabel(t('steps.exportMenuAria')); stepsExportMenu.refs.updateItemLabels({ xlsx: { label: t('steps.exportXlsx'), title: t('steps.exportXlsxTip') }, md: { label: t('steps.exportMd'), title: t('steps.exportMdTip') }, }); lastAnomalyStripSig = ''; lineMetricSwitch.setProps({ modelValue: selectedLineMetric, options: getLineMetricSwitchOptions(), }); fitMetricSwitch.setProps({ modelValue: selectedFitMetric, options: getFitMetricSwitchOptions(), }); const colKeys = normalizeClientStepColumns(latestSlice?.stepTableColumns); syncTableHeaderColumns(colKeys); if (!latestSlice) { subTabSwitch.setProps({ modelValue: uiStore.getState().stepsSubTab, options: [ { value: 'steps', label: t('steps.tabSteps', { count: 0 }) }, { value: 'models', label: t('steps.tabModels') }, ], }); } } function renderStepsData(slice, { allowNewRowFade = false } = {}) { if (!slice) return; const uiSt = uiStore.getState(); const locale = getEffectiveLocale(); const currentCid = String(slice.cascadeId || slice.activeConversation?.cascadeId || ''); if (currentCid !== fitLockedCascadeId) { if (fitLockedCascadeId !== null) { selectedAgentScopes = [uiSt.selectedAgentScope || 'all']; lastSyncedUiScope = uiSt.selectedAgentScope || 'all'; selectedTableModels = ['__all__']; selectedLineModels = ['__all__']; onlyAnomalies = false; anomalyKindFilter = ''; stepSearchQuery = ''; stepSearchInput.value = ''; patchAttr(stepSearchClearBtn, 'hidden', true); stepQuickChip = ''; sortKey = ''; sortDir = ''; } fitLockedCascadeId = currentCid; fitUserPicked = false; fitPinnedWhileVisible = false; fitLockedModelKeys = []; } const baseScope = resolveScopedConversation( { activeConversation: slice.activeConversation }, 'all', uiSt.ctxInspectorAgentId, true ); const { hasSubagents, agents, subagents, mainAgent, aggregated } = baseScope; let effectiveScopes = ['main']; let isMergedMultiAgents = false; let steps = []; let models = []; let activeModelSource = baseScope.scopedConv; patchAttr(inlineScopeSelect.el, 'hidden', !hasSubagents); if (hasSubagents) { const validAgentIds = ['main', ...subagents.map((s) => s.agentId)]; const validSet = new Set(validAgentIds); if (selectedAgentScopes.length === 0 || selectedAgentScopes.includes('all')) { effectiveScopes = ['all']; } else { const filtered = selectedAgentScopes.filter((id) => validSet.has(id)); effectiveScopes = filtered.length === 0 || filtered.length >= validAgentIds.length ? ['all'] : filtered; } selectedAgentScopes = effectiveScopes; const scopeOpts = [ { value: 'all', label: t('steps.allAgents'), meta: t('header.convMetaSteps', { count: aggregated?.stepCount ?? 0 }), }, { value: 'main', label: t('fmt.mainAgent'), meta: t('header.convMetaSteps', { count: mainAgent?.stepCount ?? 0 }), }, ...subagents.map((s) => ({ value: s.agentId, label: formatAgentLabel(s), meta: t('header.convMetaSteps', { count: s.stepCount || 0 }), })), ]; inlineScopeSelect.setProps({ modelValue: effectiveScopes, options: scopeOpts, placeholder: t('steps.allAgents'), multiUnit: t('steps.unitAgent'), }); if (effectiveScopes[0] === 'all') { steps = aggregated?.recentSteps || []; models = aggregated?.modelBreakdown || []; isMergedMultiAgents = true; activeModelSource = aggregated; } else if (effectiveScopes.length === 1) { const targetId = effectiveScopes[0]; const unit = targetId === 'main' ? mainAgent : agents.find((a) => a.agentId === targetId) || mainAgent; steps = unit?.recentSteps || []; models = unit?.modelBreakdown || []; isMergedMultiAgents = false; activeModelSource = unit; } else { const scopeSet = new Set(effectiveScopes); const selectedUnits = agents.filter((a) => scopeSet.has(a.isMain ? 'main' : a.agentId) ); const merged = mergeSelectedAgentUnits(selectedUnits); steps = merged.steps; models = merged.models; isMergedMultiAgents = true; activeModelSource = selectedUnits.find((a) => a.isRunning) || selectedUnits[0] || aggregated; } } else { inlineScopeSelect.close(); steps = slice.recentSteps || []; models = slice.sessionModelBreakdown || []; } const displaySettings = { modelDisplayMode: normalizeModelDisplayMode( slice.modelDisplayMode, slice.showUpstreamModel ), showUpstreamModel: Boolean(slice.showUpstreamModel), orchestratorIdMode: slice.orchestratorIdMode, }; const showAgentPrefix = isMergedMultiAgents; const showModels = uiSt.stepsSubTab === 'models'; const availableModelKeys = new Set(); const modelColorByGroup = new Map(); const perModelOptions = []; let breakdownCalls = 0; for (const m of models) { if (!m || typeof m !== 'object') continue; breakdownCalls += Math.max(0, Number(m.calls || 0)); const gk = getStepModelGroupKey(m); if (availableModelKeys.has(gk)) continue; availableModelKeys.add(gk); modelColorByGroup.set( gk, MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length] ); const disp = resolveModelDisplayInfo(m, displaySettings, { preferLabelInShort: false, fallback: gk, }); perModelOptions.push({ value: gk, label: disp.baseText || disp.text || gk, meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), }); } const needStepModelFallback = steps.length > 0 && (models.length === 0 || breakdownCalls < steps.length); if (needStepModelFallback) { const stepModelOptionMap = new Map(); for (const st of steps) { const gk = getStepModelGroupKey(st); if (!stepModelOptionMap.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); stepModelOptionMap.set(gk, { label: disp.baseText || disp.text || gk, calls: 0, }); } stepModelOptionMap.get(gk).calls += 1; } for (const [gk, info] of stepModelOptionMap.entries()) { if (!availableModelKeys.has(gk)) { availableModelKeys.add(gk); modelColorByGroup.set( gk, MODEL_COLOR_VARS[(availableModelKeys.size - 1) % MODEL_COLOR_VARS.length] ); perModelOptions.push({ value: gk, label: info.label, meta: t('header.convMetaSteps', { count: info.calls }), }); } } } const hasMultipleModels = availableModelKeys.size > 1; const modelSelectOptions = [ { value: '__all__', label: t('steps.allModels'), meta: t('header.convMetaSteps', { count: steps.length }), }, ...perModelOptions, ]; // 1. “按步查看”动态列头同步与表格行级增量对账 selectedTableModels = normalizeMultiModelSelection( selectedTableModels, availableModelKeys ); const showStepsModelFilter = uiSt.stepsSubTab === 'steps' && hasMultipleModels; patchAttr(stepsModelSelect.el, 'hidden', !showStepsModelFilter); patchAttr(headerFiltersEl, 'hidden', !hasSubagents && !showStepsModelFilter); if (hasMultipleModels) { stepsModelSelect.setProps({ modelValue: selectedTableModels, options: modelSelectOptions, placeholder: t('steps.allModels'), multiUnit: t('steps.unitModel'), }); if (!showStepsModelFilter) stepsModelSelect.close(); } else { stepsModelSelect.close(); } const tableModelFilterSet = selectedTableModels.includes('__all__') ? null : new Set(selectedTableModels); const modelFilteredSteps = tableModelFilterSet ? steps.filter((st) => tableModelFilterSet.has(getStepModelGroupKey(st))) : steps; const filterToolbarEnabled = slice.showStepFilterToolbar === true; if (!filterToolbarEnabled) { if (stepSearchQuery) { stepSearchQuery = ''; stepSearchInput.value = ''; patchAttr(stepSearchClearBtn, 'hidden', true); } if (stepQuickChip && stepQuickChip !== 'anomaly') { stepQuickChip = ''; } } const chipCounts = computeStepQuickChipCounts(modelFilteredSteps); const effectiveQuickChip = onlyAnomalies ? 'anomaly' : filterToolbarEnabled ? stepQuickChip : ''; const showFilterToolbar = filterToolbarEnabled && !showModels && steps.length > 0; patchAttr(stepsFilterToolbarEl, 'hidden', !showFilterToolbar); stepsExportMenu.refs.setHidden(showModels || steps.length === 0); if (showFilterToolbar) { let visibleChipsCount = 0; for (const { def, btn } of quickChipBtns) { const cnt = chipCounts[def.key] || 0; const isActive = effectiveQuickChip === def.key; const showChip = cnt > 0 || isActive; patchAttr(btn, 'hidden', !showChip); if (showChip) { visibleChipsCount += 1; patchText(btn, t(def.i18nKey, { count: cnt })); if (def.tipKey) patchAttr(btn, 'title', t(def.tipKey)); patchClasses(btn, { 'is-active': isActive }); patchAttr(btn, 'aria-pressed', isActive ? 'true' : 'false'); } } patchAttr(stepQuickChipsEl, 'hidden', visibleChipsCount === 0); } const filteredTableSteps = filterStepsBySearchAndChip(modelFilteredSteps, { query: filterToolbarEnabled ? stepSearchQuery : '', quickChip: effectiveQuickChip, anomalyKindFilter: onlyAnomalies ? anomalyKindFilter : '', displaySettings, }); const normTokenFmt = normalizeClientStepTokenComboFormat(slice.stepTokenComboFormat); const sortSig = `${sortKey}:${sortDir}:${normTokenFmt}:${displaySettings.modelDisplayMode}:${displaySettings.showUpstreamModel ? 1 : 0}:${displaySettings.orchestratorIdMode}`; let tableSteps = filteredTableSteps; if (sortKey && sortDir) { if (cachedSortSrc === filteredTableSteps && cachedSortSig === sortSig) { tableSteps = cachedSortedOut; } else { tableSteps = sortStepsByColumn(filteredTableSteps, sortKey, sortDir, { stepTokenComboFormat: normTokenFmt, displaySettings, }); cachedSortSrc = filteredTableSteps; cachedSortSig = sortSig; cachedSortedOut = tableSteps; } } else { cachedSortSrc = null; cachedSortSig = ''; cachedSortedOut = []; } const showAnomalyFilterBar = !showModels && onlyAnomalies; patchAttr(anomalyFilterBarEl, 'hidden', !showAnomalyFilterBar); if (showAnomalyFilterBar) { const baseLabel = t('steps.anomalyFilterLabel', { count: tableSteps.length }); const kindSuffix = anomalyKindFilter ? ` · ${formatAnomalyKindLabel(anomalyKindFilter)}` : ''; patchText(anomalyFilterLabelEl, `${baseLabel}${kindSuffix}`); } const stepsTabLabel = tableSteps.length !== steps.length ? t('steps.tabStepsFiltered', { filtered: tableSteps.length, total: steps.length, }) : t('steps.tabSteps', { count: steps.length }); subTabSwitch.setProps({ options: [ { value: 'steps', label: stepsTabLabel }, { value: 'models', label: t('steps.tabModels') }, ], }); const allConversationSteps = hasSubagents ? aggregated?.recentSteps || [] : slice.recentSteps || []; currentTableSteps = tableSteps; currentAllConvSteps = allConversationSteps; currentDisplaySettings = displaySettings; const shouldAnimateNewRows = Boolean( allowNewRowFade && slice.experimentalModernUi && !showModels ); if (!showModels) { const colKeys = normalizeClientStepColumns(slice.stepTableColumns); renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, { effectiveScopes, hasSubagents, isMergedMultiAgents, showStepTurnRail: slice.showStepTurnRail === true, showStepAgentBadge: slice.showStepAgentBadge !== false, showStepSpeedColor: slice.showStepSpeedColor === true, stepTokenComboFormat: slice.stepTokenComboFormat, displaySettings, allConversationSteps, allowNewRowFade: shouldAnimateNewRows, sortKey, sortDir, }); stepsScroll.refresh(); fitPinnedWhileVisible = false; return; } const chronoSteps = getMemoizedChronoSteps(steps, isMergedMultiAgents); const stepTtftFallbackMap = new Map(); const needTtftFallback = models.some((m) => m && m.avgTtftSec == null); if (needTtftFallback) { for (const st of chronoSteps) { if (!st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) { const gk = getStepModelGroupKey(st); const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 }; prev.sum += Number(st.ttftSec); prev.count += 1; stepTtftFallbackMap.set(gk, prev); } } } // 2. 顶部“会话走势”更新 selectedLineModels = normalizeMultiModelSelection( selectedLineModels, availableModelKeys ); // 3. 顶部“趋势拟合”模型锁定随当前会话与代理范围更新。 const defaultActiveModelKey = resolveDefaultActiveModelKey( activeModelSource, chronoSteps, models, availableModelKeys ); const sanitizedLocked = fitLockedModelKeys.includes('__all__') ? ['__all__'] : Array.from(new Set(fitLockedModelKeys.filter((k) => availableModelKeys.has(k)))); if ((!fitPinnedWhileVisible && !fitUserPicked) || sanitizedLocked.length === 0) { fitLockedModelKeys = [defaultActiveModelKey]; } else { fitLockedModelKeys = sanitizedLocked; } if (availableModelKeys.size > 0) fitPinnedWhileVisible = true; patchAttr(lineModelSelect.el, 'hidden', !hasMultipleModels); if (hasMultipleModels) { lineModelSelect.setProps({ modelValue: selectedLineModels, options: modelSelectOptions, placeholder: t('steps.allModels'), multiUnit: t('steps.unitModel'), }); } else { lineModelSelect.close(); } const lineRes = sessionLineChart.update({ steps: chronoSteps, modelGroupKey: selectedLineModels[0] || '__all__', modelGroupKeys: selectedLineModels, modelColorByGroup, metric: selectedLineMetric, showAgentPrefix, displaySettings, }); patchText(lineSummaryBadge, lineRes.summaryBadge); const effectiveFitModelKeys = availableModelKeys.size === 0 ? ['__all__'] : !hasMultipleModels ? [Array.from(availableModelKeys)[0]] : fitLockedModelKeys.length > 0 ? fitLockedModelKeys : [defaultActiveModelKey]; patchAttr(fitModelSelect.el, 'hidden', !hasMultipleModels); if (hasMultipleModels) { fitModelSelect.setProps({ modelValue: effectiveFitModelKeys, options: modelSelectOptions, placeholder: t('steps.selectModel'), multiUnit: t('steps.unitModel'), }); } else { fitModelSelect.close(); } const fitRes = modelFitChart.update({ steps: chronoSteps, modelGroupKey: effectiveFitModelKeys[0] || '__all__', modelGroupKeys: effectiveFitModelKeys, modelColorByGroup, metric: selectedFitMetric, showAgentPrefix, displaySettings, }); patchText(fitSummaryBadge, fitRes.summaryBadge); // 4. 极简模型总览列表增量对账 const displayModels = mergeModelsByDisplayName(models, displaySettings, { fallback: '—' }); const needStepAnomalyFallback = displayModels.every((m) => !(Number(m?.anomalyCount) > 0)); let stepAnomalyByGroup = null; if (needStepAnomalyFallback) { for (const st of chronoSteps) { const a = st?.anomaly; if (!a || !(Number(a.count) > 0)) continue; if (!stepAnomalyByGroup) stepAnomalyByGroup = new Map(); const gk = getStepModelGroupKey(st); let acc = stepAnomalyByGroup.get(gk); if (!acc) { acc = { anomalySteps: 0, anomalyCount: 0, anomalyDangerCount: 0, anomalyTotalDelaySec: 0, anomalyByKind: {}, }; stepAnomalyByGroup.set(gk, acc); } acc.anomalySteps += 1; acc.anomalyCount += Number(a.count) || 0; if (a.severity === 'danger') acc.anomalyDangerCount += 1; acc.anomalyTotalDelaySec += Number(a.totalDelaySec) || 0; if (a.kinds && typeof a.kinds === 'object') { for (const [k, cnt] of Object.entries(a.kinds)) { const n = Math.max(0, Number(cnt || 0)); if (n > 0) acc.anomalyByKind[k] = (acc.anomalyByKind[k] || 0) + n; } } } } const resolveEffectiveAnomalyModel = (m) => { if (Number(m?.anomalyCount) > 0 || !stepAnomalyByGroup) return m; const gk = getStepModelGroupKey(m); const groupKeys = Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0 ? Array.from(new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl })))) : [gk]; let anomalySteps = 0; let anomalyCount = 0; let anomalyDangerCount = 0; let anomalyTotalDelaySec = 0; const anomalyByKind = {}; for (const key of groupKeys) { const hit = stepAnomalyByGroup.get(key); if (!hit) continue; anomalySteps += hit.anomalySteps; anomalyCount += hit.anomalyCount; anomalyDangerCount += hit.anomalyDangerCount; anomalyTotalDelaySec += hit.anomalyTotalDelaySec; for (const [k, cnt] of Object.entries(hit.anomalyByKind)) { anomalyByKind[k] = (anomalyByKind[k] || 0) + cnt; } } if (anomalyCount <= 0) return m; return { ...m, anomalySteps, anomalyCount, anomalyDangerCount, anomalyTotalDelaySec: +anomalyTotalDelaySec.toFixed(1), anomalyByKind, }; }; let sumCalls = 0; let sumTokens = 0; let sumCost = 0; let sumUnpriced = 0; let sumAnomalyCount = 0; let sumAnomalySteps = 0; const sumAnomalyByKind = {}; const effectiveAnomalyModels = new Map(); for (const m of displayModels) { sumCalls += Math.max(0, Number(m.calls || 0)); sumTokens += Math.max(0, Number(m.totalTokens || 0)); sumUnpriced += Math.max(0, Number(m.unpricedCalls || 0)); if (Number.isFinite(Number(m.costUsd))) { sumCost += Math.max(0, Number(m.costUsd)); } const effM = resolveEffectiveAnomalyModel(m); effectiveAnomalyModels.set(m, effM); const anomSum = resolveModelAnomalySummary(effM); if (anomSum) { sumAnomalyCount += anomSum.count; sumAnomalySteps += anomSum.steps; for (const [k, v] of anomSum.entries) { sumAnomalyByKind[k] = (sumAnomalyByKind[k] || 0) + v; } } } if (sumAnomalyCount > 0) { patchAttr(modelsAnomalyStripEl, 'hidden', false); const sortedKinds = Object.entries(sumAnomalyByKind) .filter(([, v]) => v > 0) .sort((a, b) => b[1] - a[1]); const hasDangerKind = sortedKinds.some( ([kind]) => kind === 'rate_limit' || kind === 'auth_or_model' ); patchClasses(modelsAnomalyStripEl, { 'has-danger': hasDangerKind }); const stripSig = `${locale}:${sumAnomalyCount}:${sumAnomalySteps}:${sortedKinds.map(([k, v]) => `${k}=${v}`).join(',')}`; if (stripSig !== lastAnomalyStripSig) { lastAnomalyStripSig = stripSig; patchText( modelsAnomalyMetaEl, t('steps.anomalySummaryMeta', { count: sumAnomalyCount, steps: sumAnomalySteps }) ); while (modelsAnomalyTagsEl.firstChild) { modelsAnomalyTagsEl.removeChild(modelsAnomalyTagsEl.firstChild); } for (const [kind, cnt] of sortedKinds) { const isDanger = kind === 'rate_limit' || kind === 'auth_or_model'; const btn = h('button', { type: 'button', className: `step-anomaly-tag smodel-anomaly-tag text-mono${isDanger ? ' is-danger' : ''}`, text: formatAnomalyTagText(kind, cnt), title: `${formatAnomalyKindLabel(kind)} · ${t('steps.anomalyModelClickHint')}`, onclick: () => { hideAnomalyTip(); selectedTableModels = ['__all__']; onlyAnomalies = true; anomalyKindFilter = kind; uiStore.setState({ stepsSubTab: 'steps' }); }, }); modelsAnomalyTagsEl.appendChild(btn); } } } else { lastAnomalyStripSig = ''; patchAttr(modelsAnomalyStripEl, 'hidden', true); } if (displayModels.length === 0) { patchText(modelsSummaryMeta, t('cons.callsCount', { calls: 0 })); } else { const modelCountPart = displayModels.length > 1 ? t('steps.modelsSummaryPrefix', { count: displayModels.length }) : ''; const isAllUnpricedSum = sumCalls > 0 && sumUnpriced >= sumCalls && !(sumCost > 0); patchText( modelsSummaryMeta, `${modelCountPart}${t('cons.callsCount', { calls: sumCalls })} · ${formatTokens(sumTokens)} · ${formatUsd( isAllUnpricedSum ? null : sumCost, { precise: sumCost > 0 && sumCost < 0.1, } )}` ); } patchAttr(modelsEmptyEl, 'hidden', displayModels.length > 0); patchAttr(modelsListEl, 'hidden', displayModels.length === 0); const isFitPooledAll = effectiveFitModelKeys.includes('__all__'); const fitActiveKeySet = new Set(isFitPooledAll ? [] : effectiveFitModelKeys); patchKeyedList(modelsListEl, displayModels, { keyFn: (m) => m.displayText || m.label || m.shortName, sigFn: (m) => { const gk = getStepModelGroupKey(m); const fbTtft = stepTtftFallbackMap.get(gk); const avgTtft = m.avgTtftSec != null ? m.avgTtftSec : fbTtft && fbTtft.count > 0 ? +(fbTtft.sum / fbTtft.count).toFixed(1) : null; const cardGroupKeys = Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0 ? m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl })) : [gk]; const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); const effM = effectiveAnomalyModels.get(m) || m; const anomSum = resolveModelAnomalySummary(effM); const anomSig = anomSum ? `${anomSum.count}:${anomSum.steps}:${anomSum.primaryKind}:${anomSum.severity}:${anomSum.totalDelaySec}` : ''; return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${sumTokens}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}:${anomSig}`; }, createRow: () => { const nameEl = h('strong', { className: 'cons-row-title-text smodel-name' }); const anomalyTagEl = h('span', { className: 'step-anomaly-tag smodel-anomaly-tag text-mono', title: '', hidden: true, }); const titleWrapEl = h('strong', { className: 'cons-row-title smodel-ident' }, [ nameEl, anomalyTagEl, ]); const pctBadgeEl = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const tokEl = h('span', { className: 'cons-row-tok smodel-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost smodel-cost text-mono' }); const segBar = createFourSegmentBar(); segBar.el.classList.add('smodel-seg-bar'); const inLbl = h('span', { text: t('cons.footInput') }); const cacheLbl = h('span', { text: t('cons.footCache') }); const thinkLbl = h('span', { text: t('cons.footThinking') }); const outLbl = h('span', { text: t('cons.footOutput') }); const callsLbl = h('span', { text: t('cons.footCalls') }); const inVal = h('strong', { className: 'text-mono' }); const cacheVal = h('strong', { className: 'text-mono' }); const thinkVal = h('strong', { className: 'text-mono' }); const outVal = h('strong', { className: 'text-mono' }); const callsVal = h('strong', { className: 'text-mono' }); const footEl = h('div', { className: 'cons-item-foot smodel-foot' }, [ h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-input' }), inLbl, inVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-cached' }), cacheLbl, cacheVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-thinking' }), thinkLbl, thinkVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-output' }), outLbl, outVal, ]), h('span', { className: 'legend-left' }, [callsLbl, callsVal]), ]); const perfEl = h('span', { className: 'cons-model-perf-main smodel-perf text-mono' }); const unitCostEl = h('span', { className: 'cons-model-unit-cost smodel-unit-cost text-mono', hidden: true, }); const perfFootEl = h('div', { className: 'cons-model-perf-foot smodel-perf-foot' }, [ perfEl, unitCostEl, ]); const cardEl = h('div', { className: 'cons-item-row smodel-card' }, [ h('div', { className: 'panel-header smodel-head' }, [ titleWrapEl, h('span', { className: 'cons-row-metrics smodel-totals' }, [ pctBadgeEl, tokEl, costEl, ]), ]), segBar.el, footEl, perfFootEl, ]); return { el: cardEl, refs: { nameEl, pctBadgeEl, anomalyTagEl, tokEl, costEl, segBar, perfEl, unitCostEl, inLbl, cacheLbl, thinkLbl, outLbl, callsLbl, inVal, cacheVal, thinkVal, outVal, callsVal, cardTitle: '', isHoveringAnomaly: false, }, }; }, updateRow: (refs, m, _idx, cardEl) => { const gk = getStepModelGroupKey(m); const cardGroupKeys = Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0 ? Array.from( new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl }))) ) : [gk]; const dispText = m.displayText || '—'; const dispTitle = m.displayTitle || dispText; patchText(refs.nameEl, dispText); patchAttr(refs.nameEl, 'title', dispTitle); const calls = Math.max(0, Number(m.calls || 0)); const effM = effectiveAnomalyModels.get(m) || m; const anomSum = resolveModelAnomalySummary(effM); patchAttr(refs.anomalyTagEl, 'hidden', !anomSum); if (anomSum) { patchText(refs.anomalyTagEl, anomSum.tagText); patchClasses(refs.anomalyTagEl, { 'is-danger': anomSum.severity === 'danger' }); patchAttr(refs.anomalyTagEl, 'title', ''); refs.anomalyTagEl.onmouseenter = () => { refs.isHoveringAnomaly = true; patchAttr(cardEl, 'title', null); showAnomalyTip(refs.anomalyTagEl, buildModelAnomalyDiagnostic(effM)); }; refs.anomalyTagEl.onmouseleave = () => { refs.isHoveringAnomaly = false; patchAttr(cardEl, 'title', refs.cardTitle || null); hideAnomalyTip(); }; refs.anomalyTagEl.onclick = (e) => { e?.stopPropagation?.(); refs.isHoveringAnomaly = false; patchAttr(cardEl, 'title', refs.cardTitle || null); hideAnomalyTip(); selectedTableModels = hasMultipleModels ? [...cardGroupKeys] : ['__all__']; onlyAnomalies = true; anomalyKindFilter = ''; uiStore.setState({ stepsSubTab: 'steps' }); }; } else { refs.isHoveringAnomaly = false; refs.anomalyTagEl.onmouseenter = null; refs.anomalyTagEl.onmouseleave = null; refs.anomalyTagEl.onclick = null; } const inTok = Math.max(0, Number(m.inputTokens || 0)); const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0)); const outTok = Math.max(0, Number(m.outputTokens || 0)); const thinkTok = Math.max(0, Number(m.thinkingTokens || 0)); const respTok = m.responseTokens != null ? Math.max(0, Number(m.responseTokens)) : Math.max(0, outTok - thinkTok); const modelTok = Math.max(0, Number(m.totalTokens || 0)); const tokSharePct = sumTokens > 0 ? (modelTok / sumTokens) * 100 : sumCalls > 0 ? (calls / sumCalls) * 100 : 0; patchText(refs.pctBadgeEl, formatPctNumber(tokSharePct, { withSymbol: true })); patchText(refs.tokEl, formatTokensPrecise(modelTok)); const costNum = Number(m.costUsd || 0); const isAllUnpriced = calls > 0 && Number(m.unpricedCalls || 0) >= calls && !(costNum > 0); patchText( refs.costEl, formatUsd(isAllUnpriced ? null : costNum, { precise: costNum > 0 && costNum < 0.1 }) ); const scaleRatio = displayModels.length > 1 && sumTokens > 0 && modelTok > 0 ? Math.min(1, Math.max(0.008, modelTok / sumTokens)) : 1; refs.segBar.update({ inputTokens: inTok, cacheReadTokens: cacheTok, responseTokens: respTok, thinkingTokens: thinkTok, scaleRatio, }); const fbTtft = stepTtftFallbackMap.get(gk); const resolvedAvgTtft = m.avgTtftSec != null ? Number(m.avgTtftSec) : fbTtft && fbTtft.count > 0 ? fbTtft.sum / fbTtft.count : null; const promptTok = inTok + cacheTok; const resolvedCachePct = m.cacheHitPct != null ? Number(m.cacheHitPct) : promptTok > 0 ? +((cacheTok / promptTok) * 100).toFixed(1) : 0; patchText(refs.inLbl, t('cons.footInput')); patchText(refs.cacheLbl, t('cons.footCache')); patchText(refs.thinkLbl, t('cons.footThinking')); patchText(refs.outLbl, t('cons.footOutput')); patchText(refs.callsLbl, t('cons.footCalls')); patchText(refs.inVal, formatTokensPrecise(inTok)); patchText(refs.cacheVal, formatTokensPrecise(cacheTok)); patchText(refs.thinkVal, formatTokensPrecise(thinkTok)); patchText(refs.outVal, formatTokensPrecise(respTok)); patchText(refs.callsVal, String(calls)); patchText( refs.perfEl, t('steps.modelPerfFoot', { tps: formatSpeedMetric(m.avgTokPerSec, ' tok/s'), ttft: formatMetric(resolvedAvgTtft, 's'), cache: resolvedCachePct, }) ); const effCostPer1M = !isAllUnpriced && costNum > 0 && modelTok >= 1000 ? costNum / (modelTok / 1_000_000) : null; patchAttr(refs.unitCostEl, 'hidden', effCostPer1M === null); patchText( refs.unitCostEl, effCostPer1M !== null ? t('cons.modelUnitCost', { cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), }) : '' ); const isActiveFit = hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k)); patchClasses(cardEl, { 'is-fit-active': isActiveFit }); refs.cardTitle = !hasMultipleModels ? dispTitle : isActiveFit ? t('steps.fitActiveCardTitle', { title: dispTitle }) : t('steps.fitInactiveCardTitle', { text: dispText }); patchAttr(cardEl, 'title', refs.isHoveringAnomaly ? null : refs.cardTitle); cardEl.onclick = (e) => { if (!hasMultipleModels) return; if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && !isFitPooledAll) { const cardSet = new Set(cardGroupKeys); const next = isActiveFit ? effectiveFitModelKeys.filter((k) => !cardSet.has(k)) : Array.from(new Set([...effectiveFitModelKeys, ...cardGroupKeys])); fitLockedModelKeys = next.length > 0 ? next : [...cardGroupKeys]; fitUserPicked = true; fitPinnedWhileVisible = true; if (latestSlice) renderStepsData(latestSlice); return; } const isAlreadySole = !isFitPooledAll && effectiveFitModelKeys.length === cardGroupKeys.length && cardGroupKeys.every((k) => fitActiveKeySet.has(k)); if (!isAlreadySole || !fitUserPicked) { fitLockedModelKeys = [...cardGroupKeys]; fitUserPicked = true; fitPinnedWhileVisible = true; if (latestSlice) renderStepsData(latestSlice); } }; }, }); modelsScroll.refresh(); } const unsubUi = uiStore.subscribe( (st) => st.stepsSubTab, (tab) => { hideTurnTip(); hideAnomalyTip(); subTabSwitch.setValue(tab); patchAttr(anomalyFilterBarEl, 'hidden', tab !== 'steps' || !onlyAnomalies); const toolbarAllowed = latestSlice?.showStepFilterToolbar === true; patchAttr( stepsFilterToolbarEl, 'hidden', tab !== 'steps' || !toolbarAllowed || (currentTableSteps.length === 0 && !stepSearchQuery && !stepQuickChip) ); stepsExportMenu.refs.setHidden(tab !== 'steps' || currentAllConvSteps.length === 0); patchAttr(stepsScroll.el, 'hidden', tab !== 'steps'); patchAttr(modelsScroll.el, 'hidden', tab !== 'models'); if (getVisibleMonitorView() === 'steps' && latestSlice) { renderStepsData(latestSlice); } else if (tab === 'steps') { refreshStepTableViewport(); stepsScroll.refresh(); } else { modelsScroll.refresh(); } } ); const unsubTelemetry = telemetryStore.subscribe( (st) => ({ activeConversation: st.telemetry?.activeConversation, cascadeId: st.telemetry?.activeConversation?.cascadeId, recentSteps: st.telemetry?.activeConversation?.recentSteps, sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown, modelDisplayMode: normalizeModelDisplayMode( st.telemetry?.settings?.modelDisplayMode, st.telemetry?.settings?.showUpstreamModel ), showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), orchestratorIdMode: normalizeOrchestratorIdDisplayMode( st.telemetry?.settings?.orchestratorIdMode ), showStepTurnRail: st.telemetry?.settings?.showStepTurnRail === true, showStepAgentBadge: st.telemetry?.settings?.showStepAgentBadge !== false, showStepSpeedColor: st.telemetry?.settings?.showStepSpeedColor === true, showStepFilterToolbar: st.telemetry?.settings?.showStepFilterToolbar === true, stepTokenComboFormat: normalizeClientStepTokenComboFormat( st.telemetry?.settings?.stepTokenComboFormat ), stepTableColumns: st.telemetry?.settings?.stepTableColumns, experimentalModernUi: resolveSettingsModernUi(st.telemetry?.settings), }), (slice) => { latestSlice = slice; if (getVisibleMonitorView() !== 'steps') { if (!fitUserPicked) { fitPinnedWhileVisible = false; } isDirty = true; return; } isDirty = false; renderStepsData(slice, { allowNewRowFade: uiStore.getState().stepsSubTab === 'steps', }); } ); let prevScope = uiStore.getState().selectedAgentScope; let prevActiveView = getVisibleMonitorView(); const unsubView = uiStore.subscribe( (st) => ({ activeView: getVisibleMonitorView(st), selectedAgentScope: st.selectedAgentScope, }), (uiSlice) => { const scopeChanged = uiSlice.selectedAgentScope !== prevScope; if (uiSlice.selectedAgentScope !== lastSyncedUiScope) { lastSyncedUiScope = uiSlice.selectedAgentScope; selectedAgentScopes = [uiSlice.selectedAgentScope || 'all']; } const viewEntered = uiSlice.activeView === 'steps' && prevActiveView !== 'steps'; prevScope = uiSlice.selectedAgentScope; prevActiveView = uiSlice.activeView; if (uiSlice.activeView !== 'steps') { hideTurnTip(); hideAnomalyTip(); fitPinnedWhileVisible = false; if (scopeChanged) isDirty = true; return; } if ((isDirty || scopeChanged || viewEntered) && latestSlice) { isDirty = false; renderStepsData(latestSlice); } } ); const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { refreshStaticLocaleLabels(); if (getVisibleMonitorView() === 'steps' && latestSlice) { renderStepsData(latestSlice); } else { isDirty = true; } } ); onCleanup(() => { stepsExportMenu.destroy(); modelsAnalyticsPane.removeEventListener('scroll', onModelsPaneScroll); unsubUi(); unsubTelemetry(); unsubView(); unsubI18n(); stepTableWidget.destroy(); sessionLineChart.destroy?.(); modelFitChart.destroy?.(); inlineScopeSelect.destroy(); stepsModelSelect.destroy(); subTabSwitch.destroy(); lineModelSelect.destroy(); lineMetricSwitch.destroy(); fitModelSelect.destroy(); fitMetricSwitch.destroy(); stepsScroll.destroy(); modelsScroll.destroy(); }); return { el: rootEl, refs: { stepsTableEl, stepsTheadRow, stepsTbody, turnTipEl, anomalyTipEl, anomalyFilterBarEl, stepsFilterToolbarEl, stepSearchInput, stepQuickChipsEl, stepsExportMenu, modelsAnomalyStripEl, modelsListEl, inlineScopeSelect, stepsModelSelect, subTabSwitch, lineModelSelect, lineMetricSwitch, fitModelSelect, fitMetricSwitch, stepsScroll, modelsScroll, refreshStepTableViewport, }, }; }, }); return { mergeSelectedAgentUnits, StepsDetailView }; })(); // --- src/views/SettingsView.js --- const { SHOW_ACCOUNT_TAB, SettingsView } = (() => { /** * @fileoverview View 4: Modular preferences ("常规" / "结构" / "账号" / "其他"). * Orchestrates the four preference tabs * with top sub-navigation and a shared `CustomScrollbar` viewport. */ const SHOW_ACCOUNT_TAB = true; function getSettingsSubTabOptions() { return [ { value: 'general', label: t('settings.subTab.general') }, { value: 'structure', label: t('settings.subTab.structure') }, ...(SHOW_ACCOUNT_TAB ? [{ value: 'account', label: t('settings.subTab.account') }] : []), { value: 'other', label: t('settings.subTab.other') }, ]; } const SettingsView = defineComponent({ name: 'SettingsView', setup({ onCleanup }) { const initialSubTab = uiStore.getState().settingsSubTab || 'general'; const subNavSwitch = SegmentedControl({ ariaLabel: t('settings.subTab.aria'), modelValue: initialSubTab, options: getSettingsSubTabOptions(), onUpdateModelValue: (nextSubTab) => { uiStore.setState({ settingsSubTab: nextSubTab }, { sync: true }); }, }); const subNavBar = h('div', { className: 'settings-subnav-bar' }, [subNavSwitch.el]); let viewScrollbar = null; const refreshScroll = () => { if (viewScrollbar) { viewScrollbar.refresh(); } }; const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll }); const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll }); const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll }); const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll }); let showingAccount = false; let preloadedAccountOnce = false; function applyActiveSubTab(subTab, activeView) { const target = subTab === 'structure' || subTab === 'other' || (accountTab && subTab === 'account') ? subTab : 'general'; subNavSwitch.setValue(target); patchAttr(generalTab.el, 'hidden', target !== 'general'); patchAttr(structureTab.el, 'hidden', target !== 'structure'); patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure'); patchAttr(otherTab.el, 'hidden', target !== 'other'); if (accountTab) { patchAttr(accountTab.el, 'hidden', target !== 'account'); if (activeView === 'settings' && !preloadedAccountOnce) { preloadedAccountOnce = true; void accountTab.refs.preload?.(); } const nextShowingAccount = target === 'account' && activeView === 'settings'; if (nextShowingAccount && !showingAccount) void accountTab.refs.load(); showingAccount = nextShowingAccount; } refreshScroll(); } const contentContainer = h( 'div', {}, accountTab ? [generalTab.el, structureTab.el, accountTab.el, otherTab.el] : [generalTab.el, structureTab.el, otherTab.el] ); viewScrollbar = CustomScrollbar({ contentEl: contentContainer, className: 'view-pane', }); applyActiveSubTab(initialSubTab, uiStore.getState().activeView); const rootEl = h('div', { className: 'settings-view-root' }, [ subNavBar, structureTab.refs.thirdNavBar, viewScrollbar.el, ]); function syncActiveTab() { const ui = uiStore.getState(); const { settingsSubTab } = ui; if (getVisibleMonitorView(ui) !== 'settings') return; const telemetry = telemetryStore.getState().telemetry; const settings = telemetry?.settings; if (accountTab) { accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas, settings); } if (settingsSubTab === 'structure') { if (settings) { structureTab.refs.renderSettings( settings, telemetry?.windowBridge, telemetry?.hostPlatform, telemetry?.cliStatusLine, telemetry?.quotas ); } } else if (settingsSubTab === 'other') { if (settings) { otherTab.refs.renderSettings( settings, telemetry.contextWindowModels || [], telemetry?.windowBridge, telemetry?.hostPlatform, telemetry?.cloudCodeProxy ); } } else if (settingsSubTab !== 'account') { if (settings) { generalTab.refs.renderSettings( settings, telemetry?.windowBridge, telemetry?.hostPlatform ); } void generalTab.refs.loadHostI18n?.(false); if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus); } refreshScroll(); } const unsubTelemetry = telemetryStore.subscribe( (st) => ({ settings: st.telemetry?.settings, windowBridge: st.telemetry?.windowBridge, cloudCodeProxy: st.telemetry?.cloudCodeProxy, cliStatusLine: st.telemetry?.cliStatusLine, hostPlatform: st.telemetry?.hostPlatform, cloudStatus: st.telemetry?.cloudStatus, contextWindowModels: st.telemetry?.contextWindowModels, account: st.telemetry?.account, quotas: st.telemetry?.quotas, }), syncActiveTab ); const unsubUi = uiStore.subscribe( (st) => ({ activeView: getVisibleMonitorView(st), settingsSubTab: st.settingsSubTab, }), (slice) => { applyActiveSubTab(slice.settingsSubTab, slice.activeView); syncActiveTab(); } ); const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { subNavSwitch.setProps({ modelValue: uiStore.getState().settingsSubTab || 'general', options: getSettingsSubTabOptions(), }); generalTab.refs.refreshLabels(); structureTab.refs.refreshLabels(); accountTab?.refs.refreshLabels(); otherTab.refs.refreshLabels(); refreshScroll(); } ); onCleanup(() => { unsubTelemetry(); unsubUi(); unsubI18n(); subNavSwitch.destroy(); generalTab.destroy(); structureTab.destroy(); accountTab?.destroy(); otherTab.destroy(); viewScrollbar.destroy(); }); return { el: rootEl, refs: { subNavSwitch, generalTab, structureTab, accountTab, otherTab, viewScrollbar, // Convenience aliases for external callers / tests windowMountSelect: structureTab.refs.windowMountSelect, multiSessionToggle: structureTab.refs.multiSessionToggle, topbarSlotsList: structureTab.refs.topbarSlotsList, stepModelSelect: otherTab.refs.stepModelSelect, orchestratorIdSelect: otherTab.refs.orchestratorIdSelect, autoUpdateSelect: generalTab.refs.autoUpdateSelect, }, }; }, }); return { SHOW_ACCOUNT_TAB, SettingsView }; })(); // --- src/App.js --- const { App } = (() => { /** * @fileoverview Root Application Shell (App.js). * Combines the compact dual-layer header (TopSessionHeader + TopLongPillNav) * and single-viewport functional views. */ const APP_VIEW_SHORTCUT_MAP = Object.freeze({ 1: 'overview', 2: 'consumption', 3: 'steps', 4: 'settings', }); function isEditableKeyTarget(e) { const path = typeof e?.composedPath === 'function' ? e.composedPath() : null; const target = (Array.isArray(path) && path[0]) || e?.target; if (!target || typeof target !== 'object') return false; const tag = String(target.tagName || '').toUpperCase(); if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true; if (target.isContentEditable) return true; if (typeof target.getAttribute === 'function') { const ce = target.getAttribute('contenteditable'); if (ce === '' || ce === 'true') return true; } return false; } const App = defineComponent({ name: 'App', setup({ onCleanup }) { const sessionHeader = TopSessionHeader(); const topPillNav = TopLongPillNav({ modelValue: uiStore.getState().activeView, items: getViewTabs(), onUpdateModelValue: (nextView) => { uiStore.setState({ activeView: nextView }); }, }); const overviewView = LiveOverviewView(); const consumptionView = ConsumptionView(); const stepsView = StepsDetailView(); const settingsView = SettingsView(); const globalBridgeNotice = BridgeStatusNotice({ dismissible: true, }); const bannerSlotEl = h('div', { className: 'app-bridge-banner-slot', hidden: true }, [ globalBridgeNotice.el, ]); function syncGlobalBridgeBanner() { const activeView = uiStore.getState().activeView; const telemetry = telemetryStore.getState().telemetry; const settings = telemetry?.settings; const mountMode = settings ? normalizeClientWindowMountMode(settings.windowMountMode, settings.enableWindowOverlay) : 'sidebar'; const hasCtxOverrides = Boolean( settings?.modelContextWindows && Object.keys(settings.modelContextWindows).length > 0 ); const shouldOfferGlobal = !isWindowOverlayMode() && activeView !== 'settings' && (mountMode !== 'sidebar' || hasCtxOverrides); globalBridgeNotice.refs.update({ visible: shouldOfferGlobal, contextMode: mountMode === 'sidebar' && hasCtxOverrides, windowBridge: telemetry?.windowBridge || null, hostPlatform: telemetry?.hostPlatform || 'win32', }); patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden')); } const viewMap = { overview: overviewView.el, consumption: consumptionView.el, steps: stepsView.el, settings: settingsView.el, }; const stageEl = h('div', { className: 'viewport-stage' }, [ overviewView.el, consumptionView.el, stepsView.el, settingsView.el, ]); const toastMsgEl = h('span', { className: 'app-toast-msg' }); const toastDetailEl = h('span', { className: 'app-toast-detail text-mono', hidden: true }); let activeToastAction = null; let activeToastId = 0; let toastAutoTimer = null; let toastRemainingMs = 0; let toastStartedAt = 0; function clearToastTimer() { if (toastAutoTimer) { clearTimeout(toastAutoTimer); toastAutoTimer = null; } } function scheduleToastAutoClose(toastId, delayMs) { clearToastTimer(); if (!(delayMs > 0)) return; toastRemainingMs = delayMs; toastStartedAt = Date.now(); toastAutoTimer = setTimeout(() => { toastAutoTimer = null; dismissUiToast(toastId); }, delayMs); } const toastActionLabelEl = h('span'); const toastActionBtn = h( 'button', { type: 'button', className: 'app-toast-action', hidden: true, onclick: () => { const fn = activeToastAction; if (typeof fn === 'function') fn(); }, }, [createSvgIcon('folder', { size: 12 }), toastActionLabelEl] ); const toastCloseBtn = h( 'button', { type: 'button', className: 'app-toast-close', 'aria-label': t('export.closeToast'), title: t('export.closeToast'), onclick: () => dismissUiToast(activeToastId), }, [createSvgIcon('close', { size: 11 })] ); const toastEl = h( 'div', { className: 'app-toast', role: 'status', 'aria-live': 'polite', hidden: true, onMouseenter: () => { if (toastAutoTimer) { const elapsed = Date.now() - toastStartedAt; toastRemainingMs = Math.max(800, toastRemainingMs - elapsed); clearToastTimer(); } }, onMouseleave: () => { if (activeToastId && toastRemainingMs > 0 && !toastAutoTimer) { scheduleToastAutoClose(activeToastId, toastRemainingMs); } }, }, [ h('div', { className: 'app-toast-body' }, [toastMsgEl, toastDetailEl]), toastActionBtn, toastCloseBtn, ] ); function syncToastState(toast) { if (!toast || !toast.message) { clearToastTimer(); activeToastId = 0; activeToastAction = null; toastRemainingMs = 0; patchAttr(toastEl, 'hidden', true); return; } activeToastId = toast.id; activeToastAction = toast.onAction; patchText(toastMsgEl, toast.message); const hasDetail = Boolean(toast.detail); patchAttr(toastDetailEl, 'hidden', !hasDetail); if (hasDetail) { patchText(toastDetailEl, toast.detail); patchAttr(toastDetailEl, 'title', toast.detail); } const hasAction = Boolean(toast.actionLabel && typeof toast.onAction === 'function'); patchAttr(toastActionBtn, 'hidden', !hasAction); if (hasAction) { patchText(toastActionLabelEl, toast.actionLabel); } patchClasses(toastEl, { 'tone-ok': toast.tone === 'ok', 'tone-info': toast.tone === 'info', 'tone-warn': toast.tone === 'warn', }); patchAttr(toastEl, 'hidden', false); scheduleToastAutoClose(toast.id, toast.durationMs); } const shellEl = h( 'main', { className: 'app-shell', tabIndex: -1, onKeydown: (e) => { if (!e || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return; if (isEditableKeyTarget(e)) return; const key = String(e.key || ''); const mappedView = APP_VIEW_SHORTCUT_MAP[key]; if (mappedView) { e.preventDefault(); if (uiStore.getState().activeView !== mappedView) { uiStore.setState({ activeView: mappedView }); } return; } if (key === 'r' || key === 'R') { e.preventDefault(); void fetchTelemetry({ force: true }); return; } if (key === '/') { e.preventDefault(); sessionHeader.refs?.convSelect?.openAndFocusSearch?.(); } }, }, [ h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]), bannerSlotEl, stageEl, toastEl, ] ); function syncStepsBadge() { const uiSt = uiStore.getState(); const scopeForBadge = uiSt.activeView === 'steps' ? uiSt.selectedAgentScope : 'all'; const { scopedConv } = resolveScopedConversation( telemetryStore.getState().telemetry, scopeForBadge, uiSt.ctxInspectorAgentId ); const stepCount = scopedConv?.stepCount ?? 0; topPillNav.setProps({ items: getViewTabs().map((tabItem) => tabItem.value === 'steps' ? { ...tabItem, badge: stepCount > 0 ? stepCount : '' } : tabItem ), }); } const unsubUi = uiStore.subscribe( (st) => st.activeView, (activeView) => { topPillNav.setValue(activeView); for (const [key, paneEl] of Object.entries(viewMap)) { patchAttr(paneEl, 'hidden', key !== activeView); } if (activeView === 'overview') { overviewView.refs?.viewScrollbar?.refresh(); } else if (activeView === 'consumption') { consumptionView.refs?.viewScrollbar?.refresh(); } else if (activeView === 'steps') { stepsView.refs?.refreshStepTableViewport?.(); stepsView.refs?.stepsScroll?.refresh(); stepsView.refs?.modelsScroll?.refresh(); } else if (activeView === 'settings') { settingsView.refs?.viewScrollbar?.refresh(); } syncStepsBadge(); syncGlobalBridgeBanner(); } ); let syncedSettingsCtxMode = null; function syncContextAgentModeFromSettings(settings) { if (!settings || typeof settings !== 'object') return; const nextMode = getDefaultCtxInspectorAgentId(settings); if (nextMode === syncedSettingsCtxMode) return; const prevSynced = syncedSettingsCtxMode; syncedSettingsCtxMode = nextMode; const curCtx = uiStore.getState().ctxInspectorAgentId; if (prevSynced !== null || curCtx === 'main' || curCtx === 'auto') { if (curCtx !== nextMode) { uiStore.setState({ ctxInspectorAgentId: nextMode }); } } } syncContextAgentModeFromSettings(telemetryStore.getState().telemetry?.settings); const unsubStepCount = telemetryStore.subscribe( (st) => ({ stepCount: st.telemetry?.activeConversation?.stepCount ?? 0, totalStepsAllAgents: st.telemetry?.activeConversation?.totalStepsAllAgents ?? 0, subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0, windowMountMode: st.telemetry?.settings?.windowMountMode, enableWindowOverlay: st.telemetry?.settings?.enableWindowOverlay, contextAgentMode: st.telemetry?.settings?.contextAgentMode, modelContextWindows: st.telemetry?.settings?.modelContextWindows, windowBridge: st.telemetry?.windowBridge, hostPlatform: st.telemetry?.hostPlatform, }), () => { syncContextAgentModeFromSettings(telemetryStore.getState().telemetry?.settings); syncStepsBadge(); syncGlobalBridgeBanner(); } ); const unsubScopeBadge = uiStore.subscribe( (st) => st.selectedAgentScope, () => syncStepsBadge() ); const unsubToast = uiStore.subscribe( (st) => st.toast, (toast) => syncToastState(toast) ); syncToastState(uiStore.getState().toast); const unsubI18n = i18nStore.subscribe( (st) => st.locale, () => { syncStepsBadge(); globalBridgeNotice.refs.refreshLabels(); patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden')); patchAttr(toastCloseBtn, 'aria-label', t('export.closeToast')); patchAttr(toastCloseBtn, 'title', t('export.closeToast')); } ); onCleanup(() => { clearToastTimer(); unsubUi(); unsubStepCount(); unsubScopeBadge(); unsubToast(); unsubI18n(); globalBridgeNotice.destroy(); sessionHeader.destroy(); topPillNav.destroy(); overviewView.destroy(); consumptionView.destroy(); stepsView.destroy(); settingsView.destroy(); }); return { el: shellEl, refs: { sessionHeader, topPillNav, globalBridgeNotice, toastEl, toastActionBtn, overviewView, consumptionView, stepsView, settingsView, }, }; }, }); return { App }; })(); // --- src/components/layout/overlayHostAnchors.js --- const { CAPSULE_HOST_ID, PORTAL_HOST_ID, computeCapsuleLayoutMode, isImmediatelyBeforeNode, isIdeExtensionChatFrame, resolveActiveDockTarget, findNativeTopRightAnchor, getLeftSidebarRightEdge, attachShadowStyles } = (() => { /** * @fileoverview Host IDE/Desktop titlebar & composer button anchor discovery, * 4-stage responsive capsule hysteresis, and shared ShadowRoot CSSStyleSheet mounting * extracted from WindowOverlayShell.js. */ const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule'; const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; /** * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 * 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊; * 当槽位数超过 3 个(4..5 槽)时自动按槽位增量上浮 `wide` 阈值。 * * @param {number} availWidth * @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode * @param {{ showMulti?: boolean, hasUpdate?: boolean, slotCount?: number }} [options] * @returns {'wide'|'compact'|'minimal'|'ring-only'} */ function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) { if (availWidth == null || Number.isNaN(availWidth)) return 'wide'; const showMulti = options?.showMulti !== false; const updateReserve = options?.hasUpdate ? 52 : 0; const slotCount = Number(options?.slotCount || 3); const extraSlotWidth = slotCount > 3 ? (slotCount - 3) * 58 : 0; const wideKeep = 256 + extraSlotWidth; const wideEnter = 272 + extraSlotWidth; const baseEffWidth = showMulti ? availWidth : availWidth + 76; const effWidth = baseEffWidth - updateReserve; if (currentMode === 'wide') { if (baseEffWidth < 78) return 'ring-only'; if (effWidth < 196) return 'minimal'; if (effWidth < wideKeep) return 'compact'; return 'wide'; } if (currentMode === 'compact') { if (effWidth >= wideEnter) return 'wide'; if (baseEffWidth < 78) return 'ring-only'; if (effWidth < 196) return 'minimal'; return 'compact'; } if (currentMode === 'minimal') { if (effWidth >= wideEnter) return 'wide'; if (effWidth >= 212) return 'compact'; if (baseEffWidth < 78) return 'ring-only'; return 'minimal'; } if (effWidth >= wideEnter) return 'wide'; if (effWidth >= 212) return 'compact'; if (baseEffWidth >= 92) return 'minimal'; return 'ring-only'; } function findIdeWorkbenchTitlebar() { try { if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { return null; } const workbench = document.querySelector('.monaco-workbench'); if (!workbench?.querySelector) return null; const partTitlebar = workbench.querySelector('.part.titlebar'); if (!partTitlebar?.querySelector) return null; if (partTitlebar.getBoundingClientRect) { const pr = partTitlebar.getBoundingClientRect(); if (pr.width <= 0 || pr.height <= 0) return null; } const container = partTitlebar.querySelector(':scope > .titlebar-container') || partTitlebar.querySelector('.titlebar-container'); const rightGroup = container?.querySelector?.(':scope > .titlebar-right') || container?.querySelector?.('.titlebar-right'); if (!container || !rightGroup) return null; const actionToolbar = rightGroup.querySelector?.(':scope > .action-toolbar-container') || rightGroup.querySelector?.('.action-toolbar-container') || null; return { kind: 'ide-titlebar', workbench, titlebar: container, targetContainer: rightGroup, actionToolbar, }; } catch { return null; } } function findHostTitlebar() { try { if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { return null; } const tb = document.querySelector('[class*="@container/titlebar"]'); if (tb?.getBoundingClientRect) { const r = tb.getBoundingClientRect(); if (r.width <= 0 || r.height <= 0) return null; } return tb; } catch { return null; } } const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR = '.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]'; const COMPOSER_MODEL_LABEL_RE = /\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; const COMPOSER_MODEL_ATTR_RE = /\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i; const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i; const COMPOSER_MODE_TEXT_RE = /^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|planning|act|review|confirm|normal|fast|自动|询问|始终询问|手动|始终允许|受控|规划|快速)(?:\s*(?:mode|模式))?$/i; const COMPOSER_MODE_ATTR_RE = /\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i; const COMPOSER_ICON_FONT_CLASS_RE = /\b(?:codicon|material-symbols(?:-\w+)?|material-icons(?:-\w+)?|lucide(?:-\w+)?)\b/i; function querySimpleSelectorList(root, selectors) { if (!root || typeof root.querySelectorAll !== 'function') return []; const seen = new Set(); const out = []; for (const sel of selectors) { let list = []; try { list = root.querySelectorAll(sel) || []; } catch { list = []; } for (const item of list) { if (item && !seen.has(item)) { seen.add(item); out.push(item); } } } return out; } function extractVisibleButtonText(node, isRoot = true) { if (!node) return ''; const tag = String(node.tagName || node.nodeName || '').toLowerCase(); if (tag === 'svg' || tag === 'style' || tag === 'script') return ''; if (!isRoot) { if (node.getAttribute?.('aria-hidden') === 'true') return ''; const cls = String(node.className || ''); if (cls && COMPOSER_ICON_FONT_CLASS_RE.test(cls)) return ''; } if (tag === '#text' || node.nodeType === 3) { return String(node.nodeValue ?? node.textContent ?? ''); } const childNodes = node.childNodes || node.children; if (!childNodes || childNodes.length === 0) { return String(node.textContent || ''); } let acc = ''; for (const ch of childNodes) { acc += ` ${extractVisibleButtonText(ch, false)}`; } return acc; } function cleanComposerButtonText(btn) { const raw = extractVisibleButtonText(btn, true) .replace(/[\u200B-\u200D\uFEFF]/g, '') .replace(/\s+/g, ' ') .trim(); if (!raw) return ''; return raw.replace(/^[⌃⌄▾▴∨∧^<>›‹+\s]+|[⌃⌄▾▴∨∧^<>›‹\s]+$/g, '').trim(); } function isComposerModelButtonItem(item) { if (!item) return false; if (item.cleanText && COMPOSER_MODEL_LABEL_RE.test(item.cleanText)) return true; if (item.attrText && COMPOSER_MODEL_ATTR_RE.test(item.attrText)) return true; return false; } function hasExcludedComposerAncestor(el) { if (!el) return false; if (typeof el.closest === 'function') { try { if (el.closest(COMPOSER_EXCLUDED_ANCESTOR_SELECTOR)) return true; } catch { // 忽略选择器异常并回退祖先链遍历 } } let cur = el.parentElement || el.parentNode; while (cur) { const cls = String(cur.className || ''); if ( cls.includes('@container/titlebar') || cls.includes('quick-input-widget') || cls.includes('suggest-widget') || cls.includes('find-widget') || cls.includes('scm-editor') || cls.includes('search-view') || (cls.includes('part') && (cls.includes('titlebar') || cls.includes('statusbar'))) ) { return true; } cur = cur.parentElement || cur.parentNode; } return false; } function isNodeHiddenByStyle(el) { if (!el) return true; if (el.hasAttribute?.('hidden') || el.getAttribute?.('aria-hidden') === 'true') return true; if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { try { const cs = window.getComputedStyle(el); if (cs?.display === 'none' || cs?.visibility === 'hidden') return true; } catch { // 忽略样式读取异常 } } return false; } function getInFlowHostChildren(container, capsuleNode, portalNode) { const rawChildren = container?.children || []; const out = []; for (const ch of rawChildren) { if (!ch || ch === capsuleNode || ch === portalNode) continue; if (ch.id === CAPSULE_HOST_ID || ch.id === PORTAL_HOST_ID) continue; if (ch.hasAttribute?.('hidden')) continue; if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { try { const cs = window.getComputedStyle(ch); if (cs?.display === 'none') continue; if (cs?.position === 'absolute' || cs?.position === 'fixed') continue; } catch { // 忽略计算样式异常 } } out.push(ch); } return out; } function isHorizontalFlexContainer(el) { if (!el) return false; const cls = String(el.className || ''); if (/\b(?:inline-)?flex\b/.test(cls) && !/\bflex-col\b/.test(cls)) return true; if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { try { const cs = window.getComputedStyle(el); const disp = String(cs?.display || ''); const dir = String(cs?.flexDirection || 'row'); if (disp.includes('flex') && !dir.startsWith('column')) return true; } catch { // 忽略计算样式异常 } } return false; } function isSpaceDistributedFlexContainer(el) { if (!el) return false; const cls = String(el.className || ''); if (/\bjustify-(?:between|around|evenly)\b/.test(cls)) return true; if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { try { const jc = String(window.getComputedStyle(el)?.justifyContent || ''); if (jc.includes('space-between') || jc.includes('space-around') || jc.includes('space-evenly')) { return true; } } catch { // 忽略计算样式异常 } } return false; } function buildComposerDockDescriptor(autoBtn, composerCard, bottomRowBtns, capsuleNode, portalNode, patchedNode) { if (!autoBtn || !composerCard) return null; let item = autoBtn; while ( (item.parentElement || item.parentNode) && (item.parentElement || item.parentNode) !== composerCard && (item.parentElement || item.parentNode) !== document.body ) { const parent = item.parentElement || item.parentNode; const hostSiblings = getInFlowHostChildren(parent, capsuleNode, portalNode); if (hostSiblings.length >= 2) break; const grandParent = parent.parentElement || parent.parentNode; const parentCls = String(parent.className || ''); const parentInlineMl = String(parent.style?.marginLeft || '').trim(); const isSingleClusterInSplitRow = !/\b(?:relative|ml-auto|ms-auto)\b/.test(parentCls) && parentInlineMl !== 'auto' && isHorizontalFlexContainer(parent) && grandParent && isSpaceDistributedFlexContainer(grandParent) && getInFlowHostChildren(grandParent, capsuleNode, portalNode).length >= 2; if (isSingleClusterInSplitRow) { break; } item = parent; } const anchorNode = item; const targetContainer = anchorNode.parentElement || anchorNode.parentNode; if (!targetContainer) return null; const hostChildren = getInFlowHostChildren(targetContainer, capsuleNode, portalNode); const anchorIdx = hostChildren.indexOf(anchorNode); const isFirstHostChild = anchorIdx <= 0; let needsAutoMarginTransfer = false; let patchMarginNode = null; if (!isFirstHostChild) { const cls = String(anchorNode.className || ''); const inlineMl = String(anchorNode.style?.marginLeft || '').trim(); let computedLargeMl = false; if ( patchedNode !== anchorNode && typeof window !== 'undefined' && typeof window.getComputedStyle === 'function' ) { try { const mlPx = parseFloat(window.getComputedStyle(anchorNode)?.marginLeft) || 0; const prevSib = hostChildren[anchorIdx - 1]; const aRect = anchorNode.getBoundingClientRect?.(); const pRect = prevSib?.getBoundingClientRect?.(); if (mlPx > 24 && aRect && pRect && aRect.left - pRect.right >= mlPx - 6) { computedLargeMl = true; } } catch { // 忽略边距测量异常 } } if ( /\b(?:ml-auto|ms-auto)\b/.test(cls) || inlineMl === 'auto' || patchedNode === anchorNode || computedLargeMl ) { needsAutoMarginTransfer = true; patchMarginNode = anchorNode; } else if (isSpaceDistributedFlexContainer(targetContainer)) { needsAutoMarginTransfer = true; } } const autoRect = anchorNode.getBoundingClientRect?.() || autoBtn.getBoundingClientRect?.(); let leftClusterRightEdge = 0; if (autoRect && Array.isArray(bottomRowBtns)) { for (const entry of bottomRowBtns) { if (entry.btn === autoBtn || anchorNode.contains?.(entry.btn)) continue; if (entry.rect.left < autoRect.left - 2 && entry.rect.right <= autoRect.left + 4) { if (entry.rect.right > leftClusterRightEdge) { leftClusterRightEdge = entry.rect.right; } } } } return { kind: 'composer', workbench: null, titlebar: composerCard, targetContainer, actionToolbar: patchMarginNode, anchorNode, needsAutoMarginTransfer, leftClusterRightEdge, }; } function buildComposerRightEndDockDescriptor( leftAnchorBtn, composerCard, bottomRowBtns, capsuleNode, portalNode ) { if (!leftAnchorBtn || !composerCard) return null; const cardRect = composerCard.getBoundingClientRect?.(); const minRowWidth = cardRect && cardRect.width > 0 ? cardRect.width * 0.65 : 180; let toolbarRow = null; let cur = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode; for (let d = 0; d < 8 && cur && cur !== composerCard && cur !== document.body; d += 1) { const r = cur.getBoundingClientRect?.(); if (r && r.width >= minRowWidth && r.height > 0 && r.height <= 60 && isHorizontalFlexContainer(cur)) { toolbarRow = cur; break; } cur = cur.parentElement || cur.parentNode; } if (!toolbarRow) { const p = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode; if (!p || !isHorizontalFlexContainer(p)) return null; toolbarRow = p; } let leftClusterRightEdge = 0; if (Array.isArray(bottomRowBtns)) { for (const entry of bottomRowBtns) { if (entry?.rect?.right > leftClusterRightEdge) { leftClusterRightEdge = entry.rect.right; } } } const rowChildren = getInFlowHostChildren(toolbarRow, capsuleNode, portalNode); const lastChild = rowChildren.length >= 2 ? rowChildren[rowChildren.length - 1] : null; if ( lastChild && !lastChild.contains?.(leftAnchorBtn) && isHorizontalFlexContainer(lastChild) && getInFlowHostChildren(lastChild, capsuleNode, portalNode).length === 0 ) { return { kind: 'composer', workbench: null, titlebar: composerCard, targetContainer: lastChild, actionToolbar: null, anchorNode: null, needsAutoMarginTransfer: false, leftClusterRightEdge, }; } return { kind: 'composer', workbench: null, titlebar: composerCard, targetContainer: toolbarRow, actionToolbar: null, anchorNode: null, needsAutoMarginTransfer: true, leftClusterRightEdge, }; } function collectComposerBottomButtons(container, editorEl, editorRect, capsuleNode, portalNode) { const rawBtns = querySimpleSelectorList(container, ['button', '[role="button"]', '[aria-haspopup]']); const hostBtns = []; for (const btn of rawBtns) { if (!btn || btn === editorEl || editorEl?.contains?.(btn)) continue; if (editorEl && btn.contains?.(editorEl)) continue; if ( btn.id === CAPSULE_HOST_ID || btn.id === PORTAL_HOST_ID || capsuleNode?.contains?.(btn) || portalNode?.contains?.(btn) ) { continue; } if (isNodeHiddenByStyle(btn)) continue; // 仅排除嵌套在真实紧凑按钮内部的图标/子触发器,避免外层卡片级 role="button" 误杀工具栏按钮 let nestedInBtn = false; let p = btn.parentElement || btn.parentNode; while (p && p !== container) { const pTag = String(p.tagName || '').toLowerCase(); if (pTag === 'button') { nestedInBtn = true; break; } if ( (p.getAttribute?.('role') === 'button' || p.hasAttribute?.('aria-haspopup')) && !(editorEl && p.contains?.(editorEl)) ) { const pr = p.getBoundingClientRect?.(); if (pr && pr.height > 0 && pr.height <= 48 && pr.width > 0 && pr.width <= 360) { nestedInBtn = true; break; } } p = p.parentElement || p.parentNode; } if (nestedInBtn) continue; const br = btn.getBoundingClientRect?.(); if (!br || br.width <= 0 || br.height <= 0 || br.height > 48) continue; const centerY = (br.top + br.bottom) / 2; if (editorRect && centerY < editorRect.top - 4) continue; hostBtns.push({ btn, rect: br, centerY, centerX: (br.left + br.right) / 2, cleanText: cleanComposerButtonText(btn), attrText: `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(), }); } if (hostBtns.length === 0) return []; let maxCenterY = -Infinity; for (const item of hostBtns) { if (item.centerY > maxCenterY) maxCenterY = item.centerY; } const bottomBand = hostBtns.filter((item) => Math.abs(item.centerY - maxCenterY) <= 22); bottomBand.sort((a, b) => a.rect.left - b.rect.left); return bottomBand; } function pickAutoButtonFromRow(bottomRowBtns, containerRect, options = undefined) { if (!Array.isArray(bottomRowBtns) || bottomRowBtns.length === 0) return null; const requireModelForFallback = Boolean(options?.requireModelForFallback); const rightSplitX = containerRect ? containerRect.left + containerRect.width * 0.35 : 0; const rightFirst = [ ...bottomRowBtns.filter((b) => b.centerX >= rightSplitX), ...bottomRowBtns.filter((b) => b.centerX < rightSplitX), ]; // Tier 1: 精确文本 Auto / 自动 匹配 for (const item of rightFirst) { if (COMPOSER_MODE_EXACT_RE.test(item.cleanText)) { return { btn: item.btn, tier: 1 }; } } // Tier 2: 执行/权限模式文案或无障碍语义属性匹配(排除模型选择器按钮) for (const item of rightFirst) { if (isComposerModelButtonItem(item)) continue; if ( (item.cleanText && COMPOSER_MODE_TEXT_RE.test(item.cleanText)) || (item.attrText && COMPOSER_MODE_ATTR_RE.test(item.attrText)) ) { return { btn: item.btn, tier: 2 }; } } const hasModelBtn = bottomRowBtns.some(isComposerModelButtonItem); // Tier 3: 几何右簇首按钮兜底(适配 Antigravity IDE 无 Auto 按钮、右侧为发送/语音按钮的输入栏布局) if (bottomRowBtns.length >= 2 && (!requireModelForFallback || hasModelBtn)) { let maxGap = -Infinity; let splitIdx = -1; for (let i = 1; i < bottomRowBtns.length; i += 1) { const gap = bottomRowBtns[i].rect.left - bottomRowBtns[i - 1].rect.right; if (gap > maxGap) { maxGap = gap; splitIdx = i; } } if (splitIdx >= 1 && maxGap >= 16) { return { btn: bottomRowBtns[splitIdx].btn, tier: 3 }; } } // Tier 4: 输入为空时若右侧发送按钮暂时隐藏、仅左侧存在模型选择器按钮,停靠至工具栏最右侧 if (hasModelBtn && containerRect && containerRect.width >= 200) { const lastItem = bottomRowBtns[bottomRowBtns.length - 1]; if (lastItem.rect.right <= containerRect.left + containerRect.width * 0.72) { return { btn: null, leftAnchorBtn: lastItem.btn, tier: 4 }; } } return null; } function resolveComposerEditorRect(ed) { const er = ed?.getBoundingClientRect?.(); if (er && er.width >= 80 && er.height >= 12) return er; let cur = ed; for (let d = 0; d < 6 && cur; d += 1) { if (String(cur.className || '').includes('monaco-editor')) { const mr = cur.getBoundingClientRect?.(); if (mr && mr.width >= 80 && mr.height >= 12) return mr; break; } cur = cur.parentElement || cur.parentNode; } return er || null; } function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patchedNode = null) { try { if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') { return null; } const capEl = capsuleNode || document.getElementById?.(CAPSULE_HOST_ID) || null; const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null; const activeRouteId = extractHostRouteCascadeId(); // 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏和 Auto / 右簇发送按钮 const rawEditors = querySimpleSelectorList(document, [ 'textarea', '[contenteditable]', '[role="textbox"]', '[data-lexical-editor]', '.ProseMirror', '.monaco-editor', ]); const scoredEditors = []; for (const ed of rawEditors) { if (!ed || capEl?.contains?.(ed) || porEl?.contains?.(ed)) continue; if (ed.hasAttribute?.('contenteditable')) { const ce = String(ed.getAttribute('contenteditable') || '').trim().toLowerCase(); if (ce === 'false' && ed.getAttribute?.('role') !== 'textbox') continue; } if (isNodeHiddenByStyle(ed) || hasExcludedComposerAncestor(ed)) continue; const er = resolveComposerEditorRect(ed); if (!er || er.width < 100 || er.height < 12 || er.height > 540) continue; let score = Math.min(1200, er.width) + Math.max(0, er.bottom) * 0.2; if (activeRouteId) { let anc = ed.parentElement || ed.parentNode; while (anc) { const cid = anc.getAttribute?.('data-cascade-id'); if (cid) { score += cid === activeRouteId ? 4000 : -2000; break; } anc = anc.parentElement || anc.parentNode; } } if ( document.activeElement && (ed === document.activeElement || ed.contains?.(document.activeElement)) ) { score += 1000; } scoredEditors.push({ ed, rect: er, score }); } scoredEditors.sort((a, b) => b.score - a.score); for (const { ed, rect: er } of scoredEditors) { const isMonacoCandidate = String(ed.className || '').includes('monaco-editor') || String(ed.className || '').includes('inputarea'); let tier3Candidate = null; let tier4Candidate = null; let cur = ed.parentElement || ed.parentNode; for (let depth = 0; depth < 18 && cur; depth += 1) { if (cur === document.body || cur === document.documentElement) break; const tag = String(cur.tagName || '').toLowerCase(); if (tag === 'main' || String(cur.className || '').includes('monaco-workbench')) break; const cr = cur.getBoundingClientRect?.(); if (cr && cr.height > 680) break; if (cr && cr.width >= 180 && cr.height > 0) { const bottomRowBtns = collectComposerBottomButtons(cur, ed, er, capEl, porEl); const picked = pickAutoButtonFromRow(bottomRowBtns, cr, { requireModelForFallback: isMonacoCandidate, }); if (picked) { if (picked.tier <= 2) { const desc = buildComposerDockDescriptor( picked.btn, cur, bottomRowBtns, capEl, porEl, patchedNode ); if (desc) return desc; } else if (picked.tier === 3 && !tier3Candidate) { tier3Candidate = { btn: picked.btn, card: cur, bottomRowBtns }; } else if (picked.tier === 4 && !tier4Candidate) { tier4Candidate = { leftAnchorBtn: picked.leftAnchorBtn, card: cur, bottomRowBtns }; } } } cur = cur.parentElement || cur.parentNode; } if (tier3Candidate) { const desc = buildComposerDockDescriptor( tier3Candidate.btn, tier3Candidate.card, tier3Candidate.bottomRowBtns, capEl, porEl, patchedNode ); if (desc) return desc; } if (tier4Candidate) { const desc = buildComposerRightEndDockDescriptor( tier4Candidate.leftAnchorBtn, tier4Candidate.card, tier4Candidate.bottomRowBtns, capEl, porEl ); if (desc) return desc; } } // 2. 兜底路径:编辑器自定义封装或暂时只读时,直接扫描底部包含模型选择器或 Auto 按钮的输入工具栏 const vh = Number(window.innerHeight || 800); const allBtns = querySimpleSelectorList(document, ['button', '[role="button"]', '[aria-haspopup]']); let modelToolbarFallback = null; for (const btn of allBtns) { if (!btn || capEl?.contains?.(btn) || porEl?.contains?.(btn)) continue; if (isNodeHiddenByStyle(btn) || hasExcludedComposerAncestor(btn)) continue; const br = btn.getBoundingClientRect?.(); if (!br || br.width <= 0 || br.height <= 0 || br.height > 48 || br.top < vh * 0.2) continue; const clean = cleanComposerButtonText(btn); const attr = `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(); const itemProbe = { cleanText: clean, attrText: attr }; const isModeBtn = COMPOSER_MODE_EXACT_RE.test(clean) || (!isComposerModelButtonItem(itemProbe) && ((clean && COMPOSER_MODE_TEXT_RE.test(clean)) || (attr && COMPOSER_MODE_ATTR_RE.test(attr)))); const isModelBtn = isComposerModelButtonItem(itemProbe); if (!isModeBtn && !isModelBtn) continue; let cur = btn.parentElement || btn.parentNode; for (let depth = 0; depth < 12 && cur; depth += 1) { if (cur === document.body || cur === document.documentElement) break; if (String(cur.className || '').includes('monaco-workbench')) break; const cr = cur.getBoundingClientRect?.(); if (!cr || cr.height > 560) break; if (cr.width >= 200) { const rowBtns = collectComposerBottomButtons(cur, null, null, capEl, porEl); if (isModeBtn) { const hasModelSibling = rowBtns.some((b) => b.btn !== btn && isComposerModelButtonItem(b)); if (hasModelSibling) { const desc = buildComposerDockDescriptor(btn, cur, rowBtns, capEl, porEl, patchedNode); if (desc) return desc; } } else if (isModelBtn && !modelToolbarFallback) { const picked = pickAutoButtonFromRow(rowBtns, cr, { requireModelForFallback: true }); if (picked) { const desc = picked.tier <= 3 && picked.btn ? buildComposerDockDescriptor(picked.btn, cur, rowBtns, capEl, porEl, patchedNode) : picked.tier === 4 && picked.leftAnchorBtn ? buildComposerRightEndDockDescriptor( picked.leftAnchorBtn, cur, rowBtns, capEl, porEl ) : null; if (desc) { if (picked.tier <= 2) return desc; modelToolbarFallback = desc; break; } } } } cur = cur.parentElement || cur.parentNode; } } if (modelToolbarFallback) return modelToolbarFallback; } catch { // 忽略输入框探测异常 } return null; } function isImmediatelyBeforeNode(node, refNode) { if (!node || !refNode) return false; if (node.nextElementSibling !== undefined) { return node.nextElementSibling === refNode; } if (node.nextSibling !== undefined) { return node.nextSibling === refNode; } const parent = node.parentElement || node.parentNode; if (!parent?.children) return false; const idx = Array.prototype.indexOf.call(parent.children, node); return idx >= 0 && parent.children[idx + 1] === refNode; } function isIdeExtensionChatFrame() { try { if (typeof window === 'undefined') return false; if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true; return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || '')); } catch { return false; } } function resolveActiveDockTarget(options = undefined) { const settings = telemetryStore.getState().telemetry?.settings; const rawMode = settings?.windowMountMode ?? readInjectedWindowBridge()?.mountMode; const mountMode = options?.mountMode || normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay); if (isIdeExtensionChatFrame()) { if (mountMode !== 'composer') return null; return findHostComposerAutoTarget( options?.capsuleNode || null, options?.portalNode || null, options?.patchedNode || null ); } if (mountMode === 'composer') { const composerTarget = findHostComposerAutoTarget( options?.capsuleNode || null, options?.portalNode || null, options?.patchedNode || null ); if (composerTarget) return composerTarget; } const ideTarget = findIdeWorkbenchTitlebar(); if (ideTarget) return ideTarget; const titlebar = findHostTitlebar(); if (!titlebar) return null; let targetContainer = titlebar; try { const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild; if (rightGroup && rightGroup !== titlebar.firstElementChild) { targetContainer = rightGroup; } } catch { // 忽略子选择器不兼容场景 } return { kind: 'flow', workbench: null, titlebar, targetContainer, actionToolbar: null, }; } function findNativeTopRightAnchor() { try { if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { return null; } const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]'); if (auxToggle?.closest) { return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle; } const candidates = document.querySelectorAll('button, a, [role="button"]'); for (const btn of candidates) { const text = String(btn.textContent || '').trim(); if ( (text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) && btn.getBoundingClientRect?.().top < 52 ) { return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn; } } return document.querySelector('div.absolute.right-0.top-0'); } catch { return null; } } function getLeftSidebarRightEdge(vw) { try { if (typeof document !== 'undefined' && typeof document.querySelector === 'function') { if (document.querySelector('.monaco-workbench')) { return 0; } const navEl = document.querySelector('div[role="navigation"]'); if (navEl?.getBoundingClientRect) { const nr = navEl.getBoundingClientRect(); if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) { return Math.ceil(nr.right); } } } } catch { // 忽略侧栏测量异常 } return 0; } /** * 在主窗口挂载双栖顶栏胶囊和完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 */ const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([ 'src/styles/views-overview.css', 'src/styles/views-consumption.css', 'src/styles/views-tables.css', 'src/styles/views-settings.css', 'src/styles/controls.css', ]); let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null }; function buildSlimCapsuleCss(fullCss) { if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss; return fullCss .split(/(?=\/\* --- src\/styles\/)/) .filter((block) => { const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//); return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]); }) .join(''); } function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) { if (!shadowRoot) return; if ( fullCss && typeof CSSStyleSheet === 'function' && Array.isArray(shadowRoot.adoptedStyleSheets) ) { try { if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) { const sheet = new CSSStyleSheet(); sheet.replaceSync(fullCss); sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet }; } shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet]; return; } catch { // 降级到传统