From e1da514515a402639e7a7c6488a707ebca8d6a8e Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Wed, 11 Nov 2026 17:31:42 +0900 Subject: [PATCH] feat(panel): dual-mount topbar capsule, live multi-session HUD, and customizable topbar metrics (v1.4.3) --- .gitignore | 9 +- README.md | 16 +- plugin.json | 2 +- pricing-catalog.json | 13 +- sidecars/panel/app.js | 4151 ++++++++++++++--- sidecars/panel/backend/config.mjs | 187 +- sidecars/panel/backend/local-scanner.mjs | 221 +- sidecars/panel/backend/ls-rpc.mjs | 67 +- sidecars/panel/backend/model-pricing.mjs | 106 +- sidecars/panel/backend/plugin-updater.mjs | 97 +- sidecars/panel/backend/pricing-catalog.mjs | 270 +- sidecars/panel/backend/quota-pools.mjs | 95 +- sidecars/panel/backend/telemetry-builder.mjs | 337 +- sidecars/panel/backend/usage-aggregator.mjs | 236 +- sidecars/panel/backend/window-bridge.mjs | 826 ++++ sidecars/panel/index.html | 4 +- sidecars/panel/main.mjs | 360 +- sidecars/panel/package.json | 2 +- sidecars/panel/scripts/build-bundle.mjs | 561 ++- sidecars/panel/sidecar.json | 2 +- sidecars/panel/speed-metrics.mjs | 320 +- sidecars/panel/src/App.js | 33 +- .../src/components/charts/TrendAreaChart.js | 66 +- .../src/components/layout/TopSessionHeader.js | 49 +- .../components/layout/WindowOverlayShell.js | 2184 +++++++++ .../src/components/ui/CustomDateTimePicker.js | 25 +- .../src/components/ui/CustomNumberInput.js | 22 +- .../src/components/ui/CustomScrollbar.js | 15 +- .../panel/src/components/ui/CustomSelect.js | 30 +- .../src/components/ui/SegmentedControl.js | 3 +- sidecars/panel/src/core/component.js | 38 +- sidecars/panel/src/core/domPatch.js | 62 +- sidecars/panel/src/core/formatters.js | 14 +- sidecars/panel/src/core/httpClient.js | 153 +- sidecars/panel/src/core/reactive.js | 31 +- sidecars/panel/src/icons/svgRegistry.js | 10 +- sidecars/panel/src/main.js | 20 +- sidecars/panel/src/store/telemetryStore.js | 290 +- sidecars/panel/src/styles/animations.css | 4 +- sidecars/panel/src/styles/base.css | 5 + sidecars/panel/src/styles/controls.css | 135 +- sidecars/panel/src/styles/overlay.css | 589 +++ sidecars/panel/src/styles/tokens.css | 16 +- .../panel/src/styles/views-consumption.css | 57 +- sidecars/panel/src/styles/views-overview.css | 101 +- sidecars/panel/src/views/ConsumptionView.js | 164 +- sidecars/panel/src/views/LiveOverviewView.js | 534 ++- sidecars/panel/src/views/SettingsView.js | 475 +- sidecars/panel/src/views/StepsDetailView.js | 3 +- sidecars/panel/stream-diagnostics.mjs | 1162 ----- sidecars/panel/styles.css | 909 +++- sidecars/panel/test/audit-fixes.test.mjs | 533 +++ sidecars/panel/test/backend-harness.mjs | 58 +- sidecars/panel/test/model-identity.test.mjs | 2 +- .../panel/test/stream-diagnostics.test.mjs | 194 - sidecars/panel/test/window-bridge.test.mjs | 1200 +++++ 56 files changed, 13389 insertions(+), 3679 deletions(-) create mode 100644 sidecars/panel/backend/window-bridge.mjs create mode 100644 sidecars/panel/src/components/layout/WindowOverlayShell.js create mode 100644 sidecars/panel/src/styles/overlay.css delete mode 100644 sidecars/panel/stream-diagnostics.mjs create mode 100644 sidecars/panel/test/audit-fixes.test.mjs delete mode 100644 sidecars/panel/test/stream-diagnostics.test.mjs create mode 100644 sidecars/panel/test/window-bridge.test.mjs diff --git a/.gitignore b/.gitignore index 46fd6c9..05d6db2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,6 @@ .data/ node_modules/ -test/ -**/test/ -*.test.* -*-harness.* +plan/ *.log .DS_Store Thumbs.db - -# Keep regression tests in source control. -!sidecars/panel/test/ -!sidecars/panel/test/** diff --git a/README.md b/README.md index fdda1da..c261cba 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Antigravity Usage & Speed Monitor -Antigravity 侧边栏插件,用于查看当前会话的生成速度、上下文占用、官方配额余量以及本地历史 Token 消耗。 +Antigravity 双栖监控插件(支持主窗口顶栏胶囊悬浮面板与右侧辅助栏共存),用于查看当前会话的生成速度、上下文占用、官方配额余量以及本地历史 Token 消耗。 下载最新版本:[Releases](https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases) · [usage-monitor.zip](https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip) @@ -11,16 +11,17 @@ Antigravity 侧边栏插件,用于查看当前会话的生成速度、上下 - **实时监控** - 核心指标:输出速度、首字延迟、平均速度、本次费用与会话累计费用(支持主代理与子代理独立或汇总查看)。 - 上下文窗口:支持按代理独立切换查看当前上下文窗口,并拆分为模型回复、工具结果、用户消息、子代理通知、压缩摘要、系统提示词、系统工具、MCP 工具、Skill 与用户规则十类来源(按占用量从大到小动态排列)。 - - 额度概览:同步展示 `Gemini`、`Gemini 4 Argon`(Pro 账号独立池)与 `Claude & GPT` 模型池的 5 小时限额、每周限额及重置倒计时。 + - 额度概览:同步展示 `Gemini`、`Gemini 4 Argon`、`Gemini 4 Carbon`(Pro 账号独立池)与 `Claude & GPT` 模型池的 5 小时限额、每周限额及重置倒计时。 - **用量统计** - 支持按今天、1天、7天、14天、30天、全部或自定义时间段过滤。 - - 汇总所选时段的总 Token、折算费用、缓存命中率与缓存节省金额。 + - 汇总所选时段的总 Token、折算费用与缓存命中率,并分列展示新输入、缓存读取(含缓存节省金额)与输出用量。 - 包含用量趋势曲线、模型排行、客户端来源以及月度统计柱状图。 - **调用明细** - 按步查看:列出当前会话全部步骤的模型、输出速度、首字延迟、上下文/输出 Token、缓存命中率与单步费用。 - - 按模型汇总:按当前所选时间范围统计各模型的调用次数、均速、总 Token 与费用。 + - 按模型汇总:按当前所选会话(及所选主/子代理范围)统计各模型的调用次数、均速、总 Token 与费用。 - **偏好设置** - - 选择周额度基准:跟随官方额度,或按自定义每周 Token / 费用上限计算百分比。 + - 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。 + - 顶部栏定制:独立开关实时运行会话入口,并自由定义右侧三个指标槽位的显示内容与排列顺序。 - 选择模型名称格式:精简代号或原始模型 ID。 - 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并支持在面板内一键检查更新或开启后台自动安装新版本。 @@ -68,7 +69,8 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir ## 启用与打开面板 1. 打开左侧边栏的 **Customizations**,进入 **Installed** 标签页,找到 `usage-monitor` 并开启。 -2. 点击对话窗口右上角 `⋮` -> **Extensions** -> **用量监控**,在右侧辅助栏展开面板;或在对话中输入「打开用量监控面板」通过快捷入口唤起。 +2. **顶部栏胶囊悬浮面板(默认双栖开启)**:开启插件后,后台 Sidecar 会自动在主对话窗口右上角顶部栏挂载实时状态与指标胶囊(悬停查看速览,左键展开完整四标签面板,右键强制刷新),全程不修改宿主 `app.asar`。如需关闭顶部栏胶囊,可在 **偏好设置 -> 面板挂载方式** 中切换为「仅侧边栏」。 +3. **右侧辅助栏面板**:点击对话窗口右上角 `⋮` -> **Extensions** -> **用量监控**,在右侧辅助栏展开面板;或在对话中输入「打开用量监控面板」通过快捷入口唤起。 ## 更新 @@ -88,7 +90,7 @@ git -C "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" pull --ff-only git -C ~/.gemini/config/plugins/usage-monitor pull --ff-only ``` -通过压缩包安装时,下载新版 `usage-monitor.zip` 覆盖解压到原目录后重新开关插件即可。本地缓存与设置存放在 `~/.gemini/antigravity/sidecar_data/usage-monitor/`,更新插件不会清除历史数据。 +通过压缩包安装时,下载新版 `usage-monitor.zip` 覆盖解压到原目录后重新开关插件即可。在 Antigravity 宿主内运行时,本地缓存与设置存放在 `~/.gemini/antigravity/sidecar_data/usage-monitor/`(独立启动且未传入 `ANTIGRAVITY_EXECUTABLE_DATA_DIR` 时回退至 `sidecars/panel/.data/`),更新插件不会清除历史数据。 ## 本地构建 diff --git a/plugin.json b/plugin.json index 03c6072..ab451c1 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "usage-monitor", "displayName": "Usage & Speed Monitor", - "version": "1.4.2", + "version": "1.4.3", "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "logo": "assets/logo.svg", "suggestedPrompts": [ diff --git a/pricing-catalog.json b/pricing-catalog.json index 6c63d0b..6f4dd43 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.11.1", - "updatedAt": "2026-11-11T00:30:00+09:00", - "latestPluginVersion": "1.4.2", + "catalogVersion": "2026.11.11.2", + "updatedAt": "2026-11-11T17:25:00+09:00", + "latestPluginVersion": "1.4.3", "releaseUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", "archiveFallbackUrl": "https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main", @@ -110,13 +110,14 @@ "gpt-oss-120b-medium": { "input": 0.80, "cache": 0.10, "output": 2.40, "short": "gpt-oss", "family": "GPT" } }, "placeholders": { + "MODEL_PLACEHOLDER_M429": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" }, "MODEL_PLACEHOLDER_M417": { "modelId": "gemini-4-argon-high", "label": "Gemini 4 Argon (High)" }, "MODEL_PLACEHOLDER_M418": { "modelId": "gemini-4-argon-medium", "label": "Gemini 4 Argon (Medium)" }, "MODEL_PLACEHOLDER_M419": { "modelId": "gemini-4-argon-low", "label": "Gemini 4 Argon (Low)" }, "MODEL_PLACEHOLDER_M318": { "modelId": "gemini-3.8-flash-high", "label": "Gemini 3.8 Flash (High)" }, "MODEL_PLACEHOLDER_M319": { "modelId": "gemini-3.8-flash-medium", "label": "Gemini 3.8 Flash (Medium)" }, "MODEL_PLACEHOLDER_M320": { "modelId": "gemini-3.8-flash-low", "label": "Gemini 3.8 Flash (Low)" }, - "MODEL_PLACEHOLDER_M322": { "modelId": "gemini-3.8-flash", "label": "Gemini 3.8 Flash (Tiered)" }, + "MODEL_PLACEHOLDER_M322": { "modelId": "gemini-3.8-flash-tiered", "label": "Gemini 3.8 Flash (Tiered)" }, "MODEL_PLACEHOLDER_M298": { "modelId": "gemini-3.7-flash-high", "label": "Gemini 3.7 Flash (High)" }, "MODEL_PLACEHOLDER_M299": { "modelId": "gemini-3.7-flash-medium", "label": "Gemini 3.7 Flash (Medium)" }, "MODEL_PLACEHOLDER_M300": { "modelId": "gemini-3.7-flash-low", "label": "Gemini 3.7 Flash (Low)" }, @@ -125,8 +126,8 @@ "MODEL_PLACEHOLDER_M72": { "modelId": "gemini-3.6-flash-medium", "label": "Gemini 3.6 Flash (Medium)" }, "MODEL_PLACEHOLDER_M73": { "modelId": "gemini-3.6-flash-low", "label": "Gemini 3.6 Flash (Low)" }, "MODEL_PLACEHOLDER_M196": { "modelId": "gemini-3.6-flash", "label": "Gemini 3.6 Flash" }, - "MODEL_PLACEHOLDER_M149": { "modelId": "gemini-3.5-flash", "label": "Gemini 3.5 Flash (High)" }, - "MODEL_PLACEHOLDER_M20": { "modelId": "gemini-3.5-flash-low", "label": "Gemini 3.5 Flash" }, + "MODEL_PLACEHOLDER_M149": { "modelId": "gemini-3.5-flash-high", "label": "Gemini 3.5 Flash (High)" }, + "MODEL_PLACEHOLDER_M20": { "modelId": "gemini-3.5-flash", "label": "Gemini 3.5 Flash" }, "MODEL_PLACEHOLDER_M187": { "modelId": "gemini-3.5-flash-extra-low", "label": "Gemini 3.5 Flash (Extra Low)" }, "MODEL_PLACEHOLDER_M198": { "modelId": "gemini-3.5-flash-lite", "label": "Gemini 3.5 Flash Lite" }, "MODEL_PLACEHOLDER_M37": { "modelId": "gemini-3.1-pro-high", "label": "Gemini 3.1 Pro (High)" }, diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 7cee930..9087083 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1,3 +1,6 @@ +(() => { +'use strict'; + // --- src/icons/svgRegistry.js --- /** * @fileoverview Pure vector SVG icon registry (16x16 grid). @@ -74,11 +77,19 @@ const SVG_ICON_DEFS = Object.freeze({ { tag: 'path', attrs: { d: 'M3.5 8h9' } }, ], dot: [ - { tag: 'circle', attrs: { cx: '8', cy: '8', r: '3.2', fill: 'currentColor', stroke: 'none' } }, + { tag: 'circle', attrs: { cx: '8', cy: '8', r: '5', fill: 'currentColor', stroke: 'none' } }, ], 'arrow-down': [ { tag: 'path', attrs: { d: 'M8 2.8v10.4M4.2 9.4L8 13.2l3.8-3.8' } }, ], + dock: [ + { tag: 'rect', attrs: { x: '1.8', y: '2.5', width: '12.4', height: '11', rx: '1.5' } }, + { tag: 'path', attrs: { d: 'M1.8 6h12.4' } }, + { tag: 'path', attrs: { d: 'M9.2 4.25h3.2' } }, + ], + close: [ + { tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } }, + ], }); // --- src/icons/SvgIcon.js --- @@ -186,6 +197,19 @@ function createReactiveStore(initialState) { return state; } + function notifyAll() { + for (const sub of Array.from(subscribers)) { + if (!subscribers.has(sub)) continue; + const nextSlice = sub.selector(state); + const equal = sub.compare(sub.lastSlice, nextSlice); + if (!equal) { + const prevSlice = sub.lastSlice; + sub.lastSlice = nextSlice; + sub.listener(nextSlice, prevSlice); + } + } + } + function setState(patchOrUpdater, { sync = false } = {}) { const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater; if (!patch || typeof patch !== 'object') return; @@ -203,18 +227,6 @@ function createReactiveStore(initialState) { } state = nextState; - const notifyAll = () => { - for (const sub of subscribers) { - const nextSlice = sub.selector(state); - const equal = sub.compare(sub.lastSlice, nextSlice); - if (!equal) { - const prevSlice = sub.lastSlice; - sub.lastSlice = nextSlice; - sub.listener(nextSlice, prevSlice); - } - } - }; - if (sync) { notifyAll(); } else { @@ -302,18 +314,28 @@ function patchText(el, nextValue) { function patchAttr(el, attrName, nextValue) { if (!el) return false; if (nextValue === null || nextValue === undefined || nextValue === false) { - if (!el.hasAttribute(attrName)) { - return false; + let mutated = false; + if (el.hasAttribute(attrName)) { + el.removeAttribute(attrName); + mutated = true; } - el.removeAttribute(attrName); - return true; + if (attrName === 'value' && 'value' in el && el.value !== '') { + el.value = ''; + mutated = true; + } + return mutated; } const strVal = nextValue === true ? '' : String(nextValue); - if (el.getAttribute(attrName) === strVal) { - return false; + let mutated = false; + if (el.getAttribute(attrName) !== strVal) { + el.setAttribute(attrName, strVal); + mutated = true; } - el.setAttribute(attrName, strVal); - return true; + if (attrName === 'value' && 'value' in el && el.value !== strVal) { + el.value = strVal; + mutated = true; + } + return mutated; } function patchClasses(el, classMap) { @@ -321,11 +343,14 @@ function patchClasses(el, classMap) { let mutated = false; for (const [cls, active] of Object.entries(classMap)) { if (!cls) continue; - const has = el.classList.contains(cls); const shouldHave = Boolean(active); - if (has !== shouldHave) { - el.classList.toggle(cls, shouldHave); - mutated = true; + const tokens = String(cls).split(/\s+/).filter(Boolean); + for (const tok of tokens) { + const has = el.classList.contains(tok); + if (has !== shouldHave) { + el.classList.toggle(tok, shouldHave); + mutated = true; + } } } return mutated; @@ -342,6 +367,25 @@ function patchStyleVar(el, varName, nextValue) { return true; } +/** + * 判断事件是否发生在目标节点内部(兼容 Shadow DOM 的 `composedPath()` 穿透)。 + * + * @param {Event|null|undefined} event + * @param {Node|null|undefined} element + * @returns {boolean} + */ +function isEventInside(event, element) { + if (!event || !element) return false; + if (typeof event.composedPath === 'function') { + const path = event.composedPath(); + if (Array.isArray(path) && path.includes(element)) { + return true; + } + } + const target = event.target; + return Boolean(target && typeof element.contains === 'function' && element.contains(target)); +} + const keyedListState = new WeakMap(); /** @@ -357,11 +401,15 @@ function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow } } const nextKeys = new Set(); + const seenInPass = new Map(); const orderedNodes = []; for (let i = 0; i < items.length; i++) { const item = items[i]; - const key = String(keyFn(item, i)); + const rawKey = String(keyFn(item, i)); + const dupIdx = seenInPass.get(rawKey) || 0; + seenInPass.set(rawKey, dupIdx + 1); + const key = dupIdx === 0 ? rawKey : `${rawKey}__dup_${dupIdx}`; const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item); nextKeys.add(key); @@ -413,15 +461,6 @@ function defineComponent({ name, setup }) { return function createInstance(initialProps = {}) { let props = { ...initialProps }; const cleanups = []; - const eventHandlers = new Map(); - - function on(event, fn) { - if (!eventHandlers.has(event)) { - eventHandlers.set(event, new Set()); - } - eventHandlers.get(event).add(fn); - return () => eventHandlers.get(event)?.delete(fn); - } function emit(event, payload) { // Support Vue-style onUpdateModelValue / onChange prop callbacks @@ -433,12 +472,6 @@ function defineComponent({ name, setup }) { props.onChange(payload); } } - const handlers = eventHandlers.get(event); - if (handlers) { - for (const fn of handlers) { - fn(payload); - } - } } function onCleanup(fn) { @@ -447,15 +480,11 @@ function defineComponent({ name, setup }) { } } - const setupResult = setup({ - getProps: () => props, - emit, - onCleanup, - }); + let setupResult = null; function setProps(nextProps = {}) { props = { ...props, ...nextProps }; - if (typeof setupResult.onPropsChange === 'function') { + if (setupResult && typeof setupResult.onPropsChange === 'function') { setupResult.onPropsChange(props); } } @@ -464,11 +493,12 @@ function defineComponent({ name, setup }) { setProps({ modelValue: nextValue }); } - function getValue() { - return typeof setupResult.getValue === 'function' - ? setupResult.getValue() - : props.modelValue; - } + setupResult = setup({ + getProps: () => props, + setProps, + emit, + onCleanup, + }); function destroy() { for (const fn of cleanups.splice(0)) { @@ -478,7 +508,6 @@ function defineComponent({ name, setup }) { console.error(`[${name}] cleanup error:`, err); } } - eventHandlers.clear(); if (setupResult.el?.parentNode) { setupResult.el.parentNode.removeChild(setupResult.el); } @@ -488,11 +517,8 @@ function defineComponent({ name, setup }) { name, el: setupResult.el, refs: setupResult.refs || {}, - on, - emit, setProps, setValue, - getValue, destroy, ...setupResult.methods, }; @@ -539,15 +565,15 @@ function formatDateSpanBadge(startMs, endMs) { return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } -function formatUsd(amount, { precise = false, estimated = false, unpricedCalls = 0 } = {}) { +function formatUsd(amount, { precise = false, unpricedCalls = 0, compactPending = false } = {}) { if (amount == null || !Number.isFinite(Number(amount))) return '待定'; const val = Number(amount || 0); - const prefix = estimated ? '≈$' : '$'; - const suffix = unpricedCalls > 0 ? ' + 待定' : ''; + const suffix = unpricedCalls > 0 ? (compactPending ? '+' : ' + 待定') : ''; if (precise) { - return (val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`) + suffix; + if (val > 0 && val < 0.001) return `<$0.001${suffix}`; + return (val >= 1 ? `$${val.toFixed(2)}` : `$${val.toFixed(3)}`) + suffix; } - return `${prefix}${val.toFixed(2)}${suffix}`; + return `$${val.toFixed(2)}${suffix}`; } function speedReasonText(reason) { @@ -555,6 +581,7 @@ function speedReasonText(reason) { incomplete_or_invalid_timing: '生成未完成', invalid_output_tokens: '无有效输出', inconsistent_timing: '耗时数据异常', + short_timing: '耗时过短 (<0.5s)', legacy_cache: '旧版缓存记录', })[reason] || ''; } @@ -568,9 +595,10 @@ function sampleSummary(summary) { function formatCountdown(isoTime, nowMs = Date.now()) { if (!isoTime) return '未知重置时间'; const targetMs = Date.parse(isoTime); - if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间'; + if (!Number.isFinite(targetMs) || targetMs <= 0) return '未知重置时间'; const diffMs = targetMs - nowMs; if (diffMs <= 0) return '即将重置'; + if (diffMs < 60_000) return '<1分钟后重置'; const totalMinutes = Math.floor(diffMs / 60000); const days = Math.floor(totalMinutes / (60 * 24)); @@ -605,12 +633,124 @@ function formatElapsedSec(seconds) { // --- src/core/httpClient.js --- /** * @fileoverview Async HTTP client with AbortController cancellation for stale - * polling requests and concurrent GET deduplication. + * polling requests, concurrent GET deduplication, and dual-mode transport + * (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge). */ const inFlightGets = new Map(); const activeControllers = new Map(); +/** + * 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。 + * + * @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null} + */ +function getWindowBridgeConfig() { + if (typeof window === 'undefined') return null; + const br = window.__AGUsageMonitorBridge; + const port = Number(br?.port || 0); + if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) { + return br; + } + return null; +} + +/** + * 判断当前脚本是否以双栖悬浮模式运行在宿主主聊天窗口内(而非右侧辅助栏 Webview)。 + * + * @returns {boolean} + */ +function isWindowOverlayMode() { + if (typeof window === 'undefined') return false; + if (window.sidecar?.fetch) return false; + return Boolean(getWindowBridgeConfig()); +} + +/** + * 接收 Sidecar 通过 CDP `Runtime.evaluate` 批量投递的 RPC 响应,完成因 CSP/代理解除 HTTP 直连时的兜底请求。 + * + * @param {Array<{ id: string, ok: boolean, status?: number, data?: any, error?: string }>} responses + * @returns {number} + */ +function deliverCdpBridgeResponses(responses) { + const br = getWindowBridgeConfig(); + if (!br || !(br.rpcPending instanceof Map) || !Array.isArray(responses)) return 0; + let delivered = 0; + for (const item of responses) { + const entry = br.rpcPending.get(item?.id); + if (!entry) continue; + br.rpcPending.delete(item.id); + delivered += 1; + if (item.ok) { + entry.resolve(item.data); + } else { + entry.reject(new Error(item.error || `HTTP ${item.status || 500}`)); + } + } + return delivered; +} + +function callViaCdpBridge(bridge, path, { method, body, signal }) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + const abortErr = new Error('Request aborted'); + abortErr.name = 'AbortError'; + reject(abortErr); + return; + } + if (!Array.isArray(bridge.rpcQueue)) bridge.rpcQueue = []; + if (!(bridge.rpcPending instanceof Map)) bridge.rpcPending = new Map(); + + const reqId = `rpc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const cleanupQueueItem = () => { + if (!Array.isArray(bridge.rpcQueue)) return; + const idx = bridge.rpcQueue.findIndex((item) => item?.id === reqId); + if (idx >= 0) bridge.rpcQueue.splice(idx, 1); + }; + + const timeoutId = setTimeout(() => { + bridge.rpcPending.delete(reqId); + cleanupQueueItem(); + reject(new Error('CDP bridge timeout')); + }, 8000); + + const onAbort = () => { + clearTimeout(timeoutId); + bridge.rpcPending.delete(reqId); + cleanupQueueItem(); + const abortErr = new Error('Request aborted'); + abortErr.name = 'AbortError'; + reject(abortErr); + }; + if (signal) { + signal.addEventListener('abort', onAbort, { once: true }); + } + + bridge.rpcPending.set(reqId, { + resolve: (data) => { + clearTimeout(timeoutId); + if (signal) signal.removeEventListener('abort', onAbort); + resolve(data); + }, + reject: (err) => { + clearTimeout(timeoutId); + if (signal) signal.removeEventListener('abort', onAbort); + reject(err); + }, + }); + + if (bridge.rpcQueue.length >= 16) { + const dropped = bridge.rpcQueue.shift(); + if (dropped?.id) { + const stale = bridge.rpcPending.get(dropped.id); + bridge.rpcPending.delete(dropped.id); + stale?.reject(new Error('CDP queue superseded')); + } + } + bridge.rpcQueue.push({ id: reqId, path, method, body }); + }); +} + async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) { const upperMethod = method.toUpperCase(); const dedupKey = upperMethod === 'GET' && !abortKey ? path : ''; @@ -633,16 +773,41 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {} const runRequest = async () => { const sidecar = typeof window !== 'undefined' ? window.sidecar : null; + const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null; const fetchFn = sidecar?.fetch ? sidecar.fetch.bind(sidecar) - : globalThis.fetch.bind(globalThis); + : typeof window !== 'undefined' && typeof window.fetch === 'function' + ? window.fetch.bind(window) + : globalThis.fetch.bind(globalThis); - const res = await fetchFn(path, { - method: upperMethod, - headers: { 'Content-Type': 'application/json' }, - body: body === undefined ? undefined : JSON.stringify(body), - signal, - }); + const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path; + const headers = {}; + if (body !== undefined || !bridge) { + headers['Content-Type'] = 'application/json'; + } + if (bridge) { + headers['X-Usage-Monitor-Token'] = bridge.token; + if (bridge.transportMode === 'cdp') { + return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal }); + } + } + + let res; + try { + res = await fetchFn(requestUrl, { + method: upperMethod, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + signal, + }); + } catch (fetchErr) { + if (!bridge || signal?.aborted || fetchErr?.name === 'AbortError') { + throw fetchErr; + } + // 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道 + bridge.transportMode = 'cdp'; + return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal }); + } if (signal?.aborted) { const abortErr = new Error('Request aborted'); abortErr.name = 'AbortError'; @@ -702,15 +867,29 @@ const uiStore = createReactiveStore({ */ +/** + * 在主窗口双栖模式下,从宿主页面路径 `/c/` 提取当前正在浏览的会话 ID。 + * + * @returns {string} + */ +function extractHostRouteCascadeId() { + if (typeof window === 'undefined' || !isWindowOverlayMode()) return ''; + const pathname = String(window.location?.pathname || ''); + const m = pathname.match(/^\/c\/([a-f0-9-]{36})(?:\/|$)/i); + return m ? m[1] : ''; +} + const initialConversationId = (typeof window !== 'undefined' && window.sidecar?.conversationId) || ''; const telemetryStore = createReactiveStore({ selectedConversationId: initialConversationId, + hostRouteConversationId: extractHostRouteCascadeId(), selectedTimeRange: 'today', customStartMs: Date.now() - 24 * 3600 * 1000, customEndMs: Date.now(), syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' + minuteTick: 0, telemetry: null, }); @@ -718,12 +897,49 @@ let pollTimer = null; let feedbackTimer = null; let activeBundleVersion = 0; let latestRequestSeq = 0; +let activeForceCount = 0; +let loopActive = false; +let loopIntervalMs = 2000; +let loopTickFn = null; + +const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([ + 'context', + 'tps', + 'ttft', + 'cost', + 'quota_auto', + 'gemini_5h', + 'gemini_weekly', + 'claude_5h', + 'claude_weekly', + 'none', +]); + +const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']); + +/** + * 归一化前端顶栏胶囊三槽位配置数组,非法项回退默认值,且禁止三项同时为 `none`。 + * + * @param {unknown} raw + * @returns {[string, string, string]} + */ +function normalizeClientTopbarSlots(raw) { + const arr = Array.isArray(raw) ? raw : []; + const slots = [0, 1, 2].map((idx) => { + const val = String(arr[idx] ?? '').trim(); + return CLIENT_TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_CLIENT_TOPBAR_SLOTS[idx]; + }); + if (slots.every((s) => s === 'none')) { + slots[0] = 'context'; + } + return slots; +} function isEquivalentTelemetry(prev, next) { if (!prev || !next) return false; if (prev === next) return true; - // 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关) + // 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关、双栖与顶栏槽位配置) const pAct = prev.activeConversation; const nAct = next.activeConversation; if (prev.settings?.showUpstreamModel !== next.settings?.showUpstreamModel) return false; @@ -731,14 +947,28 @@ function isEquivalentTelemetry(prev, next) { if (prev.settings?.weeklyTokenBudget !== next.settings?.weeklyTokenBudget) return false; if (prev.settings?.weeklyCostBudget !== next.settings?.weeklyCostBudget) return false; if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false; + if (prev.settings?.enableWindowOverlay !== next.settings?.enableWindowOverlay) return false; + if ((prev.settings?.showTopbarMultiSession !== false) !== (next.settings?.showTopbarMultiSession !== false)) { + return false; + } + const pTopSlots = prev.settings?.topbarCapsuleSlots; + const nTopSlots = next.settings?.topbarCapsuleSlots; + if ( + (pTopSlots?.[0] ?? 'context') !== (nTopSlots?.[0] ?? 'context') || + (pTopSlots?.[1] ?? 'tps') !== (nTopSlots?.[1] ?? 'tps') || + (pTopSlots?.[2] ?? 'quota_auto') !== (nTopSlots?.[2] ?? 'quota_auto') + ) { + return false; + } - // 2. 比对云端状态(插件当前/最新版本、价格表版本与模型数量、同步/更新执行状态及错误信息) + // 2. 比对云端状态(插件当前/最新版本、安装模式、价格表版本与模型数量、同步/更新执行状态及错误信息) const pCloud = prev.cloudStatus; const nCloud = next.cloudStatus; if ( pCloud?.currentPluginVersion !== nCloud?.currentPluginVersion || pCloud?.latestPluginVersion !== nCloud?.latestPluginVersion || pCloud?.updateAvailable !== nCloud?.updateAvailable || + pCloud?.installMode !== nCloud?.installMode || pCloud?.catalogVersion !== nCloud?.catalogVersion || pCloud?.source !== nCloud?.source || pCloud?.lastSyncedAtMs !== nCloud?.lastSyncedAtMs || @@ -752,15 +982,25 @@ function isEquivalentTelemetry(prev, next) { return false; } - // 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与单步费用) + // 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与费用) if (pAct?.cascadeId !== nAct?.cascadeId) return false; if (pAct?.stepCount !== nAct?.stepCount) return false; if (pAct?.subagentCount !== nAct?.subagentCount) return false; if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false; if (pAct?.isRunning !== nAct?.isRunning) return false; - if (pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature) return false; + if ( + pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature || + pAct?.liveActivity?.startedAtMs !== nAct?.liveActivity?.startedAtMs + ) { + return false; + } if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false; - if (pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature) return false; + if ( + pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature || + pAct?.aggregated?.liveActivity?.startedAtMs !== nAct?.aggregated?.liveActivity?.startedAtMs + ) { + return false; + } if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false; if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false; if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false; @@ -769,17 +1009,34 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false; if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false; if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false; + if (pAct?.aggregated?.sessionUnpricedCalls !== nAct?.aggregated?.sessionUnpricedCalls) return false; + if (pAct?.aggregated?.sessionCacheHitPct !== nAct?.aggregated?.sessionCacheHitPct) return false; if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false; + if (pAct?.aggregated?.activeModelUpstream !== nAct?.aggregated?.activeModelUpstream) return false; if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false; if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false; if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false; + if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false; if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false; if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false; if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false; - if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false; - if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false; + if ( + pAct?.activeModelShort !== nAct?.activeModelShort || + pAct?.activeModelLabel !== nAct?.activeModelLabel || + pAct?.activeModelUpstream !== nAct?.activeModelUpstream + ) { + return false; + } + if ( + pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || + pAct?.sessionCostUsd !== nAct?.sessionCostUsd || + pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls + ) { + return false; + } const pAgents = pAct?.agents || []; const nAgents = nAct?.agents || []; @@ -787,8 +1044,6 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pAgents.length; i++) { const pa = pAgents[i]; const na = nAgents[i]; - const pLastStep = pa?.recentSteps?.[0]; - const nLastStep = na?.recentSteps?.[0]; if ( pa?.agentId !== na?.agentId || pa?.role !== na?.role || @@ -799,11 +1054,16 @@ function isEquivalentTelemetry(prev, next) { pa?.latestTtftSec !== na?.latestTtftSec || pa?.avgTokPerSec !== na?.avgTokPerSec || pa?.latestCacheHitPct !== na?.latestCacheHitPct || + pa?.sessionCacheHitPct !== na?.sessionCacheHitPct || pa?.latestSpeedReason !== na?.latestSpeedReason || pa?.latestStepCostUsd !== na?.latestStepCostUsd || pa?.sessionCostUsd !== na?.sessionCostUsd || + pa?.sessionUnpricedCalls !== na?.sessionUnpricedCalls || pa?.activeModelShort !== na?.activeModelShort || + pa?.activeModelUpstream !== na?.activeModelUpstream || pa?.context?.totalTokens !== na?.context?.totalTokens || + pa?.context?.compactionLimitTokens !== na?.context?.compactionLimitTokens || + pa?.context?.limitTokens !== na?.context?.limitTokens || pa?.context?.messagesTokens !== na?.context?.messagesTokens || pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens || pa?.context?.assistantTokens !== na?.context?.assistantTokens || @@ -814,21 +1074,43 @@ function isEquivalentTelemetry(prev, next) { pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens || pa?.context?.skillsTokens !== na?.context?.skillsTokens || pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens || - pa?.context?.userRulesTokens !== na?.context?.userRulesTokens || - pLastStep?.tokPerSec !== nLastStep?.tokPerSec || - pLastStep?.ttftSec !== nLastStep?.ttftSec || - pLastStep?.outputTokens !== nLastStep?.outputTokens || - pLastStep?.modelUpstream !== nLastStep?.modelUpstream || - pLastStep?.costUsd !== nLastStep?.costUsd + pa?.context?.userRulesTokens !== na?.context?.userRulesTokens ) { return false; } + const paSteps = pa?.recentSteps || []; + const naSteps = na?.recentSteps || []; + if (paSteps.length !== naSteps.length) return false; + for (let j = 0; j < paSteps.length; j++) { + const bs = paSteps[j]; + const as = naSteps[j]; + if ( + bs?.stepIndex !== as?.stepIndex || + bs?.modelKey !== as?.modelKey || + bs?.modelShort !== as?.modelShort || + bs?.modelLabel !== as?.modelLabel || + bs?.modelUpstream !== as?.modelUpstream || + bs?.responseModel !== as?.responseModel || + bs?.modelSource !== as?.modelSource || + bs?.costUsd !== as?.costUsd || + bs?.tokPerSec !== as?.tokPerSec || + bs?.ttftSec !== as?.ttftSec || + bs?.outputTokens !== as?.outputTokens || + bs?.inputTokens !== as?.inputTokens || + bs?.cacheReadTokens !== as?.cacheReadTokens || + bs?.selectedSpeedReason !== as?.selectedSpeedReason + ) { + return false; + } + } } // 4. 比对 10 通道上下文窗口构成及近期步骤明细 const pCtx = pAct?.context; const nCtx = nAct?.context; if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; + if (pCtx?.compactionLimitTokens !== nCtx?.compactionLimitTokens) return false; + if (pCtx?.limitTokens !== nCtx?.limitTokens) return false; if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false; if (pCtx?.assistantTokens !== nCtx?.assistantTokens) return false; if (pCtx?.toolResultsTokens !== nCtx?.toolResultsTokens) return false; @@ -846,6 +1128,7 @@ function isEquivalentTelemetry(prev, next) { if ( before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || + before.modelLabel !== after.modelLabel || before.modelUpstream !== after.modelUpstream || before.responseModel !== after.responseModel || before.modelSource !== after.modelSource || @@ -854,7 +1137,8 @@ function isEquivalentTelemetry(prev, next) { before.ttftSec !== after.ttftSec || before.outputTokens !== after.outputTokens || before.inputTokens !== after.inputTokens || - before.cacheReadTokens !== after.cacheReadTokens + before.cacheReadTokens !== after.cacheReadTokens || + before.selectedSpeedReason !== after.selectedSpeedReason ) { return false; } @@ -877,8 +1161,13 @@ function isEquivalentTelemetry(prev, next) { const pAcct = prev.consumption?.account; const nAcct = next.consumption?.account; if (pAcct?.totalTokens !== nAcct?.totalTokens) return false; + if (pAcct?.inputTokens !== nAcct?.inputTokens) return false; + if (pAcct?.cacheReadTokens !== nAcct?.cacheReadTokens) return false; + if (pAcct?.outputTokens !== nAcct?.outputTokens) return false; if (pAcct?.calls !== nAcct?.calls) return false; if (pAcct?.costUsd !== nAcct?.costUsd) return false; + if (pAcct?.savedCostUsd !== nAcct?.savedCostUsd) return false; + if (pAcct?.cacheHitPct !== nAcct?.cacheHitPct) return false; if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; // 6. 比对历史趋势时间分桶序列与年度分月序列 @@ -964,6 +1253,7 @@ function isEquivalentTelemetry(prev, next) { if (pQuot?.usedPct !== nQuot?.usedPct) return false; if (pQuot?.remainingPct !== nQuot?.remainingPct) return false; if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false; + if (pQuot?.weeklyRemainingPct !== nQuot?.weeklyRemainingPct) return false; if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false; if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false; if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false; @@ -1019,7 +1309,8 @@ function isEquivalentTelemetry(prev, next) { pr?.isMainRunning !== nr?.isMainRunning || pr?.subagentCount !== nr?.subagentCount || pr?.runningSubagentCount !== nr?.runningSubagentCount || - pr?.mainActivity?.signature !== nr?.mainActivity?.signature + pr?.mainActivity?.signature !== nr?.mainActivity?.signature || + pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs ) { return false; } @@ -1032,7 +1323,8 @@ function isEquivalentTelemetry(prev, next) { pSubs[j]?.role !== nSubs[j]?.role || pSubs[j]?.isRunning !== nSubs[j]?.isRunning || pSubs[j]?.stepCount !== nSubs[j]?.stepCount || - pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature + pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature || + pSubs[j]?.liveActivity?.startedAtMs !== nSubs[j]?.liveActivity?.startedAtMs ) { return false; } @@ -1043,25 +1335,46 @@ function isEquivalentTelemetry(prev, next) { } async function fetchTelemetry({ force = false } = {}) { + if (!force && activeForceCount > 0) { + return telemetryStore.getState().telemetry; + } + const st = telemetryStore.getState(); const reqSeq = ++latestRequestSeq; const startMs = Date.now(); if (force) { + activeForceCount += 1; + if (pollTimer) { + clearTimeout(pollTimer); + pollTimer = null; + } telemetryStore.setState({ syncState: 'syncing' }); } try { + if (isWindowOverlayMode()) { + const liveRouteId = extractHostRouteCascadeId(); + if (liveRouteId !== st.hostRouteConversationId) { + const patch = { hostRouteConversationId: liveRouteId }; + if (liveRouteId && st.selectedConversationId && st.selectedConversationId !== liveRouteId) { + patch.selectedConversationId = ''; + } + telemetryStore.setState(patch); + } + } + const curSt = telemetryStore.getState(); + const effectiveConvId = curSt.selectedConversationId || curSt.hostRouteConversationId || ''; const params = new URLSearchParams(); - if (st.selectedConversationId) { - params.set('conversationId', st.selectedConversationId); + if (effectiveConvId) { + params.set('conversationId', effectiveConvId); } - if (st.selectedTimeRange) { - params.set('range', st.selectedTimeRange); + if (curSt.selectedTimeRange) { + params.set('range', curSt.selectedTimeRange); } - if (st.selectedTimeRange === 'custom') { - if (st.customStartMs > 0) params.set('startMs', String(st.customStartMs)); - if (st.customEndMs > 0) params.set('endMs', String(st.customEndMs)); + if (curSt.selectedTimeRange === 'custom') { + if (curSt.customStartMs > 0) params.set('startMs', String(curSt.customStartMs)); + if (curSt.customEndMs > 0) params.set('endMs', String(curSt.customEndMs)); } if (force) { params.set('force', '1'); @@ -1069,7 +1382,7 @@ async function fetchTelemetry({ force = false } = {}) { const qs = params.toString(); const payload = await callSidecarApi(`/api/telemetry${qs ? `?${qs}` : ''}`, { method: 'GET', - abortKey: 'telemetry-poll', + abortKey: force ? 'telemetry-force' : 'telemetry-poll', }); if (reqSeq !== latestRequestSeq) { @@ -1078,7 +1391,11 @@ async function fetchTelemetry({ force = false } = {}) { if (payload?.uiBundleVersion) { if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) { - if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { + if ( + !isWindowOverlayMode() && + typeof window !== 'undefined' && + typeof window.location?.reload === 'function' + ) { window.location.reload(); return payload; } @@ -1098,6 +1415,7 @@ async function fetchTelemetry({ force = false } = {}) { if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ telemetry: payload, + minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', }); feedbackTimer = setTimeout(() => { @@ -1109,6 +1427,7 @@ async function fetchTelemetry({ force = false } = {}) { const nextTelemetry = isSame ? latestSt.telemetry : payload; telemetryStore.setState({ telemetry: nextTelemetry, + minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); } @@ -1117,37 +1436,46 @@ async function fetchTelemetry({ force = false } = {}) { if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null; telemetryStore.setState({ syncState: 'error' }); return null; + } finally { + if (force) { + activeForceCount = Math.max(0, activeForceCount - 1); + if (activeForceCount === 0 && loopActive && loopTickFn && !pollTimer) { + pollTimer = setTimeout(loopTickFn, loopIntervalMs); + } + } } } async function saveSettingsPatch(patch) { + const safePatch = patch && typeof patch === 'object' ? { ...patch } : {}; + if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { + const mode = safePatch.weeklyLimitMode; + safePatch.weeklyLimitMode = + mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official'; + } + if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) { + safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession); + } + if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { + safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); + } const prevTelemetry = telemetryStore.getState().telemetry; if (prevTelemetry?.settings) { telemetryStore.setState({ telemetry: { ...prevTelemetry, - settings: { ...prevTelemetry.settings, ...patch }, - activeConversation: patch.contextWindowLimit - ? { - ...prevTelemetry.activeConversation, - context: { - ...prevTelemetry.activeConversation?.context, - limitTokens: patch.contextWindowLimit, - usedPct: Math.min( - 100, - Math.round( - ((prevTelemetry.activeConversation?.context?.totalTokens || 0) / - Math.max(1, patch.contextWindowLimit)) * - 100 - ) - ), - }, - } - : prevTelemetry.activeConversation, + settings: { ...prevTelemetry.settings, ...safePatch }, }, }); } - await callSidecarApi('/api/settings', { method: 'POST', body: patch }); + try { + await callSidecarApi('/api/settings', { method: 'POST', body: safePatch }); + } catch (err) { + if (prevTelemetry) { + telemetryStore.setState({ telemetry: prevTelemetry }); + } + throw err; + } await fetchTelemetry({ force: true }); } @@ -1161,7 +1489,11 @@ async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { await new Promise((r) => setTimeout(r, 1100)); - if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { + if ( + !isWindowOverlayMode() && + typeof window !== 'undefined' && + typeof window.location?.reload === 'function' + ) { window.location.reload(); return res; } @@ -1172,27 +1504,44 @@ async function triggerPluginUpdate() { function startAsyncTelemetryLoop(intervalMs = 2000) { stopAsyncTelemetryLoop(); - let active = true; + loopActive = true; + loopIntervalMs = intervalMs; + + const resolveNextDelay = () => { + if (isWindowOverlayMode() && typeof document !== 'undefined' && document.hidden) { + return Math.max(loopIntervalMs, 8000); + } + return loopIntervalMs; + }; const tick = async () => { - if (!active) return; + pollTimer = null; + if (!loopActive) return; await fetchTelemetry({ force: false }); - if (!active) return; - pollTimer = setTimeout(tick, intervalMs); + if (!loopActive || activeForceCount > 0) return; + if (!pollTimer) { + pollTimer = setTimeout(tick, resolveNextDelay()); + } }; + loopTickFn = tick; tick(); return () => { - active = false; stopAsyncTelemetryLoop(); }; } function stopAsyncTelemetryLoop() { + loopActive = false; + loopTickFn = null; if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; } + if (feedbackTimer) { + clearTimeout(feedbackTimer); + feedbackTimer = null; + } } /** @@ -1446,7 +1795,7 @@ const TopLongPillNav = defineComponent({ const CustomSelect = defineComponent({ name: 'CustomSelect', - setup({ getProps, emit, onCleanup }) { + setup({ getProps, setProps, emit, onCleanup }) { let isOpen = false; let focusedIndex = -1; @@ -1504,6 +1853,7 @@ const CustomSelect = defineComponent({ const prevVal = getProps().modelValue; toggleOpen(false); if (option.value !== prevVal) { + setProps({ modelValue: option.value }); emit('update:modelValue', option.value); } } @@ -1519,6 +1869,7 @@ const CustomSelect = defineComponent({ } else { focusedIndex = (focusedIndex + 1) % opts.length; renderMenuOptions(); + menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' }); } } else if (e.key === 'ArrowUp') { e.preventDefault(); @@ -1527,6 +1878,7 @@ const CustomSelect = defineComponent({ } else { focusedIndex = (focusedIndex - 1 + opts.length) % opts.length; renderMenuOptions(); + menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' }); } } else if (e.key === 'Enter' && isOpen) { e.preventDefault(); @@ -1587,17 +1939,17 @@ const CustomSelect = defineComponent({ if (icon) { patchSvgIcon(leadIcon, icon); } - const selectedOpt = - options.find((o) => o.value === modelValue) || - (!modelValue ? options[0] : undefined); - patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder); + const matchedOpt = options.find((o) => o.value === modelValue); + const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined); + const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder; + patchText(triggerLabel, selectedOpt ? selectedOpt.label : fallbackText); if (isOpen) { renderMenuOptions(); } } const handleDocClick = (e) => { - if (isOpen && !rootEl.contains(e.target)) { + if (isOpen && !isEventInside(e, rootEl)) { toggleOpen(false); } }; @@ -1613,14 +1965,8 @@ const CustomSelect = defineComponent({ el: rootEl, refs: { triggerBtn, triggerLabel, menuEl }, onPropsChange: syncTriggerAndMenu, - getValue: () => getProps().modelValue, methods: { - open: () => toggleOpen(true), close: () => toggleOpen(false), - selectByValue: (val) => { - const found = (getProps().options || []).find((o) => o.value === val); - if (found) chooseOption(found); - }, }, }; }, @@ -1636,7 +1982,7 @@ const CustomSelect = defineComponent({ const CustomNumberInput = defineComponent({ name: 'CustomNumberInput', - setup({ getProps, emit }) { + setup({ getProps, setProps, emit }) { function clampValue(raw) { const { min = -Infinity, max = Infinity, precision = 0 } = getProps(); const num = Number(raw); @@ -1653,6 +1999,7 @@ const CustomNumberInput = defineComponent({ const next = clampValue(current + direction * step * multiplier); syncFieldDisplay(next); if (next !== current) { + setProps({ modelValue: next }); emit('update:modelValue', next); } } @@ -1706,11 +2053,22 @@ const CustomNumberInput = defineComponent({ }); function commitManualInput() { - const rawText = String(textField.value || '').replace(/[^0-9.-]/g, ''); - const next = clampValue(rawText); + const raw = String(textField.value ?? '').trim(); + if (!raw || !/\d/.test(raw)) { + syncFieldDisplay(getProps().modelValue); + return; + } + const cleaned = raw.replace(/[^0-9.-]/g, ''); + const parsed = Number(cleaned); + if (!Number.isFinite(parsed)) { + syncFieldDisplay(getProps().modelValue); + return; + } + const next = clampValue(parsed); const prev = Number(getProps().modelValue); syncFieldDisplay(next); if (next !== prev) { + setProps({ modelValue: next }); emit('update:modelValue', next); } } @@ -1733,10 +2091,8 @@ const CustomNumberInput = defineComponent({ el: rootEl, refs: { decBtn, incBtn, textField }, onPropsChange: () => syncFieldDisplay(), - getValue: () => clampValue(textField.value), methods: { - stepUp: (mult = 1) => applyStep(1, mult), - stepDown: (mult = 1) => applyStep(-1, mult), + commit: () => commitManualInput(), }, }; }, @@ -1859,9 +2215,9 @@ const CustomDateTimePicker = defineComponent({ function adjustTime(part, delta) { const cur = new Date(getProps().modelValue || Date.now()); if (part === 'hour') { - cur.setHours((cur.getHours() + delta + 24) % 24); + cur.setHours(cur.getHours() + delta); } else { - cur.setMinutes((cur.getMinutes() + delta + 60) % 60); + cur.setMinutes(cur.getMinutes() + delta); } const nextMs = cur.getTime(); viewYear = cur.getFullYear(); @@ -1992,7 +2348,7 @@ const CustomDateTimePicker = defineComponent({ } const handleDocClick = (e) => { - if (isOpen && !rootEl.contains(e.target)) { + if (isOpen && !isEventInside(e, rootEl)) { togglePopover(false); } }; @@ -2008,16 +2364,6 @@ const CustomDateTimePicker = defineComponent({ el: rootEl, refs: { triggerBtn, triggerText, popoverEl, daysGrid, hourValSpan, minValSpan }, onPropsChange: syncDisplay, - getValue: () => Number(getProps().modelValue || 0), - methods: { - open: () => togglePopover(true), - close: () => togglePopover(false), - selectDayByOffset: (daysDelta) => { - const cur = new Date(getProps().modelValue || Date.now()); - cur.setDate(cur.getDate() + daysDelta); - emit('update:modelValue', cur.getTime()); - }, - }, }; }, }); @@ -2026,13 +2372,13 @@ const CustomDateTimePicker = defineComponent({ /** * @fileoverview Bespoke custom scrollbar component (零原生滚动条). * Hides native OS scrollbars completely and renders a precision 4px floating - * rail + GPU-translated thumb with drag, track-jump, and modelValue ratio emit. + * rail + GPU-translated thumb with drag and track-jump support. */ const CustomScrollbar = defineComponent({ name: 'CustomScrollbar', - setup({ getProps, emit, onCleanup }) { + setup({ getProps, onCleanup }) { const contentEl = getProps().contentEl || h('div'); contentEl.classList.add('custom-scroll-content'); @@ -2084,11 +2430,6 @@ const CustomScrollbar = defineComponent({ function onContentScroll() { syncThumb(); - const overflow = (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0); - if (overflow > 1) { - const ratio = +Math.max(0, Math.min(1, (contentEl.scrollTop || 0) / overflow)).toFixed(3); - emit('update:modelValue', ratio); - } } function onDocMouseMove(e) { @@ -2186,12 +2527,6 @@ const CustomScrollbar = defineComponent({ refresh() { scheduleSyncThumb(); }, - scrollToRatio(ratio) { - const r = Math.max(0, Math.min(1, Number(ratio || 0))); - const overflow = Math.max(0, (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0)); - contentEl.scrollTop = Math.round(r * overflow); - syncThumb(); - }, }, }; }, @@ -2206,7 +2541,7 @@ const CustomScrollbar = defineComponent({ const SegmentedControl = defineComponent({ name: 'SegmentedControl', - setup({ getProps, emit }) { + setup({ getProps, setProps, emit }) { const rootEl = h('div', { className: 'segmented', role: 'group', @@ -2225,6 +2560,7 @@ const SegmentedControl = defineComponent({ onClick: (e) => { e.stopPropagation(); if (getProps().modelValue !== opt.value) { + setProps({ modelValue: opt.value }); emit('update:modelValue', opt.value); } }, @@ -2398,17 +2734,22 @@ function createFourSegmentBar() { */ +let chartUidCounter = 0; + +function safeSlotTokens(v) { + const n = Number(v); + return Number.isFinite(n) && n > 0 ? n : 0; +} + /** * 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。 * 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平, * 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。 * - * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组 + * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组(长度 >= 2) * @returns {string} SVG `` 的 `d` 属性字符串 */ function buildSmoothSplinePath(points) { - if (!points.length) return ''; - if (points.length === 1) return `M ${points[0].x} ${points[0].y}`; let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; for (let i = 0; i < points.length - 1; i++) { const p0 = points[i]; @@ -2465,10 +2806,11 @@ function createTrendAreaChart() { svg.setAttribute('class', 'trend-svg'); svg.setAttribute('aria-hidden', 'true'); - // 垂直线性渐变 + // 垂直线性渐变(每实例独立 ID,避免多图表挂载时 SVG url(#...) 冲突) + const gradId = `trend-area-grad-${++chartUidCounter}`; const defs = document.createElementNS(SVG_NS, 'defs'); const grad = document.createElementNS(SVG_NS, 'linearGradient'); - grad.setAttribute('id', 'trend-area-grad'); + grad.setAttribute('id', gradId); grad.setAttribute('x1', '0'); grad.setAttribute('y1', '0'); grad.setAttribute('x2', '0'); @@ -2507,7 +2849,7 @@ function createTrendAreaChart() { svg.appendChild(vGridGroup); const areaPath = document.createElementNS(SVG_NS, 'path'); - areaPath.setAttribute('fill', 'url(#trend-area-grad)'); + areaPath.setAttribute('fill', `url(#${gradId})`); svg.appendChild(areaPath); const linePath = document.createElementNS(SVG_NS, 'path'); @@ -2590,18 +2932,20 @@ function createTrendAreaChart() { patchAttr(tooltipEl, 'hidden', false); patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); - patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`); - patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`); + patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`); + const slotTok = safeSlotTokens(slot.tokens); + patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`); + const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; patchText( tipCostEl, - formatUsd(Number(slot.costUsd || 0), { + formatUsd(slotCost, { unpricedCalls: slot.unpricedCalls, - precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1, + precise: slotCost > 0 && slotCost < 0.1, }) ); const hasSubBreakdown = - Number(slot.tokens || 0) > 0 && + slotTok > 0 && (slot.inputTokens !== undefined || slot.cacheReadTokens !== undefined || slot.outputTokens !== undefined); @@ -2609,7 +2953,7 @@ function createTrendAreaChart() { if (hasSubBreakdown) { patchText( tipSubEl, - `入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}` + `入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}` ); } @@ -2656,7 +3000,7 @@ function createTrendAreaChart() { */ function update(series = []) { const slots = - Array.isArray(series) && series.length >= 2 + Array.isArray(series) && series.length >= 1 ? series : [ { label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 }, @@ -2669,7 +3013,7 @@ function createTrendAreaChart() { let maxTokens = 0; let peakIdx = 0; for (let i = 0; i < slots.length; i++) { - const t = Number(slots[i].tokens || 0); + const t = safeSlotTokens(slots[i]?.tokens); if (t >= maxTokens) { maxTokens = t; peakIdx = i; @@ -2677,22 +3021,32 @@ function createTrendAreaChart() { } const denom = Math.max(1, maxTokens); + const isSingle = slots.length === 1; const pts = slots.map((s, idx) => { - const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X; - const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0; + const tok = safeSlotTokens(s?.tokens); + const x = isSingle ? (LEFT_X + RIGHT_X) / 2 : LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X; + const ratio = maxTokens > 0 ? tok / denom : 0; const y = BOTTOM_Y - ratio * SPAN_Y; - return { x, y, tokens: Number(s.tokens || 0) }; + return { x, y, tokens: tok }; }); currentPts = pts; const sig = slots - .map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`) + .map((s) => `${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`) .join('|'); if (sig !== lastRenderSig) { lastRenderSig = sig; - const lineD = buildSmoothSplinePath(pts); - const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; + let lineD; + let areaD; + if (isSingle) { + const yStr = pts[0].y.toFixed(1); + lineD = `M ${LEFT_X.toFixed(1)} ${yStr} L ${RIGHT_X.toFixed(1)} ${yStr}`; + areaD = `${lineD} L ${RIGHT_X.toFixed(1)} ${BOTTOM_Y} L ${LEFT_X.toFixed(1)} ${BOTTOM_Y} Z`; + } else { + lineD = buildSmoothSplinePath(pts); + areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; + } patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', areaD); @@ -2717,8 +3071,8 @@ function createTrendAreaChart() { vGridGroup.appendChild(vLine); } - const isFirst = i === 0; - const isLast = i === tickIndices.length - 1; + const isFirst = !isSingle && i === 0; + const isLast = !isSingle && i === tickIndices.length - 1; const pct = (pt.x / VIEW_W) * 100; const tickEl = h('span', { className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, @@ -2759,7 +3113,9 @@ function createTrendAreaChart() { const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); - if (hoveredIdx >= 0 && hoveredIdx < slots.length) { + if (hoveredIdx >= slots.length) { + clearHover(); + } else if (hoveredIdx >= 0) { showHoverAtIndex(hoveredIdx); } } @@ -2873,22 +3229,64 @@ const TopSessionHeader = defineComponent({ lastActiveCascadeId = currentCascadeId; } + const actConv = telemetry?.activeConversation; const convs = telemetry?.conversations || []; - const latestTitle = convs[0]?.title ? `最新 (${convs[0].title})` : '跟随最新会话'; + const hostRouteId = telSt.hostRouteConversationId || ''; + const hostMatchedConv = hostRouteId + ? convs.find((c) => c.cascadeId === hostRouteId) || + (actConv?.cascadeId === hostRouteId ? actConv : null) + : null; + const defaultOptLabel = hostRouteId + ? hostMatchedConv?.title + ? `当前窗口 (${hostMatchedConv.title})` + : `当前窗口 (${hostRouteId.slice(0, 8)})` + : convs[0]?.title + ? `最新 (${convs[0].title})` + : '跟随最新会话'; + const defaultOptMeta = hostRouteId + ? hostMatchedConv + ? formatConvOptionMeta({ + stepCount: hostMatchedConv.stepCount, + subagentCount: hostMatchedConv.subagentCount, + totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents, + }) + : '' + : convs[0] + ? formatConvOptionMeta(convs[0]) + : ''; const options = [ - { value: '', label: latestTitle, meta: convs[0] ? formatConvOptionMeta(convs[0]) : '' }, + { value: '', label: defaultOptLabel, meta: defaultOptMeta }, ...convs.map((c) => ({ value: c.cascadeId, label: c.title || c.cascadeId.slice(0, 8), meta: formatConvOptionMeta(c), })), ]; + const lockedId = telSt.selectedConversationId; + if (lockedId && !convs.some((c) => c.cascadeId === lockedId)) { + const isLoadedLocked = actConv?.cascadeId === lockedId; + const lockedTitle = + isLoadedLocked && actConv?.title + ? actConv.title + : `已锁定会话 (${String(lockedId).slice(0, 8)})`; + const lockedMeta = isLoadedLocked + ? formatConvOptionMeta({ + stepCount: actConv.stepCount, + subagentCount: actConv.subagentCount, + totalStepCount: actConv.totalStepsAllAgents, + }) + : '已锁定'; + options.splice(1, 0, { + value: lockedId, + label: lockedTitle, + meta: lockedMeta, + }); + } convSelect.setProps({ modelValue: telSt.selectedConversationId, options, }); - const actConv = telemetry?.activeConversation; const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0); const aggregated = actConv?.aggregated; @@ -2971,6 +3369,7 @@ const TopSessionHeader = defineComponent({ const unsubTelemetry = telemetryStore.subscribe( (st) => ({ selectedConversationId: st.selectedConversationId, + hostRouteConversationId: st.hostRouteConversationId, syncState: st.syncState, telemetry: st.telemetry, }), @@ -2994,9 +3393,9 @@ const TopSessionHeader = defineComponent({ * @fileoverview View 1: LiveOverviewView (实时监控视图). * 负责展示当前活跃会话的核心实时遥测指标: * 1. 4 格实时测速矩阵:实时吞吐 (TPS)、首 Token 延迟 (TTFT)、会话有效加权均速与本步费用/缓存命中率; - * 2. 6 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`), - * 通过 6 段进度条与双列图例展示消息、系统工具、MCP 工具、Skill、系统提示词与用户规则的 Token 占用; - * 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon 周配额池、Claude & GPT 等动态配额池, + * 2. 10 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`), + * 通过 10 段进度条与双列图例展示模型回复、工具结果、用户消息、子代理通知、压缩摘要及系统提示词/工具/MCP/Skill/规则的 Token 占用; + * 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon/Carbon 周配额池、Claude & GPT 等动态配额池, * 自动适配 5h/每周双窗口或单窗口模式,并展示本机周累计消耗与 AI 积分脚标。 */ @@ -3015,6 +3414,239 @@ function estPillWidth(text) { return Math.ceil(w); } +/** + * 10 通道上下文窗口构成定义(供实时监控主视图与主窗口顶栏悬停概览卡共享)。 + */ +const CTX_CHANNEL_DEFS = [ + { + key: 'assistant', + label: '模型回复', + segClass: 'seg-assistant', + title: '模型推理思考、回复正文与工具调用入参', + getValue: (c) => Number(c.assistantTokens || 0), + }, + { + key: 'toolResults', + label: '工具结果', + segClass: 'seg-tool-results', + title: '文件读取、终端输出与工具执行返回内容', + getValue: (c) => Number(c.toolResultsTokens || 0), + }, + { + key: 'userInput', + label: '用户消息', + segClass: 'seg-user-input', + title: '用户提问文本与上传附件', + getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), + }, + { + key: 'subagent', + label: '子代理通知', + segClass: 'seg-subagent-msg', + title: '子代理完成汇报与后台任务系统通知', + getValue: (c) => Number(c.subagentTokens || 0), + }, + { + key: 'checkpoint', + label: '压缩摘要', + segClass: 'seg-checkpoint', + title: '自动上下文压缩生成的历史摘要检查点', + getValue: (c) => Number(c.checkpointTokens || 0), + }, + { + key: 'systemPrompt', + label: '系统提示词', + segClass: 'seg-system-prompt', + title: '核心身份、终端沙箱、制品与环境提示词', + getValue: (c) => Number(c.systemPromptTokens || 0), + }, + { + key: 'systemTools', + label: '系统工具', + segClass: 'seg-system-tools', + title: '内置系统工具 Schema 定义', + getValue: (c) => Number(c.systemToolsTokens || 0), + }, + { + key: 'mcpTools', + label: 'MCP 工具', + segClass: 'seg-mcp-tools', + title: 'MCP 外部服务工具与资源定义', + getValue: (c) => Number(c.mcpToolsTokens || 0), + }, + { + key: 'skills', + label: 'Skill', + segClass: 'seg-skills', + title: '已挂载的 Skills 技能索引与说明', + getValue: (c) => Number(c.skillsTokens || 0), + }, + { + key: 'userRules', + label: '用户规则', + segClass: 'seg-user-rules', + title: '全局与工作区自定义规则 (user_rules)', + getValue: (c) => Number(c.userRulesTokens || 0), + }, +]; + +/** + * 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。 + * + * @param {object|null|undefined} quotas + * @param {number} minuteTick + * @param {{ isPending?: boolean }} [options] + * @returns {Array} + */ +function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) { + const safeQuotas = quotas || {}; + const activePool = safeQuotas.activePool || {}; + const rawPools = + Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0 + ? safeQuotas.pools + : [ + { poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' }, + { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' }, + ]; + const weekly = safeQuotas.weekly || {}; + const poolItems = rawPools.map((p) => { + const key = p.poolKey || p.family || p.poolLabel || 'Other'; + const poolLabel = p.poolLabel || p.family || key; + const isActivePool = + Boolean(activePool.family) && + (activePool.poolKey === key || + activePool.family === p.family || + (key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family))); + return { + key, + poolLabel, + poolData: p, + fallbackWeekly: weekly, + isActivePool, + minuteTick, + isPending, + }; + }); + if ( + weekly?.isOfficial === false && + poolItems.length > 0 && + !poolItems.some((item) => item.isActivePool) + ) { + poolItems[0].isActivePool = true; + } + return poolItems; +} + +/** + * 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。 + */ +function createPoolQuotaRow() { + const title5h = h('span', { text: '5h 限额' }); + const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fill5h = h('div', { className: 'progress-fill' }); + const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [title5h, meta5h]), + h('div', { className: 'progress-track' }, [fill5h]), + ]); + + const titleWk = h('span', { text: '每周限额' }); + const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fillWk = h('div', { className: 'progress-fill' }); + const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [titleWk, metaWk]), + h('div', { className: 'progress-track' }, [fillWk]), + ]); + + const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ + row5h, + rowWk, + ]); + + return { + el, + refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk }, + }; +} + +/** + * 同步单个配额池行的 5h 与每周窗口状态: + * - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行; + * - 对于仅有 5h 限额的配额池自动隐藏每周行; + * - 若两个窗口均无数据(首次加载或拉取失败),同时保留两行以维持预占高度不跳动。 + */ +function syncPoolQuotaRow(refs, item, idx, rowEl) { + const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item; + patchAttr( + rowEl, + 'style', + idx === 0 + ? 'display: flex; flex-direction: column; gap: 8px;' + : 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' + ); + + const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; + const used5hVal = has5h ? Number(poolData.usedPct) : 0; + const rem5hVal = has5h ? Number(poolData.remainingPct) : 0; + + const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false); + const wkUsedRaw = useCustomWeekly + ? fallbackWeekly?.usedPct + : poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null); + const wkRemRaw = useCustomWeekly + ? fallbackWeekly?.remainingPct + : poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null); + const wkResetRaw = useCustomWeekly + ? fallbackWeekly?.resetTime || poolData?.weeklyResetTime + : poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null); + const hasWk = wkUsedRaw != null && wkRemRaw != null; + const usedWkVal = hasWk ? Number(wkUsedRaw) : 0; + const remWkVal = hasWk ? Number(wkRemRaw) : 0; + + // 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口 + const hide5h = !has5h && hasWk; + const hideWk = !hasWk && has5h; + refs.row5h.hidden = hide5h; + refs.row5h.style.display = hide5h ? 'none' : 'flex'; + refs.rowWk.hidden = hideWk; + refs.rowWk.style.display = hideWk ? 'none' : 'flex'; + + const fallbackMetaText = isPending ? '读取中...' : '获取失败 (--%)'; + + patchText(refs.title5h, `5h 限额 (${poolLabel})`); + patchText( + refs.meta5h, + has5h + ? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)` + : fallbackMetaText + ); + patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); + patchClasses(refs.fill5h, { + 'tone-warn': used5hVal >= 60 && used5hVal < 85, + 'tone-danger': used5hVal >= 85, + }); + + const customTitle = + isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title + ? fallbackWeekly.title + : `每周限额 (${poolLabel})`; + patchText(refs.titleWk, customTitle); + patchText( + refs.metaWk, + hasWk + ? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)` + : fallbackMetaText + ); + patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); + patchClasses(refs.fillWk, { + 'tone-warn': usedWkVal >= 60 && usedWkVal < 85, + 'tone-danger': usedWkVal >= 85, + }); +} + +function quotaPoolRowSig(item, idx) { + return `${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.remainingPct}:${item.fallbackWeekly?.resetTime}:${item.fallbackWeekly?.title}`; +} + const LiveOverviewView = defineComponent({ name: 'LiveOverviewView', setup({ onCleanup }) { @@ -3028,6 +3660,7 @@ const LiveOverviewView = defineComponent({ const expandedTaskConvIds = new Set(); const activityTimersMap = new Map(); let liveTickTimer = null; + let countdownTickTimer = null; function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { const now = Date.now(); @@ -3053,22 +3686,51 @@ const LiveOverviewView = defineComponent({ } } - function stopLiveTicker() { + function pauseLiveTicker() { if (liveTickTimer) { clearInterval(liveTickTimer); liveTickTimer = null; } + } + + function stopLiveTicker() { + pauseLiveTicker(); activityTimersMap.clear(); } function ensureLiveTicker() { + if (uiStore.getState().activeView !== 'overview' || activityTimersMap.size === 0) { + pauseLiveTicker(); + return; + } if (!liveTickTimer) { liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000); } } + function stopCountdownTicker() { + if (countdownTickTimer) { + clearInterval(countdownTickTimer); + countdownTickTimer = null; + } + } + + function ensureCountdownTicker() { + if (uiStore.getState().activeView !== 'overview') { + stopCountdownTicker(); + return; + } + if (!countdownTickTimer) { + countdownTickTimer = setInterval(() => { + if (uiStore.getState().activeView === 'overview' && latestData) { + renderData(latestData); + } + }, 30_000); + } + } + function createLiveTaskCard() { - const dotIcon = createSvgIcon('dot', { size: 9 }); + const dotIcon = createSvgIcon('dot', { size: 11 }); patchClasses(dotIcon, { 'is-pulsing': true }); const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' }); @@ -3088,7 +3750,11 @@ const LiveOverviewView = defineComponent({ h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), ]); - const mainBadge = h('span', { className: 'agent-badge badge-main', text: '主' }); + const mainBadge = h('span', { + className: 'agent-badge badge-main', + hidden: true, + text: '主', + }); const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' }); const mainProgress = h('span', { className: 'live-activity-progress text-mono', @@ -3121,6 +3787,7 @@ const LiveOverviewView = defineComponent({ titleEl, subToggleBtn, elapsedEl, + mainBadge, mainPhase, mainProgress, mainSep, @@ -3168,7 +3835,7 @@ const LiveOverviewView = defineComponent({ const avgVal = h('strong', { className: 'cell-value', text: '—' }); const avgSub = h('span', { className: 'cell-sub', text: '有效样本 0/0 步' }); - const costVal = h('strong', { className: 'cell-value', text: '$0.000' }); + const costVal = h('strong', { className: 'cell-value', text: '—' }); const cacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累计 $0.00' }); const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '实时指标' }, [ @@ -3219,78 +3886,7 @@ const LiveOverviewView = defineComponent({ [ctxPillGroup] ); - const ctxChannels = [ - { - key: 'assistant', - label: '模型回复', - segClass: 'seg-assistant', - title: '模型推理思考、回复正文与工具调用入参', - getValue: (c) => Number(c.assistantTokens || 0), - }, - { - key: 'toolResults', - label: '工具结果', - segClass: 'seg-tool-results', - title: '文件读取、终端输出与工具执行返回内容', - getValue: (c) => Number(c.toolResultsTokens || 0), - }, - { - key: 'userInput', - label: '用户消息', - segClass: 'seg-user-input', - title: '用户提问文本与上传附件', - getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), - }, - { - key: 'subagent', - label: '子代理通知', - segClass: 'seg-subagent-msg', - title: '子代理完成汇报与后台任务系统通知', - getValue: (c) => Number(c.subagentTokens || 0), - }, - { - key: 'checkpoint', - label: '压缩摘要', - segClass: 'seg-checkpoint', - title: '自动上下文压缩生成的历史摘要检查点', - getValue: (c) => Number(c.checkpointTokens || 0), - }, - { - key: 'systemPrompt', - label: '系统提示词', - segClass: 'seg-system-prompt', - title: '核心身份、终端沙箱、制品与环境提示词', - getValue: (c) => Number(c.systemPromptTokens || 0), - }, - { - key: 'systemTools', - label: '系统工具', - segClass: 'seg-system-tools', - title: '内置系统工具 Schema 定义', - getValue: (c) => Number(c.systemToolsTokens || 0), - }, - { - key: 'mcpTools', - label: 'MCP 工具', - segClass: 'seg-mcp-tools', - title: 'MCP 外部服务工具与资源定义', - getValue: (c) => Number(c.mcpToolsTokens || 0), - }, - { - key: 'skills', - label: 'Skill', - segClass: 'seg-skills', - title: '已挂载的 Skills 技能索引与说明', - getValue: (c) => Number(c.skillsTokens || 0), - }, - { - key: 'userRules', - label: '用户规则', - segClass: 'seg-user-rules', - title: '全局与工作区自定义规则 (user_rules)', - getValue: (c) => Number(c.userRulesTokens || 0), - }, - ].map((ch, idx) => { + const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => { const valEl = h('strong', { className: 'text-mono', text: '0' }); const itemEl = h('div', { className: 'legend-item', title: ch.title }, [ h('span', { className: 'legend-left' }, [ @@ -3327,37 +3923,6 @@ const LiveOverviewView = defineComponent({ const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); const poolsListEl = h('div', { style: 'display: flex; flex-direction: column; gap: 0;' }); - /** - * 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。 - */ - function createPoolQuotaRow() { - const title5h = h('span', { text: '5h 限额' }); - const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' }); - const fill5h = h('div', { className: 'progress-fill' }); - const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ - h('div', { className: 'panel-header' }, [title5h, meta5h]), - h('div', { className: 'progress-track' }, [fill5h]), - ]); - - const titleWk = h('span', { text: '每周限额' }); - const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' }); - const fillWk = h('div', { className: 'progress-fill' }); - const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ - h('div', { className: 'panel-header' }, [titleWk, metaWk]), - h('div', { className: 'progress-track' }, [fillWk]), - ]); - - const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ - row5h, - rowWk, - ]); - - return { - el, - refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk }, - }; - } - const wkFootLeft = h('span', { className: 'text-muted', text: '本周累计: 0 ($0.00)' }); const wkFootRight = h('span', { className: 'text-muted', text: '' }); @@ -3388,75 +3953,6 @@ const LiveOverviewView = defineComponent({ className: 'view-pane', }); - /** - * 同步单个配额池行的 5h 与每周窗口状态: - * - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行; - * - 对于仅有 5h 限额的配额池自动隐藏每周行; - * - 若两个窗口均无数据(如首次拉取失败),则同时保留两行并显示“获取失败 (--%)”占位提示。 - */ - function syncPoolQuotaRow(refs, item, idx, rowEl) { - const { poolData, poolLabel, fallbackWeekly, isActivePool } = item; - patchAttr( - rowEl, - 'style', - idx === 0 - ? 'display: flex; flex-direction: column; gap: 8px;' - : 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' - ); - - const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; - const used5hVal = has5h ? Number(poolData.usedPct) : 0; - const rem5hVal = has5h ? Number(poolData.remainingPct) : 0; - - const wkUsedRaw = - poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null); - const wkRemRaw = - poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null); - const wkResetRaw = - poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null); - const hasWk = wkUsedRaw != null && wkRemRaw != null; - const usedWkVal = hasWk ? Number(wkUsedRaw) : 0; - const remWkVal = hasWk ? Number(wkRemRaw) : 0; - - // 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口 - const hide5h = !has5h && hasWk; - const hideWk = !hasWk && has5h; - refs.row5h.hidden = hide5h; - refs.row5h.style.display = hide5h ? 'none' : 'flex'; - refs.rowWk.hidden = hideWk; - refs.rowWk.style.display = hideWk ? 'none' : 'flex'; - - patchText(refs.title5h, `5h 限额 (${poolLabel})`); - patchText( - refs.meta5h, - has5h - ? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)` - : '获取失败 (--%)' - ); - patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); - patchClasses(refs.fill5h, { - 'tone-warn': used5hVal >= 60 && used5hVal < 85, - 'tone-danger': used5hVal >= 85, - }); - - const customTitle = - isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title - ? fallbackWeekly.title - : `每周限额 (${poolLabel})`; - patchText(refs.titleWk, customTitle); - patchText( - refs.metaWk, - hasWk - ? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)` - : '获取失败 (--%)' - ); - patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); - patchClasses(refs.fillWk, { - 'tone-warn': usedWkVal >= 60 && usedWkVal < 85, - 'tone-danger': usedWkVal >= 85, - }); - } - let latestData = null; let isDirty = false; let ctxPillsExpanded = false; @@ -3568,10 +4064,10 @@ const LiveOverviewView = defineComponent({ const subSig = (item.subagents || []) .map( (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}` + `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${subSig}`; + return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { @@ -3585,7 +4081,11 @@ const LiveOverviewView = defineComponent({ }; const isWaiting = act.phase === 'waiting'; - patchClasses(refs.cardEl, { 'is-waiting': isWaiting }); + const isCompacting = act.phase === 'compacting'; + patchClasses(refs.cardEl, { + 'is-waiting': isWaiting, + 'is-compacting': isCompacting, + }); patchClasses(refs.dotIcon, { 'is-pulsing': true }); const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话'; @@ -3602,6 +4102,7 @@ const LiveOverviewView = defineComponent({ const subCount = Number(item.subagentCount || item.subagents?.length || 0); const runSubCount = Number(item.runningSubagentCount || 0); const isExpanded = expandedTaskConvIds.has(item.cascadeId); + patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); if (subCount > 0) { const arrow = isExpanded ? '▾' : '▸'; @@ -3721,14 +4222,19 @@ const LiveOverviewView = defineComponent({ ensureLiveTicker(); } - // 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标) + // 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标,遵循模型名称格式设置) + const showUpstream = Boolean(data.settings?.showUpstreamModel); + const activeModelDisplay = + (showUpstream + ? active.activeModelUpstream || active.activeModelShort + : active.activeModelShort) || '模型未知'; patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) }); patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s')); const reason = speedReasonText(active.latestSpeedReason); const modelAndAgent = hasSubagents && active.activeAgentBadge - ? `[${active.activeAgentBadge}] ${active.activeModelShort || '模型未知'}` - : active.activeModelShort || '模型未知'; + ? `[${active.activeAgentBadge}] ${activeModelDisplay}` + : activeModelDisplay; patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent); patchText(ttftVal, formatMetric(active.latestTtftSec, 's')); @@ -3738,7 +4244,11 @@ const LiveOverviewView = defineComponent({ patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`); const stepCost = active.latestStepCostUsd; - patchText(costVal, formatUsd(stepCost, { precise: true })); + const hasAnySteps = Number(active.stepCount || 0) > 0; + patchText( + costVal, + !hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true }) + ); patchText( cacheSub, `缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}` @@ -3766,10 +4276,13 @@ const LiveOverviewView = defineComponent({ const allAgentPills = agents.map((ag) => { const agPct = ag.context?.usedPct ?? 0; + const agModelDisplay = + (showUpstream ? ag.activeModelUpstream || ag.activeModelShort : ag.activeModelShort) || + '模型未知'; return { key: ag.agentId, label: `${ag.badgeText || ag.shortLabel} ${agPct}%`, - title: `${formatAgentLabel(ag)} (${ag.activeModelShort || '模型未知'} · ${ag.stepCount || 0}步)`, + title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${ag.stepCount || 0}步)`, isActive: effectiveCtxScope === ag.agentId, mode: 'ctx-only', }; @@ -3851,12 +4364,8 @@ const LiveOverviewView = defineComponent({ if (item.mode === 'toggle-expand') { ctxPillsExpanded = !ctxPillsExpanded; renderData(latestData); - } else if (item.mode === 'ctx-only') { - uiStore.setState({ ctxInspectorAgentId: item.key }); - } else if (item.key === 'all') { - uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); } else { - uiStore.setState({ selectedAgentScope: item.key }); + uiStore.setState({ ctxInspectorAgentId: item.key }); } }; }, @@ -3891,37 +4400,13 @@ const LiveOverviewView = defineComponent({ tierBadge, `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` ); - const activePool = quotas.activePool || {}; - const rawPools = Array.isArray(quotas.pools) && quotas.pools.length > 0 - ? quotas.pools - : [ - { poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' }, - { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' }, - ]; const weekly = quotas.weekly || {}; const minuteTick = Math.floor(Date.now() / 30000); - const poolItems = rawPools.map((p) => { - const key = p.poolKey || p.family || p.poolLabel || 'Other'; - const poolLabel = p.poolLabel || p.family || key; - const isActivePool = - Boolean(activePool.family) && - (activePool.poolKey === key || - activePool.family === p.family || - (key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family))); - return { - key, - poolLabel, - poolData: p, - fallbackWeekly: weekly, - isActivePool, - minuteTick, - }; - }); + const poolItems = buildQuotaPoolItems(quotas, minuteTick); patchKeyedList(poolsListEl, poolItems, { keyFn: (item) => item.key, - sigFn: (item, idx) => - `${idx}:${item.poolLabel}:${item.isActivePool}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.title}`, + sigFn: quotaPoolRowSig, createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); @@ -3937,12 +4422,13 @@ const LiveOverviewView = defineComponent({ : `本周调用: ${weekly.calls || 0} 次` ); + ensureCountdownTicker(); viewScrollbar.refresh(); } const unsub = telemetryStore.subscribe( - (st) => st.telemetry, - (data) => { + (st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }), + ({ telemetry: data }) => { latestData = data; if (uiStore.getState().activeView !== 'overview') { const stillRunning = @@ -3974,12 +4460,18 @@ const LiveOverviewView = defineComponent({ prevCtxTarget = slice.ctxInspectorAgentId; if (slice.activeView !== 'overview') { + pauseLiveTicker(); + stopCountdownTicker(); if (scopeChanged) isDirty = true; return; } + ensureCountdownTicker(); if ((isDirty || scopeChanged) && latestData) { isDirty = false; renderData(latestData); + } else if (activityTimersMap.size > 0) { + updateLiveElapsedDisplay(); + ensureLiveTicker(); } } ); @@ -4002,6 +4494,7 @@ const LiveOverviewView = defineComponent({ onCleanup(() => { stopLiveTicker(); + stopCountdownTicker(); unsub(); unsubView(); if (ro) ro.disconnect(); @@ -4020,9 +4513,9 @@ const LiveOverviewView = defineComponent({ /** * @fileoverview View 2: ConsumptionView (全景消耗统计视图). * 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗: - * 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+2 组合矩阵展示总 Token/调用次数、 - * USD/CNY 预估费用、缓存命中率与命中量、输入/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。 - * 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡与首/中/末三时间锚点。 + * 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+3 组合矩阵展示总 Token/调用次数、 + * USD/CNY 预估费用、缓存命中率与命中量、新输入/缓存读取(含节省费用)/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。 + * 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡、对齐多刻度时间轴与悬停详情浮层。 * 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。 * 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。 * 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。 @@ -4044,27 +4537,45 @@ const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { // --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 --- + let draftStartMs = telemetryStore.getState().customStartMs; + let draftEndMs = telemetryStore.getState().customEndMs; + let hasUncommittedCustomDraft = false; + const timeFilterSwitch = SegmentedControl({ ariaLabel: '消耗统计时间范围', modelValue: telemetryStore.getState().selectedTimeRange, options: TIME_RANGE_OPTIONS, onUpdateModelValue: (nextRange) => { + if (nextRange === 'custom') { + const st = telemetryStore.getState(); + draftStartMs = st.customStartMs; + draftEndMs = st.customEndMs; + hasUncommittedCustomDraft = false; + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + } else { + hasUncommittedCustomDraft = false; + } telemetryStore.setState({ selectedTimeRange: nextRange }); fetchTelemetry({ force: false }); }, }); const startPicker = CustomDateTimePicker({ - modelValue: telemetryStore.getState().customStartMs, + modelValue: draftStartMs, onUpdateModelValue: (ms) => { - telemetryStore.setState({ customStartMs: ms }); + draftStartMs = ms; + hasUncommittedCustomDraft = true; + startPicker.setValue(ms); }, }); const endPicker = CustomDateTimePicker({ - modelValue: telemetryStore.getState().customEndMs, + modelValue: draftEndMs, onUpdateModelValue: (ms) => { - telemetryStore.setState({ customEndMs: ms }); + draftEndMs = ms; + hasUncommittedCustomDraft = true; + endPicker.setValue(ms); }, }); @@ -4075,20 +4586,20 @@ const ConsumptionView = defineComponent({ className: 'btn-primary', style: 'height: 26px; padding: 0 10px;', onClick: () => { - const st = telemetryStore.getState(); - const sMs = Number(st.customStartMs || 0); - const eMs = Number(st.customEndMs || 0); - if (sMs > 0 && eMs > 0 && sMs > eMs) { - startPicker.setValue(eMs); - endPicker.setValue(sMs); - telemetryStore.setState({ - selectedTimeRange: 'custom', - customStartMs: eMs, - customEndMs: sMs, - }); - } else { - telemetryStore.setState({ selectedTimeRange: 'custom' }); - } + const sMs = Number(draftStartMs || 0); + const eMs = Number(draftEndMs || 0); + const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; + const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + draftStartMs = minMs; + draftEndMs = maxMs; + hasUncommittedCustomDraft = false; + startPicker.setValue(minMs); + endPicker.setValue(maxMs); + telemetryStore.setState({ + selectedTimeRange: 'custom', + customStartMs: minMs, + customEndMs: maxMs, + }); fetchTelemetry({ force: true }); }, }, @@ -4110,7 +4621,7 @@ const ConsumptionView = defineComponent({ ] ); - // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 2 列输入/输出拆分 + 底部 4 段比例条) --- + // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' }); @@ -4122,7 +4633,11 @@ const ConsumptionView = defineComponent({ const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' }); const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); - const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '新输入 0 · 缓存 0' }); + const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '未命中缓存输入' }); + + const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: 11.5px;', text: '0%' }); + const cacheMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); + const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '节省 $0.00' }); const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' }); const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); @@ -4157,27 +4672,38 @@ const ConsumptionView = defineComponent({ h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), ]), ]), - h('div', { className: 'cons-split-2 cons-matrix-bottom' }, [ + h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ h('div', { className: 'cons-col' }, [ - h('div', { className: 'panel-header' }, [ - h('span', { className: 'legend-left' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ h('span', { className: 'dot-swatch seg-input' }), - h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输入用量' }), - inputMainTokens, + h('span', { text: '新输入' }), ]), inputSharePct, ]), + inputMainTokens, inputSubText, ]), h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'panel-header' }, [ - h('span', { className: 'legend-left' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存读取' }), + ]), + cacheSharePct, + ]), + cacheMainTokens, + cacheSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ h('span', { className: 'dot-swatch seg-output' }), - h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输出用量' }), - outputMainTokens, + h('span', { text: '输出用量' }), ]), outputSharePct, ]), + outputMainTokens, outputSubText, ]), ]), @@ -4412,8 +4938,12 @@ const ConsumptionView = defineComponent({ if (!slice) return; timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); - startPicker.setValue(slice.customStartMs); - endPicker.setValue(slice.customEndMs); + if (!hasUncommittedCustomDraft) { + draftStartMs = slice.customStartMs; + draftEndMs = slice.customEndMs; + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + } const cons = slice.consumption || {}; const preset = @@ -4432,6 +4962,7 @@ const ConsumptionView = defineComponent({ const responseTokens = Number(acct.responseTokens || 0); const thinkingTokens = Number(acct.thinkingTokens || 0); const costUsd = Number(acct.costUsd || 0); + const savedCostUsd = Number(acct.savedCostUsd || 0); patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); patchText(heroTotalCalls, `${acct.calls || 0} 次`); @@ -4441,13 +4972,37 @@ const ConsumptionView = defineComponent({ patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`); patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`); - const inPct = totalTokens > 0 ? +((inputTokens / totalTokens) * 100).toFixed(1) : 0; - const outPct = totalTokens > 0 ? +((outputTokens / totalTokens) * 100).toFixed(1) : 0; + let inPct = 0; + let cachePct = 0; + let outPct = 0; + if (totalTokens > 0) { + const rawTenths = [ + (inputTokens / totalTokens) * 1000, + (cacheTokens / totalTokens) * 1000, + (outputTokens / totalTokens) * 1000, + ]; + const floored = rawTenths.map((v) => Math.max(0, Math.floor(v))); + const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2])); + const order = [0, 1, 2].sort( + (a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a]) + ); + for (let k = 0; k < rem && k < 3; k++) { + floored[order[k]] += 1; + } + inPct = +(floored[0] / 10).toFixed(1); + cachePct = +(floored[1] / 10).toFixed(1); + outPct = +(floored[2] / 10).toFixed(1); + } + patchText(inputSharePct, `${inPct}%`); patchText(inputMainTokens, formatTokensPrecise(inputTokens)); + patchText(inputSubText, '未命中缓存输入'); + + patchText(cacheSharePct, `${cachePct}%`); + patchText(cacheMainTokens, formatTokensPrecise(cacheTokens)); patchText( - inputSubText, - `新输入 ${formatTokensPrecise(inputTokens)} · 缓存 ${formatTokensPrecise(cacheTokens)}` + cacheSubText, + `节省 ${formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 })}` ); patchText(outputSharePct, `${outPct}%`); @@ -4476,7 +5031,8 @@ const ConsumptionView = defineComponent({ ); trendChart.update(trendSeries); - // 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账) + // 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账,遵循模型名称显示格式设置) + const showUpstream = Boolean(slice.showUpstreamModel); const models = (slice.modelBreakdown || []) .slice() .sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0)); @@ -4485,9 +5041,17 @@ const ConsumptionView = defineComponent({ patchKeyedList(modelsListEl, models, { keyFn: (m) => m.label || m.shortName, sigFn: (m) => - `${m.label}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, + `${showUpstream}:${m.label}:${m.upstreamName || ''}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, createRow: createBreakdownItemRow, - updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true), + updateRow: (refs, m) => + updateBreakdownItemRow( + refs, + showUpstream + ? { ...m, label: m.upstreamName || m.label || m.shortName } + : m, + modelsTotalTok, + true + ), }); // 4. 同步数据来源列表 @@ -4525,8 +5089,14 @@ const ConsumptionView = defineComponent({ patchText(col.tokText, ''); } else { const cVal = Number(m.costUsd || 0); - patchText(col.costText, m.unpricedCalls > 0 ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls }) - : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); + patchText( + col.costText, + m.unpricedCalls > 0 + ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls, compactPending: true }) + : cVal >= 10 + ? `$${Math.round(cVal)}` + : `$${cVal.toFixed(2)}` + ); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); @@ -4554,6 +5124,7 @@ const ConsumptionView = defineComponent({ customEndMs: st.customEndMs, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, + showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), }), (slice) => { latestSlice = slice; @@ -4920,7 +5491,7 @@ const StepsDetailView = defineComponent({ patchText(refs.speedMain, formatMetric(m.avgTokPerSec, ' tok/s')); patchText(refs.speedSub, `有效 ${sampleSummary(m.speedSummary)}`); patchText(refs.tdTokens, formatTokens(m.totalTokens || 0)); - patchText(refs.tdCost, formatUsd(m.costUsd, { estimated: m.isEstimatedPrice, unpricedCalls: m.unpricedCalls })); + patchText(refs.tdCost, formatUsd(m.costUsd, { unpricedCalls: m.unpricedCalls })); }, }); @@ -4938,7 +5509,6 @@ const StepsDetailView = defineComponent({ recentSteps: st.telemetry?.activeConversation?.recentSteps, sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown, modelBreakdown: st.telemetry?.modelBreakdown, - rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间', showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), }), (slice) => { @@ -5000,25 +5570,45 @@ const StepsDetailView = defineComponent({ // --- src/views/SettingsView.js --- /** * @fileoverview View 4: SettingsView (系统设置视图). - * 采用定制的 `CustomSelect` 与 `CustomNumberInput` 替代所有原生表单控件,分为两个设置面板: - * 1. 本地配额监控与预算表单:配置模型名称显示方式(内部代号/实际模型名)、周用量计算模式及自定义 Token/USD 预算; - * 2. 云端价格同步与插件更新面板:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。 + * 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板: + * 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)与模型名称格式(精简代号 / 原始模型 ID); + * 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序; + * 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。 */ -/** 每周配额计算模式可选项 */ -const WEEKLY_MODE_OPTIONS = [ - { value: 'official', label: '跟随官方额度' }, - { value: 'custom_tokens', label: '自定义 Token 上限' }, - { value: 'custom_cost', label: '自定义费用上限 (USD)' }, -]; - /** 步骤明细表中的模型名称显示方式可选项 */ const STEP_MODEL_DISPLAY_OPTIONS = [ { value: 'short', label: '精简代号 (如 argon-4-high)' }, { value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' }, ]; +/** 面板挂载模式可选项(顶部栏 + 侧边栏 vs 仅侧边栏) */ +const WINDOW_MOUNT_OPTIONS = [ + { value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' }, + { value: 'sidebar', label: '仅侧边栏' }, +]; + +/** 顶栏左侧实时运行会话入口显隐选项 */ +const TOPBAR_MULTI_TOGGLE_OPTIONS = [ + { value: 'show', label: '显示' }, + { value: 'hide', label: '隐藏' }, +]; + +/** 顶栏右侧精简胶囊三槽位可选指标项 */ +const TOPBAR_SLOT_OPTIONS = [ + { value: 'context', label: '上下文占用 (%)' }, + { value: 'tps', label: '输出速度 (TPS)' }, + { value: 'ttft', label: '首字延迟 (TTFT)' }, + { value: 'cost', label: '本次费用 ($)' }, + { value: 'quota_auto', label: '自动紧俏额度' }, + { value: 'gemini_5h', label: 'Gemini 5h 额度' }, + { value: 'gemini_weekly', label: 'Gemini 周额度' }, + { value: 'claude_5h', label: 'Claude 5h 额度' }, + { value: 'claude_weekly', label: 'Claude 周额度' }, + { value: 'none', label: '不显示' }, +]; + /** 插件版本更新策略可选项 */ const AUTO_UPDATE_OPTIONS = [ { value: 'manual', label: '仅提示新版本,手动更新 (推荐)' }, @@ -5043,20 +5633,20 @@ function formatSyncTimeText(tsMs, updatedAt) { const SettingsView = defineComponent({ name: 'SettingsView', setup({ onCleanup }) { - // --- 面板 1:本地配额监控与预算表单状态与控件 --- - let draftMode = 'official'; - let draftTokens = 150000000; - let draftCost = 100; let draftShowUpstreamModel = false; let draftAutoUpdatePlugin = false; + let draftEnableWindowOverlay = true; + let draftShowTopbarMulti = true; + let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; let statusTimer = null; + let topbarTimer = null; let cloudTimer = null; - let lastSyncedSettingsSig = ''; const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); + const topbarStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); - /** 在本地预算面板右上角展示短暂的保存状态提示 */ + /** 在常规设置面板右上角展示短暂的保存状态提示 */ function showSaveFeedback(text) { if (statusTimer) { clearTimeout(statusTimer); @@ -5071,6 +5661,21 @@ const SettingsView = defineComponent({ } } + /** 在顶部栏定制面板右上角展示短暂的状态提示 */ + function showTopbarFeedback(text, autoClearMs = 1500) { + if (topbarTimer) { + clearTimeout(topbarTimer); + topbarTimer = null; + } + patchText(topbarStatusText, text); + if (autoClearMs > 0) { + topbarTimer = setTimeout(() => { + topbarTimer = null; + patchText(topbarStatusText, ''); + }, autoClearMs); + } + } + /** 在云端同步面板右上角展示同步或更新进度提示 */ function showCloudFeedback(text, autoClearMs = 3500) { if (cloudTimer) { @@ -5086,110 +5691,54 @@ const SettingsView = defineComponent({ } } - const modeSelect = CustomSelect({ - modelValue: draftMode, - icon: 'sliders', - options: WEEKLY_MODE_OPTIONS, - onUpdateModelValue: (val) => { - draftMode = val; - }, - }); - - // 模型名显示方式切换后立即持久化并刷新遥测数据 - const stepModelSelect = CustomSelect({ - modelValue: 'short', - icon: 'table', - options: STEP_MODEL_DISPLAY_OPTIONS, + // --- 面板 1:常规设置 --- + const windowMountSelect = CustomSelect({ + modelValue: 'dual', + icon: 'dock', + options: WINDOW_MOUNT_OPTIONS, onUpdateModelValue: async (val) => { - draftShowUpstreamModel = val === 'upstream'; - if (latestSettings) { - lastSyncedSettingsSig = settingsSig({ - ...latestSettings, - showUpstreamModel: draftShowUpstreamModel, - }); - } + const nextEnable = val !== 'sidebar'; + draftEnableWindowOverlay = nextEnable; + windowMountSelect.setValue(nextEnable ? 'dual' : 'sidebar'); showSaveFeedback('保存中…'); try { await saveSettingsPatch({ - showUpstreamModel: draftShowUpstreamModel, + enableWindowOverlay: nextEnable, }); showSaveFeedback('已保存'); } catch { + if (latestSettings) { + renderSettings(latestSettings); + } showSaveFeedback('保存失败'); } }, }); - // 插件自动更新策略切换后立即保存至后端 - const autoUpdateSelect = CustomSelect({ - modelValue: 'manual', - icon: 'refresh', - options: AUTO_UPDATE_OPTIONS, + const stepModelSelect = CustomSelect({ + modelValue: 'short', + icon: 'table', + options: STEP_MODEL_DISPLAY_OPTIONS, onUpdateModelValue: async (val) => { - draftAutoUpdatePlugin = val === 'auto'; - if (latestSettings) { - lastSyncedSettingsSig = settingsSig({ - ...latestSettings, - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - } - showCloudFeedback('保存中…', 0); + const nextUpstream = val === 'upstream'; + draftShowUpstreamModel = nextUpstream; + stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short'); + showSaveFeedback('保存中…'); try { await saveSettingsPatch({ - autoUpdatePlugin: draftAutoUpdatePlugin, + showUpstreamModel: nextUpstream, }); - showCloudFeedback('已保存', 1800); + showSaveFeedback('已保存'); } catch { - showCloudFeedback('保存失败', 2500); + if (latestSettings) { + renderSettings(latestSettings); + } + showSaveFeedback('保存失败'); } }, }); - const tokenBudgetInput = CustomNumberInput({ - modelValue: draftTokens, - min: 100000, - max: 10000000000, - step: 1000000, - onUpdateModelValue: (val) => { - draftTokens = val; - }, - }); - - const costBudgetInput = CustomNumberInput({ - modelValue: draftCost, - min: 1, - max: 100000, - step: 5, - onUpdateModelValue: (val) => { - draftCost = val; - }, - }); - - const saveBtn = h( - 'button', - { - type: 'button', - className: 'btn-primary', - onClick: async () => { - showSaveFeedback('保存中…'); - try { - await saveSettingsPatch({ - weeklyLimitMode: draftMode, - weeklyTokenBudget: draftTokens, - weeklyCostBudget: draftCost, - showUpstreamModel: draftShowUpstreamModel, - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - showSaveFeedback('已保存'); - } catch { - showSaveFeedback('保存失败'); - } - }, - }, - [createSvgIcon('check', { size: 13 }), h('span', { text: '保存设置' })] - ); - - const budgetPanel = h('section', { className: 'panel' }, [ + const generalPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('sliders', { size: 13 }), @@ -5197,31 +5746,211 @@ const SettingsView = defineComponent({ ]), saveStatusText, ]), + h('div', { className: 'form-row' }, [ + h('span', { className: 'form-label', text: '面板挂载方式' }), + windowMountSelect.el, + ]), h('div', { className: 'form-row' }, [ h('span', { className: 'form-label', text: '模型名称格式' }), stepModelSelect.el, ]), - h('div', { className: 'form-row' }, [ - h('span', { className: 'form-label', text: '周额度基准' }), - modeSelect.el, - ]), - h('div', { className: 'dual-grid' }, [ - h('div', { className: 'form-row' }, [ - h('span', { className: 'form-label', text: '每周 Token 上限' }), - tokenBudgetInput.el, - ]), - h('div', { className: 'form-row' }, [ - h('span', { className: 'form-label', text: '每周费用上限 ($)' }), - costBudgetInput.el, - ]), - ]), - h('div', { style: 'display: flex; justify-content: flex-end;' }, [saveBtn]), ]); - // --- 面板 2:版本更新面板 --- + // --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) --- + const multiSessionToggle = SegmentedControl({ + ariaLabel: '实时运行会话开关', + modelValue: 'show', + options: TOPBAR_MULTI_TOGGLE_OPTIONS, + onUpdateModelValue: async (val) => { + const nextShow = val !== 'hide'; + draftShowTopbarMulti = nextShow; + syncTopbarControls(); + showTopbarFeedback('保存中…', 0); + try { + await saveSettingsPatch({ + showTopbarMultiSession: nextShow, + }); + showTopbarFeedback('已保存', 1500); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showTopbarFeedback('保存失败', 2500); + } + }, + }); + + async function persistTopbarSlots(nextRawSlots, noticeText = '') { + const normalized = normalizeClientTopbarSlots(nextRawSlots); + draftTopbarSlots = normalized; + syncTopbarControls(); + showTopbarFeedback(noticeText || '保存中…', 0); + try { + await saveSettingsPatch({ + topbarCapsuleSlots: normalized, + }); + showTopbarFeedback(noticeText || '已保存', noticeText ? 2000 : 1500); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showTopbarFeedback('保存失败', 2500); + } + } + + function handleSlotMetricChange(slotIndex, nextVal) { + const candidate = [...draftTopbarSlots]; + candidate[slotIndex] = nextVal; + const wouldAllBeHidden = candidate.every((item) => item === 'none'); + void persistTopbarSlots( + candidate, + wouldAllBeHidden ? '至少保留 1 项显示' : '' + ); + } + + function swapTopbarSlots(idxA, idxB) { + if (idxA < 0 || idxA > 2 || idxB < 0 || idxB > 2 || idxA === idxB) return; + const candidate = [...draftTopbarSlots]; + const temp = candidate[idxA]; + candidate[idxA] = candidate[idxB]; + candidate[idxB] = temp; + void persistTopbarSlots(candidate); + } + + const slotSelects = [0, 1, 2].map((idx) => + CustomSelect({ + modelValue: draftTopbarSlots[idx], + options: TOPBAR_SLOT_OPTIONS, + onUpdateModelValue: (val) => handleSlotMetricChange(idx, val), + }) + ); + + const slotRows = [0, 1, 2].map((idx) => { + const upBtn = h( + 'button', + { + type: 'button', + className: 'slot-move-btn', + disabled: idx === 0, + 'aria-label': `槽位 ${idx + 1} 左移`, + title: idx === 0 ? '已在最左' : '上移 (在顶栏靠左)', + onClick: (e) => { + e.stopPropagation(); + swapTopbarSlots(idx, idx - 1); + }, + }, + [createSvgIcon('chevron-up', { size: 12 })] + ); + + const downBtn = h( + 'button', + { + type: 'button', + className: 'slot-move-btn', + disabled: idx === 2, + 'aria-label': `槽位 ${idx + 1} 右移`, + title: idx === 2 ? '已在最右' : '下移 (在顶栏靠右)', + onClick: (e) => { + e.stopPropagation(); + swapTopbarSlots(idx, idx + 1); + }, + }, + [createSvgIcon('chevron-down', { size: 12 })] + ); + + return h('div', { className: 'topbar-slot-row', 'data-slot-row': String(idx) }, [ + h('span', { className: 'slot-index-badge', text: String(idx + 1) }), + slotSelects[idx].el, + h('span', { className: 'slot-order-btns' }, [upBtn, downBtn]), + ]); + }); + + const resetTopbarBtn = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm', + disabled: true, + onClick: async () => { + draftShowTopbarMulti = true; + draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; + syncTopbarControls(); + showTopbarFeedback('保存中…', 0); + try { + await saveSettingsPatch({ + showTopbarMultiSession: true, + topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS], + }); + showTopbarFeedback('已恢复默认', 1600); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showTopbarFeedback('保存失败', 2500); + } + }, + }, + [h('span', { text: '恢复默认' })] + ); + + function syncTopbarControls() { + multiSessionToggle.setValue(draftShowTopbarMulti ? 'show' : 'hide'); + for (let i = 0; i < 3; i += 1) { + slotSelects[i].setValue(draftTopbarSlots[i]); + } + const isDefault = + draftShowTopbarMulti === true && + draftTopbarSlots[0] === DEFAULT_CLIENT_TOPBAR_SLOTS[0] && + draftTopbarSlots[1] === DEFAULT_CLIENT_TOPBAR_SLOTS[1] && + draftTopbarSlots[2] === DEFAULT_CLIENT_TOPBAR_SLOTS[2]; + patchAttr(resetTopbarBtn, 'disabled', isDefault); + } + + const topbarPanel = h('section', { className: 'panel topbar-config-panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('dock', { size: 13 }), + h('span', { text: '顶部栏定制' }), + ]), + h('span', { className: 'topbar-header-right' }, [topbarStatusText, resetTopbarBtn]), + ]), + h('div', { className: 'settings-inline-row' }, [ + h('span', { className: 'form-label', text: '实时运行会话' }), + multiSessionToggle.el, + ]), + h('div', { className: 'form-row' }, [ + h('span', { className: 'form-label', text: '胶囊数值与顺序 (左 → 右)' }), + h('div', { className: 'topbar-slot-list' }, slotRows), + ]), + ]); + + // --- 面板 3:版本更新面板 --- + const autoUpdateSelect = CustomSelect({ + modelValue: 'manual', + icon: 'refresh', + options: AUTO_UPDATE_OPTIONS, + onUpdateModelValue: async (val) => { + const nextAuto = val === 'auto'; + draftAutoUpdatePlugin = nextAuto; + autoUpdateSelect.setValue(nextAuto ? 'auto' : 'manual'); + showCloudFeedback('保存中…', 0); + try { + await saveSettingsPatch({ + autoUpdatePlugin: nextAuto, + }); + showCloudFeedback('已保存', 1800); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showCloudFeedback('保存失败', 2500); + } + }, + }); + const pricingCountVal = h('strong', { className: 'cell-value', text: '—' }); const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' }); - const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.1' }); + const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.3' }); const versionSub = h('span', { className: 'cell-sub', text: '检查中…' }); const syncPricingBtnText = h('span', { text: '更新价格表' }); @@ -5276,7 +6005,7 @@ const SettingsView = defineComponent({ return; } if (!cs?.updateAvailable) { - const curVer = cs?.currentPluginVersion || '1.4.1'; + const curVer = cs?.currentPluginVersion || '1.4.3'; showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500); return; } @@ -5330,38 +6059,35 @@ const SettingsView = defineComponent({ h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]), ]); - const rootEl = h('div', { className: 'view-pane' }, [budgetPanel, cloudPanel]); + const settingsInner = h( + 'div', + { + style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', + }, + [generalPanel, topbarPanel, cloudPanel] + ); + const viewScrollbar = CustomScrollbar({ + contentEl: settingsInner, + className: 'view-pane', + }); let latestSettings = null; let latestCloudStatus = null; - let isDirty = false; - - /** 生成设置项签名,避免轮询返回相同配置时覆盖用户正在编辑的草稿值 */ - function settingsSig(s) { - if (!s) return ''; - return `${s.weeklyLimitMode}:${s.weeklyTokenBudget}:${s.weeklyCostBudget}:${Boolean(s.showUpstreamModel)}:${Boolean(s.autoUpdatePlugin)}`; - } /** 将后端返回的最新设置同步至表单控件 */ function renderSettings(settings) { if (!settings) return; - const nextSig = settingsSig(settings); - if (nextSig === lastSyncedSettingsSig) return; - lastSyncedSettingsSig = nextSig; - draftMode = - settings.weeklyLimitMode === 'custom_tokens' || - settings.weeklyLimitMode === 'custom_cost' - ? settings.weeklyLimitMode - : 'official'; - draftTokens = Number(settings.weeklyTokenBudget || 150000000); - draftCost = Number(settings.weeklyCostBudget || 100); draftShowUpstreamModel = Boolean(settings.showUpstreamModel); draftAutoUpdatePlugin = Boolean(settings.autoUpdatePlugin); - modeSelect.setValue(draftMode); + draftEnableWindowOverlay = settings.enableWindowOverlay !== false; + draftShowTopbarMulti = settings.showTopbarMultiSession !== false; + draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots); + + windowMountSelect.setValue(draftEnableWindowOverlay ? 'dual' : 'sidebar'); stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short'); autoUpdateSelect.setValue(draftAutoUpdatePlugin ? 'auto' : 'manual'); - tokenBudgetInput.setValue(draftTokens); - costBudgetInput.setValue(draftCost); + syncTopbarControls(); + viewScrollbar.refresh(); } /** 将云端价格表统计与插件版本对比状态同步至云端面板 */ @@ -5379,7 +6105,7 @@ const SettingsView = defineComponent({ `${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}` ); - const curVer = cs.currentPluginVersion || '1.4.1'; + const curVer = cs.currentPluginVersion || '1.4.3'; const latVer = cs.latestPluginVersion || curVer; const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP'; patchText(versionVal, `v${curVer}`); @@ -5398,6 +6124,7 @@ const SettingsView = defineComponent({ if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) { showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500); } + viewScrollbar.refresh(); } const unsub = telemetryStore.subscribe( @@ -5408,42 +6135,51 @@ const SettingsView = defineComponent({ (slice) => { latestSettings = slice.settings; latestCloudStatus = slice.cloudStatus; - if (uiStore.getState().activeView !== 'settings') { - isDirty = true; - return; - } - isDirty = false; renderSettings(slice.settings); - renderCloudStatus(slice.cloudStatus); + if (uiStore.getState().activeView === 'settings') { + renderCloudStatus(slice.cloudStatus); + } } ); const unsubView = uiStore.subscribe( (st) => st.activeView, (activeView) => { - if (activeView === 'settings' && isDirty) { - isDirty = false; + if (activeView === 'settings') { if (latestSettings) renderSettings(latestSettings); if (latestCloudStatus) renderCloudStatus(latestCloudStatus); + viewScrollbar.refresh(); } } ); onCleanup(() => { if (statusTimer) clearTimeout(statusTimer); + if (topbarTimer) clearTimeout(topbarTimer); if (cloudTimer) clearTimeout(cloudTimer); unsub(); unsubView(); - modeSelect.destroy(); + windowMountSelect.destroy(); stepModelSelect.destroy(); + multiSessionToggle.destroy(); + for (const sel of slotSelects) { + sel.destroy(); + } autoUpdateSelect.destroy(); - tokenBudgetInput.destroy(); - costBudgetInput.destroy(); + viewScrollbar.destroy(); }); return { - el: rootEl, - refs: { modeSelect, stepModelSelect, autoUpdateSelect, tokenBudgetInput, costBudgetInput }, + el: viewScrollbar.el, + refs: { + windowMountSelect, + stepModelSelect, + multiSessionToggle, + slotSelects, + resetTopbarBtn, + autoUpdateSelect, + viewScrollbar, + }, }; }, }); @@ -5492,6 +6228,22 @@ const App = defineComponent({ stageEl, ]); + function syncStepsBadge() { + const uiSt = uiStore.getState(); + const scopeForBadge = uiSt.activeView === 'steps' ? uiSt.selectedAgentScope : 'all'; + const { scopedConv } = resolveScopedConversation( + telemetryStore.getState().telemetry, + scopeForBadge, + uiSt.ctxInspectorAgentId + ); + const stepCount = scopedConv?.stepCount ?? 0; + topPillNav.setProps({ + items: VIEW_TABS.map((t) => + t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t + ), + }); + } + const unsubUi = uiStore.subscribe( (st) => st.activeView, (activeView) => { @@ -5506,24 +6258,13 @@ const App = defineComponent({ } else if (activeView === 'steps') { stepsView.refs?.stepsScroll?.refresh(); stepsView.refs?.modelsScroll?.refresh(); + } else if (activeView === 'settings') { + settingsView.refs?.viewScrollbar?.refresh(); } + syncStepsBadge(); } ); - function syncStepsBadge() { - const { scopedConv } = resolveScopedConversation( - telemetryStore.getState().telemetry, - uiStore.getState().selectedAgentScope, - uiStore.getState().ctxInspectorAgentId - ); - const stepCount = scopedConv?.stepCount ?? 0; - topPillNav.setProps({ - items: VIEW_TABS.map((t) => - t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t - ), - }); - } - const unsubStepCount = telemetryStore.subscribe( (st) => ({ stepCount: st.telemetry?.activeConversation?.stepCount ?? 0, @@ -5564,9 +6305,2158 @@ const App = defineComponent({ }, }); +// --- src/components/layout/WindowOverlayShell.js --- +/** + * @fileoverview 主窗口双栖挂载外壳 (WindowOverlayShell.js). + * + * 采用「分离式双 Shadow Host」架构,彻底规避宿主顶栏层叠上下文 (`z-0` / `overflow: hidden`) 裁切与路由重绘卸载问题: + * 1. `#ag-usage-monitor-capsule`:轻量顶栏胶囊,优先内嵌停靠至 `[class*="@container/titlebar"]` 右侧按钮组, + * 支持四级迟滞宽度自适应折叠(`wide` -> `compact` -> `minimal` -> `ring-only`),找不到顶栏时自动回退至右上角固定定位; + * 2. `#ag-usage-monitor-portal`:常驻 `document.body` 顶层的无遮挡浮层宿主,承载悬停速览卡与完整四标签 `App()` 监控面板, + * 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。 + */ + + +const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule'; +const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; +const FLOATING_CARD_WIDTH = 492; +const MULTI_PANEL_WIDTH = 484; +const RING_RADIUS = 5.2; +const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); + +/** + * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 + * 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊。 + * + * @param {number} availWidth + * @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode + * @param {{ showMulti?: boolean }} [options] + * @returns {'wide'|'compact'|'minimal'|'ring-only'} + */ +function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) { + if (availWidth == null || Number.isNaN(availWidth)) return 'wide'; + const showMulti = options?.showMulti !== false; + const effWidth = showMulti ? availWidth : availWidth + 76; + if (currentMode === 'wide') { + if (effWidth < 78) return 'ring-only'; + if (effWidth < 196) return 'minimal'; + if (effWidth < 256) return 'compact'; + return 'wide'; + } + if (currentMode === 'compact') { + if (effWidth >= 272) return 'wide'; + if (effWidth < 78) return 'ring-only'; + if (effWidth < 196) return 'minimal'; + return 'compact'; + } + if (currentMode === 'minimal') { + if (effWidth >= 272) return 'wide'; + if (effWidth >= 212) return 'compact'; + if (effWidth < 78) return 'ring-only'; + return 'minimal'; + } + if (effWidth >= 272) return 'wide'; + if (effWidth >= 212) return 'compact'; + if (effWidth >= 92) return 'minimal'; + return 'ring-only'; +} + +function findHostTitlebar() { + try { + if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { + return null; + } + return document.querySelector('[class*="@container/titlebar"]'); + } catch { + return null; + } +} + +function findNativeTopRightAnchor() { + try { + if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { + return null; + } + const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]'); + if (auxToggle?.closest) { + return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle; + } + const candidates = document.querySelectorAll('button, a, [role="button"]'); + for (const btn of candidates) { + const text = String(btn.textContent || '').trim(); + if ( + (text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) && + btn.getBoundingClientRect?.().top < 52 + ) { + return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn; + } + } + return document.querySelector('div.absolute.right-0.top-0'); + } catch { + return null; + } +} + +function getLeftSidebarRightEdge(vw) { + try { + if (typeof document !== 'undefined' && typeof document.querySelector === 'function') { + const navEl = document.querySelector('div[role="navigation"]'); + if (navEl?.getBoundingClientRect) { + const nr = navEl.getBoundingClientRect(); + if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) { + return Math.ceil(nr.right); + } + } + } + } catch { + // 忽略侧栏测量异常 + } + return 0; +} + +function resolveQuotaCapsuleSummary(quotas) { + if (!quotas) return null; + const activePool = quotas.activePool; + const weekly = quotas.weekly; + const candidates = []; + if (activePool && Number.isFinite(Number(activePool.remainingPct))) { + candidates.push({ + pct: Number(activePool.remainingPct), + label: activePool.poolLabel || activePool.family || '当前池', + windowTag: '5h', + }); + } + if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { + candidates.push({ + pct: Number(activePool.weeklyRemainingPct), + label: activePool.poolLabel || activePool.family || '当前池', + windowTag: '周', + }); + } + if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { + candidates.push({ + pct: Number(weekly.remainingPct), + label: weekly.poolFamily || '周限额', + windowTag: '周', + }); + } + if (!candidates.length) return null; + candidates.sort((a, b) => a.pct - b.pct); + const tightest = candidates[0]; + const rounded = Math.max(0, Math.min(100, Math.round(tightest.pct))); + return { + roundedPct: rounded, + shortText: `余 ${rounded}%`, + detailText: candidates + .map((c) => `${c.label} ${c.windowTag} 余 ${Math.max(0, Math.min(100, Math.round(c.pct)))}%`) + .join(' · '), + }; +} + +const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i; + +/** + * 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。 + * + * @param {object|null|undefined} quotas + * @param {'gemini_5h'|'gemini_weekly'|'claude_5h'|'claude_weekly'} slotKey + * @returns {{ roundedPct: number, shortText: string } | null} + */ +function resolveSpecificQuotaSlotSummary(quotas, slotKey) { + if (!quotas) return null; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const activePool = quotas.activePool || null; + const isClaude = slotKey.startsWith('claude_'); + const isWeekly = slotKey.endsWith('_weekly'); + let rawPct = null; + + if (isClaude) { + const claudePool = + pools.find((p) => p?.poolKey === 'Claude & GPT') || + pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || ''))); + const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + if (cand != null && Number.isFinite(Number(cand))) { + rawPct = Number(cand); + } else if ( + activePool && + THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) + ) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) { + rawPct = Number(fb); + } + } + } else { + const stdGemini = + pools.find((p) => p?.poolKey === 'Gemini') || + pools.find( + (p) => + /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && + !/carbon|argon/i.test(String(p?.poolKey || '')) + ); + const geminiFamilyPools = pools.filter((p) => + /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) + ); + const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + if (primaryCand != null && Number.isFinite(Number(primaryCand))) { + rawPct = Number(primaryCand); + } else { + const familyVals = geminiFamilyPools + .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .filter((v) => v != null && Number.isFinite(Number(v))) + .map(Number); + if (familyVals.length > 0) { + rawPct = Math.min(...familyVals); + } else if ( + activePool && + !THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) + ) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) { + rawPct = Number(fb); + } + } + if ( + rawPct == null && + isWeekly && + quotas.weekly && + !THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) && + quotas.weekly.remainingPct != null && + Number.isFinite(Number(quotas.weekly.remainingPct)) + ) { + rawPct = Number(quotas.weekly.remainingPct); + } + } + } + + if (rawPct == null || !Number.isFinite(rawPct)) return null; + const rounded = Math.max(0, Math.min(100, Math.round(rawPct))); + return { + roundedPct: rounded, + shortText: `余 ${rounded}%`, + }; +} + +function formatCompactCapsuleCost(stepCost) { + if (stepCost == null || !Number.isFinite(Number(stepCost))) return '--'; + const val = Math.max(0, Number(stepCost)); + if (val === 0) return '$0.00'; + if (val < 0.001) return '<$0.001'; + if (val < 1) return `$${val.toFixed(3)}`; + if (val < 100) return `$${val.toFixed(2)}`; + return `$${Math.round(val)}`; +} + +function formatCompactCapsuleTtft(ttftSec) { + if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; + const val = Number(ttftSec); + if (val < 1) return `${val.toFixed(2)}s`; + if (val < 100) return `${val.toFixed(1)}s`; + return `${Math.round(val)}s`; +} + +/** + * 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 + */ +function mountWindowOverlay() { + if (typeof window === 'undefined' || typeof document === 'undefined') return null; + + // 先读取旧实例缓存的遥测快照与展开态(热升级时无缝承接数据与悬停状态,杜绝闪烁或关开),再安全卸载旧实例 + let carryOverTelemetry = null; + let carryOverTooltipOpen = false; + let carryOverPopoverOpen = false; + let carryOverMultiHoverOpen = false; + let carryOverMultiPinnedOpen = false; + let carryOverPointer = null; + try { + const prevOv = window.__AGUsageMonitorOverlay; + carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null; + carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.()); + carryOverPopoverOpen = Boolean(prevOv?.isOpen?.()); + carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.()); + carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.()); + carryOverPointer = prevOv?.getLastPointer?.() || null; + prevOv?.dispose?.(); + } catch { + // 忽略旧实例卸载异常 + } + try { + document.getElementById(CAPSULE_HOST_ID)?.remove?.(); + document.getElementById(PORTAL_HOST_ID)?.remove?.(); + } catch { + // 忽略残留节点清理异常 + } + + const bridgeConfig = getWindowBridgeConfig(); + const bundleVersion = String(bridgeConfig?.bundleVersion || ''); + const stylesCss = String(bridgeConfig?.stylesCss || ''); + const seedTelemetry = + (bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object' + ? bridgeConfig.initialTelemetry + : null) || carryOverTelemetry; + if (bridgeConfig?.initialTelemetry) { + delete bridgeConfig.initialTelemetry; + } + if (seedTelemetry) { + telemetryStore.setState({ + telemetry: seedTelemetry, + minuteTick: Math.floor(Date.now() / 30000), + syncState: 'idle', + }); + } + + let disposed = false; + let popoverOpen = false; + let tooltipOpen = false; + let multiOpen = false; + let multiPinned = false; + let hoverLeaveTimer = null; + let multiLeaveTimer = null; + const manualSubExpandMap = new Map(); + const multiTimersMap = new Map(); + let multiLiveTickTimer = null; + let hasPointerCoords = Boolean( + carryOverPointer && + Number.isFinite(carryOverPointer.x) && + Number.isFinite(carryOverPointer.y) + ); + let lastPointerX = hasPointerCoords ? carryOverPointer.x : -1; + let lastPointerY = hasPointerCoords ? carryOverPointer.y : -1; + let layoutMode = 'wide'; + let observedTitlebar = null; + let dockRafId = 0; + let lastObservedRouteId = extractHostRouteCascadeId(); + + function recordPointerCoords(e) { + if (e && Number.isFinite(e.clientX) && Number.isFinite(e.clientY)) { + lastPointerX = e.clientX; + lastPointerY = e.clientY; + hasPointerCoords = true; + } + } + + function isPointerStillInCapsule() { + if (!hasPointerCoords || document.hidden || !capsuleBtn.getBoundingClientRect) { + return false; + } + const r = capsuleBtn.getBoundingClientRect(); + if (r.width <= 0 || r.height <= 0) return false; + return ( + lastPointerX >= r.left - 1 && + lastPointerX <= r.right + 1 && + lastPointerY >= r.top - 1 && + lastPointerY <= r.bottom + 1 + ); + } + + function isPointerInMultiZone() { + if (!hasPointerCoords || document.hidden || multiBtn.hasAttribute('hidden')) { + return false; + } + if (multiBtn.getBoundingClientRect) { + const mr = multiBtn.getBoundingClientRect(); + if ( + mr.width > 0 && + mr.height > 0 && + lastPointerX >= mr.left - 1 && + lastPointerX <= mr.right + 1 && + lastPointerY >= mr.top - 1 && + lastPointerY <= mr.bottom + 10 + ) { + return true; + } + } + if (multiOpen && multiPanelEl.getBoundingClientRect) { + const pr = multiPanelEl.getBoundingClientRect(); + if ( + pr.width > 0 && + pr.height > 0 && + lastPointerX >= pr.left - 1 && + lastPointerX <= pr.right + 1 && + lastPointerY >= pr.top - 4 && + lastPointerY <= pr.bottom + 1 + ) { + return true; + } + } + return false; + } + + function scheduleMultiHoverClose() { + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + } + multiLeaveTimer = setTimeout(() => { + multiLeaveTimer = null; + if (disposed || multiPinned || !multiOpen) return; + let nativeHover = false; + try { + nativeHover = Boolean( + multiBtn.matches?.(':hover') || multiPanelEl.matches?.(':hover') + ); + } catch { + nativeHover = false; + } + if (nativeHover || isPointerInMultiZone()) { + return; + } + setMultiOpen(false); + }, 90); + } + + function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) { + const now = Date.now(); + const prev = multiTimersMap.get(timerKey); + let startMs = prev?.startMs || 0; + if (!prev || prev.sig !== sig) { + const validRaw = Number(rawStartMs || 0); + startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; + } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { + startMs = Number(rawStartMs); + } + multiTimersMap.set(timerKey, { sig, startMs, el: targetEl }); + const elapsedSec = Math.max(0, (now - startMs) / 1000); + patchText(targetEl, formatElapsedSec(elapsedSec)); + } + + function tickMultiElapsedDisplay() { + const now = Date.now(); + for (const entry of multiTimersMap.values()) { + if (!entry?.el) continue; + const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; + patchText(entry.el, formatElapsedSec(elapsedSec)); + } + } + + function stopMultiLiveTicker() { + if (multiLiveTickTimer) { + clearInterval(multiLiveTickTimer); + multiLiveTickTimer = null; + } + multiTimersMap.clear(); + } + + function ensureMultiLiveTicker() { + if (multiTimersMap.size === 0) { + stopMultiLiveTicker(); + return; + } + if (!multiLiveTickTimer) { + multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000); + } + } + + function inspectSessionInMonitor(cascadeId) { + if (!cascadeId || cascadeId === 'current') return; + uiStore.setState({ + activeView: 'overview', + selectedAgentScope: 'all', + ctxInspectorAgentId: 'auto', + }); + telemetryStore.setState({ selectedConversationId: cascadeId }); + void fetchTelemetry({ force: false }); + setMultiOpen(false); + setPopoverOpen(true); + } + + // --- 1. 创建顶栏双胶囊 Shadow Host(左:多会话实时信息;右:单会话指标胶囊) --- + const capsuleHost = document.createElement('div'); + capsuleHost.id = CAPSULE_HOST_ID; + capsuleHost.className = 'wm-capsule-host'; + capsuleHost.setAttribute('data-dock', 'fixed'); + capsuleHost.setAttribute('data-layout', layoutMode); + const capsuleShadow = capsuleHost.attachShadow({ mode: 'open' }); + + const capsuleStyleEl = document.createElement('style'); + capsuleStyleEl.textContent = stylesCss; + capsuleShadow.appendChild(capsuleStyleEl); + + // 左侧无边框多会话实时触发按钮(固定预占宽度,不随运行数跳动) + const multiDot = h('span', { className: 'wm-multi-dot' }); + const multiLabel = h('span', { className: 'wm-multi-label', text: '0 运行中' }); + const multiBtn = h( + 'button', + { + type: 'button', + className: 'wm-multi-btn', + 'aria-label': '多会话实时信息', + 'aria-expanded': 'false', + onClick: (e) => { + e.stopPropagation(); + if (multiOpen && multiPinned) { + setMultiOpen(false); + } else { + setMultiOpen(true, { pinned: true }); + } + }, + onContextmenu: (e) => { + e.preventDefault(); + e.stopPropagation(); + void fetchTelemetry({ force: true }); + }, + onMouseenter: (e) => { + recordPointerCoords(e); + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + if (!popoverOpen && !multiPinned) { + setMultiOpen(true, { pinned: false }); + } + }, + onMouseleave: (e) => { + recordPointerCoords(e); + if (!multiPinned) { + scheduleMultiHoverClose(); + } + }, + }, + [multiDot, multiLabel] + ); + + // 构建可复用的预占胶囊槽位节点(仅当槽位配置为 context 时挂载环形 SVG,运行期仅就地更新文本与属性) + function createCapsuleSlot(slotIndex, initialMetric) { + const ringSvg = document.createElementNS(SVG_NS, 'svg'); + ringSvg.setAttribute('viewBox', '0 0 14 14'); + ringSvg.setAttribute('class', 'wm-ring-svg'); + ringSvg.setAttribute('aria-hidden', 'true'); + + const ringTrack = document.createElementNS(SVG_NS, 'circle'); + ringTrack.setAttribute('cx', '7'); + ringTrack.setAttribute('cy', '7'); + ringTrack.setAttribute('r', String(RING_RADIUS)); + ringTrack.setAttribute('class', 'wm-ring-track'); + + const ringFill = document.createElementNS(SVG_NS, 'circle'); + ringFill.setAttribute('cx', '7'); + ringFill.setAttribute('cy', '7'); + ringFill.setAttribute('r', String(RING_RADIUS)); + ringFill.setAttribute('class', 'wm-ring-fill'); + ringFill.setAttribute('stroke-dasharray', String(RING_CIRCUMFERENCE)); + ringFill.setAttribute('stroke-dashoffset', String(RING_CIRCUMFERENCE)); + + ringSvg.appendChild(ringTrack); + ringSvg.appendChild(ringFill); + + const isCtx = initialMetric === 'context'; + const textSpan = h('span', { + className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text', + text: isCtx ? '--%' : initialMetric === 'tps' ? '-- t/s' : '余 --%', + }); + const el = h( + 'span', + { + className: isCtx + ? 'wm-cap-slot wm-ctx-seg' + : initialMetric === 'tps' + ? 'wm-cap-slot wm-seg-speed' + : 'wm-cap-slot wm-seg-quota', + 'data-slot-idx': String(slotIndex), + 'data-metric': initialMetric, + 'data-vis-rank': String(slotIndex + 1), + }, + isCtx ? [ringSvg, textSpan] : [textSpan] + ); + + return { + el, + ringSvg, + ringFill, + textSpan, + ringMounted: isCtx, + }; + } + + const capsuleSlots = [ + createCapsuleSlot(0, 'context'), + createCapsuleSlot(1, 'tps'), + createCapsuleSlot(2, 'quota_auto'), + ]; + const sep0 = h('span', { className: 'wm-sep wm-sep-speed', 'data-sep-for-rank': '2' }); + const sep1 = h('span', { className: 'wm-sep wm-sep-quota', 'data-sep-for-rank': '3' }); + let lastShowMulti = true; + + const updateDot = h('span', { className: 'wm-update-dot', hidden: true }); + + const capsuleBtn = h( + 'button', + { + type: 'button', + className: 'wm-capsule-btn', + 'aria-label': '用量与速度监控', + 'aria-expanded': 'false', + onClick: (e) => { + e.stopPropagation(); + setPopoverOpen(!popoverOpen); + }, + onContextmenu: (e) => { + e.preventDefault(); + e.stopPropagation(); + void fetchTelemetry({ force: true }); + }, + onMouseenter: (e) => { + recordPointerCoords(e); + if (hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + hoverLeaveTimer = null; + } + if (!popoverOpen && !multiPinned) { + if (multiOpen) { + setMultiOpen(false); + } + setTooltipOpen(true); + } + }, + onMouseleave: (e) => { + recordPointerCoords(e); + if (hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + } + hoverLeaveTimer = setTimeout(() => { + hoverLeaveTimer = null; + if (disposed || popoverOpen) return; + let nativeHover = false; + try { + nativeHover = Boolean(capsuleBtn.matches?.(':hover')); + } catch { + nativeHover = false; + } + if (nativeHover || isPointerStillInCapsule()) { + return; + } + setTooltipOpen(false); + }, 40); + }, + }, + [capsuleSlots[0].el, sep0, capsuleSlots[1].el, sep1, capsuleSlots[2].el, updateDot] + ); + capsuleShadow.appendChild(multiBtn); + capsuleShadow.appendChild(capsuleBtn); + + // --- 2. 创建 Body 顶层浮层 Portal Shadow Host --- + const portalHost = document.createElement('div'); + portalHost.id = PORTAL_HOST_ID; + portalHost.className = 'wm-portal-host'; + const portalShadow = portalHost.attachShadow({ mode: 'open' }); + + const portalStyleEl = document.createElement('style'); + portalStyleEl.textContent = stylesCss; + portalShadow.appendChild(portalStyleEl); + + // 悬停全景概览浮层(复用实时概览三卡片架构:4格测速矩阵 + 10通道上下文窗口 + 动态配额池,全槽位预占) + const hoverTpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); + const hoverTpsSub = h('span', { className: 'cell-sub', text: '模型未知' }); + const hoverPulseDot = createSvgIcon('dot', { size: 10 }); + + const hoverTtftVal = h('strong', { className: 'cell-value', text: '—' }); + const hoverTtftSub = h('span', { className: 'cell-sub', text: '均值 —' }); + + const hoverAvgVal = h('strong', { className: 'cell-value', text: '—' }); + const hoverAvgSub = h('span', { className: 'cell-sub', text: '有效 0/0 步' }); + + const hoverCostVal = h('strong', { className: 'cell-value', text: '—' }); + const hoverCacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累计 $0.00' }); + + const hoverMatrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '实时指标' }, [ + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [h('span', { text: '输出速度' }), hoverPulseDot]), + hoverTpsVal, + hoverTpsSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '首字延迟' }), + createSvgIcon('clock', { size: 11 }), + ]), + hoverTtftVal, + hoverTtftSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '平均速度' }), + createSvgIcon('pulse', { size: 11 }), + ]), + hoverAvgVal, + hoverAvgSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '本次费用' }), + createSvgIcon('bolt', { size: 11 }), + ]), + hoverCostVal, + hoverCacheSub, + ]), + ]); + + const hoverCtxAgentBadge = h('span', { + className: 'agent-badge badge-main', + hidden: true, + text: '主代理', + }); + const hoverCtxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' }); + const hoverCtxSegmentBar = ContextSegmentMeter({ context: {} }); + + // 固定预占 10 个双列图例槽位,排序时仅就地替换色块类名与文本,不调用 appendChild 移动节点 + const hoverLegendSlots = CTX_CHANNEL_DEFS.map((ch) => { + const swatchEl = h('span', { className: `swatch ${ch.segClass}` }); + const labelEl = h('span', { text: ch.label }); + const valEl = h('strong', { className: 'text-mono', text: '0' }); + const itemEl = h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [swatchEl, labelEl]), + valEl, + ]); + return { itemEl, swatchEl, labelEl, valEl }; + }); + + const hoverCtxLegendGrid = h( + 'div', + { className: 'ctx-legend-grid' }, + hoverLegendSlots.map((slot) => slot.itemEl) + ); + + const hoverCtxPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('layers', { size: 13 }), + h('span', { text: '上下文窗口' }), + hoverCtxAgentBadge, + ]), + h('span', { className: 'panel-meta' }, [hoverCtxSummaryText]), + ]), + hoverCtxSegmentBar.el, + hoverCtxLegendGrid, + ]); + + const hoverTierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); + const hoverPoolsListEl = h('div', { className: 'wm-hover-quota-pools' }); + patchKeyedList( + hoverPoolsListEl, + buildQuotaPoolItems(null, 0, { isPending: true }), + { + keyFn: (item) => item.key, + sigFn: quotaPoolRowSig, + createRow: createPoolQuotaRow, + updateRow: syncPoolQuotaRow, + } + ); + const hoverWkFootLeft = h('span', { className: 'text-muted', text: '本周累计: 0 ($0.00)' }); + const hoverWkFootRight = h('span', { className: 'text-muted', text: '本周调用: 0 次' }); + + const hoverQuotaPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + h('span', { text: '可用额度' }), + ]), + hoverTierBadge, + ]), + hoverPoolsListEl, + h('div', { className: 'panel-header wm-hover-quota-foot' }, [ + hoverWkFootLeft, + hoverWkFootRight, + ]), + ]); + + const hoverTipEl = h( + 'div', + { + className: 'wm-hover-tip', + hidden: true, + }, + [hoverMatrixEl, hoverCtxPanel, hoverQuotaPanel] + ); + + // 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新) + function createMultiLiveSubRow() { + const subBadge = h('span', { className: 'agent-badge badge-sub-1', text: '子1' }); + const subRole = h('span', { className: 'live-sub-role', text: '子代理' }); + const subSummary = h('span', { className: 'live-sub-summary', text: '' }); + const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' }); + const rowEl = h('div', { className: 'live-sub-row' }, [ + h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]), + subElapsed, + ]); + return { + el: rowEl, + refs: { rowEl, subBadge, subRole, subSummary, subElapsed }, + }; + } + + function createMultiLiveTaskCard() { + const dotIcon = createSvgIcon('dot', { size: 11 }); + patchClasses(dotIcon, { 'is-pulsing': true }); + const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); + const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' }); + const hereTagEl = h('span', { + className: 'wm-session-tag is-here', + hidden: true, + text: '本窗', + }); + const metricsEl = h('span', { + className: 'wm-task-metrics text-mono', + hidden: true, + text: '', + }); + const subToggleBtn = h('button', { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + text: '子代理 (0) ▸', + }); + const elapsedEl = h('span', { + className: 'live-activity-elapsed text-mono', + text: '0s', + }); + + const headerEl = h('div', { className: 'live-task-header' }, [ + h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]), + h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]), + ]); + + const mainBadge = h('span', { + className: 'agent-badge badge-main', + hidden: true, + text: '主', + }); + const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' }); + const mainProgress = h('span', { + className: 'live-activity-progress text-mono', + hidden: true, + text: '', + }); + const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); + const mainDetail = h('span', { + className: 'live-activity-detail', + hidden: true, + text: '', + }); + + const mainRowEl = h('div', { className: 'live-task-main-row' }, [ + mainBadge, + mainPhase, + mainProgress, + mainSep, + mainDetail, + ]); + + const subListEl = h('div', { className: 'live-sub-list', hidden: true }); + const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + + return { + el: cardEl, + refs: { + cardEl, + dotIcon, + titleEl, + hereTagEl, + metricsEl, + subToggleBtn, + elapsedEl, + mainBadge, + mainPhase, + mainProgress, + mainSep, + mainDetail, + subListEl, + }, + }; + } + + const multiPinBadge = h('span', { className: 'wm-pin-badge', hidden: true, text: '已固定' }); + const multiRunningMetaEl = h('span', { className: 'panel-meta text-mono', text: '读取中...' }); + const multiEmptyHintEl = h('span', { + className: 'wm-multi-empty-hint', + text: '悬停速览 · 左键固定', + }); + const multiEmptyEl = h('div', { className: 'wm-multi-empty' }, [ + h('span', { className: 'wm-multi-empty-left' }, [ + h('span', { className: 'wm-idle-dot' }), + h('span', { text: '当前暂无在线运行的会话' }), + ]), + multiEmptyHintEl, + ]); + const multiRunningListEl = h('div', { + className: 'live-activity-list', + hidden: true, + 'aria-live': 'polite', + }); + + const multiHeaderEl = h('div', { className: 'panel-header wm-multi-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + h('span', { text: '实时运行会话' }), + multiPinBadge, + ]), + multiRunningMetaEl, + ]); + + const multiPanelEl = h( + 'div', + { + className: 'wm-multi-panel', + role: 'dialog', + 'aria-label': '多会话实时信息面板', + hidden: true, + onMouseenter: (e) => { + recordPointerCoords(e); + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + }, + onMouseleave: (e) => { + recordPointerCoords(e); + if (!multiPinned) { + scheduleMultiHoverClose(); + } + }, + }, + [multiHeaderEl, multiEmptyEl, multiRunningListEl] + ); + + // 完整四标签悬浮容器 + const appInstance = App(); + const popoverEl = h( + 'div', + { + className: 'wm-popover-panel', + role: 'dialog', + 'aria-label': '用量与速度监控面板', + hidden: true, + }, + [appInstance.el] + ); + + portalShadow.appendChild(multiPanelEl); + portalShadow.appendChild(hoverTipEl); + portalShadow.appendChild(popoverEl); + (document.body || document.documentElement).appendChild(portalHost); + + // --- 3. 几何测量、顶栏停靠与防溢出定位 --- + function updateFixedFallbackPosition() { + if (capsuleHost.getAttribute('data-dock') === 'flow') { + capsuleHost.style.top = ''; + capsuleHost.style.right = ''; + return; + } + try { + const vw = Number(window.innerWidth || 1280); + let rightOffset = 144; + const anchor = findNativeTopRightAnchor(); + if (anchor?.getBoundingClientRect) { + const r = anchor.getBoundingClientRect(); + if (r.width > 0 && r.left > 0 && r.left < vw) { + rightOffset = Math.max(144, Math.ceil(vw - r.left + 6)); + } + } + capsuleHost.style.top = '7px'; + capsuleHost.style.right = `${rightOffset}px`; + } catch { + // 忽略回退坐标计算异常 + } + } + + function measureAvailableTitlebarWidth(titlebar) { + try { + if (titlebar?.getBoundingClientRect) { + const tbRect = titlebar.getBoundingClientRect(); + if (tbRect.width > 0) { + const titleEl = titlebar.firstElementChild; + const titleInner = titleEl?.firstElementChild; + const contentStart = titleInner?.getBoundingClientRect + ? Math.max(8, titleInner.getBoundingClientRect().left - tbRect.left) + : tbRect.left < 168 + ? 168 - tbRect.left + : 12; + const minTitleWidth = 180; + let siblingButtonsWidth = 64; + let rightPad = 8; + const rightGroup = capsuleHost.parentElement; + if (rightGroup && rightGroup !== titlebar) { + const auxOpen = + typeof document.querySelector === 'function' && + Boolean(document.querySelector('[data-testid="aux-pane-sash"]')); + const root = + typeof document.querySelector === 'function' + ? document.querySelector('div.h-screen.w-screen') + : null; + const rightClusterVar = + root?.style?.getPropertyValue?.('--right-cluster-width')?.trim() || ''; + if (auxOpen) { + rightPad = 8; + } else if (rightClusterVar) { + rightPad = Math.max(8, (parseFloat(rightClusterVar) || 44) - 4); + } else if (typeof window.getComputedStyle === 'function') { + rightPad = parseFloat(window.getComputedStyle(rightGroup).paddingRight) || 0; + } + if (rightGroup.children) { + let sum = 0; + for (const child of rightGroup.children) { + if (child !== capsuleHost && child.getBoundingClientRect) { + sum += child.getBoundingClientRect().width; + } + } + if (sum > 0) siblingButtonsWidth = sum + 8; + } + } + return tbRect.width - contentStart - minTitleWidth - rightPad - siblingButtonsWidth; + } + } + if (window.innerWidth) { + return window.innerWidth - 360; + } + } catch { + // 忽略测量异常 + } + return 320; + } + + function positionFloatingElements() { + if (disposed || !capsuleBtn.getBoundingClientRect) return; + try { + const bRect = capsuleBtn.getBoundingClientRect(); + if (bRect.width === 0 && bRect.height === 0) return; + const vw = Number(window.innerWidth || 1280); + const vh = Number(window.innerHeight || 800); + const navRight = getLeftSidebarRightEdge(vw); + const minLeft = navRight > 0 ? Math.max(12, navRight + 12) : 12; + const defaultCardW = Math.min(FLOATING_CARD_WIDTH, Math.max(280, vw - 24)); + const defaultMultiW = Math.min(MULTI_PANEL_WIDTH, Math.max(280, vw - 24)); + + if (multiOpen) { + const mRect = multiBtn.getBoundingClientRect?.() || bRect; + const anchorRect = mRect.width > 0 || mRect.height > 0 ? mRect : bRect; + const rawW = + Number(multiPanelEl.offsetWidth) || + Number(multiPanelEl.getBoundingClientRect?.().width) || + defaultMultiW; + const panelW = Math.min(rawW, Math.max(280, vw - minLeft - 12)); + const panelH = + Number(multiPanelEl.offsetHeight) || + Number(multiPanelEl.getBoundingClientRect?.().height) || + 320; + let top = Math.max(38, Math.round(anchorRect.bottom + 6)); + if (top + panelH > vh - 8 && anchorRect.top > panelH + 12) { + top = Math.round(anchorRect.top - panelH - 6); + } + let left = Math.round(anchorRect.left); + left = Math.min(left, vw - panelW - 12); + left = Math.max(minLeft, left); + multiPanelEl.style.top = `${top}px`; + multiPanelEl.style.left = `${left}px`; + multiPanelEl.style.maxHeight = `${Math.max(240, vh - top - 12)}px`; + } + + if (popoverOpen) { + const rawW = + Number(popoverEl.offsetWidth) || + Number(popoverEl.getBoundingClientRect?.().width) || + defaultCardW; + const panelW = Math.min(rawW, Math.max(280, vw - minLeft - 12)); + const top = Math.max(38, Math.min(vh - 140, Math.round(bRect.bottom + 6))); + let left = Math.round(bRect.right - panelW); + left = Math.min(left, vw - panelW - 12); + left = Math.max(minLeft, left); + popoverEl.style.top = `${top}px`; + popoverEl.style.left = `${left}px`; + popoverEl.style.maxHeight = `${Math.max(240, vh - top - 12)}px`; + } + + if (tooltipOpen && !popoverOpen && !multiOpen) { + const rawW = + Number(hoverTipEl.offsetWidth) || + Number(hoverTipEl.getBoundingClientRect?.().width) || + defaultCardW; + const tipW = Math.min(rawW, Math.max(280, vw - minLeft - 12)); + const tipH = + Number(hoverTipEl.offsetHeight) || + Number(hoverTipEl.getBoundingClientRect?.().height) || + 480; + let top = Math.max(38, Math.round(bRect.bottom + 6)); + if (top + tipH > vh - 8 && bRect.top > tipH + 12) { + top = Math.round(bRect.top - tipH - 6); + } + let left = Math.round(bRect.right - tipW); + left = Math.min(left, vw - tipW - 12); + left = Math.max(minLeft, left); + hoverTipEl.style.top = `${top}px`; + hoverTipEl.style.left = `${left}px`; + hoverTipEl.style.maxHeight = `${Math.max(240, vh - top - 12)}px`; + } + } catch { + // 忽略定位异常 + } + } + + function updateResponsiveLayout() { + if (disposed) return; + const titlebar = findHostTitlebar(); + const avail = measureAvailableTitlebarWidth(titlebar); + const showMulti = + telemetryStore.getState().telemetry?.settings?.showTopbarMultiSession !== false; + const nextMode = computeCapsuleLayoutMode(avail, layoutMode, { showMulti }); + if (nextMode !== layoutMode) { + layoutMode = nextMode; + capsuleHost.setAttribute('data-layout', layoutMode); + } + if (capsuleHost.getAttribute('data-dock') === 'fixed') { + updateFixedFallbackPosition(); + } + if (popoverOpen || tooltipOpen || multiOpen) { + positionFloatingElements(); + } + } + + let resizeObserver = null; + + function ensureCapsuleDocked() { + if (disposed) return false; + const bodyOrDoc = document.body || document.documentElement; + if (bodyOrDoc && !portalHost.isConnected) { + bodyOrDoc.appendChild(portalHost); + } + + const titlebar = findHostTitlebar(); + if (titlebar) { + let targetContainer = titlebar; + try { + const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild; + if (rightGroup && rightGroup !== titlebar.firstElementChild) { + targetContainer = rightGroup; + } + } catch { + // 忽略子选择器不兼容场景 + } + + if (capsuleHost.parentElement !== targetContainer) { + if (targetContainer.firstChild && targetContainer !== titlebar) { + targetContainer.insertBefore(capsuleHost, targetContainer.firstChild); + } else { + targetContainer.appendChild(capsuleHost); + } + } + patchAttr(capsuleHost, 'data-dock', 'flow'); + if (capsuleHost.style.top) capsuleHost.style.top = ''; + if (capsuleHost.style.right) capsuleHost.style.right = ''; + + if (observedTitlebar !== titlebar) { + observedTitlebar = titlebar; + try { + if (resizeObserver) { + resizeObserver.disconnect(); + resizeObserver.observe(titlebar); + if (document.body) resizeObserver.observe(document.body); + } + } catch { + // 忽略观察器异常 + } + } + } else if (bodyOrDoc) { + if (capsuleHost.parentElement !== bodyOrDoc) { + bodyOrDoc.appendChild(capsuleHost); + } + patchAttr(capsuleHost, 'data-dock', 'fixed'); + updateFixedFallbackPosition(); + } + + updateResponsiveLayout(); + return Boolean(capsuleHost.isConnected && portalHost.isConnected); + } + + function scheduleDockSync() { + if (disposed) return; + if (typeof requestAnimationFrame === 'function') { + if (dockRafId) return; + dockRafId = requestAnimationFrame(() => { + dockRafId = 0; + ensureCapsuleDocked(); + }); + } else { + ensureCapsuleDocked(); + } + } + + function refreshActiveViewScrollbars() { + const activeView = uiStore.getState().activeView; + const refs = appInstance.refs; + if (activeView === 'overview') { + refs?.overviewView?.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'consumption') { + refs?.consumptionView?.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'steps') { + refs?.stepsView?.refs?.stepsScroll?.refresh(); + refs?.stepsView?.refs?.modelsScroll?.refresh(); + } else if (activeView === 'settings') { + refs?.settingsView?.refs?.viewScrollbar?.refresh(); + } + } + + function setMultiOpen(nextOpen, { pinned = false, instant = false } = {}) { + const targetOpen = Boolean(nextOpen); + if (targetOpen && multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + if (targetOpen) { + setTooltipOpen(false); + if (pinned && popoverOpen) { + setPopoverOpen(false); + } + } + const nextPinned = targetOpen ? Boolean(pinned) : false; + const stateChanged = multiOpen !== targetOpen || multiPinned !== nextPinned; + multiOpen = targetOpen; + multiPinned = nextPinned; + patchClasses(multiBtn, { 'is-open': multiOpen && multiPinned }); + patchAttr(multiBtn, 'aria-expanded', multiOpen ? 'true' : 'false'); + patchAttr(multiPinBadge, 'hidden', !multiPinned); + if (!stateChanged) return; + patchClasses(multiPanelEl, { 'is-instant': Boolean(instant && multiOpen) }); + patchAttr(multiPanelEl, 'hidden', !multiOpen); + if (multiOpen) { + positionFloatingElements(); + if (typeof requestAnimationFrame === 'function') { + requestAnimationFrame(() => positionFloatingElements()); + } + } + } + + function setTooltipOpen(nextOpen, { instant = false } = {}) { + const targetOpen = Boolean(nextOpen && !popoverOpen && !(multiOpen && multiPinned)); + if (targetOpen && hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + hoverLeaveTimer = null; + } + if (targetOpen && multiOpen && !multiPinned) { + setMultiOpen(false); + } + if (tooltipOpen === targetOpen) return; + tooltipOpen = targetOpen; + patchClasses(hoverTipEl, { 'is-instant': Boolean(instant && targetOpen) }); + patchAttr(hoverTipEl, 'hidden', !tooltipOpen); + if (tooltipOpen) { + positionFloatingElements(); + } + } + + function setPopoverOpen(nextOpen, { instant = false } = {}) { + const targetOpen = Boolean(nextOpen); + if (targetOpen) { + setTooltipOpen(false); + if (multiOpen) { + setMultiOpen(false); + } + } + if (popoverOpen === targetOpen) return; + popoverOpen = targetOpen; + patchClasses(capsuleBtn, { 'is-open': popoverOpen }); + patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) }); + patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false'); + patchAttr(popoverEl, 'hidden', !popoverOpen); + if (popoverOpen) { + positionFloatingElements(); + if (typeof requestAnimationFrame === 'function') { + requestAnimationFrame(() => { + positionFloatingElements(); + refreshActiveViewScrollbars(); + }); + } else { + refreshActiveViewScrollbars(); + } + } + } + + function resolveCapsuleSlotPresentation(metricKey, slotCtx) { + if (metricKey === 'none') { + return { + hidden: true, + metric: 'none', + segClass: 'wm-cap-slot', + textClass: 'wm-slot-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: '', + running: false, + warn: false, + danger: false, + }; + } + + if (metricKey === 'context') { + if (!slotCtx.hasTelemetry) { + return { + hidden: false, + metric: 'context', + segClass: 'wm-cap-slot wm-ctx-seg', + textClass: 'wm-slot-text wm-ctx-pct', + showRing: true, + dashOffset: RING_CIRCUMFERENCE, + text: '--%', + running: false, + warn: false, + danger: false, + }; + } + const isDanger = slotCtx.usedPct >= 88; + const isWarn = !isDanger && slotCtx.usedPct >= 70; + return { + hidden: false, + metric: 'context', + segClass: 'wm-cap-slot wm-ctx-seg', + textClass: 'wm-slot-text wm-ctx-pct', + showRing: true, + dashOffset: slotCtx.dashOffset, + text: `${Math.round(slotCtx.usedPct)}%`, + running: false, + warn: isWarn, + danger: isDanger, + }; + } + + if (metricKey === 'tps') { + if (!slotCtx.hasTelemetry) { + return { + hidden: false, + metric: 'tps', + segClass: 'wm-cap-slot wm-seg-speed', + textClass: 'wm-slot-text wm-speed-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: '-- t/s', + running: false, + warn: false, + danger: false, + }; + } + const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0; + const tpsText = hasValidTps + ? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s` + : slotCtx.isRunning + ? '生成中' + : '待命'; + return { + hidden: false, + metric: 'tps', + segClass: 'wm-cap-slot wm-seg-speed', + textClass: 'wm-slot-text wm-speed-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: tpsText, + running: slotCtx.isRunning, + warn: false, + danger: false, + }; + } + + if (metricKey === 'ttft') { + const val = slotCtx.hasTelemetry ? slotCtx.ttft : null; + const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0; + const numVal = valid ? Number(val) : 0; + const isDanger = valid && numVal >= 30; + const isWarn = valid && !isDanger && numVal >= 15; + return { + hidden: false, + metric: 'ttft', + segClass: 'wm-cap-slot wm-seg-ttft', + textClass: 'wm-slot-text wm-ttft-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: valid ? formatCompactCapsuleTtft(numVal) : '--s', + running: false, + warn: isWarn, + danger: isDanger, + }; + } + + if (metricKey === 'cost') { + const costVal = slotCtx.hasTelemetry ? slotCtx.stepCost : null; + return { + hidden: false, + metric: 'cost', + segClass: 'wm-cap-slot wm-seg-cost', + textClass: 'wm-slot-text wm-cost-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--', + running: false, + warn: false, + danger: false, + }; + } + + const quotaSum = !slotCtx.hasTelemetry + ? null + : metricKey === 'quota_auto' + ? resolveQuotaCapsuleSummary(slotCtx.quotas) + : resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey); + const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15); + const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30); + return { + hidden: false, + metric: metricKey, + segClass: 'wm-cap-slot wm-seg-quota', + textClass: 'wm-slot-text wm-quota-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: quotaSum ? quotaSum.shortText : '余 --%', + running: false, + warn: isWarn, + danger: isDanger, + }; + } + + function applyCapsuleSlots(slotKeys, slotCtx) { + const presList = slotKeys.map((key) => resolveCapsuleSlotPresentation(key, slotCtx)); + let visRank = 0; + const visRanks = [0, 0, 0]; + for (let i = 0; i < 3; i += 1) { + const slot = capsuleSlots[i]; + const pres = presList[i]; + if (pres.hidden) { + patchAttr(slot.el, 'hidden', true); + patchAttr(slot.el, 'data-metric', 'none'); + patchAttr(slot.el, 'data-vis-rank', ''); + continue; + } + visRank += 1; + visRanks[i] = visRank; + patchAttr(slot.el, 'hidden', false); + patchAttr(slot.el, 'data-metric', pres.metric); + patchAttr(slot.el, 'data-vis-rank', String(visRank)); + + if (pres.showRing && !slot.ringMounted) { + slot.el.insertBefore(slot.ringSvg, slot.textSpan); + slot.ringMounted = true; + } else if (!pres.showRing && slot.ringMounted) { + slot.ringSvg.remove(); + slot.ringMounted = false; + } + + const fullSegClass = + `${pres.segClass}${pres.running ? ' state-running' : ''}${pres.warn ? ' tone-warn' : ''}${pres.danger ? ' tone-danger' : ''}`; + patchAttr(slot.el, 'class', fullSegClass); + const fullTextClass = + `${pres.textClass}${pres.warn ? ' tone-warn' : ''}${pres.danger ? ' tone-danger' : ''}`; + patchAttr(slot.textSpan, 'class', fullTextClass); + patchText(slot.textSpan, pres.text); + + if (pres.showRing) { + slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset)); + patchClasses(slot.ringFill, { 'tone-warn': pres.warn, 'tone-danger': pres.danger }); + } + } + + const showSep0 = visRanks[1] >= 2; + patchAttr(sep0, 'hidden', !showSep0); + patchAttr(sep0, 'data-sep-for-rank', showSep0 ? String(visRanks[1]) : ''); + + const showSep1 = visRanks[2] >= 2; + patchAttr(sep1, 'hidden', !showSep1); + patchAttr(sep1, 'data-sep-for-rank', showSep1 ? String(visRanks[2]) : ''); + } + + // --- 4. 实时遥测状态绑定(双胶囊与多会话/全景概览浮层全部槽位预占,仅就地更新节点,零布局跳动) --- + function renderCapsuleTelemetry() { + if (disposed) return; + const telSt = telemetryStore.getState(); + const uiSt = uiStore.getState(); + const telemetry = telSt.telemetry; + + const showMulti = telemetry?.settings?.showTopbarMultiSession !== false; + patchAttr(multiBtn, 'hidden', !showMulti); + patchAttr(capsuleHost, 'data-multi', showMulti ? 'on' : 'off'); + if (!showMulti && multiOpen) { + setMultiOpen(false); + } + if (showMulti !== lastShowMulti) { + lastShowMulti = showMulti; + updateResponsiveLayout(); + } + + const slotKeys = normalizeClientTopbarSlots(telemetry?.settings?.topbarCapsuleSlots); + + if (!telemetry) { + patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); + patchText(multiLabel, '0 运行中'); + patchText(multiRunningMetaEl, '读取中...'); + stopMultiLiveTicker(); + + applyCapsuleSlots(slotKeys, { hasTelemetry: false }); + return; + } + + const { hasSubagents, agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } = + resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId); + const { scopedConv: capsuleScopedConv } = resolveScopedConversation( + telemetry, + uiSt.selectedAgentScope, + uiSt.ctxInspectorAgentId + ); + const activeConv = telemetry.activeConversation || {}; + const overviewActive = overviewScopedConv || activeConv; + const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; + const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); + const totalTokens = Number(ctx.totalTokens || 0); + const usedPct = + limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; + const dashOffset = +( + RING_CIRCUMFERENCE * + (1 - Math.max(0, Math.min(100, usedPct)) / 100) + ).toFixed(2); + + // --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 --- + const rawRunningList = + Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0 + ? telemetry.runningConversations + : activeConv.isRunning || aggregated?.isRunning + ? [ + { + cascadeId: activeConv.cascadeId || 'current', + title: activeConv.title || '当前会话', + isCurrentSelected: true, + isMainRunning: Boolean(activeConv.isRunning), + isRunning: true, + mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, + subagentCount: Math.max(0, (agents?.length || 1) - 1), + runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: usedPct, + subagents: (agents || []) + .filter((a) => !a.isMain) + .map((s, idx) => ({ + cascadeId: s.cascadeId || s.agentId, + index: s.index || idx + 1, + badgeText: s.badgeText || `子${idx + 1}`, + shortLabel: s.shortLabel || `子代理 #${idx + 1}`, + role: s.role || `子代理 #${idx + 1}`, + isRunning: Boolean(s.isRunning), + stepCount: Number(s.stepCount || 0), + lastModifiedMs: s.lastModifiedMs || 0, + liveActivity: s.liveActivity || { + phase: s.isRunning ? 'thinking' : 'done', + label: s.isRunning ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ] + : []; + + const runningCount = rawRunningList.length; + const runningSubCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSubagentCount || 0), + 0 + ); + const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + + patchClasses(multiBtn, { + 'is-running': runningCount > 0 && !hasWaiting, + 'is-waiting': runningCount > 0 && hasWaiting, + }); + const multiBtnText = + runningCount > 0 + ? runningSubCount > 0 + ? `${runningCount} 运行 · ${runningSubCount} 子` + : `${runningCount} 运行中` + : '0 运行中'; + patchText(multiLabel, multiBtnText); + + const hostRouteLower = String( + telSt.hostRouteConversationId || extractHostRouteCascadeId() || '' + ).toLowerCase(); + + patchText( + multiRunningMetaEl, + runningCount > 0 + ? runningSubCount > 0 + ? `${runningCount} 主会话 · ${runningSubCount} 子代理运行中` + : `${runningCount} 个会话运行中` + : '全部待命' + ); + patchText(multiEmptyHintEl, '悬停速览 · 左键可固定'); + patchAttr(multiEmptyEl, 'hidden', runningCount > 0); + patchAttr(multiRunningListEl, 'hidden', runningCount === 0); + + const runningIdsLower = new Set( + rawRunningList.map((item) => String(item.cascadeId || '').toLowerCase()) + ); + + if (runningCount === 0) { + stopMultiLiveTicker(); + manualSubExpandMap.clear(); + } else { + for (const cid of [...manualSubExpandMap.keys()]) { + if (!runningIdsLower.has(String(cid || '').toLowerCase())) { + manualSubExpandMap.delete(cid); + } + } + + const activeTimerKeys = new Set(); + for (const item of rawRunningList) { + activeTimerKeys.add(`main:${item.cascadeId}`); + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const runSubs = Number(item.runningSubagentCount || 0); + const isExp = manualSubExpandMap.has(item.cascadeId) + ? manualSubExpandMap.get(item.cascadeId) + : runSubs > 0; + if (subCount > 0 && isExp) { + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } + } + } + } + + patchKeyedList(multiRunningListEl, rawRunningList, { + keyFn: (item) => item.cascadeId, + sigFn: (item) => { + const runSubs = Number(item.runningSubagentCount || 0); + const isExp = manualSubExpandMap.has(item.cascadeId) + ? manualSubExpandMap.get(item.cascadeId) + : runSubs > 0; + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + const subSig = (item.subagents || []) + .map( + (s) => + `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` + ) + .join('|'); + return `${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + }, + createRow: createMultiLiveTaskCard, + updateRow: (refs, item) => { + const act = item.mainActivity || { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: item.lastModifiedMs || 0, + signature: `fallback:${item.lastModifiedMs || 0}`, + }; + const isWaiting = act.phase === 'waiting'; + const isCompacting = act.phase === 'compacting'; + patchClasses(refs.cardEl, { + 'is-waiting': isWaiting, + 'is-compacting': isCompacting, + }); + patchClasses(refs.dotIcon, { 'is-pulsing': true }); + + const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话'; + patchText(refs.titleEl, convTitle); + patchAttr(refs.titleEl, 'title', `点击在监控面板中检视会话:${convTitle}`); + refs.titleEl.onclick = (e) => { + e.stopPropagation(); + inspectSessionInMonitor(item.cascadeId); + }; + + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + patchAttr(refs.hereTagEl, 'hidden', !isHere); + + const metricParts = []; + if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { + metricParts.push( + `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` + ); + } + if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { + metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); + } + const metricsStr = metricParts.join(' · '); + patchAttr(refs.metricsEl, 'hidden', !metricsStr); + if (metricsStr) { + patchText(refs.metricsEl, metricsStr); + } + + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const runSubCount = Number(item.runningSubagentCount || 0); + const isExpanded = manualSubExpandMap.has(item.cascadeId) + ? manualSubExpandMap.get(item.cascadeId) + : runSubCount > 0; + patchAttr(refs.mainBadge, 'hidden', subCount === 0); + patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); + if (subCount > 0) { + const arrow = isExpanded ? '▾' : '▸'; + const toggleText = + runSubCount > 0 + ? `子代理 ${runSubCount}/${subCount} ${arrow}` + : `子代理 (${subCount}) ${arrow}`; + patchText(refs.subToggleBtn, toggleText); + patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); + refs.subToggleBtn.onclick = (e) => { + e.stopPropagation(); + manualSubExpandMap.set(item.cascadeId, !isExpanded); + renderCapsuleTelemetry(); + if (multiOpen) { + positionFloatingElements(); + } + }; + } + + const mainTimerKey = `main:${item.cascadeId}`; + activeTimerKeys.add(mainTimerKey); + bindMultiElapsedTimer( + mainTimerKey, + `${item.cascadeId}:${act.signature || act.label}`, + act.startedAtMs, + refs.elapsedEl + ); + + patchText(refs.mainPhase, act.label || '推理中'); + const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; + patchAttr(refs.mainProgress, 'hidden', !progText); + if (progText) { + patchText(refs.mainProgress, progText); + } + + const detailStr = act.detail || ''; + patchAttr(refs.mainSep, 'hidden', !detailStr); + patchAttr(refs.mainDetail, 'hidden', !detailStr); + patchText(refs.mainDetail, detailStr); + + const showSubs = subCount > 0 && isExpanded; + patchAttr(refs.subListEl, 'hidden', !showSubs); + if (showSubs) { + const subItems = item.subagents || []; + patchKeyedList(refs.subListEl, subItems, { + keyFn: (sub) => sub.cascadeId, + sigFn: (sub) => + `${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`, + createRow: createMultiLiveSubRow, + updateRow: (subRefs, sub) => { + const subAct = sub.liveActivity || { + phase: sub.isRunning ? 'thinking' : 'done', + label: sub.isRunning ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: sub.lastModifiedMs || 0, + }; + patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); + const subBadgeCls = getAgentBadgeClass(sub.index || 1, false); + patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`); + patchText(subRefs.subBadge, sub.badgeText || `子${sub.index || 1}`); + patchText(subRefs.subRole, sub.role || sub.shortLabel || '子代理'); + + const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; + const summaryText = sub.isRunning + ? `${subAct.label || '运行中'}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}` + : `已完成 (${sub.stepCount || 0} 步)`; + patchText(subRefs.subSummary, summaryText); + + const subTimerKey = `sub:${sub.cascadeId}`; + if (sub.isRunning) { + activeTimerKeys.add(subTimerKey); + bindMultiElapsedTimer( + subTimerKey, + `${sub.cascadeId}:${subAct.signature || subAct.label}`, + subAct.startedAtMs || sub.lastModifiedMs, + subRefs.subElapsed + ); + } else { + multiTimersMap.delete(subTimerKey); + patchText(subRefs.subElapsed, `${sub.stepCount || 0}步`); + } + }, + }); + } + }, + }); + + for (const k of [...multiTimersMap.keys()]) { + if (!activeTimerKeys.has(k)) { + multiTimersMap.delete(k); + } + } + ensureMultiLiveTicker(); + } + + // --- 4b. 同步右侧指标胶囊与悬停全景三卡片 --- + const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const tps = + capsuleScopedConv?.latestTokPerSec ?? + aggregated?.latestTokPerSec ?? + activeConv.latestTokPerSec ?? + null; + const ttft = + capsuleScopedConv?.latestTtftSec ?? + aggregated?.latestTtftSec ?? + activeConv.latestTtftSec ?? + null; + const capsuleStepCost = + capsuleScopedConv?.latestStepCostUsd ?? + aggregated?.latestStepCostUsd ?? + activeConv.latestStepCostUsd ?? + null; + + patchClasses(capsuleBtn, { 'is-running': isRunning }); + applyCapsuleSlots(slotKeys, { + hasTelemetry: true, + usedPct, + dashOffset, + isRunning, + tps, + ttft, + stepCost: capsuleStepCost, + quotas: telemetry.quotas, + }); + + const hasUpdate = Boolean(telemetry.cloudStatus?.updateAvailable); + patchAttr(updateDot, 'hidden', !hasUpdate); + + // --- 同步悬停三卡片全景概览(与 LiveOverviewView 保持完全一致的数据口径与视觉呈现) --- + const showUpstream = Boolean(telemetry.settings?.showUpstreamModel); + const activeModelDisplay = + (showUpstream + ? overviewActive.activeModelUpstream || overviewActive.activeModelShort + : overviewActive.activeModelShort) || '模型未知'; + + patchClasses(hoverPulseDot, { 'is-pulsing': Boolean(overviewActive.isRunning || isRunning) }); + patchText(hoverTpsVal, formatMetric(overviewActive.latestTokPerSec, ' tok/s')); + const reason = speedReasonText(overviewActive.latestSpeedReason); + const modelAndAgent = + hasSubagents && overviewActive.activeAgentBadge + ? `[${overviewActive.activeAgentBadge}] ${activeModelDisplay}` + : activeModelDisplay; + patchText(hoverTpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent); + + patchText(hoverTtftVal, formatMetric(overviewActive.latestTtftSec, 's')); + patchText(hoverTtftSub, `均值 ${formatMetric(overviewActive.ttftSummary?.avgSec, 's')}`); + + patchText(hoverAvgVal, formatMetric(overviewActive.avgTokPerSec, ' tok/s')); + patchText(hoverAvgSub, `有效 ${sampleSummary(overviewActive.speedSummary)}`); + + const stepCost = overviewActive.latestStepCostUsd; + const hasAnySteps = Number(overviewActive.stepCount || 0) > 0; + patchText( + hoverCostVal, + !hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true }) + ); + patchText( + hoverCacheSub, + `缓存 ${overviewActive.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(overviewActive.sessionCostUsd || 0, { unpricedCalls: overviewActive.sessionUnpricedCalls })}` + ); + + patchAttr(hoverCtxAgentBadge, 'hidden', !(hasSubagents && ctxAgent)); + if (hasSubagents && ctxAgent) { + const badgeCls = getAgentBadgeClass(ctxAgent.index || 0, Boolean(ctxAgent.isMain)); + patchAttr(hoverCtxAgentBadge, 'class', `agent-badge ${badgeCls}`); + patchText(hoverCtxAgentBadge, formatAgentLabel(ctxAgent)); + } + patchText( + hoverCtxSummaryText, + `${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)` + ); + hoverCtxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } }); + + const scoredChannels = CTX_CHANNEL_DEFS.map((ch, defaultOrder) => ({ + ch, + defaultOrder, + val: ch.getValue(ctx), + })); + scoredChannels.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder); + for (let i = 0; i < hoverLegendSlots.length; i += 1) { + const slot = hoverLegendSlots[i]; + const entry = scoredChannels[i]; + if (!slot || !entry) continue; + patchAttr(slot.swatchEl, 'class', `swatch ${entry.ch.segClass}`); + patchText(slot.labelEl, entry.ch.label); + patchText(slot.valEl, formatTokens(entry.val)); + } + + const quotas = telemetry.quotas || {}; + const weekly = quotas.weekly || {}; + const minuteTick = Number(telSt.minuteTick || Math.floor(Date.now() / 30000)); + patchText( + hoverTierBadge, + `${telemetry.account?.tierName || 'Google AI'} · ${telemetry.account?.planName || 'Pro'}` + ); + patchKeyedList(hoverPoolsListEl, buildQuotaPoolItems(quotas, minuteTick), { + keyFn: (item) => item.key, + sigFn: quotaPoolRowSig, + createRow: createPoolQuotaRow, + updateRow: syncPoolQuotaRow, + }); + patchText( + hoverWkFootLeft, + `本周累计: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0, { unpricedCalls: weekly.unpricedCalls })})` + ); + patchText( + hoverWkFootRight, + telemetry.account?.aiCredits > 0 + ? `AI 积分: ${telemetry.account.aiCredits}` + : `本周调用: ${weekly.calls || 0} 次` + ); + } + + const unsubStore = telemetryStore.subscribe( + (st) => ({ + syncState: st.syncState, + telemetry: st.telemetry, + minuteTick: st.minuteTick, + selectedConversationId: st.selectedConversationId, + }), + (slice) => { + if (slice.telemetry?.settings?.enableWindowOverlay === false) { + if (popoverOpen) setPopoverOpen(false); + if (multiOpen) setMultiOpen(false); + } + renderCapsuleTelemetry(); + } + ); + + const unsubUiScope = uiStore.subscribe( + (st) => ({ + selectedAgentScope: st.selectedAgentScope, + ctxInspectorAgentId: st.ctxInspectorAgentId, + }), + () => renderCapsuleTelemetry() + ); + + // --- 5. 宿主会话路由跟随与全局交互监听 --- + function syncHostRouteIfChanged() { + if (disposed) return; + const currentRouteId = extractHostRouteCascadeId(); + if (currentRouteId === lastObservedRouteId) return; + lastObservedRouteId = currentRouteId; + const st = telemetryStore.getState(); + const patch = { hostRouteConversationId: currentRouteId }; + if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) { + patch.selectedConversationId = ''; + } + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + telemetryStore.setState(patch); + void fetchTelemetry({ force: false }); + } + + const onDocMouseDown = (e) => { + if (popoverOpen && !isEventInside(e, popoverEl) && !isEventInside(e, capsuleHost)) { + setPopoverOpen(false); + } + if (multiOpen && !isEventInside(e, multiPanelEl) && !isEventInside(e, capsuleHost)) { + setMultiOpen(false); + } + }; + + const onDocKeyDown = (e) => { + if (e.key === 'Escape' && !e.defaultPrevented) { + if (popoverOpen) { + setPopoverOpen(false); + } + if (multiOpen) { + setMultiOpen(false); + } + } + }; + + const onWindowPointerMove = (e) => recordPointerCoords(e); + const onWindowBlur = () => { + hasPointerCoords = false; + if (tooltipOpen) { + setTooltipOpen(false); + } + if (multiOpen && !multiPinned) { + setMultiOpen(false); + } + }; + const onWindowResize = () => updateResponsiveLayout(); + const onPopState = () => syncHostRouteIfChanged(); + const onVisibilityChange = () => { + if (document.hidden) { + hasPointerCoords = false; + if (tooltipOpen) { + setTooltipOpen(false); + } + if (multiOpen && !multiPinned) { + setMultiOpen(false); + } + return; + } + if (!document.hidden && !disposed) { + syncHostRouteIfChanged(); + void fetchTelemetry({ force: false }); + } + }; + + let hostDomObserver = null; + try { + if (typeof ResizeObserver !== 'undefined') { + resizeObserver = new ResizeObserver(() => updateResponsiveLayout()); + if (document.body) resizeObserver.observe(document.body); + } + if (typeof MutationObserver !== 'undefined' && document.body) { + hostDomObserver = new MutationObserver(() => { + syncHostRouteIfChanged(); + const tb = findHostTitlebar(); + if ( + !capsuleHost.isConnected || + !portalHost.isConnected || + (tb && !tb.contains(capsuleHost)) || + (!tb && capsuleHost.getAttribute('data-dock') === 'flow') + ) { + scheduleDockSync(); + } + }); + hostDomObserver.observe(document.body, { childList: true, subtree: true }); + } + } catch { + // 忽略观察器初始化异常 + } + + document.addEventListener?.('mousedown', onDocMouseDown, true); + document.addEventListener?.('keydown', onDocKeyDown); + document.addEventListener?.('visibilitychange', onVisibilityChange); + window.addEventListener?.('pointermove', onWindowPointerMove, { passive: true }); + window.addEventListener?.('blur', onWindowBlur); + window.addEventListener?.('resize', onWindowResize); + window.addEventListener?.('popstate', onPopState); + navigator?.windowControlsOverlay?.addEventListener?.('geometrychange', onWindowResize); + + const watchdogTimer = setInterval(() => { + if (disposed) return; + syncHostRouteIfChanged(); + if (!capsuleHost.isConnected || !portalHost.isConnected) { + ensureCapsuleDocked(); + } + }, 1200); + + ensureCapsuleDocked(); + renderCapsuleTelemetry(); + const allowMultiCarryOver = + telemetryStore.getState().telemetry?.settings?.showTopbarMultiSession !== false; + if (carryOverPopoverOpen) { + setPopoverOpen(true, { instant: true }); + } else if (carryOverMultiPinnedOpen && allowMultiCarryOver) { + setMultiOpen(true, { pinned: true, instant: true }); + } else if (carryOverMultiHoverOpen && allowMultiCarryOver) { + setMultiOpen(true, { pinned: false, instant: true }); + } else if (carryOverTooltipOpen) { + setTooltipOpen(true, { instant: true }); + } + const stopPolling = startAsyncTelemetryLoop(2000); + + const handle = { + bundleVersion, + ensureAlive() { + if (disposed) return false; + return ensureCapsuleDocked(); + }, + updateBridge(nextBridge) { + if (disposed || !nextBridge || typeof nextBridge !== 'object') return false; + const port = Number(nextBridge.port || 0); + const token = String(nextBridge.token || ''); + if (!Number.isInteger(port) || port <= 0 || !token) return false; + const cur = window.__AGUsageMonitorBridge || {}; + const portChanged = Number(cur.port || 0) !== port; + cur.port = port; + cur.token = token; + if (portChanged && cur.transportMode !== 'cdp') { + cur.transportMode = 'http'; + } + window.__AGUsageMonitorBridge = cur; + void fetchTelemetry({ force: false }); + return true; + }, + getTelemetrySnapshot() { + return telemetryStore.getState().telemetry; + }, + getLastPointer() { + return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null; + }, + deliverRpc(responses) { + if (disposed) return 0; + return deliverCdpBridgeResponses(responses); + }, + open() { + setPopoverOpen(true); + }, + close() { + setPopoverOpen(false); + }, + toggle() { + setPopoverOpen(!popoverOpen); + }, + openMulti(pinned = true) { + setMultiOpen(true, { pinned: Boolean(pinned) }); + }, + closeMulti() { + setMultiOpen(false); + }, + isOpen: () => popoverOpen, + isHoverOpen: () => tooltipOpen, + isMultiOpen: () => multiOpen, + isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned), + isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned), + getLayoutMode: () => layoutMode, + dispose() { + if (disposed) return; + disposed = true; + clearInterval(watchdogTimer); + if (hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + hoverLeaveTimer = null; + } + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + stopMultiLiveTicker(); + if (dockRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(dockRafId); + dockRafId = 0; + } + stopPolling(); + stopAsyncTelemetryLoop(); + unsubStore(); + unsubUiScope(); + try { + resizeObserver?.disconnect(); + } catch {} + try { + hostDomObserver?.disconnect(); + } catch {} + document.removeEventListener?.('mousedown', onDocMouseDown, true); + document.removeEventListener?.('keydown', onDocKeyDown); + document.removeEventListener?.('visibilitychange', onVisibilityChange); + window.removeEventListener?.('pointermove', onWindowPointerMove); + window.removeEventListener?.('blur', onWindowBlur); + window.removeEventListener?.('resize', onWindowResize); + window.removeEventListener?.('popstate', onPopState); + navigator?.windowControlsOverlay?.removeEventListener?.('geometrychange', onWindowResize); + try { + hoverCtxSegmentBar.destroy(); + } catch {} + try { + appInstance.destroy(); + } catch {} + try { + capsuleHost.remove(); + } catch {} + try { + portalHost.remove(); + } catch {} + if (window.__AGUsageMonitorOverlay === handle) { + delete window.__AGUsageMonitorOverlay; + } + }, + }; + + window.__AGUsageMonitorOverlay = handle; + return handle; +} + // --- src/main.js --- /** * @fileoverview Async entry point for Antigravity Usage & Speed Monitor. + * Automatically branches between Auxiliary Sidebar Webview mode (`#app-root`) + * and Main Window Dual-Mount Overlay mode (`window.__AGUsageMonitorBridge`). */ @@ -5581,15 +8471,24 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) { }; } +function startEntry() { + if (isWindowOverlayMode()) { + mountWindowOverlay(); + return; + } + bootstrapApp(); +} + function init() { if (typeof document === 'undefined') return; if (document.readyState === 'loading' && typeof document.addEventListener === 'function') { document.addEventListener('DOMContentLoaded', () => { - bootstrapApp(); + startEntry(); }); } else { - bootstrapApp(); + startEntry(); } } init(); +})(); diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index eb5fb24..9c5d89a 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -3,12 +3,12 @@ * * 负责统一管理: * 1. 插件根目录 (`PLUGIN_ROOT`)、面板目录 (`HERE`) 与持久化数据目录 (`DATA_DIR`) 的路径解析; - * 2. Language Server RPC 连接参数 (`LS_ADDR` / `CSRF_TOKEN`) 与 GitHub 云端价格表地址; + * 2. Language Server RPC 连接参数 (`LS_ADDR` / `LS_BASE_URL` / `CSRF_TOKEN`) 与 GitHub 云端价格表地址; * 3. 安全的 JSON 读写封装 (`loadJson` / `saveJson`) 与用户设置合并 (`loadSettings`); * 4. 跨子系统共享的内存态缓存容器(采用对象属性就地更新设计,兼容 ES Module 与 VM 沙箱)。 */ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -46,9 +46,12 @@ export const DEEP_STATS_CACHE_CANDIDATES = [ ]; /** - * Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token。 + * Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(自动剥离重复协议前缀与尾部斜杠)。 */ -export const LS_ADDR = process.env.ANTIGRAVITY_LS_ADDRESS; +const rawLsAddr = String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim(); +const LS_PROTOCOL = /^https:\/\//i.test(rawLsAddr) ? 'https' : 'http'; +export const LS_ADDR = rawLsAddr.replace(/^https?:\/\//i, '').replace(/\/+$/, ''); +export const LS_BASE_URL = LS_ADDR ? `${LS_PROTOCOL}://${LS_ADDR}` : ''; export const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN; /** @@ -68,21 +71,69 @@ export const DEFAULT_ARCHIVE_FALLBACK_URL = export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000; export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000; +/** + * 顶栏右侧精简胶囊三槽位允许配置的指标枚举与默认顺序。 + */ +export const TOPBAR_SLOT_KEYS = Object.freeze([ + 'context', + 'tps', + 'ttft', + 'cost', + 'quota_auto', + 'gemini_5h', + 'gemini_weekly', + 'claude_5h', + 'claude_weekly', + 'none', +]); + +export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']); + +/** + * 归一化顶栏三槽位配置数组,兜底非法枚举值并保证至少保留一个可见槽位。 + * + * @param {unknown} raw + * @returns {[string, string, string]} + */ +export function normalizeTopbarCapsuleSlots(raw) { + const arr = Array.isArray(raw) ? raw : []; + const slots = [0, 1, 2].map((idx) => { + const val = String(arr[idx] ?? '').trim(); + return TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_TOPBAR_SLOTS[idx]; + }); + if (slots.every((s) => s === 'none')) { + slots[0] = 'context'; + } + return /** @type {[string, string, string]} */ (slots); +} + /** * 用户可配置项的默认值。 */ -export const DEFAULT_SETTINGS = { - contextWindowLimit: 256000, // 默认 256k 自动压缩上下文预算基准 - weeklyTokenBudget: 150000000, // 自定义每周 Token 预算默认值 (150M) - weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100) +const DEFAULT_SETTINGS = { + weeklyTokenBudget: 150000000, // 自定义每周 Token 预算默认值 (150M,保留底层兼容) + weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100,保留底层兼容) weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost' - showUpstreamModel: false, // 步骤明细表是否显示上游真实 responseModel 名称 + showUpstreamModel: false, // 是否显示上游真实 responseModel 名称 autoUpdatePlugin: false, // 发现新版本且本地工作区干净时是否在后台自动更新插件 + enableWindowOverlay: true, // 是否启用双栖模式(自动通过 CDP 在主窗口顶栏挂载胶囊与悬浮面板) + showTopbarMultiSession: true, // 是否在顶栏左侧显示实时运行会话入口 + topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], // 顶栏右侧胶囊三槽位指标与顺序 }; /** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */ export const CACHE_SCHEMA_VERSION = 'v10-model-identity'; +/** + * 判断输入值是否为非数组普通对象(Plain Object)。 + * + * @param {unknown} v + * @returns {boolean} + */ +export function isPlainObject(v) { + return Boolean(v) && typeof v === 'object' && !Array.isArray(v); +} + /** * 安全读取并解析本地 JSON 文件;文件不存在或解析失败时返回 `fallback`。 * @@ -119,7 +170,18 @@ export function saveJson(filePath, data) { } } -const VALID_WEEKLY_MODES = new Set(['official', 'tokens', 'cost']); +/** + * 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。 + * + * @param {unknown} mode + * @returns {'official'|'custom_tokens'|'custom_cost'} + */ +export function normalizeWeeklyLimitMode(mode) { + const m = String(mode || '').trim().toLowerCase(); + if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens'; + if (m === 'custom_cost' || m === 'cost') return 'custom_cost'; + return 'official'; +} function sanitizeSettingNumber(val, fallback) { const num = Number(val); @@ -127,33 +189,29 @@ function sanitizeSettingNumber(val, fallback) { } /** - * 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段 `speedMode` 并兜底非法数值。 + * 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段并兜底非法数值。 * * @returns {typeof DEFAULT_SETTINGS} */ export function loadSettings() { const raw = loadJson(SETTINGS_FILE, {}); - const { speedMode: _legacySpeedMode, ...settings } = - raw && typeof raw === 'object' ? raw : {}; - const merged = { ...DEFAULT_SETTINGS, ...settings }; - const mode = String(merged.weeklyLimitMode || '').trim(); + const safeRaw = isPlainObject(raw) ? raw : {}; + const merged = { ...DEFAULT_SETTINGS, ...safeRaw }; return { - ...merged, - contextWindowLimit: sanitizeSettingNumber( - merged.contextWindowLimit, - DEFAULT_SETTINGS.contextWindowLimit - ), weeklyTokenBudget: sanitizeSettingNumber( - merged.weeklyTokenBudget, + safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit ?? merged.weeklyTokenBudget, DEFAULT_SETTINGS.weeklyTokenBudget ), weeklyCostBudget: sanitizeSettingNumber( merged.weeklyCostBudget, DEFAULT_SETTINGS.weeklyCostBudget ), - weeklyLimitMode: VALID_WEEKLY_MODES.has(mode) ? mode : DEFAULT_SETTINGS.weeklyLimitMode, + weeklyLimitMode: normalizeWeeklyLimitMode(merged.weeklyLimitMode), showUpstreamModel: merged.showUpstreamModel === true, autoUpdatePlugin: merged.autoUpdatePlugin === true, + enableWindowOverlay: merged.enableWindowOverlay !== false, + showTopbarMultiSession: merged.showTopbarMultiSession !== false, + topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots), }; } @@ -167,20 +225,70 @@ export function roundMetric(value) { return Number.isFinite(value) ? +value.toFixed(1) : null; } +/** + * 计算前端产物与后端源码文件的最大修改时间戳,用于插件热更新后触发客户端重载。 + * + * @returns {string} + */ +export function computeRuntimeCodeVersion() { + let maxMtime = 0; + const candidates = [ + join(HERE, 'app.js'), + join(HERE, 'styles.css'), + join(HERE, 'main.mjs'), + join(HERE, 'speed-metrics.mjs'), + ]; + const backendDir = join(HERE, 'backend'); + try { + if (existsSync(backendDir)) { + for (const name of readdirSync(backendDir)) { + if (name.endsWith('.mjs') || name.endsWith('.js')) { + candidates.push(join(backendDir, name)); + } + } + } + } catch { + // 忽略目录列举异常 + } + for (const file of candidates) { + try { + if (existsSync(file)) { + const mtime = Math.floor(statSync(file).mtimeMs || 0); + if (mtime > maxMtime) maxMtime = mtime; + } + } catch { + // 忽略单文件 stat 异常 + } + } + return String(maxMtime || Date.now()); +} + // --------------------------------------------------------------------------- -// 跨模块共享运行时状态容器(启动时自动完成历史轨迹缓存迁移) +// 跨模块共享运行时状态容器(启动时自动完成历史轨迹缓存迁移与损坏结构防御) // --------------------------------------------------------------------------- const loadedTrajectoryCache = loadJson(CACHE_FILE, {}); -let initialCacheMigrated = false; +let initialCacheMigrated = + loadedTrajectoryCache !== null && + loadedTrajectoryCache !== undefined && + !isPlainObject(loadedTrajectoryCache); -/** - * 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }` - */ -export const trajectoryCache = Object.fromEntries( - Object.entries(loadedTrajectoryCache).map(([id, entry]) => { - const rawSteps = Array.isArray(entry?.steps) ? entry.steps : []; - const normalizedSteps = rawSteps.map((s) => { +const safeCacheEntries = []; +if (isPlainObject(loadedTrajectoryCache)) { + for (const [id, entry] of Object.entries(loadedTrajectoryCache)) { + if (!id || !isPlainObject(entry)) { + initialCacheMigrated = true; + continue; + } + const rawSteps = Array.isArray(entry.steps) ? entry.steps : []; + if (!Array.isArray(entry.steps)) { + initialCacheMigrated = true; + } + const objectSteps = rawSteps.filter((s) => isPlainObject(s)); + if (objectSteps.length !== rawSteps.length) { + initialCacheMigrated = true; + } + const normalizedSteps = objectSteps.map((s) => { const norm = normalizeCachedStep(s); if (norm !== s) initialCacheMigrated = true; return norm; @@ -192,15 +300,20 @@ export const trajectoryCache = Object.fromEntries( break; } } - return [ + safeCacheEntries.push([ id, { ...entry, steps: finalSteps, }, - ]; - }) -); + ]); + } +} + +/** + * 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }` + */ +export const trajectoryCache = Object.fromEntries(safeCacheEntries); /** * 缓存状态与外部深层统计缓存 Memo。 @@ -217,9 +330,10 @@ export const externalDeepStatsMemo = { /** 并发请求去重表(防止同一参数并发重复拉取)。 */ export const inFlightRequests = new Map(); -/** 官方配额摘要 10 秒短期缓存。 */ +/** 官方配额摘要 10 秒短期缓存与失败退避冷却记录。 */ export const quotaSummaryCache = { ts: 0, + lastAttemptTs: 0, accountName: '', data: null, error: null, @@ -245,6 +359,7 @@ export const cloudSyncState = { /** 插件自更新执行状态。 */ export const pluginUpdateState = { isUpdating: false, + inFlightIsAuto: false, lastAutoAttemptVersion: '', lastResult: null, lastError: null, diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 21fdc74..7afa24a 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -3,14 +3,19 @@ * * 负责: * 1. 扫描 `~/.gemini/antigravity/conversations` 下的本地 `.db` / `.pb` / `.db-wal` 会话文件及修改时间; - * 2. 读取跨端共享的 `.deep_stats_cache.json`(兼容 IDE / CLI / Standalone 多端步骤数据合并); - * 3. 将 Language Server 摘要、本地磁盘文件与内存缓存三方会话列表对齐,并以受控并发(最多 4 路) + * 2. 读取跨端共享的 `.deep_stats_cache.json`(兼容 IDE / CLI / Standalone 多端步骤数据合并与账号归属隔离); + * 3. 将 Language Server 摘要、本地磁盘文件与内存缓存三方会话列表按大小写不敏感键对齐,并以受控并发(最多 4 路) * 拉取新增或 Schema 过期的会话轨迹步骤,持久化至 `trajectory_usage_cache.json`。 */ import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs'; import { join } from 'node:path'; -import { extractLiveActivity, extractModelSteps, parseIsoMs } from '../speed-metrics.mjs'; +import { + extractLiveActivity, + extractModelSteps, + getMaxMeaningfulStepIndex, + parseIsoMs, +} from '../speed-metrics.mjs'; import { BRAIN_DIR, CACHE_FILE, @@ -31,7 +36,7 @@ import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs'; * * @returns {Map} */ -export function discoverLocalConversationFiles() { +function discoverLocalConversationFiles() { const map = new Map(); if (!existsSync(CONVERSATIONS_DIR)) return map; try { @@ -61,7 +66,7 @@ export function discoverLocalConversationFiles() { * 加载并解析跨端(IDE / Standalone / JetBrains)写入的 `.deep_stats_cache.json` 缓存。 * 使用文件签名 (`mtimeMs + size`) 进行 Memoize,文件未变化时直接返回内存 Map。 * - * @returns {Map} + * @returns {Map} */ export function loadExternalDeepStatsCache() { const sigParts = []; @@ -90,6 +95,7 @@ export function loadExternalDeepStatsCache() { for (const filePath of existingFiles) { const raw = loadJson(filePath, null); if (!raw || typeof raw.perConvo !== 'object' || !raw.perConvo) continue; + const fileAccountName = String(raw.accountName || raw.email || '').trim(); for (const item of Object.values(raw.perConvo)) { for (const e of item?.entries || []) { @@ -118,14 +124,18 @@ export function loadExternalDeepStatsCache() { const existing = convos.get(mapKey); if (existing && existing.steps.length >= rawEntries.length) continue; + const itemAccountName = String( + item?.accountName || item?.email || fileAccountName || '' + ).trim(); + const steps = []; let lastModifiedMs = 0; for (let idx = 0; idx < rawEntries.length; idx++) { const e = rawEntries[idx]; - const inputTokens = Math.max(0, Number(e?.inp) || 0); - const cacheReadTokens = Math.max(0, Number(e?.cache) || 0); - const responseTokens = Math.max(0, Number(e?.out) || 0); - const thinkingTokens = Math.max(0, Number(e?.reasoning) || 0); + const inputTokens = Math.max(0, Math.floor(Number(e?.inp) || 0)); + const cacheReadTokens = Math.max(0, Math.floor(Number(e?.cache) || 0)); + const responseTokens = Math.max(0, Math.floor(Number(e?.out) || 0)); + const thinkingTokens = Math.max(0, Math.floor(Number(e?.reasoning) || 0)); const outputTokens = responseTokens + thinkingTokens; if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0) continue; const createdAtMs = e?.ts ? Date.parse(e.ts) || 0 : 0; @@ -155,6 +165,7 @@ export function loadExternalDeepStatsCache() { convos.set(mapKey, { cascadeId, appSource, + accountName: itemAccountName, title: titleMap[fullKey] || titleMap[cascadeId] || cascadeId.slice(0, 8), lastModifiedMs, steps, @@ -172,6 +183,7 @@ const MAX_CONCURRENT_RPC = 4; const LEGACY_MIGRATION_BATCH_SIZE = 8; const MAX_SUBAGENT_RECONCILE_DEPTH = 4; const FAILED_RPC_COOLDOWN_MS = 60_000; +const ACTIVE_FAILED_RPC_COOLDOWN_MS = 15_000; const TRANSCRIPT_TAIL_MAX_BYTES = 96 * 1024; const MAX_TRANSCRIPT_MEMO_ENTRIES = 64; const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -277,6 +289,9 @@ function readTranscriptTailSteps(cascadeId, maxLines = 24) { function scoreLiveActivitySpecificity(act) { if (!act || typeof act !== 'object') return 0; const sig = String(act.signature || ''); + if (sig.startsWith('compacting:') || sig.startsWith('compacting-done:')) { + return 5; + } if ( sig.startsWith('planner-tool:') || sig.startsWith('step-run:') || @@ -285,7 +300,6 @@ function scoreLiveActivitySpecificity(act) { return 4; } if ( - sig.startsWith('compacting:') || sig.startsWith('responding:') || sig.startsWith('thinking:') || sig.startsWith('responding-done:') || @@ -302,37 +316,35 @@ function scoreLiveActivitySpecificity(act) { return 1; } -function extractActivityStepOrd(act) { - const m = String(act?.signature || '').match(/^[a-z0-9-]+:(\d+)(?::|$)/i); - return m ? Number(m[1]) : -1; -} - function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) { if (!isRunning) return null; - const rpcAct = - Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0 - ? extractLiveActivity(rpcRawSteps, true, fallbackMs) - : null; + const hasRpcSteps = Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0; + const rpcAct = hasRpcSteps ? extractLiveActivity(rpcRawSteps, true, fallbackMs) : null; const transcriptSteps = readTranscriptTailSteps(cascadeId); const transcriptAct = transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null; if (rpcAct && transcriptAct) { - const rpcMs = Number(rpcAct.startedAtMs || 0); - const transMs = Number(transcriptAct.startedAtMs || 0); - if (rpcMs > 0 && transMs > 0 && rpcMs !== transMs) { - return rpcMs > transMs ? rpcAct : transcriptAct; - } - const rpcOrd = extractActivityStepOrd(rpcAct); - const transOrd = extractActivityStepOrd(transcriptAct); - if (rpcOrd >= 0 && transOrd >= 0 && rpcOrd !== transOrd) { - return rpcOrd > transOrd ? rpcAct : transcriptAct; + // 1. 先按真实 Cortex 步骤序号对齐比较:尚未刷入 transcript.jsonl 的新步骤(如正在进行的 CHECKPOINT 压缩或流式回复)优先采用 RPC + const rpcStepIdx = getMaxMeaningfulStepIndex(rpcRawSteps); + const transStepIdx = getMaxMeaningfulStepIndex(transcriptSteps); + if (rpcStepIdx >= 0 && transStepIdx >= 0 && rpcStepIdx !== transStepIdx) { + return rpcStepIdx > transStepIdx ? rpcAct : transcriptAct; } + + // 2. 同一步骤序号下优先采用语义更明确的状态(上下文压缩 > 工具执行 > 流式生成 > 工具后置思考) const rpcScore = scoreLiveActivitySpecificity(rpcAct); const transScore = scoreLiveActivitySpecificity(transcriptAct); - if (transScore > rpcScore) return transcriptAct; - if (rpcScore > transScore) return rpcAct; - // 同步骤、同优先级下优先采用包含完整 tool_calls 参数的 transcript.jsonl 解析结果 + if (rpcScore !== transScore) { + return rpcScore > transScore ? rpcAct : transcriptAct; + } + + // 3. 同一步骤且均为压缩态时,优先采用携带精确完成时刻的 RPC 状态;常规步骤则优先采用含完整参数的 transcript.jsonl + const rpcMs = Number(rpcAct.startedAtMs || 0); + const transMs = Number(transcriptAct.startedAtMs || 0); + if (rpcAct.phase === 'compacting' && rpcMs !== transMs) { + return rpcMs >= transMs ? rpcAct : transcriptAct; + } return transcriptAct; } return ( @@ -377,13 +389,11 @@ function mergeSubagentSpecs(primary, secondary) { /** * 从主/父会话的原始轨迹步骤 (`CORTEX_STEP_TYPE_INVOKE_SUBAGENT`) 中提取派生子代理列表。 - * Antigravity 重启后 `GetAllCascadeTrajectories` 不再返回历史子代理摘要, - * 通过解析父轨迹内的 `invokeSubagent` 步骤即可完整找回所有子代理及其角色名称与启动顺序。 * * @param {object[]} [rawSteps=[]] * @returns {Array<{ cascadeId: string, role: string, typeName: string, createdTimeMs: number, spawnOrder: number }>} */ -export function extractSubagentRefsFromSteps(rawSteps = []) { +function extractSubagentRefsFromSteps(rawSteps = []) { const refsMap = new Map(); let orderCounter = 0; for (const st of rawSteps || []) { @@ -482,9 +492,10 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) { * 选定当前活跃会话,并以最多 4 路并发增量同步更新了的会话轨迹。 * * @param {{ - * summariesObj: Record, - * currentAccountName: string, - * requestedConvId: string + * summariesObj?: Record, + * currentAccountName?: string, + * requestedConvId?: string, + * forceRefresh?: boolean * }} params * @returns {Promise<{ * conversations: object[], @@ -496,34 +507,87 @@ export async function enumerateAndSyncConversations({ summariesObj = {}, currentAccountName = '', requestedConvId = '', + forceRefresh = false, }) { const nowSweepMs = Date.now(); - for (const [k, ts] of failedFetchCooldownMap.entries()) { - if (nowSweepMs - ts >= FAILED_RPC_COOLDOWN_MS) { - failedFetchCooldownMap.delete(k); + if (forceRefresh) { + failedFetchCooldownMap.clear(); + } else { + for (const [k, rec] of failedFetchCooldownMap.entries()) { + const failedAt = typeof rec === 'number' ? rec : rec?.failedAt || 0; + const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec?.cooldownMs || FAILED_RPC_COOLDOWN_MS; + if (nowSweepMs - failedAt >= cooldownMs) { + failedFetchCooldownMap.delete(k); + } } } + + let cacheDirty = cacheState.needsSave; const diskConvMap = discoverLocalConversationFiles(); - const allCascadeIds = new Set([ - ...Object.keys(summariesObj), - ...diskConvMap.keys(), - ...Object.keys(trajectoryCache), - ]); - const existingLowerIds = new Set(Array.from(allCascadeIds, (id) => id.toLowerCase())); - for (const entry of Object.values(trajectoryCache)) { + + // 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC) + const canonicalIdByLower = new Map(); + const summariesByLower = new Map(); + for (const [rawId, summary] of Object.entries(summariesObj || {})) { + const lower = String(rawId || '').trim().toLowerCase(); + if (!lower) continue; + canonicalIdByLower.set(lower, rawId); + summariesByLower.set(lower, summary); + } + + for (const rawCacheKey of Object.keys(trajectoryCache)) { + const lower = String(rawCacheKey || '').trim().toLowerCase(); + if (!lower) continue; + const existingCanon = canonicalIdByLower.get(lower); + if (!existingCanon) { + // 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目 + const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey; + if (normalizedKey !== rawCacheKey) { + trajectoryCache[normalizedKey] = trajectoryCache[rawCacheKey]; + delete trajectoryCache[rawCacheKey]; + cacheDirty = true; + } + canonicalIdByLower.set(lower, normalizedKey); + } else if (existingCanon !== rawCacheKey) { + const targetEntry = trajectoryCache[existingCanon]; + const dupEntry = trajectoryCache[rawCacheKey]; + if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) { + trajectoryCache[existingCanon] = dupEntry; + } + delete trajectoryCache[rawCacheKey]; + cacheDirty = true; + } + } + + for (const diskLowerId of diskConvMap.keys()) { + if (!canonicalIdByLower.has(diskLowerId)) { + canonicalIdByLower.set(diskLowerId, diskLowerId); + } + } + + // 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表 + for (const [cacheKey, entry] of Object.entries(trajectoryCache)) { + const cacheKeyLower = String(cacheKey || '').toLowerCase(); + if ( + entry?.accountName && + currentAccountName && + entry.accountName !== currentAccountName && + !summariesByLower.has(cacheKeyLower) + ) { + continue; + } for (const ref of entry?.subagentRefs || []) { const refCid = String(ref?.cascadeId || '').trim().toLowerCase(); - if (refCid && !existingLowerIds.has(refCid)) { - allCascadeIds.add(refCid); - existingLowerIds.add(refCid); + if (refCid && !canonicalIdByLower.has(refCid)) { + canonicalIdByLower.set(refCid, refCid); } } } const reqLower = String(requestedConvId || '').trim().toLowerCase(); const rawConversations = []; - for (const cascadeId of allCascadeIds) { - const item = summariesObj[cascadeId]; + for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) { + const item = summariesByLower.get(cidLower); const cached = trajectoryCache[cascadeId]; if ( cached?.accountName && @@ -533,7 +597,7 @@ export async function enumerateAndSyncConversations({ ) { continue; } - const diskMtimeMs = diskConvMap.get(cascadeId) || 0; + const diskMtimeMs = diskConvMap.get(cidLower) || 0; const rawMeta = item?.trajectoryMetadata || item?.metadata || {}; const parentConversationId = String( rawMeta.parentConversationId || cached?.parentConversationId || '' @@ -549,7 +613,7 @@ export async function enumerateAndSyncConversations({ const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null; const isSubagent = Boolean(parentConversationId) || - Boolean(rootConversationId && rootConversationId !== cascadeId.toLowerCase()); + Boolean(rootConversationId && rootConversationId !== cidLower); if (item) { const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || ''; @@ -627,7 +691,6 @@ export async function enumerateAndSyncConversations({ rawConversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs); - let cacheDirty = cacheState.needsSave; const attemptedFetchIds = new Set(); const nowPollMs = Date.now(); @@ -638,12 +701,13 @@ export async function enumerateAndSyncConversations({ } function isFetchInCooldown(conv, sig) { - if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') return false; - if (reqLower && conv.cascadeId.toLowerCase() === reqLower) return false; + if (forceRefresh) return false; const key = `${conv.cascadeId.toLowerCase()}::${sig}`; - const failedAt = failedFetchCooldownMap.get(key); - if (!failedAt) return false; - if (nowPollMs - failedAt >= FAILED_RPC_COOLDOWN_MS) { + const rec = failedFetchCooldownMap.get(key); + if (!rec) return false; + const failedAt = typeof rec === 'number' ? rec : rec.failedAt; + const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec.cooldownMs; + if (nowPollMs - failedAt >= cooldownMs) { failedFetchCooldownMap.delete(key); return false; } @@ -690,7 +754,10 @@ export async function enumerateAndSyncConversations({ const sig = buildConvSig(conv); const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; + const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower); const prev = trajectoryCache[conv.cascadeId]; + let partialTailSteps = []; + let hasTailStepInfo = false; try { const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); if (!Array.isArray(trajRes?.trajectory?.steps)) { @@ -698,6 +765,12 @@ export async function enumerateAndSyncConversations({ } const rawSteps = trajRes.trajectory.steps; if (Number(trajRes.numTotalSteps) > rawSteps.length) { + if (rawSteps.length > 0) { + partialTailSteps = rawSteps; + const tailIdx = + rawSteps[rawSteps.length - 1]?.metadata?.sourceTrajectoryStepInfo?.stepIndex; + hasTailStepInfo = Number.isFinite(Number(tailIdx)); + } throw new Error('Incomplete trajectory; retaining cached usage'); } failedFetchCooldownMap.delete(cooldownKey); @@ -777,13 +850,17 @@ export async function enumerateAndSyncConversations({ } } catch (err) { console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`); + if (!(isRunning && hasTailStepInfo)) { + const cooldownMs = + isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS; + failedFetchCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); + } if (!isRunning) { - failedFetchCooldownMap.set(cooldownKey, nowPollMs); liveActivityMemo.delete(conv.cascadeId.toLowerCase()); } else { const fallbackLive = resolveBestLiveActivity( conv.cascadeId, - [], + partialTailSteps, true, conv.lastModifiedMs || conv.createdTimeMs || 0 ); @@ -859,15 +936,17 @@ export async function enumerateAndSyncConversations({ const subCid = String(ref?.cascadeId || '').trim().toLowerCase(); if (!subCid || subCid === parentId) continue; + const canonSubId = canonicalIdByLower.get(subCid) || subCid; + canonicalIdByLower.set(subCid, canonSubId); let subConv = byLowerId.get(subCid); - const subCached = trajectoryCache[subConv?.cascadeId || subCid]; + const subCached = trajectoryCache[subConv?.cascadeId || canonSubId]; if (!subConv) { const diskMtimeMs = diskConvMap.get(subCid) || 0; const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0; const stepCount = Number(subCached?.steps?.length || 0); subConv = { - cascadeId: subCid, - title: ref.role || subCached?.title || subCid.slice(0, 8), + cascadeId: canonSubId, + title: ref.role || subCached?.title || canonSubId.slice(0, 8), stepCount, rawStepCount: stepCount, status: 'IDLE', @@ -1037,7 +1116,7 @@ export async function enumerateAndSyncConversations({ } } - // 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下 + // 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下;孤儿子代理绝不提升为顶层根会话 const subagentsByRoot = new Map(); const conversations = []; @@ -1045,11 +1124,13 @@ export async function enumerateAndSyncConversations({ const cid = conv.cascadeId.toLowerCase(); const rootId = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase(); const rootTarget = byId.get(rootId); - if (conv.isSubagent && rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) { - if (!subagentsByRoot.has(rootId)) { - subagentsByRoot.set(rootId, []); + if (conv.isSubagent) { + if (rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) { + if (!subagentsByRoot.has(rootId)) { + subagentsByRoot.set(rootId, []); + } + subagentsByRoot.get(rootId).push(conv); } - subagentsByRoot.get(rootId).push(conv); } else { conversations.push(conv); } diff --git a/sidecars/panel/backend/ls-rpc.mjs b/sidecars/panel/backend/ls-rpc.mjs index 5d30e55..ec192bb 100644 --- a/sidecars/panel/backend/ls-rpc.mjs +++ b/sidecars/panel/backend/ls-rpc.mjs @@ -3,22 +3,14 @@ * * 负责: * 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`); - * 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存, - * 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存); - * 3. 维护全局 `StreamDiagnostics` 实例以采样流式事件时序。 + * 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存与失败退避冷却, + * 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。 */ -import { StreamDiagnostics } from '../stream-diagnostics.mjs'; -import { CSRF_TOKEN, DATA_DIR, LS_ADDR, quotaSummaryCache } from './config.mjs'; +import { CSRF_TOKEN, LS_BASE_URL, quotaSummaryCache } from './config.mjs'; -/** - * 全局流式传输诊断采样器实例。 - */ -export const diagnostics = new StreamDiagnostics({ - dataDir: DATA_DIR, - lsAddress: LS_ADDR, - csrfToken: CSRF_TOKEN, -}); +const QUOTA_CACHE_TTL_MS = 10_000; +const QUOTA_RETRY_COOLDOWN_MS = 5_000; /** * 调用本地 `LanguageServerService` 的指定 RPC 方法。 @@ -29,13 +21,16 @@ export const diagnostics = new StreamDiagnostics({ * @returns {Promise} */ export async function callLsRpc(method, body = {}, timeoutMs = 5000) { + if (!LS_BASE_URL) { + throw new Error('Language Server address (ANTIGRAVITY_LS_ADDRESS) is not configured'); + } const res = await fetch( - `http://${LS_ADDR}/exa.language_server_pb.LanguageServerService/${method}`, + `${LS_BASE_URL}/exa.language_server_pb.LanguageServerService/${method}`, { method: 'POST', headers: { 'Content-Type': 'application/json', - 'x-codeium-csrf-token': CSRF_TOKEN, + 'x-codeium-csrf-token': CSRF_TOKEN || '', }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs), @@ -53,38 +48,63 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) { * * 缓存策略: * - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口; - * - 当超过 10 秒或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时, + * - 常规轮询发生网络失败或空载荷时进入 5 秒冷却退避,避免每 2 秒重复超时阻塞; + * - 当超过 TTL 或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时, * 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。 * - * @param {boolean} [forceRefresh=false] 是否强制穿透本地 10 秒缓存 - * @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null}>} + * @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却 + * @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>} */ export async function getOfficialQuotaSummary(forceRefresh = false) { const now = Date.now(); - if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < 10000) { + if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) { return { data: quotaSummaryCache.data, fetchedAtMs: quotaSummaryCache.ts, isStale: false, refreshFailed: false, error: null, + fromCache: true, }; } + if ( + !forceRefresh && + quotaSummaryCache.lastAttemptTs > 0 && + now - quotaSummaryCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS && + quotaSummaryCache.error + ) { + return { + data: quotaSummaryCache.data, + fetchedAtMs: quotaSummaryCache.ts || 0, + isStale: Boolean(quotaSummaryCache.data), + refreshFailed: true, + error: quotaSummaryCache.error, + fromCache: true, + }; + } + + quotaSummaryCache.lastAttemptTs = now; try { const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000); - const payload = res?.response || res; - if (Array.isArray(payload?.groups) || Array.isArray(payload?.buckets)) { + const payload = res?.response !== undefined ? res.response : res; + if (payload && typeof payload === 'object' && !Array.isArray(payload)) { + const normalized = + Array.isArray(payload.groups) || Array.isArray(payload.buckets) + ? payload + : { ...payload, groups: [] }; quotaSummaryCache.ts = now; - quotaSummaryCache.data = payload; + quotaSummaryCache.data = normalized; quotaSummaryCache.error = null; return { - data: payload, + data: normalized, fetchedAtMs: now, isStale: false, refreshFailed: false, error: null, + fromCache: false, }; } + quotaSummaryCache.error = 'Quota summary empty'; } catch (err) { console.error(`RetrieveUserQuotaSummary failed: ${err.message}`); quotaSummaryCache.error = err.message; @@ -95,5 +115,6 @@ export async function getOfficialQuotaSummary(forceRefresh = false) { isStale: Boolean(quotaSummaryCache.data), refreshFailed: true, error: quotaSummaryCache.error || 'Quota RPC unavailable', + fromCache: false, }; } diff --git a/sidecars/panel/backend/model-pricing.mjs b/sidecars/panel/backend/model-pricing.mjs index dbaf582..6d81687 100644 --- a/sidecars/panel/backend/model-pricing.mjs +++ b/sidecars/panel/backend/model-pricing.mjs @@ -2,8 +2,8 @@ * @fileoverview 模型身份识别、展示名称规范化与单步 API 等效成本计算。 * * 核心原则: - * 1. 优先信任服务端下发的动态模型目录 (`dynamicModelMap`) 与真实响应模型 (`responseModel`), - * 其次匹配本地/云端 `PLACEHOLDER_MAP` 与 `MODEL_PRICING`; + * 1. 优先融合服务端下发的动态模型目录 (`dynamicModelMap`)、静态占位符表 (`PLACEHOLDER_MAP`) + * 与真实响应模型 (`responseModel`),并优先匹配含档位后缀的精确价格条目; * 2. 价格未知或模型身份无法确认时,严格返回 `pricing: null` 与 `costUsd: null`, * 绝不借用其他模型单价伪造费用。 */ @@ -12,29 +12,23 @@ import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs'; /** * 根据 API 提供商枚举或模型标识符推断所属模型家族(`'Gemini'` | `'Claude'` | `'GPT'` | `'Other'`)。 + * 注意:先匹配更具体的 `ANTHROPIC`/`CLAUDE` 与 `OPENAI`/`GPT`(含 `o1`/`o3`/`o4` 系列), + * 防止 `API_PROVIDER_GOOGLE_VERTEX_ANTHROPIC` 被宽泛的 `GOOGLE` 子串抢先误判为 `'Gemini'`。 * * @param {string} [rawModelKey=''] 原始模型键名或占位符 * @param {string} [modelId=''] 规范化模型 ID * @param {string} [apiProvider=''] 上游 API 提供商枚举字符串 * @returns {'Gemini'|'Claude'|'GPT'|'Other'} */ -export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvider = '') { +function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvider = '') { const prov = String(apiProvider || '').toUpperCase(); - if (prov.includes('GEMINI') || prov.includes('GOOGLE')) return 'Gemini'; if (prov.includes('ANTHROPIC') || prov.includes('CLAUDE')) return 'Claude'; if (prov.includes('OPENAI') || prov.includes('GPT')) return 'GPT'; + if (prov.includes('GEMINI') || prov.includes('GOOGLE')) return 'Gemini'; const combined = `${rawModelKey} ${modelId}`.toUpperCase(); if ( - combined.includes('GEMINI') || - combined.includes('CARBON') || - combined.includes('ARGON') || - combined.includes('FLASH') || - combined.includes('GOOGLE') - ) { - return 'Gemini'; - } - if ( + combined.includes('ANTHROPIC') || combined.includes('CLAUDE') || combined.includes('FABLE') || combined.includes('SONNET') || @@ -43,9 +37,22 @@ export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', api ) { return 'Claude'; } - if (combined.includes('GPT') || combined.includes('OPENAI')) { + if ( + combined.includes('GPT') || + combined.includes('OPENAI') || + /\bO[134](?:[-_\s]|$)/.test(combined) + ) { return 'GPT'; } + if ( + combined.includes('GEMINI') || + combined.includes('CARBON') || + combined.includes('ARGON') || + combined.includes('FLASH') || + combined.includes('GOOGLE') + ) { + return 'Gemini'; + } return 'Other'; } @@ -60,13 +67,15 @@ export function isArgonModelIdentifier(...parts) { } /** - * 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型。 + * 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M429 枚举)。 * * @param {...string} parts 待检测的标识片段 * @returns {boolean} */ export function isCarbonModelIdentifier(...parts) { - return /\bcarbon\b|gemini-4-carbon/i.test(parts.filter(Boolean).join(' ')); + return /\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M429\b/i.test( + parts.filter(Boolean).join(' ') + ); } /** @@ -84,7 +93,8 @@ export function getBaseModelLabel(label = '') { } /** - * 将形如 `gemini-3.1-pro`、`gemini-3.5-flash-lite` 或 `gemini-4-carbon` 的通用模型 Slug 转为人类可读标签。 + * 将严格匹配的 `gemini-3.1-pro`、`gemini-3.5-flash-lite` 或 `gemini-4-carbon` 通用模型 Slug 转为人类可读标签。 + * 使用行尾锚点 `$` 防止未收录新后缀(如 `gemini-3.1-pro-ultra-v2`)被静默截断伪装成旧模型获取错误定价。 * * @param {string} [slug=''] * @returns {string} @@ -94,7 +104,7 @@ export function formatGenericModelSlug(slug = '') { .trim() .replace(/^session-display:/i, ''); if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return ''; - const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon)(?:-(lite))?/i); + const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon)(?:-(lite))?$/i); if (m) { const ver = m[1]; const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase(); @@ -107,54 +117,69 @@ export function formatGenericModelSlug(slug = '') { /** * 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与单价配置。 * - * @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M318`) - * @param {Map} dynamicModelMap 从 `GetUserStatus` 提取的动态模型表 + * @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`) + * @param {Map} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表 * @param {string} [apiProvider=''] API 提供商枚举 * @param {string} [modelDisplayName=''] 已知的模型展示名称 * @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`) - * @returns {{ - * rawModel: string, - * modelId: string, - * label: string, - * baseLabel: string, - * shortName: string, - * family: string, - * pricing: {input: number, cache: number, output: number, short: string, family: string} | null, - * isEstimatedPrice: boolean - * }} */ export function resolveModelInfo( rawModelKey, - dynamicModelMap, + dynamicModelMap = new Map(), apiProvider = '', modelDisplayName = '', responseModel = '' ) { - const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey]; + const dynEntry = + dynamicModelMap && typeof dynamicModelMap.get === 'function' + ? dynamicModelMap.get(rawModelKey) + : null; + const staticPh = PLACEHOLDER_MAP[rawModelKey] || null; + + // 若 GetUserStatus 仅下发了 label 而未下发真实 modelId(或被填成占位符自身),继续合并静态 PLACEHOLDER_MAP 的精确 modelId + const dynValidModelId = + dynEntry?.modelId && dynEntry.modelId !== rawModelKey ? dynEntry.modelId : ''; + const mergedModelId = dynValidModelId || staticPh?.modelId || dynEntry?.modelId || ''; + const mergedLabel = dynEntry?.label || staticPh?.label || ''; + const cleanResponseModel = responseModel && responseModel !== 'unknown' ? String(responseModel).trim() : ''; const cleanRawFallback = rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel; const derivedDisplay = modelDisplayName || - dyn?.label || + mergedLabel || formatGenericModelSlug(rawModelKey) || formatGenericModelSlug(cleanResponseModel) || cleanRawFallback || '模型未知'; + + // 先生成保留档位后缀的精确 Slug(如 "Gemini 3.8 Flash (Low)" -> "gemini-3.8-flash-low"),防止被基础族名定价覆盖 + const tieredSlug = derivedDisplay + .toLowerCase() + .replace(/[()]/g, ' ') + .trim() + .replace(/[^a-z0-9.]+/g, '-') + .replace(/^-+|-+$/g, ''); + const tieredDashedSlug = tieredSlug.replace(/\./g, '-'); + const baseLabel = getBaseModelLabel(derivedDisplay); const canonicalSlug = baseLabel.toLowerCase().replace(/\s+/g, '-'); const dashedSlug = canonicalSlug.replace(/\./g, '-'); const modelId = - dyn?.modelId || + mergedModelId || (rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel) || 'unknown'; + const explicitPricing = MODEL_PRICING[modelId] || MODEL_PRICING[rawModelKey] || (cleanResponseModel ? MODEL_PRICING[cleanResponseModel] : null) || + MODEL_PRICING[tieredSlug] || + MODEL_PRICING[tieredDashedSlug] || MODEL_PRICING[canonicalSlug] || MODEL_PRICING[dashedSlug]; + if (explicitPricing) { return { rawModel: rawModelKey, @@ -173,7 +198,7 @@ export function resolveModelInfo( rawModel: rawModelKey, modelId, label: derivedDisplay, - baseLabel: getBaseModelLabel(derivedDisplay), + baseLabel, shortName: derivedDisplay, family: inferredFamily, pricing: null, @@ -183,6 +208,7 @@ export function resolveModelInfo( /** * 计算单个步骤的 API 等效美元成本;若模型未定价(`pricing === null`)则返回 `null`。 + * 对负数、NaN 或非有限数值统一安全钳制为 0。 * * @param {{ inputTokens: number, cacheReadTokens: number, outputTokens: number }} step * @param {{ input: number, cache: number, output: number } | null} pricing @@ -190,8 +216,12 @@ export function resolveModelInfo( */ export function computeStepCost(step, pricing) { if (!pricing) return null; - const inCost = (step.inputTokens / 1_000_000) * pricing.input; - const cacheCost = (step.cacheReadTokens / 1_000_000) * pricing.cache; - const outCost = (step.outputTokens / 1_000_000) * pricing.output; + const safeTok = (v) => { + const n = Number(v); + return Number.isFinite(n) && n > 0 ? n : 0; + }; + const inCost = (safeTok(step?.inputTokens) / 1_000_000) * pricing.input; + const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * pricing.cache; + const outCost = (safeTok(step?.outputTokens) / 1_000_000) * pricing.output; return inCost + cacheCost + outCost; } diff --git a/sidecars/panel/backend/plugin-updater.mjs b/sidecars/panel/backend/plugin-updater.mjs index f04543f..0ad963d 100644 --- a/sidecars/panel/backend/plugin-updater.mjs +++ b/sidecars/panel/backend/plugin-updater.mjs @@ -5,15 +5,15 @@ * 1. `syncCloudCatalog`:定期或手动从 GitHub 主干拉取最新 `pricing-catalog.json`, * 经 Schema 与可信域名白名单清洗后落盘至 `DATA_DIR/remote_pricing_cache.json` 并热更新内存价格字典; * 2. `performPluginUpdate` 严格执行以下防降级与防损坏门禁: - * - 开发仓库自动更新隔离:非 `.gemini/config/plugins/` 目录一律禁止后台自动更新(`dev_repo_auto_disabled`); + * - 开发仓库自动更新隔离:非 `.gemini/config/plugins/` 目录一律禁止后台自动更新(`dev_repo_auto_disabled`), + * 且若手动更新撞上正在进行的后台自动检查,等待自动检查结束后再执行手动更新; * - 全量工作区干净度门禁(含未跟踪文件):执行 `git status --porcelain`(不带 `--untracked-files=no`), * 只要存在任何已修改或未跟踪文件(`??`),立即终止(`dirty_worktree`),绝不执行 `git stash`; - * - 分支门禁:通过 `git rev-parse --abbrev-ref HEAD` 校验当前必须处于 `main` 分支(`not_on_main_branch`),防止污染特性分支或游离 HEAD; - * - 强制远端版本门禁(Git 通道):必须且只能从 `git show origin/main:plugin.json` 解析出合法 SemVer, + * - 分支门禁:仅允许 `main` 或 `release/*` 发布分支执行快进更新(`not_on_main_branch`),防止污染特性分支或游离 HEAD; + * - 强制远端版本门禁(Git 通道):必须且只能从 `git show origin/:plugin.json` 解析出合法 SemVer, * 严禁回退使用缓存的 `cloudSyncState.latestPluginVersion`;仅当 `remoteVersion > previousVersion` 时才继续; - * - 提交拓扑与核心文件门禁:通过 `git merge-base --is-ancestor HEAD origin/main` 确认本地无分叉提交(`diverged_worktree`); - * - ZIP 通道安全覆盖:下载前与解压后双重校验 `compareSemver > 0`,覆盖前对 `main.mjs`/`app.js` 执行 `node --check` 语法预检, - * 使用 `cpSync` 过滤器严格保护 `.git`/`.data`/`node_modules`,并在覆盖前备份关键文件以支持异常回滚。 + * - 提交拓扑与核心文件门禁:通过 `git merge-base --is-ancestor HEAD origin/` 确认本地无分叉提交(`diverged_worktree`); + * - ZIP 通道安全覆盖与多余旧文件裁剪:覆盖前备份关键文件,覆盖后清理新版已删除的旧源码文件,异常回滚时同步删除残留新文件。 */ import { execFile } from 'node:child_process'; @@ -52,7 +52,7 @@ import { * @param {object} [opts] `execFile` 附加选项 * @returns {Promise<{stdout: string, stderr: string}>} */ -export function runExecFile(cmd, args, opts = {}) { +function runExecFile(cmd, args, opts = {}) { return new Promise((resolve, reject) => { if (typeof execFile !== 'function') { reject(new Error('execFile unavailable in current environment')); @@ -71,12 +71,12 @@ export function runExecFile(cmd, args, opts = {}) { /** * 更新完成后调度 Sidecar 进程平滑退出,让宿主进程监督器自动重启新代码。 - * 在单元测试环境(`LS_ADDR === 'test.invalid'`)下自动跳过。 + * 在单元测试环境(`!LS_ADDR || LS_ADDR === 'test.invalid'`)下自动跳过。 * * @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端 */ export function scheduleSidecarRestart(delayMs = 350) { - if (LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return; + if (!LS_ADDR || LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return; setTimeout(() => { try { process.exit(0); @@ -92,7 +92,7 @@ export function scheduleSidecarRestart(delayMs = 350) { * @param {string} extractDir 解压目标目录 * @returns {string|null} */ -export function locateExtractedPluginRoot(extractDir) { +function locateExtractedPluginRoot(extractDir) { if (existsSync(join(extractDir, 'plugin.json'))) return extractDir; try { for (const name of readdirSync(extractDir)) { @@ -108,7 +108,7 @@ export function locateExtractedPluginRoot(extractDir) { } /** - * `cpSync` 安全过滤函数:严格禁止覆盖 `.git`、`.data`、`node_modules` 或临时更新目录。 + * `cpSync` 安全过滤函数:严格禁止覆盖 `.git`、`.data`、`node_modules`、`plan` 或临时更新目录。 * * @param {string} srcPath * @returns {boolean} @@ -119,6 +119,7 @@ function isSafeCopyPath(srcPath) { name === '.git' || name === '.data' || name === 'node_modules' || + name === 'plan' || name.startsWith('.update-staging-') ) { return false; @@ -126,13 +127,44 @@ function isSafeCopyPath(srcPath) { return true; } +/** + * 递归清理 `targetDir` 中在 `referenceDir` 已不存在的多余文件/目录(保护 `.git`/`.data`/`node_modules`/`plan`)。 + * 用于 ZIP 升级后清理旧版废弃源码文件,以及在覆盖中途异常回滚时清除半途写入的新增文件。 + * + * @param {string} targetDir + * @param {string} referenceDir + */ +function pruneExtraneousFiles(targetDir, referenceDir) { + if (!existsSync(targetDir) || !existsSync(referenceDir)) return; + let names = []; + try { + names = readdirSync(targetDir); + } catch { + return; + } + for (const name of names) { + const targetChild = join(targetDir, name); + if (!isSafeCopyPath(targetChild)) continue; + const refChild = join(referenceDir, name); + if (!existsSync(refChild)) { + try { + rmSync(targetChild, { recursive: true, force: true }); + } catch { + // 忽略单项删除异常 + } + } else { + pruneExtraneousFiles(targetChild, refChild); + } + } +} + /** * 在真实运行环境下对目标目录的核心 JS 文件执行 `node --check` 语法预检。 * * @param {string} rootDir 插件根目录或解压目录 */ async function verifyPluginJsSyntax(rootDir) { - if (LS_ADDR === 'test.invalid') return; + if (!LS_ADDR || LS_ADDR === 'test.invalid') return; const nodeBin = process?.execPath || 'node'; const filesToCheck = [ join(rootDir, 'sidecars', 'panel', 'main.mjs'), @@ -152,7 +184,18 @@ async function verifyPluginJsSyntax(rootDir) { * @returns {Promise} 更新结果对象 */ export async function performPluginUpdate({ isAuto = false } = {}) { - if (pluginUpdateState.inFlight) return pluginUpdateState.inFlight; + if (pluginUpdateState.inFlight) { + if (isAuto || !pluginUpdateState.inFlightIsAuto) { + return pluginUpdateState.inFlight; + } + // 若用户点击手动更新时恰好有一轮后台自动更新检查正在运行,等待其收尾后再按手动模式继续执行 + await pluginUpdateState.inFlight.catch(() => {}); + if (pluginUpdateState.inFlight) { + return pluginUpdateState.inFlight; + } + } + + pluginUpdateState.inFlightIsAuto = Boolean(isAuto); pluginUpdateState.inFlight = (async () => { pluginUpdateState.isUpdating = true; pluginUpdateState.lastError = null; @@ -201,7 +244,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { return pluginUpdateState.lastResult; } - // 2. 分支检查:仅当处于 main 分支时才允许拉取 origin/main,防止污染特性分支或游离 HEAD + // 2. 分支检查:仅当处于 main 或 release/* 发布分支时才允许快进拉取,防止污染特性分支或游离 HEAD const branchRes = await runExecFile('git', [ '-C', PLUGIN_ROOT, @@ -210,7 +253,11 @@ export async function performPluginUpdate({ isAuto = false } = {}) { 'HEAD', ]); const currentBranch = branchRes.stdout.trim(); - if (currentBranch && currentBranch !== 'main') { + const isAllowedBranch = + !currentBranch || + currentBranch === 'main' || + /^release\/[0-9A-Za-z._-]+$/.test(currentBranch); + if (!isAllowedBranch) { const msg = `当前分支为 ${currentBranch},已跳过更新`; pluginUpdateState.lastError = isAuto ? null : msg; pluginUpdateState.lastResult = { @@ -227,8 +274,11 @@ export async function performPluginUpdate({ isAuto = false } = {}) { return pluginUpdateState.lastResult; } - // 3. 只读拉取远端分支引用,并严格从 origin/main:plugin.json 读取远端版本号(严禁回退使用缓存版本) - await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', 'main', '--tags']); + const targetBranch = currentBranch || 'main'; + const remoteRef = `origin/${targetBranch}`; + + // 3. 只读拉取远端分支引用,并严格从 origin/:plugin.json 读取远端版本号(严禁回退使用缓存版本) + await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', targetBranch, '--tags']); let remoteVersion = ''; try { @@ -236,7 +286,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { '-C', PLUGIN_ROOT, 'show', - 'origin/main:plugin.json', + `${remoteRef}:plugin.json`, ]); const parsedManifest = JSON.parse(showRes.stdout || '{}'); const rawVer = @@ -267,7 +317,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { return result; } - // 5. 提交拓扑预检:确保当前 HEAD 是 origin/main 的祖先提交(无本地超前或分叉提交) + // 5. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交) try { await runExecFile('git', [ '-C', @@ -275,7 +325,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { 'merge-base', '--is-ancestor', 'HEAD', - 'origin/main', + remoteRef, ]); } catch { const msg = '本地分支存在未推送提交,已跳过更新'; @@ -294,7 +344,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { } // 6. 确认全部门禁通过后,执行快进合并并校验 JS 语法 - await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', 'main']); + await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', targetBranch]); await verifyPluginJsSyntax(PLUGIN_ROOT); rebuildActiveCatalog(); const currentVersion = readInstalledPluginVersion(); @@ -406,7 +456,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { // 覆盖前先对解压目录执行 JS 语法预检,防止损坏代码覆盖现有安装 await verifyPluginJsSyntax(extractedRoot); - // 备份当前插件根目录关键文件,若覆盖途中异常则自动回滚 + // 备份当前插件根目录关键文件,覆盖后清理已废弃旧文件;若覆盖途中异常则完整回滚并移除残留新文件 mkdirSync(backupDir, { recursive: true }); cpSync(PLUGIN_ROOT, backupDir, { recursive: true, force: true, filter: isSafeCopyPath }); try { @@ -415,6 +465,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { force: true, filter: isSafeCopyPath, }); + pruneExtraneousFiles(PLUGIN_ROOT, extractedRoot); } catch (copyErr) { try { cpSync(backupDir, PLUGIN_ROOT, { @@ -422,6 +473,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { force: true, filter: isSafeCopyPath, }); + pruneExtraneousFiles(PLUGIN_ROOT, backupDir); } catch { // 忽略回滚二级异常 } @@ -473,6 +525,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) { return result; } finally { pluginUpdateState.isUpdating = false; + pluginUpdateState.inFlightIsAuto = false; pluginUpdateState.inFlight = null; } })(); diff --git a/sidecars/panel/backend/pricing-catalog.mjs b/sidecars/panel/backend/pricing-catalog.mjs index 8bde4b5..a39ec4d 100644 --- a/sidecars/panel/backend/pricing-catalog.mjs +++ b/sidecars/panel/backend/pricing-catalog.mjs @@ -1,11 +1,12 @@ /** - * @fileoverview 内置模型价格与占位符字典、Schema 安全清洗及三级目录合并(内置 + 本地 + 云端)。 + * @fileoverview 模型价格与占位符目录加载、Schema 安全清洗及本地/云端目录合并。 * * 价格口径与安全原则: * - 所有单价单位均为 USD / 1M Tokens(`input`: 未命中缓存输入, `cache`: 缓存读取, `output`: 输出与思考); * - 价格仅用于本地 API 等效成本折算,不代表订阅配额的扣减比例; + * - 离线基准统一从随包发布的 `pricing-catalog.json` 读取,避免在 JS 源码中重复维护双份硬编码字典; * - 未收录或身份未知的模型严格保持未定价状态(`null`),绝不借用其他模型价格,也绝不允许 `null`/`0` 伪价格混入; - * - 版本号与更新包 URL 均经过严格格式与可信 GitHub 域名白名单校验。 + * - 版本号(遵循 SemVer 2.0)与更新包 URL 均经过严格格式与可信 GitHub 域名白名单校验。 */ import { existsSync } from 'node:fs'; @@ -24,194 +25,23 @@ import { pluginUpdateState, } from './config.mjs'; -/** - * 代码内置兜底模型价格字典(当本地与云端目录均不可用时的离线基准)。 - */ -export const BUILTIN_MODEL_PRICING = { - // Gemini 4 (Carbon & Argon) & 3.x & 2.5 官方目录价格 (USD / 1M tokens) - 'gemini-4-carbon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4-high', family: 'Gemini' }, - 'gemini-4-carbon-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4', family: 'Gemini' }, - 'gemini-4-carbon-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4-low', family: 'Gemini' }, - 'gemini-4-carbon': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4', family: 'Gemini' }, - 'gemini-4-argon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-high', family: 'Gemini' }, - 'gemini-4-argon-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4', family: 'Gemini' }, - 'gemini-4-argon-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-low', family: 'Gemini' }, - 'gemini-4-argon': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4', family: 'Gemini' }, - 'gemini-3.8-flash-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8-high', family: 'Gemini' }, - 'gemini-3.8-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' }, - 'gemini-3.8-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.8-low', family: 'Gemini' }, - 'gemini-3.8-flash-tiered': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' }, - 'gemini-3.8-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' }, - 'gemini-3.7-flash-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7-high', family: 'Gemini' }, - 'gemini-3.7-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' }, - 'gemini-3.7-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.7-low', family: 'Gemini' }, - 'gemini-3.7-flash-tiered': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' }, - 'gemini-3.7-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' }, - 'gemini-3.6-flash-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6-high', family: 'Gemini' }, - 'gemini-3.6-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6', family: 'Gemini' }, - 'gemini-3.6-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.6-low', family: 'Gemini' }, - 'gemini-3.6-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6', family: 'Gemini' }, - 'gemini-3.5-flash-high': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5-high', family: 'Gemini' }, - 'gemini-3.5-flash-medium': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5', family: 'Gemini' }, - 'gemini-3.5-flash-low': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5-low', family: 'Gemini' }, - 'gemini-3.5-flash-extra-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-xlow', family: 'Gemini' }, - 'gemini-3.5-flash': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5', family: 'Gemini' }, - 'gemini-3.5-flash-lite': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-lite', family: 'Gemini' }, - 'gemini-3.1-pro-high': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-high', family: 'Gemini' }, - 'gemini-3.1-pro-low': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' }, - 'gemini-3.1-pro-low-thinking': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' }, - 'gemini-3.1-pro-preview': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' }, - 'gemini-3.1-pro-preview-customtools': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' }, - 'gemini-3.1-pro': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' }, - 'gemini-3.1-flash-lite-preview': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' }, - 'gemini-3.1-flash-lite': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' }, - 'gemini-for-google-3.1-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1', family: 'Gemini' }, - 'gemini-3.1-flash-image': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1-img', family: 'Gemini' }, - 'gemini-3-flash-preview': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' }, - 'gemini-3-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' }, - 'gemini-3-pro-image': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3-img', family: 'Gemini' }, - 'gemini-2.5-pro': { input: 1.25, cache: 0.125, output: 10.0, short: 'pro-2.5', family: 'Gemini' }, - 'gemini-2.5-flash': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-2.5', family: 'Gemini' }, - 'gemini-2.5-flash-lite': { input: 0.10, cache: 0.01, output: 0.40, short: 'flash-2.5-lite', family: 'Gemini' }, - - // Claude 4.5 / 4.6 / 4.7 / 4.8 / 5.x 官方目录价格 - 'claude-fable-5-2-max': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-max', family: 'Claude' }, - 'claude-fable-5-2-high': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-high', family: 'Claude' }, - 'claude-fable-5-2-medium': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' }, - 'claude-fable-5-2-low': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-low', family: 'Claude' }, - 'claude-fable-5-2': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' }, - 'claude-fable-5-1': { input: 10.0, cache: 0.25, output: 50.0, short: 'fable-5.1', family: 'Claude' }, - 'claude-fable-5': { input: 10.0, cache: 1.00, output: 50.0, short: 'fable-5', family: 'Claude' }, - 'claude-opus-5-5-max': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-max', family: 'Claude' }, - 'claude-opus-5-5-high': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-high', family: 'Claude' }, - 'claude-opus-5-5-medium': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' }, - 'claude-opus-5-5-low': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-low', family: 'Claude' }, - 'claude-opus-5-5': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' }, - 'claude-opus-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-5', family: 'Claude' }, - 'claude-opus-4-8': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.8', family: 'Claude' }, - 'claude-opus-4-7': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.7', family: 'Claude' }, - 'claude-opus-4-6-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus', family: 'Claude' }, - 'claude-opus-4-6': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.6', family: 'Claude' }, - 'claude-opus-4-5-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', family: 'Claude' }, - 'claude-opus-4-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', family: 'Claude' }, - 'claude-sonnet-5-5-max': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-max', family: 'Claude' }, - 'claude-sonnet-5-5-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-high', family: 'Claude' }, - 'claude-sonnet-5-5-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' }, - 'claude-sonnet-5-5-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-low', family: 'Claude' }, - 'claude-sonnet-5-5': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' }, - 'claude-sonnet-5': { input: 2.00, cache: 0.20, output: 10.0, short: 'sonnet-5', family: 'Claude' }, - 'claude-sonnet-4-6': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet', family: 'Claude' }, - 'claude-sonnet-4-5-thinking': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', family: 'Claude' }, - 'claude-sonnet-4-5': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', family: 'Claude' }, - 'claude-haiku-5-5': { input: 0.10, cache: 0.01, output: 0.50, short: 'haiku-5.5', family: 'Claude' }, - 'claude-haiku-4-5': { input: 1.00, cache: 0.10, output: 5.00, short: 'haiku-4.5', family: 'Claude' }, - - // OpenAI / GPT 官方目录价格 - 'gpt-6-astra': { input: 10.0, cache: 1.00, output: 50.0, short: 'gpt-6-astra', family: 'GPT' }, - 'gpt-6.1-sol': { input: 2.00, cache: 0.10, output: 10.0, short: 'gpt-6.1-sol', family: 'GPT' }, - 'gpt-6.1-terra': { input: 1.00, cache: 0.05, output: 5.00, short: 'gpt-6.1-terra', family: 'GPT' }, - 'gpt-6-sol': { input: 2.00, cache: 0.20, output: 10.0, short: 'gpt-6-sol', family: 'GPT' }, - 'gpt-6-luna': { input: 0.10, cache: 0.01, output: 0.50, short: 'gpt-6-luna', family: 'GPT' }, - 'gpt-5.6': { input: 4.00, cache: 0.40, output: 20.0, short: 'gpt-5.6', family: 'GPT' }, - 'gpt-5.6-sol': { input: 4.00, cache: 0.40, output: 20.0, short: 'gpt-5.6-sol', family: 'GPT' }, - 'gpt-5.6-terra': { input: 2.00, cache: 0.20, output: 12.0, short: 'gpt-5.6-terra', family: 'GPT' }, - 'gpt-5.6-luna': { input: 0.20, cache: 0.02, output: 1.20, short: 'gpt-5.6-luna', family: 'GPT' }, - 'gpt-5.5': { input: 5.00, cache: 0.50, output: 30.0, short: 'gpt-5.5', family: 'GPT' }, - 'gpt-5.4': { input: 2.50, cache: 0.25, output: 15.0, short: 'gpt-5.4', family: 'GPT' }, - 'gpt-5.4-mini': { input: 0.75, cache: 0.075, output: 4.50, short: 'gpt-5.4-mini', family: 'GPT' }, - 'gpt-5.4-nano': { input: 0.20, cache: 0.02, output: 1.25, short: 'gpt-5.4-nano', family: 'GPT' }, - 'gpt-5.3-codex': { input: 1.75, cache: 0.175, output: 14.0, short: 'gpt-5.3-codex', family: 'GPT' }, - 'gpt-5.2': { input: 1.75, cache: 0.175, output: 14.0, short: 'gpt-5.2', family: 'GPT' }, - 'gpt-5.1': { input: 1.25, cache: 0.125, output: 10.0, short: 'gpt-5.1', family: 'GPT' }, - 'gpt-5': { input: 1.25, cache: 0.125, output: 10.0, short: 'gpt-5', family: 'GPT' }, - 'gpt-5-mini': { input: 0.25, cache: 0.025, output: 2.00, short: 'gpt-5-mini', family: 'GPT' }, - 'gpt-5-nano': { input: 0.05, cache: 0.005, output: 0.40, short: 'gpt-5-nano', family: 'GPT' }, - 'gpt-4.1': { input: 2.00, cache: 0.50, output: 8.00, short: 'gpt-4.1', family: 'GPT' }, - 'gpt-4.1-mini': { input: 0.40, cache: 0.10, output: 1.60, short: 'gpt-4.1-mini', family: 'GPT' }, - 'gpt-4o': { input: 2.50, cache: 1.25, output: 10.0, short: 'gpt-4o', family: 'GPT' }, - 'gpt-4o-mini': { input: 0.15, cache: 0.075, output: 0.60, short: 'gpt-4o-mini', family: 'GPT' }, - 'o4-mini': { input: 1.10, cache: 0.275, output: 4.40, short: 'o4-mini', family: 'GPT' }, - 'o3': { input: 2.00, cache: 0.50, output: 8.00, short: 'o3', family: 'GPT' }, - 'o3-mini': { input: 1.10, cache: 0.55, output: 4.40, short: 'o3-mini', family: 'GPT' }, - 'gpt-oss-120b-medium': { input: 0.80, cache: 0.10, output: 2.40, short: 'gpt-oss', family: 'GPT' }, -}; - -/** - * 代码内置兜底枚举占位符映射表(`MODEL_PLACEHOLDER_Mxxx` -> `modelId` & `label`)。 - */ -export const BUILTIN_PLACEHOLDER_MAP = { - // Gemini 4 Argon - MODEL_PLACEHOLDER_M417: { modelId: 'gemini-4-argon-high', label: 'Gemini 4 Argon (High)' }, - MODEL_PLACEHOLDER_M418: { modelId: 'gemini-4-argon-medium', label: 'Gemini 4 Argon (Medium)' }, - MODEL_PLACEHOLDER_M419: { modelId: 'gemini-4-argon-low', label: 'Gemini 4 Argon (Low)' }, - // Gemini 3.8 Flash - MODEL_PLACEHOLDER_M318: { modelId: 'gemini-3.8-flash-high', label: 'Gemini 3.8 Flash (High)' }, - MODEL_PLACEHOLDER_M319: { modelId: 'gemini-3.8-flash-medium', label: 'Gemini 3.8 Flash (Medium)' }, - MODEL_PLACEHOLDER_M320: { modelId: 'gemini-3.8-flash-low', label: 'Gemini 3.8 Flash (Low)' }, - MODEL_PLACEHOLDER_M322: { modelId: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash (Tiered)' }, - // Gemini 3.7 Flash - MODEL_PLACEHOLDER_M298: { modelId: 'gemini-3.7-flash-high', label: 'Gemini 3.7 Flash (High)' }, - MODEL_PLACEHOLDER_M299: { modelId: 'gemini-3.7-flash-medium', label: 'Gemini 3.7 Flash (Medium)' }, - MODEL_PLACEHOLDER_M300: { modelId: 'gemini-3.7-flash-low', label: 'Gemini 3.7 Flash (Low)' }, - MODEL_PLACEHOLDER_M301: { modelId: 'gemini-3.7-flash-tiered', label: 'Gemini 3.7 Flash (Tiered)' }, - // Gemini 3.6 Flash - MODEL_PLACEHOLDER_M71: { modelId: 'gemini-3.6-flash-high', label: 'Gemini 3.6 Flash (High)' }, - MODEL_PLACEHOLDER_M72: { modelId: 'gemini-3.6-flash-medium', label: 'Gemini 3.6 Flash (Medium)' }, - MODEL_PLACEHOLDER_M73: { modelId: 'gemini-3.6-flash-low', label: 'Gemini 3.6 Flash (Low)' }, - MODEL_PLACEHOLDER_M196: { modelId: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash' }, - // Gemini 3.5 Flash & Lite - MODEL_PLACEHOLDER_M149: { modelId: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash (High)' }, - MODEL_PLACEHOLDER_M20: { modelId: 'gemini-3.5-flash-low', label: 'Gemini 3.5 Flash' }, - MODEL_PLACEHOLDER_M187: { modelId: 'gemini-3.5-flash-extra-low', label: 'Gemini 3.5 Flash (Extra Low)' }, - MODEL_PLACEHOLDER_M198: { modelId: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash Lite' }, - // Gemini 3.1 & 3.0 - MODEL_PLACEHOLDER_M37: { modelId: 'gemini-3.1-pro-high', label: 'Gemini 3.1 Pro (High)' }, - MODEL_PLACEHOLDER_M36: { modelId: 'gemini-3.1-pro-low', label: 'Gemini 3.1 Pro (Low)' }, - MODEL_PLACEHOLDER_M50: { modelId: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' }, - MODEL_PLACEHOLDER_M59: { modelId: 'gemini-for-google-3.1-flash', label: 'Gemini for Google 3.1 Flash' }, - MODEL_PLACEHOLDER_M21: { modelId: 'gemini-3.1-flash-image', label: 'Gemini 3.1 Flash Image' }, - MODEL_PLACEHOLDER_M18: { modelId: 'gemini-3-flash', label: 'Gemini 3 Flash' }, - MODEL_PLACEHOLDER_M9: { modelId: 'gemini-3-pro-image', label: 'Gemini 3 Pro Image' }, - // Gemini 2.5 - MODEL_GOOGLE_GEMINI_2_5_PRO: { modelId: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' }, - MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' }, - MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (Thinking)' }, - MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' }, - // Claude 5.5 / 4.8 / 4.6 / 4.5 - MODEL_PLACEHOLDER_M406: { modelId: 'claude-opus-5-5-max', label: 'Claude Opus 5.5 (Max)' }, - MODEL_PLACEHOLDER_M402: { modelId: 'claude-opus-5-5-high', label: 'Claude Opus 5.5 (High)' }, - MODEL_PLACEHOLDER_M401: { modelId: 'claude-opus-5-5-medium', label: 'Claude Opus 5.5 (Medium)' }, - MODEL_PLACEHOLDER_M400: { modelId: 'claude-opus-5-5-low', label: 'Claude Opus 5.5 (Low)' }, - MODEL_PLACEHOLDER_M368: { modelId: 'claude-opus-5-5', label: 'Claude Opus 5.5' }, - MODEL_PLACEHOLDER_M407: { modelId: 'claude-sonnet-5-5-max', label: 'Claude Sonnet 5.5 (Max)' }, - MODEL_PLACEHOLDER_M405: { modelId: 'claude-sonnet-5-5-high', label: 'Claude Sonnet 5.5 (High)' }, - MODEL_PLACEHOLDER_M404: { modelId: 'claude-sonnet-5-5-medium', label: 'Claude Sonnet 5.5 (Medium)' }, - MODEL_PLACEHOLDER_M403: { modelId: 'claude-sonnet-5-5-low', label: 'Claude Sonnet 5.5 (Low)' }, - MODEL_PLACEHOLDER_M254: { modelId: 'claude-opus-4-8', label: 'Claude Opus 4.8' }, - MODEL_PLACEHOLDER_M26: { modelId: 'claude-opus-4-6-thinking', label: 'Claude Opus 4.6 (Thinking)' }, - MODEL_PLACEHOLDER_M35: { modelId: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6 (Thinking)' }, - MODEL_PLACEHOLDER_M12: { modelId: 'claude-opus-4-5-thinking', label: 'Claude Opus 4.5 (Thinking)' }, - MODEL_PLACEHOLDER_M11: { modelId: 'claude-opus-4-5', label: 'Claude Opus 4.5' }, - MODEL_CLAUDE_4_5_SONNET_THINKING: { modelId: 'claude-sonnet-4-5-thinking', label: 'Claude Sonnet 4.5 (Thinking)' }, - MODEL_CLAUDE_4_5_SONNET: { modelId: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' }, - // OpenAI - MODEL_OPENAI_GPT_OSS_120B_MEDIUM: { modelId: 'gpt-oss-120b-medium', label: 'GPT-OSS 120B (Medium)' }, -}; - /** * 当前生效的模型价格表与占位符映射表(通过就地更新属性保持跨模块引用一致)。 */ -export const MODEL_PRICING = { ...BUILTIN_MODEL_PRICING }; -export const PLACEHOLDER_MAP = { ...BUILTIN_PLACEHOLDER_MAP }; +export const MODEL_PRICING = {}; +export const PLACEHOLDER_MAP = {}; /** - * 校验字符串是否为合法的 `X.Y.Z` 语义化版本号格式。 + * 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。 * * @param {*} v * @returns {boolean} */ export function isValidSemver(v) { - return typeof v === 'string' && /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.trim()); + return ( + typeof v === 'string' && + /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(v.trim()) + ); } const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor'; @@ -223,7 +53,7 @@ const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor'; * @param {string} fallbackUrl * @returns {string} */ -export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) { +function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) { if (typeof rawUrl !== 'string' || !rawUrl.trim()) return fallbackUrl; try { const parsed = new URL(rawUrl.trim()); @@ -247,7 +77,7 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) { } /** - * 比较两个语义化版本号(如 `'1.5.0'` vs `'1.4.0'`,支持 `-beta.1` 预发布后缀比较)。 + * 按 SemVer 2.0 规范(§10 忽略 `+build` 元数据,§11.4 按 ASCII 码序与纯数字段逐级比较预发布标签)比较两个版本号。 * * @param {string} a * @param {string} b @@ -256,7 +86,10 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) { export function compareSemver(a, b) { if (!isValidSemver(a) || !isValidSemver(b)) return 0; const parse = (v) => { - const cleaned = String(v || '').trim().replace(/^v/i, ''); + const cleaned = String(v || '') + .trim() + .replace(/^v/i, '') + .replace(/\+.*$/, ''); const dashIdx = cleaned.indexOf('-'); const coreStr = dashIdx >= 0 ? cleaned.slice(0, dashIdx) : cleaned; const preStr = dashIdx >= 0 ? cleaned.slice(dashIdx + 1) : ''; @@ -278,7 +111,30 @@ export function compareSemver(a, b) { if (!pa.pre && !pb.pre) return 0; if (!pa.pre && pb.pre) return 1; if (pa.pre && !pb.pre) return -1; - return pa.pre.localeCompare(pb.pre, undefined, { numeric: true }); + + const idsA = pa.pre.split('.'); + const idsB = pb.pre.split('.'); + const minLen = Math.min(idsA.length, idsB.length); + for (let i = 0; i < minLen; i++) { + const idA = idsA[i]; + const idB = idsB[i]; + if (idA === idB) continue; + const numA = /^\d+$/.test(idA); + const numB = /^\d+$/.test(idB); + if (numA && numB) { + const bigA = BigInt(idA); + const bigB = BigInt(idB); + if (bigA !== bigB) return bigA > bigB ? 1 : -1; + continue; + } + // SemVer 2.0 §11.4.1:纯数字标识符的优先级始终低于含字母标识符 + if (numA && !numB) return -1; + if (!numA && numB) return 1; + // SemVer 2.0 §11.4.2:含字母标识符按 ASCII 字节序比较 + return idA < idB ? -1 : 1; + } + if (idsA.length === idsB.length) return 0; + return idsA.length > idsB.length ? 1 : -1; } /** @@ -289,7 +145,17 @@ export function compareSemver(a, b) { export function readInstalledPluginVersion() { const manifest = loadJson(PLUGIN_MANIFEST_FILE, null); const ver = typeof manifest?.version === 'string' ? manifest.version.trim() : ''; - return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.2'; + return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.3'; +} + +function normalizeModelFamily(rawFamily) { + const f = String(rawFamily || '').trim(); + const lower = f.toLowerCase(); + if (lower === 'gemini' || lower === 'google') return 'Gemini'; + if (lower === 'claude' || lower === 'anthropic') return 'Claude'; + if (lower === 'gpt' || lower === 'openai') return 'GPT'; + if (lower === 'other') return 'Other'; + return f; } /** @@ -347,7 +213,7 @@ export function sanitizeCatalogPayload(raw) { cache: v.cache, output: v.output, short: String(v.short).trim(), - family: String(v.family).trim(), + family: normalizeModelFamily(v.family), }; validPricingCount++; } @@ -376,6 +242,10 @@ export function sanitizeCatalogPayload(raw) { return null; } + const explicitReleaseUrl = sanitizeTrustedGithubUrl(raw.releaseUrl, ''); + const explicitDownloadUrl = sanitizeTrustedGithubUrl(raw.downloadUrl, ''); + const explicitArchiveUrl = sanitizeTrustedGithubUrl(raw.archiveFallbackUrl, ''); + return { schemaVersion: Number(raw.schemaVersion || 1), catalogVersion: @@ -385,12 +255,12 @@ export function sanitizeCatalogPayload(raw) { updatedAt: typeof raw.updatedAt === 'string' && raw.updatedAt.trim() ? raw.updatedAt.trim() : null, latestPluginVersion, - releaseUrl: sanitizeTrustedGithubUrl(raw.releaseUrl, DEFAULT_RELEASE_URL), - downloadUrl: sanitizeTrustedGithubUrl(raw.downloadUrl, DEFAULT_DOWNLOAD_URL), - archiveFallbackUrl: sanitizeTrustedGithubUrl( - raw.archiveFallbackUrl, - DEFAULT_ARCHIVE_FALLBACK_URL - ), + releaseUrl: explicitReleaseUrl || DEFAULT_RELEASE_URL, + downloadUrl: explicitDownloadUrl || DEFAULT_DOWNLOAD_URL, + archiveFallbackUrl: explicitArchiveUrl || DEFAULT_ARCHIVE_FALLBACK_URL, + hasReleaseUrl: Boolean(explicitReleaseUrl), + hasDownloadUrl: Boolean(explicitDownloadUrl), + hasArchiveFallbackUrl: Boolean(explicitArchiveUrl), fetchedAtMs: Number(raw.fetchedAtMs || 0), sourceUrl: typeof raw.sourceUrl === 'string' ? raw.sourceUrl : '', pricing, @@ -399,7 +269,7 @@ export function sanitizeCatalogPayload(raw) { } /** - * 按「内置保底 -> 本地目录 -> 云端缓存(按 `updatedAt` 新旧自动裁决优先级)」三级合并重建内存价格表。 + * 按「随包本地目录 -> 云端缓存(按 `updatedAt` 新旧自动裁决优先级)」合并重建内存价格表。 */ export function rebuildActiveCatalog() { const localRaw = loadJson(LOCAL_CATALOG_FILE, null); @@ -423,8 +293,8 @@ export function rebuildActiveCatalog() { layers.push({ kind: 'local', cat: localCat }); } - const nextPricing = { ...BUILTIN_MODEL_PRICING }; - const nextPlaceholders = { ...BUILTIN_PLACEHOLDER_MAP }; + const nextPricing = {}; + const nextPlaceholders = {}; let activeSource = 'builtin'; let catalogVersion = 'builtin'; let updatedAt = null; @@ -437,7 +307,9 @@ export function rebuildActiveCatalog() { for (const { kind, cat } of layers) { Object.assign(nextPricing, cat.pricing); Object.assign(nextPlaceholders, cat.placeholders); - activeSource = kind; + if (kind === 'remote' || cat.catalogVersion || cat.updatedAt) { + activeSource = kind; + } if (cat.catalogVersion) catalogVersion = cat.catalogVersion; if (cat.updatedAt) updatedAt = cat.updatedAt; if (cat.latestPluginVersion) { @@ -447,9 +319,9 @@ export function rebuildActiveCatalog() { ? cat.latestPluginVersion : installedVersion; } - if (cat.releaseUrl) releaseUrl = cat.releaseUrl; - if (cat.downloadUrl) downloadUrl = cat.downloadUrl; - if (cat.archiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl; + if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl; + if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl; + if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl; } for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k]; diff --git a/sidecars/panel/backend/quota-pools.mjs b/sidecars/panel/backend/quota-pools.mjs index 38160e8..f4233fc 100644 --- a/sidecars/panel/backend/quota-pools.mjs +++ b/sidecars/panel/backend/quota-pools.mjs @@ -1,12 +1,12 @@ /** - * @fileoverview 官方配额桶归一化、周期窗口识别与多模型池(Gemini / Argon / Claude & GPT)构建。 + * @fileoverview 官方配额桶归一化、周期窗口识别与多模型池(Gemini / Argon / Carbon / Claude & GPT)构建。 * * 处理所有已知的 Antigravity 服务端配额形态: - * - Google AI Ultra:Argon 与 Flash 共享同一个 Gemini Models 配额池; - * - Google AI Pro(形态 1):`RetrieveUserQuotaSummary` 返回独立的 `Gemini 4 Argon` 组; - * - Google AI Pro(形态 2):`Gemini Models` 组内嵌套独立的 `argon-weekly` 桶; - * - Google AI Pro(形态 3):`GetUserStatus` 的 `clientModelConfigs.quotaInfo` 为 Argon 报告了与标准 Gemini 不同的独立剩余比例; - * - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略但存在有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。 + * - Google AI Ultra:Argon / Carbon 与 Flash 共享同一个 Gemini Models 配额池; + * - Google AI Pro(形态 1):`RetrieveUserQuotaSummary` 返回独立的 `Gemini 4 Argon` / `Gemini 4 Carbon` 组; + * - Google AI Pro(形态 2):`Gemini Models` 组内嵌套独立的 `argon-weekly` / `carbon-weekly` 桶; + * - Google AI Pro(形态 3):`GetUserStatus` 的 `clientModelConfigs.quotaInfo` 为 Argon / Carbon 报告了与标准 Gemini 不同的独立剩余比例; + * - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略且存在尚未过期的有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。 */ import { parseIsoMs } from '../speed-metrics.mjs'; @@ -20,6 +20,7 @@ import { * 将原始配额对象(来自 `RetrieveUserQuotaSummary` 桶或 `clientModelConfigs.quotaInfo`)归一化为百分比结构。 * * @param {object} rawObj + * @param {number} [nowMs=Date.now()] * @returns {{ * remainingFraction: number, * remainingPct: number, @@ -29,7 +30,7 @@ import { * description: string * } | null} */ -export function normalizeQuotaFraction(rawObj) { +function normalizeQuotaFraction(rawObj, nowMs = Date.now()) { if (!rawObj || typeof rawObj !== 'object') return null; let remFrac = null; if (rawObj.disabled === true) { @@ -41,8 +42,11 @@ export function normalizeQuotaFraction(rawObj) { ) { remFrac = Math.max(0, Math.min(1, Number(rawObj.remainingFraction))); } else if (typeof rawObj.resetTime === 'string' && rawObj.resetTime.trim().length > 0) { - // Proto3 在配额完全耗尽(0.0)时会省略默认数值字段,此时凭有效 resetTime 判定为剩余 0 - remFrac = 0; + // Proto3 在配额完全耗尽(0.0)时会省略默认数值字段;仅当 resetTime 是未来有效时间戳时才判定为 0% 剩余 + const resetMs = parseIsoMs(rawObj.resetTime); + if (resetMs > nowMs) { + remFrac = 0; + } } if (remFrac === null) return null; const usedFrac = Math.max(0, Math.min(1, 1 - remFrac)); @@ -60,11 +64,11 @@ export function normalizeQuotaFraction(rawObj) { * 识别官方配额桶所属的时间窗口类型(`'5h'` 或 `'weekly'`)。 * * @param {object} bucket - * @param {number} [groupBucketCount=1] 所属分组内的桶总数 + * @param {number} [_groupBucketCount=1] 所属分组内的桶总数(保留参数签名兼容) * @param {number} [nowMs=Date.now()] 当前毫秒时间戳 * @returns {'5h'|'weekly'} */ -export function classifyOfficialBucketWindow(bucket, groupBucketCount = 1, nowMs = Date.now()) { +function classifyOfficialBucketWindow(bucket, _groupBucketCount = 1, nowMs = Date.now()) { const w = String(bucket?.window || '') .trim() .toLowerCase(); @@ -80,19 +84,23 @@ export function classifyOfficialBucketWindow(bucket, groupBucketCount = 1, nowMs return 'weekly'; } const resetMs = parseIsoMs(bucket?.resetTime); - if (resetMs > nowMs + 6 * 3600 * 1000 || groupBucketCount === 1) { - return 'weekly'; + if (resetMs > 0 && resetMs <= nowMs + 6 * 3600 * 1000) { + return '5h'; } - return '5h'; + return 'weekly'; } +const THIRD_PARTY_POOL_RE = + /3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i; + /** - * 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Claude & GPT`)。 + * 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Carbon` / `Claude & GPT`)。 + * 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。 * * @param {{ groupName?: string, groupDesc?: string, bucketId?: string, bucketName?: string }} params * @returns {{ poolKey: string, poolLabel: string, poolName: string }} */ -export function classifyQuotaPoolIdentity({ +function classifyQuotaPoolIdentity({ groupName = '', groupDesc = '', bucketId = '', @@ -102,6 +110,8 @@ export function classifyQuotaPoolIdentity({ const bName = String(bucketName || ''); const gName = String(groupName || ''); const gDesc = String(groupDesc || ''); + const primaryText = `${bId} ${bName} ${gName}`; + if ( /carbon/i.test(bId) || /carbon/i.test(bName) || @@ -130,20 +140,23 @@ export function classifyQuotaPoolIdentity({ poolName: 'Gemini 4 Argon 模型池', }; } - if (/gemini/i.test(`${bId} ${bName} ${gName} ${gDesc}`)) { - return { - poolKey: 'Gemini', - poolLabel: 'Gemini', - poolName: 'Gemini 模型池', - }; - } - if (/3p|claude|fable|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) { + if ( + THIRD_PARTY_POOL_RE.test(primaryText) || + (!/gemini/i.test(primaryText) && THIRD_PARTY_POOL_RE.test(gDesc)) + ) { return { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', poolName: 'Claude & GPT 模型池', }; } + if (/gemini/i.test(`${primaryText} ${gDesc}`)) { + return { + poolKey: 'Gemini', + poolLabel: 'Gemini', + poolName: 'Gemini 模型池', + }; + } const cleanLabel = (gName || bId || 'Other').trim(); return { poolKey: cleanLabel, @@ -159,7 +172,7 @@ export function classifyQuotaPoolIdentity({ * @param {ReturnType} b * @returns {boolean} */ -export function quotaFractionsMatch(a, b) { +function quotaFractionsMatch(a, b) { if (!a || !b) return false; if (Math.abs(a.remainingFraction - b.remainingFraction) > 0.015) return false; if (a.resetTime && b.resetTime) { @@ -213,7 +226,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { for (const grp of rawGroups) { const grpBuckets = Array.isArray(grp?.buckets) ? grp.buckets : []; for (const b of grpBuckets) { - const norm = normalizeQuotaFraction(b); + const norm = normalizeQuotaFraction(b, nowForQuotaMs); if (!norm) continue; const ident = classifyQuotaPoolIdentity({ groupName: grp?.displayName, @@ -229,17 +242,27 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { window: win, }; const builder = ensurePoolBuilder(ident); - if (win === '5h' && !builder.bucket5h) { - builder.bucket5h = entry; - } else if (win === 'weekly' && !builder.bucketWeekly) { - builder.bucketWeekly = entry; - } else if (win !== '5h' && !builder.bucketWeekly) { + if (win === '5h') { + if (!builder.bucket5h) { + builder.bucket5h = entry; + } else if (!builder.bucketWeekly) { + // 当同池两个无显式标签桶都处于 <6h 临近重置期时,按重置时间早晚区分 5h 与周限桶 + const prevResetMs = parseIsoMs(builder.bucket5h.resetTime); + const nextResetMs = parseIsoMs(entry.resetTime); + if (prevResetMs > 0 && nextResetMs > 0 && nextResetMs < prevResetMs) { + builder.bucketWeekly = { ...builder.bucket5h, window: 'weekly' }; + builder.bucket5h = entry; + } else { + builder.bucketWeekly = { ...entry, window: 'weekly' }; + } + } + } else if (!builder.bucketWeekly) { builder.bucketWeekly = entry; } } } - // 注册动态模型字典,并采样 Carbon / Argon 与标准 Gemini 的单模型 quotaInfo + // 注册动态模型字典(不把占位符 rawKey 污染进 modelId),并采样 Carbon / Argon 与标准 Gemini 的单模型 quotaInfo let sampleCarbonCfgQuota = null; let sampleArgonCfgQuota = null; let sampleStdGeminiCfgQuota = null; @@ -248,13 +271,13 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { const rawKey = cfg?.modelOrAlias?.model; if (rawKey) { dynamicModelMap.set(rawKey, { - modelId: cfg.modelId || rawKey, + modelId: cfg.modelId || '', label: cfg.label || cfg.modelId || rawKey, quotaInfo: cfg.quotaInfo || null, }); } const info = resolveModelInfo(rawKey, dynamicModelMap); - const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo); + const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs); if (!cfgQuota || info.family !== 'Gemini') continue; if (isCarbonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) { if (!sampleCarbonCfgQuota) sampleCarbonCfgQuota = cfgQuota; @@ -348,7 +371,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { builder.models.push(cfg.label); } - const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo); + const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs); if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) { if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') { builder.bucketWeekly = cfgQuota; @@ -362,7 +385,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { const hasValid5h = Boolean(eff5h); modelQuotas.push({ label: cfg.label, - modelId: cfg.modelId, + modelId: cfg.modelId || info.modelId, rawKey, family: targetIdent.poolKey, isAvailable: Boolean(eff5h || effWk || cfgQuota), diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index ad1eb83..1704e02 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -1,16 +1,14 @@ /** * @fileoverview 遥测载荷组装器与并发请求合并入口。 * - * 将原来超过 1,000 行的 `buildTelemetryPayloadInternal` 拆解为清晰的子阶段: - * 1. 拉取用户状态、轨迹摘要与官方实时配额摘要(含账号切换自动穿透缓存); + * 将遥测构建拆解为清晰的子阶段: + * 1. 拉取用户状态、轨迹摘要与官方实时配额摘要(含账号切换缓存校验); * 2. 调用 `buildOfficialQuotaPools` 构建动态模型映射与多模型配额池; * 3. 调用 `enumerateAndSyncConversations` 枚举会话并增量更新轨迹缓存; - * 4. 调用 `enrichActiveConversationSteps` 与 `extractActiveContextTelemetry` 计算当前活跃会话指标与上下文拆解; - * 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装最终前端遥测 JSON。 + * 4. 调用 `enrichActiveConversationSteps` 与 `extractActiveContextTelemetry` 计算当前活跃会话指标与 10 通道上下文拆解; + * 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装精简的前端遥测 JSON。 */ -import { statSync } from 'node:fs'; -import { join } from 'node:path'; import { extractLiveActivity, parseIsoMs, @@ -19,7 +17,7 @@ import { summarizeTtft, } from '../speed-metrics.mjs'; import { - HERE, + computeRuntimeCodeVersion, inFlightRequests, loadSettings, quotaSummaryCache, @@ -27,7 +25,7 @@ import { trajectoryCache, } from './config.mjs'; import { enumerateAndSyncConversations } from './local-scanner.mjs'; -import { callLsRpc, diagnostics, getOfficialQuotaSummary } from './ls-rpc.mjs'; +import { callLsRpc, getOfficialQuotaSummary } from './ls-rpc.mjs'; import { computeStepCost, isArgonModelIdentifier, @@ -43,6 +41,22 @@ import { } from './usage-aggregator.mjs'; const MAX_RECENT_CONVERSATIONS = 30; +const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; + +function roundSessionCost(val) { + if (!Number.isFinite(val) || val <= 0) return 0; + return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2); +} + +function findTrajectoryCacheEntry(cascadeId) { + if (!cascadeId) return null; + if (trajectoryCache[cascadeId]) return trajectoryCache[cascadeId]; + const targetLower = String(cascadeId).toLowerCase(); + for (const [k, v] of Object.entries(trajectoryCache)) { + if (k.toLowerCase() === targetLower) return v; + } + return null; +} /** * 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。 @@ -62,15 +76,16 @@ function buildKnownUpstreamModelMap() { } /** - * 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标。 + * 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标, + * 并剔除前端未使用的冗余诊断字段以减小 JSON 体积。 * * @param {object[]} activeSteps 当前会话的原始缓存步骤 - * @param {Map} dynamicModelMap 动态模型字典 + * @param {Map} [dynamicModelMap=new Map()] 动态模型字典 * @param {Map} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表 */ -export function enrichActiveConversationSteps( +function enrichActiveConversationSteps( activeSteps, - dynamicModelMap, + dynamicModelMap = new Map(), sharedUpstreamMap = null ) { const sessionSpeed = summarizeSpeed(activeSteps); @@ -80,7 +95,6 @@ export function enrichActiveConversationSteps( let sessionInputTokens = 0; let sessionCacheReadTokens = 0; - // 记录已知的 modelKey -> 最近观测到的上游 responseModel,避免正在生成的步骤因尚未收到 generatorMetadata 而闪烁 const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap(); for (const s of activeSteps) { if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) { @@ -123,8 +137,15 @@ export function enrichActiveConversationSteps( (mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName); const modelUpstream = st.isCompactionStep ? `${rawUpstreamModel}·压缩` : rawUpstreamModel; + const { + viewableDelaySec: _viewableDelaySec, + ttftSource: _ttftSource, + speedBasis: _speedBasis, + ...serializedStep + } = st; + return { - ...st, + ...serializedStep, responseModel: st.responseModel || '', modelUpstream, modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label, @@ -160,22 +181,25 @@ export function enrichActiveConversationSteps( } /** - * 从当前活跃会话的最新步骤提取上下文 6 维拆解、自动压缩水位与缓存命中率。 + * 从当前活跃会话的最新步骤提取上下文 10 通道拆解、自动压缩水位与缓存命中率。 * * @param {object[]} enrichedActiveSteps * @param {object|null} latestEnriched * @param {number} sessionInputTokens * @param {number} sessionCacheReadTokens */ -export function extractActiveContextTelemetry( +function extractActiveContextTelemetry( enrichedActiveSteps, latestEnriched, sessionInputTokens, sessionCacheReadTokens ) { let latestBreakdown = latestEnriched?.contextBreakdown || null; - if (!latestBreakdown) { + if (!latestBreakdown && !latestEnriched?.isCompactionStep) { for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { + if (enrichedActiveSteps[i]?.isCompactionStep) { + break; + } if (enrichedActiveSteps[i]?.contextBreakdown) { latestBreakdown = enrichedActiveSteps[i].contextBreakdown; break; @@ -221,10 +245,10 @@ export function extractActiveContextTelemetry( const latestPromptTokens = ctxCached + ctxFreshInput; const latestCacheHitPct = - latestPromptTokens > 0 ? Math.round((ctxCached / latestPromptTokens) * 100) : 0; + latestPromptTokens > 0 ? +((ctxCached / latestPromptTokens) * 100).toFixed(1) : 0; const sessionPromptTokens = sessionCacheReadTokens + sessionInputTokens; const sessionCacheHitPct = - sessionPromptTokens > 0 ? Math.round((sessionCacheReadTokens / sessionPromptTokens) * 100) : 0; + sessionPromptTokens > 0 ? +((sessionCacheReadTokens / sessionPromptTokens) * 100).toFixed(1) : 0; return { latestCacheHitPct, @@ -256,7 +280,7 @@ export function extractActiveContextTelemetry( } /** - * 构建单个代理(主代理或子代理)的标准遥测单元对象,消除主/子代理 25 字段重复组装。 + * 构建单个代理(主代理或子代理)的标准遥测单元对象。 */ function buildAgentUnitTelemetry({ agentId, @@ -330,12 +354,16 @@ function buildAgentUnitTelemetry({ speedSummary: enrichedRes.sessionSpeed, ttftSummary: enrichedRes.sessionTtft, latestStepCostUsd: enrichedRes.latestEnriched?.costUsd ?? null, - sessionCostUsd: +enrichedRes.sessionCostUsd.toFixed(2), + sessionCostUsd: roundSessionCost(enrichedRes.sessionCostUsd), sessionUnpricedCalls: enrichedRes.sessionUnpricedCalls, latestCacheHitPct: ctxRes.latestCacheHitPct, sessionCacheHitPct: ctxRes.sessionCacheHitPct, activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知', activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知', + activeModelUpstream: + enrichedRes.latestEnriched?.modelUpstream || + enrichedRes.latestEnriched?.modelShort || + '模型未知', context: ctxRes.context, ...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}), modelBreakdown, @@ -348,7 +376,7 @@ function buildAgentUnitTelemetry({ * 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。 * * @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话) - * @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额 10 秒缓存 + * @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避 * @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项 * @returns {Promise} */ @@ -368,17 +396,24 @@ export async function buildTelemetryPayloadInternal( const currentAccountName = userStatus?.email || userStatus?.name || ''; let officialQuotaInfo = initialOfficialQuotaInfo; - // 若检测到登录账号在 10 秒缓存期内发生切换,先清空旧账号配额缓存再立即强制刷新,防止刷新失败时串号 + // 若检测到账号发生切换:仅当并发的 initialOfficialQuotaInfo 命中了旧账号本地缓存 (fromCache === true) 时才需清空并重刷; + // 若本轮已经实时穿透请求了上游 RPC (fromCache === false),直接更新归属账号即可,避免二次重复 RPC const accountChanged = Boolean( currentAccountName && quotaSummaryCache.accountName && quotaSummaryCache.accountName !== currentAccountName ); if (accountChanged) { - quotaSummaryCache.data = null; - quotaSummaryCache.ts = 0; - quotaSummaryCache.accountName = currentAccountName; - officialQuotaInfo = await getOfficialQuotaSummary(true); + if (initialOfficialQuotaInfo?.fromCache) { + quotaSummaryCache.data = null; + quotaSummaryCache.ts = 0; + quotaSummaryCache.lastAttemptTs = 0; + quotaSummaryCache.error = null; + quotaSummaryCache.accountName = currentAccountName; + officialQuotaInfo = await getOfficialQuotaSummary(true); + } else { + quotaSummaryCache.accountName = currentAccountName; + } } else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) { quotaSummaryCache.accountName = currentAccountName; } @@ -387,7 +422,7 @@ export async function buildTelemetryPayloadInternal( const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || []; // 1. 构建官方实时配额池与动态模型目录 - const { dynamicModelMap, quotaPoolsMap, modelQuotas } = buildOfficialQuotaPools( + const { dynamicModelMap, quotaPoolsMap } = buildOfficialQuotaPools( officialQuota, clientConfigs ); @@ -398,11 +433,12 @@ export async function buildTelemetryPayloadInternal( summariesObj: allTrajRes?.trajectorySummaries || {}, currentAccountName, requestedConvId, + forceRefresh: forceQuotaRefresh, }); - // 3. 计算当前活跃根会话及其子代理的步骤指标、6 通道上下文拆解与按模型汇总 + // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 const knownUpstreamByModelKey = buildKnownUpstreamModelMap(); - const activeEntry = activeCascadeId ? trajectoryCache[activeCascadeId] : null; + const activeEntry = findTrajectoryCacheEntry(activeCascadeId); const activeSteps = activeEntry?.steps || []; const mainUnit = buildAgentUnitTelemetry({ agentId: 'main', @@ -420,7 +456,6 @@ export async function buildTelemetryPayloadInternal( fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0, dynamicModelMap, knownUpstreamByModelKey, - // 主代理步骤通过 activeConversation.recentSteps 下发一次,避免 JSON 重复序列化 includeRecentSteps: false, }); @@ -452,7 +487,7 @@ export async function buildTelemetryPayloadInternal( const subSum = subagentSummaries[idx]; const subCid = subSum.cascadeId; activeFamilyCascadeIds.add(String(subCid || '').toLowerCase()); - const subEntry = trajectoryCache[subCid] || null; + const subEntry = findTrajectoryCacheEntry(subCid); const subRawSteps = subEntry?.steps || []; allCombinedRawSteps.push(...subRawSteps); @@ -520,7 +555,6 @@ export async function buildTelemetryPayloadInternal( .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || mainAgentTelemetry; - // 若刚启动的子代理尚无已完成步骤 (stepCount === 0),实时速率与上下文回退取最近有步骤的代理,避免闪现空白 const agentsWithSteps = allAgents.filter((a) => a.stepCount > 0); const latestMetricAgent = latestActiveAgent.stepCount > 0 @@ -531,7 +565,7 @@ export async function buildTelemetryPayloadInternal( .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || latestActiveAgent; - const totalCostUsd = +totalRawSessionCostUsd.toFixed(2); + const totalCostUsd = roundSessionCost(totalRawSessionCostUsd); const totalUnpricedCalls = allAgents.reduce( (sum, a) => sum + (a.sessionUnpricedCalls || 0), 0 @@ -539,7 +573,7 @@ export async function buildTelemetryPayloadInternal( const totalFamilyPromptTokens = totalFamilyInputTokens + totalFamilyCacheReadTokens; const combinedSessionCacheHitPct = totalFamilyPromptTokens > 0 - ? Math.round((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100) + ? +((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100).toFixed(1) : 0; const runningSubs = subAgentTelemetries.filter((a) => a.isRunning); @@ -591,18 +625,22 @@ export async function buildTelemetryPayloadInternal( sessionCacheHitPct: combinedSessionCacheHitPct, activeModelShort: latestMetricAgent.activeModelShort, activeModelLabel: latestMetricAgent.activeModelLabel, + activeModelUpstream: latestMetricAgent.activeModelUpstream, context: latestMetricAgent.context, modelBreakdown: combinedModelBreakdown, lastModifiedMs: latestActiveAgent.lastModifiedMs, }; } - // 4. 识别当前活跃会话家族绑定的模型池及其官方 5h / 周限重置锚点 + // 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT) const latestFamilyStep = allCombinedEnrichedSteps.length > 0 ? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1] : latestEnriched; - const latestIsCarbon = latestFamilyStep + const hasResolvedStepModel = Boolean( + latestFamilyStep && latestFamilyStep.modelKey && latestFamilyStep.modelKey !== 'unknown' + ); + const latestIsCarbon = hasResolvedStepModel ? isCarbonModelIdentifier( latestFamilyStep.modelKey, latestFamilyStep.responseModel, @@ -610,7 +648,7 @@ export async function buildTelemetryPayloadInternal( latestFamilyStep.modelLabel ) : false; - const latestIsArgon = latestFamilyStep + const latestIsArgon = hasResolvedStepModel ? isArgonModelIdentifier( latestFamilyStep.modelKey, latestFamilyStep.responseModel, @@ -619,14 +657,15 @@ export async function buildTelemetryPayloadInternal( ) : false; const rawActiveFamily = latestFamilyStep?.family || 'Other'; - const activePoolKey = - latestIsCarbon && quotaPoolsMap.has('Carbon') + const activePoolKey = !hasResolvedStepModel + ? 'Unknown' + : latestIsCarbon && quotaPoolsMap.has('Carbon') ? 'Carbon' : latestIsArgon && quotaPoolsMap.has('Argon') ? 'Argon' : rawActiveFamily === 'Gemini' ? 'Gemini' - : ['Claude', 'GPT'].includes(rawActiveFamily) + : ['Claude', 'GPT', 'Other'].includes(rawActiveFamily) ? 'Claude & GPT' : 'Unknown'; const matchedActivePool = quotaPoolsMap.get(activePoolKey) || null; @@ -646,12 +685,27 @@ export async function buildTelemetryPayloadInternal( resetTime: matchedActivePool.weeklyResetTime, } : null; + + // 全局账号周期锚点采用稳定的配额池优先级(Gemini -> Argon -> Carbon -> Claude & GPT), + // 防止切换不同会话时全局消费统计(consumption.presets.week / 5h)因重置时间偏移而突变 + let accountFiveHourResetMs = 0; + let accountWeeklyResetMs = 0; + for (const pk of POOL_PRIORITY_ORDER) { + const pool = quotaPoolsMap.get(pk); + if (!pool) continue; + if (!accountFiveHourResetMs && pool.resetTime) { + accountFiveHourResetMs = parseIsoMs(pool.resetTime); + } + if (!accountWeeklyResetMs && pool.weeklyResetTime) { + accountWeeklyResetMs = parseIsoMs(pool.weeklyResetTime); + } + } const cycleAnchors = { - fiveHourResetMs: parseIsoMs(activeLive5h?.resetTime), - weeklyResetMs: parseIsoMs(activeLiveWeekly?.resetTime), + fiveHourResetMs: accountFiveHourResetMs || parseIsoMs(activeLive5h?.resetTime), + weeklyResetMs: accountWeeklyResetMs || parseIsoMs(activeLiveWeekly?.resetTime), }; - // 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 12 段趋势 + 月序列 + 来源与模型拆解) + // 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解) const { selectedWindow, trendStartMs, @@ -663,7 +717,6 @@ export async function buildTelemetryPayloadInternal( sourcesBreakdown, currentYear, monthlySeries, - todayBucket, weekBucket, modelBreakdown, } = aggregateMultiWindowUsage({ @@ -707,7 +760,7 @@ export async function buildTelemetryPayloadInternal( }; const fallbackWeeklyPct = - settings.weeklyLimitMode === 'custom_cost' || settings.weeklyLimitMode === 'cost' + settings.weeklyLimitMode === 'custom_cost' ? weekBucket.unpricedCalls > 0 ? null : Math.min( @@ -739,18 +792,132 @@ export async function buildTelemetryPayloadInternal( ? Math.max(0, Math.floor(100 - fallbackWeeklyPct)) : null; - // 提取真实的 Google One AI Credits(忽略旧版硬编码的 500 prompt credits) const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find( (c) => c?.creditType === 'GOOGLE_ONE_AI' ); const realAiCredits = Number(g1CreditEntry?.creditAmount || 0); + const uiBundleVersion = computeRuntimeCodeVersion(); - let uiBundleVersion = 0; - try { - uiBundleVersion = statSync(join(HERE, 'app.js')).mtimeMs || 0; - } catch { - // 忽略 stat 异常 - } + const rawTierName = userStatus?.userTier?.name || ''; + const inferredPlanFallback = /\bfree\b/i.test(rawTierName) + ? 'Free' + : /\bultra\b/i.test(rawTierName) + ? 'Ultra' + : 'Pro'; + const resolvedPlanName = userStatus?.planStatus?.planInfo?.planName || inferredPlanFallback; + + // 预计算近期会话与运行中会话的轻量缓存速览指标(零额外 RPC 开销) + const quickStatsMemo = new Map(); + const getConversationQuickStats = (rootConv) => { + const cidKey = String(rootConv?.cascadeId || '').toLowerCase(); + if (cidKey && quickStatsMemo.has(cidKey)) { + return quickStatsMemo.get(cidKey); + } + const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId); + const rootSteps = rootEntry?.steps || []; + const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : []; + + let totalCost = 0; + let unpricedCalls = 0; + const accumulateStepsCost = (steps) => { + for (const st of steps) { + const mInfo = resolveModelInfo( + st.modelKey, + dynamicModelMap, + st.apiProvider, + st.modelDisplayName, + st.responseModel + ); + const c = computeStepCost(st, mInfo.pricing); + if (c === null) unpricedCalls += 1; + else totalCost += c; + } + }; + accumulateStepsCost(rootSteps); + + const lastRootStep = rootSteps.length > 0 ? rootSteps[rootSteps.length - 1] : null; + let bestMetricStep = lastRootStep; + let bestMetricRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING' && Boolean(lastRootStep); + + for (const subSum of rawSubs) { + const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId); + const subSteps = subEntry?.steps || []; + if (subSteps.length === 0) continue; + accumulateStepsCost(subSteps); + const lastSub = subSteps[subSteps.length - 1]; + const subRunning = subSum?.status === 'CASCADE_RUN_STATUS_RUNNING'; + if ( + !bestMetricStep || + (subRunning && !bestMetricRunning) || + (subRunning === bestMetricRunning && + (lastSub.createdAtMs || 0) >= (bestMetricStep.createdAtMs || 0)) + ) { + bestMetricStep = lastSub; + bestMetricRunning = subRunning; + } + } + + let contextUsedPct = null; + if (lastRootStep) { + const limitTokens = Number(lastRootStep.maxContextBudgetTokens || 256000); + const cb = lastRootStep.contextBreakdown; + const cbTotal = cb + ? Number(cb.messagesTokens || 0) + + Number(cb.systemToolsTokens || 0) + + Number(cb.mcpToolsTokens || 0) + + Number(cb.skillsTokens || 0) + + Number(cb.systemPromptTokens || 0) + + Number(cb.userRulesTokens || 0) + : 0; + const fallbackTotal = + Number(lastRootStep.inputTokens || 0) + + Number(lastRootStep.cacheReadTokens || 0) + + Number(lastRootStep.thinkingTokens || 0) + + Number(lastRootStep.responseTokens || 0); + const usedTokens = Number( + cbTotal > 0 ? cbTotal : lastRootStep.estimatedContextTokens || fallbackTotal + ); + contextUsedPct = + limitTokens > 0 ? Math.min(100, +((usedTokens / limitTokens) * 100).toFixed(1)) : 0; + } + + let modelShort = ''; + let modelUpstream = ''; + let latestTokPerSec = null; + if (bestMetricStep) { + const mInfo = resolveModelInfo( + bestMetricStep.modelKey, + dynamicModelMap, + bestMetricStep.apiProvider, + bestMetricStep.modelDisplayName, + bestMetricStep.responseModel + ); + const resolvedResp = + bestMetricStep.responseModel || + (bestMetricStep.modelKey && bestMetricStep.modelKey !== 'unknown' + ? knownUpstreamByModelKey.get(bestMetricStep.modelKey) || '' + : ''); + modelShort = mInfo.shortName || ''; + modelUpstream = + resolvedResp || + (mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName) || + ''; + latestTokPerSec = roundMetric(speedMetric(bestMetricStep).value); + } + + const stats = { + modelShort, + modelUpstream, + latestTokPerSec, + contextUsedPct, + sessionCostUsd: roundSessionCost(totalCost), + sessionUnpricedCalls: unpricedCalls, + }; + if (cidKey) { + quickStatsMemo.set(cidKey, stats); + } + return stats; + }; // 7. 构建所有正在运行的主进程(根会话)及其子代理缩略状态列表 const runningConversations = []; @@ -762,13 +929,13 @@ export async function buildTelemetryPayloadInternal( continue; } - const rootEntry = trajectoryCache[rootConv.cascadeId] || null; + const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId); const rootFallbackMs = rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0; const subItems = rawSubs.map((subSum, idx) => { const subCid = subSum.cascadeId; - const subEntry = trajectoryCache[subCid] || null; + const subEntry = findTrajectoryCacheEntry(subCid); const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; const rawRole = subSpec?.role || @@ -812,7 +979,6 @@ export async function buildTelemetryPayloadInternal( ? rootConv.liveActivity || extractLiveActivity([], true, rootFallbackMs) : null; - // 若主代理正在调用 invoke_subagent 但新子代理轨迹尚未出现在 rawSubs 中,生成临时子代理占位项 const runningSubCount = subItems.filter((s) => s.isRunning).length; if ( isMainRunning && @@ -857,6 +1023,7 @@ export async function buildTelemetryPayloadInternal( } : extractLiveActivity([], true, rootFallbackMs)); + const qStats = getConversationQuickStats(rootConv); runningConversations.push({ cascadeId: rootConv.cascadeId, title: rootConv.title || rootConv.cascadeId.slice(0, 8), @@ -873,6 +1040,12 @@ export async function buildTelemetryPayloadInternal( subagentCount: subItems.length, runningSubagentCount: runningSubList.length, subagents: subItems, + modelShort: qStats.modelShort, + modelUpstream: qStats.modelUpstream, + latestTokPerSec: qStats.latestTokPerSec, + contextUsedPct: qStats.contextUsedPct, + sessionCostUsd: qStats.sessionCostUsd, + sessionUnpricedCalls: qStats.sessionUnpricedCalls, }); } @@ -881,25 +1054,37 @@ export async function buildTelemetryPayloadInternal( uiBundleVersion, settings, cloudStatus: getCloudStatus(), - diagnostics: diagnostics.status(), account: { name: userStatus?.name || '', - tierName: userStatus?.userTier?.name || 'Google AI', - planName: userStatus?.planStatus?.planInfo?.planName || 'Pro', + tierName: rawTierName || 'Google AI', + planName: resolvedPlanName, aiCredits: realAiCredits > 0 ? realAiCredits : null, totalConversations: conversations.length, }, runningConversations, - conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => ({ - cascadeId: c.cascadeId, - title: c.title, - stepCount: c.stepCount, - subagentCount: c.subagentCount || 0, - totalStepCount: c.totalStepCount || c.stepCount || 0, - status: c.status, - lastModifiedTime: c.lastModifiedTime, - lastModifiedMs: c.lastModifiedMs, - })), + conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => { + const qStats = getConversationQuickStats(c); + const rawSubs = Array.isArray(c.subagents) ? c.subagents : []; + const runningSubCount = rawSubs.filter((s) => s.status === 'CASCADE_RUN_STATUS_RUNNING').length; + return { + cascadeId: c.cascadeId, + title: c.title, + stepCount: c.stepCount, + subagentCount: c.subagentCount || 0, + runningSubagentCount: runningSubCount, + totalStepCount: c.totalStepCount || c.stepCount || 0, + isRunning: c.status === 'CASCADE_RUN_STATUS_RUNNING' || runningSubCount > 0, + status: c.status, + lastModifiedTime: c.lastModifiedTime, + lastModifiedMs: c.groupLastModifiedMs || c.lastModifiedMs, + modelShort: qStats.modelShort, + modelUpstream: qStats.modelUpstream, + latestTokPerSec: qStats.latestTokPerSec, + contextUsedPct: qStats.contextUsedPct, + sessionCostUsd: qStats.sessionCostUsd, + sessionUnpricedCalls: qStats.sessionUnpricedCalls, + }; + }), activeConversation: { cascadeId: activeCascadeId, title: activeConvSummary?.title || '当前会话', @@ -917,12 +1102,14 @@ export async function buildTelemetryPayloadInternal( speedSummary: sessionSpeed, ttftSummary: sessionTtft, latestStepCostUsd: latestEnriched?.costUsd ?? null, - sessionCostUsd: +sessionCostUsd.toFixed(2), + sessionCostUsd: roundSessionCost(sessionCostUsd), sessionUnpricedCalls, latestCacheHitPct, sessionCacheHitPct, activeModelShort: latestEnriched?.modelShort || '模型未知', activeModelLabel: latestEnriched?.modelLabel || '模型未知', + activeModelUpstream: + latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知', context, recentSteps: enrichedActiveSteps.slice().reverse(), modelBreakdown: mainModelBreakdown, @@ -937,9 +1124,7 @@ export async function buildTelemetryPayloadInternal( endMs: trendEndMs, }, session: finalizedSelectedSession, - sessionAllTime: finalizedPresets.all.session, account: finalizedSelectedAccount, - accountAllTime: finalizedPresets.all.account, presets: finalizedPresets, trendSeries, sourcesBreakdown, @@ -960,7 +1145,6 @@ export async function buildTelemetryPayloadInternal( const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; return (order[a.family] ?? 99) - (order[b.family] ?? 99); }), - models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))), weekly: { isOfficial: useOfficialWeekly, poolFamily: activePoolKey, @@ -980,12 +1164,6 @@ export async function buildTelemetryPayloadInternal( ? getNextMondayResetIso() : null, }, - today: { - calls: todayBucket.calls, - tokens: todayBucket.totalTokens, - costUsd: todayBucket.costUsd, - unpricedCalls: todayBucket.unpricedCalls, - }, }, modelBreakdown, }; @@ -993,7 +1171,6 @@ export async function buildTelemetryPayloadInternal( /** * 带并发请求合并(In-Flight Deduplication)的遥测载荷构建入口。 - * 当相同会话、刷新模式与时间范围的请求正在处理中时,直接复用同一个 Promise。 * * @param {string} requestedConvId * @param {boolean} [forceQuotaRefresh=false] diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index e91bdc0..d61f252 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -1,9 +1,9 @@ /** - * @fileoverview 多时间窗口解析、用量桶累加、12 段趋势序列、月度序列与分模型/分来源聚合引擎。 + * @fileoverview 多时间窗口解析、用量桶累加、趋势序列、月度序列与分模型/分来源聚合引擎。 * * 负责将内存缓存 (`trajectoryCache`) 与外部深层统计缓存 (`loadExternalDeepStatsCache`) * 中的所有步骤按预设窗口(`all`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口 - * 进行一次遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。 + * 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。 */ import { @@ -15,18 +15,30 @@ import { roundMetric, trajectoryCache } from './config.mjs'; import { loadExternalDeepStatsCache } from './local-scanner.mjs'; import { computeStepCost, resolveModelInfo } from './model-pricing.mjs'; +function safeTok(val) { + const n = Number(val); + return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0; +} + /** * 获取本地当日 00:00:00.000 的毫秒时间戳。 * * @param {Date|number} [now=new Date()] * @returns {number} */ -export function getStartOfLocalDayMs(now = new Date()) { +function getStartOfLocalDayMs(now = new Date()) { const d = new Date(now); d.setHours(0, 0, 0, 0); return d.getTime(); } +function getStartOfLocalOffsetDaysMs(nowMs, offsetDays) { + const d = new Date(nowMs); + d.setDate(d.getDate() - offsetDays); + d.setHours(0, 0, 0, 0); + return d.getTime(); +} + /** * 获取本地下一个周一 00:00:00.000 的 ISO 时间字符串(用于自定义本机周限额重置倒计时)。 * @@ -48,7 +60,7 @@ export function getNextMondayResetIso(now = new Date()) { * @param {Date|number} [now=new Date()] * @returns {number} */ -export function getStartOfCurrentWeekMs(now = new Date()) { +function getStartOfCurrentWeekMs(now = new Date()) { const d = new Date(now); const day = d.getDay(); // 0 = Sun, 1 = Mon const diffToMon = day === 0 ? -6 : 1 - day; @@ -67,7 +79,7 @@ export function getStartOfCurrentWeekMs(now = new Date()) { * @param {{ fiveHourResetMs?: number, weeklyResetMs?: number }} [cycleAnchors={}] * @returns {{ key: string, label: string, startMs: number, endMs: number }} */ -export function resolveTimeWindow( +function resolveTimeWindow( rangeKey = 'all', customStartMs = 0, customEndMs = 0, @@ -79,7 +91,9 @@ export function resolveTimeWindow( case '5h': { const reset5hMs = cycleAnchors.fiveHourResetMs || 0; const start5hMs = - reset5hMs > nowMs ? reset5hMs - 5 * 3600 * 1000 : nowMs - 5 * 3600 * 1000; + reset5hMs > nowMs + ? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000) + : nowMs - 5 * 3600 * 1000; return { key: '5h', label: reset5hMs > nowMs ? '当前 5h 周期' : '近 5 小时', @@ -94,7 +108,9 @@ export function resolveTimeWindow( case 'week': { const resetWkMs = cycleAnchors.weeklyResetMs || 0; const startWkMs = - resetWkMs > nowMs ? resetWkMs - 7 * 24 * 3600 * 1000 : getStartOfCurrentWeekMs(now); + resetWkMs > nowMs + ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) + : getStartOfCurrentWeekMs(now); return { key: 'week', label: resetWkMs > nowMs ? '当前周限周期' : '本周', @@ -103,19 +119,24 @@ export function resolveTimeWindow( }; } case '7d': - return { key: '7d', label: '近 7 天', startMs: nowMs - 7 * 24 * 3600 * 1000, endMs: nowMs }; + return { + key: '7d', + label: '近 7 天', + startMs: getStartOfLocalOffsetDaysMs(nowMs, 7), + endMs: nowMs, + }; case '14d': return { key: '14d', label: '近 14 天', - startMs: nowMs - 14 * 24 * 3600 * 1000, + startMs: getStartOfLocalOffsetDaysMs(nowMs, 14), endMs: nowMs, }; case '30d': return { key: '30d', label: '近 30 天', - startMs: nowMs - 30 * 24 * 3600 * 1000, + startMs: getStartOfLocalOffsetDaysMs(nowMs, 30), endMs: nowMs, }; case 'custom': { @@ -137,7 +158,7 @@ export function resolveTimeWindow( /** * 创建一个空的用量统计累加桶。 */ -export function createUsageBucket() { +function createUsageBucket() { return { calls: 0, conversationsSet: new Set(), @@ -149,12 +170,6 @@ export function createUsageBucket() { totalTokens: 0, costUsd: 0, savedCostUsd: 0, - geminiTokens: 0, - geminiCostUsd: 0, - geminiCalls: 0, - claudeGptTokens: 0, - claudeGptCostUsd: 0, - claudeGptCalls: 0, }; } @@ -167,33 +182,32 @@ export function createUsageBucket() { * @param {number|null} stepCost 单步美元成本(未知时为 `null`) * @param {string} cascadeId 会话标识 */ -export function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) { - const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; - const savedCost = mInfo.pricing - ? (st.cacheReadTokens / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) +function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) { + const inTok = safeTok(st?.inputTokens); + const cacheTok = safeTok(st?.cacheReadTokens); + const outTok = safeTok(st?.outputTokens); + const thinkTok = safeTok(st?.thinkingTokens); + const respTok = + st?.responseTokens !== undefined && st?.responseTokens !== null + ? safeTok(st.responseTokens) + : Math.max(0, outTok - thinkTok); + + const stepTotalTokens = inTok + cacheTok + outTok; + const savedCost = mInfo?.pricing + ? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) : 0; if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1; - const resolvedCost = stepCost ?? 0; + const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; bucket.calls += 1; if (cascadeId) bucket.conversationsSet.add(cascadeId); - bucket.inputTokens += st.inputTokens; - bucket.cacheReadTokens += st.cacheReadTokens; - bucket.outputTokens += st.outputTokens; - bucket.thinkingTokens += st.thinkingTokens || 0; - bucket.responseTokens += st.responseTokens || 0; + bucket.inputTokens += inTok; + bucket.cacheReadTokens += cacheTok; + bucket.outputTokens += outTok; + bucket.thinkingTokens += thinkTok; + bucket.responseTokens += respTok; bucket.totalTokens += stepTotalTokens; bucket.costUsd += resolvedCost; bucket.savedCostUsd += savedCost; - - if (mInfo.family === 'Gemini') { - bucket.geminiTokens += stepTotalTokens; - bucket.geminiCostUsd += resolvedCost; - bucket.geminiCalls += 1; - } else if (mInfo.family === 'Claude' || mInfo.family === 'GPT') { - bucket.claudeGptTokens += stepTotalTokens; - bucket.claudeGptCostUsd += resolvedCost; - bucket.claudeGptCalls += 1; - } } /** @@ -201,7 +215,7 @@ export function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) * * @param {ReturnType} bucket */ -export function finalizeUsageBucket(bucket) { +function finalizeUsageBucket(bucket) { const promptTokens = bucket.inputTokens + bucket.cacheReadTokens; const cacheHitPct = promptTokens > 0 ? +((bucket.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0; @@ -218,12 +232,6 @@ export function finalizeUsageBucket(bucket) { unpricedCalls: bucket.unpricedCalls || 0, savedCostUsd: +bucket.savedCostUsd.toFixed(2), cacheHitPct, - geminiTokens: bucket.geminiTokens, - geminiCostUsd: +bucket.geminiCostUsd.toFixed(2), - geminiCalls: bucket.geminiCalls, - claudeGptTokens: bucket.claudeGptTokens, - claudeGptCostUsd: +bucket.claudeGptCostUsd.toFixed(2), - claudeGptCalls: bucket.claudeGptCalls, }; } @@ -236,8 +244,15 @@ export function finalizeUsageBucket(bucket) { * @param {number|null} stepCost */ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) { - const stepTotalTokens = - (st.inputTokens || 0) + (st.cacheReadTokens || 0) + (st.outputTokens || 0); + const inTok = safeTok(st?.inputTokens); + const cacheTok = safeTok(st?.cacheReadTokens); + const outTok = safeTok(st?.outputTokens); + const thinkTok = safeTok(st?.thinkingTokens); + const respTok = + st?.responseTokens !== undefined && st?.responseTokens !== null + ? safeTok(st.responseTokens) + : Math.max(0, outTok - thinkTok); + const stepTotalTokens = inTok + cacheTok + outTok; const unpriced = stepCost === null ? 1 : 0; const modelGroupKey = mInfo.baseLabel || mInfo.label; @@ -269,13 +284,13 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) { accumulateSpeed(agg.speedAccumulator, st); agg.calls += 1; - agg.inputTokens += st.inputTokens || 0; - agg.cacheReadTokens += st.cacheReadTokens || 0; - agg.outputTokens += st.outputTokens || 0; - agg.thinkingTokens += st.thinkingTokens || 0; - agg.responseTokens += st.responseTokens || 0; + agg.inputTokens += inTok; + agg.cacheReadTokens += cacheTok; + agg.outputTokens += outTok; + agg.thinkingTokens += thinkTok; + agg.responseTokens += respTok; agg.totalTokens += stepTotalTokens; - agg.costUsd += stepCost ?? 0; + agg.costUsd += Number.isFinite(stepCost) ? stepCost : 0; agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced; } @@ -309,13 +324,14 @@ function finalizeModelBreakdownMap(perModelStats) { /** * 针对给定步骤数组构建按模型聚合的统计列表(供单代理、主+子汇总及全局时间范围复用)。 * - * @param {object[]} steps - * @param {Map} dynamicModelMap + * @param {object[]} [steps=[]] + * @param {Map} [dynamicModelMap=new Map()] * @returns {object[]} */ -export function buildScopedModelBreakdown(steps = [], dynamicModelMap) { +export function buildScopedModelBreakdown(steps = [], dynamicModelMap = new Map()) { const perModelStats = new Map(); for (const st of steps) { + if (!st || typeof st !== 'object') continue; const mInfo = resolveModelInfo( st.modelKey, dynamicModelMap, @@ -330,7 +346,7 @@ export function buildScopedModelBreakdown(steps = [], dynamicModelMap) { } /** - * 聚合所有预设时间窗口、当前选定窗口、12 段趋势图、年度月序列、来源占比与分模型统计。 + * 聚合所有预设时间窗口、当前选定窗口、趋势图、年度月序列、来源占比与分模型统计。 * * @param {{ * filterOpts?: { range?: string, startMs?: number, endMs?: number }, @@ -338,7 +354,7 @@ export function buildScopedModelBreakdown(steps = [], dynamicModelMap) { * currentAccountName?: string, * activeCascadeId?: string|null, * activeFamilyCascadeIds?: Set|null, - * dynamicModelMap: Map + * dynamicModelMap?: Map * }} params */ export function aggregateMultiWindowUsage({ @@ -347,8 +363,8 @@ export function aggregateMultiWindowUsage({ currentAccountName = '', activeCascadeId = null, activeFamilyCascadeIds = null, - dynamicModelMap, -}) { + dynamicModelMap = new Map(), +} = {}) { const rawFamilyIds = activeFamilyCascadeIds instanceof Set ? Array.from(activeFamilyCascadeIds) @@ -401,10 +417,41 @@ export function aggregateMultiWindowUsage({ }; const perSourceStats = new Map(); const externalConvos = loadExternalDeepStatsCache(); + + // 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费 + const allLiveByLower = new Map(); + for (const [rawId, entry] of Object.entries(trajectoryCache)) { + const cidLower = String(rawId || '').toLowerCase(); + if (!cidLower || !entry || typeof entry !== 'object') continue; + const prev = allLiveByLower.get(cidLower); + if (!prev || (entry.steps?.length || 0) > (prev.steps?.length || 0)) { + allLiveByLower.set(cidLower, entry); + } + } + + const externalByCid = new Map(); + for (const ext of externalConvos.values()) { + const extCidLower = String(ext?.cascadeId || '').toLowerCase(); + if (!extCidLower) continue; + const knownLive = allLiveByLower.get(extCidLower); + const ownerAccount = ext.accountName || knownLive?.accountName || ''; + if ( + ownerAccount && + currentAccountName && + ownerAccount !== currentAccountName && + !familySet.has(extCidLower) + ) { + continue; + } + const prevExt = externalByCid.get(extCidLower); + if (!prevExt || (ext.steps?.length || 0) > (prevExt.steps?.length || 0)) { + externalByCid.set(extCidLower, ext); + } + } + const allEntriesToAggregate = []; - for (const [cascadeId, entry] of Object.entries(trajectoryCache)) { - const cidLower = String(cascadeId || '').toLowerCase(); + for (const [cidLower, entry] of allLiveByLower.entries()) { if ( entry?.accountName && currentAccountName && @@ -413,12 +460,12 @@ export function aggregateMultiWindowUsage({ ) { continue; } - const extMatch = externalConvos.get(cascadeId) || externalConvos.get(cidLower); + const extMatch = externalByCid.get(cidLower); if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) { continue; } const groupCascadeId = String( - entry?.rootConversationId || entry?.parentConversationId || cascadeId + entry?.rootConversationId || entry?.parentConversationId || cidLower ).toLowerCase(); allEntriesToAggregate.push({ cascadeId: groupCascadeId, @@ -428,14 +475,13 @@ export function aggregateMultiWindowUsage({ }); } - for (const ext of externalConvos.values()) { - const extCidLower = String(ext.cascadeId || '').toLowerCase(); - const liveEntry = trajectoryCache[ext.cascadeId] || trajectoryCache[extCidLower]; + for (const [extCidLower, ext] of externalByCid.entries()) { + const liveEntry = allLiveByLower.get(extCidLower); if (liveEntry && (liveEntry.steps?.length || 0) >= (ext.steps?.length || 0)) { continue; } allEntriesToAggregate.push({ - cascadeId: `${ext.appSource}:${extCidLower}`, + cascadeId: extCidLower, appSource: ext.appSource || 'ide', steps: ext.steps || [], isCurrentConv: familySet.has(extCidLower), @@ -448,6 +494,7 @@ export function aggregateMultiWindowUsage({ const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; for (const st of entry.steps || []) { + if (!st || typeof st !== 'object') continue; const mInfo = resolveModelInfo( st.modelKey, dynamicModelMap, @@ -455,10 +502,19 @@ export function aggregateMultiWindowUsage({ st.modelDisplayName, st.responseModel ); - const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; + const inTok = safeTok(st.inputTokens); + const cacheTok = safeTok(st.cacheReadTokens); + const outTok = safeTok(st.outputTokens); + const thinkTok = safeTok(st.thinkingTokens); + const respTok = + st.responseTokens !== undefined && st.responseTokens !== null + ? safeTok(st.responseTokens) + : Math.max(0, outTok - thinkTok); + const stepTotalTokens = inTok + cacheTok + outTok; const stepCost = computeStepCost(st, mInfo.pricing); + const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const unpriced = stepCost === null ? 1 : 0; - const tMs = st.createdAtMs || 0; + const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0; if (tMs > 0) { const stepDate = new Date(tMs); @@ -466,12 +522,12 @@ export function aggregateMultiWindowUsage({ const mBucket = monthlySeries[stepDate.getMonth()]; if (mBucket) { mBucket.calls += 1; - mBucket.inputTokens += st.inputTokens || 0; - mBucket.cacheReadTokens += st.cacheReadTokens || 0; - mBucket.responseTokens += st.responseTokens || 0; - mBucket.thinkingTokens += st.thinkingTokens || 0; + mBucket.inputTokens += inTok; + mBucket.cacheReadTokens += cacheTok; + mBucket.responseTokens += respTok; + mBucket.thinkingTokens += thinkTok; mBucket.totalTokens += stepTotalTokens; - mBucket.costUsd = +(mBucket.costUsd + (stepCost ?? 0)).toFixed(4); + mBucket.costUsd += resolvedCost; mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; } } @@ -479,7 +535,7 @@ export function aggregateMultiWindowUsage({ for (const k of presetKeys) { const w = presetWindows[k]; - if (k === 'all' || (tMs >= w.startMs && tMs <= w.endMs)) { + if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) { accumulateStepIntoBucket(accountBuckets[k], st, mInfo, stepCost, cascadeId); if (isCurrentConv) { accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId); @@ -489,7 +545,7 @@ export function aggregateMultiWindowUsage({ const inSelectedWindow = selectedWindow.key === 'all' || - (tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs); + (tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs); if (inSelectedWindow) { accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId); @@ -501,11 +557,10 @@ export function aggregateMultiWindowUsage({ selectedWindowSteps.push({ tMs, tokens: stepTotalTokens, - inputTokens: st.inputTokens || 0, - cacheReadTokens: st.cacheReadTokens || 0, - outputTokens: - (st.responseTokens || 0) + (st.thinkingTokens || 0) || st.outputTokens || 0, - costUsd: stepCost ?? 0, + inputTokens: inTok, + cacheReadTokens: cacheTok, + outputTokens: outTok, + costUsd: resolvedCost, unpricedCalls: unpriced, }); } @@ -524,12 +579,12 @@ export function aggregateMultiWindowUsage({ } const sAgg = perSourceStats.get(srcKey); sAgg.calls += 1; - sAgg.inputTokens += st.inputTokens || 0; - sAgg.cacheReadTokens += st.cacheReadTokens || 0; - sAgg.responseTokens += st.responseTokens || 0; - sAgg.thinkingTokens += st.thinkingTokens || 0; + sAgg.inputTokens += inTok; + sAgg.cacheReadTokens += cacheTok; + sAgg.responseTokens += respTok; + sAgg.thinkingTokens += thinkTok; sAgg.totalTokens += stepTotalTokens; - sAgg.costUsd += stepCost ?? 0; + sAgg.costUsd += resolvedCost; sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced; accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost); @@ -537,6 +592,10 @@ export function aggregateMultiWindowUsage({ } } + for (const mBucket of monthlySeries) { + mBucket.costUsd = +mBucket.costUsd.toFixed(4); + } + // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) const MAX_SAFE_MS = 8_640_000_000_000_000; const safeMs = (val, fallback) => @@ -717,10 +776,13 @@ export function aggregateMultiWindowUsage({ bucket.inputTokens += item.inputTokens || 0; bucket.cacheReadTokens += item.cacheReadTokens || 0; bucket.outputTokens += item.outputTokens || 0; - bucket.costUsd = +(bucket.costUsd + item.costUsd).toFixed(4); + bucket.costUsd += item.costUsd; bucket.unpricedCalls = (bucket.unpricedCalls || 0) + item.unpricedCalls; bucket.calls += 1; } + for (const b of trendSeries) { + b.costUsd = +b.costUsd.toFixed(4); + } } const finalizedPresets = {}; diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs new file mode 100644 index 0000000..dd56152 --- /dev/null +++ b/sidecars/panel/backend/window-bridge.mjs @@ -0,0 +1,826 @@ +/** + * @fileoverview 双栖模式(Window Overlay)本地回环桥接服务与 CDP 多窗口自动挂载调度器。 + * + * 职责边界: + * 1. 在 Sidecar 进程内维护仅绑定 `127.0.0.1` 随机端口的受保护 HTTP 桥接端点, + * 通过一次性 256-bit 随机令牌 (`X-Usage-Monitor-Token`)、严格 `Origin` 校验与 Private Network CORS 头, + * 为主窗口 Shadow DOM 内的悬浮面板提供与辅助栏完全一致的 `/api/*` 遥测与控制接口; + * 2. 周期性探测本机 `Antigravity/DevToolsActivePort`,发现所有打开的主聊天窗口(支持多窗口并存), + * 按需将最新的 `styles.css` 与 `app.js` 热挂载至窗口顶栏,并在用户关闭双栖开关时立即清理卸载; + * 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。 + */ + +import { existsSync, readFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { + DATA_DIR, + computeRuntimeCodeVersion, + loadJson, + loadSettings, + saveJson, +} from './config.mjs'; + +const BRIDGE_MAX_BODY_BYTES = 64 * 1024; +const ALLOWED_BRIDGE_PATHS = new Set([ + '/api/telemetry', + '/api/settings', + '/api/cloud-sync', + '/api/plugin-update', +]); + +/** + * 解析各操作系统下 Antigravity 写入 `DevToolsActivePort` 的候选路径列表。 + * + * @param {Record} [env=process.env] + * @param {string} [platform=process.platform] + * @param {string} [homeDir=homedir()] + * @returns {string[]} + */ +export function resolveDevToolsPortCandidates( + env = process.env, + platform = process.platform, + homeDir = homedir() +) { + const explicitFile = String(env?.ANTIGRAVITY_DEVTOOLS_PORT_FILE || '').trim(); + if (explicitFile) { + return [explicitFile]; + } + if (platform === 'win32') { + const appData = env?.APPDATA || join(homeDir, 'AppData', 'Roaming'); + const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'); + return [ + join(appData, 'Antigravity', 'DevToolsActivePort'), + join(localAppData, 'Antigravity', 'DevToolsActivePort'), + ]; + } + if (platform === 'darwin') { + return [join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort')]; + } + const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config'); + return [join(configHome, 'Antigravity', 'DevToolsActivePort')]; +} + +/** + * 从 `DevToolsActivePort` 文件文本首行提取合法的本地调试端口号。 + * + * @param {string} rawText + * @returns {number|null} + */ +export function parseDevToolsPortFile(rawText) { + if (typeof rawText !== 'string' || !rawText) return null; + const firstLine = rawText.split(/\r?\n/)[0]?.trim() || ''; + if (!/^\d+$/.test(firstLine)) return null; + const port = Number(firstLine); + return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null; +} + +/** + * 判断 CDP `/json/list` 返回的目标是否为 Antigravity 主聊天窗口页面, + * 严格排除 `vscode-webview://` 子视图、DevTools 面板与非本机回环地址。 + * + * @param {object} target + * @returns {boolean} + */ +export function isAntigravityMainPageTarget(target) { + if (!target || typeof target !== 'object') return false; + if (target.type !== 'page') return false; + const url = String(target.url || '').trim(); + const wsUrl = String(target.webSocketDebuggerUrl || '').trim(); + if (!/^https:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+(?:\/|$)/i.test(url)) { + return false; + } + if (!/^ws:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+\//i.test(wsUrl)) { + return false; + } + return true; +} + +/** + * 校验桥接请求的 `Origin` 是否来自本机 Antigravity 主窗口 HTTPS 回环源。 + * + * @param {unknown} origin + * @returns {boolean} + */ +export function isAllowedBridgeOrigin(origin) { + const text = String(origin || '').trim(); + return /^https:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+$/i.test(text); +} + +/** + * 固定时间比较两个等长 ASCII 令牌字符串,避免时序侧信道泄露。 + * + * @param {string} actual + * @param {string} expected + * @param {typeof import('node:crypto').timingSafeEqual|null} [timingSafeEqualFn=null] + * @returns {boolean} + */ +function verifyBridgeToken(actual, expected, timingSafeEqualFn = null) { + if (typeof actual !== 'string' || typeof expected !== 'string' || !expected) return false; + if (actual.length !== expected.length) return false; + if (typeof timingSafeEqualFn === 'function') { + return timingSafeEqualFn(Buffer.from(actual, 'utf8'), Buffer.from(expected, 'utf8')); + } + let diff = 0; + for (let i = 0; i < expected.length; i++) { + diff |= actual.charCodeAt(i) ^ expected.charCodeAt(i); + } + return diff === 0; +} + +/** + * 创建双栖模式桥接与 CDP 热挂载控制器实例。 + * + * @param {{ + * handleApiRequest: (pathname: string, method: string, data: Record) => Promise<{ status: number, contentType?: string, headers?: Record, body: string }>, + * readAssetFn: (relPath: string) => Promise, + * getSettingsFn?: () => { enableWindowOverlay?: boolean }, + * getBundleVersionFn?: () => string, + * env?: Record, + * platform?: string, + * homeDir?: string, + * pollIntervalMs?: number, + * cdpTimeoutMs?: number, + * WebSocketImpl?: typeof WebSocket, + * }} options + */ +export function createWindowBridgeController(options) { + const { + handleApiRequest, + readAssetFn, + getSettingsFn = loadSettings, + getBundleVersionFn = computeRuntimeCodeVersion, + env = process.env, + platform = process.platform, + homeDir = homedir(), + pollIntervalMs = 3000, + fastPollIntervalMs = 1500, + cdpTimeoutMs = 3500, + bootBundleVersion = '', + onVersionDrift = null, + leaseFilePath = '', + WebSocketImpl = globalThis.WebSocket, + } = options || {}; + + function isPidAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return false; + if (pid === process.pid) return true; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return err?.code === 'EPERM'; + } + } + + let server = null; + let serverStartPromise = null; + let bridgePort = 0; + let bridgeToken = ''; + let pollTimer = null; + let initialTimer = null; + let stopped = false; + let syncInFlight = null; + let hadInjectedTargets = false; + let cdpFallbackActive = false; + let nodeDepsPromise = null; + + async function loadNodeDeps() { + if (!nodeDepsPromise) { + nodeDepsPromise = Promise.all([import('node:http'), import('node:crypto')]).then( + ([httpMod, cryptoMod]) => ({ + http: httpMod.default || httpMod, + crypto: cryptoMod.default || cryptoMod, + }) + ); + } + return nodeDepsPromise; + } + + function applyCorsHeaders(res, origin) { + res.setHeader('Access-Control-Allow-Origin', origin); + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); + res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Usage-Monitor-Token'); + res.setHeader('Access-Control-Allow-Private-Network', 'true'); + res.setHeader('Access-Control-Max-Age', '600'); + res.setHeader('Vary', 'Origin'); + res.setHeader('Cache-Control', 'no-store'); + } + + async function executeRpcBatch(rpcBatch) { + const responses = []; + for (const item of rpcBatch) { + const reqId = String(item?.id || ''); + if (!reqId) continue; + try { + const parsedUrl = new URL(String(item.path || '/'), 'http://127.0.0.1'); + if (!ALLOWED_BRIDGE_PATHS.has(parsedUrl.pathname)) { + responses.push({ id: reqId, ok: false, status: 404, error: 'Not found' }); + continue; + } + const method = String(item.method || 'GET').toUpperCase(); + const reqData = + method === 'GET' + ? Object.fromEntries(parsedUrl.searchParams.entries()) + : item.body && typeof item.body === 'object' + ? item.body + : {}; + const out = await handleApiRequest(parsedUrl.pathname, method, reqData); + const status = Number(out?.status || 200); + const parsedBody = out?.body ? JSON.parse(out.body) : {}; + if (status >= 200 && status < 300) { + responses.push({ id: reqId, ok: true, status, data: parsedBody }); + } else { + responses.push({ + id: reqId, + ok: false, + status, + error: parsedBody?.error || `HTTP ${status}`, + }); + } + } catch (err) { + responses.push({ + id: reqId, + ok: false, + status: 500, + error: err?.message || 'Internal bridge error', + }); + } + } + return responses; + } + + async function ensureBridgeServer() { + if (server && bridgePort > 0) { + return { port: bridgePort, token: bridgeToken }; + } + if (serverStartPromise) { + return serverStartPromise; + } + serverStartPromise = (async () => { + const { http, crypto } = await loadNodeDeps(); + if (!bridgeToken) { + bridgeToken = crypto.randomBytes(32).toString('hex'); + } + + const srv = http.createServer((req, res) => { + // 注意:主窗口为 https://127.0.0.1,桥接为 http://127.0.0.1,跨协议请求在 Chromium 中必然携带 + // Sec-Fetch-Site: cross-site;此处通过严格 Origin 白名单 + Host 校验 + 256-bit 随机令牌保障回环安全。 + const origin = String(req.headers.origin || '').trim(); + if (!isAllowedBridgeOrigin(origin)) { + res.writeHead(403, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Forbidden origin' })); + return; + } + + const hostHeader = String(req.headers.host || '').trim().toLowerCase(); + if ( + hostHeader && + hostHeader !== `127.0.0.1:${bridgePort}` && + hostHeader !== `localhost:${bridgePort}` && + hostHeader !== `[::1]:${bridgePort}` + ) { + res.writeHead(403, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Forbidden host' })); + return; + } + + applyCorsHeaders(res, origin); + + const method = String(req.method || 'GET').toUpperCase(); + if (method === 'OPTIONS') { + res.writeHead(204); + res.end(); + return; + } + + let parsedUrl; + try { + parsedUrl = new URL(req.url || '/', `http://127.0.0.1:${bridgePort}`); + } catch { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Malformed URL' })); + return; + } + + if (!ALLOWED_BRIDGE_PATHS.has(parsedUrl.pathname)) { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Not found' })); + return; + } + + const headerToken = String(req.headers['x-usage-monitor-token'] || ''); + if (!verifyBridgeToken(headerToken, bridgeToken, crypto.timingSafeEqual)) { + res.writeHead(403, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid bridge token' })); + return; + } + + if (method === 'GET') { + const queryData = Object.fromEntries(parsedUrl.searchParams.entries()); + Promise.resolve(handleApiRequest(parsedUrl.pathname, 'GET', queryData)) + .then((out) => { + const hdrs = { + 'Content-Type': out.contentType || 'application/json', + ...(out.headers || {}), + }; + res.writeHead(out.status || 200, hdrs); + res.end(out.body); + }) + .catch(() => { + if (!res.headersSent) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + } + res.end(JSON.stringify({ error: 'Internal bridge error' })); + }); + return; + } + + if (method !== 'POST') { + res.writeHead(405, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Method not allowed' })); + return; + } + + const chunks = []; + let totalBytes = 0; + let aborted = false; + req.on('data', (chunk) => { + totalBytes += chunk.length; + if (totalBytes > BRIDGE_MAX_BODY_BYTES) { + aborted = true; + res.writeHead(413, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Payload too large' })); + req.destroy(); + return; + } + chunks.push(chunk); + }); + req.on('end', () => { + if (aborted) return; + let bodyObj = {}; + try { + const raw = Buffer.concat(chunks).toString('utf8').trim(); + bodyObj = raw ? JSON.parse(raw) : {}; + } catch { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid JSON body' })); + return; + } + Promise.resolve(handleApiRequest(parsedUrl.pathname, 'POST', bodyObj)) + .then((out) => { + const hdrs = { + 'Content-Type': out.contentType || 'application/json', + ...(out.headers || {}), + }; + res.writeHead(out.status || 200, hdrs); + res.end(out.body); + }) + .catch(() => { + if (!res.headersSent) { + res.writeHead(500, { 'Content-Type': 'application/json' }); + } + res.end(JSON.stringify({ error: 'Internal bridge error' })); + }); + }); + }); + + await new Promise((resolve, reject) => { + srv.once('error', reject); + srv.listen(0, '127.0.0.1', () => { + srv.removeListener('error', reject); + resolve(); + }); + }); + srv.unref?.(); + const addr = srv.address(); + bridgePort = typeof addr === 'object' && addr ? Number(addr.port || 0) : 0; + server = srv; + return { port: bridgePort, token: bridgeToken }; + })().finally(() => { + serverStartPromise = null; + }); + + return serverStartPromise; + } + + function findActiveDevToolsPort() { + const candidates = resolveDevToolsPortCandidates(env, platform, homeDir); + for (const filePath of candidates) { + try { + if (!existsSync(filePath)) continue; + const port = parseDevToolsPortFile(readFileSync(filePath, 'utf8')); + if (port) return port; + } catch { + // 忽略不可读候选文件 + } + } + return null; + } + + async function listMainWindowTargets(cdpPort) { + const { http } = await loadNodeDeps(); + const rawBody = await new Promise((resolve, reject) => { + const req = http.get(`http://127.0.0.1:${cdpPort}/json/list`, (res) => { + if (res.statusCode !== 200) { + res.resume(); + reject(new Error(`CDP HTTP ${res.statusCode}`)); + return; + } + let text = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { + text += chunk; + }); + res.on('end', () => resolve(text)); + }); + req.setTimeout(1500, () => req.destroy(new Error('CDP list timeout'))); + req.on('error', reject); + }); + const parsed = JSON.parse(rawBody); + if (!Array.isArray(parsed)) return []; + return parsed.filter(isAntigravityMainPageTarget); + } + + async function evaluateOnTarget(wsUrl, expression) { + const WS = WebSocketImpl || globalThis.WebSocket; + if (typeof WS !== 'function') { + throw new Error('WebSocket runtime unavailable'); + } + let ws = null; + let timer = null; + try { + ws = new WS(wsUrl); + const evalResult = await new Promise((resolve, reject) => { + timer = setTimeout(() => { + reject(new Error('CDP Runtime.evaluate timeout')); + }, cdpTimeoutMs); + + const onOpen = () => { + try { + ws.send( + JSON.stringify({ + id: 1, + method: 'Runtime.evaluate', + params: { + expression, + returnByValue: true, + awaitPromise: true, + }, + }) + ); + } catch (err) { + reject(err); + } + }; + + const onMessage = (ev) => { + try { + const raw = typeof ev?.data === 'string' ? ev.data : String(ev?.data || ''); + const msg = JSON.parse(raw); + if (msg && msg.id === 1) { + resolve(msg); + } + } catch { + // 忽略无关事件帧 + } + }; + + const onError = (err) => { + reject(err instanceof Error ? err : new Error('CDP WebSocket error')); + }; + + ws.addEventListener('open', onOpen, { once: true }); + ws.addEventListener('message', onMessage); + ws.addEventListener('error', onError, { once: true }); + }); + return evalResult; + } finally { + if (timer) clearTimeout(timer); + if (ws) { + try { + ws.close(); + } catch { + // 忽略关闭异常 + } + } + } + } + + async function runSyncInternal({ forceReinject = false } = {}) { + if (stopped) return { ok: false, reason: 'stopped' }; + const bundleVersion = String(getBundleVersionFn() || ''); + if (bootBundleVersion && bundleVersion && bundleVersion !== String(bootBundleVersion)) { + onVersionDrift?.(); + return { ok: false, reason: 'version_drift_restarting', injected: 0 }; + } + + const enabled = Boolean(getSettingsFn()?.enableWindowOverlay !== false); + if (enabled && leaseFilePath && !forceReinject) { + const lease = loadJson(leaseFilePath, null); + const leasePid = Number(lease?.pid || 0); + const leaseAgeMs = Date.now() - Number(lease?.updatedAtMs || 0); + if (leasePid > 0 && leasePid !== process.pid && leaseAgeMs >= 0 && leaseAgeMs < 9000 && isPidAlive(leasePid)) { + const leaseVerNum = Number(lease?.bundleVersion) || 0; + const myVerNum = Number(bundleVersion) || 0; + if (leaseVerNum > myVerNum) { + onVersionDrift?.(); + return { ok: false, enabled: true, reason: 'older_than_leader', injected: 0 }; + } + if (leaseVerNum === myVerNum || String(lease?.bundleVersion || '') === bundleVersion) { + return { ok: true, enabled: true, reason: 'follower_yield', leaderPid: leasePid, injected: 0 }; + } + } + saveJson(leaseFilePath, { + pid: process.pid, + bundleVersion, + updatedAtMs: Date.now(), + }); + } + + const cdpPort = findActiveDevToolsPort(); + if (!cdpPort) { + return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 }; + } + + let targets = []; + try { + targets = await listMainWindowTargets(cdpPort); + } catch { + return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 }; + } + if (!targets.length) { + return { ok: true, enabled, reason: 'no_targets', injected: 0 }; + } + + if (!enabled) { + if (!hadInjectedTargets && !forceReinject) { + return { ok: true, enabled: false, removed: 0 }; + } + const disposeExpr = `(() => { + try { + const existed = Boolean(window.__AGUsageMonitorOverlay || window.__AGUsageMonitorBridge); + window.__AGUsageMonitorOverlay?.dispose?.(); + delete window.__AGUsageMonitorOverlay; + delete window.__AGUsageMonitorBridge; + return existed; + } catch { + return false; + } + })()`; + let removed = 0; + for (const target of targets) { + try { + const res = await evaluateOnTarget(target.webSocketDebuggerUrl, disposeExpr); + if (res?.result?.result?.value === true) removed += 1; + } catch { + // 单窗口不可达不阻塞其余窗口卸载 + } + } + hadInjectedTargets = false; + return { ok: true, enabled: false, removed }; + } + + const { port, token } = await ensureBridgeServer(); + const probeExpr = `(() => { + try { + const ov = window.__AGUsageMonitorOverlay; + const br = window.__AGUsageMonitorBridge; + const alive = Boolean(ov && typeof ov.ensureAlive === 'function' && ov.ensureAlive()); + const rpcBatch = Array.isArray(br?.rpcQueue) && br.rpcQueue.length > 0 + ? br.rpcQueue.splice(0, 8) + : []; + return { + alive, + bundleVersion: String(ov?.bundleVersion || ''), + bridgePort: Number(br?.port || 0), + hasToken: Boolean(br?.token), + transportMode: String(br?.transportMode || 'http'), + rpcBatch, + }; + } catch { + return { alive: false, bundleVersion: '', bridgePort: 0, hasToken: false, transportMode: 'http', rpcBatch: [] }; + } + })()`; + + let cachedAssets = null; + let injected = 0; + let aliveCount = 0; + let relayedRpcCount = 0; + let sawCdpTransport = false; + + for (const target of targets) { + try { + if (!forceReinject) { + const probeRes = await evaluateOnTarget(target.webSocketDebuggerUrl, probeExpr); + const snap = probeRes?.result?.result?.value; + if (snap && snap.alive === true) { + const snapVerNum = Number(snap.bundleVersion) || 0; + const curVerNum = Number(bundleVersion) || 0; + if (snapVerNum > 0 && curVerNum > 0 && snapVerNum > curVerNum) { + onVersionDrift?.(); + aliveCount += 1; + continue; + } + if (snap.bundleVersion === bundleVersion) { + if (snap.bridgePort !== port || snap.hasToken !== true) { + const rebindExpr = `window.__AGUsageMonitorOverlay?.updateBridge?.(${JSON.stringify({ port, token })})`; + await evaluateOnTarget(target.webSocketDebuggerUrl, rebindExpr); + } + aliveCount += 1; + hadInjectedTargets = true; + if (snap.transportMode === 'cdp') { + sawCdpTransport = true; + } + if (Array.isArray(snap.rpcBatch) && snap.rpcBatch.length > 0) { + sawCdpTransport = true; + const rpcResults = await executeRpcBatch(snap.rpcBatch); + relayedRpcCount += rpcResults.length; + const deliverExpr = `window.__AGUsageMonitorOverlay?.deliverRpc?.(${JSON.stringify(rpcResults)})`; + await evaluateOnTarget(target.webSocketDebuggerUrl, deliverExpr); + } + continue; + } + } + } + + if (!cachedAssets) { + const [stylesCss, appJs] = await Promise.all([ + readAssetFn('styles.css'), + readAssetFn('app.js'), + ]); + cachedAssets = { stylesCss, appJs }; + } + + let initialTelemetry = null; + try { + const routeMatch = String(target.url || '').match(/\/c\/([a-f0-9-]{36})(?:\/|$)/i); + const targetConvId = routeMatch ? routeMatch[1] : ''; + const initOut = await handleApiRequest('/api/telemetry', 'GET', { + conversationId: targetConvId, + range: 'today', + }); + if (Number(initOut?.status || 200) === 200 && initOut?.body) { + initialTelemetry = JSON.parse(initOut.body); + } + } catch { + // 预取首帧遥测异常不阻塞注入本身 + } + + const bridgeConfigJson = JSON.stringify({ + port, + token, + bundleVersion, + stylesCss: cachedAssets.stylesCss, + initialTelemetry, + }); + const injectionScript = `(() => {\nwindow.__AGUsageMonitorBridge = ${bridgeConfigJson};\n})();\n${cachedAssets.appJs}\nBoolean(window.__AGUsageMonitorOverlay && window.__AGUsageMonitorOverlay.ensureAlive && window.__AGUsageMonitorOverlay.ensureAlive());`; + + const evalRes = await evaluateOnTarget(target.webSocketDebuggerUrl, injectionScript); + if ( + evalRes && + !evalRes.error && + !evalRes.result?.exceptionDetails && + evalRes.result?.result?.value === true + ) { + injected += 1; + aliveCount += 1; + hadInjectedTargets = true; + } + } catch { + // 单个窗口注入异常不阻断其他窗口 + } + } + + cdpFallbackActive = sawCdpTransport; + return { + ok: true, + enabled: true, + port, + targets: targets.length, + injected, + aliveCount, + relayedRpcCount, + }; + } + + function syncAllWindows(opts = {}) { + if (syncInFlight) { + return syncInFlight.then(() => runSyncInternal(opts)); + } + syncInFlight = runSyncInternal(opts).finally(() => { + syncInFlight = null; + }); + return syncInFlight; + } + + function scheduleNextPoll() { + if (stopped) return; + if (pollTimer) clearTimeout(pollTimer); + const delayMs = cdpFallbackActive ? fastPollIntervalMs : pollIntervalMs; + pollTimer = setTimeout(() => { + pollTimer = null; + syncAllWindows() + .catch(() => {}) + .finally(() => { + scheduleNextPoll(); + }); + }, delayMs); + pollTimer.unref?.(); + } + + function start() { + stopped = false; + if (initialTimer) clearTimeout(initialTimer); + if (pollTimer) clearTimeout(pollTimer); + + initialTimer = setTimeout(() => { + initialTimer = null; + syncAllWindows() + .catch(() => {}) + .finally(() => { + scheduleNextPoll(); + }); + }, 350); + initialTimer.unref?.(); + } + + async function stop({ disposeWindows = false } = {}) { + if (initialTimer) { + clearTimeout(initialTimer); + initialTimer = null; + } + if (pollTimer) { + clearTimeout(pollTimer); + pollTimer = null; + } + if (disposeWindows && hadInjectedTargets) { + const prevStopped = stopped; + stopped = false; + try { + const cdpPort = findActiveDevToolsPort(); + if (cdpPort) { + const targets = await listMainWindowTargets(cdpPort).catch(() => []); + const disposeExpr = `(() => { try { window.__AGUsageMonitorOverlay?.dispose?.(); delete window.__AGUsageMonitorOverlay; delete window.__AGUsageMonitorBridge; return true; } catch { return false; } })()`; + for (const t of targets) { + await evaluateOnTarget(t.webSocketDebuggerUrl, disposeExpr).catch(() => {}); + } + } + } finally { + stopped = prevStopped; + } + } + stopped = true; + hadInjectedTargets = false; + if (server) { + const srv = server; + server = null; + bridgePort = 0; + await new Promise((resolve) => srv.close(() => resolve())); + } + } + + function notifySettingChanged(enabled) { + if (!enabled) { + hadInjectedTargets = true; + } + return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false })); + } + + return { + ensureBridgeServer, + syncAllWindows, + notifySettingChanged, + start, + stop, + getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }), + }; +} + +let defaultBridgeController = null; + +/** + * 启动进程级默认的双栖窗口桥接控制器(幂等)。 + * + * @param {Parameters[0]} options + */ +export function startDefaultWindowBridge(options) { + if (!defaultBridgeController) { + defaultBridgeController = createWindowBridgeController({ + leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'), + ...options, + }); + defaultBridgeController.start(); + } + return defaultBridgeController; +} + +/** + * 在用户保存设置切换 `enableWindowOverlay` 时立即同步所有打开的主窗口挂载状态。 + * + * @param {boolean} enabled + */ +export function notifyWindowOverlaySetting(enabled) { + if (!defaultBridgeController) return Promise.resolve({ ok: false }); + return defaultBridgeController.notifySettingChanged(enabled); +} diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index f74f4f0..6877479 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index 37b2a9e..c23f208 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -3,16 +3,15 @@ * * 职责边界: * - 提供前端静态资产路由(`/`、`/app.js`、`/styles.css`); - * - 提供本地 Loopback 受保护的 JSON API 路由: + * - 提供严格同端口 Loopback 受保护的 JSON API 路由: * - `GET /api/telemetry`:获取实时配额、当前会话指标与历史聚合遥测数据; - * - `POST /api/settings`:保存用户偏好设置; + * - `POST /api/settings`:保存用户偏好设置(写入失败时返回 HTTP 500); * - `POST /api/cloud-sync`:立即从 GitHub 同步最新云端价格目录与版本信息; * - `POST /api/plugin-update`:一键执行插件自更新(Git / Release ZIP 双通道); - * - `GET / POST /api/diagnostics`:查询或配置流式传输诊断采样器; * - 所有核心业务逻辑均已模块化拆分至 `./backend/*.mjs`。 */ -import { readFileSync, statSync, promises as fsPromises } from 'node:fs'; +import { readFileSync, promises as fsPromises } from 'node:fs'; import { join } from 'node:path'; import { Response, SidecarApp } from 'sidecar_sdk'; import { @@ -20,10 +19,13 @@ import { LS_ADDR, SETTINGS_FILE, cloudSyncState, + computeRuntimeCodeVersion, + isPlainObject, loadSettings, + normalizeTopbarCapsuleSlots, + normalizeWeeklyLimitMode, saveJson, } from './backend/config.mjs'; -import { diagnostics } from './backend/ls-rpc.mjs'; import { performPluginUpdate, scheduleSidecarRestart, @@ -31,16 +33,14 @@ import { } from './backend/plugin-updater.mjs'; import { getCloudStatus } from './backend/pricing-catalog.mjs'; import { buildTelemetryPayload } from './backend/telemetry-builder.mjs'; +import { + notifyWindowOverlaySetting, + startDefaultWindowBridge, +} from './backend/window-bridge.mjs'; const app = new SidecarApp(); -const bootBundleVersion = (() => { - try { - return statSync(join(HERE, 'app.js')).mtimeMs || 0; - } catch { - return 0; - } -})(); +const bootBundleVersion = computeRuntimeCodeVersion(); /** * 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。 @@ -57,30 +57,42 @@ const readLocalAsync = async (relPath) => { }; /** - * 校验请求是否来自本机回环地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin, - * 防止跨站 DNS Rebinding 或局域网未授权访问。 + * 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin, + * 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。 * * @param {object} req * @returns {boolean} */ -function isLocalHostRequest(req) { +export function isLocalHostRequest(req) { if (!req?.headers) return true; + const host = String(req.headers.host || '').trim().toLowerCase(); + const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/); + if (host && !hostMatch) { + return false; + } + const origin = String(req.headers.origin || '').trim().toLowerCase(); + if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) { + return true; + } const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase(); if (secFetchSite === 'cross-site') { return false; } - const host = String(req.headers.host || '').toLowerCase(); - if (host && !/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host)) { - return false; - } - const origin = String(req.headers.origin || '').toLowerCase(); - if ( - origin && - !/^(?:https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?|vscode-webview:\/\/[a-z0-9._-]+)$/.test( - origin - ) - ) { - return false; + if (origin) { + const originMatch = origin.match( + /^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/ + ); + if (!originMatch) { + return false; + } + if (hostMatch) { + const defaultPort = originMatch[1] === 'https' ? '443' : '80'; + const originPort = originMatch[3] || defaultPort; + const hostPort = hostMatch[2] || defaultPort; + if (originPort !== hostPort) { + return false; + } + } } return true; } @@ -116,20 +128,160 @@ app.page( }) ); -app.api( +app.page( '/styles.css', async () => new Response(await readLocalAsync('styles.css'), { contentType: 'text/css; charset=utf-8', headers: NO_STORE_HEADERS, - }), - 'GET' + }) ); // --------------------------------------------------------------------------- -// 业务数据与控制 API 路由 +// 业务数据与控制 API 路由(辅助栏 Sidecar Webview 与主窗口双栖桥接共享同一套处理函数) // --------------------------------------------------------------------------- +async function executeTelemetryAction(data) { + const rawConvId = String( + data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '' + ).trim(); + const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : ''; + const force = data?.force === '1' || data?.force === true; + if (LS_ADDR && LS_ADDR !== 'test.invalid') { + if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) { + await Promise.race([ + syncCloudCatalog({ force: true }).catch(() => {}), + new Promise((r) => setTimeout(r, 1200)), + ]); + } else { + syncCloudCatalog({ force: false }).catch(() => {}); + } + } + const filterOpts = { + range: data?.range || 'all', + startMs: sanitizePositiveFiniteMs(data?.startMs), + endMs: sanitizePositiveFiniteMs(data?.endMs), + }; + const payload = await buildTelemetryPayload(convId, force, filterOpts); + if ( + bootBundleVersion && + payload.uiBundleVersion && + String(payload.uiBundleVersion) !== String(bootBundleVersion) + ) { + scheduleSidecarRestart(150); + } + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify(payload), + }; +} + +function sanitizePositiveSettingNumber(val, fallback) { + const num = Number(val); + return Number.isFinite(num) && num > 0 ? num : fallback; +} + +function executeSettingsAction(data) { + const current = loadSettings(); + const payload = isPlainObject(data) ? data : {}; + const updated = { + weeklyTokenBudget: sanitizePositiveSettingNumber( + payload.weeklyTokenBudget ?? payload.weeklyTokenLimit, + current.weeklyTokenBudget + ), + weeklyCostBudget: sanitizePositiveSettingNumber( + payload.weeklyCostBudget, + current.weeklyCostBudget + ), + weeklyLimitMode: + payload.weeklyLimitMode !== undefined + ? normalizeWeeklyLimitMode(payload.weeklyLimitMode) + : current.weeklyLimitMode, + showUpstreamModel: + typeof payload.showUpstreamModel === 'boolean' + ? payload.showUpstreamModel + : Boolean(current.showUpstreamModel), + autoUpdatePlugin: + typeof payload.autoUpdatePlugin === 'boolean' + ? payload.autoUpdatePlugin + : Boolean(current.autoUpdatePlugin), + enableWindowOverlay: + typeof payload.enableWindowOverlay === 'boolean' + ? payload.enableWindowOverlay + : current.enableWindowOverlay !== false, + showTopbarMultiSession: + typeof payload.showTopbarMultiSession === 'boolean' + ? payload.showTopbarMultiSession + : current.showTopbarMultiSession !== false, + topbarCapsuleSlots: + payload.topbarCapsuleSlots !== undefined + ? normalizeTopbarCapsuleSlots(payload.topbarCapsuleSlots) + : normalizeTopbarCapsuleSlots(current.topbarCapsuleSlots), + }; + if (!saveJson(SETTINGS_FILE, updated)) { + return { + ok: false, + status: 500, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ ok: false, error: 'Failed to persist settings' }), + }; + } + if (updated.enableWindowOverlay !== (current.enableWindowOverlay !== false)) { + void notifyWindowOverlaySetting(updated.enableWindowOverlay); + } + return { + ok: true, + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + updated, + body: JSON.stringify(updated), + }; +} + +async function executeCloudSyncAction() { + const cloudStatus = await syncCloudCatalog({ force: true }); + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ ok: !cloudStatus.lastSyncError, cloudStatus }), + }; +} + +async function executePluginUpdateAction() { + const result = await performPluginUpdate({ isAuto: false }); + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ ...result, cloudStatus: getCloudStatus() }), + }; +} + +async function dispatchBridgeApiRequest(pathname, method, data) { + if (pathname === '/api/telemetry' && method === 'GET') { + return executeTelemetryAction(data); + } + if (pathname === '/api/settings' && method === 'POST') { + return executeSettingsAction(data); + } + if (pathname === '/api/cloud-sync' && method === 'POST') { + return executeCloudSyncAction(); + } + if (pathname === '/api/plugin-update' && method === 'POST') { + return executePluginUpdateAction(); + } + return { + status: 404, + contentType: 'application/json', + body: JSON.stringify({ error: 'Not found' }), + }; +} + app.api( '/api/telemetry', async (data, req) => { @@ -139,50 +291,16 @@ app.api( contentType: 'application/json', }); } - const rawConvId = String( - data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '' - ).trim(); - const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : ''; - const force = data?.force === '1' || data?.force === true; - if (LS_ADDR !== 'test.invalid') { - if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) { - await Promise.race([ - syncCloudCatalog({ force: true }).catch(() => {}), - new Promise((r) => setTimeout(r, 1200)), - ]); - } else { - syncCloudCatalog({ force: false }).catch(() => {}); - } - } - const filterOpts = { - range: data?.range || 'all', - startMs: sanitizePositiveFiniteMs(data?.startMs), - endMs: sanitizePositiveFiniteMs(data?.endMs), - }; - const payload = await buildTelemetryPayload(convId, force, filterOpts); - if ( - bootBundleVersion > 0 && - payload.uiBundleVersion > 0 && - payload.uiBundleVersion !== bootBundleVersion - ) { - scheduleSidecarRestart(150); - } - return new Response(JSON.stringify(payload), { - status: 200, - contentType: 'application/json', - headers: { 'Cache-Control': 'no-store' }, + const out = await executeTelemetryAction(data); + return new Response(out.body, { + status: out.status, + contentType: out.contentType, + headers: out.headers, }); }, 'GET' ); -const VALID_WEEKLY_LIMIT_MODES = new Set(['official', 'tokens', 'cost']); - -function sanitizePositiveSettingNumber(val, fallback) { - const num = Number(val); - return Number.isFinite(num) && num > 0 ? num : fallback; -} - app.api('/api/settings', (data, req) => { if (!isLocalHostRequest(req)) { return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), { @@ -190,35 +308,15 @@ app.api('/api/settings', (data, req) => { contentType: 'application/json', }); } - const current = loadSettings(); - const payload = data && typeof data === 'object' ? data : {}; - const rawMode = String(payload.weeklyLimitMode || '').trim(); - const updated = { - ...current, - contextWindowLimit: sanitizePositiveSettingNumber( - payload.contextWindowLimit, - current.contextWindowLimit - ), - weeklyTokenBudget: sanitizePositiveSettingNumber( - payload.weeklyTokenBudget, - current.weeklyTokenBudget - ), - weeklyCostBudget: sanitizePositiveSettingNumber( - payload.weeklyCostBudget, - current.weeklyCostBudget - ), - weeklyLimitMode: VALID_WEEKLY_LIMIT_MODES.has(rawMode) ? rawMode : current.weeklyLimitMode, - showUpstreamModel: - typeof payload.showUpstreamModel === 'boolean' - ? payload.showUpstreamModel - : Boolean(current.showUpstreamModel), - autoUpdatePlugin: - typeof payload.autoUpdatePlugin === 'boolean' - ? payload.autoUpdatePlugin - : Boolean(current.autoUpdatePlugin), - }; - saveJson(SETTINGS_FILE, updated); - return updated; + const out = executeSettingsAction(data); + if (!out.ok) { + return new Response(out.body, { + status: out.status, + contentType: out.contentType, + headers: out.headers, + }); + } + return out.updated; }); app.api('/api/cloud-sync', async (_data, req) => { @@ -228,11 +326,11 @@ app.api('/api/cloud-sync', async (_data, req) => { contentType: 'application/json', }); } - const cloudStatus = await syncCloudCatalog({ force: true }); - return new Response(JSON.stringify({ ok: !cloudStatus.lastSyncError, cloudStatus }), { - status: 200, - contentType: 'application/json', - headers: { 'Cache-Control': 'no-store' }, + const out = await executeCloudSyncAction(); + return new Response(out.body, { + status: out.status, + contentType: out.contentType, + headers: out.headers, }); }); @@ -243,51 +341,21 @@ app.api('/api/plugin-update', async (_data, req) => { contentType: 'application/json', }); } - const result = await performPluginUpdate({ isAuto: false }); - return new Response(JSON.stringify({ ...result, cloudStatus: getCloudStatus() }), { - status: 200, - contentType: 'application/json', - headers: { 'Cache-Control': 'no-store' }, + const out = await executePluginUpdateAction(); + return new Response(out.body, { + status: out.status, + contentType: out.contentType, + headers: out.headers, }); }); -app.api( - '/api/diagnostics', - (_data, req) => { - if (!isLocalHostRequest(req)) return new Response('Forbidden host or origin', { status: 403 }); - return new Response(JSON.stringify(diagnostics.status()), { - contentType: 'application/json', - headers: { 'Cache-Control': 'no-store' }, - }); - }, - 'GET' -); - -app.api('/api/diagnostics', (data, req) => { - if (!isLocalHostRequest(req)) return new Response('Forbidden host or origin', { status: 403 }); - try { - return diagnostics.configure({ - enabled: data?.enabled, - conversationId: data?.conversationId || '', - }); - } catch (error) { - return new Response( - JSON.stringify({ - error: - error.message === 'invalid_diagnostic_config' - ? 'Invalid diagnostic settings' - : 'Could not save diagnostic settings', - }), - { - status: error.message === 'invalid_diagnostic_config' ? 400 : 500, - contentType: 'application/json', - } - ); - } -}); - app.run(); -diagnostics.start(); -if (LS_ADDR !== 'test.invalid') { +if (LS_ADDR && LS_ADDR !== 'test.invalid') { syncCloudCatalog({ force: false }).catch(() => {}); + startDefaultWindowBridge({ + handleApiRequest: dispatchBridgeApiRequest, + readAssetFn: readLocalAsync, + bootBundleVersion, + onVersionDrift: () => scheduleSidecarRestart(150), + }); } diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 725884f..477edcc 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -1,6 +1,6 @@ { "name": "usage-monitor-panel", - "version": "1.4.2", + "version": "1.4.3", "private": true, "type": "module", "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index 80b87cb..1859ae2 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -5,78 +5,503 @@ */ import { existsSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const PANEL_DIR = dirname(dirname(fileURLToPath(import.meta.url))); -const cssOrder = [ - 'src/styles/tokens.css', - 'src/styles/base.css', - 'src/styles/animations.css', - 'src/styles/controls.css', - 'src/styles/views-overview.css', - 'src/styles/views-consumption.css', - 'src/styles/views-tables.css', -]; +const REGEX_PRECEDING_KEYWORDS = new Set([ + 'return', + 'typeof', + 'void', + 'delete', + 'throw', + 'case', + 'in', + 'of', + 'instanceof', + 'new', + 'yield', + 'await', +]); -const cssBundle = - cssOrder - .map((rel) => `/* --- ${rel} --- */\n${readFileSync(join(PANEL_DIR, rel), 'utf8').trim()}`) - .join('\n\n') + '\n'; - -writeFileSync(join(PANEL_DIR, 'styles.css'), cssBundle, 'utf8'); - -const jsOrder = [ - 'src/icons/svgRegistry.js', - 'src/icons/SvgIcon.js', - 'src/core/reactive.js', - 'src/core/domPatch.js', - 'src/core/component.js', - 'src/core/formatters.js', - 'src/core/httpClient.js', - 'src/store/uiStore.js', - 'src/store/telemetryStore.js', - 'src/components/ui/TopLongPillNav.js', - 'src/components/ui/CustomSelect.js', - 'src/components/ui/CustomNumberInput.js', - 'src/components/ui/CustomDateTimePicker.js', - 'src/components/ui/CustomScrollbar.js', - 'src/components/ui/SegmentedControl.js', - 'src/components/ui/ContextSegmentMeter.js', - 'src/components/ui/FourSegmentBar.js', - 'src/components/charts/TrendAreaChart.js', - 'src/components/layout/TopSessionHeader.js', - 'src/views/LiveOverviewView.js', - 'src/views/ConsumptionView.js', - 'src/views/StepsDetailView.js', - 'src/views/SettingsView.js', - 'src/App.js', - 'src/main.js', -]; - -const jsBundle = - jsOrder - .map((rel) => { - const raw = readFileSync(join(PANEL_DIR, rel), 'utf8'); - const stripped = raw - .replace(/^import\s+[\s\S]*?from\s+['"].*?['"];?\r?\n/gm, '') - .replace(/^export\s+(?=(?:async\s+)?function|const|let|class)/gm, ''); - return `// --- ${rel} ---\n${stripped.trim()}`; - }) - .join('\n\n') + '\n'; - -writeFileSync(join(PANEL_DIR, 'app.js'), jsBundle, 'utf8'); - -const ver = Date.now(); -const indexHtmlPath = join(PANEL_DIR, 'index.html'); -if (existsSync(indexHtmlPath)) { - const html = readFileSync(indexHtmlPath, 'utf8') - .replace(/href="\/styles\.css(?:\?v=[^"]*)?"/, `href="/styles.css?v=${ver}"`) - .replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`); - writeFileSync(indexHtmlPath, html, 'utf8'); +function isIdentStart(ch) { + if (!ch) return false; + const code = ch.charCodeAt(0); + return ( + (code >= 65 && code <= 90) || + (code >= 97 && code <= 122) || + ch === '_' || + ch === '$' || + code > 127 + ); } -console.log( - `Built styles.css (${cssBundle.length} bytes) and app.js (${jsBundle.length} bytes) [v=${ver}]` -); +function isIdentPart(ch) { + if (!ch) return false; + const code = ch.charCodeAt(0); + return isIdentStart(ch) || (code >= 48 && code <= 57); +} + +function skipSimpleString(source, startIdx) { + const quote = source[startIdx]; + let idx = startIdx + 1; + while (idx < source.length) { + const ch = source[idx]; + if (ch === '\\') { + idx += 2; + continue; + } + if (ch === quote) return idx + 1; + idx += 1; + } + return source.length; +} + +function skipSpacesAndComments(source, startIdx) { + let idx = startIdx; + while (idx < source.length) { + const ch = source[idx]; + if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') { + idx += 1; + } else if (ch === '/' && source[idx + 1] === '/') { + idx += 2; + while (idx < source.length && source[idx] !== '\n') idx += 1; + } else if (ch === '/' && source[idx + 1] === '*') { + idx += 2; + while (idx < source.length && !(source[idx] === '*' && source[idx + 1] === '/')) idx += 1; + idx = Math.min(source.length, idx + 2); + } else { + break; + } + } + return idx; +} + +function consumeTrailingStatementEnd(source, startIdx) { + let idx = startIdx; + while (idx < source.length && (source[idx] === ' ' || source[idx] === '\t')) idx += 1; + if (source[idx] === ';') { + idx += 1; + while (idx < source.length && (source[idx] === ' ' || source[idx] === '\t')) idx += 1; + } + if (source[idx] === '\r' && source[idx + 1] === '\n') { + idx += 2; + } else if (source[idx] === '\n') { + idx += 1; + } + return idx; +} + +function scanImportDeclarationEnd(source, afterImportIdx) { + let idx = afterImportIdx; + let braceDepth = 0; + let sawModuleSpecifierString = false; + while (idx < source.length) { + const ch = source[idx]; + if (ch === "'" || ch === '"') { + idx = skipSimpleString(source, idx); + if (braceDepth === 0) { + sawModuleSpecifierString = true; + return consumeTrailingStatementEnd(source, idx); + } + continue; + } + if (ch === '/' && source[idx + 1] === '/') { + idx += 2; + while (idx < source.length && source[idx] !== '\n') idx += 1; + continue; + } + if (ch === '/' && source[idx + 1] === '*') { + idx += 2; + while (idx < source.length && !(source[idx] === '*' && source[idx + 1] === '/')) idx += 1; + idx = Math.min(source.length, idx + 2); + continue; + } + if (ch === '{') braceDepth += 1; + else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1); + else if (ch === ';' && braceDepth === 0) { + return consumeTrailingStatementEnd(source, idx); + } else if (ch === '\n' && braceDepth === 0 && sawModuleSpecifierString) { + return idx + 1; + } + idx += 1; + } + return source.length; +} + +function scanExportClauseEnd(source, afterExportIdx) { + let idx = afterExportIdx; + if (source[idx] === '{') { + let depth = 1; + idx += 1; + while (idx < source.length && depth > 0) { + const ch = source[idx]; + if (ch === "'" || ch === '"') { + idx = skipSimpleString(source, idx); + continue; + } + if (ch === '/' && source[idx + 1] === '/') { + idx += 2; + while (idx < source.length && source[idx] !== '\n') idx += 1; + continue; + } + if (ch === '/' && source[idx + 1] === '*') { + idx += 2; + while (idx < source.length && !(source[idx] === '*' && source[idx + 1] === '/')) idx += 1; + idx = Math.min(source.length, idx + 2); + continue; + } + if (ch === '{') depth += 1; + else if (ch === '}') depth -= 1; + idx += 1; + } + } else if (source[idx] === '*') { + idx += 1; + idx = skipSpacesAndComments(source, idx); + if (source.startsWith('as', idx) && !isIdentPart(source[idx + 2])) { + idx = skipSpacesAndComments(source, idx + 2); + while (idx < source.length && isIdentPart(source[idx])) idx += 1; + } + } + + const peekFrom = skipSpacesAndComments(source, idx); + if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) { + const specIdx = skipSpacesAndComments(source, peekFrom + 4); + if (source[specIdx] === "'" || source[specIdx] === '"') { + idx = skipSimpleString(source, specIdx); + } + } + return consumeTrailingStatementEnd(source, idx); +} + +/** + * Lexical ES module syntax stripper that skips comments, single/double-quoted + * strings, template literals (including nested `${...}` expressions), and regex + * literals, removing only true top-level `import` / `export` syntax. + * + * @param {string} source + * @returns {string} + */ +export function stripModuleSyntax(source) { + const len = source.length; + let out = ''; + let i = 0; + let braceDepth = 0; + let parenDepth = 0; + const tplBraceStack = []; + let canStartRegex = true; + let prevNonWsChar = ''; + + function scanTemplateChunk(startAfterBacktickOrBrace) { + let idx = startAfterBacktickOrBrace; + while (idx < len) { + const ch = source[idx]; + if (ch === '\\') { + idx += 2; + continue; + } + if (ch === '`') { + out += source.slice(startAfterBacktickOrBrace, idx + 1); + canStartRegex = false; + prevNonWsChar = '`'; + return idx + 1; + } + if (ch === '$' && source[idx + 1] === '{') { + out += source.slice(startAfterBacktickOrBrace, idx + 2); + tplBraceStack.push(braceDepth); + braceDepth += 1; + canStartRegex = true; + prevNonWsChar = '{'; + return idx + 2; + } + idx += 1; + } + out += source.slice(startAfterBacktickOrBrace); + return len; + } + + while (i < len) { + const ch = source[i]; + + // Whitespace + if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') { + out += ch; + i += 1; + continue; + } + + // Line comment + if (ch === '/' && source[i + 1] === '/') { + let end = i + 2; + while (end < len && source[end] !== '\n') end += 1; + out += source.slice(i, end); + i = end; + continue; + } + + // Block comment + if (ch === '/' && source[i + 1] === '*') { + let end = i + 2; + while (end < len && !(source[end] === '*' && source[end + 1] === '/')) end += 1; + end = Math.min(len, end + 2); + out += source.slice(i, end); + i = end; + continue; + } + + // Single or double quoted string + if (ch === "'" || ch === '"') { + const end = skipSimpleString(source, i); + out += source.slice(i, end); + canStartRegex = false; + prevNonWsChar = ch; + i = end; + continue; + } + + // Template literal start + if (ch === '`') { + out += '`'; + i = scanTemplateChunk(i + 1); + continue; + } + + // Regex literal + if (ch === '/' && canStartRegex) { + let end = i + 1; + let inClass = false; + while (end < len) { + const rc = source[end]; + if (rc === '\\') { + end += 2; + continue; + } + if (rc === '[') inClass = true; + else if (rc === ']') inClass = false; + else if (rc === '/' && !inClass) { + end += 1; + while (end < len && /[a-z]/i.test(source[end])) end += 1; + break; + } else if (rc === '\n') { + break; + } + end += 1; + } + out += source.slice(i, end); + canStartRegex = false; + prevNonWsChar = '/'; + i = end; + continue; + } + + // Braces & template expression resume + if (ch === '{') { + braceDepth += 1; + out += ch; + canStartRegex = true; + prevNonWsChar = ch; + i += 1; + continue; + } + + if (ch === '}') { + if (tplBraceStack.length > 0 && braceDepth === tplBraceStack[tplBraceStack.length - 1] + 1) { + braceDepth -= 1; + tplBraceStack.pop(); + out += '}'; + i = scanTemplateChunk(i + 1); + continue; + } + braceDepth = Math.max(0, braceDepth - 1); + out += ch; + canStartRegex = true; + prevNonWsChar = ch; + i += 1; + continue; + } + + if (ch === '(') { + parenDepth += 1; + out += ch; + canStartRegex = true; + prevNonWsChar = ch; + i += 1; + continue; + } + + if (ch === ')') { + parenDepth = Math.max(0, parenDepth - 1); + out += ch; + canStartRegex = false; + prevNonWsChar = ch; + i += 1; + continue; + } + + // Identifier / keyword + if (isIdentStart(ch)) { + let end = i + 1; + while (end < len && isIdentPart(source[end])) end += 1; + const word = source.slice(i, end); + + const isTrueTopLevel = + braceDepth === 0 && + parenDepth === 0 && + tplBraceStack.length === 0 && + prevNonWsChar !== '.'; + + if (isTrueTopLevel && word === 'import') { + const afterImport = skipSpacesAndComments(source, end); + const nextCh = source[afterImport]; + // Exclude `import.meta` and dynamic `import(...)` + if (nextCh && nextCh !== '.' && nextCh !== '(') { + i = scanImportDeclarationEnd(source, afterImport); + canStartRegex = true; + prevNonWsChar = ';'; + continue; + } + } + + if (isTrueTopLevel && word === 'export') { + const afterExport = skipSpacesAndComments(source, end); + const nextCh = source[afterExport]; + if (nextCh === '{' || nextCh === '*') { + i = scanExportClauseEnd(source, afterExport); + canStartRegex = true; + prevNonWsChar = ';'; + continue; + } + // `export default ...` + if (source.startsWith('default', afterExport) && !isIdentPart(source[afterExport + 7])) { + const afterDefault = skipSpacesAndComments(source, afterExport + 7); + const isDecl = + (source.startsWith('function', afterDefault) && !isIdentPart(source[afterDefault + 8])) || + (source.startsWith('class', afterDefault) && !isIdentPart(source[afterDefault + 5])) || + (source.startsWith('async', afterDefault) && !isIdentPart(source[afterDefault + 5])); + if (isDecl) { + i = afterDefault; + canStartRegex = false; + continue; + } + out += 'void '; + i = afterDefault; + canStartRegex = true; + prevNonWsChar = 'd'; + continue; + } + // `export const|let|var|function|class|async ...` + if ( + (source.startsWith('const', afterExport) && !isIdentPart(source[afterExport + 5])) || + (source.startsWith('let', afterExport) && !isIdentPart(source[afterExport + 3])) || + (source.startsWith('var', afterExport) && !isIdentPart(source[afterExport + 3])) || + (source.startsWith('function', afterExport) && !isIdentPart(source[afterExport + 8])) || + (source.startsWith('class', afterExport) && !isIdentPart(source[afterExport + 5])) || + (source.startsWith('async', afterExport) && !isIdentPart(source[afterExport + 5])) + ) { + i = afterExport; + canStartRegex = false; + continue; + } + } + + out += word; + canStartRegex = REGEX_PRECEDING_KEYWORDS.has(word); + prevNonWsChar = word[word.length - 1]; + i = end; + continue; + } + + // Numbers & other punctuation + out += ch; + if (/[0-9\]`]/.test(ch)) { + canStartRegex = false; + } else if (/[,=:[!&|?;+\-*%~^<>]/.test(ch)) { + canStartRegex = true; + } else { + canStartRegex = false; + } + prevNonWsChar = ch; + i += 1; + } + + return out; +} + +export function buildBundle() { + const cssOrder = [ + 'src/styles/tokens.css', + 'src/styles/base.css', + 'src/styles/animations.css', + 'src/styles/controls.css', + 'src/styles/views-overview.css', + 'src/styles/views-consumption.css', + 'src/styles/views-tables.css', + 'src/styles/overlay.css', + ]; + + const cssBundle = + cssOrder + .map((rel) => `/* --- ${rel} --- */\n${readFileSync(join(PANEL_DIR, rel), 'utf8').trim()}`) + .join('\n\n') + '\n'; + + writeFileSync(join(PANEL_DIR, 'styles.css'), cssBundle, 'utf8'); + + const jsOrder = [ + 'src/icons/svgRegistry.js', + 'src/icons/SvgIcon.js', + 'src/core/reactive.js', + 'src/core/domPatch.js', + 'src/core/component.js', + 'src/core/formatters.js', + 'src/core/httpClient.js', + 'src/store/uiStore.js', + 'src/store/telemetryStore.js', + 'src/components/ui/TopLongPillNav.js', + 'src/components/ui/CustomSelect.js', + 'src/components/ui/CustomNumberInput.js', + 'src/components/ui/CustomDateTimePicker.js', + 'src/components/ui/CustomScrollbar.js', + 'src/components/ui/SegmentedControl.js', + 'src/components/ui/ContextSegmentMeter.js', + 'src/components/ui/FourSegmentBar.js', + 'src/components/charts/TrendAreaChart.js', + 'src/components/layout/TopSessionHeader.js', + 'src/views/LiveOverviewView.js', + 'src/views/ConsumptionView.js', + 'src/views/StepsDetailView.js', + 'src/views/SettingsView.js', + 'src/App.js', + 'src/components/layout/WindowOverlayShell.js', + 'src/main.js', + ]; + + const innerModules = jsOrder + .map((rel) => { + const raw = readFileSync(join(PANEL_DIR, rel), 'utf8'); + const stripped = stripModuleSyntax(raw); + return `// --- ${rel} ---\n${stripped.trim()}`; + }) + .join('\n\n'); + + const jsBundle = `(() => {\n'use strict';\n\n${innerModules}\n})();\n`; + + writeFileSync(join(PANEL_DIR, 'app.js'), jsBundle, 'utf8'); + + const ver = Date.now(); + const indexHtmlPath = join(PANEL_DIR, 'index.html'); + if (existsSync(indexHtmlPath)) { + const html = readFileSync(indexHtmlPath, 'utf8') + .replace(/href="\/styles\.css(?:\?v=[^"]*)?"/, `href="/styles.css?v=${ver}"`) + .replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`); + writeFileSync(indexHtmlPath, html, 'utf8'); + } + + console.log( + `Built styles.css (${cssBundle.length} bytes) and app.js (${jsBundle.length} bytes) [v=${ver}]` + ); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + buildBundle(); +} diff --git a/sidecars/panel/sidecar.json b/sidecars/panel/sidecar.json index 31248fe..25d1ab4 100644 --- a/sidecars/panel/sidecar.json +++ b/sidecars/panel/sidecar.json @@ -3,7 +3,7 @@ "args": ["main.mjs"], "restart_policy": "always", "display_name": "用量监控", - "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史消耗。", + "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "has_web_ui": true, "ui_config": { "display_name": "用量监控", diff --git a/sidecars/panel/speed-metrics.mjs b/sidecars/panel/speed-metrics.mjs index 95391dd..3b4824b 100644 --- a/sidecars/panel/speed-metrics.mjs +++ b/sidecars/panel/speed-metrics.mjs @@ -71,6 +71,28 @@ function validCount(value) { return Number.isSafeInteger(num) && num >= 0; } +/** + * 将原始 Token 计数值安全归一化为非负整数;对负数、NaN、Infinity、空数组/对象或非法字符串统一回退为 0。 + * + * @param {unknown} value + * @returns {number} + */ +function safeTokenCount(value) { + if (validCount(value)) { + return Number(value); + } + if (typeof value === 'number' && Number.isFinite(value) && value >= 0) { + return Math.floor(value); + } + if (typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value.trim())) { + const num = Number(value.trim()); + if (Number.isFinite(num) && num >= 0) { + return Math.floor(num); + } + } + return 0; +} + /** * 将 ISO-8601 时间戳解析为纳秒级 `BigInt` 时间戳。 * @@ -213,6 +235,30 @@ function classifyChatMessageChild(child) { return 'toolResults'; } +/** + * 根据 `messagePrompts` 条目的来源与内容特征将其归类到对话上下文的 5 个细分通道。 + * + * @param {object} m + * @returns {'toolResults'|'checkpoint'|'subagent'|'assistant'|'userInput'} + */ +function classifyMessagePrompt(m) { + const text = String(m?.prompt ?? m?.content ?? ''); + const src = String(m?.source || '').toUpperCase(); + if (src.includes('TOOL')) { + return 'toolResults'; + } + if (text.startsWith('')) { + return 'checkpoint'; + } + if (text.includes('')) { + return 'subagent'; + } + if (src.includes('SYSTEM') || src.includes('ASSISTANT') || src.includes('MODEL')) { + return 'assistant'; + } + return 'userInput'; +} + /** * 从 `chatModel` 元数据中提取并拆解 10 大上下文 Token 构成分类: * - `systemPromptTokens`:核心系统提示词 @@ -358,6 +404,50 @@ export function extractContextBreakdown(chat) { if (gTokens > childSum) { userInputTokens += gTokens - childSum; } + } else if (messagePrompts.length > 0) { + const mpBuckets = { + userInput: 0, + assistant: 0, + toolResults: 0, + subagent: 0, + checkpoint: 0, + }; + let mpSum = 0; + for (const m of messagePrompts) { + const text = String(m?.prompt ?? m?.content ?? ''); + const tok = + Number.isFinite(Number(m?.numTokens)) && Number(m?.numTokens) >= 0 + ? Number(m.numTokens) + : estimateUtf8Tokens(text); + const bucketKey = classifyMessagePrompt(m); + mpBuckets[bucketKey] += tok; + mpSum += tok; + } + if (gTokens > 0 && mpSum > 0) { + const keys = ['userInput', 'assistant', 'toolResults', 'subagent', 'checkpoint']; + const scaled = {}; + let assigned = 0; + let largestKey = 'userInput'; + for (const k of keys) { + if (mpBuckets[k] > mpBuckets[largestKey]) largestKey = k; + scaled[k] = mpBuckets[k] > 0 ? Math.floor((mpBuckets[k] * gTokens) / mpSum) : 0; + assigned += scaled[k]; + } + scaled[largestKey] += Math.max(0, gTokens - assigned); + userInputTokens += scaled.userInput; + assistantTokens += scaled.assistant; + toolResultsTokens += scaled.toolResults; + subagentTokens += scaled.subagent; + checkpointTokens += scaled.checkpoint; + } else if (mpSum > 0) { + userInputTokens += mpBuckets.userInput; + assistantTokens += mpBuckets.assistant; + toolResultsTokens += mpBuckets.toolResults; + subagentTokens += mpBuckets.subagent; + checkpointTokens += mpBuckets.checkpoint; + } else if (gTokens > 0) { + userInputTokens += gTokens; + } } else if (gTokens > 0) { userInputTokens += gTokens; } @@ -408,15 +498,15 @@ export function extractContextBreakdown(chat) { Number.isFinite(Number(m?.numTokens)) && Number(m?.numTokens) >= 0 ? Number(m.numTokens) : estimateUtf8Tokens(text); - const src = String(m?.source || '').toUpperCase(); - if (src.includes('TOOL')) { + const bucketKey = classifyMessagePrompt(m); + if (bucketKey === 'toolResults') { toolResultsTokens += tok; - } else if (src.includes('SYSTEM') || src.includes('ASSISTANT') || src.includes('MODEL')) { - assistantTokens += tok; - } else if (text.startsWith('')) { + } else if (bucketKey === 'checkpoint') { checkpointTokens += tok; - } else if (text.includes('')) { + } else if (bucketKey === 'subagent') { subagentTokens += tok; + } else if (bucketKey === 'assistant') { + assistantTokens += tok; } else { userInputTokens += tok; } @@ -484,20 +574,28 @@ export function extractContextBreakdown(chat) { export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const genByStep = new Map(); let latestBreakdownChat = null; + let latestBreakdownStepIdx = -1; for (const gm of generatorMetadata || []) { if (!gm?.chatModel) { continue; } + let gmMaxIdx = -1; for (const index of gm?.stepIndices || []) { - genByStep.set(Number(index), gm); + const numIdx = Number(index); + genByStep.set(numIdx, gm); + if (Number.isFinite(numIdx) && numIdx > gmMaxIdx) { + gmMaxIdx = numIdx; + } } if (extractContextBreakdown(gm.chatModel)) { latestBreakdownChat = gm.chatModel; + latestBreakdownStepIdx = gmMaxIdx; } } const result = []; + let lastCompactionStepIdx = -1; rawSteps.forEach((s, index) => { const m = s?.metadata; @@ -513,23 +611,32 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const gm = inlineChat || genByStep.get(Number(stepIndex)); const chat = gm?.chatModel; const p = s.plannerResponse || {}; - const isCompactionStep = s.type === 'CORTEX_STEP_TYPE_CHECKPOINT'; + const isCompactionStep = isCheckpointStep(s); + if (isCompactionStep && Number.isFinite(Number(stepIndex))) { + lastCompactionStepIdx = Math.max(lastCompactionStepIdx, Number(stepIndex)); + } - const inputTokens = Number(u.inputTokens || 0); - const cacheReadTokens = Number(u.cacheReadTokens || 0); - const outputTokens = Number(u.outputTokens || 0); - const thinkingTokens = Number( + const inputTokens = safeTokenCount(u.inputTokens); + const cacheReadTokens = safeTokenCount(u.cacheReadTokens); + const outputTokens = safeTokenCount(u.outputTokens); + const rawThinkingTok = safeTokenCount( p.thinkingTokens ?? u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens ?? 0 ); - const responseTokens = Number( + const rawResponseTok = p.responseTokens ?? - u.responseOutputTokens ?? - chat?.usage?.responseOutputTokens ?? - Math.max(0, outputTokens - thinkingTokens) - ); + u.responseOutputTokens ?? + chat?.usage?.responseOutputTokens; + const thinkingTokens = + rawResponseTok !== undefined && rawResponseTok !== null + ? rawThinkingTok + : Math.min(outputTokens, rawThinkingTok); + const responseTokens = + rawResponseTok !== undefined && rawResponseTok !== null + ? safeTokenCount(rawResponseTok) + : Math.max(0, outputTokens - thinkingTokens); const start = parseIsoMs(m.createdAt); const measuredDuration = requestDuration( @@ -642,11 +749,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { }); }); - // 末尾步骤上下文回填:若最后一个步骤缺少 contextBreakdown,则使用同轨迹最近一次有效的 generatorMetadata 补齐 + // 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐 if ( result.length > 0 && + !result[result.length - 1].isCompactionStep && !result[result.length - 1].contextBreakdown && - latestBreakdownChat + latestBreakdownChat && + (lastCompactionStepIdx < 0 || latestBreakdownStepIdx > lastCompactionStepIdx) ) { const lastStep = result[result.length - 1]; const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat); @@ -675,7 +784,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { * - **第 3 轮(前向任意显式模型回退)**:若仍未找到,忽略 Provider 限制,向前查找最近的任意显式模型步骤; * - **第 4 轮(后向任意显式模型兜底)**:最后向后查找最近的任意显式模型步骤。 * - * 命中后将 `modelKey` 补齐并将 `modelSource` 标记为 `'inferred_compaction'`,同时补齐缺失的 `responseModel` 与 `modelDisplayName`。 + * 命中后将 `modelKey` 补齐并将 `modelSource` 标记为 `'inferred_compaction'`,同时补齐同模型的 `responseModel` 与 `modelDisplayName`。 * * @param {Array} steps 已提取的步骤列表 * @returns {Array} 补齐压缩步骤模型归属后的步骤列表 @@ -710,11 +819,19 @@ export function inferCompactionStepModels(steps) { return step; } + const canDonate = (cand) => { + if (!isExplicitDonor(cand)) return false; + if (!needsModel) { + return cand.modelKey === step.modelKey && Boolean(cand.responseModel); + } + return true; + }; + let donor = null; // 第 1 轮:前向查找同 API Provider 的最近显式模型步骤 for (let j = idx - 1; j >= 0; j--) { - if (isExplicitDonor(steps[j]) && isProviderCompatible(step, steps[j])) { + if (canDonate(steps[j]) && isProviderCompatible(step, steps[j])) { donor = steps[j]; break; } @@ -722,7 +839,7 @@ export function inferCompactionStepModels(steps) { // 第 2 轮:后向查找同 API Provider 的最近显式模型步骤 if (!donor) { for (let j = idx + 1; j < steps.length; j++) { - if (isExplicitDonor(steps[j]) && isProviderCompatible(step, steps[j])) { + if (canDonate(steps[j]) && isProviderCompatible(step, steps[j])) { donor = steps[j]; break; } @@ -731,7 +848,7 @@ export function inferCompactionStepModels(steps) { // 第 3 轮:前向查找任意最近显式模型步骤 if (!donor) { for (let j = idx - 1; j >= 0; j--) { - if (isExplicitDonor(steps[j])) { + if (canDonate(steps[j])) { donor = steps[j]; break; } @@ -740,7 +857,7 @@ export function inferCompactionStepModels(steps) { // 第 4 轮:后向查找任意最近显式模型步骤 if (!donor) { for (let j = idx + 1; j < steps.length; j++) { - if (isExplicitDonor(steps[j])) { + if (canDonate(steps[j])) { donor = steps[j]; break; } @@ -751,12 +868,29 @@ export function inferCompactionStepModels(steps) { return step; } + const nextModelKey = needsModel ? donor.modelKey : step.modelKey; + const nextModelSource = needsModel ? 'inferred_compaction' : step.modelSource; + const donorSameModel = donor.modelKey === nextModelKey; + const nextResponseModel = + step.responseModel || (donorSameModel ? donor.responseModel || '' : ''); + const nextDisplayName = + step.modelDisplayName || (donorSameModel ? donor.modelDisplayName || '' : ''); + + if ( + nextModelKey === step.modelKey && + nextModelSource === step.modelSource && + nextResponseModel === (step.responseModel || '') && + nextDisplayName === (step.modelDisplayName || '') + ) { + return step; + } + return { ...step, - modelKey: needsModel ? donor.modelKey : step.modelKey, - modelSource: needsModel ? 'inferred_compaction' : step.modelSource, - responseModel: step.responseModel || donor.responseModel || '', - modelDisplayName: step.modelDisplayName || donor.modelDisplayName || '', + modelKey: nextModelKey, + modelSource: nextModelSource, + responseModel: nextResponseModel, + modelDisplayName: nextDisplayName, }; }); } @@ -777,6 +911,9 @@ export function inferCompactionStepModels(steps) { * @returns {object} 迁移并清洗后的步骤对象 */ export function normalizeCachedStep(step) { + if (!step || typeof step !== 'object' || Array.isArray(step)) { + return null; + } if (step.modelIdentityVersion !== MODEL_IDENTITY_VERSION) { const ambiguous = !step.modelKey || step.modelKey === 'MODEL_PLACEHOLDER_M418'; @@ -811,6 +948,32 @@ export function normalizeCachedStep(step) { } } + const safeIn = safeTokenCount(step.inputTokens); + const safeCache = safeTokenCount(step.cacheReadTokens); + const safeOut = safeTokenCount(step.outputTokens); + const safeThink = safeTokenCount(step.thinkingTokens); + const safeResp = + step.responseTokens !== undefined && step.responseTokens !== null + ? safeTokenCount(step.responseTokens) + : Math.max(0, safeOut - safeThink); + + if ( + step.inputTokens !== safeIn || + step.cacheReadTokens !== safeCache || + step.outputTokens !== safeOut || + step.thinkingTokens !== safeThink || + step.responseTokens !== safeResp + ) { + step = { + ...step, + inputTokens: safeIn, + cacheReadTokens: safeCache, + outputTokens: safeOut, + thinkingTokens: safeThink, + responseTokens: safeResp, + }; + } + if (step.measurementVersion === MEASUREMENT_VERSION) { return step; } @@ -1190,7 +1353,23 @@ function isPlannerStep(step) { function isCheckpointStep(step) { const t = String(step?.type || '').toUpperCase(); - return t === 'CORTEX_STEP_TYPE_CHECKPOINT' || t === 'CHECKPOINT'; + if ( + t === 'CORTEX_STEP_TYPE_CHECKPOINT' || + t === 'CHECKPOINT' || + t.includes('CHECKPOINT') || + Boolean(step?.checkpoint && typeof step.checkpoint === 'object') + ) { + return true; + } + if (t.includes('SYSTEM') && typeof step?.content === 'string') { + return /^\s*#\s*Resuming from a compaction\b/i.test(step.content); + } + return false; +} + +function isAuxiliaryMetaStep(step) { + const t = String(step?.type || '').toUpperCase(); + return t.includes('MEMENTO') || t.includes('EPHEMERAL'); } /** @@ -1538,6 +1717,16 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { * signature: string * } | null} */ +export function getMaxMeaningfulStepIndex(rawSteps = []) { + if (!Array.isArray(rawSteps) || rawSteps.length === 0) return -1; + let idx = rawSteps.length - 1; + while (idx > 0 && isAuxiliaryMetaStep(rawSteps[idx]) && isRawStepComplete(rawSteps[idx])) { + idx--; + } + const numId = Number(getStepStableId(rawSteps[idx], idx)); + return Number.isFinite(numId) ? numId : idx; +} + export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackStartMs = 0) { if (!isRunning) return null; if (!Array.isArray(rawSteps) || rawSteps.length === 0) { @@ -1556,26 +1745,39 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt let lastPlannerIdx = -1; let lastUserIdx = -1; + let lastCheckpointIdx = -1; for (let i = rawSteps.length - 1; i >= 0; i--) { const st = rawSteps[i]; const t = String(st?.type || '').toUpperCase(); + if (lastCheckpointIdx === -1 && isCheckpointStep(st)) { + lastCheckpointIdx = i; + } if (lastPlannerIdx === -1 && isPlannerStep(st)) { lastPlannerIdx = i; } if (lastUserIdx === -1 && t.includes('USER_INPUT')) { lastUserIdx = i; } - if (lastPlannerIdx !== -1 && lastUserIdx !== -1) break; + if (lastPlannerIdx !== -1 && lastUserIdx !== -1 && lastCheckpointIdx !== -1) break; } - const lastIdx = rawSteps.length - 1; + // 忽略末尾已完成的辅助元数据步骤(如 MEMENTO / EPHEMERAL_MESSAGE),避免掩盖正在运行或刚完成的压缩/工具步骤 + let lastIdx = rawSteps.length - 1; + while (lastIdx > 0 && isAuxiliaryMetaStep(rawSteps[lastIdx]) && isRawStepComplete(rawSteps[lastIdx])) { + lastIdx--; + } const lastStep = rawSteps[lastIdx]; const lastStepId = getStepStableId(lastStep, lastIdx); const lastComplete = isRawStepComplete(lastStep); - // 情况 A:最后一个步骤本身尚未完成(正在流式生成或正在执行该步骤) + // 情况 A:最后一个有效步骤本身尚未完成(正在流式生成、正在上下文压缩或正在执行工具) if (!lastComplete) { - const startMs = getRawStepStartMs(lastStep) || Math.floor(fallbackStartMs || 0); + const prevStepEndMs = + lastIdx > 0 + ? getRawStepFinishMs(rawSteps[lastIdx - 1]) || getRawStepEndMs(rawSteps[lastIdx - 1]) + : 0; + const startMs = + getRawStepStartMs(lastStep) || prevStepEndMs || Math.floor(fallbackStartMs || 0); if (isCheckpointStep(lastStep)) { return { @@ -1643,10 +1845,10 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt }; } - // 末尾是未完成的工具执行步骤 + // 末尾是未完成的工具执行步骤(仅关联压缩边界之后的最近一轮 PLANNER_RESPONSE) let matchedPlannerTool = null; let stepProgress = ''; - if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx) { + if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx && lastPlannerIdx > lastCheckpointIdx) { const pTools = getStepPlannerToolCalls(rawSteps[lastPlannerIdx]); const toolStepsAfterPlanner = []; for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) { @@ -1669,8 +1871,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt stepProgress = ''; } const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser; - const prevEndMs = lastIdx > 0 ? getRawStepFinishMs(rawSteps[lastIdx - 1]) : 0; - const resolvedStartMs = startMs || prevEndMs || 0; + const resolvedStartMs = startMs || prevStepEndMs || 0; const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label; return { @@ -1683,8 +1884,49 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt }; } - // 情况 B:末尾步骤已是完成态 (DONE),但整个会话仍处于 RUNNING 状态 - if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx) { + // 情况 A2:最新关键里程碑是已完成态 (DONE) 的上下文压缩步骤(如 transcript.jsonl 写入的 CHECKPOINT + // 或 RPC 压缩刚完成正组装压缩后上下文准备下一轮推理),严禁穿透回溯到压缩前的旧工具操作 + if (lastCheckpointIdx >= 0 && lastCheckpointIdx > lastPlannerIdx && lastCheckpointIdx > lastUserIdx) { + let hasPostCheckpointToolStep = false; + for (let k = lastCheckpointIdx + 1; k <= lastIdx; k++) { + const kt = String(rawSteps[k]?.type || '').toUpperCase(); + if ( + !isCheckpointStep(rawSteps[k]) && + !isAuxiliaryMetaStep(rawSteps[k]) && + !kt.includes('GENERIC') && + !kt.includes('SYSTEM') + ) { + hasPostCheckpointToolStep = true; + break; + } + } + if (!hasPostCheckpointToolStep) { + const cpStep = rawSteps[lastCheckpointIdx]; + const cpStepId = getStepStableId(cpStep, lastCheckpointIdx); + const prevBeforeCpMs = + lastCheckpointIdx > 0 + ? getRawStepFinishMs(rawSteps[lastCheckpointIdx - 1]) || + getRawStepEndMs(rawSteps[lastCheckpointIdx - 1]) + : 0; + const cpFinishMs = getRawStepFinishMs(cpStep); + const cpStartMs = + cpFinishMs || + getRawStepStartMs(cpStep) || + prevBeforeCpMs || + Math.floor(fallbackStartMs || 0); + return { + phase: 'compacting', + label: '上下文压缩', + detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '', + stepProgress: '', + startedAtMs: cpStartMs, + signature: cpFinishMs > 0 ? `compacting-done:${cpStepId}` : `compacting:${cpStepId}`, + }; + } + } + + // 情况 B:末尾步骤已是完成态 (DONE),但整个会话仍处于 RUNNING 状态(仅在压缩边界之后匹配上一轮 PLANNER_RESPONSE) + if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx && lastPlannerIdx > lastCheckpointIdx) { const plannerStep = rawSteps[lastPlannerIdx]; const plannerStepId = getStepStableId(plannerStep, lastPlannerIdx); const pTools = getStepPlannerToolCalls(plannerStep); diff --git a/sidecars/panel/src/App.js b/sidecars/panel/src/App.js index bdbe1c4..7e88132 100644 --- a/sidecars/panel/src/App.js +++ b/sidecars/panel/src/App.js @@ -51,6 +51,22 @@ export const App = defineComponent({ stageEl, ]); + function syncStepsBadge() { + const uiSt = uiStore.getState(); + const scopeForBadge = uiSt.activeView === 'steps' ? uiSt.selectedAgentScope : 'all'; + const { scopedConv } = resolveScopedConversation( + telemetryStore.getState().telemetry, + scopeForBadge, + uiSt.ctxInspectorAgentId + ); + const stepCount = scopedConv?.stepCount ?? 0; + topPillNav.setProps({ + items: VIEW_TABS.map((t) => + t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t + ), + }); + } + const unsubUi = uiStore.subscribe( (st) => st.activeView, (activeView) => { @@ -65,24 +81,13 @@ export const App = defineComponent({ } else if (activeView === 'steps') { stepsView.refs?.stepsScroll?.refresh(); stepsView.refs?.modelsScroll?.refresh(); + } else if (activeView === 'settings') { + settingsView.refs?.viewScrollbar?.refresh(); } + syncStepsBadge(); } ); - function syncStepsBadge() { - const { scopedConv } = resolveScopedConversation( - telemetryStore.getState().telemetry, - uiStore.getState().selectedAgentScope, - uiStore.getState().ctxInspectorAgentId - ); - const stepCount = scopedConv?.stepCount ?? 0; - topPillNav.setProps({ - items: VIEW_TABS.map((t) => - t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t - ), - }); - } - const unsubStepCount = telemetryStore.subscribe( (st) => ({ stepCount: st.telemetry?.activeConversation?.stepCount ?? 0, diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 948da0f..3c31f69 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -10,17 +10,22 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core import { formatTokensPrecise, formatUsd } from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; +let chartUidCounter = 0; + +function safeSlotTokens(v) { + const n = Number(v); + return Number.isFinite(n) && n > 0 ? n : 0; +} + /** * 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。 * 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平, * 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。 * - * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组 + * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组(长度 >= 2) * @returns {string} SVG `` 的 `d` 属性字符串 */ function buildSmoothSplinePath(points) { - if (!points.length) return ''; - if (points.length === 1) return `M ${points[0].x} ${points[0].y}`; let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; for (let i = 0; i < points.length - 1; i++) { const p0 = points[i]; @@ -77,10 +82,11 @@ export function createTrendAreaChart() { svg.setAttribute('class', 'trend-svg'); svg.setAttribute('aria-hidden', 'true'); - // 垂直线性渐变 + // 垂直线性渐变(每实例独立 ID,避免多图表挂载时 SVG url(#...) 冲突) + const gradId = `trend-area-grad-${++chartUidCounter}`; const defs = document.createElementNS(SVG_NS, 'defs'); const grad = document.createElementNS(SVG_NS, 'linearGradient'); - grad.setAttribute('id', 'trend-area-grad'); + grad.setAttribute('id', gradId); grad.setAttribute('x1', '0'); grad.setAttribute('y1', '0'); grad.setAttribute('x2', '0'); @@ -119,7 +125,7 @@ export function createTrendAreaChart() { svg.appendChild(vGridGroup); const areaPath = document.createElementNS(SVG_NS, 'path'); - areaPath.setAttribute('fill', 'url(#trend-area-grad)'); + areaPath.setAttribute('fill', `url(#${gradId})`); svg.appendChild(areaPath); const linePath = document.createElementNS(SVG_NS, 'path'); @@ -202,18 +208,20 @@ export function createTrendAreaChart() { patchAttr(tooltipEl, 'hidden', false); patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); - patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`); - patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`); + patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`); + const slotTok = safeSlotTokens(slot.tokens); + patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`); + const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; patchText( tipCostEl, - formatUsd(Number(slot.costUsd || 0), { + formatUsd(slotCost, { unpricedCalls: slot.unpricedCalls, - precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1, + precise: slotCost > 0 && slotCost < 0.1, }) ); const hasSubBreakdown = - Number(slot.tokens || 0) > 0 && + slotTok > 0 && (slot.inputTokens !== undefined || slot.cacheReadTokens !== undefined || slot.outputTokens !== undefined); @@ -221,7 +229,7 @@ export function createTrendAreaChart() { if (hasSubBreakdown) { patchText( tipSubEl, - `入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}` + `入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}` ); } @@ -268,7 +276,7 @@ export function createTrendAreaChart() { */ function update(series = []) { const slots = - Array.isArray(series) && series.length >= 2 + Array.isArray(series) && series.length >= 1 ? series : [ { label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 }, @@ -281,7 +289,7 @@ export function createTrendAreaChart() { let maxTokens = 0; let peakIdx = 0; for (let i = 0; i < slots.length; i++) { - const t = Number(slots[i].tokens || 0); + const t = safeSlotTokens(slots[i]?.tokens); if (t >= maxTokens) { maxTokens = t; peakIdx = i; @@ -289,22 +297,32 @@ export function createTrendAreaChart() { } const denom = Math.max(1, maxTokens); + const isSingle = slots.length === 1; const pts = slots.map((s, idx) => { - const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X; - const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0; + const tok = safeSlotTokens(s?.tokens); + const x = isSingle ? (LEFT_X + RIGHT_X) / 2 : LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X; + const ratio = maxTokens > 0 ? tok / denom : 0; const y = BOTTOM_Y - ratio * SPAN_Y; - return { x, y, tokens: Number(s.tokens || 0) }; + return { x, y, tokens: tok }; }); currentPts = pts; const sig = slots - .map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`) + .map((s) => `${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`) .join('|'); if (sig !== lastRenderSig) { lastRenderSig = sig; - const lineD = buildSmoothSplinePath(pts); - const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; + let lineD; + let areaD; + if (isSingle) { + const yStr = pts[0].y.toFixed(1); + lineD = `M ${LEFT_X.toFixed(1)} ${yStr} L ${RIGHT_X.toFixed(1)} ${yStr}`; + areaD = `${lineD} L ${RIGHT_X.toFixed(1)} ${BOTTOM_Y} L ${LEFT_X.toFixed(1)} ${BOTTOM_Y} Z`; + } else { + lineD = buildSmoothSplinePath(pts); + areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; + } patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', areaD); @@ -329,8 +347,8 @@ export function createTrendAreaChart() { vGridGroup.appendChild(vLine); } - const isFirst = i === 0; - const isLast = i === tickIndices.length - 1; + const isFirst = !isSingle && i === 0; + const isLast = !isSingle && i === tickIndices.length - 1; const pct = (pt.x / VIEW_W) * 100; const tickEl = h('span', { className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, @@ -371,7 +389,9 @@ export function createTrendAreaChart() { const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); - if (hoveredIdx >= 0 && hoveredIdx < slots.length) { + if (hoveredIdx >= slots.length) { + clearHover(); + } else if (hoveredIdx >= 0) { showHoverAtIndex(hoveredIdx); } } diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js index 898e7df..9a636b1 100644 --- a/sidecars/panel/src/components/layout/TopSessionHeader.js +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -113,22 +113,64 @@ export const TopSessionHeader = defineComponent({ lastActiveCascadeId = currentCascadeId; } + const actConv = telemetry?.activeConversation; const convs = telemetry?.conversations || []; - const latestTitle = convs[0]?.title ? `最新 (${convs[0].title})` : '跟随最新会话'; + const hostRouteId = telSt.hostRouteConversationId || ''; + const hostMatchedConv = hostRouteId + ? convs.find((c) => c.cascadeId === hostRouteId) || + (actConv?.cascadeId === hostRouteId ? actConv : null) + : null; + const defaultOptLabel = hostRouteId + ? hostMatchedConv?.title + ? `当前窗口 (${hostMatchedConv.title})` + : `当前窗口 (${hostRouteId.slice(0, 8)})` + : convs[0]?.title + ? `最新 (${convs[0].title})` + : '跟随最新会话'; + const defaultOptMeta = hostRouteId + ? hostMatchedConv + ? formatConvOptionMeta({ + stepCount: hostMatchedConv.stepCount, + subagentCount: hostMatchedConv.subagentCount, + totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents, + }) + : '' + : convs[0] + ? formatConvOptionMeta(convs[0]) + : ''; const options = [ - { value: '', label: latestTitle, meta: convs[0] ? formatConvOptionMeta(convs[0]) : '' }, + { value: '', label: defaultOptLabel, meta: defaultOptMeta }, ...convs.map((c) => ({ value: c.cascadeId, label: c.title || c.cascadeId.slice(0, 8), meta: formatConvOptionMeta(c), })), ]; + const lockedId = telSt.selectedConversationId; + if (lockedId && !convs.some((c) => c.cascadeId === lockedId)) { + const isLoadedLocked = actConv?.cascadeId === lockedId; + const lockedTitle = + isLoadedLocked && actConv?.title + ? actConv.title + : `已锁定会话 (${String(lockedId).slice(0, 8)})`; + const lockedMeta = isLoadedLocked + ? formatConvOptionMeta({ + stepCount: actConv.stepCount, + subagentCount: actConv.subagentCount, + totalStepCount: actConv.totalStepsAllAgents, + }) + : '已锁定'; + options.splice(1, 0, { + value: lockedId, + label: lockedTitle, + meta: lockedMeta, + }); + } convSelect.setProps({ modelValue: telSt.selectedConversationId, options, }); - const actConv = telemetry?.activeConversation; const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0); const aggregated = actConv?.aggregated; @@ -211,6 +253,7 @@ export const TopSessionHeader = defineComponent({ const unsubTelemetry = telemetryStore.subscribe( (st) => ({ selectedConversationId: st.selectedConversationId, + hostRouteConversationId: st.hostRouteConversationId, syncState: st.syncState, telemetry: st.telemetry, }), diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js new file mode 100644 index 0000000..866f874 --- /dev/null +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -0,0 +1,2184 @@ +/** + * @fileoverview 主窗口双栖挂载外壳 (WindowOverlayShell.js). + * + * 采用「分离式双 Shadow Host」架构,彻底规避宿主顶栏层叠上下文 (`z-0` / `overflow: hidden`) 裁切与路由重绘卸载问题: + * 1. `#ag-usage-monitor-capsule`:轻量顶栏胶囊,优先内嵌停靠至 `[class*="@container/titlebar"]` 右侧按钮组, + * 支持四级迟滞宽度自适应折叠(`wide` -> `compact` -> `minimal` -> `ring-only`),找不到顶栏时自动回退至右上角固定定位; + * 2. `#ag-usage-monitor-portal`:常驻 `document.body` 顶层的无遮挡浮层宿主,承载悬停速览卡与完整四标签 `App()` 监控面板, + * 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。 + */ + +import { App } from '../../App.js'; +import { ContextSegmentMeter } from '../ui/ContextSegmentMeter.js'; +import { + h, + isEventInside, + patchAttr, + patchClasses, + patchKeyedList, + patchText, +} from '../../core/domPatch.js'; +import { + formatElapsedSec, + formatMetric, + formatTokens, + formatUsd, + sampleSummary, + speedReasonText, +} from '../../core/formatters.js'; +import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js'; +import { createSvgIcon, SVG_NS } from '../../icons/SvgIcon.js'; +import { + extractHostRouteCascadeId, + fetchTelemetry, + formatAgentLabel, + getAgentBadgeClass, + normalizeClientTopbarSlots, + resolveScopedConversation, + startAsyncTelemetryLoop, + stopAsyncTelemetryLoop, + telemetryStore, +} from '../../store/telemetryStore.js'; +import { uiStore } from '../../store/uiStore.js'; +import { + buildQuotaPoolItems, + createPoolQuotaRow, + CTX_CHANNEL_DEFS, + quotaPoolRowSig, + syncPoolQuotaRow, +} from '../../views/LiveOverviewView.js'; + +const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule'; +const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; +const FLOATING_CARD_WIDTH = 492; +const MULTI_PANEL_WIDTH = 484; +const RING_RADIUS = 5.2; +const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); + +/** + * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 + * 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊。 + * + * @param {number} availWidth + * @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode + * @param {{ showMulti?: boolean }} [options] + * @returns {'wide'|'compact'|'minimal'|'ring-only'} + */ +export function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) { + if (availWidth == null || Number.isNaN(availWidth)) return 'wide'; + const showMulti = options?.showMulti !== false; + const effWidth = showMulti ? availWidth : availWidth + 76; + if (currentMode === 'wide') { + if (effWidth < 78) return 'ring-only'; + if (effWidth < 196) return 'minimal'; + if (effWidth < 256) return 'compact'; + return 'wide'; + } + if (currentMode === 'compact') { + if (effWidth >= 272) return 'wide'; + if (effWidth < 78) return 'ring-only'; + if (effWidth < 196) return 'minimal'; + return 'compact'; + } + if (currentMode === 'minimal') { + if (effWidth >= 272) return 'wide'; + if (effWidth >= 212) return 'compact'; + if (effWidth < 78) return 'ring-only'; + return 'minimal'; + } + if (effWidth >= 272) return 'wide'; + if (effWidth >= 212) return 'compact'; + if (effWidth >= 92) return 'minimal'; + return 'ring-only'; +} + +function findHostTitlebar() { + try { + if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { + return null; + } + return document.querySelector('[class*="@container/titlebar"]'); + } catch { + return null; + } +} + +function findNativeTopRightAnchor() { + try { + if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { + return null; + } + const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]'); + if (auxToggle?.closest) { + return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle; + } + const candidates = document.querySelectorAll('button, a, [role="button"]'); + for (const btn of candidates) { + const text = String(btn.textContent || '').trim(); + if ( + (text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) && + btn.getBoundingClientRect?.().top < 52 + ) { + return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn; + } + } + return document.querySelector('div.absolute.right-0.top-0'); + } catch { + return null; + } +} + +function getLeftSidebarRightEdge(vw) { + try { + if (typeof document !== 'undefined' && typeof document.querySelector === 'function') { + const navEl = document.querySelector('div[role="navigation"]'); + if (navEl?.getBoundingClientRect) { + const nr = navEl.getBoundingClientRect(); + if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) { + return Math.ceil(nr.right); + } + } + } + } catch { + // 忽略侧栏测量异常 + } + return 0; +} + +function resolveQuotaCapsuleSummary(quotas) { + if (!quotas) return null; + const activePool = quotas.activePool; + const weekly = quotas.weekly; + const candidates = []; + if (activePool && Number.isFinite(Number(activePool.remainingPct))) { + candidates.push({ + pct: Number(activePool.remainingPct), + label: activePool.poolLabel || activePool.family || '当前池', + windowTag: '5h', + }); + } + if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { + candidates.push({ + pct: Number(activePool.weeklyRemainingPct), + label: activePool.poolLabel || activePool.family || '当前池', + windowTag: '周', + }); + } + if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { + candidates.push({ + pct: Number(weekly.remainingPct), + label: weekly.poolFamily || '周限额', + windowTag: '周', + }); + } + if (!candidates.length) return null; + candidates.sort((a, b) => a.pct - b.pct); + const tightest = candidates[0]; + const rounded = Math.max(0, Math.min(100, Math.round(tightest.pct))); + return { + roundedPct: rounded, + shortText: `余 ${rounded}%`, + detailText: candidates + .map((c) => `${c.label} ${c.windowTag} 余 ${Math.max(0, Math.min(100, Math.round(c.pct)))}%`) + .join(' · '), + }; +} + +const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i; + +/** + * 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。 + * + * @param {object|null|undefined} quotas + * @param {'gemini_5h'|'gemini_weekly'|'claude_5h'|'claude_weekly'} slotKey + * @returns {{ roundedPct: number, shortText: string } | null} + */ +function resolveSpecificQuotaSlotSummary(quotas, slotKey) { + if (!quotas) return null; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const activePool = quotas.activePool || null; + const isClaude = slotKey.startsWith('claude_'); + const isWeekly = slotKey.endsWith('_weekly'); + let rawPct = null; + + if (isClaude) { + const claudePool = + pools.find((p) => p?.poolKey === 'Claude & GPT') || + pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || ''))); + const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + if (cand != null && Number.isFinite(Number(cand))) { + rawPct = Number(cand); + } else if ( + activePool && + THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) + ) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) { + rawPct = Number(fb); + } + } + } else { + const stdGemini = + pools.find((p) => p?.poolKey === 'Gemini') || + pools.find( + (p) => + /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && + !/carbon|argon/i.test(String(p?.poolKey || '')) + ); + const geminiFamilyPools = pools.filter((p) => + /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) + ); + const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + if (primaryCand != null && Number.isFinite(Number(primaryCand))) { + rawPct = Number(primaryCand); + } else { + const familyVals = geminiFamilyPools + .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .filter((v) => v != null && Number.isFinite(Number(v))) + .map(Number); + if (familyVals.length > 0) { + rawPct = Math.min(...familyVals); + } else if ( + activePool && + !THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) + ) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) { + rawPct = Number(fb); + } + } + if ( + rawPct == null && + isWeekly && + quotas.weekly && + !THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) && + quotas.weekly.remainingPct != null && + Number.isFinite(Number(quotas.weekly.remainingPct)) + ) { + rawPct = Number(quotas.weekly.remainingPct); + } + } + } + + if (rawPct == null || !Number.isFinite(rawPct)) return null; + const rounded = Math.max(0, Math.min(100, Math.round(rawPct))); + return { + roundedPct: rounded, + shortText: `余 ${rounded}%`, + }; +} + +function formatCompactCapsuleCost(stepCost) { + if (stepCost == null || !Number.isFinite(Number(stepCost))) return '--'; + const val = Math.max(0, Number(stepCost)); + if (val === 0) return '$0.00'; + if (val < 0.001) return '<$0.001'; + if (val < 1) return `$${val.toFixed(3)}`; + if (val < 100) return `$${val.toFixed(2)}`; + return `$${Math.round(val)}`; +} + +function formatCompactCapsuleTtft(ttftSec) { + if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; + const val = Number(ttftSec); + if (val < 1) return `${val.toFixed(2)}s`; + if (val < 100) return `${val.toFixed(1)}s`; + return `${Math.round(val)}s`; +} + +/** + * 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 + */ +export function mountWindowOverlay() { + if (typeof window === 'undefined' || typeof document === 'undefined') return null; + + // 先读取旧实例缓存的遥测快照与展开态(热升级时无缝承接数据与悬停状态,杜绝闪烁或关开),再安全卸载旧实例 + let carryOverTelemetry = null; + let carryOverTooltipOpen = false; + let carryOverPopoverOpen = false; + let carryOverMultiHoverOpen = false; + let carryOverMultiPinnedOpen = false; + let carryOverPointer = null; + try { + const prevOv = window.__AGUsageMonitorOverlay; + carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null; + carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.()); + carryOverPopoverOpen = Boolean(prevOv?.isOpen?.()); + carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.()); + carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.()); + carryOverPointer = prevOv?.getLastPointer?.() || null; + prevOv?.dispose?.(); + } catch { + // 忽略旧实例卸载异常 + } + try { + document.getElementById(CAPSULE_HOST_ID)?.remove?.(); + document.getElementById(PORTAL_HOST_ID)?.remove?.(); + } catch { + // 忽略残留节点清理异常 + } + + const bridgeConfig = getWindowBridgeConfig(); + const bundleVersion = String(bridgeConfig?.bundleVersion || ''); + const stylesCss = String(bridgeConfig?.stylesCss || ''); + const seedTelemetry = + (bridgeConfig?.initialTelemetry && typeof bridgeConfig.initialTelemetry === 'object' + ? bridgeConfig.initialTelemetry + : null) || carryOverTelemetry; + if (bridgeConfig?.initialTelemetry) { + delete bridgeConfig.initialTelemetry; + } + if (seedTelemetry) { + telemetryStore.setState({ + telemetry: seedTelemetry, + minuteTick: Math.floor(Date.now() / 30000), + syncState: 'idle', + }); + } + + let disposed = false; + let popoverOpen = false; + let tooltipOpen = false; + let multiOpen = false; + let multiPinned = false; + let hoverLeaveTimer = null; + let multiLeaveTimer = null; + const manualSubExpandMap = new Map(); + const multiTimersMap = new Map(); + let multiLiveTickTimer = null; + let hasPointerCoords = Boolean( + carryOverPointer && + Number.isFinite(carryOverPointer.x) && + Number.isFinite(carryOverPointer.y) + ); + let lastPointerX = hasPointerCoords ? carryOverPointer.x : -1; + let lastPointerY = hasPointerCoords ? carryOverPointer.y : -1; + let layoutMode = 'wide'; + let observedTitlebar = null; + let dockRafId = 0; + let lastObservedRouteId = extractHostRouteCascadeId(); + + function recordPointerCoords(e) { + if (e && Number.isFinite(e.clientX) && Number.isFinite(e.clientY)) { + lastPointerX = e.clientX; + lastPointerY = e.clientY; + hasPointerCoords = true; + } + } + + function isPointerStillInCapsule() { + if (!hasPointerCoords || document.hidden || !capsuleBtn.getBoundingClientRect) { + return false; + } + const r = capsuleBtn.getBoundingClientRect(); + if (r.width <= 0 || r.height <= 0) return false; + return ( + lastPointerX >= r.left - 1 && + lastPointerX <= r.right + 1 && + lastPointerY >= r.top - 1 && + lastPointerY <= r.bottom + 1 + ); + } + + function isPointerInMultiZone() { + if (!hasPointerCoords || document.hidden || multiBtn.hasAttribute('hidden')) { + return false; + } + if (multiBtn.getBoundingClientRect) { + const mr = multiBtn.getBoundingClientRect(); + if ( + mr.width > 0 && + mr.height > 0 && + lastPointerX >= mr.left - 1 && + lastPointerX <= mr.right + 1 && + lastPointerY >= mr.top - 1 && + lastPointerY <= mr.bottom + 10 + ) { + return true; + } + } + if (multiOpen && multiPanelEl.getBoundingClientRect) { + const pr = multiPanelEl.getBoundingClientRect(); + if ( + pr.width > 0 && + pr.height > 0 && + lastPointerX >= pr.left - 1 && + lastPointerX <= pr.right + 1 && + lastPointerY >= pr.top - 4 && + lastPointerY <= pr.bottom + 1 + ) { + return true; + } + } + return false; + } + + function scheduleMultiHoverClose() { + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + } + multiLeaveTimer = setTimeout(() => { + multiLeaveTimer = null; + if (disposed || multiPinned || !multiOpen) return; + let nativeHover = false; + try { + nativeHover = Boolean( + multiBtn.matches?.(':hover') || multiPanelEl.matches?.(':hover') + ); + } catch { + nativeHover = false; + } + if (nativeHover || isPointerInMultiZone()) { + return; + } + setMultiOpen(false); + }, 90); + } + + function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) { + const now = Date.now(); + const prev = multiTimersMap.get(timerKey); + let startMs = prev?.startMs || 0; + if (!prev || prev.sig !== sig) { + const validRaw = Number(rawStartMs || 0); + startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; + } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { + startMs = Number(rawStartMs); + } + multiTimersMap.set(timerKey, { sig, startMs, el: targetEl }); + const elapsedSec = Math.max(0, (now - startMs) / 1000); + patchText(targetEl, formatElapsedSec(elapsedSec)); + } + + function tickMultiElapsedDisplay() { + const now = Date.now(); + for (const entry of multiTimersMap.values()) { + if (!entry?.el) continue; + const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; + patchText(entry.el, formatElapsedSec(elapsedSec)); + } + } + + function stopMultiLiveTicker() { + if (multiLiveTickTimer) { + clearInterval(multiLiveTickTimer); + multiLiveTickTimer = null; + } + multiTimersMap.clear(); + } + + function ensureMultiLiveTicker() { + if (multiTimersMap.size === 0) { + stopMultiLiveTicker(); + return; + } + if (!multiLiveTickTimer) { + multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000); + } + } + + function inspectSessionInMonitor(cascadeId) { + if (!cascadeId || cascadeId === 'current') return; + uiStore.setState({ + activeView: 'overview', + selectedAgentScope: 'all', + ctxInspectorAgentId: 'auto', + }); + telemetryStore.setState({ selectedConversationId: cascadeId }); + void fetchTelemetry({ force: false }); + setMultiOpen(false); + setPopoverOpen(true); + } + + // --- 1. 创建顶栏双胶囊 Shadow Host(左:多会话实时信息;右:单会话指标胶囊) --- + const capsuleHost = document.createElement('div'); + capsuleHost.id = CAPSULE_HOST_ID; + capsuleHost.className = 'wm-capsule-host'; + capsuleHost.setAttribute('data-dock', 'fixed'); + capsuleHost.setAttribute('data-layout', layoutMode); + const capsuleShadow = capsuleHost.attachShadow({ mode: 'open' }); + + const capsuleStyleEl = document.createElement('style'); + capsuleStyleEl.textContent = stylesCss; + capsuleShadow.appendChild(capsuleStyleEl); + + // 左侧无边框多会话实时触发按钮(固定预占宽度,不随运行数跳动) + const multiDot = h('span', { className: 'wm-multi-dot' }); + const multiLabel = h('span', { className: 'wm-multi-label', text: '0 运行中' }); + const multiBtn = h( + 'button', + { + type: 'button', + className: 'wm-multi-btn', + 'aria-label': '多会话实时信息', + 'aria-expanded': 'false', + onClick: (e) => { + e.stopPropagation(); + if (multiOpen && multiPinned) { + setMultiOpen(false); + } else { + setMultiOpen(true, { pinned: true }); + } + }, + onContextmenu: (e) => { + e.preventDefault(); + e.stopPropagation(); + void fetchTelemetry({ force: true }); + }, + onMouseenter: (e) => { + recordPointerCoords(e); + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + if (!popoverOpen && !multiPinned) { + setMultiOpen(true, { pinned: false }); + } + }, + onMouseleave: (e) => { + recordPointerCoords(e); + if (!multiPinned) { + scheduleMultiHoverClose(); + } + }, + }, + [multiDot, multiLabel] + ); + + // 构建可复用的预占胶囊槽位节点(仅当槽位配置为 context 时挂载环形 SVG,运行期仅就地更新文本与属性) + function createCapsuleSlot(slotIndex, initialMetric) { + const ringSvg = document.createElementNS(SVG_NS, 'svg'); + ringSvg.setAttribute('viewBox', '0 0 14 14'); + ringSvg.setAttribute('class', 'wm-ring-svg'); + ringSvg.setAttribute('aria-hidden', 'true'); + + const ringTrack = document.createElementNS(SVG_NS, 'circle'); + ringTrack.setAttribute('cx', '7'); + ringTrack.setAttribute('cy', '7'); + ringTrack.setAttribute('r', String(RING_RADIUS)); + ringTrack.setAttribute('class', 'wm-ring-track'); + + const ringFill = document.createElementNS(SVG_NS, 'circle'); + ringFill.setAttribute('cx', '7'); + ringFill.setAttribute('cy', '7'); + ringFill.setAttribute('r', String(RING_RADIUS)); + ringFill.setAttribute('class', 'wm-ring-fill'); + ringFill.setAttribute('stroke-dasharray', String(RING_CIRCUMFERENCE)); + ringFill.setAttribute('stroke-dashoffset', String(RING_CIRCUMFERENCE)); + + ringSvg.appendChild(ringTrack); + ringSvg.appendChild(ringFill); + + const isCtx = initialMetric === 'context'; + const textSpan = h('span', { + className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text', + text: isCtx ? '--%' : initialMetric === 'tps' ? '-- t/s' : '余 --%', + }); + const el = h( + 'span', + { + className: isCtx + ? 'wm-cap-slot wm-ctx-seg' + : initialMetric === 'tps' + ? 'wm-cap-slot wm-seg-speed' + : 'wm-cap-slot wm-seg-quota', + 'data-slot-idx': String(slotIndex), + 'data-metric': initialMetric, + 'data-vis-rank': String(slotIndex + 1), + }, + isCtx ? [ringSvg, textSpan] : [textSpan] + ); + + return { + el, + ringSvg, + ringFill, + textSpan, + ringMounted: isCtx, + }; + } + + const capsuleSlots = [ + createCapsuleSlot(0, 'context'), + createCapsuleSlot(1, 'tps'), + createCapsuleSlot(2, 'quota_auto'), + ]; + const sep0 = h('span', { className: 'wm-sep wm-sep-speed', 'data-sep-for-rank': '2' }); + const sep1 = h('span', { className: 'wm-sep wm-sep-quota', 'data-sep-for-rank': '3' }); + let lastShowMulti = true; + + const updateDot = h('span', { className: 'wm-update-dot', hidden: true }); + + const capsuleBtn = h( + 'button', + { + type: 'button', + className: 'wm-capsule-btn', + 'aria-label': '用量与速度监控', + 'aria-expanded': 'false', + onClick: (e) => { + e.stopPropagation(); + setPopoverOpen(!popoverOpen); + }, + onContextmenu: (e) => { + e.preventDefault(); + e.stopPropagation(); + void fetchTelemetry({ force: true }); + }, + onMouseenter: (e) => { + recordPointerCoords(e); + if (hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + hoverLeaveTimer = null; + } + if (!popoverOpen && !multiPinned) { + if (multiOpen) { + setMultiOpen(false); + } + setTooltipOpen(true); + } + }, + onMouseleave: (e) => { + recordPointerCoords(e); + if (hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + } + hoverLeaveTimer = setTimeout(() => { + hoverLeaveTimer = null; + if (disposed || popoverOpen) return; + let nativeHover = false; + try { + nativeHover = Boolean(capsuleBtn.matches?.(':hover')); + } catch { + nativeHover = false; + } + if (nativeHover || isPointerStillInCapsule()) { + return; + } + setTooltipOpen(false); + }, 40); + }, + }, + [capsuleSlots[0].el, sep0, capsuleSlots[1].el, sep1, capsuleSlots[2].el, updateDot] + ); + capsuleShadow.appendChild(multiBtn); + capsuleShadow.appendChild(capsuleBtn); + + // --- 2. 创建 Body 顶层浮层 Portal Shadow Host --- + const portalHost = document.createElement('div'); + portalHost.id = PORTAL_HOST_ID; + portalHost.className = 'wm-portal-host'; + const portalShadow = portalHost.attachShadow({ mode: 'open' }); + + const portalStyleEl = document.createElement('style'); + portalStyleEl.textContent = stylesCss; + portalShadow.appendChild(portalStyleEl); + + // 悬停全景概览浮层(复用实时概览三卡片架构:4格测速矩阵 + 10通道上下文窗口 + 动态配额池,全槽位预占) + const hoverTpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); + const hoverTpsSub = h('span', { className: 'cell-sub', text: '模型未知' }); + const hoverPulseDot = createSvgIcon('dot', { size: 10 }); + + const hoverTtftVal = h('strong', { className: 'cell-value', text: '—' }); + const hoverTtftSub = h('span', { className: 'cell-sub', text: '均值 —' }); + + const hoverAvgVal = h('strong', { className: 'cell-value', text: '—' }); + const hoverAvgSub = h('span', { className: 'cell-sub', text: '有效 0/0 步' }); + + const hoverCostVal = h('strong', { className: 'cell-value', text: '—' }); + const hoverCacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累计 $0.00' }); + + const hoverMatrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '实时指标' }, [ + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [h('span', { text: '输出速度' }), hoverPulseDot]), + hoverTpsVal, + hoverTpsSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '首字延迟' }), + createSvgIcon('clock', { size: 11 }), + ]), + hoverTtftVal, + hoverTtftSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '平均速度' }), + createSvgIcon('pulse', { size: 11 }), + ]), + hoverAvgVal, + hoverAvgSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '本次费用' }), + createSvgIcon('bolt', { size: 11 }), + ]), + hoverCostVal, + hoverCacheSub, + ]), + ]); + + const hoverCtxAgentBadge = h('span', { + className: 'agent-badge badge-main', + hidden: true, + text: '主代理', + }); + const hoverCtxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' }); + const hoverCtxSegmentBar = ContextSegmentMeter({ context: {} }); + + // 固定预占 10 个双列图例槽位,排序时仅就地替换色块类名与文本,不调用 appendChild 移动节点 + const hoverLegendSlots = CTX_CHANNEL_DEFS.map((ch) => { + const swatchEl = h('span', { className: `swatch ${ch.segClass}` }); + const labelEl = h('span', { text: ch.label }); + const valEl = h('strong', { className: 'text-mono', text: '0' }); + const itemEl = h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [swatchEl, labelEl]), + valEl, + ]); + return { itemEl, swatchEl, labelEl, valEl }; + }); + + const hoverCtxLegendGrid = h( + 'div', + { className: 'ctx-legend-grid' }, + hoverLegendSlots.map((slot) => slot.itemEl) + ); + + const hoverCtxPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('layers', { size: 13 }), + h('span', { text: '上下文窗口' }), + hoverCtxAgentBadge, + ]), + h('span', { className: 'panel-meta' }, [hoverCtxSummaryText]), + ]), + hoverCtxSegmentBar.el, + hoverCtxLegendGrid, + ]); + + const hoverTierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); + const hoverPoolsListEl = h('div', { className: 'wm-hover-quota-pools' }); + patchKeyedList( + hoverPoolsListEl, + buildQuotaPoolItems(null, 0, { isPending: true }), + { + keyFn: (item) => item.key, + sigFn: quotaPoolRowSig, + createRow: createPoolQuotaRow, + updateRow: syncPoolQuotaRow, + } + ); + const hoverWkFootLeft = h('span', { className: 'text-muted', text: '本周累计: 0 ($0.00)' }); + const hoverWkFootRight = h('span', { className: 'text-muted', text: '本周调用: 0 次' }); + + const hoverQuotaPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + h('span', { text: '可用额度' }), + ]), + hoverTierBadge, + ]), + hoverPoolsListEl, + h('div', { className: 'panel-header wm-hover-quota-foot' }, [ + hoverWkFootLeft, + hoverWkFootRight, + ]), + ]); + + const hoverTipEl = h( + 'div', + { + className: 'wm-hover-tip', + hidden: true, + }, + [hoverMatrixEl, hoverCtxPanel, hoverQuotaPanel] + ); + + // 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新) + function createMultiLiveSubRow() { + const subBadge = h('span', { className: 'agent-badge badge-sub-1', text: '子1' }); + const subRole = h('span', { className: 'live-sub-role', text: '子代理' }); + const subSummary = h('span', { className: 'live-sub-summary', text: '' }); + const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' }); + const rowEl = h('div', { className: 'live-sub-row' }, [ + h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]), + subElapsed, + ]); + return { + el: rowEl, + refs: { rowEl, subBadge, subRole, subSummary, subElapsed }, + }; + } + + function createMultiLiveTaskCard() { + const dotIcon = createSvgIcon('dot', { size: 11 }); + patchClasses(dotIcon, { 'is-pulsing': true }); + const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); + const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' }); + const hereTagEl = h('span', { + className: 'wm-session-tag is-here', + hidden: true, + text: '本窗', + }); + const metricsEl = h('span', { + className: 'wm-task-metrics text-mono', + hidden: true, + text: '', + }); + const subToggleBtn = h('button', { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + text: '子代理 (0) ▸', + }); + const elapsedEl = h('span', { + className: 'live-activity-elapsed text-mono', + text: '0s', + }); + + const headerEl = h('div', { className: 'live-task-header' }, [ + h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]), + h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]), + ]); + + const mainBadge = h('span', { + className: 'agent-badge badge-main', + hidden: true, + text: '主', + }); + const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' }); + const mainProgress = h('span', { + className: 'live-activity-progress text-mono', + hidden: true, + text: '', + }); + const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); + const mainDetail = h('span', { + className: 'live-activity-detail', + hidden: true, + text: '', + }); + + const mainRowEl = h('div', { className: 'live-task-main-row' }, [ + mainBadge, + mainPhase, + mainProgress, + mainSep, + mainDetail, + ]); + + const subListEl = h('div', { className: 'live-sub-list', hidden: true }); + const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + + return { + el: cardEl, + refs: { + cardEl, + dotIcon, + titleEl, + hereTagEl, + metricsEl, + subToggleBtn, + elapsedEl, + mainBadge, + mainPhase, + mainProgress, + mainSep, + mainDetail, + subListEl, + }, + }; + } + + const multiPinBadge = h('span', { className: 'wm-pin-badge', hidden: true, text: '已固定' }); + const multiRunningMetaEl = h('span', { className: 'panel-meta text-mono', text: '读取中...' }); + const multiEmptyHintEl = h('span', { + className: 'wm-multi-empty-hint', + text: '悬停速览 · 左键固定', + }); + const multiEmptyEl = h('div', { className: 'wm-multi-empty' }, [ + h('span', { className: 'wm-multi-empty-left' }, [ + h('span', { className: 'wm-idle-dot' }), + h('span', { text: '当前暂无在线运行的会话' }), + ]), + multiEmptyHintEl, + ]); + const multiRunningListEl = h('div', { + className: 'live-activity-list', + hidden: true, + 'aria-live': 'polite', + }); + + const multiHeaderEl = h('div', { className: 'panel-header wm-multi-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + h('span', { text: '实时运行会话' }), + multiPinBadge, + ]), + multiRunningMetaEl, + ]); + + const multiPanelEl = h( + 'div', + { + className: 'wm-multi-panel', + role: 'dialog', + 'aria-label': '多会话实时信息面板', + hidden: true, + onMouseenter: (e) => { + recordPointerCoords(e); + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + }, + onMouseleave: (e) => { + recordPointerCoords(e); + if (!multiPinned) { + scheduleMultiHoverClose(); + } + }, + }, + [multiHeaderEl, multiEmptyEl, multiRunningListEl] + ); + + // 完整四标签悬浮容器 + const appInstance = App(); + const popoverEl = h( + 'div', + { + className: 'wm-popover-panel', + role: 'dialog', + 'aria-label': '用量与速度监控面板', + hidden: true, + }, + [appInstance.el] + ); + + portalShadow.appendChild(multiPanelEl); + portalShadow.appendChild(hoverTipEl); + portalShadow.appendChild(popoverEl); + (document.body || document.documentElement).appendChild(portalHost); + + // --- 3. 几何测量、顶栏停靠与防溢出定位 --- + function updateFixedFallbackPosition() { + if (capsuleHost.getAttribute('data-dock') === 'flow') { + capsuleHost.style.top = ''; + capsuleHost.style.right = ''; + return; + } + try { + const vw = Number(window.innerWidth || 1280); + let rightOffset = 144; + const anchor = findNativeTopRightAnchor(); + if (anchor?.getBoundingClientRect) { + const r = anchor.getBoundingClientRect(); + if (r.width > 0 && r.left > 0 && r.left < vw) { + rightOffset = Math.max(144, Math.ceil(vw - r.left + 6)); + } + } + capsuleHost.style.top = '7px'; + capsuleHost.style.right = `${rightOffset}px`; + } catch { + // 忽略回退坐标计算异常 + } + } + + function measureAvailableTitlebarWidth(titlebar) { + try { + if (titlebar?.getBoundingClientRect) { + const tbRect = titlebar.getBoundingClientRect(); + if (tbRect.width > 0) { + const titleEl = titlebar.firstElementChild; + const titleInner = titleEl?.firstElementChild; + const contentStart = titleInner?.getBoundingClientRect + ? Math.max(8, titleInner.getBoundingClientRect().left - tbRect.left) + : tbRect.left < 168 + ? 168 - tbRect.left + : 12; + const minTitleWidth = 180; + let siblingButtonsWidth = 64; + let rightPad = 8; + const rightGroup = capsuleHost.parentElement; + if (rightGroup && rightGroup !== titlebar) { + const auxOpen = + typeof document.querySelector === 'function' && + Boolean(document.querySelector('[data-testid="aux-pane-sash"]')); + const root = + typeof document.querySelector === 'function' + ? document.querySelector('div.h-screen.w-screen') + : null; + const rightClusterVar = + root?.style?.getPropertyValue?.('--right-cluster-width')?.trim() || ''; + if (auxOpen) { + rightPad = 8; + } else if (rightClusterVar) { + rightPad = Math.max(8, (parseFloat(rightClusterVar) || 44) - 4); + } else if (typeof window.getComputedStyle === 'function') { + rightPad = parseFloat(window.getComputedStyle(rightGroup).paddingRight) || 0; + } + if (rightGroup.children) { + let sum = 0; + for (const child of rightGroup.children) { + if (child !== capsuleHost && child.getBoundingClientRect) { + sum += child.getBoundingClientRect().width; + } + } + if (sum > 0) siblingButtonsWidth = sum + 8; + } + } + return tbRect.width - contentStart - minTitleWidth - rightPad - siblingButtonsWidth; + } + } + if (window.innerWidth) { + return window.innerWidth - 360; + } + } catch { + // 忽略测量异常 + } + return 320; + } + + function positionFloatingElements() { + if (disposed || !capsuleBtn.getBoundingClientRect) return; + try { + const bRect = capsuleBtn.getBoundingClientRect(); + if (bRect.width === 0 && bRect.height === 0) return; + const vw = Number(window.innerWidth || 1280); + const vh = Number(window.innerHeight || 800); + const navRight = getLeftSidebarRightEdge(vw); + const minLeft = navRight > 0 ? Math.max(12, navRight + 12) : 12; + const defaultCardW = Math.min(FLOATING_CARD_WIDTH, Math.max(280, vw - 24)); + const defaultMultiW = Math.min(MULTI_PANEL_WIDTH, Math.max(280, vw - 24)); + + if (multiOpen) { + const mRect = multiBtn.getBoundingClientRect?.() || bRect; + const anchorRect = mRect.width > 0 || mRect.height > 0 ? mRect : bRect; + const rawW = + Number(multiPanelEl.offsetWidth) || + Number(multiPanelEl.getBoundingClientRect?.().width) || + defaultMultiW; + const panelW = Math.min(rawW, Math.max(280, vw - minLeft - 12)); + const panelH = + Number(multiPanelEl.offsetHeight) || + Number(multiPanelEl.getBoundingClientRect?.().height) || + 320; + let top = Math.max(38, Math.round(anchorRect.bottom + 6)); + if (top + panelH > vh - 8 && anchorRect.top > panelH + 12) { + top = Math.round(anchorRect.top - panelH - 6); + } + let left = Math.round(anchorRect.left); + left = Math.min(left, vw - panelW - 12); + left = Math.max(minLeft, left); + multiPanelEl.style.top = `${top}px`; + multiPanelEl.style.left = `${left}px`; + multiPanelEl.style.maxHeight = `${Math.max(240, vh - top - 12)}px`; + } + + if (popoverOpen) { + const rawW = + Number(popoverEl.offsetWidth) || + Number(popoverEl.getBoundingClientRect?.().width) || + defaultCardW; + const panelW = Math.min(rawW, Math.max(280, vw - minLeft - 12)); + const top = Math.max(38, Math.min(vh - 140, Math.round(bRect.bottom + 6))); + let left = Math.round(bRect.right - panelW); + left = Math.min(left, vw - panelW - 12); + left = Math.max(minLeft, left); + popoverEl.style.top = `${top}px`; + popoverEl.style.left = `${left}px`; + popoverEl.style.maxHeight = `${Math.max(240, vh - top - 12)}px`; + } + + if (tooltipOpen && !popoverOpen && !multiOpen) { + const rawW = + Number(hoverTipEl.offsetWidth) || + Number(hoverTipEl.getBoundingClientRect?.().width) || + defaultCardW; + const tipW = Math.min(rawW, Math.max(280, vw - minLeft - 12)); + const tipH = + Number(hoverTipEl.offsetHeight) || + Number(hoverTipEl.getBoundingClientRect?.().height) || + 480; + let top = Math.max(38, Math.round(bRect.bottom + 6)); + if (top + tipH > vh - 8 && bRect.top > tipH + 12) { + top = Math.round(bRect.top - tipH - 6); + } + let left = Math.round(bRect.right - tipW); + left = Math.min(left, vw - tipW - 12); + left = Math.max(minLeft, left); + hoverTipEl.style.top = `${top}px`; + hoverTipEl.style.left = `${left}px`; + hoverTipEl.style.maxHeight = `${Math.max(240, vh - top - 12)}px`; + } + } catch { + // 忽略定位异常 + } + } + + function updateResponsiveLayout() { + if (disposed) return; + const titlebar = findHostTitlebar(); + const avail = measureAvailableTitlebarWidth(titlebar); + const showMulti = + telemetryStore.getState().telemetry?.settings?.showTopbarMultiSession !== false; + const nextMode = computeCapsuleLayoutMode(avail, layoutMode, { showMulti }); + if (nextMode !== layoutMode) { + layoutMode = nextMode; + capsuleHost.setAttribute('data-layout', layoutMode); + } + if (capsuleHost.getAttribute('data-dock') === 'fixed') { + updateFixedFallbackPosition(); + } + if (popoverOpen || tooltipOpen || multiOpen) { + positionFloatingElements(); + } + } + + let resizeObserver = null; + + function ensureCapsuleDocked() { + if (disposed) return false; + const bodyOrDoc = document.body || document.documentElement; + if (bodyOrDoc && !portalHost.isConnected) { + bodyOrDoc.appendChild(portalHost); + } + + const titlebar = findHostTitlebar(); + if (titlebar) { + let targetContainer = titlebar; + try { + const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild; + if (rightGroup && rightGroup !== titlebar.firstElementChild) { + targetContainer = rightGroup; + } + } catch { + // 忽略子选择器不兼容场景 + } + + if (capsuleHost.parentElement !== targetContainer) { + if (targetContainer.firstChild && targetContainer !== titlebar) { + targetContainer.insertBefore(capsuleHost, targetContainer.firstChild); + } else { + targetContainer.appendChild(capsuleHost); + } + } + patchAttr(capsuleHost, 'data-dock', 'flow'); + if (capsuleHost.style.top) capsuleHost.style.top = ''; + if (capsuleHost.style.right) capsuleHost.style.right = ''; + + if (observedTitlebar !== titlebar) { + observedTitlebar = titlebar; + try { + if (resizeObserver) { + resizeObserver.disconnect(); + resizeObserver.observe(titlebar); + if (document.body) resizeObserver.observe(document.body); + } + } catch { + // 忽略观察器异常 + } + } + } else if (bodyOrDoc) { + if (capsuleHost.parentElement !== bodyOrDoc) { + bodyOrDoc.appendChild(capsuleHost); + } + patchAttr(capsuleHost, 'data-dock', 'fixed'); + updateFixedFallbackPosition(); + } + + updateResponsiveLayout(); + return Boolean(capsuleHost.isConnected && portalHost.isConnected); + } + + function scheduleDockSync() { + if (disposed) return; + if (typeof requestAnimationFrame === 'function') { + if (dockRafId) return; + dockRafId = requestAnimationFrame(() => { + dockRafId = 0; + ensureCapsuleDocked(); + }); + } else { + ensureCapsuleDocked(); + } + } + + function refreshActiveViewScrollbars() { + const activeView = uiStore.getState().activeView; + const refs = appInstance.refs; + if (activeView === 'overview') { + refs?.overviewView?.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'consumption') { + refs?.consumptionView?.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'steps') { + refs?.stepsView?.refs?.stepsScroll?.refresh(); + refs?.stepsView?.refs?.modelsScroll?.refresh(); + } else if (activeView === 'settings') { + refs?.settingsView?.refs?.viewScrollbar?.refresh(); + } + } + + function setMultiOpen(nextOpen, { pinned = false, instant = false } = {}) { + const targetOpen = Boolean(nextOpen); + if (targetOpen && multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + if (targetOpen) { + setTooltipOpen(false); + if (pinned && popoverOpen) { + setPopoverOpen(false); + } + } + const nextPinned = targetOpen ? Boolean(pinned) : false; + const stateChanged = multiOpen !== targetOpen || multiPinned !== nextPinned; + multiOpen = targetOpen; + multiPinned = nextPinned; + patchClasses(multiBtn, { 'is-open': multiOpen && multiPinned }); + patchAttr(multiBtn, 'aria-expanded', multiOpen ? 'true' : 'false'); + patchAttr(multiPinBadge, 'hidden', !multiPinned); + if (!stateChanged) return; + patchClasses(multiPanelEl, { 'is-instant': Boolean(instant && multiOpen) }); + patchAttr(multiPanelEl, 'hidden', !multiOpen); + if (multiOpen) { + positionFloatingElements(); + if (typeof requestAnimationFrame === 'function') { + requestAnimationFrame(() => positionFloatingElements()); + } + } + } + + function setTooltipOpen(nextOpen, { instant = false } = {}) { + const targetOpen = Boolean(nextOpen && !popoverOpen && !(multiOpen && multiPinned)); + if (targetOpen && hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + hoverLeaveTimer = null; + } + if (targetOpen && multiOpen && !multiPinned) { + setMultiOpen(false); + } + if (tooltipOpen === targetOpen) return; + tooltipOpen = targetOpen; + patchClasses(hoverTipEl, { 'is-instant': Boolean(instant && targetOpen) }); + patchAttr(hoverTipEl, 'hidden', !tooltipOpen); + if (tooltipOpen) { + positionFloatingElements(); + } + } + + function setPopoverOpen(nextOpen, { instant = false } = {}) { + const targetOpen = Boolean(nextOpen); + if (targetOpen) { + setTooltipOpen(false); + if (multiOpen) { + setMultiOpen(false); + } + } + if (popoverOpen === targetOpen) return; + popoverOpen = targetOpen; + patchClasses(capsuleBtn, { 'is-open': popoverOpen }); + patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) }); + patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false'); + patchAttr(popoverEl, 'hidden', !popoverOpen); + if (popoverOpen) { + positionFloatingElements(); + if (typeof requestAnimationFrame === 'function') { + requestAnimationFrame(() => { + positionFloatingElements(); + refreshActiveViewScrollbars(); + }); + } else { + refreshActiveViewScrollbars(); + } + } + } + + function resolveCapsuleSlotPresentation(metricKey, slotCtx) { + if (metricKey === 'none') { + return { + hidden: true, + metric: 'none', + segClass: 'wm-cap-slot', + textClass: 'wm-slot-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: '', + running: false, + warn: false, + danger: false, + }; + } + + if (metricKey === 'context') { + if (!slotCtx.hasTelemetry) { + return { + hidden: false, + metric: 'context', + segClass: 'wm-cap-slot wm-ctx-seg', + textClass: 'wm-slot-text wm-ctx-pct', + showRing: true, + dashOffset: RING_CIRCUMFERENCE, + text: '--%', + running: false, + warn: false, + danger: false, + }; + } + const isDanger = slotCtx.usedPct >= 88; + const isWarn = !isDanger && slotCtx.usedPct >= 70; + return { + hidden: false, + metric: 'context', + segClass: 'wm-cap-slot wm-ctx-seg', + textClass: 'wm-slot-text wm-ctx-pct', + showRing: true, + dashOffset: slotCtx.dashOffset, + text: `${Math.round(slotCtx.usedPct)}%`, + running: false, + warn: isWarn, + danger: isDanger, + }; + } + + if (metricKey === 'tps') { + if (!slotCtx.hasTelemetry) { + return { + hidden: false, + metric: 'tps', + segClass: 'wm-cap-slot wm-seg-speed', + textClass: 'wm-slot-text wm-speed-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: '-- t/s', + running: false, + warn: false, + danger: false, + }; + } + const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0; + const tpsText = hasValidTps + ? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s` + : slotCtx.isRunning + ? '生成中' + : '待命'; + return { + hidden: false, + metric: 'tps', + segClass: 'wm-cap-slot wm-seg-speed', + textClass: 'wm-slot-text wm-speed-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: tpsText, + running: slotCtx.isRunning, + warn: false, + danger: false, + }; + } + + if (metricKey === 'ttft') { + const val = slotCtx.hasTelemetry ? slotCtx.ttft : null; + const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0; + const numVal = valid ? Number(val) : 0; + const isDanger = valid && numVal >= 30; + const isWarn = valid && !isDanger && numVal >= 15; + return { + hidden: false, + metric: 'ttft', + segClass: 'wm-cap-slot wm-seg-ttft', + textClass: 'wm-slot-text wm-ttft-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: valid ? formatCompactCapsuleTtft(numVal) : '--s', + running: false, + warn: isWarn, + danger: isDanger, + }; + } + + if (metricKey === 'cost') { + const costVal = slotCtx.hasTelemetry ? slotCtx.stepCost : null; + return { + hidden: false, + metric: 'cost', + segClass: 'wm-cap-slot wm-seg-cost', + textClass: 'wm-slot-text wm-cost-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--', + running: false, + warn: false, + danger: false, + }; + } + + const quotaSum = !slotCtx.hasTelemetry + ? null + : metricKey === 'quota_auto' + ? resolveQuotaCapsuleSummary(slotCtx.quotas) + : resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey); + const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15); + const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30); + return { + hidden: false, + metric: metricKey, + segClass: 'wm-cap-slot wm-seg-quota', + textClass: 'wm-slot-text wm-quota-text', + showRing: false, + dashOffset: RING_CIRCUMFERENCE, + text: quotaSum ? quotaSum.shortText : '余 --%', + running: false, + warn: isWarn, + danger: isDanger, + }; + } + + function applyCapsuleSlots(slotKeys, slotCtx) { + const presList = slotKeys.map((key) => resolveCapsuleSlotPresentation(key, slotCtx)); + let visRank = 0; + const visRanks = [0, 0, 0]; + for (let i = 0; i < 3; i += 1) { + const slot = capsuleSlots[i]; + const pres = presList[i]; + if (pres.hidden) { + patchAttr(slot.el, 'hidden', true); + patchAttr(slot.el, 'data-metric', 'none'); + patchAttr(slot.el, 'data-vis-rank', ''); + continue; + } + visRank += 1; + visRanks[i] = visRank; + patchAttr(slot.el, 'hidden', false); + patchAttr(slot.el, 'data-metric', pres.metric); + patchAttr(slot.el, 'data-vis-rank', String(visRank)); + + if (pres.showRing && !slot.ringMounted) { + slot.el.insertBefore(slot.ringSvg, slot.textSpan); + slot.ringMounted = true; + } else if (!pres.showRing && slot.ringMounted) { + slot.ringSvg.remove(); + slot.ringMounted = false; + } + + const fullSegClass = + `${pres.segClass}${pres.running ? ' state-running' : ''}${pres.warn ? ' tone-warn' : ''}${pres.danger ? ' tone-danger' : ''}`; + patchAttr(slot.el, 'class', fullSegClass); + const fullTextClass = + `${pres.textClass}${pres.warn ? ' tone-warn' : ''}${pres.danger ? ' tone-danger' : ''}`; + patchAttr(slot.textSpan, 'class', fullTextClass); + patchText(slot.textSpan, pres.text); + + if (pres.showRing) { + slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset)); + patchClasses(slot.ringFill, { 'tone-warn': pres.warn, 'tone-danger': pres.danger }); + } + } + + const showSep0 = visRanks[1] >= 2; + patchAttr(sep0, 'hidden', !showSep0); + patchAttr(sep0, 'data-sep-for-rank', showSep0 ? String(visRanks[1]) : ''); + + const showSep1 = visRanks[2] >= 2; + patchAttr(sep1, 'hidden', !showSep1); + patchAttr(sep1, 'data-sep-for-rank', showSep1 ? String(visRanks[2]) : ''); + } + + // --- 4. 实时遥测状态绑定(双胶囊与多会话/全景概览浮层全部槽位预占,仅就地更新节点,零布局跳动) --- + function renderCapsuleTelemetry() { + if (disposed) return; + const telSt = telemetryStore.getState(); + const uiSt = uiStore.getState(); + const telemetry = telSt.telemetry; + + const showMulti = telemetry?.settings?.showTopbarMultiSession !== false; + patchAttr(multiBtn, 'hidden', !showMulti); + patchAttr(capsuleHost, 'data-multi', showMulti ? 'on' : 'off'); + if (!showMulti && multiOpen) { + setMultiOpen(false); + } + if (showMulti !== lastShowMulti) { + lastShowMulti = showMulti; + updateResponsiveLayout(); + } + + const slotKeys = normalizeClientTopbarSlots(telemetry?.settings?.topbarCapsuleSlots); + + if (!telemetry) { + patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); + patchText(multiLabel, '0 运行中'); + patchText(multiRunningMetaEl, '读取中...'); + stopMultiLiveTicker(); + + applyCapsuleSlots(slotKeys, { hasTelemetry: false }); + return; + } + + const { hasSubagents, agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } = + resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId); + const { scopedConv: capsuleScopedConv } = resolveScopedConversation( + telemetry, + uiSt.selectedAgentScope, + uiSt.ctxInspectorAgentId + ); + const activeConv = telemetry.activeConversation || {}; + const overviewActive = overviewScopedConv || activeConv; + const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; + const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); + const totalTokens = Number(ctx.totalTokens || 0); + const usedPct = + limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; + const dashOffset = +( + RING_CIRCUMFERENCE * + (1 - Math.max(0, Math.min(100, usedPct)) / 100) + ).toFixed(2); + + // --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 --- + const rawRunningList = + Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0 + ? telemetry.runningConversations + : activeConv.isRunning || aggregated?.isRunning + ? [ + { + cascadeId: activeConv.cascadeId || 'current', + title: activeConv.title || '当前会话', + isCurrentSelected: true, + isMainRunning: Boolean(activeConv.isRunning), + isRunning: true, + mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, + subagentCount: Math.max(0, (agents?.length || 1) - 1), + runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: usedPct, + subagents: (agents || []) + .filter((a) => !a.isMain) + .map((s, idx) => ({ + cascadeId: s.cascadeId || s.agentId, + index: s.index || idx + 1, + badgeText: s.badgeText || `子${idx + 1}`, + shortLabel: s.shortLabel || `子代理 #${idx + 1}`, + role: s.role || `子代理 #${idx + 1}`, + isRunning: Boolean(s.isRunning), + stepCount: Number(s.stepCount || 0), + lastModifiedMs: s.lastModifiedMs || 0, + liveActivity: s.liveActivity || { + phase: s.isRunning ? 'thinking' : 'done', + label: s.isRunning ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ] + : []; + + const runningCount = rawRunningList.length; + const runningSubCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSubagentCount || 0), + 0 + ); + const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + + patchClasses(multiBtn, { + 'is-running': runningCount > 0 && !hasWaiting, + 'is-waiting': runningCount > 0 && hasWaiting, + }); + const multiBtnText = + runningCount > 0 + ? runningSubCount > 0 + ? `${runningCount} 运行 · ${runningSubCount} 子` + : `${runningCount} 运行中` + : '0 运行中'; + patchText(multiLabel, multiBtnText); + + const hostRouteLower = String( + telSt.hostRouteConversationId || extractHostRouteCascadeId() || '' + ).toLowerCase(); + + patchText( + multiRunningMetaEl, + runningCount > 0 + ? runningSubCount > 0 + ? `${runningCount} 主会话 · ${runningSubCount} 子代理运行中` + : `${runningCount} 个会话运行中` + : '全部待命' + ); + patchText(multiEmptyHintEl, '悬停速览 · 左键可固定'); + patchAttr(multiEmptyEl, 'hidden', runningCount > 0); + patchAttr(multiRunningListEl, 'hidden', runningCount === 0); + + const runningIdsLower = new Set( + rawRunningList.map((item) => String(item.cascadeId || '').toLowerCase()) + ); + + if (runningCount === 0) { + stopMultiLiveTicker(); + manualSubExpandMap.clear(); + } else { + for (const cid of [...manualSubExpandMap.keys()]) { + if (!runningIdsLower.has(String(cid || '').toLowerCase())) { + manualSubExpandMap.delete(cid); + } + } + + const activeTimerKeys = new Set(); + for (const item of rawRunningList) { + activeTimerKeys.add(`main:${item.cascadeId}`); + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const runSubs = Number(item.runningSubagentCount || 0); + const isExp = manualSubExpandMap.has(item.cascadeId) + ? manualSubExpandMap.get(item.cascadeId) + : runSubs > 0; + if (subCount > 0 && isExp) { + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } + } + } + } + + patchKeyedList(multiRunningListEl, rawRunningList, { + keyFn: (item) => item.cascadeId, + sigFn: (item) => { + const runSubs = Number(item.runningSubagentCount || 0); + const isExp = manualSubExpandMap.has(item.cascadeId) + ? manualSubExpandMap.get(item.cascadeId) + : runSubs > 0; + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + const subSig = (item.subagents || []) + .map( + (s) => + `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` + ) + .join('|'); + return `${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + }, + createRow: createMultiLiveTaskCard, + updateRow: (refs, item) => { + const act = item.mainActivity || { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: item.lastModifiedMs || 0, + signature: `fallback:${item.lastModifiedMs || 0}`, + }; + const isWaiting = act.phase === 'waiting'; + const isCompacting = act.phase === 'compacting'; + patchClasses(refs.cardEl, { + 'is-waiting': isWaiting, + 'is-compacting': isCompacting, + }); + patchClasses(refs.dotIcon, { 'is-pulsing': true }); + + const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话'; + patchText(refs.titleEl, convTitle); + patchAttr(refs.titleEl, 'title', `点击在监控面板中检视会话:${convTitle}`); + refs.titleEl.onclick = (e) => { + e.stopPropagation(); + inspectSessionInMonitor(item.cascadeId); + }; + + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + patchAttr(refs.hereTagEl, 'hidden', !isHere); + + const metricParts = []; + if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { + metricParts.push( + `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` + ); + } + if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { + metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); + } + const metricsStr = metricParts.join(' · '); + patchAttr(refs.metricsEl, 'hidden', !metricsStr); + if (metricsStr) { + patchText(refs.metricsEl, metricsStr); + } + + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const runSubCount = Number(item.runningSubagentCount || 0); + const isExpanded = manualSubExpandMap.has(item.cascadeId) + ? manualSubExpandMap.get(item.cascadeId) + : runSubCount > 0; + patchAttr(refs.mainBadge, 'hidden', subCount === 0); + patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); + if (subCount > 0) { + const arrow = isExpanded ? '▾' : '▸'; + const toggleText = + runSubCount > 0 + ? `子代理 ${runSubCount}/${subCount} ${arrow}` + : `子代理 (${subCount}) ${arrow}`; + patchText(refs.subToggleBtn, toggleText); + patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); + refs.subToggleBtn.onclick = (e) => { + e.stopPropagation(); + manualSubExpandMap.set(item.cascadeId, !isExpanded); + renderCapsuleTelemetry(); + if (multiOpen) { + positionFloatingElements(); + } + }; + } + + const mainTimerKey = `main:${item.cascadeId}`; + activeTimerKeys.add(mainTimerKey); + bindMultiElapsedTimer( + mainTimerKey, + `${item.cascadeId}:${act.signature || act.label}`, + act.startedAtMs, + refs.elapsedEl + ); + + patchText(refs.mainPhase, act.label || '推理中'); + const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; + patchAttr(refs.mainProgress, 'hidden', !progText); + if (progText) { + patchText(refs.mainProgress, progText); + } + + const detailStr = act.detail || ''; + patchAttr(refs.mainSep, 'hidden', !detailStr); + patchAttr(refs.mainDetail, 'hidden', !detailStr); + patchText(refs.mainDetail, detailStr); + + const showSubs = subCount > 0 && isExpanded; + patchAttr(refs.subListEl, 'hidden', !showSubs); + if (showSubs) { + const subItems = item.subagents || []; + patchKeyedList(refs.subListEl, subItems, { + keyFn: (sub) => sub.cascadeId, + sigFn: (sub) => + `${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`, + createRow: createMultiLiveSubRow, + updateRow: (subRefs, sub) => { + const subAct = sub.liveActivity || { + phase: sub.isRunning ? 'thinking' : 'done', + label: sub.isRunning ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: sub.lastModifiedMs || 0, + }; + patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); + const subBadgeCls = getAgentBadgeClass(sub.index || 1, false); + patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`); + patchText(subRefs.subBadge, sub.badgeText || `子${sub.index || 1}`); + patchText(subRefs.subRole, sub.role || sub.shortLabel || '子代理'); + + const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; + const summaryText = sub.isRunning + ? `${subAct.label || '运行中'}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}` + : `已完成 (${sub.stepCount || 0} 步)`; + patchText(subRefs.subSummary, summaryText); + + const subTimerKey = `sub:${sub.cascadeId}`; + if (sub.isRunning) { + activeTimerKeys.add(subTimerKey); + bindMultiElapsedTimer( + subTimerKey, + `${sub.cascadeId}:${subAct.signature || subAct.label}`, + subAct.startedAtMs || sub.lastModifiedMs, + subRefs.subElapsed + ); + } else { + multiTimersMap.delete(subTimerKey); + patchText(subRefs.subElapsed, `${sub.stepCount || 0}步`); + } + }, + }); + } + }, + }); + + for (const k of [...multiTimersMap.keys()]) { + if (!activeTimerKeys.has(k)) { + multiTimersMap.delete(k); + } + } + ensureMultiLiveTicker(); + } + + // --- 4b. 同步右侧指标胶囊与悬停全景三卡片 --- + const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const tps = + capsuleScopedConv?.latestTokPerSec ?? + aggregated?.latestTokPerSec ?? + activeConv.latestTokPerSec ?? + null; + const ttft = + capsuleScopedConv?.latestTtftSec ?? + aggregated?.latestTtftSec ?? + activeConv.latestTtftSec ?? + null; + const capsuleStepCost = + capsuleScopedConv?.latestStepCostUsd ?? + aggregated?.latestStepCostUsd ?? + activeConv.latestStepCostUsd ?? + null; + + patchClasses(capsuleBtn, { 'is-running': isRunning }); + applyCapsuleSlots(slotKeys, { + hasTelemetry: true, + usedPct, + dashOffset, + isRunning, + tps, + ttft, + stepCost: capsuleStepCost, + quotas: telemetry.quotas, + }); + + const hasUpdate = Boolean(telemetry.cloudStatus?.updateAvailable); + patchAttr(updateDot, 'hidden', !hasUpdate); + + // --- 同步悬停三卡片全景概览(与 LiveOverviewView 保持完全一致的数据口径与视觉呈现) --- + const showUpstream = Boolean(telemetry.settings?.showUpstreamModel); + const activeModelDisplay = + (showUpstream + ? overviewActive.activeModelUpstream || overviewActive.activeModelShort + : overviewActive.activeModelShort) || '模型未知'; + + patchClasses(hoverPulseDot, { 'is-pulsing': Boolean(overviewActive.isRunning || isRunning) }); + patchText(hoverTpsVal, formatMetric(overviewActive.latestTokPerSec, ' tok/s')); + const reason = speedReasonText(overviewActive.latestSpeedReason); + const modelAndAgent = + hasSubagents && overviewActive.activeAgentBadge + ? `[${overviewActive.activeAgentBadge}] ${activeModelDisplay}` + : activeModelDisplay; + patchText(hoverTpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent); + + patchText(hoverTtftVal, formatMetric(overviewActive.latestTtftSec, 's')); + patchText(hoverTtftSub, `均值 ${formatMetric(overviewActive.ttftSummary?.avgSec, 's')}`); + + patchText(hoverAvgVal, formatMetric(overviewActive.avgTokPerSec, ' tok/s')); + patchText(hoverAvgSub, `有效 ${sampleSummary(overviewActive.speedSummary)}`); + + const stepCost = overviewActive.latestStepCostUsd; + const hasAnySteps = Number(overviewActive.stepCount || 0) > 0; + patchText( + hoverCostVal, + !hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true }) + ); + patchText( + hoverCacheSub, + `缓存 ${overviewActive.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(overviewActive.sessionCostUsd || 0, { unpricedCalls: overviewActive.sessionUnpricedCalls })}` + ); + + patchAttr(hoverCtxAgentBadge, 'hidden', !(hasSubagents && ctxAgent)); + if (hasSubagents && ctxAgent) { + const badgeCls = getAgentBadgeClass(ctxAgent.index || 0, Boolean(ctxAgent.isMain)); + patchAttr(hoverCtxAgentBadge, 'class', `agent-badge ${badgeCls}`); + patchText(hoverCtxAgentBadge, formatAgentLabel(ctxAgent)); + } + patchText( + hoverCtxSummaryText, + `${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)` + ); + hoverCtxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } }); + + const scoredChannels = CTX_CHANNEL_DEFS.map((ch, defaultOrder) => ({ + ch, + defaultOrder, + val: ch.getValue(ctx), + })); + scoredChannels.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder); + for (let i = 0; i < hoverLegendSlots.length; i += 1) { + const slot = hoverLegendSlots[i]; + const entry = scoredChannels[i]; + if (!slot || !entry) continue; + patchAttr(slot.swatchEl, 'class', `swatch ${entry.ch.segClass}`); + patchText(slot.labelEl, entry.ch.label); + patchText(slot.valEl, formatTokens(entry.val)); + } + + const quotas = telemetry.quotas || {}; + const weekly = quotas.weekly || {}; + const minuteTick = Number(telSt.minuteTick || Math.floor(Date.now() / 30000)); + patchText( + hoverTierBadge, + `${telemetry.account?.tierName || 'Google AI'} · ${telemetry.account?.planName || 'Pro'}` + ); + patchKeyedList(hoverPoolsListEl, buildQuotaPoolItems(quotas, minuteTick), { + keyFn: (item) => item.key, + sigFn: quotaPoolRowSig, + createRow: createPoolQuotaRow, + updateRow: syncPoolQuotaRow, + }); + patchText( + hoverWkFootLeft, + `本周累计: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0, { unpricedCalls: weekly.unpricedCalls })})` + ); + patchText( + hoverWkFootRight, + telemetry.account?.aiCredits > 0 + ? `AI 积分: ${telemetry.account.aiCredits}` + : `本周调用: ${weekly.calls || 0} 次` + ); + } + + const unsubStore = telemetryStore.subscribe( + (st) => ({ + syncState: st.syncState, + telemetry: st.telemetry, + minuteTick: st.minuteTick, + selectedConversationId: st.selectedConversationId, + }), + (slice) => { + if (slice.telemetry?.settings?.enableWindowOverlay === false) { + if (popoverOpen) setPopoverOpen(false); + if (multiOpen) setMultiOpen(false); + } + renderCapsuleTelemetry(); + } + ); + + const unsubUiScope = uiStore.subscribe( + (st) => ({ + selectedAgentScope: st.selectedAgentScope, + ctxInspectorAgentId: st.ctxInspectorAgentId, + }), + () => renderCapsuleTelemetry() + ); + + // --- 5. 宿主会话路由跟随与全局交互监听 --- + function syncHostRouteIfChanged() { + if (disposed) return; + const currentRouteId = extractHostRouteCascadeId(); + if (currentRouteId === lastObservedRouteId) return; + lastObservedRouteId = currentRouteId; + const st = telemetryStore.getState(); + const patch = { hostRouteConversationId: currentRouteId }; + if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) { + patch.selectedConversationId = ''; + } + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + telemetryStore.setState(patch); + void fetchTelemetry({ force: false }); + } + + const onDocMouseDown = (e) => { + if (popoverOpen && !isEventInside(e, popoverEl) && !isEventInside(e, capsuleHost)) { + setPopoverOpen(false); + } + if (multiOpen && !isEventInside(e, multiPanelEl) && !isEventInside(e, capsuleHost)) { + setMultiOpen(false); + } + }; + + const onDocKeyDown = (e) => { + if (e.key === 'Escape' && !e.defaultPrevented) { + if (popoverOpen) { + setPopoverOpen(false); + } + if (multiOpen) { + setMultiOpen(false); + } + } + }; + + const onWindowPointerMove = (e) => recordPointerCoords(e); + const onWindowBlur = () => { + hasPointerCoords = false; + if (tooltipOpen) { + setTooltipOpen(false); + } + if (multiOpen && !multiPinned) { + setMultiOpen(false); + } + }; + const onWindowResize = () => updateResponsiveLayout(); + const onPopState = () => syncHostRouteIfChanged(); + const onVisibilityChange = () => { + if (document.hidden) { + hasPointerCoords = false; + if (tooltipOpen) { + setTooltipOpen(false); + } + if (multiOpen && !multiPinned) { + setMultiOpen(false); + } + return; + } + if (!document.hidden && !disposed) { + syncHostRouteIfChanged(); + void fetchTelemetry({ force: false }); + } + }; + + let hostDomObserver = null; + try { + if (typeof ResizeObserver !== 'undefined') { + resizeObserver = new ResizeObserver(() => updateResponsiveLayout()); + if (document.body) resizeObserver.observe(document.body); + } + if (typeof MutationObserver !== 'undefined' && document.body) { + hostDomObserver = new MutationObserver(() => { + syncHostRouteIfChanged(); + const tb = findHostTitlebar(); + if ( + !capsuleHost.isConnected || + !portalHost.isConnected || + (tb && !tb.contains(capsuleHost)) || + (!tb && capsuleHost.getAttribute('data-dock') === 'flow') + ) { + scheduleDockSync(); + } + }); + hostDomObserver.observe(document.body, { childList: true, subtree: true }); + } + } catch { + // 忽略观察器初始化异常 + } + + document.addEventListener?.('mousedown', onDocMouseDown, true); + document.addEventListener?.('keydown', onDocKeyDown); + document.addEventListener?.('visibilitychange', onVisibilityChange); + window.addEventListener?.('pointermove', onWindowPointerMove, { passive: true }); + window.addEventListener?.('blur', onWindowBlur); + window.addEventListener?.('resize', onWindowResize); + window.addEventListener?.('popstate', onPopState); + navigator?.windowControlsOverlay?.addEventListener?.('geometrychange', onWindowResize); + + const watchdogTimer = setInterval(() => { + if (disposed) return; + syncHostRouteIfChanged(); + if (!capsuleHost.isConnected || !portalHost.isConnected) { + ensureCapsuleDocked(); + } + }, 1200); + + ensureCapsuleDocked(); + renderCapsuleTelemetry(); + const allowMultiCarryOver = + telemetryStore.getState().telemetry?.settings?.showTopbarMultiSession !== false; + if (carryOverPopoverOpen) { + setPopoverOpen(true, { instant: true }); + } else if (carryOverMultiPinnedOpen && allowMultiCarryOver) { + setMultiOpen(true, { pinned: true, instant: true }); + } else if (carryOverMultiHoverOpen && allowMultiCarryOver) { + setMultiOpen(true, { pinned: false, instant: true }); + } else if (carryOverTooltipOpen) { + setTooltipOpen(true, { instant: true }); + } + const stopPolling = startAsyncTelemetryLoop(2000); + + const handle = { + bundleVersion, + ensureAlive() { + if (disposed) return false; + return ensureCapsuleDocked(); + }, + updateBridge(nextBridge) { + if (disposed || !nextBridge || typeof nextBridge !== 'object') return false; + const port = Number(nextBridge.port || 0); + const token = String(nextBridge.token || ''); + if (!Number.isInteger(port) || port <= 0 || !token) return false; + const cur = window.__AGUsageMonitorBridge || {}; + const portChanged = Number(cur.port || 0) !== port; + cur.port = port; + cur.token = token; + if (portChanged && cur.transportMode !== 'cdp') { + cur.transportMode = 'http'; + } + window.__AGUsageMonitorBridge = cur; + void fetchTelemetry({ force: false }); + return true; + }, + getTelemetrySnapshot() { + return telemetryStore.getState().telemetry; + }, + getLastPointer() { + return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null; + }, + deliverRpc(responses) { + if (disposed) return 0; + return deliverCdpBridgeResponses(responses); + }, + open() { + setPopoverOpen(true); + }, + close() { + setPopoverOpen(false); + }, + toggle() { + setPopoverOpen(!popoverOpen); + }, + openMulti(pinned = true) { + setMultiOpen(true, { pinned: Boolean(pinned) }); + }, + closeMulti() { + setMultiOpen(false); + }, + isOpen: () => popoverOpen, + isHoverOpen: () => tooltipOpen, + isMultiOpen: () => multiOpen, + isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned), + isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned), + getLayoutMode: () => layoutMode, + dispose() { + if (disposed) return; + disposed = true; + clearInterval(watchdogTimer); + if (hoverLeaveTimer) { + clearTimeout(hoverLeaveTimer); + hoverLeaveTimer = null; + } + if (multiLeaveTimer) { + clearTimeout(multiLeaveTimer); + multiLeaveTimer = null; + } + stopMultiLiveTicker(); + if (dockRafId && typeof cancelAnimationFrame === 'function') { + cancelAnimationFrame(dockRafId); + dockRafId = 0; + } + stopPolling(); + stopAsyncTelemetryLoop(); + unsubStore(); + unsubUiScope(); + try { + resizeObserver?.disconnect(); + } catch {} + try { + hostDomObserver?.disconnect(); + } catch {} + document.removeEventListener?.('mousedown', onDocMouseDown, true); + document.removeEventListener?.('keydown', onDocKeyDown); + document.removeEventListener?.('visibilitychange', onVisibilityChange); + window.removeEventListener?.('pointermove', onWindowPointerMove); + window.removeEventListener?.('blur', onWindowBlur); + window.removeEventListener?.('resize', onWindowResize); + window.removeEventListener?.('popstate', onPopState); + navigator?.windowControlsOverlay?.removeEventListener?.('geometrychange', onWindowResize); + try { + hoverCtxSegmentBar.destroy(); + } catch {} + try { + appInstance.destroy(); + } catch {} + try { + capsuleHost.remove(); + } catch {} + try { + portalHost.remove(); + } catch {} + if (window.__AGUsageMonitorOverlay === handle) { + delete window.__AGUsageMonitorOverlay; + } + }, + }; + + window.__AGUsageMonitorOverlay = handle; + return handle; +} diff --git a/sidecars/panel/src/components/ui/CustomDateTimePicker.js b/sidecars/panel/src/components/ui/CustomDateTimePicker.js index 5cc1d68..c95dfba 100644 --- a/sidecars/panel/src/components/ui/CustomDateTimePicker.js +++ b/sidecars/panel/src/components/ui/CustomDateTimePicker.js @@ -4,7 +4,14 @@ */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js'; +import { + h, + isEventInside, + patchAttr, + patchClasses, + patchKeyedList, + patchText, +} from '../../core/domPatch.js'; import { formatCompactDateTime } from '../../core/formatters.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; @@ -118,9 +125,9 @@ export const CustomDateTimePicker = defineComponent({ function adjustTime(part, delta) { const cur = new Date(getProps().modelValue || Date.now()); if (part === 'hour') { - cur.setHours((cur.getHours() + delta + 24) % 24); + cur.setHours(cur.getHours() + delta); } else { - cur.setMinutes((cur.getMinutes() + delta + 60) % 60); + cur.setMinutes(cur.getMinutes() + delta); } const nextMs = cur.getTime(); viewYear = cur.getFullYear(); @@ -251,7 +258,7 @@ export const CustomDateTimePicker = defineComponent({ } const handleDocClick = (e) => { - if (isOpen && !rootEl.contains(e.target)) { + if (isOpen && !isEventInside(e, rootEl)) { togglePopover(false); } }; @@ -267,16 +274,6 @@ export const CustomDateTimePicker = defineComponent({ el: rootEl, refs: { triggerBtn, triggerText, popoverEl, daysGrid, hourValSpan, minValSpan }, onPropsChange: syncDisplay, - getValue: () => Number(getProps().modelValue || 0), - methods: { - open: () => togglePopover(true), - close: () => togglePopover(false), - selectDayByOffset: (daysDelta) => { - const cur = new Date(getProps().modelValue || Date.now()); - cur.setDate(cur.getDate() + daysDelta); - emit('update:modelValue', cur.getTime()); - }, - }, }; }, }); diff --git a/sidecars/panel/src/components/ui/CustomNumberInput.js b/sidecars/panel/src/components/ui/CustomNumberInput.js index cb25413..f57d3fa 100644 --- a/sidecars/panel/src/components/ui/CustomNumberInput.js +++ b/sidecars/panel/src/components/ui/CustomNumberInput.js @@ -10,7 +10,7 @@ import { createSvgIcon } from '../../icons/SvgIcon.js'; export const CustomNumberInput = defineComponent({ name: 'CustomNumberInput', - setup({ getProps, emit }) { + setup({ getProps, setProps, emit }) { function clampValue(raw) { const { min = -Infinity, max = Infinity, precision = 0 } = getProps(); const num = Number(raw); @@ -27,6 +27,7 @@ export const CustomNumberInput = defineComponent({ const next = clampValue(current + direction * step * multiplier); syncFieldDisplay(next); if (next !== current) { + setProps({ modelValue: next }); emit('update:modelValue', next); } } @@ -80,11 +81,22 @@ export const CustomNumberInput = defineComponent({ }); function commitManualInput() { - const rawText = String(textField.value || '').replace(/[^0-9.-]/g, ''); - const next = clampValue(rawText); + const raw = String(textField.value ?? '').trim(); + if (!raw || !/\d/.test(raw)) { + syncFieldDisplay(getProps().modelValue); + return; + } + const cleaned = raw.replace(/[^0-9.-]/g, ''); + const parsed = Number(cleaned); + if (!Number.isFinite(parsed)) { + syncFieldDisplay(getProps().modelValue); + return; + } + const next = clampValue(parsed); const prev = Number(getProps().modelValue); syncFieldDisplay(next); if (next !== prev) { + setProps({ modelValue: next }); emit('update:modelValue', next); } } @@ -107,10 +119,8 @@ export const CustomNumberInput = defineComponent({ el: rootEl, refs: { decBtn, incBtn, textField }, onPropsChange: () => syncFieldDisplay(), - getValue: () => clampValue(textField.value), methods: { - stepUp: (mult = 1) => applyStep(1, mult), - stepDown: (mult = 1) => applyStep(-1, mult), + commit: () => commitManualInput(), }, }; }, diff --git a/sidecars/panel/src/components/ui/CustomScrollbar.js b/sidecars/panel/src/components/ui/CustomScrollbar.js index 37e1ef3..435ddfe 100644 --- a/sidecars/panel/src/components/ui/CustomScrollbar.js +++ b/sidecars/panel/src/components/ui/CustomScrollbar.js @@ -1,7 +1,7 @@ /** * @fileoverview Bespoke custom scrollbar component (零原生滚动条). * Hides native OS scrollbars completely and renders a precision 4px floating - * rail + GPU-translated thumb with drag, track-jump, and modelValue ratio emit. + * rail + GPU-translated thumb with drag and track-jump support. */ import { defineComponent } from '../../core/component.js'; @@ -9,7 +9,7 @@ import { h, patchClasses, patchStyleVar } from '../../core/domPatch.js'; export const CustomScrollbar = defineComponent({ name: 'CustomScrollbar', - setup({ getProps, emit, onCleanup }) { + setup({ getProps, onCleanup }) { const contentEl = getProps().contentEl || h('div'); contentEl.classList.add('custom-scroll-content'); @@ -61,11 +61,6 @@ export const CustomScrollbar = defineComponent({ function onContentScroll() { syncThumb(); - const overflow = (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0); - if (overflow > 1) { - const ratio = +Math.max(0, Math.min(1, (contentEl.scrollTop || 0) / overflow)).toFixed(3); - emit('update:modelValue', ratio); - } } function onDocMouseMove(e) { @@ -163,12 +158,6 @@ export const CustomScrollbar = defineComponent({ refresh() { scheduleSyncThumb(); }, - scrollToRatio(ratio) { - const r = Math.max(0, Math.min(1, Number(ratio || 0))); - const overflow = Math.max(0, (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0)); - contentEl.scrollTop = Math.round(r * overflow); - syncThumb(); - }, }, }; }, diff --git a/sidecars/panel/src/components/ui/CustomSelect.js b/sidecars/panel/src/components/ui/CustomSelect.js index 87135f5..c6da807 100644 --- a/sidecars/panel/src/components/ui/CustomSelect.js +++ b/sidecars/panel/src/components/ui/CustomSelect.js @@ -4,12 +4,19 @@ */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js'; +import { + h, + isEventInside, + patchAttr, + patchClasses, + patchKeyedList, + patchText, +} from '../../core/domPatch.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; export const CustomSelect = defineComponent({ name: 'CustomSelect', - setup({ getProps, emit, onCleanup }) { + setup({ getProps, setProps, emit, onCleanup }) { let isOpen = false; let focusedIndex = -1; @@ -67,6 +74,7 @@ export const CustomSelect = defineComponent({ const prevVal = getProps().modelValue; toggleOpen(false); if (option.value !== prevVal) { + setProps({ modelValue: option.value }); emit('update:modelValue', option.value); } } @@ -82,6 +90,7 @@ export const CustomSelect = defineComponent({ } else { focusedIndex = (focusedIndex + 1) % opts.length; renderMenuOptions(); + menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' }); } } else if (e.key === 'ArrowUp') { e.preventDefault(); @@ -90,6 +99,7 @@ export const CustomSelect = defineComponent({ } else { focusedIndex = (focusedIndex - 1 + opts.length) % opts.length; renderMenuOptions(); + menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' }); } } else if (e.key === 'Enter' && isOpen) { e.preventDefault(); @@ -150,17 +160,17 @@ export const CustomSelect = defineComponent({ if (icon) { patchSvgIcon(leadIcon, icon); } - const selectedOpt = - options.find((o) => o.value === modelValue) || - (!modelValue ? options[0] : undefined); - patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder); + const matchedOpt = options.find((o) => o.value === modelValue); + const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined); + const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder; + patchText(triggerLabel, selectedOpt ? selectedOpt.label : fallbackText); if (isOpen) { renderMenuOptions(); } } const handleDocClick = (e) => { - if (isOpen && !rootEl.contains(e.target)) { + if (isOpen && !isEventInside(e, rootEl)) { toggleOpen(false); } }; @@ -176,14 +186,8 @@ export const CustomSelect = defineComponent({ el: rootEl, refs: { triggerBtn, triggerLabel, menuEl }, onPropsChange: syncTriggerAndMenu, - getValue: () => getProps().modelValue, methods: { - open: () => toggleOpen(true), close: () => toggleOpen(false), - selectByValue: (val) => { - const found = (getProps().options || []).find((o) => o.value === val); - if (found) chooseOption(found); - }, }, }; }, diff --git a/sidecars/panel/src/components/ui/SegmentedControl.js b/sidecars/panel/src/components/ui/SegmentedControl.js index 210c352..4c5670d 100644 --- a/sidecars/panel/src/components/ui/SegmentedControl.js +++ b/sidecars/panel/src/components/ui/SegmentedControl.js @@ -8,7 +8,7 @@ import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../cor export const SegmentedControl = defineComponent({ name: 'SegmentedControl', - setup({ getProps, emit }) { + setup({ getProps, setProps, emit }) { const rootEl = h('div', { className: 'segmented', role: 'group', @@ -27,6 +27,7 @@ export const SegmentedControl = defineComponent({ onClick: (e) => { e.stopPropagation(); if (getProps().modelValue !== opt.value) { + setProps({ modelValue: opt.value }); emit('update:modelValue', opt.value); } }, diff --git a/sidecars/panel/src/core/component.js b/sidecars/panel/src/core/component.js index 77f98a5..1d073fa 100644 --- a/sidecars/panel/src/core/component.js +++ b/sidecars/panel/src/core/component.js @@ -8,15 +8,6 @@ export function defineComponent({ name, setup }) { return function createInstance(initialProps = {}) { let props = { ...initialProps }; const cleanups = []; - const eventHandlers = new Map(); - - function on(event, fn) { - if (!eventHandlers.has(event)) { - eventHandlers.set(event, new Set()); - } - eventHandlers.get(event).add(fn); - return () => eventHandlers.get(event)?.delete(fn); - } function emit(event, payload) { // Support Vue-style onUpdateModelValue / onChange prop callbacks @@ -28,12 +19,6 @@ export function defineComponent({ name, setup }) { props.onChange(payload); } } - const handlers = eventHandlers.get(event); - if (handlers) { - for (const fn of handlers) { - fn(payload); - } - } } function onCleanup(fn) { @@ -42,15 +27,11 @@ export function defineComponent({ name, setup }) { } } - const setupResult = setup({ - getProps: () => props, - emit, - onCleanup, - }); + let setupResult = null; function setProps(nextProps = {}) { props = { ...props, ...nextProps }; - if (typeof setupResult.onPropsChange === 'function') { + if (setupResult && typeof setupResult.onPropsChange === 'function') { setupResult.onPropsChange(props); } } @@ -59,11 +40,12 @@ export function defineComponent({ name, setup }) { setProps({ modelValue: nextValue }); } - function getValue() { - return typeof setupResult.getValue === 'function' - ? setupResult.getValue() - : props.modelValue; - } + setupResult = setup({ + getProps: () => props, + setProps, + emit, + onCleanup, + }); function destroy() { for (const fn of cleanups.splice(0)) { @@ -73,7 +55,6 @@ export function defineComponent({ name, setup }) { console.error(`[${name}] cleanup error:`, err); } } - eventHandlers.clear(); if (setupResult.el?.parentNode) { setupResult.el.parentNode.removeChild(setupResult.el); } @@ -83,11 +64,8 @@ export function defineComponent({ name, setup }) { name, el: setupResult.el, refs: setupResult.refs || {}, - on, - emit, setProps, setValue, - getValue, destroy, ...setupResult.methods, }; diff --git a/sidecars/panel/src/core/domPatch.js b/sidecars/panel/src/core/domPatch.js index 92c7b93..7bf5a94 100644 --- a/sidecars/panel/src/core/domPatch.js +++ b/sidecars/panel/src/core/domPatch.js @@ -53,18 +53,28 @@ export function patchText(el, nextValue) { export function patchAttr(el, attrName, nextValue) { if (!el) return false; if (nextValue === null || nextValue === undefined || nextValue === false) { - if (!el.hasAttribute(attrName)) { - return false; + let mutated = false; + if (el.hasAttribute(attrName)) { + el.removeAttribute(attrName); + mutated = true; } - el.removeAttribute(attrName); - return true; + if (attrName === 'value' && 'value' in el && el.value !== '') { + el.value = ''; + mutated = true; + } + return mutated; } const strVal = nextValue === true ? '' : String(nextValue); - if (el.getAttribute(attrName) === strVal) { - return false; + let mutated = false; + if (el.getAttribute(attrName) !== strVal) { + el.setAttribute(attrName, strVal); + mutated = true; } - el.setAttribute(attrName, strVal); - return true; + if (attrName === 'value' && 'value' in el && el.value !== strVal) { + el.value = strVal; + mutated = true; + } + return mutated; } export function patchClasses(el, classMap) { @@ -72,11 +82,14 @@ export function patchClasses(el, classMap) { let mutated = false; for (const [cls, active] of Object.entries(classMap)) { if (!cls) continue; - const has = el.classList.contains(cls); const shouldHave = Boolean(active); - if (has !== shouldHave) { - el.classList.toggle(cls, shouldHave); - mutated = true; + const tokens = String(cls).split(/\s+/).filter(Boolean); + for (const tok of tokens) { + const has = el.classList.contains(tok); + if (has !== shouldHave) { + el.classList.toggle(tok, shouldHave); + mutated = true; + } } } return mutated; @@ -93,6 +106,25 @@ export function patchStyleVar(el, varName, nextValue) { return true; } +/** + * 判断事件是否发生在目标节点内部(兼容 Shadow DOM 的 `composedPath()` 穿透)。 + * + * @param {Event|null|undefined} event + * @param {Node|null|undefined} element + * @returns {boolean} + */ +export function isEventInside(event, element) { + if (!event || !element) return false; + if (typeof event.composedPath === 'function') { + const path = event.composedPath(); + if (Array.isArray(path) && path.includes(element)) { + return true; + } + } + const target = event.target; + return Boolean(target && typeof element.contains === 'function' && element.contains(target)); +} + const keyedListState = new WeakMap(); /** @@ -108,11 +140,15 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda } const nextKeys = new Set(); + const seenInPass = new Map(); const orderedNodes = []; for (let i = 0; i < items.length; i++) { const item = items[i]; - const key = String(keyFn(item, i)); + const rawKey = String(keyFn(item, i)); + const dupIdx = seenInPass.get(rawKey) || 0; + seenInPass.set(rawKey, dupIdx + 1); + const key = dupIdx === 0 ? rawKey : `${rawKey}__dup_${dupIdx}`; const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item); nextKeys.add(key); diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index d3f17f8..54e686c 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -37,15 +37,15 @@ export function formatDateSpanBadge(startMs, endMs) { return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } -export function formatUsd(amount, { precise = false, estimated = false, unpricedCalls = 0 } = {}) { +export function formatUsd(amount, { precise = false, unpricedCalls = 0, compactPending = false } = {}) { if (amount == null || !Number.isFinite(Number(amount))) return '待定'; const val = Number(amount || 0); - const prefix = estimated ? '≈$' : '$'; - const suffix = unpricedCalls > 0 ? ' + 待定' : ''; + const suffix = unpricedCalls > 0 ? (compactPending ? '+' : ' + 待定') : ''; if (precise) { - return (val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`) + suffix; + if (val > 0 && val < 0.001) return `<$0.001${suffix}`; + return (val >= 1 ? `$${val.toFixed(2)}` : `$${val.toFixed(3)}`) + suffix; } - return `${prefix}${val.toFixed(2)}${suffix}`; + return `$${val.toFixed(2)}${suffix}`; } export function speedReasonText(reason) { @@ -53,6 +53,7 @@ export function speedReasonText(reason) { incomplete_or_invalid_timing: '生成未完成', invalid_output_tokens: '无有效输出', inconsistent_timing: '耗时数据异常', + short_timing: '耗时过短 (<0.5s)', legacy_cache: '旧版缓存记录', })[reason] || ''; } @@ -66,9 +67,10 @@ export function sampleSummary(summary) { export function formatCountdown(isoTime, nowMs = Date.now()) { if (!isoTime) return '未知重置时间'; const targetMs = Date.parse(isoTime); - if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间'; + if (!Number.isFinite(targetMs) || targetMs <= 0) return '未知重置时间'; const diffMs = targetMs - nowMs; if (diffMs <= 0) return '即将重置'; + if (diffMs < 60_000) return '<1分钟后重置'; const totalMinutes = Math.floor(diffMs / 60000); const days = Math.floor(totalMinutes / (60 * 24)); diff --git a/sidecars/panel/src/core/httpClient.js b/sidecars/panel/src/core/httpClient.js index 28d1f3a..92d2615 100644 --- a/sidecars/panel/src/core/httpClient.js +++ b/sidecars/panel/src/core/httpClient.js @@ -1,11 +1,123 @@ /** * @fileoverview Async HTTP client with AbortController cancellation for stale - * polling requests and concurrent GET deduplication. + * polling requests, concurrent GET deduplication, and dual-mode transport + * (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge). */ const inFlightGets = new Map(); const activeControllers = new Map(); +/** + * 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。 + * + * @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null} + */ +export function getWindowBridgeConfig() { + if (typeof window === 'undefined') return null; + const br = window.__AGUsageMonitorBridge; + const port = Number(br?.port || 0); + if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) { + return br; + } + return null; +} + +/** + * 判断当前脚本是否以双栖悬浮模式运行在宿主主聊天窗口内(而非右侧辅助栏 Webview)。 + * + * @returns {boolean} + */ +export function isWindowOverlayMode() { + if (typeof window === 'undefined') return false; + if (window.sidecar?.fetch) return false; + return Boolean(getWindowBridgeConfig()); +} + +/** + * 接收 Sidecar 通过 CDP `Runtime.evaluate` 批量投递的 RPC 响应,完成因 CSP/代理解除 HTTP 直连时的兜底请求。 + * + * @param {Array<{ id: string, ok: boolean, status?: number, data?: any, error?: string }>} responses + * @returns {number} + */ +export function deliverCdpBridgeResponses(responses) { + const br = getWindowBridgeConfig(); + if (!br || !(br.rpcPending instanceof Map) || !Array.isArray(responses)) return 0; + let delivered = 0; + for (const item of responses) { + const entry = br.rpcPending.get(item?.id); + if (!entry) continue; + br.rpcPending.delete(item.id); + delivered += 1; + if (item.ok) { + entry.resolve(item.data); + } else { + entry.reject(new Error(item.error || `HTTP ${item.status || 500}`)); + } + } + return delivered; +} + +function callViaCdpBridge(bridge, path, { method, body, signal }) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + const abortErr = new Error('Request aborted'); + abortErr.name = 'AbortError'; + reject(abortErr); + return; + } + if (!Array.isArray(bridge.rpcQueue)) bridge.rpcQueue = []; + if (!(bridge.rpcPending instanceof Map)) bridge.rpcPending = new Map(); + + const reqId = `rpc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const cleanupQueueItem = () => { + if (!Array.isArray(bridge.rpcQueue)) return; + const idx = bridge.rpcQueue.findIndex((item) => item?.id === reqId); + if (idx >= 0) bridge.rpcQueue.splice(idx, 1); + }; + + const timeoutId = setTimeout(() => { + bridge.rpcPending.delete(reqId); + cleanupQueueItem(); + reject(new Error('CDP bridge timeout')); + }, 8000); + + const onAbort = () => { + clearTimeout(timeoutId); + bridge.rpcPending.delete(reqId); + cleanupQueueItem(); + const abortErr = new Error('Request aborted'); + abortErr.name = 'AbortError'; + reject(abortErr); + }; + if (signal) { + signal.addEventListener('abort', onAbort, { once: true }); + } + + bridge.rpcPending.set(reqId, { + resolve: (data) => { + clearTimeout(timeoutId); + if (signal) signal.removeEventListener('abort', onAbort); + resolve(data); + }, + reject: (err) => { + clearTimeout(timeoutId); + if (signal) signal.removeEventListener('abort', onAbort); + reject(err); + }, + }); + + if (bridge.rpcQueue.length >= 16) { + const dropped = bridge.rpcQueue.shift(); + if (dropped?.id) { + const stale = bridge.rpcPending.get(dropped.id); + bridge.rpcPending.delete(dropped.id); + stale?.reject(new Error('CDP queue superseded')); + } + } + bridge.rpcQueue.push({ id: reqId, path, method, body }); + }); +} + export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) { const upperMethod = method.toUpperCase(); const dedupKey = upperMethod === 'GET' && !abortKey ? path : ''; @@ -28,16 +140,41 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' const runRequest = async () => { const sidecar = typeof window !== 'undefined' ? window.sidecar : null; + const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null; const fetchFn = sidecar?.fetch ? sidecar.fetch.bind(sidecar) - : globalThis.fetch.bind(globalThis); + : typeof window !== 'undefined' && typeof window.fetch === 'function' + ? window.fetch.bind(window) + : globalThis.fetch.bind(globalThis); - const res = await fetchFn(path, { - method: upperMethod, - headers: { 'Content-Type': 'application/json' }, - body: body === undefined ? undefined : JSON.stringify(body), - signal, - }); + const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path; + const headers = {}; + if (body !== undefined || !bridge) { + headers['Content-Type'] = 'application/json'; + } + if (bridge) { + headers['X-Usage-Monitor-Token'] = bridge.token; + if (bridge.transportMode === 'cdp') { + return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal }); + } + } + + let res; + try { + res = await fetchFn(requestUrl, { + method: upperMethod, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + signal, + }); + } catch (fetchErr) { + if (!bridge || signal?.aborted || fetchErr?.name === 'AbortError') { + throw fetchErr; + } + // 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道 + bridge.transportMode = 'cdp'; + return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal }); + } if (signal?.aborted) { const abortErr = new Error('Request aborted'); abortErr.name = 'AbortError'; diff --git a/sidecars/panel/src/core/reactive.js b/sidecars/panel/src/core/reactive.js index e269e39..7f1d230 100644 --- a/sidecars/panel/src/core/reactive.js +++ b/sidecars/panel/src/core/reactive.js @@ -6,7 +6,7 @@ const pendingJobs = new Set(); let isFlushPending = false; -export function scheduleAsyncJob(job) { +function scheduleAsyncJob(job) { pendingJobs.add(job); if (!isFlushPending) { isFlushPending = true; @@ -14,7 +14,7 @@ export function scheduleAsyncJob(job) { } } -export function flushAsyncJobs() { +function flushAsyncJobs() { isFlushPending = false; const jobs = Array.from(pendingJobs); pendingJobs.clear(); @@ -23,7 +23,7 @@ export function flushAsyncJobs() { } } -export function isShallowEqual(a, b) { +function isShallowEqual(a, b) { if (Object.is(a, b)) return true; if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) { return false; @@ -55,6 +55,19 @@ export function createReactiveStore(initialState) { return state; } + function notifyAll() { + for (const sub of Array.from(subscribers)) { + if (!subscribers.has(sub)) continue; + const nextSlice = sub.selector(state); + const equal = sub.compare(sub.lastSlice, nextSlice); + if (!equal) { + const prevSlice = sub.lastSlice; + sub.lastSlice = nextSlice; + sub.listener(nextSlice, prevSlice); + } + } + } + function setState(patchOrUpdater, { sync = false } = {}) { const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater; if (!patch || typeof patch !== 'object') return; @@ -72,18 +85,6 @@ export function createReactiveStore(initialState) { } state = nextState; - const notifyAll = () => { - for (const sub of subscribers) { - const nextSlice = sub.selector(state); - const equal = sub.compare(sub.lastSlice, nextSlice); - if (!equal) { - const prevSlice = sub.lastSlice; - sub.lastSlice = nextSlice; - sub.listener(nextSlice, prevSlice); - } - } - }; - if (sync) { notifyAll(); } else { diff --git a/sidecars/panel/src/icons/svgRegistry.js b/sidecars/panel/src/icons/svgRegistry.js index e6bb452..538268f 100644 --- a/sidecars/panel/src/icons/svgRegistry.js +++ b/sidecars/panel/src/icons/svgRegistry.js @@ -73,9 +73,17 @@ export const SVG_ICON_DEFS = Object.freeze({ { tag: 'path', attrs: { d: 'M3.5 8h9' } }, ], dot: [ - { tag: 'circle', attrs: { cx: '8', cy: '8', r: '3.2', fill: 'currentColor', stroke: 'none' } }, + { tag: 'circle', attrs: { cx: '8', cy: '8', r: '5', fill: 'currentColor', stroke: 'none' } }, ], 'arrow-down': [ { tag: 'path', attrs: { d: 'M8 2.8v10.4M4.2 9.4L8 13.2l3.8-3.8' } }, ], + dock: [ + { tag: 'rect', attrs: { x: '1.8', y: '2.5', width: '12.4', height: '11', rx: '1.5' } }, + { tag: 'path', attrs: { d: 'M1.8 6h12.4' } }, + { tag: 'path', attrs: { d: 'M9.2 4.25h3.2' } }, + ], + close: [ + { tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } }, + ], }); diff --git a/sidecars/panel/src/main.js b/sidecars/panel/src/main.js index 60582ed..c3cb7d0 100644 --- a/sidecars/panel/src/main.js +++ b/sidecars/panel/src/main.js @@ -1,11 +1,15 @@ /** * @fileoverview Async entry point for Antigravity Usage & Speed Monitor. + * Automatically branches between Auxiliary Sidebar Webview mode (`#app-root`) + * and Main Window Dual-Mount Overlay mode (`window.__AGUsageMonitorBridge`). */ import { App } from './App.js'; +import { mountWindowOverlay } from './components/layout/WindowOverlayShell.js'; +import { isWindowOverlayMode } from './core/httpClient.js'; import { startAsyncTelemetryLoop } from './store/telemetryStore.js'; -export async function bootstrapApp(mountTarget = document.getElementById('app-root')) { +async function bootstrapApp(mountTarget = document.getElementById('app-root')) { if (!mountTarget) return null; const appInstance = App(); mountTarget.appendChild(appInstance.el); @@ -16,14 +20,22 @@ export async function bootstrapApp(mountTarget = document.getElementById('app-ro }; } -export function init() { +function startEntry() { + if (isWindowOverlayMode()) { + mountWindowOverlay(); + return; + } + bootstrapApp(); +} + +function init() { if (typeof document === 'undefined') return; if (document.readyState === 'loading' && typeof document.addEventListener === 'function') { document.addEventListener('DOMContentLoaded', () => { - bootstrapApp(); + startEntry(); }); } else { - bootstrapApp(); + startEntry(); } } diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index ac1482e..7db6ceb 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -4,17 +4,31 @@ */ import { createReactiveStore } from '../core/reactive.js'; -import { callSidecarApi } from '../core/httpClient.js'; +import { callSidecarApi, isWindowOverlayMode } from '../core/httpClient.js'; + +/** + * 在主窗口双栖模式下,从宿主页面路径 `/c/` 提取当前正在浏览的会话 ID。 + * + * @returns {string} + */ +export function extractHostRouteCascadeId() { + if (typeof window === 'undefined' || !isWindowOverlayMode()) return ''; + const pathname = String(window.location?.pathname || ''); + const m = pathname.match(/^\/c\/([a-f0-9-]{36})(?:\/|$)/i); + return m ? m[1] : ''; +} const initialConversationId = (typeof window !== 'undefined' && window.sidecar?.conversationId) || ''; export const telemetryStore = createReactiveStore({ selectedConversationId: initialConversationId, + hostRouteConversationId: extractHostRouteCascadeId(), selectedTimeRange: 'today', customStartMs: Date.now() - 24 * 3600 * 1000, customEndMs: Date.now(), syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' + minuteTick: 0, telemetry: null, }); @@ -22,12 +36,49 @@ let pollTimer = null; let feedbackTimer = null; let activeBundleVersion = 0; let latestRequestSeq = 0; +let activeForceCount = 0; +let loopActive = false; +let loopIntervalMs = 2000; +let loopTickFn = null; + +export const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([ + 'context', + 'tps', + 'ttft', + 'cost', + 'quota_auto', + 'gemini_5h', + 'gemini_weekly', + 'claude_5h', + 'claude_weekly', + 'none', +]); + +export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']); + +/** + * 归一化前端顶栏胶囊三槽位配置数组,非法项回退默认值,且禁止三项同时为 `none`。 + * + * @param {unknown} raw + * @returns {[string, string, string]} + */ +export function normalizeClientTopbarSlots(raw) { + const arr = Array.isArray(raw) ? raw : []; + const slots = [0, 1, 2].map((idx) => { + const val = String(arr[idx] ?? '').trim(); + return CLIENT_TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_CLIENT_TOPBAR_SLOTS[idx]; + }); + if (slots.every((s) => s === 'none')) { + slots[0] = 'context'; + } + return slots; +} function isEquivalentTelemetry(prev, next) { if (!prev || !next) return false; if (prev === next) return true; - // 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关) + // 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关、双栖与顶栏槽位配置) const pAct = prev.activeConversation; const nAct = next.activeConversation; if (prev.settings?.showUpstreamModel !== next.settings?.showUpstreamModel) return false; @@ -35,14 +86,28 @@ function isEquivalentTelemetry(prev, next) { if (prev.settings?.weeklyTokenBudget !== next.settings?.weeklyTokenBudget) return false; if (prev.settings?.weeklyCostBudget !== next.settings?.weeklyCostBudget) return false; if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false; + if (prev.settings?.enableWindowOverlay !== next.settings?.enableWindowOverlay) return false; + if ((prev.settings?.showTopbarMultiSession !== false) !== (next.settings?.showTopbarMultiSession !== false)) { + return false; + } + const pTopSlots = prev.settings?.topbarCapsuleSlots; + const nTopSlots = next.settings?.topbarCapsuleSlots; + if ( + (pTopSlots?.[0] ?? 'context') !== (nTopSlots?.[0] ?? 'context') || + (pTopSlots?.[1] ?? 'tps') !== (nTopSlots?.[1] ?? 'tps') || + (pTopSlots?.[2] ?? 'quota_auto') !== (nTopSlots?.[2] ?? 'quota_auto') + ) { + return false; + } - // 2. 比对云端状态(插件当前/最新版本、价格表版本与模型数量、同步/更新执行状态及错误信息) + // 2. 比对云端状态(插件当前/最新版本、安装模式、价格表版本与模型数量、同步/更新执行状态及错误信息) const pCloud = prev.cloudStatus; const nCloud = next.cloudStatus; if ( pCloud?.currentPluginVersion !== nCloud?.currentPluginVersion || pCloud?.latestPluginVersion !== nCloud?.latestPluginVersion || pCloud?.updateAvailable !== nCloud?.updateAvailable || + pCloud?.installMode !== nCloud?.installMode || pCloud?.catalogVersion !== nCloud?.catalogVersion || pCloud?.source !== nCloud?.source || pCloud?.lastSyncedAtMs !== nCloud?.lastSyncedAtMs || @@ -56,15 +121,25 @@ function isEquivalentTelemetry(prev, next) { return false; } - // 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与单步费用) + // 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与费用) if (pAct?.cascadeId !== nAct?.cascadeId) return false; if (pAct?.stepCount !== nAct?.stepCount) return false; if (pAct?.subagentCount !== nAct?.subagentCount) return false; if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false; if (pAct?.isRunning !== nAct?.isRunning) return false; - if (pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature) return false; + if ( + pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature || + pAct?.liveActivity?.startedAtMs !== nAct?.liveActivity?.startedAtMs + ) { + return false; + } if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false; - if (pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature) return false; + if ( + pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature || + pAct?.aggregated?.liveActivity?.startedAtMs !== nAct?.aggregated?.liveActivity?.startedAtMs + ) { + return false; + } if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false; if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false; if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false; @@ -73,17 +148,34 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false; if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false; if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false; + if (pAct?.aggregated?.sessionUnpricedCalls !== nAct?.aggregated?.sessionUnpricedCalls) return false; + if (pAct?.aggregated?.sessionCacheHitPct !== nAct?.aggregated?.sessionCacheHitPct) return false; if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false; + if (pAct?.aggregated?.activeModelUpstream !== nAct?.aggregated?.activeModelUpstream) return false; if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false; if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false; if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false; + if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false; if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false; if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false; if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false; - if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false; - if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false; + if ( + pAct?.activeModelShort !== nAct?.activeModelShort || + pAct?.activeModelLabel !== nAct?.activeModelLabel || + pAct?.activeModelUpstream !== nAct?.activeModelUpstream + ) { + return false; + } + if ( + pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || + pAct?.sessionCostUsd !== nAct?.sessionCostUsd || + pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls + ) { + return false; + } const pAgents = pAct?.agents || []; const nAgents = nAct?.agents || []; @@ -91,8 +183,6 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pAgents.length; i++) { const pa = pAgents[i]; const na = nAgents[i]; - const pLastStep = pa?.recentSteps?.[0]; - const nLastStep = na?.recentSteps?.[0]; if ( pa?.agentId !== na?.agentId || pa?.role !== na?.role || @@ -103,11 +193,16 @@ function isEquivalentTelemetry(prev, next) { pa?.latestTtftSec !== na?.latestTtftSec || pa?.avgTokPerSec !== na?.avgTokPerSec || pa?.latestCacheHitPct !== na?.latestCacheHitPct || + pa?.sessionCacheHitPct !== na?.sessionCacheHitPct || pa?.latestSpeedReason !== na?.latestSpeedReason || pa?.latestStepCostUsd !== na?.latestStepCostUsd || pa?.sessionCostUsd !== na?.sessionCostUsd || + pa?.sessionUnpricedCalls !== na?.sessionUnpricedCalls || pa?.activeModelShort !== na?.activeModelShort || + pa?.activeModelUpstream !== na?.activeModelUpstream || pa?.context?.totalTokens !== na?.context?.totalTokens || + pa?.context?.compactionLimitTokens !== na?.context?.compactionLimitTokens || + pa?.context?.limitTokens !== na?.context?.limitTokens || pa?.context?.messagesTokens !== na?.context?.messagesTokens || pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens || pa?.context?.assistantTokens !== na?.context?.assistantTokens || @@ -118,21 +213,43 @@ function isEquivalentTelemetry(prev, next) { pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens || pa?.context?.skillsTokens !== na?.context?.skillsTokens || pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens || - pa?.context?.userRulesTokens !== na?.context?.userRulesTokens || - pLastStep?.tokPerSec !== nLastStep?.tokPerSec || - pLastStep?.ttftSec !== nLastStep?.ttftSec || - pLastStep?.outputTokens !== nLastStep?.outputTokens || - pLastStep?.modelUpstream !== nLastStep?.modelUpstream || - pLastStep?.costUsd !== nLastStep?.costUsd + pa?.context?.userRulesTokens !== na?.context?.userRulesTokens ) { return false; } + const paSteps = pa?.recentSteps || []; + const naSteps = na?.recentSteps || []; + if (paSteps.length !== naSteps.length) return false; + for (let j = 0; j < paSteps.length; j++) { + const bs = paSteps[j]; + const as = naSteps[j]; + if ( + bs?.stepIndex !== as?.stepIndex || + bs?.modelKey !== as?.modelKey || + bs?.modelShort !== as?.modelShort || + bs?.modelLabel !== as?.modelLabel || + bs?.modelUpstream !== as?.modelUpstream || + bs?.responseModel !== as?.responseModel || + bs?.modelSource !== as?.modelSource || + bs?.costUsd !== as?.costUsd || + bs?.tokPerSec !== as?.tokPerSec || + bs?.ttftSec !== as?.ttftSec || + bs?.outputTokens !== as?.outputTokens || + bs?.inputTokens !== as?.inputTokens || + bs?.cacheReadTokens !== as?.cacheReadTokens || + bs?.selectedSpeedReason !== as?.selectedSpeedReason + ) { + return false; + } + } } // 4. 比对 10 通道上下文窗口构成及近期步骤明细 const pCtx = pAct?.context; const nCtx = nAct?.context; if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; + if (pCtx?.compactionLimitTokens !== nCtx?.compactionLimitTokens) return false; + if (pCtx?.limitTokens !== nCtx?.limitTokens) return false; if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false; if (pCtx?.assistantTokens !== nCtx?.assistantTokens) return false; if (pCtx?.toolResultsTokens !== nCtx?.toolResultsTokens) return false; @@ -150,6 +267,7 @@ function isEquivalentTelemetry(prev, next) { if ( before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || + before.modelLabel !== after.modelLabel || before.modelUpstream !== after.modelUpstream || before.responseModel !== after.responseModel || before.modelSource !== after.modelSource || @@ -158,7 +276,8 @@ function isEquivalentTelemetry(prev, next) { before.ttftSec !== after.ttftSec || before.outputTokens !== after.outputTokens || before.inputTokens !== after.inputTokens || - before.cacheReadTokens !== after.cacheReadTokens + before.cacheReadTokens !== after.cacheReadTokens || + before.selectedSpeedReason !== after.selectedSpeedReason ) { return false; } @@ -181,8 +300,13 @@ function isEquivalentTelemetry(prev, next) { const pAcct = prev.consumption?.account; const nAcct = next.consumption?.account; if (pAcct?.totalTokens !== nAcct?.totalTokens) return false; + if (pAcct?.inputTokens !== nAcct?.inputTokens) return false; + if (pAcct?.cacheReadTokens !== nAcct?.cacheReadTokens) return false; + if (pAcct?.outputTokens !== nAcct?.outputTokens) return false; if (pAcct?.calls !== nAcct?.calls) return false; if (pAcct?.costUsd !== nAcct?.costUsd) return false; + if (pAcct?.savedCostUsd !== nAcct?.savedCostUsd) return false; + if (pAcct?.cacheHitPct !== nAcct?.cacheHitPct) return false; if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; // 6. 比对历史趋势时间分桶序列与年度分月序列 @@ -268,6 +392,7 @@ function isEquivalentTelemetry(prev, next) { if (pQuot?.usedPct !== nQuot?.usedPct) return false; if (pQuot?.remainingPct !== nQuot?.remainingPct) return false; if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false; + if (pQuot?.weeklyRemainingPct !== nQuot?.weeklyRemainingPct) return false; if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false; if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false; if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false; @@ -323,7 +448,8 @@ function isEquivalentTelemetry(prev, next) { pr?.isMainRunning !== nr?.isMainRunning || pr?.subagentCount !== nr?.subagentCount || pr?.runningSubagentCount !== nr?.runningSubagentCount || - pr?.mainActivity?.signature !== nr?.mainActivity?.signature + pr?.mainActivity?.signature !== nr?.mainActivity?.signature || + pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs ) { return false; } @@ -336,7 +462,8 @@ function isEquivalentTelemetry(prev, next) { pSubs[j]?.role !== nSubs[j]?.role || pSubs[j]?.isRunning !== nSubs[j]?.isRunning || pSubs[j]?.stepCount !== nSubs[j]?.stepCount || - pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature + pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature || + pSubs[j]?.liveActivity?.startedAtMs !== nSubs[j]?.liveActivity?.startedAtMs ) { return false; } @@ -347,25 +474,46 @@ function isEquivalentTelemetry(prev, next) { } export async function fetchTelemetry({ force = false } = {}) { + if (!force && activeForceCount > 0) { + return telemetryStore.getState().telemetry; + } + const st = telemetryStore.getState(); const reqSeq = ++latestRequestSeq; const startMs = Date.now(); if (force) { + activeForceCount += 1; + if (pollTimer) { + clearTimeout(pollTimer); + pollTimer = null; + } telemetryStore.setState({ syncState: 'syncing' }); } try { + if (isWindowOverlayMode()) { + const liveRouteId = extractHostRouteCascadeId(); + if (liveRouteId !== st.hostRouteConversationId) { + const patch = { hostRouteConversationId: liveRouteId }; + if (liveRouteId && st.selectedConversationId && st.selectedConversationId !== liveRouteId) { + patch.selectedConversationId = ''; + } + telemetryStore.setState(patch); + } + } + const curSt = telemetryStore.getState(); + const effectiveConvId = curSt.selectedConversationId || curSt.hostRouteConversationId || ''; const params = new URLSearchParams(); - if (st.selectedConversationId) { - params.set('conversationId', st.selectedConversationId); + if (effectiveConvId) { + params.set('conversationId', effectiveConvId); } - if (st.selectedTimeRange) { - params.set('range', st.selectedTimeRange); + if (curSt.selectedTimeRange) { + params.set('range', curSt.selectedTimeRange); } - if (st.selectedTimeRange === 'custom') { - if (st.customStartMs > 0) params.set('startMs', String(st.customStartMs)); - if (st.customEndMs > 0) params.set('endMs', String(st.customEndMs)); + if (curSt.selectedTimeRange === 'custom') { + if (curSt.customStartMs > 0) params.set('startMs', String(curSt.customStartMs)); + if (curSt.customEndMs > 0) params.set('endMs', String(curSt.customEndMs)); } if (force) { params.set('force', '1'); @@ -373,7 +521,7 @@ export async function fetchTelemetry({ force = false } = {}) { const qs = params.toString(); const payload = await callSidecarApi(`/api/telemetry${qs ? `?${qs}` : ''}`, { method: 'GET', - abortKey: 'telemetry-poll', + abortKey: force ? 'telemetry-force' : 'telemetry-poll', }); if (reqSeq !== latestRequestSeq) { @@ -382,7 +530,11 @@ export async function fetchTelemetry({ force = false } = {}) { if (payload?.uiBundleVersion) { if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) { - if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { + if ( + !isWindowOverlayMode() && + typeof window !== 'undefined' && + typeof window.location?.reload === 'function' + ) { window.location.reload(); return payload; } @@ -402,6 +554,7 @@ export async function fetchTelemetry({ force = false } = {}) { if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ telemetry: payload, + minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', }); feedbackTimer = setTimeout(() => { @@ -413,6 +566,7 @@ export async function fetchTelemetry({ force = false } = {}) { const nextTelemetry = isSame ? latestSt.telemetry : payload; telemetryStore.setState({ telemetry: nextTelemetry, + minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', }); } @@ -421,37 +575,46 @@ export async function fetchTelemetry({ force = false } = {}) { if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null; telemetryStore.setState({ syncState: 'error' }); return null; + } finally { + if (force) { + activeForceCount = Math.max(0, activeForceCount - 1); + if (activeForceCount === 0 && loopActive && loopTickFn && !pollTimer) { + pollTimer = setTimeout(loopTickFn, loopIntervalMs); + } + } } } export async function saveSettingsPatch(patch) { + const safePatch = patch && typeof patch === 'object' ? { ...patch } : {}; + if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { + const mode = safePatch.weeklyLimitMode; + safePatch.weeklyLimitMode = + mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official'; + } + if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) { + safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession); + } + if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { + safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); + } const prevTelemetry = telemetryStore.getState().telemetry; if (prevTelemetry?.settings) { telemetryStore.setState({ telemetry: { ...prevTelemetry, - settings: { ...prevTelemetry.settings, ...patch }, - activeConversation: patch.contextWindowLimit - ? { - ...prevTelemetry.activeConversation, - context: { - ...prevTelemetry.activeConversation?.context, - limitTokens: patch.contextWindowLimit, - usedPct: Math.min( - 100, - Math.round( - ((prevTelemetry.activeConversation?.context?.totalTokens || 0) / - Math.max(1, patch.contextWindowLimit)) * - 100 - ) - ), - }, - } - : prevTelemetry.activeConversation, + settings: { ...prevTelemetry.settings, ...safePatch }, }, }); } - await callSidecarApi('/api/settings', { method: 'POST', body: patch }); + try { + await callSidecarApi('/api/settings', { method: 'POST', body: safePatch }); + } catch (err) { + if (prevTelemetry) { + telemetryStore.setState({ telemetry: prevTelemetry }); + } + throw err; + } await fetchTelemetry({ force: true }); } @@ -465,7 +628,11 @@ export async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { await new Promise((r) => setTimeout(r, 1100)); - if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { + if ( + !isWindowOverlayMode() && + typeof window !== 'undefined' && + typeof window.location?.reload === 'function' + ) { window.location.reload(); return res; } @@ -476,27 +643,44 @@ export async function triggerPluginUpdate() { export function startAsyncTelemetryLoop(intervalMs = 2000) { stopAsyncTelemetryLoop(); - let active = true; + loopActive = true; + loopIntervalMs = intervalMs; + + const resolveNextDelay = () => { + if (isWindowOverlayMode() && typeof document !== 'undefined' && document.hidden) { + return Math.max(loopIntervalMs, 8000); + } + return loopIntervalMs; + }; const tick = async () => { - if (!active) return; + pollTimer = null; + if (!loopActive) return; await fetchTelemetry({ force: false }); - if (!active) return; - pollTimer = setTimeout(tick, intervalMs); + if (!loopActive || activeForceCount > 0) return; + if (!pollTimer) { + pollTimer = setTimeout(tick, resolveNextDelay()); + } }; + loopTickFn = tick; tick(); return () => { - active = false; stopAsyncTelemetryLoop(); }; } export function stopAsyncTelemetryLoop() { + loopActive = false; + loopTickFn = null; if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; } + if (feedbackTimer) { + clearTimeout(feedbackTimer); + feedbackTimer = null; + } } /** diff --git a/sidecars/panel/src/styles/animations.css b/sidecars/panel/src/styles/animations.css index 9d9099a..acbb341 100644 --- a/sidecars/panel/src/styles/animations.css +++ b/sidecars/panel/src/styles/animations.css @@ -14,12 +14,10 @@ @keyframes anim-pulse-dot { 0%, 100% { - transform: scale(1); opacity: 1; } 50% { - transform: scale(1.22); - opacity: 0.62; + opacity: 0.22; } } diff --git a/sidecars/panel/src/styles/base.css b/sidecars/panel/src/styles/base.css index 5f13853..1e963cd 100644 --- a/sidecars/panel/src/styles/base.css +++ b/sidecars/panel/src/styles/base.css @@ -40,6 +40,11 @@ button, input { font-family: inherit; font-size: inherit; + font-stretch: inherit; + font-variation-settings: inherit; + line-height: inherit; + letter-spacing: inherit; + font-variant-numeric: inherit; color: inherit; } diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index 4507135..333b12c 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -523,10 +523,6 @@ overflow: hidden; } -.custom-scroll-host[hidden] { - display: none !important; -} - .custom-scroll-content { flex: 1; min-width: 0; @@ -678,10 +674,6 @@ transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast); } -.update-badge-btn[hidden] { - display: none !important; -} - .update-badge-btn:hover { opacity: 0.9; } @@ -689,3 +681,130 @@ .update-badge-btn:active { transform: scale(0.96); } + +/* --- 9. 顶部栏定制面板专属表单与排序槽位控件 (Topbar Customization Controls) --- */ +.settings-inline-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + min-height: 26px; +} + +.topbar-header-right { + display: inline-flex; + align-items: center; + gap: var(--space-2); +} + +.btn-ghost-sm { + display: inline-flex; + align-items: center; + justify-content: center; + height: 20px; + padding: 0 6px; + font-size: 11px; + font-weight: 500; + color: var(--text-secondary); + background: transparent; + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + cursor: pointer; + white-space: nowrap; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast), + border-color var(--dur-instant) var(--ease-fast); +} + +.btn-ghost-sm:hover:not(:disabled) { + background: var(--surface-hover); + color: var(--text-primary); + border-color: var(--border-strong); +} + +.btn-ghost-sm:disabled { + opacity: 0.42; + cursor: default; +} + +.topbar-slot-list { + display: flex; + flex-direction: column; + gap: 6px; +} + +.topbar-slot-row { + position: relative; + display: flex; + align-items: center; + gap: 6px; + padding: 2px 4px 2px 6px; + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + background: transparent; + transition: border-color var(--dur-instant) var(--ease-fast); +} + +.topbar-slot-row:focus-within, +.topbar-slot-row:has(.is-open) { + z-index: 30; + border-color: var(--border-strong); +} + +.topbar-slot-row .select-menu { + max-height: 216px; +} + +.slot-index-badge { + display: inline-flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + font-size: 10.5px; + font-weight: 600; + font-variant-numeric: tabular-nums; + color: var(--text-secondary); + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + border-radius: var(--radius-xs); + flex-shrink: 0; +} + +.slot-order-btns { + display: inline-flex; + align-items: center; + gap: 2px; + flex-shrink: 0; +} + +.slot-move-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + padding: 0; + border: none; + border-radius: var(--radius-xs); + background: transparent; + color: var(--text-secondary); + cursor: pointer; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.slot-move-btn:hover:not(:disabled) { + background: var(--surface-hover); + color: var(--text-primary); +} + +.slot-move-btn:active:not(:disabled) { + transform: scale(0.94); +} + +.slot-move-btn:disabled { + opacity: 0.28; + cursor: default; +} diff --git a/sidecars/panel/src/styles/overlay.css b/sidecars/panel/src/styles/overlay.css new file mode 100644 index 0000000..c5fa8fa --- /dev/null +++ b/sidecars/panel/src/styles/overlay.css @@ -0,0 +1,589 @@ +/* + * 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css). + * 严格遵循单层微边框与语义变量规范(零硬编码色值、零 Emoji、硬件加速合成层动画)。 + */ + +/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */ +:host(.wm-capsule-host) { + display: inline-flex; + align-items: center; + gap: 6px; + height: 28px; + flex-shrink: 0; + vertical-align: middle; + -webkit-app-region: no-drag; + pointer-events: auto; + user-select: none; + font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; + font-size: 12px; + font-weight: 450; + font-stretch: 100%; + font-variation-settings: normal; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + -webkit-font-smoothing: antialiased; + color: var(--text-primary); + z-index: 2147482900; +} + +:host(.wm-capsule-host[data-dock="flow"]) { + position: relative; + margin-right: 4px; +} + +:host(.wm-capsule-host[data-dock="fixed"]) { + position: fixed; + top: 6px; + right: 144px; +} + +@keyframes wm-dot-pulse { + 0%, 100% { + opacity: 1; + } + 50% { + opacity: 0.38; + } +} + +/* 左侧多会话实时状态触发器(无边框、与宿主顶栏按钮同高 28px、整数行高防压扁) */ +.wm-multi-btn { + position: relative; + display: inline-flex; + align-items: center; + gap: 6px; + height: 28px; + padding: 0 8px; + margin: 0; + background: transparent; + color: var(--text-secondary); + border: none; + outline: none; + box-shadow: none; + border-radius: var(--radius-sm); + font-family: inherit; + font-size: 12px; + font-weight: 450; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + cursor: pointer; + -webkit-app-region: no-drag; + white-space: nowrap; + contain: layout style; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.wm-multi-btn[hidden], +.wm-cap-slot[hidden], +.wm-sep[hidden] { + display: none !important; +} + +.wm-multi-btn:hover { + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + color: var(--text-primary); +} + +.wm-multi-btn.is-open { + background: color-mix(in srgb, var(--text-primary) 11%, transparent); + color: var(--text-primary); +} + +.wm-multi-dot { + width: 8px; + height: 8px; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-secondary) 44%, transparent); + flex-shrink: 0; +} + +.wm-multi-btn.is-running .wm-multi-dot { + background: var(--accent-primary); + animation: wm-dot-pulse 1.5s ease-in-out infinite; +} + +.wm-multi-btn.is-waiting .wm-multi-dot { + background: var(--metric-warn); + animation: wm-dot-pulse 1.5s ease-in-out infinite; +} + +.wm-multi-label { + display: inline-block; + min-width: 46px; + line-height: 18px; + text-align: left; + white-space: nowrap; + flex-shrink: 0; +} + +.wm-multi-btn.is-running .wm-multi-label, +.wm-multi-btn.is-waiting .wm-multi-label { + color: var(--text-primary); + font-weight: 500; +} + +.wm-capsule-btn { + position: relative; + display: inline-flex; + align-items: center; + gap: 8px; + height: 28px; + padding: 0 9px; + margin: 0; + background: transparent; + color: var(--text-secondary); + border: none; + outline: none; + box-shadow: none; + border-radius: var(--radius-sm); + font-family: inherit; + font-size: 12px; + font-weight: 450; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + cursor: pointer; + -webkit-app-region: no-drag; + white-space: nowrap; + contain: layout style; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.wm-capsule-btn:hover { + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + color: var(--text-primary); +} + +.wm-capsule-btn.is-open { + background: color-mix(in srgb, var(--text-primary) 11%, transparent); + color: var(--text-primary); +} + +/* 右侧胶囊通用槽位容器与按指标预占定宽(严格防止动态数值跳动,保留舒展字间距) */ +.wm-cap-slot { + display: inline-flex; + align-items: center; + justify-content: center; + height: 18px; + line-height: 18px; + flex-shrink: 0; + color: var(--text-secondary); +} + +.wm-slot-text { + display: inline-block; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + flex-shrink: 0; +} + +/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */ +.wm-ctx-seg { + justify-content: center; + gap: 5px; + width: 50px; +} + +.wm-ring-svg { + width: 14px; + height: 14px; + flex-shrink: 0; + transform: rotate(-90deg); +} + +.wm-ring-track { + fill: none; + stroke: color-mix(in srgb, var(--text-secondary) 24%, transparent); + stroke-width: 2; +} + +.wm-ring-fill { + fill: none; + stroke: var(--accent-primary); + stroke-width: 2; + stroke-linecap: round; + transition: + stroke-dashoffset var(--dur-normal) var(--ease-fast), + stroke var(--dur-fast) var(--ease-fast); +} + +.wm-ring-fill.tone-warn { + stroke: var(--metric-warn); +} + +.wm-ring-fill.tone-danger { + stroke: var(--metric-danger); +} + +.wm-ctx-pct { + min-width: 27px; + max-width: 31px; + text-align: left; + font-weight: 500; + color: var(--text-primary); +} + +.wm-sep { + width: 1px; + height: 12px; + background: color-mix(in srgb, var(--text-secondary) 26%, transparent); + flex-shrink: 0; +} + +/* 速度槽位(固定预占宽度 58px 居中对齐) */ +.wm-seg-speed { + width: 58px; +} + +.wm-speed-text { + width: 58px; + text-align: center; +} + +.wm-seg-speed.state-running { + color: var(--metric-speed); + font-weight: 500; +} + +/* 首字延迟槽位(固定预占宽度 46px 居中对齐,覆盖 0.85s ~ 105s) */ +.wm-seg-ttft { + width: 46px; +} + +.wm-ttft-text { + width: 46px; + text-align: center; +} + +/* 本次费用槽位(固定预占宽度 52px 居中对齐,覆盖 <$0.001 ~ $99.99) */ +.wm-seg-cost { + width: 52px; +} + +.wm-cost-text { + width: 52px; + text-align: center; + color: var(--text-primary); + font-weight: 500; +} + +/* 配额槽位(固定预占宽度 52px 居中对齐,完整容纳 余 100% / 余 --% 且在任意槽位对称) */ +.wm-seg-quota { + width: 52px; +} + +.wm-quota-text { + width: 52px; + text-align: center; +} + +.wm-cap-slot.tone-warn, +.wm-cap-slot.tone-warn .wm-slot-text { + color: var(--metric-warn); + font-weight: 500; +} + +.wm-cap-slot.tone-danger, +.wm-cap-slot.tone-danger .wm-slot-text { + color: var(--metric-danger); + font-weight: 500; +} + +/* 右上角绝对定位更新圆点,不参与文档流,零宽度抖动 */ +.wm-update-dot { + position: absolute; + top: 3px; + right: 3px; + width: 5px; + height: 5px; + border-radius: var(--radius-pill); + background: var(--metric-ok); + pointer-events: none; +} + +/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 与分隔线次序 data-sep-for-rank 动态折叠) */ +:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="3"], +:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"] { + display: none !important; +} + +:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="2"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="3"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="2"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="3"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-label { + display: none !important; +} + +:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-btn, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-btn { + padding: 0 7px; +} + +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="2"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="3"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="2"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="3"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label { + display: none !important; +} + +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-capsule-btn { + padding: 0 6px; +} + +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg { + width: 14px; +} + +/* --- 2. 顶层浮层传送门宿主 (Body Portal Host: Multi-Session HUD, Tooltip & Full 4-Tab Popover) --- */ +:host(.wm-portal-host) { + position: fixed; + inset: 0; + width: 0; + height: 0; + overflow: visible; + pointer-events: none; + z-index: 2147483000; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; + font-size: 12.5px; + line-height: 1.4; + font-variant-numeric: tabular-nums; + -webkit-font-smoothing: antialiased; + color: var(--text-primary); +} + +@keyframes wm-popover-in { + from { + opacity: 0; + transform: translateY(-3px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.wm-popover-panel { + position: fixed; + top: 42px; + left: 12px; + width: min(492px, calc(100vw - 24px)); + height: min(588px, calc(100vh - 54px)); + max-height: calc(100vh - 54px); + display: flex; + flex-direction: column; + background: var(--surface-bg); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-overlay); + pointer-events: auto; + overflow: hidden; + -webkit-app-region: no-drag; + transform-origin: top right; + animation: wm-popover-in var(--dur-fast) var(--ease-fast); +} + +.wm-popover-panel .app-shell { + height: 100%; + max-height: 100%; + max-width: none; +} + +/* 顶栏胶囊悬停全景概览浮层(复用实时概览三卡片架构,全槽位预占,仅就地更新节点不跳动) */ +.wm-hover-tip { + position: fixed; + top: 42px; + left: 12px; + width: min(492px, calc(100vw - 24px)); + max-height: calc(100vh - 54px); + padding: var(--space-3) var(--space-4); + display: flex; + flex-direction: column; + gap: var(--space-3); + background: var(--surface-bg); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-overlay); + pointer-events: none; + overflow: hidden; + contain: layout style; + z-index: 2147483001; + transform-origin: top right; + animation: wm-popover-in var(--dur-instant) var(--ease-fast); +} + +/* 左侧在线多会话实时看板浮层(单层无套娃细线卡片,仅显示在线运行会话,留足呼吸感) */ +.wm-multi-panel { + position: fixed; + top: 42px; + left: 12px; + width: min(484px, calc(100vw - 24px)); + max-height: calc(100vh - 54px); + padding: 14px 16px; + display: flex; + flex-direction: column; + gap: 0; + background: var(--surface-bg); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-overlay); + pointer-events: auto; + overflow-x: hidden; + overflow-y: auto; + -webkit-app-region: no-drag; + contain: layout style; + z-index: 2147483002; + transform-origin: top left; + animation: wm-popover-in var(--dur-instant) var(--ease-fast); +} + +.wm-popover-panel.is-instant, +.wm-hover-tip.is-instant, +.wm-multi-panel.is-instant { + animation: none !important; +} + +.wm-hover-tip .cell-label, +.wm-hover-tip .legend-item, +.wm-hover-tip .legend-left, +.wm-hover-tip .panel-header > span { + white-space: nowrap; + min-width: 0; +} + +.wm-hover-tip .panel-header > span:first-child:not(.panel-title) { + overflow: hidden; + text-overflow: ellipsis; +} + +.wm-hover-quota-pools { + display: flex; + flex-direction: column; + gap: 0; +} + +.wm-hover-quota-foot { + font-size: 11px; + padding-top: 2px; +} + +.wm-pin-badge { + display: inline-flex; + align-items: center; + height: 16px; + padding: 0 5px; + font-size: 10px; + font-weight: 600; + color: var(--accent-primary); + background: var(--accent-primary-soft); + border-radius: var(--radius-xs); + flex-shrink: 0; +} + +.wm-session-tag { + display: inline-flex; + align-items: center; + height: 16px; + padding: 0 4px; + font-size: 10px; + font-weight: 600; + color: var(--text-secondary); + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + border-radius: var(--radius-xs); + white-space: nowrap; + flex-shrink: 0; +} + +.wm-session-tag.is-here { + color: var(--accent-primary); + background: var(--accent-primary-soft); +} + +.wm-task-metrics { + font-size: 11px; + color: var(--text-secondary); + white-space: nowrap; + flex-shrink: 0; +} + +.wm-multi-header { + padding-bottom: 10px; + border-bottom: 1px solid var(--border-hairline); +} + +/* 多会话单层面板内去除重复边框与底色,留足行距与段落呼吸感,仅靠左侧圆点闪烁表达状态 */ +.wm-multi-panel .live-activity-list { + gap: 0; +} + +.wm-multi-panel .live-task-card { + gap: 8px; + padding: 12px 2px; + border: none; + border-radius: 0; + background: transparent; +} + +.wm-multi-panel .live-task-card:first-child { + padding-top: 11px; +} + +.wm-multi-panel .live-task-card:last-child { + padding-bottom: 2px; +} + +.wm-multi-panel .live-task-card + .live-task-card { + border-top: 1px solid var(--border-hairline); +} + +.wm-multi-panel .live-task-title { + font-size: 12.5px; +} + +.wm-multi-empty { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + min-height: 36px; + padding: 12px 2px 4px; + font-size: 12px; + color: var(--text-secondary); +} + +.wm-multi-empty-left { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; +} + +.wm-idle-dot { + width: 8px; + height: 8px; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-secondary) 38%, transparent); + flex-shrink: 0; +} + +.wm-multi-empty-hint { + font-size: 11px; + color: var(--text-muted); + white-space: nowrap; + flex-shrink: 0; +} diff --git a/sidecars/panel/src/styles/tokens.css b/sidecars/panel/src/styles/tokens.css index 099fe8e..48a7b42 100644 --- a/sidecars/panel/src/styles/tokens.css +++ b/sidecars/panel/src/styles/tokens.css @@ -4,26 +4,24 @@ * eliminating hardcoded hex colors across components and views. */ -:root { +:root, +:host { /* Architectural Geometry: Only Top Nav uses --radius-pill */ --radius-pill: 999px; --radius-sm: 4px; --radius-xs: 2px; - /* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode) */ + /* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode & safe dark fallback) */ --surface-bg: var(--background, hsl(0 0% 100%)); - --surface-panel: var(--card, hsl(0 0% 100%)); + --surface-panel: var(--card, var(--background, hsl(0 0% 100%))); --surface-subtle: color-mix(in srgb, var(--surface-panel) 97%, var(--text-primary) 3%); --surface-track: color-mix(in srgb, var(--border-hairline) 42%, var(--surface-panel)); - --surface-elevated: var(--surface-panel); --surface-hover: color-mix(in srgb, var(--accent-primary) 6%, var(--surface-panel)); --surface-active: color-mix(in srgb, var(--accent-primary) 12%, var(--surface-panel)); - --surface-backdrop: color-mix(in srgb, var(--surface-bg) 78%, transparent); /* Crisp 1px Hairline Borders */ --border-hairline: color-mix(in srgb, var(--border, hsl(214 18% 88%)) 82%, var(--surface-panel)); --border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%); - --border-focus: var(--accent-primary); /* Typography Hierarchy */ --text-primary: var(--foreground, hsl(215 22% 15%)); @@ -46,10 +44,8 @@ --metric-warn-soft: color-mix(in srgb, var(--metric-warn) 15%, transparent); --metric-danger: var(--destructive, hsl(0 74% 50%)); - --metric-danger-soft: color-mix(in srgb, var(--metric-danger) 15%, transparent); /* Context Window 10-Channel Palette */ - --ctx-messages: hsl(217 82% 51%); --ctx-assistant: hsl(217 82% 54%); --ctx-tool-results: hsl(192 82% 43%); --ctx-user-input: hsl(245 72% 62%); @@ -69,7 +65,7 @@ /* Elevation & Shadows */ --shadow-popover: 0 4px 12px rgb(0 0 0 / 0.22); - --shadow-glider: 0 1px 2px rgb(0 0 0 / 0.14); + --shadow-overlay: 0 16px 38px rgb(0 0 0 / 0.38), 0 3px 10px rgb(0 0 0 / 0.22); /* Fast Hardware-Accelerated Motion Tokens */ --ease-fast: cubic-bezier(0.22, 1, 0.36, 1); @@ -78,10 +74,8 @@ --dur-normal: 180ms; /* Spacing & Density */ - --space-1: 4px; --space-2: 6px; --space-3: 8px; --space-4: 10px; --space-5: 12px; - --space-6: 14px; } diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index f5187a1..ca789e7 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -1,14 +1,14 @@ /* * 全景消耗统计视图样式表 (views-consumption.css). * 包含: - * 1. 消费概览顶栏与 3+2 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-*, .cons-col) + * 1. 消费概览顶栏与 3+3 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-3, .cons-col) * 2. 4 段比例条与圆点色块 (.dot-swatch, .cons-seg-bar) * 3. 热门模型与数据来源列表项样式 (.cons-row-*, .cons-share-pill, .cons-item-*) * 4. 历史趋势纯 SVG 平滑曲线图与峰值胶囊 (.trend-*) * 5. 12 个月垂直堆叠柱状图与月度图例 (.monthly-*, .month-*) */ -/* --- 1. 消费概览顶栏与 3+2 组合指标矩阵 (Consumption Overview Matrix) --- */ +/* --- 1. 消费概览顶栏与 3+3 组合指标矩阵 (Consumption Overview Matrix) --- */ .cons-overview-head { flex-wrap: wrap; gap: 6px; @@ -48,15 +48,28 @@ grid-template-columns: repeat(3, 1fr); } -.cons-split-2 { - display: grid; - grid-template-columns: 1fr 1fr; -} - .cons-matrix-bottom { border-top: 1px solid var(--border-hairline); } +.cons-matrix-bottom .cons-col { + gap: 4px; +} + +@media (max-width: 350px) { + .cons-matrix-bottom.cons-split-3 { + grid-template-columns: 1fr; + } + .cons-matrix-bottom .cons-col { + padding-left: 0; + padding-right: 0; + } + .cons-matrix-bottom .cons-col.is-bordered-col { + border-left: none; + border-top: 1px solid var(--border-hairline); + } +} + .cons-col { display: flex; flex-direction: column; @@ -105,10 +118,34 @@ letter-spacing: -0.02em; } -.cons-mid-num { - font-size: 13px; - font-weight: 700; +.cons-sub-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + min-width: 0; +} + +.cons-sub-head > span { + white-space: nowrap; + flex-shrink: 0; +} + +.cons-sub-label { + font-size: 11.5px; + font-weight: 600; color: var(--text-primary); + white-space: nowrap; + flex-shrink: 0; +} + +.cons-mid-num { + font-size: 14.5px; + font-weight: 700; + line-height: 1.25; + color: var(--text-primary); + letter-spacing: -0.015em; + white-space: nowrap; } /* --- 2. 4 段比例条与圆点色块 (Four-Segment Bar & Dot Swatches) --- */ diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 36933a4..2b3b930 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -3,7 +3,7 @@ * 包含: * 1. 通用面板容器与标题头 (.panel, .panel-header, .panel-title, .panel-meta) * 2. 4 格实时测速指标矩阵 (.telemetry-matrix, .matrix-cell, .cell-*) - * 3. 6 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill) + * 3. 10 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill) * 4. 上下文双列图例网格与色块 (.ctx-legend-grid, .legend-*, .swatch) * 5. 双栏布局网格与窄屏响应式断点 (.dual-grid) */ @@ -57,50 +57,42 @@ .live-activity-list { display: flex; flex-direction: column; - gap: 6px; + gap: 8px; flex-shrink: 0; min-width: 0; } -.live-activity-list[hidden] { - display: none !important; -} - .live-task-card { display: flex; flex-direction: column; - gap: 5px; - padding: 7px 10px; - border: 1px solid var(--accent-primary-border); + gap: 7px; + padding: 10px 12px; + border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); - background: color-mix(in srgb, var(--accent-primary) 5%, var(--surface-panel)); + background: var(--surface-panel); min-width: 0; } -.live-task-card.is-waiting { - border-color: color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); - background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel)); -} - .live-task-header { display: flex; align-items: center; justify-content: space-between; - gap: var(--space-2); + gap: var(--space-3); min-width: 0; } .live-task-title-wrap { display: flex; align-items: center; - gap: 5px; + gap: 7px; min-width: 0; flex: 1; } .live-task-title { - font-size: 11.5px; + font-size: 12px; font-weight: 600; + line-height: 1.45; color: var(--text-primary); white-space: nowrap; overflow: hidden; @@ -116,7 +108,7 @@ .live-task-header-right { display: inline-flex; align-items: center; - gap: 6px; + gap: 8px; flex-shrink: 0; } @@ -151,16 +143,13 @@ background: var(--accent-primary-soft); } -.live-sub-toggle[hidden] { - display: none !important; -} - .live-task-main-row { display: flex; align-items: center; - gap: 5px; + gap: 6px; min-width: 0; - padding-left: 1px; + padding-left: 18px; + line-height: 1.45; } .live-activity-dot { @@ -174,37 +163,37 @@ color: var(--metric-warn); } +.live-task-card.is-compacting .live-activity-dot { + color: var(--ctx-checkpoint); +} + .live-activity-phase { - font-size: 11px; + font-size: 11.5px; font-weight: 600; color: var(--text-primary); white-space: nowrap; flex-shrink: 0; } -.live-task-card.is-waiting .live-activity-phase { - color: var(--metric-warn); -} - .live-activity-progress { - font-size: 10px; + font-size: 10.5px; font-weight: 600; color: var(--accent-primary); background: var(--accent-primary-soft); - padding: 0 4px; + padding: 0 5px; border-radius: var(--radius-xs); white-space: nowrap; flex-shrink: 0; } .live-activity-sep { - font-size: 11px; + font-size: 11.5px; color: var(--text-muted); flex-shrink: 0; } .live-activity-detail { - font-size: 11px; + font-size: 11.5px; color: var(--text-secondary); white-space: nowrap; overflow: hidden; @@ -214,38 +203,35 @@ } .live-activity-elapsed { - font-size: 11px; - font-weight: 600; - color: var(--accent-primary); + font-size: 11.5px; + font-weight: 500; + color: var(--text-secondary); white-space: nowrap; + min-width: 28px; + text-align: right; flex-shrink: 0; } -.live-task-card.is-waiting .live-activity-elapsed { - color: var(--metric-warn); -} - .live-sub-list { display: flex; flex-direction: column; - gap: 4px; - padding-top: 5px; - margin-top: 1px; + gap: 8px; + padding-top: 9px; + margin-top: 3px; + margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; } -.live-sub-list[hidden] { - display: none !important; -} - .live-sub-row { display: flex; align-items: center; justify-content: space-between; - gap: var(--space-2); + gap: 10px; + min-height: 22px; min-width: 0; - font-size: 10.5px; + font-size: 11.5px; + line-height: 1.45; } .live-sub-row.is-done { @@ -255,7 +241,7 @@ .live-sub-left { display: flex; align-items: center; - gap: 5px; + gap: 7px; min-width: 0; flex: 1; } @@ -266,7 +252,7 @@ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - max-width: 110px; + max-width: 148px; flex-shrink: 0; } @@ -280,9 +266,11 @@ } .live-sub-elapsed { - font-size: 10.5px; + font-size: 11px; color: var(--text-secondary); white-space: nowrap; + min-width: 28px; + text-align: right; flex-shrink: 0; } @@ -339,7 +327,7 @@ text-overflow: ellipsis; } -/* --- 3. 6 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */ +/* --- 3. 10 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */ .progress-track { width: 100%; height: 6px; @@ -444,6 +432,7 @@ align-items: center; gap: 5px; color: var(--text-secondary); + white-space: nowrap; } .swatch { @@ -463,10 +452,6 @@ .swatch.seg-skills { background: var(--ctx-skills); } .swatch.seg-system-prompt { background: var(--ctx-system-prompt); } .swatch.seg-user-rules { background: var(--ctx-user-rules); } -.swatch.seg-cached { background: var(--ctx-cached); } -.swatch.seg-input { background: var(--ctx-input); } -.swatch.seg-thinking { background: var(--ctx-thinking); } -.swatch.seg-output { background: var(--ctx-output); } /* --- 5. 双栏网格与窄视口响应式折叠 (Dual Grid & Responsive Breakpoints) --- */ .dual-grid { diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 7447121..99c74c3 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -1,9 +1,9 @@ /** * @fileoverview View 2: ConsumptionView (全景消耗统计视图). * 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗: - * 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+2 组合矩阵展示总 Token/调用次数、 - * USD/CNY 预估费用、缓存命中率与命中量、输入/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。 - * 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡与首/中/末三时间锚点。 + * 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+3 组合矩阵展示总 Token/调用次数、 + * USD/CNY 预估费用、缓存命中率与命中量、新输入/缓存读取(含节省费用)/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。 + * 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡、对齐多刻度时间轴与悬停详情浮层。 * 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。 * 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。 * 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。 @@ -48,27 +48,45 @@ export const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { // --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 --- + let draftStartMs = telemetryStore.getState().customStartMs; + let draftEndMs = telemetryStore.getState().customEndMs; + let hasUncommittedCustomDraft = false; + const timeFilterSwitch = SegmentedControl({ ariaLabel: '消耗统计时间范围', modelValue: telemetryStore.getState().selectedTimeRange, options: TIME_RANGE_OPTIONS, onUpdateModelValue: (nextRange) => { + if (nextRange === 'custom') { + const st = telemetryStore.getState(); + draftStartMs = st.customStartMs; + draftEndMs = st.customEndMs; + hasUncommittedCustomDraft = false; + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + } else { + hasUncommittedCustomDraft = false; + } telemetryStore.setState({ selectedTimeRange: nextRange }); fetchTelemetry({ force: false }); }, }); const startPicker = CustomDateTimePicker({ - modelValue: telemetryStore.getState().customStartMs, + modelValue: draftStartMs, onUpdateModelValue: (ms) => { - telemetryStore.setState({ customStartMs: ms }); + draftStartMs = ms; + hasUncommittedCustomDraft = true; + startPicker.setValue(ms); }, }); const endPicker = CustomDateTimePicker({ - modelValue: telemetryStore.getState().customEndMs, + modelValue: draftEndMs, onUpdateModelValue: (ms) => { - telemetryStore.setState({ customEndMs: ms }); + draftEndMs = ms; + hasUncommittedCustomDraft = true; + endPicker.setValue(ms); }, }); @@ -79,20 +97,20 @@ export const ConsumptionView = defineComponent({ className: 'btn-primary', style: 'height: 26px; padding: 0 10px;', onClick: () => { - const st = telemetryStore.getState(); - const sMs = Number(st.customStartMs || 0); - const eMs = Number(st.customEndMs || 0); - if (sMs > 0 && eMs > 0 && sMs > eMs) { - startPicker.setValue(eMs); - endPicker.setValue(sMs); - telemetryStore.setState({ - selectedTimeRange: 'custom', - customStartMs: eMs, - customEndMs: sMs, - }); - } else { - telemetryStore.setState({ selectedTimeRange: 'custom' }); - } + const sMs = Number(draftStartMs || 0); + const eMs = Number(draftEndMs || 0); + const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs; + const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs; + draftStartMs = minMs; + draftEndMs = maxMs; + hasUncommittedCustomDraft = false; + startPicker.setValue(minMs); + endPicker.setValue(maxMs); + telemetryStore.setState({ + selectedTimeRange: 'custom', + customStartMs: minMs, + customEndMs: maxMs, + }); fetchTelemetry({ force: true }); }, }, @@ -114,7 +132,7 @@ export const ConsumptionView = defineComponent({ ] ); - // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 2 列输入/输出拆分 + 底部 4 段比例条) --- + // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' }); @@ -126,7 +144,11 @@ export const ConsumptionView = defineComponent({ const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' }); const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); - const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '新输入 0 · 缓存 0' }); + const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '未命中缓存输入' }); + + const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: 11.5px;', text: '0%' }); + const cacheMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); + const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '节省 $0.00' }); const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' }); const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); @@ -161,27 +183,38 @@ export const ConsumptionView = defineComponent({ h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), ]), ]), - h('div', { className: 'cons-split-2 cons-matrix-bottom' }, [ + h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ h('div', { className: 'cons-col' }, [ - h('div', { className: 'panel-header' }, [ - h('span', { className: 'legend-left' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ h('span', { className: 'dot-swatch seg-input' }), - h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输入用量' }), - inputMainTokens, + h('span', { text: '新输入' }), ]), inputSharePct, ]), + inputMainTokens, inputSubText, ]), h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'panel-header' }, [ - h('span', { className: 'legend-left' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存读取' }), + ]), + cacheSharePct, + ]), + cacheMainTokens, + cacheSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ h('span', { className: 'dot-swatch seg-output' }), - h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输出用量' }), - outputMainTokens, + h('span', { text: '输出用量' }), ]), outputSharePct, ]), + outputMainTokens, outputSubText, ]), ]), @@ -416,8 +449,12 @@ export const ConsumptionView = defineComponent({ if (!slice) return; timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); - startPicker.setValue(slice.customStartMs); - endPicker.setValue(slice.customEndMs); + if (!hasUncommittedCustomDraft) { + draftStartMs = slice.customStartMs; + draftEndMs = slice.customEndMs; + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + } const cons = slice.consumption || {}; const preset = @@ -436,6 +473,7 @@ export const ConsumptionView = defineComponent({ const responseTokens = Number(acct.responseTokens || 0); const thinkingTokens = Number(acct.thinkingTokens || 0); const costUsd = Number(acct.costUsd || 0); + const savedCostUsd = Number(acct.savedCostUsd || 0); patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); patchText(heroTotalCalls, `${acct.calls || 0} 次`); @@ -445,13 +483,37 @@ export const ConsumptionView = defineComponent({ patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`); patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`); - const inPct = totalTokens > 0 ? +((inputTokens / totalTokens) * 100).toFixed(1) : 0; - const outPct = totalTokens > 0 ? +((outputTokens / totalTokens) * 100).toFixed(1) : 0; + let inPct = 0; + let cachePct = 0; + let outPct = 0; + if (totalTokens > 0) { + const rawTenths = [ + (inputTokens / totalTokens) * 1000, + (cacheTokens / totalTokens) * 1000, + (outputTokens / totalTokens) * 1000, + ]; + const floored = rawTenths.map((v) => Math.max(0, Math.floor(v))); + const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2])); + const order = [0, 1, 2].sort( + (a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a]) + ); + for (let k = 0; k < rem && k < 3; k++) { + floored[order[k]] += 1; + } + inPct = +(floored[0] / 10).toFixed(1); + cachePct = +(floored[1] / 10).toFixed(1); + outPct = +(floored[2] / 10).toFixed(1); + } + patchText(inputSharePct, `${inPct}%`); patchText(inputMainTokens, formatTokensPrecise(inputTokens)); + patchText(inputSubText, '未命中缓存输入'); + + patchText(cacheSharePct, `${cachePct}%`); + patchText(cacheMainTokens, formatTokensPrecise(cacheTokens)); patchText( - inputSubText, - `新输入 ${formatTokensPrecise(inputTokens)} · 缓存 ${formatTokensPrecise(cacheTokens)}` + cacheSubText, + `节省 ${formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 })}` ); patchText(outputSharePct, `${outPct}%`); @@ -480,7 +542,8 @@ export const ConsumptionView = defineComponent({ ); trendChart.update(trendSeries); - // 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账) + // 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账,遵循模型名称显示格式设置) + const showUpstream = Boolean(slice.showUpstreamModel); const models = (slice.modelBreakdown || []) .slice() .sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0)); @@ -489,9 +552,17 @@ export const ConsumptionView = defineComponent({ patchKeyedList(modelsListEl, models, { keyFn: (m) => m.label || m.shortName, sigFn: (m) => - `${m.label}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, + `${showUpstream}:${m.label}:${m.upstreamName || ''}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, createRow: createBreakdownItemRow, - updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true), + updateRow: (refs, m) => + updateBreakdownItemRow( + refs, + showUpstream + ? { ...m, label: m.upstreamName || m.label || m.shortName } + : m, + modelsTotalTok, + true + ), }); // 4. 同步数据来源列表 @@ -529,8 +600,14 @@ export const ConsumptionView = defineComponent({ patchText(col.tokText, ''); } else { const cVal = Number(m.costUsd || 0); - patchText(col.costText, m.unpricedCalls > 0 ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls }) - : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); + patchText( + col.costText, + m.unpricedCalls > 0 + ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls, compactPending: true }) + : cVal >= 10 + ? `$${Math.round(cVal)}` + : `$${cVal.toFixed(2)}` + ); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); @@ -558,6 +635,7 @@ export const ConsumptionView = defineComponent({ customEndMs: st.customEndMs, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, + showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), }), (slice) => { latestSlice = slice; diff --git a/sidecars/panel/src/views/LiveOverviewView.js b/sidecars/panel/src/views/LiveOverviewView.js index c534aa8..7d43c9d 100644 --- a/sidecars/panel/src/views/LiveOverviewView.js +++ b/sidecars/panel/src/views/LiveOverviewView.js @@ -2,9 +2,9 @@ * @fileoverview View 1: LiveOverviewView (实时监控视图). * 负责展示当前活跃会话的核心实时遥测指标: * 1. 4 格实时测速矩阵:实时吞吐 (TPS)、首 Token 延迟 (TTFT)、会话有效加权均速与本步费用/缓存命中率; - * 2. 6 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`), - * 通过 6 段进度条与双列图例展示消息、系统工具、MCP 工具、Skill、系统提示词与用户规则的 Token 占用; - * 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon 周配额池、Claude & GPT 等动态配额池, + * 2. 10 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`), + * 通过 10 段进度条与双列图例展示模型回复、工具结果、用户消息、子代理通知、压缩摘要及系统提示词/工具/MCP/Skill/规则的 Token 占用; + * 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon/Carbon 周配额池、Claude & GPT 等动态配额池, * 自动适配 5h/每周双窗口或单窗口模式,并展示本机周累计消耗与 AI 积分脚标。 */ @@ -52,6 +52,239 @@ function estPillWidth(text) { return Math.ceil(w); } +/** + * 10 通道上下文窗口构成定义(供实时监控主视图与主窗口顶栏悬停概览卡共享)。 + */ +export const CTX_CHANNEL_DEFS = [ + { + key: 'assistant', + label: '模型回复', + segClass: 'seg-assistant', + title: '模型推理思考、回复正文与工具调用入参', + getValue: (c) => Number(c.assistantTokens || 0), + }, + { + key: 'toolResults', + label: '工具结果', + segClass: 'seg-tool-results', + title: '文件读取、终端输出与工具执行返回内容', + getValue: (c) => Number(c.toolResultsTokens || 0), + }, + { + key: 'userInput', + label: '用户消息', + segClass: 'seg-user-input', + title: '用户提问文本与上传附件', + getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), + }, + { + key: 'subagent', + label: '子代理通知', + segClass: 'seg-subagent-msg', + title: '子代理完成汇报与后台任务系统通知', + getValue: (c) => Number(c.subagentTokens || 0), + }, + { + key: 'checkpoint', + label: '压缩摘要', + segClass: 'seg-checkpoint', + title: '自动上下文压缩生成的历史摘要检查点', + getValue: (c) => Number(c.checkpointTokens || 0), + }, + { + key: 'systemPrompt', + label: '系统提示词', + segClass: 'seg-system-prompt', + title: '核心身份、终端沙箱、制品与环境提示词', + getValue: (c) => Number(c.systemPromptTokens || 0), + }, + { + key: 'systemTools', + label: '系统工具', + segClass: 'seg-system-tools', + title: '内置系统工具 Schema 定义', + getValue: (c) => Number(c.systemToolsTokens || 0), + }, + { + key: 'mcpTools', + label: 'MCP 工具', + segClass: 'seg-mcp-tools', + title: 'MCP 外部服务工具与资源定义', + getValue: (c) => Number(c.mcpToolsTokens || 0), + }, + { + key: 'skills', + label: 'Skill', + segClass: 'seg-skills', + title: '已挂载的 Skills 技能索引与说明', + getValue: (c) => Number(c.skillsTokens || 0), + }, + { + key: 'userRules', + label: '用户规则', + segClass: 'seg-user-rules', + title: '全局与工作区自定义规则 (user_rules)', + getValue: (c) => Number(c.userRulesTokens || 0), + }, +]; + +/** + * 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。 + * + * @param {object|null|undefined} quotas + * @param {number} minuteTick + * @param {{ isPending?: boolean }} [options] + * @returns {Array} + */ +export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) { + const safeQuotas = quotas || {}; + const activePool = safeQuotas.activePool || {}; + const rawPools = + Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0 + ? safeQuotas.pools + : [ + { poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' }, + { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' }, + ]; + const weekly = safeQuotas.weekly || {}; + const poolItems = rawPools.map((p) => { + const key = p.poolKey || p.family || p.poolLabel || 'Other'; + const poolLabel = p.poolLabel || p.family || key; + const isActivePool = + Boolean(activePool.family) && + (activePool.poolKey === key || + activePool.family === p.family || + (key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family))); + return { + key, + poolLabel, + poolData: p, + fallbackWeekly: weekly, + isActivePool, + minuteTick, + isPending, + }; + }); + if ( + weekly?.isOfficial === false && + poolItems.length > 0 && + !poolItems.some((item) => item.isActivePool) + ) { + poolItems[0].isActivePool = true; + } + return poolItems; +} + +/** + * 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。 + */ +export function createPoolQuotaRow() { + const title5h = h('span', { text: '5h 限额' }); + const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fill5h = h('div', { className: 'progress-fill' }); + const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [title5h, meta5h]), + h('div', { className: 'progress-track' }, [fill5h]), + ]); + + const titleWk = h('span', { text: '每周限额' }); + const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fillWk = h('div', { className: 'progress-fill' }); + const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [titleWk, metaWk]), + h('div', { className: 'progress-track' }, [fillWk]), + ]); + + const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ + row5h, + rowWk, + ]); + + return { + el, + refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk }, + }; +} + +/** + * 同步单个配额池行的 5h 与每周窗口状态: + * - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行; + * - 对于仅有 5h 限额的配额池自动隐藏每周行; + * - 若两个窗口均无数据(首次加载或拉取失败),同时保留两行以维持预占高度不跳动。 + */ +export function syncPoolQuotaRow(refs, item, idx, rowEl) { + const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item; + patchAttr( + rowEl, + 'style', + idx === 0 + ? 'display: flex; flex-direction: column; gap: 8px;' + : 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' + ); + + const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; + const used5hVal = has5h ? Number(poolData.usedPct) : 0; + const rem5hVal = has5h ? Number(poolData.remainingPct) : 0; + + const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false); + const wkUsedRaw = useCustomWeekly + ? fallbackWeekly?.usedPct + : poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null); + const wkRemRaw = useCustomWeekly + ? fallbackWeekly?.remainingPct + : poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null); + const wkResetRaw = useCustomWeekly + ? fallbackWeekly?.resetTime || poolData?.weeklyResetTime + : poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null); + const hasWk = wkUsedRaw != null && wkRemRaw != null; + const usedWkVal = hasWk ? Number(wkUsedRaw) : 0; + const remWkVal = hasWk ? Number(wkRemRaw) : 0; + + // 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口 + const hide5h = !has5h && hasWk; + const hideWk = !hasWk && has5h; + refs.row5h.hidden = hide5h; + refs.row5h.style.display = hide5h ? 'none' : 'flex'; + refs.rowWk.hidden = hideWk; + refs.rowWk.style.display = hideWk ? 'none' : 'flex'; + + const fallbackMetaText = isPending ? '读取中...' : '获取失败 (--%)'; + + patchText(refs.title5h, `5h 限额 (${poolLabel})`); + patchText( + refs.meta5h, + has5h + ? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)` + : fallbackMetaText + ); + patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); + patchClasses(refs.fill5h, { + 'tone-warn': used5hVal >= 60 && used5hVal < 85, + 'tone-danger': used5hVal >= 85, + }); + + const customTitle = + isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title + ? fallbackWeekly.title + : `每周限额 (${poolLabel})`; + patchText(refs.titleWk, customTitle); + patchText( + refs.metaWk, + hasWk + ? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)` + : fallbackMetaText + ); + patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); + patchClasses(refs.fillWk, { + 'tone-warn': usedWkVal >= 60 && usedWkVal < 85, + 'tone-danger': usedWkVal >= 85, + }); +} + +export function quotaPoolRowSig(item, idx) { + return `${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.remainingPct}:${item.fallbackWeekly?.resetTime}:${item.fallbackWeekly?.title}`; +} + export const LiveOverviewView = defineComponent({ name: 'LiveOverviewView', setup({ onCleanup }) { @@ -65,6 +298,7 @@ export const LiveOverviewView = defineComponent({ const expandedTaskConvIds = new Set(); const activityTimersMap = new Map(); let liveTickTimer = null; + let countdownTickTimer = null; function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { const now = Date.now(); @@ -90,22 +324,51 @@ export const LiveOverviewView = defineComponent({ } } - function stopLiveTicker() { + function pauseLiveTicker() { if (liveTickTimer) { clearInterval(liveTickTimer); liveTickTimer = null; } + } + + function stopLiveTicker() { + pauseLiveTicker(); activityTimersMap.clear(); } function ensureLiveTicker() { + if (uiStore.getState().activeView !== 'overview' || activityTimersMap.size === 0) { + pauseLiveTicker(); + return; + } if (!liveTickTimer) { liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000); } } + function stopCountdownTicker() { + if (countdownTickTimer) { + clearInterval(countdownTickTimer); + countdownTickTimer = null; + } + } + + function ensureCountdownTicker() { + if (uiStore.getState().activeView !== 'overview') { + stopCountdownTicker(); + return; + } + if (!countdownTickTimer) { + countdownTickTimer = setInterval(() => { + if (uiStore.getState().activeView === 'overview' && latestData) { + renderData(latestData); + } + }, 30_000); + } + } + function createLiveTaskCard() { - const dotIcon = createSvgIcon('dot', { size: 9 }); + const dotIcon = createSvgIcon('dot', { size: 11 }); patchClasses(dotIcon, { 'is-pulsing': true }); const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' }); @@ -125,7 +388,11 @@ export const LiveOverviewView = defineComponent({ h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), ]); - const mainBadge = h('span', { className: 'agent-badge badge-main', text: '主' }); + const mainBadge = h('span', { + className: 'agent-badge badge-main', + hidden: true, + text: '主', + }); const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' }); const mainProgress = h('span', { className: 'live-activity-progress text-mono', @@ -158,6 +425,7 @@ export const LiveOverviewView = defineComponent({ titleEl, subToggleBtn, elapsedEl, + mainBadge, mainPhase, mainProgress, mainSep, @@ -205,7 +473,7 @@ export const LiveOverviewView = defineComponent({ const avgVal = h('strong', { className: 'cell-value', text: '—' }); const avgSub = h('span', { className: 'cell-sub', text: '有效样本 0/0 步' }); - const costVal = h('strong', { className: 'cell-value', text: '$0.000' }); + const costVal = h('strong', { className: 'cell-value', text: '—' }); const cacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累计 $0.00' }); const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '实时指标' }, [ @@ -256,78 +524,7 @@ export const LiveOverviewView = defineComponent({ [ctxPillGroup] ); - const ctxChannels = [ - { - key: 'assistant', - label: '模型回复', - segClass: 'seg-assistant', - title: '模型推理思考、回复正文与工具调用入参', - getValue: (c) => Number(c.assistantTokens || 0), - }, - { - key: 'toolResults', - label: '工具结果', - segClass: 'seg-tool-results', - title: '文件读取、终端输出与工具执行返回内容', - getValue: (c) => Number(c.toolResultsTokens || 0), - }, - { - key: 'userInput', - label: '用户消息', - segClass: 'seg-user-input', - title: '用户提问文本与上传附件', - getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0), - }, - { - key: 'subagent', - label: '子代理通知', - segClass: 'seg-subagent-msg', - title: '子代理完成汇报与后台任务系统通知', - getValue: (c) => Number(c.subagentTokens || 0), - }, - { - key: 'checkpoint', - label: '压缩摘要', - segClass: 'seg-checkpoint', - title: '自动上下文压缩生成的历史摘要检查点', - getValue: (c) => Number(c.checkpointTokens || 0), - }, - { - key: 'systemPrompt', - label: '系统提示词', - segClass: 'seg-system-prompt', - title: '核心身份、终端沙箱、制品与环境提示词', - getValue: (c) => Number(c.systemPromptTokens || 0), - }, - { - key: 'systemTools', - label: '系统工具', - segClass: 'seg-system-tools', - title: '内置系统工具 Schema 定义', - getValue: (c) => Number(c.systemToolsTokens || 0), - }, - { - key: 'mcpTools', - label: 'MCP 工具', - segClass: 'seg-mcp-tools', - title: 'MCP 外部服务工具与资源定义', - getValue: (c) => Number(c.mcpToolsTokens || 0), - }, - { - key: 'skills', - label: 'Skill', - segClass: 'seg-skills', - title: '已挂载的 Skills 技能索引与说明', - getValue: (c) => Number(c.skillsTokens || 0), - }, - { - key: 'userRules', - label: '用户规则', - segClass: 'seg-user-rules', - title: '全局与工作区自定义规则 (user_rules)', - getValue: (c) => Number(c.userRulesTokens || 0), - }, - ].map((ch, idx) => { + const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => { const valEl = h('strong', { className: 'text-mono', text: '0' }); const itemEl = h('div', { className: 'legend-item', title: ch.title }, [ h('span', { className: 'legend-left' }, [ @@ -364,37 +561,6 @@ export const LiveOverviewView = defineComponent({ const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); const poolsListEl = h('div', { style: 'display: flex; flex-direction: column; gap: 0;' }); - /** - * 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。 - */ - function createPoolQuotaRow() { - const title5h = h('span', { text: '5h 限额' }); - const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' }); - const fill5h = h('div', { className: 'progress-fill' }); - const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ - h('div', { className: 'panel-header' }, [title5h, meta5h]), - h('div', { className: 'progress-track' }, [fill5h]), - ]); - - const titleWk = h('span', { text: '每周限额' }); - const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' }); - const fillWk = h('div', { className: 'progress-fill' }); - const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ - h('div', { className: 'panel-header' }, [titleWk, metaWk]), - h('div', { className: 'progress-track' }, [fillWk]), - ]); - - const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ - row5h, - rowWk, - ]); - - return { - el, - refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk }, - }; - } - const wkFootLeft = h('span', { className: 'text-muted', text: '本周累计: 0 ($0.00)' }); const wkFootRight = h('span', { className: 'text-muted', text: '' }); @@ -425,75 +591,6 @@ export const LiveOverviewView = defineComponent({ className: 'view-pane', }); - /** - * 同步单个配额池行的 5h 与每周窗口状态: - * - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行; - * - 对于仅有 5h 限额的配额池自动隐藏每周行; - * - 若两个窗口均无数据(如首次拉取失败),则同时保留两行并显示“获取失败 (--%)”占位提示。 - */ - function syncPoolQuotaRow(refs, item, idx, rowEl) { - const { poolData, poolLabel, fallbackWeekly, isActivePool } = item; - patchAttr( - rowEl, - 'style', - idx === 0 - ? 'display: flex; flex-direction: column; gap: 8px;' - : 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' - ); - - const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; - const used5hVal = has5h ? Number(poolData.usedPct) : 0; - const rem5hVal = has5h ? Number(poolData.remainingPct) : 0; - - const wkUsedRaw = - poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null); - const wkRemRaw = - poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null); - const wkResetRaw = - poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null); - const hasWk = wkUsedRaw != null && wkRemRaw != null; - const usedWkVal = hasWk ? Number(wkUsedRaw) : 0; - const remWkVal = hasWk ? Number(wkRemRaw) : 0; - - // 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口 - const hide5h = !has5h && hasWk; - const hideWk = !hasWk && has5h; - refs.row5h.hidden = hide5h; - refs.row5h.style.display = hide5h ? 'none' : 'flex'; - refs.rowWk.hidden = hideWk; - refs.rowWk.style.display = hideWk ? 'none' : 'flex'; - - patchText(refs.title5h, `5h 限额 (${poolLabel})`); - patchText( - refs.meta5h, - has5h - ? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)` - : '获取失败 (--%)' - ); - patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); - patchClasses(refs.fill5h, { - 'tone-warn': used5hVal >= 60 && used5hVal < 85, - 'tone-danger': used5hVal >= 85, - }); - - const customTitle = - isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title - ? fallbackWeekly.title - : `每周限额 (${poolLabel})`; - patchText(refs.titleWk, customTitle); - patchText( - refs.metaWk, - hasWk - ? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)` - : '获取失败 (--%)' - ); - patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); - patchClasses(refs.fillWk, { - 'tone-warn': usedWkVal >= 60 && usedWkVal < 85, - 'tone-danger': usedWkVal >= 85, - }); - } - let latestData = null; let isDirty = false; let ctxPillsExpanded = false; @@ -605,10 +702,10 @@ export const LiveOverviewView = defineComponent({ const subSig = (item.subagents || []) .map( (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}` + `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${subSig}`; + return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { @@ -622,7 +719,11 @@ export const LiveOverviewView = defineComponent({ }; const isWaiting = act.phase === 'waiting'; - patchClasses(refs.cardEl, { 'is-waiting': isWaiting }); + const isCompacting = act.phase === 'compacting'; + patchClasses(refs.cardEl, { + 'is-waiting': isWaiting, + 'is-compacting': isCompacting, + }); patchClasses(refs.dotIcon, { 'is-pulsing': true }); const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话'; @@ -639,6 +740,7 @@ export const LiveOverviewView = defineComponent({ const subCount = Number(item.subagentCount || item.subagents?.length || 0); const runSubCount = Number(item.runningSubagentCount || 0); const isExpanded = expandedTaskConvIds.has(item.cascadeId); + patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); if (subCount > 0) { const arrow = isExpanded ? '▾' : '▸'; @@ -758,14 +860,19 @@ export const LiveOverviewView = defineComponent({ ensureLiveTicker(); } - // 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标) + // 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标,遵循模型名称格式设置) + const showUpstream = Boolean(data.settings?.showUpstreamModel); + const activeModelDisplay = + (showUpstream + ? active.activeModelUpstream || active.activeModelShort + : active.activeModelShort) || '模型未知'; patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) }); patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s')); const reason = speedReasonText(active.latestSpeedReason); const modelAndAgent = hasSubagents && active.activeAgentBadge - ? `[${active.activeAgentBadge}] ${active.activeModelShort || '模型未知'}` - : active.activeModelShort || '模型未知'; + ? `[${active.activeAgentBadge}] ${activeModelDisplay}` + : activeModelDisplay; patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent); patchText(ttftVal, formatMetric(active.latestTtftSec, 's')); @@ -775,7 +882,11 @@ export const LiveOverviewView = defineComponent({ patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`); const stepCost = active.latestStepCostUsd; - patchText(costVal, formatUsd(stepCost, { precise: true })); + const hasAnySteps = Number(active.stepCount || 0) > 0; + patchText( + costVal, + !hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true }) + ); patchText( cacheSub, `缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}` @@ -803,10 +914,13 @@ export const LiveOverviewView = defineComponent({ const allAgentPills = agents.map((ag) => { const agPct = ag.context?.usedPct ?? 0; + const agModelDisplay = + (showUpstream ? ag.activeModelUpstream || ag.activeModelShort : ag.activeModelShort) || + '模型未知'; return { key: ag.agentId, label: `${ag.badgeText || ag.shortLabel} ${agPct}%`, - title: `${formatAgentLabel(ag)} (${ag.activeModelShort || '模型未知'} · ${ag.stepCount || 0}步)`, + title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${ag.stepCount || 0}步)`, isActive: effectiveCtxScope === ag.agentId, mode: 'ctx-only', }; @@ -888,12 +1002,8 @@ export const LiveOverviewView = defineComponent({ if (item.mode === 'toggle-expand') { ctxPillsExpanded = !ctxPillsExpanded; renderData(latestData); - } else if (item.mode === 'ctx-only') { - uiStore.setState({ ctxInspectorAgentId: item.key }); - } else if (item.key === 'all') { - uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); } else { - uiStore.setState({ selectedAgentScope: item.key }); + uiStore.setState({ ctxInspectorAgentId: item.key }); } }; }, @@ -928,37 +1038,13 @@ export const LiveOverviewView = defineComponent({ tierBadge, `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` ); - const activePool = quotas.activePool || {}; - const rawPools = Array.isArray(quotas.pools) && quotas.pools.length > 0 - ? quotas.pools - : [ - { poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' }, - { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' }, - ]; const weekly = quotas.weekly || {}; const minuteTick = Math.floor(Date.now() / 30000); - const poolItems = rawPools.map((p) => { - const key = p.poolKey || p.family || p.poolLabel || 'Other'; - const poolLabel = p.poolLabel || p.family || key; - const isActivePool = - Boolean(activePool.family) && - (activePool.poolKey === key || - activePool.family === p.family || - (key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family))); - return { - key, - poolLabel, - poolData: p, - fallbackWeekly: weekly, - isActivePool, - minuteTick, - }; - }); + const poolItems = buildQuotaPoolItems(quotas, minuteTick); patchKeyedList(poolsListEl, poolItems, { keyFn: (item) => item.key, - sigFn: (item, idx) => - `${idx}:${item.poolLabel}:${item.isActivePool}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.title}`, + sigFn: quotaPoolRowSig, createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); @@ -974,12 +1060,13 @@ export const LiveOverviewView = defineComponent({ : `本周调用: ${weekly.calls || 0} 次` ); + ensureCountdownTicker(); viewScrollbar.refresh(); } const unsub = telemetryStore.subscribe( - (st) => st.telemetry, - (data) => { + (st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }), + ({ telemetry: data }) => { latestData = data; if (uiStore.getState().activeView !== 'overview') { const stillRunning = @@ -1011,12 +1098,18 @@ export const LiveOverviewView = defineComponent({ prevCtxTarget = slice.ctxInspectorAgentId; if (slice.activeView !== 'overview') { + pauseLiveTicker(); + stopCountdownTicker(); if (scopeChanged) isDirty = true; return; } + ensureCountdownTicker(); if ((isDirty || scopeChanged) && latestData) { isDirty = false; renderData(latestData); + } else if (activityTimersMap.size > 0) { + updateLiveElapsedDisplay(); + ensureLiveTicker(); } } ); @@ -1039,6 +1132,7 @@ export const LiveOverviewView = defineComponent({ onCleanup(() => { stopLiveTicker(); + stopCountdownTicker(); unsub(); unsubView(); if (ro) ro.disconnect(); diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index 0eb1a96..9c984be 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -1,29 +1,26 @@ /** * @fileoverview View 4: SettingsView (系统设置视图). - * 采用定制的 `CustomSelect` 与 `CustomNumberInput` 替代所有原生表单控件,分为两个设置面板: - * 1. 本地配额监控与预算表单:配置模型名称显示方式(内部代号/实际模型名)、周用量计算模式及自定义 Token/USD 预算; - * 2. 云端价格同步与插件更新面板:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。 + * 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板: + * 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)与模型名称格式(精简代号 / 原始模型 ID); + * 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序; + * 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。 */ import { defineComponent } from '../core/component.js'; import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js'; import { createSvgIcon } from '../icons/SvgIcon.js'; import { + DEFAULT_CLIENT_TOPBAR_SLOTS, + normalizeClientTopbarSlots, saveSettingsPatch, telemetryStore, triggerCloudSync, triggerPluginUpdate, } from '../store/telemetryStore.js'; import { uiStore } from '../store/uiStore.js'; -import { CustomNumberInput } from '../components/ui/CustomNumberInput.js'; +import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; import { CustomSelect } from '../components/ui/CustomSelect.js'; - -/** 每周配额计算模式可选项 */ -const WEEKLY_MODE_OPTIONS = [ - { value: 'official', label: '跟随官方额度' }, - { value: 'custom_tokens', label: '自定义 Token 上限' }, - { value: 'custom_cost', label: '自定义费用上限 (USD)' }, -]; +import { SegmentedControl } from '../components/ui/SegmentedControl.js'; /** 步骤明细表中的模型名称显示方式可选项 */ const STEP_MODEL_DISPLAY_OPTIONS = [ @@ -31,6 +28,32 @@ const STEP_MODEL_DISPLAY_OPTIONS = [ { value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' }, ]; +/** 面板挂载模式可选项(顶部栏 + 侧边栏 vs 仅侧边栏) */ +const WINDOW_MOUNT_OPTIONS = [ + { value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' }, + { value: 'sidebar', label: '仅侧边栏' }, +]; + +/** 顶栏左侧实时运行会话入口显隐选项 */ +const TOPBAR_MULTI_TOGGLE_OPTIONS = [ + { value: 'show', label: '显示' }, + { value: 'hide', label: '隐藏' }, +]; + +/** 顶栏右侧精简胶囊三槽位可选指标项 */ +const TOPBAR_SLOT_OPTIONS = [ + { value: 'context', label: '上下文占用 (%)' }, + { value: 'tps', label: '输出速度 (TPS)' }, + { value: 'ttft', label: '首字延迟 (TTFT)' }, + { value: 'cost', label: '本次费用 ($)' }, + { value: 'quota_auto', label: '自动紧俏额度' }, + { value: 'gemini_5h', label: 'Gemini 5h 额度' }, + { value: 'gemini_weekly', label: 'Gemini 周额度' }, + { value: 'claude_5h', label: 'Claude 5h 额度' }, + { value: 'claude_weekly', label: 'Claude 周额度' }, + { value: 'none', label: '不显示' }, +]; + /** 插件版本更新策略可选项 */ const AUTO_UPDATE_OPTIONS = [ { value: 'manual', label: '仅提示新版本,手动更新 (推荐)' }, @@ -55,20 +78,20 @@ function formatSyncTimeText(tsMs, updatedAt) { export const SettingsView = defineComponent({ name: 'SettingsView', setup({ onCleanup }) { - // --- 面板 1:本地配额监控与预算表单状态与控件 --- - let draftMode = 'official'; - let draftTokens = 150000000; - let draftCost = 100; let draftShowUpstreamModel = false; let draftAutoUpdatePlugin = false; + let draftEnableWindowOverlay = true; + let draftShowTopbarMulti = true; + let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; let statusTimer = null; + let topbarTimer = null; let cloudTimer = null; - let lastSyncedSettingsSig = ''; const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); + const topbarStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); - /** 在本地预算面板右上角展示短暂的保存状态提示 */ + /** 在常规设置面板右上角展示短暂的保存状态提示 */ function showSaveFeedback(text) { if (statusTimer) { clearTimeout(statusTimer); @@ -83,6 +106,21 @@ export const SettingsView = defineComponent({ } } + /** 在顶部栏定制面板右上角展示短暂的状态提示 */ + function showTopbarFeedback(text, autoClearMs = 1500) { + if (topbarTimer) { + clearTimeout(topbarTimer); + topbarTimer = null; + } + patchText(topbarStatusText, text); + if (autoClearMs > 0) { + topbarTimer = setTimeout(() => { + topbarTimer = null; + patchText(topbarStatusText, ''); + }, autoClearMs); + } + } + /** 在云端同步面板右上角展示同步或更新进度提示 */ function showCloudFeedback(text, autoClearMs = 3500) { if (cloudTimer) { @@ -98,110 +136,54 @@ export const SettingsView = defineComponent({ } } - const modeSelect = CustomSelect({ - modelValue: draftMode, - icon: 'sliders', - options: WEEKLY_MODE_OPTIONS, - onUpdateModelValue: (val) => { - draftMode = val; - }, - }); - - // 模型名显示方式切换后立即持久化并刷新遥测数据 - const stepModelSelect = CustomSelect({ - modelValue: 'short', - icon: 'table', - options: STEP_MODEL_DISPLAY_OPTIONS, + // --- 面板 1:常规设置 --- + const windowMountSelect = CustomSelect({ + modelValue: 'dual', + icon: 'dock', + options: WINDOW_MOUNT_OPTIONS, onUpdateModelValue: async (val) => { - draftShowUpstreamModel = val === 'upstream'; - if (latestSettings) { - lastSyncedSettingsSig = settingsSig({ - ...latestSettings, - showUpstreamModel: draftShowUpstreamModel, - }); - } + const nextEnable = val !== 'sidebar'; + draftEnableWindowOverlay = nextEnable; + windowMountSelect.setValue(nextEnable ? 'dual' : 'sidebar'); showSaveFeedback('保存中…'); try { await saveSettingsPatch({ - showUpstreamModel: draftShowUpstreamModel, + enableWindowOverlay: nextEnable, }); showSaveFeedback('已保存'); } catch { + if (latestSettings) { + renderSettings(latestSettings); + } showSaveFeedback('保存失败'); } }, }); - // 插件自动更新策略切换后立即保存至后端 - const autoUpdateSelect = CustomSelect({ - modelValue: 'manual', - icon: 'refresh', - options: AUTO_UPDATE_OPTIONS, + const stepModelSelect = CustomSelect({ + modelValue: 'short', + icon: 'table', + options: STEP_MODEL_DISPLAY_OPTIONS, onUpdateModelValue: async (val) => { - draftAutoUpdatePlugin = val === 'auto'; - if (latestSettings) { - lastSyncedSettingsSig = settingsSig({ - ...latestSettings, - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - } - showCloudFeedback('保存中…', 0); + const nextUpstream = val === 'upstream'; + draftShowUpstreamModel = nextUpstream; + stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short'); + showSaveFeedback('保存中…'); try { await saveSettingsPatch({ - autoUpdatePlugin: draftAutoUpdatePlugin, + showUpstreamModel: nextUpstream, }); - showCloudFeedback('已保存', 1800); + showSaveFeedback('已保存'); } catch { - showCloudFeedback('保存失败', 2500); + if (latestSettings) { + renderSettings(latestSettings); + } + showSaveFeedback('保存失败'); } }, }); - const tokenBudgetInput = CustomNumberInput({ - modelValue: draftTokens, - min: 100000, - max: 10000000000, - step: 1000000, - onUpdateModelValue: (val) => { - draftTokens = val; - }, - }); - - const costBudgetInput = CustomNumberInput({ - modelValue: draftCost, - min: 1, - max: 100000, - step: 5, - onUpdateModelValue: (val) => { - draftCost = val; - }, - }); - - const saveBtn = h( - 'button', - { - type: 'button', - className: 'btn-primary', - onClick: async () => { - showSaveFeedback('保存中…'); - try { - await saveSettingsPatch({ - weeklyLimitMode: draftMode, - weeklyTokenBudget: draftTokens, - weeklyCostBudget: draftCost, - showUpstreamModel: draftShowUpstreamModel, - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - showSaveFeedback('已保存'); - } catch { - showSaveFeedback('保存失败'); - } - }, - }, - [createSvgIcon('check', { size: 13 }), h('span', { text: '保存设置' })] - ); - - const budgetPanel = h('section', { className: 'panel' }, [ + const generalPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('sliders', { size: 13 }), @@ -209,31 +191,211 @@ export const SettingsView = defineComponent({ ]), saveStatusText, ]), + h('div', { className: 'form-row' }, [ + h('span', { className: 'form-label', text: '面板挂载方式' }), + windowMountSelect.el, + ]), h('div', { className: 'form-row' }, [ h('span', { className: 'form-label', text: '模型名称格式' }), stepModelSelect.el, ]), - h('div', { className: 'form-row' }, [ - h('span', { className: 'form-label', text: '周额度基准' }), - modeSelect.el, - ]), - h('div', { className: 'dual-grid' }, [ - h('div', { className: 'form-row' }, [ - h('span', { className: 'form-label', text: '每周 Token 上限' }), - tokenBudgetInput.el, - ]), - h('div', { className: 'form-row' }, [ - h('span', { className: 'form-label', text: '每周费用上限 ($)' }), - costBudgetInput.el, - ]), - ]), - h('div', { style: 'display: flex; justify-content: flex-end;' }, [saveBtn]), ]); - // --- 面板 2:版本更新面板 --- + // --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) --- + const multiSessionToggle = SegmentedControl({ + ariaLabel: '实时运行会话开关', + modelValue: 'show', + options: TOPBAR_MULTI_TOGGLE_OPTIONS, + onUpdateModelValue: async (val) => { + const nextShow = val !== 'hide'; + draftShowTopbarMulti = nextShow; + syncTopbarControls(); + showTopbarFeedback('保存中…', 0); + try { + await saveSettingsPatch({ + showTopbarMultiSession: nextShow, + }); + showTopbarFeedback('已保存', 1500); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showTopbarFeedback('保存失败', 2500); + } + }, + }); + + async function persistTopbarSlots(nextRawSlots, noticeText = '') { + const normalized = normalizeClientTopbarSlots(nextRawSlots); + draftTopbarSlots = normalized; + syncTopbarControls(); + showTopbarFeedback(noticeText || '保存中…', 0); + try { + await saveSettingsPatch({ + topbarCapsuleSlots: normalized, + }); + showTopbarFeedback(noticeText || '已保存', noticeText ? 2000 : 1500); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showTopbarFeedback('保存失败', 2500); + } + } + + function handleSlotMetricChange(slotIndex, nextVal) { + const candidate = [...draftTopbarSlots]; + candidate[slotIndex] = nextVal; + const wouldAllBeHidden = candidate.every((item) => item === 'none'); + void persistTopbarSlots( + candidate, + wouldAllBeHidden ? '至少保留 1 项显示' : '' + ); + } + + function swapTopbarSlots(idxA, idxB) { + if (idxA < 0 || idxA > 2 || idxB < 0 || idxB > 2 || idxA === idxB) return; + const candidate = [...draftTopbarSlots]; + const temp = candidate[idxA]; + candidate[idxA] = candidate[idxB]; + candidate[idxB] = temp; + void persistTopbarSlots(candidate); + } + + const slotSelects = [0, 1, 2].map((idx) => + CustomSelect({ + modelValue: draftTopbarSlots[idx], + options: TOPBAR_SLOT_OPTIONS, + onUpdateModelValue: (val) => handleSlotMetricChange(idx, val), + }) + ); + + const slotRows = [0, 1, 2].map((idx) => { + const upBtn = h( + 'button', + { + type: 'button', + className: 'slot-move-btn', + disabled: idx === 0, + 'aria-label': `槽位 ${idx + 1} 左移`, + title: idx === 0 ? '已在最左' : '上移 (在顶栏靠左)', + onClick: (e) => { + e.stopPropagation(); + swapTopbarSlots(idx, idx - 1); + }, + }, + [createSvgIcon('chevron-up', { size: 12 })] + ); + + const downBtn = h( + 'button', + { + type: 'button', + className: 'slot-move-btn', + disabled: idx === 2, + 'aria-label': `槽位 ${idx + 1} 右移`, + title: idx === 2 ? '已在最右' : '下移 (在顶栏靠右)', + onClick: (e) => { + e.stopPropagation(); + swapTopbarSlots(idx, idx + 1); + }, + }, + [createSvgIcon('chevron-down', { size: 12 })] + ); + + return h('div', { className: 'topbar-slot-row', 'data-slot-row': String(idx) }, [ + h('span', { className: 'slot-index-badge', text: String(idx + 1) }), + slotSelects[idx].el, + h('span', { className: 'slot-order-btns' }, [upBtn, downBtn]), + ]); + }); + + const resetTopbarBtn = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm', + disabled: true, + onClick: async () => { + draftShowTopbarMulti = true; + draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; + syncTopbarControls(); + showTopbarFeedback('保存中…', 0); + try { + await saveSettingsPatch({ + showTopbarMultiSession: true, + topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS], + }); + showTopbarFeedback('已恢复默认', 1600); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showTopbarFeedback('保存失败', 2500); + } + }, + }, + [h('span', { text: '恢复默认' })] + ); + + function syncTopbarControls() { + multiSessionToggle.setValue(draftShowTopbarMulti ? 'show' : 'hide'); + for (let i = 0; i < 3; i += 1) { + slotSelects[i].setValue(draftTopbarSlots[i]); + } + const isDefault = + draftShowTopbarMulti === true && + draftTopbarSlots[0] === DEFAULT_CLIENT_TOPBAR_SLOTS[0] && + draftTopbarSlots[1] === DEFAULT_CLIENT_TOPBAR_SLOTS[1] && + draftTopbarSlots[2] === DEFAULT_CLIENT_TOPBAR_SLOTS[2]; + patchAttr(resetTopbarBtn, 'disabled', isDefault); + } + + const topbarPanel = h('section', { className: 'panel topbar-config-panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('dock', { size: 13 }), + h('span', { text: '顶部栏定制' }), + ]), + h('span', { className: 'topbar-header-right' }, [topbarStatusText, resetTopbarBtn]), + ]), + h('div', { className: 'settings-inline-row' }, [ + h('span', { className: 'form-label', text: '实时运行会话' }), + multiSessionToggle.el, + ]), + h('div', { className: 'form-row' }, [ + h('span', { className: 'form-label', text: '胶囊数值与顺序 (左 → 右)' }), + h('div', { className: 'topbar-slot-list' }, slotRows), + ]), + ]); + + // --- 面板 3:版本更新面板 --- + const autoUpdateSelect = CustomSelect({ + modelValue: 'manual', + icon: 'refresh', + options: AUTO_UPDATE_OPTIONS, + onUpdateModelValue: async (val) => { + const nextAuto = val === 'auto'; + draftAutoUpdatePlugin = nextAuto; + autoUpdateSelect.setValue(nextAuto ? 'auto' : 'manual'); + showCloudFeedback('保存中…', 0); + try { + await saveSettingsPatch({ + autoUpdatePlugin: nextAuto, + }); + showCloudFeedback('已保存', 1800); + } catch { + if (latestSettings) { + renderSettings(latestSettings); + } + showCloudFeedback('保存失败', 2500); + } + }, + }); + const pricingCountVal = h('strong', { className: 'cell-value', text: '—' }); const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' }); - const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.1' }); + const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.3' }); const versionSub = h('span', { className: 'cell-sub', text: '检查中…' }); const syncPricingBtnText = h('span', { text: '更新价格表' }); @@ -288,7 +450,7 @@ export const SettingsView = defineComponent({ return; } if (!cs?.updateAvailable) { - const curVer = cs?.currentPluginVersion || '1.4.1'; + const curVer = cs?.currentPluginVersion || '1.4.3'; showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500); return; } @@ -342,38 +504,35 @@ export const SettingsView = defineComponent({ h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]), ]); - const rootEl = h('div', { className: 'view-pane' }, [budgetPanel, cloudPanel]); + const settingsInner = h( + 'div', + { + style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', + }, + [generalPanel, topbarPanel, cloudPanel] + ); + const viewScrollbar = CustomScrollbar({ + contentEl: settingsInner, + className: 'view-pane', + }); let latestSettings = null; let latestCloudStatus = null; - let isDirty = false; - - /** 生成设置项签名,避免轮询返回相同配置时覆盖用户正在编辑的草稿值 */ - function settingsSig(s) { - if (!s) return ''; - return `${s.weeklyLimitMode}:${s.weeklyTokenBudget}:${s.weeklyCostBudget}:${Boolean(s.showUpstreamModel)}:${Boolean(s.autoUpdatePlugin)}`; - } /** 将后端返回的最新设置同步至表单控件 */ function renderSettings(settings) { if (!settings) return; - const nextSig = settingsSig(settings); - if (nextSig === lastSyncedSettingsSig) return; - lastSyncedSettingsSig = nextSig; - draftMode = - settings.weeklyLimitMode === 'custom_tokens' || - settings.weeklyLimitMode === 'custom_cost' - ? settings.weeklyLimitMode - : 'official'; - draftTokens = Number(settings.weeklyTokenBudget || 150000000); - draftCost = Number(settings.weeklyCostBudget || 100); draftShowUpstreamModel = Boolean(settings.showUpstreamModel); draftAutoUpdatePlugin = Boolean(settings.autoUpdatePlugin); - modeSelect.setValue(draftMode); + draftEnableWindowOverlay = settings.enableWindowOverlay !== false; + draftShowTopbarMulti = settings.showTopbarMultiSession !== false; + draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots); + + windowMountSelect.setValue(draftEnableWindowOverlay ? 'dual' : 'sidebar'); stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short'); autoUpdateSelect.setValue(draftAutoUpdatePlugin ? 'auto' : 'manual'); - tokenBudgetInput.setValue(draftTokens); - costBudgetInput.setValue(draftCost); + syncTopbarControls(); + viewScrollbar.refresh(); } /** 将云端价格表统计与插件版本对比状态同步至云端面板 */ @@ -391,7 +550,7 @@ export const SettingsView = defineComponent({ `${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}` ); - const curVer = cs.currentPluginVersion || '1.4.1'; + const curVer = cs.currentPluginVersion || '1.4.3'; const latVer = cs.latestPluginVersion || curVer; const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP'; patchText(versionVal, `v${curVer}`); @@ -410,6 +569,7 @@ export const SettingsView = defineComponent({ if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) { showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500); } + viewScrollbar.refresh(); } const unsub = telemetryStore.subscribe( @@ -420,42 +580,51 @@ export const SettingsView = defineComponent({ (slice) => { latestSettings = slice.settings; latestCloudStatus = slice.cloudStatus; - if (uiStore.getState().activeView !== 'settings') { - isDirty = true; - return; - } - isDirty = false; renderSettings(slice.settings); - renderCloudStatus(slice.cloudStatus); + if (uiStore.getState().activeView === 'settings') { + renderCloudStatus(slice.cloudStatus); + } } ); const unsubView = uiStore.subscribe( (st) => st.activeView, (activeView) => { - if (activeView === 'settings' && isDirty) { - isDirty = false; + if (activeView === 'settings') { if (latestSettings) renderSettings(latestSettings); if (latestCloudStatus) renderCloudStatus(latestCloudStatus); + viewScrollbar.refresh(); } } ); onCleanup(() => { if (statusTimer) clearTimeout(statusTimer); + if (topbarTimer) clearTimeout(topbarTimer); if (cloudTimer) clearTimeout(cloudTimer); unsub(); unsubView(); - modeSelect.destroy(); + windowMountSelect.destroy(); stepModelSelect.destroy(); + multiSessionToggle.destroy(); + for (const sel of slotSelects) { + sel.destroy(); + } autoUpdateSelect.destroy(); - tokenBudgetInput.destroy(); - costBudgetInput.destroy(); + viewScrollbar.destroy(); }); return { - el: rootEl, - refs: { modeSelect, stepModelSelect, autoUpdateSelect, tokenBudgetInput, costBudgetInput }, + el: viewScrollbar.el, + refs: { + windowMountSelect, + stepModelSelect, + multiSessionToggle, + slotSelects, + resetTopbarBtn, + autoUpdateSelect, + viewScrollbar, + }, }; }, }); diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index 90bb576..d685efb 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -349,7 +349,7 @@ export const StepsDetailView = defineComponent({ patchText(refs.speedMain, formatMetric(m.avgTokPerSec, ' tok/s')); patchText(refs.speedSub, `有效 ${sampleSummary(m.speedSummary)}`); patchText(refs.tdTokens, formatTokens(m.totalTokens || 0)); - patchText(refs.tdCost, formatUsd(m.costUsd, { estimated: m.isEstimatedPrice, unpricedCalls: m.unpricedCalls })); + patchText(refs.tdCost, formatUsd(m.costUsd, { unpricedCalls: m.unpricedCalls })); }, }); @@ -367,7 +367,6 @@ export const StepsDetailView = defineComponent({ recentSteps: st.telemetry?.activeConversation?.recentSteps, sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown, modelBreakdown: st.telemetry?.modelBreakdown, - rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间', showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), }), (slice) => { diff --git a/sidecars/panel/stream-diagnostics.mjs b/sidecars/panel/stream-diagnostics.mjs deleted file mode 100644 index abc0b8b..0000000 --- a/sidecars/panel/stream-diagnostics.mjs +++ /dev/null @@ -1,1162 +0,0 @@ -/** - * Antigravity 本地状态流(State Stream)诊断观测模块。 - * - * 设计原则与隐私边界: - * 1. 本模块观测的是 LanguageServer 的本地状态同步流(`StreamAgentStateUpdates`),而非底层大模型原始 Token 流。 - * 2. 严格隐私保护:仅在内存中计算文本片段的 UTF-8 字节数、UTF-16 码元长度与 SHA-256 摘要(`digest`)以检测增量变化; - * 落盘日志(`events.jsonl`)只记录白名单内的数值计数器与时间戳,绝不落盘任何对话明文、思维链或工具参数内容。 - */ -import { createHash, randomUUID } from 'node:crypto'; -import { - appendFileSync, - existsSync, - mkdirSync, - readFileSync, - renameSync, - statSync, - unlinkSync, - writeFileSync, -} from 'node:fs'; -import { join } from 'node:path'; -import { performance } from 'node:perf_hooks'; - -/** LanguageServer Connect RPC 服务路径前缀 */ -const SERVICE = '/exa.language_server_pb.LanguageServerService/'; - -/** 单个 Connect 协议帧的最大允许负载字节数(32 MiB),防止异常帧导致进程 OOM */ -const MAX_FRAME = 32 * 1024 * 1024; - -/** 诊断事件日志文件最大字节数(5 MiB),超出后触发单文件滚动备份 */ -const MAX_LOG = 5 * 1024 * 1024; - -/** 会话 UUID 格式校验正则 */ -const UUID = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; - -/** 标志着 Cortex 步骤已进入终态的状态枚举集合 */ -const END = new Set([ - 'CORTEX_STEP_STATUS_DONE', - 'CORTEX_STEP_STATUS_ERROR', - 'CORTEX_STEP_STATUS_CANCELED', - 'CORTEX_STEP_STATUS_CANCELLED', -]); - -/** 允许直接透传的流式诊断可预期错误码正则(避免泄露可能包含敏感文本的底层异常消息) */ -const KNOWN_STREAM_ERROR_RE = new RegExp( - '^(?:' + - [ - 'stream_http_\\d+', - 'unsupported_stream_content_type', - 'frame_too_large', - 'unsupported_frame_flags', - 'invalid_frame_json', - 'truncated_frame', - 'invalid_step_indices', - 'invalid_step_index', - 'too_many_active_steps', - 'stream_rpc_error', - 'stream_ended', - 'data_after_end', - ].join('|') + - ')$' -); - -/** - * 将输入值校验并转换为非负安全整数。 - * - * @param {unknown} value 待校验的原始计数值或索引值 - * @returns {number | null} 合法的非负安全整数,不合法时返回 null - */ -function number(value) { - if (value === undefined || value === null || value === '') { - return null; - } - const parsed = Number(value); - if (Number.isSafeInteger(parsed) && parsed >= 0) { - return parsed; - } - return null; -} - -/** - * 计算字符串的 SHA-256 十六进制摘要。 - * 用于在不保存对话明文的前提下比对流式文本片段是否发生变化或是否为纯尾部追加。 - * - * @param {string} value 待计算摘要的文本内容 - * @returns {string} 64 位十六进制 SHA-256 摘要 - */ -function digest(value) { - return createHash('sha256').update(value).digest('hex'); -} - -/** - * 解析 Protobuf Duration 格式字符串(如 `"1.25s"`)为秒数。 - * - * @param {unknown} value 原始耗时字符串 - * @returns {number | null} 解析后的秒数(浮点数),格式不匹配时返回 null - */ -function duration(value) { - if (typeof value !== 'string' || !/^\d+(\.\d+)?s$/.test(value)) { - return null; - } - return Number(value.slice(0, -1)); -} - -/** - * 校验 ISO-8601 UTC 时间戳字符串是否合法且可解析。 - * - * @param {unknown} value 原始时间戳字符串 - * @returns {string | null} 合法的原时间戳字符串,不合法时返回 null - */ -function timestamp(value) { - if (typeof value !== 'string') { - return null; - } - if (!/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value)) { - return null; - } - if (!Number.isFinite(Date.parse(value))) { - return null; - } - return value; -} - -/** - * 将浮点数四舍五入保留 3 位小数(常用于毫秒耗时格式化)。 - * - * @param {number} value 原始数值 - * @returns {number} 保留 3 位小数后的数值 - */ -function rounded(value) { - return Math.round(value * 1000) / 1000; -} - -/** - * 将请求对象编码为 Connect 协议流式帧(`application/connect+json`)。 - * - * Connect 帧头固定为 5 字节: - * - Byte 0: 标志位(`0x00` 表示常规数据帧) - * - Bytes 1–4: 无符号 32 位大端整数(`UInt32BE`),表示后续 JSON 负载的 UTF-8 字节长度 - * - * @param {unknown} value 待序列化的 JSON 负载对象 - * @returns {Buffer} 拼接好 5 字节帧头与 JSON 负载的二进制 Buffer - */ -export function encodeConnectJson(value) { - const body = Buffer.from(JSON.stringify(value)); - const header = Buffer.alloc(5); - header.writeUInt32BE(body.length, 1); - return Buffer.concat([header, body]); -} - -/** - * Connect 流式协议(`application/connect+json`)增量帧解码器。 - * - * 协议帧格式与粘包/半包处理机制: - * 1. **5 字节定长帧头**: - * - `Byte 0` (`flags`):帧类型标志位。`0x00` 代表标准数据帧(Data Frame),`0x02` 代表流结束尾帧(EndStream Frame,可携带 Trailer / RPC Error)。 - * - `Bytes 1..4` (`length`):`UInt32BE`(大端序 32 位无符号整数),代表紧随帧头之后的 JSON 负载字节数。 - * 2. **HTTP 分块与协议帧边界解耦**: - * 底层 HTTP `ReadableStream` 的单次 `read()` 可能包含半个帧(半包)或连续多个帧(粘包)。 - * 解码器通过 `this.pending` 缓冲区累积未处理的字节,循环切分出完整帧;同一次 HTTP 读取中解码出的所有消息共享该批次的 `receiveBatch` 与接收时间戳。 - * 3. **防 OOM 保护(`MAX_FRAME`)**: - * 在读取负载前先校验帧头声明的 `length` 是否超过 `this.maxFrame`(默认 32 MiB),超限立即抛出 `'frame_too_large'` 中断连接。 - */ -export class ConnectJsonDecoder { - /** - * @param {number} [maxFrame=MAX_FRAME] 单帧允许的最大负载字节数上限 - */ - constructor(maxFrame = MAX_FRAME) { - this.pending = Buffer.alloc(0); - this.maxFrame = maxFrame; - this.ended = false; - } - - /** - * 推入一段新接收到的二进制数据块,并解析出所有已完整到达的 Connect 消息帧。 - * - * @param {Buffer | Uint8Array} chunk 新接收到的字节块 - * @returns {Array<{ end: boolean, value: any }>} 本次解析出的完整帧列表 - */ - push(chunk) { - if (this.ended) { - throw new Error('data_after_end'); - } - this.pending = Buffer.concat([this.pending, chunk]); - const messages = []; - - // 只要缓冲区达到至少 5 字节帧头长度,就尝试读取帧头并检查完整负载是否就绪 - while (this.pending.length >= 5) { - const flags = this.pending[0]; - const length = this.pending.readUInt32BE(1); - - if (length > this.maxFrame) { - throw new Error('frame_too_large'); - } - if (flags !== 0 && flags !== 2) { - throw new Error('unsupported_frame_flags'); - } - // 半包等待:当前缓冲区尚不足以容纳完整帧(5 字节头 + length 字节负载),留待下次 push - if (this.pending.length < length + 5) { - break; - } - - const payload = this.pending.subarray(5, length + 5); - this.pending = this.pending.subarray(length + 5); - - let value; - try { - value = JSON.parse(payload.toString('utf8')); - } catch { - throw new Error('invalid_frame_json'); - } - - messages.push({ - end: flags === 2, - value, - }); - - // 遇到 0x02 结束帧后,流正式终结;若尾帧之后仍残留未消费字节则视为协议违规 - if (flags === 2) { - this.ended = true; - if (this.pending.length) { - throw new Error('data_after_end'); - } - break; - } - } - - return messages; - } - - /** - * 在底层传输流正常关闭时调用,校验是否仍有未拼完的半包残留。 - */ - finish() { - if (this.pending.length) { - throw new Error('truncated_frame'); - } - } -} - -/** - * 从单个步骤对象中提取正文文本、思维链文本与工具调用参数数组。 - * - * @param {object} step Cortex 轨迹步骤对象 - * @returns {{ text: string, thinking: string, toolArguments: string[], toolCount: number }} - */ -function content(step) { - const p = step.plannerResponse || {}; - const tools = Array.isArray(p.toolCalls) ? p.toolCalls : []; - const rawText = p.modifiedResponse || p.response; - const rawThinking = p.rawThinking || p.thinking; - - return { - text: typeof rawText === 'string' ? rawText : '', - thinking: typeof rawThinking === 'string' ? rawThinking : '', - // 不拼接分隔符,而是按每个工具独立保存参数字符串,防止第一个工具参数被修改时被误判为尾部追加 - toolArguments: tools.map((t) => { - return typeof t.argumentsJson === 'string' ? t.argumentsJson : ''; - }), - toolCount: tools.length, - }; -} - -/** - * 为一组字符串片段生成脱敏指纹(仅保留 SHA-256 摘要、UTF-8 字节数与 UTF-16 码元长度)。 - * - * @param {string[]} parts 字符串片段列表 - * @returns {Array<{ hash: string, bytes: number, units: number }>} 脱敏指纹列表 - */ -function fingerprint(parts) { - return parts.map((s) => ({ - hash: digest(s), - bytes: Buffer.byteLength(s), - units: s.length, - })); -} - -/** - * 对比当前文本片段数组与上一帧指纹,判定内容是否发生变化以及是否属于纯尾部追加(append-only)。 - * - * @param {string[]} parts 当前帧的原始字符串数组 - * @param {Array<{ hash: string, bytes: number, units: number }>} [previous=[]] 上一帧的脱敏指纹数组 - * @returns {{ - * next: Array<{ hash: string, bytes: number, units: number }>, - * changed: boolean, - * appendOnly: boolean, - * bytes: number, - * utf16Units: number, - * deltaBytes: number - * }} - */ -function compareParts(parts, previous = []) { - const next = fingerprint(parts); - let changed = next.length !== previous.length; - let appendOnly = next.length >= previous.length; - const maxLen = Math.max(parts.length, previous.length); - - for (let i = 0; i < maxLen; i++) { - const old = previous[i]; - const now = next[i]; - - if (!old) { - changed ||= Boolean(now?.bytes); - continue; - } - if (!now) { - changed = true; - appendOnly = false; - continue; - } - if (now.hash !== old.hash) { - changed = true; - // 若新字符串长度反而缩短,或截取旧长度前缀后的 SHA-256 与旧摘要不一致,则说明发生了回写/覆写而非纯追加 - const prefixChanged = - now.units < old.units || - digest(parts[i].slice(0, old.units)) !== old.hash; - if (prefixChanged) { - appendOnly = false; - } - } - } - - const bytes = next.reduce((n, p) => n + p.bytes, 0); - const units = next.reduce((n, p) => n + p.units, 0); - const previousBytes = previous.reduce((n, p) => n + p.bytes, 0); - const deltaBytes = bytes - previousBytes; - - return { - next, - changed, - appendOnly, - bytes, - utf16Units: units, - deltaBytes, - }; -} - -/** - * 提取并清洗模型输出 Token 用量统计。 - * - * @param {object} usage 原始用量对象 - * @returns {object | null} 包含合法非负整数 Token 字段的对象,全部缺失时返回 null - */ -function tokenUsage(usage) { - if (!usage || typeof usage !== 'object') { - return null; - } - const result = {}; - const keys = ['outputTokens', 'thinkingOutputTokens', 'responseOutputTokens']; - for (const key of keys) { - const n = number(usage[key]); - if (n !== null) { - result[key] = n; - } - } - return Object.keys(result).length ? result : null; -} - -/** - * 提取并校验步骤元数据中的关键生命周期时间戳。 - * - * @param {object} [metadata={}] 步骤元数据对象 - * @returns {Record} 合法的阶段时间戳键值对 - */ -function timing(metadata = {}) { - const result = {}; - const keys = ['createdAt', 'viewableAt', 'finishedGeneratingAt', 'completedAt']; - for (const key of keys) { - const value = timestamp(metadata[key]); - if (value) { - result[key] = value; - } - } - return result; -} - -/** - * 单个会话连接周期内的状态流诊断观测器。 - * - * 核心设计机制说明: - * 1. **隐私保护设计(零明文落盘)**: - * 观测器在 `observeStep` 中仅提取 `text`、`thinking`、`toolArguments` 的 UTF-8 字节长度(`bytes`)、 - * UTF-16 长度(`utf16Units`)和 SHA-256 摘要(`digest`)用于前后帧差分计算,随即便丢弃明文引用; - * 写入 `emit` 的日志仅包含增量字节数、事件计数与时间戳,从根本上杜绝对话内容与敏感凭据泄露。 - * 2. **半途捕获(`partialCapture`)判定逻辑**: - * 当监控器在会话中途建立连接时,首帧(`initial`)或早于连接建立时刻(`Date.parse(createdAt) < this.connectedWallMs`) - * 以及索引落在初始基线内(`index < this.baselineLength`)的步骤,可能在订阅前就已经生成了部分内容。 - * 此类步骤会被标记为 `partialCapture = true`,避免将“建连前的历史存量 + 建连后的尾帧”误当作完整的流式生成跨度。 - * 3. **多批次流式跨度判定(`contentBatches.size >= 2`)**: - * 只有当同一个步骤的内容更新横跨至少 2 个独立的 HTTP 读取批次(`contentBatches.size >= 2`)时, - * 其状态才会被归类为 `'multiple_receive_batches'`。若所有内容变更均在同一个 HTTP 读取批次内到达 - * (`contentBatches.size < 2`),则归类为 `'single_receive_batch'`,防止因服务端合并推送或一次性快照返回而计算出虚假的极高流速。 - * 4. **活跃步骤状态表容量保护(`states.size > 512` 淘汰策略)**: - * `this.states` 维护步骤级观测状态。当条目数超过 512 时,优先查找并淘汰首个已观测到完成状态(`observedCompletion === true`)的步骤; - * 若超过 512 个步骤全部处于未完成活跃态,则抛出 `'too_many_active_steps'` 主动熔断,防止内存无限增长。 - */ -export class StreamObservation { - /** - * @param {object} options - * @param {string} options.conversationId 目标会话 UUID - * @param {string} [options.connectionId] 本次流式订阅连接 UUID - * @param {(record: object) => void} options.emit 诊断事件落盘回调 - * @param {number} [options.connectedWallMs] 建立连接时的本地墙钟毫秒时间戳 - */ - constructor({ - conversationId, - connectionId = randomUUID(), - emit, - connectedWallMs = Date.now(), - }) { - this.conversationId = conversationId; - this.connectionId = connectionId; - this.emit = emit; - this.connectedWallMs = connectedWallMs; - this.initialized = false; - this.baselineLength = 0; - this.states = new Map(); - this.messages = 0; - this.contentEvents = 0; - this.baselineSteps = 0; - this.recent = []; - } - - /** - * 封装公共元数据并向日志回调发射一条诊断记录。 - * - * @param {string} kind 事件类型标识(`baseline` | `step_update` | `model_timing`) - * @param {{ receivedAt: string, elapsedMs: number, receiveBatch: number }} event HTTP 接收批次上下文 - * @param {object} data 事件附加字段 - */ - record(kind, event, data) { - this.emit({ - version: 1, - kind, - conversationId: this.conversationId, - connectionId: this.connectionId, - receivedAt: event.receivedAt, - elapsedMs: rounded(event.elapsedMs), - receiveBatch: event.receiveBatch, - ...data, - }); - } - - /** - * 消费一条解码后的 `StreamAgentStateUpdates` 增量消息。 - * - * @param {object} message Connect 数据帧解码后的 JSON 对象 - * @param {{ receivedAt: string, elapsedMs: number, receiveBatch: number }} event 接收批次上下文 - */ - accept(message, event) { - const update = message?.update; - if (!update || update.conversationId !== this.conversationId) { - return; - } - this.messages++; - - const trajectory = update.mainTrajectoryUpdate; - const page = trajectory?.stepsUpdate; - const isInitial = !this.initialized; - - // 首个有效快照必须包含 stepsUpdate 基线页,否则忽略等待 - if (isInitial && !page) { - return; - } - if (isInitial) { - this.initialized = true; - this.baselineLength = number(page?.totalLength) ?? 0; - this.baselineSteps = Array.isArray(page?.steps) ? page.steps.length : 0; - this.record('baseline', event, { - totalSteps: this.baselineLength, - receivedSteps: this.baselineSteps, - historical: true, - }); - } - - if (page) { - const steps = Array.isArray(page.steps) ? page.steps : []; - const indices = Array.isArray(page.indices) ? page.indices : []; - if (steps.length !== indices.length) { - throw new Error('invalid_step_indices'); - } - for (let i = 0; i < steps.length; i++) { - const index = number(indices[i]); - if (index === null) { - throw new Error('invalid_step_index'); - } - this.observeStep(index, steps[i], event, isInitial); - } - } - - // 处理模型生成元数据更新(包含服务端原生统计的 TTFT、流式耗时与 Token 用量) - const generators = trajectory?.generatorMetadatasUpdate?.generatorMetadatas; - if (Array.isArray(generators)) { - for (const gen of generators) { - const cm = gen.chatModel; - if (!cm) { - continue; - } - const data = { - usage: tokenUsage(cm.usage), - nativeTtftSec: duration(cm.timeToFirstToken), - nativeStreamSec: duration(cm.streamingDuration), - }; - for (const index of gen.stepIndices || []) { - const state = this.states.get(index); - if (!state || state.historical) { - continue; - } - const signature = JSON.stringify(data); - if (signature === state.generatorSignature) { - continue; - } - state.generatorSignature = signature; - state.nativeTtftSec = data.nativeTtftSec; - state.nativeStreamSec = data.nativeStreamSec; - if (data.usage) { - state.usage = data.usage; - } - this.record('model_timing', event, { - stepIndex: index, - ...data, - }); - this.refreshRecent(state); - } - } - } - } - - /** - * 观测单个规划步骤(`PLANNER_RESPONSE`)的状态与内容增量。 - * - * @param {number} index 步骤在轨迹中的索引 - * @param {object} step 步骤原始数据 - * @param {{ receivedAt: string, elapsedMs: number, receiveBatch: number }} event 接收批次上下文 - * @param {boolean} initial 是否为建连后的首帧基线快照 - */ - observeStep(index, step, event, initial) { - if ( - !step || - (step.type !== 'CORTEX_STEP_TYPE_PLANNER_RESPONSE' && !step.plannerResponse) - ) { - return; - } - - const sourceTiming = timing(step.metadata); - const complete = - Boolean(sourceTiming.finishedGeneratingAt) || END.has(step.status); - let state = this.states.get(index); - - if (!state) { - const historical = initial && complete; - // 建连前已完成的旧步骤即使后续被重新分页加载,也绝不属于新产生的流式输出,直接忽略 - if (historical || (index < this.baselineLength && complete)) { - return; - } - - // 判定是否为半途加入捕获:首帧即存在、索引早于基线总长、缺少创建时间或创建时间早于建连时刻 - const partialCapture = - initial || - index < this.baselineLength || - !sourceTiming.createdAt || - Date.parse(sourceTiming.createdAt) < this.connectedWallMs; - - state = { - index, - historical, - partialCapture, - channels: {}, - events: 0, - toolEvents: 0, - revisions: 0, - firstContentMs: null, - lastContentMs: null, - contentBatches: new Set(), - observedCompletion: false, - toolCount: 0, - usage: null, - }; - this.states.set(index, state); - - // 状态表上限淘汰保护:超出 512 条时移除最早一条已观测完成的步骤,若全部未完成则抛错防泄漏 - if (this.states.size > 512) { - const finished = [...this.states].find(([, s]) => s.observedCompletion); - if (!finished) { - throw new Error('too_many_active_steps'); - } - this.states.delete(finished[0]); - } - } - - const c = content(step); - const changes = {}; - let contentChanged = false; - - for (const key of ['text', 'thinking', 'toolArguments']) { - const parts = key === 'toolArguments' ? c[key] : [c[key]]; - const previous = state.channels[key]; - const diff = compareParts(parts, previous?.parts); - const channel = previous || { - events: 0, - firstMs: null, - lastMs: null, - }; - channel.parts = diff.next; - channel.bytes = diff.bytes; - channel.utf16Units = diff.utf16Units; - - // 初始空快照仅用于建立基准,不计为内容变更事件 - const changed = - diff.changed && (diff.bytes > 0 || (previous && diff.deltaBytes !== 0)); - if (changed && !initial) { - channel.events++; - channel.firstMs ??= event.elapsedMs; - channel.lastMs = event.elapsedMs; - changes[key] = { - bytes: diff.bytes, - utf16Units: diff.utf16Units, - deltaBytes: diff.deltaBytes, - appendOnly: diff.appendOnly, - }; - contentChanged = true; - if (!diff.appendOnly) { - state.revisions++; - } - if (key === 'toolArguments') { - state.toolEvents++; - } - } - state.channels[key] = channel; - } - - if (contentChanged) { - state.events++; - this.contentEvents++; - state.firstContentMs ??= event.elapsedMs; - state.lastContentMs = event.elapsedMs; - state.contentBatches.add(event.receiveBatch); - } - - const usage = tokenUsage(step.metadata?.modelUsage) || state.usage; - const status = - typeof step.status === 'string' && - /^CORTEX_STEP_STATUS_[A-Z_]+$/.test(step.status) - ? step.status - : 'UNKNOWN'; - const signature = JSON.stringify({ - status, - complete, - sourceTiming, - usage, - toolCount: c.toolCount, - }); - const changed = state.signature !== signature; - - state.signature = signature; - state.status = status; - state.observedCompletion ||= !initial && complete; - state.toolCount = c.toolCount; - state.usage = usage; - - if (!initial && (contentChanged || changed)) { - this.record('step_update', event, { - stepIndex: index, - status, - complete, - partialCapture: state.partialCapture, - toolCount: c.toolCount, - changes, - usage, - sourceTiming, - }); - this.refreshRecent(state); - } - } - - /** - * 刷新最近观测步骤摘要列表(最多保留最近更新的 30 个步骤)。 - * - * @param {object} state 步骤内部状态对象 - */ - refreshRecent(state) { - const channels = Object.fromEntries( - Object.entries(state.channels).map(([key, ch]) => [ - key, - { - events: ch.events, - bytes: ch.bytes, - utf16Units: ch.utf16Units, - observedSpanMs: - ch.firstMs === null ? null : rounded(ch.lastMs - ch.firstMs), - }, - ]) - ); - - // 区分单批次到达与跨多批次流式到达:仅当 contentBatches.size >= 2 时才代表观测到了跨批次增量流 - let observationKind; - if (state.partialCapture) { - observationKind = 'partial_capture'; - } else if (state.events === 0) { - observationKind = 'no_content_observed'; - } else if (state.contentBatches.size < 2) { - observationKind = 'single_receive_batch'; - } else { - observationKind = 'multiple_receive_batches'; - } - - const observedSpanMs = - state.firstContentMs === null - ? null - : rounded(state.lastContentMs - state.firstContentMs); - - const item = { - stepIndex: state.index, - complete: state.observedCompletion, - partialCapture: state.partialCapture, - contentEvents: state.events, - contentReceiveBatches: state.contentBatches.size, - toolArgumentEvents: state.toolEvents, - toolCount: state.toolCount, - revisions: state.revisions, - observation: observationKind, - observedSpanMs, - usage: state.usage, - nativeTtftSec: state.nativeTtftSec ?? null, - nativeStreamSec: state.nativeStreamSec ?? null, - channels, - }; - - this.recent = [ - item, - ...this.recent.filter((r) => r.stepIndex !== state.index), - ].slice(0, 30); - } - - /** - * 返回当前连接观测器的实时汇总状态。 - */ - status() { - return { - initialized: this.initialized, - baselineSteps: this.baselineSteps, - messages: this.messages, - contentEvents: this.contentEvents, - recentSteps: this.recent, - }; - } -} - -/** - * 诊断事件 JSONL 循环日志写入器。 - * 当单文件体积超过 `MAX_LOG`(5 MiB)时,自动将当前文件轮转为 `events.jsonl.1` 并创建新文件。 - */ -class DiagnosticLog { - /** - * @param {string} directory 日志存储目录路径 - */ - constructor(directory) { - this.directory = directory; - this.path = join(directory, 'events.jsonl'); - this.size = null; - } - - /** - * 追加写入一条 JSONL 诊断记录。 - * - * @param {object} record 待写入的诊断事件对象 - */ - write(record) { - if (this.size === null) { - mkdirSync(this.directory, { recursive: true }); - this.size = existsSync(this.path) ? statSync(this.path).size : 0; - } - const line = JSON.stringify(record) + '\n'; - const bytes = Buffer.byteLength(line); - if (this.size + bytes > MAX_LOG) { - const previous = this.path + '.1'; - if (existsSync(previous)) { - unlinkSync(previous); - } - if (existsSync(this.path)) { - renameSync(this.path, previous); - } - this.size = 0; - } - appendFileSync(this.path, line, 'utf8'); - this.size += bytes; - } -} - -/** - * 后台状态流诊断管理器。 - * - * 职责与工作机制: - * 1. **配置持久化**: - * 将启用状态(`enabled`)与目标会话 ID(`conversationId`,留空代表自动追踪最新活跃会话) - * 持久化至 `/stream-diagnostics-config.json`;默认关闭(opt-in),与计费和主面板测速完全独立。 - * 2. **会话发现与自动切换(`tick`)**: - * 开启后按 `pollMs`(默认 2000ms)周期轮询 `GetAllCascadeTrajectories`,按最后修改时间降序挑选目标会话; - * 若最新活跃会话发生切换,自动中止旧流并无缝切换到新会话。 - * 3. **后台订阅 `StreamAgentStateUpdates` 与退避重连(`consume`)**: - * 通过 Connect 流式协议建立长连接,设置 15 秒首帧超时保护;当遇到网络断开、流意外结束或 RPC 错误时, - * 对错误码进行白名单脱敏并记录 `nextRetryAt = Date.now() + this.retryMs`,在冷却期过后由 `tick` 自动发起重连。 - */ -export class StreamDiagnostics { - /** - * @param {object} options - * @param {string} options.dataDir 持久化配置与日志根目录 - * @param {string} options.lsAddress LanguageServer 监听地址(`host:port`) - * @param {string} options.csrfToken LanguageServer CSRF 校验令牌 - * @param {typeof fetch} [options.fetchImpl=fetch] 自定义 fetch 实现(便于单测注入) - * @param {number} [options.pollMs=2000] 会话发现轮询间隔毫秒数 - * @param {number} [options.retryMs=5000] 异常断开后的重连退避等待毫秒数 - */ - constructor({ - dataDir, - lsAddress, - csrfToken, - fetchImpl = fetch, - pollMs = 2000, - retryMs = 5000, - }) { - this.dataDir = dataDir; - this.lsAddress = lsAddress; - this.csrfToken = csrfToken; - this.fetch = fetchImpl; - this.pollMs = pollMs; - this.retryMs = retryMs; - this.configPath = join(dataDir, 'stream-diagnostics-config.json'); - this.log = new DiagnosticLog(join(dataDir, 'stream-diagnostics')); - this.config = { enabled: false, conversationId: '' }; - - try { - const config = JSON.parse(readFileSync(this.configPath, 'utf8')); - this.config = { - enabled: config.enabled === true, - conversationId: UUID.test(config.conversationId) - ? config.conversationId - : '', - }; - } catch { - /* 诊断捕获属于可选特性(opt-in),配置文件不存在或损坏时保持默认关闭,不影响主流程 */ - } - - this.phase = 'disabled'; - this.error = null; - this.current = null; - this.lastObservation = null; - this.nextRetryAt = 0; - this.timer = null; - this.discoveryController = null; - this.discovering = false; - } - - /** - * 启动后台轮询与流式订阅定时器。 - */ - start() { - if (this.timer || !this.config.enabled) { - return; - } - this.phase = 'waiting'; - this.tick(); - this.timer = setInterval(() => this.tick(), this.pollMs); - this.timer.unref?.(); - } - - /** - * 停止后台定时器并中止所有正在进行的发现请求与流式连接。 - */ - stop() { - clearInterval(this.timer); - this.timer = null; - this.discoveryController?.abort(); - this.current?.controller.abort(); - this.current = null; - this.phase = 'disabled'; - } - - /** - * 更新并持久化诊断配置,随后重启订阅状态机。 - * - * @param {{ enabled: boolean, conversationId?: string }} options 新配置项 - */ - configure({ enabled, conversationId = '' }) { - if ( - typeof enabled !== 'boolean' || - (conversationId !== '' && !UUID.test(conversationId)) - ) { - throw new Error('invalid_diagnostic_config'); - } - const config = { enabled, conversationId }; - mkdirSync(this.dataDir, { recursive: true }); - writeFileSync(this.configPath, JSON.stringify(config, null, 2), 'utf8'); - this.stop(); - this.config = config; - this.error = null; - this.nextRetryAt = 0; - this.start(); - return this.status(); - } - - /** - * 获取当前流诊断模块的工作状态快照。 - */ - status() { - const activeObservation = this.current?.observation || this.lastObservation; - return { - enabled: this.config.enabled, - phase: this.phase, - error: this.error, - targetMode: this.config.conversationId ? 'fixed' : 'latest', - conversationId: - this.current?.id || this.lastObservation?.conversationId || '', - connectedAt: this.current?.connectedAt || null, - ...activeObservation?.status(), - source: 'antigravity_state_stream', - affectsTps: false, - }; - } - - /** - * 定期轮询 `GetAllCascadeTrajectories` 以发现目标会话并在必要时发起或切换流式订阅。 - */ - async tick() { - if ( - !this.config.enabled || - this.discovering || - Date.now() < this.nextRetryAt - ) { - return; - } - this.discovering = true; - const controller = new AbortController(); - this.discoveryController = controller; - const timeout = setTimeout(() => controller.abort(), 5000); - - try { - const res = await this.fetch( - `http://${this.lsAddress}${SERVICE}GetAllCascadeTrajectories`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-codeium-csrf-token': this.csrfToken, - }, - body: '{}', - signal: controller.signal, - } - ); - if (!res.ok) { - throw new Error('discovery_http_' + res.status); - } - - const body = await res.json(); - if (controller.signal.aborted || !this.config.enabled) { - return; - } - - const entries = Object.entries(body?.trajectorySummaries || {}).filter( - ([id]) => UUID.test(id) - ); - entries.sort((a, b) => { - const timeB = - Date.parse(b[1].lastModifiedTime || b[1].createdTime) || 0; - const timeA = - Date.parse(a[1].lastModifiedTime || a[1].createdTime) || 0; - return timeB - timeA; - }); - - const selected = this.config.conversationId - ? entries.find(([id]) => id === this.config.conversationId) - : entries[0]; - - if (!selected) { - if (!this.current) { - this.phase = 'waiting'; - } - return; - } - - const [id, summary] = selected; - if (this.current?.id === id) { - return; - } - - this.current?.controller.abort(); - const session = { - id, - controller: new AbortController(), - observation: null, - connectedAt: null, - }; - this.current = session; - this.consume(session, number(summary.stepCount) || 0); - } catch (error) { - if ( - !this.config.enabled || - (controller.signal.aborted && this.discoveryController !== controller) - ) { - return; - } - if (!this.current) { - this.phase = 'error'; - } - this.error = /^discovery_http_\d+$/.test(error.message) - ? error.message - : 'discovery_failed'; - this.nextRetryAt = Date.now() + this.retryMs; - } finally { - clearTimeout(timeout); - if (this.discoveryController === controller) { - this.discoveryController = null; - } - this.discovering = false; - } - } - - /** - * 订阅指定会话的 `StreamAgentStateUpdates` Connect 流并持续消费增量帧。 - * - * @param {{ id: string, controller: AbortController, observation: StreamObservation | null, connectedAt: string | null }} session 当前订阅会话上下文 - * @param {number} stepCount 会话发现阶段获知的当前步骤总数(用于计算初始分页窗口起点) - */ - async consume(session, stepCount) { - let reader; - let firstTimer; - this.phase = 'connecting'; - const started = performance.now(); - const connectedWallMs = Date.now(); - const connectionId = randomUUID(); - let receiveBatch = 0; - - try { - firstTimer = setTimeout(() => session.controller.abort(), 15000); - const requestPayload = { - conversationId: session.id, - subscriberId: 'usage-monitor-' + connectionId, - initialStepsPageBounds: { - startIndex: Math.max(0, stepCount - 16), - endIndexExclusive: 2147483647, - }, - initialGeneratorMetadatasPageBounds: { - startIndex: 0, - endIndexExclusive: 2147483647, - }, - initialExecutorMetadatasPageBounds: { - startIndex: 2147483647, - endIndexExclusive: 2147483647, - }, - trajectoryVerbosity: 'CLIENT_TRAJECTORY_VERBOSITY_FULL', - }; - - const res = await this.fetch( - `http://${this.lsAddress}${SERVICE}StreamAgentStateUpdates`, - { - method: 'POST', - headers: { - 'Content-Type': 'application/connect+json', - 'Connect-Protocol-Version': '1', - 'Connect-Accept-Encoding': 'identity', - 'x-codeium-csrf-token': this.csrfToken, - }, - body: encodeConnectJson(requestPayload), - signal: session.controller.signal, - } - ); - - if (!res.ok) { - throw new Error('stream_http_' + res.status); - } - const contentType = res.headers.get('content-type'); - if ( - !contentType?.startsWith('application/connect+json') || - !res.body - ) { - throw new Error('unsupported_stream_content_type'); - } - - const observation = new StreamObservation({ - conversationId: session.id, - connectionId, - connectedWallMs, - emit: (record) => this.log.write(record), - }); - session.observation = observation; - this.lastObservation = observation; - session.connectedAt = new Date(connectedWallMs).toISOString(); - - this.log.write({ - version: 1, - kind: 'connection', - conversationId: session.id, - connectionId, - receivedAt: session.connectedAt, - elapsedMs: 0, - source: 'antigravity_state_stream', - }); - - const decoder = new ConnectJsonDecoder(); - reader = res.body.getReader(); - - while (!session.controller.signal.aborted) { - const { value, done } = await reader.read(); - if (done) { - break; - } - const event = { - elapsedMs: performance.now() - started, - receivedAt: new Date().toISOString(), - receiveBatch: ++receiveBatch, - }; - for (const message of decoder.push(value)) { - if (message.end) { - if (message.value?.error) { - throw new Error('stream_rpc_error'); - } - continue; - } - observation.accept(message.value, event); - if (observation.initialized) { - clearTimeout(firstTimer); - if (this.current === session) { - this.phase = 'collecting'; - this.error = null; - } - } - } - if (decoder.ended) { - break; - } - } - - decoder.finish(); - if (!session.controller.signal.aborted) { - throw new Error('stream_ended'); - } - } catch (error) { - if (this.current === session && this.config.enabled) { - this.phase = 'error'; - // 严禁直接暴露未知异常的原始 message,因为底层解析异常可能夹带模型输出正文或认证凭据 - if (KNOWN_STREAM_ERROR_RE.test(error.message)) { - this.error = error.message; - } else if (session.controller.signal.aborted) { - this.error = 'stream_timeout'; - } else { - this.error = 'stream_failed'; - } - this.nextRetryAt = Date.now() + this.retryMs; - } - } finally { - clearTimeout(firstTimer); - session.controller.abort(); - try { - await reader?.cancel(); - } catch { - /* 底层套接字已关闭时忽略取消异常 */ - } - if (this.current === session) { - this.current = null; - } - } - } -} diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 6b6632c..b78729c 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -5,26 +5,24 @@ * eliminating hardcoded hex colors across components and views. */ -:root { +:root, +:host { /* Architectural Geometry: Only Top Nav uses --radius-pill */ --radius-pill: 999px; --radius-sm: 4px; --radius-xs: 2px; - /* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode) */ + /* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode & safe dark fallback) */ --surface-bg: var(--background, hsl(0 0% 100%)); - --surface-panel: var(--card, hsl(0 0% 100%)); + --surface-panel: var(--card, var(--background, hsl(0 0% 100%))); --surface-subtle: color-mix(in srgb, var(--surface-panel) 97%, var(--text-primary) 3%); --surface-track: color-mix(in srgb, var(--border-hairline) 42%, var(--surface-panel)); - --surface-elevated: var(--surface-panel); --surface-hover: color-mix(in srgb, var(--accent-primary) 6%, var(--surface-panel)); --surface-active: color-mix(in srgb, var(--accent-primary) 12%, var(--surface-panel)); - --surface-backdrop: color-mix(in srgb, var(--surface-bg) 78%, transparent); /* Crisp 1px Hairline Borders */ --border-hairline: color-mix(in srgb, var(--border, hsl(214 18% 88%)) 82%, var(--surface-panel)); --border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%); - --border-focus: var(--accent-primary); /* Typography Hierarchy */ --text-primary: var(--foreground, hsl(215 22% 15%)); @@ -47,10 +45,8 @@ --metric-warn-soft: color-mix(in srgb, var(--metric-warn) 15%, transparent); --metric-danger: var(--destructive, hsl(0 74% 50%)); - --metric-danger-soft: color-mix(in srgb, var(--metric-danger) 15%, transparent); /* Context Window 10-Channel Palette */ - --ctx-messages: hsl(217 82% 51%); --ctx-assistant: hsl(217 82% 54%); --ctx-tool-results: hsl(192 82% 43%); --ctx-user-input: hsl(245 72% 62%); @@ -70,7 +66,7 @@ /* Elevation & Shadows */ --shadow-popover: 0 4px 12px rgb(0 0 0 / 0.22); - --shadow-glider: 0 1px 2px rgb(0 0 0 / 0.14); + --shadow-overlay: 0 16px 38px rgb(0 0 0 / 0.38), 0 3px 10px rgb(0 0 0 / 0.22); /* Fast Hardware-Accelerated Motion Tokens */ --ease-fast: cubic-bezier(0.22, 1, 0.36, 1); @@ -79,12 +75,10 @@ --dur-normal: 180ms; /* Spacing & Density */ - --space-1: 4px; --space-2: 6px; --space-3: 8px; --space-4: 10px; --space-5: 12px; - --space-6: 14px; } /* --- src/styles/base.css --- */ @@ -130,6 +124,11 @@ button, input { font-family: inherit; font-size: inherit; + font-stretch: inherit; + font-variation-settings: inherit; + line-height: inherit; + letter-spacing: inherit; + font-variant-numeric: inherit; color: inherit; } @@ -205,12 +204,10 @@ input { @keyframes anim-pulse-dot { 0%, 100% { - transform: scale(1); opacity: 1; } 50% { - transform: scale(1.22); - opacity: 0.62; + opacity: 0.22; } } @@ -774,10 +771,6 @@ input { overflow: hidden; } -.custom-scroll-host[hidden] { - display: none !important; -} - .custom-scroll-content { flex: 1; min-width: 0; @@ -929,10 +922,6 @@ input { transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast); } -.update-badge-btn[hidden] { - display: none !important; -} - .update-badge-btn:hover { opacity: 0.9; } @@ -941,13 +930,140 @@ input { transform: scale(0.96); } +/* --- 9. 顶部栏定制面板专属表单与排序槽位控件 (Topbar Customization Controls) --- */ +.settings-inline-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + min-height: 26px; +} + +.topbar-header-right { + display: inline-flex; + align-items: center; + gap: var(--space-2); +} + +.btn-ghost-sm { + display: inline-flex; + align-items: center; + justify-content: center; + height: 20px; + padding: 0 6px; + font-size: 11px; + font-weight: 500; + color: var(--text-secondary); + background: transparent; + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + cursor: pointer; + white-space: nowrap; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast), + border-color var(--dur-instant) var(--ease-fast); +} + +.btn-ghost-sm:hover:not(:disabled) { + background: var(--surface-hover); + color: var(--text-primary); + border-color: var(--border-strong); +} + +.btn-ghost-sm:disabled { + opacity: 0.42; + cursor: default; +} + +.topbar-slot-list { + display: flex; + flex-direction: column; + gap: 6px; +} + +.topbar-slot-row { + position: relative; + display: flex; + align-items: center; + gap: 6px; + padding: 2px 4px 2px 6px; + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + background: transparent; + transition: border-color var(--dur-instant) var(--ease-fast); +} + +.topbar-slot-row:focus-within, +.topbar-slot-row:has(.is-open) { + z-index: 30; + border-color: var(--border-strong); +} + +.topbar-slot-row .select-menu { + max-height: 216px; +} + +.slot-index-badge { + display: inline-flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + font-size: 10.5px; + font-weight: 600; + font-variant-numeric: tabular-nums; + color: var(--text-secondary); + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + border-radius: var(--radius-xs); + flex-shrink: 0; +} + +.slot-order-btns { + display: inline-flex; + align-items: center; + gap: 2px; + flex-shrink: 0; +} + +.slot-move-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + padding: 0; + border: none; + border-radius: var(--radius-xs); + background: transparent; + color: var(--text-secondary); + cursor: pointer; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.slot-move-btn:hover:not(:disabled) { + background: var(--surface-hover); + color: var(--text-primary); +} + +.slot-move-btn:active:not(:disabled) { + transform: scale(0.94); +} + +.slot-move-btn:disabled { + opacity: 0.28; + cursor: default; +} + /* --- src/styles/views-overview.css --- */ /* * 实时概览视图与通用面板卡片样式表 (views-overview.css). * 包含: * 1. 通用面板容器与标题头 (.panel, .panel-header, .panel-title, .panel-meta) * 2. 4 格实时测速指标矩阵 (.telemetry-matrix, .matrix-cell, .cell-*) - * 3. 6 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill) + * 3. 10 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill) * 4. 上下文双列图例网格与色块 (.ctx-legend-grid, .legend-*, .swatch) * 5. 双栏布局网格与窄屏响应式断点 (.dual-grid) */ @@ -1001,50 +1117,42 @@ input { .live-activity-list { display: flex; flex-direction: column; - gap: 6px; + gap: 8px; flex-shrink: 0; min-width: 0; } -.live-activity-list[hidden] { - display: none !important; -} - .live-task-card { display: flex; flex-direction: column; - gap: 5px; - padding: 7px 10px; - border: 1px solid var(--accent-primary-border); + gap: 7px; + padding: 10px 12px; + border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); - background: color-mix(in srgb, var(--accent-primary) 5%, var(--surface-panel)); + background: var(--surface-panel); min-width: 0; } -.live-task-card.is-waiting { - border-color: color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); - background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel)); -} - .live-task-header { display: flex; align-items: center; justify-content: space-between; - gap: var(--space-2); + gap: var(--space-3); min-width: 0; } .live-task-title-wrap { display: flex; align-items: center; - gap: 5px; + gap: 7px; min-width: 0; flex: 1; } .live-task-title { - font-size: 11.5px; + font-size: 12px; font-weight: 600; + line-height: 1.45; color: var(--text-primary); white-space: nowrap; overflow: hidden; @@ -1060,7 +1168,7 @@ input { .live-task-header-right { display: inline-flex; align-items: center; - gap: 6px; + gap: 8px; flex-shrink: 0; } @@ -1095,16 +1203,13 @@ input { background: var(--accent-primary-soft); } -.live-sub-toggle[hidden] { - display: none !important; -} - .live-task-main-row { display: flex; align-items: center; - gap: 5px; + gap: 6px; min-width: 0; - padding-left: 1px; + padding-left: 18px; + line-height: 1.45; } .live-activity-dot { @@ -1118,37 +1223,37 @@ input { color: var(--metric-warn); } +.live-task-card.is-compacting .live-activity-dot { + color: var(--ctx-checkpoint); +} + .live-activity-phase { - font-size: 11px; + font-size: 11.5px; font-weight: 600; color: var(--text-primary); white-space: nowrap; flex-shrink: 0; } -.live-task-card.is-waiting .live-activity-phase { - color: var(--metric-warn); -} - .live-activity-progress { - font-size: 10px; + font-size: 10.5px; font-weight: 600; color: var(--accent-primary); background: var(--accent-primary-soft); - padding: 0 4px; + padding: 0 5px; border-radius: var(--radius-xs); white-space: nowrap; flex-shrink: 0; } .live-activity-sep { - font-size: 11px; + font-size: 11.5px; color: var(--text-muted); flex-shrink: 0; } .live-activity-detail { - font-size: 11px; + font-size: 11.5px; color: var(--text-secondary); white-space: nowrap; overflow: hidden; @@ -1158,38 +1263,35 @@ input { } .live-activity-elapsed { - font-size: 11px; - font-weight: 600; - color: var(--accent-primary); + font-size: 11.5px; + font-weight: 500; + color: var(--text-secondary); white-space: nowrap; + min-width: 28px; + text-align: right; flex-shrink: 0; } -.live-task-card.is-waiting .live-activity-elapsed { - color: var(--metric-warn); -} - .live-sub-list { display: flex; flex-direction: column; - gap: 4px; - padding-top: 5px; - margin-top: 1px; + gap: 8px; + padding-top: 9px; + margin-top: 3px; + margin-left: 18px; border-top: 1px dashed var(--border-hairline); min-width: 0; } -.live-sub-list[hidden] { - display: none !important; -} - .live-sub-row { display: flex; align-items: center; justify-content: space-between; - gap: var(--space-2); + gap: 10px; + min-height: 22px; min-width: 0; - font-size: 10.5px; + font-size: 11.5px; + line-height: 1.45; } .live-sub-row.is-done { @@ -1199,7 +1301,7 @@ input { .live-sub-left { display: flex; align-items: center; - gap: 5px; + gap: 7px; min-width: 0; flex: 1; } @@ -1210,7 +1312,7 @@ input { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - max-width: 110px; + max-width: 148px; flex-shrink: 0; } @@ -1224,9 +1326,11 @@ input { } .live-sub-elapsed { - font-size: 10.5px; + font-size: 11px; color: var(--text-secondary); white-space: nowrap; + min-width: 28px; + text-align: right; flex-shrink: 0; } @@ -1283,7 +1387,7 @@ input { text-overflow: ellipsis; } -/* --- 3. 6 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */ +/* --- 3. 10 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */ .progress-track { width: 100%; height: 6px; @@ -1388,6 +1492,7 @@ input { align-items: center; gap: 5px; color: var(--text-secondary); + white-space: nowrap; } .swatch { @@ -1407,10 +1512,6 @@ input { .swatch.seg-skills { background: var(--ctx-skills); } .swatch.seg-system-prompt { background: var(--ctx-system-prompt); } .swatch.seg-user-rules { background: var(--ctx-user-rules); } -.swatch.seg-cached { background: var(--ctx-cached); } -.swatch.seg-input { background: var(--ctx-input); } -.swatch.seg-thinking { background: var(--ctx-thinking); } -.swatch.seg-output { background: var(--ctx-output); } /* --- 5. 双栏网格与窄视口响应式折叠 (Dual Grid & Responsive Breakpoints) --- */ .dual-grid { @@ -1547,14 +1648,14 @@ input { /* * 全景消耗统计视图样式表 (views-consumption.css). * 包含: - * 1. 消费概览顶栏与 3+2 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-*, .cons-col) + * 1. 消费概览顶栏与 3+3 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-3, .cons-col) * 2. 4 段比例条与圆点色块 (.dot-swatch, .cons-seg-bar) * 3. 热门模型与数据来源列表项样式 (.cons-row-*, .cons-share-pill, .cons-item-*) * 4. 历史趋势纯 SVG 平滑曲线图与峰值胶囊 (.trend-*) * 5. 12 个月垂直堆叠柱状图与月度图例 (.monthly-*, .month-*) */ -/* --- 1. 消费概览顶栏与 3+2 组合指标矩阵 (Consumption Overview Matrix) --- */ +/* --- 1. 消费概览顶栏与 3+3 组合指标矩阵 (Consumption Overview Matrix) --- */ .cons-overview-head { flex-wrap: wrap; gap: 6px; @@ -1594,15 +1695,28 @@ input { grid-template-columns: repeat(3, 1fr); } -.cons-split-2 { - display: grid; - grid-template-columns: 1fr 1fr; -} - .cons-matrix-bottom { border-top: 1px solid var(--border-hairline); } +.cons-matrix-bottom .cons-col { + gap: 4px; +} + +@media (max-width: 350px) { + .cons-matrix-bottom.cons-split-3 { + grid-template-columns: 1fr; + } + .cons-matrix-bottom .cons-col { + padding-left: 0; + padding-right: 0; + } + .cons-matrix-bottom .cons-col.is-bordered-col { + border-left: none; + border-top: 1px solid var(--border-hairline); + } +} + .cons-col { display: flex; flex-direction: column; @@ -1651,10 +1765,34 @@ input { letter-spacing: -0.02em; } -.cons-mid-num { - font-size: 13px; - font-weight: 700; +.cons-sub-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + min-width: 0; +} + +.cons-sub-head > span { + white-space: nowrap; + flex-shrink: 0; +} + +.cons-sub-label { + font-size: 11.5px; + font-weight: 600; color: var(--text-primary); + white-space: nowrap; + flex-shrink: 0; +} + +.cons-mid-num { + font-size: 14.5px; + font-weight: 700; + line-height: 1.25; + color: var(--text-primary); + letter-spacing: -0.015em; + white-space: nowrap; } /* --- 2. 4 段比例条与圆点色块 (Four-Segment Bar & Dot Swatches) --- */ @@ -2117,3 +2255,594 @@ input { border: 1px solid var(--border-hairline); background: var(--surface-subtle); } + +/* --- src/styles/overlay.css --- */ +/* + * 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css). + * 严格遵循单层微边框与语义变量规范(零硬编码色值、零 Emoji、硬件加速合成层动画)。 + */ + +/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */ +:host(.wm-capsule-host) { + display: inline-flex; + align-items: center; + gap: 6px; + height: 28px; + flex-shrink: 0; + vertical-align: middle; + -webkit-app-region: no-drag; + pointer-events: auto; + user-select: none; + font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; + font-size: 12px; + font-weight: 450; + font-stretch: 100%; + font-variation-settings: normal; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + -webkit-font-smoothing: antialiased; + color: var(--text-primary); + z-index: 2147482900; +} + +:host(.wm-capsule-host[data-dock="flow"]) { + position: relative; + margin-right: 4px; +} + +:host(.wm-capsule-host[data-dock="fixed"]) { + position: fixed; + top: 6px; + right: 144px; +} + +@keyframes wm-dot-pulse { + 0%, 100% { + opacity: 1; + } + 50% { + opacity: 0.38; + } +} + +/* 左侧多会话实时状态触发器(无边框、与宿主顶栏按钮同高 28px、整数行高防压扁) */ +.wm-multi-btn { + position: relative; + display: inline-flex; + align-items: center; + gap: 6px; + height: 28px; + padding: 0 8px; + margin: 0; + background: transparent; + color: var(--text-secondary); + border: none; + outline: none; + box-shadow: none; + border-radius: var(--radius-sm); + font-family: inherit; + font-size: 12px; + font-weight: 450; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + cursor: pointer; + -webkit-app-region: no-drag; + white-space: nowrap; + contain: layout style; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.wm-multi-btn[hidden], +.wm-cap-slot[hidden], +.wm-sep[hidden] { + display: none !important; +} + +.wm-multi-btn:hover { + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + color: var(--text-primary); +} + +.wm-multi-btn.is-open { + background: color-mix(in srgb, var(--text-primary) 11%, transparent); + color: var(--text-primary); +} + +.wm-multi-dot { + width: 8px; + height: 8px; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-secondary) 44%, transparent); + flex-shrink: 0; +} + +.wm-multi-btn.is-running .wm-multi-dot { + background: var(--accent-primary); + animation: wm-dot-pulse 1.5s ease-in-out infinite; +} + +.wm-multi-btn.is-waiting .wm-multi-dot { + background: var(--metric-warn); + animation: wm-dot-pulse 1.5s ease-in-out infinite; +} + +.wm-multi-label { + display: inline-block; + min-width: 46px; + line-height: 18px; + text-align: left; + white-space: nowrap; + flex-shrink: 0; +} + +.wm-multi-btn.is-running .wm-multi-label, +.wm-multi-btn.is-waiting .wm-multi-label { + color: var(--text-primary); + font-weight: 500; +} + +.wm-capsule-btn { + position: relative; + display: inline-flex; + align-items: center; + gap: 8px; + height: 28px; + padding: 0 9px; + margin: 0; + background: transparent; + color: var(--text-secondary); + border: none; + outline: none; + box-shadow: none; + border-radius: var(--radius-sm); + font-family: inherit; + font-size: 12px; + font-weight: 450; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + cursor: pointer; + -webkit-app-region: no-drag; + white-space: nowrap; + contain: layout style; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.wm-capsule-btn:hover { + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + color: var(--text-primary); +} + +.wm-capsule-btn.is-open { + background: color-mix(in srgb, var(--text-primary) 11%, transparent); + color: var(--text-primary); +} + +/* 右侧胶囊通用槽位容器与按指标预占定宽(严格防止动态数值跳动,保留舒展字间距) */ +.wm-cap-slot { + display: inline-flex; + align-items: center; + justify-content: center; + height: 18px; + line-height: 18px; + flex-shrink: 0; + color: var(--text-secondary); +} + +.wm-slot-text { + display: inline-block; + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + flex-shrink: 0; +} + +/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */ +.wm-ctx-seg { + justify-content: center; + gap: 5px; + width: 50px; +} + +.wm-ring-svg { + width: 14px; + height: 14px; + flex-shrink: 0; + transform: rotate(-90deg); +} + +.wm-ring-track { + fill: none; + stroke: color-mix(in srgb, var(--text-secondary) 24%, transparent); + stroke-width: 2; +} + +.wm-ring-fill { + fill: none; + stroke: var(--accent-primary); + stroke-width: 2; + stroke-linecap: round; + transition: + stroke-dashoffset var(--dur-normal) var(--ease-fast), + stroke var(--dur-fast) var(--ease-fast); +} + +.wm-ring-fill.tone-warn { + stroke: var(--metric-warn); +} + +.wm-ring-fill.tone-danger { + stroke: var(--metric-danger); +} + +.wm-ctx-pct { + min-width: 27px; + max-width: 31px; + text-align: left; + font-weight: 500; + color: var(--text-primary); +} + +.wm-sep { + width: 1px; + height: 12px; + background: color-mix(in srgb, var(--text-secondary) 26%, transparent); + flex-shrink: 0; +} + +/* 速度槽位(固定预占宽度 58px 居中对齐) */ +.wm-seg-speed { + width: 58px; +} + +.wm-speed-text { + width: 58px; + text-align: center; +} + +.wm-seg-speed.state-running { + color: var(--metric-speed); + font-weight: 500; +} + +/* 首字延迟槽位(固定预占宽度 46px 居中对齐,覆盖 0.85s ~ 105s) */ +.wm-seg-ttft { + width: 46px; +} + +.wm-ttft-text { + width: 46px; + text-align: center; +} + +/* 本次费用槽位(固定预占宽度 52px 居中对齐,覆盖 <$0.001 ~ $99.99) */ +.wm-seg-cost { + width: 52px; +} + +.wm-cost-text { + width: 52px; + text-align: center; + color: var(--text-primary); + font-weight: 500; +} + +/* 配额槽位(固定预占宽度 52px 居中对齐,完整容纳 余 100% / 余 --% 且在任意槽位对称) */ +.wm-seg-quota { + width: 52px; +} + +.wm-quota-text { + width: 52px; + text-align: center; +} + +.wm-cap-slot.tone-warn, +.wm-cap-slot.tone-warn .wm-slot-text { + color: var(--metric-warn); + font-weight: 500; +} + +.wm-cap-slot.tone-danger, +.wm-cap-slot.tone-danger .wm-slot-text { + color: var(--metric-danger); + font-weight: 500; +} + +/* 右上角绝对定位更新圆点,不参与文档流,零宽度抖动 */ +.wm-update-dot { + position: absolute; + top: 3px; + right: 3px; + width: 5px; + height: 5px; + border-radius: var(--radius-pill); + background: var(--metric-ok); + pointer-events: none; +} + +/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 与分隔线次序 data-sep-for-rank 动态折叠) */ +:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="3"], +:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"] { + display: none !important; +} + +:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="2"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="3"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="2"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="3"], +:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-label { + display: none !important; +} + +:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-btn, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-btn { + padding: 0 7px; +} + +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="2"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="3"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="2"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="3"], +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label { + display: none !important; +} + +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-capsule-btn { + padding: 0 6px; +} + +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg { + width: 14px; +} + +/* --- 2. 顶层浮层传送门宿主 (Body Portal Host: Multi-Session HUD, Tooltip & Full 4-Tab Popover) --- */ +:host(.wm-portal-host) { + position: fixed; + inset: 0; + width: 0; + height: 0; + overflow: visible; + pointer-events: none; + z-index: 2147483000; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; + font-size: 12.5px; + line-height: 1.4; + font-variant-numeric: tabular-nums; + -webkit-font-smoothing: antialiased; + color: var(--text-primary); +} + +@keyframes wm-popover-in { + from { + opacity: 0; + transform: translateY(-3px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.wm-popover-panel { + position: fixed; + top: 42px; + left: 12px; + width: min(492px, calc(100vw - 24px)); + height: min(588px, calc(100vh - 54px)); + max-height: calc(100vh - 54px); + display: flex; + flex-direction: column; + background: var(--surface-bg); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-overlay); + pointer-events: auto; + overflow: hidden; + -webkit-app-region: no-drag; + transform-origin: top right; + animation: wm-popover-in var(--dur-fast) var(--ease-fast); +} + +.wm-popover-panel .app-shell { + height: 100%; + max-height: 100%; + max-width: none; +} + +/* 顶栏胶囊悬停全景概览浮层(复用实时概览三卡片架构,全槽位预占,仅就地更新节点不跳动) */ +.wm-hover-tip { + position: fixed; + top: 42px; + left: 12px; + width: min(492px, calc(100vw - 24px)); + max-height: calc(100vh - 54px); + padding: var(--space-3) var(--space-4); + display: flex; + flex-direction: column; + gap: var(--space-3); + background: var(--surface-bg); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-overlay); + pointer-events: none; + overflow: hidden; + contain: layout style; + z-index: 2147483001; + transform-origin: top right; + animation: wm-popover-in var(--dur-instant) var(--ease-fast); +} + +/* 左侧在线多会话实时看板浮层(单层无套娃细线卡片,仅显示在线运行会话,留足呼吸感) */ +.wm-multi-panel { + position: fixed; + top: 42px; + left: 12px; + width: min(484px, calc(100vw - 24px)); + max-height: calc(100vh - 54px); + padding: 14px 16px; + display: flex; + flex-direction: column; + gap: 0; + background: var(--surface-bg); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); + box-shadow: var(--shadow-overlay); + pointer-events: auto; + overflow-x: hidden; + overflow-y: auto; + -webkit-app-region: no-drag; + contain: layout style; + z-index: 2147483002; + transform-origin: top left; + animation: wm-popover-in var(--dur-instant) var(--ease-fast); +} + +.wm-popover-panel.is-instant, +.wm-hover-tip.is-instant, +.wm-multi-panel.is-instant { + animation: none !important; +} + +.wm-hover-tip .cell-label, +.wm-hover-tip .legend-item, +.wm-hover-tip .legend-left, +.wm-hover-tip .panel-header > span { + white-space: nowrap; + min-width: 0; +} + +.wm-hover-tip .panel-header > span:first-child:not(.panel-title) { + overflow: hidden; + text-overflow: ellipsis; +} + +.wm-hover-quota-pools { + display: flex; + flex-direction: column; + gap: 0; +} + +.wm-hover-quota-foot { + font-size: 11px; + padding-top: 2px; +} + +.wm-pin-badge { + display: inline-flex; + align-items: center; + height: 16px; + padding: 0 5px; + font-size: 10px; + font-weight: 600; + color: var(--accent-primary); + background: var(--accent-primary-soft); + border-radius: var(--radius-xs); + flex-shrink: 0; +} + +.wm-session-tag { + display: inline-flex; + align-items: center; + height: 16px; + padding: 0 4px; + font-size: 10px; + font-weight: 600; + color: var(--text-secondary); + background: color-mix(in srgb, var(--text-primary) 7%, transparent); + border-radius: var(--radius-xs); + white-space: nowrap; + flex-shrink: 0; +} + +.wm-session-tag.is-here { + color: var(--accent-primary); + background: var(--accent-primary-soft); +} + +.wm-task-metrics { + font-size: 11px; + color: var(--text-secondary); + white-space: nowrap; + flex-shrink: 0; +} + +.wm-multi-header { + padding-bottom: 10px; + border-bottom: 1px solid var(--border-hairline); +} + +/* 多会话单层面板内去除重复边框与底色,留足行距与段落呼吸感,仅靠左侧圆点闪烁表达状态 */ +.wm-multi-panel .live-activity-list { + gap: 0; +} + +.wm-multi-panel .live-task-card { + gap: 8px; + padding: 12px 2px; + border: none; + border-radius: 0; + background: transparent; +} + +.wm-multi-panel .live-task-card:first-child { + padding-top: 11px; +} + +.wm-multi-panel .live-task-card:last-child { + padding-bottom: 2px; +} + +.wm-multi-panel .live-task-card + .live-task-card { + border-top: 1px solid var(--border-hairline); +} + +.wm-multi-panel .live-task-title { + font-size: 12.5px; +} + +.wm-multi-empty { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + min-height: 36px; + padding: 12px 2px 4px; + font-size: 12px; + color: var(--text-secondary); +} + +.wm-multi-empty-left { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; +} + +.wm-idle-dot { + width: 8px; + height: 8px; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-secondary) 38%, transparent); + flex-shrink: 0; +} + +.wm-multi-empty-hint { + font-size: 11px; + color: var(--text-muted); + white-space: nowrap; + flex-shrink: 0; +} diff --git a/sidecars/panel/test/audit-fixes.test.mjs b/sidecars/panel/test/audit-fixes.test.mjs new file mode 100644 index 0000000..f895495 --- /dev/null +++ b/sidecars/panel/test/audit-fixes.test.mjs @@ -0,0 +1,533 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import { backendHarness } from './backend-harness.mjs'; +import { + extractContextBreakdown, + extractModelSteps, + normalizeCachedStep, +} from '../speed-metrics.mjs'; +import { + formatCountdown, + formatUsd, + speedReasonText, +} from '../src/core/formatters.js'; +import { createReactiveStore } from '../src/core/reactive.js'; +import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; + +const nowMs = Date.now(); +const nowIso = new Date(nowMs - 5_000).toISOString(); +const doneIso = new Date(nowMs - 3_000).toISOString(); + +test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as Gemini, and M429/M322/M149/M20 resolve accurately', () => { + const h = backendHarness({ + userStatus: { + cascadeModelConfigData: { + clientModelConfigs: [ + { + modelOrAlias: { model: 'MODEL_CLAUDE_PROXY' }, + label: 'Claude Opus 4.6 (Google Vertex)', + quotaInfo: { remainingFraction: 0.75, resetTime: new Date(nowMs + 3600_000).toISOString() }, + }, + ], + }, + }, + }); + + const infoClaude = h.resolveModelInfo('claude-opus-4-6', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(infoClaude.family, 'Claude'); + const infoO3 = h.resolveModelInfo('o3-mini', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(infoO3.family, 'GPT'); + + // Calling resolveModelInfo with omitted dynamicModelMap must not throw (BUG-03) + const infoDefaultMap = h.resolveModelInfo('MODEL_PLACEHOLDER_M320'); + assert.equal(infoDefaultMap.modelId, 'gemini-3.8-flash-low'); + assert.equal(infoDefaultMap.pricing?.input, 0.3); + + const m429 = h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m429.modelId, 'gemini-4-carbon-high'); + assert.equal(m429.shortName, 'carbon-4-high'); + + const m322 = h.resolveModelInfo('MODEL_PLACEHOLDER_M322', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m322.modelId, 'gemini-3.8-flash-tiered'); + assert.equal( + h.computeStepCost( + { + modelKey: 'MODEL_PLACEHOLDER_M322', + inputTokens: 1_000_000, + cacheReadTokens: 0, + outputTokens: 0, + }, + m322.pricing + ), + 0.75 + ); + + const m149 = h.resolveModelInfo('MODEL_PLACEHOLDER_M149', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m149.modelId, 'gemini-3.5-flash-high'); + + const m20 = h.resolveModelInfo('MODEL_PLACEHOLDER_M20', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m20.modelId, 'gemini-3.5-flash'); +}); + +test('BUG-02 & BUG-11: ide: external sessions do not double-count live conversations, cross-account entries are isolated, and orphan subagents never leak to top-level list', async () => { + const stepObj = { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '10000', + cacheReadTokens: '20000', + outputTokens: '5000', + }, + }, + }; + const h = backendHarness({ + userStatus: { email: 'alice@example.com' }, + deepStats: { + accountName: 'alice@example.com', + perConvo: { + // Same conversation ID as live 'abcd-1234' (case-insensitive, prefixed with 'ide:') -> must deduplicate! + 'ide:AbCd-1234': { + accountName: 'alice@example.com', + appSource: 'ide', + entries: [ + { ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 }, + { ts: doneIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 }, + ], + }, + // Different account -> must be excluded when logged in as alice@example.com! + 'ide:bob-conv': { + accountName: 'bob@example.com', + appSource: 'ide', + entries: [ + { ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 99000, cache: 0, out: 1000, reasoning: 0 }, + ], + }, + }, + }, + cache: { + 'orphan-sub': { + accountName: 'bob@example.com', + isSubagent: true, + parentCascadeId: 'deleted-parent', + signature: 'v10-model-identity:sub', + steps: extractModelSteps([stepObj]), + }, + }, + summaries: { + 'abcd-1234': { stepCount: 1, lastModifiedTime: doneIso, status: 'IDLE' }, + }, + trajectories: { + 'abcd-1234': { trajectory: { steps: [stepObj] } }, + }, + }); + + const p = await h.buildTelemetryPayloadInternal('abcd-1234', false, { range: 'all' }); + // ide:AbCd-1234 has 2 entries vs live abcd-1234's 1 step -> deduplicated (no 1 + 2 = 3 double counting!), bob excluded! + assert.equal(p.consumption.account.conversationsCount, 1); + assert.equal(p.consumption.account.calls, 2); + assert.equal(p.consumption.account.totalTokens, 70_000); + assert.equal( + p.conversations.some((c) => c.cascadeId === 'orphan-sub'), + false, + 'orphan subagent must not appear in top-level conversation dropdown' + ); +}); + +test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd rounding, and dynamicModelMap default', async () => { + const badStep = { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '-5000', + cacheReadTokens: 'NaN', + outputTokens: '1000', + thinkingOutputTokens: '2500', + }, + }, + }; + const extracted = extractModelSteps([badStep]); + assert.equal(extracted[0].inputTokens, 0); + assert.equal(extracted[0].cacheReadTokens, 0); + assert.equal(extracted[0].outputTokens, 1000); + assert.equal(extracted[0].thinkingTokens, 1000); + assert.equal(extracted[0].responseTokens, 0); + assert.equal(normalizeCachedStep({ ...extracted[0], inputTokens: -99 }).inputTokens, 0); + assert.equal(normalizeCachedStep(null), null); + + // Micro-steps: 100 steps * (1067 output * $3.75 / 1M = $0.00400125) = $0.40 (previously rounded per-step to $0.00 -> $0.00!) + const microSteps = Array.from({ length: 100 }, (_, idx) => ({ + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx + 1 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', // gemini-3.8-flash-high: $0.75/1M input, $3.75/1M output + inputTokens: '0', + cacheReadTokens: '0', + outputTokens: '1067', + }, + }, + })); + const h = backendHarness({ + summaries: { micro: { stepCount: 100, lastModifiedTime: doneIso, status: 'IDLE' } }, + trajectories: { micro: { trajectory: { steps: microSteps } } }, + }); + const p = await h.buildTelemetryPayloadInternal('micro', false, { range: 'today' }); + assert.equal(p.consumption.account.costUsd, 0.4); +}); + +test('BUG-04 & BUG-10: failed RUNNING trajectory fetch enters cooldown instead of hammering RPC every poll, cleared by forceRefresh', async () => { + const h = backendHarness({ + summaries: { run1: { stepCount: 2, lastModifiedTime: doneIso, status: 'CASCADE_RUN_STATUS_RUNNING' } }, + trajectories: { run1: new Error('LS timeout') }, + quotaSummary: new Error('Quota RPC down'), + }); + + await h.buildTelemetryPayloadInternal('run1', false); + const callsAfterFirst = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; + const quotaCallsAfterFirst = h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length; + assert.equal(callsAfterFirst, 1); + assert.equal(quotaCallsAfterFirst, 1); + + // Immediate second background poll must respect cooldown for both trajectory and quota RPC + await h.buildTelemetryPayloadInternal('run1', false); + assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 1); + assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 1); + + // Manual forceRefresh=true bypasses cooldown immediately + await h.buildTelemetryPayloadInternal('run1', true); + assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 2); + assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 2); +}); + +test('BUG-09, BUG-14 & BUG-15: SemVer 2.0 prerelease/build ordering, future-only exhausted quota inference, and <6h dual-bucket classification', async () => { + const h = backendHarness({ + quotaSummary: { + groups: [ + { + displayName: 'Gemini', + buckets: [ + { + // Omitted remainingFraction with epoch-0 resetTime must NOT falsely report 0% remaining! + resetTime: '1970-01-01T00:00:00Z', + }, + ], + }, + { + displayName: 'Claude & GPT', + buckets: [ + { + remainingFraction: 0.4, + resetTime: new Date(nowMs + 2 * 3600_000).toISOString(), + }, + { + remainingFraction: 0.8, + // Weekly bucket that happens to be 4h away from resetting! + resetTime: new Date(nowMs + 4 * 3600_000).toISOString(), + }, + ], + }, + ], + }, + }); + + assert.equal(h.compareSemver('1.4.2+20261110', '1.4.2'), 0); + assert.equal(h.compareSemver('1.5.0-beta.2', '1.5.0-alpha.10'), 1); + assert.equal(h.compareSemver('1.5.0-alpha.1', '1.5.0-alpha.beta'), -1); + + const p = await h.buildTelemetryPayloadInternal(''); + const geminiPool = p.quotas.pools.find((x) => x.poolKey === 'Gemini'); + assert.ok(geminiPool); + assert.equal(geminiPool.isAvailable, false, 'epoch-0 omitted remainingFraction must not create fake 0% exhausted pool'); + assert.equal(geminiPool.remainingPct, null); + assert.equal(geminiPool.usedPct, null); + + const claudePool = p.quotas.pools.find((x) => x.poolKey === 'Claude & GPT'); + assert.ok(claudePool); + assert.equal(claudePool.remainingPct, 40); + assert.equal(claudePool.weeklyRemainingPct, 80); + + assert.equal(formatCountdown(new Date(nowMs + 30_000).toISOString(), nowMs), '<1分钟后重置'); + assert.equal(formatCountdown('1969-12-31T23:59:59Z', nowMs), '未知重置时间'); + assert.equal(formatUsd(0.0004, { precise: true }), '<$0.001'); + assert.equal(formatUsd(12.34, { unpricedCalls: 1, compactPending: true }), '$12.34+'); + assert.equal(speedReasonText('short_timing'), '耗时过短 (<0.5s)'); +}); + +test('BUG-17 & CANCEL-06: extractContextBreakdown classifies messagePrompts when children are empty and blocks post-compaction carryover', () => { + const ctx = extractContextBreakdown({ + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 10000, + tokenBreakdown: { + groups: [ + { type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 2000 }, + { type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 8000, children: [] }, + ], + }, + }, + }, + messagePrompts: [ + { source: 'CHAT_MESSAGE_SOURCE_USER', prompt: 'hello world' }, + { source: 'CHAT_MESSAGE_SOURCE_MODEL', prompt: 'Assistant reply content here!' }, + ], + }); + assert.ok(ctx); + assert.equal(ctx.systemPromptTokens, 2000); + assert.ok(ctx.userInputTokens > 0); + assert.ok(ctx.assistantTokens > 0); + assert.equal(ctx.userInputTokens + ctx.assistantTokens, 8000); + + const stepsWithTrailingCheckpoint = extractModelSteps( + [ + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '500' }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '1200' }, + }, + }, + ], + [ + { + stepIndices: [1], + chatModel: { + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 180_000, + tokenBreakdown: { + groups: [{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 180_000 }], + }, + }, + }, + }, + }, + ] + ); + assert.equal(stepsWithTrailingCheckpoint.length, 2); + assert.equal(stepsWithTrailingCheckpoint[1].isCompactionStep, true); + assert.equal( + stepsWithTrailingCheckpoint[1].contextBreakdown, + null, + 'compaction checkpoint must not inherit pre-compaction 180k contextBreakdown' + ); +}); + +test('BUG-20 & BUG-24: reactive store microtask deduplication, stripModuleSyntax safety, and IIFE bundle isolation', async () => { + const store = createReactiveStore({ a: 1, b: 2 }); + let calls = 0; + store.subscribe((s) => s.a + s.b, () => { + calls += 1; + }, { immediate: false }); + + store.setState({ a: 10 }); + store.setState({ b: 20 }); + await new Promise((r) => queueMicrotask(r)); + assert.equal(calls, 1, 'multiple setState calls in same microtask must batch into 1 subscriber flush'); + + const trickyModule = [ + "import './side-effect.js';", + "import { foo,\n bar } from './multi.js';", + 'const tpl = `\nimport { keepMe } from "tpl";\nexport const KEEP_ME = 42;\n`;', + 'export async function runTask() { return tpl; }', + 'export { runTask };', + ].join('\n'); + + const stripped = stripModuleSyntax(trickyModule); + assert.ok(stripped.includes('import { keepMe } from "tpl"')); + assert.ok(stripped.includes('export const KEEP_ME = 42')); + assert.equal(/^\s*import\s/m.test(stripped.replace(/`[\s\S]*?`/g, '')), false); + assert.doesNotThrow(() => new vm.Script(stripped)); + + const appBundle = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); + assert.ok(appBundle.startsWith('(() => {\n\'use strict\';')); + assert.ok(appBundle.trimEnd().endsWith('})();')); +}); + +test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => { + const convId = '4432b724-3e1e-4421-a375-c6855a7b7b37'; + + // Pre-compaction steps (matching real-world step 0..2: planner edit_file x2 + 2 completed tool results) + const rpcPreCompactionSteps = [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-11T02:18:21Z', + finishedGeneratingAt: '2026-11-11T02:18:35Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '2918', + cacheReadTokens: '252465', + outputTokens: '814', + }, + }, + plannerResponse: { + toolCalls: [ + { name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/backend-harness.mjs' }) }, + { name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/04-post-fix-verify.mjs' }) }, + ], + }, + }, + { + type: 'CORTEX_STEP_TYPE_CODE_ACTION', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:38Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_CODE_ACTION', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:40Z' }, + }, + ]; + + // transcript.jsonl still ends at step_index 2 (since CHECKPOINT only flushes to transcript.jsonl when DONE) + const transcriptPreFlush = [ + { + step_index: 0, + source: 'MODEL', + type: 'PLANNER_RESPONSE', + status: 'DONE', + created_at: '2026-11-11T02:18:21Z', + tool_calls: [ + { name: 'edit_file', args: { Path: '"f:\\\\repo\\\\backend-harness.mjs"' } }, + { name: 'edit_file', args: { Path: '"f:\\\\repo\\\\04-post-fix-verify.mjs"' } }, + ], + }, + { + step_index: 1, + source: 'MODEL', + type: 'GENERIC', + status: 'DONE', + created_at: '2026-11-11T02:18:35Z', + content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:38+09:00\nMade 1 replacement', + }, + { + step_index: 2, + source: 'MODEL', + type: 'GENERIC', + status: 'DONE', + created_at: '2026-11-11T02:18:35Z', + content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:40+09:00\nMade 1 replacement', + }, + ]; + + // Phase 1: In-progress CORTEX_STEP_TYPE_CHECKPOINT in RPC WITHOUT metadata.createdAt yet + trailing MEMENTO + const h = backendHarness({ + summaries: { + [convId]: { + stepCount: 4, + lastModifiedTime: '2026-11-11T02:18:35Z', + status: 'CASCADE_RUN_STATUS_RUNNING', + annotations: { title: 'Audit & Fix Session' }, + }, + }, + trajectories: { + [convId]: { + trajectory: { + steps: [ + ...rpcPreCompactionSteps, + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_RUNNING', + metadata: {}, + }, + { + type: 'CORTEX_STEP_TYPE_MEMENTO', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-11-11T02:18:40Z' }, + }, + ], + }, + }, + }, + transcripts: { + [convId]: transcriptPreFlush, + }, + }); + + const pCompacting = await h.buildTelemetryPayloadInternal(convId); + assert.equal(pCompacting.activeConversation.liveActivity.phase, 'compacting'); + assert.equal(pCompacting.activeConversation.liveActivity.label, '上下文压缩'); + assert.equal( + pCompacting.activeConversation.liveActivity.startedAtMs, + Date.parse('2026-11-11T02:18:40Z'), + 'uses previous tool completion timestamp when in-progress CHECKPOINT lacks createdAt' + ); + assert.equal(pCompacting.runningConversations[0].mainActivity.phase, 'compacting'); + assert.equal(pCompacting.runningConversations[0].mainActivity.label, '上下文压缩'); + + // Phase 2: CHECKPOINT finishes (status=DONE in both RPC & transcript.jsonl) while resuming before next PLANNER_RESPONSE + h.state.trajectories[convId] = { + trajectory: { + steps: [ + ...rpcPreCompactionSteps, + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-11T02:18:40Z', + finishedGeneratingAt: '2026-11-11T02:19:33Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '3082', + cacheReadTokens: '254224', + outputTokens: '4627', + }, + }, + }, + ], + }, + }; + h.state.transcripts[convId] = [ + ...transcriptPreFlush, + { + step_index: 3, + source: 'SYSTEM', + type: 'CHECKPOINT', + status: 'DONE', + created_at: '2026-11-11T02:18:40Z', + content: '# Resuming from a compaction\n...', + }, + ]; + h.state.transcriptMtimeMs = 2; + + const pResuming = await h.buildTelemetryPayloadInternal(convId); + assert.equal(pResuming.activeConversation.liveActivity.phase, 'compacting'); + assert.equal(pResuming.activeConversation.liveActivity.label, '上下文压缩'); + assert.equal(pResuming.activeConversation.liveActivity.detail, '已完成压缩,正在恢复推理'); + assert.equal( + pResuming.activeConversation.liveActivity.startedAtMs, + Date.parse('2026-11-11T02:19:33Z') + ); + + // Phase 3: Even when RPC fails/cools down and ONLY transcript.jsonl (with status="DONE" CHECKPOINT) is available, + // it STILL detects compaction instead of regressing to pre-compaction "修改文件" + h.state.trajectories[convId] = new Error('temporary RPC timeout'); + const pTranscriptOnly = await h.buildTelemetryPayloadInternal(convId, true); + assert.equal(pTranscriptOnly.activeConversation.liveActivity.phase, 'compacting'); + assert.equal(pTranscriptOnly.activeConversation.liveActivity.label, '上下文压缩'); +}); diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 96081c8..34e5534 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -2,6 +2,16 @@ import fs from 'node:fs'; import path from 'node:path'; import vm from 'node:vm'; import * as metrics from '../speed-metrics.mjs'; +import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; + +const REAL_CATALOG_RAW = JSON.parse( + fs.readFileSync(new URL('../../../pricing-catalog.json', import.meta.url), 'utf8') +); +const DEFAULT_BUNDLED_CATALOG = { + schemaVersion: 1, + pricing: REAL_CATALOG_RAW.pricing, + placeholders: REAL_CATALOG_RAW.placeholders, +}; const BACKEND_MODULE_FILES = [ '../backend/config.mjs', @@ -13,6 +23,7 @@ const BACKEND_MODULE_FILES = [ '../backend/local-scanner.mjs', '../backend/usage-aggregator.mjs', '../backend/telemetry-builder.mjs', + '../backend/window-bridge.mjs', '../main.mjs', ]; @@ -23,20 +34,19 @@ function loadCombinedBackendSource() { } function stripEsmSyntax(rawSource, mainUrl) { - return rawSource - .replace(/^\s*import\s+[\s\S]*?from\s+['"][^'"]+['"];?\r?\n/gm, '') - .replace(/^\s*export\s+(?=(?:async\s+)?function\b|const\b|let\b|class\b)/gm, '') - .replaceAll('import.meta.url', JSON.stringify(mainUrl)); + return stripModuleSyntax(rawSource).replaceAll('import.meta.url', JSON.stringify(mainUrl)); } export function backendHarness({ cache={}, + deepStats=null, + transcripts={}, settings={}, trajectories={}, summaries={}, userStatus={}, quotaSummary={groups:[]}, - localCatalog=null, + localCatalog=DEFAULT_BUNDLED_CATALOG, remoteCatalog=null, pluginManifest=null, hasGitDir=false, @@ -49,7 +59,7 @@ export function backendHarness({ const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs'; const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs'; const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl); - const state={calls:[],errors:[],saves:[],trajectories,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir}; + const state={calls:[],errors:[],saves:[],trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1}; const ctx={ ...metricsImplementation, URL, AbortSignal, Buffer, process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}}, @@ -63,16 +73,42 @@ export function backendHarness({ existsSync:p=>{ const norm = String(p).replace(/\\/g, '/'); if (norm.endsWith('settings.json') || norm.endsWith('trajectory_usage_cache.json')) return true; + if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return Boolean(state.deepStats); if (norm.endsWith('pricing-catalog.json')) return Boolean(state.localCatalog); if (norm.endsWith('remote_pricing_cache.json')) return Boolean(state.remoteCatalog); if (norm.endsWith('plugin.json')) return Boolean(state.pluginManifest); + if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) { + const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i); + return Boolean(m && state.transcripts?.[m[1]]); + } if (norm.endsWith('/.git')) return Boolean(state.hasGitDir); return false; }, - mkdirSync:()=>{},readdirSync:()=>[],statSync:()=>({mtimeMs:0}), + mkdirSync:()=>{},readdirSync:()=>[], + statSync:p=>{ + const norm = String(p).replace(/\\/g, '/'); + if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) { + const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i); + const lines = m && state.transcripts?.[m[1]]; + if (lines) { + const text = Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines); + return {mtimeMs:state.transcriptMtimeMs,size:Buffer.byteLength(text,'utf8')}; + } + } + if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json') && state.deepStats) { + return {mtimeMs:state.deepStatsMtimeMs,size:JSON.stringify(state.deepStats).length}; + } + return {mtimeMs:0,size:0}; + }, readFileSync:p=>{ const norm = String(p).replace(/\\/g, '/'); + if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) { + const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i); + const lines = m && state.transcripts?.[m[1]]; + return Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines || ''); + } if (norm.endsWith('settings.json')) return JSON.stringify(settings); + if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return JSON.stringify(state.deepStats); if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog); if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog); if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest); @@ -89,7 +125,6 @@ export function backendHarness({ homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,fileURLToPath:()=>mainPath, Response:class {constructor(body,options){this.body=body;this.options=options;}}, SidecarApp:class {page(){} api(){} run(){}}, - StreamDiagnostics:class {status(){return {enabled:false};} start(){}}, fetch:async(url,options={})=>{ if (/^https?:\/\/(?!test\.invalid)/i.test(String(url)) && remoteFetch) { return remoteFetch(url, options); @@ -101,13 +136,14 @@ export function backendHarness({ return {ok:true,json:async()=>data||{}}; } if(method==='RetrieveUserQuotaSummary') { - if(state.quotaSummary instanceof Error) throw state.quotaSummary; - return {ok:true,json:async()=>({response:state.quotaSummary})}; + const qs=state.quotaSummary; + if(qs instanceof Error) throw qs; + return {ok:true,json:async()=>({response:qs})}; } const data={GetUserStatus:{userStatus:state.userStatus},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method]; return {ok:true,json:async()=>data}; }, }; - vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,compareSemver,performPluginUpdate};',ctx); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isCarbonModelIdentifier,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate};',ctx); return {...ctx.api,state}; } diff --git a/sidecars/panel/test/model-identity.test.mjs b/sidecars/panel/test/model-identity.test.mjs index cbeb0c8..1283a88 100644 --- a/sidecars/panel/test/model-identity.test.mjs +++ b/sidecars/panel/test/model-identity.test.mjs @@ -158,7 +158,7 @@ test('old ambiguous Argon cache is persisted as unresolved while retaining moder await h.buildTelemetryPayloadInternal('test'); assert.equal(h.state.saves.length,1,'do not rewrite identical migrated cache every poll'); h.state.trajectories.test = {trajectory:{steps:[step(211,FLASH,true)]}}; - const restored = await h.buildTelemetryPayloadInternal('test'); + const restored = await h.buildTelemetryPayloadInternal('test', true); assert.equal(restored.activeConversation.activeModelShort,'flash-3.8-high·压缩'); assert.equal(restored.consumption.account.unpricedCalls,0); }); diff --git a/sidecars/panel/test/stream-diagnostics.test.mjs b/sidecars/panel/test/stream-diagnostics.test.mjs deleted file mode 100644 index 149dcc9..0000000 --- a/sidecars/panel/test/stream-diagnostics.test.mjs +++ /dev/null @@ -1,194 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; -import { ConnectJsonDecoder, StreamObservation, StreamDiagnostics, encodeConnectJson } from '../stream-diagnostics.mjs'; - -const ID = '12345678-1234-1234-1234-123456789abc'; -const CREATED = '2026-10-15T01:00:00.000Z'; -const FINISHED = '2026-10-15T01:00:08.000Z'; -const event = (ms, batch = ms) => ({ elapsedMs: ms, receiveBatch: batch, receivedAt: CREATED }); -const model = (p = {}, done = false, extra = {}) => ({ - type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', status: done ? 'CORTEX_STEP_STATUS_DONE' : 'CORTEX_STEP_STATUS_STREAMING', - metadata: { createdAt: CREATED, ...(done ? { finishedGeneratingAt: FINISHED, modelUsage: { outputTokens: '400' } } : {}) }, - plannerResponse: p, ...extra, -}); -const update = (indices, steps, totalLength, more = {}) => ({ update: { conversationId: ID, - mainTrajectoryUpdate: { stepsUpdate: { indices, steps, totalLength }, ...more } } }); -function observer() { - const records = []; - const observation = new StreamObservation({ conversationId: ID, connectedWallMs: Date.parse(CREATED) - 1000, emit: r => records.push(r) }); - return { records, observation }; -} - -test('Connect decoder reconstructs fragmented headers/UTF-8 and keeps coalesced messages separate', () => { - const a = { update: { text: '中文🙂' } }; - const b = { update: { text: 'second' } }; - const bytes = Buffer.concat([encodeConnectJson(a), encodeConnectJson(b)]); - const decoder = new ConnectJsonDecoder(); - const messages = []; - for (let i = 0; i < bytes.length; i += 3) messages.push(...decoder.push(bytes.subarray(i, i + 3))); - decoder.finish(); - assert.deepEqual(messages.map(m => m.value), [a, b]); - const end = encodeConnectJson({}); end[0] = 2; - assert.equal(decoder.push(end)[0].end, true); - assert.throws(() => decoder.push(encodeConnectJson(a)), /data_after_end/); -}); - -test('Connect decoder rejects oversized, compressed, malformed and truncated frames', () => { - const huge = Buffer.from([0, 0, 0, 1, 0]); - assert.throws(() => new ConnectJsonDecoder(100).push(huge), /frame_too_large/); - const compressed = encodeConnectJson({}); compressed[0] = 1; - assert.throws(() => new ConnectJsonDecoder().push(compressed), /unsupported_frame_flags/); - assert.throws(() => new ConnectJsonDecoder().push(Buffer.from([0, 0, 0, 0, 1, 120])), /invalid_frame_json/); - const decoder = new ConnectJsonDecoder(); decoder.push(Buffer.from([0, 0])); - assert.throws(() => decoder.finish(), /truncated_frame/); -}); - -test('history, delayed rehydration and status-only notifications never become live output', () => { - const { observation: o, records } = observer(); - o.accept({ update: { conversationId: ID, status: 'IDLE' } }, event(0)); - assert.equal(o.initialized, false); - o.accept(update([9], [model({ response: 'old response' }, true)], 10), event(1)); - o.accept(update([4], [model({ response: 'late history' }, true)], 10), event(2)); - assert.equal(o.contentEvents, 0); - assert.equal(o.recent.length, 0); - assert.deepEqual(records.map(r => r.kind), ['baseline']); -}); - -test('tool arguments, thinking and text are counted independently; receive batches are not tokens', () => { - const { observation: o, records } = observer(); - o.accept(update([], [], 10), event(0)); - o.accept(update([10], [model()], 11), event(10)); - o.accept(update([10], [model({ thinking: 'hidden-secret', response: '中', toolCalls: [{ argumentsJson: '{', name: 'secret-tool' }] })], 11), event(20, 2)); - o.accept(update([10], [model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"' }] })], 11), event(20, 2)); - const full = model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"argument-secret"}' }] }, true); - o.accept(update([10], [full], 11), event(120, 3)); - o.accept(update([10], [full], 11), event(300, 4)); - o.accept(update([], [], 11, { generatorMetadatasUpdate: { generatorMetadatas: [{ stepIndices: [10], chatModel: { - usage: { outputTokens: '400', thinkingOutputTokens: '50', responseHeader: { authorization: 'credential-secret' } }, - timeToFirstToken: '7.999s', streamingDuration: '0.001s', systemPrompt: 'prompt-secret', - } }] } }), event(400, 5)); - const r = o.recent[0]; - assert.equal(r.contentEvents, 3); - assert.equal(r.contentReceiveBatches, 2); - assert.equal(r.toolArgumentEvents, 3); - assert.equal(r.observedSpanMs, 100); - assert.equal(r.channels.text.bytes, 6); - assert.equal(r.channels.text.utf16Units, 2); - assert.equal(r.usage.outputTokens, 400); - assert.equal(r.nativeStreamSec, 0.001); - assert.equal(r.partialCapture, false); - const serialized = JSON.stringify([records, r]); - for (const secret of ['hidden-secret', 'argument-secret', 'secret-tool', 'credential-secret', 'prompt-secret', '中文']) assert.ok(!serialized.includes(secret)); - assert.ok(!/tokPerSec|tps|firstTokenMs/i.test(serialized)); -}); - -test('same-batch delivery is not reported as a timed stream, even with several updates', () => { - const { observation: o } = observer(); - o.accept(update([], [], 0), event(0)); - o.accept(update([0], [model({ response: 'a' })], 1), event(5, 1)); - o.accept(update([0], [model({ response: 'ab' }, true)], 1), event(5, 1)); - assert.equal(o.recent[0].observation, 'single_receive_batch'); - assert.equal(o.recent[0].observedSpanMs, 0); -}); - -test('rewrites, shrinking output and tool-only updates are retained as revisions', () => { - const { observation: o, records } = observer(); - o.accept(update([], [], 0), event(0)); - o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'abcd' }] })], 1), event(10)); - o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wxyz' }] })], 1), event(20)); - o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wx' }] }, true)], 1), event(30)); - assert.equal(o.recent[0].revisions, 2); - assert.equal(o.recent[0].toolArgumentEvents, 3); - assert.equal(records.at(-1).changes.toolArguments.deltaBytes, -2); - assert.equal(records.at(-1).changes.toolArguments.appendOnly, false); -}); - -test('joining during generation marks partial capture and excludes initial content from updates', () => { - const { observation: o } = observer(); - o.accept(update([2], [model({ response: 'already there' })], 3), event(10)); - o.accept(update([2], [model({ response: 'already there plus more' }, true)], 3), event(20)); - assert.equal(o.recent[0].partialCapture, true); - assert.equal(o.recent[0].contentEvents, 1); - assert.equal(o.recent[0].observation, 'partial_capture'); -}); - -test('missing or earlier creation time never claims a complete observation', () => { - const { observation: o } = observer(); - o.accept(update([], [], 0), event(0)); - o.accept(update([0], [model({ response: 'arrived' }, true, { metadata: { finishedGeneratingAt: FINISHED } })], 1), event(20)); - assert.equal(o.recent[0].partialCapture, true); - assert.throws(() => o.accept(update([], [model()], 2), event(25)), /invalid_step_indices/); -}); - -const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); -async function until(check) { - for (let i = 0; i < 100; i++) { if (check()) return; await sleep(10); } - assert.fail('timed out'); -} -function temp(t) { - const dir = mkdtempSync(join(tmpdir(), 'usage-monitor-diag-test-')); - t.after(() => { - const absolute = resolve(dir); - assert.equal(dirname(absolute), resolve(tmpdir())); - assert.ok(absolute.startsWith(join(resolve(tmpdir()), 'usage-monitor-diag-test-'))); - rmSync(absolute, { recursive: true, force: true }); - }); - return dir; -} - -test('collector only subscribes to read APIs, persists counters and stops without touching billing', async t => { - const dir = temp(t); - const calls = []; - let streamController; - const fetchImpl = async (url, options) => { - calls.push({ url, options }); - if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: { stepCount: 0, lastModifiedTime: CREATED } } })); - assert.ok(url.endsWith('StreamAgentStateUpdates')); - const request = new ConnectJsonDecoder().push(options.body)[0].value; - assert.equal(request.trajectoryVerbosity, 'CLIENT_TRAJECTORY_VERBOSITY_FULL'); - const stream = new ReadableStream({ start(c) { - streamController = c; - c.enqueue(encodeConnectJson(update([], [], 0))); - options.signal.addEventListener('abort', () => c.error(new Error('aborted')), { once: true }); - } }); - return new Response(stream, { headers: { 'Content-Type': 'application/connect+json' } }); - }; - const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'secret-csrf', fetchImpl, pollMs: 60000 }); - t.after(() => d.stop()); - assert.equal(d.status().enabled, false); - d.configure({ enabled: true }); - await until(() => d.status().phase === 'collecting'); - streamController.enqueue(encodeConnectJson(update([0], [model({ toolCalls: [{ argumentsJson: 'private-arguments' }] }, true)], 1))); - await until(() => d.status().contentEvents === 1); - assert.equal(d.status().affectsTps, false); - d.configure({ enabled: false }); - await sleep(10); - assert.equal(d.status().phase, 'disabled'); - assert.equal(d.current, null); - const log = readFileSync(join(dir, 'stream-diagnostics', 'events.jsonl'), 'utf8'); - assert.ok(!log.includes('secret-csrf')); - assert.ok(!log.includes('private-arguments')); - assert.ok(log.includes('step_update')); - assert.deepEqual(readdirSync(dir).sort(), ['stream-diagnostics', 'stream-diagnostics-config.json']); - assert.equal(calls.length, 2); -}); - -test('failed subscriptions back off and never expose the server error body', async t => { - const dir = temp(t); - let calls = 0; - const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'csrf', pollMs: 10, retryMs: 5000, - fetchImpl: async url => { - calls++; - if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: {} } })); - return new Response('private server error with credentials', { status: 403 }); - } }); - t.after(() => d.stop()); - d.configure({ enabled: true }); - await until(() => d.status().error === 'stream_http_403'); - await sleep(40); - assert.equal(calls, 2); - assert.ok(!JSON.stringify(d.status()).includes('private')); -}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs new file mode 100644 index 0000000..793632a --- /dev/null +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -0,0 +1,1200 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import vm from 'node:vm'; +import { + createWindowBridgeController, + isAllowedBridgeOrigin, + isAntigravityMainPageTarget, + parseDevToolsPortFile, + resolveDevToolsPortCandidates, +} from '../backend/window-bridge.mjs'; +import { computeCapsuleLayoutMode } from '../src/components/layout/WindowOverlayShell.js'; +import { backendHarness } from './backend-harness.mjs'; + +test('DevToolsActivePort parsing, cross-platform discovery, and strict target/origin filtering', () => { + assert.equal(parseDevToolsPortFile('9222\n/devtools/browser/abc-123\n'), 9222); + assert.equal(parseDevToolsPortFile('54321\r\n/devtools/browser/win'), 54321); + assert.equal(parseDevToolsPortFile('0\n/devtools'), null); + assert.equal(parseDevToolsPortFile('70000\n/devtools'), null); + assert.equal(parseDevToolsPortFile('not-a-port'), null); + + const explicit = resolveDevToolsPortCandidates( + { ANTIGRAVITY_DEVTOOLS_PORT_FILE: '/tmp/custom-port' }, + 'win32', + 'C:\\Users\\Dev' + ); + assert.deepEqual(explicit, ['/tmp/custom-port']); + + const winPaths = resolveDevToolsPortCandidates( + { APPDATA: 'C:\\Roaming', LOCALAPPDATA: 'C:\\Local' }, + 'win32', + 'C:\\Users\\Dev' + ); + assert.equal(winPaths.length, 2); + assert.ok(winPaths[0].includes('Roaming')); + assert.ok(winPaths[1].includes('Local')); + + const macPaths = resolveDevToolsPortCandidates({}, 'darwin', '/Users/dev'); + assert.equal(macPaths[0], path.join('/Users/dev', 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort')); + + assert.equal( + isAntigravityMainPageTarget({ + type: 'page', + url: 'https://127.0.0.1:51234/c/12345678-1234-1234-1234-123456789abc', + webSocketDebuggerUrl: 'ws://127.0.0.1:9222/devtools/page/main1', + }), + true + ); + // Reject auxiliary webviews, non-HTTPS pages, and non-loopback debugger sockets + assert.equal( + isAntigravityMainPageTarget({ + type: 'iframe', + url: 'vscode-webview://panel/index.html', + webSocketDebuggerUrl: 'ws://127.0.0.1:9222/devtools/page/wv1', + }), + false + ); + assert.equal( + isAntigravityMainPageTarget({ + type: 'page', + url: 'http://127.0.0.1:51234/', + webSocketDebuggerUrl: 'ws://127.0.0.1:9222/devtools/page/http1', + }), + false + ); + assert.equal( + isAntigravityMainPageTarget({ + type: 'page', + url: 'https://127.0.0.1:51234/', + webSocketDebuggerUrl: 'ws://evil.example.com:9222/devtools/page/remote', + }), + false + ); + + assert.equal(isAllowedBridgeOrigin('https://127.0.0.1:58123'), true); + assert.equal(isAllowedBridgeOrigin('https://localhost:58123'), true); + assert.equal(isAllowedBridgeOrigin('http://127.0.0.1:58123'), false); + assert.equal(isAllowedBridgeOrigin('https://example.com:58123'), false); + assert.equal(isAllowedBridgeOrigin('vscode-webview://panel'), false); +}); + +test('Loopback HTTP bridge enforces Origin, Private Network CORS, token auth, and body limits', async () => { + const receivedCalls = []; + const controller = createWindowBridgeController({ + handleApiRequest: async (pathname, method, data) => { + receivedCalls.push({ pathname, method, data }); + return { + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ok: true, echoPath: pathname, echoData: data }), + }; + }, + readAssetFn: async () => '', + getSettingsFn: () => ({ enableWindowOverlay: true }), + getBundleVersionFn: () => 'v1', + }); + + try { + const { port, token } = await controller.ensureBridgeServer(); + assert.ok(port > 0); + assert.equal(token.length, 64); + + const validOrigin = 'https://127.0.0.1:60123'; + + // 1. Disallowed origin -> 403 + const badOriginRes = await fetch(`http://127.0.0.1:${port}/api/telemetry`, { + headers: { Origin: 'https://evil.example', 'X-Usage-Monitor-Token': token }, + }); + assert.equal(badOriginRes.status, 403); + + // 2. OPTIONS preflight -> 204 with Private Network header (including Chromium cross-scheme Sec-Fetch-Site: cross-site) + const rawCrossSchemePreflight = await new Promise((resolve, reject) => { + const req = http.request( + { + hostname: '127.0.0.1', + port, + path: '/api/telemetry', + method: 'OPTIONS', + headers: { + Origin: validOrigin, + 'Sec-Fetch-Site': 'cross-site', + 'Access-Control-Request-Method': 'GET', + 'Access-Control-Request-Headers': 'x-usage-monitor-token', + }, + }, + (res) => { + res.resume(); + resolve({ status: res.statusCode, headers: res.headers }); + } + ); + req.on('error', reject); + req.end(); + }); + assert.equal(rawCrossSchemePreflight.status, 204); + assert.equal(rawCrossSchemePreflight.headers['access-control-allow-origin'], validOrigin); + assert.equal(rawCrossSchemePreflight.headers['access-control-allow-private-network'], 'true'); + + const rawCrossSchemeGetStatus = await new Promise((resolve, reject) => { + const req = http.request( + { + hostname: '127.0.0.1', + port, + path: '/api/telemetry?conversationId=conv-sec&range=today', + method: 'GET', + headers: { + Origin: validOrigin, + 'Sec-Fetch-Site': 'cross-site', + 'X-Usage-Monitor-Token': token, + }, + }, + (res) => { + res.resume(); + resolve(res.statusCode); + } + ); + req.on('error', reject); + req.end(); + }); + assert.equal(rawCrossSchemeGetStatus, 200); + + // 3. Invalid token -> 403 + const badTokenRes = await fetch(`http://127.0.0.1:${port}/api/telemetry`, { + headers: { Origin: validOrigin, 'X-Usage-Monitor-Token': 'wrong-token' }, + }); + assert.equal(badTokenRes.status, 403); + + // 4. Valid GET /api/telemetry -> 200 + const okGetRes = await fetch( + `http://127.0.0.1:${port}/api/telemetry?conversationId=conv-1&range=today`, + { + headers: { Origin: validOrigin, 'X-Usage-Monitor-Token': token }, + } + ); + assert.equal(okGetRes.status, 200); + const getBody = await okGetRes.json(); + assert.equal(getBody.ok, true); + assert.equal(getBody.echoData.conversationId, 'conv-1'); + assert.equal(getBody.echoData.range, 'today'); + + // 5. Valid POST /api/settings -> 200 + const okPostRes = await fetch(`http://127.0.0.1:${port}/api/settings`, { + method: 'POST', + headers: { + Origin: validOrigin, + 'Content-Type': 'application/json', + 'X-Usage-Monitor-Token': token, + }, + body: JSON.stringify({ enableWindowOverlay: false }), + }); + assert.equal(okPostRes.status, 200); + const postBody = await okPostRes.json(); + assert.equal(postBody.echoData.enableWindowOverlay, false); + assert.equal(receivedCalls.length, 3); + + // 6. Oversized POST body -> 413 + const hugePayload = JSON.stringify({ pad: 'x'.repeat(70 * 1024) }); + const hugeRes = await fetch(`http://127.0.0.1:${port}/api/settings`, { + method: 'POST', + headers: { + Origin: validOrigin, + 'Content-Type': 'application/json', + 'X-Usage-Monitor-Token': token, + }, + body: hugePayload, + }).catch(() => ({ status: 413 })); + assert.equal(hugeRes.status, 413); + } finally { + await controller.stop(); + } +}); + +test('CDP multi-window sync injects, skips healthy windows, hot-upgrades on version bump, and cleans up on disable', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-wm-cdp-test-')); + const portFile = path.join(tmpDir, 'DevToolsActivePort'); + + // Simulated VM contexts for two open Antigravity windows + const windowContexts = new Map(); + for (const id of ['win1', 'win2']) { + const winObj = {}; + winObj.window = winObj; + winObj.globalThis = winObj; + windowContexts.set(id, vm.createContext(winObj)); + } + + let injectEvalCount = 0; + + class MockCdpWebSocket { + constructor(url) { + this.url = url; + this.targetId = url.split('/').pop(); + this.listeners = new Map(); + queueMicrotask(() => this._emit('open', {})); + } + addEventListener(type, fn) { + if (!this.listeners.has(type)) this.listeners.set(type, []); + this.listeners.get(type).push(fn); + } + send(raw) { + const msg = JSON.parse(raw); + if (msg.method === 'Runtime.evaluate') { + const expr = msg.params.expression; + if (expr.includes('__AGUsageMonitorBridge =')) { + injectEvalCount += 1; + } + const ctx = windowContexts.get(this.targetId); + const value = vm.runInContext(expr, ctx); + queueMicrotask(() => + this._emit('message', { + data: JSON.stringify({ id: msg.id, result: { result: { value } } }), + }) + ); + } + } + close() {} + _emit(type, ev) { + for (const fn of this.listeners.get(type) || []) fn(ev); + } + } + + const cdpHttpServer = http.createServer((req, res) => { + if (req.url === '/json/list') { + const cdpPort = cdpHttpServer.address().port; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify([ + { + type: 'page', + url: 'https://127.0.0.1:61001/c/11111111-1111-1111-1111-111111111111', + webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win1`, + }, + { + type: 'page', + url: 'https://127.0.0.1:61002/c/22222222-2222-2222-2222-222222222222', + webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win2`, + }, + { + type: 'iframe', + url: 'vscode-webview://aux-pane/index.html', + webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/ignored`, + }, + ]) + ); + return; + } + res.writeHead(404); + res.end(); + }); + + await new Promise((resolve) => cdpHttpServer.listen(0, '127.0.0.1', resolve)); + fs.writeFileSync(portFile, `${cdpHttpServer.address().port}\n/devtools/browser/mock`, 'utf8'); + + let overlayEnabled = true; + let currentVer = 'bundle-v1'; + + const mockAppJs = ` + (() => { + window.__AGUsageMonitorOverlay?.dispose?.(); + const br = window.__AGUsageMonitorBridge; + let alive = true; + window.__AGUsageMonitorOverlay = { + bundleVersion: br.bundleVersion, + ensureAlive: () => alive, + dispose: () => { alive = false; }, + }; + })(); + `; + + const controller = createWindowBridgeController({ + handleApiRequest: async () => ({ status: 200, body: '{}' }), + readAssetFn: async (rel) => (rel === 'styles.css' ? ':host{}' : mockAppJs), + getSettingsFn: () => ({ enableWindowOverlay: overlayEnabled }), + getBundleVersionFn: () => currentVer, + env: { ANTIGRAVITY_DEVTOOLS_PORT_FILE: portFile }, + WebSocketImpl: MockCdpWebSocket, + }); + + try { + // 1. Initial sync mounts onto both main windows and ignores the webview + const first = await controller.syncAllWindows(); + assert.equal(first.ok, true); + assert.equal(first.targets, 2); + assert.equal(first.injected, 2); + assert.equal(first.aliveCount, 2); + assert.equal(injectEvalCount, 2); + + // 2. Subsequent poll sees matching bundleVersion & port -> 0 re-injections + const second = await controller.syncAllWindows(); + assert.equal(second.injected, 0); + assert.equal(second.aliveCount, 2); + assert.equal(injectEvalCount, 2); + + // 3. Hot bundle update triggers seamless re-injection on both windows + currentVer = 'bundle-v2'; + const upgraded = await controller.syncAllWindows(); + assert.equal(upgraded.injected, 2); + assert.equal(upgraded.aliveCount, 2); + assert.equal(windowContexts.get('win1').__AGUsageMonitorOverlay.bundleVersion, 'bundle-v2'); + assert.equal(windowContexts.get('win2').__AGUsageMonitorOverlay.bundleVersion, 'bundle-v2'); + + // 4. Disabling enableWindowOverlay disposes and removes globals from all windows + overlayEnabled = false; + const disabled = await controller.notifySettingChanged(false); + assert.equal(disabled.enabled, false); + assert.equal(disabled.removed, 2); + assert.equal(windowContexts.get('win1').__AGUsageMonitorOverlay, undefined); + assert.equal(windowContexts.get('win1').__AGUsageMonitorBridge, undefined); + } finally { + await controller.stop(); + await new Promise((resolve) => cdpHttpServer.close(resolve)); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test('Capsule 4-stage responsive hysteresis and backend settings default/override', async () => { + // Hysteresis stability check for dual-capsule topbar layout (multiBtn + capsuleBtn) + let mode = computeCapsuleLayoutMode(300, 'wide'); + assert.equal(mode, 'wide'); + mode = computeCapsuleLayoutMode(240, mode); + assert.equal(mode, 'compact'); + // At 265px (< 272px restore threshold), stays compact instead of flickering back to wide + mode = computeCapsuleLayoutMode(265, mode); + assert.equal(mode, 'compact'); + mode = computeCapsuleLayoutMode(280, mode); + assert.equal(mode, 'wide'); + mode = computeCapsuleLayoutMode(150, mode); + assert.equal(mode, 'minimal'); + mode = computeCapsuleLayoutMode(70, mode); + assert.equal(mode, 'ring-only'); + mode = computeCapsuleLayoutMode(85, mode); + assert.equal(mode, 'ring-only'); + mode = computeCapsuleLayoutMode(96, mode); + assert.equal(mode, 'minimal'); + + // Single-capsule mode (showMulti: false) grants ~76px extra breathing room before collapsing + assert.equal(computeCapsuleLayoutMode(200, 'wide', { showMulti: false }), 'wide'); + assert.equal(computeCapsuleLayoutMode(150, 'wide', { showMulti: false }), 'compact'); + + // Backend harness verifies enableWindowOverlay, showTopbarMultiSession, and topbarCapsuleSlots defaults & normalization + const defaultEnv = backendHarness({ settings: {} }); + const defaultPayload = await defaultEnv.buildTelemetryPayloadInternal('', false, {}); + assert.equal(defaultPayload.settings.enableWindowOverlay, true); + assert.equal(defaultPayload.settings.showTopbarMultiSession, true); + assert.deepEqual(Array.from(defaultPayload.settings.topbarCapsuleSlots), [ + 'context', + 'tps', + 'quota_auto', + ]); + + const disabledEnv = backendHarness({ + settings: { + enableWindowOverlay: false, + showTopbarMultiSession: false, + topbarCapsuleSlots: ['gemini_5h', 'ttft', 'claude_weekly'], + }, + }); + const disabledPayload = await disabledEnv.buildTelemetryPayloadInternal('', false, {}); + assert.equal(disabledPayload.settings.enableWindowOverlay, false); + assert.equal(disabledPayload.settings.showTopbarMultiSession, false); + assert.deepEqual(Array.from(disabledPayload.settings.topbarCapsuleSlots), [ + 'gemini_5h', + 'ttft', + 'claude_weekly', + ]); + + const allNoneEnv = backendHarness({ + settings: { topbarCapsuleSlots: ['none', 'none', 'none'] }, + }); + const allNonePayload = await allNoneEnv.buildTelemetryPayloadInternal('', false, {}); + assert.deepEqual(Array.from(allNonePayload.settings.topbarCapsuleSlots), [ + 'context', + 'none', + 'none', + ]); +}); + +test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, protects host reload, and supports composedPath()', async () => { + const appJsPath = new URL('../app.js', import.meta.url); + const stylesCssPath = new URL('../styles.css', import.meta.url); + const appJs = fs.readFileSync(appJsPath, 'utf8'); + const stylesCss = fs.readFileSync(stylesCssPath, 'utf8'); + + // Minimal DOM mock supporting ShadowRoot, querySelector, attributes, classes, and composedPath + class MockNode { + constructor(tag = 'div') { + this.tagName = String(tag).toUpperCase(); + this.id = ''; + this.className = ''; + this.textContent = ''; + this.style = { + _vars: new Map(), + setProperty(k, v) { this._vars.set(k, String(v)); }, + getPropertyValue(k) { return this._vars.get(k) || ''; }, + }; + this.dataset = {}; + this.attributes = new Map(); + this.children = []; + this.parentNode = null; + this.shadowRoot = null; + this._listeners = new Map(); + const self = this; + this.classList = { + _set() { + return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); + }, + add(...tokens) { + const s = this._set(); + for (const t of tokens) if (t) s.add(t); + self.className = Array.from(s).join(' '); + }, + contains(tok) { + return this._set().has(tok); + }, + toggle(tok, force) { + const s = this._set(); + const should = force === undefined ? !s.has(tok) : Boolean(force); + if (should) s.add(tok); + else s.delete(tok); + self.className = Array.from(s).join(' '); + }, + }; + } + get parentElement() { return this.parentNode; } + get firstChild() { return this.children[0] || null; } + get firstElementChild() { return this.children[0] || null; } + get lastElementChild() { return this.children[this.children.length - 1] || null; } + get isConnected() { + let cur = this; + while (cur) { + if (cur.isDocumentRoot) return true; + cur = cur.parentNode || cur.host || null; + } + return false; + } + setAttribute(k, v) { + const s = String(v); + this.attributes.set(k, s); + if (k === 'id') this.id = s; + if (k === 'class') this.className = s; + } + getAttribute(k) { return this.attributes.has(k) ? this.attributes.get(k) : null; } + hasAttribute(k) { return this.attributes.has(k); } + removeAttribute(k) { this.attributes.delete(k); } + appendChild(child) { + if (child.parentNode) child.parentNode.removeChild(child); + child.parentNode = this; + this.children.push(child); + return child; + } + insertBefore(node, refNode) { + if (!refNode) return this.appendChild(node); + if (node.parentNode) node.parentNode.removeChild(node); + const idx = this.children.indexOf(refNode); + node.parentNode = this; + if (idx < 0) this.children.push(node); + else this.children.splice(idx, 0, node); + return node; + } + removeChild(child) { + const idx = this.children.indexOf(child); + if (idx >= 0) { + this.children.splice(idx, 1); + child.parentNode = null; + } + return child; + } + remove() { + if (this.parentNode) this.parentNode.removeChild(this); + } + attachShadow() { + const sr = new MockNode('#shadow-root'); + sr.host = this; + this.shadowRoot = sr; + return sr; + } + contains(other) { + let cur = other; + while (cur) { + if (cur === this) return true; + cur = cur.parentNode; + } + return false; + } + addEventListener(type, fn) { + if (!this._listeners.has(type)) this._listeners.set(type, []); + this._listeners.get(type).push(fn); + } + removeEventListener(type, fn) { + const arr = this._listeners.get(type); + if (!arr) return; + const idx = arr.indexOf(fn); + if (idx >= 0) arr.splice(idx, 1); + } + dispatchEvent(ev) { + for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); + } + getBoundingClientRect() { + return { left: 900, right: 1080, top: 6, bottom: 32, width: 180, height: 26 }; + } + querySelector(sel) { + if (sel === ':scope > div.shrink-0') { + return this.children.find((c) => c.classList.contains('shrink-0')) || null; + } + return this._find((n) => { + if (sel === '[class*="@container/titlebar"]') { + return String(n.className || '').includes('@container/titlebar'); + } + if (sel.startsWith('.')) { + return n.classList.contains(sel.slice(1)); + } + return false; + }); + } + querySelectorAll(sel) { + const s = String(sel || '').trim(); + if (!s || s.includes(',')) return []; + if (s.includes(' ')) { + const [first, ...rest] = s.split(/\s+/); + const roots = this.querySelectorAll(first); + const out = []; + for (const r of roots) { + for (const item of r.querySelectorAll(rest.join(' '))) { + if (!out.includes(item)) out.push(item); + } + } + return out; + } + if (!s.startsWith('.')) return []; + const cls = s.slice(1); + const out = []; + const walk = (node) => { + for (const c of node.children) { + if (c.classList.contains(cls)) out.push(c); + walk(c); + } + }; + walk(this); + return out; + } + _find(pred) { + for (const c of this.children) { + if (pred(c)) return c; + const hit = c._find(pred); + if (hit) return hit; + } + return null; + } + } + + const docRoot = new MockNode('html'); + docRoot.isDocumentRoot = true; + const body = new MockNode('body'); + docRoot.appendChild(body); + + // Build simulated Antigravity titlebar + const titlebar = new MockNode('div'); + titlebar.className = 'flex items-center @container/titlebar'; + const titleLeft = new MockNode('div'); + titleLeft.textContent = 'Chat Title'; + const titleRight = new MockNode('div'); + titleRight.className = 'shrink-0 flex items-center'; + const nativeBtn = new MockNode('button'); + titleRight.appendChild(nativeBtn); + titlebar.appendChild(titleLeft); + titlebar.appendChild(titleRight); + body.appendChild(titlebar); + + let reloadCalled = false; + let currentBundleVer = 'ver-100'; + const fetchedUrls = []; + const fetchedHeaders = []; + + const docListeners = new Map(); + const winListeners = new Map(); + + const mockDocument = { + readyState: 'complete', + hidden: false, + documentElement: docRoot, + body, + createElement: (tag) => new MockNode(tag), + createElementNS: (_ns, tag) => new MockNode(tag), + createTextNode: (txt) => { + const t = new MockNode('#text'); + t.textContent = String(txt); + return t; + }, + getElementById: (id) => docRoot._find((n) => n.id === id), + querySelector: (sel) => docRoot.querySelector(sel), + querySelectorAll: () => [], + addEventListener(type, fn) { + if (!docListeners.has(type)) docListeners.set(type, []); + docListeners.get(type).push(fn); + }, + removeEventListener(type, fn) { + const arr = docListeners.get(type); + if (!arr) return; + const i = arr.indexOf(fn); + if (i >= 0) arr.splice(i, 1); + }, + }; + + const mockLocation = { + pathname: '/c/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb', + reload() { + reloadCalled = true; + }, + }; + + const mockSettings = { + weeklyLimitMode: 'official', + weeklyTokenBudget: 150000000, + weeklyCostBudget: 100, + showUpstreamModel: false, + autoUpdatePlugin: false, + enableWindowOverlay: true, + showTopbarMultiSession: true, + topbarCapsuleSlots: ['context', 'tps', 'quota_auto'], + }; + + const mockWindow = { + innerWidth: 1440, + innerHeight: 900, + location: mockLocation, + document: mockDocument, + __AGUsageMonitorBridge: { + port: 49152, + token: 'secret-bridge-token-123', + bundleVersion: 'ver-100', + stylesCss, + }, + addEventListener(type, fn) { + if (!winListeners.has(type)) winListeners.set(type, []); + winListeners.get(type).push(fn); + }, + removeEventListener(type, fn) { + const arr = winListeners.get(type); + if (!arr) return; + const i = arr.indexOf(fn); + if (i >= 0) arr.splice(i, 1); + }, + getComputedStyle: () => ({ paddingRight: '8px', getPropertyValue: () => '' }), + fetch: async (url, opts = {}) => { + const urlStr = String(url); + fetchedUrls.push(urlStr); + fetchedHeaders.push(opts.headers || {}); + if (urlStr.includes('/api/settings') && String(opts.method || '').toUpperCase() === 'POST') { + const patch = opts.body ? JSON.parse(opts.body) : {}; + Object.assign(mockSettings, patch); + return { + ok: true, + status: 200, + json: async () => ({ ...mockSettings }), + }; + } + return { + ok: true, + status: 200, + json: async () => ({ + uiBundleVersion: currentBundleVer, + settings: { ...mockSettings }, + cloudStatus: { updateAvailable: true, currentPluginVersion: '1.4.2', latestPluginVersion: '1.5.0' }, + account: { tierName: 'Google AI Ultra', planName: 'Pro', totalConversations: 5 }, + runningConversations: [ + { + cascadeId: 'bbbbbbbb-2222-3333-4444-cccccccccccc', + title: 'Background Security Audit', + isCurrentSelected: false, + isMainRunning: true, + isRunning: true, + stepCount: 24, + totalStepCount: 38, + latestTokPerSec: 64.2, + contextUsedPct: 48.4, + mainActivity: { + phase: 'tool', + label: '执行命令', + detail: 'rg -n ProtectedURLFilter', + stepProgress: '1/2', + startedAtMs: Date.now() - 12000, + signature: 'tool:rg:1', + }, + subagentCount: 1, + runningSubagentCount: 1, + subagents: [ + { + cascadeId: 'bbbbbbbb-2222-3333-4444-cccccccccccc:sub1', + index: 1, + badgeText: '子1', + shortLabel: '子代理 #1', + role: 'Auth Researcher', + isRunning: true, + stepCount: 14, + lastModifiedMs: Date.now() - 8000, + liveActivity: { + phase: 'thinking', + label: '读取文件', + detail: 'MastLoginFilter.java', + stepProgress: '', + startedAtMs: Date.now() - 8000, + signature: 'sub1:read', + }, + }, + ], + }, + { + cascadeId: 'eeeeeeee-5555-6666-7777-ffffffffffff', + title: 'Solo Refactor Task', + isCurrentSelected: false, + isMainRunning: true, + isRunning: true, + stepCount: 9, + totalStepCount: 9, + latestTokPerSec: 72.1, + contextUsedPct: 21.0, + mainActivity: { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: Date.now() - 4000, + signature: 'solo:think', + }, + subagentCount: 0, + runningSubagentCount: 0, + subagents: [], + }, + ], + conversations: [ + { + cascadeId: 'bbbbbbbb-2222-3333-4444-cccccccccccc', + title: 'Background Security Audit', + stepCount: 24, + subagentCount: 1, + runningSubagentCount: 1, + totalStepCount: 38, + isRunning: true, + contextUsedPct: 48.4, + sessionCostUsd: 1.85, + lastModifiedMs: Date.now() - 2000, + }, + { + cascadeId: 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb', + title: 'Dual Mode Session', + stepCount: 6, + subagentCount: 0, + totalStepCount: 6, + isRunning: false, + contextUsedPct: 50, + sessionCostUsd: 7.3, + lastModifiedMs: Date.now() - 180000, + }, + ], + activeConversation: { + cascadeId: 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb', + title: 'Dual Mode Session', + isRunning: false, + stepCount: 6, + latestTokPerSec: 92.4, + latestTtftSec: 0.85, + avgTokPerSec: 88.2, + latestStepCostUsd: 0.04, + latestCacheHitPct: 98.7, + sessionCostUsd: 7.3, + activeModelShort: 'carbon-high', + context: { + totalTokens: 128000, + compactionLimitTokens: 256000, + limitTokens: 256000, + toolResultsTokens: 76000, + assistantTokens: 42000, + userRulesTokens: 10000, + }, + recentSteps: [], + }, + consumption: { + selectedRange: { key: 'today', label: '今天', startMs: 1, endMs: 2 }, + session: { totalTokens: 128000, costUsd: 0.42 }, + account: { totalTokens: 500000, costUsd: 1.5 }, + trendSeries: [], + monthlySeries: [], + }, + quotas: { + meta: { hasOfficialData: true }, + activePool: { family: 'Carbon', poolLabel: 'Carbon', remainingPct: 68, weeklyRemainingPct: 81 }, + pools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + remainingPct: 44, + weeklyRemainingPct: 26, + }, + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + remainingPct: 100, + weeklyRemainingPct: 91, + }, + ], + weekly: { remainingPct: 81 }, + }, + modelBreakdown: [], + }), + }; + }, + }; + mockWindow.window = mockWindow; + mockWindow.globalThis = mockWindow; + + const sandbox = vm.createContext({ + window: mockWindow, + globalThis: mockWindow, + document: mockDocument, + location: mockLocation, + navigator: {}, + URLSearchParams, + AbortController, + setTimeout, + clearTimeout, + setInterval, + clearInterval, + queueMicrotask, + fetch: mockWindow.fetch, + console, + }); + + vm.runInContext(appJs, sandbox); + await new Promise((r) => setTimeout(r, 40)); + + try { + const ov = mockWindow.__AGUsageMonitorOverlay; + assert.ok(ov, 'Overlay handle should be registered on window'); + assert.equal(ov.ensureAlive(), true); + + const capsuleHost = mockDocument.getElementById('ag-usage-monitor-capsule'); + const portalHost = mockDocument.getElementById('ag-usage-monitor-portal'); + assert.ok(capsuleHost, 'Capsule host mounted'); + assert.ok(portalHost, 'Portal host mounted'); + assert.equal(capsuleHost.getAttribute('data-dock'), 'flow'); + assert.equal(capsuleHost.parentNode, titleRight); + assert.equal(titleRight.firstChild, capsuleHost, 'Capsule inserted before native right buttons'); + + // Verify authenticated bridge call & automatic /c/ route tracking + assert.ok(fetchedUrls.length >= 1); + assert.ok(fetchedUrls[0].startsWith('http://127.0.0.1:49152/api/telemetry?')); + assert.ok(fetchedUrls[0].includes('conversationId=aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb')); + assert.equal(fetchedHeaders[0]['X-Usage-Monitor-Token'], 'secret-bridge-token-123'); + + // Verify dual topbar buttons: left multi-session button (.wm-multi-btn) before right telemetry capsule (.wm-capsule-btn) + const multiBtn = capsuleHost.shadowRoot.querySelector('.wm-multi-btn'); + const capsuleBtn = capsuleHost.shadowRoot.querySelector('.wm-capsule-btn'); + assert.ok(multiBtn, 'Left multi-session button mounted'); + assert.ok(capsuleBtn, 'Right telemetry capsule button mounted'); + assert.ok( + capsuleHost.shadowRoot.children.indexOf(multiBtn) < + capsuleHost.shadowRoot.children.indexOf(capsuleBtn), + 'Multi-session button sits immediately to the left of telemetry capsule' + ); + assert.equal(multiBtn.querySelector('.svg-icon'), null, 'Multi-session button has zero SVG clutter'); + assert.equal(multiBtn.classList.contains('is-running'), true); + const multiLabelEl = multiBtn.querySelector('.wm-multi-label'); + assert.equal(multiLabelEl.textContent, '2 运行 · 1 子'); + + // Verify capsule reactive text (50% context, 92.4 t/s without bolt SVG, 余 68%) + const ctxPctEl = capsuleHost.shadowRoot.querySelector('.wm-ctx-pct'); + const speedSegEl = capsuleHost.shadowRoot.querySelector('.wm-seg-speed'); + const quotaSegEl = capsuleHost.shadowRoot.querySelector('.wm-seg-quota'); + assert.equal(ctxPctEl.textContent, '50%'); + assert.equal(speedSegEl.children.length, 1, 'Speed segment has no lightning bolt SVG'); + assert.equal(speedSegEl.querySelector('.svg-icon'), null); + assert.ok(speedSegEl.children[0].textContent.includes('92.4 t/s')); + assert.equal(quotaSegEl.children[0].textContent, '余 68%'); + + // Verify hovering left multi-session button opens .wm-multi-panel with live tasks, subagents, and recent sessions + const multiPanelEl = portalHost.shadowRoot.querySelector('.wm-multi-panel'); + const hoverTipEl = portalHost.shadowRoot.querySelector('.wm-hover-tip'); + assert.ok(multiPanelEl, 'Multi-session floating panel mounted in portal shadow root'); + assert.equal(multiPanelEl.children.length, 3, 'Single-layer online sessions panel (header + empty state + running list)'); + + multiBtn.dispatchEvent({ type: 'mouseenter', clientX: 930, clientY: 18 }); + assert.equal(ov.isMultiOpen(), true); + assert.equal(ov.isMultiHoverOpen(), true); + assert.equal(multiPanelEl.hasAttribute('hidden'), false); + + // Stationary pointer inside multiBtn prevents synthetic mouseleave blink + multiBtn.dispatchEvent({ type: 'mouseleave', clientX: 930, clientY: 18 }); + await new Promise((r) => setTimeout(r, 110)); + assert.equal(ov.isMultiOpen(), true, 'Stationary pointer inside multi button prevents synthetic mouseleave blink'); + + const runningListEl = multiPanelEl.querySelector('.live-activity-list'); + assert.equal(runningListEl.children.length, 2, 'Both running session cards rendered'); + const liveTaskCard = runningListEl.children[0]; + const soloTaskCard = runningListEl.children[1]; + assert.equal(liveTaskCard.querySelector('.live-task-title').textContent, 'Background Security Audit'); + assert.equal(liveTaskCard.querySelector('.badge-main').hasAttribute('hidden'), false, 'Session with subagents shows 主 badge'); + assert.equal(liveTaskCard.querySelector('.live-activity-phase').textContent, '执行命令'); + assert.equal(liveTaskCard.querySelector('.live-sub-list').hasAttribute('hidden'), false, 'Active subagents auto-expanded'); + assert.equal(liveTaskCard.querySelector('.live-sub-role').textContent, 'Auth Researcher'); + assert.equal(soloTaskCard.querySelector('.live-task-title').textContent, 'Solo Refactor Task'); + assert.equal(soloTaskCard.querySelector('.badge-main').hasAttribute('hidden'), true, 'Session without subagents hides 主 badge'); + const liveDotSvg = liveTaskCard.querySelector('.live-activity-dot').children[0]; + assert.equal(liveDotSvg.attributes.get('width'), '11', 'Enlarged live activity SVG dot size is 11'); + assert.equal(liveDotSvg.children[0].attributes.get('r'), '5', 'Enlarged dot circle radius is 5'); + assert.match(stylesCss, /\.wm-multi-dot\s*\{\s*width:\s*8px;\s*height:\s*8px;/, 'Topbar multi-session dot enlarged to 8px'); + assert.equal(multiPanelEl.querySelector('.wm-recent-list'), null, 'Recent sessions list removed so panel shows online sessions only'); + assert.equal(multiPanelEl.querySelector('.panel'), null, 'Single-layer multi-session panel without nested .panel box'); + + // Verify hovering right capsule closes unpinned multi-session panel and opens rich 3-card hover overview HUD (.wm-hover-tip) + assert.ok(hoverTipEl, 'Hover overview HUD mounted in portal shadow root'); + assert.equal(hoverTipEl.children.length, 3, 'Hover HUD has 3 signature cards (matrix + context + quotas)'); + + capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 }); + assert.equal(ov.isMultiOpen(), false, 'Mutual exclusion closes unpinned multi-session panel'); + assert.equal(ov.isHoverOpen(), true); + assert.equal(hoverTipEl.hasAttribute('hidden'), false); + + // Transient mouseleave while pointer remains inside capsule rect (900..1080 x 6..32) must NOT close hover HUD + capsuleBtn.dispatchEvent({ type: 'mouseleave', clientX: 960, clientY: 18 }); + await new Promise((r) => setTimeout(r, 55)); + assert.equal(ov.isHoverOpen(), true, 'Stationary pointer inside capsule prevents synthetic mouseleave blink'); + + const hoverMatrix = hoverTipEl.querySelector('.telemetry-matrix'); + const hoverLegendGrid = hoverTipEl.querySelector('.ctx-legend-grid'); + const hoverQuotaPools = hoverTipEl.querySelector('.wm-hover-quota-pools'); + assert.equal(hoverMatrix.children.length, 4); + assert.equal(hoverMatrix.children[0].children[1].textContent, '92.4 tok/s'); + assert.equal(hoverMatrix.children[3].children[1].textContent, '$0.040'); + assert.equal(hoverLegendGrid.children.length, 10, 'All 10 context legend slots pre-reserved'); + const firstLegendSlotBefore = hoverLegendGrid.children[0]; + assert.equal(firstLegendSlotBefore.children[0].children[1].textContent, '工具结果'); + assert.equal(firstLegendSlotBefore.children[1].textContent, '76.0k'); + assert.equal(hoverQuotaPools.children.length, 2, 'Default Gemini & Claude/GPT quota pools pre-reserved'); + + // Verify clicking multi-session button pins open multi-session panel, and clicking capsule switches to 4-tab panel + multiBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(ov.isMultiPinnedOpen(), true); + assert.equal(ov.isHoverOpen(), false); + assert.equal(multiBtn.classList.contains('is-open'), true); + + ov.open(); + assert.equal(ov.isMultiOpen(), false); + assert.equal(ov.isHoverOpen(), false); + assert.equal(hoverTipEl.hasAttribute('hidden'), true); + assert.equal(ov.isOpen(), true); + const popoverEl = portalHost.shadowRoot.querySelector('.wm-popover-panel'); + assert.equal(popoverEl.hasAttribute('hidden'), false); + + // Verify Shadow DOM retargeted click inside CustomSelect does NOT close select or popover + const selectRoot = portalHost.shadowRoot.querySelector('.custom-select'); + const selectTrigger = selectRoot.querySelector('.select-trigger'); + selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(selectRoot.classList.contains('is-open'), true); + + // Simulate document capture-phase click retargeted to portalHost while composedPath includes selectRoot + for (const fn of docListeners.get('click') || []) { + fn({ + target: portalHost, + composedPath: () => [selectTrigger, selectRoot, popoverEl, portalHost.shadowRoot, portalHost, body, docRoot], + }); + } + assert.equal(selectRoot.classList.contains('is-open'), true, 'CustomSelect stays open via composedPath'); + selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} }); + + // Verify SettingsView: weekly budget UI removed; topbar multi-session switch & 3-slot customization work live + const pillTabs = popoverEl.querySelectorAll('.pill-tab'); + pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 15)); + + const allPanes = popoverEl.querySelectorAll('.view-pane'); + const settingsPane = allPanes[allPanes.length - 1]; + assert.equal(settingsPane.querySelectorAll('.number-input').length, 0, 'Obsolete weekly budget number inputs removed'); + const settingsSelects = settingsPane.querySelectorAll('.custom-select'); + assert.equal( + settingsSelects.length, + 6, + 'SettingsView renders 6 CustomSelect controls (mount, modelFormat, 3 topbar slots, autoUpdate)' + ); + const mountSelectEl = settingsSelects[0]; + const modelFormatSelectEl = settingsSelects[1]; + const slot0SelectEl = settingsSelects[2]; + const slot1SelectEl = settingsSelects[3]; + const slot2SelectEl = settingsSelects[4]; + + // Toggle windowMountSelect: dual -> sidebar -> dual + assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('顶部栏 + 侧边栏')); + mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + mountSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.enableWindowOverlay, false, 'enableWindowOverlay persisted as false'); + assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('仅侧边栏'), 'UI reflects sidebar mode'); + + mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + mountSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true'); + assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('顶部栏 + 侧边栏'), 'UI reflects dual mode'); + + // Toggle stepModelSelect: short -> upstream -> short + assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('精简代号')); + modelFormatSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + modelFormatSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.showUpstreamModel, true); + assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('原始模型 ID')); + + modelFormatSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + modelFormatSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.showUpstreamModel, false); + assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('精简代号')); + + // Toggle topbar multi-session switch: show -> hide -> show + const topbarSegBtns = settingsPane.querySelectorAll('.seg-btn'); + assert.equal(topbarSegBtns.length, 2, 'Topbar multi-session toggle has 显示 / 隐藏 buttons'); + topbarSegBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.showTopbarMultiSession, false); + assert.equal(multiBtn.hasAttribute('hidden'), true, 'Topbar multi-session button hidden immediately'); + assert.equal(capsuleHost.getAttribute('data-multi'), 'off'); + + topbarSegBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.showTopbarMultiSession, true); + assert.equal(multiBtn.hasAttribute('hidden'), false, 'Topbar multi-session button restored immediately'); + + // Customize 3 topbar capsule slots: [gemini_5h, ttft, cost], then swap order, test claude_weekly + none, then reset default + const capSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot'); + const capSeps = capsuleHost.shadowRoot.querySelectorAll('.wm-sep'); + assert.equal(capSlots.length, 3); + assert.equal(capSeps.length, 2); + + // Slot 0 -> Gemini 5h (option index 5) + slot0SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + slot0SelectEl.querySelectorAll('.select-option')[5].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h'); + assert.equal(capSlots[0].children.length, 1, 'Ring SVG detached cleanly when slot leaves context'); + assert.equal(capSlots[0].children[0].textContent, '余 44%'); + + // Slot 1 -> TTFT (option index 2) + slot1SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + slot1SelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); + assert.equal(capSlots[1].children[0].textContent, '0.85s'); + + // Slot 2 -> Cost (option index 3) + slot2SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + slot2SelectEl.querySelectorAll('.select-option')[3].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(capSlots[2].getAttribute('data-metric'), 'cost'); + assert.equal(capSlots[2].children[0].textContent, '$0.040'); + assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']); + + // Swap Slot 1 up (left) so order becomes ['ttft', 'gemini_5h', 'cost'] + const slotMoveBtns = settingsPane.querySelectorAll('.slot-move-btn'); + // Row 1 up button is index 2 ([row0Up, row0Down, row1Up, row1Down, row2Up, row2Down]) + slotMoveBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']); + assert.equal(capSlots[0].children[0].textContent, '0.85s'); + assert.equal(capSlots[1].children[0].textContent, '余 44%'); + + // Test hiding middle slot ('none', option index 9) and setting Slot 2 to Claude Weekly (option index 8) + slot1SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + slot1SelectEl.querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + slot2SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} }); + slot2SelectEl.querySelectorAll('.select-option')[8].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(capSlots[1].hasAttribute('hidden'), true, 'Middle slot hidden when set to none'); + assert.equal(capSeps[0].hasAttribute('hidden'), true, 'Separator before hidden middle slot collapses'); + assert.equal(capSeps[1].hasAttribute('hidden'), false, 'Single separator remains between Slot 0 and Slot 2'); + assert.equal(capSeps[1].getAttribute('data-sep-for-rank'), '2'); + assert.equal(capSlots[2].getAttribute('data-vis-rank'), '2'); + assert.equal(capSlots[2].children[0].textContent, '余 91%'); + + // Reset default restores ['context', 'tps', 'quota_auto'] with ring SVG re-attached on Slot 0 + const resetTopbarBtn = settingsPane.querySelector('.btn-ghost-sm'); + resetTopbarBtn.dispatchEvent({ type: 'click' }); + await new Promise((r) => setTimeout(r, 260)); + assert.deepEqual(mockSettings.topbarCapsuleSlots, ['context', 'tps', 'quota_auto']); + assert.equal(capSlots[0].getAttribute('data-metric'), 'context'); + assert.equal(capSlots[0].children.length, 2, 'Ring SVG re-attached on Slot 0'); + assert.equal(capSlots[0].querySelector('.wm-ctx-pct').textContent, '50%'); + + // Verify bundle version bump NEVER calls window.location.reload() in overlay mode + currentBundleVer = 'ver-200'; + mockLocation.pathname = '/c/cccccccc-4444-5555-6666-dddddddddddd'; + for (const fn of winListeners.get('popstate') || []) fn({}); + await new Promise((r) => setTimeout(r, 40)); + assert.equal(reloadCalled, false, 'Host window must never reload on bundle version change'); + assert.ok( + fetchedUrls.some((u) => u.includes('conversationId=cccccccc-4444-5555-6666-dddddddddddd')), + 'Navigated host route immediately tracked' + ); + // Verify fallback to CDP RPC relay when browser fetch fails (e.g. CSP connect-src or proxy block) + let fetchShouldFail = true; + const origFetch = mockWindow.fetch; + mockWindow.fetch = async (url, opts) => { + if (fetchShouldFail) { + throw new TypeError('Failed to fetch'); + } + return origFetch(url, opts); + }; + mockLocation.pathname = '/c/dddddddd-7777-8888-9999-eeeeeeeeeeee'; + for (const fn of winListeners.get('popstate') || []) fn({}); + await new Promise((r) => setTimeout(r, 15)); + assert.equal(mockWindow.__AGUsageMonitorBridge.transportMode, 'cdp'); + assert.equal(Array.isArray(mockWindow.__AGUsageMonitorBridge.rpcQueue), true); + assert.equal(mockWindow.__AGUsageMonitorBridge.rpcQueue.length, 1); + const queuedItem = mockWindow.__AGUsageMonitorBridge.rpcQueue.shift(); + const delivered = ov.deliverRpc([ + { + id: queuedItem.id, + ok: true, + status: 200, + data: { + uiBundleVersion: 'ver-200', + settings: { weeklyLimitMode: 'official', weeklyTokenBudget: 150000000, weeklyCostBudget: 100, enableWindowOverlay: true }, + activeConversation: { + cascadeId: 'dddddddd-7777-8888-9999-eeeeeeeeeeee', + title: 'CDP Relay Session', + isRunning: false, + stepCount: 8, + latestTokPerSec: 120.5, + context: { totalTokens: 64000, compactionLimitTokens: 256000, limitTokens: 256000 }, + recentSteps: [], + }, + consumption: { selectedRange: { key: 'today', label: '今天', startMs: 1, endMs: 2 }, session: {}, account: {}, trendSeries: [], monthlySeries: [] }, + quotas: null, + modelBreakdown: [], + }, + }, + ]); + assert.equal(delivered, 1); + await new Promise((r) => setTimeout(r, 20)); + assert.equal(ctxPctEl.textContent, '25%', 'CDP relay delivered live telemetry without HTTP'); + assert.equal(speedSegEl.children[0].textContent, '121 t/s'); + assert.equal(quotaSegEl.hasAttribute('hidden'), false, 'Quota slot stays pre-reserved even when quotas=null'); + assert.equal(quotaSegEl.children[0].textContent, '余 --%'); + assert.equal( + hoverLegendGrid.children[0], + firstLegendSlotBefore, + 'Hover legend updates strictly in-place without DOM node replacement or appendChild' + ); + + // Verify in-place bridge port rotation preserves exact DOM host nodes without remount + fetchShouldFail = false; + assert.equal(ov.updateBridge({ port: 51234, token: 'rotated-token-456' }), true); + assert.equal(mockWindow.__AGUsageMonitorBridge.port, 51234); + assert.equal(mockDocument.getElementById('ag-usage-monitor-capsule'), capsuleHost); + } finally { + mockWindow.__AGUsageMonitorOverlay?.dispose?.(); + assert.equal(mockDocument.getElementById('ag-usage-monitor-capsule'), null); + assert.equal(mockDocument.getElementById('ag-usage-monitor-portal'), null); + } +});