diff --git a/.gitignore b/.gitignore index 252335f..46fd6c9 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,7 @@ test/ *.log .DS_Store Thumbs.db + +# Keep regression tests in source control. +!sidecars/panel/test/ +!sidecars/panel/test/** diff --git a/README.md b/README.md index 214178f..77bdeec 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,14 @@ Antigravity 侧边栏插件,用于查看当前会话的生成速度、上下 - **系统设置** - 选择每周限额进度条的计算基准:使用官方云端周限额,或按自定义每周 Token / 美元预算计算百分比。 +## 模型识别与费用口径 + +模型取自当前步骤的原始用量或对应生成记录。自动压缩可能使用独立模型;记录未提供模型时显示“模型未知·压缩”,不会默认标为 Argon,也不会直接沿用相邻步骤的模型。 + +模型或价格未能确认时,单步费用显示“待定”,Token 仍计入统计。汇总费用显示“已知金额 + 待定”,消耗页注明未定价步数。模型明确且价格表已收录的步骤继续按本地 API 单价折算;这不代表订阅额度的美元换算关系。 + +升级时会重新读取旧缓存的原始记录。旧版默认填入的 Argon 标签无法与真实 Argon 区分;原始记录暂时无法读取时,该标签会暂记为未知,Token 和已有有效计时保留。压缩步骤可显示完整请求 TPS,但不进入会话均速。 + ## 安装 插件目录名需保持为 `usage-monitor`,无需运行 `npm install`。 @@ -83,3 +91,9 @@ git -C ~/.gemini/config/plugins/usage-monitor pull --ff-only ```bash npm run build ``` + +运行模型识别、缓存迁移与计时回归测试(无需额外安装依赖): + +```bash +npm test +``` diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index f39a1d8..026bb1b 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -571,18 +571,20 @@ function formatDateSpanBadge(startMs, endMs) { return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } -function formatUsd(amount, { precise = false, estimated = false } = {}) { +function formatUsd(amount, { precise = false, estimated = false, unpricedCalls = 0 } = {}) { + if (amount == null || !Number.isFinite(Number(amount))) return '待定'; const val = Number(amount || 0); const prefix = estimated ? '≈$' : '$'; + const suffix = unpricedCalls > 0 ? ' + 待定' : ''; if (precise) { - return val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`; + return (val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`) + suffix; } - return `${prefix}${val.toFixed(2)}`; + return `${prefix}${val.toFixed(2)}${suffix}`; } function speedReasonText(reason) { return ({ - compaction: '自动压缩不计测速', + compaction: '自动压缩不计均速', incomplete_or_invalid_timing: '未完成或计时缺失', invalid_output_tokens: '输出 Token 计数无效', inconsistent_timing: '原生首响应与总计时不一致', @@ -754,6 +756,8 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.isRunning !== nAct?.isRunning) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false; + if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false; const pCtx = pAct?.context; const nCtx = nAct?.context; if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; @@ -764,6 +768,11 @@ function isEquivalentTelemetry(prev, next) { if (pCtx?.systemPromptTokens !== nCtx?.systemPromptTokens) return false; if (pCtx?.userRulesTokens !== nCtx?.userRulesTokens) return false; if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false; + for (let i = 0; i < (pAct?.recentSteps?.length || 0); i++) { + const before = pAct.recentSteps[i], after = nAct.recentSteps[i]; + if (before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || + before.modelSource !== after.modelSource || before.costUsd !== after.costUsd) return false; + } const pRange = prev.consumption?.selectedRange; const nRange = next.consumption?.selectedRange; @@ -776,12 +785,14 @@ function isEquivalentTelemetry(prev, next) { const nCons = next.consumption?.session; if (pCons?.totalTokens !== nCons?.totalTokens) return false; if (pCons?.costUsd !== nCons?.costUsd) return false; + if (pCons?.unpricedCalls !== nCons?.unpricedCalls) return false; const pAcct = prev.consumption?.account; const nAcct = next.consumption?.account; if (pAcct?.totalTokens !== nAcct?.totalTokens) return false; if (pAcct?.calls !== nAcct?.calls) return false; if (pAcct?.costUsd !== nAcct?.costUsd) return false; + if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; const pTrend = prev.consumption?.trendSeries || []; const nTrend = next.consumption?.trendSeries || []; @@ -798,6 +809,9 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pModels.length; i++) { if ( pModels[i]?.label !== nModels[i]?.label || + pModels[i]?.shortName !== nModels[i]?.shortName || + pModels[i]?.costUsd !== nModels[i]?.costUsd || + pModels[i]?.unpricedCalls !== nModels[i]?.unpricedCalls || pModels[i]?.totalTokens !== nModels[i]?.totalTokens || pModels[i]?.calls !== nModels[i]?.calls ) { @@ -811,6 +825,8 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pSources.length; i++) { if ( pSources[i]?.name !== nSources[i]?.name || + pSources[i]?.costUsd !== nSources[i]?.costUsd || + pSources[i]?.unpricedCalls !== nSources[i]?.unpricedCalls || pSources[i]?.totalTokens !== nSources[i]?.totalTokens || pSources[i]?.calls !== nSources[i]?.calls ) { @@ -2078,7 +2094,7 @@ const LiveOverviewView = defineComponent({ setup({ onCleanup }) { // 1. 4-Cell Real-time Telemetry Matrix const tpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); - const tpsSub = h('span', { className: 'cell-sub', text: 'argon-4' }); + const tpsSub = h('span', { className: 'cell-sub', text: '模型未知' }); const pulseDot = createSvgIcon('dot', { size: 10 }); const ttftVal = h('strong', { className: 'cell-value', text: '—' }); @@ -2312,7 +2328,7 @@ const LiveOverviewView = defineComponent({ const reason = speedReasonText(active.latestSpeedReason); patchText( tpsSub, - reason ? `${active.activeModelShort || 'argon-4'} · ${reason}` : active.activeModelShort || 'argon-4' + reason ? `${active.activeModelShort || '模型未知'} · ${reason}` : active.activeModelShort || '模型未知' ); patchText(ttftVal, formatMetric(active.latestTtftSec, 's')); @@ -2321,11 +2337,11 @@ const LiveOverviewView = defineComponent({ patchText(avgVal, formatMetric(active.avgTokPerSec, ' tok/s')); patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`); - const stepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0); + const stepCost = active.latestStepCostUsd; patchText(costVal, formatUsd(stepCost, { precise: true })); patchText( cacheSub, - `缓 ${active.latestCacheHitPct ?? 0}% · 累 ${formatUsd(active.sessionCostUsd || 0)}` + `缓 ${active.latestCacheHitPct ?? 0}% · 累 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}` ); // 2. Context (Auto Compaction Baseline) @@ -2360,16 +2376,17 @@ const LiveOverviewView = defineComponent({ {}; const claudePool = pools.find((p) => p.family === 'Claude & GPT' || p.family === 'Claude') || - (activePool.family && activePool.family !== 'Gemini' ? activePool : null) || + (['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family) ? activePool : null) || {}; - const activeIsGemini = (activePool.family || 'Gemini') === 'Gemini'; + const activeIsGemini = activePool.family === 'Gemini'; + const activeIsThirdParty = ['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family); syncPoolQuotaBlock(geminiQuotaBlock, 'Gemini', geminiPool, weekly, activeIsGemini); - syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, !activeIsGemini); + syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, activeIsThirdParty); patchText( wkFootLeft, - `本周本机: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0)})` + `本周本机: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0, { unpricedCalls: weekly.unpricedCalls })})` ); patchText( wkFootRight, @@ -2923,7 +2940,7 @@ const ConsumptionView = defineComponent({ patchText(refs.pctBadge, `${share.toFixed(1)}%`); patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : ''); patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader); - patchText(refs.costEl, formatUsd(item.costUsd || 0)); + patchText(refs.costEl, formatUsd(item.costUsd || 0, { unpricedCalls: item.unpricedCalls })); const responseTok = item.responseTokens != null @@ -2975,8 +2992,8 @@ const ConsumptionView = defineComponent({ patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); patchText(heroTotalCalls, `${acct.calls || 0} 调用`); - patchText(heroCostUsd, formatUsd(costUsd)); - patchText(heroCostCny, formatCnyApprox(costUsd)); + patchText(heroCostUsd, formatUsd(costUsd, { unpricedCalls: acct.unpricedCalls })); + patchText(heroCostCny, acct.unpricedCalls > 0 ? `${acct.unpricedCalls} 步费用待定` : formatCnyApprox(costUsd)); patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`); patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`); @@ -3029,7 +3046,7 @@ const ConsumptionView = defineComponent({ patchKeyedList(modelsListEl, models, { keyFn: (m) => m.label || m.shortName, sigFn: (m) => - `${m.label}:${m.totalTokens}:${m.costUsd}:${m.calls}:${modelsTotalTok}`, + `${m.label}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true), }); @@ -3039,7 +3056,7 @@ const ConsumptionView = defineComponent({ const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); patchKeyedList(sourcesListEl, sources, { keyFn: (s) => s.name, - sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.calls}:${sourcesTotalTok}`, + sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true), }); @@ -3069,7 +3086,8 @@ const ConsumptionView = defineComponent({ patchText(col.tokText, ''); } else { const cVal = Number(m.costUsd || 0); - patchText(col.costText, cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); + patchText(col.costText, m.unpricedCalls > 0 ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls }) + : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); @@ -3309,7 +3327,7 @@ const StepsDetailView = defineComponent({ ); patchText(refs.tdCache, `${Number(st.cacheHitPct ?? 0)}%`); - const costVal = Number(st.costUsd || 0); + const costVal = st.costUsd; patchText(refs.tdCost, formatUsd(costVal, { precise: true })); patchClasses(refs.tdCost, { 'accent-speed': costVal >= 0.15 }); }, @@ -3318,7 +3336,7 @@ const StepsDetailView = defineComponent({ patchKeyedList(modelsTbody, models, { keyFn: (m) => m.label || m.shortName, sigFn: (m) => - `${m.shortName}:${m.calls}:${m.avgTokPerSec}:${m.totalTokens}:${m.costUsd}:${m.speedSummary?.sampleCount}`, + `${m.shortName}:${m.calls}:${m.avgTokPerSec}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.speedSummary?.sampleCount}`, createRow: () => { const tdName = h('td', { style: 'font-weight: 600;' }); const tdCalls = h('td'); @@ -3339,7 +3357,7 @@ const StepsDetailView = defineComponent({ patchText(refs.speedMain, formatMetric(m.avgTokPerSec, ' tok/s')); patchText(refs.speedSub, `有效 ${sampleSummary(m.speedSummary)}`); patchText(refs.tdTokens, formatTokens(m.totalTokens || 0)); - patchText(refs.tdCost, formatUsd(m.costUsd || 0, { estimated: m.isEstimatedPrice })); + patchText(refs.tdCost, formatUsd(m.costUsd, { estimated: m.isEstimatedPrice, unpricedCalls: m.unpricedCalls })); }, }); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 82cc40d..1cddd21 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 测速与额度监控 - +
- + diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index e0af73a..732a7e4 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -24,14 +24,13 @@ const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN; const DEFAULT_SETTINGS = { contextWindowLimit: 256000, // 256k auto-compaction budget default (can be toggled to 256k / 1M / 2M) weeklyTokenBudget: 150000000, // 150M tokens default custom weekly target - weeklyCostBudget: 100, // $100 default custom weekly cost target (matches Ultra weekly pool) + weeklyCostBudget: 100, // Default user-configurable local cost target weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost' }; -// Official API pricing in USD per 1M tokens (Input, CacheRead, Output incl. Thinking) -// Verified to 6 decimal places against RetrieveUserQuotaSummary({ forceRefresh: true }): -// Gemini 4 Argon official price (until 2026-11-30): Input $2.00 / Cache $0.10 / Output $10.00 -// Ultra 5h Pool (100%) = $25.00 USD | Ultra Weekly Pool (100%) = $100.00 USD +// Local API price catalog in USD per 1M tokens (Input, CacheRead, Output). +// These estimates do not establish a conversion to subscription quota. +// Missing model/price evidence is left unpriced, never filled from another model. const MODEL_PRICING = { // Gemini 4 & 3.x & 2.5 Official Catalog Pricing (USD / 1M tokens) 'gemini-4-argon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-high', family: 'Gemini' }, @@ -116,10 +115,12 @@ const PLACEHOLDER_MAP = { }; // In-memory cache of trajectory step usage: cascadeId -> { signature, steps } -const CACHE_SCHEMA_VERSION = 'v9-unified-throughput'; -let trajectoryCache = Object.fromEntries(Object.entries(loadJson(CACHE_FILE, {})).map(([id, entry]) => [ +const CACHE_SCHEMA_VERSION = 'v10-model-identity'; +const loadedTrajectoryCache = loadJson(CACHE_FILE, {}); +let trajectoryCache = Object.fromEntries(Object.entries(loadedTrajectoryCache).map(([id, entry]) => [ id, { ...entry, steps: (entry.steps || []).map(normalizeCachedStep) }, ])); +let cacheNeedsSave = JSON.stringify(trajectoryCache) !== JSON.stringify(loadedTrajectoryCache); let externalDeepStatsMemo = { sig: '', convos: new Map() }; const inFlightRequests = new Map(); let quotaSummaryCache = { ts: 0, data: null, error: null }; @@ -137,8 +138,10 @@ function saveJson(filePath, data) { try { mkdirSync(DATA_DIR, { recursive: true }); writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8'); + return true; } catch (err) { console.error(`Failed writing ${filePath}: ${err.message}`); + return false; } } @@ -250,13 +253,13 @@ function formatGenericModelSlug(slug = '') { function resolveModelInfo(rawModelKey, dynamicModelMap, apiProvider = '', modelDisplayName = '') { const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey]; const cleanRawFallback = - rawModelKey && !/^MODEL_PLACEHOLDER_/i.test(String(rawModelKey)) ? rawModelKey : ''; + rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : ''; const derivedDisplay = modelDisplayName || dyn?.label || formatGenericModelSlug(rawModelKey) || cleanRawFallback || - 'Unknown Model'; + '模型未知'; const baseLabel = getBaseModelLabel(derivedDisplay); const canonicalSlug = baseLabel.toLowerCase().replace(/\s+/g, '-'); const dashedSlug = canonicalSlug.replace(/\./g, '-'); @@ -280,45 +283,20 @@ function resolveModelInfo(rawModelKey, dynamicModelMap, apiProvider = '', modelD } const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, modelId, apiProvider); - const rawUpper = String(`${rawModelKey || ''} ${modelId || ''} ${derivedDisplay}`).toUpperCase(); - let fallbackPricing; - if (inferredFamily === 'Gemini') { - if (rawUpper.includes('LITE')) { - fallbackPricing = { input: 0.10, cache: 0.01, output: 0.40, short: 'gemini-lite', family: 'Gemini' }; - } else if (rawUpper.includes('FLASH')) { - fallbackPricing = { input: 0.30, cache: 0.03, output: 2.50, short: 'gemini-flash', family: 'Gemini' }; - } else if (rawUpper.includes('PRO')) { - fallbackPricing = { input: 1.25, cache: 0.125, output: 10.0, short: 'gemini-pro', family: 'Gemini' }; - } else { - fallbackPricing = { input: 2.00, cache: 0.10, output: 10.0, short: 'gemini', family: 'Gemini' }; - } - } else if (inferredFamily === 'Claude') { - fallbackPricing = { input: 3.0, cache: 0.30, output: 15.0, short: 'claude', family: 'Claude' }; - } else if (inferredFamily === 'GPT') { - fallbackPricing = { input: 0.80, cache: 0.10, output: 2.40, short: 'gpt', family: 'GPT' }; - } else { - fallbackPricing = { - input: 0, - cache: 0, - output: 0, - short: (derivedDisplay || 'unknown').split(' ')[0].toLowerCase(), - family: 'Other', - }; - } - return { rawModel: rawModelKey, modelId, label: derivedDisplay, baseLabel: getBaseModelLabel(derivedDisplay), - shortName: fallbackPricing.short, - family: fallbackPricing.family, - pricing: fallbackPricing, + shortName: derivedDisplay, + family: inferredFamily, + pricing: null, isEstimatedPrice: true, }; } function computeStepCost(step, pricing) { + if (!pricing) return null; const inCost = (step.inputTokens / 1_000_000) * pricing.input; const cacheCost = (step.cacheReadTokens / 1_000_000) * pricing.cache; const outCost = (step.outputTokens / 1_000_000) * pricing.output; @@ -433,8 +411,10 @@ function createUsageBucket() { function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) { const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; - const savedCost = - (st.cacheReadTokens / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache); + const savedCost = mInfo.pricing + ? (st.cacheReadTokens / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache) : 0; + if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1; + stepCost = stepCost ?? 0; bucket.calls += 1; if (cascadeId) bucket.conversationsSet.add(cascadeId); bucket.inputTokens += st.inputTokens; @@ -471,6 +451,7 @@ function finalizeUsageBucket(bucket) { responseTokens: bucket.responseTokens, totalTokens: bucket.totalTokens, costUsd: +bucket.costUsd.toFixed(2), + unpricedCalls: bucket.unpricedCalls || 0, savedCostUsd: +bucket.savedCostUsd.toFixed(2), cacheHitPct, geminiTokens: bucket.geminiTokens, @@ -815,7 +796,7 @@ async function buildTelemetryPayloadInternal( const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null; // Refresh trajectory cache for any uncached, schema-outdated, or updated conversation - let cacheDirty = false; + let cacheDirty = cacheNeedsSave; const toFetch = conversations.filter((conv) => { const cached = trajectoryCache[conv.cascadeId]; @@ -891,7 +872,7 @@ async function buildTelemetryPayloadInternal( } if (cacheDirty) { - saveJson(CACHE_FILE, trajectoryCache); + cacheNeedsSave = !saveJson(CACHE_FILE, trajectoryCache); } // Compute Active Conversation Metrics @@ -901,15 +882,17 @@ async function buildTelemetryPayloadInternal( const sessionSpeed = summarizeSpeed(activeSteps); const sessionTtft = summarizeTtft(activeSteps); let sessionCostUsd = 0; + let sessionUnpricedCalls = 0; let sessionInputTokens = 0; let sessionCacheReadTokens = 0; const enrichedActiveSteps = activeSteps.map((st) => { - const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider); + const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider, st.modelDisplayName); const costUsd = computeStepCost(st, mInfo.pricing); const metric = speedMetric(st); - sessionCostUsd += costUsd; + sessionCostUsd += costUsd ?? 0; + if (costUsd === null) sessionUnpricedCalls++; sessionInputTokens += st.inputTokens; sessionCacheReadTokens += st.cacheReadTokens; @@ -917,9 +900,9 @@ 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; + const inCostUsd = mInfo.pricing ? (st.inputTokens / 1_000_000) * mInfo.pricing.input : null; + const cacheCostUsd = mInfo.pricing ? (st.cacheReadTokens / 1_000_000) * mInfo.pricing.cache : null; + const outCostUsd = mInfo.pricing ? (st.outputTokens / 1_000_000) * mInfo.pricing.output : null; return { ...st, @@ -930,10 +913,10 @@ async function buildTelemetryPayloadInternal( selectedSpeedReason: metric.reason, ttftSec: st.nativeTtftSec, cacheHitPct: +cacheHitPct.toFixed(1), - costUsd: +costUsd.toFixed(4), - inCostUsd: +inCostUsd.toFixed(4), - cacheCostUsd: +cacheCostUsd.toFixed(4), - outCostUsd: +outCostUsd.toFixed(4), + costUsd: costUsd === null ? null : +costUsd.toFixed(4), + inCostUsd: inCostUsd === null ? null : +inCostUsd.toFixed(4), + cacheCostUsd: cacheCostUsd === null ? null : +cacheCostUsd.toFixed(4), + outCostUsd: outCostUsd === null ? null : +outCostUsd.toFixed(4), contextTokens: st.inputTokens + st.cacheReadTokens + st.outputTokens, }; }); @@ -991,11 +974,13 @@ async function buildTelemetryPayloadInternal( sessionPromptTokens > 0 ? Math.round((sessionCacheReadTokens / sessionPromptTokens) * 100) : 0; // Determine active pool and its official cycle anchors for time window alignment - const rawActiveFamily = latestEnriched?.family || 'Gemini'; - const activePoolKey = rawActiveFamily === 'Gemini' ? 'Gemini' : 'Claude & GPT'; - const activeLive5h = officialBuckets.get(activePoolKey === 'Gemini' ? 'gemini-5h' : '3p-5h'); + const rawActiveFamily = latestEnriched?.family || 'Other'; + const activePoolKey = rawActiveFamily === 'Gemini' ? 'Gemini' + : ['Claude', 'GPT'].includes(rawActiveFamily) ? 'Claude & GPT' : 'Unknown'; + const activeLive5h = officialBuckets.get(activePoolKey === 'Gemini' ? 'gemini-5h' + : activePoolKey === 'Claude & GPT' ? '3p-5h' : null); const activeLiveWeekly = officialBuckets.get( - activePoolKey === 'Gemini' ? 'gemini-weekly' : '3p-weekly' + activePoolKey === 'Gemini' ? 'gemini-weekly' : activePoolKey === 'Claude & GPT' ? '3p-weekly' : null ); const cycleAnchors = { fiveHourResetMs: parseIsoMs(activeLive5h?.resetTime), @@ -1098,6 +1083,7 @@ async function buildTelemetryPayloadInternal( ); const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; const stepCost = computeStepCost(st, mInfo.pricing); + const unpriced = stepCost === null ? 1 : 0; const tMs = st.createdAtMs || 0; if (tMs > 0) { @@ -1111,7 +1097,8 @@ async function buildTelemetryPayloadInternal( mBucket.responseTokens += st.responseTokens || 0; mBucket.thinkingTokens += st.thinkingTokens || 0; mBucket.totalTokens += stepTotalTokens; - mBucket.costUsd = +(mBucket.costUsd + stepCost).toFixed(4); + mBucket.costUsd = +(mBucket.costUsd + (stepCost ?? 0)).toFixed(4); + mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; } } } @@ -1140,7 +1127,8 @@ async function buildTelemetryPayloadInternal( selectedWindowSteps.push({ tMs, tokens: stepTotalTokens, - costUsd: stepCost, + costUsd: stepCost ?? 0, + unpricedCalls: unpriced, }); } @@ -1163,7 +1151,8 @@ async function buildTelemetryPayloadInternal( sAgg.responseTokens += st.responseTokens || 0; sAgg.thinkingTokens += st.thinkingTokens || 0; sAgg.totalTokens += stepTotalTokens; - sAgg.costUsd += stepCost; + sAgg.costUsd += stepCost ?? 0; + sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced; const modelGroupKey = mInfo.baseLabel || mInfo.label; if (!perModelStats.has(modelGroupKey)) { @@ -1192,7 +1181,8 @@ async function buildTelemetryPayloadInternal( agg.thinkingTokens += st.thinkingTokens || 0; agg.responseTokens += st.responseTokens || 0; agg.totalTokens += stepTotalTokens; - agg.costUsd += stepCost; + agg.costUsd += stepCost ?? 0; + agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced; } } } @@ -1235,6 +1225,7 @@ async function buildTelemetryPayloadInternal( const idx = Math.max(0, Math.min(trendSlotsCount - 1, rawIdx)); trendSeries[idx].tokens += item.tokens; trendSeries[idx].costUsd = +(trendSeries[idx].costUsd + item.costUsd).toFixed(4); + trendSeries[idx].unpricedCalls = (trendSeries[idx].unpricedCalls || 0) + item.unpricedCalls; trendSeries[idx].calls += 1; } @@ -1263,7 +1254,8 @@ async function buildTelemetryPayloadInternal( const familyPoolQuota = quotaPoolsMap.get(activePoolKey); const activePoolQuota = familyPoolQuota || { - poolName: activePoolKey === 'Gemini' ? 'Gemini 模型池' : 'Claude & GPT 模型池', + poolName: activePoolKey === 'Gemini' ? 'Gemini 模型池' + : activePoolKey === 'Claude & GPT' ? 'Claude & GPT 模型池' : '模型池未知', family: activePoolKey, isAvailable: Boolean(activeLive5h), remainingPct: activeLive5h?.remainingPct ?? null, @@ -1279,7 +1271,8 @@ async function buildTelemetryPayloadInternal( const fallbackWeeklyPct = settings.weeklyLimitMode === 'custom_cost' || settings.weeklyLimitMode === 'cost' - ? Math.min(100, +((weekBucket.costUsd / Math.max(1, settings.weeklyCostBudget)) * 100).toFixed(1)) + ? weekBucket.unpricedCalls > 0 ? null + : Math.min(100, +((weekBucket.costUsd / Math.max(1, settings.weeklyCostBudget)) * 100).toFixed(1)) : Math.min( 100, +((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1) @@ -1296,12 +1289,12 @@ async function buildTelemetryPayloadInternal( : null; const weeklyRemainingPct = useOfficialWeekly ? activeLiveWeekly.remainingPct - : isCustomWeeklyMode + : isCustomWeeklyMode && fallbackWeeklyPct !== null ? +(100 - fallbackWeeklyPct).toFixed(1) : null; const weeklyRemainingIntPct = useOfficialWeekly ? activeLiveWeekly.remainingIntPct - : isCustomWeeklyMode + : isCustomWeeklyMode && fallbackWeeklyPct !== null ? Math.max(0, Math.floor(100 - fallbackWeeklyPct)) : null; @@ -1341,12 +1334,13 @@ async function buildTelemetryPayloadInternal( avgTokPerSec: sessionAvgTokPerSec, speedSummary: sessionSpeed, ttftSummary: sessionTtft, - latestStepCostUsd: latestEnriched?.costUsd ?? 0, + latestStepCostUsd: latestEnriched?.costUsd ?? null, sessionCostUsd: +sessionCostUsd.toFixed(2), + sessionUnpricedCalls, latestCacheHitPct, sessionCacheHitPct, - activeModelShort: latestEnriched?.modelShort || 'argon-4', - activeModelLabel: latestEnriched?.modelLabel || 'Gemini 4 Argon (Medium)', + activeModelShort: latestEnriched?.modelShort || '模型未知', + activeModelLabel: latestEnriched?.modelLabel || '模型未知', context: { totalTokens: ctxTotal, limitTokens: ctxLimit, @@ -1408,6 +1402,7 @@ async function buildTelemetryPayloadInternal( calls: weekBucket.calls, tokens: weekBucket.totalTokens, costUsd: weekBucket.costUsd, + unpricedCalls: weekBucket.unpricedCalls, usedPct: weeklyUsedPct, remainingPct: weeklyRemainingPct, remainingIntPct: weeklyRemainingIntPct, @@ -1421,6 +1416,7 @@ async function buildTelemetryPayloadInternal( calls: todayBucket.calls, tokens: todayBucket.totalTokens, costUsd: todayBucket.costUsd, + unpricedCalls: todayBucket.unpricedCalls, }, }, modelBreakdown: Array.from(perModelStats.values()) diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 35e297a..53b528e 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -5,6 +5,7 @@ "type": "module", "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", "scripts": { - "build": "node scripts/build-bundle.mjs" + "build": "node scripts/build-bundle.mjs", + "test": "node --test test/*.test.mjs" } } diff --git a/sidecars/panel/speed-metrics.mjs b/sidecars/panel/speed-metrics.mjs index 9c8f6d9..ea6020b 100644 --- a/sidecars/panel/speed-metrics.mjs +++ b/sidecars/panel/speed-metrics.mjs @@ -1,6 +1,7 @@ // Client-observed request throughput, including waiting and thinking. // One formula for text and tools; no rate-based clipping or denominator changes. export const MEASUREMENT_VERSION = 4; +export const MODEL_IDENTITY_VERSION = 1; export const MIN_SPEED_DURATION_SECONDS = 0.5; export const MIN_MEAN_OUTPUT_TOKENS = 50; @@ -267,9 +268,22 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const speedReason = timingReason || (isCompactionStep ? 'compaction' : shortOutputSample ? 'short_sample' : null); const context = chat?.chatStartMetadata?.contextWindowMetadata; const contextBreakdown = extractContextBreakdown(chat); + // Only use model evidence belonging to this request. A checkpoint can use + // a different model from its neighbouring planner steps (or omit it). + const modelCandidates = [ + ['usage.model', u.model], ['chat.usage.model', chat?.usage?.model], + ['chat.model', chat?.model], ['metadata.generatorModel', m.generatorModel], + ['chat.responseModel', chat?.responseModel], + ]; + const identity = modelCandidates.find(([, value]) => + typeof value === 'string' && value.trim() && + !/^(?:0|unknown|MODEL_(?:UNSPECIFIED|UNKNOWN))$/i.test(value.trim())); result.push({ stepIndex, isCompactionStep, - modelKey: u.model || chat?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418', + modelKey: identity ? identity[1].trim() : 'unknown', + modelSource: identity?.[0] || 'unavailable', + modelIdentityVersion: MODEL_IDENTITY_VERSION, + modelDisplayName: chat?.modelDisplayName || '', apiProvider: u.apiProvider || chat?.usage?.apiProvider || '', createdAt: m.createdAt || null, createdAtMs: Math.floor(start), hasVisibleText: String(p.modifiedResponse || p.response || '').trim().length > 0, @@ -306,6 +320,19 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { } export function normalizeCachedStep(step) { + if (step.modelIdentityVersion !== MODEL_IDENTITY_VERSION) { + // v9 wrote M418 both for real Argon calls and as the missing-model default. + // Without raw evidence they are indistinguishable; keep usage and timing, + // mark the identity unresolved, and let the schema reload recover it. + const ambiguous = !step.modelKey || step.modelKey === 'MODEL_PLACEHOLDER_M418'; + step = { + ...step, modelIdentityVersion: MODEL_IDENTITY_VERSION, + ...(ambiguous ? { + legacyModelKey: step.modelKey || null, modelKey: 'unknown', + modelDisplayName: '', modelSource: 'legacy_unverified', + } : { modelSource: 'legacy_explicit' }), + }; + } if (step.measurementVersion === MEASUREMENT_VERSION) return step; // Keep billing through failed reloads, but never show old derived speeds as // current measurements. Raw trajectories rebuild measurements after migration. diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index f702f30..679d124 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -37,18 +37,20 @@ export function formatDateSpanBadge(startMs, endMs) { return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } -export function formatUsd(amount, { precise = false, estimated = false } = {}) { +export function formatUsd(amount, { precise = false, estimated = false, unpricedCalls = 0 } = {}) { + if (amount == null || !Number.isFinite(Number(amount))) return '待定'; const val = Number(amount || 0); const prefix = estimated ? '≈$' : '$'; + const suffix = unpricedCalls > 0 ? ' + 待定' : ''; if (precise) { - return val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`; + return (val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`) + suffix; } - return `${prefix}${val.toFixed(2)}`; + return `${prefix}${val.toFixed(2)}${suffix}`; } export function speedReasonText(reason) { return ({ - compaction: '自动压缩不计测速', + compaction: '自动压缩不计均速', incomplete_or_invalid_timing: '未完成或计时缺失', invalid_output_tokens: '输出 Token 计数无效', inconsistent_timing: '原生首响应与总计时不一致', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 31ef94b..3159560 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -34,6 +34,8 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.isRunning !== nAct?.isRunning) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false; + if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false; const pCtx = pAct?.context; const nCtx = nAct?.context; if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; @@ -44,6 +46,11 @@ function isEquivalentTelemetry(prev, next) { if (pCtx?.systemPromptTokens !== nCtx?.systemPromptTokens) return false; if (pCtx?.userRulesTokens !== nCtx?.userRulesTokens) return false; if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false; + for (let i = 0; i < (pAct?.recentSteps?.length || 0); i++) { + const before = pAct.recentSteps[i], after = nAct.recentSteps[i]; + if (before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || + before.modelSource !== after.modelSource || before.costUsd !== after.costUsd) return false; + } const pRange = prev.consumption?.selectedRange; const nRange = next.consumption?.selectedRange; @@ -56,12 +63,14 @@ function isEquivalentTelemetry(prev, next) { const nCons = next.consumption?.session; if (pCons?.totalTokens !== nCons?.totalTokens) return false; if (pCons?.costUsd !== nCons?.costUsd) return false; + if (pCons?.unpricedCalls !== nCons?.unpricedCalls) return false; const pAcct = prev.consumption?.account; const nAcct = next.consumption?.account; if (pAcct?.totalTokens !== nAcct?.totalTokens) return false; if (pAcct?.calls !== nAcct?.calls) return false; if (pAcct?.costUsd !== nAcct?.costUsd) return false; + if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; const pTrend = prev.consumption?.trendSeries || []; const nTrend = next.consumption?.trendSeries || []; @@ -78,6 +87,9 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pModels.length; i++) { if ( pModels[i]?.label !== nModels[i]?.label || + pModels[i]?.shortName !== nModels[i]?.shortName || + pModels[i]?.costUsd !== nModels[i]?.costUsd || + pModels[i]?.unpricedCalls !== nModels[i]?.unpricedCalls || pModels[i]?.totalTokens !== nModels[i]?.totalTokens || pModels[i]?.calls !== nModels[i]?.calls ) { @@ -91,6 +103,8 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pSources.length; i++) { if ( pSources[i]?.name !== nSources[i]?.name || + pSources[i]?.costUsd !== nSources[i]?.costUsd || + pSources[i]?.unpricedCalls !== nSources[i]?.unpricedCalls || pSources[i]?.totalTokens !== nSources[i]?.totalTokens || pSources[i]?.calls !== nSources[i]?.calls ) { diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 4c241b1..d153567 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -521,7 +521,7 @@ export const ConsumptionView = defineComponent({ patchText(refs.pctBadge, `${share.toFixed(1)}%`); patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : ''); patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader); - patchText(refs.costEl, formatUsd(item.costUsd || 0)); + patchText(refs.costEl, formatUsd(item.costUsd || 0, { unpricedCalls: item.unpricedCalls })); const responseTok = item.responseTokens != null @@ -573,8 +573,8 @@ export const ConsumptionView = defineComponent({ patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); patchText(heroTotalCalls, `${acct.calls || 0} 调用`); - patchText(heroCostUsd, formatUsd(costUsd)); - patchText(heroCostCny, formatCnyApprox(costUsd)); + patchText(heroCostUsd, formatUsd(costUsd, { unpricedCalls: acct.unpricedCalls })); + patchText(heroCostCny, acct.unpricedCalls > 0 ? `${acct.unpricedCalls} 步费用待定` : formatCnyApprox(costUsd)); patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`); patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`); @@ -627,7 +627,7 @@ export const ConsumptionView = defineComponent({ patchKeyedList(modelsListEl, models, { keyFn: (m) => m.label || m.shortName, sigFn: (m) => - `${m.label}:${m.totalTokens}:${m.costUsd}:${m.calls}:${modelsTotalTok}`, + `${m.label}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true), }); @@ -637,7 +637,7 @@ export const ConsumptionView = defineComponent({ const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); patchKeyedList(sourcesListEl, sources, { keyFn: (s) => s.name, - sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.calls}:${sourcesTotalTok}`, + sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true), }); @@ -667,7 +667,8 @@ export const ConsumptionView = defineComponent({ patchText(col.tokText, ''); } else { const cVal = Number(m.costUsd || 0); - patchText(col.costText, cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); + patchText(col.costText, m.unpricedCalls > 0 ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls }) + : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); diff --git a/sidecars/panel/src/views/LiveOverviewView.js b/sidecars/panel/src/views/LiveOverviewView.js index efc05c2..fe7e558 100644 --- a/sidecars/panel/src/views/LiveOverviewView.js +++ b/sidecars/panel/src/views/LiveOverviewView.js @@ -31,7 +31,7 @@ export const LiveOverviewView = defineComponent({ setup({ onCleanup }) { // 1. 4-Cell Real-time Telemetry Matrix const tpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); - const tpsSub = h('span', { className: 'cell-sub', text: 'argon-4' }); + const tpsSub = h('span', { className: 'cell-sub', text: '模型未知' }); const pulseDot = createSvgIcon('dot', { size: 10 }); const ttftVal = h('strong', { className: 'cell-value', text: '—' }); @@ -265,7 +265,7 @@ export const LiveOverviewView = defineComponent({ const reason = speedReasonText(active.latestSpeedReason); patchText( tpsSub, - reason ? `${active.activeModelShort || 'argon-4'} · ${reason}` : active.activeModelShort || 'argon-4' + reason ? `${active.activeModelShort || '模型未知'} · ${reason}` : active.activeModelShort || '模型未知' ); patchText(ttftVal, formatMetric(active.latestTtftSec, 's')); @@ -274,11 +274,11 @@ export const LiveOverviewView = defineComponent({ patchText(avgVal, formatMetric(active.avgTokPerSec, ' tok/s')); patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`); - const stepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0); + const stepCost = active.latestStepCostUsd; patchText(costVal, formatUsd(stepCost, { precise: true })); patchText( cacheSub, - `缓 ${active.latestCacheHitPct ?? 0}% · 累 ${formatUsd(active.sessionCostUsd || 0)}` + `缓 ${active.latestCacheHitPct ?? 0}% · 累 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}` ); // 2. Context (Auto Compaction Baseline) @@ -313,16 +313,17 @@ export const LiveOverviewView = defineComponent({ {}; const claudePool = pools.find((p) => p.family === 'Claude & GPT' || p.family === 'Claude') || - (activePool.family && activePool.family !== 'Gemini' ? activePool : null) || + (['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family) ? activePool : null) || {}; - const activeIsGemini = (activePool.family || 'Gemini') === 'Gemini'; + const activeIsGemini = activePool.family === 'Gemini'; + const activeIsThirdParty = ['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family); syncPoolQuotaBlock(geminiQuotaBlock, 'Gemini', geminiPool, weekly, activeIsGemini); - syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, !activeIsGemini); + syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, activeIsThirdParty); patchText( wkFootLeft, - `本周本机: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0)})` + `本周本机: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0, { unpricedCalls: weekly.unpricedCalls })})` ); patchText( wkFootRight, diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index 1d14bc4..d8a37de 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -189,7 +189,7 @@ export const StepsDetailView = defineComponent({ ); patchText(refs.tdCache, `${Number(st.cacheHitPct ?? 0)}%`); - const costVal = Number(st.costUsd || 0); + const costVal = st.costUsd; patchText(refs.tdCost, formatUsd(costVal, { precise: true })); patchClasses(refs.tdCost, { 'accent-speed': costVal >= 0.15 }); }, @@ -198,7 +198,7 @@ export const StepsDetailView = defineComponent({ patchKeyedList(modelsTbody, models, { keyFn: (m) => m.label || m.shortName, sigFn: (m) => - `${m.shortName}:${m.calls}:${m.avgTokPerSec}:${m.totalTokens}:${m.costUsd}:${m.speedSummary?.sampleCount}`, + `${m.shortName}:${m.calls}:${m.avgTokPerSec}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.speedSummary?.sampleCount}`, createRow: () => { const tdName = h('td', { style: 'font-weight: 600;' }); const tdCalls = h('td'); @@ -219,7 +219,7 @@ export const StepsDetailView = defineComponent({ patchText(refs.speedMain, formatMetric(m.avgTokPerSec, ' tok/s')); patchText(refs.speedSub, `有效 ${sampleSummary(m.speedSummary)}`); patchText(refs.tdTokens, formatTokens(m.totalTokens || 0)); - patchText(refs.tdCost, formatUsd(m.costUsd || 0, { estimated: m.isEstimatedPrice })); + patchText(refs.tdCost, formatUsd(m.costUsd, { estimated: m.isEstimatedPrice, unpricedCalls: m.unpricedCalls })); }, }); diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs new file mode 100644 index 0000000..573bfbc --- /dev/null +++ b/sidecars/panel/test/backend-harness.mjs @@ -0,0 +1,35 @@ +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={},userStatus={},sourceText=null,metricsImplementation=metrics}={}) { + 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={ + ...metricsImplementation, 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(){}}, + StreamDiagnostics:class {status(){return {enabled:false};} start(){}}, + 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,resolveModelInfo};',ctx); + return {...ctx.api,state}; +} diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs new file mode 100644 index 0000000..412e781 --- /dev/null +++ b/sidecars/panel/test/backend.test.mjs @@ -0,0 +1,73 @@ +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,1); + assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600); + assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown'); +}); +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,60); + assert.equal(p.activeConversation.latestTtftSec,3); + assert.equal(p.activeConversation.avgTokPerSec,60); + assert.equal(p.modelBreakdown[0].avgTokPerSec,60); + assert.equal(p.modelBreakdown[0].speedSummary.sampleCount,1); + assert.equal(p.consumption.session.totalTokens,900); + assert.match(h.state.saves[0].data.test.signature,/^v10-model-identity:/); +}); +test('a legacy stream setting cannot re-enable mixed speed formulas',async()=>{ + const h=backendHarness({cache:{test:old},trajectories:{test:raw},settings:{speedMode:'stream'}}); + 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); + assert.equal(p.settings.speedMode,undefined); +}); +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,1); + assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600); + assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown'); +}); +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,1); + assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600); + assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown'); + assert.match(h.state.errors[0],/Incomplete trajectory/); +}); + +test('a TTFT-only correction is persisted even when usage, duration and signature match',async()=>{ + const h=backendHarness({cache:{test:old},trajectories:{test:raw},summaries:{test:{ + stepCount:1,lastModifiedTime:'2026-01-01T00:00:10Z',status:'CASCADE_RUN_STATUS_RUNNING', + }}}); + await h.buildTelemetryPayloadInternal('test'); + h.state.trajectories.test=structuredClone(raw); + h.state.trajectories.test.trajectory.generatorMetadata[0].chatModel.timeToFirstToken='9s'; + const next=await h.buildTelemetryPayloadInternal('test'); + assert.equal(next.activeConversation.latestTtftSec,9); + assert.equal(h.state.saves.length,2); + assert.equal(h.state.saves[1].data.test.steps[0].ttftSec,9); +}); diff --git a/sidecars/panel/test/model-identity.test.mjs b/sidecars/panel/test/model-identity.test.mjs new file mode 100644 index 0000000..d955edd --- /dev/null +++ b/sidecars/panel/test/model-identity.test.mjs @@ -0,0 +1,155 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs'; +import { formatUsd } from '../src/core/formatters.js'; +import { backendHarness } from './backend-harness.mjs'; + +const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418'; +const createdAtMs = Date.now() - 20_000; +function step(index, model, checkpoint = false) { + return { type: checkpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', metadata: { + sourceTrajectoryStepInfo: { stepIndex: index }, + createdAt: new Date(createdAtMs).toISOString(), completedAt: new Date(createdAtMs + 10_000).toISOString(), + modelUsage: { ...(model === undefined ? {} : { model }), apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '1000', cacheReadTokens: '9000', outputTokens: '1000' }, + } }; +} +async function payload(steps, options = {}) { + return backendHarness({ summaries: { test: { stepCount: steps.length } }, + trajectories: { test: { trajectory: { steps } } }, ...options }).buildTelemetryPayloadInternal('test'); +} + +test('missing checkpoint identity stays unknown between Flash steps; its token totals survive', async () => { + const rows = [step(209, FLASH), step(211, undefined, true), step(212, FLASH)]; + const p = await payload(rows); + const cp = p.activeConversation.recentSteps.find(s => s.stepIndex === 211); + assert.equal(cp.modelKey, 'unknown'); assert.equal(cp.modelShort, '模型未知·压缩'); + assert.equal(cp.costUsd, null); assert.equal(cp.inCostUsd, null); + assert.equal(cp.contextTokens, 11000); assert.equal(cp.tokPerSec, 100); + assert.equal(p.activeConversation.speedSummary.sampleCount, 2); + assert.equal(p.consumption.account.totalTokens, 33000); + assert.equal(p.consumption.account.unpricedCalls, 1); + assert.equal(p.modelBreakdown.find(m => m.label === '模型未知').unpricedCalls, 1); + assert.equal(p.modelBreakdown.find(m => m.shortName === 'flash-3.8-high').calls, 2); + assert(!p.modelBreakdown.some(m => /argon/i.test(m.label))); + assert.equal(p.consumption.trendSeries.reduce((n,s) => n+(s.unpricedCalls || 0),0), 1); + assert.equal(p.consumption.sourcesBreakdown[0].unpricedCalls, 1); + assert.equal(p.consumption.monthlySeries.reduce((n,s) => n+(s.unpricedCalls || 0),0), 1); +}); + +test('checkpoint can explicitly use a different model; no neighbour-based overwrite', async () => { + const p = await payload([step(209, FLASH), step(211, ARGON, true), step(212, FLASH)]); + const cp = p.activeConversation.recentSteps.find(s => s.stepIndex === 211); + assert.equal(cp.modelShort, 'argon-4·压缩'); assert.equal(cp.modelSource, 'usage.model'); + assert.equal(cp.costUsd, 0.0129); assert.equal(p.consumption.account.unpricedCalls, 0); +}); + +test('ordinary calls with missing model are unknown too', () => { + const [s] = extractModelSteps([step(1)]); + assert.equal(s.modelKey, 'unknown'); assert.equal(s.modelSource, 'unavailable'); + assert.equal(s.totalTokPerSec, 100); +}); + +test('retry usage preserves its own model and counters', () => { + const row = step(211, FLASH, true); + row.metadata.retryInfos = [{ usage: row.metadata.modelUsage }]; delete row.metadata.modelUsage; + const [s] = extractModelSteps([row]); + assert.equal(s.modelKey, FLASH); assert.equal(s.inputTokens, 1000); +}); + +test('matching generator usage supplies model and wins over requested generator model', () => { + const [s] = extractModelSteps([step(211)], [{stepIndices: [211], chatModel: { + usage: { model: FLASH }, model: ARGON, + }}]); + assert.equal(s.modelKey, FLASH); assert.equal(s.modelSource, 'chat.usage.model'); +}); + +test('unrelated generator metadata never supplies the missing model', () => { + const [s] = extractModelSteps([step(211)], [{stepIndices: [0], chatModel: {model: FLASH}}]); + assert.equal(s.modelKey, 'unknown'); +}); + +test('unspecified enum values fall through to actual step model evidence', () => { + for (const missing of ['', ' ', 'unknown', 'MODEL_UNSPECIFIED', 'MODEL_UNKNOWN', '0', 0, null]) { + const row = step(211, missing); row.metadata.generatorModel = FLASH; + const [s] = extractModelSteps([row]); assert.equal(s.modelKey, FLASH); + } +}); + +test('response model and display name are preserved when enum model is absent', async () => { + const row = step(211); + const raw = {trajectory: { steps: [row], generatorMetadata: [{stepIndices:[211],chatModel:{ + responseModel:'gemini-3.8-flash-high',modelDisplayName:'Gemini 3.8 Flash (High)', + }}]}}; + const p = await payload([], {trajectories: {test:raw}}); + assert.equal(p.activeConversation.activeModelShort,'flash-3.8-high'); +}); + +test('server model catalog overrides static placeholder mapping', () => { + const {resolveModelInfo} = backendHarness(); + const result = resolveModelInfo(ARGON, new Map([[ARGON, {modelId:'gemini-3.8-flash-high', label:'Gemini 3.8 Flash (High)'}]])); + assert.equal(result.shortName,'flash-3.8-high'); assert.equal(result.pricing.input,0.75); +}); + +test('uncatalogued model keeps identity and does not borrow another model price', async () => { + const p = await payload([step(211, 'MODEL_PLACEHOLDER_M999')]); + assert.equal(p.activeConversation.activeModelShort,'MODEL_PLACEHOLDER_M999'); + assert.equal(p.activeConversation.latestStepCostUsd,null); + assert.equal(p.consumption.account.unpricedCalls,1); +}); + +test('old ambiguous Argon cache is persisted as unresolved while retaining modern measurements', async () => { + const original = extractModelSteps([step(211, ARGON, true)])[0]; + delete original.modelIdentityVersion; delete original.modelSource; + const old = {signature:'v9-unified-throughput:old',steps:[original]}; + const h = backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}}); + const p = await h.buildTelemetryPayloadInternal('test'); + const s = p.activeConversation.recentSteps[0]; + assert.equal(s.modelKey,'unknown'); assert.equal(s.legacyModelKey,ARGON); + assert.equal(s.modelSource,'legacy_unverified'); assert.equal(s.totalTokPerSec,100); + assert.equal(p.consumption.account.totalTokens,11000); + assert.equal(p.consumption.account.unpricedCalls,1); + assert.equal(h.state.saves.length,1); + await h.buildTelemetryPayloadInternal('test'); + assert.equal(h.state.saves.length,1,'do not rewrite identical migrated cache every poll'); + h.state.trajectories.test = {trajectory:{steps:[step(211,FLASH,true)]}}; + const restored = await h.buildTelemetryPayloadInternal('test'); + assert.equal(restored.activeConversation.activeModelShort,'flash-3.8-high·压缩'); + assert.equal(restored.consumption.account.unpricedCalls,0); +}); + +test('explicit historical models and verified real Argon identities survive cache load', () => { + const known = extractModelSteps([step(211, ARGON)])[0]; + assert.equal(normalizeCachedStep(known).modelKey,ARGON); + const flash = {...known,modelKey:FLASH}; delete flash.modelIdentityVersion; + assert.equal(normalizeCachedStep(flash).modelKey,FLASH); + assert.equal(normalizeCachedStep(flash).modelIdentityVersion, MODEL_IDENTITY_VERSION); +}); + +test('empty session does not invent an Argon model or a model quota pool', async () => { + const p = await backendHarness().buildTelemetryPayloadInternal('test'); + assert.equal(p.activeConversation.activeModelShort,'模型未知'); + assert.equal(p.quotas.activePool.isAvailable,false); assert.equal(p.quotas.activePool.family,'Unknown'); +}); + +test('unknown cost renders as pending, known subtotals disclose missing calls', () => { + assert.equal(formatUsd(null),'待定'); assert.equal(formatUsd(0),'$0.00'); + assert.equal(formatUsd(0.1,{unpricedCalls:1}),'$0.10 + 待定'); +}); + +test('custom cost budget cannot claim a complete remaining percentage when prices are missing', async () => { + const p = await payload([step(211)], {settings:{weeklyLimitMode:'custom_cost'}}); + assert.equal(p.quotas.weekly.usedPct,null); assert.equal(p.quotas.weekly.remainingPct,null); +}); + +test('frontend considers a model-only correction a real telemetry update', () => { + const source = fs.readFileSync(new URL('../src/store/telemetryStore.js',import.meta.url),'utf8'); + const fn = source.slice(source.indexOf('function isEquivalentTelemetry'),source.indexOf('export async function fetchTelemetry')); + const ctx = {}; vm.runInNewContext(fn+'\nglobalThis.compare=isEquivalentTelemetry;',ctx); + const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}}; + const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model'; + assert.equal(ctx.compare(a,b),false); assert.equal(ctx.compare(a,structuredClone(a)),true); +}); diff --git a/sidecars/panel/test/speed-metrics.test.mjs b/sidecars/panel/test/speed-metrics.test.mjs new file mode 100644 index 0000000..18810cd --- /dev/null +++ b/sidecars/panel/test/speed-metrics.test.mjs @@ -0,0 +1,157 @@ +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 s={status,type:'CORTEX_STEP_TYPE_PLANNER_RESPONSE',metadata:{ + createdAt:'2026-01-01T00:00:00Z',viewableAt:'2026-01-01T00:00:02Z', + finishedGeneratingAt:new Date(Date.parse('2026-01-01T00:00:00Z')+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('text, tools and mixed output all use total output / full request duration',()=>{ + for(const tools of [false,true])for(const text of [false,true]){ + const step=parse({tools,text}); + assert.equal(speedMetric(step).value,1100/12); + assert.equal(step.speedBasis,'request_total'); + assert.equal(step.speedSampleEligible,true); + } +}); +test('buffered JSON cannot create a burst peak by shortening native or thinking phase timers',()=>{ + for(const stream of ['0.001s','0.01s','1s','10s',undefined]){ + for(const thinkingDuration of ['0.01s','9.999s',undefined]){ + const step=parse({total:10,ttft:'9.999s',stream,thinkingDuration,output:300,tools:true,text:false}); + assert.equal(step.totalTokPerSec,30); + assert.equal(step.ttftSec,9.999); + } + } +}); +test('TTFT is the exact native value, never a token-ratio guess or viewable-event substitute',()=>{ + assert.equal(parse({total:20,ttft:'19.9s',thinkingDuration:'19.95s',tools:true,text:false}).ttftSec,19.9); + const {s,gm}=sample();delete gm.chatModel.timeToFirstToken; + const step=extractModelSteps([s],[gm])[0]; + assert.equal(step.ttftSec,null);assert.equal(step.viewableDelaySec,2); + assert.deepEqual(summarizeTtft([step]),{sampleCount:0,avgSec:null}); +}); +test('zero TTFT is preserved and malformed or negative durations remain unknown',()=>{ + const zero=parse({ttft:'0s'}); + assert.equal(zero.ttftSec,0); + assert.equal(summarizeTtft([zero]).avgSec,0); + for(const ttft of ['-1s','12garbage','NaNs','Infinitys',''])assert.equal(parse({ttft}).ttftSec,null); +}); +test('short output keeps the same formula but does not bias the mean',()=>{ + const short=parse({output:13,response:13,thinking:0,total:5.015,stream:'0.118s'}); + assert.equal(short.totalTokPerSec,13/5.015); + assert.equal(short.speedReason,'short_sample'); + assert.equal(summarizeSpeed([short,parse()]).avgTokPerSec,1100/12); + assert.equal(summarizeSpeed([short]).avgTokPerSec,null); + assert.equal(parse({output:50}).speedSampleEligible,true); +}); +test('sub-half-second whole requests are withheld, never divided by a tiny interval',()=>{ + const tiny=parse({total:.05,output:1000}); + assert.equal(tiny.totalTokPerSec,null);assert.equal(tiny.speedReason,'short_timing'); + assert.equal(speedMetric(tiny).value,null); + assert.equal(summarizeSpeed([tiny]).sampleCount,0); + assert.equal(parse({total:.5,output:100,ttft:'0.1s'}).totalTokPerSec,200); +}); +test('weighted mean matches token/time totals and does not average step rates',()=>{ + const a=parse({output:1000,total:10}),b=parse({output:1000,total:20,tools:true}); + const mean=summarizeSpeed([a,b]); + assert.equal(mean.tokens,2000);assert.equal(mean.seconds,30); + assert.equal(mean.avgTokPerSec,2000/30);assert.equal(mean.sampleCount,2); +}); +test('unfinished, missing-completion and reversed-time requests cannot fabricate speed',()=>{ + const {s,gm}=sample();delete s.metadata.finishedGeneratingAt; + assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null); + assert.equal(parse({total:-1}).totalTokPerSec,null); + assert.equal(parse({total:0}).totalTokPerSec,null); + assert.equal(parse({status:'CORTEX_STEP_STATUS_GENERATING'}).totalTokPerSec,null); +}); +test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{ + const zero=parse({output:0,response:0,thinking:0}); + assert.equal(zero.totalTokPerSec,0);assert.equal(zero.responseTokens,0); + for(const output of [-1,1.5,NaN,Infinity])assert.equal(parse({output}).totalTokPerSec,null); + const {s,gm}=sample();delete s.metadata.modelUsage.outputTokens; + assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null); +}); +test('missing phase/token breakdown cannot change a valid full-request rate',()=>{ + const {s,gm}=sample();delete s.plannerResponse.thinkingDuration; + delete s.metadata.modelUsage.thinkingOutputTokens;delete s.metadata.modelUsage.responseOutputTokens; + delete gm.chatModel.streamingDuration; + assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,1100/12); +}); +test('no rate-dependent cap or formula switch at the former 260 TPS boundary',()=>{ + const a=parse({total:10,output:2590,tools:true}),b=parse({total:10,output:2610,tools:true}); + assert.equal(a.totalTokPerSec,259);assert.equal(b.totalTokPerSec,261); + assert.equal(a.speedBasis,b.speedBasis); +}); +test('legacy cache retains billing but cannot masquerade as current measurements',()=>{ + for(const measurementVersion of [undefined,1,2,3]){ + const old={measurementVersion,inputTokens:500,cacheReadTokens:2000,outputTokens:1100,ttftSec:0.4,totalTokPerSec:55}; + const migrated=normalizeCachedStep(old); + assert.equal(migrated.outputTokens,1100);assert.equal(migrated.inputTokens,500); + assert.equal(migrated.ttftSec,null);assert.equal(speedMetric(migrated).value,null); + assert.equal(speedMetric(migrated).reason,'legacy_cache'); + } +}); + +test('half-second cutoff uses the original nanoseconds, not rounded epoch milliseconds',()=>{ + const {s,gm}=sample({output:100,ttft:'0.1s'}); + s.metadata.createdAt='2026-01-01T00:00:00.000000001Z'; + s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000000Z'; + const below=extractModelSteps([s],[gm])[0]; + assert.equal(below.totalDurationSec,.499999999);assert.equal(below.totalTokPerSec,null); + s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000001Z'; + assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200); + s.metadata.createdAt='2026-01-01T08:00:00.000000001+08:00'; + assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200); +}); +test('non-chat generator metadata cannot overwrite matching model timing',()=>{ + const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42};gm.stepIndices=[42]; + const other={stepIndices:[42],tool:{}}; + assert.equal(extractModelSteps([s],[gm,other])[0].nativeTtftSec,2); + s.metadata.generatorMetadata=[other,{chatModel:{timeToFirstToken:'3s'}}]; + assert.equal(extractModelSteps([s],[gm])[0].nativeTtftSec,3); +}); +test('a paginated source step never borrows timing from an unrelated array position',()=>{ + const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42}; + const step=extractModelSteps([s],[gm])[0]; + assert.equal(step.nativeTtftSec,null);assert.equal(step.totalTokPerSec,1100/12); +}); +test('contradictory native TTFT is preserved but cannot validate TPS or bias the TTFT mean',()=>{ + const bad=parse({total:5,ttft:'9s'}); + assert.equal(bad.nativeTtftSec,9);assert.equal(bad.totalTokPerSec,null); + assert.equal(bad.speedReason,'inconsistent_timing'); + assert.deepEqual(summarizeTtft([bad,parse()]),{sampleCount:1,avgSec:2}); +}); +test('unfinished steps do not enter the TTFT mean even when partial metadata includes TTFT',()=>{ + const partial=parse({status:'CORTEX_STEP_STATUS_GENERATING',ttft:'8s'}); + assert.deepEqual(summarizeTtft([partial,parse()]),{sampleCount:1,avgSec:2}); +}); +test('coercible non-token values cannot silently become zero or one output token',()=>{ + for(const value of [true,false,' ',[],{}]){ + const {s,gm}=sample();s.metadata.modelUsage.outputTokens=value; + assert.equal(extractModelSteps([s],[gm])[0].speedReason,'invalid_output_tokens'); + } +}); +test('visible buffered text and tools use full time without a rate-dependent switch',()=>{ + const {s,gm}=sample({output:64,thinking:33,response:31,ttft:'7.0108593s',stream:'0.0045919s'}); + s.metadata.finishedGeneratingAt='2026-01-01T00:00:07.015451200Z'; + delete s.plannerResponse.thinkingDuration; + const step=extractModelSteps([s],[gm])[0]; + assert.equal(step.totalDurationSec,7.0154512); + assert.equal(speedMetric(step).value,64/7.0154512); + assert.equal(step.speedBasis,'request_total'); +}); +test('compaction displays a valid rate and retains billing but is excluded from speed/TTFT means',()=>{ + const {s,gm}=sample();s.type='CORTEX_STEP_TYPE_CHECKPOINT'; + const step=extractModelSteps([s],[gm])[0]; + assert.equal(step.outputTokens,1100);assert.equal(speedMetric(step).value,1100/12); + assert.equal(summarizeSpeed([step]).sampleCount,0); + assert.equal(summarizeTtft([step]).sampleCount,0); +}); diff --git a/sidecars/panel/test/stream-diagnostics.test.mjs b/sidecars/panel/test/stream-diagnostics.test.mjs new file mode 100644 index 0000000..149dcc9 --- /dev/null +++ b/sidecars/panel/test/stream-diagnostics.test.mjs @@ -0,0 +1,194 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { ConnectJsonDecoder, StreamObservation, StreamDiagnostics, encodeConnectJson } from '../stream-diagnostics.mjs'; + +const ID = '12345678-1234-1234-1234-123456789abc'; +const CREATED = '2026-10-15T01:00:00.000Z'; +const FINISHED = '2026-10-15T01:00:08.000Z'; +const event = (ms, batch = ms) => ({ elapsedMs: ms, receiveBatch: batch, receivedAt: CREATED }); +const model = (p = {}, done = false, extra = {}) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', status: done ? 'CORTEX_STEP_STATUS_DONE' : 'CORTEX_STEP_STATUS_STREAMING', + metadata: { createdAt: CREATED, ...(done ? { finishedGeneratingAt: FINISHED, modelUsage: { outputTokens: '400' } } : {}) }, + plannerResponse: p, ...extra, +}); +const update = (indices, steps, totalLength, more = {}) => ({ update: { conversationId: ID, + mainTrajectoryUpdate: { stepsUpdate: { indices, steps, totalLength }, ...more } } }); +function observer() { + const records = []; + const observation = new StreamObservation({ conversationId: ID, connectedWallMs: Date.parse(CREATED) - 1000, emit: r => records.push(r) }); + return { records, observation }; +} + +test('Connect decoder reconstructs fragmented headers/UTF-8 and keeps coalesced messages separate', () => { + const a = { update: { text: '中文🙂' } }; + const b = { update: { text: 'second' } }; + const bytes = Buffer.concat([encodeConnectJson(a), encodeConnectJson(b)]); + const decoder = new ConnectJsonDecoder(); + const messages = []; + for (let i = 0; i < bytes.length; i += 3) messages.push(...decoder.push(bytes.subarray(i, i + 3))); + decoder.finish(); + assert.deepEqual(messages.map(m => m.value), [a, b]); + const end = encodeConnectJson({}); end[0] = 2; + assert.equal(decoder.push(end)[0].end, true); + assert.throws(() => decoder.push(encodeConnectJson(a)), /data_after_end/); +}); + +test('Connect decoder rejects oversized, compressed, malformed and truncated frames', () => { + const huge = Buffer.from([0, 0, 0, 1, 0]); + assert.throws(() => new ConnectJsonDecoder(100).push(huge), /frame_too_large/); + const compressed = encodeConnectJson({}); compressed[0] = 1; + assert.throws(() => new ConnectJsonDecoder().push(compressed), /unsupported_frame_flags/); + assert.throws(() => new ConnectJsonDecoder().push(Buffer.from([0, 0, 0, 0, 1, 120])), /invalid_frame_json/); + const decoder = new ConnectJsonDecoder(); decoder.push(Buffer.from([0, 0])); + assert.throws(() => decoder.finish(), /truncated_frame/); +}); + +test('history, delayed rehydration and status-only notifications never become live output', () => { + const { observation: o, records } = observer(); + o.accept({ update: { conversationId: ID, status: 'IDLE' } }, event(0)); + assert.equal(o.initialized, false); + o.accept(update([9], [model({ response: 'old response' }, true)], 10), event(1)); + o.accept(update([4], [model({ response: 'late history' }, true)], 10), event(2)); + assert.equal(o.contentEvents, 0); + assert.equal(o.recent.length, 0); + assert.deepEqual(records.map(r => r.kind), ['baseline']); +}); + +test('tool arguments, thinking and text are counted independently; receive batches are not tokens', () => { + const { observation: o, records } = observer(); + o.accept(update([], [], 10), event(0)); + o.accept(update([10], [model()], 11), event(10)); + o.accept(update([10], [model({ thinking: 'hidden-secret', response: '中', toolCalls: [{ argumentsJson: '{', name: 'secret-tool' }] })], 11), event(20, 2)); + o.accept(update([10], [model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"' }] })], 11), event(20, 2)); + const full = model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"argument-secret"}' }] }, true); + o.accept(update([10], [full], 11), event(120, 3)); + o.accept(update([10], [full], 11), event(300, 4)); + o.accept(update([], [], 11, { generatorMetadatasUpdate: { generatorMetadatas: [{ stepIndices: [10], chatModel: { + usage: { outputTokens: '400', thinkingOutputTokens: '50', responseHeader: { authorization: 'credential-secret' } }, + timeToFirstToken: '7.999s', streamingDuration: '0.001s', systemPrompt: 'prompt-secret', + } }] } }), event(400, 5)); + const r = o.recent[0]; + assert.equal(r.contentEvents, 3); + assert.equal(r.contentReceiveBatches, 2); + assert.equal(r.toolArgumentEvents, 3); + assert.equal(r.observedSpanMs, 100); + assert.equal(r.channels.text.bytes, 6); + assert.equal(r.channels.text.utf16Units, 2); + assert.equal(r.usage.outputTokens, 400); + assert.equal(r.nativeStreamSec, 0.001); + assert.equal(r.partialCapture, false); + const serialized = JSON.stringify([records, r]); + for (const secret of ['hidden-secret', 'argument-secret', 'secret-tool', 'credential-secret', 'prompt-secret', '中文']) assert.ok(!serialized.includes(secret)); + assert.ok(!/tokPerSec|tps|firstTokenMs/i.test(serialized)); +}); + +test('same-batch delivery is not reported as a timed stream, even with several updates', () => { + const { observation: o } = observer(); + o.accept(update([], [], 0), event(0)); + o.accept(update([0], [model({ response: 'a' })], 1), event(5, 1)); + o.accept(update([0], [model({ response: 'ab' }, true)], 1), event(5, 1)); + assert.equal(o.recent[0].observation, 'single_receive_batch'); + assert.equal(o.recent[0].observedSpanMs, 0); +}); + +test('rewrites, shrinking output and tool-only updates are retained as revisions', () => { + const { observation: o, records } = observer(); + o.accept(update([], [], 0), event(0)); + o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'abcd' }] })], 1), event(10)); + o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wxyz' }] })], 1), event(20)); + o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wx' }] }, true)], 1), event(30)); + assert.equal(o.recent[0].revisions, 2); + assert.equal(o.recent[0].toolArgumentEvents, 3); + assert.equal(records.at(-1).changes.toolArguments.deltaBytes, -2); + assert.equal(records.at(-1).changes.toolArguments.appendOnly, false); +}); + +test('joining during generation marks partial capture and excludes initial content from updates', () => { + const { observation: o } = observer(); + o.accept(update([2], [model({ response: 'already there' })], 3), event(10)); + o.accept(update([2], [model({ response: 'already there plus more' }, true)], 3), event(20)); + assert.equal(o.recent[0].partialCapture, true); + assert.equal(o.recent[0].contentEvents, 1); + assert.equal(o.recent[0].observation, 'partial_capture'); +}); + +test('missing or earlier creation time never claims a complete observation', () => { + const { observation: o } = observer(); + o.accept(update([], [], 0), event(0)); + o.accept(update([0], [model({ response: 'arrived' }, true, { metadata: { finishedGeneratingAt: FINISHED } })], 1), event(20)); + assert.equal(o.recent[0].partialCapture, true); + assert.throws(() => o.accept(update([], [model()], 2), event(25)), /invalid_step_indices/); +}); + +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +async function until(check) { + for (let i = 0; i < 100; i++) { if (check()) return; await sleep(10); } + assert.fail('timed out'); +} +function temp(t) { + const dir = mkdtempSync(join(tmpdir(), 'usage-monitor-diag-test-')); + t.after(() => { + const absolute = resolve(dir); + assert.equal(dirname(absolute), resolve(tmpdir())); + assert.ok(absolute.startsWith(join(resolve(tmpdir()), 'usage-monitor-diag-test-'))); + rmSync(absolute, { recursive: true, force: true }); + }); + return dir; +} + +test('collector only subscribes to read APIs, persists counters and stops without touching billing', async t => { + const dir = temp(t); + const calls = []; + let streamController; + const fetchImpl = async (url, options) => { + calls.push({ url, options }); + if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: { stepCount: 0, lastModifiedTime: CREATED } } })); + assert.ok(url.endsWith('StreamAgentStateUpdates')); + const request = new ConnectJsonDecoder().push(options.body)[0].value; + assert.equal(request.trajectoryVerbosity, 'CLIENT_TRAJECTORY_VERBOSITY_FULL'); + const stream = new ReadableStream({ start(c) { + streamController = c; + c.enqueue(encodeConnectJson(update([], [], 0))); + options.signal.addEventListener('abort', () => c.error(new Error('aborted')), { once: true }); + } }); + return new Response(stream, { headers: { 'Content-Type': 'application/connect+json' } }); + }; + const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'secret-csrf', fetchImpl, pollMs: 60000 }); + t.after(() => d.stop()); + assert.equal(d.status().enabled, false); + d.configure({ enabled: true }); + await until(() => d.status().phase === 'collecting'); + streamController.enqueue(encodeConnectJson(update([0], [model({ toolCalls: [{ argumentsJson: 'private-arguments' }] }, true)], 1))); + await until(() => d.status().contentEvents === 1); + assert.equal(d.status().affectsTps, false); + d.configure({ enabled: false }); + await sleep(10); + assert.equal(d.status().phase, 'disabled'); + assert.equal(d.current, null); + const log = readFileSync(join(dir, 'stream-diagnostics', 'events.jsonl'), 'utf8'); + assert.ok(!log.includes('secret-csrf')); + assert.ok(!log.includes('private-arguments')); + assert.ok(log.includes('step_update')); + assert.deepEqual(readdirSync(dir).sort(), ['stream-diagnostics', 'stream-diagnostics-config.json']); + assert.equal(calls.length, 2); +}); + +test('failed subscriptions back off and never expose the server error body', async t => { + const dir = temp(t); + let calls = 0; + const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'csrf', pollMs: 10, retryMs: 5000, + fetchImpl: async url => { + calls++; + if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: {} } })); + return new Response('private server error with credentials', { status: 403 }); + } }); + t.after(() => d.stop()); + d.configure({ enabled: true }); + await until(() => d.status().error === 'stream_http_403'); + await sleep(40); + assert.equal(calls, 2); + assert.ok(!JSON.stringify(d.status()).includes('private')); +});