diff --git a/.gitignore b/.gitignore index 524df6a..e9cd78b 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ usage-monitor.zip .account-test-* .DS_Store Thumbs.db +docs/ diff --git a/plugin.json b/plugin.json index a65a10c..8ce64a6 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "usage-monitor", "displayName": "Usage & Speed Monitor", - "version": "1.5.3", + "version": "1.5.4", "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "logo": "assets/logo.svg", "suggestedPrompts": [ diff --git a/pricing-catalog.json b/pricing-catalog.json index 3c9697f..0f27733 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.21.1", - "updatedAt": "2026-11-21T00:35:00+09:00", - "latestPluginVersion": "1.5.3", + "catalogVersion": "2026.11.21.3", + "updatedAt": "2026-11-21T14:35:00+09:00", + "latestPluginVersion": "1.5.4", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", "archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main", @@ -13,6 +13,12 @@ "orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-pro-orchestrator-neon": { "input": 3.00, "cache": 0.15, "output": 15.0, "short": "orch-neon", "family": "Gemini" }, "orchestrator-neon": { "input": 3.00, "cache": 0.15, "output": 15.0, "short": "orch-neon", "family": "Gemini" }, + "orchestrator-worker-neon": { "input": 3.00, "cache": 0.15, "output": 15.0, "short": "neon-4", "family": "Gemini" }, + "gemini-neon-worker-agy": { "input": 3.00, "cache": 0.15, "output": 15.0, "short": "neon-4", "family": "Gemini" }, + "gemini-4-neon-worker-agy": { "input": 3.00, "cache": 0.15, "output": 15.0, "short": "neon-4", "family": "Gemini" }, + "orchestrator-opus-5-5": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "orch-opus-5.5", "family": "Claude" }, + "orchestrator-claude-opus-5-5": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "orch-opus-5.5", "family": "Claude" }, + "claude-opus-5-5-orchestrator": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "orch-opus-5.5", "family": "Claude" }, "gemini-4-carbon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-high", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-carbon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-carbon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-low", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 3beaf73..8b0b961 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2,7 +2,7 @@ 'use strict'; // --- shared/settings-normalization.mjs --- -const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi } = (() => { +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, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -33,6 +33,7 @@ const TOPBAR_SLOT_KEYS = Object.freeze([ 'quota_auto', 'gemini_5h', 'gemini_weekly', + 'argon_weekly', 'claude_5h', 'claude_weekly', ]); @@ -41,6 +42,21 @@ 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', @@ -341,6 +357,69 @@ function normalizeTopbarCapsuleSlots(raw) { 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 项)。 * @@ -469,6 +548,37 @@ function normalizeModernUi(val) { return Boolean(val); } +const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']); +const DEFAULT_CONTEXT_AGENT_MODE = 'main'; + +/** + * 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'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`)。 * @@ -482,11 +592,11 @@ function normalizeExperimentalModernUi(val) { } return Boolean(val); } -return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi }; +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, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- -const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { +const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { /** * @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。 */ @@ -585,8 +695,40 @@ function formatCompactCapsuleTtft(ttftSec) { 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 || '')); +} + /** - * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 + * 判断当前配额摘要中是否存在独立的 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 @@ -603,8 +745,9 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (activePool && Number.isFinite(Number(activePool.remainingPct))) { candidates.push(Number(activePool.remainingPct)); } - if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { - candidates.push(Number(activePool.weeklyRemainingPct)); + const activeWk = readPoolWeeklyRemainingPct(activePool); + if (activeWk != null) { + candidates.push(activeWk); } if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { candidates.push(Number(weekly.remainingPct)); @@ -612,15 +755,24 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (!candidates.length && pools.length > 0) { for (const p of pools) { if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); - if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { - candidates.push(Number(p.weeklyRemainingPct)); - } + 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; @@ -629,11 +781,11 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const claudePool = pools.find((p) => p?.poolKey === 'Claude & GPT') || pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + 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 ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } } else { @@ -647,12 +799,12 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const geminiFamilyPools = pools.filter((p) => /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + const primaryCand = isWeekly ? readPoolWeeklyRemainingPct(stdGemini) : stdGemini?.remainingPct; if (primaryCand != null && Number.isFinite(Number(primaryCand))) { rawPct = Number(primaryCand); } else { const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .map((p) => (isWeekly ? readPoolWeeklyRemainingPct(p) : p?.remainingPct)) .filter((v) => v != null && Number.isFinite(Number(v))) .map(Number); if (familyVals.length > 0) { @@ -661,7 +813,7 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { activePool && !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } if ( @@ -730,7 +882,7 @@ function scaleBucketsExact(buckets, keys, targetTotal) { } return out; } -return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; +return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; })(); // --- shared/window-bridge-protocol.mjs --- @@ -765,6 +917,23 @@ const BRIDGE_API_ROUTE_DEFS = Object.freeze([ 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', + }), ]); const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); @@ -801,6 +970,11 @@ const SVG_ICON_DEFS = Object.freeze({ { 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' } }, ], @@ -872,6 +1046,31 @@ const SVG_ICON_DEFS = Object.freeze({ { 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' } }, @@ -1092,6 +1291,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', 'header.statusLive': '监控中', + 'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…', + 'select.searchPlaceholder': '输入关键词筛选…', + 'select.noMatches': '没有匹配的选项', + 'select.clearSearch': '清空搜索', // Formatters & Common Labels 'fmt.pending': '待定', @@ -1181,6 +1384,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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 周额度', @@ -1238,6 +1442,13 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.loading': '读取中...', 'quota.failed': '获取失败 (--%)', 'quota.usedAndLeft': '{reset} · 已用 {used}% (余 {rem}%)', + 'quota.usedBeforeReserved': '{reset} · 已用 {used}% (', + 'quota.reservedTag': '预占 {rsv}%', + 'quota.usedAfterReserved': ' · 余 {rem}%)', + '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} 次调用', @@ -1248,6 +1459,17 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', + 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', // Live Activity Widget 'live.currentSession': '当前会话', @@ -1313,6 +1535,40 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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.workspaceJumpTip': '点击跳转到该项目最近会话', + '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': '调用记录', @@ -1389,6 +1645,17 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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} 步', @@ -1397,6 +1664,36 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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': '步序', @@ -1582,7 +1879,20 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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': '开启', @@ -1607,6 +1917,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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 项)', @@ -1632,11 +1943,24 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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': '跟随宿主设置', @@ -1666,6 +1990,48 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ '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': '执行命令', @@ -1761,6 +2127,21 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', 'chart.trend.hmActiveZero': '活跃 0/{total} 天', '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 }; })(); @@ -1801,6 +2182,10 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', 'header.statusLive': 'Monitoring', + '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', @@ -1890,6 +2275,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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', @@ -1947,6 +2333,13 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.loading': 'Loading...', 'quota.failed': 'Unavailable (--%)', 'quota.usedAndLeft': '{reset} · Used {used}% ({rem}% left)', + 'quota.usedBeforeReserved': '{reset} · Used {used}% (', + 'quota.reservedTag': '{rsv}% rsv', + 'quota.usedAfterReserved': ' · {rem}% left)', + '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', @@ -1957,6 +2350,17 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.', + 'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.', // Live Activity Widget 'live.currentSession': 'Current Session', @@ -2022,6 +2426,40 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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.workspaceJumpTip': 'Click to inspect latest session in this project', + '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', @@ -2098,6 +2536,17 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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', @@ -2106,6 +2555,36 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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', @@ -2291,7 +2770,20 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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', @@ -2316,6 +2808,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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)', @@ -2341,11 +2834,24 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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', @@ -2375,6 +2881,48 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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', @@ -2470,6 +3018,21 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', 'chart.trend.hmActiveZero': 'Active 0/{total}d', '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 }; })(); @@ -3479,7 +4042,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { +const { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, 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. @@ -3507,6 +4070,26 @@ function formatCachePct(value) { 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)}`; } @@ -3728,6 +4311,123 @@ function buildStepCompactionDiagnostic(st, displaySettings = {}) { }; } +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; @@ -3818,15 +4518,105 @@ function stripCompactionMarker(rawText) { 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)`、`Orchestrator (Argon)`、`Orchestrator (Neon)`、`gemini-flash-worker-agy` / `M669`) - * 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `orchestrator-neon` / `worker-agy-hydrogen`; + * - 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`(`·压缩`),供步骤表单独保护压缩尾标永不截断。 + * - 独立拆分 `baseText` 及 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。 * * @param {object|null|undefined} target * @param {{ modelDisplayMode?: string, showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings] @@ -3878,6 +4668,7 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { target.baseModelUpstream ?? target.activeModelUpstream ?? target.modelUpstream ?? + target.upstreamModel ?? target.upstreamName ?? '' ).trim(); @@ -3891,22 +4682,16 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { 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-hydrogen\b|\bOrchestrator\s+Worker\b/i.test( + /\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 dynamicOrchVariantMatch = - combined.match(/\bOrchestrator\s*\(\s*([a-z0-9-]+)\s*\)/i) || - combined.match(/\bgemini-pro-orchestrator-([a-z0-9-]+)\b/i) || - combined.match(/\b(?:orchestrator|orch)-([a-z0-9]+)(?=·|\s|$)/i); - const dynamicOrchVariant = - dynamicOrchVariantMatch && dynamicOrchVariantMatch[1].toLowerCase() !== 'worker' - ? dynamicOrchVariantMatch[1].toLowerCase() - : ''; + const dynamicOrchVariant = isOrchWorker ? '' : extractDynamicOrchVariant(fields); const hasBareProOrch = /\bgemini-pro-orchestrator\b(?![-_][a-z0-9])/i.test(combined); const isOrchSeries = isOrchWorker || @@ -3920,8 +4705,41 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { let compactId = ''; let fullId = ''; if (isOrchWorker) { - compactId = 'worker-agy-hydrogen'; - fullId = 'gemini-flash-worker-agy (hydrogen-4)'; + 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)'; @@ -3938,11 +4756,23 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { } else if (dynamicOrchVariant) { compactId = `orchestrator-${dynamicOrchVariant}`; const cleanUpstream = stripCompactionMarker(upstreamText || responseText || '').trim(); - fullId = cleanUpstream - ? cleanUpstream.toLowerCase().includes(dynamicOrchVariant) - ? cleanUpstream - : `${cleanUpstream} (${dynamicOrchVariant})` - : `gemini-pro-orchestrator-${dynamicOrchVariant}`; + 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; @@ -4031,14 +4861,30 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { 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 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; + 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, @@ -4058,10 +4904,15 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { 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, @@ -4110,12 +4961,24 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { } } + 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; @@ -4135,8 +4998,13 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { } const promptTok = acc.inputTokens + acc.cacheReadTokens; const cacheHitPct = promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0; - const avgTokPerSec = - acc.speedWeight > 0 ? +(acc.speedWeightedSum / acc.speedWeight).toFixed(1) : null; + 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); @@ -4169,12 +5037,15 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { anomalyByKind: acc.anomalyByKind, } : {}), - speedSummary: acc.baseItem.speedSummary + speedSummary: acc.hasAnySpeedSummary ? { - ...acc.baseItem.speedSummary, + ...(acc.baseItem.speedSummary || {}), + tokens: acc.speedTokens, + seconds: +acc.speedSeconds.toFixed(6), sampleCount: acc.speedSampleCount, excludedCount: acc.speedExcludedCount, - avgTokPerSec, + excludedReasons: acc.speedExcludedReasons, + avgTokPerSec: rawAvgTps, } : undefined, upstreamModels, @@ -4537,7 +5408,2841 @@ function buildDeterministicModelColorMap(models = []) { return colorMap; } -return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; +return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, 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), +]); + +/** + * 将当前用户偏好设置序列化为跨设备可迁移的安全 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 { 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 INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g; +const INVALID_SHEET_NAME_RE = /[\\/?*[\]:]/g; + +// --- 样式索引常量(对应下方 STYLES_XML 中的 cellXfs 顺序) --- +const STYLE_TEXT_LEFT = 1; +const STYLE_TEXT_LEFT_ALT = 2; +const STYLE_TEXT_CENTER = 3; +const STYLE_TEXT_CENTER_ALT = 4; +const STYLE_TEXT_RIGHT = 5; +const STYLE_TEXT_RIGHT_ALT = 6; +const STYLE_INT = 7; +const STYLE_INT_ALT = 8; +const STYLE_DEC1 = 9; +const STYLE_DEC1_ALT = 10; +const STYLE_DEC2 = 11; +const STYLE_DEC2_ALT = 12; +const STYLE_PCT = 13; +const STYLE_PCT_ALT = 14; +const STYLE_USD2 = 15; +const STYLE_USD2_ALT = 16; +const STYLE_USD4 = 17; +const STYLE_USD4_ALT = 18; +const STYLE_HEADER_LEFT = 19; +const STYLE_HEADER_CENTER = 20; +const STYLE_HEADER_RIGHT = 21; +const STYLE_DANGER_TEXT = 22; +const STYLE_DANGER_CENTER = 23; +const STYLE_DANGER_INT = 24; +const STYLE_DANGER_DEC1 = 25; +const STYLE_DANGER_DEC2 = 26; +const STYLE_DANGER_PCT = 27; +const STYLE_DANGER_USD4 = 28; +const STYLE_INFO_TEXT = 29; +const STYLE_INFO_CENTER = 30; +const STYLE_INFO_INT = 31; +const STYLE_INFO_DEC1 = 32; +const STYLE_INFO_DEC2 = 33; +const STYLE_INFO_PCT = 34; +const STYLE_INFO_USD4 = 35; +const STYLE_SUMMARY_LABEL = 36; +const STYLE_SUMMARY_CENTER = 37; +const STYLE_SUMMARY_TEXT_RIGHT = 38; +const STYLE_SUMMARY_INT = 39; +const STYLE_SUMMARY_DEC1 = 40; +const STYLE_SUMMARY_DEC2 = 41; +const STYLE_SUMMARY_PCT = 42; +const STYLE_SUMMARY_USD2 = 43; +const STYLE_SUMMARY_USD4 = 44; + +const CRC32_TABLE = (() => { + 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 escapeXmlText(val) { + return String(val ?? '') + .replace(INVALID_XML_CTRL_RE, '') + .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 宽)。 + */ +function measureExcelVisualWidth(str) { + const s = String(str ?? '').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 { 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({ + today: '今日', + '24h': '近24小时', + '7d': '近7天', + '14d': '近14天', + '30d': '近30天', + all: '全部时间', + cycle: '当前周期', + custom: '自定义区间', +}); + +const RANGE_LABELS_EN = Object.freeze({ + today: 'Today', + '24h': 'Last 24 Hours', + '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(); + if (en) { + return RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + } + return r.label || RANGE_LABELS_ZH[key] || key || '全部时间'; +} + +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 && + 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 && 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' + : '自动压缩' + : 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 } = {} +) { + 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', + range.label || range.key || 'all', + 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', + slot.fullLabel || 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 isHourly = + 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 granLabel = 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 --- @@ -4827,7 +8532,7 @@ return { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliver })(); // --- src/store/uiStore.js --- -const { getViewTabs, uiStore, getVisibleMonitorView } = (() => { +const { getViewTabs, uiStore, showUiToast, dismissUiToast, getVisibleMonitorView } = (() => { /** * @fileoverview UI navigation and view state store. */ @@ -4849,17 +8554,322 @@ const uiStore = createReactiveStore({ settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other' settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps' selectedAgentScope: 'all', // 'all' | 'main' | - ctxInspectorAgentId: 'auto', // 'auto' | '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, getVisibleMonitorView }; +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) 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, +}) { + 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 宿主内, 会被静默吞掉,绝不误报“已下载到浏览器” + if (isHostEmbeddedWebview()) { + 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/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_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, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +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, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, 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. @@ -5159,6 +9169,8 @@ function recordConsumptionSliceToCache( 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 : [], }); } @@ -5176,6 +9188,10 @@ function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision 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, }; @@ -5239,6 +9255,9 @@ function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) { 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; @@ -5257,6 +9276,36 @@ const normalizeClientPopoverWidthMode = normalizePopoverWidthMode; const normalizeClientPopoverWidth = normalizePopoverWidth; const normalizeClientModelDisplayMode = normalizeModelDisplayMode; const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; +const normalizeClientContextAgentMode = normalizeContextAgentMode; +const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation; +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; @@ -5299,6 +9348,20 @@ function isEquivalentTelemetry(prev, next) { 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) @@ -5345,9 +9408,16 @@ function isEquivalentTelemetry(prev, next) { 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; } @@ -5357,6 +9427,15 @@ function isEquivalentTelemetry(prev, next) { 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 (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false; if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false; if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false; @@ -5376,6 +9455,16 @@ function isEquivalentTelemetry(prev, next) { ) { 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 ( @@ -5525,6 +9614,9 @@ function isEquivalentTelemetry(prev, next) { 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 || @@ -5582,6 +9674,9 @@ function isEquivalentTelemetry(prev, next) { 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 || @@ -5652,7 +9747,14 @@ function isEquivalentTelemetry(prev, next) { 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) ) { @@ -5668,6 +9770,10 @@ function isEquivalentTelemetry(prev, next) { 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]?.label !== nTrend[i]?.label || pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || @@ -5716,12 +9822,47 @@ function isEquivalentTelemetry(prev, next) { } } + 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 ) { @@ -5759,16 +9900,22 @@ function isEquivalentTelemetry(prev, next) { 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 + pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls || + JSON.stringify(pPools[i]?.rateEstimate || null) !== + JSON.stringify(nPools[i]?.rateEstimate || null) ) { return false; } @@ -5786,6 +9933,7 @@ function isEquivalentTelemetry(prev, next) { 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; @@ -6028,6 +10176,8 @@ async function requestTelemetry(params, force) { 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, }; @@ -6467,6 +10617,9 @@ async function saveSettingsPatch(patch) { 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); } @@ -6476,9 +10629,20 @@ async function saveSettingsPatch(patch) { 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, '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); } @@ -6516,6 +10680,12 @@ async function saveSettingsPatch(patch) { 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); } @@ -6724,6 +10894,65 @@ async function triggerBridgeHostRelaunch() { } } +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) { @@ -6981,7 +11210,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_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, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +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, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -7106,8 +11335,129 @@ const TopLongPillNav = defineComponent({ 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 { CustomSelect } = (() => { +const { filterSelectOptionsByQuery, CustomSelect } = (() => { /** * @fileoverview Bespoke CustomSelect dropdown component replacing native