commit 40c4ea9f1b3c897936d485c077172021abca27ce Author: yuhuan2498281558 Date: Wed Oct 14 03:39:01 2026 +0800 feat: real-time tok/s speed & official 5h/weekly quota monitor plugin diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7d98f0b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.data/ +node_modules/ +*.log +.DS_Store +Thumbs.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..4f6f8e0 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# Usage & Speed Monitor (`usage-monitor`) + +Antigravity 实时测速与额度监控面板插件(UI Extension Sidecar),提供紧凑测速状态栏与官方配额监控卡片: + +- **实时 `tok/s` 与均速**:基于 `GetCascadeTrajectory` 纳秒级时间戳与 `plannerResponse.thinkingDuration` 精确计算纯输出流速度(扣除思考耗时)与含思考整体速度(点击 `tok/s` 可一键切换口径),自动过滤纯工具调用步骤的缓冲尖峰。 +- **首字耗时 (TTFT)**:精确计算 `viewableAt - createdAt` 端到端首包响应时间。 +- **缓存命中率 & 上下文进度格**:显示 `cacheReadTokens` 占比、5 格平行四边形进度指示(`▰▱▱▱▱`),以及四色分段上下文窗口进度条(缓存读取 / 新增输入 / 思考输出 / 正文输出,支持 `200k` / `1M` / `2M` 切换)。 +- **5h 会话限额 & 官方每周限额**:直连 Language Server `RetrieveUserQuotaSummary` 与 `GetUserStatus` 接口,实时同步展示 `Gemini 模型池` 与 `Claude & GPT 模型池` 的 5 小时限额及官方每周限额(精确到小数点后一位,显示已用与剩余百分比及重置倒计时)。 +- **今日与每周累计消耗**:跨会话统计本机今日与本周所有模型的累计 Token、调用步数与折算美元费用,并提供单步测速明细表(悬停查看思考/输出细分)与按模型汇总表。 diff --git a/assets/logo.svg b/assets/logo.svg new file mode 100644 index 0000000..84ae1c4 --- /dev/null +++ b/assets/logo.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/plugin.json b/plugin.json new file mode 100644 index 0000000..f2eafb7 --- /dev/null +++ b/plugin.json @@ -0,0 +1,12 @@ +{ + "name": "usage-monitor", + "displayName": "Usage & Speed Monitor", + "version": "1.0.0", + "description": "实时监控 Token/s 生成测速、首字延迟(TTFT)、缓存命中率、上下文窗口占用、5h 会话限额倒计时以及今日/每周累计消耗。", + "logo": "assets/logo.svg", + "suggestedPrompts": [ + "打开测速与额度监控面板查看当前会话性能", + "分析当前会话的 Token 消耗与缓存命中率", + "查看今日和本周各模型的累计 Token 与费用明细" + ] +} diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js new file mode 100644 index 0000000..db8204d --- /dev/null +++ b/sidecars/panel/app.js @@ -0,0 +1,377 @@ +// Frontend controller for Antigravity Usage & Speed Monitor. +const sidecar = window.sidecar; +const $ = (id) => document.getElementById(id); + +let selectedConversationId = sidecar?.conversationId || ''; +let latestTelemetry = null; +let showAllPools = true; +let lastConvSelectSig = ''; + +function escapeHtml(str) { + return String(str ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +function formatTokens(num) { + const n = Number(num || 0); + if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; + if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; + return String(n); +} + +function formatCountdown(isoTime) { + if (!isoTime) return '未知重置时间'; + const targetMs = Date.parse(isoTime); + if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间'; + const diffMs = targetMs - Date.now(); + if (diffMs <= 0) return '即将重置'; + + const totalMinutes = Math.floor(diffMs / 60000); + const days = Math.floor(totalMinutes / (60 * 24)); + const hours = Math.floor((totalMinutes % (60 * 24)) / 60); + const minutes = totalMinutes % 60; + + if (days > 0) { + return `${days} 天 ${hours} 小时后重置`; + } + if (hours > 0) { + return `${hours} 小时 ${minutes} 分钟后重置`; + } + return `${minutes} 分钟后重置`; +} + +function renderParallelograms(usedPct) { + const container = $('ctx-parallelograms'); + container.innerHTML = ''; + // 5 blocks, each representing 20% context usage (at least 1 filled when > 0%) + const filledCount = usedPct <= 0 ? 0 : Math.min(5, Math.max(1, Math.ceil(usedPct / 20))); + const toneClass = usedPct >= 80 ? 'danger' : usedPct >= 55 ? 'warn' : ''; + + for (let i = 0; i < 5; i++) { + const blk = document.createElement('span'); + blk.className = `para-block ${toneClass} ${i < filledCount ? 'filled' : ''}`.trim(); + container.appendChild(blk); + } +} + +async function callApi(path, { method = 'GET', body } = {}) { + const fetchFn = sidecar?.fetch ? sidecar.fetch.bind(sidecar) : window.fetch.bind(window); + const res = await fetchFn(path, { + method, + headers: { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + throw new Error(data.error || `${res.status}`); + } + return data; +} + +function renderConversationsSelect(conversations, activeId) { + const sel = $('conv-select'); + // Avoid resetting dropdown DOM while user is actively interacting with it + if (document.activeElement === sel) return; + + const sig = `${selectedConversationId}::${activeId}::${conversations + .map((c) => `${c.cascadeId}:${c.stepCount}:${c.title}`) + .join('|')}`; + if (sig === lastConvSelectSig) return; + lastConvSelectSig = sig; + + sel.innerHTML = ''; + + const autoOpt = document.createElement('option'); + autoOpt.value = ''; + const latestConv = conversations[0]; + autoOpt.textContent = latestConv + ? `⚡ 自动跟随 (${latestConv.title})` + : '⚡ 自动跟随最新会话'; + if (!selectedConversationId) autoOpt.selected = true; + sel.appendChild(autoOpt); + + for (const c of conversations) { + const opt = document.createElement('option'); + opt.value = c.cascadeId; + opt.textContent = `${c.title} (${c.stepCount}步)`; + if (selectedConversationId && c.cascadeId === selectedConversationId) { + opt.selected = true; + } + sel.appendChild(opt); + } +} + +function renderAllPools(pools, activeFamily) { + const box = $('all-pools-container'); + box.hidden = !showAllPools; + if (!showAllPools) return; + + box.innerHTML = ''; + for (const p of pools) { + const row = document.createElement('div'); + row.className = 'pool-mini-row'; + const isCurrent = p.family === activeFamily; + const used5h = Number(p.usedPct ?? 0).toFixed(1); + const rem5h = Number(p.remainingPct ?? 100).toFixed(1); + const wkPart = + p.weeklyUsedPct != null + ? ` · 周已用 ${Number(p.weeklyUsedPct).toFixed(1)}% (余 ${Number(p.weeklyRemainingPct ?? 100).toFixed(1)}%)` + : ''; + row.innerHTML = ` + ${isCurrent ? '● ' : ''}${escapeHtml(p.poolName)} + 5h已用 ${used5h}% (余 ${rem5h}%)${wkPart} + `; + box.appendChild(row); + } +} + +function renderTables(activeConv, modelBreakdown) { + const stepsTbody = $('steps-tbody'); + stepsTbody.innerHTML = ''; + for (const st of activeConv.recentSteps || []) { + const tr = document.createElement('tr'); + const thinkInfo = st.thinkingTokens + ? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | ` + : ''; + tr.title = `${thinkInfo}正文/工具输出: ${st.responseTokens} tok | 流耗时: ${st.streamDurationSec}s | 总耗时: ${st.totalDurationSec}s`; + tr.innerHTML = ` + #${Number(st.stepIndex)} + ${escapeHtml(st.modelShort)} + ${Number(st.tokPerSec).toFixed(1)} tok/s + ${Number(st.ttftSec).toFixed(1)}s + ${formatTokens(st.contextTokens)} / +${Number(st.outputTokens)} + ${Number(st.cacheHitPct)}% + `; + stepsTbody.appendChild(tr); + } + + const modelsTbody = $('models-tbody'); + modelsTbody.innerHTML = ''; + for (const m of modelBreakdown || []) { + const tr = document.createElement('tr'); + tr.innerHTML = ` + ${escapeHtml(m.shortName)} (${Number(m.calls)}) + ${Number(m.calls)} + ${Number(m.avgTokPerSec).toFixed(1)} tok/s + ${formatTokens(m.totalTokens)} + ≈$${Number(m.costUsd).toFixed(2)} + `; + modelsTbody.appendChild(tr); + } +} + +function applyTelemetryToDom(data) { + latestTelemetry = data; + const active = data.activeConversation || {}; + const ctx = active.context || {}; + const quotas = data.quotas || {}; + const settings = data.settings || {}; + + // 1. Top session bar + $('conv-title').textContent = active.title || '当前会话'; + renderConversationsSelect(data.conversations || [], active.cascadeId); + + const livePill = $('live-status-pill'); + const speedDot = $('speed-dot'); + if (active.isRunning) { + livePill.textContent = '生成中…'; + livePill.classList.add('running'); + speedDot.classList.add('pulsing'); + } else { + livePill.textContent = '实时 2s'; + livePill.classList.remove('running'); + speedDot.classList.remove('pulsing'); + } + + // 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)}`; + $('session-cost-value').textContent = `$${Number(active.sessionCostUsd || 0).toFixed(2)}`; + $('cache-hit-value').textContent = `${active.latestCacheHitPct ?? 0}%`; + renderParallelograms(ctx.usedPct || 0); + + $('active-model-short').textContent = active.activeModelShort || 'argon-4'; + $('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' ? '整体测速(含思考)' : '输出流测速'; + + // 3. Context Window Popover Section + const limitLabel = formatTokens(ctx.limitTokens || 1000000); + $('ctx-summary-text').textContent = `${formatTokens(ctx.totalTokens || 0)} / ${limitLabel} (${ctx.usedPct || 0}%)`; + + const limit = Math.max(1, ctx.limitTokens || 1000000); + $('bar-ctx-cached').style.width = `${Math.min(100, (ctx.cachedTokens / limit) * 100)}%`; + $('bar-ctx-input').style.width = `${Math.min(100, (ctx.freshInputTokens / limit) * 100)}%`; + $('bar-ctx-thinking').style.width = `${Math.min(100, (ctx.thinkingTokens / limit) * 100)}%`; + $('bar-ctx-output').style.width = `${Math.min(100, (ctx.responseTokens / limit) * 100)}%`; + + $('bd-cached').textContent = formatTokens(ctx.cachedTokens); + $('bd-input').textContent = formatTokens(ctx.freshInputTokens); + $('bd-thinking').textContent = formatTokens(ctx.thinkingTokens); + $('bd-output').textContent = formatTokens(ctx.responseTokens); + + document.querySelectorAll('[data-ctx-limit]').forEach((btn) => { + btn.classList.toggle('active', Number(btn.dataset.ctxLimit) === Number(ctx.limitTokens)); + }); + + // 4. Quotas Section + $('account-tier-label').textContent = `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`; + const activePool = quotas.activePool || {}; + const used5hStr = Number(activePool.usedPct ?? 0).toFixed(1); + const rem5hStr = Number(activePool.remainingPct ?? 100).toFixed(1); + $('session-quota-title').textContent = `5h 限额 (${activePool.family || '当前'})`; + $('session-reset-text').textContent = formatCountdown(activePool.resetTime); + $('session-used-pct').textContent = `已用 ${used5hStr}% (余 ${rem5hStr}%)`; + + const sessionBar = $('bar-session-quota'); + sessionBar.style.width = `${Math.min(100, activePool.usedPct || 0)}%`; + sessionBar.className = `bar-fill ${activePool.usedPct >= 85 ? 'danger' : activePool.usedPct >= 60 ? 'warn' : ''}`; + + renderAllPools(quotas.pools || [], activePool.family); + + const weekly = quotas.weekly || {}; + const usedWkStr = Number(weekly.usedPct ?? 0).toFixed(1); + const remWkStr = Number(weekly.remainingPct ?? 100).toFixed(1); + $('weekly-reset-text').textContent = formatCountdown(weekly.resetTime); + $('weekly-used-pct').textContent = `已用 ${usedWkStr}% (余 ${remWkStr}%)`; + const weeklyBar = $('bar-weekly-quota'); + weeklyBar.style.width = `${Math.min(100, weekly.usedPct || 0)}%`; + weeklyBar.className = `bar-fill ${weekly.usedPct >= 85 ? 'danger' : weekly.usedPct >= 60 ? 'warn' : ''}`; + + $('weekly-tokens-text').textContent = formatTokens(weekly.tokens || 0); + $('weekly-cost-text').textContent = `≈$${Number(weekly.costUsd || 0).toFixed(2)}`; + + if (data.account?.aiCredits != null && data.account.aiCredits > 0) { + $('credits-badge').textContent = `AI 积分: ${data.account.aiCredits}`; + } else if (weekly.calls != null) { + $('credits-badge').textContent = `本机调用: ${weekly.calls} 步`; + } else { + $('credits-badge').textContent = ''; + } + + // Sync settings inputs + const wkMode = + settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost' + ? settings.weeklyLimitMode + : 'official'; + $('setting-speed-mode').value = settings.speedMode || 'stream'; + $('setting-weekly-mode').value = wkMode; + $('setting-weekly-tokens').value = settings.weeklyTokenBudget || 80000000; + $('setting-weekly-cost').value = settings.weeklyCostBudget || 35; + + renderTables(active, data.modelBreakdown); +} + +async function refreshTelemetry(force = false) { + try { + const params = new URLSearchParams(); + if (selectedConversationId) params.set('conversationId', selectedConversationId); + if (force === true) params.set('force', '1'); + const qs = params.toString(); + const data = await callApi(`/api/telemetry${qs ? `?${qs}` : ''}`); + applyTelemetryToDom(data); + } catch (err) { + console.error('Telemetry refresh failed:', err); + $('live-status-pill').textContent = '连接重试中'; + } +} + +async function updateSettings(patch) { + try { + await callApi('/api/settings', { method: 'POST', body: patch }); + await refreshTelemetry(true); + } catch (err) { + console.error('Failed saving settings:', err); + } +} + +function bindEvents() { + $('refresh-btn').addEventListener('click', () => refreshTelemetry(true)); + + $('conv-select').addEventListener('change', (e) => { + selectedConversationId = e.target.value; + refreshTelemetry(); + }); + + // Toggle context breakdown + const toggleCtx = () => { + const box = $('ctx-breakdown-box'); + box.hidden = !box.hidden; + $('ctx-chevron').textContent = box.hidden ? '›' : '⌄'; + }; + $('ctx-detail-toggle').addEventListener('click', toggleCtx); + $('ctx-inline-trigger').addEventListener('click', toggleCtx); + + // Switch context window limit (200k / 1M / 2M) + document.querySelectorAll('[data-ctx-limit]').forEach((btn) => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + updateSettings({ contextWindowLimit: Number(btn.dataset.ctxLimit) }); + }); + }); + + // Toggle speed mode by clicking tok/s + $('speed-mode-toggle').addEventListener('click', () => { + const current = latestTelemetry?.settings?.speedMode || 'stream'; + const next = current === 'stream' ? 'total' : 'stream'; + updateSettings({ speedMode: next }); + }); + + // Toggle all model pools + $('pool-switch-toggle').addEventListener('click', () => { + showAllPools = !showAllPools; + if (latestTelemetry) { + renderAllPools( + latestTelemetry.quotas?.pools || [], + latestTelemetry.quotas?.activePool?.family + ); + } + }); + + // Toggle details panel + $('toggle-details-btn').addEventListener('click', () => { + const card = $('details-card'); + card.hidden = !card.hidden; + $('toggle-details-btn').textContent = card.hidden ? '查看详细明细' : '收起详细明细'; + }); + + // Switch tabs inside details panel + document.querySelectorAll('.tab-btn').forEach((btn) => { + btn.addEventListener('click', () => { + document.querySelectorAll('.tab-btn').forEach((b) => b.classList.remove('active')); + btn.classList.add('active'); + const tab = btn.dataset.tab; + $('tab-steps').hidden = tab !== 'steps'; + $('tab-models').hidden = tab !== 'models'; + }); + }); + + // Toggle settings panel + $('toggle-settings-btn').addEventListener('click', () => { + const card = $('settings-card'); + card.hidden = !card.hidden; + }); + + $('save-settings-btn').addEventListener('click', () => { + updateSettings({ + speedMode: $('setting-speed-mode').value, + weeklyLimitMode: $('setting-weekly-mode').value, + weeklyTokenBudget: Number($('setting-weekly-tokens').value), + weeklyCostBudget: Number($('setting-weekly-cost').value), + }); + $('settings-card').hidden = true; + }); +} + +function init() { + bindEvents(); + refreshTelemetry(); + setInterval(refreshTelemetry, 2000); +} + +init(); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html new file mode 100644 index 0000000..ca431bb --- /dev/null +++ b/sidecars/panel/index.html @@ -0,0 +1,220 @@ + + + + + + 测速与额度监控 + + + + +
+ +
+
+ 当前会话 + +
+
+ 实时 2s + +
+
+ + +
+
+ + + 0.0 tok/s + + 首字 0.0s + 均速 0.0 + | + $0.00 + 缓存 0% + | + + 上下文 + + +
+ +
+ + ⇄ + argon-4 + + + 今日 0 · ≈$0.00 + + 输出流测速 +
+
+ + +
+ +
+
+ + + 0 / 1M (0%) + › + +
+
+
+
+
+
+
+ + + +
+ +
+ + +
+
+ + → +
+ + +
+
+ 会话限额 + + -- 后重置 + 0% + +
+
+
+
+
+ + +
+ + +
+
+ 每周·所有模型 + + -- 后重置 + 0% + +
+
+
+
+
+ 本周累计: 0 (≈$0.00) + +
+
+ +
+ + +
+
+
+ + + + + + +
+ + + + diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs new file mode 100644 index 0000000..6f06d0c --- /dev/null +++ b/sidecars/panel/main.mjs @@ -0,0 +1,768 @@ +// Backend for Antigravity Usage & Speed Monitor Sidecar Extension. +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { Response, SidecarApp } from 'sidecar_sdk'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data'); +const SETTINGS_FILE = join(DATA_DIR, 'settings.json'); +const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json'); + +const LS_ADDR = process.env.ANTIGRAVITY_LS_ADDRESS; +const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN; + +const DEFAULT_SETTINGS = { + contextWindowLimit: 1000000, // 1M default (can be toggled to 200k / 2M) + weeklyTokenBudget: 80000000, // 80M tokens default custom weekly target + weeklyCostBudget: 35, // $35 default custom weekly cost target + weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost' + speedMode: 'stream', // 'stream' (streamTokens / streamTime) | 'total' (outputTokens / totalTime) +}; + +// Model pricing table in USD per 1M tokens (Input, CacheRead, Output) +const MODEL_PRICING = { + 'gemini-4-argon-high': { input: 1.25, cache: 0.3125, output: 10.0, short: 'argon-4-high', family: 'Gemini' }, + 'gemini-4-argon-medium': { input: 1.00, cache: 0.25, output: 6.0, short: 'argon-4', family: 'Gemini' }, + 'gemini-4-argon-low': { input: 0.50, cache: 0.125, output: 3.0, short: 'argon-4-low', family: 'Gemini' }, + 'gemini-3.8-flash-high': { input: 0.30, cache: 0.075, output: 2.5, short: 'flash-3.8-high', family: 'Gemini' }, + 'gemini-3.8-flash-medium': { input: 0.20, cache: 0.05, output: 1.5, short: 'flash-3.8', family: 'Gemini' }, + 'gemini-3.8-flash-low': { input: 0.10, cache: 0.025, output: 0.8, short: 'flash-3.8-low', family: 'Gemini' }, + 'claude-opus-4-6-thinking': { input: 15.0, cache: 1.50, output: 75.0, short: 'opus', family: 'Claude' }, + 'claude-sonnet-4-6': { input: 3.0, cache: 0.30, output: 15.0, short: 'sonnet', family: 'Claude' }, + 'gpt-oss-120b-medium': { input: 1.0, cache: 0.25, output: 4.0, short: 'gpt-oss', family: 'GPT' }, +}; + +// Fallback placeholder -> modelId mapping +const PLACEHOLDER_MAP = { + MODEL_PLACEHOLDER_M417: { modelId: 'gemini-4-argon-high', label: 'Gemini 4 Argon (High)' }, + MODEL_PLACEHOLDER_M418: { modelId: 'gemini-4-argon-medium', label: 'Gemini 4 Argon (Medium)' }, + MODEL_PLACEHOLDER_M419: { modelId: 'gemini-4-argon-low', label: 'Gemini 4 Argon (Low)' }, + MODEL_PLACEHOLDER_M318: { modelId: 'gemini-3.8-flash-high', label: 'Gemini 3.8 Flash (High)' }, + MODEL_PLACEHOLDER_M319: { modelId: 'gemini-3.8-flash-medium', label: 'Gemini 3.8 Flash (Medium)' }, + MODEL_PLACEHOLDER_M320: { modelId: 'gemini-3.8-flash-low', label: 'Gemini 3.8 Flash (Low)' }, + MODEL_PLACEHOLDER_M26: { modelId: 'claude-opus-4-6-thinking', label: 'Claude Opus 4.6 (Thinking)' }, + MODEL_PLACEHOLDER_M35: { modelId: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6 (Thinking)' }, + MODEL_OPENAI_GPT_OSS_120B_MEDIUM: { modelId: 'gpt-oss-120b-medium', label: 'GPT-OSS 120B (Medium)' }, +}; + +// In-memory cache of trajectory step usage: cascadeId -> { signature, steps } +const CACHE_SCHEMA_VERSION = 'v2'; +let trajectoryCache = loadJson(CACHE_FILE, {}); +const inFlightRequests = new Map(); +let quotaSummaryCache = { ts: 0, data: null }; + +function loadJson(filePath, fallback) { + if (!existsSync(filePath)) return fallback; + try { + return JSON.parse(readFileSync(filePath, 'utf8')); + } catch { + return fallback; + } +} + +function saveJson(filePath, data) { + try { + mkdirSync(DATA_DIR, { recursive: true }); + writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8'); + } catch (err) { + console.error(`Failed writing ${filePath}: ${err.message}`); + } +} + +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; +} + +async function callLsRpc(method, body = {}) { + const res = await fetch( + `http://${LS_ADDR}/exa.language_server_pb.LanguageServerService/${method}`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-codeium-csrf-token': CSRF_TOKEN, + }, + body: JSON.stringify(body), + } + ); + if (!res.ok) { + const text = await res.text().catch(() => ''); + throw new Error(`RPC ${method} failed (${res.status}): ${text}`); + } + return res.json(); +} + +async function getOfficialQuotaSummary(forceRefresh = false) { + const now = Date.now(); + if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < 8000) { + return quotaSummaryCache.data; + } + try { + const res = await callLsRpc('RetrieveUserQuotaSummary', {}); + if (res?.response?.groups) { + quotaSummaryCache = { ts: now, data: res.response }; + return res.response; + } + } catch (err) { + console.error(`RetrieveUserQuotaSummary failed: ${err.message}`); + } + return quotaSummaryCache.data; +} + +function resolveModelInfo(rawModelKey, dynamicModelMap) { + const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey] || { + modelId: rawModelKey || 'unknown', + label: rawModelKey || 'Unknown Model', + }; + const pricing = MODEL_PRICING[dyn.modelId] || { + input: 1.0, + cache: 0.25, + output: 5.0, + short: (dyn.label || 'model').split(' ')[0].toLowerCase(), + family: 'Other', + }; + return { + rawModel: rawModelKey, + modelId: dyn.modelId, + label: dyn.label, + shortName: pricing.short, + family: pricing.family, + pricing, + }; +} + +function computeStepCost(step, pricing) { + 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; + return inCost + cacheCost + outCost; +} + +function extractModelSteps(rawSteps = []) { + const parsed = []; + rawSteps.forEach((s, idx) => { + const m = s?.metadata; + const u = m?.modelUsage; + if (!u) return; + + 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(u.thinkingOutputTokens || 0); + const responseTokens = Number( + u.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 thinkingDurationSec = parseDurationSec(p.thinkingDuration); + const respText = String(p.modifiedResponse || p.response || '').trim(); + const hasVisibleText = respText.length > 0; + + let streamTokens = responseTokens; + let streamDurationSec = 0; + const ttftSec = rawViewableSec; + + if (hasVisibleText) { + const postThinkingSec = + thinkingDurationSec > 0 && totalDurationSec > thinkingDurationSec + ? totalDurationSec - thinkingDurationSec + : afterViewableSec; + + if ( + postThinkingSec >= 0.25 && + responseTokens > 0 && + responseTokens / postThinkingSec <= 240 + ) { + streamTokens = responseTokens; + streamDurationSec = postThinkingSec; + } else if ( + afterViewableSec >= 0.5 && + outputTokens > 0 && + outputTokens / afterViewableSec <= 240 + ) { + streamTokens = outputTokens; + streamDurationSec = afterViewableSec; + } else { + streamTokens = outputTokens; + streamDurationSec = totalDurationSec; + } + } else if ( + afterViewableSec >= 2.0 && + totalDurationSec > 0 && + afterViewableSec / totalDurationSec >= 0.35 && + outputTokens / afterViewableSec <= 240 + ) { + streamTokens = outputTokens; + streamDurationSec = afterViewableSec; + } else { + streamTokens = outputTokens; + streamDurationSec = totalDurationSec; + } + + const totalTokPerSec = + totalDurationSec >= 0.12 && outputTokens > 0 ? outputTokens / totalDurationSec : 0; + const streamTokPerSec = + streamDurationSec >= 0.12 && streamTokens > 0 + ? streamTokens / streamDurationSec + : totalTokPerSec; + + parsed.push({ + stepIndex: s?.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? idx, + modelKey: u.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418', + createdAt: m.createdAt || null, + createdAtMs: Math.floor(createdAtMs), + hasVisibleText, + inputTokens, + cacheReadTokens, + outputTokens, + thinkingTokens, + responseTokens, + streamTokens, + 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); + return d.getTime(); +} + +function getNextMondayResetIso(now = new Date()) { + const d = new Date(now); + const day = d.getDay(); // 0 = Sun, 1 = Mon ... + const daysUntilMon = day === 0 ? 1 : 8 - day; + d.setDate(d.getDate() + daysUntilMon); + d.setHours(0, 0, 0, 0); + return d.toISOString(); +} + +function getStartOfCurrentWeekMs(now = new Date()) { + const d = new Date(now); + const day = d.getDay(); // 0 = Sun, 1 = Mon + const diffToMon = day === 0 ? -6 : 1 - day; + d.setDate(d.getDate() + diffToMon); + d.setHours(0, 0, 0, 0); + return d.getTime(); +} + +async function buildTelemetryPayloadInternal(requestedConvId, forceQuotaRefresh = false) { + const settings = loadSettings(); + const [userStatusRes, allTrajRes, officialQuota] = await Promise.all([ + callLsRpc('GetUserStatus', {}).catch(() => ({})), + callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), + getOfficialQuotaSummary(forceQuotaRefresh), + ]); + + const userStatus = userStatusRes?.userStatus || {}; + const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || []; + const dynamicModelMap = new Map(); + + // Extract official real-time buckets from RetrieveUserQuotaSummary if available + const officialBuckets = new Map(); + for (const grp of officialQuota?.groups || []) { + for (const b of grp?.buckets || []) { + if (b?.bucketId) { + const remFrac = b.remainingFraction ?? 1; + const usedFrac = Math.max(0, Math.min(1, 1 - remFrac)); + officialBuckets.set(b.bucketId, { + bucketId: b.bucketId, + groupName: grp.displayName, + remainingFraction: remFrac, + remainingPct: +(remFrac * 100).toFixed(1), + remainingIntPct: Math.floor(remFrac * 100 + 1e-6), + usedPct: +(usedFrac * 100).toFixed(1), + resetTime: b.resetTime || null, + description: b.description || '', + }); + } + } + } + + // Group 5h quotas by model pool + const quotaPoolsMap = new Map(); + const modelQuotas = []; + const modelQuotaByKey = new Map(); + + for (const cfg of clientConfigs) { + const rawKey = cfg?.modelOrAlias?.model; + if (rawKey) { + dynamicModelMap.set(rawKey, { + modelId: cfg.modelId || rawKey, + label: cfg.label || cfg.modelId || rawKey, + quotaInfo: cfg.quotaInfo || null, + }); + } + const info = resolveModelInfo(rawKey, dynamicModelMap); + const isGemini = info.family === 'Gemini'; + const live5h = officialBuckets.get(isGemini ? 'gemini-5h' : '3p-5h'); + const liveWeekly = officialBuckets.get(isGemini ? 'gemini-weekly' : '3p-weekly'); + + const remFrac = live5h?.remainingFraction ?? cfg?.quotaInfo?.remainingFraction ?? 1; + const usedFrac = Math.max(0, Math.min(1, 1 - remFrac)); + const resetTime = live5h?.resetTime || cfg?.quotaInfo?.resetTime || null; + + const quotaItem = { + label: cfg.label, + modelId: cfg.modelId, + rawKey, + family: info.family, + remainingPct: +(remFrac * 100).toFixed(1), + remainingIntPct: Math.floor(remFrac * 100 + 1e-6), + usedPct: +(usedFrac * 100).toFixed(1), + resetTime, + weeklyRemainingPct: liveWeekly?.remainingPct ?? null, + weeklyRemainingIntPct: liveWeekly?.remainingIntPct ?? null, + weeklyUsedPct: liveWeekly?.usedPct ?? null, + weeklyResetTime: liveWeekly?.resetTime ?? null, + }; + modelQuotas.push(quotaItem); + if (rawKey) modelQuotaByKey.set(rawKey, quotaItem); + + const poolKey = isGemini ? 'Gemini' : 'Claude & GPT'; + if (!quotaPoolsMap.has(poolKey)) { + quotaPoolsMap.set(poolKey, { + poolName: isGemini ? 'Gemini 模型池' : 'Claude & GPT 模型池', + family: poolKey, + remainingPct: quotaItem.remainingPct, + remainingIntPct: quotaItem.remainingIntPct, + usedPct: quotaItem.usedPct, + resetTime, + weeklyRemainingPct: quotaItem.weeklyRemainingPct, + weeklyRemainingIntPct: quotaItem.weeklyRemainingIntPct, + weeklyUsedPct: quotaItem.weeklyUsedPct, + weeklyResetTime: quotaItem.weeklyResetTime, + models: [cfg.label], + }); + } else { + const existingPool = quotaPoolsMap.get(poolKey); + existingPool.models.push(cfg.label); + } + } + + // Enumerate all conversations + const summariesObj = allTrajRes?.trajectorySummaries || {}; + const conversations = Object.entries(summariesObj) + .map(([cascadeId, item]) => ({ + cascadeId, + title: item?.annotations?.title || item?.summary || cascadeId.slice(0, 8), + stepCount: Number(item?.stepCount || 0), + status: item?.status || '', + lastModifiedTime: item?.lastModifiedTime || item?.createdTime || '', + lastModifiedMs: parseIsoMs(item?.lastModifiedTime || item?.createdTime || ''), + })) + .sort((a, b) => b.lastModifiedMs - a.lastModifiedMs); + + // Pick active conversation: requestedConvId if valid, else most recently modified conversation + const activeConvSummary = + conversations.find((c) => c.cascadeId === requestedConvId) || + conversations[0] || + null; + const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null; + + // Refresh trajectory cache for recent conversations (modified within last 8 days) + const eightDaysAgoMs = Date.now() - 8 * 24 * 3600 * 1000; + let cacheDirty = false; + + const toFetch = conversations.filter((conv) => { + if (conv.lastModifiedMs < eightDaysAgoMs && conv.cascadeId !== activeCascadeId) { + return false; + } + const sig = `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`; + const cached = trajectoryCache[conv.cascadeId]; + const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; + return !cached || cached.signature !== sig || isRunning || Boolean(cached.wasRunning); + }); + + // Fetch trajectories with bounded concurrency (up to 4 at a time) + const CONCURRENCY = 4; + for (let i = 0; i < toFetch.length; i += CONCURRENCY) { + const batch = toFetch.slice(i, i + CONCURRENCY); + await Promise.all( + batch.map(async (conv) => { + const sig = `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`; + const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; + const prev = trajectoryCache[conv.cascadeId]; + try { + const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); + const steps = extractModelSteps(trajRes?.trajectory?.steps || []); + const prevLast = prev?.steps?.[prev.steps.length - 1]; + const nextLast = steps[steps.length - 1]; + const stepsChanged = + !prev || + prev.signature !== sig || + Boolean(prev.wasRunning) !== isRunning || + prev.steps?.length !== steps.length || + prevLast?.outputTokens !== nextLast?.outputTokens || + prevLast?.totalDurationSec !== nextLast?.totalDurationSec; + + trajectoryCache[conv.cascadeId] = { + signature: sig, + title: conv.title, + lastModifiedMs: conv.lastModifiedMs, + wasRunning: isRunning, + steps, + }; + if (stepsChanged) { + cacheDirty = true; + } + } catch (err) { + console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`); + } + }) + ); + } + + if (cacheDirty) { + saveJson(CACHE_FILE, trajectoryCache); + } + + // Compute Active Conversation Metrics + const activeEntry = activeCascadeId ? trajectoryCache[activeCascadeId] : null; + const activeSteps = activeEntry?.steps || []; + const latestStep = activeSteps.length > 0 ? activeSteps[activeSteps.length - 1] : null; + + const useStreamSpeed = settings.speedMode !== 'total'; + let sessionSpeedNumeratorTokens = 0; + let sessionSpeedDenominatorSec = 0; + let sessionCostUsd = 0; + let sessionInputTokens = 0; + let sessionCacheReadTokens = 0; + + const enrichedActiveSteps = activeSteps.map((st) => { + const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap); + const costUsd = computeStepCost(st, mInfo.pricing); + const stepStreamTokens = st.streamTokens ?? st.outputTokens; + const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec; + + if (useStreamSpeed) { + sessionSpeedNumeratorTokens += stepStreamTokens; + sessionSpeedDenominatorSec += stepStreamSec; + } else { + sessionSpeedNumeratorTokens += st.outputTokens; + sessionSpeedDenominatorSec += st.totalDurationSec; + } + + sessionCostUsd += costUsd; + sessionInputTokens += st.inputTokens; + sessionCacheReadTokens += st.cacheReadTokens; + + const tokPerSec = useStreamSpeed ? st.streamTokPerSec : st.totalTokPerSec; + const totalPrompt = st.inputTokens + st.cacheReadTokens; + const cacheHitPct = totalPrompt > 0 ? (st.cacheReadTokens / totalPrompt) * 100 : 0; + + return { + ...st, + modelLabel: mInfo.label, + modelShort: mInfo.shortName, + family: mInfo.family, + tokPerSec: +tokPerSec.toFixed(1), + ttftSec: +st.ttftSec.toFixed(1), + cacheHitPct: +cacheHitPct.toFixed(1), + costUsd: +costUsd.toFixed(4), + contextTokens: st.inputTokens + st.cacheReadTokens + st.outputTokens, + }; + }); + + const latestEnriched = + enrichedActiveSteps.length > 0 ? enrichedActiveSteps[enrichedActiveSteps.length - 1] : null; + + const sessionAvgTokPerSec = + sessionSpeedDenominatorSec > 0.1 + ? +(sessionSpeedNumeratorTokens / sessionSpeedDenominatorSec).toFixed(1) + : latestEnriched?.tokPerSec || 0; + + // Context breakdown from the latest step + const ctxCached = latestEnriched?.cacheReadTokens || 0; + const ctxFreshInput = latestEnriched?.inputTokens || 0; + const ctxThinking = latestEnriched?.thinkingTokens || 0; + const ctxResponse = latestEnriched?.responseTokens || 0; + const ctxTotal = ctxCached + ctxFreshInput + ctxThinking + ctxResponse; + const ctxLimit = Number(settings.contextWindowLimit || 1000000); + const ctxPct = ctxLimit > 0 ? Math.min(100, +((ctxTotal / ctxLimit) * 100).toFixed(1)) : 0; + + // Cache hit rate (latest step & session-wide) + const latestPromptTokens = ctxCached + ctxFreshInput; + const latestCacheHitPct = + latestPromptTokens > 0 ? Math.round((ctxCached / latestPromptTokens) * 100) : 0; + const sessionPromptTokens = sessionCacheReadTokens + sessionInputTokens; + const sessionCacheHitPct = + sessionPromptTokens > 0 ? Math.round((sessionCacheReadTokens / sessionPromptTokens) * 100) : 0; + + // Aggregate Today & Weekly across all cached trajectories + const startOfTodayMs = getStartOfLocalDayMs(); + const startOfWeekMs = getStartOfCurrentWeekMs(); + + let todayTokens = 0; + let todayCostUsd = 0; + let todayCalls = 0; + let weekTokens = 0; + let weekCostUsd = 0; + let weekCalls = 0; + const perModelStats = new Map(); + + for (const [, entry] of Object.entries(trajectoryCache)) { + for (const st of entry?.steps || []) { + const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap); + const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; + const stepCost = computeStepCost(st, mInfo.pricing); + + if (st.createdAtMs >= startOfTodayMs) { + todayTokens += stepTotalTokens; + todayCostUsd += stepCost; + todayCalls += 1; + } + if (st.createdAtMs >= startOfWeekMs) { + weekTokens += stepTotalTokens; + weekCostUsd += stepCost; + weekCalls += 1; + + if (!perModelStats.has(mInfo.label)) { + perModelStats.set(mInfo.label, { + label: mInfo.label, + shortName: mInfo.shortName, + family: mInfo.family, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + outputTokens: 0, + speedTokens: 0, + totalTokens: 0, + costUsd: 0, + totalDurationSec: 0, + }); + } + const agg = perModelStats.get(mInfo.label); + const stepStreamTokens = st.streamTokens ?? st.outputTokens; + const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec; + + 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; + } + } + } + + const rawActiveFamily = latestEnriched?.family || 'Gemini'; + const activePoolKey = rawActiveFamily === 'Gemini' ? 'Gemini' : 'Claude & GPT'; + const activeLive5h = officialBuckets.get(activePoolKey === 'Gemini' ? 'gemini-5h' : '3p-5h'); + const activeLiveWeekly = officialBuckets.get( + activePoolKey === 'Gemini' ? 'gemini-weekly' : '3p-weekly' + ); + const familyPoolQuota = quotaPoolsMap.get(activePoolKey); + + const activePoolQuota = familyPoolQuota || { + poolName: activePoolKey === 'Gemini' ? 'Gemini 模型池' : 'Claude & GPT 模型池', + family: activePoolKey, + remainingPct: activeLive5h?.remainingPct ?? 100, + remainingIntPct: activeLive5h?.remainingIntPct ?? 100, + usedPct: activeLive5h?.usedPct ?? 0, + resetTime: activeLive5h?.resetTime || null, + weeklyRemainingPct: activeLiveWeekly?.remainingPct ?? 100, + weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? 100, + weeklyUsedPct: activeLiveWeekly?.usedPct ?? 0, + weeklyResetTime: activeLiveWeekly?.resetTime || null, + models: [], + }; + + const fallbackWeeklyPct = + settings.weeklyLimitMode === 'custom_cost' || settings.weeklyLimitMode === 'cost' + ? Math.min(100, +((weekCostUsd / Math.max(1, settings.weeklyCostBudget)) * 100).toFixed(1)) + : Math.min( + 100, + +((weekTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1) + ); + + const useOfficialWeekly = + Boolean(activeLiveWeekly) && + settings.weeklyLimitMode !== 'custom_tokens' && + settings.weeklyLimitMode !== 'custom_cost'; + + const weeklyUsedPct = useOfficialWeekly ? activeLiveWeekly.usedPct : fallbackWeeklyPct; + const weeklyRemainingPct = useOfficialWeekly + ? activeLiveWeekly.remainingPct + : +(100 - fallbackWeeklyPct).toFixed(1); + const weeklyRemainingIntPct = useOfficialWeekly + ? activeLiveWeekly.remainingIntPct + : Math.max(0, Math.floor(100 - fallbackWeeklyPct)); + + // Extract genuine Google One AI credits if present (ignore legacy hardcoded 500 prompt credits) + const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find( + (c) => c?.creditType === 'GOOGLE_ONE_AI' + ); + const realAiCredits = Number(g1CreditEntry?.creditAmount || 0); + + return { + timestamp: new Date().toISOString(), + settings, + account: { + name: userStatus?.name || '', + tierName: userStatus?.userTier?.name || 'Google AI', + planName: userStatus?.planStatus?.planInfo?.planName || 'Pro', + aiCredits: realAiCredits > 0 ? realAiCredits : null, + }, + conversations: conversations.slice(0, 20), + activeConversation: { + cascadeId: activeCascadeId, + title: activeConvSummary?.title || '当前会话', + isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING', + status: activeConvSummary?.status || 'IDLE', + stepCount: enrichedActiveSteps.length, + latestTokPerSec: latestEnriched?.tokPerSec ?? 0, + latestTtftSec: latestEnriched?.ttftSec ?? 0, + avgTokPerSec: sessionAvgTokPerSec, + sessionCostUsd: +sessionCostUsd.toFixed(2), + latestCacheHitPct, + sessionCacheHitPct, + activeModelShort: latestEnriched?.modelShort || 'argon-4', + activeModelLabel: latestEnriched?.modelLabel || 'Gemini 4 Argon (Medium)', + context: { + totalTokens: ctxTotal, + limitTokens: ctxLimit, + usedPct: ctxPct, + cachedTokens: ctxCached, + freshInputTokens: ctxFreshInput, + thinkingTokens: ctxThinking, + responseTokens: ctxResponse, + }, + recentSteps: enrichedActiveSteps.slice(-15).reverse(), + }, + quotas: { + activePool: activePoolQuota, + pools: Array.from(quotaPoolsMap.values()).sort((a, b) => { + const order = { Gemini: 0, 'Claude & GPT': 1 }; + return (order[a.family] ?? 99) - (order[b.family] ?? 99); + }), + models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))), + weekly: { + isOfficial: useOfficialWeekly, + calls: weekCalls, + tokens: weekTokens, + costUsd: +weekCostUsd.toFixed(2), + usedPct: weeklyUsedPct, + remainingPct: weeklyRemainingPct, + remainingIntPct: weeklyRemainingIntPct, + resetTime: useOfficialWeekly + ? activeLiveWeekly.resetTime + : getNextMondayResetIso(), + }, + today: { + calls: todayCalls, + tokens: todayTokens, + costUsd: +todayCostUsd.toFixed(2), + }, + }, + modelBreakdown: Array.from(perModelStats.values()) + .sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label))) + .map((m) => ({ + ...m, + costUsd: +m.costUsd.toFixed(3), + avgTokPerSec: + m.totalDurationSec > 0.1 + ? +((m.speedTokens ?? m.outputTokens) / m.totalDurationSec).toFixed(1) + : 0, + })), + }; +} + +function buildTelemetryPayload(requestedConvId, forceQuotaRefresh = false) { + const key = `${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}`; + if (inFlightRequests.has(key)) { + return inFlightRequests.get(key); + } + const p = buildTelemetryPayloadInternal(requestedConvId, forceQuotaRefresh).finally(() => { + inFlightRequests.delete(key); + }); + inFlightRequests.set(key, p); + return p; +} + +// --------------------------------------------------------------------------- +// Sidecar Server Setup +// --------------------------------------------------------------------------- + +const app = new SidecarApp(); +const readLocal = (name) => readFileSync(join(HERE, name), 'utf8'); + +app.page('/', () => readLocal('index.html')); +app.page('/app.js', () => readLocal('app.js')); +app.api( + '/styles.css', + () => new Response(readLocal('styles.css'), { contentType: 'text/css' }), + 'GET' +); + +app.api( + '/api/telemetry', + async (data) => { + const convId = data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''; + const force = data?.force === '1' || data?.force === true; + return buildTelemetryPayload(convId, force); + }, + 'GET' +); + +app.api('/api/settings', (data) => { + const current = loadSettings(); + const updated = { + ...current, + contextWindowLimit: Number(data.contextWindowLimit || current.contextWindowLimit), + weeklyTokenBudget: Number(data.weeklyTokenBudget || current.weeklyTokenBudget), + weeklyCostBudget: Number(data.weeklyCostBudget || current.weeklyCostBudget), + weeklyLimitMode: data.weeklyLimitMode || current.weeklyLimitMode, + speedMode: data.speedMode || current.speedMode, + }; + saveJson(SETTINGS_FILE, updated); + return updated; +}); + +app.run(); diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json new file mode 100644 index 0000000..1f85fee --- /dev/null +++ b/sidecars/panel/package.json @@ -0,0 +1,7 @@ +{ + "name": "usage-monitor-panel", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor." +} diff --git a/sidecars/panel/sidecar.json b/sidecars/panel/sidecar.json new file mode 100644 index 0000000..79a18dd --- /dev/null +++ b/sidecars/panel/sidecar.json @@ -0,0 +1,18 @@ +{ + "command": "node", + "args": ["main.mjs"], + "restart_policy": "always", + "display_name": "测速与额度监控", + "description": "实时显示 tok/s 速度、首字耗时、缓存率、上下文占用、5h 限额与周消耗统计。", + "has_web_ui": true, + "ui_config": { + "display_name": "测速与额度监控", + "views": [ + { + "path": "/", + "entrypoint": "SIDECAR_UI_ENTRYPOINT_AUX_PANE", + "title": "测速与额度监控" + } + ] + } +} diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css new file mode 100644 index 0000000..182b8b1 --- /dev/null +++ b/sidecars/panel/styles.css @@ -0,0 +1,622 @@ +/* + * Theme-aware stylesheet for Antigravity Usage & Speed Monitor. + * Automatically adapts to host dark/light CSS variables injected by /preload.js. + */ + +:root { + --radius-lg: 12px; + --radius-md: 9px; + --radius-sm: 6px; + --speed-accent: #e05638; + --cache-green: #16a34a; + --model-blue: #2563eb; + --bar-blue: #2563eb; + --seg-cached-color: #2563eb; + --seg-input-color: #ea580c; + --seg-thinking-color: #16a34a; + --seg-output-color: #0891b2; +} + +* { + box-sizing: border-box; +} + +[hidden] { + display: none !important; +} + +body { + margin: 0; + padding: 0; + background: var(--background, #f6f7f9); + color: var(--foreground, #1f2328); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; + font-size: 13px; + line-height: 1.45; + -webkit-font-smoothing: antialiased; +} + +.monitor-container { + display: flex; + flex-direction: column; + gap: 10px; + max-width: 560px; + margin: 0 auto; + padding: 12px; +} + +/* 1. Top Session Pill Bar ------------------------------------------------- */ + +.session-pill-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 7px 12px; + background: var(--card, #ffffff); + border: 1px solid var(--card-border, var(--border, #e2e5e9)); + border-radius: var(--radius-md); +} + +.session-pill-left { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + flex: 1; +} + +.session-title { + font-weight: 600; + font-size: 12.5px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.conv-select { + flex: 1; + min-width: 90px; + max-width: 210px; + padding: 2px 6px; + font-size: 12px; + color: var(--muted-foreground, #656d76); + background: var(--secondary, #f0f2f5); + border: 1px solid var(--border, #d8dee4); + border-radius: 5px; + outline: none; +} + +.session-pill-right { + display: flex; + align-items: center; + gap: 6px; + flex-shrink: 0; +} + +.live-pill { + font-size: 11px; + padding: 1px 7px; + border-radius: 999px; + background: color-mix(in srgb, #16a34a 15%, transparent); + color: var(--cache-green); + font-weight: 500; +} + +.live-pill.running { + background: color-mix(in srgb, #e05638 18%, transparent); + color: var(--speed-accent); +} + +.icon-btn { + padding: 2px 7px; + font-size: 13px; + line-height: 1.2; + color: var(--muted-foreground, #5f6368); + background: transparent; + border: 1px solid var(--border, #d8dee4); + border-radius: 5px; + cursor: pointer; +} + +.icon-btn:hover { + background: var(--secondary, #eef1f4); + color: var(--foreground, #1f2328); +} + +/* 2. Compact Status Strip Card (Left status bar in screenshot) ------------ */ + +.status-strip-card { + display: flex; + flex-direction: column; + gap: 4px; + padding: 10px 13px; + background: var(--card, #ffffff); + border: 1px solid var(--card-border, var(--border, #e2e5e9)); + border-radius: var(--radius-md); + box-shadow: 0 1px 3px rgb(0 0 0 / 4%); +} + +.strip-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 7px; +} + +.strip-row-main { + font-size: 13px; +} + +.strip-row-sub { + font-size: 12.5px; + justify-content: space-between; +} + +.speed-group { + display: inline-flex; + align-items: center; + gap: 5px; + cursor: pointer; + user-select: none; +} + +.speed-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--speed-accent); + display: inline-block; +} + +.speed-dot.pulsing { + animation: pulse-dot 1s infinite ease-in-out; + box-shadow: 0 0 0 3px color-mix(in srgb, var(--speed-accent) 28%, transparent); +} + +@keyframes pulse-dot { + 0%, 100% { transform: scale(1); opacity: 1; } + 50% { transform: scale(1.25); opacity: 0.65; } +} + +.speed-value { + color: var(--speed-accent); + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.metric-item { + color: var(--muted-foreground, #656d76); + font-variant-numeric: tabular-nums; +} + +.metric-item strong { + color: var(--foreground, #1f2328); + font-weight: 600; +} + +.strip-divider { + color: var(--border, #d0d7de); + margin: 0 1px; +} + +.cost-value { + color: var(--foreground, #1f2328); + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.cache-value { + color: var(--cache-green) !important; + font-weight: 600; +} + +.ctx-inline-trigger { + display: inline-flex; + align-items: center; + gap: 5px; + cursor: pointer; +} + +.parallelogram-group { + display: inline-flex; + align-items: center; + gap: 2px; + vertical-align: middle; +} + +.para-block { + width: 9px; + height: 9px; + transform: skewX(-18deg); + border: 1.3px solid #16a34a; + border-radius: 1.5px; + background: transparent; + transition: background-color 0.2s ease; +} + +.para-block.filled { + background: #16a34a; +} + +.para-block.warn { + border-color: #d97706; +} +.para-block.warn.filled { + background: #d97706; +} + +.para-block.danger { + border-color: #dc2626; +} +.para-block.danger.filled { + background: #dc2626; +} + +.model-tag { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--model-blue); + font-weight: 600; +} + +.swap-icon { + font-size: 13px; + font-weight: 700; +} + +.today-summary { + color: var(--muted-foreground, #656d76); + font-variant-numeric: tabular-nums; + margin-right: auto; + padding-left: 4px; +} + +.today-summary strong { + color: var(--foreground, #1f2328); + font-weight: 600; +} + +.speed-mode-label { + font-size: 11px; + padding: 1px 6px; + border-radius: 4px; + background: var(--secondary, #f0f2f5); +} + +/* 3. Quota & Context Popover Card (Right popover in screenshot) ----------- */ + +.quota-popover-card { + display: flex; + flex-direction: column; + gap: 12px; + padding: 15px 16px; + background: var(--card, #ffffff); + border: 1px solid var(--card-border, var(--border, #e2e5e9)); + border-radius: var(--radius-lg); + box-shadow: 0 4px 16px rgb(0 0 0 / 7%); +} + +.popover-section { + display: flex; + flex-direction: column; + gap: 9px; +} + +.section-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.section-row.clickable { + cursor: pointer; + user-select: none; +} + +.section-label { + color: var(--muted-foreground, #656d76); + font-size: 13px; +} + +.section-value { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--muted-foreground, #656d76); + font-size: 13px; + font-variant-numeric: tabular-nums; +} + +.chevron, .arrow-icon { + color: var(--muted-foreground, #8c959f); + font-size: 15px; + cursor: pointer; +} + +.multi-progress-track, +.single-progress-track { + width: 100%; + height: 5px; + background: var(--secondary, #eaeef2); + border-radius: 999px; + overflow: hidden; + display: flex; +} + +.bar-seg { + height: 100%; + transition: width 0.25s ease; +} + +.seg-cached { background: var(--seg-cached-color); } +.seg-input { background: var(--seg-input-color); } +.seg-thinking { background: var(--seg-thinking-color); } +.seg-output { background: var(--seg-output-color); } + +.bar-fill { + height: 100%; + background: var(--bar-blue); + border-radius: 999px; + transition: width 0.25s ease; +} + +.bar-fill.warn { background: #d97706; } +.bar-fill.danger { background: #dc2626; } + +.ctx-breakdown { + margin-top: 4px; + padding: 9px 10px; + background: var(--secondary, #f4f6f8); + border-radius: var(--radius-sm); + display: flex; + flex-direction: column; + gap: 8px; + font-size: 12px; +} + +.legend-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 5px 12px; +} + +.legend-item { + display: flex; + align-items: center; + gap: 6px; + color: var(--muted-foreground, #656d76); +} + +.legend-item strong { + color: var(--foreground, #1f2328); +} + +.dot { + width: 8px; + height: 8px; + border-radius: 2px; + display: inline-block; +} + +.ctx-limit-switch { + display: flex; + align-items: center; + gap: 6px; + padding-top: 4px; + border-top: 1px dashed var(--border, #d8dee4); + color: var(--muted-foreground, #656d76); +} + +.chip-btn { + padding: 2px 8px; + font-size: 11.5px; + border-radius: 4px; + border: 1px solid var(--border, #d0d7de); + background: var(--card, #ffffff); + color: var(--foreground, #1f2328); + cursor: pointer; +} + +.chip-btn.active { + background: var(--bar-blue); + color: #ffffff; + border-color: var(--bar-blue); +} + +.popover-divider { + border: none; + border-top: 1px solid var(--border, #eaeef2); + margin: 2px 0; +} + +.quota-block { + display: flex; + flex-direction: column; + gap: 6px; + margin-top: 2px; +} + +.quota-title { + color: var(--foreground, #1f2328); + font-weight: 500; + font-size: 13px; +} + +.quota-meta { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--muted-foreground, #656d76); + font-size: 12.5px; + font-variant-numeric: tabular-nums; +} + +.quota-meta strong { + color: var(--muted-foreground, #656d76); + font-weight: 600; + min-width: 28px; + text-align: right; +} + +.all-pools-box { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px 10px; + background: var(--secondary, #f4f6f8); + border-radius: var(--radius-sm); +} + +.pool-mini-row { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 12px; + gap: 8px; +} + +.pool-mini-name { + font-weight: 500; + color: var(--foreground, #1f2328); +} + +.pool-mini-meta { + color: var(--muted-foreground, #656d76); + font-variant-numeric: tabular-nums; +} + +.weekly-sub-meta { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 12px; + margin-top: 1px; +} + +.popover-actions { + display: flex; + align-items: center; + gap: 8px; + margin-top: 4px; +} + +.detail-pill-btn { + padding: 4px 12px; + font-size: 12px; + font-weight: 500; + color: var(--foreground, #1f2328); + background: var(--card, #ffffff); + border: 1px solid var(--border, #d0d7de); + border-radius: 6px; + cursor: pointer; + box-shadow: 0 1px 2px rgb(0 0 0 / 4%); +} + +.detail-pill-btn:hover { + background: var(--secondary, #f3f4f6); +} + +.secondary-pill { + color: var(--muted-foreground, #656d76); +} + +/* 4. Details & Settings Cards --------------------------------------------- */ + +.details-card { + display: flex; + flex-direction: column; + gap: 10px; + padding: 12px 14px; + background: var(--card, #ffffff); + border: 1px solid var(--card-border, var(--border, #e2e5e9)); + border-radius: var(--radius-lg); +} + +.tabs-header { + display: flex; + gap: 6px; + border-bottom: 1px solid var(--border, #eaeef2); + padding-bottom: 8px; +} + +.tab-btn { + padding: 4px 10px; + font-size: 12px; + border-radius: 5px; + border: 1px solid transparent; + background: transparent; + color: var(--muted-foreground, #656d76); + cursor: pointer; +} + +.tab-btn.active { + background: var(--secondary, #eef1f4); + color: var(--foreground, #1f2328); + font-weight: 600; +} + +.table-scroll { + overflow-x: auto; +} + +.data-table { + width: 100%; + border-collapse: collapse; + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.data-table th, +.data-table td { + padding: 6px 6px; + text-align: left; + border-bottom: 1px solid var(--border, #eaeef2); + white-space: nowrap; +} + +.data-table th { + color: var(--muted-foreground, #656d76); + font-weight: 500; +} + +.settings-title { + margin: 0; + font-size: 13px; + font-weight: 600; +} + +.settings-grid { + display: flex; + flex-direction: column; + gap: 8px; +} + +.field-label { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 12px; + color: var(--muted-foreground, #656d76); +} + +.field-label select, +.field-label input { + padding: 5px 8px; + font-size: 12.5px; + color: var(--foreground, #1f2328); + background: var(--background, #f6f7f9); + border: 1px solid var(--border, #d0d7de); + border-radius: 5px; +} + +.settings-actions { + display: flex; + justify-content: flex-end; +} + +.muted { + color: var(--muted-foreground, #656d76); +}