mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
fix(metrics): separate answer estimates from request throughput
This commit is contained in:
@@ -7,10 +7,10 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side
|
||||
## ✨ 核心功能
|
||||
|
||||
- **⚡ 实时 `tok/s` 测速与会话均速**
|
||||
- 基于 Language Server `GetCascadeTrajectory` 纳秒级时间戳与 `plannerResponse.thinkingDuration` 思考耗时字段,精确剥离思考阶段,计算真实的**纯输出流速度 (`stream tok/s`)** 与 **含思考整体速度 (`total tok/s`)**。
|
||||
- 自动识别纯工具调用(Tool Call)步骤的缓冲机制,消除虚高脉冲尖峰。
|
||||
- 分开显示**正文阶段估算 (`stream`)** 与**请求整体吞吐 (`total`)**。正文估算只接受纯文本且阶段计时可用的步骤,显示 `≈`;整体吞吐使用含思考的输出 Token 除以请求总耗时。两者不互相回退,也不混算均速。
|
||||
- 工具调用和正文/工具混合输出无法独立计时,正文速度显示 `—`,仍可切换到整体吞吐查看。短于 0.5 秒或少于 50 个正文 Token 的样本保留估算,但不计正文均速;这些门槛只用于样本筛选,不会切换公式或限制 TPS。
|
||||
- **⏱️ 首字耗时 (TTFT) & 缓存命中率**
|
||||
- 实时显示每一步从发起请求到收到首个流式分块的响应时间(`TTFT`),以及 Prompt 缓存读取命中率(`cacheReadTokens` 占比)。
|
||||
- 显示原始 `timeToFirstToken`(可能先返回思考内容,非必然为答案首字);缺失显示 `—`,不再按思考 Token 比例推算。悬停可见会话平均 TTFT。同时显示 Prompt 缓存读取命中率(`cacheReadTokens` 占比)。
|
||||
- **📊 上下文窗口四色分段监控(默认对齐 `256k` 自动压缩阈值)**
|
||||
- 5 格平行四边形紧凑指示器(`▰▱▱▱▱`)+ 可展开的四色分段进度条:**缓存读取(蓝)** / **新增输入(橙)** / **思考输出(绿)** / **正文输出(青)**,默认以官方 `256k` 自动压缩水位线为基准,支持一键切换 `256k(压缩)` / `200k` / `1M` / `2M`。
|
||||
- **🔋 官方 5h 限额 & 每周限额零延迟同步(`{"forceRefresh": true}`)**
|
||||
@@ -101,7 +101,7 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side
|
||||
| :--- | :--- |
|
||||
| **顶部会话下拉框** | 默认选中 `⚡ 自动跟随`,自动监控当前最新活跃的对话;也可手动切换到任意历史会话(自动扫描 `~/.gemini/antigravity/conversations/` 全量历史记录)查看当时的测速与消耗。 |
|
||||
| **顶部 `↻` 按钮** | 点击带旋转动画与 `同步中…` $\rightarrow$ `✓ 已刷新` 状态反馈,向 Language Server 发送 `{"forceRefresh": true}` 绕过内部配额缓存,实时拉取云端最新配额与轨迹数据。 |
|
||||
| **点击 `0.0 tok/s` 速度数字** | 一键在 **「输出流测速」**(扣除思考耗时的纯解码速度)与 **「整体测速(含思考)」**(端到端整体吞吐速度)之间切换。 |
|
||||
| **点击 `0.0 tok/s` 速度数字** | 一键在 **「正文估算」**(仅有效纯文本样本)与 **「整体吞吐」**(含等待与思考的请求吞吐)之间切换。 |
|
||||
| **点击 `上下文` 或 `上下文窗口 ›`** | 展开/收起四色 Token 构成细分(缓存读取、新增输入、思考输出、正文输出),并可切换 `256k(压缩)` / `200k` / `1M` / `2M` 窗口上限基准。 |
|
||||
| **消耗额度统计 & 时间筛选栏** | 实时对比 **💬 本对话消耗** 与 **👤 本机累计消耗(本机全会话)**;点击右侧 `全部` / `近5h` / `今日` / `本周` / `30天` 可 **0 延迟瞬时切换**统计时间段,点击 `自定义` 可按任意精确到分钟的起止时间段过滤。 |
|
||||
| **点击 `查看详细明细`** | 展开底部数据表,可切换查看 **「当前会话步骤测速」**(悬停某步可看思考、输出耗时与单步精确美元费用)和 **「按模型汇总 (跟随当前所选时间范围)」**。 |
|
||||
@@ -154,3 +154,17 @@ git -C ~/.gemini/config/plugins/usage-monitor pull
|
||||
- **0 额度消耗**:所有测速与配额查询均通过本地 Language Server 的状态与轨迹接口完成,**不调用大模型推理,不消耗任何 Token、5h 额度或积分**。
|
||||
- **极低资源占用**:会话空闲时不触发重复轨迹解析或磁盘写入,CPU 占用接近 `0%`。
|
||||
- **纯本地运行**:所有统计缓存仅保存在本机 `~/.gemini/antigravity/sidecar_data/usage-monitor/` 目录下,不向任何第三方服务器发送数据。
|
||||
|
||||
|
||||
## 测速试用分支说明
|
||||
|
||||
本地试用分支:`codex/tps-metrics-trial`。该版本不把汇总日志称为服务端真实解码测速。
|
||||
|
||||
- **正文估算**:有思考 Token 时,需要记录的思考阶段时长,并用正文 Token /(请求总时长 − 思考阶段时长)估算;没有思考且正文 Token 等于总输出时,可采用原始流时长。计时来源随每步保存。没有可靠阶段起点的步骤显示未知。
|
||||
- **整体吞吐**:输出 Token(含思考)/ 已完成请求的总时长。不包含调用之间的用户停顿或外部工具执行空档。未完成请求或非法时间显示未知。
|
||||
- **均速**:有效样本 Token 合计 / 有效样本时长合计,展示有效/普通调用样本数;自动压缩仍计入费用,但不计两种均速。短样本筛选会影响样本覆盖率,均速只代表纳入的样本。
|
||||
- **首 Token**:保留原始字段,不使用 `viewableAt` 或 Token 比例替换。`viewableAt` 的延迟仅作为单独诊断字段保存。
|
||||
- **旧缓存**:版本升级为 `v6-speed-metrics`,从原始轨迹重新读取。读取失败时保留用量账目,旧版推算的速度和延迟显示未知。
|
||||
- **使用**:在 Antigravity 的 Customizations → Installed 中关闭再开启本插件,然后重新打开侧栏,以确保后端与页面一起加载新版本。
|
||||
- **退回原版**:先保存试用分支的本地改动,再在插件目录执行 `git switch main`,关闭再开启本插件。原版会按自己的缓存版本重新读取轨迹。
|
||||
- **验证**:在 `sidecars/panel` 目录执行 `npm test`。测试不调用模型、真实配额服务或修改用户统计缓存。私有会话回放和浏览器验收结果不包含在仓库测试夹具中。
|
||||
|
||||
+44
-12
@@ -18,6 +18,27 @@ function escapeHtml(str) {
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function formatMetric(value, unit = '', estimated = false) {
|
||||
return Number.isFinite(value) ? `${estimated ? '≈' : ''}${value.toFixed(1)}${unit}` : '—';
|
||||
}
|
||||
|
||||
function speedReasonText(reason) {
|
||||
return ({
|
||||
compaction: '自动压缩不计测速',
|
||||
incomplete_or_invalid_timing: '未完成或计时缺失',
|
||||
tool_timing_unavailable: '工具输出无法独立计时',
|
||||
no_answer_text: '无正文',
|
||||
token_breakdown_unavailable: '输出 Token 构成不明',
|
||||
answer_start_unavailable: '缺少正文起点',
|
||||
short_sample: '短样本,不计均速',
|
||||
legacy_cache: '旧缓存,等待重新读取',
|
||||
})[reason] || '';
|
||||
}
|
||||
|
||||
function sampleSummary(summary) {
|
||||
return `${summary?.sampleCount || 0}/${(summary?.sampleCount || 0) + (summary?.excludedCount || 0)} 步`;
|
||||
}
|
||||
|
||||
function formatTokens(num) {
|
||||
const n = Number(num || 0);
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
@@ -135,14 +156,15 @@ function renderAllPools(pools, activeFamily) {
|
||||
let lastStepsRenderSig = '';
|
||||
let lastModelsRenderSig = '';
|
||||
|
||||
function renderTables(activeConv, modelBreakdown) {
|
||||
function renderTables(activeConv, modelBreakdown, speedMode = 'stream') {
|
||||
const estimated = speedMode !== 'total';
|
||||
const steps = activeConv.recentSteps || [];
|
||||
const tabStepsBtn = $('tab-steps-btn');
|
||||
if (tabStepsBtn) {
|
||||
tabStepsBtn.textContent = `当前会话步骤测速与计费 (${steps.length}步)`;
|
||||
}
|
||||
|
||||
const stepsSig = `${activeConv.cascadeId || ''}:${steps.length}:${steps[0]?.stepIndex ?? -1}:${steps[0]?.tokPerSec ?? 0}:${steps[0]?.costUsd ?? 0}`;
|
||||
const stepsSig = `${activeConv.cascadeId || ''}:${speedMode}:${JSON.stringify(steps)}`;
|
||||
if (stepsSig !== lastStepsRenderSig) {
|
||||
lastStepsRenderSig = stepsSig;
|
||||
const stepsTbody = $('steps-tbody');
|
||||
@@ -156,6 +178,8 @@ function renderTables(activeConv, modelBreakdown) {
|
||||
? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | `
|
||||
: '';
|
||||
const compTag = st.isCompactionStep ? ' [压缩汇总步]' : '';
|
||||
const reason = speedReasonText(st.selectedSpeedReason);
|
||||
const timingSource = st.responseTimingSource === 'post_thinking_estimate' ? '总时长减记录的思考阶段(估算)' : st.responseTimingSource === 'native_text_stream' ? '无思考正文的原始流时长(估算)' : '不可用';
|
||||
const stepCostVal = Number(st.costUsd || 0);
|
||||
const stepCostDisplay = stepCostVal >= 1 ? `$${stepCostVal.toFixed(2)}` : `$${stepCostVal.toFixed(3)}`;
|
||||
const costStyle =
|
||||
@@ -164,12 +188,12 @@ function renderTables(activeConv, modelBreakdown) {
|
||||
: '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.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 | 正文阶段: ${formatMetric(st.streamDurationSec, 's')} (${timingSource}) | 请求总耗时: ${formatMetric(st.totalDurationSec, 's')} | 整体吞吐: ${formatMetric(st.totalTokPerSec, ' tok/s')} | ${reason}`;
|
||||
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><strong style="color: var(--speed-accent)">${formatMetric(st.tokPerSec, ' tok/s', estimated)}</strong><div class="speed-detail muted">${escapeHtml(reason)}</div></td>
|
||||
<td>${formatMetric(st.ttftSec, '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>
|
||||
@@ -184,7 +208,7 @@ function renderTables(activeConv, modelBreakdown) {
|
||||
}
|
||||
|
||||
const models = modelBreakdown || [];
|
||||
const modelsSig = models.map((m) => `${m.modelId}:${m.calls}:${m.totalTokens}:${m.avgTokPerSec}`).join('|');
|
||||
const modelsSig = `${speedMode}:${JSON.stringify(models)}`;
|
||||
if (modelsSig !== lastModelsRenderSig) {
|
||||
lastModelsRenderSig = modelsSig;
|
||||
const modelsTbody = $('models-tbody');
|
||||
@@ -195,7 +219,7 @@ function renderTables(activeConv, modelBreakdown) {
|
||||
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>${formatMetric(m.avgTokPerSec, ' tok/s', estimated)}<div class="speed-detail muted">有效 ${sampleSummary(m.speedSummary)}</div></td>
|
||||
<td>${formatTokens(m.totalTokens)}</td>
|
||||
<td>${pricePrefix}${Number(m.costUsd).toFixed(2)}</td>
|
||||
`;
|
||||
@@ -296,9 +320,17 @@ function applyTelemetryToDom(data) {
|
||||
}
|
||||
|
||||
// 2. Status strip metrics
|
||||
$('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 estimatedSpeed = settings.speedMode !== 'total';
|
||||
$('tok-per-sec').textContent = formatMetric(active.latestTokPerSec, ' tok/s', estimatedSpeed);
|
||||
$('speed-mode-toggle').title = `最新一步:${speedReasonText(active.latestSpeedReason) || (estimatedSpeed ? '正文阶段估算' : '请求整体吞吐')};点击切换口径`;
|
||||
$('ttft-value').textContent = formatMetric(active.latestTtftSec, 's');
|
||||
$('ttft-value').title = `原始首 Token 延迟,可能先返回思考内容;会话平均 ${formatMetric(active.ttftSummary?.avgSec, 's')}(${active.ttftSummary?.sampleCount || 0} 步)`;
|
||||
$('avg-speed-value').textContent = formatMetric(active.avgTokPerSec, '', estimatedSpeed);
|
||||
$('speed-sample-count').textContent = `有效 ${sampleSummary(active.speedSummary)}`;
|
||||
$('speed-sample-count').title = Object.entries(active.speedSummary?.excludedReasons || {}).map(([reason, count]) => `${speedReasonText(reason)}:${count} 步`).join(';') || '全部有效;自动压缩单独排除';
|
||||
$('speed-method-note').textContent = estimatedSpeed
|
||||
? '正文阶段估算;工具混合输出和起点不明的步骤不计均速,短样本单列。'
|
||||
: '含思考的输出 Token ÷ 请求总耗时;不含调用之间的空闲和外部工具执行时间。';
|
||||
const latestStepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0);
|
||||
if ($('step-cost-value')) {
|
||||
$('step-cost-value').textContent = `$${latestStepCost.toFixed(3)}`;
|
||||
@@ -311,7 +343,7 @@ function applyTelemetryToDom(data) {
|
||||
$('active-model-short').title = active.activeModelLabel || '';
|
||||
$('today-tokens').textContent = formatTokens(quotas.today?.tokens || 0);
|
||||
$('today-cost').textContent = `$${Number(quotas.today?.costUsd || 0).toFixed(2)}`;
|
||||
$('speed-mode-badge').textContent = settings.speedMode === 'total' ? '整体测速(含思考)' : '输出流测速';
|
||||
$('speed-mode-badge').textContent = settings.speedMode === 'total' ? '整体吞吐' : '正文估算';
|
||||
|
||||
// 3. Context Window Popover Section
|
||||
const limitTokens = ctx.limitTokens || 256000;
|
||||
@@ -390,7 +422,7 @@ function applyTelemetryToDom(data) {
|
||||
$('setting-weekly-tokens').value = settings.weeklyTokenBudget || 150000000;
|
||||
$('setting-weekly-cost').value = settings.weeklyCostBudget || 100;
|
||||
|
||||
renderTables(active, data.modelBreakdown);
|
||||
renderTables(active, data.modelBreakdown, settings.speedMode);
|
||||
}
|
||||
|
||||
let manualRefreshFeedbackTimer = null;
|
||||
|
||||
@@ -26,12 +26,12 @@
|
||||
<!-- Compact Speed & Token Status Strip (1:1 replica of the left status bar above input) -->
|
||||
<section class="status-strip-card" aria-label="实时测速与消耗状态栏">
|
||||
<div class="strip-row strip-row-main">
|
||||
<span class="speed-group" title="点击切换「纯输出流速度」与「含思考整体速度」" id="speed-mode-toggle">
|
||||
<span class="speed-group" title="最新一步;点击切换「正文估算」与「整体吞吐」" id="speed-mode-toggle">
|
||||
<span id="speed-dot" class="speed-dot"></span>
|
||||
<strong id="tok-per-sec" class="speed-value">0.0 tok/s</strong>
|
||||
<strong id="tok-per-sec" class="speed-value">—</strong>
|
||||
</span>
|
||||
<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="metric-item">首Token <strong id="ttft-value">—</strong></span>
|
||||
<span class="metric-item">均速 <strong id="avg-speed-value">—</strong> <small id="speed-sample-count" class="muted">有效 0/0 步</small></span>
|
||||
<span class="strip-divider">|</span>
|
||||
<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>
|
||||
@@ -50,8 +50,9 @@
|
||||
<span class="today-summary">
|
||||
今日 <strong id="today-tokens">0</strong> · ≈<strong id="today-cost">$0.00</strong>
|
||||
</span>
|
||||
<span class="speed-mode-label muted" id="speed-mode-badge">输出流测速</span>
|
||||
<span class="speed-mode-label muted" id="speed-mode-badge">正文估算</span>
|
||||
</div>
|
||||
<div id="speed-method-note" class="speed-method-note muted">正文阶段估算;计时不明的步骤不计均速。</div>
|
||||
</section>
|
||||
|
||||
<!-- Quota & Context Popover Card (1:1 replica of the right popover card in screenshot) -->
|
||||
@@ -210,7 +211,7 @@
|
||||
<th>步</th>
|
||||
<th>模型</th>
|
||||
<th>速度</th>
|
||||
<th>首字</th>
|
||||
<th>首Token</th>
|
||||
<th>上下文/输出</th>
|
||||
<th>缓存</th>
|
||||
<th>消费</th>
|
||||
@@ -246,8 +247,8 @@
|
||||
<label class="field-label">
|
||||
<span>tok/s 测速口径</span>
|
||||
<select id="setting-speed-mode">
|
||||
<option value="stream">纯输出流速度 (扣除首字思考时间)</option>
|
||||
<option value="total">整体生成速度 (含首字思考总耗时)</option>
|
||||
<option value="stream">正文阶段估算 (仅有效纯文本样本)</option>
|
||||
<option value="total">请求整体吞吐 (含等待与思考)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field-label">
|
||||
|
||||
+31
-192
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||
import { extractModelSteps, parseIsoMs, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft, createSpeedAccumulator, accumulateSpeed, finishSpeed } from './speed-metrics.mjs';
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data');
|
||||
@@ -19,7 +20,7 @@ const DEFAULT_SETTINGS = {
|
||||
weeklyTokenBudget: 150000000, // 150M tokens default custom weekly target
|
||||
weeklyCostBudget: 100, // $100 default custom weekly cost target (matches Ultra weekly pool)
|
||||
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
||||
speedMode: 'stream', // 'stream' (streamTokens / streamTime) | 'total' (outputTokens / totalTime)
|
||||
speedMode: 'stream', // Answer-phase estimate, or request-level throughput; never mixed.
|
||||
};
|
||||
|
||||
// Official API pricing in USD per 1M tokens (Input, CacheRead, Output incl. Thinking)
|
||||
@@ -58,8 +59,10 @@ const PLACEHOLDER_MAP = {
|
||||
};
|
||||
|
||||
// In-memory cache of trajectory step usage: cascadeId -> { signature, steps }
|
||||
const CACHE_SCHEMA_VERSION = 'v5';
|
||||
let trajectoryCache = loadJson(CACHE_FILE, {});
|
||||
const CACHE_SCHEMA_VERSION = 'v6-speed-metrics';
|
||||
let trajectoryCache = Object.fromEntries(Object.entries(loadJson(CACHE_FILE, {})).map(([id, entry]) => [
|
||||
id, { ...entry, steps: (entry.steps || []).map(normalizeCachedStep) },
|
||||
]));
|
||||
const inFlightRequests = new Map();
|
||||
let quotaSummaryCache = { ts: 0, data: null, error: null };
|
||||
|
||||
@@ -85,21 +88,8 @@ function loadSettings() {
|
||||
return { ...DEFAULT_SETTINGS, ...loadJson(SETTINGS_FILE, {}) };
|
||||
}
|
||||
|
||||
function parseIsoMs(isoStr) {
|
||||
if (!isoStr || typeof isoStr !== 'string') return 0;
|
||||
const baseMs = Date.parse(isoStr);
|
||||
if (!baseMs || Number.isNaN(baseMs)) return 0;
|
||||
const match = isoStr.match(/\.(\d+)Z$/);
|
||||
if (!match) return baseMs;
|
||||
const fracSec = Number(`0.${match[1]}`);
|
||||
const wholeSecMs = Math.floor(baseMs / 1000) * 1000;
|
||||
return wholeSecMs + fracSec * 1000;
|
||||
}
|
||||
|
||||
function parseDurationSec(durStr) {
|
||||
if (!durStr || typeof durStr !== 'string') return 0;
|
||||
const n = Number.parseFloat(durStr);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
function roundMetric(value) {
|
||||
return Number.isFinite(value) ? +value.toFixed(1) : null;
|
||||
}
|
||||
|
||||
async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
||||
@@ -240,145 +230,6 @@ function computeStepCost(step, pricing) {
|
||||
return inCost + cacheCost + outCost;
|
||||
}
|
||||
|
||||
function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const genMetaByStep = new Map();
|
||||
for (const gm of generatorMetadata || []) {
|
||||
const indices = gm?.stepIndices || [];
|
||||
for (const idx of indices) {
|
||||
genMetaByStep.set(Number(idx), gm);
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = [];
|
||||
rawSteps.forEach((s, idx) => {
|
||||
const m = s?.metadata;
|
||||
const isCompactionStep = s?.type === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
const u = m?.modelUsage || (m?.retryInfos?.[0]?.usage ?? null);
|
||||
if (!u) return;
|
||||
|
||||
const stepIndex = s?.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? idx;
|
||||
const gm = m?.generatorMetadata?.[0] || genMetaByStep.get(Number(stepIndex)) || genMetaByStep.get(idx) || null;
|
||||
const chatModel = gm?.chatModel || null;
|
||||
const ctxWinMeta = chatModel?.chatStartMetadata?.contextWindowMetadata || null;
|
||||
|
||||
const p = s?.plannerResponse || {};
|
||||
const inputTokens = Number(u.inputTokens || 0);
|
||||
const cacheReadTokens = Number(u.cacheReadTokens || 0);
|
||||
const outputTokens = Number(u.outputTokens || 0);
|
||||
const thinkingTokens = Number(p.thinkingTokens || u.thinkingOutputTokens || chatModel?.usage?.thinkingOutputTokens || 0);
|
||||
const responseTokens = Number(
|
||||
p.responseTokens || u.responseOutputTokens || chatModel?.usage?.responseOutputTokens || Math.max(0, outputTokens - thinkingTokens)
|
||||
);
|
||||
|
||||
const createdAtMs = parseIsoMs(m.createdAt);
|
||||
const viewableAtMs = parseIsoMs(m.viewableAt || m.createdAt) || createdAtMs;
|
||||
const finishedAtMs =
|
||||
parseIsoMs(m.finishedGeneratingAt || m.completedAt || m.viewableAt || m.createdAt) ||
|
||||
viewableAtMs;
|
||||
|
||||
const rawViewableSec =
|
||||
createdAtMs > 0 && viewableAtMs >= createdAtMs
|
||||
? Math.max(0.05, (viewableAtMs - createdAtMs) / 1000)
|
||||
: 0;
|
||||
const afterViewableSec =
|
||||
viewableAtMs > 0 && finishedAtMs > viewableAtMs
|
||||
? (finishedAtMs - viewableAtMs) / 1000
|
||||
: 0;
|
||||
const totalDurationSec =
|
||||
createdAtMs > 0 && finishedAtMs > createdAtMs
|
||||
? (finishedAtMs - createdAtMs) / 1000
|
||||
: 0;
|
||||
|
||||
const nativeTtftSec = parseDurationSec(chatModel?.timeToFirstToken);
|
||||
const nativeStreamSec = parseDurationSec(chatModel?.streamingDuration);
|
||||
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;
|
||||
|
||||
let ttftSec = nativeTtftSec > 0 ? nativeTtftSec : rawViewableSec;
|
||||
let streamTokens = outputTokens;
|
||||
let streamDurationSec = 0;
|
||||
let speedBasis = 'model_stream';
|
||||
|
||||
const postThinkingSec =
|
||||
thinkingDurationSec > 0 && totalDurationSec > thinkingDurationSec
|
||||
? totalDurationSec - thinkingDurationSec
|
||||
: afterViewableSec;
|
||||
|
||||
if (hasVisibleText && responseTokens > 0 && postThinkingSec >= 0.35) {
|
||||
streamTokens = responseTokens;
|
||||
streamDurationSec = postThinkingSec;
|
||||
speedBasis = 'response_stream';
|
||||
} 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 {
|
||||
// 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;
|
||||
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);
|
||||
|
||||
parsed.push({
|
||||
stepIndex,
|
||||
isCompactionStep,
|
||||
modelKey: u.model || chatModel?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418',
|
||||
apiProvider: u.apiProvider || chatModel?.usage?.apiProvider || '',
|
||||
createdAt: m.createdAt || null,
|
||||
createdAtMs: Math.floor(createdAtMs),
|
||||
hasVisibleText,
|
||||
inputTokens,
|
||||
cacheReadTokens,
|
||||
outputTokens,
|
||||
thinkingTokens,
|
||||
responseTokens,
|
||||
streamTokens,
|
||||
speedBasis,
|
||||
estimatedContextTokens,
|
||||
maxContextBudgetTokens,
|
||||
thinkingDurationSec: +thinkingDurationSec.toFixed(3),
|
||||
ttftSec: +ttftSec.toFixed(3),
|
||||
streamDurationSec: +streamDurationSec.toFixed(3),
|
||||
totalDurationSec: +totalDurationSec.toFixed(3),
|
||||
streamTokPerSec,
|
||||
totalTokPerSec,
|
||||
});
|
||||
});
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function getStartOfLocalDayMs(now = new Date()) {
|
||||
const d = new Date(now);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
@@ -762,7 +613,9 @@ async function buildTelemetryPayloadInternal(
|
||||
const prev = trajectoryCache[conv.cascadeId];
|
||||
try {
|
||||
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
||||
const rawSteps = trajRes?.trajectory?.steps || [];
|
||||
if (!Array.isArray(trajRes?.trajectory?.steps)) throw new Error('Trajectory steps unavailable');
|
||||
const rawSteps = trajRes.trajectory.steps;
|
||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) throw new Error('Incomplete trajectory; retaining cached usage');
|
||||
const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||
const prevLast = prev?.steps?.[prev.steps.length - 1];
|
||||
@@ -810,8 +663,9 @@ async function buildTelemetryPayloadInternal(
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
|
||||
const useStreamSpeed = settings.speedMode !== 'total';
|
||||
let sessionSpeedNumeratorTokens = 0;
|
||||
let sessionSpeedDenominatorSec = 0;
|
||||
const speedMode = useStreamSpeed ? 'stream' : 'total';
|
||||
const sessionSpeed = summarizeSpeed(activeSteps, speedMode);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
let sessionCostUsd = 0;
|
||||
let sessionInputTokens = 0;
|
||||
let sessionCacheReadTokens = 0;
|
||||
@@ -819,24 +673,13 @@ async function buildTelemetryPayloadInternal(
|
||||
const enrichedActiveSteps = activeSteps.map((st) => {
|
||||
const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider);
|
||||
const costUsd = computeStepCost(st, mInfo.pricing);
|
||||
const stepStreamTokens = st.streamTokens ?? st.outputTokens;
|
||||
const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec;
|
||||
|
||||
if (!st.isCompactionStep) {
|
||||
if (useStreamSpeed) {
|
||||
sessionSpeedNumeratorTokens += stepStreamTokens;
|
||||
sessionSpeedDenominatorSec += stepStreamSec;
|
||||
} else {
|
||||
sessionSpeedNumeratorTokens += st.outputTokens;
|
||||
sessionSpeedDenominatorSec += st.totalDurationSec;
|
||||
}
|
||||
}
|
||||
const metric = speedMetric(st, speedMode);
|
||||
|
||||
sessionCostUsd += costUsd;
|
||||
sessionInputTokens += st.inputTokens;
|
||||
sessionCacheReadTokens += st.cacheReadTokens;
|
||||
|
||||
const tokPerSec = useStreamSpeed ? st.streamTokPerSec : st.totalTokPerSec;
|
||||
const tokPerSec = metric.value;
|
||||
const totalPrompt = st.inputTokens + st.cacheReadTokens;
|
||||
const cacheHitPct = totalPrompt > 0 ? (st.cacheReadTokens / totalPrompt) * 100 : 0;
|
||||
|
||||
@@ -849,8 +692,9 @@ async function buildTelemetryPayloadInternal(
|
||||
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
|
||||
modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
|
||||
family: mInfo.family,
|
||||
tokPerSec: +tokPerSec.toFixed(1),
|
||||
ttftSec: +st.ttftSec.toFixed(1),
|
||||
tokPerSec: roundMetric(tokPerSec),
|
||||
selectedSpeedReason: metric.reason,
|
||||
ttftSec: st.nativeTtftSec,
|
||||
cacheHitPct: +cacheHitPct.toFixed(1),
|
||||
costUsd: +costUsd.toFixed(4),
|
||||
inCostUsd: +inCostUsd.toFixed(4),
|
||||
@@ -863,10 +707,7 @@ async function buildTelemetryPayloadInternal(
|
||||
const latestEnriched =
|
||||
enrichedActiveSteps.length > 0 ? enrichedActiveSteps[enrichedActiveSteps.length - 1] : null;
|
||||
|
||||
const sessionAvgTokPerSec =
|
||||
sessionSpeedDenominatorSec > 0.1
|
||||
? +(sessionSpeedNumeratorTokens / sessionSpeedDenominatorSec).toFixed(1)
|
||||
: latestEnriched?.tokPerSec || 0;
|
||||
const sessionAvgTokPerSec = roundMetric(sessionSpeed.avgTokPerSec);
|
||||
|
||||
// Context breakdown from the latest step
|
||||
const ctxCached = latestEnriched?.cacheReadTokens || 0;
|
||||
@@ -975,24 +816,20 @@ async function buildTelemetryPayloadInternal(
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
speedTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
totalDurationSec: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(mInfo.label);
|
||||
const stepStreamTokens = st.streamTokens ?? st.outputTokens;
|
||||
const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec;
|
||||
accumulateSpeed(agg.speedAccumulator, st, speedMode);
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += st.inputTokens;
|
||||
agg.cacheReadTokens += st.cacheReadTokens;
|
||||
agg.outputTokens += st.outputTokens;
|
||||
agg.speedTokens += useStreamSpeed ? stepStreamTokens : st.outputTokens;
|
||||
agg.totalTokens += stepTotalTokens;
|
||||
agg.costUsd += stepCost;
|
||||
agg.totalDurationSec += useStreamSpeed ? stepStreamSec : st.totalDurationSec;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1076,9 +913,13 @@ async function buildTelemetryPayloadInternal(
|
||||
isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? 0,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? 0,
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
latestTotalTokPerSec: roundMetric(speedMetric(latestEnriched || {}, 'total').value),
|
||||
avgTokPerSec: sessionAvgTokPerSec,
|
||||
speedSummary: sessionSpeed,
|
||||
ttftSummary: sessionTtft,
|
||||
latestStepCostUsd: latestEnriched?.costUsd ?? 0,
|
||||
sessionCostUsd: +sessionCostUsd.toFixed(2),
|
||||
latestCacheHitPct,
|
||||
@@ -1153,13 +994,11 @@ async function buildTelemetryPayloadInternal(
|
||||
},
|
||||
modelBreakdown: Array.from(perModelStats.values())
|
||||
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
||||
.map((m) => ({
|
||||
.map(({ speedAccumulator, ...m }) => ({
|
||||
...m,
|
||||
costUsd: +m.costUsd.toFixed(3),
|
||||
avgTokPerSec:
|
||||
m.totalDurationSec > 0.1
|
||||
? +((m.speedTokens ?? m.outputTokens) / m.totalDurationSec).toFixed(1)
|
||||
: 0,
|
||||
avgTokPerSec: roundMetric(finishSpeed(speedAccumulator).avgTokPerSec),
|
||||
speedSummary: finishSpeed(speedAccumulator),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,5 +3,8 @@
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor."
|
||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||
"scripts": {
|
||||
"test": "node --test test/*.test.mjs"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
// Client-observed timing estimates, not server-side decoding benchmarks.
|
||||
export const MEASUREMENT_VERSION = 1;
|
||||
export const MIN_MEAN_RESPONSE_TOKENS = 50;
|
||||
export const MIN_MEAN_RESPONSE_SECONDS = 0.5;
|
||||
|
||||
export function parseIsoMs(value) {
|
||||
if (typeof value !== 'string' || !value) return 0;
|
||||
const ms = Date.parse(value);
|
||||
if (!Number.isFinite(ms)) return 0;
|
||||
const fraction = value.match(/\.(\d+)Z$/);
|
||||
return fraction ? Math.floor(ms / 1000) * 1000 + Number(`0.${fraction[1]}`) * 1000 : ms;
|
||||
}
|
||||
|
||||
function duration(value) {
|
||||
if (typeof value !== 'string' || !/^\d+(?:\.\d+)?s$/.test(value)) return null;
|
||||
const n = Number(value.slice(0, -1));
|
||||
return Number.isFinite(n) && n >= 0 ? n : null;
|
||||
}
|
||||
|
||||
function validCount(value) {
|
||||
return value !== undefined && value !== null && value !== '' &&
|
||||
Number.isSafeInteger(Number(value)) && Number(value) >= 0;
|
||||
}
|
||||
|
||||
function elapsed(start, end) {
|
||||
return start > 0 && end >= start ? (end - start) / 1000 : null;
|
||||
}
|
||||
|
||||
export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const genByStep = new Map();
|
||||
for (const gm of generatorMetadata || []) {
|
||||
for (const index of gm?.stepIndices || []) genByStep.set(Number(index), gm);
|
||||
}
|
||||
const result = [];
|
||||
rawSteps.forEach((s, index) => {
|
||||
const m = s?.metadata;
|
||||
const u = m?.modelUsage || m?.retryInfos?.[0]?.usage;
|
||||
if (!u) return;
|
||||
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
||||
const gm = m.generatorMetadata?.[0] || genByStep.get(Number(stepIndex)) || genByStep.get(index);
|
||||
const chat = gm?.chatModel;
|
||||
const p = s.plannerResponse || {};
|
||||
const isCompactionStep = s.type === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
const inputTokens = Number(u.inputTokens || 0);
|
||||
const cacheReadTokens = Number(u.cacheReadTokens || 0);
|
||||
const outputTokens = Number(u.outputTokens || 0);
|
||||
const rawThinking = p.thinkingTokens ?? u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens;
|
||||
const thinkingTokens = Number(rawThinking ?? 0);
|
||||
const rawResponse = p.responseTokens ?? u.responseOutputTokens ?? chat?.usage?.responseOutputTokens;
|
||||
const responseTokens = Number(rawResponse ?? Math.max(0, outputTokens - thinkingTokens));
|
||||
const breakdownKnown = validCount(rawResponse) || validCount(rawThinking);
|
||||
const hasVisibleText = String(p.modifiedResponse || p.response || '').trim().length > 0;
|
||||
const hasToolCalls = Array.isArray(p.toolCalls) && p.toolCalls.length > 0;
|
||||
const start = parseIsoMs(m.createdAt);
|
||||
const end = parseIsoMs(m.finishedGeneratingAt || m.completedAt);
|
||||
const explicitlyIncomplete = Boolean(s.status && s.status !== 'CORTEX_STEP_STATUS_DONE');
|
||||
const complete = !explicitlyIncomplete && start > 0 && end >= start;
|
||||
const totalDurationSec = complete ? elapsed(start, end) : null;
|
||||
const viewableDelaySec = elapsed(start, parseIsoMs(m.viewableAt));
|
||||
const nativeTtftSec = duration(chat?.timeToFirstToken);
|
||||
const nativeStreamSec = duration(chat?.streamingDuration);
|
||||
const thinkingDurationSec = duration(p.thinkingDuration);
|
||||
const totalTokPerSec = complete && totalDurationSec > 0 && validCount(u.outputTokens)
|
||||
? outputTokens / totalDurationSec : null;
|
||||
|
||||
let streamDurationSec = null;
|
||||
let responseTimingSource = null;
|
||||
let speedReason = null;
|
||||
if (isCompactionStep) speedReason = 'compaction';
|
||||
else if (!complete) speedReason = 'incomplete_or_invalid_timing';
|
||||
else if (hasToolCalls) speedReason = 'tool_timing_unavailable';
|
||||
else if (!hasVisibleText) speedReason = 'no_answer_text';
|
||||
else if (!breakdownKnown || !validCount(u.outputTokens) || !validCount(responseTokens) ||
|
||||
!validCount(thinkingTokens) || responseTokens <= 0 || responseTokens + thinkingTokens > outputTokens) {
|
||||
speedReason = 'token_breakdown_unavailable';
|
||||
} else if (thinkingTokens > 0) {
|
||||
if (thinkingDurationSec > 0 && thinkingDurationSec < totalDurationSec) {
|
||||
streamDurationSec = totalDurationSec - thinkingDurationSec;
|
||||
responseTimingSource = 'post_thinking_estimate';
|
||||
} else speedReason = 'answer_start_unavailable';
|
||||
} else if (responseTokens === outputTokens && nativeStreamSec > 0 && nativeStreamSec <= totalDurationSec + 0.001) {
|
||||
streamDurationSec = nativeStreamSec;
|
||||
responseTimingSource = 'native_text_stream';
|
||||
} else speedReason = 'answer_start_unavailable';
|
||||
|
||||
const streamTokPerSec = streamDurationSec > 0 ? responseTokens / streamDurationSec : null;
|
||||
// Short samples retain their estimate. The threshold changes eligibility only,
|
||||
// never the formula or the displayed metric. There is no TPS-based clipping.
|
||||
const responseShortSample = streamTokPerSec !== null &&
|
||||
(responseTokens < MIN_MEAN_RESPONSE_TOKENS || streamDurationSec < MIN_MEAN_RESPONSE_SECONDS);
|
||||
if (responseShortSample) speedReason = 'short_sample';
|
||||
const context = chat?.chatStartMetadata?.contextWindowMetadata;
|
||||
result.push({
|
||||
stepIndex, isCompactionStep,
|
||||
modelKey: u.model || chat?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418',
|
||||
apiProvider: u.apiProvider || chat?.usage?.apiProvider || '',
|
||||
createdAt: m.createdAt || null, createdAtMs: Math.floor(start),
|
||||
hasVisibleText, hasToolCalls,
|
||||
inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens,
|
||||
estimatedContextTokens: Number(context?.estimatedTokensUsed || 0),
|
||||
maxContextBudgetTokens: Number(context?.maxContextTokens || 256000),
|
||||
measurementVersion: MEASUREMENT_VERSION,
|
||||
isComplete: complete, nativeTtftSec, nativeStreamSec, viewableDelaySec,
|
||||
ttftSec: nativeTtftSec, ttftSource: nativeTtftSec === null ? 'unavailable' : 'native',
|
||||
thinkingDurationSec, totalDurationSec, streamDurationSec,
|
||||
streamTokens: streamTokPerSec === null ? null : responseTokens,
|
||||
totalTokPerSec, streamTokPerSec,
|
||||
speedBasis: streamTokPerSec === null ? 'unavailable' : 'response_estimate',
|
||||
responseTimingSource, responseShortSample,
|
||||
responseSampleEligible: streamTokPerSec !== null && !responseShortSample,
|
||||
speedReason,
|
||||
});
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
export function normalizeCachedStep(step) {
|
||||
if (step.measurementVersion === MEASUREMENT_VERSION) return step;
|
||||
// v5 did not retain the original TTFT or trustworthy phase boundaries. Keep
|
||||
// accounting, but do not reconstruct measurements from its derived values.
|
||||
return {
|
||||
...step, measurementVersion: null, isComplete: false,
|
||||
nativeTtftSec: null, nativeStreamSec: null, viewableDelaySec: null,
|
||||
ttftSec: null, ttftSource: 'unavailable', thinkingDurationSec: null,
|
||||
totalDurationSec: null, streamDurationSec: null, streamTokens: null,
|
||||
totalTokPerSec: null, streamTokPerSec: null, speedBasis: 'unavailable',
|
||||
responseTimingSource: null, responseShortSample: false,
|
||||
responseSampleEligible: false, speedReason: 'legacy_cache',
|
||||
};
|
||||
}
|
||||
|
||||
export function speedMetric(step, mode) {
|
||||
const missing = (reason) => ({ value: null, tokens: 0, seconds: 0, eligible: false, reason });
|
||||
if (step.measurementVersion !== MEASUREMENT_VERSION) return missing('legacy_cache');
|
||||
if (step.isCompactionStep) return missing('compaction');
|
||||
if (mode === 'total') {
|
||||
if (!Number.isFinite(step.totalTokPerSec) || !(step.totalDurationSec > 0) || !step.isComplete) {
|
||||
return missing('incomplete_or_invalid_timing');
|
||||
}
|
||||
return { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec, eligible: true, reason: null };
|
||||
}
|
||||
if (!Number.isFinite(step.streamTokPerSec) || !(step.streamDurationSec > 0)) return missing(step.speedReason || 'answer_start_unavailable');
|
||||
return {
|
||||
value: step.streamTokPerSec, tokens: step.streamTokens, seconds: step.streamDurationSec,
|
||||
eligible: step.responseSampleEligible === true, reason: step.speedReason,
|
||||
};
|
||||
}
|
||||
|
||||
export function createSpeedAccumulator() {
|
||||
return { tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {}, timingSources: {} };
|
||||
}
|
||||
|
||||
export function accumulateSpeed(acc, step, mode) {
|
||||
if (step.isCompactionStep) return;
|
||||
const metric = speedMetric(step, mode);
|
||||
if (metric.eligible) {
|
||||
acc.tokens += metric.tokens;
|
||||
acc.seconds += metric.seconds;
|
||||
acc.sampleCount++;
|
||||
const source = mode === 'total' ? 'request_total' : step.responseTimingSource;
|
||||
acc.timingSources[source] = (acc.timingSources[source] || 0) + 1;
|
||||
} else {
|
||||
acc.excludedCount++;
|
||||
acc.excludedReasons[metric.reason] = (acc.excludedReasons[metric.reason] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
export function finishSpeed(acc) {
|
||||
return { ...acc, avgTokPerSec: acc.seconds > 0 ? acc.tokens / acc.seconds : null };
|
||||
}
|
||||
|
||||
export function summarizeSpeed(steps, mode) {
|
||||
const acc = createSpeedAccumulator();
|
||||
for (const step of steps) accumulateSpeed(acc, step, mode);
|
||||
return finishSpeed(acc);
|
||||
}
|
||||
|
||||
export function summarizeTtft(steps) {
|
||||
const values = steps.filter(s => !s.isCompactionStep && s.measurementVersion === MEASUREMENT_VERSION &&
|
||||
Number.isFinite(s.nativeTtftSec) && s.nativeTtftSec >= 0).map(s => s.nativeTtftSec);
|
||||
return { sampleCount: values.length, avgSec: values.length ? values.reduce((a,b) => a+b,0) / values.length : null };
|
||||
}
|
||||
@@ -811,3 +811,7 @@ body {
|
||||
.muted {
|
||||
color: var(--muted-foreground, #656d76);
|
||||
}
|
||||
|
||||
.speed-method-note { font-size: 11px; margin-top: 6px; }
|
||||
.speed-detail { font-size: 10px; white-space: normal; max-width: 150px; }
|
||||
#steps-tbody td:nth-child(3) { min-width: 120px; }
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import * as metrics from '../speed-metrics.mjs';
|
||||
|
||||
export function backendHarness({cache={},settings={},trajectories={},summaries={},sourceText=null}={}) {
|
||||
const source=(sourceText ?? fs.readFileSync(new URL('../main.mjs',import.meta.url),'utf8'))
|
||||
.replace(/^import .*;\r?\n/gm,'').replaceAll('import.meta.url',JSON.stringify('file:///test/main.mjs'));
|
||||
const state={calls:[],errors:[],saves:[],trajectories};
|
||||
const ctx={
|
||||
...metrics, URL, AbortSignal,
|
||||
process:{env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
console:{error:m=>state.errors.push(m)},
|
||||
existsSync:p=>p.endsWith('settings.json') || p.endsWith('trajectory_usage_cache.json'),
|
||||
mkdirSync:()=>{},readdirSync:()=>[],statSync:()=>({mtimeMs:0}),
|
||||
readFileSync:p=>JSON.stringify(p.endsWith('settings.json')?settings:cache),
|
||||
writeFileSync:(p,s)=>state.saves.push({path:p,data:JSON.parse(s)}),
|
||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,fileURLToPath:()=>'/test/main.mjs',
|
||||
Response:class {constructor(body,options){this.body=body;this.options=options;}},
|
||||
SidecarApp:class {page(){} api(){} run(){}},
|
||||
fetch:async(url,options)=>{
|
||||
const method=url.split('/').pop(); const body=JSON.parse(options.body);state.calls.push({method,body});
|
||||
if(method==='GetCascadeTrajectory') {
|
||||
const data=state.trajectories[body.cascadeId];
|
||||
if(data instanceof Error) throw data;
|
||||
return {ok:true,json:async()=>data||{}};
|
||||
}
|
||||
const data={GetUserStatus:{userStatus:{}},GetAllCascadeTrajectories:{trajectorySummaries:summaries},RetrieveUserQuotaSummary:{response:{groups:[]}}}[method];
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {backendHarness} from './backend-harness.mjs';
|
||||
|
||||
const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
|
||||
createdAt:'2026-01-01T00:00:00Z',finishedGeneratingAt:'2026-01-01T00:00:10Z',
|
||||
modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'},
|
||||
},plannerResponse:{response:'answer',thinkingDuration:'5s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}]}};
|
||||
const old={signature:'v5:old',title:'test',steps:[{stepIndex:0,modelKey:'MODEL_PLACEHOLDER_M418',inputTokens:100,cacheReadTokens:200,outputTokens:600,thinkingTokens:100,responseTokens:500,createdAtMs:1767225600000,ttftSec:0.4,streamTokPerSec:200,streamTokens:500,streamDurationSec:2.5,totalDurationSec:10,totalTokPerSec:60}]};
|
||||
|
||||
test('failed migration retains all accounting, makes legacy speed and TTFT unavailable',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}});
|
||||
const p=await h.buildTelemetryPayloadInternal('test');
|
||||
assert.equal(p.activeConversation.latestTokPerSec,null);
|
||||
assert.equal(p.activeConversation.latestTtftSec,null);
|
||||
assert.equal(p.activeConversation.avgTokPerSec,null);
|
||||
assert.equal(p.activeConversation.recentSteps[0].outputTokens,600);
|
||||
assert.equal(p.consumption.session.totalTokens,900);
|
||||
assert.equal(p.modelBreakdown[0].avgTokPerSec,null);
|
||||
assert.equal(h.state.saves.length,0);
|
||||
});
|
||||
test('successful migration rebuilds measurements and uses the same mean in both tables',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:raw}});
|
||||
const p=await h.buildTelemetryPayloadInternal('test');
|
||||
assert.equal(p.activeConversation.latestTokPerSec,100);
|
||||
assert.equal(p.activeConversation.latestTtftSec,3);
|
||||
assert.equal(p.activeConversation.avgTokPerSec,100);
|
||||
assert.equal(p.modelBreakdown[0].avgTokPerSec,100);
|
||||
assert.equal(p.modelBreakdown[0].speedSummary.sampleCount,1);
|
||||
assert.equal(p.consumption.session.totalTokens,900);
|
||||
assert.match(h.state.saves[0].data.test.signature,/^v6-speed-metrics:/);
|
||||
});
|
||||
test('mode switching applies to latest step, session mean and per-model mean',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:raw},settings:{speedMode:'total'}});
|
||||
const p=await h.buildTelemetryPayloadInternal('test');
|
||||
assert.equal(p.activeConversation.latestTokPerSec,60);
|
||||
assert.equal(p.activeConversation.avgTokPerSec,60);
|
||||
assert.equal(p.modelBreakdown[0].avgTokPerSec,60);
|
||||
});
|
||||
test('a malformed successful RPC cannot erase previously recorded usage',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:{}}});
|
||||
const p=await h.buildTelemetryPayloadInternal('test');
|
||||
assert.equal(p.consumption.session.totalTokens,900);
|
||||
assert.equal(p.activeConversation.latestTtftSec,null);
|
||||
assert.equal(h.state.saves.length,0);
|
||||
});
|
||||
test('a partial trajectory cannot replace a complete historical cache',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:{trajectory:{steps:[]},numTotalSteps:3}}});
|
||||
const p=await h.buildTelemetryPayloadInternal('test');
|
||||
assert.equal(p.consumption.session.totalTokens,900);
|
||||
assert.equal(h.state.saves.length,0);
|
||||
assert.match(h.state.errors[0],/Incomplete trajectory/);
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft } from '../speed-metrics.mjs';
|
||||
|
||||
function sample({ total = 12, ttft = '2s', stream = '10s', output = 1100, thinking = 100, response = 1000, thinkingDuration = '4s', tools = false, text = true, status = 'CORTEX_STEP_STATUS_DONE' } = {}) {
|
||||
const createdAt = '2026-01-01T00:00:00Z';
|
||||
const s = { status, type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', metadata: {
|
||||
createdAt, viewableAt: '2026-01-01T00:00:02Z',
|
||||
finishedGeneratingAt: new Date(Date.parse(createdAt) + total * 1000).toISOString(),
|
||||
modelUsage: { inputTokens: '500', cacheReadTokens: '2000', outputTokens: String(output), thinkingOutputTokens: String(thinking), responseOutputTokens: String(response) },
|
||||
}, plannerResponse: { response: text ? 'answer' : '', thinkingDuration, toolCalls: tools ? [{}] : [] } };
|
||||
const gm = { stepIndices: [0], chatModel: { timeToFirstToken: ttft, streamingDuration: stream } };
|
||||
return { s, gm };
|
||||
}
|
||||
function parse(options) { const {s,gm}=sample(options); return extractModelSteps([s],[gm])[0]; }
|
||||
|
||||
test('raw TTFT is not replaced by a thinking-token ratio, even for buffered tools', () => {
|
||||
const s=parse({total:20,ttft:'19.9s',stream:'0.1s',thinkingDuration:'19.95s',tools:true,text:false});
|
||||
assert.equal(s.ttftSec,19.9);
|
||||
assert.equal(s.streamTokPerSec,null);
|
||||
assert.equal(s.totalTokPerSec,55);
|
||||
});
|
||||
test('missing TTFT stays unknown; separately preserve the viewable-event delay', () => {
|
||||
const raw=sample(); delete raw.gm.chatModel.timeToFirstToken;
|
||||
const measured=extractModelSteps([raw.s],[raw.gm])[0];
|
||||
assert.equal(measured.ttftSec,null);
|
||||
assert.equal(measured.viewableDelaySec,2);
|
||||
});
|
||||
test('a reported zero TTFT is valid and missing data is not zero', () => {
|
||||
const s=parse({ttft:'0s'});
|
||||
assert.equal(s.ttftSec,0);
|
||||
assert.deepEqual(summarizeTtft([s]),{sampleCount:1,avgSec:0});
|
||||
});
|
||||
test('pure-text thinking phases are explicitly estimates', () => {
|
||||
const s=parse();
|
||||
assert.equal(s.streamTokPerSec,125);
|
||||
assert.equal(s.totalTokPerSec,1100/12);
|
||||
assert.equal(s.speedBasis,'response_estimate');
|
||||
assert.equal(s.responseTimingSource,'post_thinking_estimate');
|
||||
});
|
||||
test('a native stream spanning reasoning does not become a pure-answer timer', () => {
|
||||
const raw=sample(); delete raw.s.plannerResponse.thinkingDuration;
|
||||
const unknown=extractModelSteps([raw.s],[raw.gm])[0];
|
||||
assert.equal(unknown.streamTokPerSec,null);
|
||||
assert.equal(unknown.speedReason,'answer_start_unavailable');
|
||||
});
|
||||
test('mixed text/tool and tool-only output never enter the answer mean', () => {
|
||||
for (const text of [true,false]) {
|
||||
const s=parse({tools:true,text});
|
||||
assert.equal(s.streamTokPerSec,null);
|
||||
assert.equal(summarizeSpeed([s],'stream').sampleCount,0);
|
||||
assert.equal(summarizeSpeed([s],'total').sampleCount,1);
|
||||
}
|
||||
});
|
||||
test('short greeting keeps its phase estimate without falling back to whole-call speed', () => {
|
||||
const s=parse({output:13,thinking:0,response:13,total:5.015,ttft:'4.897s',stream:'0.118s',thinkingDuration:undefined});
|
||||
assert.equal(s.streamTokPerSec,13/.118);
|
||||
assert.equal(s.responseShortSample,true);
|
||||
assert.equal(summarizeSpeed([s],'stream').avgTokPerSec,null);
|
||||
assert.equal(speedMetric(s,'total').value,13/5.015);
|
||||
});
|
||||
test('mean uses summed tokens/time of eligible samples, not an arithmetic mean or fallback', () => {
|
||||
const a=parse(); // 1000 / 8
|
||||
const b=parse({output:600,response:500}); // 500 / 8
|
||||
const tool=parse({tools:true});
|
||||
const result=summarizeSpeed([a,b,tool],'stream');
|
||||
assert.equal(result.avgTokPerSec,1500/16);
|
||||
assert.equal(result.sampleCount,2);
|
||||
assert.equal(result.excludedCount,1);
|
||||
});
|
||||
test('unfinished and invalid-order requests do not invent completion from viewableAt', () => {
|
||||
const raw=sample(); delete raw.s.metadata.finishedGeneratingAt;
|
||||
assert.equal(extractModelSteps([raw.s],[raw.gm])[0].totalTokPerSec,null);
|
||||
assert.equal(parse({total:-1}).totalTokPerSec,null);
|
||||
assert.equal(parse({status:'CORTEX_STEP_STATUS_GENERATING'}).totalTokPerSec,null);
|
||||
});
|
||||
test('zero response token count and invalid breakdowns are not overwritten', () => {
|
||||
assert.equal(parse({response:0}).responseTokens,0);
|
||||
assert.equal(parse({response:0}).streamTokPerSec,null);
|
||||
assert.equal(parse({response:2000}).streamTokPerSec,null);
|
||||
});
|
||||
test('there is no rate-based clipping or method switch around 260 TPS', () => {
|
||||
const below=parse({output:2172,response:2072});
|
||||
const above=parse({output:2188,response:2088});
|
||||
assert.equal(below.streamTokPerSec,259);
|
||||
assert.equal(above.streamTokPerSec,261);
|
||||
assert.equal(above.speedBasis,below.speedBasis);
|
||||
});
|
||||
test('old cache keeps accounting but drops all derived timing, including manipulated TTFT', () => {
|
||||
const old={inputTokens:500,cacheReadTokens:2000,outputTokens:1100,ttftSec:0.4,streamTokPerSec:99,totalTokPerSec:55};
|
||||
const migrated=normalizeCachedStep(old);
|
||||
assert.equal(migrated.outputTokens,1100);
|
||||
assert.equal(migrated.inputTokens,500);
|
||||
assert.equal(migrated.cacheReadTokens,2000);
|
||||
assert.equal(migrated.ttftSec,null);
|
||||
assert.equal(speedMetric(migrated,'total').value,null);
|
||||
assert.equal(speedMetric(migrated,'stream').reason,'legacy_cache');
|
||||
});
|
||||
test('compaction retains its billed tokens but is excluded from both speed aggregates', () => {
|
||||
const {s,gm}=sample(); s.type='CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
const parsed=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(parsed.outputTokens,1100);
|
||||
for(const mode of ['stream','total']) assert.equal(summarizeSpeed([parsed],mode).sampleCount,0);
|
||||
});
|
||||
Reference in New Issue
Block a user