mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): live task cards, interactive usage trend chart, and Gemini 4 Carbon support (v1.4.2)
This commit is contained in:
@@ -1,16 +1,18 @@
|
||||
/**
|
||||
* @fileoverview 纯 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
|
||||
* 负责将按时间分桶的 Token 消耗序列渲染为带垂直渐变填充、虚线参考网格、
|
||||
* 峰值描点与自适应防溢出的顶部峰值胶囊标签的面积图。
|
||||
* @fileoverview 交互式 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
|
||||
* 支持:
|
||||
* 1. 自适应整点小时(<=72h)与自然日(>72h)高精度分桶序列渲染;
|
||||
* 2. 鼠标悬停/滑动十字准星探针、高亮圆点与自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数);
|
||||
* 3. 与 SVG 垂直网格线像素级对齐的多刻度底部时间轴(彻底告别首/中/末简单对半切分)。
|
||||
*/
|
||||
|
||||
import { h, patchAttr, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise } from '../../core/formatters.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
|
||||
/**
|
||||
* 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。
|
||||
* 控制点沿 X 轴取相邻点间距的 `0.45` 张力系数,Y 轴与各自端点齐平,
|
||||
* 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平,
|
||||
* 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。
|
||||
*
|
||||
* @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组
|
||||
@@ -23,33 +25,59 @@ function buildSmoothSplinePath(points) {
|
||||
for (let i = 0; i < points.length - 1; i++) {
|
||||
const p0 = points[i];
|
||||
const p1 = points[i + 1];
|
||||
const cpx1 = p0.x + (p1.x - p0.x) * 0.45;
|
||||
const cpx2 = p1.x - (p1.x - p0.x) * 0.45;
|
||||
const cpx1 = p0.x + (p1.x - p0.x) * 0.42;
|
||||
const cpx2 = p1.x - (p1.x - p0.x) * 0.42;
|
||||
d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 SVG 历史趋势平滑面积图组件。
|
||||
* 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。
|
||||
*
|
||||
* SVG 视口坐标系 (`viewBox="0 0 460 116"`) 布局约定:
|
||||
* - 水平绘图区:`leftX = 12` 至 `rightX = 448`(总跨度 `spanX = 436`),左右预留边距容纳端点圆点描边;
|
||||
* - 垂直绘图区:顶部峰值线 `topY = 26` 至底部零基线 `bottomY = 98`(总跨度 `spanY = 72`),
|
||||
* 顶部预留 26px 空间给 HTML 峰值胶囊 (`.trend-peak-pill`)。
|
||||
* @param {Array<{ label?: string }>} slots
|
||||
* @returns {number[]}
|
||||
*/
|
||||
function computeTickIndices(slots) {
|
||||
const n = slots.length;
|
||||
if (n <= 1) return [0];
|
||||
if (n <= 8) {
|
||||
return Array.from({ length: n }, (_, i) => i);
|
||||
}
|
||||
const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || '');
|
||||
const maxTicks = sampleLabel.length > 6 ? 5 : 6;
|
||||
const set = new Set();
|
||||
for (let k = 0; k < maxTicks; k++) {
|
||||
const idx = Math.round((k / (maxTicks - 1)) * (n - 1));
|
||||
set.add(idx);
|
||||
}
|
||||
return Array.from(set).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建交互式 SVG 历史趋势平滑面积图组件。
|
||||
*
|
||||
* @returns {{
|
||||
* el: HTMLElement,
|
||||
* update: (series?: Array<{ label: string, tokens: number }>) => void
|
||||
* }} 图表容器节点与序列更新方法
|
||||
* update: (series?: Array<object>) => void
|
||||
* }}
|
||||
*/
|
||||
export function createTrendAreaChart() {
|
||||
const VIEW_W = 460;
|
||||
const VIEW_H = 120;
|
||||
const LEFT_X = 14;
|
||||
const RIGHT_X = 446;
|
||||
const TOP_Y = 24;
|
||||
const BOTTOM_Y = 102;
|
||||
const SPAN_X = RIGHT_X - LEFT_X;
|
||||
const SPAN_Y = BOTTOM_Y - TOP_Y;
|
||||
|
||||
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 460 116');
|
||||
svg.setAttribute('viewBox', `0 0 ${VIEW_W} ${VIEW_H}`);
|
||||
svg.setAttribute('class', 'trend-svg');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
|
||||
// 垂直线性渐变:由顶部 36% 不透明度的主题色平滑衰减至底部全透明
|
||||
// 垂直线性渐变
|
||||
const defs = document.createElementNS(SVG_NS, 'defs');
|
||||
const grad = document.createElementNS(SVG_NS, 'linearGradient');
|
||||
grad.setAttribute('id', 'trend-area-grad');
|
||||
@@ -61,7 +89,7 @@ export function createTrendAreaChart() {
|
||||
const stop1 = document.createElementNS(SVG_NS, 'stop');
|
||||
stop1.setAttribute('offset', '0%');
|
||||
stop1.setAttribute('stop-color', 'var(--ctx-cached)');
|
||||
stop1.setAttribute('stop-opacity', '0.36');
|
||||
stop1.setAttribute('stop-opacity', '0.34');
|
||||
|
||||
const stop2 = document.createElementNS(SVG_NS, 'stop');
|
||||
stop2.setAttribute('offset', '100%');
|
||||
@@ -73,26 +101,22 @@ export function createTrendAreaChart() {
|
||||
defs.appendChild(grad);
|
||||
svg.appendChild(defs);
|
||||
|
||||
// 背景辅助参考网格线:3 条水平分位线 + 3 条垂直时间锚点分割线
|
||||
const gridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
gridGroup.setAttribute('class', 'trend-grid');
|
||||
for (const y of [26, 62, 98]) {
|
||||
// 背景水平与垂直参考网格线
|
||||
const hGridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
hGridGroup.setAttribute('class', 'trend-grid');
|
||||
for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', '10');
|
||||
line.setAttribute('x1', String(LEFT_X));
|
||||
line.setAttribute('y1', String(y));
|
||||
line.setAttribute('x2', '450');
|
||||
line.setAttribute('x2', String(RIGHT_X));
|
||||
line.setAttribute('y2', String(y));
|
||||
gridGroup.appendChild(line);
|
||||
hGridGroup.appendChild(line);
|
||||
}
|
||||
for (const x of [118, 230, 342]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', String(x));
|
||||
line.setAttribute('y1', '16');
|
||||
line.setAttribute('x2', String(x));
|
||||
line.setAttribute('y2', '98');
|
||||
gridGroup.appendChild(line);
|
||||
}
|
||||
svg.appendChild(gridGroup);
|
||||
svg.appendChild(hGridGroup);
|
||||
|
||||
const vGridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
vGridGroup.setAttribute('class', 'trend-grid trend-v-grid');
|
||||
svg.appendChild(vGridGroup);
|
||||
|
||||
const areaPath = document.createElementNS(SVG_NS, 'path');
|
||||
areaPath.setAttribute('fill', 'url(#trend-area-grad)');
|
||||
@@ -103,25 +127,157 @@ export function createTrendAreaChart() {
|
||||
linePath.setAttribute('fill', 'none');
|
||||
svg.appendChild(linePath);
|
||||
|
||||
const dotsGroup = document.createElementNS(SVG_NS, 'g');
|
||||
dotsGroup.setAttribute('class', 'trend-dots-group');
|
||||
svg.appendChild(dotsGroup);
|
||||
|
||||
const peakDot = document.createElementNS(SVG_NS, 'circle');
|
||||
peakDot.setAttribute('r', '3');
|
||||
peakDot.setAttribute('class', 'trend-peak-dot');
|
||||
svg.appendChild(peakDot);
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]);
|
||||
// 悬停十字准星与焦点圆点
|
||||
const hoverLine = document.createElementNS(SVG_NS, 'line');
|
||||
hoverLine.setAttribute('class', 'trend-hover-line');
|
||||
hoverLine.setAttribute('y1', '12');
|
||||
hoverLine.setAttribute('y2', String(BOTTOM_Y));
|
||||
hoverLine.setAttribute('hidden', 'true');
|
||||
svg.appendChild(hoverLine);
|
||||
|
||||
let lastLineD = '';
|
||||
const hoverDot = document.createElementNS(SVG_NS, 'circle');
|
||||
hoverDot.setAttribute('r', '3.2');
|
||||
hoverDot.setAttribute('class', 'trend-hover-dot');
|
||||
hoverDot.setAttribute('hidden', 'true');
|
||||
svg.appendChild(hoverDot);
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
|
||||
// 悬停详情浮层卡片
|
||||
const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' });
|
||||
const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' });
|
||||
const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' });
|
||||
const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true });
|
||||
|
||||
const tooltipEl = h(
|
||||
'div',
|
||||
{ className: 'trend-tooltip', hidden: true },
|
||||
[
|
||||
h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]),
|
||||
h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]),
|
||||
tipSubEl,
|
||||
]
|
||||
);
|
||||
|
||||
// 底部对齐刻度轴
|
||||
const xAxisEl = h('div', { className: 'trend-x-axis' });
|
||||
|
||||
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, tooltipEl, svg]);
|
||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [plotStage, xAxisEl]);
|
||||
|
||||
let currentSlots = [];
|
||||
let currentPts = [];
|
||||
let tickElsByIdx = new Map();
|
||||
let hoveredIdx = -1;
|
||||
let lastRenderSig = '';
|
||||
|
||||
function showHoverAtIndex(idx) {
|
||||
if (idx < 0 || idx >= currentSlots.length || !currentPts[idx]) {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
hoveredIdx = idx;
|
||||
const slot = currentSlots[idx];
|
||||
const pt = currentPts[idx];
|
||||
|
||||
patchAttr(hoverLine, 'hidden', false);
|
||||
patchAttr(hoverLine, 'x1', pt.x.toFixed(1));
|
||||
patchAttr(hoverLine, 'x2', pt.x.toFixed(1));
|
||||
|
||||
patchAttr(hoverDot, 'hidden', false);
|
||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
|
||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||
patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`);
|
||||
patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`);
|
||||
patchText(
|
||||
tipCostEl,
|
||||
formatUsd(Number(slot.costUsd || 0), {
|
||||
unpricedCalls: slot.unpricedCalls,
|
||||
precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1,
|
||||
})
|
||||
);
|
||||
|
||||
const hasSubBreakdown =
|
||||
Number(slot.tokens || 0) > 0 &&
|
||||
(slot.inputTokens !== undefined ||
|
||||
slot.cacheReadTokens !== undefined ||
|
||||
slot.outputTokens !== undefined);
|
||||
patchAttr(tipSubEl, 'hidden', !hasSubBreakdown);
|
||||
if (hasSubBreakdown) {
|
||||
patchText(
|
||||
tipSubEl,
|
||||
`入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}`
|
||||
);
|
||||
}
|
||||
|
||||
const rawPct = (pt.x / VIEW_W) * 100;
|
||||
const clampedPct = Math.max(2, Math.min(98, rawPct));
|
||||
const shiftX = rawPct < 28 ? '0%' : rawPct > 72 ? '-100%' : '-50%';
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', shiftX);
|
||||
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
}
|
||||
}
|
||||
|
||||
function clearHover() {
|
||||
hoveredIdx = -1;
|
||||
patchAttr(hoverLine, 'hidden', true);
|
||||
patchAttr(hoverDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
patchAttr(peakPill, 'hidden', false);
|
||||
for (const el of tickElsByIdx.values()) {
|
||||
patchClasses(el, { 'is-hovered': false });
|
||||
}
|
||||
}
|
||||
|
||||
function handlePointerMove(e) {
|
||||
if (!currentSlots.length) return;
|
||||
const rect = svg.getBoundingClientRect();
|
||||
if (!rect || rect.width <= 0) return;
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * VIEW_W;
|
||||
const ratio = (relX - LEFT_X) / Math.max(1, SPAN_X);
|
||||
const idx = Math.max(
|
||||
0,
|
||||
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
||||
);
|
||||
showHoverAtIndex(idx);
|
||||
}
|
||||
|
||||
plotStage.addEventListener('mousemove', handlePointerMove);
|
||||
plotStage.addEventListener('mouseleave', clearHover);
|
||||
|
||||
/**
|
||||
* 根据最新时间分桶序列重绘平滑曲线、闭合渐变区域以及最高峰标记位置。
|
||||
* 根据最新时间分桶序列重绘平滑曲线、渐变区域、峰值气泡与底部对齐刻度。
|
||||
*/
|
||||
function update(series = []) {
|
||||
const slots = series.length >= 2 ? series : [
|
||||
{ label: '00:00', tokens: 0 },
|
||||
{ label: '06:00', tokens: 0 },
|
||||
{ label: '12:00', tokens: 0 },
|
||||
];
|
||||
const slots =
|
||||
Array.isArray(series) && series.length >= 2
|
||||
? series
|
||||
: [
|
||||
{ label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 },
|
||||
{ label: '06:00', fullLabel: '06:00 - 07:00', tokens: 0, calls: 0, costUsd: 0 },
|
||||
{ label: '12:00', fullLabel: '12:00 - 13:00', tokens: 0, calls: 0, costUsd: 0 },
|
||||
{ label: '18:00', fullLabel: '18:00 - 19:00', tokens: 0, calls: 0, costUsd: 0 },
|
||||
];
|
||||
currentSlots = slots;
|
||||
|
||||
let maxTokens = 0;
|
||||
let peakIdx = 0;
|
||||
for (let i = 0; i < slots.length; i++) {
|
||||
@@ -132,39 +288,92 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
}
|
||||
|
||||
// SVG 绘图区边界与跨度参数(Y 轴向下递增,因此数值越大对应的 y 坐标越小)
|
||||
const leftX = 12;
|
||||
const rightX = 448;
|
||||
const topY = 26;
|
||||
const bottomY = 98;
|
||||
const spanX = rightX - leftX;
|
||||
const spanY = bottomY - topY;
|
||||
const denom = Math.max(1, maxTokens);
|
||||
|
||||
const pts = slots.map((s, idx) => {
|
||||
const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX;
|
||||
const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
|
||||
const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0;
|
||||
const y = bottomY - ratio * spanY;
|
||||
return { x, y };
|
||||
const y = BOTTOM_Y - ratio * SPAN_Y;
|
||||
return { x, y, tokens: Number(s.tokens || 0) };
|
||||
});
|
||||
currentPts = pts;
|
||||
|
||||
// 仅在曲线路径发生变化时更新 DOM 属性,避免无意义的 SVG 重绘
|
||||
const lineD = buildSmoothSplinePath(pts);
|
||||
if (lineD !== lastLineD) {
|
||||
lastLineD = lineD;
|
||||
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`;
|
||||
const sig = slots
|
||||
.map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`)
|
||||
.join('|');
|
||||
|
||||
if (sig !== lastRenderSig) {
|
||||
lastRenderSig = sig;
|
||||
const lineD = buildSmoothSplinePath(pts);
|
||||
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
patchAttr(linePath, 'd', lineD);
|
||||
patchAttr(areaPath, 'd', areaD);
|
||||
|
||||
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签
|
||||
const tickIndices = computeTickIndices(slots);
|
||||
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
|
||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||
tickElsByIdx = new Map();
|
||||
|
||||
for (let i = 0; i < tickIndices.length; i++) {
|
||||
const tIdx = tickIndices[i];
|
||||
const pt = pts[tIdx];
|
||||
const slot = slots[tIdx];
|
||||
if (!pt || !slot) continue;
|
||||
|
||||
if (i > 0 && i < tickIndices.length - 1) {
|
||||
const vLine = document.createElementNS(SVG_NS, 'line');
|
||||
vLine.setAttribute('x1', pt.x.toFixed(1));
|
||||
vLine.setAttribute('y1', '16');
|
||||
vLine.setAttribute('x2', pt.x.toFixed(1));
|
||||
vLine.setAttribute('y2', String(BOTTOM_Y));
|
||||
vGridGroup.appendChild(vLine);
|
||||
}
|
||||
|
||||
const isFirst = i === 0;
|
||||
const isLast = i === tickIndices.length - 1;
|
||||
const pct = (pt.x / VIEW_W) * 100;
|
||||
const tickEl = h('span', {
|
||||
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
|
||||
text: slot.label || '',
|
||||
title: slot.fullLabel || slot.label || '',
|
||||
});
|
||||
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
|
||||
tickEl.onclick = () => showHoverAtIndex(tIdx);
|
||||
xAxisEl.appendChild(tickEl);
|
||||
tickElsByIdx.set(tIdx, tickEl);
|
||||
}
|
||||
|
||||
// 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期)
|
||||
while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild);
|
||||
if (pts.length <= 36) {
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
if (pts[i].tokens <= 0) continue;
|
||||
const dot = document.createElementNS(SVG_NS, 'circle');
|
||||
dot.setAttribute('cx', pts[i].x.toFixed(1));
|
||||
dot.setAttribute('cy', pts[i].y.toFixed(1));
|
||||
dot.setAttribute('r', '2');
|
||||
dot.setAttribute('class', 'trend-node-dot');
|
||||
dotsGroup.appendChild(dot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 定位峰值圆点,并将顶部峰值气泡水平位置钳制在 [8%, 92%] 区间内以防贴边裁切
|
||||
const peakPt = pts[peakIdx] || { x: 230, y: bottomY };
|
||||
const peakPt = pts[peakIdx] || { x: 230, y: BOTTOM_Y };
|
||||
patchAttr(peakDot, 'cx', peakPt.x.toFixed(1));
|
||||
patchAttr(peakDot, 'cy', peakPt.y.toFixed(1));
|
||||
|
||||
patchText(peakPill, formatTokensPrecise(maxTokens));
|
||||
const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100));
|
||||
const peakSlot = slots[peakIdx];
|
||||
const peakText =
|
||||
maxTokens > 0 && peakSlot?.label
|
||||
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
||||
: formatTokensPrecise(maxTokens);
|
||||
patchText(peakPill, peakText);
|
||||
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100));
|
||||
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
||||
|
||||
if (hoveredIdx >= 0 && hoveredIdx < slots.length) {
|
||||
showHoverAtIndex(hoveredIdx);
|
||||
}
|
||||
}
|
||||
|
||||
return { el: chartWrap, update };
|
||||
|
||||
@@ -6,12 +6,9 @@
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { formatUsd } from '../../core/formatters.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
formatAgentLabel,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
triggerPluginUpdate,
|
||||
} from '../../store/telemetryStore.js';
|
||||
@@ -97,59 +94,7 @@ export const TopSessionHeader = defineComponent({
|
||||
h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]),
|
||||
]);
|
||||
|
||||
// --- 方案 A:顶栏二级主/子代理切换条 (.agent-scope-bar,无子代理时自动隐藏) ---
|
||||
const scopeAllBtnText = h('span', { text: '全部汇总' });
|
||||
const scopeAllBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'scope-pill-btn is-active',
|
||||
onClick: () =>
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }),
|
||||
},
|
||||
[scopeAllBtnText]
|
||||
);
|
||||
|
||||
const scopeMainBtnText = h('span', { text: '主代理' });
|
||||
const scopeMainBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'scope-pill-btn',
|
||||
onClick: () => uiStore.setState({ selectedAgentScope: 'main' }),
|
||||
},
|
||||
[scopeMainBtnText]
|
||||
);
|
||||
|
||||
const subagentSelect = CustomSelect({
|
||||
modelValue: '',
|
||||
icon: 'cpu',
|
||||
placeholder: '子代理 (0)',
|
||||
className: 'scope-subagent-select',
|
||||
options: [],
|
||||
onUpdateModelValue: (nextSubId) => {
|
||||
if (nextSubId) {
|
||||
uiStore.setState({ selectedAgentScope: nextSubId });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const scopeRightText = h('span', { className: 'agent-scope-right text-mono', text: '' });
|
||||
|
||||
const scopeBarEl = h(
|
||||
'div',
|
||||
{ className: 'agent-scope-bar', hidden: true },
|
||||
[
|
||||
h('div', { className: 'agent-scope-left' }, [
|
||||
scopeAllBtn,
|
||||
scopeMainBtn,
|
||||
subagentSelect.el,
|
||||
]),
|
||||
scopeRightText,
|
||||
]
|
||||
);
|
||||
|
||||
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl, scopeBarEl]);
|
||||
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]);
|
||||
|
||||
let lastActiveCascadeId = '';
|
||||
|
||||
@@ -183,45 +128,9 @@ export const TopSessionHeader = defineComponent({
|
||||
options,
|
||||
});
|
||||
|
||||
const {
|
||||
hasSubagents,
|
||||
effectiveScope,
|
||||
subagents,
|
||||
mainAgent,
|
||||
aggregated,
|
||||
scopedConv,
|
||||
} = resolveScopedConversation(telemetry, uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId);
|
||||
|
||||
patchAttr(scopeBarEl, 'hidden', !hasSubagents);
|
||||
if (hasSubagents) {
|
||||
patchText(scopeAllBtnText, `全部 (${aggregated?.stepCount ?? 0})`);
|
||||
patchClasses(scopeAllBtn, { 'is-active': effectiveScope === 'all' });
|
||||
|
||||
patchText(scopeMainBtnText, `主代理 (${mainAgent?.stepCount ?? 0})`);
|
||||
patchClasses(scopeMainBtn, { 'is-active': effectiveScope === 'main' });
|
||||
|
||||
const isSubSelected = effectiveScope !== 'all' && effectiveScope !== 'main';
|
||||
patchClasses(subagentSelect.el, { 'is-active-sub': isSubSelected });
|
||||
const subOptions = subagents.map((s) => ({
|
||||
value: s.agentId,
|
||||
label: formatAgentLabel(s),
|
||||
meta: `${s.stepCount || 0}步 · 窗${s.context?.usedPct ?? 0}%`,
|
||||
}));
|
||||
subagentSelect.setProps({
|
||||
modelValue: isSubSelected ? effectiveScope : '',
|
||||
placeholder: `子代理 (${subagents.length})`,
|
||||
options: subOptions,
|
||||
});
|
||||
|
||||
patchText(
|
||||
scopeRightText,
|
||||
formatUsd(scopedConv?.sessionCostUsd || 0, {
|
||||
unpricedCalls: scopedConv?.sessionUnpricedCalls,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
subagentSelect.close();
|
||||
}
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0);
|
||||
const aggregated = actConv?.aggregated;
|
||||
|
||||
const cloudStatus = telemetry?.cloudStatus;
|
||||
const hasUpdate = Boolean(cloudStatus?.updateAvailable);
|
||||
@@ -308,21 +217,14 @@ export const TopSessionHeader = defineComponent({
|
||||
() => renderHeaderState()
|
||||
);
|
||||
|
||||
const unsubUi = uiStore.subscribe(
|
||||
(st) => st.selectedAgentScope,
|
||||
() => renderHeaderState()
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubTelemetry();
|
||||
unsubUi();
|
||||
convSelect.destroy();
|
||||
subagentSelect.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: headerEl,
|
||||
refs: { convSelect, subagentSelect, statusTag, refreshBtn, scopeBarEl },
|
||||
refs: { convSelect, statusTag, refreshBtn },
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchStyleVar } from '../../core/domPatch.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar } from '../../core/domPatch.js';
|
||||
|
||||
const SEGMENT_DEFS = [
|
||||
{ key: 'assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) },
|
||||
@@ -27,11 +27,10 @@ const SEGMENT_DEFS = [
|
||||
export const ContextSegmentMeter = defineComponent({
|
||||
name: 'ContextSegmentMeter',
|
||||
setup({ getProps }) {
|
||||
const segments = SEGMENT_DEFS.map((def, idx) => ({
|
||||
...def,
|
||||
defaultOrder: idx,
|
||||
el: h('div', { className: `progress-seg ${def.cls}` }),
|
||||
}));
|
||||
// 固定 10 个位置槽位节点,不通过 appendChild 移动 DOM,防止浏览器中断 CSS transition 动画
|
||||
const slotEls = SEGMENT_DEFS.map((def) =>
|
||||
h('div', { className: `progress-seg ${def.cls}` })
|
||||
);
|
||||
|
||||
const trackEl = h(
|
||||
'div',
|
||||
@@ -41,28 +40,38 @@ export const ContextSegmentMeter = defineComponent({
|
||||
'aria-valuemin': '0',
|
||||
'aria-valuemax': '100',
|
||||
},
|
||||
segments.map((s) => s.el)
|
||||
slotEls
|
||||
);
|
||||
|
||||
let lastOrderSig = segments.map((s) => s.key).join(',');
|
||||
let lastOrderSig = '';
|
||||
|
||||
function syncMeter() {
|
||||
const ctx = getProps().context || {};
|
||||
const limit = Math.max(1, Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000));
|
||||
const scored = segments.map((seg) => {
|
||||
const val = seg.getVal(ctx);
|
||||
const scored = SEGMENT_DEFS.map((def, defaultOrder) => {
|
||||
const val = def.getVal(ctx);
|
||||
const pct = Math.min(100, (val / limit) * 100);
|
||||
patchStyleVar(seg.el, '--seg-w', `${pct.toFixed(2)}%`);
|
||||
return { seg, val };
|
||||
return { def, defaultOrder, val, pct };
|
||||
});
|
||||
|
||||
scored.sort((a, b) => b.val - a.val || a.seg.defaultOrder - b.seg.defaultOrder);
|
||||
const nextOrderSig = scored.map((x) => x.seg.key).join(',');
|
||||
if (nextOrderSig !== lastOrderSig) {
|
||||
lastOrderSig = nextOrderSig;
|
||||
for (const { seg } of scored) {
|
||||
trackEl.appendChild(seg.el);
|
||||
}
|
||||
scored.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder);
|
||||
// 仅关注非零通道的相对顺序变化,决定是否启用 0.05s 先变色再伸缩的衔接延迟
|
||||
const activeOrderSig = scored
|
||||
.filter((x) => x.val > 0)
|
||||
.map((x) => x.def.key)
|
||||
.join(',');
|
||||
const orderChanged = Boolean(lastOrderSig && activeOrderSig && activeOrderSig !== lastOrderSig);
|
||||
if (activeOrderSig) {
|
||||
lastOrderSig = activeOrderSig;
|
||||
}
|
||||
|
||||
patchClasses(trackEl, { 'is-reordering': orderChanged });
|
||||
|
||||
for (let i = 0; i < slotEls.length; i++) {
|
||||
const slotEl = slotEls[i];
|
||||
const item = scored[i];
|
||||
patchAttr(slotEl, 'class', `progress-seg ${item.def.cls}`);
|
||||
patchStyleVar(slotEl, '--seg-w', `${item.pct.toFixed(2)}%`);
|
||||
}
|
||||
|
||||
patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0));
|
||||
@@ -72,7 +81,7 @@ export const ContextSegmentMeter = defineComponent({
|
||||
|
||||
return {
|
||||
el: trackEl,
|
||||
refs: { segments },
|
||||
refs: { segments: slotEls },
|
||||
onPropsChange: syncMeter,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -257,8 +257,8 @@ export const CustomDateTimePicker = defineComponent({
|
||||
};
|
||||
|
||||
if (typeof document !== 'undefined' && document.addEventListener) {
|
||||
document.addEventListener('click', handleDocClick);
|
||||
onCleanup(() => document.removeEventListener('click', handleDocClick));
|
||||
document.addEventListener('click', handleDocClick, true);
|
||||
onCleanup(() => document.removeEventListener('click', handleDocClick, true));
|
||||
}
|
||||
|
||||
syncDisplay();
|
||||
|
||||
@@ -141,16 +141,27 @@ export const CustomScrollbar = defineComponent({
|
||||
}
|
||||
});
|
||||
|
||||
let pendingSync = false;
|
||||
function scheduleSyncThumb() {
|
||||
if (typeof queueMicrotask === 'function') {
|
||||
if (pendingSync) return;
|
||||
pendingSync = true;
|
||||
queueMicrotask(() => {
|
||||
pendingSync = false;
|
||||
syncThumb();
|
||||
});
|
||||
} else {
|
||||
syncThumb();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
el: hostEl,
|
||||
refs: { contentEl, railEl, thumbEl },
|
||||
onPropsChange: syncThumb,
|
||||
onPropsChange: scheduleSyncThumb,
|
||||
methods: {
|
||||
refresh() {
|
||||
syncThumb();
|
||||
if (typeof queueMicrotask === 'function') {
|
||||
queueMicrotask(syncThumb);
|
||||
}
|
||||
scheduleSyncThumb();
|
||||
},
|
||||
scrollToRatio(ratio) {
|
||||
const r = Math.max(0, Math.min(1, Number(ratio || 0)));
|
||||
|
||||
@@ -152,9 +152,7 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
const selectedOpt =
|
||||
options.find((o) => o.value === modelValue) ||
|
||||
(modelValue !== '' && modelValue !== null && modelValue !== undefined
|
||||
? options[0]
|
||||
: undefined);
|
||||
(!modelValue ? options[0] : undefined);
|
||||
patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder);
|
||||
if (isOpen) {
|
||||
renderMenuOptions();
|
||||
@@ -168,8 +166,8 @@ export const CustomSelect = defineComponent({
|
||||
};
|
||||
|
||||
if (typeof document !== 'undefined' && document.addEventListener) {
|
||||
document.addEventListener('click', handleDocClick);
|
||||
onCleanup(() => document.removeEventListener('click', handleDocClick));
|
||||
document.addEventListener('click', handleDocClick, true);
|
||||
onCleanup(() => document.removeEventListener('click', handleDocClick, true));
|
||||
}
|
||||
|
||||
syncTriggerAndMenu();
|
||||
|
||||
@@ -35,6 +35,16 @@ export const TopLongPillNav = defineComponent({
|
||||
const { items = [], modelValue } = getProps();
|
||||
patchStyleVar(navEl, '--pill-count', Math.max(1, items.length));
|
||||
|
||||
const validValues = new Set(items.map((it) => it.value));
|
||||
for (const [val, entry] of tabButtons.entries()) {
|
||||
if (!validValues.has(val)) {
|
||||
if (entry.btn?.parentNode === navEl) {
|
||||
navEl.removeChild(entry.btn);
|
||||
}
|
||||
tabButtons.delete(val);
|
||||
}
|
||||
}
|
||||
|
||||
let activeIdx = 0;
|
||||
items.forEach((item, index) => {
|
||||
if (item.value === modelValue) {
|
||||
@@ -57,8 +67,13 @@ export const TopLongPillNav = defineComponent({
|
||||
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
const curItems = getProps().items || [];
|
||||
if (!curItems.length) return;
|
||||
const curIndex = Math.max(
|
||||
0,
|
||||
curItems.findIndex((it) => it.value === item.value)
|
||||
);
|
||||
const delta = e.key === 'ArrowRight' ? 1 : -1;
|
||||
const nextIndex = (index + delta + curItems.length) % curItems.length;
|
||||
const nextIndex = (curIndex + delta + curItems.length) % curItems.length;
|
||||
const target = curItems[nextIndex];
|
||||
if (target) {
|
||||
selectValue(target.value);
|
||||
|
||||
Reference in New Issue
Block a user