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 @@ 用量监控 - +
- + diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index b8fea9d..56bbd33 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -636,6 +636,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/registries/stepColumnRegistry.js', 'src/components/widgets/CapsuleBarWidget.js', 'src/components/widgets/StepTableWidget.js', + 'src/components/widgets/ConsumptionBreakdownRows.js', 'src/components/settings/structurePreviewMock.js', 'src/components/settings/CollapsibleSection.js', 'src/components/settings/EditableSlotList.js', @@ -652,6 +653,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/views/StepsDetailView.js', 'src/views/SettingsView.js', 'src/App.js', + 'src/components/layout/overlayHostAnchors.js', 'src/components/layout/WindowOverlayShell.js', 'src/main.js', ]; diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 7d3230c..3404d0e 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -66,916 +66,25 @@ import { } from '../../store/telemetryStore.js'; import { uiStore } from '../../store/uiStore.js'; -const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule'; -const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; +import { + CAPSULE_HOST_ID, + PORTAL_HOST_ID, + attachShadowStyles, + computeCapsuleLayoutMode, + findNativeTopRightAnchor, + getLeftSidebarRightEdge, + isIdeExtensionChatFrame, + isImmediatelyBeforeNode, + resolveActiveDockTarget, +} from './overlayHostAnchors.js'; + +export { computeCapsuleLayoutMode }; + const FLOATING_CARD_WIDTH = 522; const POPOVER_BASE_WIDTH = 540; const POPOVER_MAX_AUTO_WIDTH = 960; const MULTI_PANEL_WIDTH = 464; -/** - * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 - * 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊; - * 当槽位数超过 3 个(4..5 槽)时自动按槽位增量上浮 `wide` 阈值。 - * - * @param {number} availWidth - * @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode - * @param {{ showMulti?: boolean, hasUpdate?: boolean, slotCount?: number }} [options] - * @returns {'wide'|'compact'|'minimal'|'ring-only'} - */ -export function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) { - if (availWidth == null || Number.isNaN(availWidth)) return 'wide'; - const showMulti = options?.showMulti !== false; - const updateReserve = options?.hasUpdate ? 52 : 0; - const slotCount = Number(options?.slotCount || 3); - const extraSlotWidth = slotCount > 3 ? (slotCount - 3) * 58 : 0; - const wideKeep = 256 + extraSlotWidth; - const wideEnter = 272 + extraSlotWidth; - const baseEffWidth = showMulti ? availWidth : availWidth + 76; - const effWidth = baseEffWidth - updateReserve; - if (currentMode === 'wide') { - if (baseEffWidth < 78) return 'ring-only'; - if (effWidth < 196) return 'minimal'; - if (effWidth < wideKeep) return 'compact'; - return 'wide'; - } - if (currentMode === 'compact') { - if (effWidth >= wideEnter) return 'wide'; - if (baseEffWidth < 78) return 'ring-only'; - if (effWidth < 196) return 'minimal'; - return 'compact'; - } - if (currentMode === 'minimal') { - if (effWidth >= wideEnter) return 'wide'; - if (effWidth >= 212) return 'compact'; - if (baseEffWidth < 78) return 'ring-only'; - return 'minimal'; - } - if (effWidth >= wideEnter) return 'wide'; - if (effWidth >= 212) return 'compact'; - if (baseEffWidth >= 92) return 'minimal'; - return 'ring-only'; -} - -function findIdeWorkbenchTitlebar() { - try { - if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { - return null; - } - const workbench = document.querySelector('.monaco-workbench'); - if (!workbench?.querySelector) return null; - const partTitlebar = workbench.querySelector('.part.titlebar'); - if (!partTitlebar?.querySelector) return null; - if (partTitlebar.getBoundingClientRect) { - const pr = partTitlebar.getBoundingClientRect(); - if (pr.width <= 0 || pr.height <= 0) return null; - } - const container = - partTitlebar.querySelector(':scope > .titlebar-container') || - partTitlebar.querySelector('.titlebar-container'); - const rightGroup = - container?.querySelector?.(':scope > .titlebar-right') || - container?.querySelector?.('.titlebar-right'); - if (!container || !rightGroup) return null; - const actionToolbar = - rightGroup.querySelector?.(':scope > .action-toolbar-container') || - rightGroup.querySelector?.('.action-toolbar-container') || - null; - return { - kind: 'ide-titlebar', - workbench, - titlebar: container, - targetContainer: rightGroup, - actionToolbar, - }; - } catch { - return null; - } -} - -function findHostTitlebar() { - try { - if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { - return null; - } - const tb = document.querySelector('[class*="@container/titlebar"]'); - if (tb?.getBoundingClientRect) { - const r = tb.getBoundingClientRect(); - if (r.width <= 0 || r.height <= 0) return null; - } - return tb; - } catch { - return null; - } -} - -const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR = - '.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]'; -const COMPOSER_MODEL_LABEL_RE = - /\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; -const COMPOSER_MODEL_ATTR_RE = - /\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i; -const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i; -const COMPOSER_MODE_TEXT_RE = - /^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|act|review|confirm|normal|fast|自动|询问|手动|始终允许|受控|规划)(?:\s*(?:mode|模式))?$/i; -const COMPOSER_MODE_ATTR_RE = - /\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i; -const COMPOSER_ICON_FONT_CLASS_RE = - /\b(?:codicon|material-symbols(?:-\w+)?|material-icons(?:-\w+)?|lucide(?:-\w+)?)\b/i; - -function querySimpleSelectorList(root, selectors) { - if (!root || typeof root.querySelectorAll !== 'function') return []; - const seen = new Set(); - const out = []; - for (const sel of selectors) { - let list = []; - try { - list = root.querySelectorAll(sel) || []; - } catch { - list = []; - } - for (const item of list) { - if (item && !seen.has(item)) { - seen.add(item); - out.push(item); - } - } - } - return out; -} - -function extractVisibleButtonText(node, isRoot = true) { - if (!node) return ''; - const tag = String(node.tagName || node.nodeName || '').toLowerCase(); - if (tag === 'svg' || tag === 'style' || tag === 'script') return ''; - if (!isRoot) { - if (node.getAttribute?.('aria-hidden') === 'true') return ''; - const cls = String(node.className || ''); - if (cls && COMPOSER_ICON_FONT_CLASS_RE.test(cls)) return ''; - } - if (tag === '#text' || node.nodeType === 3) { - return String(node.nodeValue ?? node.textContent ?? ''); - } - const childNodes = node.childNodes || node.children; - if (!childNodes || childNodes.length === 0) { - return String(node.textContent || ''); - } - let acc = ''; - for (const ch of childNodes) { - acc += ` ${extractVisibleButtonText(ch, false)}`; - } - return acc; -} - -function cleanComposerButtonText(btn) { - const raw = extractVisibleButtonText(btn, true) - .replace(/[\u200B-\u200D\uFEFF]/g, '') - .replace(/\s+/g, ' ') - .trim(); - if (!raw) return ''; - return raw.replace(/^[⌃⌄▾▴∨∧^<>›‹+\s]+|[⌃⌄▾▴∨∧^<>›‹\s]+$/g, '').trim(); -} - -function isComposerModelButtonItem(item) { - if (!item) return false; - if (item.cleanText && COMPOSER_MODEL_LABEL_RE.test(item.cleanText)) return true; - if (item.attrText && COMPOSER_MODEL_ATTR_RE.test(item.attrText)) return true; - return false; -} - -function hasExcludedComposerAncestor(el) { - if (!el) return false; - if (typeof el.closest === 'function') { - try { - if (el.closest(COMPOSER_EXCLUDED_ANCESTOR_SELECTOR)) return true; - } catch { - // 忽略选择器异常并回退祖先链遍历 - } - } - let cur = el.parentElement || el.parentNode; - while (cur) { - const cls = String(cur.className || ''); - if ( - cls.includes('@container/titlebar') || - cls.includes('quick-input-widget') || - cls.includes('suggest-widget') || - cls.includes('find-widget') || - cls.includes('scm-editor') || - cls.includes('search-view') || - (cls.includes('part') && (cls.includes('titlebar') || cls.includes('statusbar'))) - ) { - return true; - } - cur = cur.parentElement || cur.parentNode; - } - return false; -} - -function isNodeHiddenByStyle(el) { - if (!el) return true; - if (el.hasAttribute?.('hidden') || el.getAttribute?.('aria-hidden') === 'true') return true; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const cs = window.getComputedStyle(el); - if (cs?.display === 'none' || cs?.visibility === 'hidden') return true; - } catch { - // 忽略样式读取异常 - } - } - return false; -} - -function getInFlowHostChildren(container, capsuleNode, portalNode) { - const rawChildren = container?.children || []; - const out = []; - for (const ch of rawChildren) { - if (!ch || ch === capsuleNode || ch === portalNode) continue; - if (ch.id === CAPSULE_HOST_ID || ch.id === PORTAL_HOST_ID) continue; - if (ch.hasAttribute?.('hidden')) continue; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const cs = window.getComputedStyle(ch); - if (cs?.display === 'none') continue; - if (cs?.position === 'absolute' || cs?.position === 'fixed') continue; - } catch { - // 忽略计算样式异常 - } - } - out.push(ch); - } - return out; -} - -function isHorizontalFlexContainer(el) { - if (!el) return false; - const cls = String(el.className || ''); - if (/\b(?:inline-)?flex\b/.test(cls) && !/\bflex-col\b/.test(cls)) return true; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const cs = window.getComputedStyle(el); - const disp = String(cs?.display || ''); - const dir = String(cs?.flexDirection || 'row'); - if (disp.includes('flex') && !dir.startsWith('column')) return true; - } catch { - // 忽略计算样式异常 - } - } - return false; -} - -function isSpaceDistributedFlexContainer(el) { - if (!el) return false; - const cls = String(el.className || ''); - if (/\bjustify-(?:between|around|evenly)\b/.test(cls)) return true; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const jc = String(window.getComputedStyle(el)?.justifyContent || ''); - if (jc.includes('space-between') || jc.includes('space-around') || jc.includes('space-evenly')) { - return true; - } - } catch { - // 忽略计算样式异常 - } - } - return false; -} - -function buildComposerDockDescriptor(autoBtn, composerCard, bottomRowBtns, capsuleNode, portalNode, patchedNode) { - if (!autoBtn || !composerCard) return null; - let item = autoBtn; - while ( - (item.parentElement || item.parentNode) && - (item.parentElement || item.parentNode) !== composerCard && - (item.parentElement || item.parentNode) !== document.body - ) { - const parent = item.parentElement || item.parentNode; - const hostSiblings = getInFlowHostChildren(parent, capsuleNode, portalNode); - if (hostSiblings.length >= 2) break; - const grandParent = parent.parentElement || parent.parentNode; - const parentCls = String(parent.className || ''); - const parentInlineMl = String(parent.style?.marginLeft || '').trim(); - const isSingleClusterInSplitRow = - !/\b(?:relative|ml-auto|ms-auto)\b/.test(parentCls) && - parentInlineMl !== 'auto' && - isHorizontalFlexContainer(parent) && - grandParent && - isSpaceDistributedFlexContainer(grandParent) && - getInFlowHostChildren(grandParent, capsuleNode, portalNode).length >= 2; - if (isSingleClusterInSplitRow) { - break; - } - item = parent; - } - - const anchorNode = item; - const targetContainer = anchorNode.parentElement || anchorNode.parentNode; - if (!targetContainer) return null; - - const hostChildren = getInFlowHostChildren(targetContainer, capsuleNode, portalNode); - const anchorIdx = hostChildren.indexOf(anchorNode); - const isFirstHostChild = anchorIdx <= 0; - - let needsAutoMarginTransfer = false; - let patchMarginNode = null; - - if (!isFirstHostChild) { - const cls = String(anchorNode.className || ''); - const inlineMl = String(anchorNode.style?.marginLeft || '').trim(); - let computedLargeMl = false; - if ( - patchedNode !== anchorNode && - typeof window !== 'undefined' && - typeof window.getComputedStyle === 'function' - ) { - try { - const mlPx = parseFloat(window.getComputedStyle(anchorNode)?.marginLeft) || 0; - const prevSib = hostChildren[anchorIdx - 1]; - const aRect = anchorNode.getBoundingClientRect?.(); - const pRect = prevSib?.getBoundingClientRect?.(); - if (mlPx > 24 && aRect && pRect && aRect.left - pRect.right >= mlPx - 6) { - computedLargeMl = true; - } - } catch { - // 忽略边距测量异常 - } - } - - if ( - /\b(?:ml-auto|ms-auto)\b/.test(cls) || - inlineMl === 'auto' || - patchedNode === anchorNode || - computedLargeMl - ) { - needsAutoMarginTransfer = true; - patchMarginNode = anchorNode; - } else if (isSpaceDistributedFlexContainer(targetContainer)) { - needsAutoMarginTransfer = true; - } - } - - const autoRect = anchorNode.getBoundingClientRect?.() || autoBtn.getBoundingClientRect?.(); - let leftClusterRightEdge = 0; - if (autoRect && Array.isArray(bottomRowBtns)) { - for (const entry of bottomRowBtns) { - if (entry.btn === autoBtn || anchorNode.contains?.(entry.btn)) continue; - if (entry.rect.left < autoRect.left - 2 && entry.rect.right <= autoRect.left + 4) { - if (entry.rect.right > leftClusterRightEdge) { - leftClusterRightEdge = entry.rect.right; - } - } - } - } - - return { - kind: 'composer', - workbench: null, - titlebar: composerCard, - targetContainer, - actionToolbar: patchMarginNode, - anchorNode, - needsAutoMarginTransfer, - leftClusterRightEdge, - }; -} - -function buildComposerRightEndDockDescriptor( - leftAnchorBtn, - composerCard, - bottomRowBtns, - capsuleNode, - portalNode -) { - if (!leftAnchorBtn || !composerCard) return null; - const cardRect = composerCard.getBoundingClientRect?.(); - const minRowWidth = cardRect && cardRect.width > 0 ? cardRect.width * 0.65 : 180; - let toolbarRow = null; - let cur = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode; - for (let d = 0; d < 8 && cur && cur !== composerCard && cur !== document.body; d += 1) { - const r = cur.getBoundingClientRect?.(); - if (r && r.width >= minRowWidth && r.height > 0 && r.height <= 60 && isHorizontalFlexContainer(cur)) { - toolbarRow = cur; - break; - } - cur = cur.parentElement || cur.parentNode; - } - if (!toolbarRow) { - const p = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode; - if (!p || !isHorizontalFlexContainer(p)) return null; - toolbarRow = p; - } - - let leftClusterRightEdge = 0; - if (Array.isArray(bottomRowBtns)) { - for (const entry of bottomRowBtns) { - if (entry?.rect?.right > leftClusterRightEdge) { - leftClusterRightEdge = entry.rect.right; - } - } - } - - const rowChildren = getInFlowHostChildren(toolbarRow, capsuleNode, portalNode); - const lastChild = rowChildren.length >= 2 ? rowChildren[rowChildren.length - 1] : null; - if ( - lastChild && - !lastChild.contains?.(leftAnchorBtn) && - isHorizontalFlexContainer(lastChild) && - getInFlowHostChildren(lastChild, capsuleNode, portalNode).length === 0 - ) { - return { - kind: 'composer', - workbench: null, - titlebar: composerCard, - targetContainer: lastChild, - actionToolbar: null, - anchorNode: null, - needsAutoMarginTransfer: false, - leftClusterRightEdge, - }; - } - - return { - kind: 'composer', - workbench: null, - titlebar: composerCard, - targetContainer: toolbarRow, - actionToolbar: null, - anchorNode: null, - needsAutoMarginTransfer: true, - leftClusterRightEdge, - }; -} - -function collectComposerBottomButtons(container, editorEl, editorRect, capsuleNode, portalNode) { - const rawBtns = querySimpleSelectorList(container, ['button', '[role="button"]', '[aria-haspopup]']); - const hostBtns = []; - for (const btn of rawBtns) { - if (!btn || btn === editorEl || editorEl?.contains?.(btn)) continue; - if (editorEl && btn.contains?.(editorEl)) continue; - if ( - btn.id === CAPSULE_HOST_ID || - btn.id === PORTAL_HOST_ID || - capsuleNode?.contains?.(btn) || - portalNode?.contains?.(btn) - ) { - continue; - } - if (isNodeHiddenByStyle(btn)) continue; - // 仅排除嵌套在真实紧凑按钮内部的图标/子触发器,避免外层卡片级 role="button" 误杀工具栏按钮 - let nestedInBtn = false; - let p = btn.parentElement || btn.parentNode; - while (p && p !== container) { - const pTag = String(p.tagName || '').toLowerCase(); - if (pTag === 'button') { - nestedInBtn = true; - break; - } - if ( - (p.getAttribute?.('role') === 'button' || p.hasAttribute?.('aria-haspopup')) && - !(editorEl && p.contains?.(editorEl)) - ) { - const pr = p.getBoundingClientRect?.(); - if (pr && pr.height > 0 && pr.height <= 48 && pr.width > 0 && pr.width <= 360) { - nestedInBtn = true; - break; - } - } - p = p.parentElement || p.parentNode; - } - if (nestedInBtn) continue; - - const br = btn.getBoundingClientRect?.(); - if (!br || br.width <= 0 || br.height <= 0 || br.height > 48) continue; - const centerY = (br.top + br.bottom) / 2; - if (editorRect && centerY < editorRect.top - 4) continue; - hostBtns.push({ - btn, - rect: br, - centerY, - centerX: (br.left + br.right) / 2, - cleanText: cleanComposerButtonText(btn), - attrText: `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(), - }); - } - if (hostBtns.length === 0) return []; - let maxCenterY = -Infinity; - for (const item of hostBtns) { - if (item.centerY > maxCenterY) maxCenterY = item.centerY; - } - const bottomBand = hostBtns.filter((item) => Math.abs(item.centerY - maxCenterY) <= 22); - bottomBand.sort((a, b) => a.rect.left - b.rect.left); - return bottomBand; -} - -function pickAutoButtonFromRow(bottomRowBtns, containerRect, options = undefined) { - if (!Array.isArray(bottomRowBtns) || bottomRowBtns.length === 0) return null; - const requireModelForFallback = Boolean(options?.requireModelForFallback); - const rightSplitX = containerRect ? containerRect.left + containerRect.width * 0.35 : 0; - const rightFirst = [ - ...bottomRowBtns.filter((b) => b.centerX >= rightSplitX), - ...bottomRowBtns.filter((b) => b.centerX < rightSplitX), - ]; - - // Tier 1: 精确文本 Auto / 自动 匹配 - for (const item of rightFirst) { - if (COMPOSER_MODE_EXACT_RE.test(item.cleanText)) { - return { btn: item.btn, tier: 1 }; - } - } - - // Tier 2: 执行/权限模式文案或无障碍语义属性匹配(排除模型选择器按钮) - for (const item of rightFirst) { - if (isComposerModelButtonItem(item)) continue; - if ( - (item.cleanText && COMPOSER_MODE_TEXT_RE.test(item.cleanText)) || - (item.attrText && COMPOSER_MODE_ATTR_RE.test(item.attrText)) - ) { - return { btn: item.btn, tier: 2 }; - } - } - - const hasModelBtn = bottomRowBtns.some(isComposerModelButtonItem); - - // Tier 3: 几何右簇首按钮兜底(适配 Antigravity IDE 无 Auto 按钮、右侧为发送/语音按钮的输入栏布局) - if (bottomRowBtns.length >= 2 && (!requireModelForFallback || hasModelBtn)) { - let maxGap = -Infinity; - let splitIdx = -1; - for (let i = 1; i < bottomRowBtns.length; i += 1) { - const gap = bottomRowBtns[i].rect.left - bottomRowBtns[i - 1].rect.right; - if (gap > maxGap) { - maxGap = gap; - splitIdx = i; - } - } - if (splitIdx >= 1 && maxGap >= 16) { - return { btn: bottomRowBtns[splitIdx].btn, tier: 3 }; - } - } - - // Tier 4: 输入为空时若右侧发送按钮暂时隐藏、仅左侧存在模型选择器按钮,停靠至工具栏最右侧 - if (hasModelBtn && containerRect && containerRect.width >= 200) { - const lastItem = bottomRowBtns[bottomRowBtns.length - 1]; - if (lastItem.rect.right <= containerRect.left + containerRect.width * 0.72) { - return { btn: null, leftAnchorBtn: lastItem.btn, tier: 4 }; - } - } - - return null; -} - -function resolveComposerEditorRect(ed) { - const er = ed?.getBoundingClientRect?.(); - if (er && er.width >= 80 && er.height >= 12) return er; - let cur = ed; - for (let d = 0; d < 6 && cur; d += 1) { - if (String(cur.className || '').includes('monaco-editor')) { - const mr = cur.getBoundingClientRect?.(); - if (mr && mr.width >= 80 && mr.height >= 12) return mr; - break; - } - cur = cur.parentElement || cur.parentNode; - } - return er || null; -} - -function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patchedNode = null) { - try { - if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') { - return null; - } - const capEl = capsuleNode || document.getElementById?.(CAPSULE_HOST_ID) || null; - const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null; - const activeRouteId = extractHostRouteCascadeId(); - - // 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏与 Auto / 右簇发送按钮 - const rawEditors = querySimpleSelectorList(document, [ - 'textarea', - '[contenteditable]', - '[role="textbox"]', - '[data-lexical-editor]', - '.ProseMirror', - '.monaco-editor', - ]); - const scoredEditors = []; - for (const ed of rawEditors) { - if (!ed || capEl?.contains?.(ed) || porEl?.contains?.(ed)) continue; - if (ed.hasAttribute?.('contenteditable')) { - const ce = String(ed.getAttribute('contenteditable') || '').trim().toLowerCase(); - if (ce === 'false' && ed.getAttribute?.('role') !== 'textbox') continue; - } - if (isNodeHiddenByStyle(ed) || hasExcludedComposerAncestor(ed)) continue; - const er = resolveComposerEditorRect(ed); - if (!er || er.width < 100 || er.height < 12 || er.height > 540) continue; - - let score = Math.min(1200, er.width) + Math.max(0, er.bottom) * 0.2; - if (activeRouteId) { - let anc = ed.parentElement || ed.parentNode; - while (anc) { - const cid = anc.getAttribute?.('data-cascade-id'); - if (cid) { - score += cid === activeRouteId ? 4000 : -2000; - break; - } - anc = anc.parentElement || anc.parentNode; - } - } - if ( - document.activeElement && - (ed === document.activeElement || ed.contains?.(document.activeElement)) - ) { - score += 1000; - } - scoredEditors.push({ ed, rect: er, score }); - } - scoredEditors.sort((a, b) => b.score - a.score); - - for (const { ed, rect: er } of scoredEditors) { - const isMonacoCandidate = String(ed.className || '').includes('monaco-editor') || - String(ed.className || '').includes('inputarea'); - let tier3Candidate = null; - let tier4Candidate = null; - let cur = ed.parentElement || ed.parentNode; - for (let depth = 0; depth < 18 && cur; depth += 1) { - if (cur === document.body || cur === document.documentElement) break; - const tag = String(cur.tagName || '').toLowerCase(); - if (tag === 'main' || String(cur.className || '').includes('monaco-workbench')) break; - const cr = cur.getBoundingClientRect?.(); - if (cr && cr.height > 680) break; - if (cr && cr.width >= 180 && cr.height > 0) { - const bottomRowBtns = collectComposerBottomButtons(cur, ed, er, capEl, porEl); - const picked = pickAutoButtonFromRow(bottomRowBtns, cr, { - requireModelForFallback: isMonacoCandidate, - }); - if (picked) { - if (picked.tier <= 2) { - const desc = buildComposerDockDescriptor( - picked.btn, - cur, - bottomRowBtns, - capEl, - porEl, - patchedNode - ); - if (desc) return desc; - } else if (picked.tier === 3 && !tier3Candidate) { - tier3Candidate = { btn: picked.btn, card: cur, bottomRowBtns }; - } else if (picked.tier === 4 && !tier4Candidate) { - tier4Candidate = { leftAnchorBtn: picked.leftAnchorBtn, card: cur, bottomRowBtns }; - } - } - } - cur = cur.parentElement || cur.parentNode; - } - if (tier3Candidate) { - const desc = buildComposerDockDescriptor( - tier3Candidate.btn, - tier3Candidate.card, - tier3Candidate.bottomRowBtns, - capEl, - porEl, - patchedNode - ); - if (desc) return desc; - } - if (tier4Candidate) { - const desc = buildComposerRightEndDockDescriptor( - tier4Candidate.leftAnchorBtn, - tier4Candidate.card, - tier4Candidate.bottomRowBtns, - capEl, - porEl - ); - if (desc) return desc; - } - } - - // 2. 兜底路径:编辑器自定义封装或暂时只读时,直接扫描底部包含模型选择器或 Auto 按钮的输入工具栏 - const vh = Number(window.innerHeight || 800); - const allBtns = querySimpleSelectorList(document, ['button', '[role="button"]', '[aria-haspopup]']); - let modelToolbarFallback = null; - for (const btn of allBtns) { - if (!btn || capEl?.contains?.(btn) || porEl?.contains?.(btn)) continue; - if (isNodeHiddenByStyle(btn) || hasExcludedComposerAncestor(btn)) continue; - const br = btn.getBoundingClientRect?.(); - if (!br || br.width <= 0 || br.height <= 0 || br.height > 48 || br.top < vh * 0.2) continue; - const clean = cleanComposerButtonText(btn); - const attr = `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(); - const itemProbe = { cleanText: clean, attrText: attr }; - const isModeBtn = - COMPOSER_MODE_EXACT_RE.test(clean) || - (!isComposerModelButtonItem(itemProbe) && - ((clean && COMPOSER_MODE_TEXT_RE.test(clean)) || (attr && COMPOSER_MODE_ATTR_RE.test(attr)))); - const isModelBtn = isComposerModelButtonItem(itemProbe); - if (!isModeBtn && !isModelBtn) continue; - - let cur = btn.parentElement || btn.parentNode; - for (let depth = 0; depth < 12 && cur; depth += 1) { - if (cur === document.body || cur === document.documentElement) break; - if (String(cur.className || '').includes('monaco-workbench')) break; - const cr = cur.getBoundingClientRect?.(); - if (!cr || cr.height > 560) break; - if (cr.width >= 200) { - const rowBtns = collectComposerBottomButtons(cur, null, null, capEl, porEl); - if (isModeBtn) { - const hasModelSibling = rowBtns.some((b) => b.btn !== btn && isComposerModelButtonItem(b)); - if (hasModelSibling) { - const desc = buildComposerDockDescriptor(btn, cur, rowBtns, capEl, porEl, patchedNode); - if (desc) return desc; - } - } else if (isModelBtn && !modelToolbarFallback) { - const picked = pickAutoButtonFromRow(rowBtns, cr, { requireModelForFallback: true }); - if (picked) { - const desc = - picked.tier <= 3 && picked.btn - ? buildComposerDockDescriptor(picked.btn, cur, rowBtns, capEl, porEl, patchedNode) - : picked.tier === 4 && picked.leftAnchorBtn - ? buildComposerRightEndDockDescriptor( - picked.leftAnchorBtn, - cur, - rowBtns, - capEl, - porEl - ) - : null; - if (desc) { - if (picked.tier <= 2) return desc; - modelToolbarFallback = desc; - break; - } - } - } - } - cur = cur.parentElement || cur.parentNode; - } - } - if (modelToolbarFallback) return modelToolbarFallback; - } catch { - // 忽略输入框探测异常 - } - return null; -} - -function isImmediatelyBeforeNode(node, refNode) { - if (!node || !refNode) return false; - if (node.nextElementSibling !== undefined) { - return node.nextElementSibling === refNode; - } - if (node.nextSibling !== undefined) { - return node.nextSibling === refNode; - } - const parent = node.parentElement || node.parentNode; - if (!parent?.children) return false; - const idx = Array.prototype.indexOf.call(parent.children, node); - return idx >= 0 && parent.children[idx + 1] === refNode; -} - -function isIdeExtensionChatFrame() { - try { - if (typeof window === 'undefined') return false; - if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true; - return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || '')); - } catch { - return false; - } -} - -function resolveActiveDockTarget(options = undefined) { - const settings = telemetryStore.getState().telemetry?.settings; - const rawMode = - settings?.windowMountMode ?? - readInjectedWindowBridge()?.mountMode; - const mountMode = - options?.mountMode || - normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay); - if (isIdeExtensionChatFrame()) { - if (mountMode !== 'composer') return null; - return findHostComposerAutoTarget( - options?.capsuleNode || null, - options?.portalNode || null, - options?.patchedNode || null - ); - } - if (mountMode === 'composer') { - const composerTarget = findHostComposerAutoTarget( - options?.capsuleNode || null, - options?.portalNode || null, - options?.patchedNode || null - ); - if (composerTarget) return composerTarget; - } - const ideTarget = findIdeWorkbenchTitlebar(); - if (ideTarget) return ideTarget; - const titlebar = findHostTitlebar(); - if (!titlebar) return null; - let targetContainer = titlebar; - try { - const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild; - if (rightGroup && rightGroup !== titlebar.firstElementChild) { - targetContainer = rightGroup; - } - } catch { - // 忽略子选择器不兼容场景 - } - return { - kind: 'flow', - workbench: null, - titlebar, - targetContainer, - actionToolbar: null, - }; -} - -function findNativeTopRightAnchor() { - try { - if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { - return null; - } - const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]'); - if (auxToggle?.closest) { - return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle; - } - const candidates = document.querySelectorAll('button, a, [role="button"]'); - for (const btn of candidates) { - const text = String(btn.textContent || '').trim(); - if ( - (text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) && - btn.getBoundingClientRect?.().top < 52 - ) { - return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn; - } - } - return document.querySelector('div.absolute.right-0.top-0'); - } catch { - return null; - } -} - -function getLeftSidebarRightEdge(vw) { - try { - if (typeof document !== 'undefined' && typeof document.querySelector === 'function') { - if (document.querySelector('.monaco-workbench')) { - return 0; - } - const navEl = document.querySelector('div[role="navigation"]'); - if (navEl?.getBoundingClientRect) { - const nr = navEl.getBoundingClientRect(); - if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) { - return Math.ceil(nr.right); - } - } - } - } catch { - // 忽略侧栏测量异常 - } - return 0; -} - -/** - * 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 - */ -const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([ - 'src/styles/views-overview.css', - 'src/styles/views-consumption.css', - 'src/styles/views-tables.css', - 'src/styles/views-settings.css', - 'src/styles/controls.css', -]); - -let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null }; - -function buildSlimCapsuleCss(fullCss) { - if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss; - return fullCss - .split(/(?=\/\* --- src\/styles\/)/) - .filter((block) => { - const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//); - return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]); - }) - .join(''); -} - -function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) { - if (!shadowRoot) return; - if ( - fullCss && - typeof CSSStyleSheet === 'function' && - Array.isArray(shadowRoot.adoptedStyleSheets) - ) { - try { - if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) { - const sheet = new CSSStyleSheet(); - sheet.replaceSync(fullCss); - sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet }; - } - shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet]; - return; - } catch { - // 降级到传统