From de35e54589c70e03c36856f8769672f0b51ac1df Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Wed, 25 Nov 2026 01:39:56 +0900 Subject: [PATCH] refactor(panel): extract overlay anchors and consumption row builders - Extract host anchor discovery, 4-stage capsule layout hysteresis, and ShadowRoot stylesheet mounting from WindowOverlayShell into overlayHostAnchors - Extract reusable model, client-source, workspace, and top-conversation breakdown row builders from ConsumptionView into ConsumptionBreakdownRows - Add root CHANGELOG.md and regression coverage for extracted P3 modules and export header documentation --- CHANGELOG.md | 39 + sidecars/panel/app.js | 1892 +++++++++-------- sidecars/panel/backend/file-exporter.mjs | 6 +- sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 2 + .../components/layout/WindowOverlayShell.js | 919 +------- .../components/layout/overlayHostAnchors.js | 919 ++++++++ .../widgets/ConsumptionBreakdownRows.js | 887 ++++++++ sidecars/panel/src/views/ConsumptionView.js | 979 +-------- .../test/practical-enhancements.test.mjs | 112 + 10 files changed, 2977 insertions(+), 2782 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 sidecars/panel/src/components/layout/overlayHostAnchors.js create mode 100644 sidecars/panel/src/components/widgets/ConsumptionBreakdownRows.js diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..528d65e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,39 @@ +# Changelog + +All notable changes to **Antigravity Usage & Speed Monitor** are documented in this file. + +## [1.5.4] - Unreleased + +### Added +- **Local CloudCode Proxy & Dual Context-Window Controls**: Added `cloudcode-proxy.mjs` loopback reverse proxy (`SetCloudCodeURL`) to synchronize custom per-model context window limits to non-`self` subagents and Swarm workers alongside independent `contextWindowMainEnabled` / `contextWindowSwarmEnabled` toggles. +- **Experimental Quota Lease Reservation Estimator**: Added `quota-reservation.mjs` 5h/weekly dual-bucket in-flight quota lease tracking, FIFO settlement, delayed refund confirmation, outlier-filtered rolling median rate calibration, violet bar indicator, and `GET /api/quota-reservation/log`. +- **Native Multi-Sheet `.xlsx` & Markdown Exports**: Added zero-dependency OOXML workbook builder (`xlsxBuilder.js`) and localized multi-sheet Excel / Markdown report exports with local `~/Downloads` save and one-click file manager reveal toast. +- **Step Diagnostic Drawer & Live Filtering**: Added click-to-inspect `StepDiagnosticDrawer` (timing waterfall, token/cost breakdown, 9-kind V4 `anomaly.events` list, Markdown copy), live multi-term step search, and danger-tier diagnostic filter chips. +- **Workspace Cost Attribution & Session Migration**: Added **Projects (Workspaces)** cost ranking tab, session project tags, portable JSON settings backup/import, and opt-in cross-client session migration/cloning (`CLI ↔ Desktop/IDE` and `Legacy IDE`) with isolated UUID rewriting. +- **CLI `statusLine` Gauge Styles & JSON Output**: Added `--style pill|bar|compact`, `--preset compact|balanced|full`, and single-line `--json` snapshot output for external prompt/bar integrations. + +### Changed & Optimized +- **Hot-Path Performance (P1)**: Made `trajectoryCache` lazy via `createTrajectoryCacheStore` and added tail-row (`LIMIT 16`) SQLite reads for `cli-statusline.mjs` (`~419ms → <60ms`); skipped redundant per-poll WAL `statSync` on unchanged `IDLE` sessions; switched `cloudcode-proxy` Windows system proxy lookup to async `execFile` with TTL caching; deferred overlay `App()` instantiation until first popover open; coalesced host `MutationObserver` via `requestAnimationFrame`; shared `adoptedStyleSheets` across overlay portals and cached chart `DOMRect` on hover. +- **Shared Primitives & Modular Architecture (P2–P3)**: Extracted `fs-atomic.mjs`, `trajectory-cache-store.mjs`, `workspace-uri.mjs`, `prompt-clean.mjs`, `windows-shortcut-provision.ps1`, `ToggleSwitch.js` (cutting `SettingsView` `ResizeObserver` count by ~59%), `SearchInput.js`, `StepDiagnosticDrawer.js`, `ConsumptionBreakdownRows.js`, `stepChartMath.js`, and `overlayHostAnchors.js`; upgraded `build-bundle.mjs` regex-after-condition-paren lexer and inner-IIFE `import/export { a as b }` alias support. + +### Fixed +- **Telemetry & Inspector Accuracy (P0)**: Unified step selection keys so clicking any step reliably opens the diagnostic drawer; preserved V4 `nativeStreamSec`, `thinkingDurationSec`, and `hasToolCalls` across step projections; fixed `reportExporter.js` and `stepInspector.js` duration/waterfall fields and `anomaly.events` rendering; computed merged model average speed from exact `speedSummary.{tokens, seconds}` harmonic totals; honored `ANTIGRAVITY_GEMINI_DIR` override and cleaned up `multiRunningWidget` on overlay disposal. + +## [1.5.3] - 2026-04 + +### Added & Changed +- Graduated borderless **Modern UI** to default, defaulted language to host/system (`auto`), and unified token breakdown ordering and flat tooltip cards. +- Added SSH Remote multi-window isolation (`endpoint-registry.mjs`) with per-endpoint trajectory/quota caches and RPC routing. +- Added support for Opus 5.5 Orchestrator (`Neon` variants) and prevented unknown future variants from misrouting to Carbon pools. +- Fixed 5-hour quota cycle boundary accounting and macOS host relaunch ancestor process matching. + +## [1.5.2] - 2026-03 + +### Added & Changed +- Added runtime-only whitelist Release ZIP packager (`pack-release-zip.mjs`), Native Swarm mode worker telemetry, 9-category step anomaly diagnostics, virtualized large step tables (`>80` rows), and pruned `scope=consumption` / `scope=conversation` fast paths. +- Hardened Desktop `2.33.0+` launcher auto-provisioning and out-of-job 1-click host relaunch across Windows (UIPI-safe user relaunch + on-demand UAC), macOS, and Linux (`.desktop` / AppImage). + +## [1.5.1] - 2026-03 + +### Added & Changed +- Added hybrid SQLite + WAL direct reader, `384k` context window preset, time-phased promotional model pricing, scalable `--fs-*` typography tokens, and isolated `sidecar-worker.mjs` hot-reloadable runtime. diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 5dd7476..6e3b297 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -27295,6 +27295,878 @@ const StepTableWidget = defineComponent({ return { formatTurnPromptText, StepTableWidget }; })(); +// --- src/components/widgets/ConsumptionBreakdownRows.js --- +const { partitionModelSegments, createBreakdownItemRow, updateBreakdownItemRow, createConsumptionBreakdownRowBuilders } = (() => { +/** + * @fileoverview Reusable model, client-source, workspace, and top-conversation breakdown + * row builders (`ConsumptionBreakdownRows.js`) extracted from `ConsumptionView.js`. + * Consolidates shared long-tail model partitioning, hover-popover event binding, and top-model pill rendering. + */ + + +function createSourceModelSegment() { + const segEl = h('div', { className: 'progress-seg cons-model-seg' }); + return { el: segEl, refs: { segEl } }; +} + +function createSourceTopModelItem() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' }); + const nameEl = h('span', { className: 'cons-source-top-name' }); + const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' }); + const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]); + return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } }; +} + +function formatCompactSourceSharePct(pct) { + const num = Number(pct || 0); + if (!Number.isFinite(num) || num <= 0) return '0%'; + if (num >= 10) return `${Math.round(num)}%`; + return `${num.toFixed(1)}%`; +} + +function renderSegmentedModelBarAndTopPills( + trackEl, + topModelsEl, + partitioned, + scaleRatio, + fallbackKey +) { + const barItems = + partitioned.length > 0 + ? partitioned.map((seg) => ({ + key: seg.key, + segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, + color: seg.color, + })) + : scaleRatio > 0 + ? [ + { + key: fallbackKey, + segPct: scaleRatio * 100, + color: 'var(--accent-primary)', + }, + ] + : []; + + patchKeyedList(trackEl, barItems, { + keyFn: (seg) => seg.key, + sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, + createRow: createSourceModelSegment, + updateRow: (segRefs, seg) => { + patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); + patchStyleVar(segRefs.segEl, '--seg-color', seg.color); + }, + }); + + const topModels = partitioned + .filter((seg) => !seg.isOther) + .slice(0, 3) + .map((seg) => ({ + key: seg.key, + label: seg.label, + pctText: formatCompactSourceSharePct(seg.pct), + color: seg.color, + })); + patchAttr(topModelsEl, 'hidden', topModels.length === 0); + patchKeyedList(topModelsEl, topModels, { + keyFn: (m) => m.key, + sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, + createRow: createSourceTopModelItem, + updateRow: (mRefs, m) => { + patchStyleVar(mRefs.dotEl, '--dot-color', m.color); + patchText(mRefs.nameEl, m.label); + patchText(mRefs.pctEl, m.pctText); + patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); + }, + }); + + return topModels; +} + +/** + * Collapses long-tail model entries into primary segments + an aggregated "Other (N)" tail. + */ +function partitionModelSegments( + mergedModels, + modelColorMap, + { maxMain = 5, minSharePct = 1.5 } = {} +) { + if (!Array.isArray(mergedModels) || mergedModels.length === 0) return []; + const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); + const mainModels = []; + const tailModels = []; + + for (let i = 0; i < mergedModels.length; i += 1) { + const m = mergedModels[i]; + const mTok = Number(m.totalTokens || 0); + const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0; + if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) { + mainModels.push(m); + } else { + tailModels.push(m); + } + } + + if (tailModels.length === 1) { + mainModels.push(tailModels.pop()); + } + + const out = mainModels.map((m) => { + const seed = getCanonicalModelColorSeed(m); + const color = + modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText); + const tok = Number(m.totalTokens || 0); + const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0; + const label = m.displayText || m.label || m.shortName || '—'; + const inputTokens = Math.max(0, Number(m.inputTokens || 0)); + const cacheReadTokens = Math.max(0, Number(m.cacheReadTokens || 0)); + const thinkingTokens = Math.max(0, Number(m.thinkingTokens || 0)); + const responseTokens = + m.responseTokens != null + ? Math.max(0, Number(m.responseTokens)) + : Math.max(0, Number(m.outputTokens || 0) - thinkingTokens); + return { + key: label, + label, + tok, + pct, + inputTokens, + cacheReadTokens, + thinkingTokens, + responseTokens, + outputTokens: responseTokens + thinkingTokens, + tokText: formatTokensPrecise(tok), + pctText: formatPctNumber(pct, { withSymbol: true }), + color, + isOther: false, + }; + }); + + if (tailModels.length >= 2) { + let otherTok = 0; + let otherIn = 0; + let otherCache = 0; + let otherThink = 0; + let otherResp = 0; + for (const m of tailModels) { + const mt = Math.max(0, Number(m.thinkingTokens || 0)); + const mr = + m.responseTokens != null + ? Math.max(0, Number(m.responseTokens)) + : Math.max(0, Number(m.outputTokens || 0) - mt); + otherTok += Number(m.totalTokens || 0); + otherIn += Math.max(0, Number(m.inputTokens || 0)); + otherCache += Math.max(0, Number(m.cacheReadTokens || 0)); + otherThink += mt; + otherResp += mr; + } + const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0; + const otherLabel = t('cons.otherModelsCount', { count: tailModels.length }); + out.push({ + key: '__other__', + label: otherLabel, + tok: otherTok, + pct: otherPct, + inputTokens: otherIn, + cacheReadTokens: otherCache, + thinkingTokens: otherThink, + responseTokens: otherResp, + outputTokens: otherResp + otherThink, + tokText: formatTokensPrecise(otherTok), + pctText: formatPctNumber(otherPct, { withSymbol: true }), + color: 'var(--cons-other-seg)', + isOther: true, + }); + } + + return out; +} + +/** + * Creates a model ranking row (`tokens` | `cost` | `speed` | `calls` sort modes). + */ +function createBreakdownItemRow() { + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const segBar = createFourSegmentBar(); + + const inLbl = h('span', { text: t('cons.footInput') }); + const cacheLbl = h('span', { text: t('cons.footCache') }); + const outLbl = h('span', { text: t('cons.footOutput') }); + const thinkLbl = h('span', { text: t('cons.footThinking') }); + const callsLbl = h('span', { text: t('cons.footCalls') }); + + const inVal = h('strong', { className: 'text-mono' }); + const cacheVal = h('strong', { className: 'text-mono' }); + const outVal = h('strong', { className: 'text-mono' }); + const thinkVal = h('strong', { className: 'text-mono' }); + const callsVal = h('strong', { className: 'text-mono' }); + const metricBarFillEl = h('div', { className: 'progress-seg cons-metric-fill' }); + const metricBarEl = h( + 'div', + { className: 'progress-track cons-seg-bar cons-metric-bar', hidden: true }, + [metricBarFillEl] + ); + const tokenFootEl = h('div', { className: 'cons-item-foot' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + inLbl, + inVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheLbl, + cacheVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + thinkLbl, + thinkVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outLbl, + outVal, + ]), + h('span', { className: 'legend-left' }, [callsLbl, callsVal]), + ]); + const perfMainEl = h('span', { className: 'cons-model-perf-main text-mono' }); + const perfUnitCostEl = h('span', { className: 'cons-model-unit-cost text-mono', hidden: true }); + const perfFootEl = h('div', { className: 'cons-model-perf-foot', hidden: true }, [ + perfMainEl, + perfUnitCostEl, + ]); + const focusLeftEl = h('span', { className: 'cons-model-focus-left text-mono' }); + const focusRightEl = h('span', { className: 'cons-model-focus-right text-mono' }); + const focusFootEl = h( + 'div', + { className: 'cons-item-foot cons-model-focus-foot', hidden: true }, + [focusLeftEl, focusRightEl] + ); + + const rowEl = h('div', { className: 'cons-item-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), + ]), + segBar.el, + metricBarEl, + tokenFootEl, + perfFootEl, + focusFootEl, + ]); + + return { + el: rowEl, + refs: { + nameEl, + nameTextEl, + pctBadge, + totalTokEl, + costEl, + segBar, + metricBarEl, + metricBarFillEl, + tokenFootEl, + inLbl, + cacheLbl, + outLbl, + thinkLbl, + callsLbl, + inVal, + cacheVal, + outVal, + thinkVal, + callsVal, + perfFootEl, + perfMainEl, + perfUnitCostEl, + focusFootEl, + focusLeftEl, + focusRightEl, + }, + }; +} + +/** + * Incrementally patches a model ranking row. + */ +function updateBreakdownItemRow(refs, item, totalsCtx, sortMode = 'tokens') { + const displayLabel = item.label || item.name || item.shortName || '—'; + patchText(refs.nameTextEl, displayLabel); + patchAttr(refs.nameEl, 'title', item.title || displayLabel); + + const total = Number(item.totalTokens || 0); + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + + const avgTps = + item.avgTokPerSec != null && + Number.isFinite(Number(item.avgTokPerSec)) && + Number(item.avgTokPerSec) > 0 + ? Number(item.avgTokPerSec) + : null; + const avgTtft = + item.avgTtftSec != null && + Number.isFinite(Number(item.avgTtftSec)) && + Number(item.avgTtftSec) >= 0 + ? Number(item.avgTtftSec) + : null; + const hasExplicitCachePct = + item.cacheHitPct != null && Number.isFinite(Number(item.cacheHitPct)); + const promptTok = Number(item.inputTokens || 0) + Number(item.cacheReadTokens || 0); + const cachePctVal = hasExplicitCachePct + ? Number(item.cacheHitPct) + : promptTok > 0 && Number(item.cacheReadTokens || 0) > 0 + ? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1) + : 0; + const cachePctStr = formatPctNumber(cachePctVal); + const effCostPer1M = + !isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null; + const outTok = Number( + item.outputTokens ?? Number(item.responseTokens || 0) + Number(item.thinkingTokens || 0) + ); + + if (sortMode === 'cost') { + const costBase = Number(totalsCtx?.totalCost || 0); + const costShare = costBase > 0 ? +((costVal / costBase) * 100).toFixed(1) : 0; + const barPct = + costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0; + patchAttr(refs.pctBadge, 'hidden', false); + patchAttr(refs.pctBadge, 'title', null); + patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true })); + patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal)); + patchText(refs.costEl, costText); + + patchAttr(refs.segBar.el, 'hidden', true); + patchAttr(refs.metricBarEl, 'hidden', false); + patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); + patchClasses(refs.metricBarFillEl, { + 'tone-cost': true, + 'tone-speed': false, + 'tone-calls': false, + }); + + patchAttr(refs.tokenFootEl, 'hidden', true); + patchAttr(refs.perfFootEl, 'hidden', true); + patchAttr(refs.focusFootEl, 'hidden', false); + const unitPart = + effCostPer1M !== null + ? t('cons.modelUnitCost', { + cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), + }) + : ''; + const cachePart = t('cons.topConvCacheMeta', { pct: cachePctStr }); + patchText(refs.focusLeftEl, unitPart ? `${unitPart} · ${cachePart}` : cachePart); + patchText( + refs.focusRightEl, + `${formatTokensPrecise(total)} · ${t('cons.callsCount', { calls: callsCount })}` + ); + return; + } + + if (sortMode === 'speed') { + const maxTps = Number(totalsCtx?.maxAvgTps || 0); + const speedPct = + maxTps > 0 && avgTps !== null ? Math.min(100, Math.max(2, (avgTps / maxTps) * 100)) : 0; + patchAttr(refs.pctBadge, 'hidden', avgTps === null); + patchAttr(refs.pctBadge, 'title', avgTps !== null ? t('cons.speedRelTip') : null); + patchText(refs.pctBadge, avgTps !== null ? `${Math.round(speedPct)}%` : ''); + patchText( + refs.totalTokEl, + avgTtft !== null ? t('cons.focusTtft', { ttft: formatMetric(avgTtft, 's') }) : '' + ); + patchText(refs.costEl, formatSpeedMetric(avgTps, ' tok/s')); + + patchAttr(refs.segBar.el, 'hidden', true); + patchAttr(refs.metricBarEl, 'hidden', false); + patchStyleVar(refs.metricBarFillEl, '--seg-w', `${speedPct.toFixed(2)}%`); + patchClasses(refs.metricBarFillEl, { + 'tone-cost': false, + 'tone-speed': true, + 'tone-calls': false, + }); + + patchAttr(refs.tokenFootEl, 'hidden', true); + patchAttr(refs.perfFootEl, 'hidden', true); + patchAttr(refs.focusFootEl, 'hidden', false); + patchText( + refs.focusLeftEl, + t('cons.focusSpeedMeta', { + ttft: formatMetric(avgTtft, 's'), + cache: cachePctStr, + out: formatTokensPrecise(outTok), + }) + ); + patchText(refs.focusRightEl, t('cons.callsCount', { calls: callsCount })); + return; + } + + if (sortMode === 'calls') { + const callsBase = Number(totalsCtx?.totalCalls || 0); + const callsShare = callsBase > 0 ? +((callsCount / callsBase) * 100).toFixed(1) : 0; + const barPct = + callsBase > 0 && callsCount > 0 + ? Math.min(100, Math.max(1, (callsCount / callsBase) * 100)) + : 0; + patchAttr(refs.pctBadge, 'hidden', false); + patchAttr(refs.pctBadge, 'title', null); + patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true })); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + patchText(refs.costEl, t('cons.callsCount', { calls: callsCount })); + + patchAttr(refs.segBar.el, 'hidden', true); + patchAttr(refs.metricBarEl, 'hidden', false); + patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); + patchClasses(refs.metricBarFillEl, { + 'tone-cost': false, + 'tone-speed': false, + 'tone-calls': true, + }); + + patchAttr(refs.tokenFootEl, 'hidden', true); + patchAttr(refs.perfFootEl, 'hidden', true); + patchAttr(refs.focusFootEl, 'hidden', false); + const avgPerCall = callsCount > 0 ? total / callsCount : 0; + patchText( + refs.focusLeftEl, + t('cons.focusCallsMeta', { + avgTok: formatTokensPrecise(avgPerCall), + cost: costText, + }) + ); + patchText(refs.focusRightEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); + return; + } + + patchText(refs.inLbl, t('cons.footInput')); + patchText(refs.cacheLbl, t('cons.footCache')); + patchText(refs.outLbl, t('cons.footOutput')); + patchText(refs.thinkLbl, t('cons.footThinking')); + patchText(refs.callsLbl, t('cons.footCalls')); + const grandTotalTokens = Number(totalsCtx?.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; + patchAttr(refs.pctBadge, 'hidden', false); + patchAttr(refs.pctBadge, 'title', null); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + patchText(refs.costEl, costText); + + const responseTok = + item.responseTokens != null + ? Number(item.responseTokens) + : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); + const thinkingTok = Number(item.thinkingTokens || 0); + + patchAttr(refs.segBar.el, 'hidden', false); + patchAttr(refs.metricBarEl, 'hidden', true); + refs.segBar.update({ + inputTokens: Number(item.inputTokens || 0), + cacheReadTokens: Number(item.cacheReadTokens || 0), + responseTokens: responseTok, + thinkingTokens: thinkingTok, + scaleRatio, + }); + + patchAttr(refs.tokenFootEl, 'hidden', false); + patchAttr(refs.focusFootEl, 'hidden', true); + patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); + patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); + patchText(refs.outVal, formatTokensPrecise(responseTok)); + patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); + patchText(refs.callsVal, String(callsCount)); + + const hasPerfMeta = avgTps !== null || avgTtft !== null || effCostPer1M !== null; + patchAttr(refs.perfFootEl, 'hidden', !hasPerfMeta); + if (hasPerfMeta) { + if (avgTps !== null || avgTtft !== null) { + patchText( + refs.perfMainEl, + t('steps.modelPerfFoot', { + tps: formatSpeedMetric(avgTps, ' tok/s'), + ttft: formatMetric(avgTtft, 's'), + cache: cachePctStr, + }) + ); + } else { + patchText(refs.perfMainEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); + } + patchAttr(refs.perfUnitCostEl, 'hidden', effCostPer1M === null); + patchText( + refs.perfUnitCostEl, + effCostPer1M !== null + ? t('cons.modelUnitCost', { + cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), + }) + : '' + ); + } +} + +/** + * Binds shared popover hover callbacks to build source-breakdown and workspace/conversation rows. + */ +function createConsumptionBreakdownRowBuilders({ + showPopover, + movePopover, + hidePopover, + isHoveredTarget, + onSelectConversation, +}) { + function isNodeInside(root, node) { + if (!root || !node) return false; + if (typeof root.contains === 'function') return root.contains(node); + let cur = node; + while (cur) { + if (cur === root) return true; + cur = cur.parentNode || null; + } + return false; + } + + function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) { + zoneEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && isHoveredTarget(zoneEl)) { + movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mouseleave', () => { + if (isHoveredTarget(zoneEl)) hidePopover(); + }); + + for (const childEl of compatTargets) { + if (!childEl) continue; + childEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && isHoveredTarget(zoneEl)) { + movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mouseleave', (e) => { + const nextEl = e?.relatedTarget || null; + if (isNodeInside(zoneEl, nextEl)) { + return; + } + if (isHoveredTarget(zoneEl)) hidePopover(); + }); + } + } + + function createSourceBreakdownRow() { + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); + const rowState = { hoverPayload: null }; + + const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); + const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); + + const callsLbl = h('span', { text: t('cons.footCalls') }); + const callsVal = h('strong', { className: 'text-mono' }); + + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + + const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), + ]), + hoverZoneEl, + ]); + + return { + el: rowEl, + refs: { + nameEl, + nameTextEl, + pctBadge, + totalTokEl, + costEl, + hoverZoneEl, + barHitEl, + trackEl, + topModelsEl, + callsLbl, + callsVal, + rowState, + }, + }; + } + + function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) { + patchText(refs.callsLbl, t('cons.footCalls')); + const displayLabel = item.label || item.name || '—'; + patchText(refs.nameTextEl, displayLabel); + patchAttr(refs.nameEl, 'title', item.title || displayLabel); + + const total = Number(item.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + patchText(refs.costEl, costText); + patchText(refs.callsVal, String(callsCount)); + + const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; + const partitioned = partitionModelSegments(sourceModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + + renderSegmentedModelBarAndTopPills( + refs.trackEl, + refs.topModelsEl, + partitioned, + total > 0 ? scaleRatio : 0, + '__source_fallback__' + ); + + refs.rowState.hoverPayload = + total > 0 || callsCount > 0 + ? { + title: displayLabel, + calls: callsCount, + totalTokens: total, + costText, + inputTokens: item.inputTokens, + cacheReadTokens: item.cacheReadTokens, + thinkingTokens: item.thinkingTokens, + responseTokens: item.responseTokens, + outputTokens: item.outputTokens, + segments: partitioned, + } + : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); + } + + function createTopConversationRow() { + const titleTextEl = h('span', { className: 'cons-row-title-text' }); + const wsBadgeEl = h('span', { className: 'cons-ws-sessions-tag text-mono', hidden: true }); + const titleEl = h('strong', { className: 'cons-row-title cons-top-conv-title' }, [ + titleTextEl, + wsBadgeEl, + ]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); + const rowState = { cascadeId: '', canJump: false, hoverPayload: null }; + + const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); + const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); + + const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true }); + const callsLbl = h('span', { text: t('cons.footCalls') }); + const callsVal = h('strong', { className: 'text-mono' }); + + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + fallbackMetaEl, + h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + + const rowEl = h( + 'div', + { + className: 'cons-top-conv-row', + onClick: () => { + if (!rowState.canJump || !rowState.cascadeId) return; + hidePopover(); + onSelectConversation?.(rowState.cascadeId); + }, + }, + [ + h('div', { className: 'panel-header' }, [ + titleEl, + h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), + ]), + hoverZoneEl, + ] + ); + + return { + el: rowEl, + refs: { + rowEl, + titleEl, + titleTextEl, + wsBadgeEl, + pctBadge, + totalTokEl, + costEl, + hoverZoneEl, + barHitEl, + trackEl, + topModelsEl, + fallbackMetaEl, + callsLbl, + callsVal, + rowState, + }, + }; + } + + function updateTopConversationRow(refs, item, bases, modelColorMap, sortMode = 'cost') { + patchText(refs.callsLbl, t('cons.footCalls')); + const isWorkspaceRow = Boolean(item.isWorkspaceRow); + const title = isWorkspaceRow + ? item.isUnbound + ? t('cons.workspaceUnbound') + : String(item.label || item.workspacePath || '—').trim() + : String(item.title || item.cascadeId || '—').trim(); + refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || ''); + refs.rowState.canJump = + !isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId); + patchClasses(refs.rowEl, { + 'is-jumpable': refs.rowState.canJump, + 'cons-workspace-row': isWorkspaceRow, + }); + const baseTip = + isWorkspaceRow && item.workspacePath && item.workspacePath !== title + ? `${title} (${item.workspacePath})` + : title; + patchAttr( + refs.rowEl, + 'title', + refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip + ); + patchText(refs.titleTextEl, title); + if (refs.wsBadgeEl) { + const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0; + patchAttr(refs.wsBadgeEl, 'hidden', !showWsBadge); + if (showWsBadge) { + patchText(refs.wsBadgeEl, t('cons.workspaceSessions', { count: item.sessionCount })); + } + } + + const total = Number(item.totalTokens || 0); + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + + const tokBase = Number(bases?.tokens || 0); + const costBase = Number(bases?.cost || 0); + const useCostBasis = sortMode === 'cost' && costBase > 0; + const share = useCostBasis + ? +((costVal / costBase) * 100).toFixed(1) + : tokBase > 0 + ? +((total / tokBase) * 100).toFixed(1) + : 0; + const scaleRatio = useCostBasis + ? costVal > 0 + ? Math.min(1, Math.max(0.01, costVal / costBase)) + : 0 + : tokBase > 0 && total > 0 + ? Math.min(1, Math.max(0.01, total / tokBase)) + : 0; + + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); + if (sortMode === 'tokens') { + patchText(refs.totalTokEl, costText); + patchText(refs.costEl, formatTokensPrecise(total)); + } else { + patchText(refs.totalTokEl, formatTokensPrecise(total)); + patchText(refs.costEl, costText); + } + patchText(refs.callsVal, String(callsCount)); + + const convModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; + const partitioned = partitionModelSegments(convModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + const topModels = renderSegmentedModelBarAndTopPills( + refs.trackEl, + refs.topModelsEl, + partitioned, + scaleRatio, + '__conv_fallback__' + ); + + const showFallbackMeta = topModels.length === 0; + patchAttr(refs.fallbackMetaEl, 'hidden', !showFallbackMeta); + if (showFallbackMeta) { + const srcLabel = item.sourceName || item.appSource || ''; + const cacheLabel = t('cons.topConvCacheMeta', { + pct: formatPctNumber(item.cacheHitPct ?? 0), + }); + patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel); + } + + refs.rowState.hoverPayload = + partitioned.length > 0 && (total > 0 || callsCount > 0) + ? { + title, + calls: callsCount, + totalTokens: total, + costText, + inputTokens: item.inputTokens, + cacheReadTokens: item.cacheReadTokens, + thinkingTokens: item.thinkingTokens, + responseTokens: item.responseTokens, + outputTokens: item.outputTokens, + segments: partitioned, + } + : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); + } + + return { + createSourceBreakdownRow, + updateSourceBreakdownRow, + createTopConversationRow, + updateTopConversationRow, + }; +} +return { partitionModelSegments, createBreakdownItemRow, updateBreakdownItemRow, createConsumptionBreakdownRowBuilders }; +})(); + // --- src/components/settings/structurePreviewMock.js --- const { buildStructurePreviewTelemetry } = (() => { /** @@ -35635,911 +36507,28 @@ const ConsumptionView = defineComponent({ breakdownPopoverEl, ]); - /** - * 将分模型列表收敛为主力模型 + 长尾「其他 (N)」,避免进度条尾部与浮层出现 0.0% 碎屑噪音。 - */ - function partitionModelSegments( - mergedModels, - modelColorMap, - { maxMain = 5, minSharePct = 1.5 } = {} - ) { - if (!Array.isArray(mergedModels) || mergedModels.length === 0) return []; - const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); - const mainModels = []; - const tailModels = []; - - for (let i = 0; i < mergedModels.length; i++) { - const m = mergedModels[i]; - const mTok = Number(m.totalTokens || 0); - const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0; - if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) { - mainModels.push(m); - } else { - tailModels.push(m); - } - } - - if (tailModels.length === 1) { - mainModels.push(tailModels.pop()); - } - - const out = mainModels.map((m) => { - const seed = getCanonicalModelColorSeed(m); - const color = - modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText); - const tok = Number(m.totalTokens || 0); - const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0; - const label = m.displayText || m.label || m.shortName || '—'; - const inputTokens = Math.max(0, Number(m.inputTokens || 0)); - const cacheReadTokens = Math.max(0, Number(m.cacheReadTokens || 0)); - const thinkingTokens = Math.max(0, Number(m.thinkingTokens || 0)); - const responseTokens = - m.responseTokens != null - ? Math.max(0, Number(m.responseTokens)) - : Math.max(0, Number(m.outputTokens || 0) - thinkingTokens); - return { - key: label, - label, - tok, - pct, - inputTokens, - cacheReadTokens, - thinkingTokens, - responseTokens, - outputTokens: responseTokens + thinkingTokens, - tokText: formatTokensPrecise(tok), - pctText: formatPctNumber(pct, { withSymbol: true }), - color, - isOther: false, - }; - }); - - if (tailModels.length >= 2) { - let otherTok = 0; - let otherIn = 0; - let otherCache = 0; - let otherThink = 0; - let otherResp = 0; - for (const m of tailModels) { - const mt = Math.max(0, Number(m.thinkingTokens || 0)); - const mr = - m.responseTokens != null - ? Math.max(0, Number(m.responseTokens)) - : Math.max(0, Number(m.outputTokens || 0) - mt); - otherTok += Number(m.totalTokens || 0); - otherIn += Math.max(0, Number(m.inputTokens || 0)); - otherCache += Math.max(0, Number(m.cacheReadTokens || 0)); - otherThink += mt; - otherResp += mr; - } - const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0; - const otherLabel = t('cons.otherModelsCount', { count: tailModels.length }); - out.push({ - key: '__other__', - label: otherLabel, - tok: otherTok, - pct: otherPct, - inputTokens: otherIn, - cacheReadTokens: otherCache, - thinkingTokens: otherThink, - responseTokens: otherResp, - outputTokens: otherResp + otherThink, - tokText: formatTokensPrecise(otherTok), - pctText: formatPctNumber(otherPct, { withSymbol: true }), - color: 'var(--cons-other-seg)', - isOther: true, + const { + createSourceBreakdownRow, + updateSourceBreakdownRow, + createTopConversationRow, + updateTopConversationRow, + } = createConsumptionBreakdownRowBuilders({ + showPopover: showBreakdownPopover, + movePopover: positionBreakdownPopover, + hidePopover: hideBreakdownPopover, + isHoveredTarget: (targetEl) => activeHoverTargetEl === targetEl, + onSelectConversation: (cascadeId) => { + selectConversation(cascadeId); + uiStore.setState({ + activeView: 'steps', + stepsSubTab: 'steps', + selectedAgentScope: 'all', + ctxInspectorAgentId: getDefaultCtxInspectorAgentId( + telemetryStore.getState().telemetry?.settings + ), }); - } - - return out; - } - - /** - * 创建热门模型单行 DOM 结构(模型名称 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 - */ - function createBreakdownItemRow() { - const nameTextEl = h('span', { className: 'cons-row-title-text' }); - const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); - const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); - const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); - const costEl = h('strong', { className: 'cons-row-cost text-mono' }); - const segBar = createFourSegmentBar(); - - const inLbl = h('span', { text: t('cons.footInput') }); - const cacheLbl = h('span', { text: t('cons.footCache') }); - const outLbl = h('span', { text: t('cons.footOutput') }); - const thinkLbl = h('span', { text: t('cons.footThinking') }); - const callsLbl = h('span', { text: t('cons.footCalls') }); - - const inVal = h('strong', { className: 'text-mono' }); - const cacheVal = h('strong', { className: 'text-mono' }); - const outVal = h('strong', { className: 'text-mono' }); - const thinkVal = h('strong', { className: 'text-mono' }); - const callsVal = h('strong', { className: 'text-mono' }); - const metricBarFillEl = h('div', { className: 'progress-seg cons-metric-fill' }); - const metricBarEl = h( - 'div', - { className: 'progress-track cons-seg-bar cons-metric-bar', hidden: true }, - [metricBarFillEl] - ); - const tokenFootEl = h('div', { className: 'cons-item-foot' }, [ - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-input' }), - inLbl, - inVal, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheLbl, - cacheVal, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-thinking' }), - thinkLbl, - thinkVal, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-output' }), - outLbl, - outVal, - ]), - h('span', { className: 'legend-left' }, [ - callsLbl, - callsVal, - ]), - ]); - const perfMainEl = h('span', { className: 'cons-model-perf-main text-mono' }); - const perfUnitCostEl = h('span', { className: 'cons-model-unit-cost text-mono', hidden: true }); - const perfFootEl = h('div', { className: 'cons-model-perf-foot', hidden: true }, [ - perfMainEl, - perfUnitCostEl, - ]); - const focusLeftEl = h('span', { className: 'cons-model-focus-left text-mono' }); - const focusRightEl = h('span', { className: 'cons-model-focus-right text-mono' }); - const focusFootEl = h( - 'div', - { className: 'cons-item-foot cons-model-focus-foot', hidden: true }, - [focusLeftEl, focusRightEl] - ); - - const rowEl = h('div', { className: 'cons-item-row' }, [ - h('div', { className: 'panel-header' }, [ - nameEl, - h('span', { className: 'cons-row-metrics' }, [ - pctBadge, - totalTokEl, - costEl, - ]), - ]), - segBar.el, - metricBarEl, - tokenFootEl, - perfFootEl, - focusFootEl, - ]); - - return { - el: rowEl, - refs: { - nameEl, - nameTextEl, - pctBadge, - totalTokEl, - costEl, - segBar, - metricBarEl, - metricBarFillEl, - tokenFootEl, - inLbl, - cacheLbl, - outLbl, - thinkLbl, - callsLbl, - inVal, - cacheVal, - outVal, - thinkVal, - callsVal, - perfFootEl, - perfMainEl, - perfUnitCostEl, - focusFootEl, - focusLeftEl, - focusRightEl, - }, - }; - } - - /** - * 增量更新模型排行单行: - * - `tokens` 模式展示完整四段 Token 构成及效率副行; - * - `cost` / `speed` / `calls` 模式切换对应占比百分比、进度条尺度及聚焦单行脚标。 - */ - function updateBreakdownItemRow(refs, item, totalsCtx, sortMode = 'tokens') { - const displayLabel = item.label || item.name || item.shortName || '—'; - patchText(refs.nameTextEl, displayLabel); - patchAttr(refs.nameEl, 'title', item.title || displayLabel); - - const total = Number(item.totalTokens || 0); - const costVal = Number(item.costUsd || 0); - const callsCount = Number(item.calls || 0); - const isAllUnpriced = - callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); - const costText = formatUsd(isAllUnpriced ? null : costVal, { - precise: costVal > 0 && costVal < 0.1, - }); - - const avgTps = - item.avgTokPerSec != null && - Number.isFinite(Number(item.avgTokPerSec)) && - Number(item.avgTokPerSec) > 0 - ? Number(item.avgTokPerSec) - : null; - const avgTtft = - item.avgTtftSec != null && - Number.isFinite(Number(item.avgTtftSec)) && - Number(item.avgTtftSec) >= 0 - ? Number(item.avgTtftSec) - : null; - const hasExplicitCachePct = - item.cacheHitPct != null && Number.isFinite(Number(item.cacheHitPct)); - const promptTok = Number(item.inputTokens || 0) + Number(item.cacheReadTokens || 0); - const cachePctVal = hasExplicitCachePct - ? Number(item.cacheHitPct) - : promptTok > 0 && Number(item.cacheReadTokens || 0) > 0 - ? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1) - : 0; - const cachePctStr = formatPctNumber(cachePctVal); - const effCostPer1M = - !isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null; - const outTok = Number( - item.outputTokens ?? - Number(item.responseTokens || 0) + Number(item.thinkingTokens || 0) - ); - - if (sortMode === 'cost') { - const costBase = Number(totalsCtx?.totalCost || 0); - const costShare = costBase > 0 ? +((costVal / costBase) * 100).toFixed(1) : 0; - const barPct = costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0; - patchAttr(refs.pctBadge, 'hidden', false); - patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true })); - patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal)); - patchText(refs.costEl, costText); - - patchAttr(refs.segBar.el, 'hidden', true); - patchAttr(refs.metricBarEl, 'hidden', false); - patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); - patchClasses(refs.metricBarFillEl, { - 'tone-cost': true, - 'tone-speed': false, - 'tone-calls': false, - }); - - patchAttr(refs.tokenFootEl, 'hidden', true); - patchAttr(refs.perfFootEl, 'hidden', true); - patchAttr(refs.focusFootEl, 'hidden', false); - const unitPart = - effCostPer1M !== null - ? t('cons.modelUnitCost', { - cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), - }) - : ''; - const cachePart = t('cons.topConvCacheMeta', { pct: cachePctStr }); - patchText(refs.focusLeftEl, unitPart ? `${unitPart} · ${cachePart}` : cachePart); - patchText( - refs.focusRightEl, - `${formatTokensPrecise(total)} · ${t('cons.callsCount', { calls: callsCount })}` - ); - return; - } - - if (sortMode === 'speed') { - const maxTps = Number(totalsCtx?.maxAvgTps || 0); - const speedPct = - maxTps > 0 && avgTps !== null ? Math.min(100, Math.max(2, (avgTps / maxTps) * 100)) : 0; - patchAttr(refs.pctBadge, 'hidden', avgTps === null); - patchAttr(refs.pctBadge, 'title', avgTps !== null ? t('cons.speedRelTip') : null); - patchText(refs.pctBadge, avgTps !== null ? `${Math.round(speedPct)}%` : ''); - patchText( - refs.totalTokEl, - avgTtft !== null ? t('cons.focusTtft', { ttft: formatMetric(avgTtft, 's') }) : '' - ); - patchText(refs.costEl, formatSpeedMetric(avgTps, ' tok/s')); - - patchAttr(refs.segBar.el, 'hidden', true); - patchAttr(refs.metricBarEl, 'hidden', false); - patchStyleVar(refs.metricBarFillEl, '--seg-w', `${speedPct.toFixed(2)}%`); - patchClasses(refs.metricBarFillEl, { - 'tone-cost': false, - 'tone-speed': true, - 'tone-calls': false, - }); - - patchAttr(refs.tokenFootEl, 'hidden', true); - patchAttr(refs.perfFootEl, 'hidden', true); - patchAttr(refs.focusFootEl, 'hidden', false); - patchText( - refs.focusLeftEl, - t('cons.focusSpeedMeta', { - ttft: formatMetric(avgTtft, 's'), - cache: cachePctStr, - out: formatTokensPrecise(outTok), - }) - ); - patchText(refs.focusRightEl, t('cons.callsCount', { calls: callsCount })); - return; - } - - if (sortMode === 'calls') { - const callsBase = Number(totalsCtx?.totalCalls || 0); - const callsShare = callsBase > 0 ? +((callsCount / callsBase) * 100).toFixed(1) : 0; - const barPct = - callsBase > 0 && callsCount > 0 ? Math.min(100, Math.max(1, (callsCount / callsBase) * 100)) : 0; - patchAttr(refs.pctBadge, 'hidden', false); - patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true })); - patchText(refs.totalTokEl, formatTokensPrecise(total)); - patchText(refs.costEl, t('cons.callsCount', { calls: callsCount })); - - patchAttr(refs.segBar.el, 'hidden', true); - patchAttr(refs.metricBarEl, 'hidden', false); - patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); - patchClasses(refs.metricBarFillEl, { - 'tone-cost': false, - 'tone-speed': false, - 'tone-calls': true, - }); - - patchAttr(refs.tokenFootEl, 'hidden', true); - patchAttr(refs.perfFootEl, 'hidden', true); - patchAttr(refs.focusFootEl, 'hidden', false); - const avgPerCall = callsCount > 0 ? total / callsCount : 0; - patchText( - refs.focusLeftEl, - t('cons.focusCallsMeta', { - avgTok: formatTokensPrecise(avgPerCall), - cost: costText, - }) - ); - patchText(refs.focusRightEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); - return; - } - - // 默认 Token 模式:展示全部四段 Token 构成及效率副行 - patchText(refs.inLbl, t('cons.footInput')); - patchText(refs.cacheLbl, t('cons.footCache')); - patchText(refs.outLbl, t('cons.footOutput')); - patchText(refs.thinkLbl, t('cons.footThinking')); - patchText(refs.callsLbl, t('cons.footCalls')); - const grandTotalTokens = Number(totalsCtx?.totalTokens || 0); - const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; - const scaleRatio = - grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; - patchAttr(refs.pctBadge, 'hidden', false); - patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); - patchText(refs.totalTokEl, formatTokensPrecise(total)); - patchText(refs.costEl, costText); - - const responseTok = - item.responseTokens != null - ? Number(item.responseTokens) - : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); - const thinkingTok = Number(item.thinkingTokens || 0); - - patchAttr(refs.segBar.el, 'hidden', false); - patchAttr(refs.metricBarEl, 'hidden', true); - refs.segBar.update({ - inputTokens: Number(item.inputTokens || 0), - cacheReadTokens: Number(item.cacheReadTokens || 0), - responseTokens: responseTok, - thinkingTokens: thinkingTok, - scaleRatio, - }); - - patchAttr(refs.tokenFootEl, 'hidden', false); - patchAttr(refs.focusFootEl, 'hidden', true); - patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); - patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); - patchText(refs.outVal, formatTokensPrecise(responseTok)); - patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); - patchText(refs.callsVal, String(callsCount)); - - const hasPerfMeta = avgTps !== null || avgTtft !== null || effCostPer1M !== null; - patchAttr(refs.perfFootEl, 'hidden', !hasPerfMeta); - if (hasPerfMeta) { - if (avgTps !== null || avgTtft !== null) { - patchText( - refs.perfMainEl, - t('steps.modelPerfFoot', { - tps: formatSpeedMetric(avgTps, ' tok/s'), - ttft: formatMetric(avgTtft, 's'), - cache: cachePctStr, - }) - ); - } else { - patchText(refs.perfMainEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); - } - patchAttr(refs.perfUnitCostEl, 'hidden', effCostPer1M === null); - patchText( - refs.perfUnitCostEl, - effCostPer1M !== null - ? t('cons.modelUnitCost', { - cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), - }) - : '' - ); - } - } - - function createSourceModelSegment() { - const segEl = h('div', { className: 'progress-seg cons-model-seg' }); - return { el: segEl, refs: { segEl } }; - } - - function createSourceTopModelItem() { - const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' }); - const nameEl = h('span', { className: 'cons-source-top-name' }); - const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' }); - const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]); - return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } }; - } - - function formatCompactSourceSharePct(pct) { - const num = Number(pct || 0); - if (!Number.isFinite(num) || num <= 0) return '0%'; - if (num >= 10) return `${Math.round(num)}%`; - return `${num.toFixed(1)}%`; - } - - /** - * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。 - */ - function isNodeInside(root, node) { - if (!root || !node) return false; - if (typeof root.contains === 'function') return root.contains(node); - let cur = node; - while (cur) { - if (cur === root) return true; - cur = cur.parentNode || null; - } - return false; - } - - function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) { - zoneEl.addEventListener('mouseenter', (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); - } - }); - zoneEl.addEventListener('mousemove', (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { - positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); - } - }); - zoneEl.addEventListener('mouseleave', () => { - if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); - }); - - for (const childEl of compatTargets) { - if (!childEl) continue; - childEl.addEventListener('mouseenter', (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); - } - }); - childEl.addEventListener('mousemove', (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { - positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); - } - }); - childEl.addEventListener('mouseleave', (e) => { - const nextEl = e?.relatedTarget || null; - if (isNodeInside(zoneEl, nextEl)) { - return; - } - if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); - }); - } - } - - function createSourceBreakdownRow() { - const nameTextEl = h('span', { className: 'cons-row-title-text' }); - const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); - const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); - const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); - const costEl = h('strong', { className: 'cons-row-cost text-mono' }); - const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); - const rowState = { hoverPayload: null }; - - const barHitEl = h( - 'div', - { - className: 'cons-source-bar-hit', - }, - [trackEl] - ); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - - const callsLbl = h('span', { text: t('cons.footCalls') }); - const callsVal = h('strong', { className: 'text-mono' }); - - const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), - ]); - attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); - - const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ - h('div', { className: 'panel-header' }, [ - nameEl, - h('span', { className: 'cons-row-metrics' }, [ - pctBadge, - totalTokEl, - costEl, - ]), - ]), - hoverZoneEl, - ]); - - return { - el: rowEl, - refs: { - nameEl, - nameTextEl, - pctBadge, - totalTokEl, - costEl, - hoverZoneEl, - barHitEl, - trackEl, - topModelsEl, - callsLbl, - callsVal, - rowState, - }, - }; - } - - function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) { - patchText(refs.callsLbl, t('cons.footCalls')); - const displayLabel = item.label || item.name || '—'; - patchText(refs.nameTextEl, displayLabel); - patchAttr(refs.nameEl, 'title', item.title || displayLabel); - - const total = Number(item.totalTokens || 0); - const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; - const scaleRatio = - grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; - patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); - patchText(refs.totalTokEl, formatTokensPrecise(total)); - - const costVal = Number(item.costUsd || 0); - const callsCount = Number(item.calls || 0); - const isAllUnpriced = - callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); - const costText = formatUsd(isAllUnpriced ? null : costVal, { - precise: costVal > 0 && costVal < 0.1, - }); - patchText(refs.costEl, costText); - patchText(refs.callsVal, String(callsCount)); - - const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; - const partitioned = partitionModelSegments(sourceModels, modelColorMap, { - maxMain: 5, - minSharePct: 1.5, - }); - - const barItems = - partitioned.length > 0 - ? partitioned.map((seg) => ({ - key: seg.key, - segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, - color: seg.color, - })) - : total > 0 - ? [ - { - key: '__source_fallback__', - segPct: scaleRatio * 100, - color: 'var(--accent-primary)', - }, - ] - : []; - - patchKeyedList(refs.trackEl, barItems, { - keyFn: (seg) => seg.key, - sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, - createRow: createSourceModelSegment, - updateRow: (segRefs, seg) => { - patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); - patchStyleVar(segRefs.segEl, '--seg-color', seg.color); - }, - }); - - const topModels = partitioned - .filter((seg) => !seg.isOther) - .slice(0, 3) - .map((seg) => ({ - key: seg.key, - label: seg.label, - pctText: formatCompactSourceSharePct(seg.pct), - color: seg.color, - })); - patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0); - patchKeyedList(refs.topModelsEl, topModels, { - keyFn: (m) => m.key, - sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, - createRow: createSourceTopModelItem, - updateRow: (mRefs, m) => { - patchStyleVar(mRefs.dotEl, '--dot-color', m.color); - patchText(mRefs.nameEl, m.label); - patchText(mRefs.pctEl, m.pctText); - patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); - }, - }); - - refs.rowState.hoverPayload = - total > 0 || callsCount > 0 - ? { - title: displayLabel, - calls: callsCount, - totalTokens: total, - costText, - inputTokens: item.inputTokens, - cacheReadTokens: item.cacheReadTokens, - thinkingTokens: item.thinkingTokens, - responseTokens: item.responseTokens, - outputTokens: item.outputTokens, - segments: partitioned, - } - : null; - patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); - } - - function createTopConversationRow() { - const titleTextEl = h('span', { className: 'cons-row-title-text' }); - const wsBadgeEl = h('span', { className: 'cons-ws-sessions-tag text-mono', hidden: true }); - const titleEl = h('strong', { className: 'cons-row-title cons-top-conv-title' }, [ - titleTextEl, - wsBadgeEl, - ]); - const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); - const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); - const costEl = h('strong', { className: 'cons-row-cost text-mono' }); - const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); - const rowState = { cascadeId: '', canJump: false, hoverPayload: null }; - - const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - - const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true }); - const callsLbl = h('span', { text: t('cons.footCalls') }); - const callsVal = h('strong', { className: 'text-mono' }); - - const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - fallbackMetaEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), - ]); - attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); - - const rowEl = h( - 'div', - { - className: 'cons-top-conv-row', - onClick: () => { - if (!rowState.canJump || !rowState.cascadeId) return; - hideBreakdownPopover(); - selectConversation(rowState.cascadeId); - uiStore.setState({ - activeView: 'steps', - stepsSubTab: 'steps', - selectedAgentScope: 'all', - ctxInspectorAgentId: getDefaultCtxInspectorAgentId( - telemetryStore.getState().telemetry?.settings - ), - }); - }, - }, - [ - h('div', { className: 'panel-header' }, [ - titleEl, - h('span', { className: 'cons-row-metrics' }, [ - pctBadge, - totalTokEl, - costEl, - ]), - ]), - hoverZoneEl, - ] - ); - - return { - el: rowEl, - refs: { - rowEl, - titleEl, - titleTextEl, - wsBadgeEl, - pctBadge, - totalTokEl, - costEl, - hoverZoneEl, - barHitEl, - trackEl, - topModelsEl, - fallbackMetaEl, - callsLbl, - callsVal, - rowState, - }, - }; - } - - function updateTopConversationRow(refs, item, bases, modelColorMap, sortMode = 'cost') { - patchText(refs.callsLbl, t('cons.footCalls')); - const isWorkspaceRow = Boolean(item.isWorkspaceRow); - const title = isWorkspaceRow - ? item.isUnbound - ? t('cons.workspaceUnbound') - : String(item.label || item.workspacePath || '—').trim() - : String(item.title || item.cascadeId || '—').trim(); - refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || ''); - refs.rowState.canJump = - !isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId); - patchClasses(refs.rowEl, { - 'is-jumpable': refs.rowState.canJump, - 'cons-workspace-row': isWorkspaceRow, - }); - const baseTip = - isWorkspaceRow && item.workspacePath && item.workspacePath !== title - ? `${title} (${item.workspacePath})` - : title; - patchAttr( - refs.rowEl, - 'title', - refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip - ); - patchText(refs.titleTextEl, title); - if (refs.wsBadgeEl) { - const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0; - patchAttr(refs.wsBadgeEl, 'hidden', !showWsBadge); - if (showWsBadge) { - patchText(refs.wsBadgeEl, t('cons.workspaceSessions', { count: item.sessionCount })); - } - } - - const total = Number(item.totalTokens || 0); - const costVal = Number(item.costUsd || 0); - const callsCount = Number(item.calls || 0); - const isAllUnpriced = - callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); - const costText = formatUsd(isAllUnpriced ? null : costVal, { - precise: costVal > 0 && costVal < 0.1, - }); - - const tokBase = Number(bases?.tokens || 0); - const costBase = Number(bases?.cost || 0); - const useCostBasis = sortMode === 'cost' && costBase > 0; - const share = useCostBasis - ? +((costVal / costBase) * 100).toFixed(1) - : tokBase > 0 - ? +((total / tokBase) * 100).toFixed(1) - : 0; - const scaleRatio = useCostBasis - ? costVal > 0 - ? Math.min(1, Math.max(0.01, costVal / costBase)) - : 0 - : tokBase > 0 && total > 0 - ? Math.min(1, Math.max(0.01, total / tokBase)) - : 0; - - patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); - if (sortMode === 'tokens') { - patchText(refs.totalTokEl, costText); - patchText(refs.costEl, formatTokensPrecise(total)); - } else { - patchText(refs.totalTokEl, formatTokensPrecise(total)); - patchText(refs.costEl, costText); - } - patchText(refs.callsVal, String(callsCount)); - - // 复用客户端来源同款按模型配色分段进度条、Top 2-3 模型速览及共享悬浮详情浮层 - const convModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; - const partitioned = partitionModelSegments(convModels, modelColorMap, { - maxMain: 5, - minSharePct: 1.5, - }); - const barItems = - partitioned.length > 0 - ? partitioned.map((seg) => ({ - key: seg.key, - segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, - color: seg.color, - })) - : scaleRatio > 0 - ? [ - { - key: '__conv_fallback__', - segPct: scaleRatio * 100, - color: 'var(--accent-primary)', - }, - ] - : []; - - patchKeyedList(refs.trackEl, barItems, { - keyFn: (seg) => seg.key, - sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, - createRow: createSourceModelSegment, - updateRow: (segRefs, seg) => { - patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); - patchStyleVar(segRefs.segEl, '--seg-color', seg.color); - }, - }); - - const topModels = partitioned - .filter((seg) => !seg.isOther) - .slice(0, 3) - .map((seg) => ({ - key: seg.key, - label: seg.label, - pctText: formatCompactSourceSharePct(seg.pct), - color: seg.color, - })); - patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0); - patchKeyedList(refs.topModelsEl, topModels, { - keyFn: (m) => m.key, - sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, - createRow: createSourceTopModelItem, - updateRow: (mRefs, m) => { - patchStyleVar(mRefs.dotEl, '--dot-color', m.color); - patchText(mRefs.nameEl, m.label); - patchText(mRefs.pctEl, m.pctText); - patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); - }, - }); - - const showFallbackMeta = topModels.length === 0; - patchAttr(refs.fallbackMetaEl, 'hidden', !showFallbackMeta); - if (showFallbackMeta) { - const srcLabel = item.sourceName || item.appSource || ''; - const cacheLabel = t('cons.topConvCacheMeta', { - pct: formatPctNumber(item.cacheHitPct ?? 0), - }); - patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel); - } - - refs.rowState.hoverPayload = - partitioned.length > 0 && (total > 0 || callsCount > 0) - ? { - title, - calls: callsCount, - totalTokens: total, - costText, - inputTokens: item.inputTokens, - cacheReadTokens: item.cacheReadTokens, - thinkingTokens: item.thinkingTokens, - responseTokens: item.responseTokens, - outputTokens: item.outputTokens, - segments: partitioned, - } - : null; - patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); - } + }, + }); let latestSlice = null; let isDirty = false; @@ -36966,6 +36955,30 @@ const ConsumptionView = defineComponent({ patchAttr(topConvsEmptyEl, 'hidden', !showSessionsTab || sortedTopConvs.length > 0); patchText(topConvsEmptyEl, t('cons.topConvsEmpty')); + const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRankingKey = showWorkspacesTab + ? 'workspaces' + : showSessionsTab + ? 'sessions' + : 'models'; + const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`; + const activeRankingEl = showWorkspacesTab + ? workspacesListEl + : showSessionsTab + ? sortedTopConvs.length > 0 + ? topConvsListEl + : topConvsEmptyEl + : modelsListEl; + + const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig; + const tabSwitched = + hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey; + const sortSwitched = + hasCompletedInitialDraw && + !rangeSwitched && + !tabSwitched && + nextSortSig !== lastAnimatedSortSig; + patchKeyedList(modelsListEl, models, { keyFn: (m) => m.displayText || m.label || m.shortName, sigFn: (m) => @@ -37047,30 +37060,6 @@ const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; - const nextRankingKey = showWorkspacesTab - ? 'workspaces' - : showSessionsTab - ? 'sessions' - : 'models'; - const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`; - const activeRankingEl = showWorkspacesTab - ? workspacesListEl - : showSessionsTab - ? sortedTopConvs.length > 0 - ? topConvsListEl - : topConvsEmptyEl - : modelsListEl; - - const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig; - const tabSwitched = - hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey; - const sortSwitched = - hasCompletedInitialDraw && - !rangeSwitched && - !tabSwitched && - nextSortSig !== lastAnimatedSortSig; - if (tabSwitched || sortSwitched) { triggerConsAnim(activeRankingEl, 'is-bars-revealing'); } @@ -39697,25 +39686,17 @@ const App = defineComponent({ return { App }; })(); -// --- src/components/layout/WindowOverlayShell.js --- -const { computeCapsuleLayoutMode, mountWindowOverlay } = (() => { +// --- src/components/layout/overlayHostAnchors.js --- +const { CAPSULE_HOST_ID, PORTAL_HOST_ID, computeCapsuleLayoutMode, isImmediatelyBeforeNode, isIdeExtensionChatFrame, resolveActiveDockTarget, findNativeTopRightAnchor, getLeftSidebarRightEdge, attachShadowStyles } = (() => { /** - * @fileoverview 主窗口双栖挂载外壳 (WindowOverlayShell.js). - * - * 采用「分离式双 Shadow Host」架构,彻底规避宿主顶栏层叠上下文 (`z-0` / `overflow: hidden`) 裁切与路由重绘卸载问题: - * 1. `#ag-usage-monitor-capsule`:轻量顶栏胶囊,优先内嵌停靠至 `[class*="@container/titlebar"]` 右侧按钮组, - * 支持四级迟滞宽度自适应折叠(`wide` -> `compact` -> `minimal` -> `ring-only`),找不到顶栏时自动回退至右上角固定定位; - * 2. `#ag-usage-monitor-portal`:常驻 `document.body` 顶层的无遮挡浮层宿主,承载悬停速览卡与完整四标签 `App()` 监控面板, - * 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。 + * @fileoverview Host IDE/Desktop titlebar & composer button anchor discovery, + * 4-stage responsive capsule hysteresis, and shared ShadowRoot CSSStyleSheet mounting + * extracted from WindowOverlayShell.js. */ const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule'; const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; -const FLOATING_CARD_WIDTH = 522; -const POPOVER_BASE_WIDTH = 540; -const POPOVER_MAX_AUTO_WIDTH = 960; -const MULTI_PANEL_WIDTH = 464; /** * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 @@ -40290,7 +40271,7 @@ function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patch const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null; const activeRouteId = extractHostRouteCascadeId(); - // 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏与 Auto / 右簇发送按钮 + // 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏和 Auto / 右簇发送按钮 const rawEditors = querySimpleSelectorList(document, [ 'textarea', '[contenteditable]', @@ -40574,7 +40555,7 @@ function getLeftSidebarRightEdge(vw) { } /** - * 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 + * 在主窗口挂载双栖顶栏胶囊和完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 */ const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([ 'src/styles/views-overview.css', @@ -40620,6 +40601,29 @@ function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) { styleEl.textContent = slimCapsule ? buildSlimCapsuleCss(fullCss) : fullCss; shadowRoot.appendChild(styleEl); } +return { CAPSULE_HOST_ID, PORTAL_HOST_ID, computeCapsuleLayoutMode, isImmediatelyBeforeNode, isIdeExtensionChatFrame, resolveActiveDockTarget, findNativeTopRightAnchor, getLeftSidebarRightEdge, attachShadowStyles }; +})(); + +// --- src/components/layout/WindowOverlayShell.js --- +const { mountWindowOverlay } = (() => { +/** + * @fileoverview 主窗口双栖挂载外壳 (WindowOverlayShell.js). + * + * 采用「分离式双 Shadow Host」架构,彻底规避宿主顶栏层叠上下文 (`z-0` / `overflow: hidden`) 裁切与路由重绘卸载问题: + * 1. `#ag-usage-monitor-capsule`:轻量顶栏胶囊,优先内嵌停靠至 `[class*="@container/titlebar"]` 右侧按钮组, + * 支持四级迟滞宽度自适应折叠(`wide` -> `compact` -> `minimal` -> `ring-only`),找不到顶栏时自动回退至右上角固定定位; + * 2. `#ag-usage-monitor-portal`:常驻 `document.body` 顶层的无遮挡浮层宿主,承载悬停速览卡与完整四标签 `App()` 监控面板, + * 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。 + */ + + + + +const FLOATING_CARD_WIDTH = 522; +const POPOVER_BASE_WIDTH = 540; +const POPOVER_MAX_AUTO_WIDTH = 960; +const MULTI_PANEL_WIDTH = 464; + function mountWindowOverlay() { if (typeof window === 'undefined' || typeof document === 'undefined') return null; @@ -42675,7 +42679,7 @@ function mountWindowOverlay() { window[WINDOW_OVERLAY_KEY] = handle; return handle; } -return { computeCapsuleLayoutMode, mountWindowOverlay }; +return { mountWindowOverlay }; })(); // --- src/main.js --- diff --git a/sidecars/panel/backend/file-exporter.mjs b/sidecars/panel/backend/file-exporter.mjs index 5ead6ea..4fcec67 100644 --- a/sidecars/panel/backend/file-exporter.mjs +++ b/sidecars/panel/backend/file-exporter.mjs @@ -1,7 +1,7 @@ /** - * @fileoverview 本机安全文本文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。 - * 仅允许导出受控白名单文本扩展名(.json / .csv / .md / .txt),严格清洗文件名防止路径穿越, - * 并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。 + * @fileoverview 本机安全文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。 + * 仅允许导出受控白名单扩展名(.json / .csv / .md / .txt / .xlsx,含 UTF-8 文本和 Base64 二进制工作簿), + * 严格清洗文件名防止路径穿越,并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。 */ import { spawn } from 'node:child_process'; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 676c489..817c021 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@