fix(panel): eliminate buffered tool-call speed spikes, add per-step cost column and full step history scroll

This commit is contained in:
yuhuan2498281558
2026-10-14 15:42:19 +08:00
parent 6c7f9eb49d
commit 44386f38d8
5 changed files with 121 additions and 47 deletions
+2 -2
View File
@@ -18,8 +18,8 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side
- **💰 本对话消耗 & 本机累计消耗(含后台自动压缩步 `CHECKPOINT` 账单)**
- 自动扫描本地全量历史会话并聚合统计 **💬 本对话消耗** 与 **👤 本机累计消耗**(总 Token、精确官方 API 美元费用、输入/缓存/输出明细、Gemini 与 Claude/GPT 模型池分账),同时完整捕获 `CORTEX_STEP_TYPE_CHECKPOINT` 后台自动压缩步骤写入 `metadata.retryInfos[0].usage` 的隐藏 Token 消耗。
- 支持 **`全部` / `近5h` / `今日` / `本周` / `30天` / `自定义起止时间`** 一键切换筛选,底部「按模型汇总」表也会同步按所选时间段过滤。
- **📋 步骤测速明细表 & 按模型汇总表**
- 提供当前会话最近 15 步的单步测速明细(鼠标悬停可查看每步的思考 Token/耗时、正文输出流耗时及单步精确美元消耗)以及所选时间段内按模型分类的调用次数、均速、总 Token 与 API 费用统计。
- **📋 全量步骤测速与计费明细表 & 按模型汇总表**
- 提供当前会话**全量历史步骤**(无 15 步截断限制,支持吸顶表头平滑滚动)的单步测速与**单步精确美元消费 (`$0.XXX`)** 明细(鼠标悬停可查看每步的输入/缓存/输出费用拆解、折合 5h/周限扣减百分比、思考 Token/耗时与正文输出流耗时),以及所选时间段内按模型分类的调用次数、均速、总 Token 与 API 费用统计。
---
+70 -31
View File
@@ -132,40 +132,75 @@ function renderAllPools(pools, activeFamily) {
}
}
let lastStepsRenderSig = '';
let lastModelsRenderSig = '';
function renderTables(activeConv, modelBreakdown) {
const stepsTbody = $('steps-tbody');
stepsTbody.innerHTML = '';
for (const st of activeConv.recentSteps || []) {
const tr = document.createElement('tr');
const thinkInfo = st.thinkingTokens
? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | `
: '';
const compTag = st.isCompactionStep ? ' [压缩汇总步]' : '';
tr.title = `${thinkInfo}正文/工具输出: ${st.responseTokens} tok | 流耗时: ${st.streamDurationSec}s | 总耗时: ${st.totalDurationSec}s | 单步费用: $${Number(st.costUsd || 0).toFixed(4)}`;
tr.innerHTML = `
<td>#${Number(st.stepIndex)}${compTag ? '<span class="muted">⚡</span>' : ''}</td>
<td>${escapeHtml(st.modelShort)}</td>
<td><strong style="color: var(--speed-accent)">${Number(st.tokPerSec).toFixed(1)}</strong> tok/s</td>
<td>${Number(st.ttftSec).toFixed(1)}s</td>
<td>${formatTokens(st.contextTokens)} / +${Number(st.outputTokens)}</td>
<td style="color: var(--cache-green)">${Number(st.cacheHitPct)}%</td>
`;
stepsTbody.appendChild(tr);
const steps = activeConv.recentSteps || [];
const tabStepsBtn = $('tab-steps-btn');
if (tabStepsBtn) {
tabStepsBtn.textContent = `当前会话步骤测速与计费 (${steps.length}步)`;
}
const modelsTbody = $('models-tbody');
modelsTbody.innerHTML = '';
for (const m of modelBreakdown || []) {
const tr = document.createElement('tr');
const pricePrefix = m.isEstimatedPrice ? '≈$' : '$';
tr.innerHTML = `
<td><strong>${escapeHtml(m.shortName)}</strong> <span class="muted">(${Number(m.calls)})</span></td>
<td>${Number(m.calls)}</td>
<td>${Number(m.avgTokPerSec).toFixed(1)} tok/s</td>
<td>${formatTokens(m.totalTokens)}</td>
<td>${pricePrefix}${Number(m.costUsd).toFixed(2)}</td>
`;
modelsTbody.appendChild(tr);
const stepsSig = `${activeConv.cascadeId || ''}:${steps.length}:${steps[0]?.stepIndex ?? -1}:${steps[0]?.tokPerSec ?? 0}:${steps[0]?.costUsd ?? 0}`;
if (stepsSig !== lastStepsRenderSig) {
lastStepsRenderSig = stepsSig;
const stepsTbody = $('steps-tbody');
const scrollParent = stepsTbody.closest('.table-scroll');
const prevScrollTop = scrollParent ? scrollParent.scrollTop : 0;
const frag = document.createDocumentFragment();
for (const st of steps) {
const tr = document.createElement('tr');
const thinkInfo = st.thinkingTokens
? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | `
: '';
const compTag = st.isCompactionStep ? ' [压缩汇总步]' : '';
const stepCostVal = Number(st.costUsd || 0);
const stepCostDisplay = stepCostVal >= 1 ? `$${stepCostVal.toFixed(2)}` : `$${stepCostVal.toFixed(3)}`;
const costStyle =
stepCostVal >= 0.15
? 'color: var(--speed-accent); font-weight: 700;'
: 'color: var(--foreground); font-weight: 600;';
const pct5h = (stepCostVal / 0.25).toFixed(2);
const pctWk = stepCostVal.toFixed(3);
tr.title = `单步消费: $${stepCostVal.toFixed(4)} (入 $${Number(st.inCostUsd || 0).toFixed(4)} + 缓 $${Number(st.cacheCostUsd || 0).toFixed(4)} + 出 $${Number(st.outCostUsd || 0).toFixed(4)} | 约合 5h ${pct5h}% / 周限 ${pctWk}%) | ${thinkInfo}正文/工具输出: ${st.responseTokens} tok | 流耗时: ${st.streamDurationSec}s | 总耗时: ${st.totalDurationSec}s`;
tr.innerHTML = `
<td>#${Number(st.stepIndex)}${compTag ? '<span class="muted">⚡</span>' : ''}</td>
<td>${escapeHtml(st.modelShort)}</td>
<td><strong style="color: var(--speed-accent)">${Number(st.tokPerSec).toFixed(1)}</strong> tok/s</td>
<td>${Number(st.ttftSec).toFixed(1)}s</td>
<td>${formatTokens(st.contextTokens)} / +${Number(st.outputTokens)}</td>
<td style="color: var(--cache-green)">${Number(st.cacheHitPct)}%</td>
<td style="${costStyle}">${stepCostDisplay}</td>
`;
frag.appendChild(tr);
}
stepsTbody.innerHTML = '';
stepsTbody.appendChild(frag);
if (scrollParent && prevScrollTop > 0) {
scrollParent.scrollTop = prevScrollTop;
}
}
const models = modelBreakdown || [];
const modelsSig = models.map((m) => `${m.modelId}:${m.calls}:${m.totalTokens}:${m.avgTokPerSec}`).join('|');
if (modelsSig !== lastModelsRenderSig) {
lastModelsRenderSig = modelsSig;
const modelsTbody = $('models-tbody');
modelsTbody.innerHTML = '';
for (const m of models) {
const tr = document.createElement('tr');
const pricePrefix = m.isEstimatedPrice ? '≈$' : '$';
tr.innerHTML = `
<td><strong>${escapeHtml(m.shortName)}</strong> <span class="muted">(${Number(m.calls)})</span></td>
<td>${Number(m.calls)}</td>
<td>${Number(m.avgTokPerSec).toFixed(1)} tok/s</td>
<td>${formatTokens(m.totalTokens)}</td>
<td>${pricePrefix}${Number(m.costUsd).toFixed(2)}</td>
`;
modelsTbody.appendChild(tr);
}
}
}
@@ -264,6 +299,10 @@ function applyTelemetryToDom(data) {
$('tok-per-sec').textContent = `${Number(active.latestTokPerSec || 0).toFixed(1)} tok/s`;
$('ttft-value').textContent = `${Number(active.latestTtftSec || 0).toFixed(1)}s`;
$('avg-speed-value').textContent = `${Number(active.avgTokPerSec || 0).toFixed(1)}`;
const latestStepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0);
if ($('step-cost-value')) {
$('step-cost-value').textContent = `$${latestStepCost.toFixed(3)}`;
}
$('session-cost-value').textContent = `$${Number(active.sessionCostUsd || 0).toFixed(2)}`;
$('cache-hit-value').textContent = `${active.latestCacheHitPct ?? 0}%`;
renderParallelograms(ctx.usedPct || 0);
+3 -2
View File
@@ -33,7 +33,7 @@
<span class="metric-item">首字 <strong id="ttft-value">0.0s</strong></span>
<span class="metric-item">均速 <strong id="avg-speed-value">0.0</strong></span>
<span class="strip-divider">|</span>
<strong id="session-cost-value" class="cost-value">$0.00</strong>
<span class="metric-item" title="最新一步消费 / 当前会话累计消费">本步 <strong id="step-cost-value" class="cost-value">$0.000</strong> · 累计 <strong id="session-cost-value" class="cost-value">$0.00</strong></span>
<span class="metric-item">缓存 <strong id="cache-hit-value" class="cache-value">0%</strong></span>
<span class="strip-divider">|</span>
<span class="metric-item ctx-inline-trigger" id="ctx-inline-trigger" title="点击展开上下文细分">
@@ -198,7 +198,7 @@
<!-- Detailed Breakdown Card (Toggled by 查看详细明细) -->
<section id="details-card" class="details-card" hidden>
<div class="tabs-header">
<button type="button" class="tab-btn active" data-tab="steps">当前会话步骤测速</button>
<button type="button" class="tab-btn active" data-tab="steps" id="tab-steps-btn">当前会话步骤测速与计费</button>
<button type="button" class="tab-btn" data-tab="models" id="tab-models-btn">按模型汇总 (全部时间)</button>
</div>
@@ -213,6 +213,7 @@
<th>首字</th>
<th>上下文/输出</th>
<th>缓存</th>
<th>消费</th>
</tr>
</thead>
<tbody id="steps-tbody"></tbody>
+37 -11
View File
@@ -58,7 +58,7 @@ const PLACEHOLDER_MAP = {
};
// In-memory cache of trajectory step usage: cascadeId -> { signature, steps }
const CACHE_SCHEMA_VERSION = 'v4';
const CACHE_SCHEMA_VERSION = 'v5';
let trajectoryCache = loadJson(CACHE_FILE, {});
const inFlightRequests = new Map();
let quotaSummaryCache = { ts: 0, data: null, error: null };
@@ -294,8 +294,9 @@ function extractModelSteps(rawSteps = [], generatorMetadata = []) {
const thinkingDurationSec = parseDurationSec(p.thinkingDuration);
const respText = String(p.modifiedResponse || p.response || '').trim();
const hasVisibleText = respText.length > 0;
const hasToolCalls = Array.isArray(p.toolCalls) && p.toolCalls.length > 0;
const ttftSec = nativeTtftSec > 0 ? nativeTtftSec : rawViewableSec;
let ttftSec = nativeTtftSec > 0 ? nativeTtftSec : rawViewableSec;
let streamTokens = outputTokens;
let streamDurationSec = 0;
let speedBasis = 'model_stream';
@@ -305,31 +306,48 @@ function extractModelSteps(rawSteps = [], generatorMetadata = []) {
? totalDurationSec - thinkingDurationSec
: afterViewableSec;
if (hasVisibleText && responseTokens > 0 && postThinkingSec >= 0.2) {
if (hasVisibleText && responseTokens > 0 && postThinkingSec >= 0.35) {
streamTokens = responseTokens;
streamDurationSec = postThinkingSec;
speedBasis = 'response_stream';
} else if (nativeStreamSec >= 0.2 && outputTokens > 0) {
streamTokens = outputTokens;
} else if (
nativeStreamSec >= 1.0 &&
outputTokens > 0 &&
(!hasToolCalls || nativeStreamSec >= totalDurationSec * 0.35)
) {
// Unbuffered streaming (e.g. write_to_file streaming file content)
streamTokens = responseTokens > 0 ? responseTokens : outputTokens;
streamDurationSec = nativeStreamSec;
speedBasis = 'native_stream';
} else if (afterViewableSec >= 0.25 && outputTokens > 0) {
streamTokens = outputTokens;
streamDurationSec = afterViewableSec;
speedBasis = 'viewable_stream';
} else {
// Buffered tool call (e.g. run_command where server buffers JSON until completion):
// use totalDurationSec for decoding rate, and thinkingDurationSec (if < total) for TTFT
streamTokens = outputTokens;
streamDurationSec = totalDurationSec;
speedBasis = 'total_fallback';
if (!hasVisibleText && hasToolCalls && thinkingDurationSec > 0 && thinkingDurationSec >= totalDurationSec * 0.9) {
// Server merged thinking + buffered tool generation into thinkingDuration;
// estimate true TTFT from thinking token ratio
const thinkRatio = outputTokens > 0 ? Math.min(0.85, thinkingTokens / outputTokens) : 0.2;
ttftSec = Math.max(0.4, totalDurationSec * thinkRatio);
}
}
const totalTokPerSec =
totalDurationSec >= 0.12 && outputTokens > 0 ? outputTokens / totalDurationSec : 0;
const streamTokPerSec =
let streamTokPerSec =
streamDurationSec >= 0.12 && streamTokens > 0
? streamTokens / streamDurationSec
: totalTokPerSec;
// Guard against mixed text + buffered large tool call spikes
if (hasToolCalls && streamTokPerSec > 260 && totalTokPerSec > 0 && totalTokPerSec < 180) {
streamTokens = outputTokens;
streamDurationSec = totalDurationSec;
streamTokPerSec = totalTokPerSec;
speedBasis = 'total_fallback';
}
const estimatedContextTokens = Number(ctxWinMeta?.estimatedTokensUsed || 0);
const maxContextBudgetTokens = Number(ctxWinMeta?.maxContextTokens || 256000);
@@ -822,6 +840,10 @@ async function buildTelemetryPayloadInternal(
const totalPrompt = st.inputTokens + st.cacheReadTokens;
const cacheHitPct = totalPrompt > 0 ? (st.cacheReadTokens / totalPrompt) * 100 : 0;
const inCostUsd = (st.inputTokens / 1_000_000) * mInfo.pricing.input;
const cacheCostUsd = (st.cacheReadTokens / 1_000_000) * mInfo.pricing.cache;
const outCostUsd = (st.outputTokens / 1_000_000) * mInfo.pricing.output;
return {
...st,
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
@@ -831,6 +853,9 @@ async function buildTelemetryPayloadInternal(
ttftSec: +st.ttftSec.toFixed(1),
cacheHitPct: +cacheHitPct.toFixed(1),
costUsd: +costUsd.toFixed(4),
inCostUsd: +inCostUsd.toFixed(4),
cacheCostUsd: +cacheCostUsd.toFixed(4),
outCostUsd: +outCostUsd.toFixed(4),
contextTokens: st.inputTokens + st.cacheReadTokens + st.outputTokens,
};
});
@@ -1054,6 +1079,7 @@ async function buildTelemetryPayloadInternal(
latestTokPerSec: latestEnriched?.tokPerSec ?? 0,
latestTtftSec: latestEnriched?.ttftSec ?? 0,
avgTokPerSec: sessionAvgTokPerSec,
latestStepCostUsd: latestEnriched?.costUsd ?? 0,
sessionCostUsd: +sessionCostUsd.toFixed(2),
latestCacheHitPct,
sessionCacheHitPct,
@@ -1071,7 +1097,7 @@ async function buildTelemetryPayloadInternal(
thinkingTokens: ctxThinking,
responseTokens: ctxResponse,
},
recentSteps: enrichedActiveSteps.slice(-15).reverse(),
recentSteps: enrichedActiveSteps.slice().reverse(),
},
consumption: {
selectedRange: {
+9 -1
View File
@@ -742,7 +742,10 @@ body {
}
.table-scroll {
max-height: 420px;
overflow-y: auto;
overflow-x: auto;
border-radius: var(--radius-sm);
}
.data-table {
@@ -761,8 +764,13 @@ body {
}
.data-table th {
position: sticky;
top: 0;
z-index: 1;
background: var(--card, #ffffff);
color: var(--muted-foreground, #656d76);
font-weight: 500;
font-weight: 600;
box-shadow: 0 1px 0 var(--border, #eaeef2);
}
.settings-title {