From 10a002afbea538dc18af9500e8014593d6d2ebf4 Mon Sep 17 00:00:00 2001 From: yuhuan2498281558 Date: Thu, 15 Oct 2026 19:02:53 +0900 Subject: [PATCH] feat(panel): upgrade modular dashboard UI, 6-segment context meter, and consumption analytics --- .gitignore | 4 + README.md | 3 - assets/logo.svg | 144 +- sidecars/panel/app.js | 4116 ++++++++++++++--- sidecars/panel/index.html | 269 +- sidecars/panel/main.mjs | 545 ++- sidecars/panel/package.json | 2 +- sidecars/panel/scripts/build-bundle.mjs | 77 + sidecars/panel/speed-metrics.mjs | 200 +- sidecars/panel/src/App.js | 106 + .../src/components/layout/TopSessionHeader.js | 142 + .../src/components/ui/ContextSegmentMeter.js | 64 + .../src/components/ui/CustomDateTimePicker.js | 282 ++ .../src/components/ui/CustomNumberInput.js | 117 + .../src/components/ui/CustomScrollbar.js | 164 + .../panel/src/components/ui/CustomSelect.js | 182 + .../src/components/ui/SegmentedControl.js | 55 + .../panel/src/components/ui/TopLongPillNav.js | 103 + sidecars/panel/src/core/component.js | 109 + sidecars/panel/src/core/domPatch.js | 154 + sidecars/panel/src/core/formatters.js | 97 + sidecars/panel/src/core/httpClient.js | 67 + sidecars/panel/src/core/reactive.js | 116 + sidecars/panel/src/icons/SvgIcon.js | 46 + sidecars/panel/src/icons/svgRegistry.js | 99 + sidecars/panel/src/main.js | 30 + sidecars/panel/src/store/telemetryStore.js | 244 + sidecars/panel/src/store/uiStore.js | 19 + sidecars/panel/src/styles/animations.css | 58 + sidecars/panel/src/styles/base.css | 99 + sidecars/panel/src/styles/components.css | 1299 ++++++ sidecars/panel/src/styles/tokens.css | 82 + sidecars/panel/src/views/ConsumptionView.js | 736 +++ sidecars/panel/src/views/LiveOverviewView.js | 374 ++ sidecars/panel/src/views/SettingsView.js | 163 + sidecars/panel/src/views/StepsDetailView.js | 274 ++ sidecars/panel/styles.css | 1916 +++++--- sidecars/panel/test/backend-harness.mjs | 35 - sidecars/panel/test/backend.test.mjs | 67 - sidecars/panel/test/speed-display.test.mjs | 52 - sidecars/panel/test/speed-metrics.test.mjs | 157 - .../panel/test/stream-diagnostics.test.mjs | 194 - 42 files changed, 11102 insertions(+), 1960 deletions(-) create mode 100644 sidecars/panel/scripts/build-bundle.mjs create mode 100644 sidecars/panel/src/App.js create mode 100644 sidecars/panel/src/components/layout/TopSessionHeader.js create mode 100644 sidecars/panel/src/components/ui/ContextSegmentMeter.js create mode 100644 sidecars/panel/src/components/ui/CustomDateTimePicker.js create mode 100644 sidecars/panel/src/components/ui/CustomNumberInput.js create mode 100644 sidecars/panel/src/components/ui/CustomScrollbar.js create mode 100644 sidecars/panel/src/components/ui/CustomSelect.js create mode 100644 sidecars/panel/src/components/ui/SegmentedControl.js create mode 100644 sidecars/panel/src/components/ui/TopLongPillNav.js create mode 100644 sidecars/panel/src/core/component.js create mode 100644 sidecars/panel/src/core/domPatch.js create mode 100644 sidecars/panel/src/core/formatters.js create mode 100644 sidecars/panel/src/core/httpClient.js create mode 100644 sidecars/panel/src/core/reactive.js create mode 100644 sidecars/panel/src/icons/SvgIcon.js create mode 100644 sidecars/panel/src/icons/svgRegistry.js create mode 100644 sidecars/panel/src/main.js create mode 100644 sidecars/panel/src/store/telemetryStore.js create mode 100644 sidecars/panel/src/store/uiStore.js create mode 100644 sidecars/panel/src/styles/animations.css create mode 100644 sidecars/panel/src/styles/base.css create mode 100644 sidecars/panel/src/styles/components.css create mode 100644 sidecars/panel/src/styles/tokens.css create mode 100644 sidecars/panel/src/views/ConsumptionView.js create mode 100644 sidecars/panel/src/views/LiveOverviewView.js create mode 100644 sidecars/panel/src/views/SettingsView.js create mode 100644 sidecars/panel/src/views/StepsDetailView.js delete mode 100644 sidecars/panel/test/backend-harness.mjs delete mode 100644 sidecars/panel/test/backend.test.mjs delete mode 100644 sidecars/panel/test/speed-display.test.mjs delete mode 100644 sidecars/panel/test/speed-metrics.test.mjs delete mode 100644 sidecars/panel/test/stream-diagnostics.test.mjs diff --git a/.gitignore b/.gitignore index 7d98f0b..252335f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,9 @@ .data/ node_modules/ +test/ +**/test/ +*.test.* +*-harness.* *.log .DS_Store Thumbs.db diff --git a/README.md b/README.md index 30f904c..cb38170 100644 --- a/README.md +++ b/README.md @@ -166,9 +166,6 @@ git -C ~/.gemini/config/plugins/usage-monitor pull --ff-only - **均速**:有效步骤总输出 Token 合计 / 请求时长合计,所有输出类型同口径。少于 50 个输出 Token 的请求保留单步速率,但不计均速;覆盖步数会显示。自动压缩仍计费,不计速度或 TTFT 均值。 - **首 Token**:保留原生 TTFT,包括真实零值;缺失显示未知,不按 Token 比例推算。元数据按源步骤索引匹配,忽略非模型元数据,避免分页时错配。平均 TTFT 只包含已完成且计时一致的普通模型步骤。 - **缓存**:`v9-unified-throughput` / measurementVersion 4。旧缓存重新读取原始轨迹;失败时保留 Token 和费用,不沿用旧派生速率。表中缓存百分比是本次请求的缓存命中率,原始记录为零时保留 0%,不沿用上一请求的高命中率。 -- **验证**:在 `sidecars/panel` 执行 `npm test`。测试使用本地合成数据,不触发模型生成。 - -发布前验证:40 项自动化测试通过;另以本地 5 个会话的 372 条历史记录回放复算,Token、费用与原生 TTFT 保持一致,369 条普通模型步骤均可展示 TPS。页面经过历史回放与窄屏检查。样本验证不代表能消除真实请求中的等待或上游缓冲。 ### 实时诊断采集(试用) diff --git a/assets/logo.svg b/assets/logo.svg index 84ae1c4..852b45a 100644 --- a/assets/logo.svg +++ b/assets/logo.svg @@ -1,15 +1,131 @@ - - - - - - - - - - - - - - + + + Antigravity Usage Monitor logo + Original blue abstract mark with three sharp negative-space points on a fully transparent background. Constructed exclusively from an SVG Bézier path and vector gradient. + + + + + + + + + + + diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 0b0eaaa..f39a1d8 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1,27 +1,585 @@ -// Frontend controller for Antigravity Usage & Speed Monitor. -const sidecar = window.sidecar; -const $ = (id) => document.getElementById(id); +// --- src/icons/svgRegistry.js --- +/** + * @fileoverview Pure vector SVG icon registry (16x16 grid). + * Strictly zero emoji characters anywhere in the codebase. + */ -let selectedConversationId = sidecar?.conversationId || ''; -let selectedTimeRange = 'all'; -let customStartMs = 0; -let customEndMs = 0; -let latestTelemetry = null; -let showAllPools = true; -let lastConvSelectSig = ''; +const SVG_ICON_DEFS = Object.freeze({ + pulse: [ + { tag: 'path', attrs: { d: 'M1.5 8h2.5l2.2-5.5 3.6 11 2.2-5.5h2.5' } }, + ], + bolt: [ + { tag: 'path', attrs: { d: 'M9.2 1.5L3.5 9h4.2l-.9 5.5L12.5 7H8.3l.9-5.5z' } }, + ], + refresh: [ + { tag: 'path', attrs: { d: 'M13.5 8a5.5 5.5 0 1 1-1.4-3.7' } }, + { tag: 'path', attrs: { d: 'M13.5 2.2v2.6h-2.6' } }, + ], + check: [ + { tag: 'path', attrs: { d: 'M3 8.5l3.2 3.2L13 4.8' } }, + ], + warning: [ + { tag: 'path', attrs: { d: 'M8 2.2L1.8 13.2h12.4L8 2.2z' } }, + { tag: 'path', attrs: { d: 'M8 6.2v3.4' } }, + { tag: 'circle', attrs: { cx: '8', cy: '11.5', r: '0.6', fill: 'currentColor', stroke: 'none' } }, + ], + 'chevron-down': [ + { tag: 'path', attrs: { d: 'M4 6.2l4 4 4-4' } }, + ], + 'chevron-up': [ + { tag: 'path', attrs: { d: 'M4 9.8l4-4 4 4' } }, + ], + 'chevron-right': [ + { tag: 'path', attrs: { d: 'M6.2 4l4 4-4 4' } }, + ], + 'chevron-left': [ + { tag: 'path', attrs: { d: 'M9.8 4l-4 4 4 4' } }, + ], + layers: [ + { tag: 'path', attrs: { d: 'M8 2L2 5.2 8 8.4l6-3.2L8 2z' } }, + { tag: 'path', attrs: { d: 'M2 8.2L8 11.4l6-3.2' } }, + { tag: 'path', attrs: { d: 'M2 11.2L8 14.4l6-3.2' } }, + ], + 'chart-bar': [ + { tag: 'path', attrs: { d: 'M2 13.5h12' } }, + { tag: 'path', attrs: { d: 'M4.5 13.5V7.5' } }, + { tag: 'path', attrs: { d: 'M8 13.5V2.5' } }, + { tag: 'path', attrs: { d: 'M11.5 13.5V5.2' } }, + ], + table: [ + { tag: 'rect', attrs: { x: '2', y: '2.5', width: '12', height: '11', rx: '1.5' } }, + { tag: 'path', attrs: { d: 'M2 6.2h12' } }, + { tag: 'path', attrs: { d: 'M6.2 6.2v7.3' } }, + ], + sliders: [ + { tag: 'path', attrs: { d: 'M2 3.5h2M7 3.5h7' } }, + { tag: 'path', attrs: { d: 'M2 8h7M12 8h2' } }, + { tag: 'path', attrs: { d: 'M2 12.5h3.3M8.3 12.5H14' } }, + { tag: 'circle', attrs: { cx: '5.5', cy: '3.5', r: '1.5' } }, + { tag: 'circle', attrs: { cx: '10.5', cy: '8', r: '1.5' } }, + { tag: 'circle', attrs: { cx: '6.8', cy: '12.5', r: '1.5' } }, + ], + flask: [ + { tag: 'path', attrs: { d: 'M6 2.2h4' } }, + { tag: 'path', attrs: { d: 'M6.8 2.2v3.6L3.2 12.2a1.2 1.2 0 0 0 1.1 1.8h7.4a1.2 1.2 0 0 0 1.1-1.8L9.2 5.8V2.2' } }, + { tag: 'path', attrs: { d: 'M4.6 10.2h6.8' } }, + ], + session: [ + { tag: 'path', attrs: { d: 'M2.5 3.2h11v7.6H6l-3.5 2.5V3.2z' } }, + ], + cpu: [ + { tag: 'rect', attrs: { x: '4', y: '4', width: '8', height: '8', rx: '1' } }, + { tag: 'path', attrs: { d: 'M6.5 1.8v2.2M9.5 1.8v2.2M6.5 12v2.2M9.5 12v2.2M1.8 6.5H4M1.8 9.5H4M12 6.5h2.2M12 9.5h2.2' } }, + ], + calendar: [ + { tag: 'rect', attrs: { x: '2.2', y: '3.2', width: '11.6', height: '10.6', rx: '1' } }, + { tag: 'path', attrs: { d: 'M5.2 1.8v2.4M10.8 1.8v2.4M2.2 6.5h11.6' } }, + ], + clock: [ + { tag: 'circle', attrs: { cx: '8', cy: '8', r: '5.8' } }, + { tag: 'path', attrs: { d: 'M8 4.8v3.5l2.4 1.5' } }, + ], + plus: [ + { tag: 'path', attrs: { d: 'M8 3.5v9M3.5 8h9' } }, + ], + minus: [ + { tag: 'path', attrs: { d: 'M3.5 8h9' } }, + ], + swap: [ + { tag: 'path', attrs: { d: 'M3 5.5h10l-2.6-2.6M13 10.5H3l2.6 2.6' } }, + ], + close: [ + { tag: 'path', attrs: { d: 'M4 4l8 8M12 4l-8 8' } }, + ], + dot: [ + { tag: 'circle', attrs: { cx: '8', cy: '8', r: '3.2', fill: 'currentColor', stroke: 'none' } }, + ], + 'arrow-down': [ + { tag: 'path', attrs: { d: 'M8 2.8v10.4M4.2 9.4L8 13.2l3.8-3.8' } }, + ], +}); -function escapeHtml(str) { - return String(str ?? '') - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); +// --- src/icons/SvgIcon.js --- +/** + * @fileoverview Dynamic SVG icon component and incremental icon patcher. + */ + + +const SVG_NS = 'http://www.w3.org/2000/svg'; + +function createSvgIcon(name, { size = 14, className = '' } = {}) { + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('viewBox', '0 0 16 16'); + svg.setAttribute('width', String(size)); + svg.setAttribute('height', String(size)); + svg.setAttribute('fill', 'none'); + svg.setAttribute('stroke', 'currentColor'); + svg.setAttribute('stroke-width', '1.5'); + svg.setAttribute('stroke-linecap', 'round'); + svg.setAttribute('stroke-linejoin', 'round'); + svg.setAttribute('aria-hidden', 'true'); + if (className) { + svg.setAttribute('class', `svg-icon ${className}`.trim()); + } else { + svg.setAttribute('class', 'svg-icon'); + } + patchSvgIcon(svg, name); + return svg; } +function patchSvgIcon(svgEl, name) { + if (!svgEl || svgEl.dataset?.iconName === name) return false; + if (svgEl.dataset) { + svgEl.dataset.iconName = name; + } + while (svgEl.firstChild) { + svgEl.removeChild(svgEl.firstChild); + } + const shapes = SVG_ICON_DEFS[name] || SVG_ICON_DEFS.dot; + for (const shape of shapes) { + const child = document.createElementNS(SVG_NS, shape.tag); + for (const [k, v] of Object.entries(shape.attrs)) { + child.setAttribute(k, v); + } + svgEl.appendChild(child); + } + return true; +} + +// --- src/core/reactive.js --- +/** + * @fileoverview Fine-grained reactive store with async microtask batching + * and structural slice comparison to prevent full-page re-renders. + */ + +const pendingJobs = new Set(); +let isFlushPending = false; + +function scheduleAsyncJob(job) { + pendingJobs.add(job); + if (!isFlushPending) { + isFlushPending = true; + queueMicrotask(flushAsyncJobs); + } +} + +function flushAsyncJobs() { + isFlushPending = false; + const jobs = Array.from(pendingJobs); + pendingJobs.clear(); + for (const job of jobs) { + job(); + } +} + +function isShallowEqual(a, b) { + if (Object.is(a, b)) return true; + if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) { + return false; + } + if (Array.isArray(a) !== Array.isArray(b)) return false; + if (Array.isArray(a)) { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (!Object.is(a[i], b[i])) return false; + } + return true; + } + const keysA = Object.keys(a); + const keysB = Object.keys(b); + if (keysA.length !== keysB.length) return false; + for (const k of keysA) { + if (!Object.prototype.hasOwnProperty.call(b, k) || !Object.is(a[k], b[k])) { + return false; + } + } + return true; +} + +function createReactiveStore(initialState) { + let state = { ...initialState }; + const subscribers = new Set(); + + function getState() { + return state; + } + + function setState(patchOrUpdater, { sync = false } = {}) { + const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater; + if (!patch || typeof patch !== 'object') return; + + let changed = false; + const nextState = { ...state }; + for (const [k, v] of Object.entries(patch)) { + if (!Object.is(state[k], v)) { + nextState[k] = v; + changed = true; + } + } + if (!changed) { + return; + } + state = nextState; + + 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 { + scheduleAsyncJob(notifyAll); + } + } + + function subscribe(selector, listener, { immediate = true, compare = isShallowEqual } = {}) { + const initialSlice = selector(state); + const sub = { + selector, + listener, + compare, + lastSlice: initialSlice, + }; + subscribers.add(sub); + if (immediate) { + listener(initialSlice, undefined); + } + return () => { + subscribers.delete(sub); + }; + } + + return { + getState, + setState, + subscribe, + }; +} + +// --- src/core/domPatch.js --- +/** + * @fileoverview Incremental DOM patching utilities and keyed list reconciler. + * Prevents full innerHTML replacements and preserves active DOM element state. + */ + +function h(tag, props = {}, children = []) { + const el = document.createElement(tag); + if (props) { + for (const [key, val] of Object.entries(props)) { + if (val === undefined || val === null || val === false) continue; + if (key === 'className' || key === 'class') { + el.className = String(val); + } else if (key === 'dataset' && typeof val === 'object') { + for (const [dk, dv] of Object.entries(val)) { + if (dv !== undefined && dv !== null) { + el.dataset[dk] = String(dv); + } + } + } else if (key.startsWith('on') && typeof val === 'function') { + const evt = key.slice(2).toLowerCase(); + el.addEventListener(evt, val); + } else if (key === 'text') { + el.textContent = String(val); + } else if (val === true) { + el.setAttribute(key, ''); + } else { + el.setAttribute(key, String(val)); + } + } + } + const childArray = Array.isArray(children) ? children : [children]; + for (const child of childArray) { + if (child === null || child === undefined || child === false) continue; + if (typeof child === 'string' || typeof child === 'number') { + el.appendChild(document.createTextNode(String(child))); + } else { + el.appendChild(child); + } + } + return el; +} + +function patchText(el, nextValue) { + if (!el) return false; + const nextStr = String(nextValue ?? ''); + if (el.textContent === nextStr) { + return false; + } + el.textContent = nextStr; + return true; +} + +function patchAttr(el, attrName, nextValue) { + if (!el) return false; + if (nextValue === null || nextValue === undefined || nextValue === false) { + if (!el.hasAttribute(attrName)) { + return false; + } + el.removeAttribute(attrName); + return true; + } + const strVal = nextValue === true ? '' : String(nextValue); + if (el.getAttribute(attrName) === strVal) { + return false; + } + el.setAttribute(attrName, strVal); + return true; +} + +function patchClasses(el, classMap) { + if (!el || !classMap) return false; + 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; + } + } + return mutated; +} + +function patchStyleVar(el, varName, nextValue) { + if (!el) return false; + const strVal = String(nextValue ?? ''); + const prev = el.style.getPropertyValue(varName); + if (prev === strVal) { + return false; + } + el.style.setProperty(varName, strVal); + return true; +} + +const keyedListState = new WeakMap(); + +/** + * Keyed incremental list reconciler. + * Reuses existing DOM nodes by key and patches only changed items in-place. + */ +function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) { + if (!container) return; + let map = keyedListState.get(container); + if (!map) { + map = new Map(); + keyedListState.set(container, map); + } + + const nextKeys = new Set(); + const orderedNodes = []; + + for (let i = 0; i < items.length; i++) { + const item = items[i]; + const key = String(keyFn(item, i)); + const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item); + nextKeys.add(key); + + let record = map.get(key); + if (!record) { + const created = createRow(item, i); + record = { + el: created.el, + refs: created.refs, + sig, + }; + updateRow(record.refs, item, i, record.el); + map.set(key, record); + } else if (record.sig !== sig) { + record.sig = sig; + updateRow(record.refs, item, i, record.el); + } + orderedNodes.push(record.el); + } + + // Remove stale keys + for (const [oldKey, record] of map.entries()) { + if (!nextKeys.has(oldKey)) { + if (record.el.parentNode === container) { + container.removeChild(record.el); + } + map.delete(oldKey); + } + } + + // Reorder or insert nodes with minimal DOM moves + for (let i = 0; i < orderedNodes.length; i++) { + const targetNode = orderedNodes[i]; + const currentNode = container.children[i] || null; + if (currentNode !== targetNode) { + container.insertBefore(targetNode, currentNode); + } + } +} + +// --- src/core/component.js --- +/** + * @fileoverview Vue-inspired lightweight component kernel supporting + * props, custom v-model value transmission (emit('update:modelValue', val)), + * reactive subscriptions, and lifecycle cleanup. + */ + +const globalEmitListeners = new Set(); + +function onComponentEmit(listener) { + globalEmitListeners.add(listener); + return () => globalEmitListeners.delete(listener); +} + +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 + if (event === 'update:modelValue') { + if (typeof props.onUpdateModelValue === 'function') { + props.onUpdateModelValue(payload); + } + if (typeof props.onChange === 'function') { + props.onChange(payload); + } + } + const handlers = eventHandlers.get(event); + if (handlers) { + for (const fn of handlers) { + fn(payload); + } + } + for (const observer of globalEmitListeners) { + observer({ + component: name || 'AnonymousComponent', + event, + payload, + timestamp: Date.now(), + }); + } + } + + function onCleanup(fn) { + if (typeof fn === 'function') { + cleanups.push(fn); + } + } + + const setupResult = setup({ + getProps: () => props, + emit, + onCleanup, + }); + + function setProps(nextProps = {}) { + props = { ...props, ...nextProps }; + if (typeof setupResult.onPropsChange === 'function') { + setupResult.onPropsChange(props); + } + } + + function setValue(nextValue) { + setProps({ modelValue: nextValue }); + } + + function getValue() { + return typeof setupResult.getValue === 'function' + ? setupResult.getValue() + : props.modelValue; + } + + function destroy() { + for (const fn of cleanups.splice(0)) { + try { + fn(); + } catch (err) { + console.error(`[${name}] cleanup error:`, err); + } + } + if (setupResult.el?.parentNode) { + setupResult.el.parentNode.removeChild(setupResult.el); + } + } + + return { + name, + el: setupResult.el, + refs: setupResult.refs || {}, + on, + emit, + setProps, + setValue, + getValue, + destroy, + ...setupResult.methods, + }; + }; +} + +// --- src/core/formatters.js --- +/** + * @fileoverview Pure formatting utilities for speed metrics, token counts, + * USD estimates, countdown timers, and custom datetime displays. + */ + function formatMetric(value, unit = '') { return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—'; } +function formatTokens(num) { + const n = Number(num || 0); + if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; + if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; + if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; + return String(Math.round(n)); +} + +function formatTokensPrecise(num) { + const n = Number(num || 0); + if (n <= 0) return '0'; + if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; + if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`; + if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; + return String(Math.round(n)); +} + +function formatCnyApprox(usdAmount, rate = 7.2) { + const rmb = Number(usdAmount || 0) * rate; + if (rmb <= 0) return '≈ ¥0'; + if (rmb >= 10) return `≈ ¥${Math.round(rmb)}`; + return `≈ ¥${rmb.toFixed(1)}`; +} + +function formatDateSpanBadge(startMs, endMs) { + const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); + const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date(); + return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; +} + +function formatUsd(amount, { precise = false, estimated = false } = {}) { + const val = Number(amount || 0); + const prefix = estimated ? '≈$' : '$'; + if (precise) { + return val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`; + } + return `${prefix}${val.toFixed(2)}`; +} + function speedReasonText(reason) { return ({ compaction: '自动压缩不计测速', @@ -35,21 +593,16 @@ function speedReasonText(reason) { } function sampleSummary(summary) { - return `${summary?.sampleCount || 0}/${(summary?.sampleCount || 0) + (summary?.excludedCount || 0)} 步`; + const valid = summary?.sampleCount || 0; + const excluded = summary?.excludedCount || 0; + return `${valid}/${valid + excluded} 步`; } -function formatTokens(num) { - const n = Number(num || 0); - if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; - if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; - return String(n); -} - -function formatCountdown(isoTime) { +function formatCountdown(isoTime, nowMs = Date.now()) { if (!isoTime) return '未知重置时间'; const targetMs = Date.parse(isoTime); if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间'; - const diffMs = targetMs - Date.now(); + const diffMs = targetMs - nowMs; if (diffMs <= 0) return '即将重置'; const totalMinutes = Math.floor(diffMs / 60000); @@ -57,573 +610,3068 @@ function formatCountdown(isoTime) { const hours = Math.floor((totalMinutes % (60 * 24)) / 60); const minutes = totalMinutes % 60; - if (days > 0) { - return `${days} 天 ${hours} 小时后重置`; - } - if (hours > 0) { - return `${hours} 小时 ${minutes} 分钟后重置`; - } - return `${minutes} 分钟后重置`; + if (days > 0) return `${days}天 ${hours}小时后重置`; + if (hours > 0) return `${hours}小时 ${minutes}分后重置`; + return `${minutes}分钟后重置`; } -function renderParallelograms(usedPct) { - const container = $('ctx-parallelograms'); - container.innerHTML = ''; - // 5 blocks, each representing 20% context usage (at least 1 filled when > 0%) - const filledCount = usedPct <= 0 ? 0 : Math.min(5, Math.max(1, Math.ceil(usedPct / 20))); - const toneClass = usedPct >= 80 ? 'danger' : usedPct >= 55 ? 'warn' : ''; - - for (let i = 0; i < 5; i++) { - const blk = document.createElement('span'); - blk.className = `para-block ${toneClass} ${i < filledCount ? 'filled' : ''}`.trim(); - container.appendChild(blk); - } -} - -async function callApi(path, { method = 'GET', body } = {}) { - const fetchFn = sidecar?.fetch ? sidecar.fetch.bind(sidecar) : window.fetch.bind(window); - const res = await fetchFn(path, { - method, - headers: { 'Content-Type': 'application/json' }, - body: body === undefined ? undefined : JSON.stringify(body), - }); - const data = await res.json().catch(() => ({})); - if (!res.ok) { - throw new Error(data.error || `${res.status}`); - } - return data; -} - -function renderConversationsSelect(conversations, activeId) { - const sel = $('conv-select'); - // Avoid resetting dropdown DOM while user is actively interacting with it - if (document.activeElement === sel) return; - - const sig = `${selectedConversationId}::${activeId}::${conversations - .map((c) => `${c.cascadeId}:${c.stepCount}:${c.title}`) - .join('|')}`; - if (sig === lastConvSelectSig) return; - lastConvSelectSig = sig; - - sel.innerHTML = ''; - - const autoOpt = document.createElement('option'); - autoOpt.value = ''; - const latestConv = conversations[0]; - autoOpt.textContent = latestConv - ? `⚡ 自动跟随 (${latestConv.title})` - : '⚡ 自动跟随最新会话'; - if (!selectedConversationId) autoOpt.selected = true; - sel.appendChild(autoOpt); - - for (const c of conversations) { - const opt = document.createElement('option'); - opt.value = c.cascadeId; - opt.textContent = `${c.title} (${c.stepCount}步)`; - if (selectedConversationId && c.cascadeId === selectedConversationId) { - opt.selected = true; - } - sel.appendChild(opt); - } -} - -function renderAllPools(pools, activeFamily) { - const box = $('all-pools-container'); - box.hidden = !showAllPools; - if (!showAllPools) return; - - box.innerHTML = ''; - for (const p of pools) { - const row = document.createElement('div'); - row.className = 'pool-mini-row'; - const isCurrent = p.family === activeFamily; - const has5h = p.usedPct != null && p.remainingPct != null; - const used5h = has5h ? `${Number(p.usedPct).toFixed(1)}%` : '--'; - const rem5h = has5h ? `${Number(p.remainingPct).toFixed(1)}%` : '--'; - const wkPart = - p.weeklyUsedPct != null && p.weeklyRemainingPct != null - ? ` · 周已用 ${Number(p.weeklyUsedPct).toFixed(1)}% (余 ${Number(p.weeklyRemainingPct).toFixed(1)}%)` - : ''; - row.innerHTML = ` - ${isCurrent ? '● ' : ''}${escapeHtml(p.poolName)} - 5h已用 ${used5h} (余 ${rem5h})${wkPart} - `; - box.appendChild(row); - } -} - -let lastStepsRenderSig = ''; -let lastModelsRenderSig = ''; - -function renderTables(activeConv, modelBreakdown) { - const steps = activeConv.recentSteps || []; - const tabStepsBtn = $('tab-steps-btn'); - if (tabStepsBtn) { - tabStepsBtn.textContent = `当前会话步骤测速与计费 (${steps.length}步)`; - } - - const stepsSig = `${activeConv.cascadeId || ''}:${JSON.stringify(steps)}`; - if (stepsSig !== lastStepsRenderSig) { - lastStepsRenderSig = stepsSig; - const stepsTbody = $('steps-tbody'); - const scrollParent = stepsTbody.closest('.table-scroll'); - const prevScrollTop = scrollParent ? scrollParent.scrollTop : 0; - - const frag = document.createDocumentFragment(); - for (const st of steps) { - const tr = document.createElement('tr'); - const thinkInfo = st.thinkingTokens - ? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | ` - : ''; - const compTag = st.isCompactionStep ? ' [压缩汇总步]' : ''; - const reason = speedReasonText(st.selectedSpeedReason); - const stepCostVal = Number(st.costUsd || 0); - const stepCostDisplay = stepCostVal >= 1 ? `$${stepCostVal.toFixed(2)}` : `$${stepCostVal.toFixed(3)}`; - const costStyle = - stepCostVal >= 0.15 - ? 'color: var(--speed-accent); font-weight: 700;' - : 'color: var(--foreground); font-weight: 600;'; - const pct5h = (stepCostVal / 0.25).toFixed(2); - const pctWk = stepCostVal.toFixed(3); - tr.title = `单步消费: $${stepCostVal.toFixed(4)} (入 $${Number(st.inCostUsd || 0).toFixed(4)} + 缓 $${Number(st.cacheCostUsd || 0).toFixed(4)} + 出 $${Number(st.outCostUsd || 0).toFixed(4)} | 约合 5h ${pct5h}% / 周限 ${pctWk}%) | ${thinkInfo}正文/工具输出: ${st.responseTokens} tok | TPS = 总输出 ${st.outputTokens} Token ÷ 请求总耗时 ${formatMetric(st.totalDurationSec, 's')}(含等待与思考) | ${reason}`; - tr.innerHTML = ` - #${Number(st.stepIndex)}${compTag ? '⚡' : ''} - ${escapeHtml(st.modelShort)} - ${formatMetric(st.tokPerSec, ' tok/s')}${reason ? `
${escapeHtml(reason)}
` : ''} - ${formatMetric(st.ttftSec, 's')} - ${formatTokens(st.contextTokens)} / +${Number(st.outputTokens)} - ${Number(st.cacheHitPct)}% - ${stepCostDisplay} - `; - frag.appendChild(tr); - } - stepsTbody.innerHTML = ''; - stepsTbody.appendChild(frag); - if (scrollParent && prevScrollTop > 0) { - scrollParent.scrollTop = prevScrollTop; - } - } - - const models = modelBreakdown || []; - const modelsSig = JSON.stringify(models); - if (modelsSig !== lastModelsRenderSig) { - lastModelsRenderSig = modelsSig; - const modelsTbody = $('models-tbody'); - modelsTbody.innerHTML = ''; - for (const m of models) { - const tr = document.createElement('tr'); - const pricePrefix = m.isEstimatedPrice ? '≈$' : '$'; - tr.innerHTML = ` - ${escapeHtml(m.shortName)} (${Number(m.calls)}) - ${Number(m.calls)} - ${formatMetric(m.avgTokPerSec, ' tok/s')}
有效 ${sampleSummary(m.speedSummary)}
- ${formatTokens(m.totalTokens)} - ${pricePrefix}${Number(m.costUsd).toFixed(2)} - `; - modelsTbody.appendChild(tr); - } - } -} - -function toLocalDateTimeInputValue(ms) { +function formatCompactDateTime(ms) { + if (!ms || !Number.isFinite(ms)) return '选择时间'; const d = new Date(ms); const pad = (n) => String(n).padStart(2, '0'); - return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; } -function renderConsumptionCards(data) { - const cons = data?.consumption || {}; - const preset = - selectedTimeRange !== 'custom' && cons.presets?.[selectedTimeRange] - ? cons.presets[selectedTimeRange] - : null; +function escapeHtml(str) { + return String(str || '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} - const sess = preset?.session || cons.session || {}; - const acct = preset?.account || cons.account || {}; - const sessAll = cons.sessionAllTime || sess; - const rangeLabel = preset?.label || cons.selectedRange?.label || '全部时间'; +// --- src/core/httpClient.js --- +/** + * @fileoverview Async HTTP client with AbortController cancellation for stale + * polling requests and concurrent GET deduplication. + */ - document.querySelectorAll('[data-time-range]').forEach((btn) => { - btn.classList.toggle('active', btn.dataset.timeRange === selectedTimeRange); +const inFlightGets = new Map(); +const activeControllers = new Map(); + +async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) { + const upperMethod = method.toUpperCase(); + const dedupKey = upperMethod === 'GET' && !abortKey ? path : ''; + + if (dedupKey && inFlightGets.has(dedupKey)) { + return inFlightGets.get(dedupKey); + } + + let signal; + if (abortKey && typeof AbortController !== 'undefined') { + const prev = activeControllers.get(abortKey); + if (prev) { + prev.abort(); + } + const controller = new AbortController(); + activeControllers.set(abortKey, controller); + signal = controller.signal; + } + + const runRequest = async () => { + const sidecar = typeof window !== 'undefined' ? window.sidecar : null; + const fetchFn = sidecar?.fetch + ? sidecar.fetch.bind(sidecar) + : globalThis.fetch.bind(globalThis); + + const res = await fetchFn(path, { + method: upperMethod, + headers: { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + signal, + }); + if (signal?.aborted) { + const abortErr = new Error('Request aborted'); + abortErr.name = 'AbortError'; + throw abortErr; + } + const data = await res.json().catch(() => ({})); + if (signal?.aborted) { + const abortErr = new Error('Request aborted'); + abortErr.name = 'AbortError'; + throw abortErr; + } + if (!res.ok) { + throw new Error(data.error || `HTTP ${res.status}`); + } + return data; + }; + + const promise = runRequest().finally(() => { + if (dedupKey) { + inFlightGets.delete(dedupKey); + } }); - const sessPrefix = sess.hasEstimatedPricing ? '≈$' : '$'; - const acctPrefix = acct.hasEstimatedPricing ? '≈$' : '$'; - - // 1. Current conversation consumption card - $('cons-session-steps').textContent = `${sess.calls || 0} 步`; - $('cons-session-tokens').textContent = formatTokens(sess.totalTokens || 0); - $('cons-session-cost').textContent = `${sessPrefix}${Number(sess.costUsd || 0).toFixed(2)}`; - $('cons-session-breakdown').textContent = `入 ${formatTokens(sess.inputTokens)} · 缓 ${formatTokens(sess.cacheReadTokens)} · 出 ${formatTokens(sess.outputTokens)}`; - $('cons-session-breakdown').title = `新增输入: ${sess.inputTokens || 0} | 缓存读取: ${sess.cacheReadTokens || 0} (${sess.cacheHitPct || 0}%) | 思考输出: ${sess.thinkingTokens || 0} | 正文输出: ${sess.responseTokens || 0}`; - - const sharePct = - acct.totalTokens > 0 - ? Math.min(100, +((sess.totalTokens / acct.totalTokens) * 100).toFixed(1)) - : 0; - if (selectedTimeRange !== 'all' && (sessAll.totalTokens || 0) > (sess.totalTokens || 0)) { - $('cons-session-pool').textContent = `占同期 ${sharePct}% · 全对话 ${formatTokens(sessAll.totalTokens)} ($${Number(sessAll.costUsd || 0).toFixed(2)})`; - } else { - $('cons-session-pool').textContent = `占同期本机 ${sharePct}% · 缓存命中 ${sess.cacheHitPct ?? 0}%`; - } - - // 2. Account total consumption card (local machine) - $('cons-account-meta').textContent = `${acct.conversationsCount || 0} 会话 · ${acct.calls || 0} 步`; - $('cons-account-tokens').textContent = formatTokens(acct.totalTokens || 0); - $('cons-account-cost').textContent = `${acctPrefix}${Number(acct.costUsd || 0).toFixed(2)}`; - $('cons-account-breakdown').textContent = `入 ${formatTokens(acct.inputTokens)} · 缓 ${formatTokens(acct.cacheReadTokens)} · 出 ${formatTokens(acct.outputTokens)}`; - $('cons-account-breakdown').title = `筛选范围: ${rangeLabel} (本机全会话) | 新增输入: ${acct.inputTokens || 0} | 缓存读取: ${acct.cacheReadTokens || 0} (${acct.cacheHitPct || 0}%) | 思考输出: ${acct.thinkingTokens || 0} | 正文输出: ${acct.responseTokens || 0}`; - $('cons-account-pool').textContent = `Gemini $${Number(acct.geminiCostUsd || 0).toFixed(2)} · Claude/GPT $${Number(acct.claudeGptCostUsd || 0).toFixed(2)}`; - $('cons-account-pool').title = `Gemini: ${formatTokens(acct.geminiTokens)} (${acct.geminiCalls || 0}步) | Claude & GPT: ${formatTokens(acct.claudeGptTokens)} (${acct.claudeGptCalls || 0}步)`; - - const tabModelsBtn = $('tab-models-btn'); - if (tabModelsBtn) { - tabModelsBtn.textContent = `按模型汇总 (${rangeLabel})`; + if (dedupKey) { + inFlightGets.set(dedupKey, promise); } + return promise; } -function applyTelemetryToDom(data) { - latestTelemetry = data; - const active = data.activeConversation || {}; - const ctx = active.context || {}; - const quotas = data.quotas || {}; - const quotaMeta = quotas.meta || {}; - const settings = data.settings || {}; +// --- src/store/uiStore.js --- +/** + * @fileoverview UI navigation and view state store. + */ - // 1. Top session bar - $('conv-title').textContent = active.title || '当前会话'; - renderConversationsSelect(data.conversations || [], active.cascadeId); - const livePill = $('live-status-pill'); - const speedDot = $('speed-dot'); - if (active.isRunning) { - speedDot.classList.add('pulsing'); - } else { - speedDot.classList.remove('pulsing'); +const VIEW_TABS = Object.freeze([ + { value: 'overview', label: '实时监控', icon: 'pulse' }, + { value: 'consumption', label: '消耗统计', icon: 'chart-bar' }, + { value: 'steps', label: '步骤明细', icon: 'table' }, + { value: 'settings', label: '系统设置', icon: 'sliders' }, +]); + +const uiStore = createReactiveStore({ + activeView: 'overview', + stepsSubTab: 'steps', // 'steps' | 'models' + showAllPools: true, + ctxBreakdownOpen: true, +}); + +// --- src/store/telemetryStore.js --- +/** + * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler + * and granular slice updates. + */ + + +const initialConversationId = + (typeof window !== 'undefined' && window.sidecar?.conversationId) || ''; + +const telemetryStore = createReactiveStore({ + selectedConversationId: initialConversationId, + selectedTimeRange: 'today', + customStartMs: Date.now() - 24 * 3600 * 1000, + customEndMs: Date.now(), + syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' + telemetry: null, +}); + +let pollTimer = null; +let feedbackTimer = null; +let activeBundleVersion = 0; +let latestRequestSeq = 0; + +function isEquivalentTelemetry(prev, next) { + if (!prev || !next) return false; + if (prev === next) return true; + + const pAct = prev.activeConversation; + const nAct = next.activeConversation; + if (pAct?.cascadeId !== nAct?.cascadeId) return false; + if (pAct?.stepCount !== nAct?.stepCount) return false; + if (pAct?.isRunning !== nAct?.isRunning) return false; + if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; + if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + const pCtx = pAct?.context; + const nCtx = nAct?.context; + if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; + if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false; + if (pCtx?.systemToolsTokens !== nCtx?.systemToolsTokens) return false; + if (pCtx?.mcpToolsTokens !== nCtx?.mcpToolsTokens) return false; + if (pCtx?.skillsTokens !== nCtx?.skillsTokens) return false; + if (pCtx?.systemPromptTokens !== nCtx?.systemPromptTokens) return false; + if (pCtx?.userRulesTokens !== nCtx?.userRulesTokens) return false; + if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false; + + const pRange = prev.consumption?.selectedRange; + const nRange = next.consumption?.selectedRange; + if (pRange?.key !== nRange?.key) return false; + if (nRange?.key === 'custom') { + if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false; } - if (!manualRefreshFeedbackTimer) { - if (active.isRunning) { - livePill.textContent = '生成中…'; - livePill.classList.add('running'); - } else if (quotaMeta.refreshFailed || quotaMeta.isStale) { - livePill.textContent = quotaMeta.hasOfficialData ? '⚠ 额度缓存' : '⚠ 额度离线'; - livePill.classList.remove('running'); - livePill.title = quotaMeta.errorMessage || '配额接口响应滞后,当前显示最近一次缓存数据'; - } else { - livePill.textContent = '实时 2s'; - livePill.classList.remove('running'); - livePill.title = ''; + + const pCons = prev.consumption?.session; + const nCons = next.consumption?.session; + if (pCons?.totalTokens !== nCons?.totalTokens) return false; + if (pCons?.costUsd !== nCons?.costUsd) return false; + + const pAcct = prev.consumption?.account; + const nAcct = next.consumption?.account; + if (pAcct?.totalTokens !== nAcct?.totalTokens) return false; + if (pAcct?.calls !== nAcct?.calls) return false; + if (pAcct?.costUsd !== nAcct?.costUsd) return false; + + const pTrend = prev.consumption?.trendSeries || []; + const nTrend = next.consumption?.trendSeries || []; + if (pTrend.length !== nTrend.length) return false; + for (let i = 0; i < pTrend.length; i++) { + if (pTrend[i]?.tokens !== nTrend[i]?.tokens || pTrend[i]?.label !== nTrend[i]?.label) { + return false; } } - // 2. Status strip metrics - $('tok-per-sec').textContent = formatMetric(active.latestTokPerSec, ' tok/s'); - $('speed-status').title = `最新一步:总输出 Token ÷ 请求总耗时(含等待与思考);${speedReasonText(active.latestSpeedReason) || '计时有效'}`; - $('ttft-value').textContent = formatMetric(active.latestTtftSec, 's'); - $('ttft-value').title = `原始首 Token 延迟,可能先返回思考内容;会话平均 ${formatMetric(active.ttftSummary?.avgSec, 's')}(${active.ttftSummary?.sampleCount || 0} 个已完成且计时一致的步骤)`; - $('avg-speed-value').textContent = formatMetric(active.avgTokPerSec); - $('speed-sample-count').textContent = `有效 ${sampleSummary(active.speedSummary)}`; - $('speed-sample-count').title = Object.entries(active.speedSummary?.excludedReasons || {}).map(([reason, count]) => `${speedReasonText(reason)}:${count} 步`).join(';') || '全部有效;自动压缩单独排除'; - const latestStepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0); - if ($('step-cost-value')) { - $('step-cost-value').textContent = `$${latestStepCost.toFixed(3)}`; - } - $('session-cost-value').textContent = `$${Number(active.sessionCostUsd || 0).toFixed(2)}`; - $('cache-hit-value').textContent = `${active.latestCacheHitPct ?? 0}%`; - renderParallelograms(ctx.usedPct || 0); - - $('active-model-short').textContent = active.activeModelShort || 'argon-4'; - $('active-model-short').title = active.activeModelLabel || ''; - $('today-tokens').textContent = formatTokens(quotas.today?.tokens || 0); - $('today-cost').textContent = `$${Number(quotas.today?.costUsd || 0).toFixed(2)}`; - - // 3. Context Window Popover Section - const limitTokens = ctx.limitTokens || 256000; - const limitLabel = formatTokens(limitTokens); - $('ctx-summary-text').textContent = `${formatTokens(ctx.totalTokens || 0)} / ${limitLabel} (${ctx.usedPct || 0}%)`; - $('ctx-summary-text').title = `距离 256k 自动压缩阈值: ${formatTokens(ctx.totalTokens || 0)} / 256.0k (${ctx.compactionUsedPct ?? 0}%)`; - - const limit = Math.max(1, limitTokens); - $('bar-ctx-cached').style.width = `${Math.min(100, (ctx.cachedTokens / limit) * 100)}%`; - $('bar-ctx-input').style.width = `${Math.min(100, (ctx.freshInputTokens / limit) * 100)}%`; - $('bar-ctx-thinking').style.width = `${Math.min(100, (ctx.thinkingTokens / limit) * 100)}%`; - $('bar-ctx-output').style.width = `${Math.min(100, (ctx.responseTokens / limit) * 100)}%`; - - $('bd-cached').textContent = formatTokens(ctx.cachedTokens); - $('bd-input').textContent = formatTokens(ctx.freshInputTokens); - $('bd-thinking').textContent = formatTokens(ctx.thinkingTokens); - $('bd-output').textContent = formatTokens(ctx.responseTokens); - - document.querySelectorAll('[data-ctx-limit]').forEach((btn) => { - btn.classList.toggle('active', Number(btn.dataset.ctxLimit) === Number(limitTokens)); - }); - - // 3.5 Session & Account Consumption Cards - renderConsumptionCards(data); - - // 4. Quotas Section - $('account-tier-label').textContent = `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`; - const activePool = quotas.activePool || {}; - const has5h = activePool.usedPct != null && activePool.remainingPct != null; - const used5hVal = has5h ? Number(activePool.usedPct) : 0; - $('session-quota-title').textContent = `5h 限额 (${activePool.family || '当前'})`; - $('session-reset-text').textContent = formatCountdown(activePool.resetTime); - $('session-used-pct').textContent = has5h - ? `已用 ${used5hVal.toFixed(1)}% (余 ${Number(activePool.remainingPct).toFixed(1)}%)` - : '获取失败 (--%)'; - - const sessionBar = $('bar-session-quota'); - sessionBar.style.width = `${Math.min(100, used5hVal)}%`; - sessionBar.className = `bar-fill ${used5hVal >= 85 ? 'danger' : used5hVal >= 60 ? 'warn' : ''}`; - - renderAllPools(quotas.pools || [], activePool.family); - - const weekly = quotas.weekly || {}; - const wkTitleEl = $('weekly-quota-title'); - if (wkTitleEl) { - wkTitleEl.textContent = weekly.title || `每周限额 (${activePool.family || '当前'})`; - } - const hasWk = weekly.usedPct != null && weekly.remainingPct != null; - const usedWkVal = hasWk ? Number(weekly.usedPct) : 0; - $('weekly-reset-text').textContent = formatCountdown(weekly.resetTime); - $('weekly-used-pct').textContent = hasWk - ? `已用 ${usedWkVal.toFixed(1)}% (余 ${Number(weekly.remainingPct).toFixed(1)}%)` - : '获取失败 (--%)'; - const weeklyBar = $('bar-weekly-quota'); - weeklyBar.style.width = `${Math.min(100, usedWkVal)}%`; - weeklyBar.className = `bar-fill ${usedWkVal >= 85 ? 'danger' : usedWkVal >= 60 ? 'warn' : ''}`; - - $('weekly-tokens-text').textContent = formatTokens(weekly.tokens || 0); - $('weekly-cost-text').textContent = `$${Number(weekly.costUsd || 0).toFixed(2)}`; - - if (data.account?.aiCredits != null && data.account.aiCredits > 0) { - $('credits-badge').textContent = `AI 积分: ${data.account.aiCredits}`; - } else if (weekly.calls != null) { - $('credits-badge').textContent = `本机调用: ${weekly.calls} 步`; - } else { - $('credits-badge').textContent = ''; + const pModels = prev.modelBreakdown || []; + const nModels = next.modelBreakdown || []; + if (pModels.length !== nModels.length) return false; + for (let i = 0; i < pModels.length; i++) { + if ( + pModels[i]?.label !== nModels[i]?.label || + pModels[i]?.totalTokens !== nModels[i]?.totalTokens || + pModels[i]?.calls !== nModels[i]?.calls + ) { + return false; + } } - // Sync settings inputs - const wkMode = - settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost' - ? settings.weeklyLimitMode - : 'official'; - $('setting-weekly-mode').value = wkMode; - $('setting-weekly-tokens').value = settings.weeklyTokenBudget || 150000000; - $('setting-weekly-cost').value = settings.weeklyCostBudget || 100; + const pSources = prev.consumption?.sourcesBreakdown || []; + const nSources = next.consumption?.sourcesBreakdown || []; + if (pSources.length !== nSources.length) return false; + for (let i = 0; i < pSources.length; i++) { + if ( + pSources[i]?.name !== nSources[i]?.name || + pSources[i]?.totalTokens !== nSources[i]?.totalTokens || + pSources[i]?.calls !== nSources[i]?.calls + ) { + return false; + } + } - const diagnostic = data.diagnostics || {}; - const phase = ({ disabled: '未开启', waiting: '等待会话', connecting: '连接中', collecting: '采集中', error: '连接异常,稍后重试' })[diagnostic.phase] || '未开启'; - $('diagnostics-status').textContent = `诊断${phase} · 已观察 ${diagnostic.contentEvents || 0} 次内容更新${diagnostic.conversationId ? ` · 会话 ${diagnostic.conversationId.slice(0, 8)}` : ''}`; - $('toggle-diagnostics-btn').textContent = diagnostic.enabled ? '停止诊断采集' : '开启诊断采集'; + const pQuot = prev.quotas?.activePool; + const nQuot = next.quotas?.activePool; + if (pQuot?.usedPct !== nQuot?.usedPct) return false; + if (pQuot?.remainingPct !== nQuot?.remainingPct) return false; + if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false; - renderTables(active, data.modelBreakdown); + if ((prev.conversations?.length || 0) !== (next.conversations?.length || 0)) return false; + + return true; } -let manualRefreshFeedbackTimer = null; - -async function refreshTelemetry(force = false) { - const btn = $('refresh-btn'); - const livePill = $('live-status-pill'); +async function fetchTelemetry({ force = false } = {}) { + const st = telemetryStore.getState(); + const reqSeq = ++latestRequestSeq; const startMs = Date.now(); - if (force && btn) { - btn.classList.add('refreshing'); - if (livePill) { - livePill.textContent = '同步中…'; - livePill.classList.remove('running'); - livePill.classList.add('synced'); - } + if (force) { + telemetryStore.setState({ syncState: 'syncing' }); } try { const params = new URLSearchParams(); - if (selectedConversationId) params.set('conversationId', selectedConversationId); - if (selectedTimeRange) params.set('range', selectedTimeRange); - if (selectedTimeRange === 'custom') { - if (customStartMs > 0) params.set('startMs', String(customStartMs)); - if (customEndMs > 0) params.set('endMs', String(customEndMs)); + if (st.selectedConversationId) { + params.set('conversationId', st.selectedConversationId); + } + if (st.selectedTimeRange) { + params.set('range', st.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 (force) { + params.set('force', '1'); } - if (force === true) params.set('force', '1'); const qs = params.toString(); - const data = await callApi(`/api/telemetry${qs ? `?${qs}` : ''}`); + const payload = await callSidecarApi(`/api/telemetry${qs ? `?${qs}` : ''}`, { + method: 'GET', + abortKey: 'telemetry-poll', + }); + if (reqSeq !== latestRequestSeq) { + return payload; + } + + if (payload?.uiBundleVersion) { + if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) { + if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { + window.location.reload(); + return payload; + } + } + activeBundleVersion = payload.uiBundleVersion; + } + + const latestSt = telemetryStore.getState(); if (force) { const elapsed = Date.now() - startMs; - if (elapsed < 320) { - await new Promise((r) => setTimeout(r, 320 - elapsed)); + if (elapsed < 220) { + await new Promise((r) => setTimeout(r, 220 - elapsed)); } + if (reqSeq !== latestRequestSeq) { + return payload; + } + if (feedbackTimer) clearTimeout(feedbackTimer); + telemetryStore.setState({ + telemetry: payload, + syncState: 'synced', + }); + feedbackTimer = setTimeout(() => { + feedbackTimer = null; + telemetryStore.setState({ syncState: 'idle' }); + }, 1100); + } else { + const isSame = isEquivalentTelemetry(latestSt.telemetry, payload); + const nextTelemetry = isSame ? latestSt.telemetry : payload; + telemetryStore.setState({ + telemetry: nextTelemetry, + syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', + }); } - - applyTelemetryToDom(data); - - if (force && livePill) { - if (manualRefreshFeedbackTimer) clearTimeout(manualRefreshFeedbackTimer); - livePill.textContent = '✓ 已刷新'; - livePill.classList.remove('running'); - livePill.classList.add('synced'); - manualRefreshFeedbackTimer = setTimeout(() => { - manualRefreshFeedbackTimer = null; - livePill.classList.remove('synced'); - if (latestTelemetry?.activeConversation?.isRunning) { - livePill.textContent = '生成中…'; - livePill.classList.add('running'); - } else { - livePill.textContent = '实时 2s'; - } - }, 1200); - } + return payload; } catch (err) { - console.error('Telemetry refresh failed:', err); - if (livePill) { - livePill.classList.remove('synced'); - livePill.textContent = '连接重试中'; - } - } finally { - if (force && btn) { - btn.classList.remove('refreshing'); - } + if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null; + telemetryStore.setState({ syncState: 'error' }); + return null; } } -async function updateSettings(patch) { - try { - await callApi('/api/settings', { method: 'POST', body: patch }); - await refreshTelemetry(true); - } catch (err) { - console.error('Failed saving settings:', err); +async function saveSettingsPatch(patch) { + 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, + }, + }); } + await callSidecarApi('/api/settings', { method: 'POST', body: patch }); + await fetchTelemetry({ force: true }); } -function bindEvents() { - $('refresh-btn').addEventListener('click', () => refreshTelemetry(true)); +function startAsyncTelemetryLoop(intervalMs = 2000) { + stopAsyncTelemetryLoop(); + let active = true; - $('toggle-diagnostics-btn').addEventListener('click', async () => { - const button = $('toggle-diagnostics-btn'); - button.disabled = true; - try { - await callApi('/api/diagnostics', { method: 'POST', body: { enabled: !latestTelemetry?.diagnostics?.enabled } }); - await refreshTelemetry(); - } catch { - $('diagnostics-status').textContent = '诊断设置未保存,请稍后重试'; - } finally { - button.disabled = false; - } - }); - - $('conv-select').addEventListener('change', (e) => { - selectedConversationId = e.target.value; - refreshTelemetry(); - }); - - // Time filter buttons - document.querySelectorAll('[data-time-range]').forEach((btn) => { - btn.addEventListener('click', () => { - const nextRange = btn.dataset.timeRange || 'all'; - selectedTimeRange = nextRange; - const customBox = $('custom-time-box'); - if (customBox) { - customBox.hidden = nextRange !== 'custom'; - } - if (nextRange === 'custom') { - const now = Date.now(); - if (!customStartMs) customStartMs = now - 24 * 3600 * 1000; - if (!customEndMs) customEndMs = now; - if (!$('custom-start-input').value) { - $('custom-start-input').value = toLocalDateTimeInputValue(customStartMs); - } - if (!$('custom-end-input').value) { - $('custom-end-input').value = toLocalDateTimeInputValue(customEndMs); - } - } - if (latestTelemetry && nextRange !== 'custom') { - renderConsumptionCards(latestTelemetry); - } - refreshTelemetry(); - }); - }); - - const applyCustomBtn = $('apply-custom-time-btn'); - if (applyCustomBtn) { - applyCustomBtn.addEventListener('click', () => { - const sVal = $('custom-start-input').value; - const eVal = $('custom-end-input').value; - const sMs = sVal ? Date.parse(sVal) : 0; - const eMs = eVal ? Date.parse(eVal) : Date.now(); - if (sMs > 0) customStartMs = sMs; - if (eMs > 0) customEndMs = eMs; - selectedTimeRange = 'custom'; - refreshTelemetry(true); - }); - } - - // Toggle context breakdown - const toggleCtx = () => { - const box = $('ctx-breakdown-box'); - box.hidden = !box.hidden; - $('ctx-chevron').textContent = box.hidden ? '›' : '⌄'; + const tick = async () => { + if (!active) return; + await fetchTelemetry({ force: false }); + if (!active) return; + pollTimer = setTimeout(tick, intervalMs); }; - $('ctx-detail-toggle').addEventListener('click', toggleCtx); - $('ctx-inline-trigger').addEventListener('click', toggleCtx); - // Switch context window limit (200k / 1M / 2M) - document.querySelectorAll('[data-ctx-limit]').forEach((btn) => { - btn.addEventListener('click', (e) => { - e.stopPropagation(); - updateSettings({ contextWindowLimit: Number(btn.dataset.ctxLimit) }); - }); - }); + tick(); + return () => { + active = false; + stopAsyncTelemetryLoop(); + }; +} - // Toggle all model pools - $('pool-switch-toggle').addEventListener('click', () => { - showAllPools = !showAllPools; - if (latestTelemetry) { - renderAllPools( - latestTelemetry.quotas?.pools || [], - latestTelemetry.quotas?.activePool?.family - ); +function stopAsyncTelemetryLoop() { + if (pollTimer) { + clearTimeout(pollTimer); + pollTimer = null; + } +} + +// --- src/components/ui/TopLongPillNav.js --- +/** + * @fileoverview Top Long-Pill Navigation Bar (顶部唯一长药丸功能分割栏). + * Splits the application into focused single-viewport views and animates + * the active glider using GPU-accelerated translate3d. + */ + + +const TopLongPillNav = defineComponent({ + name: 'TopLongPillNav', + setup({ getProps, emit }) { + const glider = h('div', { className: 'pill-glider', 'aria-hidden': 'true' }); + const navEl = h( + 'nav', + { + className: 'long-pill-nav', + role: 'tablist', + 'aria-label': '主功能视图分割导航', + }, + [glider] + ); + + const tabButtons = new Map(); + + function selectValue(nextVal) { + const current = getProps().modelValue; + if (nextVal !== current) { + emit('update:modelValue', nextVal); + } } - }); - // Toggle details panel - $('toggle-details-btn').addEventListener('click', () => { - const card = $('details-card'); - card.hidden = !card.hidden; - $('toggle-details-btn').textContent = card.hidden ? '查看详细明细' : '收起详细明细'; - }); + function syncTabs() { + const { items = [], modelValue } = getProps(); + patchStyleVar(navEl, '--pill-count', Math.max(1, items.length)); - // Switch tabs inside details panel - document.querySelectorAll('.tab-btn').forEach((btn) => { - btn.addEventListener('click', () => { - document.querySelectorAll('.tab-btn').forEach((b) => b.classList.remove('active')); - btn.classList.add('active'); - const tab = btn.dataset.tab; - $('tab-steps').hidden = tab !== 'steps'; - $('tab-models').hidden = tab !== 'models'; + let activeIdx = 0; + items.forEach((item, index) => { + if (item.value === modelValue) { + activeIdx = index; + } + let entry = tabButtons.get(item.value); + if (!entry) { + const iconEl = item.icon ? createSvgIcon(item.icon, { size: 14 }) : null; + const labelEl = h('span', { className: 'pill-tab-label', text: item.label }); + const badgeEl = h('span', { className: 'pill-tab-badge', hidden: true }); + const btn = h( + 'button', + { + type: 'button', + role: 'tab', + className: 'pill-tab', + dataset: { pillValue: item.value }, + onClick: () => selectValue(item.value), + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const curItems = getProps().items || []; + const delta = e.key === 'ArrowRight' ? 1 : -1; + const nextIndex = (index + delta + curItems.length) % curItems.length; + const target = curItems[nextIndex]; + if (target) { + selectValue(target.value); + tabButtons.get(target.value)?.btn?.focus(); + } + } + }, + }, + [iconEl, labelEl, badgeEl] + ); + entry = { btn, labelEl, badgeEl }; + tabButtons.set(item.value, entry); + navEl.appendChild(btn); + } + + patchText(entry.labelEl, item.label); + if (item.badge !== undefined && item.badge !== null && item.badge !== '') { + patchAttr(entry.badgeEl, 'hidden', false); + patchText(entry.badgeEl, `(${item.badge})`); + } else { + patchAttr(entry.badgeEl, 'hidden', true); + } + + const isActive = item.value === modelValue; + patchClasses(entry.btn, { 'is-active': isActive }); + patchAttr(entry.btn, 'aria-selected', isActive ? 'true' : 'false'); + patchAttr(entry.btn, 'tabindex', isActive ? '0' : '-1'); + }); + + patchStyleVar(navEl, '--active-index', activeIdx); + } + + syncTabs(); + + return { + el: navEl, + refs: { glider, tabButtons }, + onPropsChange: syncTabs, + getValue: () => getProps().modelValue, + }; + }, +}); + +// --- src/components/ui/CustomSelect.js --- +/** + * @fileoverview Bespoke CustomSelect dropdown component replacing native with custom SVG step controls, + * keyboard ArrowUp/ArrowDown (+Shift 10x), and min/max clamping. + */ + + +const CustomNumberInput = defineComponent({ + name: 'CustomNumberInput', + setup({ getProps, emit }) { + function clampValue(raw) { + const { min = -Infinity, max = Infinity, precision = 0 } = getProps(); + const num = Number(raw); + if (!Number.isFinite(num)) { + return Number(getProps().modelValue ?? (Number.isFinite(min) ? min : 0)); + } + const clamped = Math.min(max, Math.max(min, num)); + return precision > 0 ? Number(clamped.toFixed(precision)) : Math.round(clamped); + } + + function applyStep(direction, multiplier = 1) { + const { step = 1, modelValue = 0 } = getProps(); + const current = Number(modelValue) || 0; + const next = clampValue(current + direction * step * multiplier); + syncFieldDisplay(next); + if (next !== current) { + emit('update:modelValue', next); + } + } + + const decBtn = h( + 'button', + { + type: 'button', + className: 'num-step-btn', + 'aria-label': '减少数值', + onClick: (e) => { + e.preventDefault(); + applyStep(-1, e.shiftKey ? 10 : 1); + }, + }, + [createSvgIcon('minus', { size: 12 })] + ); + + const incBtn = h( + 'button', + { + type: 'button', + className: 'num-step-btn', + 'aria-label': '增加数值', + onClick: (e) => { + e.preventDefault(); + applyStep(1, e.shiftKey ? 10 : 1); + }, + }, + [createSvgIcon('plus', { size: 12 })] + ); + + const textField = h('input', { + type: 'text', + inputmode: 'decimal', + role: 'spinbutton', + className: 'num-field', + onKeydown: (e) => { + if (e.key === 'ArrowUp') { + e.preventDefault(); + applyStep(1, e.shiftKey ? 10 : 1); + } else if (e.key === 'ArrowDown') { + e.preventDefault(); + applyStep(-1, e.shiftKey ? 10 : 1); + } else if (e.key === 'Enter') { + e.preventDefault(); + commitManualInput(); + } + }, + onBlur: () => commitManualInput(), }); - $('settings-card').hidden = true; - }); + + function commitManualInput() { + const rawText = String(textField.value || '').replace(/[^0-9.-]/g, ''); + const next = clampValue(rawText); + const prev = Number(getProps().modelValue); + syncFieldDisplay(next); + if (next !== prev) { + emit('update:modelValue', next); + } + } + + function syncFieldDisplay(val = getProps().modelValue) { + const { min, max } = getProps(); + const normalized = clampValue(val); + if (textField.value !== String(normalized)) { + textField.value = String(normalized); + } + patchAttr(textField, 'aria-valuenow', normalized); + if (Number.isFinite(min)) patchAttr(textField, 'aria-valuemin', min); + if (Number.isFinite(max)) patchAttr(textField, 'aria-valuemax', max); + } + + const rootEl = h('div', { className: 'number-input' }, [decBtn, textField, incBtn]); + syncFieldDisplay(); + + return { + 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), + }, + }; + }, +}); + +// --- src/components/ui/CustomDateTimePicker.js --- +/** + * @fileoverview Bespoke CustomDateTimePicker calendar matrix and hour/minute stepper. + * Replaces native and emits Unix epoch ms. + */ + + +const WEEKDAYS = ['一', '二', '三', '四', '五', '六', '日']; + +function buildCalendarDays(viewYear, viewMonth, selectedDate) { + const firstDay = new Date(viewYear, viewMonth, 1); + // Convert Sunday=0..Saturday=6 into Monday=0..Sunday=6 + const startOffset = (firstDay.getDay() + 6) % 7; + const cells = []; + + for (let i = 0; i < 42; i++) { + const cellDate = new Date(viewYear, viewMonth, 1 - startOffset + i); + const y = cellDate.getFullYear(); + const m = cellDate.getMonth(); + const d = cellDate.getDate(); + const isCurrentMonth = m === viewMonth; + const isSelected = + selectedDate && + selectedDate.getFullYear() === y && + selectedDate.getMonth() === m && + selectedDate.getDate() === d; + + cells.push({ + key: `${y}-${m}-${d}`, + year: y, + month: m, + day: d, + isCurrentMonth, + isSelected, + }); + } + return cells; +} + +const CustomDateTimePicker = defineComponent({ + name: 'CustomDateTimePicker', + setup({ getProps, emit, onCleanup }) { + let isOpen = false; + const initialDate = new Date(getProps().modelValue || Date.now()); + let viewYear = initialDate.getFullYear(); + let viewMonth = initialDate.getMonth(); + + const triggerText = h('span', { className: 'text-mono' }); + const triggerBtn = h( + 'button', + { + type: 'button', + className: 'dt-trigger', + 'aria-expanded': 'false', + onClick: (e) => { + e.stopPropagation(); + togglePopover(!isOpen); + }, + }, + [createSvgIcon('calendar', { size: 13 }), triggerText] + ); + + const monthTitle = h('span', { className: 'text-mono' }); + const prevMonthBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn', + 'aria-label': '上个月', + onClick: (e) => { + e.stopPropagation(); + viewMonth -= 1; + if (viewMonth < 0) { + viewMonth = 11; + viewYear -= 1; + } + renderCalendar(); + }, + }, + [createSvgIcon('chevron-left', { size: 12 })] + ); + + const nextMonthBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn', + 'aria-label': '下个月', + onClick: (e) => { + e.stopPropagation(); + viewMonth += 1; + if (viewMonth > 11) { + viewMonth = 0; + viewYear += 1; + } + renderCalendar(); + }, + }, + [createSvgIcon('chevron-right', { size: 12 })] + ); + + const navBar = h('div', { className: 'dt-nav' }, [prevMonthBtn, monthTitle, nextMonthBtn]); + + const weekdayRow = h( + 'div', + { className: 'dt-weekdays' }, + WEEKDAYS.map((w) => h('span', { className: 'dt-weekday', text: w })) + ); + + const daysGrid = h('div', { className: 'dt-days' }); + + const hourValSpan = h('strong', { className: 'text-mono', text: '00' }); + const minValSpan = h('strong', { className: 'text-mono', text: '00' }); + + function adjustTime(part, delta) { + const cur = new Date(getProps().modelValue || Date.now()); + if (part === 'hour') { + cur.setHours((cur.getHours() + delta + 24) % 24); + } else { + cur.setMinutes((cur.getMinutes() + delta + 60) % 60); + } + const nextMs = cur.getTime(); + viewYear = cur.getFullYear(); + viewMonth = cur.getMonth(); + emit('update:modelValue', nextMs); + } + + const timeRow = h('div', { className: 'dt-time-row' }, [ + h('span', { className: 'text-muted', text: '时 / 分' }), + h('div', { className: 'dt-time-controls' }, [ + h('div', { className: 'dt-mini-step' }, [ + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '-', + onClick: (e) => { + e.stopPropagation(); + adjustTime('hour', -1); + }, + }), + hourValSpan, + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '+', + onClick: (e) => { + e.stopPropagation(); + adjustTime('hour', 1); + }, + }), + ]), + h('span', { text: ':' }), + h('div', { className: 'dt-mini-step' }, [ + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '-', + onClick: (e) => { + e.stopPropagation(); + adjustTime('minute', -5); + }, + }), + minValSpan, + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '+', + onClick: (e) => { + e.stopPropagation(); + adjustTime('minute', 5); + }, + }), + ]), + ]), + ]); + + const popoverEl = h( + 'div', + { + className: 'dt-popover', + hidden: true, + }, + [navBar, weekdayRow, daysGrid, timeRow] + ); + + const rootEl = h('div', { className: 'datetime-picker' }, [triggerBtn, popoverEl]); + + function togglePopover(nextOpen) { + isOpen = Boolean(nextOpen); + patchAttr(popoverEl, 'hidden', !isOpen); + patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); + if (isOpen) { + const cur = new Date(getProps().modelValue || Date.now()); + viewYear = cur.getFullYear(); + viewMonth = cur.getMonth(); + renderCalendar(); + } + } + + function selectDay(cell) { + const cur = new Date(getProps().modelValue || Date.now()); + cur.setFullYear(cell.year, cell.month, cell.day); + const nextMs = cur.getTime(); + viewYear = cell.year; + viewMonth = cell.month; + emit('update:modelValue', nextMs); + } + + function renderCalendar() { + const cur = new Date(getProps().modelValue || Date.now()); + const pad = (n) => String(n).padStart(2, '0'); + patchText(monthTitle, `${viewYear}-${pad(viewMonth + 1)}`); + patchText(hourValSpan, pad(cur.getHours())); + patchText(minValSpan, pad(cur.getMinutes())); + + const cells = buildCalendarDays(viewYear, viewMonth, cur); + patchKeyedList(daysGrid, cells, { + keyFn: (c) => c.key, + sigFn: (c) => `${c.key}:${c.isCurrentMonth}:${c.isSelected}`, + createRow: (cell) => { + const btn = h('button', { + type: 'button', + className: 'dt-day', + onClick: (e) => { + e.stopPropagation(); + selectDay(cell); + }, + }); + return { el: btn, refs: {} }; + }, + updateRow: (_refs, cell, _idx, el) => { + patchText(el, cell.day); + patchClasses(el, { + 'is-selected': cell.isSelected, + 'is-outside': !cell.isCurrentMonth, + }); + patchAttr(el, 'data-date-key', cell.key); + }, + }); + } + + function syncDisplay() { + const ms = Number(getProps().modelValue || Date.now()); + patchText(triggerText, formatCompactDateTime(ms)); + if (isOpen) { + renderCalendar(); + } + } + + const handleDocClick = (e) => { + if (isOpen && !rootEl.contains(e.target)) { + togglePopover(false); + } + }; + + if (typeof document !== 'undefined' && document.addEventListener) { + document.addEventListener('click', handleDocClick); + onCleanup(() => document.removeEventListener('click', handleDocClick)); + } + + syncDisplay(); + + return { + 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()); + }, + }, + }; + }, +}); + +// --- src/components/ui/CustomScrollbar.js --- +/** + * @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. + */ + + +const CustomScrollbar = defineComponent({ + name: 'CustomScrollbar', + setup({ getProps, emit, onCleanup }) { + const contentEl = getProps().contentEl || h('div'); + contentEl.classList.add('custom-scroll-content'); + + const thumbEl = h('div', { className: 'scrollbar-thumb' }); + const railEl = h( + 'div', + { + className: 'scrollbar-rail is-inactive', + 'aria-hidden': 'true', + }, + [thumbEl] + ); + + const hostEl = h( + 'div', + { + className: `custom-scroll-host ${getProps().className || ''}`.trim(), + }, + [contentEl, railEl] + ); + + let isDragging = false; + let dragStartY = 0; + let dragStartScrollTop = 0; + + function syncThumb() { + const scrollHeight = Number(contentEl.scrollHeight || 0); + const clientHeight = Number(contentEl.clientHeight || 0); + const scrollTop = Number(contentEl.scrollTop || 0); + const overflow = scrollHeight - clientHeight; + + if (overflow <= 1 || clientHeight <= 0) { + patchClasses(railEl, { 'is-inactive': true }); + patchStyleVar(thumbEl, '--thumb-h', '0px'); + patchStyleVar(thumbEl, '--thumb-y', '0px'); + return; + } + + patchClasses(railEl, { 'is-inactive': false }); + const railHeight = Math.max(24, clientHeight - 4); + const thumbHeight = Math.max(24, Math.round((clientHeight / scrollHeight) * railHeight)); + const maxThumbTop = Math.max(0, railHeight - thumbHeight); + const ratio = Math.max(0, Math.min(1, scrollTop / overflow)); + const thumbTop = Math.round(ratio * maxThumbTop); + + patchStyleVar(thumbEl, '--thumb-h', `${thumbHeight}px`); + patchStyleVar(thumbEl, '--thumb-y', `${thumbTop}px`); + } + + function onContentScroll() { + 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) { + if (!isDragging) return; + const clientHeight = Number(contentEl.clientHeight || 0); + const scrollHeight = Number(contentEl.scrollHeight || 0); + const overflow = scrollHeight - clientHeight; + if (overflow <= 1) return; + + const railHeight = Math.max(24, clientHeight - 4); + const thumbHeight = Math.max(24, Math.round((clientHeight / scrollHeight) * railHeight)); + const maxThumbTop = Math.max(1, railHeight - thumbHeight); + + const deltaY = (e.clientY || 0) - dragStartY; + const scrollDelta = (deltaY / maxThumbTop) * overflow; + contentEl.scrollTop = Math.max(0, Math.min(overflow, dragStartScrollTop + scrollDelta)); + syncThumb(); + } + + function onDocMouseUp() { + if (!isDragging) return; + isDragging = false; + patchClasses(railEl, { 'is-dragging': false }); + if (typeof document !== 'undefined') { + document.removeEventListener('mousemove', onDocMouseMove); + document.removeEventListener('mouseup', onDocMouseUp); + } + } + + thumbEl.addEventListener('mousedown', (e) => { + e.preventDefault(); + e.stopPropagation(); + isDragging = true; + dragStartY = e.clientY || 0; + dragStartScrollTop = Number(contentEl.scrollTop || 0); + patchClasses(railEl, { 'is-dragging': true }); + if (typeof document !== 'undefined') { + document.addEventListener('mousemove', onDocMouseMove); + document.addEventListener('mouseup', onDocMouseUp); + } + }); + + railEl.addEventListener('mousedown', (e) => { + if (e.target === thumbEl) return; + e.preventDefault(); + const rect = railEl.getBoundingClientRect ? railEl.getBoundingClientRect() : null; + if (!rect || rect.height <= 0) return; + const clickOffset = (e.clientY || 0) - rect.top; + const ratio = Math.max(0, Math.min(1, clickOffset / rect.height)); + const overflow = Math.max(0, (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0)); + contentEl.scrollTop = Math.round(ratio * overflow); + syncThumb(); + }); + + contentEl.addEventListener('scroll', onContentScroll); + hostEl.addEventListener('mouseenter', syncThumb); + + let resizeObserver = null; + if (typeof ResizeObserver !== 'undefined') { + resizeObserver = new ResizeObserver(() => syncThumb()); + resizeObserver.observe(hostEl); + resizeObserver.observe(contentEl); + } + + syncThumb(); + + onCleanup(() => { + onDocMouseUp(); + contentEl.removeEventListener('scroll', onContentScroll); + hostEl.removeEventListener('mouseenter', syncThumb); + if (resizeObserver) { + resizeObserver.disconnect(); + } + }); + + return { + el: hostEl, + refs: { contentEl, railEl, thumbEl }, + onPropsChange: syncThumb, + methods: { + refresh() { + syncThumb(); + if (typeof queueMicrotask === 'function') { + queueMicrotask(syncThumb); + } + }, + 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(); + }, + }, + }; + }, +}); + +// --- src/components/ui/SegmentedControl.js --- +/** + * @fileoverview Micro-bezel (2px radius) SegmentedControl switcher + * for time-range filtering, context limit selection, and sub-table switching. + */ + + +const SegmentedControl = defineComponent({ + name: 'SegmentedControl', + setup({ getProps, emit }) { + const rootEl = h('div', { + className: 'segmented', + role: 'group', + 'aria-label': getProps().ariaLabel || '分段切换器', + }); + + function syncSegments() { + const { options = [], modelValue } = getProps(); + patchKeyedList(rootEl, options, { + keyFn: (opt) => opt.value, + sigFn: (opt) => `${opt.value}::${opt.label}::${opt.value === modelValue}`, + createRow: (opt) => { + const btn = h('button', { + type: 'button', + className: 'seg-btn', + onClick: (e) => { + e.stopPropagation(); + if (getProps().modelValue !== opt.value) { + emit('update:modelValue', opt.value); + } + }, + }); + return { el: btn, refs: {} }; + }, + updateRow: (_refs, opt, _idx, el) => { + const active = opt.value === modelValue; + patchText(el, opt.label); + patchClasses(el, { 'is-active': active }); + patchAttr(el, 'aria-pressed', active ? 'true' : 'false'); + patchAttr(el, 'data-seg-value', opt.value); + }, + }); + } + + syncSegments(); + + return { + el: rootEl, + refs: {}, + onPropsChange: syncSegments, + getValue: () => getProps().modelValue, + }; + }, +}); + +// --- src/components/ui/ContextSegmentMeter.js --- +/** + * @fileoverview 6-channel segmented context window progress bar updated via + * CSS custom variables against the current model's automatic compaction baseline. + */ + + +const ContextSegmentMeter = defineComponent({ + name: 'ContextSegmentMeter', + setup({ getProps }) { + const segMessages = h('div', { className: 'progress-seg seg-messages' }); + const segSystemTools = h('div', { className: 'progress-seg seg-system-tools' }); + const segMcpTools = h('div', { className: 'progress-seg seg-mcp-tools' }); + const segSkills = h('div', { className: 'progress-seg seg-skills' }); + const segSystemPrompt = h('div', { className: 'progress-seg seg-system-prompt' }); + const segUserRules = h('div', { className: 'progress-seg seg-user-rules' }); + + const trackEl = h( + 'div', + { + className: 'progress-track', + role: 'progressbar', + 'aria-valuemin': '0', + 'aria-valuemax': '100', + }, + [segMessages, segSystemTools, segMcpTools, segSkills, segSystemPrompt, segUserRules] + ); + + function syncMeter() { + const ctx = getProps().context || {}; + const limit = Math.max(1, Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000)); + const pctMessages = Math.min(100, ((ctx.messagesTokens || 0) / limit) * 100); + const pctSystemTools = Math.min(100, ((ctx.systemToolsTokens || 0) / limit) * 100); + const pctMcpTools = Math.min(100, ((ctx.mcpToolsTokens || 0) / limit) * 100); + const pctSkills = Math.min(100, ((ctx.skillsTokens || 0) / limit) * 100); + const pctSystemPrompt = Math.min(100, ((ctx.systemPromptTokens || 0) / limit) * 100); + const pctUserRules = Math.min(100, ((ctx.userRulesTokens || 0) / limit) * 100); + + patchStyleVar(segMessages, '--seg-w', `${pctMessages.toFixed(2)}%`); + patchStyleVar(segSystemTools, '--seg-w', `${pctSystemTools.toFixed(2)}%`); + patchStyleVar(segMcpTools, '--seg-w', `${pctMcpTools.toFixed(2)}%`); + patchStyleVar(segSkills, '--seg-w', `${pctSkills.toFixed(2)}%`); + patchStyleVar(segSystemPrompt, '--seg-w', `${pctSystemPrompt.toFixed(2)}%`); + patchStyleVar(segUserRules, '--seg-w', `${pctUserRules.toFixed(2)}%`); + patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0)); + } + + syncMeter(); + + return { + el: trackEl, + refs: { + segMessages, + segSystemTools, + segMcpTools, + segSkills, + segSystemPrompt, + segUserRules, + }, + onPropsChange: syncMeter, + }; + }, +}); + +// --- src/components/layout/TopSessionHeader.js --- +/** + * @fileoverview Row 1 of the compact top bar: + * Bespoke CustomSelect for session switching, SVG live status indicator, + * and async force-refresh button. + */ + + +const TopSessionHeader = defineComponent({ + name: 'TopSessionHeader', + setup({ onCleanup }) { + const convSelect = CustomSelect({ + modelValue: telemetryStore.getState().selectedConversationId, + icon: 'bolt', + placeholder: '自动跟随最新会话', + options: [{ value: '', label: '自动跟随最新会话' }], + onUpdateModelValue: (nextConvId) => { + telemetryStore.setState({ selectedConversationId: nextConvId }); + fetchTelemetry({ force: false }); + }, + }); + + const statusIcon = createSvgIcon('pulse', { size: 12 }); + const statusText = h('span', { text: '实时 2s' }); + const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]); + + const refreshBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn', + 'aria-label': '立即强制同步官方额度与测速', + onClick: () => fetchTelemetry({ force: true }), + }, + [createSvgIcon('refresh', { size: 13 })] + ); + + const headerEl = h('header', { className: 'session-header' }, [ + h('div', { className: 'session-left' }, [convSelect.el]), + h('div', { className: 'session-right' }, [statusTag, refreshBtn]), + ]); + + const unsubTelemetry = telemetryStore.subscribe( + (st) => ({ + selectedConversationId: st.selectedConversationId, + syncState: st.syncState, + conversations: st.telemetry?.conversations, + isRunning: st.telemetry?.activeConversation?.isRunning, + quotaMeta: st.telemetry?.quotas?.meta, + }), + (slice) => { + const convs = slice.conversations || []; + const latestTitle = convs[0]?.title ? `自动跟随 (${convs[0].title})` : '自动跟随最新会话'; + const options = [ + { value: '', label: latestTitle, meta: convs[0] ? `${convs[0].stepCount}步` : '' }, + ...convs.map((c) => ({ + value: c.cascadeId, + label: c.title || c.cascadeId.slice(0, 8), + meta: `${c.stepCount || 0}步`, + })), + ]; + convSelect.setProps({ + modelValue: slice.selectedConversationId, + options, + }); + + const isSyncing = slice.syncState === 'syncing'; + const isSynced = slice.syncState === 'synced'; + const isError = slice.syncState === 'error'; + const isRunning = Boolean(slice.isRunning); + const quotaStale = Boolean(slice.quotaMeta?.refreshFailed || slice.quotaMeta?.isStale); + + patchClasses(refreshBtn, { 'is-spinning': isSyncing }); + patchAttr(refreshBtn, 'disabled', isSyncing); + + if (isSyncing) { + patchSvgIcon(statusIcon, 'refresh'); + patchText(statusText, '同步中'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': true, + 'state-warn': false, + }); + } else if (isSynced) { + patchSvgIcon(statusIcon, 'check'); + patchText(statusText, '已刷新'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': true, + 'state-warn': false, + }); + } else if (isError) { + patchSvgIcon(statusIcon, 'warning'); + patchText(statusText, '重试中'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': false, + 'state-warn': true, + }); + } else if (isRunning) { + patchSvgIcon(statusIcon, 'bolt'); + patchText(statusText, '生成中'); + patchClasses(statusTag, { + 'state-running': true, + 'state-synced': false, + 'state-warn': false, + }); + } else if (quotaStale) { + patchSvgIcon(statusIcon, 'warning'); + patchText(statusText, slice.quotaMeta?.hasOfficialData ? '额度缓存' : '额度离线'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': false, + 'state-warn': true, + }); + } else { + patchSvgIcon(statusIcon, 'pulse'); + patchText(statusText, '实时 2s'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': false, + 'state-warn': false, + }); + } + } + ); + + onCleanup(() => { + unsubTelemetry(); + convSelect.destroy(); + }); + + return { + el: headerEl, + refs: { convSelect, statusTag, refreshBtn }, + }; + }, +}); + +// --- src/views/LiveOverviewView.js --- +/** + * @fileoverview View 1: LiveOverviewView (实时监控视图). + * Displays real-time TPS, TTFT, weighted mean speed, 4-channel Context Window + * breakdown automatically anchored to the current model's compaction baseline, + * and official 5h/weekly quota pools for both Gemini and Claude & GPT. + */ + + +const LiveOverviewView = defineComponent({ + name: 'LiveOverviewView', + setup({ onCleanup }) { + // 1. 4-Cell Real-time Telemetry Matrix + const tpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); + const tpsSub = h('span', { className: 'cell-sub', text: 'argon-4' }); + const pulseDot = createSvgIcon('dot', { size: 10 }); + + const ttftVal = h('strong', { className: 'cell-value', text: '—' }); + const ttftSub = h('span', { className: 'cell-sub', text: '均值 —' }); + + 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 cacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累 $0.00' }); + + const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '核心测速指标' }, [ + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [h('span', { text: '实时吞吐' }), pulseDot]), + tpsVal, + tpsSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '首Token' }), + createSvgIcon('clock', { size: 11 }), + ]), + ttftVal, + ttftSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '会话均速' }), + createSvgIcon('pulse', { size: 11 }), + ]), + avgVal, + avgSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '本步消费' }), + createSvgIcon('bolt', { size: 11 }), + ]), + costVal, + cacheSub, + ]), + ]); + + // 2. Context Window 6-Segment Panel (Auto Compaction Baseline) + const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' }); + const ctxSegmentBar = ContextSegmentMeter({ context: {} }); + + const bdMessages = h('strong', { className: 'text-mono', text: '0' }); + const bdSystemTools = h('strong', { className: 'text-mono', text: '0' }); + const bdMcpTools = h('strong', { className: 'text-mono', text: '0' }); + const bdSkills = h('strong', { className: 'text-mono', text: '0' }); + const bdSystemPrompt = h('strong', { className: 'text-mono', text: '0' }); + const bdUserRules = h('strong', { className: 'text-mono', text: '0' }); + + const ctxPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('layers', { size: 13 }), + h('span', { text: '上下文窗口构成' }), + ]), + h('span', { className: 'panel-meta' }, [ctxSummaryText]), + ]), + ctxSegmentBar.el, + h('div', { className: 'ctx-legend-grid' }, [ + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-messages' }), + h('span', { text: '消息' }), + ]), + bdMessages, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-system-tools' }), + h('span', { text: '系统工具' }), + ]), + bdSystemTools, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-mcp-tools' }), + h('span', { text: 'MCP 工具' }), + ]), + bdMcpTools, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-skills' }), + h('span', { text: 'Skill' }), + ]), + bdSkills, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-system-prompt' }), + h('span', { text: '系统提示词' }), + ]), + bdSystemPrompt, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-user-rules' }), + h('span', { text: 'user_rule' }), + ]), + bdUserRules, + ]), + ]), + ]); + + // 3. Official 5h & Weekly Quotas Panel (Gemini Pool + Claude Pool) + const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); + + function createPoolQuotaBlock(poolLabel) { + const title5h = h('span', { text: `5h 限额 (${poolLabel})` }); + const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fill5h = h('div', { className: 'progress-fill' }); + + const titleWk = h('span', { text: `每周限额 (${poolLabel})` }); + const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fillWk = h('div', { className: 'progress-fill' }); + + const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ + h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [title5h, meta5h]), + h('div', { className: 'progress-track' }, [fill5h]), + ]), + h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [titleWk, metaWk]), + h('div', { className: 'progress-track' }, [fillWk]), + ]), + ]); + + return { el, title5h, meta5h, fill5h, titleWk, metaWk, fillWk }; + } + + const geminiQuotaBlock = createPoolQuotaBlock('Gemini'); + const claudeQuotaBlock = createPoolQuotaBlock('Claude & GPT'); + claudeQuotaBlock.el.setAttribute( + 'style', + 'display: flex; flex-direction: column; gap: 8px; margin-top: 3px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' + ); + + const wkFootLeft = h('span', { className: 'text-muted', text: '本周本机: 0 ($0.00)' }); + const wkFootRight = h('span', { className: 'text-muted', text: '' }); + + const quotaPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + h('span', { text: '官方配额与周期监控' }), + ]), + tierBadge, + ]), + geminiQuotaBlock.el, + claudeQuotaBlock.el, + h('div', { className: 'panel-header', style: 'font-size: 11px; padding-top: 2px;' }, [ + wkFootLeft, + wkFootRight, + ]), + ]); + + const overviewInner = h( + 'div', + { + style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', + }, + [matrixEl, ctxPanel, quotaPanel] + ); + const viewScrollbar = CustomScrollbar({ + contentEl: overviewInner, + className: 'view-pane', + }); + + function syncPoolQuotaBlock(block, poolLabel, poolData, fallbackWeekly, isActiveFamily) { + const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; + const used5hVal = has5h ? Number(poolData.usedPct) : 0; + const rem5hVal = has5h ? Number(poolData.remainingPct) : 0; + patchText(block.title5h, `5h 限额 (${poolLabel})`); + patchText( + block.meta5h, + has5h + ? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)` + : '获取失败 (--%)' + ); + patchStyleVar(block.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); + patchClasses(block.fill5h, { + 'tone-warn': used5hVal >= 60 && used5hVal < 85, + 'tone-danger': used5hVal >= 85, + }); + + const wkUsedRaw = + poolData?.weeklyUsedPct ?? (isActiveFamily ? fallbackWeekly?.usedPct : null); + const wkRemRaw = + poolData?.weeklyRemainingPct ?? (isActiveFamily ? fallbackWeekly?.remainingPct : null); + const wkResetRaw = + poolData?.weeklyResetTime || (isActiveFamily ? fallbackWeekly?.resetTime : null); + const hasWk = wkUsedRaw != null && wkRemRaw != null; + const usedWkVal = hasWk ? Number(wkUsedRaw) : 0; + const remWkVal = hasWk ? Number(wkRemRaw) : 0; + + const customTitle = + isActiveFamily && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title + ? fallbackWeekly.title + : `每周限额 (${poolLabel})`; + patchText(block.titleWk, customTitle); + patchText( + block.metaWk, + hasWk + ? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)` + : '获取失败 (--%)' + ); + patchStyleVar(block.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); + patchClasses(block.fillWk, { + 'tone-warn': usedWkVal >= 60 && usedWkVal < 85, + 'tone-danger': usedWkVal >= 85, + }); + } + + let latestData = null; + let isDirty = false; + + function renderData(data) { + if (!data) return; + const active = data.activeConversation || {}; + const ctx = active.context || {}; + const quotas = data.quotas || {}; + + // 1. Matrix + patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) }); + patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s')); + const reason = speedReasonText(active.latestSpeedReason); + patchText( + tpsSub, + reason ? `${active.activeModelShort || 'argon-4'} · ${reason}` : active.activeModelShort || 'argon-4' + ); + + patchText(ttftVal, formatMetric(active.latestTtftSec, 's')); + patchText(ttftSub, `均值 ${formatMetric(active.ttftSummary?.avgSec, 's')}`); + + patchText(avgVal, formatMetric(active.avgTokPerSec, ' tok/s')); + patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`); + + const stepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0); + patchText(costVal, formatUsd(stepCost, { precise: true })); + patchText( + cacheSub, + `缓 ${active.latestCacheHitPct ?? 0}% · 累 ${formatUsd(active.sessionCostUsd || 0)}` + ); + + // 2. Context (Auto Compaction Baseline) + 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; + patchText( + ctxSummaryText, + `${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)` + ); + ctxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } }); + patchText(bdMessages, formatTokens(ctx.messagesTokens || 0)); + patchText(bdSystemTools, formatTokens(ctx.systemToolsTokens || 0)); + patchText(bdMcpTools, formatTokens(ctx.mcpToolsTokens || 0)); + patchText(bdSkills, formatTokens(ctx.skillsTokens || 0)); + patchText(bdSystemPrompt, formatTokens(ctx.systemPromptTokens || 0)); + patchText(bdUserRules, formatTokens(ctx.userRulesTokens || 0)); + + // 3. Quotas (Gemini + Claude & GPT) + patchText( + tierBadge, + `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` + ); + const activePool = quotas.activePool || {}; + const pools = quotas.pools || []; + const weekly = quotas.weekly || {}; + + const geminiPool = + pools.find((p) => p.family === 'Gemini') || + (activePool.family === 'Gemini' ? activePool : null) || + {}; + const claudePool = + pools.find((p) => p.family === 'Claude & GPT' || p.family === 'Claude') || + (activePool.family && activePool.family !== 'Gemini' ? activePool : null) || + {}; + + const activeIsGemini = (activePool.family || 'Gemini') === 'Gemini'; + syncPoolQuotaBlock(geminiQuotaBlock, 'Gemini', geminiPool, weekly, activeIsGemini); + syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, !activeIsGemini); + + patchText( + wkFootLeft, + `本周本机: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0)})` + ); + patchText( + wkFootRight, + data.account?.aiCredits > 0 + ? `AI 积分: ${data.account.aiCredits}` + : `本机调用: ${weekly.calls || 0} 步` + ); + + viewScrollbar.refresh(); + } + + const unsub = telemetryStore.subscribe( + (st) => st.telemetry, + (data) => { + latestData = data; + if (uiStore.getState().activeView !== 'overview') { + isDirty = true; + return; + } + isDirty = false; + renderData(data); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'overview' && isDirty) { + isDirty = false; + if (latestData) { + renderData(latestData); + } + } + } + ); + + onCleanup(() => { + unsub(); + unsubView(); + ctxSegmentBar.destroy(); + viewScrollbar.destroy(); + }); + + return { + el: viewScrollbar.el, + refs: { viewScrollbar }, + }; + }, +}); + +// --- src/views/ConsumptionView.js --- +/** + * @fileoverview View 2: ConsumptionView (全景消耗统计视图). + * Implements the 5-part analytics layout: + * 1. 用量概览 (Total Tokens k/M/B, USD + CNY approx, Input/Output split, Cache Hit % + Saved Cost badge, 4-color bar) + * 2. 历史趋势 (Pure SVG smooth cubic-bezier spline area chart with peak callout and 3 time anchors) + * 3. 热门模型 (Per-model share badge, 4-segment bar, and Input/Cache/Output/Thinking breakdown) + * 4. 数据来源 (SOURCES breakdown with 4-segment bar) + * 5. 按月细分 (12-month stacked vertical bar chart with cost, stacked bars, and k/M/B totals) + */ + + +const TIME_RANGE_OPTIONS = [ + { value: 'today', label: '今天' }, + { value: '24h', label: '1天' }, + { value: '7d', label: '7天' }, + { value: '14d', label: '14天' }, + { value: '30d', label: '30天' }, + { value: 'all', label: '全部' }, + { value: 'custom', label: '自定义' }, +]; + +function createFourSegmentBar() { + const segInput = h('div', { className: 'progress-seg seg-input' }); + const segCached = h('div', { className: 'progress-seg seg-cached' }); + const segOutput = h('div', { className: 'progress-seg seg-output' }); + const segThinking = h('div', { className: 'progress-seg seg-thinking' }); + const el = h('div', { className: 'progress-track cons-seg-bar' }, [ + segInput, + segCached, + segOutput, + segThinking, + ]); + + function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0 }) { + const total = Math.max(1, inputTokens + cacheReadTokens + responseTokens + thinkingTokens); + patchStyleVar(segInput, '--seg-w', `${((inputTokens / total) * 100).toFixed(2)}%`); + patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / total) * 100).toFixed(2)}%`); + patchStyleVar(segOutput, '--seg-w', `${((responseTokens / total) * 100).toFixed(2)}%`); + patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / total) * 100).toFixed(2)}%`); + } + + return { el, update }; +} + +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]; + const p1 = points[i + 1]; + const cpx1 = p0.x + (p1.x - p0.x) * 0.45; + const cpx2 = p1.x - (p1.x - p0.x) * 0.45; + d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; + } + return d; +} + +function createTrendAreaChart() { + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('viewBox', '0 0 460 116'); + svg.setAttribute('class', 'trend-svg'); + svg.setAttribute('aria-hidden', 'true'); + + const defs = document.createElementNS(SVG_NS, 'defs'); + const grad = document.createElementNS(SVG_NS, 'linearGradient'); + grad.setAttribute('id', 'trend-area-grad'); + grad.setAttribute('x1', '0'); + grad.setAttribute('y1', '0'); + grad.setAttribute('x2', '0'); + grad.setAttribute('y2', '1'); + + const stop1 = document.createElementNS(SVG_NS, 'stop'); + stop1.setAttribute('offset', '0%'); + stop1.setAttribute('stop-color', 'var(--ctx-cached)'); + stop1.setAttribute('stop-opacity', '0.36'); + + const stop2 = document.createElementNS(SVG_NS, 'stop'); + stop2.setAttribute('offset', '100%'); + stop2.setAttribute('stop-color', 'var(--ctx-cached)'); + stop2.setAttribute('stop-opacity', '0.0'); + + grad.appendChild(stop1); + grad.appendChild(stop2); + defs.appendChild(grad); + svg.appendChild(defs); + + // Subtle grid lines + const gridGroup = document.createElementNS(SVG_NS, 'g'); + gridGroup.setAttribute('class', 'trend-grid'); + for (const y of [26, 62, 98]) { + const line = document.createElementNS(SVG_NS, 'line'); + line.setAttribute('x1', '10'); + line.setAttribute('y1', String(y)); + line.setAttribute('x2', '450'); + line.setAttribute('y2', String(y)); + gridGroup.appendChild(line); + } + for (const x of [118, 230, 342]) { + const line = document.createElementNS(SVG_NS, 'line'); + line.setAttribute('x1', String(x)); + line.setAttribute('y1', '16'); + line.setAttribute('x2', String(x)); + line.setAttribute('y2', '98'); + gridGroup.appendChild(line); + } + svg.appendChild(gridGroup); + + const areaPath = document.createElementNS(SVG_NS, 'path'); + areaPath.setAttribute('fill', 'url(#trend-area-grad)'); + svg.appendChild(areaPath); + + const linePath = document.createElementNS(SVG_NS, 'path'); + linePath.setAttribute('class', 'trend-line'); + linePath.setAttribute('fill', 'none'); + svg.appendChild(linePath); + + const peakDot = document.createElementNS(SVG_NS, 'circle'); + peakDot.setAttribute('r', '3'); + peakDot.setAttribute('class', 'trend-peak-dot'); + svg.appendChild(peakDot); + + const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); + const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]); + + let lastLineD = ''; + + function update(series = []) { + const slots = series.length >= 2 ? series : [ + { label: '00:00', tokens: 0 }, + { label: '06:00', tokens: 0 }, + { label: '12:00', tokens: 0 }, + ]; + let maxTokens = 0; + let peakIdx = 0; + for (let i = 0; i < slots.length; i++) { + const t = Number(slots[i].tokens || 0); + if (t >= maxTokens) { + maxTokens = t; + peakIdx = i; + } + } + + const leftX = 12; + const rightX = 448; + const topY = 26; + const bottomY = 98; + const spanX = rightX - leftX; + const spanY = bottomY - topY; + const denom = Math.max(1, maxTokens); + + const pts = slots.map((s, idx) => { + const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX; + const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0; + const y = bottomY - ratio * spanY; + return { x, y }; + }); + + const lineD = buildSmoothSplinePath(pts); + if (lineD !== lastLineD) { + lastLineD = lineD; + const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`; + patchAttr(linePath, 'd', lineD); + patchAttr(areaPath, 'd', areaD); + } + + const peakPt = pts[peakIdx] || { x: 230, y: bottomY }; + patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); + patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); + + patchText(peakPill, formatTokensPrecise(maxTokens)); + const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100)); + patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + } + + return { el: chartWrap, update }; +} + +const ConsumptionView = defineComponent({ + name: 'ConsumptionView', + setup({ onCleanup }) { + // Default to 'today' if store is on initial 'all' or keep user's selection + const timeFilterSwitch = SegmentedControl({ + ariaLabel: '消耗统计时间范围', + modelValue: telemetryStore.getState().selectedTimeRange, + options: TIME_RANGE_OPTIONS, + onUpdateModelValue: (nextRange) => { + telemetryStore.setState({ selectedTimeRange: nextRange }); + fetchTelemetry({ force: false }); + }, + }); + + const startPicker = CustomDateTimePicker({ + modelValue: telemetryStore.getState().customStartMs, + onUpdateModelValue: (ms) => { + telemetryStore.setState({ customStartMs: ms }); + }, + }); + + const endPicker = CustomDateTimePicker({ + modelValue: telemetryStore.getState().customEndMs, + onUpdateModelValue: (ms) => { + telemetryStore.setState({ customEndMs: ms }); + }, + }); + + const applyCustomBtn = h( + 'button', + { + type: 'button', + className: 'btn-primary', + style: 'height: 26px; padding: 0 10px;', + onClick: () => { + telemetryStore.setState({ selectedTimeRange: 'custom' }); + fetchTelemetry({ force: true }); + }, + }, + [createSvgIcon('check', { size: 12 }), h('span', { text: '筛选' })] + ); + + const customRangeBar = h( + 'div', + { + style: + 'display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs);', + hidden: true, + }, + [ + startPicker.el, + h('span', { className: 'text-muted', text: '至' }), + endPicker.el, + applyCustomBtn, + ] + ); + + // --- Section 1: 用量概览 (Compact Integrated Overview) --- + 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 调用' }); + const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); + const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '≈ ¥0' }); + + const cacheHitPctEl = h('strong', { className: 'cons-hero-cache text-mono', text: '0%' }); + const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '命中 0' }); + + 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 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' }); + const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '内容生成 0 · 思考推理 0' }); + + const overviewSegBar = createFourSegmentBar(); + + const overviewPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header cons-overview-head' }, [ + h('span', { className: 'panel-title' }, [ + h('span', { text: '用量概览' }), + dateSpanBadge, + ]), + timeFilterSwitch.el, + ]), + customRangeBar, + h('div', { className: 'cons-box cons-unified-matrix' }, [ + h('div', { className: 'cons-split-3' }, [ + h('div', { className: 'cons-col' }, [ + h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token 数' }), + h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '预估费用' }), + h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('span', { className: 'legend-left', style: 'font-size: 11px;' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存命中率' }), + ]), + h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), + ]), + ]), + h('div', { className: 'cons-split-2 cons-matrix-bottom' }, [ + h('div', { className: 'cons-col' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输入用量' }), + inputMainTokens, + ]), + inputSharePct, + ]), + inputSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输出用量' }), + outputMainTokens, + ]), + outputSharePct, + ]), + outputSubText, + ]), + ]), + ]), + overviewSegBar.el, + ]); + + // --- Section 2: 历史趋势 (Historical Trend SVG Spline Area Chart) --- + const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' }); + const trendChart = createTrendAreaChart(); + const anchorStartTime = h('span', { className: 'text-muted text-mono', text: '00:00' }); + const anchorStartVal = h('strong', { className: 'text-mono', text: '0' }); + const anchorMidTime = h('span', { className: 'text-muted text-mono', text: '06:00' }); + const anchorMidVal = h('strong', { className: 'text-mono', text: '0' }); + const anchorEndTime = h('span', { className: 'text-muted text-mono', text: '12:00' }); + const anchorEndVal = h('strong', { className: 'text-mono', text: '0' }); + + const trendPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '历史趋势' }), + trendRangeBadge, + ]), + trendChart.el, + h('div', { className: 'trend-anchors' }, [ + h('div', { className: 'trend-anchor-col' }, [anchorStartTime, anchorStartVal]), + h('div', { className: 'trend-anchor-col is-center' }, [anchorMidTime, anchorMidVal]), + h('div', { className: 'trend-anchor-col is-end' }, [anchorEndTime, anchorEndVal]), + ]), + ]); + + // --- Section 3: 热门模型 (Popular Models Breakdown) --- + const modelsListEl = h('div', { className: 'cons-item-list' }); + const modelsPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '热门模型' }), + ]), + modelsListEl, + ]); + + // --- Section 4: 数据来源 --- + const sourcesListEl = h('div', { className: 'cons-item-list' }); + const sourcesPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '数据来源' }), + ]), + sourcesListEl, + ]); + + // --- Section 5: 按月细分 (12-Month Stacked Bar Chart) --- + const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' }); + const monthlyCols = Array.from({ length: 12 }, (_, idx) => { + const costText = h('span', { className: 'month-cost text-mono', text: '' }); + const barThink = h('div', { className: 'month-seg seg-thinking' }); + const barOut = h('div', { className: 'month-seg seg-output' }); + const barCache = h('div', { className: 'month-seg seg-cached' }); + const barIn = h('div', { className: 'month-seg seg-input' }); + const stackWrap = h('div', { className: 'month-stack' }, [ + barThink, + barOut, + barCache, + barIn, + ]); + const zeroDot = h('span', { className: 'month-zero-dot' }); + const monthLabel = h('span', { className: 'month-label', text: `${idx + 1}月` }); + const tokText = h('span', { className: 'month-tok text-mono', text: '' }); + + const colEl = h('div', { className: 'month-col' }, [ + costText, + h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), + monthLabel, + tokText, + ]); + return { + el: colEl, + costText, + stackWrap, + zeroDot, + barThink, + barOut, + barCache, + barIn, + monthLabel, + tokText, + }; + }); + + const monthlyPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '按月细分' }), + monthlyYearBadge, + ]), + h( + 'div', + { className: 'monthly-grid' }, + monthlyCols.map((c) => c.el) + ), + h('div', { className: 'monthly-legend' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + h('span', { text: '输入' }), + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存' }), + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + h('span', { text: '输出' }), + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + h('span', { text: '思考' }), + ]), + ]), + ]); + + const scrollInner = h( + 'div', + { + style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: var(--space-3);', + }, + [ + overviewPanel, + trendPanel, + modelsPanel, + sourcesPanel, + monthlyPanel, + ] + ); + + const viewScrollbar = CustomScrollbar({ + contentEl: scrollInner, + className: 'view-pane', + }); + + function createBreakdownItemRow() { + const nameEl = h('strong', { className: 'cons-row-title' }); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const segBar = createFourSegmentBar(); + + const inVal = h('strong', { className: 'text-mono' }); + const cacheVal = h('strong', { className: 'text-mono' }); + const outVal = h('strong', { className: 'text-mono' }); + const thinkVal = h('strong', { className: 'text-mono' }); + const callsVal = h('strong', { className: 'text-mono' }); + + const rowEl = h('div', { className: 'cons-item-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [ + pctBadge, + totalTokEl, + costEl, + ]), + ]), + segBar.el, + h('div', { className: 'cons-item-foot' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + h('span', { text: '输入 ' }), + inVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存 ' }), + cacheVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + h('span', { text: '输出 ' }), + outVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + h('span', { text: '思考 ' }), + thinkVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { text: '调用 ' }), + callsVal, + ]), + ]), + ]); + + return { + el: rowEl, + refs: { nameEl, pctBadge, totalTokEl, costEl, segBar, inVal, cacheVal, outVal, thinkVal, callsVal }, + }; + } + + function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) { + patchText(refs.nameEl, item.label || item.name || item.shortName || '—'); + const total = Number(item.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : ''); + patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader); + patchText(refs.costEl, formatUsd(item.costUsd || 0)); + + const responseTok = + item.responseTokens != null + ? Number(item.responseTokens) + : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); + const thinkingTok = Number(item.thinkingTokens || 0); + + refs.segBar.update({ + inputTokens: Number(item.inputTokens || 0), + cacheReadTokens: Number(item.cacheReadTokens || 0), + responseTokens: responseTok, + thinkingTokens: thinkingTok, + }); + + patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); + patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); + patchText(refs.outVal, formatTokensPrecise(responseTok)); + patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); + patchText(refs.callsVal, String(Number(item.calls || 0))); + } + + let latestSlice = null; + let isDirty = false; + + function renderConsumptionData(slice) { + if (!slice) return; + timeFilterSwitch.setValue(slice.range); + patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); + startPicker.setValue(slice.customStartMs); + endPicker.setValue(slice.customEndMs); + + const cons = slice.consumption || {}; + const preset = + slice.range !== 'custom' && cons.presets?.[slice.range] + ? cons.presets[slice.range] + : null; + const acct = preset?.account || cons.account || {}; + const rangeInfo = cons.selectedRange || {}; + + // 1. Overview + patchText(dateSpanBadge, formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs)); + const totalTokens = Number(acct.totalTokens || 0); + const inputTokens = Number(acct.inputTokens || 0); + const cacheTokens = Number(acct.cacheReadTokens || 0); + const outputTokens = Number(acct.outputTokens || 0); + const responseTokens = Number(acct.responseTokens || 0); + const thinkingTokens = Number(acct.thinkingTokens || 0); + const costUsd = Number(acct.costUsd || 0); + + patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); + patchText(heroTotalCalls, `${acct.calls || 0} 调用`); + patchText(heroCostUsd, formatUsd(costUsd)); + patchText(heroCostCny, formatCnyApprox(costUsd)); + + 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; + patchText(inputSharePct, `${inPct}%`); + patchText(inputMainTokens, formatTokensPrecise(inputTokens)); + patchText( + inputSubText, + `直接输入 ${formatTokensPrecise(inputTokens)} · 缓存读取 ${formatTokensPrecise(cacheTokens)}` + ); + + patchText(outputSharePct, `${outPct}%`); + patchText(outputMainTokens, formatTokensPrecise(outputTokens)); + patchText( + outputSubText, + `内容生成 ${formatTokensPrecise(responseTokens)} · 思考推理 ${formatTokensPrecise(thinkingTokens)}` + ); + + overviewSegBar.update({ + inputTokens, + cacheReadTokens: cacheTokens, + responseTokens, + thinkingTokens, + }); + + // 2. Historical Trend + patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间'); + const trendSeries = cons.trendSeries || []; + trendChart.update(trendSeries); + if (trendSeries.length > 0) { + const first = trendSeries[0]; + const mid = trendSeries[Math.floor(trendSeries.length / 2)]; + const last = trendSeries[trendSeries.length - 1]; + patchText(anchorStartTime, first.label); + patchText(anchorStartVal, formatTokensPrecise(first.tokens)); + patchText(anchorMidTime, mid.label); + patchText(anchorMidVal, formatTokensPrecise(mid.tokens)); + patchText(anchorEndTime, last.label); + patchText(anchorEndVal, formatTokensPrecise(last.tokens)); + } + + // 3. Popular Models + const models = (slice.modelBreakdown || []) + .slice() + .sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0)); + const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0); + + patchKeyedList(modelsListEl, models, { + keyFn: (m) => m.label || m.shortName, + sigFn: (m) => + `${m.label}:${m.totalTokens}:${m.costUsd}:${m.calls}:${modelsTotalTok}`, + createRow: createBreakdownItemRow, + updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true), + }); + + // 4. Sources Breakdown + const sources = cons.sourcesBreakdown || []; + const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); + patchKeyedList(sourcesListEl, sources, { + keyFn: (s) => s.name, + sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.calls}:${sourcesTotalTok}`, + createRow: createBreakdownItemRow, + updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true), + }); + + // 5. Monthly Breakdown + const monthlyYear = cons.monthlyYear || new Date().getFullYear(); + const currentMonthIdx = new Date().getMonth(); + patchText(monthlyYearBadge, String(monthlyYear)); + const monthlySeries = cons.monthlySeries || []; + const maxMonthTokens = Math.max( + 1, + ...monthlySeries.map((m) => Number(m.totalTokens || 0)) + ); + + for (let i = 0; i < 12; i++) { + const col = monthlyCols[i]; + const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0 }; + const mTot = Number(m.totalTokens || 0); + const hasData = mTot > 0; + + patchClasses(col.monthLabel, { 'is-current': i === currentMonthIdx }); + patchAttr(col.stackWrap, 'hidden', !hasData); + patchAttr(col.zeroDot, 'hidden', hasData); + + if (!hasData) { + patchText(col.costText, ''); + patchText(col.tokText, ''); + } else { + const cVal = Number(m.costUsd || 0); + patchText(col.costText, cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); + patchText(col.tokText, formatTokensPrecise(mTot)); + + const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); + patchStyleVar(col.stackWrap, '--bar-h', `${totalHeightPct.toFixed(1)}%`); + + const inPctM = (Number(m.inputTokens || 0) / mTot) * 100; + const cachePctM = (Number(m.cacheReadTokens || 0) / mTot) * 100; + const outPctM = (Number(m.responseTokens || 0) / mTot) * 100; + const thinkPctM = (Number(m.thinkingTokens || 0) / mTot) * 100; + + patchStyleVar(col.barIn, '--seg-h', `${inPctM.toFixed(1)}%`); + patchStyleVar(col.barCache, '--seg-h', `${cachePctM.toFixed(1)}%`); + patchStyleVar(col.barOut, '--seg-h', `${outPctM.toFixed(1)}%`); + patchStyleVar(col.barThink, '--seg-h', `${thinkPctM.toFixed(1)}%`); + } + } + + viewScrollbar.refresh(); + } + + const unsub = telemetryStore.subscribe( + (st) => ({ + range: st.selectedTimeRange, + customStartMs: st.customStartMs, + customEndMs: st.customEndMs, + consumption: st.telemetry?.consumption, + modelBreakdown: st.telemetry?.modelBreakdown, + }), + (slice) => { + latestSlice = slice; + if (uiStore.getState().activeView !== 'consumption') { + isDirty = true; + return; + } + isDirty = false; + renderConsumptionData(slice); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'consumption' && isDirty) { + isDirty = false; + if (latestSlice) { + renderConsumptionData(latestSlice); + } + } + } + ); + + onCleanup(() => { + unsub(); + unsubView(); + timeFilterSwitch.destroy(); + startPicker.destroy(); + endPicker.destroy(); + viewScrollbar.destroy(); + }); + + return { + el: viewScrollbar.el, + refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar }, + }; + }, +}); + +// --- src/views/StepsDetailView.js --- +/** + * @fileoverview View 3: StepsDetailView (步骤明细与按模型汇总视图). + * Uses patchKeyedList for incremental row reconciliation without innerHTML resets, + * wraps tables in bespoke CustomScrollbar (zero native OS scrollbars), and provides + * a live row inspector bar replacing native browser title tooltips. + */ + + +const StepsDetailView = defineComponent({ + name: 'StepsDetailView', + setup({ onCleanup }) { + const subTabSwitch = SegmentedControl({ + ariaLabel: '明细表视图切换', + modelValue: uiStore.getState().stepsSubTab, + options: [ + { value: 'steps', label: '单步测速 (0步)' }, + { value: 'models', label: '按模型汇总' }, + ], + onUpdateModelValue: (nextTab) => { + uiStore.setState({ stepsSubTab: nextTab }); + }, + }); + + const stepsTbody = h('tbody'); + const stepsTablePane = h('div', { className: 'table-viewport' }, [ + h('table', { className: 'data-table' }, [ + h('thead', {}, [ + h('tr', {}, [ + h('th', { text: '步' }), + h('th', { text: '模型' }), + h('th', { text: '速度' }), + h('th', { text: '首Token' }), + h('th', { text: '上下文/输出' }), + h('th', { text: '缓存' }), + h('th', { text: '消费' }), + ]), + ]), + stepsTbody, + ]), + ]); + const stepsScroll = CustomScrollbar({ + contentEl: stepsTablePane, + className: 'table-scroll-host', + }); + + const modelsTbody = h('tbody'); + const modelsTablePane = h('div', { className: 'table-viewport' }, [ + h('table', { className: 'data-table' }, [ + h('thead', {}, [ + h('tr', {}, [ + h('th', { text: '模型' }), + h('th', { text: '次数' }), + h('th', { text: '均速' }), + h('th', { text: '总 Token' }), + h('th', { text: '折算费用' }), + ]), + ]), + modelsTbody, + ]), + ]); + const modelsScroll = CustomScrollbar({ + contentEl: modelsTablePane, + className: 'table-scroll-host', + }); + modelsScroll.el.setAttribute('hidden', ''); + + const panelEl = h( + 'section', + { + className: 'panel', + style: 'flex: 1; min-height: 0; display: flex; flex-direction: column;', + }, + [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('table', { size: 13 }), + h('span', { text: '全量测速与计费矩阵' }), + ]), + subTabSwitch.el, + ]), + stepsScroll.el, + modelsScroll.el, + ] + ); + + const rootEl = h('div', { className: 'view-pane' }, [panelEl]); + + const unsubUi = uiStore.subscribe( + (st) => st.stepsSubTab, + (tab) => { + subTabSwitch.setValue(tab); + patchAttr(stepsScroll.el, 'hidden', tab !== 'steps'); + patchAttr(modelsScroll.el, 'hidden', tab !== 'models'); + if (tab === 'steps') stepsScroll.refresh(); + else modelsScroll.refresh(); + } + ); + + let latestSlice = null; + let isDirty = false; + + function renderStepsData(slice) { + if (!slice) return; + const steps = slice.recentSteps || []; + const models = slice.modelBreakdown || []; + + subTabSwitch.setProps({ + options: [ + { value: 'steps', label: `单步测速 (${steps.length}步)` }, + { value: 'models', label: `按模型汇总 (${slice.rangeLabel})` }, + ], + }); + + patchKeyedList(stepsTbody, steps, { + keyFn: (st) => `${slice.cascadeId || 'conv'}-${st.stepIndex}`, + sigFn: (st) => + `${st.stepIndex}:${st.modelShort}:${st.tokPerSec}:${st.ttftSec}:${st.contextTokens}:${st.outputTokens}:${st.cacheHitPct}:${st.costUsd}:${st.selectedSpeedReason}`, + createRow: () => { + const stepNumText = h('span'); + const compIcon = createSvgIcon('bolt', { size: 11, className: 'text-muted' }); + const tdStep = h('td', {}, [stepNumText, compIcon]); + + const tdModel = h('td'); + const speedMain = h('strong', { + className: 'cell-value accent-speed', + style: 'font-size: 11px;', + }); + const speedReason = h('div', { className: 'text-muted', style: 'font-size: 9.5px;' }); + const tdSpeed = h('td', {}, [speedMain, speedReason]); + + const tdTtft = h('td'); + const tdCtx = h('td'); + const tdCache = h('td', { + className: 'cell-value accent-ok', + style: 'font-size: 11px;', + }); + const tdCost = h('td', { style: 'font-weight: 600;' }); + + const tr = h('tr', {}, [tdStep, tdModel, tdSpeed, tdTtft, tdCtx, tdCache, tdCost]); + return { + el: tr, + refs: { + stepNumText, + compIcon, + tdModel, + speedMain, + speedReason, + tdTtft, + tdCtx, + tdCache, + tdCost, + }, + }; + }, + updateRow: (refs, st) => { + patchText(refs.stepNumText, `#${Number(st.stepIndex)} `); + patchAttr(refs.compIcon, 'hidden', !st.isCompactionStep); + patchText(refs.tdModel, st.modelShort || '—'); + + patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s')); + const reason = speedReasonText(st.selectedSpeedReason); + patchText(refs.speedReason, reason); + patchAttr(refs.speedReason, 'hidden', !reason); + + patchText(refs.tdTtft, formatMetric(st.ttftSec, 's')); + patchText( + refs.tdCtx, + `${formatTokens(st.contextTokens)} / +${Number(st.outputTokens || 0)}` + ); + patchText(refs.tdCache, `${Number(st.cacheHitPct ?? 0)}%`); + + const costVal = Number(st.costUsd || 0); + patchText(refs.tdCost, formatUsd(costVal, { precise: true })); + patchClasses(refs.tdCost, { 'accent-speed': costVal >= 0.15 }); + }, + }); + + patchKeyedList(modelsTbody, models, { + keyFn: (m) => m.label || m.shortName, + sigFn: (m) => + `${m.shortName}:${m.calls}:${m.avgTokPerSec}:${m.totalTokens}:${m.costUsd}:${m.speedSummary?.sampleCount}`, + createRow: () => { + const tdName = h('td', { style: 'font-weight: 600;' }); + const tdCalls = h('td'); + const speedMain = h('div'); + const speedSub = h('div', { className: 'text-muted', style: 'font-size: 9.5px;' }); + const tdSpeed = h('td', {}, [speedMain, speedSub]); + const tdTokens = h('td'); + const tdCost = h('td', { style: 'font-weight: 600;' }); + const tr = h('tr', {}, [tdName, tdCalls, tdSpeed, tdTokens, tdCost]); + return { + el: tr, + refs: { tdName, tdCalls, speedMain, speedSub, tdTokens, tdCost }, + }; + }, + updateRow: (refs, m) => { + patchText(refs.tdName, m.shortName || m.label); + patchText(refs.tdCalls, String(Number(m.calls || 0))); + 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 || 0, { estimated: m.isEstimatedPrice })); + }, + }); + + stepsScroll.refresh(); + modelsScroll.refresh(); + } + + const unsubTelemetry = telemetryStore.subscribe( + (st) => ({ + cascadeId: st.telemetry?.activeConversation?.cascadeId, + recentSteps: st.telemetry?.activeConversation?.recentSteps, + modelBreakdown: st.telemetry?.modelBreakdown, + rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间', + }), + (slice) => { + latestSlice = slice; + if (uiStore.getState().activeView !== 'steps') { + isDirty = true; + return; + } + isDirty = false; + renderStepsData(slice); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'steps' && isDirty) { + isDirty = false; + if (latestSlice) { + renderStepsData(latestSlice); + } + } + } + ); + + onCleanup(() => { + unsubUi(); + unsubTelemetry(); + unsubView(); + subTabSwitch.destroy(); + stepsScroll.destroy(); + modelsScroll.destroy(); + }); + + return { + el: rootEl, + refs: { stepsTbody, modelsTbody, subTabSwitch, stepsScroll, modelsScroll }, + }; + }, +}); + +// --- src/views/SettingsView.js --- +/** + * @fileoverview View 4: SettingsView (系统设置视图). + * Replaces all native form controls () with + * bespoke CustomSelect and CustomNumberInput components. + */ + + +const WEEKLY_MODE_OPTIONS = [ + { value: 'official', label: '官方云端周限额 (与 Models & Usage 同步)' }, + { value: 'custom_tokens', label: '按自定义每周 Token 预算计算百分比' }, + { value: 'custom_cost', label: '按自定义每周美元 ($) 预算计算百分比' }, +]; + +const SettingsView = defineComponent({ + name: 'SettingsView', + setup({ onCleanup }) { + let draftMode = 'official'; + let draftTokens = 150000000; + let draftCost = 100; + + const modeSelect = CustomSelect({ + modelValue: draftMode, + icon: 'sliders', + options: WEEKLY_MODE_OPTIONS, + onUpdateModelValue: (val) => { + draftMode = val; + }, + }); + + 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 saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); + + const saveBtn = h( + 'button', + { + type: 'button', + className: 'btn-primary', + onClick: async () => { + patchText(saveStatusText, '正在异步保存...'); + await saveSettingsPatch({ + weeklyLimitMode: draftMode, + weeklyTokenBudget: draftTokens, + weeklyCostBudget: draftCost, + }); + patchText(saveStatusText, '设置已生效'); + setTimeout(() => patchText(saveStatusText, ''), 1500); + }, + }, + [createSvgIcon('check', { size: 13 }), h('span', { text: '保存参数设置' })] + ); + + const budgetPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('sliders', { size: 13 }), + h('span', { text: '监控口径与周限额基准设置' }), + ]), + saveStatusText, + ]), + 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 预算基准 (步进 1M)' }), + tokenBudgetInput.el, + ]), + h('div', { className: 'form-row' }, [ + h('span', { className: 'form-label', text: '每周费用预算基准 (USD $, 步进 $5)' }), + costBudgetInput.el, + ]), + ]), + h('div', { style: 'display: flex; justify-content: flex-end;' }, [saveBtn]), + ]); + + const rootEl = h('div', { className: 'view-pane' }, [budgetPanel]); + + let latestSettings = null; + let isDirty = false; + + function renderSettings(settings) { + if (!settings) return; + draftMode = + settings.weeklyLimitMode === 'custom_tokens' || + settings.weeklyLimitMode === 'custom_cost' + ? settings.weeklyLimitMode + : 'official'; + draftTokens = Number(settings.weeklyTokenBudget || 150000000); + draftCost = Number(settings.weeklyCostBudget || 100); + modeSelect.setValue(draftMode); + tokenBudgetInput.setValue(draftTokens); + costBudgetInput.setValue(draftCost); + } + + const unsub = telemetryStore.subscribe( + (st) => st.telemetry?.settings, + (settings) => { + latestSettings = settings; + if (uiStore.getState().activeView !== 'settings') { + isDirty = true; + return; + } + isDirty = false; + renderSettings(settings); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'settings' && isDirty) { + isDirty = false; + if (latestSettings) { + renderSettings(latestSettings); + } + } + } + ); + + onCleanup(() => { + unsub(); + unsubView(); + modeSelect.destroy(); + tokenBudgetInput.destroy(); + costBudgetInput.destroy(); + }); + + return { + el: rootEl, + refs: { modeSelect, tokenBudgetInput, costBudgetInput }, + }; + }, +}); + +// --- src/App.js --- +/** + * @fileoverview Root Application Shell (App.js). + * Combines the compact dual-layer header (TopSessionHeader + TopLongPillNav) + * and single-viewport functional views. + */ + + +const App = defineComponent({ + name: 'App', + setup({ onCleanup }) { + const sessionHeader = TopSessionHeader(); + const topPillNav = TopLongPillNav({ + modelValue: uiStore.getState().activeView, + items: VIEW_TABS, + onUpdateModelValue: (nextView) => { + uiStore.setState({ activeView: nextView }); + }, + }); + + const overviewView = LiveOverviewView(); + const consumptionView = ConsumptionView(); + const stepsView = StepsDetailView(); + const settingsView = SettingsView(); + + const viewMap = { + overview: overviewView.el, + consumption: consumptionView.el, + steps: stepsView.el, + settings: settingsView.el, + }; + + const stageEl = h('div', { className: 'viewport-stage' }, [ + overviewView.el, + consumptionView.el, + stepsView.el, + settingsView.el, + ]); + + const shellEl = h('main', { className: 'app-shell' }, [ + h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]), + stageEl, + ]); + + const unsubUi = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + topPillNav.setValue(activeView); + for (const [key, paneEl] of Object.entries(viewMap)) { + patchAttr(paneEl, 'hidden', key !== activeView); + } + if (activeView === 'overview') { + overviewView.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'consumption') { + consumptionView.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'steps') { + stepsView.refs?.stepsScroll?.refresh(); + stepsView.refs?.modelsScroll?.refresh(); + } + } + ); + + const unsubStepCount = telemetryStore.subscribe( + (st) => st.telemetry?.activeConversation?.stepCount ?? 0, + (stepCount) => { + topPillNav.setProps({ + items: VIEW_TABS.map((t) => + t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t + ), + }); + } + ); + + onCleanup(() => { + unsubUi(); + unsubStepCount(); + sessionHeader.destroy(); + topPillNav.destroy(); + overviewView.destroy(); + consumptionView.destroy(); + stepsView.destroy(); + settingsView.destroy(); + }); + + return { + el: shellEl, + refs: { + sessionHeader, + topPillNav, + overviewView, + consumptionView, + stepsView, + settingsView, + }, + }; + }, +}); + +// --- src/main.js --- +/** + * @fileoverview Async entry point for Antigravity Usage & Speed Monitor. + */ + + +async function bootstrapApp(mountTarget = document.getElementById('app-root')) { + if (!mountTarget) return null; + const appInstance = App(); + mountTarget.appendChild(appInstance.el); + const stopPolling = startAsyncTelemetryLoop(2000); + return { + appInstance, + stopPolling, + }; } function init() { - bindEvents(); - refreshTelemetry(); - setInterval(refreshTelemetry, 2000); + if (typeof document === 'undefined') return; + if (document.readyState === 'loading' && typeof document.addEventListener === 'function') { + document.addEventListener('DOMContentLoaded', () => { + bootstrapApp(); + }); + } else { + bootstrapApp(); + } } init(); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 1935622..82cc40d 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,274 +4,11 @@ 测速与额度监控 - + -
- -
-
- 当前会话 - -
-
- 实时 2s - -
-
- - -
-
- - - — - - 首Token — - 均速 — 有效 0/0 步 - | - 本步 $0.000 · 累计 $0.00 - 缓存 0% - | - - 上下文 - - -
- -
- - ⇄ - argon-4 - - - 今日 0 · ≈$0.00 - -
-
TPS = 总输出 Token ÷ 请求总耗时(含等待与思考)
-
- - -
- -
-
- - - 0 / 256k (0%) - › - -
-
-
-
-
-
-
- - - -
- -
- - -
-
- -
- - - - - - -
-
- - - -
- -
-
- 💬 本对话消耗 - 0 步 -
-
- 0 - $0.00 -
-
入 0 · 缓 0 · 出 0
-
占同期本机 0%
-
- - - -
-
- -
- - -
-
- - → -
- - -
-
- 5h 限额 - - -- 后重置 - -- - -
-
-
-
-
- - -
- - -
-
- 每周限额 (Gemini) - - -- 后重置 - -- - -
-
-
-
-
- 本周本机: 0 ($0.00) - -
-
- -
- - -
-
-
- - - - - - -
- - +
+ diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index a5d4ef4..e0af73a 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -1,5 +1,5 @@ // Backend for Antigravity Usage & Speed Monitor Sidecar Extension. -import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, promises as fsPromises, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -12,6 +12,11 @@ const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.dat const SETTINGS_FILE = join(DATA_DIR, 'settings.json'); const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json'); const CONVERSATIONS_DIR = join(homedir(), '.gemini', 'antigravity', 'conversations'); +const DEEP_STATS_CACHE_CANDIDATES = [ + join(homedir(), '.gemini', 'antigravity-ide', 'brain', '.deep_stats_cache.json'), + join(homedir(), '.gemini', 'antigravity', 'brain', '.deep_stats_cache.json'), + join(homedir(), '.gemini', 'antigravity-idea', 'brain', '.deep_stats_cache.json'), +]; const LS_ADDR = process.env.ANTIGRAVITY_LS_ADDRESS; const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN; @@ -28,17 +33,69 @@ const DEFAULT_SETTINGS = { // Gemini 4 Argon official price (until 2026-11-30): Input $2.00 / Cache $0.10 / Output $10.00 // Ultra 5h Pool (100%) = $25.00 USD | Ultra Weekly Pool (100%) = $100.00 USD const MODEL_PRICING = { + // Gemini 4 & 3.x & 2.5 Official Catalog Pricing (USD / 1M tokens) '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-3.8-flash-high': { input: 0.30, cache: 0.03, output: 2.5, short: 'flash-3.8-high', family: 'Gemini' }, - 'gemini-3.8-flash-medium': { input: 0.30, cache: 0.03, output: 2.5, short: 'flash-3.8', family: 'Gemini' }, - 'gemini-3.8-flash-low': { input: 0.15, cache: 0.015, output: 1.0, short: 'flash-3.8-low', family: 'Gemini' }, - 'gemini-2.5-flash-lite': { input: 0.10, cache: 0.01, output: 0.40, short: 'flash-2.5-lite', family: 'Gemini' }, - 'gemini-2.5-flash': { input: 0.30, cache: 0.03, output: 2.5, short: 'flash-2.5', 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': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', 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': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6', 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': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' }, + 'gemini-3.1-flash-lite': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' }, + 'gemini-3-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' }, 'gemini-2.5-pro': { input: 1.25, cache: 0.125, output: 10.0, short: 'pro-2.5', family: 'Gemini' }, - 'claude-opus-4-6-thinking': { input: 5.0, cache: 0.50, output: 25.0, short: 'opus', family: 'Claude' }, - 'claude-sonnet-4-6': { input: 3.0, cache: 0.30, output: 15.0, short: 'sonnet', family: 'Claude' }, + '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 Official Catalog Pricing + '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': { 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': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', 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': { 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 Official Catalog Pricing + '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-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' }, }; @@ -63,6 +120,7 @@ const CACHE_SCHEMA_VERSION = 'v9-unified-throughput'; let trajectoryCache = Object.fromEntries(Object.entries(loadJson(CACHE_FILE, {})).map(([id, entry]) => [ id, { ...entry, steps: (entry.steps || []).map(normalizeCachedStep) }, ])); +let externalDeepStatsMemo = { sig: '', convos: new Map() }; const inFlightRequests = new Map(); let quotaSummaryCache = { ts: 0, data: null, error: null }; @@ -170,17 +228,50 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide return 'Other'; } -function resolveModelInfo(rawModelKey, dynamicModelMap, apiProvider = '') { - const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey] || { - modelId: rawModelKey || 'unknown', - label: rawModelKey || 'Unknown Model', - }; - const explicitPricing = MODEL_PRICING[dyn.modelId]; +function getBaseModelLabel(label = '') { + return String(label || '') + .replace(/\s*\((?:High|Medium|Low|Thinking|Extra Low)\)\s*$/i, '') + .trim() || String(label || 'Unknown Model'); +} + +function formatGenericModelSlug(slug = '') { + const s = String(slug || '').trim().replace(/^session-display:/i, ''); + if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return ''; + const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon)(?:-(lite))?/i); + if (m) { + const ver = m[1]; + const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase(); + const lite = m[3] ? ' Lite' : ''; + return `Gemini ${ver} ${tier}${lite}`; + } + return ''; +} + +function resolveModelInfo(rawModelKey, dynamicModelMap, apiProvider = '', modelDisplayName = '') { + const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey]; + const cleanRawFallback = + rawModelKey && !/^MODEL_PLACEHOLDER_/i.test(String(rawModelKey)) ? rawModelKey : ''; + const derivedDisplay = + modelDisplayName || + dyn?.label || + formatGenericModelSlug(rawModelKey) || + cleanRawFallback || + 'Unknown Model'; + const baseLabel = getBaseModelLabel(derivedDisplay); + const canonicalSlug = baseLabel.toLowerCase().replace(/\s+/g, '-'); + const dashedSlug = canonicalSlug.replace(/\./g, '-'); + const modelId = dyn?.modelId || rawModelKey || 'unknown'; + const explicitPricing = + MODEL_PRICING[modelId] || + MODEL_PRICING[rawModelKey] || + MODEL_PRICING[canonicalSlug] || + MODEL_PRICING[dashedSlug]; if (explicitPricing) { return { rawModel: rawModelKey, - modelId: dyn.modelId, - label: dyn.label, + modelId, + label: derivedDisplay, + baseLabel, shortName: explicitPricing.short, family: explicitPricing.family, pricing: explicitPricing, @@ -188,14 +279,16 @@ function resolveModelInfo(rawModelKey, dynamicModelMap, apiProvider = '') { }; } - const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, dyn.modelId, apiProvider); - const rawUpper = String(rawModelKey || dyn.modelId || '').toUpperCase(); + const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, modelId, apiProvider); + const rawUpper = String(`${rawModelKey || ''} ${modelId || ''} ${derivedDisplay}`).toUpperCase(); let fallbackPricing; if (inferredFamily === 'Gemini') { if (rawUpper.includes('LITE')) { fallbackPricing = { input: 0.10, cache: 0.01, output: 0.40, short: 'gemini-lite', family: 'Gemini' }; } else if (rawUpper.includes('FLASH')) { fallbackPricing = { input: 0.30, cache: 0.03, output: 2.50, short: 'gemini-flash', family: 'Gemini' }; + } else if (rawUpper.includes('PRO')) { + fallbackPricing = { input: 1.25, cache: 0.125, output: 10.0, short: 'gemini-pro', family: 'Gemini' }; } else { fallbackPricing = { input: 2.00, cache: 0.10, output: 10.0, short: 'gemini', family: 'Gemini' }; } @@ -208,15 +301,16 @@ function resolveModelInfo(rawModelKey, dynamicModelMap, apiProvider = '') { input: 0, cache: 0, output: 0, - short: (dyn.label || 'unknown').split(' ')[0].toLowerCase(), + short: (derivedDisplay || 'unknown').split(' ')[0].toLowerCase(), family: 'Other', }; } return { rawModel: rawModelKey, - modelId: dyn.modelId, - label: dyn.label, + modelId, + label: derivedDisplay, + baseLabel: getBaseModelLabel(derivedDisplay), shortName: fallbackPricing.short, family: fallbackPricing.family, pricing: fallbackPricing, @@ -296,6 +390,8 @@ function resolveTimeWindow( } case '7d': return { key: '7d', label: '近 7 天', startMs: nowMs - 7 * 24 * 3600 * 1000, endMs: nowMs }; + case '14d': + return { key: '14d', label: '近 14 天', startMs: nowMs - 14 * 24 * 3600 * 1000, endMs: nowMs }; case '30d': return { key: '30d', label: '近 30 天', startMs: nowMs - 30 * 24 * 3600 * 1000, endMs: nowMs }; case 'custom': { @@ -325,6 +421,7 @@ function createUsageBucket() { responseTokens: 0, totalTokens: 0, costUsd: 0, + savedCostUsd: 0, geminiTokens: 0, geminiCostUsd: 0, geminiCalls: 0, @@ -336,6 +433,8 @@ function createUsageBucket() { function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) { const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; + const savedCost = + (st.cacheReadTokens / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache); bucket.calls += 1; if (cascadeId) bucket.conversationsSet.add(cascadeId); bucket.inputTokens += st.inputTokens; @@ -345,6 +444,7 @@ function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) { bucket.responseTokens += st.responseTokens || 0; bucket.totalTokens += stepTotalTokens; bucket.costUsd += stepCost; + bucket.savedCostUsd += savedCost; if (mInfo.family === 'Gemini') { bucket.geminiTokens += stepTotalTokens; @@ -360,7 +460,7 @@ function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) { function finalizeUsageBucket(bucket) { const promptTokens = bucket.inputTokens + bucket.cacheReadTokens; const cacheHitPct = - promptTokens > 0 ? Math.round((bucket.cacheReadTokens / promptTokens) * 100) : 0; + promptTokens > 0 ? +((bucket.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0; return { calls: bucket.calls, conversationsCount: bucket.conversationsSet.size, @@ -371,6 +471,7 @@ function finalizeUsageBucket(bucket) { responseTokens: bucket.responseTokens, totalTokens: bucket.totalTokens, costUsd: +bucket.costUsd.toFixed(2), + savedCostUsd: +bucket.savedCostUsd.toFixed(2), cacheHitPct, geminiTokens: bucket.geminiTokens, geminiCostUsd: +bucket.geminiCostUsd.toFixed(2), @@ -407,6 +508,110 @@ function discoverLocalConversationFiles() { return map; } +function loadExternalDeepStatsCache() { + const sigParts = []; + const existingFiles = []; + for (const candidate of DEEP_STATS_CACHE_CANDIDATES) { + if (!existsSync(candidate)) continue; + try { + const st = statSync(candidate); + sigParts.push(`${candidate}:${st.mtimeMs || 0}:${st.size || 0}`); + existingFiles.push(candidate); + } catch { + // Ignore stat errors + } + } + if (existingFiles.length === 0) { + return new Map(); + } + const sig = sigParts.join('|'); + if (externalDeepStatsMemo.sig === sig && externalDeepStatsMemo.convos.size > 0) { + return externalDeepStatsMemo.convos; + } + + const convos = new Map(); + const runtimeDisplayMap = new Map(); + + for (const filePath of existingFiles) { + const raw = loadJson(filePath, null); + if (!raw || typeof raw.perConvo !== 'object' || !raw.perConvo) continue; + + for (const item of Object.values(raw.perConvo)) { + for (const e of item?.entries || []) { + const display = + e?.modelDisplayName || + formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId); + if (!display) continue; + const base = getBaseModelLabel(display); + if (e?.modelRuntimeId && !runtimeDisplayMap.has(e.modelRuntimeId)) { + runtimeDisplayMap.set(e.modelRuntimeId, base); + } + if (e?.model && !runtimeDisplayMap.has(e.model)) { + runtimeDisplayMap.set(e.model, base); + } + } + } + + const titleMap = raw.titleMap || {}; + for (const [fullKey, item] of Object.entries(raw.perConvo)) { + const rawEntries = item?.entries; + if (!Array.isArray(rawEntries) || rawEntries.length === 0) continue; + const colonIdx = fullKey.indexOf(':'); + const appSource = item?.appSource || (colonIdx > 0 ? fullKey.slice(0, colonIdx) : 'ide'); + const cascadeId = (colonIdx > 0 ? fullKey.slice(colonIdx + 1) : fullKey).toLowerCase(); + const mapKey = `${appSource}:${cascadeId}`; + const existing = convos.get(mapKey); + if (existing && existing.steps.length >= rawEntries.length) continue; + + 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 outputTokens = responseTokens + thinkingTokens; + if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0) continue; + const createdAtMs = e?.ts ? Date.parse(e.ts) || 0 : 0; + if (createdAtMs > lastModifiedMs) lastModifiedMs = createdAtMs; + const resolvedDisplay = + e?.modelDisplayName || + runtimeDisplayMap.get(e?.model) || + runtimeDisplayMap.get(e?.modelRuntimeId) || + formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId) || + ''; + steps.push({ + stepIndex: idx + 1, + createdAt: e?.ts || '', + createdAtMs, + modelKey: e?.modelCanonicalId || e?.model || e?.modelRuntimeId || 'unknown', + modelDisplayName: resolvedDisplay, + apiProvider: e?.provider || '', + appSource, + inputTokens, + cacheReadTokens, + outputTokens, + thinkingTokens, + responseTokens, + }); + } + if (steps.length > 0) { + convos.set(mapKey, { + cascadeId, + appSource, + title: titleMap[fullKey] || titleMap[cascadeId] || cascadeId.slice(0, 8), + lastModifiedMs, + steps, + }); + } + } + } + + externalDeepStatsMemo = { sig, convos }; + return convos; +} + async function buildTelemetryPayloadInternal( requestedConvId, forceQuotaRefresh = false, @@ -511,6 +716,30 @@ async function buildTelemetryPayloadInternal( } } + for (const [poolKey, b5hKey, bWkKey, poolName] of [ + ['Gemini', 'gemini-5h', 'gemini-weekly', 'Gemini 模型池'], + ['Claude & GPT', '3p-5h', '3p-weekly', 'Claude & GPT 模型池'], + ]) { + if (!quotaPoolsMap.has(poolKey)) { + const b5h = officialBuckets.get(b5hKey); + const bWk = officialBuckets.get(bWkKey); + quotaPoolsMap.set(poolKey, { + poolName, + family: poolKey, + isAvailable: Boolean(b5h), + remainingPct: b5h?.remainingPct ?? null, + remainingIntPct: b5h?.remainingIntPct ?? null, + usedPct: b5h?.usedPct ?? null, + resetTime: b5h?.resetTime || null, + weeklyRemainingPct: bWk?.remainingPct ?? null, + weeklyRemainingIntPct: bWk?.remainingIntPct ?? null, + weeklyUsedPct: bWk?.usedPct ?? null, + weeklyResetTime: bWk?.resetTime || null, + models: [], + }); + } + } + // Enumerate all conversations from LS + local disk + existing cache const summariesObj = allTrajRes?.trajectorySummaries || {}; const diskConvMap = discoverLocalConversationFiles(); @@ -598,7 +827,16 @@ async function buildTelemetryPayloadInternal( } const sig = `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; - return cached.signature !== sig || isRunning || Boolean(cached.wasRunning); + const lastCachedStep = cached.steps?.[cached.steps.length - 1]; + const missingBreakdownField = + Boolean(lastCachedStep) && + !Object.prototype.hasOwnProperty.call(lastCachedStep, 'contextBreakdown'); + return ( + cached.signature !== sig || + isRunning || + Boolean(cached.wasRunning) || + missingBreakdownField + ); }); // Fetch trajectories with bounded concurrency (up to 4 at a time) @@ -706,21 +944,42 @@ async function buildTelemetryPayloadInternal( const sessionAvgTokPerSec = roundMetric(sessionSpeed.avgTokPerSec); // Context breakdown from the latest step + let latestBreakdown = latestEnriched?.contextBreakdown || null; + if (!latestBreakdown) { + for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { + if (enrichedActiveSteps[i]?.contextBreakdown) { + latestBreakdown = enrichedActiveSteps[i].contextBreakdown; + break; + } + } + } + const ctxMessages = Number(latestBreakdown?.messagesTokens || 0); + const ctxSystemTools = Number(latestBreakdown?.systemToolsTokens || 0); + const ctxMcpTools = Number(latestBreakdown?.mcpToolsTokens || 0); + const ctxSkills = Number(latestBreakdown?.skillsTokens || 0); + const ctxSystemPrompt = Number(latestBreakdown?.systemPromptTokens || 0); + const ctxUserRules = Number(latestBreakdown?.userRulesTokens || 0); + const ctxBreakdownTotal = + ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules; + const ctxCached = latestEnriched?.cacheReadTokens || 0; const ctxFreshInput = latestEnriched?.inputTokens || 0; const ctxThinking = latestEnriched?.thinkingTokens || 0; const ctxResponse = latestEnriched?.responseTokens || 0; - const ctxTotal = ctxCached + ctxFreshInput + ctxThinking + ctxResponse; + const ctxTotal = + ctxBreakdownTotal > 0 + ? ctxBreakdownTotal + : ctxCached + ctxFreshInput + ctxThinking + ctxResponse; const compactionLimitTokens = Number(latestEnriched?.maxContextBudgetTokens || 256000); const compactionUsedTokens = Number( - latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput + latestEnriched?.estimatedContextTokens || ctxBreakdownTotal || ctxCached + ctxFreshInput ); const compactionUsedPct = compactionLimitTokens > 0 ? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1)) : 0; - const ctxLimit = Number(settings.contextWindowLimit || 256000); + const ctxLimit = compactionLimitTokens; const ctxPct = ctxLimit > 0 ? Math.min(100, +((ctxTotal / ctxLimit) * 100).toFixed(1)) : 0; // Cache hit rate (latest step & session-wide) @@ -753,7 +1012,7 @@ async function buildTelemetryPayloadInternal( cycleAnchors ); - const presetKeys = ['all', '5h', 'today', '24h', 'week', '7d', '30d']; + const presetKeys = ['all', '5h', 'today', '24h', 'week', '7d', '14d', '30d']; const presetWindows = {}; const accountBuckets = {}; const sessionBuckets = {}; @@ -766,6 +1025,30 @@ async function buildTelemetryPayloadInternal( const selectedAccountBucket = createUsageBucket(); const selectedSessionBucket = createUsageBucket(); const perModelStats = new Map(); + const selectedWindowSteps = []; + let earliestSelectedStepMs = Infinity; + + const currentYear = new Date(nowMs).getFullYear(); + const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({ + month: idx + 1, + label: `${idx + 1}月`, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + responseTokens: 0, + thinkingTokens: 0, + totalTokens: 0, + costUsd: 0, + })); + + const SOURCE_LABELS = { + standalone: 'Antigravity App', + ide: 'Antigravity IDE', + cli: 'Antigravity CLI', + }; + const perSourceStats = new Map(); + const externalConvos = loadExternalDeepStatsCache(); + const allEntriesToAggregate = []; for (const [cascadeId, entry] of Object.entries(trajectoryCache)) { if ( @@ -776,13 +1059,63 @@ async function buildTelemetryPayloadInternal( ) { continue; } - const isCurrentConv = cascadeId === activeCascadeId; - for (const st of entry?.steps || []) { - const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider); + allEntriesToAggregate.push({ + cascadeId, + appSource: entry?.appSource || 'standalone', + steps: entry?.steps || [], + isCurrentConv: cascadeId === activeCascadeId, + }); + } + + for (const ext of externalConvos.values()) { + const liveEntry = trajectoryCache[ext.cascadeId]; + if ( + ext.appSource === 'standalone' && + liveEntry && + (liveEntry.steps?.length || 0) >= ext.steps.length + ) { + continue; + } + allEntriesToAggregate.push({ + cascadeId: `${ext.appSource}:${ext.cascadeId}`, + appSource: ext.appSource || 'ide', + steps: ext.steps || [], + isCurrentConv: ext.cascadeId === activeCascadeId && !liveEntry, + }); + } + + for (const entry of allEntriesToAggregate) { + const { cascadeId, isCurrentConv } = entry; + const srcKey = entry.appSource || 'standalone'; + const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; + + for (const st of entry.steps || []) { + const mInfo = resolveModelInfo( + st.modelKey, + dynamicModelMap, + st.apiProvider, + st.modelDisplayName + ); const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; const stepCost = computeStepCost(st, mInfo.pricing); const tMs = st.createdAtMs || 0; + if (tMs > 0) { + const stepDate = new Date(tMs); + if (stepDate.getFullYear() === currentYear) { + 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.totalTokens += stepTotalTokens; + mBucket.costUsd = +(mBucket.costUsd + stepCost).toFixed(4); + } + } + } + for (const k of presetKeys) { const w = presetWindows[k]; if (k === 'all' || (tMs >= w.startMs && tMs <= w.endMs)) { @@ -802,34 +1135,109 @@ async function buildTelemetryPayloadInternal( if (isCurrentConv) { accumulateStepIntoBucket(selectedSessionBucket, st, mInfo, stepCost, cascadeId); } + if (tMs > 0) { + if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs; + selectedWindowSteps.push({ + tMs, + tokens: stepTotalTokens, + costUsd: stepCost, + }); + } - if (!perModelStats.has(mInfo.label)) { - perModelStats.set(mInfo.label, { - label: mInfo.label, + if (!perSourceStats.has(srcKey)) { + perSourceStats.set(srcKey, { + name: srcName, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + responseTokens: 0, + thinkingTokens: 0, + totalTokens: 0, + costUsd: 0, + }); + } + 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.totalTokens += stepTotalTokens; + sAgg.costUsd += stepCost; + + const modelGroupKey = mInfo.baseLabel || mInfo.label; + if (!perModelStats.has(modelGroupKey)) { + perModelStats.set(modelGroupKey, { + label: modelGroupKey, shortName: mInfo.shortName, family: mInfo.family, calls: 0, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0, + thinkingTokens: 0, + responseTokens: 0, totalTokens: 0, costUsd: 0, speedAccumulator: createSpeedAccumulator(), }); } - const agg = perModelStats.get(mInfo.label); + const agg = perModelStats.get(modelGroupKey); accumulateSpeed(agg.speedAccumulator, st); agg.calls += 1; agg.inputTokens += st.inputTokens; agg.cacheReadTokens += st.cacheReadTokens; agg.outputTokens += st.outputTokens; + agg.thinkingTokens += st.thinkingTokens || 0; + agg.responseTokens += st.responseTokens || 0; agg.totalTokens += stepTotalTokens; agg.costUsd += stepCost; } } } + // Build 12-slot trendSeries across selectedWindow + const trendSlotsCount = 12; + const trendEndMs = Number.isFinite(selectedWindow.endMs) ? selectedWindow.endMs : nowMs; + const rawTrendStartMs = + selectedWindow.key === 'all' + ? Number.isFinite(earliestSelectedStepMs) + ? earliestSelectedStepMs + : nowMs - 24 * 3600 * 1000 + : selectedWindow.startMs; + const trendStartMs = Math.min(rawTrendStartMs, trendEndMs - 60 * 1000); + const trendSpanMs = Math.max(60 * 1000, trendEndMs - trendStartMs); + const slotWidthMs = trendSpanMs / trendSlotsCount; + const isShortSpan = trendSpanMs <= 36 * 3600 * 1000; + const pad2 = (n) => String(n).padStart(2, '0'); + const formatTrendLabel = (ms) => { + const d = new Date(ms); + if (isShortSpan) { + return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; + } + return `${d.getMonth() + 1}/${d.getDate()}`; + }; + + const trendSeries = Array.from({ length: trendSlotsCount }, (_, idx) => { + const sMs = trendStartMs + idx * slotWidthMs; + return { + index: idx, + label: formatTrendLabel(sMs), + tokens: 0, + costUsd: 0, + calls: 0, + }; + }); + + for (const item of selectedWindowSteps) { + const rawIdx = Math.floor((item.tMs - trendStartMs) / slotWidthMs); + const idx = Math.max(0, Math.min(trendSlotsCount - 1, rawIdx)); + trendSeries[idx].tokens += item.tokens; + trendSeries[idx].costUsd = +(trendSeries[idx].costUsd + item.costUsd).toFixed(4); + trendSeries[idx].calls += 1; + } + const finalizedPresets = {}; for (const k of presetKeys) { finalizedPresets[k] = { @@ -839,6 +1247,17 @@ async function buildTelemetryPayloadInternal( }; } + const finalizedSelectedSession = finalizeUsageBucket(selectedSessionBucket); + const finalizedSelectedAccount = finalizeUsageBucket(selectedAccountBucket); + + const sourcesBreakdown = Array.from(perSourceStats.values()) + .filter((s) => s.totalTokens > 0 || s.calls > 0) + .map((s) => ({ + ...s, + costUsd: +s.costUsd.toFixed(2), + })) + .sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls); + const todayBucket = finalizedPresets.today.account; const weekBucket = finalizedPresets.week.account; @@ -892,8 +1311,14 @@ async function buildTelemetryPayloadInternal( ); const realAiCredits = Number(g1CreditEntry?.creditAmount || 0); + let uiBundleVersion = 0; + try { + uiBundleVersion = statSync(join(HERE, 'app.js')).mtimeMs || 0; + } catch {} + return { timestamp: new Date().toISOString(), + uiBundleVersion, settings, diagnostics: diagnostics.status(), account: { @@ -929,6 +1354,12 @@ async function buildTelemetryPayloadInternal( compactionUsedTokens, compactionLimitTokens, compactionUsedPct, + messagesTokens: ctxMessages, + systemToolsTokens: ctxSystemTools, + mcpToolsTokens: ctxMcpTools, + skillsTokens: ctxSkills, + systemPromptTokens: ctxSystemPrompt, + userRulesTokens: ctxUserRules, cachedTokens: ctxCached, freshInputTokens: ctxFreshInput, thinkingTokens: ctxThinking, @@ -940,14 +1371,18 @@ async function buildTelemetryPayloadInternal( selectedRange: { key: selectedWindow.key, label: selectedWindow.label, - startMs: selectedWindow.startMs, - endMs: Number.isFinite(selectedWindow.endMs) ? selectedWindow.endMs : nowMs, + startMs: trendStartMs, + endMs: trendEndMs, }, - session: finalizeUsageBucket(selectedSessionBucket), + session: finalizedSelectedSession, sessionAllTime: finalizedPresets.all.session, - account: finalizeUsageBucket(selectedAccountBucket), + account: finalizedSelectedAccount, accountAllTime: finalizedPresets.all.account, presets: finalizedPresets, + trendSeries, + sourcesBreakdown, + monthlyYear: currentYear, + monthlySeries, }, quotas: { meta: { @@ -1020,7 +1455,13 @@ function buildTelemetryPayload(requestedConvId, forceQuotaRefresh = false, filte const app = new SidecarApp(); const diagnostics = new StreamDiagnostics({ dataDir: DATA_DIR, lsAddress: LS_ADDR, csrfToken: CSRF_TOKEN }); -const readLocal = (name) => readFileSync(join(HERE, name), 'utf8'); +const readLocalAsync = async (relPath) => { + const fullPath = join(HERE, relPath); + if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) { + return fsPromises.readFile(fullPath, 'utf8'); + } + return readFileSync(fullPath, 'utf8'); +}; function isLocalHostRequest(req) { if (!req?.headers) return true; @@ -1038,11 +1479,31 @@ function isLocalHostRequest(req) { return true; } -app.page('/', () => readLocal('index.html')); -app.page('/app.js', () => readLocal('app.js')); +const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate' }; + +app.page( + '/', + async () => + new Response(await readLocalAsync('index.html'), { + contentType: 'text/html; charset=utf-8', + headers: NO_STORE_HEADERS, + }) +); +app.page( + '/app.js', + async () => + new Response(await readLocalAsync('app.js'), { + contentType: 'application/javascript; charset=utf-8', + headers: NO_STORE_HEADERS, + }) +); app.api( '/styles.css', - () => new Response(readLocal('styles.css'), { contentType: 'text/css' }), + async () => + new Response(await readLocalAsync('styles.css'), { + contentType: 'text/css; charset=utf-8', + headers: NO_STORE_HEADERS, + }), 'GET' ); diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 9984a66..35e297a 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -5,6 +5,6 @@ "type": "module", "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", "scripts": { - "test": "node --test test/*.test.mjs" + "build": "node scripts/build-bundle.mjs" } } diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs new file mode 100644 index 0000000..5e7f2cc --- /dev/null +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -0,0 +1,77 @@ +/** + * @fileoverview Assembles the modular ES files under src/ into the root + * classic scripts (/styles.css and /app.js) required by the Antigravity + * Sidecar Webview sandbox. + */ + +import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'; +import { dirname, join } 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/components.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/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'); +} + +console.log( + `Built styles.css (${cssBundle.length} bytes) and app.js (${jsBundle.length} bytes) [v=${ver}]` +); diff --git a/sidecars/panel/speed-metrics.mjs b/sidecars/panel/speed-metrics.mjs index 665728a..9c8f6d9 100644 --- a/sidecars/panel/speed-metrics.mjs +++ b/sidecars/panel/speed-metrics.mjs @@ -43,11 +43,193 @@ function elapsed(start, end) { return start > 0 && end >= start ? (end - start) / 1000 : null; } +function estimateUtf8Tokens(text) { + if (typeof text !== 'string' || !text) return 0; + return Math.ceil(Buffer.byteLength(text, 'utf8') / 3); +} + +function classifyPromptSection(name) { + const key = String(name || '').trim().toLowerCase(); + if (key === 'skills' || key === 'skill') return 'skills'; + if (key === 'user_rules' || key === 'user_rule' || key === 'rules') return 'userRules'; + if (key === 'mcp_servers' || key === 'mcp' || key.startsWith('mcp_')) return 'mcpTools'; + return 'systemPrompt'; +} + +function isMcpToolItem(name, source = '', type = '') { + const n = String(name || '').trim().toLowerCase(); + const src = String(source || '').toUpperCase(); + const t = String(type || '').toUpperCase(); + return ( + src.includes('MCP') || + t.includes('MCP') || + n.startsWith('mcp_') || + n.startsWith('mcp-') || + n === 'call_mcp_tool' || + n === 'list_mcp_resources' || + n === 'read_mcp_resource' + ); +} + +export function extractContextBreakdown(chat) { + if (!chat || typeof chat !== 'object') return null; + const tb = chat?.chatStartMetadata?.contextWindowMetadata?.tokenBreakdown; + const groups = Array.isArray(tb?.groups) ? tb.groups : []; + const promptSections = Array.isArray(chat?.promptSections) ? chat.promptSections : []; + const tools = Array.isArray(chat?.tools) ? chat.tools : []; + const messagePrompts = Array.isArray(chat?.messagePrompts) ? chat.messagePrompts : []; + + if (!groups.length && !promptSections.length && !tools.length && !messagePrompts.length) { + return null; + } + + let messagesTokens = 0; + let systemToolsTokens = 0; + let mcpToolsTokens = 0; + let skillsTokens = 0; + let systemPromptTokens = 0; + let userRulesTokens = 0; + + let hasPromptGroup = false; + let hasToolsGroup = false; + let hasMessagesGroup = false; + + for (const g of groups) { + const gType = String(g?.type || '').toUpperCase(); + const gName = String(g?.name || '').trim().toLowerCase(); + const gSource = String(g?.source || '').toUpperCase(); + const gTokens = Math.max(0, Number(g?.numTokens || 0)); + const children = Array.isArray(g?.children) ? g.children : []; + + if (gType === 'TOKEN_TYPE_SYSTEM_PROMPT' || gName === 'system prompt') { + hasPromptGroup = true; + if (children.length > 0) { + let childSum = 0; + for (const c of children) { + const tok = Math.max(0, Number(c?.numTokens || 0)); + childSum += tok; + const bucket = classifyPromptSection(c?.name ?? c?.title); + if (bucket === 'skills') skillsTokens += tok; + else if (bucket === 'userRules') userRulesTokens += tok; + else if (bucket === 'mcpTools') mcpToolsTokens += tok; + else systemPromptTokens += tok; + } + if (gTokens > childSum) { + systemPromptTokens += gTokens - childSum; + } + } else { + systemPromptTokens += gTokens; + } + } else if ( + gType === 'TOKEN_TYPE_TOOLS' || + gName === 'tools' || + gType.includes('MCP') || + gSource.includes('MCP') + ) { + hasToolsGroup = true; + if (children.length > 0) { + let childSum = 0; + for (const c of children) { + const tok = Math.max(0, Number(c?.numTokens || 0)); + childSum += tok; + if (isMcpToolItem(c?.name, c?.source || g?.source, c?.type || g?.type)) { + mcpToolsTokens += tok; + } else { + systemToolsTokens += tok; + } + } + if (gTokens > childSum) { + if (isMcpToolItem(g?.name, g?.source, g?.type)) mcpToolsTokens += gTokens - childSum; + else systemToolsTokens += gTokens - childSum; + } + } else if (isMcpToolItem(g?.name, g?.source, g?.type)) { + mcpToolsTokens += gTokens; + } else { + systemToolsTokens += gTokens; + } + } else if ( + gType === 'TOKEN_TYPE_CHAT_MESSAGES' || + gName === 'chat messages' || + gName === 'messages' + ) { + hasMessagesGroup = true; + if (gTokens > 0) { + messagesTokens += gTokens; + } else { + for (const c of children) { + messagesTokens += Math.max(0, Number(c?.numTokens || 0)); + } + } + } + } + + if (!hasPromptGroup && promptSections.length > 0) { + for (const s of promptSections) { + const tok = + Number.isFinite(Number(s?.numTokens)) && Number(s?.numTokens) >= 0 + ? Number(s.numTokens) + : estimateUtf8Tokens(s?.content ?? s?.text ?? ''); + const bucket = classifyPromptSection(s?.title ?? s?.name); + if (bucket === 'skills') skillsTokens += tok; + else if (bucket === 'userRules') userRulesTokens += tok; + else if (bucket === 'mcpTools') mcpToolsTokens += tok; + else systemPromptTokens += tok; + } + } + + if (!hasToolsGroup && tools.length > 0) { + for (const t of tools) { + const rawText = `${t?.name || ''}${t?.description || ''}${t?.jsonSchemaString || ''}`; + const tok = + Number.isFinite(Number(t?.numTokens)) && Number(t?.numTokens) >= 0 + ? Number(t.numTokens) + : estimateUtf8Tokens(rawText); + if (isMcpToolItem(t?.name, t?.source, t?.type)) { + mcpToolsTokens += tok; + } else { + systemToolsTokens += tok; + } + } + } + + if (!hasMessagesGroup && messagePrompts.length > 0) { + for (const m of messagePrompts) { + const tok = + Number.isFinite(Number(m?.numTokens)) && Number(m?.numTokens) >= 0 + ? Number(m.numTokens) + : estimateUtf8Tokens(m?.prompt ?? m?.content ?? ''); + messagesTokens += tok; + } + } + + const totalTokens = + messagesTokens + + systemToolsTokens + + mcpToolsTokens + + skillsTokens + + systemPromptTokens + + userRulesTokens; + + return { + messagesTokens, + systemToolsTokens, + mcpToolsTokens, + skillsTokens, + systemPromptTokens, + userRulesTokens, + totalTokens, + }; +} + export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const genByStep = new Map(); + let latestBreakdownChat = null; for (const gm of generatorMetadata || []) { if (!gm?.chatModel) continue; for (const index of gm?.stepIndices || []) genByStep.set(Number(index), gm); + if (extractContextBreakdown(gm.chatModel)) { + latestBreakdownChat = gm.chatModel; + } } const result = []; rawSteps.forEach((s, index) => { @@ -84,6 +266,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const shortOutputSample = totalTokPerSec !== null && outputTokens < MIN_MEAN_OUTPUT_TOKENS; const speedReason = timingReason || (isCompactionStep ? 'compaction' : shortOutputSample ? 'short_sample' : null); const context = chat?.chatStartMetadata?.contextWindowMetadata; + const contextBreakdown = extractContextBreakdown(chat); result.push({ stepIndex, isCompactionStep, modelKey: u.model || chat?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418', @@ -92,8 +275,9 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { hasVisibleText: String(p.modifiedResponse || p.response || '').trim().length > 0, hasToolCalls: Array.isArray(p.toolCalls) && p.toolCalls.length > 0, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, - estimatedContextTokens: Number(context?.estimatedTokensUsed || 0), + estimatedContextTokens: Number(context?.estimatedTokensUsed || contextBreakdown?.totalTokens || 0), maxContextBudgetTokens: Number(context?.maxContextTokens || 256000), + contextBreakdown, measurementVersion: MEASUREMENT_VERSION, isComplete: complete, nativeTtftSec, nativeStreamSec, viewableDelaySec: elapsed(start, parseIsoMs(m.viewableAt)), @@ -104,6 +288,20 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { speedReason, }); }); + if (result.length > 0 && !result[result.length - 1].contextBreakdown && latestBreakdownChat) { + const lastStep = result[result.length - 1]; + const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat); + const fallbackCtx = latestBreakdownChat?.chatStartMetadata?.contextWindowMetadata; + lastStep.contextBreakdown = fallbackBreakdown; + if (!lastStep.estimatedContextTokens) { + lastStep.estimatedContextTokens = Number( + fallbackCtx?.estimatedTokensUsed || fallbackBreakdown?.totalTokens || 0 + ); + } + if (fallbackCtx?.maxContextTokens) { + lastStep.maxContextBudgetTokens = Number(fallbackCtx.maxContextTokens); + } + } return result; } diff --git a/sidecars/panel/src/App.js b/sidecars/panel/src/App.js new file mode 100644 index 0000000..cbba662 --- /dev/null +++ b/sidecars/panel/src/App.js @@ -0,0 +1,106 @@ +/** + * @fileoverview Root Application Shell (App.js). + * Combines the compact dual-layer header (TopSessionHeader + TopLongPillNav) + * and single-viewport functional views. + */ + +import { defineComponent } from './core/component.js'; +import { h, patchAttr } from './core/domPatch.js'; +import { telemetryStore } from './store/telemetryStore.js'; +import { uiStore, VIEW_TABS } from './store/uiStore.js'; +import { TopSessionHeader } from './components/layout/TopSessionHeader.js'; +import { TopLongPillNav } from './components/ui/TopLongPillNav.js'; +import { LiveOverviewView } from './views/LiveOverviewView.js'; +import { ConsumptionView } from './views/ConsumptionView.js'; +import { StepsDetailView } from './views/StepsDetailView.js'; +import { SettingsView } from './views/SettingsView.js'; + +export const App = defineComponent({ + name: 'App', + setup({ onCleanup }) { + const sessionHeader = TopSessionHeader(); + const topPillNav = TopLongPillNav({ + modelValue: uiStore.getState().activeView, + items: VIEW_TABS, + onUpdateModelValue: (nextView) => { + uiStore.setState({ activeView: nextView }); + }, + }); + + const overviewView = LiveOverviewView(); + const consumptionView = ConsumptionView(); + const stepsView = StepsDetailView(); + const settingsView = SettingsView(); + + const viewMap = { + overview: overviewView.el, + consumption: consumptionView.el, + steps: stepsView.el, + settings: settingsView.el, + }; + + const stageEl = h('div', { className: 'viewport-stage' }, [ + overviewView.el, + consumptionView.el, + stepsView.el, + settingsView.el, + ]); + + const shellEl = h('main', { className: 'app-shell' }, [ + h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]), + stageEl, + ]); + + const unsubUi = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + topPillNav.setValue(activeView); + for (const [key, paneEl] of Object.entries(viewMap)) { + patchAttr(paneEl, 'hidden', key !== activeView); + } + if (activeView === 'overview') { + overviewView.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'consumption') { + consumptionView.refs?.viewScrollbar?.refresh(); + } else if (activeView === 'steps') { + stepsView.refs?.stepsScroll?.refresh(); + stepsView.refs?.modelsScroll?.refresh(); + } + } + ); + + const unsubStepCount = telemetryStore.subscribe( + (st) => st.telemetry?.activeConversation?.stepCount ?? 0, + (stepCount) => { + topPillNav.setProps({ + items: VIEW_TABS.map((t) => + t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t + ), + }); + } + ); + + onCleanup(() => { + unsubUi(); + unsubStepCount(); + sessionHeader.destroy(); + topPillNav.destroy(); + overviewView.destroy(); + consumptionView.destroy(); + stepsView.destroy(); + settingsView.destroy(); + }); + + return { + el: shellEl, + refs: { + sessionHeader, + topPillNav, + overviewView, + consumptionView, + stepsView, + settingsView, + }, + }; + }, +}); diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js new file mode 100644 index 0000000..9094fc8 --- /dev/null +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -0,0 +1,142 @@ +/** + * @fileoverview Row 1 of the compact top bar: + * Bespoke CustomSelect for session switching, SVG live status indicator, + * and async force-refresh button. + */ + +import { defineComponent } from '../../core/component.js'; +import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; +import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; +import { fetchTelemetry, telemetryStore } from '../../store/telemetryStore.js'; +import { CustomSelect } from '../ui/CustomSelect.js'; + +export const TopSessionHeader = defineComponent({ + name: 'TopSessionHeader', + setup({ onCleanup }) { + const convSelect = CustomSelect({ + modelValue: telemetryStore.getState().selectedConversationId, + icon: 'bolt', + placeholder: '自动跟随最新会话', + options: [{ value: '', label: '自动跟随最新会话' }], + onUpdateModelValue: (nextConvId) => { + telemetryStore.setState({ selectedConversationId: nextConvId }); + fetchTelemetry({ force: false }); + }, + }); + + const statusIcon = createSvgIcon('pulse', { size: 12 }); + const statusText = h('span', { text: '实时 2s' }); + const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]); + + const refreshBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn', + 'aria-label': '立即强制同步官方额度与测速', + onClick: () => fetchTelemetry({ force: true }), + }, + [createSvgIcon('refresh', { size: 13 })] + ); + + const headerEl = h('header', { className: 'session-header' }, [ + h('div', { className: 'session-left' }, [convSelect.el]), + h('div', { className: 'session-right' }, [statusTag, refreshBtn]), + ]); + + const unsubTelemetry = telemetryStore.subscribe( + (st) => ({ + selectedConversationId: st.selectedConversationId, + syncState: st.syncState, + conversations: st.telemetry?.conversations, + isRunning: st.telemetry?.activeConversation?.isRunning, + quotaMeta: st.telemetry?.quotas?.meta, + }), + (slice) => { + const convs = slice.conversations || []; + const latestTitle = convs[0]?.title ? `自动跟随 (${convs[0].title})` : '自动跟随最新会话'; + const options = [ + { value: '', label: latestTitle, meta: convs[0] ? `${convs[0].stepCount}步` : '' }, + ...convs.map((c) => ({ + value: c.cascadeId, + label: c.title || c.cascadeId.slice(0, 8), + meta: `${c.stepCount || 0}步`, + })), + ]; + convSelect.setProps({ + modelValue: slice.selectedConversationId, + options, + }); + + const isSyncing = slice.syncState === 'syncing'; + const isSynced = slice.syncState === 'synced'; + const isError = slice.syncState === 'error'; + const isRunning = Boolean(slice.isRunning); + const quotaStale = Boolean(slice.quotaMeta?.refreshFailed || slice.quotaMeta?.isStale); + + patchClasses(refreshBtn, { 'is-spinning': isSyncing }); + patchAttr(refreshBtn, 'disabled', isSyncing); + + if (isSyncing) { + patchSvgIcon(statusIcon, 'refresh'); + patchText(statusText, '同步中'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': true, + 'state-warn': false, + }); + } else if (isSynced) { + patchSvgIcon(statusIcon, 'check'); + patchText(statusText, '已刷新'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': true, + 'state-warn': false, + }); + } else if (isError) { + patchSvgIcon(statusIcon, 'warning'); + patchText(statusText, '重试中'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': false, + 'state-warn': true, + }); + } else if (isRunning) { + patchSvgIcon(statusIcon, 'bolt'); + patchText(statusText, '生成中'); + patchClasses(statusTag, { + 'state-running': true, + 'state-synced': false, + 'state-warn': false, + }); + } else if (quotaStale) { + patchSvgIcon(statusIcon, 'warning'); + patchText(statusText, slice.quotaMeta?.hasOfficialData ? '额度缓存' : '额度离线'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': false, + 'state-warn': true, + }); + } else { + patchSvgIcon(statusIcon, 'pulse'); + patchText(statusText, '实时 2s'); + patchClasses(statusTag, { + 'state-running': false, + 'state-synced': false, + 'state-warn': false, + }); + } + } + ); + + onCleanup(() => { + unsubTelemetry(); + convSelect.destroy(); + }); + + return { + el: headerEl, + refs: { convSelect, statusTag, refreshBtn }, + }; + }, +}); diff --git a/sidecars/panel/src/components/ui/ContextSegmentMeter.js b/sidecars/panel/src/components/ui/ContextSegmentMeter.js new file mode 100644 index 0000000..2a29629 --- /dev/null +++ b/sidecars/panel/src/components/ui/ContextSegmentMeter.js @@ -0,0 +1,64 @@ +/** + * @fileoverview 6-channel segmented context window progress bar updated via + * CSS custom variables against the current model's automatic compaction baseline. + */ + +import { defineComponent } from '../../core/component.js'; +import { h, patchAttr, patchStyleVar } from '../../core/domPatch.js'; + +export const ContextSegmentMeter = defineComponent({ + name: 'ContextSegmentMeter', + setup({ getProps }) { + const segMessages = h('div', { className: 'progress-seg seg-messages' }); + const segSystemTools = h('div', { className: 'progress-seg seg-system-tools' }); + const segMcpTools = h('div', { className: 'progress-seg seg-mcp-tools' }); + const segSkills = h('div', { className: 'progress-seg seg-skills' }); + const segSystemPrompt = h('div', { className: 'progress-seg seg-system-prompt' }); + const segUserRules = h('div', { className: 'progress-seg seg-user-rules' }); + + const trackEl = h( + 'div', + { + className: 'progress-track', + role: 'progressbar', + 'aria-valuemin': '0', + 'aria-valuemax': '100', + }, + [segMessages, segSystemTools, segMcpTools, segSkills, segSystemPrompt, segUserRules] + ); + + function syncMeter() { + const ctx = getProps().context || {}; + const limit = Math.max(1, Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000)); + const pctMessages = Math.min(100, ((ctx.messagesTokens || 0) / limit) * 100); + const pctSystemTools = Math.min(100, ((ctx.systemToolsTokens || 0) / limit) * 100); + const pctMcpTools = Math.min(100, ((ctx.mcpToolsTokens || 0) / limit) * 100); + const pctSkills = Math.min(100, ((ctx.skillsTokens || 0) / limit) * 100); + const pctSystemPrompt = Math.min(100, ((ctx.systemPromptTokens || 0) / limit) * 100); + const pctUserRules = Math.min(100, ((ctx.userRulesTokens || 0) / limit) * 100); + + patchStyleVar(segMessages, '--seg-w', `${pctMessages.toFixed(2)}%`); + patchStyleVar(segSystemTools, '--seg-w', `${pctSystemTools.toFixed(2)}%`); + patchStyleVar(segMcpTools, '--seg-w', `${pctMcpTools.toFixed(2)}%`); + patchStyleVar(segSkills, '--seg-w', `${pctSkills.toFixed(2)}%`); + patchStyleVar(segSystemPrompt, '--seg-w', `${pctSystemPrompt.toFixed(2)}%`); + patchStyleVar(segUserRules, '--seg-w', `${pctUserRules.toFixed(2)}%`); + patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0)); + } + + syncMeter(); + + return { + el: trackEl, + refs: { + segMessages, + segSystemTools, + segMcpTools, + segSkills, + segSystemPrompt, + segUserRules, + }, + onPropsChange: syncMeter, + }; + }, +}); diff --git a/sidecars/panel/src/components/ui/CustomDateTimePicker.js b/sidecars/panel/src/components/ui/CustomDateTimePicker.js new file mode 100644 index 0000000..b1792de --- /dev/null +++ b/sidecars/panel/src/components/ui/CustomDateTimePicker.js @@ -0,0 +1,282 @@ +/** + * @fileoverview Bespoke CustomDateTimePicker calendar matrix and hour/minute stepper. + * Replaces native and emits Unix epoch ms. + */ + +import { defineComponent } from '../../core/component.js'; +import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js'; +import { formatCompactDateTime } from '../../core/formatters.js'; +import { createSvgIcon } from '../../icons/SvgIcon.js'; + +const WEEKDAYS = ['一', '二', '三', '四', '五', '六', '日']; + +function buildCalendarDays(viewYear, viewMonth, selectedDate) { + const firstDay = new Date(viewYear, viewMonth, 1); + // Convert Sunday=0..Saturday=6 into Monday=0..Sunday=6 + const startOffset = (firstDay.getDay() + 6) % 7; + const cells = []; + + for (let i = 0; i < 42; i++) { + const cellDate = new Date(viewYear, viewMonth, 1 - startOffset + i); + const y = cellDate.getFullYear(); + const m = cellDate.getMonth(); + const d = cellDate.getDate(); + const isCurrentMonth = m === viewMonth; + const isSelected = + selectedDate && + selectedDate.getFullYear() === y && + selectedDate.getMonth() === m && + selectedDate.getDate() === d; + + cells.push({ + key: `${y}-${m}-${d}`, + year: y, + month: m, + day: d, + isCurrentMonth, + isSelected, + }); + } + return cells; +} + +export const CustomDateTimePicker = defineComponent({ + name: 'CustomDateTimePicker', + setup({ getProps, emit, onCleanup }) { + let isOpen = false; + const initialDate = new Date(getProps().modelValue || Date.now()); + let viewYear = initialDate.getFullYear(); + let viewMonth = initialDate.getMonth(); + + const triggerText = h('span', { className: 'text-mono' }); + const triggerBtn = h( + 'button', + { + type: 'button', + className: 'dt-trigger', + 'aria-expanded': 'false', + onClick: (e) => { + e.stopPropagation(); + togglePopover(!isOpen); + }, + }, + [createSvgIcon('calendar', { size: 13 }), triggerText] + ); + + const monthTitle = h('span', { className: 'text-mono' }); + const prevMonthBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn', + 'aria-label': '上个月', + onClick: (e) => { + e.stopPropagation(); + viewMonth -= 1; + if (viewMonth < 0) { + viewMonth = 11; + viewYear -= 1; + } + renderCalendar(); + }, + }, + [createSvgIcon('chevron-left', { size: 12 })] + ); + + const nextMonthBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn', + 'aria-label': '下个月', + onClick: (e) => { + e.stopPropagation(); + viewMonth += 1; + if (viewMonth > 11) { + viewMonth = 0; + viewYear += 1; + } + renderCalendar(); + }, + }, + [createSvgIcon('chevron-right', { size: 12 })] + ); + + const navBar = h('div', { className: 'dt-nav' }, [prevMonthBtn, monthTitle, nextMonthBtn]); + + const weekdayRow = h( + 'div', + { className: 'dt-weekdays' }, + WEEKDAYS.map((w) => h('span', { className: 'dt-weekday', text: w })) + ); + + const daysGrid = h('div', { className: 'dt-days' }); + + const hourValSpan = h('strong', { className: 'text-mono', text: '00' }); + const minValSpan = h('strong', { className: 'text-mono', text: '00' }); + + function adjustTime(part, delta) { + const cur = new Date(getProps().modelValue || Date.now()); + if (part === 'hour') { + cur.setHours((cur.getHours() + delta + 24) % 24); + } else { + cur.setMinutes((cur.getMinutes() + delta + 60) % 60); + } + const nextMs = cur.getTime(); + viewYear = cur.getFullYear(); + viewMonth = cur.getMonth(); + emit('update:modelValue', nextMs); + } + + const timeRow = h('div', { className: 'dt-time-row' }, [ + h('span', { className: 'text-muted', text: '时 / 分' }), + h('div', { className: 'dt-time-controls' }, [ + h('div', { className: 'dt-mini-step' }, [ + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '-', + onClick: (e) => { + e.stopPropagation(); + adjustTime('hour', -1); + }, + }), + hourValSpan, + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '+', + onClick: (e) => { + e.stopPropagation(); + adjustTime('hour', 1); + }, + }), + ]), + h('span', { text: ':' }), + h('div', { className: 'dt-mini-step' }, [ + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '-', + onClick: (e) => { + e.stopPropagation(); + adjustTime('minute', -5); + }, + }), + minValSpan, + h('button', { + type: 'button', + className: 'dt-mini-btn', + text: '+', + onClick: (e) => { + e.stopPropagation(); + adjustTime('minute', 5); + }, + }), + ]), + ]), + ]); + + const popoverEl = h( + 'div', + { + className: 'dt-popover', + hidden: true, + }, + [navBar, weekdayRow, daysGrid, timeRow] + ); + + const rootEl = h('div', { className: 'datetime-picker' }, [triggerBtn, popoverEl]); + + function togglePopover(nextOpen) { + isOpen = Boolean(nextOpen); + patchAttr(popoverEl, 'hidden', !isOpen); + patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false'); + if (isOpen) { + const cur = new Date(getProps().modelValue || Date.now()); + viewYear = cur.getFullYear(); + viewMonth = cur.getMonth(); + renderCalendar(); + } + } + + function selectDay(cell) { + const cur = new Date(getProps().modelValue || Date.now()); + cur.setFullYear(cell.year, cell.month, cell.day); + const nextMs = cur.getTime(); + viewYear = cell.year; + viewMonth = cell.month; + emit('update:modelValue', nextMs); + } + + function renderCalendar() { + const cur = new Date(getProps().modelValue || Date.now()); + const pad = (n) => String(n).padStart(2, '0'); + patchText(monthTitle, `${viewYear}-${pad(viewMonth + 1)}`); + patchText(hourValSpan, pad(cur.getHours())); + patchText(minValSpan, pad(cur.getMinutes())); + + const cells = buildCalendarDays(viewYear, viewMonth, cur); + patchKeyedList(daysGrid, cells, { + keyFn: (c) => c.key, + sigFn: (c) => `${c.key}:${c.isCurrentMonth}:${c.isSelected}`, + createRow: (cell) => { + const btn = h('button', { + type: 'button', + className: 'dt-day', + onClick: (e) => { + e.stopPropagation(); + selectDay(cell); + }, + }); + return { el: btn, refs: {} }; + }, + updateRow: (_refs, cell, _idx, el) => { + patchText(el, cell.day); + patchClasses(el, { + 'is-selected': cell.isSelected, + 'is-outside': !cell.isCurrentMonth, + }); + patchAttr(el, 'data-date-key', cell.key); + }, + }); + } + + function syncDisplay() { + const ms = Number(getProps().modelValue || Date.now()); + patchText(triggerText, formatCompactDateTime(ms)); + if (isOpen) { + renderCalendar(); + } + } + + const handleDocClick = (e) => { + if (isOpen && !rootEl.contains(e.target)) { + togglePopover(false); + } + }; + + if (typeof document !== 'undefined' && document.addEventListener) { + document.addEventListener('click', handleDocClick); + onCleanup(() => document.removeEventListener('click', handleDocClick)); + } + + syncDisplay(); + + return { + 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 new file mode 100644 index 0000000..cb25413 --- /dev/null +++ b/sidecars/panel/src/components/ui/CustomNumberInput.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Bespoke CustomNumberInput spinbutton & precision stepper. + * Replaces native with custom SVG step controls, + * keyboard ArrowUp/ArrowDown (+Shift 10x), and min/max clamping. + */ + +import { defineComponent } from '../../core/component.js'; +import { h, patchAttr } from '../../core/domPatch.js'; +import { createSvgIcon } from '../../icons/SvgIcon.js'; + +export const CustomNumberInput = defineComponent({ + name: 'CustomNumberInput', + setup({ getProps, emit }) { + function clampValue(raw) { + const { min = -Infinity, max = Infinity, precision = 0 } = getProps(); + const num = Number(raw); + if (!Number.isFinite(num)) { + return Number(getProps().modelValue ?? (Number.isFinite(min) ? min : 0)); + } + const clamped = Math.min(max, Math.max(min, num)); + return precision > 0 ? Number(clamped.toFixed(precision)) : Math.round(clamped); + } + + function applyStep(direction, multiplier = 1) { + const { step = 1, modelValue = 0 } = getProps(); + const current = Number(modelValue) || 0; + const next = clampValue(current + direction * step * multiplier); + syncFieldDisplay(next); + if (next !== current) { + emit('update:modelValue', next); + } + } + + const decBtn = h( + 'button', + { + type: 'button', + className: 'num-step-btn', + 'aria-label': '减少数值', + onClick: (e) => { + e.preventDefault(); + applyStep(-1, e.shiftKey ? 10 : 1); + }, + }, + [createSvgIcon('minus', { size: 12 })] + ); + + const incBtn = h( + 'button', + { + type: 'button', + className: 'num-step-btn', + 'aria-label': '增加数值', + onClick: (e) => { + e.preventDefault(); + applyStep(1, e.shiftKey ? 10 : 1); + }, + }, + [createSvgIcon('plus', { size: 12 })] + ); + + const textField = h('input', { + type: 'text', + inputmode: 'decimal', + role: 'spinbutton', + className: 'num-field', + onKeydown: (e) => { + if (e.key === 'ArrowUp') { + e.preventDefault(); + applyStep(1, e.shiftKey ? 10 : 1); + } else if (e.key === 'ArrowDown') { + e.preventDefault(); + applyStep(-1, e.shiftKey ? 10 : 1); + } else if (e.key === 'Enter') { + e.preventDefault(); + commitManualInput(); + } + }, + onBlur: () => commitManualInput(), + }); + + function commitManualInput() { + const rawText = String(textField.value || '').replace(/[^0-9.-]/g, ''); + const next = clampValue(rawText); + const prev = Number(getProps().modelValue); + syncFieldDisplay(next); + if (next !== prev) { + emit('update:modelValue', next); + } + } + + function syncFieldDisplay(val = getProps().modelValue) { + const { min, max } = getProps(); + const normalized = clampValue(val); + if (textField.value !== String(normalized)) { + textField.value = String(normalized); + } + patchAttr(textField, 'aria-valuenow', normalized); + if (Number.isFinite(min)) patchAttr(textField, 'aria-valuemin', min); + if (Number.isFinite(max)) patchAttr(textField, 'aria-valuemax', max); + } + + const rootEl = h('div', { className: 'number-input' }, [decBtn, textField, incBtn]); + syncFieldDisplay(); + + return { + 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), + }, + }; + }, +}); diff --git a/sidecars/panel/src/components/ui/CustomScrollbar.js b/sidecars/panel/src/components/ui/CustomScrollbar.js new file mode 100644 index 0000000..b6fd305 --- /dev/null +++ b/sidecars/panel/src/components/ui/CustomScrollbar.js @@ -0,0 +1,164 @@ +/** + * @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. + */ + +import { defineComponent } from '../../core/component.js'; +import { h, patchClasses, patchStyleVar } from '../../core/domPatch.js'; + +export const CustomScrollbar = defineComponent({ + name: 'CustomScrollbar', + setup({ getProps, emit, onCleanup }) { + const contentEl = getProps().contentEl || h('div'); + contentEl.classList.add('custom-scroll-content'); + + const thumbEl = h('div', { className: 'scrollbar-thumb' }); + const railEl = h( + 'div', + { + className: 'scrollbar-rail is-inactive', + 'aria-hidden': 'true', + }, + [thumbEl] + ); + + const hostEl = h( + 'div', + { + className: `custom-scroll-host ${getProps().className || ''}`.trim(), + }, + [contentEl, railEl] + ); + + let isDragging = false; + let dragStartY = 0; + let dragStartScrollTop = 0; + + function syncThumb() { + const scrollHeight = Number(contentEl.scrollHeight || 0); + const clientHeight = Number(contentEl.clientHeight || 0); + const scrollTop = Number(contentEl.scrollTop || 0); + const overflow = scrollHeight - clientHeight; + + if (overflow <= 1 || clientHeight <= 0) { + patchClasses(railEl, { 'is-inactive': true }); + patchStyleVar(thumbEl, '--thumb-h', '0px'); + patchStyleVar(thumbEl, '--thumb-y', '0px'); + return; + } + + patchClasses(railEl, { 'is-inactive': false }); + const railHeight = Math.max(24, clientHeight - 4); + const thumbHeight = Math.max(24, Math.round((clientHeight / scrollHeight) * railHeight)); + const maxThumbTop = Math.max(0, railHeight - thumbHeight); + const ratio = Math.max(0, Math.min(1, scrollTop / overflow)); + const thumbTop = Math.round(ratio * maxThumbTop); + + patchStyleVar(thumbEl, '--thumb-h', `${thumbHeight}px`); + patchStyleVar(thumbEl, '--thumb-y', `${thumbTop}px`); + } + + function onContentScroll() { + 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) { + if (!isDragging) return; + const clientHeight = Number(contentEl.clientHeight || 0); + const scrollHeight = Number(contentEl.scrollHeight || 0); + const overflow = scrollHeight - clientHeight; + if (overflow <= 1) return; + + const railHeight = Math.max(24, clientHeight - 4); + const thumbHeight = Math.max(24, Math.round((clientHeight / scrollHeight) * railHeight)); + const maxThumbTop = Math.max(1, railHeight - thumbHeight); + + const deltaY = (e.clientY || 0) - dragStartY; + const scrollDelta = (deltaY / maxThumbTop) * overflow; + contentEl.scrollTop = Math.max(0, Math.min(overflow, dragStartScrollTop + scrollDelta)); + syncThumb(); + } + + function onDocMouseUp() { + if (!isDragging) return; + isDragging = false; + patchClasses(railEl, { 'is-dragging': false }); + if (typeof document !== 'undefined') { + document.removeEventListener('mousemove', onDocMouseMove); + document.removeEventListener('mouseup', onDocMouseUp); + } + } + + thumbEl.addEventListener('mousedown', (e) => { + e.preventDefault(); + e.stopPropagation(); + isDragging = true; + dragStartY = e.clientY || 0; + dragStartScrollTop = Number(contentEl.scrollTop || 0); + patchClasses(railEl, { 'is-dragging': true }); + if (typeof document !== 'undefined') { + document.addEventListener('mousemove', onDocMouseMove); + document.addEventListener('mouseup', onDocMouseUp); + } + }); + + railEl.addEventListener('mousedown', (e) => { + if (e.target === thumbEl) return; + e.preventDefault(); + const rect = railEl.getBoundingClientRect ? railEl.getBoundingClientRect() : null; + if (!rect || rect.height <= 0) return; + const clickOffset = (e.clientY || 0) - rect.top; + const ratio = Math.max(0, Math.min(1, clickOffset / rect.height)); + const overflow = Math.max(0, (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0)); + contentEl.scrollTop = Math.round(ratio * overflow); + syncThumb(); + }); + + contentEl.addEventListener('scroll', onContentScroll); + hostEl.addEventListener('mouseenter', syncThumb); + + let resizeObserver = null; + if (typeof ResizeObserver !== 'undefined') { + resizeObserver = new ResizeObserver(() => syncThumb()); + resizeObserver.observe(hostEl); + resizeObserver.observe(contentEl); + } + + syncThumb(); + + onCleanup(() => { + onDocMouseUp(); + contentEl.removeEventListener('scroll', onContentScroll); + hostEl.removeEventListener('mouseenter', syncThumb); + if (resizeObserver) { + resizeObserver.disconnect(); + } + }); + + return { + el: hostEl, + refs: { contentEl, railEl, thumbEl }, + onPropsChange: syncThumb, + methods: { + refresh() { + syncThumb(); + if (typeof queueMicrotask === 'function') { + queueMicrotask(syncThumb); + } + }, + 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 new file mode 100644 index 0000000..92bc94d --- /dev/null +++ b/sidecars/panel/src/components/ui/CustomSelect.js @@ -0,0 +1,182 @@ +/** + * @fileoverview Bespoke CustomSelect dropdown component replacing native ) --- */ +.custom-select { + position: relative; + display: inline-flex; + flex-direction: column; + min-width: 0; + flex: 1; +} + +.select-trigger { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + width: 100%; + height: 24px; + padding: 0 6px; + background: transparent; + color: var(--text-primary); + border: none; + border-radius: var(--radius-xs); + font-size: 12px; + cursor: pointer; + text-align: left; + transition: background-color var(--dur-instant) var(--ease-fast); +} + +.select-trigger:hover, +.custom-select.is-open .select-trigger { + background: var(--surface-hover); +} + +.select-label { + flex: 1; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-weight: 500; +} + +.select-menu { + position: absolute; + top: calc(100% + 4px); + left: 0; + right: 0; + min-width: 210px; + max-height: 220px; + overflow-y: auto; + background: var(--surface-panel); + border: none; + border-radius: var(--radius-sm); + box-shadow: var(--shadow-popover); + padding: 4px; + z-index: 60; + animation: popover-in var(--dur-fast) var(--ease-fast); +} + +.select-option { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + width: 100%; + padding: 5px var(--space-2); + border: none; + background: transparent; + color: var(--text-primary); + font-size: 12px; + text-align: left; + border-radius: var(--radius-xs); + cursor: pointer; +} + +.select-option:hover, +.select-option.is-focused { + background: var(--surface-hover); +} + +.select-option.is-selected { + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-weight: 600; +} + +.select-option-text { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* --- Bespoke Custom Number Input (零原生 ) --- */ +.number-input { + display: inline-flex; + align-items: stretch; + height: 28px; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + overflow: hidden; +} + +.number-input:focus-within { + border-color: var(--accent-primary); +} + +.num-step-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + border: none; + background: var(--surface-panel); + color: var(--text-secondary); + cursor: pointer; + transition: background-color var(--dur-instant) var(--ease-fast), color var(--dur-instant) var(--ease-fast); +} + +.num-step-btn:hover { + background: var(--surface-hover); + color: var(--text-primary); +} + +.num-step-btn:active { + background: var(--surface-active); +} + +.num-field { + flex: 1; + min-width: 90px; + padding: 0 var(--space-3); + border: none; + border-left: 1px solid var(--border-hairline); + border-right: 1px solid var(--border-hairline); + background: transparent; + color: var(--text-primary); + font-weight: 600; + font-variant-numeric: tabular-nums; + outline: none; +} + +/* --- Bespoke Custom DateTime Picker (零原生 ) --- */ +.datetime-picker { + position: relative; + display: inline-flex; + flex: 1; + min-width: 145px; +} + +.dt-trigger { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + width: 100%; + height: 26px; + padding: 0 var(--space-2); + background: var(--surface-panel); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + font-size: 11.5px; + cursor: pointer; +} + +.dt-trigger:hover { + border-color: var(--border-strong); +} + +.dt-popover { + position: absolute; + top: calc(100% + 4px); + left: 0; + width: 248px; + background: var(--surface-panel); + border: 1px solid var(--border-strong); + border-radius: var(--radius-xs); + box-shadow: var(--shadow-popover); + padding: var(--space-3); + z-index: 70; + display: flex; + flex-direction: column; + gap: var(--space-2); + animation: popover-in var(--dur-fast) var(--ease-fast); +} + +.dt-nav { + display: flex; + align-items: center; + justify-content: space-between; + font-weight: 600; + font-size: 12px; +} + +.dt-weekdays, +.dt-days { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 2px; + text-align: center; +} + +.dt-weekday { + font-size: 10.5px; + color: var(--text-secondary); + padding: 2px 0; +} + +.dt-day { + height: 22px; + border: none; + background: transparent; + color: var(--text-primary); + font-size: 11px; + border-radius: var(--radius-xs); + cursor: pointer; +} + +.dt-day:hover { + background: var(--surface-hover); +} + +.dt-day.is-selected { + background: var(--accent-primary); + color: var(--text-inverse); + font-weight: 600; +} + +.dt-day.is-outside { + color: var(--text-muted); +} + +.dt-time-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + padding-top: var(--space-2); + border-top: 1px solid var(--border-hairline); + font-size: 11.5px; +} + +.dt-time-controls { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.dt-mini-step { + display: inline-flex; + align-items: center; + gap: 2px; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + padding: 1px 3px; +} + +.dt-mini-btn { + border: none; + background: transparent; + color: var(--text-secondary); + cursor: pointer; + padding: 1px 3px; +} + +.dt-mini-btn:hover { + color: var(--text-primary); +} + +/* --- Micro-Bezel Segmented Control --- */ +.segmented { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 0; + background: transparent; + border: none; +} + +.seg-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + height: 22px; + padding: 0 7px; + border: none; + background: transparent; + color: var(--text-secondary); + font-size: 11px; + border-radius: var(--radius-xs); + cursor: pointer; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.seg-btn:hover { + color: var(--text-primary); + background: var(--surface-hover); +} + +.seg-btn.is-active { + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-weight: 600; +} + +/* --- Architectural Precision Panels & Metric Matrices --- */ +.panel { + display: flex; + flex-direction: column; + flex-shrink: 0; + gap: var(--space-3); + padding: var(--space-4) var(--space-5); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); +} + +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); +} + +.panel-title { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + font-weight: 600; + color: var(--text-primary); +} + +.panel-meta { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 11.5px; + color: var(--text-secondary); +} + +/* 4-Cell Telemetry Matrix */ +.telemetry-matrix { + display: grid; + grid-template-columns: repeat(4, 1fr); + flex-shrink: 0; + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + background: var(--border-hairline); + gap: 1px; + overflow: hidden; +} + +.matrix-cell { + display: flex; + flex-direction: column; + gap: 2px; + padding: 7px 9px; + background: var(--surface-panel); + min-width: 0; +} + +.cell-label { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 11px; + color: var(--text-secondary); +} + +.cell-value { + font-size: 14.5px; + font-weight: 700; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.cell-value.accent-speed { + color: var(--metric-speed); +} + +.cell-value.accent-ok { + color: var(--metric-ok); +} + +.cell-sub { + font-size: 10.5px; + color: var(--text-secondary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* Context Segment Meter & Progress Bars */ +.progress-track { + width: 100%; + height: 6px; + background: var(--surface-track); + border-radius: var(--radius-xs); + overflow: hidden; + display: flex; +} + +.progress-seg { + height: 100%; + width: var(--seg-w, 0%); + transition: width var(--dur-normal) var(--ease-fast); +} + +.progress-seg.seg-messages { + background: var(--ctx-messages); +} +.progress-seg.seg-system-tools { + background: var(--ctx-system-tools); +} +.progress-seg.seg-mcp-tools { + background: var(--ctx-mcp-tools); +} +.progress-seg.seg-skills { + background: var(--ctx-skills); +} +.progress-seg.seg-system-prompt { + background: var(--ctx-system-prompt); +} +.progress-seg.seg-user-rules { + background: var(--ctx-user-rules); +} +.progress-seg.seg-cached { + background: var(--ctx-cached); +} +.progress-seg.seg-input { + background: var(--ctx-input); +} +.progress-seg.seg-thinking { + background: var(--ctx-thinking); +} +.progress-seg.seg-output { + background: var(--ctx-output); +} + +.progress-fill { + height: 100%; + width: var(--fill-w, 0%); + background: var(--accent-primary); + transition: width var(--dur-normal) var(--ease-fast); +} + +.progress-fill.tone-warn { + background: var(--metric-warn); +} + +.progress-fill.tone-danger { + background: var(--metric-danger); +} + +.ctx-legend-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 5px var(--space-4); + padding: 2px 0 0 0; + background: transparent; + border: none; + font-size: 11.5px; +} + +.legend-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); +} + +.legend-left { + display: inline-flex; + align-items: center; + gap: 5px; + color: var(--text-secondary); +} + +.swatch { + width: 7px; + height: 7px; + border-radius: 1px; + display: inline-block; +} + +.swatch.seg-messages { background: var(--ctx-messages); } +.swatch.seg-system-tools { background: var(--ctx-system-tools); } +.swatch.seg-mcp-tools { background: var(--ctx-mcp-tools); } +.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); } + +/* Dual Consumption Comparison Grid */ +.dual-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--space-3); +} + +@media (max-width: 390px) { + .telemetry-matrix { + grid-template-columns: repeat(2, 1fr); + } + .dual-grid { + grid-template-columns: 1fr; + } +} + +.ledger-box { + display: flex; + flex-direction: column; + gap: 5px; + padding: var(--space-3) var(--space-4); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); +} + +.ledger-box.is-primary { + background: color-mix(in srgb, var(--accent-primary) 4%, var(--surface-panel)); + border-color: var(--accent-primary-border); +} + +.ledger-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); +} + +.ledger-tag { + font-size: 10.5px; + padding: 0; + background: transparent; + border: none; + color: var(--text-secondary); +} + +.ledger-main { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-2); +} + +.ledger-tokens { + font-size: 16px; + font-weight: 700; + color: var(--text-primary); +} + +.ledger-cost { + font-size: 13px; + font-weight: 600; + color: var(--metric-speed); +} + +.ledger-foot { + font-size: 11px; + color: var(--text-secondary); + padding-top: 4px; + border-top: 1px solid var(--border-hairline); +} + +/* --- Rich Consumption Analytics Dashboard (5-Section Layout) --- */ +.cons-overview-head { + flex-wrap: wrap; + gap: 6px; +} + +.cons-badge { + font-size: 11px; + font-weight: 500; + padding: 0; + background: transparent; + border: none; + color: var(--text-secondary); +} + +.cons-box { + display: flex; + flex-direction: column; + gap: var(--space-3); + padding: var(--space-3) var(--space-4); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); +} + +.cons-unified-matrix { + gap: 0; + padding: 0; + border: none; + border-top: 1px solid var(--border-hairline); + border-bottom: 1px solid var(--border-hairline); + border-radius: 0; + overflow: hidden; +} + +.cons-split-3 { + display: grid; + 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-col { + display: flex; + flex-direction: column; + gap: 3px; + padding: 8px 10px; + min-width: 0; +} + +.cons-col:first-child { + padding-left: 0; +} + +.cons-col:last-child { + padding-right: 0; +} + +.cons-col.is-bordered-col, +.cons-col.is-right-col { + border-left: 1px solid var(--border-hairline); +} + +.cons-baseline { + display: flex; + align-items: baseline; + gap: 5px; + flex-wrap: wrap; +} + +.cons-hero-num { + font-size: 17px; + font-weight: 700; + color: var(--text-primary); + letter-spacing: -0.02em; +} + +.cons-hero-cost { + font-size: 17px; + font-weight: 700; + color: var(--accent-primary); + letter-spacing: -0.02em; +} + +.cons-hero-cache { + font-size: 17px; + font-weight: 700; + color: var(--ctx-cached); + letter-spacing: -0.02em; +} + +.cons-mid-num { + font-size: 13px; + font-weight: 700; + color: var(--text-primary); +} + +.dot-swatch { + width: 6px; + height: 6px; + border-radius: var(--radius-pill); + display: inline-block; + flex-shrink: 0; +} + +.dot-swatch.seg-input { background: var(--ctx-input); } +.dot-swatch.seg-cached { background: var(--ctx-cached); } +.dot-swatch.seg-output { background: var(--ctx-output); } +.dot-swatch.seg-thinking { background: var(--ctx-thinking); } + +/* Uniform 12px / 20px Row Header Alignment for Popular Models & Sources */ +.cons-row-title { + display: inline-flex; + align-items: center; + height: 20px; + line-height: 20px; + font-size: 12px; + font-weight: 600; + color: var(--text-primary); +} + +.cons-row-metrics { + display: inline-flex; + align-items: center; + gap: 8px; + height: 20px; +} + +.cons-share-pill { + display: inline-flex; + align-items: center; + justify-content: center; + height: 20px; + line-height: 1; + padding: 0 6px; + font-size: 12px; + font-weight: 600; + color: var(--metric-ok); + background: color-mix(in srgb, var(--metric-ok) 11%, transparent); + border: none; + border-radius: var(--radius-xs); + box-sizing: border-box; +} + +.cons-row-tok { + display: inline-flex; + align-items: center; + height: 20px; + line-height: 1; + font-size: 12px; + font-weight: 500; + color: var(--text-secondary); +} + +.cons-row-cost { + display: inline-flex; + align-items: center; + height: 20px; + line-height: 1; + font-size: 12px; + font-weight: 700; + color: var(--text-primary); +} + +.cons-seg-bar { + height: 5px; +} + +/* Historical Trend SVG Chart */ +.trend-chart-wrap { + position: relative; + width: 100%; + padding-top: 8px; +} + +.trend-svg { + width: 100%; + height: 112px; + display: block; + overflow: visible; +} + +.trend-grid line { + stroke: var(--border-hairline); + stroke-width: 1; + stroke-dasharray: 2 3; +} + +.trend-line { + stroke: var(--ctx-cached); + stroke-width: 2; + stroke-linecap: round; +} + +.trend-peak-dot { + fill: var(--ctx-cached); + stroke: var(--surface-panel); + stroke-width: 1.5; +} + +.trend-peak-pill { + position: absolute; + top: 2px; + left: var(--peak-x, 50%); + transform: translateX(-50%); + font-size: 10px; + font-weight: 600; + padding: 1px 6px; + color: var(--text-primary); + background: color-mix(in srgb, var(--ctx-cached) 16%, var(--surface-panel)); + border: none; + border-radius: var(--radius-xs); + pointer-events: none; + white-space: nowrap; +} + +.trend-anchors { + display: grid; + grid-template-columns: repeat(3, 1fr); + padding-top: 2px; + font-size: 11px; +} + +.trend-anchor-col { + display: flex; + flex-direction: column; + gap: 1px; +} + +.trend-anchor-col.is-center { + align-items: center; +} + +.trend-anchor-col.is-end { + align-items: flex-end; +} + +/* Popular Models & Sources Rows */ +.cons-item-list { + display: flex; + flex-direction: column; + gap: var(--space-4); +} + +.cons-item-row { + display: flex; + flex-direction: column; + gap: 6px; +} + +.cons-item-foot { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 10px; + font-size: 11px; + color: var(--text-secondary); +} + +.cons-item-foot strong { + color: var(--text-primary); + font-weight: 600; +} + +/* 12-Month Stacked Bar Chart */ +.monthly-grid { + display: grid; + grid-template-columns: repeat(12, 1fr); + gap: 3px; + align-items: end; + padding-top: var(--space-2); +} + +.month-col { + display: flex; + flex-direction: column; + align-items: center; + gap: 3px; + min-width: 0; +} + +.month-cost { + font-size: 9.5px; + color: var(--text-secondary); + min-height: 14px; + white-space: nowrap; +} + +.month-bar-well { + width: 100%; + height: 82px; + display: flex; + align-items: flex-end; + justify-content: center; +} + +.month-stack { + width: 72%; + max-width: 20px; + height: var(--bar-h, 0%); + display: flex; + flex-direction: column; + border-radius: 2px 2px 0 0; + overflow: hidden; + transition: height var(--dur-normal) var(--ease-fast); +} + +.month-seg { + width: 100%; + height: var(--seg-h, 0%); +} + +.month-seg.seg-input { background: var(--ctx-input); } +.month-seg.seg-cached { background: var(--ctx-cached); } +.month-seg.seg-output { background: var(--ctx-output); } +.month-seg.seg-thinking { background: var(--ctx-thinking); } + +.month-zero-dot { + width: 3px; + height: 3px; + border-radius: var(--radius-pill); + background: var(--border-strong); + margin-bottom: 4px; +} + +.month-label { + font-size: 10px; + color: var(--text-secondary); + padding: 1px 3px; + border-radius: var(--radius-xs); + white-space: nowrap; +} + +.month-label.is-current { + color: var(--ctx-cached); + background: color-mix(in srgb, var(--ctx-cached) 14%, transparent); + font-weight: 600; +} + +.month-tok { + font-size: 9px; + color: var(--text-muted); + min-height: 12px; + white-space: nowrap; +} + +.monthly-legend { + display: flex; + align-items: center; + justify-content: center; + gap: var(--space-4); + padding-top: var(--space-2); + font-size: 11px; + color: var(--text-secondary); +} + +/* --- Bespoke Custom Scrollbar (Dedicated Layout Gutter, Never Overlaps Content) --- */ +.custom-scroll-host { + position: relative; + display: flex; + flex-direction: row; + align-items: stretch; + gap: 5px; + min-height: 0; + overflow: hidden; +} + +.custom-scroll-host[hidden] { + display: none !important; +} + +.table-scroll-host { + flex: 1; + min-height: 0; + gap: 4px; + padding-top: 2px; + padding-right: 0; + border: none; + border-top: 1px solid var(--border-hairline); + border-radius: 0; + background: var(--surface-panel); +} + +.custom-scroll-content { + flex: 1; + min-width: 0; + min-height: 0; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + -ms-overflow-style: none; +} + +.custom-scroll-content::-webkit-scrollbar { + width: 0 !important; + height: 0 !important; + display: none !important; +} + +.scrollbar-rail { + position: relative; + flex-shrink: 0; + width: 5px; + margin: 2px 0; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--border-hairline) 35%, transparent); + z-index: 15; + opacity: 0.85; + transition: opacity var(--dur-fast) var(--ease-fast), background-color var(--dur-fast) var(--ease-fast); + cursor: pointer; +} + +.custom-scroll-host:hover .scrollbar-rail, +.scrollbar-rail.is-dragging { + opacity: 1; + background: color-mix(in srgb, var(--border-hairline) 65%, transparent); +} + +.scrollbar-rail.is-inactive { + display: none !important; + opacity: 0 !important; + pointer-events: none; +} + +.scrollbar-thumb { + width: 100%; + height: var(--thumb-h, 0px); + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-secondary) 32%, transparent); + transform: translate3d(0, var(--thumb-y, 0px), 0); + will-change: transform, height; + transition: background-color var(--dur-instant) var(--ease-fast); +} + +.scrollbar-rail:hover .scrollbar-thumb, +.scrollbar-rail.is-dragging .scrollbar-thumb { + background: color-mix(in srgb, var(--accent-primary) 72%, transparent); +} + +.table-viewport { + flex: 1; + min-height: 0; + overflow-y: auto; + overflow-x: hidden; + background: var(--surface-panel); +} + +.data-table { + width: 100%; + border-collapse: collapse; + font-size: 11px; +} + +.data-table th, +.data-table td { + padding: 5px 4px; + text-align: left; + border-bottom: 1px solid var(--border-hairline); + white-space: nowrap; +} + +.data-table th:first-child, +.data-table td:first-child { + padding-left: 7px; +} + +.data-table th:last-child, +.data-table td:last-child { + text-align: right; + padding-right: 10px; +} + +.data-table th { + position: sticky; + top: 0; + z-index: 2; + background: var(--surface-panel); + color: var(--text-secondary); + font-weight: 600; +} + +.data-table tbody tr:hover { + background: var(--surface-hover); +} + +/* Settings Form Layout */ +.form-row { + display: flex; + flex-direction: column; + gap: 5px; +} + +.form-label { + font-size: 11.5px; + font-weight: 500; + color: var(--text-secondary); +} + +.btn-primary { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 28px; + padding: 0 var(--space-5); + background: var(--accent-primary); + color: var(--text-inverse); + border: 1px solid var(--accent-primary); + border-radius: var(--radius-xs); + font-weight: 600; + font-size: 12px; + cursor: pointer; + transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast); +} + +.btn-primary:hover { + opacity: 0.92; +} + +.btn-primary:active { + transform: scale(0.98); +} diff --git a/sidecars/panel/src/styles/tokens.css b/sidecars/panel/src/styles/tokens.css new file mode 100644 index 0000000..dec6ba0 --- /dev/null +++ b/sidecars/panel/src/styles/tokens.css @@ -0,0 +1,82 @@ +/* + * Semantic Design Tokens for Antigravity Usage & Speed Monitor. + * All visual tokens derive from host CSS variables and perceptual color-mix(), + * eliminating hardcoded hex colors across components and views. + */ + +:root { + /* 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) */ + --surface-bg: var(--background, hsl(0 0% 100%)); + --surface-panel: var(--card, 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%)); + --text-secondary: var(--muted-foreground, hsl(215 12% 44%)); + --text-muted: color-mix(in srgb, var(--text-secondary) 74%, var(--surface-panel) 26%); + --text-inverse: var(--surface-panel); + + /* Semantic Telemetry Accents */ + --accent-primary: var(--primary, hsl(217 82% 51%)); + --accent-primary-soft: color-mix(in srgb, var(--accent-primary) 13%, transparent); + --accent-primary-border: color-mix(in srgb, var(--accent-primary) 38%, var(--border-hairline)); + + --metric-speed: hsl(14 76% 52%); + --metric-speed-soft: color-mix(in srgb, var(--metric-speed) 14%, transparent); + + --metric-ok: hsl(145 64% 38%); + --metric-ok-soft: color-mix(in srgb, var(--metric-ok) 14%, transparent); + + --metric-warn: hsl(34 86% 44%); + --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 6-Channel Palette */ + --ctx-messages: hsl(217 82% 51%); + --ctx-system-tools: hsl(22 86% 50%); + --ctx-mcp-tools: hsl(268 72% 56%); + --ctx-skills: hsl(145 64% 38%); + --ctx-system-prompt: hsl(190 80% 38%); + --ctx-user-rules: hsl(340 76% 52%); + + /* Legacy 4-Channel Palette (retained for compatibility) */ + --ctx-cached: hsl(217 82% 51%); + --ctx-input: hsl(22 86% 50%); + --ctx-thinking: hsl(145 64% 38%); + --ctx-output: hsl(190 80% 38%); + + /* Elevation & Shadows */ + --shadow-popover: 0 6px 20px color-mix(in srgb, var(--text-primary) 14%, transparent); + --shadow-glider: 0 1px 2px color-mix(in srgb, var(--text-primary) 10%, transparent); + + /* Fast Hardware-Accelerated Motion Tokens */ + --ease-fast: cubic-bezier(0.22, 1, 0.36, 1); + --dur-instant: 90ms; + --dur-fast: 140ms; + --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/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js new file mode 100644 index 0000000..4c241b1 --- /dev/null +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -0,0 +1,736 @@ +/** + * @fileoverview View 2: ConsumptionView (全景消耗统计视图). + * Implements the 5-part analytics layout: + * 1. 用量概览 (Total Tokens k/M/B, USD + CNY approx, Input/Output split, Cache Hit % + Saved Cost badge, 4-color bar) + * 2. 历史趋势 (Pure SVG smooth cubic-bezier spline area chart with peak callout and 3 time anchors) + * 3. 热门模型 (Per-model share badge, 4-segment bar, and Input/Cache/Output/Thinking breakdown) + * 4. 数据来源 (SOURCES breakdown with 4-segment bar) + * 5. 按月细分 (12-month stacked vertical bar chart with cost, stacked bars, and k/M/B totals) + */ + +import { defineComponent } from '../core/component.js'; +import { + h, + patchAttr, + patchClasses, + patchKeyedList, + patchStyleVar, + patchText, +} from '../core/domPatch.js'; +import { + formatCnyApprox, + formatDateSpanBadge, + formatTokensPrecise, + formatUsd, +} from '../core/formatters.js'; +import { createSvgIcon, SVG_NS } from '../icons/SvgIcon.js'; +import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js'; +import { uiStore } from '../store/uiStore.js'; +import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js'; +import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; +import { SegmentedControl } from '../components/ui/SegmentedControl.js'; + +const TIME_RANGE_OPTIONS = [ + { value: 'today', label: '今天' }, + { value: '24h', label: '1天' }, + { value: '7d', label: '7天' }, + { value: '14d', label: '14天' }, + { value: '30d', label: '30天' }, + { value: 'all', label: '全部' }, + { value: 'custom', label: '自定义' }, +]; + +function createFourSegmentBar() { + const segInput = h('div', { className: 'progress-seg seg-input' }); + const segCached = h('div', { className: 'progress-seg seg-cached' }); + const segOutput = h('div', { className: 'progress-seg seg-output' }); + const segThinking = h('div', { className: 'progress-seg seg-thinking' }); + const el = h('div', { className: 'progress-track cons-seg-bar' }, [ + segInput, + segCached, + segOutput, + segThinking, + ]); + + function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0 }) { + const total = Math.max(1, inputTokens + cacheReadTokens + responseTokens + thinkingTokens); + patchStyleVar(segInput, '--seg-w', `${((inputTokens / total) * 100).toFixed(2)}%`); + patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / total) * 100).toFixed(2)}%`); + patchStyleVar(segOutput, '--seg-w', `${((responseTokens / total) * 100).toFixed(2)}%`); + patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / total) * 100).toFixed(2)}%`); + } + + return { el, update }; +} + +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]; + const p1 = points[i + 1]; + const cpx1 = p0.x + (p1.x - p0.x) * 0.45; + const cpx2 = p1.x - (p1.x - p0.x) * 0.45; + d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; + } + return d; +} + +function createTrendAreaChart() { + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('viewBox', '0 0 460 116'); + svg.setAttribute('class', 'trend-svg'); + svg.setAttribute('aria-hidden', 'true'); + + const defs = document.createElementNS(SVG_NS, 'defs'); + const grad = document.createElementNS(SVG_NS, 'linearGradient'); + grad.setAttribute('id', 'trend-area-grad'); + grad.setAttribute('x1', '0'); + grad.setAttribute('y1', '0'); + grad.setAttribute('x2', '0'); + grad.setAttribute('y2', '1'); + + const stop1 = document.createElementNS(SVG_NS, 'stop'); + stop1.setAttribute('offset', '0%'); + stop1.setAttribute('stop-color', 'var(--ctx-cached)'); + stop1.setAttribute('stop-opacity', '0.36'); + + const stop2 = document.createElementNS(SVG_NS, 'stop'); + stop2.setAttribute('offset', '100%'); + stop2.setAttribute('stop-color', 'var(--ctx-cached)'); + stop2.setAttribute('stop-opacity', '0.0'); + + grad.appendChild(stop1); + grad.appendChild(stop2); + defs.appendChild(grad); + svg.appendChild(defs); + + // Subtle grid lines + const gridGroup = document.createElementNS(SVG_NS, 'g'); + gridGroup.setAttribute('class', 'trend-grid'); + for (const y of [26, 62, 98]) { + const line = document.createElementNS(SVG_NS, 'line'); + line.setAttribute('x1', '10'); + line.setAttribute('y1', String(y)); + line.setAttribute('x2', '450'); + line.setAttribute('y2', String(y)); + gridGroup.appendChild(line); + } + for (const x of [118, 230, 342]) { + const line = document.createElementNS(SVG_NS, 'line'); + line.setAttribute('x1', String(x)); + line.setAttribute('y1', '16'); + line.setAttribute('x2', String(x)); + line.setAttribute('y2', '98'); + gridGroup.appendChild(line); + } + svg.appendChild(gridGroup); + + const areaPath = document.createElementNS(SVG_NS, 'path'); + areaPath.setAttribute('fill', 'url(#trend-area-grad)'); + svg.appendChild(areaPath); + + const linePath = document.createElementNS(SVG_NS, 'path'); + linePath.setAttribute('class', 'trend-line'); + linePath.setAttribute('fill', 'none'); + svg.appendChild(linePath); + + const peakDot = document.createElementNS(SVG_NS, 'circle'); + peakDot.setAttribute('r', '3'); + peakDot.setAttribute('class', 'trend-peak-dot'); + svg.appendChild(peakDot); + + const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); + const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]); + + let lastLineD = ''; + + function update(series = []) { + const slots = series.length >= 2 ? series : [ + { label: '00:00', tokens: 0 }, + { label: '06:00', tokens: 0 }, + { label: '12:00', tokens: 0 }, + ]; + let maxTokens = 0; + let peakIdx = 0; + for (let i = 0; i < slots.length; i++) { + const t = Number(slots[i].tokens || 0); + if (t >= maxTokens) { + maxTokens = t; + peakIdx = i; + } + } + + const leftX = 12; + const rightX = 448; + const topY = 26; + const bottomY = 98; + const spanX = rightX - leftX; + const spanY = bottomY - topY; + const denom = Math.max(1, maxTokens); + + const pts = slots.map((s, idx) => { + const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX; + const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0; + const y = bottomY - ratio * spanY; + return { x, y }; + }); + + const lineD = buildSmoothSplinePath(pts); + if (lineD !== lastLineD) { + lastLineD = lineD; + const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`; + patchAttr(linePath, 'd', lineD); + patchAttr(areaPath, 'd', areaD); + } + + const peakPt = pts[peakIdx] || { x: 230, y: bottomY }; + patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); + patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); + + patchText(peakPill, formatTokensPrecise(maxTokens)); + const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100)); + patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + } + + return { el: chartWrap, update }; +} + +export const ConsumptionView = defineComponent({ + name: 'ConsumptionView', + setup({ onCleanup }) { + // Default to 'today' if store is on initial 'all' or keep user's selection + const timeFilterSwitch = SegmentedControl({ + ariaLabel: '消耗统计时间范围', + modelValue: telemetryStore.getState().selectedTimeRange, + options: TIME_RANGE_OPTIONS, + onUpdateModelValue: (nextRange) => { + telemetryStore.setState({ selectedTimeRange: nextRange }); + fetchTelemetry({ force: false }); + }, + }); + + const startPicker = CustomDateTimePicker({ + modelValue: telemetryStore.getState().customStartMs, + onUpdateModelValue: (ms) => { + telemetryStore.setState({ customStartMs: ms }); + }, + }); + + const endPicker = CustomDateTimePicker({ + modelValue: telemetryStore.getState().customEndMs, + onUpdateModelValue: (ms) => { + telemetryStore.setState({ customEndMs: ms }); + }, + }); + + const applyCustomBtn = h( + 'button', + { + type: 'button', + className: 'btn-primary', + style: 'height: 26px; padding: 0 10px;', + onClick: () => { + telemetryStore.setState({ selectedTimeRange: 'custom' }); + fetchTelemetry({ force: true }); + }, + }, + [createSvgIcon('check', { size: 12 }), h('span', { text: '筛选' })] + ); + + const customRangeBar = h( + 'div', + { + style: + 'display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs);', + hidden: true, + }, + [ + startPicker.el, + h('span', { className: 'text-muted', text: '至' }), + endPicker.el, + applyCustomBtn, + ] + ); + + // --- Section 1: 用量概览 (Compact Integrated Overview) --- + 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 调用' }); + const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); + const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '≈ ¥0' }); + + const cacheHitPctEl = h('strong', { className: 'cons-hero-cache text-mono', text: '0%' }); + const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '命中 0' }); + + 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 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' }); + const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '内容生成 0 · 思考推理 0' }); + + const overviewSegBar = createFourSegmentBar(); + + const overviewPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header cons-overview-head' }, [ + h('span', { className: 'panel-title' }, [ + h('span', { text: '用量概览' }), + dateSpanBadge, + ]), + timeFilterSwitch.el, + ]), + customRangeBar, + h('div', { className: 'cons-box cons-unified-matrix' }, [ + h('div', { className: 'cons-split-3' }, [ + h('div', { className: 'cons-col' }, [ + h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token 数' }), + h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '预估费用' }), + h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('span', { className: 'legend-left', style: 'font-size: 11px;' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存命中率' }), + ]), + h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), + ]), + ]), + h('div', { className: 'cons-split-2 cons-matrix-bottom' }, [ + h('div', { className: 'cons-col' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输入用量' }), + inputMainTokens, + ]), + inputSharePct, + ]), + inputSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输出用量' }), + outputMainTokens, + ]), + outputSharePct, + ]), + outputSubText, + ]), + ]), + ]), + overviewSegBar.el, + ]); + + // --- Section 2: 历史趋势 (Historical Trend SVG Spline Area Chart) --- + const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' }); + const trendChart = createTrendAreaChart(); + const anchorStartTime = h('span', { className: 'text-muted text-mono', text: '00:00' }); + const anchorStartVal = h('strong', { className: 'text-mono', text: '0' }); + const anchorMidTime = h('span', { className: 'text-muted text-mono', text: '06:00' }); + const anchorMidVal = h('strong', { className: 'text-mono', text: '0' }); + const anchorEndTime = h('span', { className: 'text-muted text-mono', text: '12:00' }); + const anchorEndVal = h('strong', { className: 'text-mono', text: '0' }); + + const trendPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '历史趋势' }), + trendRangeBadge, + ]), + trendChart.el, + h('div', { className: 'trend-anchors' }, [ + h('div', { className: 'trend-anchor-col' }, [anchorStartTime, anchorStartVal]), + h('div', { className: 'trend-anchor-col is-center' }, [anchorMidTime, anchorMidVal]), + h('div', { className: 'trend-anchor-col is-end' }, [anchorEndTime, anchorEndVal]), + ]), + ]); + + // --- Section 3: 热门模型 (Popular Models Breakdown) --- + const modelsListEl = h('div', { className: 'cons-item-list' }); + const modelsPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '热门模型' }), + ]), + modelsListEl, + ]); + + // --- Section 4: 数据来源 --- + const sourcesListEl = h('div', { className: 'cons-item-list' }); + const sourcesPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '数据来源' }), + ]), + sourcesListEl, + ]); + + // --- Section 5: 按月细分 (12-Month Stacked Bar Chart) --- + const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' }); + const monthlyCols = Array.from({ length: 12 }, (_, idx) => { + const costText = h('span', { className: 'month-cost text-mono', text: '' }); + const barThink = h('div', { className: 'month-seg seg-thinking' }); + const barOut = h('div', { className: 'month-seg seg-output' }); + const barCache = h('div', { className: 'month-seg seg-cached' }); + const barIn = h('div', { className: 'month-seg seg-input' }); + const stackWrap = h('div', { className: 'month-stack' }, [ + barThink, + barOut, + barCache, + barIn, + ]); + const zeroDot = h('span', { className: 'month-zero-dot' }); + const monthLabel = h('span', { className: 'month-label', text: `${idx + 1}月` }); + const tokText = h('span', { className: 'month-tok text-mono', text: '' }); + + const colEl = h('div', { className: 'month-col' }, [ + costText, + h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), + monthLabel, + tokText, + ]); + return { + el: colEl, + costText, + stackWrap, + zeroDot, + barThink, + barOut, + barCache, + barIn, + monthLabel, + tokText, + }; + }); + + const monthlyPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title', text: '按月细分' }), + monthlyYearBadge, + ]), + h( + 'div', + { className: 'monthly-grid' }, + monthlyCols.map((c) => c.el) + ), + h('div', { className: 'monthly-legend' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + h('span', { text: '输入' }), + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存' }), + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + h('span', { text: '输出' }), + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + h('span', { text: '思考' }), + ]), + ]), + ]); + + const scrollInner = h( + 'div', + { + style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: var(--space-3);', + }, + [ + overviewPanel, + trendPanel, + modelsPanel, + sourcesPanel, + monthlyPanel, + ] + ); + + const viewScrollbar = CustomScrollbar({ + contentEl: scrollInner, + className: 'view-pane', + }); + + function createBreakdownItemRow() { + const nameEl = h('strong', { className: 'cons-row-title' }); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const segBar = createFourSegmentBar(); + + const inVal = h('strong', { className: 'text-mono' }); + const cacheVal = h('strong', { className: 'text-mono' }); + const outVal = h('strong', { className: 'text-mono' }); + const thinkVal = h('strong', { className: 'text-mono' }); + const callsVal = h('strong', { className: 'text-mono' }); + + const rowEl = h('div', { className: 'cons-item-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [ + pctBadge, + totalTokEl, + costEl, + ]), + ]), + segBar.el, + h('div', { className: 'cons-item-foot' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + h('span', { text: '输入 ' }), + inVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + h('span', { text: '缓存 ' }), + cacheVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + h('span', { text: '输出 ' }), + outVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + h('span', { text: '思考 ' }), + thinkVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { text: '调用 ' }), + callsVal, + ]), + ]), + ]); + + return { + el: rowEl, + refs: { nameEl, pctBadge, totalTokEl, costEl, segBar, inVal, cacheVal, outVal, thinkVal, callsVal }, + }; + } + + function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) { + patchText(refs.nameEl, item.label || item.name || item.shortName || '—'); + const total = Number(item.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : ''); + patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader); + patchText(refs.costEl, formatUsd(item.costUsd || 0)); + + const responseTok = + item.responseTokens != null + ? Number(item.responseTokens) + : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); + const thinkingTok = Number(item.thinkingTokens || 0); + + refs.segBar.update({ + inputTokens: Number(item.inputTokens || 0), + cacheReadTokens: Number(item.cacheReadTokens || 0), + responseTokens: responseTok, + thinkingTokens: thinkingTok, + }); + + patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); + patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); + patchText(refs.outVal, formatTokensPrecise(responseTok)); + patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); + patchText(refs.callsVal, String(Number(item.calls || 0))); + } + + let latestSlice = null; + let isDirty = false; + + function renderConsumptionData(slice) { + if (!slice) return; + timeFilterSwitch.setValue(slice.range); + patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); + startPicker.setValue(slice.customStartMs); + endPicker.setValue(slice.customEndMs); + + const cons = slice.consumption || {}; + const preset = + slice.range !== 'custom' && cons.presets?.[slice.range] + ? cons.presets[slice.range] + : null; + const acct = preset?.account || cons.account || {}; + const rangeInfo = cons.selectedRange || {}; + + // 1. Overview + patchText(dateSpanBadge, formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs)); + const totalTokens = Number(acct.totalTokens || 0); + const inputTokens = Number(acct.inputTokens || 0); + const cacheTokens = Number(acct.cacheReadTokens || 0); + const outputTokens = Number(acct.outputTokens || 0); + const responseTokens = Number(acct.responseTokens || 0); + const thinkingTokens = Number(acct.thinkingTokens || 0); + const costUsd = Number(acct.costUsd || 0); + + patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); + patchText(heroTotalCalls, `${acct.calls || 0} 调用`); + patchText(heroCostUsd, formatUsd(costUsd)); + patchText(heroCostCny, formatCnyApprox(costUsd)); + + 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; + patchText(inputSharePct, `${inPct}%`); + patchText(inputMainTokens, formatTokensPrecise(inputTokens)); + patchText( + inputSubText, + `直接输入 ${formatTokensPrecise(inputTokens)} · 缓存读取 ${formatTokensPrecise(cacheTokens)}` + ); + + patchText(outputSharePct, `${outPct}%`); + patchText(outputMainTokens, formatTokensPrecise(outputTokens)); + patchText( + outputSubText, + `内容生成 ${formatTokensPrecise(responseTokens)} · 思考推理 ${formatTokensPrecise(thinkingTokens)}` + ); + + overviewSegBar.update({ + inputTokens, + cacheReadTokens: cacheTokens, + responseTokens, + thinkingTokens, + }); + + // 2. Historical Trend + patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间'); + const trendSeries = cons.trendSeries || []; + trendChart.update(trendSeries); + if (trendSeries.length > 0) { + const first = trendSeries[0]; + const mid = trendSeries[Math.floor(trendSeries.length / 2)]; + const last = trendSeries[trendSeries.length - 1]; + patchText(anchorStartTime, first.label); + patchText(anchorStartVal, formatTokensPrecise(first.tokens)); + patchText(anchorMidTime, mid.label); + patchText(anchorMidVal, formatTokensPrecise(mid.tokens)); + patchText(anchorEndTime, last.label); + patchText(anchorEndVal, formatTokensPrecise(last.tokens)); + } + + // 3. Popular Models + const models = (slice.modelBreakdown || []) + .slice() + .sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0)); + const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0); + + patchKeyedList(modelsListEl, models, { + keyFn: (m) => m.label || m.shortName, + sigFn: (m) => + `${m.label}:${m.totalTokens}:${m.costUsd}:${m.calls}:${modelsTotalTok}`, + createRow: createBreakdownItemRow, + updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true), + }); + + // 4. Sources Breakdown + const sources = cons.sourcesBreakdown || []; + const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); + patchKeyedList(sourcesListEl, sources, { + keyFn: (s) => s.name, + sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.calls}:${sourcesTotalTok}`, + createRow: createBreakdownItemRow, + updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true), + }); + + // 5. Monthly Breakdown + const monthlyYear = cons.monthlyYear || new Date().getFullYear(); + const currentMonthIdx = new Date().getMonth(); + patchText(monthlyYearBadge, String(monthlyYear)); + const monthlySeries = cons.monthlySeries || []; + const maxMonthTokens = Math.max( + 1, + ...monthlySeries.map((m) => Number(m.totalTokens || 0)) + ); + + for (let i = 0; i < 12; i++) { + const col = monthlyCols[i]; + const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0 }; + const mTot = Number(m.totalTokens || 0); + const hasData = mTot > 0; + + patchClasses(col.monthLabel, { 'is-current': i === currentMonthIdx }); + patchAttr(col.stackWrap, 'hidden', !hasData); + patchAttr(col.zeroDot, 'hidden', hasData); + + if (!hasData) { + patchText(col.costText, ''); + patchText(col.tokText, ''); + } else { + const cVal = Number(m.costUsd || 0); + patchText(col.costText, cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); + patchText(col.tokText, formatTokensPrecise(mTot)); + + const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); + patchStyleVar(col.stackWrap, '--bar-h', `${totalHeightPct.toFixed(1)}%`); + + const inPctM = (Number(m.inputTokens || 0) / mTot) * 100; + const cachePctM = (Number(m.cacheReadTokens || 0) / mTot) * 100; + const outPctM = (Number(m.responseTokens || 0) / mTot) * 100; + const thinkPctM = (Number(m.thinkingTokens || 0) / mTot) * 100; + + patchStyleVar(col.barIn, '--seg-h', `${inPctM.toFixed(1)}%`); + patchStyleVar(col.barCache, '--seg-h', `${cachePctM.toFixed(1)}%`); + patchStyleVar(col.barOut, '--seg-h', `${outPctM.toFixed(1)}%`); + patchStyleVar(col.barThink, '--seg-h', `${thinkPctM.toFixed(1)}%`); + } + } + + viewScrollbar.refresh(); + } + + const unsub = telemetryStore.subscribe( + (st) => ({ + range: st.selectedTimeRange, + customStartMs: st.customStartMs, + customEndMs: st.customEndMs, + consumption: st.telemetry?.consumption, + modelBreakdown: st.telemetry?.modelBreakdown, + }), + (slice) => { + latestSlice = slice; + if (uiStore.getState().activeView !== 'consumption') { + isDirty = true; + return; + } + isDirty = false; + renderConsumptionData(slice); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'consumption' && isDirty) { + isDirty = false; + if (latestSlice) { + renderConsumptionData(latestSlice); + } + } + } + ); + + onCleanup(() => { + unsub(); + unsubView(); + timeFilterSwitch.destroy(); + startPicker.destroy(); + endPicker.destroy(); + viewScrollbar.destroy(); + }); + + return { + el: viewScrollbar.el, + refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar }, + }; + }, +}); diff --git a/sidecars/panel/src/views/LiveOverviewView.js b/sidecars/panel/src/views/LiveOverviewView.js new file mode 100644 index 0000000..efc05c2 --- /dev/null +++ b/sidecars/panel/src/views/LiveOverviewView.js @@ -0,0 +1,374 @@ +/** + * @fileoverview View 1: LiveOverviewView (实时监控视图). + * Displays real-time TPS, TTFT, weighted mean speed, 4-channel Context Window + * breakdown automatically anchored to the current model's compaction baseline, + * and official 5h/weekly quota pools for both Gemini and Claude & GPT. + */ + +import { defineComponent } from '../core/component.js'; +import { + h, + patchClasses, + patchStyleVar, + patchText, +} from '../core/domPatch.js'; +import { + formatCountdown, + formatMetric, + formatTokens, + formatUsd, + sampleSummary, + speedReasonText, +} from '../core/formatters.js'; +import { createSvgIcon } from '../icons/SvgIcon.js'; +import { telemetryStore } from '../store/telemetryStore.js'; +import { uiStore } from '../store/uiStore.js'; +import { ContextSegmentMeter } from '../components/ui/ContextSegmentMeter.js'; +import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; + +export const LiveOverviewView = defineComponent({ + name: 'LiveOverviewView', + setup({ onCleanup }) { + // 1. 4-Cell Real-time Telemetry Matrix + const tpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); + const tpsSub = h('span', { className: 'cell-sub', text: 'argon-4' }); + const pulseDot = createSvgIcon('dot', { size: 10 }); + + const ttftVal = h('strong', { className: 'cell-value', text: '—' }); + const ttftSub = h('span', { className: 'cell-sub', text: '均值 —' }); + + 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 cacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累 $0.00' }); + + const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '核心测速指标' }, [ + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [h('span', { text: '实时吞吐' }), pulseDot]), + tpsVal, + tpsSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '首Token' }), + createSvgIcon('clock', { size: 11 }), + ]), + ttftVal, + ttftSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '会话均速' }), + createSvgIcon('pulse', { size: 11 }), + ]), + avgVal, + avgSub, + ]), + h('div', { className: 'matrix-cell' }, [ + h('div', { className: 'cell-label' }, [ + h('span', { text: '本步消费' }), + createSvgIcon('bolt', { size: 11 }), + ]), + costVal, + cacheSub, + ]), + ]); + + // 2. Context Window 6-Segment Panel (Auto Compaction Baseline) + const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' }); + const ctxSegmentBar = ContextSegmentMeter({ context: {} }); + + const bdMessages = h('strong', { className: 'text-mono', text: '0' }); + const bdSystemTools = h('strong', { className: 'text-mono', text: '0' }); + const bdMcpTools = h('strong', { className: 'text-mono', text: '0' }); + const bdSkills = h('strong', { className: 'text-mono', text: '0' }); + const bdSystemPrompt = h('strong', { className: 'text-mono', text: '0' }); + const bdUserRules = h('strong', { className: 'text-mono', text: '0' }); + + const ctxPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('layers', { size: 13 }), + h('span', { text: '上下文窗口构成' }), + ]), + h('span', { className: 'panel-meta' }, [ctxSummaryText]), + ]), + ctxSegmentBar.el, + h('div', { className: 'ctx-legend-grid' }, [ + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-messages' }), + h('span', { text: '消息' }), + ]), + bdMessages, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-system-tools' }), + h('span', { text: '系统工具' }), + ]), + bdSystemTools, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-mcp-tools' }), + h('span', { text: 'MCP 工具' }), + ]), + bdMcpTools, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-skills' }), + h('span', { text: 'Skill' }), + ]), + bdSkills, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-system-prompt' }), + h('span', { text: '系统提示词' }), + ]), + bdSystemPrompt, + ]), + h('div', { className: 'legend-item' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'swatch seg-user-rules' }), + h('span', { text: 'user_rule' }), + ]), + bdUserRules, + ]), + ]), + ]); + + // 3. Official 5h & Weekly Quotas Panel (Gemini Pool + Claude Pool) + const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); + + function createPoolQuotaBlock(poolLabel) { + const title5h = h('span', { text: `5h 限额 (${poolLabel})` }); + const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fill5h = h('div', { className: 'progress-fill' }); + + const titleWk = h('span', { text: `每周限额 (${poolLabel})` }); + const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' }); + const fillWk = h('div', { className: 'progress-fill' }); + + const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ + h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [title5h, meta5h]), + h('div', { className: 'progress-track' }, [fill5h]), + ]), + h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ + h('div', { className: 'panel-header' }, [titleWk, metaWk]), + h('div', { className: 'progress-track' }, [fillWk]), + ]), + ]); + + return { el, title5h, meta5h, fill5h, titleWk, metaWk, fillWk }; + } + + const geminiQuotaBlock = createPoolQuotaBlock('Gemini'); + const claudeQuotaBlock = createPoolQuotaBlock('Claude & GPT'); + claudeQuotaBlock.el.setAttribute( + 'style', + 'display: flex; flex-direction: column; gap: 8px; margin-top: 3px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' + ); + + const wkFootLeft = h('span', { className: 'text-muted', text: '本周本机: 0 ($0.00)' }); + const wkFootRight = h('span', { className: 'text-muted', text: '' }); + + const quotaPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + h('span', { text: '官方配额与周期监控' }), + ]), + tierBadge, + ]), + geminiQuotaBlock.el, + claudeQuotaBlock.el, + h('div', { className: 'panel-header', style: 'font-size: 11px; padding-top: 2px;' }, [ + wkFootLeft, + wkFootRight, + ]), + ]); + + const overviewInner = h( + 'div', + { + style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', + }, + [matrixEl, ctxPanel, quotaPanel] + ); + const viewScrollbar = CustomScrollbar({ + contentEl: overviewInner, + className: 'view-pane', + }); + + function syncPoolQuotaBlock(block, poolLabel, poolData, fallbackWeekly, isActiveFamily) { + const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; + const used5hVal = has5h ? Number(poolData.usedPct) : 0; + const rem5hVal = has5h ? Number(poolData.remainingPct) : 0; + patchText(block.title5h, `5h 限额 (${poolLabel})`); + patchText( + block.meta5h, + has5h + ? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)` + : '获取失败 (--%)' + ); + patchStyleVar(block.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); + patchClasses(block.fill5h, { + 'tone-warn': used5hVal >= 60 && used5hVal < 85, + 'tone-danger': used5hVal >= 85, + }); + + const wkUsedRaw = + poolData?.weeklyUsedPct ?? (isActiveFamily ? fallbackWeekly?.usedPct : null); + const wkRemRaw = + poolData?.weeklyRemainingPct ?? (isActiveFamily ? fallbackWeekly?.remainingPct : null); + const wkResetRaw = + poolData?.weeklyResetTime || (isActiveFamily ? fallbackWeekly?.resetTime : null); + const hasWk = wkUsedRaw != null && wkRemRaw != null; + const usedWkVal = hasWk ? Number(wkUsedRaw) : 0; + const remWkVal = hasWk ? Number(wkRemRaw) : 0; + + const customTitle = + isActiveFamily && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title + ? fallbackWeekly.title + : `每周限额 (${poolLabel})`; + patchText(block.titleWk, customTitle); + patchText( + block.metaWk, + hasWk + ? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)` + : '获取失败 (--%)' + ); + patchStyleVar(block.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); + patchClasses(block.fillWk, { + 'tone-warn': usedWkVal >= 60 && usedWkVal < 85, + 'tone-danger': usedWkVal >= 85, + }); + } + + let latestData = null; + let isDirty = false; + + function renderData(data) { + if (!data) return; + const active = data.activeConversation || {}; + const ctx = active.context || {}; + const quotas = data.quotas || {}; + + // 1. Matrix + patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) }); + patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s')); + const reason = speedReasonText(active.latestSpeedReason); + patchText( + tpsSub, + reason ? `${active.activeModelShort || 'argon-4'} · ${reason}` : active.activeModelShort || 'argon-4' + ); + + patchText(ttftVal, formatMetric(active.latestTtftSec, 's')); + patchText(ttftSub, `均值 ${formatMetric(active.ttftSummary?.avgSec, 's')}`); + + patchText(avgVal, formatMetric(active.avgTokPerSec, ' tok/s')); + patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`); + + const stepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0); + patchText(costVal, formatUsd(stepCost, { precise: true })); + patchText( + cacheSub, + `缓 ${active.latestCacheHitPct ?? 0}% · 累 ${formatUsd(active.sessionCostUsd || 0)}` + ); + + // 2. Context (Auto Compaction Baseline) + 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; + patchText( + ctxSummaryText, + `${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)` + ); + ctxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } }); + patchText(bdMessages, formatTokens(ctx.messagesTokens || 0)); + patchText(bdSystemTools, formatTokens(ctx.systemToolsTokens || 0)); + patchText(bdMcpTools, formatTokens(ctx.mcpToolsTokens || 0)); + patchText(bdSkills, formatTokens(ctx.skillsTokens || 0)); + patchText(bdSystemPrompt, formatTokens(ctx.systemPromptTokens || 0)); + patchText(bdUserRules, formatTokens(ctx.userRulesTokens || 0)); + + // 3. Quotas (Gemini + Claude & GPT) + patchText( + tierBadge, + `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` + ); + const activePool = quotas.activePool || {}; + const pools = quotas.pools || []; + const weekly = quotas.weekly || {}; + + const geminiPool = + pools.find((p) => p.family === 'Gemini') || + (activePool.family === 'Gemini' ? activePool : null) || + {}; + const claudePool = + pools.find((p) => p.family === 'Claude & GPT' || p.family === 'Claude') || + (activePool.family && activePool.family !== 'Gemini' ? activePool : null) || + {}; + + const activeIsGemini = (activePool.family || 'Gemini') === 'Gemini'; + syncPoolQuotaBlock(geminiQuotaBlock, 'Gemini', geminiPool, weekly, activeIsGemini); + syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, !activeIsGemini); + + patchText( + wkFootLeft, + `本周本机: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0)})` + ); + patchText( + wkFootRight, + data.account?.aiCredits > 0 + ? `AI 积分: ${data.account.aiCredits}` + : `本机调用: ${weekly.calls || 0} 步` + ); + + viewScrollbar.refresh(); + } + + const unsub = telemetryStore.subscribe( + (st) => st.telemetry, + (data) => { + latestData = data; + if (uiStore.getState().activeView !== 'overview') { + isDirty = true; + return; + } + isDirty = false; + renderData(data); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'overview' && isDirty) { + isDirty = false; + if (latestData) { + renderData(latestData); + } + } + } + ); + + onCleanup(() => { + unsub(); + unsubView(); + ctxSegmentBar.destroy(); + viewScrollbar.destroy(); + }); + + return { + el: viewScrollbar.el, + refs: { viewScrollbar }, + }; + }, +}); diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js new file mode 100644 index 0000000..7acc752 --- /dev/null +++ b/sidecars/panel/src/views/SettingsView.js @@ -0,0 +1,163 @@ +/** + * @fileoverview View 4: SettingsView (系统设置视图). + * Replaces all native form controls () with + * bespoke CustomSelect and CustomNumberInput components. + */ + +import { defineComponent } from '../core/component.js'; +import { h, patchText } from '../core/domPatch.js'; +import { createSvgIcon } from '../icons/SvgIcon.js'; +import { + saveSettingsPatch, + telemetryStore, +} from '../store/telemetryStore.js'; +import { uiStore } from '../store/uiStore.js'; +import { CustomNumberInput } from '../components/ui/CustomNumberInput.js'; +import { CustomSelect } from '../components/ui/CustomSelect.js'; + +const WEEKLY_MODE_OPTIONS = [ + { value: 'official', label: '官方云端周限额 (与 Models & Usage 同步)' }, + { value: 'custom_tokens', label: '按自定义每周 Token 预算计算百分比' }, + { value: 'custom_cost', label: '按自定义每周美元 ($) 预算计算百分比' }, +]; + +export const SettingsView = defineComponent({ + name: 'SettingsView', + setup({ onCleanup }) { + let draftMode = 'official'; + let draftTokens = 150000000; + let draftCost = 100; + + const modeSelect = CustomSelect({ + modelValue: draftMode, + icon: 'sliders', + options: WEEKLY_MODE_OPTIONS, + onUpdateModelValue: (val) => { + draftMode = val; + }, + }); + + 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 saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' }); + + const saveBtn = h( + 'button', + { + type: 'button', + className: 'btn-primary', + onClick: async () => { + patchText(saveStatusText, '正在异步保存...'); + await saveSettingsPatch({ + weeklyLimitMode: draftMode, + weeklyTokenBudget: draftTokens, + weeklyCostBudget: draftCost, + }); + patchText(saveStatusText, '设置已生效'); + setTimeout(() => patchText(saveStatusText, ''), 1500); + }, + }, + [createSvgIcon('check', { size: 13 }), h('span', { text: '保存参数设置' })] + ); + + const budgetPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('sliders', { size: 13 }), + h('span', { text: '监控口径与周限额基准设置' }), + ]), + saveStatusText, + ]), + 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 预算基准 (步进 1M)' }), + tokenBudgetInput.el, + ]), + h('div', { className: 'form-row' }, [ + h('span', { className: 'form-label', text: '每周费用预算基准 (USD $, 步进 $5)' }), + costBudgetInput.el, + ]), + ]), + h('div', { style: 'display: flex; justify-content: flex-end;' }, [saveBtn]), + ]); + + const rootEl = h('div', { className: 'view-pane' }, [budgetPanel]); + + let latestSettings = null; + let isDirty = false; + + function renderSettings(settings) { + if (!settings) return; + draftMode = + settings.weeklyLimitMode === 'custom_tokens' || + settings.weeklyLimitMode === 'custom_cost' + ? settings.weeklyLimitMode + : 'official'; + draftTokens = Number(settings.weeklyTokenBudget || 150000000); + draftCost = Number(settings.weeklyCostBudget || 100); + modeSelect.setValue(draftMode); + tokenBudgetInput.setValue(draftTokens); + costBudgetInput.setValue(draftCost); + } + + const unsub = telemetryStore.subscribe( + (st) => st.telemetry?.settings, + (settings) => { + latestSettings = settings; + if (uiStore.getState().activeView !== 'settings') { + isDirty = true; + return; + } + isDirty = false; + renderSettings(settings); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'settings' && isDirty) { + isDirty = false; + if (latestSettings) { + renderSettings(latestSettings); + } + } + } + ); + + onCleanup(() => { + unsub(); + unsubView(); + modeSelect.destroy(); + tokenBudgetInput.destroy(); + costBudgetInput.destroy(); + }); + + return { + el: rootEl, + refs: { modeSelect, tokenBudgetInput, costBudgetInput }, + }; + }, +}); diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js new file mode 100644 index 0000000..1d14bc4 --- /dev/null +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -0,0 +1,274 @@ +/** + * @fileoverview View 3: StepsDetailView (步骤明细与按模型汇总视图). + * Uses patchKeyedList for incremental row reconciliation without innerHTML resets, + * wraps tables in bespoke CustomScrollbar (zero native OS scrollbars), and provides + * a live row inspector bar replacing native browser title tooltips. + */ + +import { defineComponent } from '../core/component.js'; +import { + h, + patchAttr, + patchClasses, + patchKeyedList, + patchText, +} from '../core/domPatch.js'; +import { + formatMetric, + formatTokens, + formatUsd, + sampleSummary, + speedReasonText, +} from '../core/formatters.js'; +import { createSvgIcon } from '../icons/SvgIcon.js'; +import { telemetryStore } from '../store/telemetryStore.js'; +import { uiStore } from '../store/uiStore.js'; +import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; +import { SegmentedControl } from '../components/ui/SegmentedControl.js'; + +export const StepsDetailView = defineComponent({ + name: 'StepsDetailView', + setup({ onCleanup }) { + const subTabSwitch = SegmentedControl({ + ariaLabel: '明细表视图切换', + modelValue: uiStore.getState().stepsSubTab, + options: [ + { value: 'steps', label: '单步测速 (0步)' }, + { value: 'models', label: '按模型汇总' }, + ], + onUpdateModelValue: (nextTab) => { + uiStore.setState({ stepsSubTab: nextTab }); + }, + }); + + const stepsTbody = h('tbody'); + const stepsTablePane = h('div', { className: 'table-viewport' }, [ + h('table', { className: 'data-table' }, [ + h('thead', {}, [ + h('tr', {}, [ + h('th', { text: '步' }), + h('th', { text: '模型' }), + h('th', { text: '速度' }), + h('th', { text: '首Token' }), + h('th', { text: '上下文/输出' }), + h('th', { text: '缓存' }), + h('th', { text: '消费' }), + ]), + ]), + stepsTbody, + ]), + ]); + const stepsScroll = CustomScrollbar({ + contentEl: stepsTablePane, + className: 'table-scroll-host', + }); + + const modelsTbody = h('tbody'); + const modelsTablePane = h('div', { className: 'table-viewport' }, [ + h('table', { className: 'data-table' }, [ + h('thead', {}, [ + h('tr', {}, [ + h('th', { text: '模型' }), + h('th', { text: '次数' }), + h('th', { text: '均速' }), + h('th', { text: '总 Token' }), + h('th', { text: '折算费用' }), + ]), + ]), + modelsTbody, + ]), + ]); + const modelsScroll = CustomScrollbar({ + contentEl: modelsTablePane, + className: 'table-scroll-host', + }); + modelsScroll.el.setAttribute('hidden', ''); + + const panelEl = h( + 'section', + { + className: 'panel', + style: 'flex: 1; min-height: 0; display: flex; flex-direction: column;', + }, + [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('table', { size: 13 }), + h('span', { text: '全量测速与计费矩阵' }), + ]), + subTabSwitch.el, + ]), + stepsScroll.el, + modelsScroll.el, + ] + ); + + const rootEl = h('div', { className: 'view-pane' }, [panelEl]); + + const unsubUi = uiStore.subscribe( + (st) => st.stepsSubTab, + (tab) => { + subTabSwitch.setValue(tab); + patchAttr(stepsScroll.el, 'hidden', tab !== 'steps'); + patchAttr(modelsScroll.el, 'hidden', tab !== 'models'); + if (tab === 'steps') stepsScroll.refresh(); + else modelsScroll.refresh(); + } + ); + + let latestSlice = null; + let isDirty = false; + + function renderStepsData(slice) { + if (!slice) return; + const steps = slice.recentSteps || []; + const models = slice.modelBreakdown || []; + + subTabSwitch.setProps({ + options: [ + { value: 'steps', label: `单步测速 (${steps.length}步)` }, + { value: 'models', label: `按模型汇总 (${slice.rangeLabel})` }, + ], + }); + + patchKeyedList(stepsTbody, steps, { + keyFn: (st) => `${slice.cascadeId || 'conv'}-${st.stepIndex}`, + sigFn: (st) => + `${st.stepIndex}:${st.modelShort}:${st.tokPerSec}:${st.ttftSec}:${st.contextTokens}:${st.outputTokens}:${st.cacheHitPct}:${st.costUsd}:${st.selectedSpeedReason}`, + createRow: () => { + const stepNumText = h('span'); + const compIcon = createSvgIcon('bolt', { size: 11, className: 'text-muted' }); + const tdStep = h('td', {}, [stepNumText, compIcon]); + + const tdModel = h('td'); + const speedMain = h('strong', { + className: 'cell-value accent-speed', + style: 'font-size: 11px;', + }); + const speedReason = h('div', { className: 'text-muted', style: 'font-size: 9.5px;' }); + const tdSpeed = h('td', {}, [speedMain, speedReason]); + + const tdTtft = h('td'); + const tdCtx = h('td'); + const tdCache = h('td', { + className: 'cell-value accent-ok', + style: 'font-size: 11px;', + }); + const tdCost = h('td', { style: 'font-weight: 600;' }); + + const tr = h('tr', {}, [tdStep, tdModel, tdSpeed, tdTtft, tdCtx, tdCache, tdCost]); + return { + el: tr, + refs: { + stepNumText, + compIcon, + tdModel, + speedMain, + speedReason, + tdTtft, + tdCtx, + tdCache, + tdCost, + }, + }; + }, + updateRow: (refs, st) => { + patchText(refs.stepNumText, `#${Number(st.stepIndex)} `); + patchAttr(refs.compIcon, 'hidden', !st.isCompactionStep); + patchText(refs.tdModel, st.modelShort || '—'); + + patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s')); + const reason = speedReasonText(st.selectedSpeedReason); + patchText(refs.speedReason, reason); + patchAttr(refs.speedReason, 'hidden', !reason); + + patchText(refs.tdTtft, formatMetric(st.ttftSec, 's')); + patchText( + refs.tdCtx, + `${formatTokens(st.contextTokens)} / +${Number(st.outputTokens || 0)}` + ); + patchText(refs.tdCache, `${Number(st.cacheHitPct ?? 0)}%`); + + const costVal = Number(st.costUsd || 0); + patchText(refs.tdCost, formatUsd(costVal, { precise: true })); + patchClasses(refs.tdCost, { 'accent-speed': costVal >= 0.15 }); + }, + }); + + patchKeyedList(modelsTbody, models, { + keyFn: (m) => m.label || m.shortName, + sigFn: (m) => + `${m.shortName}:${m.calls}:${m.avgTokPerSec}:${m.totalTokens}:${m.costUsd}:${m.speedSummary?.sampleCount}`, + createRow: () => { + const tdName = h('td', { style: 'font-weight: 600;' }); + const tdCalls = h('td'); + const speedMain = h('div'); + const speedSub = h('div', { className: 'text-muted', style: 'font-size: 9.5px;' }); + const tdSpeed = h('td', {}, [speedMain, speedSub]); + const tdTokens = h('td'); + const tdCost = h('td', { style: 'font-weight: 600;' }); + const tr = h('tr', {}, [tdName, tdCalls, tdSpeed, tdTokens, tdCost]); + return { + el: tr, + refs: { tdName, tdCalls, speedMain, speedSub, tdTokens, tdCost }, + }; + }, + updateRow: (refs, m) => { + patchText(refs.tdName, m.shortName || m.label); + patchText(refs.tdCalls, String(Number(m.calls || 0))); + 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 || 0, { estimated: m.isEstimatedPrice })); + }, + }); + + stepsScroll.refresh(); + modelsScroll.refresh(); + } + + const unsubTelemetry = telemetryStore.subscribe( + (st) => ({ + cascadeId: st.telemetry?.activeConversation?.cascadeId, + recentSteps: st.telemetry?.activeConversation?.recentSteps, + modelBreakdown: st.telemetry?.modelBreakdown, + rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间', + }), + (slice) => { + latestSlice = slice; + if (uiStore.getState().activeView !== 'steps') { + isDirty = true; + return; + } + isDirty = false; + renderStepsData(slice); + } + ); + + const unsubView = uiStore.subscribe( + (st) => st.activeView, + (activeView) => { + if (activeView === 'steps' && isDirty) { + isDirty = false; + if (latestSlice) { + renderStepsData(latestSlice); + } + } + } + ); + + onCleanup(() => { + unsubUi(); + unsubTelemetry(); + unsubView(); + subTabSwitch.destroy(); + stepsScroll.destroy(); + modelsScroll.destroy(); + }); + + return { + el: rootEl, + refs: { stepsTbody, modelsTbody, subTabSwitch, stepsScroll, modelsScroll }, + }; + }, +}); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 47db50d..b83a678 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -1,817 +1,1545 @@ +/* --- src/styles/tokens.css --- */ /* - * Theme-aware stylesheet for Antigravity Usage & Speed Monitor. - * Automatically adapts to host dark/light CSS variables injected by /preload.js. + * Semantic Design Tokens for Antigravity Usage & Speed Monitor. + * All visual tokens derive from host CSS variables and perceptual color-mix(), + * eliminating hardcoded hex colors across components and views. */ :root { - --radius-lg: 12px; - --radius-md: 9px; - --radius-sm: 6px; - --speed-accent: #e05638; - --cache-green: #16a34a; - --model-blue: #2563eb; - --bar-blue: #2563eb; - --seg-cached-color: #2563eb; - --seg-input-color: #ea580c; - --seg-thinking-color: #16a34a; - --seg-output-color: #0891b2; + /* 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) */ + --surface-bg: var(--background, hsl(0 0% 100%)); + --surface-panel: var(--card, 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%)); + --text-secondary: var(--muted-foreground, hsl(215 12% 44%)); + --text-muted: color-mix(in srgb, var(--text-secondary) 74%, var(--surface-panel) 26%); + --text-inverse: var(--surface-panel); + + /* Semantic Telemetry Accents */ + --accent-primary: var(--primary, hsl(217 82% 51%)); + --accent-primary-soft: color-mix(in srgb, var(--accent-primary) 13%, transparent); + --accent-primary-border: color-mix(in srgb, var(--accent-primary) 38%, var(--border-hairline)); + + --metric-speed: hsl(14 76% 52%); + --metric-speed-soft: color-mix(in srgb, var(--metric-speed) 14%, transparent); + + --metric-ok: hsl(145 64% 38%); + --metric-ok-soft: color-mix(in srgb, var(--metric-ok) 14%, transparent); + + --metric-warn: hsl(34 86% 44%); + --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 6-Channel Palette */ + --ctx-messages: hsl(217 82% 51%); + --ctx-system-tools: hsl(22 86% 50%); + --ctx-mcp-tools: hsl(268 72% 56%); + --ctx-skills: hsl(145 64% 38%); + --ctx-system-prompt: hsl(190 80% 38%); + --ctx-user-rules: hsl(340 76% 52%); + + /* Legacy 4-Channel Palette (retained for compatibility) */ + --ctx-cached: hsl(217 82% 51%); + --ctx-input: hsl(22 86% 50%); + --ctx-thinking: hsl(145 64% 38%); + --ctx-output: hsl(190 80% 38%); + + /* Elevation & Shadows */ + --shadow-popover: 0 6px 20px color-mix(in srgb, var(--text-primary) 14%, transparent); + --shadow-glider: 0 1px 2px color-mix(in srgb, var(--text-primary) 10%, transparent); + + /* Fast Hardware-Accelerated Motion Tokens */ + --ease-fast: cubic-bezier(0.22, 1, 0.36, 1); + --dur-instant: 90ms; + --dur-fast: 140ms; + --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 --- */ +/* + * Base reset, viewport-locked shell (preventing ultra-long px scroll pages), + * and precision tabular typography. + */ + * { box-sizing: border-box; + scrollbar-width: none; + -ms-overflow-style: none; +} + +*::-webkit-scrollbar { + width: 0 !important; + height: 0 !important; + display: none !important; } [hidden] { display: none !important; } +html, body { margin: 0; padding: 0; - background: var(--background, #f6f7f9); - color: var(--foreground, #1f2328); + width: 100%; + height: 100dvh; + max-height: 100dvh; + overflow: hidden; + background: var(--surface-bg); + color: var(--text-primary); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; - font-size: 13px; - line-height: 1.45; + font-size: 12.5px; + line-height: 1.4; + font-variant-numeric: tabular-nums; -webkit-font-smoothing: antialiased; } -.monitor-container { +button, +input { + font-family: inherit; + font-size: inherit; + color: inherit; +} + +.app-shell { display: flex; flex-direction: column; - gap: 10px; + width: 100%; max-width: 560px; + height: 100dvh; + max-height: 100dvh; margin: 0 auto; - padding: 12px; -} - -/* 1. Top Session Pill Bar ------------------------------------------------- */ - -.session-pill-bar { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - padding: 7px 12px; - background: var(--card, #ffffff); - border: 1px solid var(--card-border, var(--border, #e2e5e9)); - border-radius: var(--radius-md); -} - -.session-pill-left { - display: flex; - align-items: center; - gap: 8px; - min-width: 0; - flex: 1; -} - -.session-title { - font-weight: 600; - font-size: 12.5px; - white-space: nowrap; + padding: var(--space-3) var(--space-4); + gap: var(--space-3); overflow: hidden; - text-overflow: ellipsis; + position: relative; } -.conv-select { - flex: 1; - min-width: 90px; - max-width: 210px; - padding: 2px 6px; - font-size: 12px; - color: var(--muted-foreground, #656d76); - background: var(--secondary, #f0f2f5); - border: 1px solid var(--border, #d8dee4); - border-radius: 5px; - outline: none; -} - -.session-pill-right { +.top-deck { display: flex; - align-items: center; - gap: 6px; + flex-direction: column; + gap: var(--space-2); flex-shrink: 0; } -.live-pill { +.viewport-stage { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; + position: relative; +} + +.view-pane { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + gap: var(--space-3); + overflow-y: auto; + overflow-x: hidden; + padding-right: 1px; +} + +.svg-icon { + display: inline-block; + vertical-align: middle; + flex-shrink: 0; +} + +.text-muted { + color: var(--text-secondary); +} + +.text-mono { + font-variant-numeric: tabular-nums; +} + +/* --- src/styles/animations.css --- */ +/* + * Fast, hardware-accelerated transitions (120ms-160ms) with zero sluggish bounce. + */ + +@keyframes anim-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@keyframes anim-pulse-dot { + 0%, + 100% { + transform: scale(1); + opacity: 1; + } + 50% { + transform: scale(1.22); + opacity: 0.62; + } +} + +@keyframes anim-view-fade { + from { + opacity: 0; + transform: translate3d(0, 3px, 0); + } + to { + opacity: 1; + transform: translate3d(0, 0, 0); + } +} + +@keyframes anim-popover-in { + from { + opacity: 0; + transform: translate3d(0, -3px, 0) scale(0.985); + } + to { + opacity: 1; + transform: translate3d(0, 0, 0) scale(1); + } +} + +.view-pane { + animation: anim-view-fade var(--dur-fast) var(--ease-fast); +} + +.is-spinning .svg-icon { + animation: anim-spin 520ms linear infinite; +} + +.is-pulsing { + animation: anim-pulse-dot 950ms ease-in-out infinite; +} + +/* --- src/styles/components.css --- */ +/* + * Component Stylesheet for Antigravity Usage & Speed Monitor Monitor. + * Enforces: + * 1. Top Long-Pill Navigation Bar (--radius-pill) + * 2. Internal 2px-4px micro-bezel precision grid (--radius-xs / --radius-sm) + * 3. Zero hardcoded colors (all tokens from tokens.css) + */ + +/* --- Row 1: Top Session Control Header --- */ +.session-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + padding: 5px var(--space-3); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); +} + +.session-left { + display: flex; + align-items: center; + gap: var(--space-2); + flex: 1; + min-width: 0; +} + +.session-right { + display: flex; + align-items: center; + gap: 5px; + flex-shrink: 0; +} + +.status-tag { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 6px; font-size: 11px; - padding: 1px 7px; - border-radius: 999px; - background: color-mix(in srgb, #16a34a 15%, transparent); - color: var(--cache-green); - font-weight: 500; + font-weight: 600; + border-radius: var(--radius-xs); + border: 1px solid color-mix(in srgb, var(--metric-ok) 32%, var(--border-hairline)); + background: var(--metric-ok-soft); + color: var(--metric-ok); } -.live-pill.running { - background: color-mix(in srgb, #e05638 18%, transparent); - color: var(--speed-accent); +.status-tag.state-running { + color: var(--metric-speed); + background: var(--metric-speed-soft); + border-color: color-mix(in srgb, var(--metric-speed) 35%, var(--border-hairline)); } -.live-pill.synced { - background: color-mix(in srgb, #2563eb 16%, transparent); - color: var(--model-blue); +.status-tag.state-synced { + color: var(--accent-primary); + background: var(--accent-primary-soft); + border-color: var(--accent-primary-border); +} + +.status-tag.state-warn { + color: var(--metric-warn); + background: var(--metric-warn-soft); + border-color: color-mix(in srgb, var(--metric-warn) 35%, var(--border-hairline)); } .icon-btn { display: inline-flex; align-items: center; justify-content: center; - width: 24px; - height: 22px; - padding: 0; - font-size: 13px; - line-height: 1; - color: var(--muted-foreground, #5f6368); - background: transparent; - border: 1px solid var(--border, #d8dee4); - border-radius: 5px; + gap: 4px; + height: 24px; + min-width: 24px; + padding: 0 6px; + background: var(--surface-panel); + color: var(--text-secondary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); cursor: pointer; user-select: none; - transition: transform 0.12s ease, background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast), + border-color var(--dur-instant) var(--ease-fast), + transform var(--dur-instant) var(--ease-fast); } .icon-btn:hover { - background: var(--secondary, #eef1f4); - color: var(--foreground, #1f2328); - border-color: var(--muted-foreground, #8c959f); + background: var(--surface-hover); + color: var(--text-primary); + border-color: var(--border-strong); } .icon-btn:active { - transform: scale(0.88); + transform: scale(0.95); } -.icon-btn.refreshing { - color: var(--model-blue); - border-color: var(--model-blue); - background: color-mix(in srgb, var(--model-blue) 10%, transparent); - pointer-events: none; +.icon-btn.is-active { + background: var(--accent-primary-soft); + color: var(--accent-primary); + border-color: var(--accent-primary-border); } -.icon-btn.refreshing .refresh-glyph { - display: inline-block; - animation: spin-refresh 0.55s linear infinite; -} - -@keyframes spin-refresh { - from { transform: rotate(0deg); } - to { transform: rotate(360deg); } -} - -/* 2. Compact Status Strip Card (Left status bar in screenshot) ------------ */ - -.status-strip-card { - display: flex; - flex-direction: column; - gap: 4px; - padding: 10px 13px; - background: var(--card, #ffffff); - border: 1px solid var(--card-border, var(--border, #e2e5e9)); - border-radius: var(--radius-md); - box-shadow: 0 1px 3px rgb(0 0 0 / 4%); -} - -.strip-row { - display: flex; +/* --- Row 2: Top Long-Pill Navigation Bar (唯一长药丸功能分割顶栏) --- */ +.long-pill-nav { + position: relative; + display: grid; + grid-template-columns: repeat(var(--pill-count, 4), 1fr); align-items: center; - flex-wrap: wrap; - gap: 7px; -} - -.strip-row-main { - font-size: 13px; -} - -.strip-row-sub { - font-size: 12.5px; - justify-content: space-between; -} - -.speed-group { - display: inline-flex; - align-items: center; - gap: 5px; - cursor: default; + padding: 3px; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-pill); user-select: none; } -.speed-dot { - width: 7px; - height: 7px; - border-radius: 50%; - background: var(--speed-accent); - display: inline-block; +.pill-glider { + position: absolute; + top: 3px; + bottom: 3px; + left: 3px; + width: calc((100% - 6px) / var(--pill-count, 4)); + background: var(--accent-primary-soft); + border: 1px solid var(--accent-primary-border); + border-radius: var(--radius-pill); + transform: translate3d(calc(var(--active-index, 0) * 100%), 0, 0); + transition: transform var(--dur-fast) var(--ease-fast); + pointer-events: none; + z-index: 0; } -.speed-dot.pulsing { - animation: pulse-dot 1s infinite ease-in-out; - box-shadow: 0 0 0 3px color-mix(in srgb, var(--speed-accent) 28%, transparent); -} - -@keyframes pulse-dot { - 0%, 100% { transform: scale(1); opacity: 1; } - 50% { transform: scale(1.25); opacity: 0.65; } -} - -.speed-value { - color: var(--speed-accent); - font-weight: 600; - font-variant-numeric: tabular-nums; -} - -.metric-item { - color: var(--muted-foreground, #656d76); - font-variant-numeric: tabular-nums; -} - -.metric-item strong { - color: var(--foreground, #1f2328); - font-weight: 600; -} - -.strip-divider { - color: var(--border, #d0d7de); - margin: 0 1px; -} - -.cost-value { - color: var(--foreground, #1f2328); - font-weight: 600; - font-variant-numeric: tabular-nums; -} - -.cache-value { - color: var(--cache-green) !important; - font-weight: 600; -} - -.ctx-inline-trigger { +.pill-tab { + position: relative; + z-index: 1; display: inline-flex; align-items: center; + justify-content: center; gap: 5px; + height: 26px; + padding: 0 var(--space-2); + border: none; + background: transparent; + color: var(--text-secondary); + font-size: 12px; + font-weight: 500; + line-height: 1; + border-radius: var(--radius-pill); + cursor: pointer; + white-space: nowrap; + transition: color var(--dur-instant) var(--ease-fast); +} + +.pill-tab .svg-icon { + display: block; + width: 14px; + height: 14px; + stroke-width: 1.65; + flex-shrink: 0; +} + +.pill-tab-label, +.pill-tab-badge { + display: inline-flex; + align-items: center; + height: 14px; + line-height: 1; +} + +.pill-tab-badge { + margin-left: -2px; + font-size: 11.5px; + opacity: 0.85; +} + +.pill-tab:hover { + color: var(--text-primary); +} + +.pill-tab.is-active { + color: var(--accent-primary); + font-weight: 600; +} + +.pill-tab.is-active .svg-icon { + color: var(--accent-primary); + stroke-width: 1.8; +} + +.pill-tab.is-active .pill-tab-badge { + color: var(--accent-primary); + opacity: 0.92; +} + +/* --- Bespoke Custom Select (零原生 ) --- */ +.number-input { + display: inline-flex; + align-items: stretch; + height: 28px; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + overflow: hidden; +} + +.number-input:focus-within { + border-color: var(--accent-primary); +} + +.num-step-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + border: none; + background: var(--surface-panel); + color: var(--text-secondary); + cursor: pointer; + transition: background-color var(--dur-instant) var(--ease-fast), color var(--dur-instant) var(--ease-fast); +} + +.num-step-btn:hover { + background: var(--surface-hover); + color: var(--text-primary); +} + +.num-step-btn:active { + background: var(--surface-active); +} + +.num-field { + flex: 1; + min-width: 90px; + padding: 0 var(--space-3); + border: none; + border-left: 1px solid var(--border-hairline); + border-right: 1px solid var(--border-hairline); + background: transparent; + color: var(--text-primary); + font-weight: 600; + font-variant-numeric: tabular-nums; + outline: none; +} + +/* --- Bespoke Custom DateTime Picker (零原生 ) --- */ +.datetime-picker { + position: relative; + display: inline-flex; + flex: 1; + min-width: 145px; +} + +.dt-trigger { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + width: 100%; + height: 26px; + padding: 0 var(--space-2); + background: var(--surface-panel); + color: var(--text-primary); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + font-size: 11.5px; + cursor: pointer; +} + +.dt-trigger:hover { + border-color: var(--border-strong); +} + +.dt-popover { + position: absolute; + top: calc(100% + 4px); + left: 0; + width: 248px; + background: var(--surface-panel); + border: 1px solid var(--border-strong); + border-radius: var(--radius-xs); + box-shadow: var(--shadow-popover); + padding: var(--space-3); + z-index: 70; + display: flex; + flex-direction: column; + gap: var(--space-2); + animation: popover-in var(--dur-fast) var(--ease-fast); +} + +.dt-nav { + display: flex; + align-items: center; + justify-content: space-between; + font-weight: 600; + font-size: 12px; +} + +.dt-weekdays, +.dt-days { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 2px; + text-align: center; +} + +.dt-weekday { + font-size: 10.5px; + color: var(--text-secondary); + padding: 2px 0; +} + +.dt-day { + height: 22px; + border: none; + background: transparent; + color: var(--text-primary); + font-size: 11px; + border-radius: var(--radius-xs); + cursor: pointer; +} + +.dt-day:hover { + background: var(--surface-hover); +} + +.dt-day.is-selected { + background: var(--accent-primary); + color: var(--text-inverse); + font-weight: 600; +} + +.dt-day.is-outside { + color: var(--text-muted); +} + +.dt-time-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + padding-top: var(--space-2); + border-top: 1px solid var(--border-hairline); + font-size: 11.5px; +} + +.dt-time-controls { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.dt-mini-step { display: inline-flex; align-items: center; gap: 2px; - vertical-align: middle; + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + padding: 1px 3px; } -.para-block { - width: 9px; - height: 9px; - transform: skewX(-18deg); - border: 1.3px solid #16a34a; - border-radius: 1.5px; +.dt-mini-btn { + border: none; background: transparent; - transition: background-color 0.2s ease; + color: var(--text-secondary); + cursor: pointer; + padding: 1px 3px; } -.para-block.filled { - background: #16a34a; +.dt-mini-btn:hover { + color: var(--text-primary); } -.para-block.warn { - border-color: #d97706; -} -.para-block.warn.filled { - background: #d97706; -} - -.para-block.danger { - border-color: #dc2626; -} -.para-block.danger.filled { - background: #dc2626; -} - -.model-tag { +/* --- Micro-Bezel Segmented Control --- */ +.segmented { display: inline-flex; align-items: center; + gap: 2px; + padding: 0; + background: transparent; + border: none; +} + +.seg-btn { + display: inline-flex; + align-items: center; + justify-content: center; gap: 4px; - color: var(--model-blue); - font-weight: 600; -} - -.swap-icon { - font-size: 13px; - font-weight: 700; -} - -.today-summary { - color: var(--muted-foreground, #656d76); - font-variant-numeric: tabular-nums; - margin-right: auto; - padding-left: 4px; -} - -.today-summary strong { - color: var(--foreground, #1f2328); - font-weight: 600; -} - -.speed-mode-label { + height: 22px; + padding: 0 7px; + border: none; + background: transparent; + color: var(--text-secondary); font-size: 11px; - padding: 1px 6px; - border-radius: 4px; - background: var(--secondary, #f0f2f5); + border-radius: var(--radius-xs); + cursor: pointer; + transition: + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); } -/* 3. Quota & Context Popover Card (Right popover in screenshot) ----------- */ +.seg-btn:hover { + color: var(--text-primary); + background: var(--surface-hover); +} -.quota-popover-card { +.seg-btn.is-active { + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-weight: 600; +} + +/* --- Architectural Precision Panels & Metric Matrices --- */ +.panel { display: flex; flex-direction: column; - gap: 12px; - padding: 15px 16px; - background: var(--card, #ffffff); - border: 1px solid var(--card-border, var(--border, #e2e5e9)); - border-radius: var(--radius-lg); - box-shadow: 0 4px 16px rgb(0 0 0 / 7%); + flex-shrink: 0; + gap: var(--space-3); + padding: var(--space-4) var(--space-5); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-sm); } -.popover-section { - display: flex; - flex-direction: column; - gap: 9px; -} - -.section-row { +.panel-header { display: flex; align-items: center; justify-content: space-between; - gap: 8px; + gap: var(--space-2); } -.section-row.clickable { - cursor: pointer; - user-select: none; -} - -.section-label { - color: var(--muted-foreground, #656d76); - font-size: 13px; -} - -.section-value { +.panel-title { display: inline-flex; align-items: center; gap: 6px; - color: var(--muted-foreground, #656d76); - font-size: 13px; - font-variant-numeric: tabular-nums; + font-size: 12px; + font-weight: 600; + color: var(--text-primary); } -.chevron, .arrow-icon { - color: var(--muted-foreground, #8c959f); - font-size: 15px; - cursor: pointer; +.panel-meta { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 11.5px; + color: var(--text-secondary); } -.multi-progress-track, -.single-progress-track { +/* 4-Cell Telemetry Matrix */ +.telemetry-matrix { + display: grid; + grid-template-columns: repeat(4, 1fr); + flex-shrink: 0; + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + background: var(--border-hairline); + gap: 1px; + overflow: hidden; +} + +.matrix-cell { + display: flex; + flex-direction: column; + gap: 2px; + padding: 7px 9px; + background: var(--surface-panel); + min-width: 0; +} + +.cell-label { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 11px; + color: var(--text-secondary); +} + +.cell-value { + font-size: 14.5px; + font-weight: 700; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.cell-value.accent-speed { + color: var(--metric-speed); +} + +.cell-value.accent-ok { + color: var(--metric-ok); +} + +.cell-sub { + font-size: 10.5px; + color: var(--text-secondary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* Context Segment Meter & Progress Bars */ +.progress-track { width: 100%; - height: 5px; - background: var(--secondary, #eaeef2); - border-radius: 999px; + height: 6px; + background: var(--surface-track); + border-radius: var(--radius-xs); overflow: hidden; display: flex; } -.bar-seg { +.progress-seg { height: 100%; - transition: width 0.25s ease; + width: var(--seg-w, 0%); + transition: width var(--dur-normal) var(--ease-fast); } -.seg-cached { background: var(--seg-cached-color); } -.seg-input { background: var(--seg-input-color); } -.seg-thinking { background: var(--seg-thinking-color); } -.seg-output { background: var(--seg-output-color); } +.progress-seg.seg-messages { + background: var(--ctx-messages); +} +.progress-seg.seg-system-tools { + background: var(--ctx-system-tools); +} +.progress-seg.seg-mcp-tools { + background: var(--ctx-mcp-tools); +} +.progress-seg.seg-skills { + background: var(--ctx-skills); +} +.progress-seg.seg-system-prompt { + background: var(--ctx-system-prompt); +} +.progress-seg.seg-user-rules { + background: var(--ctx-user-rules); +} +.progress-seg.seg-cached { + background: var(--ctx-cached); +} +.progress-seg.seg-input { + background: var(--ctx-input); +} +.progress-seg.seg-thinking { + background: var(--ctx-thinking); +} +.progress-seg.seg-output { + background: var(--ctx-output); +} -.bar-fill { +.progress-fill { height: 100%; - background: var(--bar-blue); - border-radius: 999px; - transition: width 0.25s ease; + width: var(--fill-w, 0%); + background: var(--accent-primary); + transition: width var(--dur-normal) var(--ease-fast); } -.bar-fill.warn { background: #d97706; } -.bar-fill.danger { background: #dc2626; } - -.ctx-breakdown { - margin-top: 4px; - padding: 9px 10px; - background: var(--secondary, #f4f6f8); - border-radius: var(--radius-sm); - display: flex; - flex-direction: column; - gap: 8px; - font-size: 12px; +.progress-fill.tone-warn { + background: var(--metric-warn); } -.legend-grid { +.progress-fill.tone-danger { + background: var(--metric-danger); +} + +.ctx-legend-grid { display: grid; - grid-template-columns: 1fr 1fr; - gap: 5px 12px; + grid-template-columns: repeat(2, 1fr); + gap: 5px var(--space-4); + padding: 2px 0 0 0; + background: transparent; + border: none; + font-size: 11.5px; } .legend-item { display: flex; align-items: center; - gap: 6px; - color: var(--muted-foreground, #656d76); + justify-content: space-between; + gap: var(--space-2); } -.legend-item strong { - color: var(--foreground, #1f2328); +.legend-left { + display: inline-flex; + align-items: center; + gap: 5px; + color: var(--text-secondary); } -.dot { - width: 8px; - height: 8px; - border-radius: 2px; +.swatch { + width: 7px; + height: 7px; + border-radius: 1px; display: inline-block; } -.ctx-limit-switch { - display: flex; - align-items: center; - gap: 6px; - padding-top: 4px; - border-top: 1px dashed var(--border, #d8dee4); - color: var(--muted-foreground, #656d76); -} +.swatch.seg-messages { background: var(--ctx-messages); } +.swatch.seg-system-tools { background: var(--ctx-system-tools); } +.swatch.seg-mcp-tools { background: var(--ctx-mcp-tools); } +.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); } -.chip-btn { - padding: 2px 8px; - font-size: 11.5px; - border-radius: 4px; - border: 1px solid var(--border, #d0d7de); - background: var(--card, #ffffff); - color: var(--foreground, #1f2328); - cursor: pointer; -} - -.chip-btn.active { - background: var(--bar-blue); - color: #ffffff; - border-color: var(--bar-blue); -} - -.popover-divider { - border: none; - border-top: 1px solid var(--border, #eaeef2); - margin: 2px 0; -} - -.consumption-header-row { - flex-wrap: wrap; - gap: 6px; -} - -.time-filter-bar { - display: inline-flex; - align-items: center; - flex-wrap: wrap; - gap: 3px; - background: var(--secondary, #f0f2f5); - padding: 2px; - border-radius: 6px; - border: 1px solid var(--border, #e2e5e9); -} - -.time-chip { - padding: 2px 7px; - font-size: 11px; - line-height: 1.35; - border-radius: 4px; - border: none; - background: transparent; - color: var(--muted-foreground, #656d76); - cursor: pointer; - transition: background-color 0.15s ease, color 0.15s ease; -} - -.time-chip:hover { - color: var(--foreground, #1f2328); -} - -.time-chip.active { - background: var(--card, #ffffff); - color: var(--bar-blue); - font-weight: 600; - box-shadow: 0 1px 2px rgb(0 0 0 / 8%); -} - -.custom-time-box { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 5px; - padding: 6px 8px; - background: var(--secondary, #f4f6f8); - border-radius: var(--radius-sm); - font-size: 11.5px; -} - -.time-input { - flex: 1; - min-width: 125px; - padding: 3px 5px; - font-size: 11px; - color: var(--foreground, #1f2328); - background: var(--card, #ffffff); - border: 1px solid var(--border, #d0d7de); - border-radius: 4px; -} - -.consumption-cards-grid { +/* Dual Consumption Comparison Grid */ +.dual-grid { display: grid; grid-template-columns: 1fr 1fr; - gap: 8px; + gap: var(--space-3); } -@media (max-width: 380px) { - .consumption-cards-grid { +@media (max-width: 390px) { + .telemetry-matrix { + grid-template-columns: repeat(2, 1fr); + } + .dual-grid { grid-template-columns: 1fr; } } -.consumption-card { +.ledger-box { display: flex; flex-direction: column; - gap: 4px; - padding: 9px 10px; - background: var(--secondary, #f4f6f8); - border: 1px solid var(--border, #e2e5e9); - border-radius: var(--radius-md); - font-variant-numeric: tabular-nums; + gap: 5px; + padding: var(--space-3) var(--space-4); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); } -.consumption-card.account-card { - background: color-mix(in srgb, var(--bar-blue) 5%, var(--secondary, #f4f6f8)); - border-color: color-mix(in srgb, var(--bar-blue) 22%, var(--border, #e2e5e9)); +.ledger-box.is-primary { + background: color-mix(in srgb, var(--accent-primary) 4%, var(--surface-panel)); + border-color: var(--accent-primary-border); } -.cons-card-header { +.ledger-top { display: flex; align-items: center; justify-content: space-between; - gap: 4px; + gap: var(--space-2); } -.cons-card-title { - font-size: 11.5px; - font-weight: 600; - color: var(--foreground, #1f2328); -} - -.cons-card-badge { +.ledger-tag { font-size: 10.5px; - padding: 0 5px; - border-radius: 999px; - background: var(--card, #ffffff); - color: var(--muted-foreground, #656d76); - border: 1px solid var(--border, #e2e5e9); - white-space: nowrap; + padding: 0; + background: transparent; + border: none; + color: var(--text-secondary); } -.cons-card-main { +.ledger-main { display: flex; align-items: baseline; justify-content: space-between; - gap: 6px; - margin-top: 1px; + gap: var(--space-2); } -.cons-tokens { - font-size: 15px; +.ledger-tokens { + font-size: 16px; font-weight: 700; - color: var(--foreground, #1f2328); + color: var(--text-primary); } -.cons-cost { - font-size: 12.5px; +.ledger-cost { + font-size: 13px; font-weight: 600; - color: var(--speed-accent); + color: var(--metric-speed); } -.cons-card-sub { +.ledger-foot { font-size: 11px; - color: var(--muted-foreground, #656d76); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; + color: var(--text-secondary); + padding-top: 4px; + border-top: 1px solid var(--border-hairline); } -.cons-card-foot { - font-size: 10.5px; - padding-top: 3px; - border-top: 1px dashed var(--border, #d8dee4); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; +/* --- Rich Consumption Analytics Dashboard (5-Section Layout) --- */ +.cons-overview-head { + flex-wrap: wrap; + gap: 6px; } -.quota-block { +.cons-badge { + font-size: 11px; + font-weight: 500; + padding: 0; + background: transparent; + border: none; + color: var(--text-secondary); +} + +.cons-box { display: flex; flex-direction: column; - gap: 6px; - margin-top: 2px; + gap: var(--space-3); + padding: var(--space-3) var(--space-4); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); } -.quota-title { - color: var(--foreground, #1f2328); - font-weight: 500; +.cons-unified-matrix { + gap: 0; + padding: 0; + border: none; + border-top: 1px solid var(--border-hairline); + border-bottom: 1px solid var(--border-hairline); + border-radius: 0; + overflow: hidden; +} + +.cons-split-3 { + display: grid; + 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-col { + display: flex; + flex-direction: column; + gap: 3px; + padding: 8px 10px; + min-width: 0; +} + +.cons-col:first-child { + padding-left: 0; +} + +.cons-col:last-child { + padding-right: 0; +} + +.cons-col.is-bordered-col, +.cons-col.is-right-col { + border-left: 1px solid var(--border-hairline); +} + +.cons-baseline { + display: flex; + align-items: baseline; + gap: 5px; + flex-wrap: wrap; +} + +.cons-hero-num { + font-size: 17px; + font-weight: 700; + color: var(--text-primary); + letter-spacing: -0.02em; +} + +.cons-hero-cost { + font-size: 17px; + font-weight: 700; + color: var(--accent-primary); + letter-spacing: -0.02em; +} + +.cons-hero-cache { + font-size: 17px; + font-weight: 700; + color: var(--ctx-cached); + letter-spacing: -0.02em; +} + +.cons-mid-num { font-size: 13px; + font-weight: 700; + color: var(--text-primary); } -.quota-meta { +.dot-swatch { + width: 6px; + height: 6px; + border-radius: var(--radius-pill); + display: inline-block; + flex-shrink: 0; +} + +.dot-swatch.seg-input { background: var(--ctx-input); } +.dot-swatch.seg-cached { background: var(--ctx-cached); } +.dot-swatch.seg-output { background: var(--ctx-output); } +.dot-swatch.seg-thinking { background: var(--ctx-thinking); } + +/* Uniform 12px / 20px Row Header Alignment for Popular Models & Sources */ +.cons-row-title { + display: inline-flex; + align-items: center; + height: 20px; + line-height: 20px; + font-size: 12px; + font-weight: 600; + color: var(--text-primary); +} + +.cons-row-metrics { display: inline-flex; align-items: center; gap: 8px; - color: var(--muted-foreground, #656d76); - font-size: 12.5px; - font-variant-numeric: tabular-nums; + height: 20px; } -.quota-meta strong { - color: var(--muted-foreground, #656d76); +.cons-share-pill { + display: inline-flex; + align-items: center; + justify-content: center; + height: 20px; + line-height: 1; + padding: 0 6px; + font-size: 12px; font-weight: 600; - min-width: 28px; - text-align: right; + color: var(--metric-ok); + background: color-mix(in srgb, var(--metric-ok) 11%, transparent); + border: none; + border-radius: var(--radius-xs); + box-sizing: border-box; } -.all-pools-box { +.cons-row-tok { + display: inline-flex; + align-items: center; + height: 20px; + line-height: 1; + font-size: 12px; + font-weight: 500; + color: var(--text-secondary); +} + +.cons-row-cost { + display: inline-flex; + align-items: center; + height: 20px; + line-height: 1; + font-size: 12px; + font-weight: 700; + color: var(--text-primary); +} + +.cons-seg-bar { + height: 5px; +} + +/* Historical Trend SVG Chart */ +.trend-chart-wrap { + position: relative; + width: 100%; + padding-top: 8px; +} + +.trend-svg { + width: 100%; + height: 112px; + display: block; + overflow: visible; +} + +.trend-grid line { + stroke: var(--border-hairline); + stroke-width: 1; + stroke-dasharray: 2 3; +} + +.trend-line { + stroke: var(--ctx-cached); + stroke-width: 2; + stroke-linecap: round; +} + +.trend-peak-dot { + fill: var(--ctx-cached); + stroke: var(--surface-panel); + stroke-width: 1.5; +} + +.trend-peak-pill { + position: absolute; + top: 2px; + left: var(--peak-x, 50%); + transform: translateX(-50%); + font-size: 10px; + font-weight: 600; + padding: 1px 6px; + color: var(--text-primary); + background: color-mix(in srgb, var(--ctx-cached) 16%, var(--surface-panel)); + border: none; + border-radius: var(--radius-xs); + pointer-events: none; + white-space: nowrap; +} + +.trend-anchors { + display: grid; + grid-template-columns: repeat(3, 1fr); + padding-top: 2px; + font-size: 11px; +} + +.trend-anchor-col { + display: flex; + flex-direction: column; + gap: 1px; +} + +.trend-anchor-col.is-center { + align-items: center; +} + +.trend-anchor-col.is-end { + align-items: flex-end; +} + +/* Popular Models & Sources Rows */ +.cons-item-list { + display: flex; + flex-direction: column; + gap: var(--space-4); +} + +.cons-item-row { display: flex; flex-direction: column; gap: 6px; - padding: 8px 10px; - background: var(--secondary, #f4f6f8); - border-radius: var(--radius-sm); } -.pool-mini-row { +.cons-item-foot { display: flex; align-items: center; - justify-content: space-between; - font-size: 12px; - gap: 8px; + flex-wrap: wrap; + gap: 4px 10px; + font-size: 11px; + color: var(--text-secondary); } -.pool-mini-name { - font-weight: 500; - color: var(--foreground, #1f2328); -} - -.pool-mini-meta { - color: var(--muted-foreground, #656d76); - font-variant-numeric: tabular-nums; -} - -.weekly-sub-meta { - display: flex; - align-items: center; - justify-content: space-between; - font-size: 12px; - margin-top: 1px; -} - -.popover-actions { - display: flex; - align-items: center; - gap: 8px; - margin-top: 4px; -} - -.detail-pill-btn { - padding: 4px 12px; - font-size: 12px; - font-weight: 500; - color: var(--foreground, #1f2328); - background: var(--card, #ffffff); - border: 1px solid var(--border, #d0d7de); - border-radius: 6px; - cursor: pointer; - box-shadow: 0 1px 2px rgb(0 0 0 / 4%); -} - -.detail-pill-btn:hover { - background: var(--secondary, #f3f4f6); -} - -.secondary-pill { - color: var(--muted-foreground, #656d76); -} - -/* 4. Details & Settings Cards --------------------------------------------- */ - -.details-card { - display: flex; - flex-direction: column; - gap: 10px; - padding: 12px 14px; - background: var(--card, #ffffff); - border: 1px solid var(--card-border, var(--border, #e2e5e9)); - border-radius: var(--radius-lg); -} - -.tabs-header { - display: flex; - gap: 6px; - border-bottom: 1px solid var(--border, #eaeef2); - padding-bottom: 8px; -} - -.tab-btn { - padding: 4px 10px; - font-size: 12px; - border-radius: 5px; - border: 1px solid transparent; - background: transparent; - color: var(--muted-foreground, #656d76); - cursor: pointer; -} - -.tab-btn.active { - background: var(--secondary, #eef1f4); - color: var(--foreground, #1f2328); +.cons-item-foot strong { + color: var(--text-primary); font-weight: 600; } -.table-scroll { - max-height: 420px; +/* 12-Month Stacked Bar Chart */ +.monthly-grid { + display: grid; + grid-template-columns: repeat(12, 1fr); + gap: 3px; + align-items: end; + padding-top: var(--space-2); +} + +.month-col { + display: flex; + flex-direction: column; + align-items: center; + gap: 3px; + min-width: 0; +} + +.month-cost { + font-size: 9.5px; + color: var(--text-secondary); + min-height: 14px; + white-space: nowrap; +} + +.month-bar-well { + width: 100%; + height: 82px; + display: flex; + align-items: flex-end; + justify-content: center; +} + +.month-stack { + width: 72%; + max-width: 20px; + height: var(--bar-h, 0%); + display: flex; + flex-direction: column; + border-radius: 2px 2px 0 0; + overflow: hidden; + transition: height var(--dur-normal) var(--ease-fast); +} + +.month-seg { + width: 100%; + height: var(--seg-h, 0%); +} + +.month-seg.seg-input { background: var(--ctx-input); } +.month-seg.seg-cached { background: var(--ctx-cached); } +.month-seg.seg-output { background: var(--ctx-output); } +.month-seg.seg-thinking { background: var(--ctx-thinking); } + +.month-zero-dot { + width: 3px; + height: 3px; + border-radius: var(--radius-pill); + background: var(--border-strong); + margin-bottom: 4px; +} + +.month-label { + font-size: 10px; + color: var(--text-secondary); + padding: 1px 3px; + border-radius: var(--radius-xs); + white-space: nowrap; +} + +.month-label.is-current { + color: var(--ctx-cached); + background: color-mix(in srgb, var(--ctx-cached) 14%, transparent); + font-weight: 600; +} + +.month-tok { + font-size: 9px; + color: var(--text-muted); + min-height: 12px; + white-space: nowrap; +} + +.monthly-legend { + display: flex; + align-items: center; + justify-content: center; + gap: var(--space-4); + padding-top: var(--space-2); + font-size: 11px; + color: var(--text-secondary); +} + +/* --- Bespoke Custom Scrollbar (Dedicated Layout Gutter, Never Overlaps Content) --- */ +.custom-scroll-host { + position: relative; + display: flex; + flex-direction: row; + align-items: stretch; + gap: 5px; + min-height: 0; + overflow: hidden; +} + +.custom-scroll-host[hidden] { + display: none !important; +} + +.table-scroll-host { + flex: 1; + min-height: 0; + gap: 4px; + padding-top: 2px; + padding-right: 0; + border: none; + border-top: 1px solid var(--border-hairline); + border-radius: 0; + background: var(--surface-panel); +} + +.custom-scroll-content { + flex: 1; + min-width: 0; + min-height: 0; overflow-y: auto; - overflow-x: auto; - border-radius: var(--radius-sm); + overflow-x: hidden; + scrollbar-width: none; + -ms-overflow-style: none; +} + +.custom-scroll-content::-webkit-scrollbar { + width: 0 !important; + height: 0 !important; + display: none !important; +} + +.scrollbar-rail { + position: relative; + flex-shrink: 0; + width: 5px; + margin: 2px 0; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--border-hairline) 35%, transparent); + z-index: 15; + opacity: 0.85; + transition: opacity var(--dur-fast) var(--ease-fast), background-color var(--dur-fast) var(--ease-fast); + cursor: pointer; +} + +.custom-scroll-host:hover .scrollbar-rail, +.scrollbar-rail.is-dragging { + opacity: 1; + background: color-mix(in srgb, var(--border-hairline) 65%, transparent); +} + +.scrollbar-rail.is-inactive { + display: none !important; + opacity: 0 !important; + pointer-events: none; +} + +.scrollbar-thumb { + width: 100%; + height: var(--thumb-h, 0px); + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-secondary) 32%, transparent); + transform: translate3d(0, var(--thumb-y, 0px), 0); + will-change: transform, height; + transition: background-color var(--dur-instant) var(--ease-fast); +} + +.scrollbar-rail:hover .scrollbar-thumb, +.scrollbar-rail.is-dragging .scrollbar-thumb { + background: color-mix(in srgb, var(--accent-primary) 72%, transparent); +} + +.table-viewport { + flex: 1; + min-height: 0; + overflow-y: auto; + overflow-x: hidden; + background: var(--surface-panel); } .data-table { width: 100%; border-collapse: collapse; - font-size: 12px; - font-variant-numeric: tabular-nums; + font-size: 11px; } .data-table th, .data-table td { - padding: 6px 6px; + padding: 5px 4px; text-align: left; - border-bottom: 1px solid var(--border, #eaeef2); + border-bottom: 1px solid var(--border-hairline); white-space: nowrap; } +.data-table th:first-child, +.data-table td:first-child { + padding-left: 7px; +} + +.data-table th:last-child, +.data-table td:last-child { + text-align: right; + padding-right: 10px; +} + .data-table th { position: sticky; top: 0; - z-index: 1; - background: var(--card, #ffffff); - color: var(--muted-foreground, #656d76); - font-weight: 600; - box-shadow: 0 1px 0 var(--border, #eaeef2); -} - -.settings-title { - margin: 0; - font-size: 13px; + z-index: 2; + background: var(--surface-panel); + color: var(--text-secondary); font-weight: 600; } -.settings-grid { - display: flex; - flex-direction: column; - gap: 8px; +.data-table tbody tr:hover { + background: var(--surface-hover); } -.field-label { +/* Settings Form Layout */ +.form-row { display: flex; flex-direction: column; - gap: 4px; + gap: 5px; +} + +.form-label { + font-size: 11.5px; + font-weight: 500; + color: var(--text-secondary); +} + +.btn-primary { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 28px; + padding: 0 var(--space-5); + background: var(--accent-primary); + color: var(--text-inverse); + border: 1px solid var(--accent-primary); + border-radius: var(--radius-xs); + font-weight: 600; font-size: 12px; - color: var(--muted-foreground, #656d76); + cursor: pointer; + transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast); } -.field-label select, -.field-label input { - padding: 5px 8px; - font-size: 12.5px; - color: var(--foreground, #1f2328); - background: var(--background, #f6f7f9); - border: 1px solid var(--border, #d0d7de); - border-radius: 5px; +.btn-primary:hover { + opacity: 0.92; } -.settings-actions { - display: flex; - justify-content: flex-end; +.btn-primary:active { + transform: scale(0.98); } - -.muted { - color: var(--muted-foreground, #656d76); -} - -.speed-method-note { font-size: 11px; margin-top: 6px; } -.speed-detail { font-size: 10px; white-space: normal; max-width: 150px; } -#steps-tbody td:nth-child(3) { min-width: 120px; } diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs deleted file mode 100644 index bbdec3b..0000000 --- a/sidecars/panel/test/backend-harness.mjs +++ /dev/null @@ -1,35 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import vm from 'node:vm'; -import * as metrics from '../speed-metrics.mjs'; - -export function backendHarness({cache={},settings={},trajectories={},summaries={},sourceText=null,metricsImplementation=metrics}={}) { - const source=(sourceText ?? fs.readFileSync(new URL('../main.mjs',import.meta.url),'utf8')) - .replace(/^import .*;\r?\n/gm,'').replaceAll('import.meta.url',JSON.stringify('file:///test/main.mjs')); - const state={calls:[],errors:[],saves:[],trajectories}; - const ctx={ - ...metricsImplementation, URL, AbortSignal, - process:{env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}}, - console:{error:m=>state.errors.push(m)}, - existsSync:p=>p.endsWith('settings.json') || p.endsWith('trajectory_usage_cache.json'), - mkdirSync:()=>{},readdirSync:()=>[],statSync:()=>({mtimeMs:0}), - readFileSync:p=>JSON.stringify(p.endsWith('settings.json')?settings:cache), - writeFileSync:(p,s)=>state.saves.push({path:p,data:JSON.parse(s)}), - homedir:()=>'/test-home',dirname:path.dirname,join:path.join,fileURLToPath:()=>'/test/main.mjs', - 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)=>{ - const method=url.split('/').pop(); const body=JSON.parse(options.body);state.calls.push({method,body}); - if(method==='GetCascadeTrajectory') { - const data=state.trajectories[body.cascadeId]; - if(data instanceof Error) throw data; - return {ok:true,json:async()=>data||{}}; - } - const data={GetUserStatus:{userStatus:{}},GetAllCascadeTrajectories:{trajectorySummaries:summaries},RetrieveUserQuotaSummary:{response:{groups:[]}}}[method]; - return {ok:true,json:async()=>data}; - }, - }; - vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost};',ctx); - return {...ctx.api,state}; -} diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs deleted file mode 100644 index 31c05c1..0000000 --- a/sidecars/panel/test/backend.test.mjs +++ /dev/null @@ -1,67 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import {backendHarness} from './backend-harness.mjs'; - -const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{ - createdAt:'2026-01-01T00:00:00Z',finishedGeneratingAt:'2026-01-01T00:00:10Z', - modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'}, -},plannerResponse:{response:'answer',thinkingDuration:'5s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}]}}; -const old={signature:'v5:old',title:'test',steps:[{stepIndex:0,modelKey:'MODEL_PLACEHOLDER_M418',inputTokens:100,cacheReadTokens:200,outputTokens:600,thinkingTokens:100,responseTokens:500,createdAtMs:1767225600000,ttftSec:0.4,streamTokPerSec:200,streamTokens:500,streamDurationSec:2.5,totalDurationSec:10,totalTokPerSec:60}]}; - -test('failed migration retains all accounting, makes legacy speed and TTFT unavailable',async()=>{ - const h=backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}}); - const p=await h.buildTelemetryPayloadInternal('test'); - assert.equal(p.activeConversation.latestTokPerSec,null); - assert.equal(p.activeConversation.latestTtftSec,null); - assert.equal(p.activeConversation.avgTokPerSec,null); - assert.equal(p.activeConversation.recentSteps[0].outputTokens,600); - assert.equal(p.consumption.session.totalTokens,900); - assert.equal(p.modelBreakdown[0].avgTokPerSec,null); - assert.equal(h.state.saves.length,0); -}); -test('successful migration rebuilds measurements and uses the same mean in both tables',async()=>{ - const h=backendHarness({cache:{test:old},trajectories:{test:raw}}); - const p=await h.buildTelemetryPayloadInternal('test'); - assert.equal(p.activeConversation.latestTokPerSec,60); - assert.equal(p.activeConversation.latestTtftSec,3); - assert.equal(p.activeConversation.avgTokPerSec,60); - assert.equal(p.modelBreakdown[0].avgTokPerSec,60); - assert.equal(p.modelBreakdown[0].speedSummary.sampleCount,1); - assert.equal(p.consumption.session.totalTokens,900); - assert.match(h.state.saves[0].data.test.signature,/^v9-unified-throughput:/); -}); -test('a legacy stream setting cannot re-enable mixed speed formulas',async()=>{ - const h=backendHarness({cache:{test:old},trajectories:{test:raw},settings:{speedMode:'stream'}}); - const p=await h.buildTelemetryPayloadInternal('test'); - assert.equal(p.activeConversation.latestTokPerSec,60); - assert.equal(p.activeConversation.avgTokPerSec,60); - assert.equal(p.modelBreakdown[0].avgTokPerSec,60); - assert.equal(p.settings.speedMode,undefined); -}); -test('a malformed successful RPC cannot erase previously recorded usage',async()=>{ - const h=backendHarness({cache:{test:old},trajectories:{test:{}}}); - const p=await h.buildTelemetryPayloadInternal('test'); - assert.equal(p.consumption.session.totalTokens,900); - assert.equal(p.activeConversation.latestTtftSec,null); - assert.equal(h.state.saves.length,0); -}); -test('a partial trajectory cannot replace a complete historical cache',async()=>{ - const h=backendHarness({cache:{test:old},trajectories:{test:{trajectory:{steps:[]},numTotalSteps:3}}}); - const p=await h.buildTelemetryPayloadInternal('test'); - assert.equal(p.consumption.session.totalTokens,900); - assert.equal(h.state.saves.length,0); - assert.match(h.state.errors[0],/Incomplete trajectory/); -}); - -test('a TTFT-only correction is persisted even when usage, duration and signature match',async()=>{ - const h=backendHarness({cache:{test:old},trajectories:{test:raw},summaries:{test:{ - stepCount:1,lastModifiedTime:'2026-01-01T00:00:10Z',status:'CASCADE_RUN_STATUS_RUNNING', - }}}); - await h.buildTelemetryPayloadInternal('test'); - h.state.trajectories.test=structuredClone(raw); - h.state.trajectories.test.trajectory.generatorMetadata[0].chatModel.timeToFirstToken='9s'; - const next=await h.buildTelemetryPayloadInternal('test'); - assert.equal(next.activeConversation.latestTtftSec,9); - assert.equal(h.state.saves.length,2); - assert.equal(h.state.saves[1].data.test.steps[0].ttftSec,9); -}); diff --git a/sidecars/panel/test/speed-display.test.mjs b/sidecars/panel/test/speed-display.test.mjs deleted file mode 100644 index 740cbc5..0000000 --- a/sidecars/panel/test/speed-display.test.mjs +++ /dev/null @@ -1,52 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import {readFileSync} from 'node:fs'; -import vm from 'node:vm'; - -function page() { - function element(){return {children:[],_html:'',textContent:'',title:'',scrollTop:0, - get innerHTML(){return this._html;},set innerHTML(s){this._html=s;this.children=[];}, - appendChild(child){if(child.fragment)this.children.push(...child.children);else this.children.push(child);}, - closest(){return null;}};} - const elements=Object.fromEntries(['tab-steps-btn','steps-tbody','models-tbody'].map(id=>[id,element()])); - const document={getElementById:id=>elements[id],createElement:element,createDocumentFragment:()=>({...element(),fragment:true})}; - const source=readFileSync(new URL('../app.js',import.meta.url),'utf8'); - assert.match(source,/\ninit\(\);\s*$/); - const ctx=vm.createContext({window:{},document}); - vm.runInContext(source.replace(/\ninit\(\);\s*$/,'\n'),ctx); - return {ctx,elements}; -} -const step={stepIndex:1,modelShort:'test',outputTokens:300,responseTokens:200,thinkingTokens:100, - totalDurationSec:10,tokPerSec:30,ttftSec:2,costUsd:.01}; -test('tools and text render one TPS column without per-row speed categories',()=>{ - const {ctx,elements}=page(); - ctx.renderTables({recentSteps:[{...step,hasToolCalls:true}]},[]); - const row=elements['steps-tbody'].children[0]; - assert.match(row.innerHTML,/30\.0 tok\/s/); - assert.doesNotMatch(row.innerHTML,/正文估算|整体吞吐|≈/); - assert.match(row.title,/含等待与思考/); -}); -test('unknown and zero are distinct, and insufficient timing explains the missing rate',()=>{ - const {ctx,elements}=page(); - ctx.renderTables({recentSteps:[{...step,tokPerSec:null,ttftSec:null,selectedSpeedReason:'short_timing'}]},[]); - assert.match(elements['steps-tbody'].children[0].innerHTML,/计时过短/); - assert.match(elements['steps-tbody'].children[0].innerHTML,/—<\/td>/); - ctx.renderTables({recentSteps:[{...step,tokPerSec:0,ttftSec:0}]},[]); - assert.match(elements['steps-tbody'].children[0].innerHTML,/0\.0 tok\/s/); - assert.match(elements['steps-tbody'].children[0].innerHTML,/0\.0s<\/td>/); -}); -test('a TTFT-only correction refreshes the table even when TPS and step count do not change',()=>{ - const {ctx,elements}=page(); - ctx.renderTables({recentSteps:[step]},[]); - ctx.renderTables({recentSteps:[{...step,ttftSec:12.974}]},[]); - assert.match(elements['steps-tbody'].children[0].innerHTML,/13\.0s<\/td>/); -}); - -test('contradictory timing is explained and zero cache remains a per-request usage fact',()=>{ - const {ctx,elements}=page(); - ctx.renderTables({recentSteps:[{...step,tokPerSec:null,cacheHitPct:0,selectedSpeedReason:'inconsistent_timing'}]},[]); - const row=elements['steps-tbody'].children[0]; - assert.match(row.innerHTML,/原生首响应与总计时不一致/); - assert.match(row.innerHTML,/不是缓存容量/);assert.match(row.innerHTML,/>0%<\/td>/); - assert.doesNotMatch(row.innerHTML,/≈/); -}); diff --git a/sidecars/panel/test/speed-metrics.test.mjs b/sidecars/panel/test/speed-metrics.test.mjs deleted file mode 100644 index 18810cd..0000000 --- a/sidecars/panel/test/speed-metrics.test.mjs +++ /dev/null @@ -1,157 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import {extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs'; - -function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,response=1000, - thinkingDuration='4s',tools=false,text=true,status='CORTEX_STEP_STATUS_DONE'}={}) { - const s={status,type:'CORTEX_STEP_TYPE_PLANNER_RESPONSE',metadata:{ - createdAt:'2026-01-01T00:00:00Z',viewableAt:'2026-01-01T00:00:02Z', - finishedGeneratingAt:new Date(Date.parse('2026-01-01T00:00:00Z')+total*1000).toISOString(), - modelUsage:{inputTokens:'500',cacheReadTokens:'2000',outputTokens:String(output),thinkingOutputTokens:String(thinking),responseOutputTokens:String(response)}, - },plannerResponse:{response:text?'answer':'',thinkingDuration,toolCalls:tools?[{}]:[]}}; - const gm={stepIndices:[0],chatModel:{timeToFirstToken:ttft,streamingDuration:stream}}; - return {s,gm}; -} -function parse(options) {const {s,gm}=sample(options);return extractModelSteps([s],[gm])[0];} - -test('text, tools and mixed output all use total output / full request duration',()=>{ - for(const tools of [false,true])for(const text of [false,true]){ - const step=parse({tools,text}); - assert.equal(speedMetric(step).value,1100/12); - assert.equal(step.speedBasis,'request_total'); - assert.equal(step.speedSampleEligible,true); - } -}); -test('buffered JSON cannot create a burst peak by shortening native or thinking phase timers',()=>{ - for(const stream of ['0.001s','0.01s','1s','10s',undefined]){ - for(const thinkingDuration of ['0.01s','9.999s',undefined]){ - const step=parse({total:10,ttft:'9.999s',stream,thinkingDuration,output:300,tools:true,text:false}); - assert.equal(step.totalTokPerSec,30); - assert.equal(step.ttftSec,9.999); - } - } -}); -test('TTFT is the exact native value, never a token-ratio guess or viewable-event substitute',()=>{ - assert.equal(parse({total:20,ttft:'19.9s',thinkingDuration:'19.95s',tools:true,text:false}).ttftSec,19.9); - const {s,gm}=sample();delete gm.chatModel.timeToFirstToken; - const step=extractModelSteps([s],[gm])[0]; - assert.equal(step.ttftSec,null);assert.equal(step.viewableDelaySec,2); - assert.deepEqual(summarizeTtft([step]),{sampleCount:0,avgSec:null}); -}); -test('zero TTFT is preserved and malformed or negative durations remain unknown',()=>{ - const zero=parse({ttft:'0s'}); - assert.equal(zero.ttftSec,0); - assert.equal(summarizeTtft([zero]).avgSec,0); - for(const ttft of ['-1s','12garbage','NaNs','Infinitys',''])assert.equal(parse({ttft}).ttftSec,null); -}); -test('short output keeps the same formula but does not bias the mean',()=>{ - const short=parse({output:13,response:13,thinking:0,total:5.015,stream:'0.118s'}); - assert.equal(short.totalTokPerSec,13/5.015); - assert.equal(short.speedReason,'short_sample'); - assert.equal(summarizeSpeed([short,parse()]).avgTokPerSec,1100/12); - assert.equal(summarizeSpeed([short]).avgTokPerSec,null); - assert.equal(parse({output:50}).speedSampleEligible,true); -}); -test('sub-half-second whole requests are withheld, never divided by a tiny interval',()=>{ - const tiny=parse({total:.05,output:1000}); - assert.equal(tiny.totalTokPerSec,null);assert.equal(tiny.speedReason,'short_timing'); - assert.equal(speedMetric(tiny).value,null); - assert.equal(summarizeSpeed([tiny]).sampleCount,0); - assert.equal(parse({total:.5,output:100,ttft:'0.1s'}).totalTokPerSec,200); -}); -test('weighted mean matches token/time totals and does not average step rates',()=>{ - const a=parse({output:1000,total:10}),b=parse({output:1000,total:20,tools:true}); - const mean=summarizeSpeed([a,b]); - assert.equal(mean.tokens,2000);assert.equal(mean.seconds,30); - assert.equal(mean.avgTokPerSec,2000/30);assert.equal(mean.sampleCount,2); -}); -test('unfinished, missing-completion and reversed-time requests cannot fabricate speed',()=>{ - const {s,gm}=sample();delete s.metadata.finishedGeneratingAt; - assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null); - assert.equal(parse({total:-1}).totalTokPerSec,null); - assert.equal(parse({total:0}).totalTokPerSec,null); - assert.equal(parse({status:'CORTEX_STEP_STATUS_GENERATING'}).totalTokPerSec,null); -}); -test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{ - const zero=parse({output:0,response:0,thinking:0}); - assert.equal(zero.totalTokPerSec,0);assert.equal(zero.responseTokens,0); - for(const output of [-1,1.5,NaN,Infinity])assert.equal(parse({output}).totalTokPerSec,null); - const {s,gm}=sample();delete s.metadata.modelUsage.outputTokens; - assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null); -}); -test('missing phase/token breakdown cannot change a valid full-request rate',()=>{ - const {s,gm}=sample();delete s.plannerResponse.thinkingDuration; - delete s.metadata.modelUsage.thinkingOutputTokens;delete s.metadata.modelUsage.responseOutputTokens; - delete gm.chatModel.streamingDuration; - assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,1100/12); -}); -test('no rate-dependent cap or formula switch at the former 260 TPS boundary',()=>{ - const a=parse({total:10,output:2590,tools:true}),b=parse({total:10,output:2610,tools:true}); - assert.equal(a.totalTokPerSec,259);assert.equal(b.totalTokPerSec,261); - assert.equal(a.speedBasis,b.speedBasis); -}); -test('legacy cache retains billing but cannot masquerade as current measurements',()=>{ - for(const measurementVersion of [undefined,1,2,3]){ - const old={measurementVersion,inputTokens:500,cacheReadTokens:2000,outputTokens:1100,ttftSec:0.4,totalTokPerSec:55}; - const migrated=normalizeCachedStep(old); - assert.equal(migrated.outputTokens,1100);assert.equal(migrated.inputTokens,500); - assert.equal(migrated.ttftSec,null);assert.equal(speedMetric(migrated).value,null); - assert.equal(speedMetric(migrated).reason,'legacy_cache'); - } -}); - -test('half-second cutoff uses the original nanoseconds, not rounded epoch milliseconds',()=>{ - const {s,gm}=sample({output:100,ttft:'0.1s'}); - s.metadata.createdAt='2026-01-01T00:00:00.000000001Z'; - s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000000Z'; - const below=extractModelSteps([s],[gm])[0]; - assert.equal(below.totalDurationSec,.499999999);assert.equal(below.totalTokPerSec,null); - s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000001Z'; - assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200); - s.metadata.createdAt='2026-01-01T08:00:00.000000001+08:00'; - assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200); -}); -test('non-chat generator metadata cannot overwrite matching model timing',()=>{ - const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42};gm.stepIndices=[42]; - const other={stepIndices:[42],tool:{}}; - assert.equal(extractModelSteps([s],[gm,other])[0].nativeTtftSec,2); - s.metadata.generatorMetadata=[other,{chatModel:{timeToFirstToken:'3s'}}]; - assert.equal(extractModelSteps([s],[gm])[0].nativeTtftSec,3); -}); -test('a paginated source step never borrows timing from an unrelated array position',()=>{ - const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42}; - const step=extractModelSteps([s],[gm])[0]; - assert.equal(step.nativeTtftSec,null);assert.equal(step.totalTokPerSec,1100/12); -}); -test('contradictory native TTFT is preserved but cannot validate TPS or bias the TTFT mean',()=>{ - const bad=parse({total:5,ttft:'9s'}); - assert.equal(bad.nativeTtftSec,9);assert.equal(bad.totalTokPerSec,null); - assert.equal(bad.speedReason,'inconsistent_timing'); - assert.deepEqual(summarizeTtft([bad,parse()]),{sampleCount:1,avgSec:2}); -}); -test('unfinished steps do not enter the TTFT mean even when partial metadata includes TTFT',()=>{ - const partial=parse({status:'CORTEX_STEP_STATUS_GENERATING',ttft:'8s'}); - assert.deepEqual(summarizeTtft([partial,parse()]),{sampleCount:1,avgSec:2}); -}); -test('coercible non-token values cannot silently become zero or one output token',()=>{ - for(const value of [true,false,' ',[],{}]){ - const {s,gm}=sample();s.metadata.modelUsage.outputTokens=value; - assert.equal(extractModelSteps([s],[gm])[0].speedReason,'invalid_output_tokens'); - } -}); -test('visible buffered text and tools use full time without a rate-dependent switch',()=>{ - const {s,gm}=sample({output:64,thinking:33,response:31,ttft:'7.0108593s',stream:'0.0045919s'}); - s.metadata.finishedGeneratingAt='2026-01-01T00:00:07.015451200Z'; - delete s.plannerResponse.thinkingDuration; - const step=extractModelSteps([s],[gm])[0]; - assert.equal(step.totalDurationSec,7.0154512); - assert.equal(speedMetric(step).value,64/7.0154512); - assert.equal(step.speedBasis,'request_total'); -}); -test('compaction displays a valid rate and retains billing but is excluded from speed/TTFT means',()=>{ - const {s,gm}=sample();s.type='CORTEX_STEP_TYPE_CHECKPOINT'; - const step=extractModelSteps([s],[gm])[0]; - assert.equal(step.outputTokens,1100);assert.equal(speedMetric(step).value,1100/12); - assert.equal(summarizeSpeed([step]).sampleCount,0); - assert.equal(summarizeTtft([step]).sampleCount,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')); -});