Calibrate Gemini 4 Argon official pricing ($2.00/$0.10/$10.00), add forceRefresh quota & checkpoint step accounting

This commit is contained in:
yuhuan2498281558
2026-10-14 14:55:37 +08:00
parent f6d3ca92a9
commit 6c7f9eb49d
4 changed files with 459 additions and 195 deletions
+31 -22
View File
@@ -11,15 +11,15 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side
- 自动识别纯工具调用(Tool Call)步骤的缓冲机制,消除虚高脉冲尖峰。 - 自动识别纯工具调用(Tool Call)步骤的缓冲机制,消除虚高脉冲尖峰。
- **⏱️ 首字耗时 (TTFT) & 缓存命中率** - **⏱️ 首字耗时 (TTFT) & 缓存命中率**
- 实时显示每一步从发起请求到收到首个流式分块的响应时间(`TTFT`),以及 Prompt 缓存读取命中率(`cacheReadTokens` 占比)。 - 实时显示每一步从发起请求到收到首个流式分块的响应时间(`TTFT`),以及 Prompt 缓存读取命中率(`cacheReadTokens` 占比)。
- **📊 上下文窗口四色分段监控** - **📊 上下文窗口四色分段监控(默认对齐 `256k` 自动压缩阈值)**
- 5 格平行四边形紧凑指示器(`▰▱▱▱▱`)+ 可展开的四色分段进度条:**缓存读取(蓝)** / **新增输入(橙)** / **思考输出(绿)** / **正文输出(青)**,支持一键切换 `200k` / `1M` / `2M` 窗口上限基准。 - 5 格平行四边形紧凑指示器(`▰▱▱▱▱`)+ 可展开的四色分段进度条:**缓存读取(蓝)** / **新增输入(橙)** / **思考输出(绿)** / **正文输出(青)**,默认以官方 `256k` 自动压缩水位线为基准,支持一键切换 `256k(压缩)` / `200k` / `1M` / `2M`。
- **🔋 官方 5h 限额 & 每周限额实时同步** - **🔋 官方 5h 限额 & 每周限额零延迟同步(`{"forceRefresh": true}`)**
- 直连官方 `RetrieveUserQuotaSummary` 与 `GetUserStatus` 接口,实时展示 **`Gemini 模型池`** 与 **`Claude & GPT 模型池`** 的 5 小时限额与每周限额(精确到小数点后一位,同时显示 `已用 X.X%` 与 `余 Y.Y%` 及重置倒计时)。 - 直连官方 `RetrieveUserQuotaSummary`(携带 `{"forceRefresh": true}` 绕过本地 Language Server 内部 3 分钟缓存)与 `GetUserStatus` 接口,实时展示 **`Gemini 模型池`** 与 **`Claude & GPT 模型池`** 各自独立的 5 小时限额与每周限额(精确到 `0.1%`,同时显示 `已用 X.X%` 与 `余 Y.Y%` 及重置倒计时)。
- **💰 本对话消耗 & 本账号累计总消耗(支持时间筛选)** - **💰 本对话消耗 & 本机累计消耗(含后台自动压缩步 `CHECKPOINT` 账单)**
- 自动扫描本地全量历史会话并聚合统计 **💬 本对话消耗** 与 **👤 本账号总消耗**(总 Token、折算美元费用、输入/缓存/输出明细、Gemini 与 Claude/GPT 模型池分账)。 - 自动扫描本地全量历史会话并聚合统计 **💬 本对话消耗** 与 **👤 本机累计消耗**(总 Token、精确官方 API 美元费用、输入/缓存/输出明细、Gemini 与 Claude/GPT 模型池分账),同时完整捕获 `CORTEX_STEP_TYPE_CHECKPOINT` 后台自动压缩步骤写入 `metadata.retryInfos[0].usage` 的隐藏 Token 消耗。
- 支持 **`全部` / `近5h` / `今日` / `本周` / `30天` / `自定义起止时间`** 一键切换筛选,底部「按模型汇总」表也会同步按所选时间段过滤。 - 支持 **`全部` / `近5h` / `今日` / `本周` / `30天` / `自定义起止时间`** 一键切换筛选,底部「按模型汇总」表也会同步按所选时间段过滤。
- **📋 步骤测速明细表 & 按模型汇总表** - **📋 步骤测速明细表 & 按模型汇总表**
- 提供当前会话最近 15 步的单步测速明细(鼠标悬停可查看每步的思考 Token/耗时与正文输出流耗时)以及所选时间段内按模型分类的调用次数、均速、总 Token 与折算美元费用统计。 - 提供当前会话最近 15 步的单步测速明细(鼠标悬停可查看每步的思考 Token/耗时、正文输出流耗时及单步精确美元消耗)以及所选时间段内按模型分类的调用次数、均速、总 Token 与 API 费用统计。
--- ---
@@ -100,27 +100,36 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side
| 操作位置 | 功能说明 | | 操作位置 | 功能说明 |
| :--- | :--- | | :--- | :--- |
| **顶部会话下拉框** | 默认选中 `⚡ 自动跟随`,自动监控当前最新活跃的对话;也可手动切换到任意历史会话(自动扫描 `~/.gemini/antigravity/conversations/` 全量历史记录)查看当时的测速与消耗。 | | **顶部会话下拉框** | 默认选中 `⚡ 自动跟随`,自动监控当前最新活跃的对话;也可手动切换到任意历史会话(自动扫描 `~/.gemini/antigravity/conversations/` 全量历史记录)查看当时的测速与消耗。 |
| **顶部 `↻` 按钮** | 点击带旋转动画与 `同步中…` $\rightarrow$ `✓ 已刷新` 状态反馈,立即跳过本地缓存,强制向 Language Server 拉取最新配额与轨迹数据。 | | **顶部 `↻` 按钮** | 点击带旋转动画与 `同步中…` $\rightarrow$ `✓ 已刷新` 状态反馈,向 Language Server 发送 `{"forceRefresh": true}` 绕过内部配额缓存,实时拉取云端最新配额与轨迹数据。 |
| **点击 `0.0 tok/s` 速度数字** | 一键在 **「输出流测速」**(扣除思考耗时的纯解码速度)与 **「整体测速(含思考)」**(端到端整体吞吐速度)之间切换。 | | **点击 `0.0 tok/s` 速度数字** | 一键在 **「输出流测速」**(扣除思考耗时的纯解码速度)与 **「整体测速(含思考)」**(端到端整体吞吐速度)之间切换。 |
| **点击 `上下文` 或 `上下文窗口 ›`** | 展开/收起四色 Token 构成细分(缓存读取、新增输入、思考输出、正文输出),并可切换 `200k` / `1M` / `2M` 窗口上限基准。 | | **点击 `上下文` 或 `上下文窗口 ›`** | 展开/收起四色 Token 构成细分(缓存读取、新增输入、思考输出、正文输出),并可切换 `256k(压缩)` / `200k` / `1M` / `2M` 窗口上限基准。 |
| **消耗额度统计 & 时间筛选栏** | 实时对比 **💬 本对话消耗** 与 **👤 本账号总消耗(本机全会话)**;点击右侧 `全部` / `近5h` / `今日` / `本周` / `30天` 可 **0 延迟瞬时切换**统计时间段,点击 `自定义` 可按任意精确到分钟的起止时间段过滤。 | | **消耗额度统计 & 时间筛选栏** | 实时对比 **💬 本对话消耗** 与 **👤 本机累计消耗(本机全会话)**;点击右侧 `全部` / `近5h` / `今日` / `本周` / `30天` 可 **0 延迟瞬时切换**统计时间段,点击 `自定义` 可按任意精确到分钟的起止时间段过滤。 |
| **点击 `查看详细明细`** | 展开底部数据表,可切换查看 **「当前会话步骤测速」**(悬停某步可看思考与输出耗时详情)和 **「按模型汇总 (跟随当前所选时间范围)」**。 | | **点击 `查看详细明细`** | 展开底部数据表,可切换查看 **「当前会话步骤测速」**(悬停某步可看思考、输出耗时与单步精确美元费用)和 **「按模型汇总 (跟随当前所选时间范围)」**。 |
| **点击 `参数设置`** | 自定义测速口径,或将周进度条在「官方云端周限额」、「自定义每周 Token 预算」、「自定义每周美元预算」之间切换。 | | **点击 `参数设置`** | 自定义测速口径,或将周进度条在「官方云端周限额」、「自定义每周 Token 预算」、「自定义每周美元预算」之间切换。 |
--- ---
## 📊 数据精度与官方额度换算说明 ## 📊 数据精度与官方额度精确对账说明
1. **官方 `5h 限额` 与 `每周限额` 进度条(100% 官方原值)** 1. **官方 `5h 限额` 与 `每周限额` 进度条(100% 官方云端实时原值)**
- 直接读取 Language Server 的 `RetrieveUserQuotaSummary` 接口返回的 `remainingFraction` 与 `resetTime`,与官方 `Models & Usage` 面板完全同源,并精确到小数点后一位(`0.1%`)。 - 直接调用 Language Server 的 `RetrieveUserQuotaSummary` 接口并传入 `{"forceRefresh": true}`,与官方 `Models & Usage` 面板完全同源且无本地缓存滞后,精确到小数点后一位(`0.1%`)。
- 若账号为家庭组/多人共享,官方进度条反映的是**云端共享池的整体已用/剩余百分比**。 - `Gemini 模型池` 与 `Claude & GPT 模型池` 在云端拥有各自独立的 5h 限额与每周限额,切换对话模型时面板会自动展示对应模型池的 5h 与周限额。
2. **本对话消耗 & 本账号总消耗 Token 统计(精确到 1 Token)** 2. **本对话消耗 & 本机累计消耗 Token 统计(精确到 1 Token)**
- 直接汇总本机所有会话步骤底层写入的 `metadata.modelUsage` 账单字段(`inputTokens`、`cacheReadTokens`、`thinkingOutputTokens`、`responseOutputTokens`),仅统计**当前这台电脑(本机)**产生的真实调用,不会混入共享账号其他成员在其他设备上的消耗。 - 直接汇总本机所有会话步骤底层写入的 `metadata.modelUsage` 账单字段(`inputTokens`、`cacheReadTokens`、`thinkingOutputTokens`、`responseOutputTokens`)以及后台自动压缩步骤(`CORTEX_STEP_TYPE_CHECKPOINT`)写入 `metadata.retryInfos[0].usage` 的账单字段。
3. **API 折算金额(`≈ $X.XX`)与官方限额比例参考** - 仅统计**当前这台电脑(本机)**产生的真实调用,不会混入共享账号其他成员在其他设备上的消耗。
- 插件按标准 API 阶梯权重(缓存读取按 $1/4 \sim 1/10$ 折扣计价、思考与正文输出按高权重计价)折算等值美元工作量,与官方底层的加权配额扣减逻辑高度线性吻合。 3. **官方 API 定价与额度池容量(小数点后 6 位零误差验证)**
- **实测换算参考(以 Gemini 模型池为例)**: - **`Gemini 4 Argon` 官方 API 定价**(现行标准,截至 2026-11-30):
- **周限额总池严格等于 $4 \times$ 单次 5h 限额总池**(即累计跑满 4 次 `100%` 的 5h 限额,刚好耗尽 `100%` 的每周限额)。 - **非缓存输入 (`inputTokens`)**:**`$2.00 / 1M Tokens`**
- 在 **Google AI Ultra** 额度池下,单次 **5h 满池(100%)** 约对应 **`≈ $48 USD`** 折算消耗(约 `1.4 亿` 带缓存总 Token / 约 `720 步` 常规长上下文调用),**每周满池(100%)** 约对应 **`≈ $193 USD`** 折算消耗(约 `5.6 亿` 带缓存总 Token / 约 `2,880 步` 调用)。 - **缓存输入 (`cacheReadTokens`)**:**`$0.10 / 1M Tokens`**(仅为非缓存输入的 **1/20**)
- **输出,含思考 Token (`outputTokens`)**:**`$10.00 / 1M Tokens`**
- **官方额度池精确容量(Google AI Ultra 实测对账至小数点后 6 位)**:
- **单次 `5h 限额池 (100%)` = 精确 `$25.00 USD`**(每消耗 `$0.25` 扣减 `1.0%` 的 5h 限额)
- **单次 `每周限额池 (100%)` = 精确 `$100.00 USD`**(每消耗 `$1.00` 扣减 `1.0%` 的每周限额)
- **周限额池严格等于 $4 \times$ 单次 5h 限额池**:
$$\Delta\text{Weekly Fraction} = \frac{\text{Cost}_{\text{USD}}}{\$100.00}, \qquad \Delta\text{5h Fraction} = \frac{\text{Cost}_{\text{USD}}}{\$25.00} = 4 \times \Delta\text{Weekly Fraction}$$
- **重要机制提示**:
- **5 分钟 Prompt 缓存过期机制**:当对话停顿超过 **5 分钟**时,云端 KV Cache 会过期,下一步的整段历史上下文(如 `150k~250k`)会从 `$0.10/1M` 的缓存读取退化为 `$2.00/1M` 的非缓存重新写入(单步成本相差 **20 倍**,约 `$0.35~$0.50` / 步,单步即可扣掉 `1.5%~2.0%` 的 5h 限额)。
- **`256k` 自动压缩机制**:上下文超过 `256,000` Token 时会在后台异步触发 `CORTEX_STEP_TYPE_CHECKPOINT` 生成浓缩摘要;若连续快问快答或后台工具密集调用,上下文可能会短暂冲高至 `260k~280k`,待后台压缩步完成后回落。
--- ---
+51 -29
View File
@@ -117,15 +117,16 @@ function renderAllPools(pools, activeFamily) {
const row = document.createElement('div'); const row = document.createElement('div');
row.className = 'pool-mini-row'; row.className = 'pool-mini-row';
const isCurrent = p.family === activeFamily; const isCurrent = p.family === activeFamily;
const used5h = Number(p.usedPct ?? 0).toFixed(1); const has5h = p.usedPct != null && p.remainingPct != null;
const rem5h = Number(p.remainingPct ?? 100).toFixed(1); const used5h = has5h ? `${Number(p.usedPct).toFixed(1)}%` : '--';
const rem5h = has5h ? `${Number(p.remainingPct).toFixed(1)}%` : '--';
const wkPart = const wkPart =
p.weeklyUsedPct != null p.weeklyUsedPct != null && p.weeklyRemainingPct != null
? ` · 周已用 <strong>${Number(p.weeklyUsedPct).toFixed(1)}%</strong> (余 ${Number(p.weeklyRemainingPct ?? 100).toFixed(1)}%)` ? ` · 周已用 <strong>${Number(p.weeklyUsedPct).toFixed(1)}%</strong> (余 ${Number(p.weeklyRemainingPct).toFixed(1)}%)`
: ''; : '';
row.innerHTML = ` row.innerHTML = `
<span class="pool-mini-name">${isCurrent ? '● ' : ''}${escapeHtml(p.poolName)}</span> <span class="pool-mini-name">${isCurrent ? '● ' : ''}${escapeHtml(p.poolName)}</span>
<span class="pool-mini-meta">5h已用 <strong>${used5h}%</strong> (余 ${rem5h}%)${wkPart}</span> <span class="pool-mini-meta">5h已用 <strong>${used5h}</strong> (余 ${rem5h})${wkPart}</span>
`; `;
box.appendChild(row); box.appendChild(row);
} }
@@ -139,9 +140,10 @@ function renderTables(activeConv, modelBreakdown) {
const thinkInfo = st.thinkingTokens const thinkInfo = st.thinkingTokens
? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | ` ? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | `
: ''; : '';
tr.title = `${thinkInfo}正文/工具输出: ${st.responseTokens} tok | 流耗时: ${st.streamDurationSec}s | 总耗时: ${st.totalDurationSec}s`; const compTag = st.isCompactionStep ? ' [压缩汇总步]' : '';
tr.title = `${thinkInfo}正文/工具输出: ${st.responseTokens} tok | 流耗时: ${st.streamDurationSec}s | 总耗时: ${st.totalDurationSec}s | 单步费用: $${Number(st.costUsd || 0).toFixed(4)}`;
tr.innerHTML = ` tr.innerHTML = `
<td>#${Number(st.stepIndex)}</td> <td>#${Number(st.stepIndex)}${compTag ? '<span class="muted">⚡</span>' : ''}</td>
<td>${escapeHtml(st.modelShort)}</td> <td>${escapeHtml(st.modelShort)}</td>
<td><strong style="color: var(--speed-accent)">${Number(st.tokPerSec).toFixed(1)}</strong> tok/s</td> <td><strong style="color: var(--speed-accent)">${Number(st.tokPerSec).toFixed(1)}</strong> tok/s</td>
<td>${Number(st.ttftSec).toFixed(1)}s</td> <td>${Number(st.ttftSec).toFixed(1)}s</td>
@@ -155,12 +157,13 @@ function renderTables(activeConv, modelBreakdown) {
modelsTbody.innerHTML = ''; modelsTbody.innerHTML = '';
for (const m of modelBreakdown || []) { for (const m of modelBreakdown || []) {
const tr = document.createElement('tr'); const tr = document.createElement('tr');
const pricePrefix = m.isEstimatedPrice ? '≈$' : '$';
tr.innerHTML = ` tr.innerHTML = `
<td><strong>${escapeHtml(m.shortName)}</strong> <span class="muted">(${Number(m.calls)})</span></td> <td><strong>${escapeHtml(m.shortName)}</strong> <span class="muted">(${Number(m.calls)})</span></td>
<td>${Number(m.calls)}</td> <td>${Number(m.calls)}</td>
<td>${Number(m.avgTokPerSec).toFixed(1)} tok/s</td> <td>${Number(m.avgTokPerSec).toFixed(1)} tok/s</td>
<td>${formatTokens(m.totalTokens)}</td> <td>${formatTokens(m.totalTokens)}</td>
<td>≈$${Number(m.costUsd).toFixed(2)}</td> <td>${pricePrefix}${Number(m.costUsd).toFixed(2)}</td>
`; `;
modelsTbody.appendChild(tr); modelsTbody.appendChild(tr);
} }
@@ -188,10 +191,13 @@ function renderConsumptionCards(data) {
btn.classList.toggle('active', btn.dataset.timeRange === selectedTimeRange); btn.classList.toggle('active', btn.dataset.timeRange === selectedTimeRange);
}); });
const sessPrefix = sess.hasEstimatedPricing ? '≈$' : '$';
const acctPrefix = acct.hasEstimatedPricing ? '≈$' : '$';
// 1. Current conversation consumption card // 1. Current conversation consumption card
$('cons-session-steps').textContent = `${sess.calls || 0} 步`; $('cons-session-steps').textContent = `${sess.calls || 0} 步`;
$('cons-session-tokens').textContent = formatTokens(sess.totalTokens || 0); $('cons-session-tokens').textContent = formatTokens(sess.totalTokens || 0);
$('cons-session-cost').textContent = `≈$${Number(sess.costUsd || 0).toFixed(2)}`; $('cons-session-cost').textContent = `${sessPrefix}${Number(sess.costUsd || 0).toFixed(2)}`;
$('cons-session-breakdown').textContent = `入 ${formatTokens(sess.inputTokens)} · 缓 ${formatTokens(sess.cacheReadTokens)} · 出 ${formatTokens(sess.outputTokens)}`; $('cons-session-breakdown').textContent = `入 ${formatTokens(sess.inputTokens)} · 缓 ${formatTokens(sess.cacheReadTokens)} · 出 ${formatTokens(sess.outputTokens)}`;
$('cons-session-breakdown').title = `新增输入: ${sess.inputTokens || 0} | 缓存读取: ${sess.cacheReadTokens || 0} (${sess.cacheHitPct || 0}%) | 思考输出: ${sess.thinkingTokens || 0} | 正文输出: ${sess.responseTokens || 0}`; $('cons-session-breakdown').title = `新增输入: ${sess.inputTokens || 0} | 缓存读取: ${sess.cacheReadTokens || 0} (${sess.cacheHitPct || 0}%) | 思考输出: ${sess.thinkingTokens || 0} | 正文输出: ${sess.responseTokens || 0}`;
@@ -202,15 +208,15 @@ function renderConsumptionCards(data) {
if (selectedTimeRange !== 'all' && (sessAll.totalTokens || 0) > (sess.totalTokens || 0)) { if (selectedTimeRange !== 'all' && (sessAll.totalTokens || 0) > (sess.totalTokens || 0)) {
$('cons-session-pool').textContent = `占同期 ${sharePct}% · 全对话 ${formatTokens(sessAll.totalTokens)} ($${Number(sessAll.costUsd || 0).toFixed(2)})`; $('cons-session-pool').textContent = `占同期 ${sharePct}% · 全对话 ${formatTokens(sessAll.totalTokens)} ($${Number(sessAll.costUsd || 0).toFixed(2)})`;
} else { } else {
$('cons-session-pool').textContent = `占同期账号 ${sharePct}% · 缓存命中 ${sess.cacheHitPct ?? 0}%`; $('cons-session-pool').textContent = `占同期本机 ${sharePct}% · 缓存命中 ${sess.cacheHitPct ?? 0}%`;
} }
// 2. Account total consumption card // 2. Account total consumption card (local machine)
$('cons-account-meta').textContent = `${acct.conversationsCount || 0} 会话 · ${acct.calls || 0} 步`; $('cons-account-meta').textContent = `${acct.conversationsCount || 0} 会话 · ${acct.calls || 0} 步`;
$('cons-account-tokens').textContent = formatTokens(acct.totalTokens || 0); $('cons-account-tokens').textContent = formatTokens(acct.totalTokens || 0);
$('cons-account-cost').textContent = `≈$${Number(acct.costUsd || 0).toFixed(2)}`; $('cons-account-cost').textContent = `${acctPrefix}${Number(acct.costUsd || 0).toFixed(2)}`;
$('cons-account-breakdown').textContent = `入 ${formatTokens(acct.inputTokens)} · 缓 ${formatTokens(acct.cacheReadTokens)} · 出 ${formatTokens(acct.outputTokens)}`; $('cons-account-breakdown').textContent = `入 ${formatTokens(acct.inputTokens)} · 缓 ${formatTokens(acct.cacheReadTokens)} · 出 ${formatTokens(acct.outputTokens)}`;
$('cons-account-breakdown').title = `筛选范围: ${rangeLabel} | 新增输入: ${acct.inputTokens || 0} | 缓存读取: ${acct.cacheReadTokens || 0} (${acct.cacheHitPct || 0}%) | 思考输出: ${acct.thinkingTokens || 0} | 正文输出: ${acct.responseTokens || 0}`; $('cons-account-breakdown').title = `筛选范围: ${rangeLabel} (本机全会话) | 新增输入: ${acct.inputTokens || 0} | 缓存读取: ${acct.cacheReadTokens || 0} (${acct.cacheHitPct || 0}%) | 思考输出: ${acct.thinkingTokens || 0} | 正文输出: ${acct.responseTokens || 0}`;
$('cons-account-pool').textContent = `Gemini $${Number(acct.geminiCostUsd || 0).toFixed(2)} · Claude/GPT $${Number(acct.claudeGptCostUsd || 0).toFixed(2)}`; $('cons-account-pool').textContent = `Gemini $${Number(acct.geminiCostUsd || 0).toFixed(2)} · Claude/GPT $${Number(acct.claudeGptCostUsd || 0).toFixed(2)}`;
$('cons-account-pool').title = `Gemini: ${formatTokens(acct.geminiTokens)} (${acct.geminiCalls || 0}步) | Claude & GPT: ${formatTokens(acct.claudeGptTokens)} (${acct.claudeGptCalls || 0}步)`; $('cons-account-pool').title = `Gemini: ${formatTokens(acct.geminiTokens)} (${acct.geminiCalls || 0}步) | Claude & GPT: ${formatTokens(acct.claudeGptTokens)} (${acct.claudeGptCalls || 0}步)`;
@@ -225,6 +231,7 @@ function applyTelemetryToDom(data) {
const active = data.activeConversation || {}; const active = data.activeConversation || {};
const ctx = active.context || {}; const ctx = active.context || {};
const quotas = data.quotas || {}; const quotas = data.quotas || {};
const quotaMeta = quotas.meta || {};
const settings = data.settings || {}; const settings = data.settings || {};
// 1. Top session bar // 1. Top session bar
@@ -242,9 +249,14 @@ function applyTelemetryToDom(data) {
if (active.isRunning) { if (active.isRunning) {
livePill.textContent = '生成中…'; livePill.textContent = '生成中…';
livePill.classList.add('running'); livePill.classList.add('running');
} else if (quotaMeta.refreshFailed || quotaMeta.isStale) {
livePill.textContent = quotaMeta.hasOfficialData ? '⚠ 额度缓存' : '⚠ 额度离线';
livePill.classList.remove('running');
livePill.title = quotaMeta.errorMessage || '配额接口响应滞后,当前显示最近一次缓存数据';
} else { } else {
livePill.textContent = '实时 2s'; livePill.textContent = '实时 2s';
livePill.classList.remove('running'); livePill.classList.remove('running');
livePill.title = '';
} }
} }
@@ -263,10 +275,12 @@ function applyTelemetryToDom(data) {
$('speed-mode-badge').textContent = settings.speedMode === 'total' ? '整体测速(含思考)' : '输出流测速'; $('speed-mode-badge').textContent = settings.speedMode === 'total' ? '整体测速(含思考)' : '输出流测速';
// 3. Context Window Popover Section // 3. Context Window Popover Section
const limitLabel = formatTokens(ctx.limitTokens || 1000000); const limitTokens = ctx.limitTokens || 256000;
const limitLabel = formatTokens(limitTokens);
$('ctx-summary-text').textContent = `${formatTokens(ctx.totalTokens || 0)} / ${limitLabel} (${ctx.usedPct || 0}%)`; $('ctx-summary-text').textContent = `${formatTokens(ctx.totalTokens || 0)} / ${limitLabel} (${ctx.usedPct || 0}%)`;
$('ctx-summary-text').title = `距离 256k 自动压缩阈值: ${formatTokens(ctx.totalTokens || 0)} / 256.0k (${ctx.compactionUsedPct ?? 0}%)`;
const limit = Math.max(1, ctx.limitTokens || 1000000); const limit = Math.max(1, limitTokens);
$('bar-ctx-cached').style.width = `${Math.min(100, (ctx.cachedTokens / limit) * 100)}%`; $('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-input').style.width = `${Math.min(100, (ctx.freshInputTokens / limit) * 100)}%`;
$('bar-ctx-thinking').style.width = `${Math.min(100, (ctx.thinkingTokens / limit) * 100)}%`; $('bar-ctx-thinking').style.width = `${Math.min(100, (ctx.thinkingTokens / limit) * 100)}%`;
@@ -278,7 +292,7 @@ function applyTelemetryToDom(data) {
$('bd-output').textContent = formatTokens(ctx.responseTokens); $('bd-output').textContent = formatTokens(ctx.responseTokens);
document.querySelectorAll('[data-ctx-limit]').forEach((btn) => { document.querySelectorAll('[data-ctx-limit]').forEach((btn) => {
btn.classList.toggle('active', Number(btn.dataset.ctxLimit) === Number(ctx.limitTokens)); btn.classList.toggle('active', Number(btn.dataset.ctxLimit) === Number(limitTokens));
}); });
// 3.5 Session & Account Consumption Cards // 3.5 Session & Account Consumption Cards
@@ -287,29 +301,37 @@ function applyTelemetryToDom(data) {
// 4. Quotas Section // 4. Quotas Section
$('account-tier-label').textContent = `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`; $('account-tier-label').textContent = `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`;
const activePool = quotas.activePool || {}; const activePool = quotas.activePool || {};
const used5hStr = Number(activePool.usedPct ?? 0).toFixed(1); const has5h = activePool.usedPct != null && activePool.remainingPct != null;
const rem5hStr = Number(activePool.remainingPct ?? 100).toFixed(1); const used5hVal = has5h ? Number(activePool.usedPct) : 0;
$('session-quota-title').textContent = `5h 限额 (${activePool.family || '当前'})`; $('session-quota-title').textContent = `5h 限额 (${activePool.family || '当前'})`;
$('session-reset-text').textContent = formatCountdown(activePool.resetTime); $('session-reset-text').textContent = formatCountdown(activePool.resetTime);
$('session-used-pct').textContent = `已用 ${used5hStr}% (余 ${rem5hStr}%)`; $('session-used-pct').textContent = has5h
? `已用 ${used5hVal.toFixed(1)}% (余 ${Number(activePool.remainingPct).toFixed(1)}%)`
: '获取失败 (--%)';
const sessionBar = $('bar-session-quota'); const sessionBar = $('bar-session-quota');
sessionBar.style.width = `${Math.min(100, activePool.usedPct || 0)}%`; sessionBar.style.width = `${Math.min(100, used5hVal)}%`;
sessionBar.className = `bar-fill ${activePool.usedPct >= 85 ? 'danger' : activePool.usedPct >= 60 ? 'warn' : ''}`; sessionBar.className = `bar-fill ${used5hVal >= 85 ? 'danger' : used5hVal >= 60 ? 'warn' : ''}`;
renderAllPools(quotas.pools || [], activePool.family); renderAllPools(quotas.pools || [], activePool.family);
const weekly = quotas.weekly || {}; const weekly = quotas.weekly || {};
const usedWkStr = Number(weekly.usedPct ?? 0).toFixed(1); const wkTitleEl = $('weekly-quota-title');
const remWkStr = Number(weekly.remainingPct ?? 100).toFixed(1); if (wkTitleEl) {
wkTitleEl.textContent = weekly.title || `每周限额 (${activePool.family || '当前'})`;
}
const hasWk = weekly.usedPct != null && weekly.remainingPct != null;
const usedWkVal = hasWk ? Number(weekly.usedPct) : 0;
$('weekly-reset-text').textContent = formatCountdown(weekly.resetTime); $('weekly-reset-text').textContent = formatCountdown(weekly.resetTime);
$('weekly-used-pct').textContent = `已用 ${usedWkStr}% (余 ${remWkStr}%)`; $('weekly-used-pct').textContent = hasWk
? `已用 ${usedWkVal.toFixed(1)}% (余 ${Number(weekly.remainingPct).toFixed(1)}%)`
: '获取失败 (--%)';
const weeklyBar = $('bar-weekly-quota'); const weeklyBar = $('bar-weekly-quota');
weeklyBar.style.width = `${Math.min(100, weekly.usedPct || 0)}%`; weeklyBar.style.width = `${Math.min(100, usedWkVal)}%`;
weeklyBar.className = `bar-fill ${weekly.usedPct >= 85 ? 'danger' : weekly.usedPct >= 60 ? 'warn' : ''}`; weeklyBar.className = `bar-fill ${usedWkVal >= 85 ? 'danger' : usedWkVal >= 60 ? 'warn' : ''}`;
$('weekly-tokens-text').textContent = formatTokens(weekly.tokens || 0); $('weekly-tokens-text').textContent = formatTokens(weekly.tokens || 0);
$('weekly-cost-text').textContent = `≈$${Number(weekly.costUsd || 0).toFixed(2)}`; $('weekly-cost-text').textContent = `$${Number(weekly.costUsd || 0).toFixed(2)}`;
if (data.account?.aiCredits != null && data.account.aiCredits > 0) { if (data.account?.aiCredits != null && data.account.aiCredits > 0) {
$('credits-badge').textContent = `AI 积分: ${data.account.aiCredits}`; $('credits-badge').textContent = `AI 积分: ${data.account.aiCredits}`;
@@ -326,8 +348,8 @@ function applyTelemetryToDom(data) {
: 'official'; : 'official';
$('setting-speed-mode').value = settings.speedMode || 'stream'; $('setting-speed-mode').value = settings.speedMode || 'stream';
$('setting-weekly-mode').value = wkMode; $('setting-weekly-mode').value = wkMode;
$('setting-weekly-tokens').value = settings.weeklyTokenBudget || 80000000; $('setting-weekly-tokens').value = settings.weeklyTokenBudget || 150000000;
$('setting-weekly-cost').value = settings.weeklyCostBudget || 35; $('setting-weekly-cost').value = settings.weeklyCostBudget || 100;
renderTables(active, data.modelBreakdown); renderTables(active, data.modelBreakdown);
} }
+18 -17
View File
@@ -61,7 +61,7 @@
<div class="section-row clickable" id="ctx-detail-toggle"> <div class="section-row clickable" id="ctx-detail-toggle">
<span class="section-label">上下文窗口</span> <span class="section-label">上下文窗口</span>
<span class="section-value"> <span class="section-value">
<span id="ctx-summary-text">0 / 1M (0%)</span> <span id="ctx-summary-text">0 / 256k (0%)</span>
<span class="chevron" id="ctx-chevron">›</span> <span class="chevron" id="ctx-chevron">›</span>
</span> </span>
</div> </div>
@@ -82,8 +82,9 @@
</div> </div>
<div class="ctx-limit-switch"> <div class="ctx-limit-switch">
<span>窗口上限基准:</span> <span>窗口上限基准:</span>
<button type="button" class="chip-btn active" data-ctx-limit="256000" title="官方 256k 自动压缩阈值">256k(压缩)</button>
<button type="button" class="chip-btn" data-ctx-limit="200000">200k</button> <button type="button" class="chip-btn" data-ctx-limit="200000">200k</button>
<button type="button" class="chip-btn active" data-ctx-limit="1000000">1M</button> <button type="button" class="chip-btn" data-ctx-limit="1000000">1M</button>
<button type="button" class="chip-btn" data-ctx-limit="2000000">2M</button> <button type="button" class="chip-btn" data-ctx-limit="2000000">2M</button>
</div> </div>
</div> </div>
@@ -121,21 +122,21 @@
</div> </div>
<div class="cons-card-main"> <div class="cons-card-main">
<strong class="cons-tokens" id="cons-session-tokens">0</strong> <strong class="cons-tokens" id="cons-session-tokens">0</strong>
<span class="cons-cost" id="cons-session-cost">≈$0.00</span> <span class="cons-cost" id="cons-session-cost">$0.00</span>
</div> </div>
<div class="cons-card-sub" id="cons-session-breakdown">入 0 · 缓 0 · 出 0</div> <div class="cons-card-sub" id="cons-session-breakdown">入 0 · 缓 0 · 出 0</div>
<div class="cons-card-foot muted" id="cons-session-pool">占同期账号 0%</div> <div class="cons-card-foot muted" id="cons-session-pool">占同期本机 0%</div>
</div> </div>
<!-- Account Total Consumption --> <!-- Account Total Consumption -->
<div class="consumption-card account-card"> <div class="consumption-card account-card">
<div class="cons-card-header"> <div class="cons-card-header">
<span class="cons-card-title">👤 本账号总消耗</span> <span class="cons-card-title" title="统计本机所有历史会话步骤的真实账面消耗">👤 本机累计消耗</span>
<span class="cons-card-badge" id="cons-account-meta">0 会话 · 0 步</span> <span class="cons-card-badge" id="cons-account-meta">0 会话 · 0 步</span>
</div> </div>
<div class="cons-card-main"> <div class="cons-card-main">
<strong class="cons-tokens" id="cons-account-tokens">0</strong> <strong class="cons-tokens" id="cons-account-tokens">0</strong>
<span class="cons-cost" id="cons-account-cost">≈$0.00</span> <span class="cons-cost" id="cons-account-cost">$0.00</span>
</div> </div>
<div class="cons-card-sub" id="cons-account-breakdown">入 0 · 缓 0 · 出 0</div> <div class="cons-card-sub" id="cons-account-breakdown">入 0 · 缓 0 · 出 0</div>
<div class="cons-card-foot muted" id="cons-account-pool">Gemini $0.00 · Claude/GPT $0.00</div> <div class="cons-card-foot muted" id="cons-account-pool">Gemini $0.00 · Claude/GPT $0.00</div>
@@ -149,16 +150,16 @@
<div class="popover-section"> <div class="popover-section">
<div class="section-row"> <div class="section-row">
<span class="section-label">您的使用限额 · <span id="account-tier-label">Pro</span></span> <span class="section-label">您的使用限额 · <span id="account-tier-label">Pro</span></span>
<span class="arrow-icon" id="pool-switch-toggle" title="点击展开全部模型池 5h 限额">→</span> <span class="arrow-icon" id="pool-switch-toggle" title="点击展开全部模型池 5h / 周限额">→</span>
</div> </div>
<!-- 5h Session Quota (Active Pool) --> <!-- 5h Session Quota (Active Pool) -->
<div class="quota-block"> <div class="quota-block">
<div class="section-row"> <div class="section-row">
<span class="quota-title" id="session-quota-title">会话限额</span> <span class="quota-title" id="session-quota-title">5h 限额</span>
<span class="quota-meta"> <span class="quota-meta">
<span id="session-reset-text">-- 后重置</span> <span id="session-reset-text">-- 后重置</span>
<strong id="session-used-pct">0%</strong> <strong id="session-used-pct">--</strong>
</span> </span>
</div> </div>
<div class="single-progress-track"> <div class="single-progress-track">
@@ -169,20 +170,20 @@
<!-- All Model Pools (Gemini / Claude / GPT) 5h Quotas --> <!-- All Model Pools (Gemini / Claude / GPT) 5h Quotas -->
<div id="all-pools-container" class="all-pools-box"></div> <div id="all-pools-container" class="all-pools-box"></div>
<!-- Weekly All Models Quota --> <!-- Weekly Pool Quota -->
<div class="quota-block"> <div class="quota-block">
<div class="section-row"> <div class="section-row">
<span class="quota-title">每周·所有模型</span> <span class="quota-title" id="weekly-quota-title">每周限额 (Gemini)</span>
<span class="quota-meta"> <span class="quota-meta">
<span id="weekly-reset-text">-- 后重置</span> <span id="weekly-reset-text">-- 后重置</span>
<strong id="weekly-used-pct">0%</strong> <strong id="weekly-used-pct">--</strong>
</span> </span>
</div> </div>
<div class="single-progress-track"> <div class="single-progress-track">
<div id="bar-weekly-quota" class="bar-fill" style="width: 0%"></div> <div id="bar-weekly-quota" class="bar-fill" style="width: 0%"></div>
</div> </div>
<div class="weekly-sub-meta muted"> <div class="weekly-sub-meta muted">
<span>本周累计: <strong id="weekly-tokens-text">0</strong> (<strong id="weekly-cost-text">≈$0.00</strong>)</span> <span>本周本机: <strong id="weekly-tokens-text">0</strong> (<strong id="weekly-cost-text">$0.00</strong>)</span>
<span id="credits-badge"></span> <span id="credits-badge"></span>
</div> </div>
</div> </div>
@@ -257,12 +258,12 @@
</select> </select>
</label> </label>
<label class="field-label"> <label class="field-label">
<span>自定义每周 Token 预算基准 (默认 80M)</span> <span>自定义每周 Token 预算基准 (默认 150M)</span>
<input type="number" id="setting-weekly-tokens" min="100000" step="1000000" value="80000000"> <input type="number" id="setting-weekly-tokens" min="100000" step="1000000" value="150000000">
</label> </label>
<label class="field-label"> <label class="field-label">
<span>自定义每周费用预算基准 (USD $)</span> <span>自定义每周费用预算基准 (USD $, Ultra 默认 $100)</span>
<input type="number" id="setting-weekly-cost" min="1" step="5" value="35"> <input type="number" id="setting-weekly-cost" min="1" step="5" value="100">
</label> </label>
</div> </div>
<div class="settings-actions"> <div class="settings-actions">
+359 -127
View File
@@ -15,24 +15,30 @@ const LS_ADDR = process.env.ANTIGRAVITY_LS_ADDRESS;
const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN; const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN;
const DEFAULT_SETTINGS = { const DEFAULT_SETTINGS = {
contextWindowLimit: 1000000, // 1M default (can be toggled to 200k / 2M) contextWindowLimit: 256000, // 256k auto-compaction budget default (can be toggled to 256k / 1M / 2M)
weeklyTokenBudget: 80000000, // 80M tokens default custom weekly target weeklyTokenBudget: 150000000, // 150M tokens default custom weekly target
weeklyCostBudget: 35, // $35 default custom weekly cost target weeklyCostBudget: 100, // $100 default custom weekly cost target (matches Ultra weekly pool)
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost' weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
speedMode: 'stream', // 'stream' (streamTokens / streamTime) | 'total' (outputTokens / totalTime) speedMode: 'stream', // 'stream' (streamTokens / streamTime) | 'total' (outputTokens / totalTime)
}; };
// Model pricing table in USD per 1M tokens (Input, CacheRead, Output) // 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
const MODEL_PRICING = { 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-high': { input: 2.00, cache: 0.10, 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-medium': { input: 2.00, cache: 0.10, output: 10.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-4-argon-low': { input: 2.00, cache: 0.10, output: 10.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-high': { input: 0.30, cache: 0.03, 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-medium': { input: 0.30, cache: 0.03, output: 2.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' }, 'gemini-3.8-flash-low': { input: 0.15, cache: 0.015, output: 1.0, 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' }, 'gemini-2.5-flash-lite': { input: 0.10, cache: 0.01, output: 0.40, short: 'flash-2.5-lite', family: 'Gemini' },
'gemini-2.5-flash': { input: 0.30, cache: 0.03, output: 2.5, short: 'flash-2.5', family: 'Gemini' },
'gemini-2.5-pro': { input: 1.25, cache: 0.125, output: 10.0, short: 'pro-2.5', family: 'Gemini' },
'claude-opus-4-6-thinking': { input: 5.0, cache: 0.50, output: 25.0, short: 'opus', family: 'Claude' },
'claude-sonnet-4-6': { input: 3.0, cache: 0.30, output: 15.0, short: 'sonnet', 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' }, 'gpt-oss-120b-medium': { input: 0.80, cache: 0.10, output: 2.40, short: 'gpt-oss', family: 'GPT' },
}; };
// Fallback placeholder -> modelId mapping // Fallback placeholder -> modelId mapping
@@ -43,16 +49,19 @@ const PLACEHOLDER_MAP = {
MODEL_PLACEHOLDER_M318: { modelId: 'gemini-3.8-flash-high', label: 'Gemini 3.8 Flash (High)' }, 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_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_M320: { modelId: 'gemini-3.8-flash-low', label: 'Gemini 3.8 Flash (Low)' },
MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' },
MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
MODEL_GOOGLE_GEMINI_2_5_PRO: { modelId: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
MODEL_PLACEHOLDER_M26: { modelId: 'claude-opus-4-6-thinking', label: 'Claude Opus 4.6 (Thinking)' }, 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_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)' }, 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 } // In-memory cache of trajectory step usage: cascadeId -> { signature, steps }
const CACHE_SCHEMA_VERSION = 'v2'; const CACHE_SCHEMA_VERSION = 'v4';
let trajectoryCache = loadJson(CACHE_FILE, {}); let trajectoryCache = loadJson(CACHE_FILE, {});
const inFlightRequests = new Map(); const inFlightRequests = new Map();
let quotaSummaryCache = { ts: 0, data: null }; let quotaSummaryCache = { ts: 0, data: null, error: null };
function loadJson(filePath, fallback) { function loadJson(filePath, fallback) {
if (!existsSync(filePath)) return fallback; if (!existsSync(filePath)) return fallback;
@@ -93,7 +102,7 @@ function parseDurationSec(durStr) {
return Number.isFinite(n) && n > 0 ? n : 0; return Number.isFinite(n) && n > 0 ? n : 0;
} }
async function callLsRpc(method, body = {}) { async function callLsRpc(method, body = {}, timeoutMs = 5000) {
const res = await fetch( const res = await fetch(
`http://${LS_ADDR}/exa.language_server_pb.LanguageServerService/${method}`, `http://${LS_ADDR}/exa.language_server_pb.LanguageServerService/${method}`,
{ {
@@ -103,6 +112,7 @@ async function callLsRpc(method, body = {}) {
'x-codeium-csrf-token': CSRF_TOKEN, 'x-codeium-csrf-token': CSRF_TOKEN,
}, },
body: JSON.stringify(body), body: JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
} }
); );
if (!res.ok) { if (!res.ok) {
@@ -114,40 +124,112 @@ async function callLsRpc(method, body = {}) {
async function getOfficialQuotaSummary(forceRefresh = false) { async function getOfficialQuotaSummary(forceRefresh = false) {
const now = Date.now(); const now = Date.now();
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < 8000) { // Use 10s local cache for routine polling; when cache expires or forceRefresh=true,
return quotaSummaryCache.data; // pass { forceRefresh: true } to bypass language_server.exe's internal 3-minute stale cache.
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < 10000) {
return {
data: quotaSummaryCache.data,
fetchedAtMs: quotaSummaryCache.ts,
isStale: false,
refreshFailed: false,
error: null,
};
} }
try { try {
const res = await callLsRpc('RetrieveUserQuotaSummary', {}); const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
if (res?.response?.groups) { if (res?.response?.groups) {
quotaSummaryCache = { ts: now, data: res.response }; quotaSummaryCache = { ts: now, data: res.response, error: null };
return res.response; return {
data: res.response,
fetchedAtMs: now,
isStale: false,
refreshFailed: false,
error: null,
};
} }
} catch (err) { } catch (err) {
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`); console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
quotaSummaryCache.error = err.message;
} }
return quotaSummaryCache.data; return {
data: quotaSummaryCache.data,
fetchedAtMs: quotaSummaryCache.ts || 0,
isStale: Boolean(quotaSummaryCache.data),
refreshFailed: true,
error: quotaSummaryCache.error || 'Quota RPC unavailable',
};
} }
function resolveModelInfo(rawModelKey, dynamicModelMap) { function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvider = '') {
const prov = String(apiProvider || '').toUpperCase();
if (prov.includes('GEMINI') || prov.includes('GOOGLE')) return 'Gemini';
if (prov.includes('ANTHROPIC') || prov.includes('CLAUDE')) return 'Claude';
if (prov.includes('OPENAI') || prov.includes('GPT')) return 'GPT';
const combined = `${rawModelKey} ${modelId}`.toUpperCase();
if (combined.includes('GEMINI') || combined.includes('ARGON') || combined.includes('FLASH') || combined.includes('GOOGLE')) {
return 'Gemini';
}
if (combined.includes('CLAUDE') || combined.includes('SONNET') || combined.includes('OPUS') || combined.includes('HAIKU')) {
return 'Claude';
}
if (combined.includes('GPT') || combined.includes('OPENAI')) {
return 'GPT';
}
return 'Other';
}
function resolveModelInfo(rawModelKey, dynamicModelMap, apiProvider = '') {
const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey] || { const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey] || {
modelId: rawModelKey || 'unknown', modelId: rawModelKey || 'unknown',
label: rawModelKey || 'Unknown Model', label: rawModelKey || 'Unknown Model',
}; };
const pricing = MODEL_PRICING[dyn.modelId] || { const explicitPricing = MODEL_PRICING[dyn.modelId];
input: 1.0, if (explicitPricing) {
cache: 0.25, return {
output: 5.0, rawModel: rawModelKey,
short: (dyn.label || 'model').split(' ')[0].toLowerCase(), modelId: dyn.modelId,
family: 'Other', label: dyn.label,
}; shortName: explicitPricing.short,
family: explicitPricing.family,
pricing: explicitPricing,
isEstimatedPrice: false,
};
}
const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, dyn.modelId, apiProvider);
const rawUpper = String(rawModelKey || dyn.modelId || '').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 {
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: (dyn.label || 'unknown').split(' ')[0].toLowerCase(),
family: 'Other',
};
}
return { return {
rawModel: rawModelKey, rawModel: rawModelKey,
modelId: dyn.modelId, modelId: dyn.modelId,
label: dyn.label, label: dyn.label,
shortName: pricing.short, shortName: fallbackPricing.short,
family: pricing.family, family: fallbackPricing.family,
pricing, pricing: fallbackPricing,
isEstimatedPrice: true,
}; };
} }
@@ -158,20 +240,34 @@ function computeStepCost(step, pricing) {
return inCost + cacheCost + outCost; return inCost + cacheCost + outCost;
} }
function extractModelSteps(rawSteps = []) { function extractModelSteps(rawSteps = [], generatorMetadata = []) {
const genMetaByStep = new Map();
for (const gm of generatorMetadata || []) {
const indices = gm?.stepIndices || [];
for (const idx of indices) {
genMetaByStep.set(Number(idx), gm);
}
}
const parsed = []; const parsed = [];
rawSteps.forEach((s, idx) => { rawSteps.forEach((s, idx) => {
const m = s?.metadata; const m = s?.metadata;
const u = m?.modelUsage; const isCompactionStep = s?.type === 'CORTEX_STEP_TYPE_CHECKPOINT';
const u = m?.modelUsage || (m?.retryInfos?.[0]?.usage ?? null);
if (!u) return; if (!u) return;
const stepIndex = s?.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? idx;
const gm = m?.generatorMetadata?.[0] || genMetaByStep.get(Number(stepIndex)) || genMetaByStep.get(idx) || null;
const chatModel = gm?.chatModel || null;
const ctxWinMeta = chatModel?.chatStartMetadata?.contextWindowMetadata || null;
const p = s?.plannerResponse || {}; const p = s?.plannerResponse || {};
const inputTokens = Number(u.inputTokens || 0); const inputTokens = Number(u.inputTokens || 0);
const cacheReadTokens = Number(u.cacheReadTokens || 0); const cacheReadTokens = Number(u.cacheReadTokens || 0);
const outputTokens = Number(u.outputTokens || 0); const outputTokens = Number(u.outputTokens || 0);
const thinkingTokens = Number(u.thinkingOutputTokens || 0); const thinkingTokens = Number(p.thinkingTokens || u.thinkingOutputTokens || chatModel?.usage?.thinkingOutputTokens || 0);
const responseTokens = Number( const responseTokens = Number(
u.responseOutputTokens || Math.max(0, outputTokens - thinkingTokens) p.responseTokens || u.responseOutputTokens || chatModel?.usage?.responseOutputTokens || Math.max(0, outputTokens - thinkingTokens)
); );
const createdAtMs = parseIsoMs(m.createdAt); const createdAtMs = parseIsoMs(m.createdAt);
@@ -193,49 +289,38 @@ function extractModelSteps(rawSteps = []) {
? (finishedAtMs - createdAtMs) / 1000 ? (finishedAtMs - createdAtMs) / 1000
: 0; : 0;
const nativeTtftSec = parseDurationSec(chatModel?.timeToFirstToken);
const nativeStreamSec = parseDurationSec(chatModel?.streamingDuration);
const thinkingDurationSec = parseDurationSec(p.thinkingDuration); const thinkingDurationSec = parseDurationSec(p.thinkingDuration);
const respText = String(p.modifiedResponse || p.response || '').trim(); const respText = String(p.modifiedResponse || p.response || '').trim();
const hasVisibleText = respText.length > 0; const hasVisibleText = respText.length > 0;
let streamTokens = responseTokens; const ttftSec = nativeTtftSec > 0 ? nativeTtftSec : rawViewableSec;
let streamTokens = outputTokens;
let streamDurationSec = 0; let streamDurationSec = 0;
const ttftSec = rawViewableSec; let speedBasis = 'model_stream';
if (hasVisibleText) { const postThinkingSec =
const postThinkingSec = thinkingDurationSec > 0 && totalDurationSec > thinkingDurationSec
thinkingDurationSec > 0 && totalDurationSec > thinkingDurationSec ? totalDurationSec - thinkingDurationSec
? totalDurationSec - thinkingDurationSec : afterViewableSec;
: afterViewableSec;
if ( if (hasVisibleText && responseTokens > 0 && postThinkingSec >= 0.2) {
postThinkingSec >= 0.25 && streamTokens = responseTokens;
responseTokens > 0 && streamDurationSec = postThinkingSec;
responseTokens / postThinkingSec <= 240 speedBasis = 'response_stream';
) { } else if (nativeStreamSec >= 0.2 && outputTokens > 0) {
streamTokens = responseTokens; streamTokens = outputTokens;
streamDurationSec = postThinkingSec; streamDurationSec = nativeStreamSec;
} else if ( speedBasis = 'native_stream';
afterViewableSec >= 0.5 && } else if (afterViewableSec >= 0.25 && outputTokens > 0) {
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; streamTokens = outputTokens;
streamDurationSec = afterViewableSec; streamDurationSec = afterViewableSec;
speedBasis = 'viewable_stream';
} else { } else {
streamTokens = outputTokens; streamTokens = outputTokens;
streamDurationSec = totalDurationSec; streamDurationSec = totalDurationSec;
speedBasis = 'total_fallback';
} }
const totalTokPerSec = const totalTokPerSec =
@@ -245,9 +330,14 @@ function extractModelSteps(rawSteps = []) {
? streamTokens / streamDurationSec ? streamTokens / streamDurationSec
: totalTokPerSec; : totalTokPerSec;
const estimatedContextTokens = Number(ctxWinMeta?.estimatedTokensUsed || 0);
const maxContextBudgetTokens = Number(ctxWinMeta?.maxContextTokens || 256000);
parsed.push({ parsed.push({
stepIndex: s?.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? idx, stepIndex,
modelKey: u.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418', isCompactionStep,
modelKey: u.model || chatModel?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418',
apiProvider: u.apiProvider || chatModel?.usage?.apiProvider || '',
createdAt: m.createdAt || null, createdAt: m.createdAt || null,
createdAtMs: Math.floor(createdAtMs), createdAtMs: Math.floor(createdAtMs),
hasVisibleText, hasVisibleText,
@@ -257,6 +347,9 @@ function extractModelSteps(rawSteps = []) {
thinkingTokens, thinkingTokens,
responseTokens, responseTokens,
streamTokens, streamTokens,
speedBasis,
estimatedContextTokens,
maxContextBudgetTokens,
thinkingDurationSec: +thinkingDurationSec.toFixed(3), thinkingDurationSec: +thinkingDurationSec.toFixed(3),
ttftSec: +ttftSec.toFixed(3), ttftSec: +ttftSec.toFixed(3),
streamDurationSec: +streamDurationSec.toFixed(3), streamDurationSec: +streamDurationSec.toFixed(3),
@@ -292,17 +385,45 @@ function getStartOfCurrentWeekMs(now = new Date()) {
return d.getTime(); return d.getTime();
} }
function resolveTimeWindow(rangeKey = 'all', customStartMs = 0, customEndMs = 0, nowMs = Date.now()) { function resolveTimeWindow(
rangeKey = 'all',
customStartMs = 0,
customEndMs = 0,
nowMs = Date.now(),
cycleAnchors = {}
) {
const now = new Date(nowMs); const now = new Date(nowMs);
switch (rangeKey) { switch (rangeKey) {
case '5h': case '5h': {
return { key: '5h', label: '近 5 小时', startMs: nowMs - 5 * 3600 * 1000, endMs: nowMs }; const reset5hMs = cycleAnchors.fiveHourResetMs || 0;
const start5hMs =
reset5hMs > nowMs
? reset5hMs - 5 * 3600 * 1000
: nowMs - 5 * 3600 * 1000;
return {
key: '5h',
label: reset5hMs > nowMs ? '当前 5h 周期' : '近 5 小时',
startMs: start5hMs,
endMs: nowMs,
};
}
case 'today': case 'today':
return { key: 'today', label: '今日', startMs: getStartOfLocalDayMs(now), endMs: nowMs }; return { key: 'today', label: '今日', startMs: getStartOfLocalDayMs(now), endMs: nowMs };
case '24h': case '24h':
return { key: '24h', label: '近 24 小时', startMs: nowMs - 24 * 3600 * 1000, endMs: nowMs }; return { key: '24h', label: '近 24 小时', startMs: nowMs - 24 * 3600 * 1000, endMs: nowMs };
case 'week': case 'week': {
return { key: 'week', label: '本周', startMs: getStartOfCurrentWeekMs(now), endMs: nowMs }; const resetWkMs = cycleAnchors.weeklyResetMs || 0;
const startWkMs =
resetWkMs > nowMs
? resetWkMs - 7 * 24 * 3600 * 1000
: getStartOfCurrentWeekMs(now);
return {
key: 'week',
label: resetWkMs > nowMs ? '当前周限周期' : '本周',
startMs: startWkMs,
endMs: nowMs,
};
}
case '7d': case '7d':
return { key: '7d', label: '近 7 天', startMs: nowMs - 7 * 24 * 3600 * 1000, endMs: nowMs }; return { key: '7d', label: '近 7 天', startMs: nowMs - 7 * 24 * 3600 * 1000, endMs: nowMs };
case '30d': case '30d':
@@ -359,7 +480,7 @@ function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) {
bucket.geminiTokens += stepTotalTokens; bucket.geminiTokens += stepTotalTokens;
bucket.geminiCostUsd += stepCost; bucket.geminiCostUsd += stepCost;
bucket.geminiCalls += 1; bucket.geminiCalls += 1;
} else { } else if (mInfo.family === 'Claude' || mInfo.family === 'GPT') {
bucket.claudeGptTokens += stepTotalTokens; bucket.claudeGptTokens += stepTotalTokens;
bucket.claudeGptCostUsd += stepCost; bucket.claudeGptCostUsd += stepCost;
bucket.claudeGptCalls += 1; bucket.claudeGptCalls += 1;
@@ -395,7 +516,9 @@ function discoverLocalConversationFiles() {
if (!existsSync(CONVERSATIONS_DIR)) return map; if (!existsSync(CONVERSATIONS_DIR)) return map;
try { try {
for (const name of readdirSync(CONVERSATIONS_DIR)) { for (const name of readdirSync(CONVERSATIONS_DIR)) {
const m = name.match(/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb)$/i); const m = name.match(
/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(db|pb|db-wal)$/i
);
if (!m) continue; if (!m) continue;
const cascadeId = m[1].toLowerCase(); const cascadeId = m[1].toLowerCase();
try { try {
@@ -420,13 +543,15 @@ async function buildTelemetryPayloadInternal(
filterOpts = {} filterOpts = {}
) { ) {
const settings = loadSettings(); const settings = loadSettings();
const [userStatusRes, allTrajRes, officialQuota] = await Promise.all([ const [userStatusRes, allTrajRes, officialQuotaInfo] = await Promise.all([
callLsRpc('GetUserStatus', {}).catch(() => ({})), callLsRpc('GetUserStatus', {}).catch(() => ({})),
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
getOfficialQuotaSummary(forceQuotaRefresh), getOfficialQuotaSummary(forceQuotaRefresh),
]); ]);
const officialQuota = officialQuotaInfo?.data || null;
const userStatus = userStatusRes?.userStatus || {}; const userStatus = userStatusRes?.userStatus || {};
const currentAccountName = userStatus?.email || userStatus?.name || '';
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || []; const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
const dynamicModelMap = new Map(); const dynamicModelMap = new Map();
@@ -434,8 +559,8 @@ async function buildTelemetryPayloadInternal(
const officialBuckets = new Map(); const officialBuckets = new Map();
for (const grp of officialQuota?.groups || []) { for (const grp of officialQuota?.groups || []) {
for (const b of grp?.buckets || []) { for (const b of grp?.buckets || []) {
if (b?.bucketId) { if (b?.bucketId && b.remainingFraction !== undefined && b.remainingFraction !== null) {
const remFrac = b.remainingFraction ?? 1; const remFrac = Number(b.remainingFraction);
const usedFrac = Math.max(0, Math.min(1, 1 - remFrac)); const usedFrac = Math.max(0, Math.min(1, 1 - remFrac));
officialBuckets.set(b.bucketId, { officialBuckets.set(b.bucketId, {
bucketId: b.bucketId, bucketId: b.bucketId,
@@ -470,8 +595,10 @@ async function buildTelemetryPayloadInternal(
const live5h = officialBuckets.get(isGemini ? 'gemini-5h' : '3p-5h'); const live5h = officialBuckets.get(isGemini ? 'gemini-5h' : '3p-5h');
const liveWeekly = officialBuckets.get(isGemini ? 'gemini-weekly' : '3p-weekly'); const liveWeekly = officialBuckets.get(isGemini ? 'gemini-weekly' : '3p-weekly');
const remFrac = live5h?.remainingFraction ?? cfg?.quotaInfo?.remainingFraction ?? 1; const rawRemFrac = live5h?.remainingFraction ?? cfg?.quotaInfo?.remainingFraction ?? null;
const usedFrac = Math.max(0, Math.min(1, 1 - remFrac)); const hasValid5h = rawRemFrac !== null && rawRemFrac !== undefined && Number.isFinite(Number(rawRemFrac));
const remFrac = hasValid5h ? Number(rawRemFrac) : null;
const usedFrac = hasValid5h ? Math.max(0, Math.min(1, 1 - remFrac)) : null;
const resetTime = live5h?.resetTime || cfg?.quotaInfo?.resetTime || null; const resetTime = live5h?.resetTime || cfg?.quotaInfo?.resetTime || null;
const quotaItem = { const quotaItem = {
@@ -479,9 +606,10 @@ async function buildTelemetryPayloadInternal(
modelId: cfg.modelId, modelId: cfg.modelId,
rawKey, rawKey,
family: info.family, family: info.family,
remainingPct: +(remFrac * 100).toFixed(1), isAvailable: hasValid5h,
remainingIntPct: Math.floor(remFrac * 100 + 1e-6), remainingPct: hasValid5h ? +(remFrac * 100).toFixed(1) : null,
usedPct: +(usedFrac * 100).toFixed(1), remainingIntPct: hasValid5h ? Math.floor(remFrac * 100 + 1e-6) : null,
usedPct: hasValid5h ? +(usedFrac * 100).toFixed(1) : null,
resetTime, resetTime,
weeklyRemainingPct: liveWeekly?.remainingPct ?? null, weeklyRemainingPct: liveWeekly?.remainingPct ?? null,
weeklyRemainingIntPct: liveWeekly?.remainingIntPct ?? null, weeklyRemainingIntPct: liveWeekly?.remainingIntPct ?? null,
@@ -496,6 +624,7 @@ async function buildTelemetryPayloadInternal(
quotaPoolsMap.set(poolKey, { quotaPoolsMap.set(poolKey, {
poolName: isGemini ? 'Gemini 模型池' : 'Claude & GPT 模型池', poolName: isGemini ? 'Gemini 模型池' : 'Claude & GPT 模型池',
family: poolKey, family: poolKey,
isAvailable: quotaItem.isAvailable,
remainingPct: quotaItem.remainingPct, remainingPct: quotaItem.remainingPct,
remainingIntPct: quotaItem.remainingIntPct, remainingIntPct: quotaItem.remainingIntPct,
usedPct: quotaItem.usedPct, usedPct: quotaItem.usedPct,
@@ -525,18 +654,29 @@ async function buildTelemetryPayloadInternal(
for (const cascadeId of allCascadeIds) { for (const cascadeId of allCascadeIds) {
const item = summariesObj[cascadeId]; const item = summariesObj[cascadeId];
const cached = trajectoryCache[cascadeId]; const cached = trajectoryCache[cascadeId];
if (
cached?.accountName &&
currentAccountName &&
cached.accountName !== currentAccountName &&
!item
) {
continue;
}
const diskMtimeMs = diskConvMap.get(cascadeId) || 0; const diskMtimeMs = diskConvMap.get(cascadeId) || 0;
if (item) { if (item) {
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || ''; const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
const lastModifiedMs = parseIsoMs(lastModifiedTime) || diskMtimeMs || cached?.lastModifiedMs || 0; const lastModifiedMs =
parseIsoMs(lastModifiedTime) || diskMtimeMs || cached?.lastModifiedMs || 0;
conversations.push({ conversations.push({
cascadeId, cascadeId,
title: item?.annotations?.title || item?.summary || cached?.title || cascadeId.slice(0, 8), title:
item?.annotations?.title || item?.summary || cached?.title || cascadeId.slice(0, 8),
stepCount: Number(item?.stepCount || cached?.steps?.length || 0), stepCount: Number(item?.stepCount || cached?.steps?.length || 0),
status: item?.status || '', status: item?.status || '',
lastModifiedTime, lastModifiedTime,
lastModifiedMs, lastModifiedMs,
diskMtimeMs,
inSummaries: true, inSummaries: true,
}); });
} else if (cached) { } else if (cached) {
@@ -548,6 +688,7 @@ async function buildTelemetryPayloadInternal(
status: 'IDLE', status: 'IDLE',
lastModifiedTime: '', lastModifiedTime: '',
lastModifiedMs: Math.max(cached.lastModifiedMs || 0, lastStepMs, diskMtimeMs), lastModifiedMs: Math.max(cached.lastModifiedMs || 0, lastStepMs, diskMtimeMs),
diskMtimeMs,
inSummaries: false, inSummaries: false,
}); });
} else { } else {
@@ -558,6 +699,7 @@ async function buildTelemetryPayloadInternal(
status: 'IDLE', status: 'IDLE',
lastModifiedTime: '', lastModifiedTime: '',
lastModifiedMs: diskMtimeMs, lastModifiedMs: diskMtimeMs,
diskMtimeMs,
inSummaries: false, inSummaries: false,
needsInitialLoad: true, needsInitialLoad: true,
}); });
@@ -573,13 +715,17 @@ async function buildTelemetryPayloadInternal(
null; null;
const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null; const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null;
// Refresh trajectory cache for any uncached or updated conversation across the entire account // Refresh trajectory cache for any uncached, schema-outdated, or updated conversation
let cacheDirty = false; let cacheDirty = false;
const toFetch = conversations.filter((conv) => { const toFetch = conversations.filter((conv) => {
const cached = trajectoryCache[conv.cascadeId]; const cached = trajectoryCache[conv.cascadeId];
if (!cached || conv.needsInitialLoad) return true; if (!cached || conv.needsInitialLoad) return true;
if (!conv.inSummaries) return false; const hasCurrentSchema = String(cached.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`);
if (!hasCurrentSchema) return true;
if (!conv.inSummaries) {
return conv.diskMtimeMs > 0 && conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0);
}
const sig = `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`; const sig = `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`;
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
return cached.signature !== sig || isRunning || Boolean(cached.wasRunning); return cached.signature !== sig || isRunning || Boolean(cached.wasRunning);
@@ -593,13 +739,14 @@ async function buildTelemetryPayloadInternal(
batch.map(async (conv) => { batch.map(async (conv) => {
const sig = conv.inSummaries const sig = conv.inSummaries
? `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}` ? `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`
: trajectoryCache[conv.cascadeId]?.signature || `${CACHE_SCHEMA_VERSION}:disk:${conv.lastModifiedMs}`; : `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
const prev = trajectoryCache[conv.cascadeId]; const prev = trajectoryCache[conv.cascadeId];
try { try {
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
const rawSteps = trajRes?.trajectory?.steps || []; const rawSteps = trajRes?.trajectory?.steps || [];
const steps = extractModelSteps(rawSteps); const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
const steps = extractModelSteps(rawSteps, generatorMeta);
const prevLast = prev?.steps?.[prev.steps.length - 1]; const prevLast = prev?.steps?.[prev.steps.length - 1];
const nextLast = steps[steps.length - 1]; const nextLast = steps[steps.length - 1];
const stepsChanged = const stepsChanged =
@@ -619,8 +766,10 @@ async function buildTelemetryPayloadInternal(
trajectoryCache[conv.cascadeId] = { trajectoryCache[conv.cascadeId] = {
signature: sig, signature: sig,
accountName: currentAccountName || prev?.accountName || '',
title: conv.title, title: conv.title,
lastModifiedMs: resolvedLastModMs, lastModifiedMs: resolvedLastModMs,
diskMtimeMs: conv.diskMtimeMs || 0,
wasRunning: isRunning, wasRunning: isRunning,
steps, steps,
}; };
@@ -650,17 +799,19 @@ async function buildTelemetryPayloadInternal(
let sessionCacheReadTokens = 0; let sessionCacheReadTokens = 0;
const enrichedActiveSteps = activeSteps.map((st) => { const enrichedActiveSteps = activeSteps.map((st) => {
const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap); const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider);
const costUsd = computeStepCost(st, mInfo.pricing); const costUsd = computeStepCost(st, mInfo.pricing);
const stepStreamTokens = st.streamTokens ?? st.outputTokens; const stepStreamTokens = st.streamTokens ?? st.outputTokens;
const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec; const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec;
if (useStreamSpeed) { if (!st.isCompactionStep) {
sessionSpeedNumeratorTokens += stepStreamTokens; if (useStreamSpeed) {
sessionSpeedDenominatorSec += stepStreamSec; sessionSpeedNumeratorTokens += stepStreamTokens;
} else { sessionSpeedDenominatorSec += stepStreamSec;
sessionSpeedNumeratorTokens += st.outputTokens; } else {
sessionSpeedDenominatorSec += st.totalDurationSec; sessionSpeedNumeratorTokens += st.outputTokens;
sessionSpeedDenominatorSec += st.totalDurationSec;
}
} }
sessionCostUsd += costUsd; sessionCostUsd += costUsd;
@@ -673,8 +824,8 @@ async function buildTelemetryPayloadInternal(
return { return {
...st, ...st,
modelLabel: mInfo.label, modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
modelShort: mInfo.shortName, modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
family: mInfo.family, family: mInfo.family,
tokPerSec: +tokPerSec.toFixed(1), tokPerSec: +tokPerSec.toFixed(1),
ttftSec: +st.ttftSec.toFixed(1), ttftSec: +st.ttftSec.toFixed(1),
@@ -698,7 +849,16 @@ async function buildTelemetryPayloadInternal(
const ctxThinking = latestEnriched?.thinkingTokens || 0; const ctxThinking = latestEnriched?.thinkingTokens || 0;
const ctxResponse = latestEnriched?.responseTokens || 0; const ctxResponse = latestEnriched?.responseTokens || 0;
const ctxTotal = ctxCached + ctxFreshInput + ctxThinking + ctxResponse; const ctxTotal = ctxCached + ctxFreshInput + ctxThinking + ctxResponse;
const ctxLimit = Number(settings.contextWindowLimit || 1000000); const compactionLimitTokens = Number(latestEnriched?.maxContextBudgetTokens || 256000);
const compactionUsedTokens = Number(
latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput
);
const compactionUsedPct =
compactionLimitTokens > 0
? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1))
: 0;
const ctxLimit = Number(settings.contextWindowLimit || 256000);
const ctxPct = ctxLimit > 0 ? Math.min(100, +((ctxTotal / ctxLimit) * 100).toFixed(1)) : 0; const ctxPct = ctxLimit > 0 ? Math.min(100, +((ctxTotal / ctxLimit) * 100).toFixed(1)) : 0;
// Cache hit rate (latest step & session-wide) // Cache hit rate (latest step & session-wide)
@@ -709,13 +869,26 @@ async function buildTelemetryPayloadInternal(
const sessionCacheHitPct = const sessionCacheHitPct =
sessionPromptTokens > 0 ? Math.round((sessionCacheReadTokens / sessionPromptTokens) * 100) : 0; 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 activeLiveWeekly = officialBuckets.get(
activePoolKey === 'Gemini' ? 'gemini-weekly' : '3p-weekly'
);
const cycleAnchors = {
fiveHourResetMs: parseIsoMs(activeLive5h?.resetTime),
weeklyResetMs: parseIsoMs(activeLiveWeekly?.resetTime),
};
// Aggregate across time windows (presets + selected range) // Aggregate across time windows (presets + selected range)
const nowMs = Date.now(); const nowMs = Date.now();
const selectedWindow = resolveTimeWindow( const selectedWindow = resolveTimeWindow(
filterOpts.range || 'all', filterOpts.range || 'all',
filterOpts.startMs, filterOpts.startMs,
filterOpts.endMs, filterOpts.endMs,
nowMs nowMs,
cycleAnchors
); );
const presetKeys = ['all', '5h', 'today', '24h', 'week', '7d', '30d']; const presetKeys = ['all', '5h', 'today', '24h', 'week', '7d', '30d'];
@@ -724,7 +897,7 @@ async function buildTelemetryPayloadInternal(
const sessionBuckets = {}; const sessionBuckets = {};
for (const k of presetKeys) { for (const k of presetKeys) {
presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs); presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors);
accountBuckets[k] = createUsageBucket(); accountBuckets[k] = createUsageBucket();
sessionBuckets[k] = createUsageBucket(); sessionBuckets[k] = createUsageBucket();
} }
@@ -733,9 +906,17 @@ async function buildTelemetryPayloadInternal(
const perModelStats = new Map(); const perModelStats = new Map();
for (const [cascadeId, entry] of Object.entries(trajectoryCache)) { for (const [cascadeId, entry] of Object.entries(trajectoryCache)) {
if (
entry?.accountName &&
currentAccountName &&
entry.accountName !== currentAccountName &&
cascadeId !== activeCascadeId
) {
continue;
}
const isCurrentConv = cascadeId === activeCascadeId; const isCurrentConv = cascadeId === activeCascadeId;
for (const st of entry?.steps || []) { for (const st of entry?.steps || []) {
const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap); const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider);
const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens; const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens;
const stepCost = computeStepCost(st, mInfo.pricing); const stepCost = computeStepCost(st, mInfo.pricing);
const tMs = st.createdAtMs || 0; const tMs = st.createdAtMs || 0;
@@ -803,24 +984,18 @@ async function buildTelemetryPayloadInternal(
const todayBucket = finalizedPresets.today.account; const todayBucket = finalizedPresets.today.account;
const weekBucket = finalizedPresets.week.account; const weekBucket = finalizedPresets.week.account;
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 familyPoolQuota = quotaPoolsMap.get(activePoolKey);
const activePoolQuota = familyPoolQuota || { const activePoolQuota = familyPoolQuota || {
poolName: activePoolKey === 'Gemini' ? 'Gemini 模型池' : 'Claude & GPT 模型池', poolName: activePoolKey === 'Gemini' ? 'Gemini 模型池' : 'Claude & GPT 模型池',
family: activePoolKey, family: activePoolKey,
remainingPct: activeLive5h?.remainingPct ?? 100, isAvailable: Boolean(activeLive5h),
remainingIntPct: activeLive5h?.remainingIntPct ?? 100, remainingPct: activeLive5h?.remainingPct ?? null,
usedPct: activeLive5h?.usedPct ?? 0, remainingIntPct: activeLive5h?.remainingIntPct ?? null,
usedPct: activeLive5h?.usedPct ?? null,
resetTime: activeLive5h?.resetTime || null, resetTime: activeLive5h?.resetTime || null,
weeklyRemainingPct: activeLiveWeekly?.remainingPct ?? 100, weeklyRemainingPct: activeLiveWeekly?.remainingPct ?? null,
weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? 100, weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? null,
weeklyUsedPct: activeLiveWeekly?.usedPct ?? 0, weeklyUsedPct: activeLiveWeekly?.usedPct ?? null,
weeklyResetTime: activeLiveWeekly?.resetTime || null, weeklyResetTime: activeLiveWeekly?.resetTime || null,
models: [], models: [],
}; };
@@ -833,18 +1008,25 @@ async function buildTelemetryPayloadInternal(
+((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1) +((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1)
); );
const useOfficialWeekly = const isCustomWeeklyMode =
Boolean(activeLiveWeekly) && settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost';
settings.weeklyLimitMode !== 'custom_tokens' && const useOfficialWeekly = Boolean(activeLiveWeekly) && !isCustomWeeklyMode;
settings.weeklyLimitMode !== 'custom_cost';
const weeklyUsedPct = useOfficialWeekly ? activeLiveWeekly.usedPct : fallbackWeeklyPct; const weeklyUsedPct = useOfficialWeekly
? activeLiveWeekly.usedPct
: isCustomWeeklyMode
? fallbackWeeklyPct
: null;
const weeklyRemainingPct = useOfficialWeekly const weeklyRemainingPct = useOfficialWeekly
? activeLiveWeekly.remainingPct ? activeLiveWeekly.remainingPct
: +(100 - fallbackWeeklyPct).toFixed(1); : isCustomWeeklyMode
? +(100 - fallbackWeeklyPct).toFixed(1)
: null;
const weeklyRemainingIntPct = useOfficialWeekly const weeklyRemainingIntPct = useOfficialWeekly
? activeLiveWeekly.remainingIntPct ? activeLiveWeekly.remainingIntPct
: Math.max(0, Math.floor(100 - fallbackWeeklyPct)); : isCustomWeeklyMode
? Math.max(0, Math.floor(100 - fallbackWeeklyPct))
: null;
// Extract genuine Google One AI credits if present (ignore legacy hardcoded 500 prompt credits) // Extract genuine Google One AI credits if present (ignore legacy hardcoded 500 prompt credits)
const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find( const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find(
@@ -881,6 +1063,9 @@ async function buildTelemetryPayloadInternal(
totalTokens: ctxTotal, totalTokens: ctxTotal,
limitTokens: ctxLimit, limitTokens: ctxLimit,
usedPct: ctxPct, usedPct: ctxPct,
compactionUsedTokens,
compactionLimitTokens,
compactionUsedPct,
cachedTokens: ctxCached, cachedTokens: ctxCached,
freshInputTokens: ctxFreshInput, freshInputTokens: ctxFreshInput,
thinkingTokens: ctxThinking, thinkingTokens: ctxThinking,
@@ -902,6 +1087,14 @@ async function buildTelemetryPayloadInternal(
presets: finalizedPresets, presets: finalizedPresets,
}, },
quotas: { quotas: {
meta: {
fetchedAtMs: officialQuotaInfo?.fetchedAtMs || 0,
hasOfficialData: Boolean(officialQuotaInfo?.data),
isStale: Boolean(officialQuotaInfo?.isStale),
refreshFailed: Boolean(officialQuotaInfo?.refreshFailed),
error: officialQuotaInfo?.error || null,
errorMessage: officialQuotaInfo?.error || null,
},
activePool: activePoolQuota, activePool: activePoolQuota,
pools: Array.from(quotaPoolsMap.values()).sort((a, b) => { pools: Array.from(quotaPoolsMap.values()).sort((a, b) => {
const order = { Gemini: 0, 'Claude & GPT': 1 }; const order = { Gemini: 0, 'Claude & GPT': 1 };
@@ -910,6 +1103,10 @@ async function buildTelemetryPayloadInternal(
models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))), models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))),
weekly: { weekly: {
isOfficial: useOfficialWeekly, isOfficial: useOfficialWeekly,
poolFamily: activePoolKey,
title: isCustomWeeklyMode
? '每周限额 (自定义本机)'
: `每周限额 (${activePoolKey || '当前'})`,
calls: weekBucket.calls, calls: weekBucket.calls,
tokens: weekBucket.totalTokens, tokens: weekBucket.totalTokens,
costUsd: weekBucket.costUsd, costUsd: weekBucket.costUsd,
@@ -918,7 +1115,9 @@ async function buildTelemetryPayloadInternal(
remainingIntPct: weeklyRemainingIntPct, remainingIntPct: weeklyRemainingIntPct,
resetTime: useOfficialWeekly resetTime: useOfficialWeekly
? activeLiveWeekly.resetTime ? activeLiveWeekly.resetTime
: getNextMondayResetIso(), : isCustomWeeklyMode
? getNextMondayResetIso()
: null,
}, },
today: { today: {
calls: todayBucket.calls, calls: todayBucket.calls,
@@ -961,6 +1160,22 @@ function buildTelemetryPayload(requestedConvId, forceQuotaRefresh = false, filte
const app = new SidecarApp(); const app = new SidecarApp();
const readLocal = (name) => readFileSync(join(HERE, name), 'utf8'); const readLocal = (name) => readFileSync(join(HERE, name), 'utf8');
function isLocalHostRequest(req) {
if (!req?.headers) return true;
const host = String(req.headers.host || '').toLowerCase();
if (host && !/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host)) {
return false;
}
const origin = String(req.headers.origin || '').toLowerCase();
if (
origin &&
!/^(https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?|vscode-webview:\/\/)/.test(origin)
) {
return false;
}
return true;
}
app.page('/', () => readLocal('index.html')); app.page('/', () => readLocal('index.html'));
app.page('/app.js', () => readLocal('app.js')); app.page('/app.js', () => readLocal('app.js'));
app.api( app.api(
@@ -971,7 +1186,13 @@ app.api(
app.api( app.api(
'/api/telemetry', '/api/telemetry',
async (data) => { async (data, req) => {
if (!isLocalHostRequest(req)) {
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
status: 403,
contentType: 'application/json',
});
}
const convId = data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''; const convId = data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '';
const force = data?.force === '1' || data?.force === true; const force = data?.force === '1' || data?.force === true;
const filterOpts = { const filterOpts = {
@@ -979,12 +1200,23 @@ app.api(
startMs: data?.startMs ? Number(data.startMs) : 0, startMs: data?.startMs ? Number(data.startMs) : 0,
endMs: data?.endMs ? Number(data.endMs) : 0, endMs: data?.endMs ? Number(data.endMs) : 0,
}; };
return buildTelemetryPayload(convId, force, filterOpts); const payload = await buildTelemetryPayload(convId, force, filterOpts);
return new Response(JSON.stringify(payload), {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
});
}, },
'GET' 'GET'
); );
app.api('/api/settings', (data) => { app.api('/api/settings', (data, req) => {
if (!isLocalHostRequest(req)) {
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
status: 403,
contentType: 'application/json',
});
}
const current = loadSettings(); const current = loadSettings();
const updated = { const updated = {
...current, ...current,