mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(release): v1.4.0 cloud pricing sync, one-click plugin update, and UI copy refresh
This commit is contained in:
@@ -9,19 +9,20 @@ Antigravity 侧边栏插件,用于查看当前会话的生成速度、上下
|
||||
面板分为四个标签页,顶部可切换要查看的会话或手动刷新配额:
|
||||
|
||||
- **实时监控**
|
||||
- 核心指标:实时吞吐、首 Token 耗时、当前会话均速、单步与会话累计折算费用。
|
||||
- 上下文窗口构成:展示当前上下文占用,并拆分为消息、系统工具、MCP 工具、Skill、系统提示词、`user_rule` 六类来源。
|
||||
- 官方配额:按账号实际额度池展示限额与重置倒计时,支持 `Gemini`、`Claude & GPT`,以及 Pro 账号独立的 `Gemini 4 Argon` 每周额度池;Ultra 账号共享 Gemini 配额时仍合并展示。仅有每周限额的模型池不显示 5 小时限额。
|
||||
- **消耗统计**
|
||||
- 核心指标:输出速度、首字延迟、平均速度、本次费用与会话累计费用。
|
||||
- 上下文占用:展示当前上下文占用,并拆分为消息、系统工具、MCP 工具、Skill、系统提示词、`user_rule` 六类来源。
|
||||
- 额度概览:同步展示 `Gemini`、`Gemini 4 Argon`(Pro 账号独立池)与 `Claude & GPT` 模型池的 5 小时限额、每周限额及重置倒计时。
|
||||
- **用量统计**
|
||||
- 支持按今天、1天、7天、14天、30天、全部或自定义时间段过滤。
|
||||
- 汇总所选时段的总 Token、API 折算费用、缓存命中率与缓存节省金额。
|
||||
- 包含时段趋势曲线、各模型用量占比、客户端来源分布以及月度用量柱状图。
|
||||
- **步骤明细**
|
||||
- 单步测速:列出当前会话全部步骤的模型、吞吐速度、首 Token 耗时、上下文/输出 Token、缓存命中率与单步费用。
|
||||
- 按模型汇总:按当前所选时间范围统计各模型的调用次数、均速、总 Token 与折算费用。
|
||||
- **系统设置**
|
||||
- 选择每周限额进度条的计算基准:使用官方云端周限额,或按自定义每周 Token / 美元预算计算百分比。
|
||||
- 选择显示模型简称或上游 `responseModel` 名称。
|
||||
- 汇总所选时段的总 Token、折算费用、缓存命中率与缓存节省金额。
|
||||
- 包含用量趋势曲线、模型排行、客户端来源以及月度统计柱状图。
|
||||
- **调用明细**
|
||||
- 按步查看:列出当前会话全部步骤的模型、输出速度、首字延迟、上下文/输出 Token、缓存命中率与单步费用。
|
||||
- 按模型汇总:按当前所选时间范围统计各模型的调用次数、均速、总 Token 与费用。
|
||||
- **偏好设置**
|
||||
- 选择周额度基准:跟随官方额度,或按自定义每周 Token / 费用上限计算百分比。
|
||||
- 选择模型名称格式:精简代号或原始模型 ID。
|
||||
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并支持在面板内一键检查更新或开启后台自动安装新版本。
|
||||
|
||||
## 模型识别与费用口径
|
||||
|
||||
@@ -67,11 +68,15 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
||||
## 启用与打开面板
|
||||
|
||||
1. 打开左侧边栏的 **Customizations**,进入 **Installed** 标签页,找到 `usage-monitor` 并开启。
|
||||
2. 点击对话窗口右上角 `⋮` -> **Extensions** -> **测速与额度监控**,在右侧辅助栏展开面板;或在对话中输入「打开测速与额度监控面板」通过快捷入口唤起。
|
||||
2. 点击对话窗口右上角 `⋮` -> **Extensions** -> **用量监控**,在右侧辅助栏展开面板;或在对话中输入「打开用量监控面板」通过快捷入口唤起。
|
||||
|
||||
## 更新
|
||||
|
||||
通过 Git 安装时,拉取最新代码后在 **Customizations -> Installed** 中重新开关一次插件即可:
|
||||
插件内置了云端版本检测与一键更新支持:
|
||||
- 当检测到新版本时,面板顶部栏会显示 **「升级 vX.Y.Z」** 徽章,点击即可自动拉取更新并重启面板;也可在 **偏好设置 -> 版本更新** 中手动更新价格表、检查更新或开启「后台自动安装新版本」。
|
||||
|
||||
如需通过命令行手动更新:
|
||||
- 通过 Git 安装时,拉取最新代码后在 **Customizations -> Installed** 中重新开关一次插件即可:
|
||||
|
||||
```powershell
|
||||
# Windows PowerShell
|
||||
@@ -93,7 +98,7 @@ git -C ~/.gemini/config/plugins/usage-monitor pull --ff-only
|
||||
npm run build
|
||||
```
|
||||
|
||||
运行配额池、模型识别、缓存迁移与计时回归测试(无需额外安装依赖):
|
||||
运行模型识别、缓存迁移与计时回归测试(无需额外安装依赖):
|
||||
|
||||
```bash
|
||||
npm test
|
||||
|
||||
+5
-5
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "usage-monitor",
|
||||
"displayName": "Usage & Speed Monitor",
|
||||
"version": "1.3.1",
|
||||
"description": "实时监控请求整体 TPS、原生首 Token 延迟(TTFT)、缓存命中率、上下文窗口占用、5h 限额以及今日/每周累计消耗。",
|
||||
"version": "1.4.0",
|
||||
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
||||
"logo": "assets/logo.svg",
|
||||
"suggestedPrompts": [
|
||||
"打开测速与额度监控面板查看当前会话性能",
|
||||
"分析当前会话的 Token 消耗与缓存命中率",
|
||||
"查看今日和本周各模型的累计 Token 与费用明细"
|
||||
"打开用量监控面板",
|
||||
"查看当前会话的 Token 消耗",
|
||||
"查看今日和本周的模型用量明细"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"catalogVersion": "2026.11.03.1",
|
||||
"updatedAt": "2026-11-03T13:00:00+09:00",
|
||||
"latestPluginVersion": "1.4.0",
|
||||
"releaseUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest",
|
||||
"downloadUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
|
||||
"archiveFallbackUrl": "https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main",
|
||||
"pricing": {
|
||||
"gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "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": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini" },
|
||||
"gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
||||
"gemini-3.8-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8-high", "family": "Gemini" },
|
||||
"gemini-3.8-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" },
|
||||
"gemini-3.8-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.8-low", "family": "Gemini" },
|
||||
"gemini-3.8-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" },
|
||||
"gemini-3.7-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" },
|
||||
"gemini-3.6-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini" },
|
||||
"gemini-3.5-flash": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5", "family": "Gemini" },
|
||||
"gemini-3.5-flash-lite": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.5-lite", "family": "Gemini" },
|
||||
"gemini-3.1-pro": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1", "family": "Gemini" },
|
||||
"gemini-3.1-flash-lite": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" },
|
||||
"gemini-3-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" },
|
||||
"gemini-2.5-pro": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "pro-2.5", "family": "Gemini" },
|
||||
"gemini-2.5-flash": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-2.5", "family": "Gemini" },
|
||||
"gemini-2.5-flash-lite": { "input": 0.10, "cache": 0.01, "output": 0.40, "short": "flash-2.5-lite", "family": "Gemini" },
|
||||
"claude-fable-5-1": { "input": 10.0, "cache": 0.25, "output": 50.0, "short": "fable-5.1", "family": "Claude" },
|
||||
"claude-fable-5": { "input": 10.0, "cache": 1.00, "output": 50.0, "short": "fable-5", "family": "Claude" },
|
||||
"claude-opus-5-5": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "opus-5.5", "family": "Claude" },
|
||||
"claude-opus-5": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-5", "family": "Claude" },
|
||||
"claude-opus-4-8": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.8", "family": "Claude" },
|
||||
"claude-opus-4-7": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.7", "family": "Claude" },
|
||||
"claude-opus-4-6-thinking": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus", "family": "Claude" },
|
||||
"claude-opus-4-6": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.6", "family": "Claude" },
|
||||
"claude-opus-4-5": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.5", "family": "Claude" },
|
||||
"claude-sonnet-5-5": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "sonnet-5.5", "family": "Claude" },
|
||||
"claude-sonnet-5": { "input": 2.00, "cache": 0.20, "output": 10.0, "short": "sonnet-5", "family": "Claude" },
|
||||
"claude-sonnet-4-6": { "input": 3.00, "cache": 0.30, "output": 15.0, "short": "sonnet", "family": "Claude" },
|
||||
"claude-sonnet-4-5": { "input": 3.00, "cache": 0.30, "output": 15.0, "short": "sonnet-4.5", "family": "Claude" },
|
||||
"claude-haiku-5-5": { "input": 0.10, "cache": 0.01, "output": 0.50, "short": "haiku-5.5", "family": "Claude" },
|
||||
"claude-haiku-4-5": { "input": 1.00, "cache": 0.10, "output": 5.00, "short": "haiku-4.5", "family": "Claude" },
|
||||
"gpt-6-astra": { "input": 10.0, "cache": 1.00, "output": 50.0, "short": "gpt-6-astra", "family": "GPT" },
|
||||
"gpt-6.1-sol": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "gpt-6.1-sol", "family": "GPT" },
|
||||
"gpt-6-sol": { "input": 2.00, "cache": 0.20, "output": 10.0, "short": "gpt-6-sol", "family": "GPT" },
|
||||
"gpt-6-luna": { "input": 0.10, "cache": 0.01, "output": 0.50, "short": "gpt-6-luna", "family": "GPT" },
|
||||
"gpt-5.6": { "input": 4.00, "cache": 0.40, "output": 20.0, "short": "gpt-5.6", "family": "GPT" },
|
||||
"gpt-5.6-sol": { "input": 4.00, "cache": 0.40, "output": 20.0, "short": "gpt-5.6-sol", "family": "GPT" },
|
||||
"gpt-5.6-terra": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "gpt-5.6-terra", "family": "GPT" },
|
||||
"gpt-5.6-luna": { "input": 0.20, "cache": 0.02, "output": 1.20, "short": "gpt-5.6-luna", "family": "GPT" },
|
||||
"gpt-5.5": { "input": 5.00, "cache": 0.50, "output": 30.0, "short": "gpt-5.5", "family": "GPT" },
|
||||
"gpt-5.4": { "input": 2.50, "cache": 0.25, "output": 15.0, "short": "gpt-5.4", "family": "GPT" },
|
||||
"gpt-5.4-mini": { "input": 0.75, "cache": 0.075, "output": 4.50, "short": "gpt-5.4-mini", "family": "GPT" },
|
||||
"gpt-5.4-nano": { "input": 0.20, "cache": 0.02, "output": 1.25, "short": "gpt-5.4-nano", "family": "GPT" },
|
||||
"gpt-5.3-codex": { "input": 1.75, "cache": 0.175, "output": 14.0, "short": "gpt-5.3-codex", "family": "GPT" },
|
||||
"gpt-5.2": { "input": 1.75, "cache": 0.175, "output": 14.0, "short": "gpt-5.2", "family": "GPT" },
|
||||
"gpt-5.1": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "gpt-5.1", "family": "GPT" },
|
||||
"gpt-5": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "gpt-5", "family": "GPT" },
|
||||
"gpt-5-mini": { "input": 0.25, "cache": 0.025, "output": 2.00, "short": "gpt-5-mini", "family": "GPT" },
|
||||
"gpt-5-nano": { "input": 0.05, "cache": 0.005, "output": 0.40, "short": "gpt-5-nano", "family": "GPT" },
|
||||
"gpt-4.1": { "input": 2.00, "cache": 0.50, "output": 8.00, "short": "gpt-4.1", "family": "GPT" },
|
||||
"gpt-4.1-mini": { "input": 0.40, "cache": 0.10, "output": 1.60, "short": "gpt-4.1-mini", "family": "GPT" },
|
||||
"gpt-4o": { "input": 2.50, "cache": 1.25, "output": 10.0, "short": "gpt-4o", "family": "GPT" },
|
||||
"gpt-4o-mini": { "input": 0.15, "cache": 0.075, "output": 0.60, "short": "gpt-4o-mini", "family": "GPT" },
|
||||
"o4-mini": { "input": 1.10, "cache": 0.275, "output": 4.40, "short": "o4-mini", "family": "GPT" },
|
||||
"o3": { "input": 2.00, "cache": 0.50, "output": 8.00, "short": "o3", "family": "GPT" },
|
||||
"o3-mini": { "input": 1.10, "cache": 0.55, "output": 4.40, "short": "o3-mini", "family": "GPT" },
|
||||
"gpt-oss-120b-medium": { "input": 0.80, "cache": 0.10, "output": 2.40, "short": "gpt-oss", "family": "GPT" }
|
||||
},
|
||||
"placeholders": {
|
||||
"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_M322": { "modelId": "gemini-3.8-flash", "label": "Gemini 3.8 Flash (Tiered)" },
|
||||
"MODEL_PLACEHOLDER_M198": { "modelId": "gemini-3.5-flash-lite", "label": "Gemini 3.5 Flash Lite" },
|
||||
"MODEL_PLACEHOLDER_M50": { "modelId": "gemini-3.1-flash-lite", "label": "Gemini 3.1 Flash Lite" },
|
||||
"MODEL_PLACEHOLDER_M18": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" },
|
||||
"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_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)" }
|
||||
}
|
||||
}
|
||||
+679
-261
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* @fileoverview 后端全局路径常量、默认配置、JSON 持久化工具与运行时共享状态容器。
|
||||
*
|
||||
* 负责统一管理:
|
||||
* 1. 插件根目录 (`PLUGIN_ROOT`)、面板目录 (`HERE`) 与持久化数据目录 (`DATA_DIR`) 的路径解析;
|
||||
* 2. Language Server RPC 连接参数 (`LS_ADDR` / `CSRF_TOKEN`) 与 GitHub 云端价格表地址;
|
||||
* 3. 安全的 JSON 读写封装 (`loadJson` / `saveJson`) 与用户设置合并 (`loadSettings`);
|
||||
* 4. 跨子系统共享的内存态缓存容器(采用对象属性就地更新设计,兼容 ES Module 与 VM 沙箱)。
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
|
||||
|
||||
/**
|
||||
* 自适应解析 `sidecars/panel` 目录路径:
|
||||
* - 在真实 Node ESM 运行时中,本文件位于 `sidecars/panel/backend/config.mjs`,向上取一级即为 `sidecars/panel`;
|
||||
* - 在 `backend-harness.mjs` 单元测试沙箱中,`fileURLToPath` 返回 `.../sidecars/panel/main.mjs`,当前目录即为 `sidecars/panel`。
|
||||
*/
|
||||
const rawModuleDir = dirname(fileURLToPath(import.meta.url));
|
||||
export const HERE = /[\\/]backend$/i.test(rawModuleDir) ? dirname(rawModuleDir) : rawModuleDir;
|
||||
export const PLUGIN_ROOT = dirname(dirname(HERE));
|
||||
export const PLUGIN_MANIFEST_FILE = join(PLUGIN_ROOT, 'plugin.json');
|
||||
export const LOCAL_CATALOG_FILE = join(PLUGIN_ROOT, 'pricing-catalog.json');
|
||||
|
||||
/**
|
||||
* 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor`)。
|
||||
* 存放用户偏好设置、历史轨迹缓存及云端价格表缓存,插件升级不会清除此目录。
|
||||
*/
|
||||
export const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data');
|
||||
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
|
||||
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
|
||||
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
|
||||
|
||||
/**
|
||||
* 本地对话记录目录与跨端深层统计缓存路径候选列表。
|
||||
*/
|
||||
export const CONVERSATIONS_DIR = join(homedir(), '.gemini', 'antigravity', 'conversations');
|
||||
export const DEEP_STATS_CACHE_CANDIDATES = [
|
||||
join(homedir(), '.gemini', 'antigravity-ide', 'brain', '.deep_stats_cache.json'),
|
||||
join(homedir(), '.gemini', 'antigravity', 'brain', '.deep_stats_cache.json'),
|
||||
join(homedir(), '.gemini', 'antigravity-idea', 'brain', '.deep_stats_cache.json'),
|
||||
];
|
||||
|
||||
/**
|
||||
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token。
|
||||
*/
|
||||
export const LS_ADDR = process.env.ANTIGRAVITY_LS_ADDRESS;
|
||||
export const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN;
|
||||
|
||||
/**
|
||||
* GitHub 官方云端价格目录与插件发布包地址配置。
|
||||
*/
|
||||
export const CLOUD_CATALOG_URLS = [
|
||||
'https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json',
|
||||
];
|
||||
export const DEFAULT_RELEASE_URL =
|
||||
'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest';
|
||||
export const DEFAULT_DOWNLOAD_URL =
|
||||
'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip';
|
||||
export const DEFAULT_ARCHIVE_FALLBACK_URL =
|
||||
'https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main';
|
||||
|
||||
/** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */
|
||||
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
||||
export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 用户可配置项的默认值。
|
||||
*/
|
||||
export const DEFAULT_SETTINGS = {
|
||||
contextWindowLimit: 256000, // 默认 256k 自动压缩上下文预算基准
|
||||
weeklyTokenBudget: 150000000, // 自定义每周 Token 预算默认值 (150M)
|
||||
weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100)
|
||||
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
||||
showUpstreamModel: false, // 步骤明细表是否显示上游真实 responseModel 名称
|
||||
autoUpdatePlugin: false, // 发现新版本且本地工作区干净时是否在后台自动更新插件
|
||||
};
|
||||
|
||||
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
||||
export const CACHE_SCHEMA_VERSION = 'v10-model-identity';
|
||||
|
||||
/**
|
||||
* 安全读取并解析本地 JSON 文件;文件不存在或解析失败时返回 `fallback`。
|
||||
*
|
||||
* @param {string} filePath 目标文件绝对路径
|
||||
* @param {*} fallback 失败时的回退值
|
||||
* @returns {*}
|
||||
*/
|
||||
export function loadJson(filePath, fallback) {
|
||||
if (!existsSync(filePath)) return fallback;
|
||||
try {
|
||||
return JSON.parse(readFileSync(filePath, 'utf8'));
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据序列化为格式化 JSON 并写入 `DATA_DIR` 下的指定文件。
|
||||
*
|
||||
* @param {string} filePath 目标文件绝对路径
|
||||
* @param {*} data 待写入的数据对象
|
||||
* @returns {boolean} 是否写入成功
|
||||
*/
|
||||
export function saveJson(filePath, data) {
|
||||
try {
|
||||
mkdirSync(DATA_DIR, { recursive: true });
|
||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed writing ${filePath}: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段 `speedMode`。
|
||||
*
|
||||
* @returns {typeof DEFAULT_SETTINGS}
|
||||
*/
|
||||
export function loadSettings() {
|
||||
const { speedMode: _legacySpeedMode, ...settings } = loadJson(SETTINGS_FILE, {});
|
||||
const merged = { ...DEFAULT_SETTINGS, ...settings };
|
||||
return {
|
||||
...merged,
|
||||
showUpstreamModel: merged.showUpstreamModel === true,
|
||||
autoUpdatePlugin: merged.autoUpdatePlugin === true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将浮点指标保留 1 位小数;非有限数值返回 `null`。
|
||||
*
|
||||
* @param {number} value
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function roundMetric(value) {
|
||||
return Number.isFinite(value) ? +value.toFixed(1) : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 跨模块共享运行时状态容器(启动时自动完成历史轨迹缓存迁移)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const loadedTrajectoryCache = loadJson(CACHE_FILE, {});
|
||||
|
||||
/**
|
||||
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
|
||||
*/
|
||||
export const trajectoryCache = Object.fromEntries(
|
||||
Object.entries(loadedTrajectoryCache).map(([id, entry]) => [
|
||||
id,
|
||||
{
|
||||
...entry,
|
||||
steps: inferCompactionStepModels((entry.steps || []).map(normalizeCachedStep)),
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
/**
|
||||
* 缓存状态与外部深层统计缓存 Memo。
|
||||
*/
|
||||
export const cacheState = {
|
||||
needsSave: JSON.stringify(trajectoryCache) !== JSON.stringify(loadedTrajectoryCache),
|
||||
};
|
||||
|
||||
export const externalDeepStatsMemo = {
|
||||
sig: '',
|
||||
convos: new Map(),
|
||||
};
|
||||
|
||||
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
||||
export const inFlightRequests = new Map();
|
||||
|
||||
/** 官方配额摘要 10 秒短期缓存。 */
|
||||
export const quotaSummaryCache = {
|
||||
ts: 0,
|
||||
accountName: '',
|
||||
data: null,
|
||||
error: null,
|
||||
};
|
||||
|
||||
/** 云端价格与版本目录同步状态。 */
|
||||
export const cloudSyncState = {
|
||||
catalogVersion: 'builtin',
|
||||
updatedAt: null,
|
||||
fetchedAtMs: 0,
|
||||
lastAttemptMs: 0,
|
||||
source: 'builtin', // 'builtin' | 'local' | 'remote'
|
||||
sourceUrl: '',
|
||||
latestPluginVersion: null,
|
||||
releaseUrl: DEFAULT_RELEASE_URL,
|
||||
downloadUrl: DEFAULT_DOWNLOAD_URL,
|
||||
archiveFallbackUrl: DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||
isSyncing: false,
|
||||
lastError: null,
|
||||
inFlight: null,
|
||||
};
|
||||
|
||||
/** 插件自更新执行状态。 */
|
||||
export const pluginUpdateState = {
|
||||
isUpdating: false,
|
||||
lastAutoAttemptVersion: '',
|
||||
lastResult: null,
|
||||
lastError: null,
|
||||
inFlight: null,
|
||||
};
|
||||
@@ -0,0 +1,350 @@
|
||||
/**
|
||||
* @fileoverview 本地磁盘会话文件发现、外部 IDE/CLI 深层统计缓存加载与历史轨迹增量同步。
|
||||
*
|
||||
* 负责:
|
||||
* 1. 扫描 `~/.gemini/antigravity/conversations` 下的本地 `.db` / `.pb` / `.db-wal` 会话文件及修改时间;
|
||||
* 2. 读取跨端共享的 `.deep_stats_cache.json`(兼容 IDE / CLI / Standalone 多端步骤数据合并);
|
||||
* 3. 将 Language Server 摘要、本地磁盘文件与内存缓存三方会话列表对齐,并以受控并发(最多 4 路)
|
||||
* 拉取新增或 Schema 过期的会话轨迹步骤,持久化至 `trajectory_usage_cache.json`。
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { extractModelSteps, parseIsoMs } from '../speed-metrics.mjs';
|
||||
import {
|
||||
CACHE_FILE,
|
||||
CACHE_SCHEMA_VERSION,
|
||||
CONVERSATIONS_DIR,
|
||||
DEEP_STATS_CACHE_CANDIDATES,
|
||||
cacheState,
|
||||
externalDeepStatsMemo,
|
||||
loadJson,
|
||||
saveJson,
|
||||
trajectoryCache,
|
||||
} from './config.mjs';
|
||||
import { callLsRpc } from './ls-rpc.mjs';
|
||||
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
||||
|
||||
/**
|
||||
* 扫描本地 `conversations` 目录,返回 `cascadeId -> 最新磁盘修改时间 (mtimeMs)` 映射表。
|
||||
*
|
||||
* @returns {Map<string, number>}
|
||||
*/
|
||||
export function discoverLocalConversationFiles() {
|
||||
const map = new Map();
|
||||
if (!existsSync(CONVERSATIONS_DIR)) return map;
|
||||
try {
|
||||
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|db-wal)$/i
|
||||
);
|
||||
if (!m) continue;
|
||||
const cascadeId = m[1].toLowerCase();
|
||||
try {
|
||||
const st = statSync(join(CONVERSATIONS_DIR, name));
|
||||
const prevMtime = map.get(cascadeId) || 0;
|
||||
if (st.mtimeMs > prevMtime) {
|
||||
map.set(cascadeId, st.mtimeMs);
|
||||
}
|
||||
} catch {
|
||||
if (!map.has(cascadeId)) map.set(cascadeId, 0);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略目录读取异常
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载并解析跨端(IDE / Standalone / JetBrains)写入的 `.deep_stats_cache.json` 缓存。
|
||||
* 使用文件签名 (`mtimeMs + size`) 进行 Memoize,文件未变化时直接返回内存 Map。
|
||||
*
|
||||
* @returns {Map<string, {cascadeId: string, appSource: string, title: string, lastModifiedMs: number, steps: object[]}>}
|
||||
*/
|
||||
export function loadExternalDeepStatsCache() {
|
||||
const sigParts = [];
|
||||
const existingFiles = [];
|
||||
for (const candidate of DEEP_STATS_CACHE_CANDIDATES) {
|
||||
if (!existsSync(candidate)) continue;
|
||||
try {
|
||||
const st = statSync(candidate);
|
||||
sigParts.push(`${candidate}:${st.mtimeMs || 0}:${st.size || 0}`);
|
||||
existingFiles.push(candidate);
|
||||
} catch {
|
||||
// 忽略 stat 异常
|
||||
}
|
||||
}
|
||||
if (existingFiles.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
const sig = sigParts.join('|');
|
||||
if (externalDeepStatsMemo.sig === sig && externalDeepStatsMemo.convos.size > 0) {
|
||||
return externalDeepStatsMemo.convos;
|
||||
}
|
||||
|
||||
const convos = new Map();
|
||||
const runtimeDisplayMap = new Map();
|
||||
|
||||
for (const filePath of existingFiles) {
|
||||
const raw = loadJson(filePath, null);
|
||||
if (!raw || typeof raw.perConvo !== 'object' || !raw.perConvo) continue;
|
||||
|
||||
for (const item of Object.values(raw.perConvo)) {
|
||||
for (const e of item?.entries || []) {
|
||||
const display =
|
||||
e?.modelDisplayName ||
|
||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId);
|
||||
if (!display) continue;
|
||||
const base = getBaseModelLabel(display);
|
||||
if (e?.modelRuntimeId && !runtimeDisplayMap.has(e.modelRuntimeId)) {
|
||||
runtimeDisplayMap.set(e.modelRuntimeId, base);
|
||||
}
|
||||
if (e?.model && !runtimeDisplayMap.has(e.model)) {
|
||||
runtimeDisplayMap.set(e.model, base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const titleMap = raw.titleMap || {};
|
||||
for (const [fullKey, item] of Object.entries(raw.perConvo)) {
|
||||
const rawEntries = item?.entries;
|
||||
if (!Array.isArray(rawEntries) || rawEntries.length === 0) continue;
|
||||
const colonIdx = fullKey.indexOf(':');
|
||||
const appSource = item?.appSource || (colonIdx > 0 ? fullKey.slice(0, colonIdx) : 'ide');
|
||||
const cascadeId = (colonIdx > 0 ? fullKey.slice(colonIdx + 1) : fullKey).toLowerCase();
|
||||
const mapKey = `${appSource}:${cascadeId}`;
|
||||
const existing = convos.get(mapKey);
|
||||
if (existing && existing.steps.length >= rawEntries.length) continue;
|
||||
|
||||
const steps = [];
|
||||
let lastModifiedMs = 0;
|
||||
for (let idx = 0; idx < rawEntries.length; idx++) {
|
||||
const e = rawEntries[idx];
|
||||
const inputTokens = Math.max(0, Number(e?.inp) || 0);
|
||||
const cacheReadTokens = Math.max(0, Number(e?.cache) || 0);
|
||||
const responseTokens = Math.max(0, Number(e?.out) || 0);
|
||||
const thinkingTokens = Math.max(0, Number(e?.reasoning) || 0);
|
||||
const outputTokens = responseTokens + thinkingTokens;
|
||||
if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0) continue;
|
||||
const createdAtMs = e?.ts ? Date.parse(e.ts) || 0 : 0;
|
||||
if (createdAtMs > lastModifiedMs) lastModifiedMs = createdAtMs;
|
||||
const resolvedDisplay =
|
||||
e?.modelDisplayName ||
|
||||
runtimeDisplayMap.get(e?.model) ||
|
||||
runtimeDisplayMap.get(e?.modelRuntimeId) ||
|
||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId) ||
|
||||
'';
|
||||
steps.push({
|
||||
stepIndex: idx + 1,
|
||||
createdAt: e?.ts || '',
|
||||
createdAtMs,
|
||||
modelKey: e?.modelCanonicalId || e?.model || e?.modelRuntimeId || 'unknown',
|
||||
modelDisplayName: resolvedDisplay,
|
||||
apiProvider: e?.provider || '',
|
||||
appSource,
|
||||
inputTokens,
|
||||
cacheReadTokens,
|
||||
outputTokens,
|
||||
thinkingTokens,
|
||||
responseTokens,
|
||||
});
|
||||
}
|
||||
if (steps.length > 0) {
|
||||
convos.set(mapKey, {
|
||||
cascadeId,
|
||||
appSource,
|
||||
title: titleMap[fullKey] || titleMap[cascadeId] || cascadeId.slice(0, 8),
|
||||
lastModifiedMs,
|
||||
steps,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
externalDeepStatsMemo.sig = sig;
|
||||
externalDeepStatsMemo.convos = convos;
|
||||
return convos;
|
||||
}
|
||||
|
||||
/**
|
||||
* 枚举所有会话(合并 LS `trajectorySummaries`、本地磁盘文件与 `trajectoryCache`),
|
||||
* 选定当前活跃会话,并以最多 4 路并发增量同步更新了的会话轨迹。
|
||||
*
|
||||
* @param {{
|
||||
* summariesObj: Record<string, object>,
|
||||
* currentAccountName: string,
|
||||
* requestedConvId: string
|
||||
* }} params
|
||||
* @returns {Promise<{
|
||||
* conversations: object[],
|
||||
* activeConvSummary: object|null,
|
||||
* activeCascadeId: string|null
|
||||
* }>}
|
||||
*/
|
||||
export async function enumerateAndSyncConversations({
|
||||
summariesObj = {},
|
||||
currentAccountName = '',
|
||||
requestedConvId = '',
|
||||
}) {
|
||||
const diskConvMap = discoverLocalConversationFiles();
|
||||
const allCascadeIds = new Set([
|
||||
...Object.keys(summariesObj),
|
||||
...diskConvMap.keys(),
|
||||
...Object.keys(trajectoryCache),
|
||||
]);
|
||||
|
||||
const conversations = [];
|
||||
for (const cascadeId of allCascadeIds) {
|
||||
const item = summariesObj[cascadeId];
|
||||
const cached = trajectoryCache[cascadeId];
|
||||
if (
|
||||
cached?.accountName &&
|
||||
currentAccountName &&
|
||||
cached.accountName !== currentAccountName &&
|
||||
!item
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const diskMtimeMs = diskConvMap.get(cascadeId) || 0;
|
||||
|
||||
if (item) {
|
||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||
const lastModifiedMs =
|
||||
parseIsoMs(lastModifiedTime) || diskMtimeMs || cached?.lastModifiedMs || 0;
|
||||
conversations.push({
|
||||
cascadeId,
|
||||
title:
|
||||
item?.annotations?.title || item?.summary || cached?.title || cascadeId.slice(0, 8),
|
||||
stepCount: Number(item?.stepCount || cached?.steps?.length || 0),
|
||||
status: item?.status || '',
|
||||
lastModifiedTime,
|
||||
lastModifiedMs,
|
||||
diskMtimeMs,
|
||||
inSummaries: true,
|
||||
});
|
||||
} else if (cached) {
|
||||
const lastStepMs = cached.steps?.[cached.steps.length - 1]?.createdAtMs || 0;
|
||||
conversations.push({
|
||||
cascadeId,
|
||||
title: cached.title || cascadeId.slice(0, 8),
|
||||
stepCount: Number(cached.steps?.length || 0),
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: Math.max(cached.lastModifiedMs || 0, lastStepMs, diskMtimeMs),
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
});
|
||||
} else {
|
||||
conversations.push({
|
||||
cascadeId,
|
||||
title: cascadeId.slice(0, 8),
|
||||
stepCount: 0,
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: diskMtimeMs,
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
needsInitialLoad: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
conversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);
|
||||
|
||||
// 选定当前活跃会话:若指定了有效 requestedConvId 则优先使用,否则取最近修改的会话
|
||||
const activeConvSummary =
|
||||
conversations.find((c) => c.cascadeId === requestedConvId) || conversations[0] || null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null;
|
||||
|
||||
let cacheDirty = cacheState.needsSave;
|
||||
|
||||
const toFetch = conversations.filter((conv) => {
|
||||
const cached = trajectoryCache[conv.cascadeId];
|
||||
if (!cached || conv.needsInitialLoad) return true;
|
||||
const hasCurrentSchema = String(cached.signature || '').startsWith(
|
||||
`${CACHE_SCHEMA_VERSION}:`
|
||||
);
|
||||
if (!hasCurrentSchema) return true;
|
||||
const lastCachedStep = cached.steps?.[cached.steps.length - 1];
|
||||
const missingBreakdownField =
|
||||
Boolean(lastCachedStep) &&
|
||||
(!Object.prototype.hasOwnProperty.call(lastCachedStep, 'contextBreakdown') ||
|
||||
cached.steps.some((s) => !Object.prototype.hasOwnProperty.call(s, 'responseModel')));
|
||||
if (missingBreakdownField) 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 isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
return cached.signature !== sig || isRunning || Boolean(cached.wasRunning);
|
||||
});
|
||||
|
||||
// 限制并发度为 4,批量拉取需要更新的会话轨迹
|
||||
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 = conv.inSummaries
|
||||
? `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`
|
||||
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const prev = trajectoryCache[conv.cascadeId];
|
||||
try {
|
||||
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
||||
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
||||
throw new Error('Trajectory steps unavailable');
|
||||
}
|
||||
const rawSteps = trajRes.trajectory.steps;
|
||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) {
|
||||
throw new Error('Incomplete trajectory; retaining cached usage');
|
||||
}
|
||||
const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||
const nextLast = steps[steps.length - 1];
|
||||
const stepsChanged =
|
||||
!prev ||
|
||||
prev.signature !== sig ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs);
|
||||
conv.lastModifiedMs = resolvedLastModMs;
|
||||
if (!conv.inSummaries) {
|
||||
conv.stepCount = rawSteps.length || steps.length;
|
||||
}
|
||||
|
||||
trajectoryCache[conv.cascadeId] = {
|
||||
signature: sig,
|
||||
accountName: currentAccountName || prev?.accountName || '',
|
||||
title: conv.title,
|
||||
lastModifiedMs: resolvedLastModMs,
|
||||
diskMtimeMs: conv.diskMtimeMs || 0,
|
||||
wasRunning: isRunning,
|
||||
steps,
|
||||
};
|
||||
if (stepsChanged) {
|
||||
cacheDirty = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (cacheDirty) {
|
||||
cacheState.needsSave = !saveJson(CACHE_FILE, trajectoryCache);
|
||||
}
|
||||
|
||||
return {
|
||||
conversations,
|
||||
activeConvSummary,
|
||||
activeCascadeId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* @fileoverview Antigravity Language Server Connect RPC 客户端与官方配额摘要缓存。
|
||||
*
|
||||
* 负责:
|
||||
* 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
|
||||
* 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存,
|
||||
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存);
|
||||
* 3. 维护全局 `StreamDiagnostics` 实例以采样流式事件时序。
|
||||
*/
|
||||
|
||||
import { StreamDiagnostics } from '../stream-diagnostics.mjs';
|
||||
import { CSRF_TOKEN, DATA_DIR, LS_ADDR, quotaSummaryCache } from './config.mjs';
|
||||
|
||||
/**
|
||||
* 全局流式传输诊断采样器实例。
|
||||
*/
|
||||
export const diagnostics = new StreamDiagnostics({
|
||||
dataDir: DATA_DIR,
|
||||
lsAddress: LS_ADDR,
|
||||
csrfToken: CSRF_TOKEN,
|
||||
});
|
||||
|
||||
/**
|
||||
* 调用本地 `LanguageServerService` 的指定 RPC 方法。
|
||||
*
|
||||
* @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`)
|
||||
* @param {object} [body={}] 请求 JSON 载荷
|
||||
* @param {number} [timeoutMs=5000] 超时时间(毫秒)
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
||||
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),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
}
|
||||
);
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
throw new Error(`RPC ${method} failed (${res.status}): ${text}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取官方实时配额摘要(`RetrieveUserQuotaSummary`)。
|
||||
*
|
||||
* 缓存策略:
|
||||
* - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口;
|
||||
* - 当超过 10 秒或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时,
|
||||
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
|
||||
*
|
||||
* @param {boolean} [forceRefresh=false] 是否强制穿透本地 10 秒缓存
|
||||
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null}>}
|
||||
*/
|
||||
export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||
const now = Date.now();
|
||||
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < 10000) {
|
||||
return {
|
||||
data: quotaSummaryCache.data,
|
||||
fetchedAtMs: quotaSummaryCache.ts,
|
||||
isStale: false,
|
||||
refreshFailed: false,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
try {
|
||||
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
|
||||
const payload = res?.response || res;
|
||||
if (Array.isArray(payload?.groups) || Array.isArray(payload?.buckets)) {
|
||||
quotaSummaryCache.ts = now;
|
||||
quotaSummaryCache.data = payload;
|
||||
quotaSummaryCache.error = null;
|
||||
return {
|
||||
data: payload,
|
||||
fetchedAtMs: now,
|
||||
isStale: false,
|
||||
refreshFailed: false,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
|
||||
quotaSummaryCache.error = err.message;
|
||||
}
|
||||
return {
|
||||
data: quotaSummaryCache.data,
|
||||
fetchedAtMs: quotaSummaryCache.ts || 0,
|
||||
isStale: Boolean(quotaSummaryCache.data),
|
||||
refreshFailed: true,
|
||||
error: quotaSummaryCache.error || 'Quota RPC unavailable',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* @fileoverview 模型身份识别、展示名称规范化与单步 API 等效成本计算。
|
||||
*
|
||||
* 核心原则:
|
||||
* 1. 优先信任服务端下发的动态模型目录 (`dynamicModelMap`) 与真实响应模型 (`responseModel`),
|
||||
* 其次匹配本地/云端 `PLACEHOLDER_MAP` 与 `MODEL_PRICING`;
|
||||
* 2. 价格未知或模型身份无法确认时,严格返回 `pricing: null` 与 `costUsd: null`,
|
||||
* 绝不借用其他模型单价伪造费用。
|
||||
*/
|
||||
|
||||
import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||
|
||||
/**
|
||||
* 根据 API 提供商枚举或模型标识符推断所属模型家族(`'Gemini'` | `'Claude'` | `'GPT'` | `'Other'`)。
|
||||
*
|
||||
* @param {string} [rawModelKey=''] 原始模型键名或占位符
|
||||
* @param {string} [modelId=''] 规范化模型 ID
|
||||
* @param {string} [apiProvider=''] 上游 API 提供商枚举字符串
|
||||
* @returns {'Gemini'|'Claude'|'GPT'|'Other'}
|
||||
*/
|
||||
export 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';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 枚举)。
|
||||
*
|
||||
* @param {...string} parts 待检测的标识片段
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isArgonModelIdentifier(...parts) {
|
||||
return /argon|MODEL_PLACEHOLDER_M41[789]\b/i.test(parts.filter(Boolean).join(' '));
|
||||
}
|
||||
|
||||
/**
|
||||
* 剥离模型展示名称末尾的思考档位后缀(如 `(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。
|
||||
*
|
||||
* @param {string} [label='']
|
||||
* @returns {string}
|
||||
*/
|
||||
export function getBaseModelLabel(label = '') {
|
||||
return (
|
||||
String(label || '')
|
||||
.replace(/\s*\((?:High|Medium|Low|Thinking|Extra Low)\)\s*$/i, '')
|
||||
.trim() || String(label || 'Unknown Model')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将形如 `gemini-3.1-pro` 或 `gemini-3.5-flash-lite` 的通用模型 Slug 转为人类可读标签。
|
||||
*
|
||||
* @param {string} [slug='']
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatGenericModelSlug(slug = '') {
|
||||
const s = String(slug || '')
|
||||
.trim()
|
||||
.replace(/^session-display:/i, '');
|
||||
if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return '';
|
||||
const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon)(?:-(lite))?/i);
|
||||
if (m) {
|
||||
const ver = m[1];
|
||||
const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase();
|
||||
const lite = m[3] ? ' Lite' : '';
|
||||
return `Gemini ${ver} ${tier}${lite}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与单价配置。
|
||||
*
|
||||
* @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M318`)
|
||||
* @param {Map<string, {modelId: string, label: string, quotaInfo?: object}>} dynamicModelMap 从 `GetUserStatus` 提取的动态模型表
|
||||
* @param {string} [apiProvider=''] API 提供商枚举
|
||||
* @param {string} [modelDisplayName=''] 已知的模型展示名称
|
||||
* @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`)
|
||||
* @returns {{
|
||||
* rawModel: string,
|
||||
* modelId: string,
|
||||
* label: string,
|
||||
* baseLabel: string,
|
||||
* shortName: string,
|
||||
* family: string,
|
||||
* pricing: {input: number, cache: number, output: number, short: string, family: string} | null,
|
||||
* isEstimatedPrice: boolean
|
||||
* }}
|
||||
*/
|
||||
export function resolveModelInfo(
|
||||
rawModelKey,
|
||||
dynamicModelMap,
|
||||
apiProvider = '',
|
||||
modelDisplayName = '',
|
||||
responseModel = ''
|
||||
) {
|
||||
const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey];
|
||||
const cleanResponseModel =
|
||||
responseModel && responseModel !== 'unknown' ? String(responseModel).trim() : '';
|
||||
const cleanRawFallback =
|
||||
rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel;
|
||||
const derivedDisplay =
|
||||
modelDisplayName ||
|
||||
dyn?.label ||
|
||||
formatGenericModelSlug(rawModelKey) ||
|
||||
formatGenericModelSlug(cleanResponseModel) ||
|
||||
cleanRawFallback ||
|
||||
'模型未知';
|
||||
const baseLabel = getBaseModelLabel(derivedDisplay);
|
||||
const canonicalSlug = baseLabel.toLowerCase().replace(/\s+/g, '-');
|
||||
const dashedSlug = canonicalSlug.replace(/\./g, '-');
|
||||
const modelId =
|
||||
dyn?.modelId ||
|
||||
(rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel) ||
|
||||
'unknown';
|
||||
const explicitPricing =
|
||||
MODEL_PRICING[modelId] ||
|
||||
MODEL_PRICING[rawModelKey] ||
|
||||
(cleanResponseModel ? MODEL_PRICING[cleanResponseModel] : null) ||
|
||||
MODEL_PRICING[canonicalSlug] ||
|
||||
MODEL_PRICING[dashedSlug];
|
||||
if (explicitPricing) {
|
||||
return {
|
||||
rawModel: rawModelKey,
|
||||
modelId,
|
||||
label: derivedDisplay,
|
||||
baseLabel,
|
||||
shortName: explicitPricing.short,
|
||||
family: explicitPricing.family,
|
||||
pricing: explicitPricing,
|
||||
isEstimatedPrice: false,
|
||||
};
|
||||
}
|
||||
|
||||
const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, modelId, apiProvider);
|
||||
return {
|
||||
rawModel: rawModelKey,
|
||||
modelId,
|
||||
label: derivedDisplay,
|
||||
baseLabel: getBaseModelLabel(derivedDisplay),
|
||||
shortName: derivedDisplay,
|
||||
family: inferredFamily,
|
||||
pricing: null,
|
||||
isEstimatedPrice: true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算单个步骤的 API 等效美元成本;若模型未定价(`pricing === null`)则返回 `null`。
|
||||
*
|
||||
* @param {{ inputTokens: number, cacheReadTokens: number, outputTokens: number }} step
|
||||
* @param {{ input: number, cache: number, output: number } | null} pricing
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function computeStepCost(step, pricing) {
|
||||
if (!pricing) return null;
|
||||
const inCost = (step.inputTokens / 1_000_000) * pricing.input;
|
||||
const cacheCost = (step.cacheReadTokens / 1_000_000) * pricing.cache;
|
||||
const outCost = (step.outputTokens / 1_000_000) * pricing.output;
|
||||
return inCost + cacheCost + outCost;
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
/**
|
||||
* @fileoverview 云端价格表同步与插件双通道更新器(Git Fast-Forward / Release ZIP 覆盖)。
|
||||
*
|
||||
* 核心能力与多重防御不变量:
|
||||
* 1. `syncCloudCatalog`:定期或手动从 GitHub 主干拉取最新 `pricing-catalog.json`,
|
||||
* 经 Schema 与可信域名白名单清洗后落盘至 `DATA_DIR/remote_pricing_cache.json` 并热更新内存价格字典;
|
||||
* 2. `performPluginUpdate` 严格执行以下防降级与防损坏门禁:
|
||||
* - 开发仓库自动更新隔离:非 `.gemini/config/plugins/` 目录一律禁止后台自动更新(`dev_repo_auto_disabled`);
|
||||
* - 全量工作区干净度门禁(含未跟踪文件):执行 `git status --porcelain`(不带 `--untracked-files=no`),
|
||||
* 只要存在任何已修改或未跟踪文件(`??`),立即终止(`dirty_worktree`),绝不执行 `git stash`;
|
||||
* - 分支门禁:通过 `git rev-parse --abbrev-ref HEAD` 校验当前必须处于 `main` 分支(`not_on_main_branch`),防止污染特性分支或游离 HEAD;
|
||||
* - 强制远端版本门禁(Git 通道):必须且只能从 `git show origin/main:plugin.json` 解析出合法 SemVer,
|
||||
* 严禁回退使用缓存的 `cloudSyncState.latestPluginVersion`;仅当 `remoteVersion > previousVersion` 时才继续;
|
||||
* - 提交拓扑与核心文件门禁:通过 `git merge-base --is-ancestor HEAD origin/main` 确认本地无分叉提交(`diverged_worktree`);
|
||||
* - ZIP 通道安全覆盖:下载前与解压后双重校验 `compareSemver > 0`,覆盖前对 `main.mjs`/`app.js` 执行 `node --check` 语法预检,
|
||||
* 使用 `cpSync` 过滤器严格保护 `.git`/`.data`/`node_modules`,并在覆盖前备份关键文件以支持异常回滚。
|
||||
*/
|
||||
|
||||
import { execFile } from 'node:child_process';
|
||||
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import {
|
||||
CLOUD_CATALOG_URLS,
|
||||
CLOUD_SYNC_RETRY_COOLDOWN_MS,
|
||||
CLOUD_SYNC_TTL_MS,
|
||||
DATA_DIR,
|
||||
DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||
DEFAULT_DOWNLOAD_URL,
|
||||
LS_ADDR,
|
||||
PLUGIN_ROOT,
|
||||
REMOTE_CATALOG_CACHE_FILE,
|
||||
cloudSyncState,
|
||||
loadJson,
|
||||
loadSettings,
|
||||
pluginUpdateState,
|
||||
saveJson,
|
||||
} from './config.mjs';
|
||||
import {
|
||||
compareSemver,
|
||||
getCloudStatus,
|
||||
isValidSemver,
|
||||
readInstalledPluginVersion,
|
||||
rebuildActiveCatalog,
|
||||
sanitizeCatalogPayload,
|
||||
} from './pricing-catalog.mjs';
|
||||
|
||||
/**
|
||||
* 以 Promise 形式安全执行外部子进程命令(默认隐藏 Windows 控制台窗口并设置 25 秒超时)。
|
||||
*
|
||||
* @param {string} cmd 可执行文件名
|
||||
* @param {string[]} args 参数列表
|
||||
* @param {object} [opts] `execFile` 附加选项
|
||||
* @returns {Promise<{stdout: string, stderr: string}>}
|
||||
*/
|
||||
export function runExecFile(cmd, args, opts = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof execFile !== 'function') {
|
||||
reject(new Error('execFile unavailable in current environment'));
|
||||
return;
|
||||
}
|
||||
execFile(cmd, args, { windowsHide: true, timeout: 25000, ...opts }, (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
const detail = String(stderr || stdout || err.message || '').trim();
|
||||
reject(new Error(detail || err.message));
|
||||
return;
|
||||
}
|
||||
resolve({ stdout: String(stdout || ''), stderr: String(stderr || '') });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新完成后调度 Sidecar 进程平滑退出,让宿主进程监督器自动重启新代码。
|
||||
* 在单元测试环境(`LS_ADDR === 'test.invalid'`)下自动跳过。
|
||||
*
|
||||
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
||||
*/
|
||||
export function scheduleSidecarRestart(delayMs = 350) {
|
||||
if (LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.exit(0);
|
||||
} catch {
|
||||
// 忽略退出异常
|
||||
}
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在解压后的临时目录中定位包含 `plugin.json` 的插件根目录(兼容顶层平铺或单层子目录包装)。
|
||||
*
|
||||
* @param {string} extractDir 解压目标目录
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function locateExtractedPluginRoot(extractDir) {
|
||||
if (existsSync(join(extractDir, 'plugin.json'))) return extractDir;
|
||||
try {
|
||||
for (const name of readdirSync(extractDir)) {
|
||||
const sub = join(extractDir, name);
|
||||
if (existsSync(join(sub, 'plugin.json'))) {
|
||||
return sub;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略目录读取错误
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `cpSync` 安全过滤函数:严格禁止覆盖 `.git`、`.data`、`node_modules` 或临时更新目录。
|
||||
*
|
||||
* @param {string} srcPath
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isSafeCopyPath(srcPath) {
|
||||
const name = basename(String(srcPath || '')).toLowerCase();
|
||||
if (
|
||||
name === '.git' ||
|
||||
name === '.data' ||
|
||||
name === 'node_modules' ||
|
||||
name.startsWith('.update-staging-')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在真实运行环境下对目标目录的核心 JS 文件执行 `node --check` 语法预检。
|
||||
*
|
||||
* @param {string} rootDir 插件根目录或解压目录
|
||||
*/
|
||||
async function verifyPluginJsSyntax(rootDir) {
|
||||
if (LS_ADDR === 'test.invalid') return;
|
||||
const nodeBin = process?.execPath || 'node';
|
||||
const filesToCheck = [
|
||||
join(rootDir, 'sidecars', 'panel', 'main.mjs'),
|
||||
join(rootDir, 'sidecars', 'panel', 'app.js'),
|
||||
];
|
||||
for (const file of filesToCheck) {
|
||||
if (existsSync(file)) {
|
||||
await runExecFile(nodeBin, ['--check', file]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行插件本体更新(支持手动一键更新与后台静默更新)。
|
||||
*
|
||||
* @param {{ isAuto?: boolean }} [options]
|
||||
* @returns {Promise<object>} 更新结果对象
|
||||
*/
|
||||
export async function performPluginUpdate({ isAuto = false } = {}) {
|
||||
if (pluginUpdateState.inFlight) return pluginUpdateState.inFlight;
|
||||
pluginUpdateState.inFlight = (async () => {
|
||||
pluginUpdateState.isUpdating = true;
|
||||
pluginUpdateState.lastError = null;
|
||||
const previousVersion = readInstalledPluginVersion();
|
||||
const hasGit = existsSync(join(PLUGIN_ROOT, '.git'));
|
||||
const normalizedRoot = PLUGIN_ROOT.replace(/\\/g, '/').toLowerCase();
|
||||
const isInstalledPluginDir = normalizedRoot.includes('/.gemini/config/plugins/');
|
||||
|
||||
try {
|
||||
if (hasGit) {
|
||||
// 0. 开发仓库(非 ~/.gemini/config/plugins/)一律禁止后台自动更新
|
||||
if (isAuto && !isInstalledPluginDir) {
|
||||
const msg = '当前处于本地开发仓库,已自动禁用后台静默更新';
|
||||
const result = {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
mode: 'git',
|
||||
reason: 'dev_repo_auto_disabled',
|
||||
previousVersion,
|
||||
currentVersion: previousVersion,
|
||||
message: msg,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
pluginUpdateState.lastResult = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
// 1. 全量工作区检查(包含未跟踪文件 ??):只要存在任何未提交改动或新增未跟踪文件,立即中止
|
||||
const statusRes = await runExecFile('git', ['-C', PLUGIN_ROOT, 'status', '--porcelain']);
|
||||
const isDirty = statusRes.stdout.trim().length > 0;
|
||||
if (isDirty) {
|
||||
const msg = isInstalledPluginDir
|
||||
? '本地文件有改动,已跳过覆盖更新'
|
||||
: '开发目录有未提交修改,已跳过更新';
|
||||
pluginUpdateState.lastError = isAuto ? null : msg;
|
||||
pluginUpdateState.lastResult = {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
mode: 'git',
|
||||
reason: 'dirty_worktree',
|
||||
previousVersion,
|
||||
currentVersion: previousVersion,
|
||||
message: msg,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
return pluginUpdateState.lastResult;
|
||||
}
|
||||
|
||||
// 2. 分支检查:仅当处于 main 分支时才允许拉取 origin/main,防止污染特性分支或游离 HEAD
|
||||
const branchRes = await runExecFile('git', [
|
||||
'-C',
|
||||
PLUGIN_ROOT,
|
||||
'rev-parse',
|
||||
'--abbrev-ref',
|
||||
'HEAD',
|
||||
]);
|
||||
const currentBranch = branchRes.stdout.trim();
|
||||
if (currentBranch && currentBranch !== 'main') {
|
||||
const msg = `当前分支为 ${currentBranch},已跳过更新`;
|
||||
pluginUpdateState.lastError = isAuto ? null : msg;
|
||||
pluginUpdateState.lastResult = {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
mode: 'git',
|
||||
reason: 'not_on_main_branch',
|
||||
branch: currentBranch,
|
||||
previousVersion,
|
||||
currentVersion: previousVersion,
|
||||
message: msg,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
return pluginUpdateState.lastResult;
|
||||
}
|
||||
|
||||
// 3. 只读拉取远端分支引用,并严格从 origin/main:plugin.json 读取远端版本号(严禁回退使用缓存版本)
|
||||
await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', 'main', '--tags']);
|
||||
|
||||
let remoteVersion = '';
|
||||
try {
|
||||
const showRes = await runExecFile('git', [
|
||||
'-C',
|
||||
PLUGIN_ROOT,
|
||||
'show',
|
||||
'origin/main:plugin.json',
|
||||
]);
|
||||
const parsedManifest = JSON.parse(showRes.stdout || '{}');
|
||||
const rawVer =
|
||||
typeof parsedManifest?.version === 'string' ? parsedManifest.version.trim() : '';
|
||||
if (isValidSemver(rawVer)) {
|
||||
remoteVersion = rawVer.replace(/^v/i, '');
|
||||
}
|
||||
} catch {
|
||||
remoteVersion = '';
|
||||
}
|
||||
|
||||
// 4. 强制版本门禁:远端版本无法确认或不高于当前版本时,严禁执行 git pull 降级/覆盖
|
||||
if (!remoteVersion || compareSemver(remoteVersion, previousVersion) <= 0) {
|
||||
const msg = `当前已是最新版本 (v${previousVersion})`;
|
||||
const result = {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
upToDate: true,
|
||||
mode: 'git',
|
||||
reason: 'already_up_to_date',
|
||||
previousVersion,
|
||||
currentVersion: previousVersion,
|
||||
remoteVersion: remoteVersion || previousVersion,
|
||||
message: msg,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
pluginUpdateState.lastResult = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
// 5. 提交拓扑预检:确保当前 HEAD 是 origin/main 的祖先提交(无本地超前或分叉提交)
|
||||
try {
|
||||
await runExecFile('git', [
|
||||
'-C',
|
||||
PLUGIN_ROOT,
|
||||
'merge-base',
|
||||
'--is-ancestor',
|
||||
'HEAD',
|
||||
'origin/main',
|
||||
]);
|
||||
} catch {
|
||||
const msg = '本地分支存在未推送提交,已跳过更新';
|
||||
pluginUpdateState.lastError = isAuto ? null : msg;
|
||||
pluginUpdateState.lastResult = {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
mode: 'git',
|
||||
reason: 'diverged_worktree',
|
||||
previousVersion,
|
||||
currentVersion: previousVersion,
|
||||
message: msg,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
return pluginUpdateState.lastResult;
|
||||
}
|
||||
|
||||
// 6. 确认全部门禁通过后,执行快进合并并校验 JS 语法
|
||||
await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', 'main']);
|
||||
await verifyPluginJsSyntax(PLUGIN_ROOT);
|
||||
rebuildActiveCatalog();
|
||||
const currentVersion = readInstalledPluginVersion();
|
||||
const result = {
|
||||
ok: true,
|
||||
mode: 'git',
|
||||
previousVersion,
|
||||
currentVersion,
|
||||
restarting: true,
|
||||
message: `已升级至 v${currentVersion},正在重启面板…`,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
pluginUpdateState.lastResult = result;
|
||||
scheduleSidecarRestart();
|
||||
return result;
|
||||
}
|
||||
|
||||
// Release ZIP 归档更新通道(适用于无 .git 的压缩包安装目录)
|
||||
const targetVersion = cloudSyncState.latestPluginVersion || '';
|
||||
if (!isValidSemver(targetVersion) || compareSemver(targetVersion, previousVersion) <= 0) {
|
||||
const msg = `当前已是最新版本 (v${previousVersion})`;
|
||||
const result = {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
upToDate: true,
|
||||
mode: 'zip',
|
||||
reason: 'already_up_to_date',
|
||||
previousVersion,
|
||||
currentVersion: previousVersion,
|
||||
remoteVersion: targetVersion || previousVersion,
|
||||
message: msg,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
pluginUpdateState.lastResult = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
const candidateUrls = [
|
||||
cloudSyncState.downloadUrl || DEFAULT_DOWNLOAD_URL,
|
||||
cloudSyncState.archiveFallbackUrl || DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||
].filter(Boolean);
|
||||
|
||||
let lastZipErr = null;
|
||||
for (const zipUrl of candidateUrls) {
|
||||
const stagingDir = join(DATA_DIR, `.update-staging-${Date.now()}`);
|
||||
const zipFile = join(stagingDir, 'bundle.zip');
|
||||
const extractDir = join(stagingDir, 'extracted');
|
||||
const backupDir = join(stagingDir, 'backup');
|
||||
try {
|
||||
mkdirSync(extractDir, { recursive: true });
|
||||
const res = await fetch(zipUrl, {
|
||||
method: 'GET',
|
||||
signal: AbortSignal.timeout(25000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`下载更新包失败 (HTTP ${res.status})`);
|
||||
}
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
// 校验 ZIP 文件头魔数 ('PK') 与最小合理体积
|
||||
if (buf.length < 1024 || buf[0] !== 0x50 || buf[1] !== 0x4b) {
|
||||
throw new Error('下载的更新包格式校验未通过');
|
||||
}
|
||||
writeFileSync(zipFile, buf);
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
await runExecFile('powershell.exe', [
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
`Expand-Archive -LiteralPath '${zipFile.replace(/'/g, "''")}' -DestinationPath '${extractDir.replace(/'/g, "''")}' -Force`,
|
||||
]);
|
||||
} else {
|
||||
await runExecFile('unzip', ['-oq', zipFile, '-d', extractDir]);
|
||||
}
|
||||
|
||||
const extractedRoot = locateExtractedPluginRoot(extractDir);
|
||||
if (
|
||||
!extractedRoot ||
|
||||
!existsSync(join(extractedRoot, 'sidecars', 'panel', 'main.mjs')) ||
|
||||
!existsSync(join(extractedRoot, 'sidecars', 'panel', 'app.js')) ||
|
||||
!existsSync(join(extractedRoot, 'sidecars', 'panel', 'styles.css')) ||
|
||||
!existsSync(join(extractedRoot, 'sidecars', 'panel', 'index.html'))
|
||||
) {
|
||||
throw new Error('更新包缺少核心插件文件');
|
||||
}
|
||||
|
||||
const extractedManifest = loadJson(join(extractedRoot, 'plugin.json'), null);
|
||||
const rawExtractedVer =
|
||||
typeof extractedManifest?.version === 'string'
|
||||
? extractedManifest.version.trim()
|
||||
: '';
|
||||
const extractedVer = isValidSemver(rawExtractedVer)
|
||||
? rawExtractedVer.replace(/^v/i, '')
|
||||
: '';
|
||||
if (!extractedVer || compareSemver(extractedVer, previousVersion) <= 0) {
|
||||
throw new Error(
|
||||
`下载包版本 (v${extractedVer || '未知'}) 不高于当前已安装版本 (v${previousVersion}),已拒绝降级覆盖`
|
||||
);
|
||||
}
|
||||
if (
|
||||
zipUrl !== candidateUrls[candidateUrls.length - 1] &&
|
||||
compareSemver(targetVersion, extractedVer) > 0
|
||||
) {
|
||||
throw new Error(
|
||||
`Release 压缩包版本 (v${extractedVer}) 尚未同步至 v${targetVersion},切换至主干归档源`
|
||||
);
|
||||
}
|
||||
|
||||
// 覆盖前先对解压目录执行 JS 语法预检,防止损坏代码覆盖现有安装
|
||||
await verifyPluginJsSyntax(extractedRoot);
|
||||
|
||||
// 备份当前插件根目录关键文件,若覆盖途中异常则自动回滚
|
||||
mkdirSync(backupDir, { recursive: true });
|
||||
cpSync(PLUGIN_ROOT, backupDir, { recursive: true, force: true, filter: isSafeCopyPath });
|
||||
try {
|
||||
cpSync(extractedRoot, PLUGIN_ROOT, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
filter: isSafeCopyPath,
|
||||
});
|
||||
} catch (copyErr) {
|
||||
try {
|
||||
cpSync(backupDir, PLUGIN_ROOT, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
filter: isSafeCopyPath,
|
||||
});
|
||||
} catch {
|
||||
// 忽略回滚二级异常
|
||||
}
|
||||
throw copyErr;
|
||||
}
|
||||
|
||||
try {
|
||||
rmSync(stagingDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// 忽略临时目录清理错误
|
||||
}
|
||||
|
||||
rebuildActiveCatalog();
|
||||
const currentVersion = readInstalledPluginVersion();
|
||||
const result = {
|
||||
ok: true,
|
||||
mode: 'zip',
|
||||
previousVersion,
|
||||
currentVersion,
|
||||
restarting: true,
|
||||
message: `已下载并更新至 v${currentVersion},正在重载面板…`,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
pluginUpdateState.lastResult = result;
|
||||
scheduleSidecarRestart();
|
||||
return result;
|
||||
} catch (err) {
|
||||
lastZipErr = err;
|
||||
try {
|
||||
rmSync(stagingDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// 忽略临时目录清理错误
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastZipErr || new Error('未能下载可用的插件更新包');
|
||||
} catch (err) {
|
||||
const errMsg = err?.message || '插件更新失败';
|
||||
pluginUpdateState.lastError = errMsg;
|
||||
const result = {
|
||||
ok: false,
|
||||
mode: hasGit ? 'git' : 'zip',
|
||||
previousVersion,
|
||||
currentVersion: readInstalledPluginVersion(),
|
||||
message: errMsg,
|
||||
updatedAtMs: Date.now(),
|
||||
};
|
||||
pluginUpdateState.lastResult = result;
|
||||
return result;
|
||||
} finally {
|
||||
pluginUpdateState.isUpdating = false;
|
||||
pluginUpdateState.inFlight = null;
|
||||
}
|
||||
})();
|
||||
return pluginUpdateState.inFlight;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步云端 `pricing-catalog.json` 目录并在满足条件时触发插件自动更新。
|
||||
*
|
||||
* @param {{ force?: boolean, urls?: string[] }} [options]
|
||||
* @returns {Promise<ReturnType<typeof getCloudStatus>>}
|
||||
*/
|
||||
export async function syncCloudCatalog({ force = false, urls = CLOUD_CATALOG_URLS } = {}) {
|
||||
if (cloudSyncState.inFlight) return cloudSyncState.inFlight;
|
||||
const now = Date.now();
|
||||
if (!force) {
|
||||
if (cloudSyncState.fetchedAtMs > 0 && now - cloudSyncState.fetchedAtMs < CLOUD_SYNC_TTL_MS) {
|
||||
return getCloudStatus();
|
||||
}
|
||||
if (
|
||||
cloudSyncState.lastAttemptMs > 0 &&
|
||||
now - cloudSyncState.lastAttemptMs < CLOUD_SYNC_RETRY_COOLDOWN_MS
|
||||
) {
|
||||
return getCloudStatus();
|
||||
}
|
||||
}
|
||||
|
||||
cloudSyncState.inFlight = (async () => {
|
||||
cloudSyncState.isSyncing = true;
|
||||
cloudSyncState.lastAttemptMs = Date.now();
|
||||
let lastErr = null;
|
||||
try {
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const sep = url.includes('?') ? '&' : '?';
|
||||
const reqUrl = force ? `${url}${sep}_t=${Date.now()}` : url;
|
||||
const res = await fetch(reqUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
signal: AbortSignal.timeout(4500),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
}
|
||||
const raw = await res.json();
|
||||
const sanitized = sanitizeCatalogPayload(raw);
|
||||
if (!sanitized) {
|
||||
throw new Error('Invalid cloud catalog schema');
|
||||
}
|
||||
const persisted = {
|
||||
...sanitized,
|
||||
fetchedAtMs: Date.now(),
|
||||
sourceUrl: url,
|
||||
};
|
||||
saveJson(REMOTE_CATALOG_CACHE_FILE, persisted);
|
||||
cloudSyncState.fetchedAtMs = persisted.fetchedAtMs;
|
||||
cloudSyncState.sourceUrl = url;
|
||||
cloudSyncState.lastError = null;
|
||||
rebuildActiveCatalog();
|
||||
|
||||
const statusAfter = getCloudStatus();
|
||||
const settings = loadSettings();
|
||||
if (
|
||||
statusAfter.updateAvailable &&
|
||||
settings.autoUpdatePlugin &&
|
||||
!pluginUpdateState.isUpdating &&
|
||||
pluginUpdateState.lastAutoAttemptVersion !== statusAfter.latestPluginVersion
|
||||
) {
|
||||
pluginUpdateState.lastAutoAttemptVersion = statusAfter.latestPluginVersion;
|
||||
performPluginUpdate({ isAuto: true }).catch(() => {});
|
||||
}
|
||||
return statusAfter;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
}
|
||||
}
|
||||
cloudSyncState.lastError = lastErr?.message || '云端价格表同步失败';
|
||||
return getCloudStatus();
|
||||
} finally {
|
||||
cloudSyncState.isSyncing = false;
|
||||
cloudSyncState.inFlight = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return cloudSyncState.inFlight;
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
/**
|
||||
* @fileoverview 内置模型价格与占位符字典、Schema 安全清洗及三级目录合并(内置 + 本地 + 云端)。
|
||||
*
|
||||
* 价格口径与安全原则:
|
||||
* - 所有单价单位均为 USD / 1M Tokens(`input`: 未命中缓存输入, `cache`: 缓存读取, `output`: 输出与思考);
|
||||
* - 价格仅用于本地 API 等效成本折算,不代表订阅配额的扣减比例;
|
||||
* - 未收录或身份未知的模型严格保持未定价状态(`null`),绝不借用其他模型价格,也绝不允许 `null`/`0` 伪价格混入;
|
||||
* - 版本号与更新包 URL 均经过严格格式与可信 GitHub 域名白名单校验。
|
||||
*/
|
||||
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
||||
import {
|
||||
DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||
DEFAULT_DOWNLOAD_URL,
|
||||
DEFAULT_RELEASE_URL,
|
||||
LOCAL_CATALOG_FILE,
|
||||
PLUGIN_MANIFEST_FILE,
|
||||
PLUGIN_ROOT,
|
||||
REMOTE_CATALOG_CACHE_FILE,
|
||||
cloudSyncState,
|
||||
loadJson,
|
||||
pluginUpdateState,
|
||||
} from './config.mjs';
|
||||
|
||||
/**
|
||||
* 代码内置兜底模型价格字典(当本地与云端目录均不可用时的离线基准)。
|
||||
*/
|
||||
export const BUILTIN_MODEL_PRICING = {
|
||||
// Gemini 4 & 3.x & 2.5 官方目录价格 (USD / 1M tokens)
|
||||
'gemini-4-argon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-high', 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: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-low', family: 'Gemini' },
|
||||
'gemini-4-argon': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4', family: 'Gemini' },
|
||||
'gemini-3.8-flash-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8-high', family: 'Gemini' },
|
||||
'gemini-3.8-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' },
|
||||
'gemini-3.8-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.8-low', family: 'Gemini' },
|
||||
'gemini-3.8-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', family: 'Gemini' },
|
||||
'gemini-3.7-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' },
|
||||
'gemini-3.6-flash': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6', family: 'Gemini' },
|
||||
'gemini-3.5-flash': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5', family: 'Gemini' },
|
||||
'gemini-3.5-flash-lite': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-lite', family: 'Gemini' },
|
||||
'gemini-3.1-pro': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' },
|
||||
'gemini-3.1-flash-lite': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' },
|
||||
'gemini-3-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' },
|
||||
'gemini-2.5-pro': { input: 1.25, cache: 0.125, output: 10.0, short: 'pro-2.5', family: 'Gemini' },
|
||||
'gemini-2.5-flash': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-2.5', family: 'Gemini' },
|
||||
'gemini-2.5-flash-lite': { input: 0.10, cache: 0.01, output: 0.40, short: 'flash-2.5-lite', family: 'Gemini' },
|
||||
|
||||
// Claude 4.5 / 4.6 / 4.7 / 4.8 / 5.x 官方目录价格
|
||||
'claude-fable-5-1': { input: 10.0, cache: 0.25, output: 50.0, short: 'fable-5.1', family: 'Claude' },
|
||||
'claude-fable-5': { input: 10.0, cache: 1.00, output: 50.0, short: 'fable-5', family: 'Claude' },
|
||||
'claude-opus-5-5': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' },
|
||||
'claude-opus-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-5', family: 'Claude' },
|
||||
'claude-opus-4-8': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.8', family: 'Claude' },
|
||||
'claude-opus-4-7': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.7', family: 'Claude' },
|
||||
'claude-opus-4-6-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus', family: 'Claude' },
|
||||
'claude-opus-4-6': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.6', family: 'Claude' },
|
||||
'claude-opus-4-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', family: 'Claude' },
|
||||
'claude-sonnet-5-5': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' },
|
||||
'claude-sonnet-5': { input: 2.00, cache: 0.20, output: 10.0, short: 'sonnet-5', family: 'Claude' },
|
||||
'claude-sonnet-4-6': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet', family: 'Claude' },
|
||||
'claude-sonnet-4-5': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', family: 'Claude' },
|
||||
'claude-haiku-5-5': { input: 0.10, cache: 0.01, output: 0.50, short: 'haiku-5.5', family: 'Claude' },
|
||||
'claude-haiku-4-5': { input: 1.00, cache: 0.10, output: 5.00, short: 'haiku-4.5', family: 'Claude' },
|
||||
|
||||
// OpenAI / GPT 官方目录价格
|
||||
'gpt-6-astra': { input: 10.0, cache: 1.00, output: 50.0, short: 'gpt-6-astra', family: 'GPT' },
|
||||
'gpt-6.1-sol': { input: 2.00, cache: 0.10, output: 10.0, short: 'gpt-6.1-sol', family: 'GPT' },
|
||||
'gpt-6-sol': { input: 2.00, cache: 0.20, output: 10.0, short: 'gpt-6-sol', family: 'GPT' },
|
||||
'gpt-6-luna': { input: 0.10, cache: 0.01, output: 0.50, short: 'gpt-6-luna', family: 'GPT' },
|
||||
'gpt-5.6': { input: 4.00, cache: 0.40, output: 20.0, short: 'gpt-5.6', family: 'GPT' },
|
||||
'gpt-5.6-sol': { input: 4.00, cache: 0.40, output: 20.0, short: 'gpt-5.6-sol', family: 'GPT' },
|
||||
'gpt-5.6-terra': { input: 2.00, cache: 0.20, output: 12.0, short: 'gpt-5.6-terra', family: 'GPT' },
|
||||
'gpt-5.6-luna': { input: 0.20, cache: 0.02, output: 1.20, short: 'gpt-5.6-luna', family: 'GPT' },
|
||||
'gpt-5.5': { input: 5.00, cache: 0.50, output: 30.0, short: 'gpt-5.5', family: 'GPT' },
|
||||
'gpt-5.4': { input: 2.50, cache: 0.25, output: 15.0, short: 'gpt-5.4', family: 'GPT' },
|
||||
'gpt-5.4-mini': { input: 0.75, cache: 0.075, output: 4.50, short: 'gpt-5.4-mini', family: 'GPT' },
|
||||
'gpt-5.4-nano': { input: 0.20, cache: 0.02, output: 1.25, short: 'gpt-5.4-nano', family: 'GPT' },
|
||||
'gpt-5.3-codex': { input: 1.75, cache: 0.175, output: 14.0, short: 'gpt-5.3-codex', family: 'GPT' },
|
||||
'gpt-5.2': { input: 1.75, cache: 0.175, output: 14.0, short: 'gpt-5.2', family: 'GPT' },
|
||||
'gpt-5.1': { input: 1.25, cache: 0.125, output: 10.0, short: 'gpt-5.1', family: 'GPT' },
|
||||
'gpt-5': { input: 1.25, cache: 0.125, output: 10.0, short: 'gpt-5', family: 'GPT' },
|
||||
'gpt-5-mini': { input: 0.25, cache: 0.025, output: 2.00, short: 'gpt-5-mini', family: 'GPT' },
|
||||
'gpt-5-nano': { input: 0.05, cache: 0.005, output: 0.40, short: 'gpt-5-nano', family: 'GPT' },
|
||||
'gpt-4.1': { input: 2.00, cache: 0.50, output: 8.00, short: 'gpt-4.1', family: 'GPT' },
|
||||
'gpt-4.1-mini': { input: 0.40, cache: 0.10, output: 1.60, short: 'gpt-4.1-mini', family: 'GPT' },
|
||||
'gpt-4o': { input: 2.50, cache: 1.25, output: 10.0, short: 'gpt-4o', family: 'GPT' },
|
||||
'gpt-4o-mini': { input: 0.15, cache: 0.075, output: 0.60, short: 'gpt-4o-mini', family: 'GPT' },
|
||||
'o4-mini': { input: 1.10, cache: 0.275, output: 4.40, short: 'o4-mini', family: 'GPT' },
|
||||
'o3': { input: 2.00, cache: 0.50, output: 8.00, short: 'o3', family: 'GPT' },
|
||||
'o3-mini': { input: 1.10, cache: 0.55, output: 4.40, short: 'o3-mini', family: 'GPT' },
|
||||
'gpt-oss-120b-medium': { input: 0.80, cache: 0.10, output: 2.40, short: 'gpt-oss', family: 'GPT' },
|
||||
};
|
||||
|
||||
/**
|
||||
* 代码内置兜底枚举占位符映射表(`MODEL_PLACEHOLDER_Mxxx` -> `modelId` & `label`)。
|
||||
*/
|
||||
export const BUILTIN_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_M322: { modelId: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash (Tiered)' },
|
||||
MODEL_PLACEHOLDER_M198: { modelId: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash Lite' },
|
||||
MODEL_PLACEHOLDER_M50: { modelId: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' },
|
||||
MODEL_PLACEHOLDER_M18: { modelId: 'gemini-3-flash', label: 'Gemini 3 Flash' },
|
||||
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_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)' },
|
||||
};
|
||||
|
||||
/**
|
||||
* 当前生效的模型价格表与占位符映射表(通过就地更新属性保持跨模块引用一致)。
|
||||
*/
|
||||
export const MODEL_PRICING = { ...BUILTIN_MODEL_PRICING };
|
||||
export const PLACEHOLDER_MAP = { ...BUILTIN_PLACEHOLDER_MAP };
|
||||
|
||||
/**
|
||||
* 校验字符串是否为合法的 `X.Y.Z` 语义化版本号格式。
|
||||
*
|
||||
* @param {*} v
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isValidSemver(v) {
|
||||
return typeof v === 'string' && /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验更新/下载链接是否属于可信的 GitHub 官方 HTTPS 域名白名单。
|
||||
*
|
||||
* @param {*} rawUrl
|
||||
* @param {string} fallbackUrl
|
||||
* @returns {string}
|
||||
*/
|
||||
export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) {
|
||||
if (typeof rawUrl !== 'string' || !rawUrl.trim()) return fallbackUrl;
|
||||
try {
|
||||
const parsed = new URL(rawUrl.trim());
|
||||
if (parsed.protocol !== 'https:') return fallbackUrl;
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
const isTrustedHost =
|
||||
host === 'github.com' ||
|
||||
host === 'raw.githubusercontent.com' ||
|
||||
host === 'codeload.github.com' ||
|
||||
host === 'objects.githubusercontent.com';
|
||||
return isTrustedHost ? parsed.toString() : fallbackUrl;
|
||||
} catch {
|
||||
return fallbackUrl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个语义化版本号(如 `'1.5.0'` vs `'1.4.0'`)。
|
||||
*
|
||||
* @param {string} a
|
||||
* @param {string} b
|
||||
* @returns {number} `1` 表示 `a > b`,`-1` 表示 `a < b`,`0` 表示相等
|
||||
*/
|
||||
export function compareSemver(a, b) {
|
||||
if (!isValidSemver(a) || !isValidSemver(b)) return 0;
|
||||
const parse = (v) =>
|
||||
String(v || '')
|
||||
.trim()
|
||||
.replace(/^v/i, '')
|
||||
.split('-')[0]
|
||||
.split('.')
|
||||
.map((n) => {
|
||||
const parsed = parseInt(n, 10);
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
|
||||
});
|
||||
const pa = parse(a);
|
||||
const pb = parse(b);
|
||||
const len = Math.max(pa.length, pb.length, 3);
|
||||
for (let i = 0; i < len; i++) {
|
||||
const va = pa[i] || 0;
|
||||
const vb = pb[i] || 0;
|
||||
if (va > vb) return 1;
|
||||
if (va < vb) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取当前已安装插件的 `plugin.json` 版本号。
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
export function readInstalledPluginVersion() {
|
||||
const manifest = loadJson(PLUGIN_MANIFEST_FILE, null);
|
||||
const ver = typeof manifest?.version === 'string' ? manifest.version.trim() : '';
|
||||
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.0';
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单条模型价格配置是否合法:
|
||||
* - `input`/`cache`/`output` 必须为原生 `number` 类型(阻止 `Number(null) === 0` 或 `Number("") === 0` 的隐式转换漏洞);
|
||||
* - 数值必须非负且 `<= 10000`,且至少 `input > 0` 或 `output > 0`(拒绝全 0 伪价格将未定价模型篡改为 $0.00);
|
||||
* - `short`/`family` 必须为非空字符串。
|
||||
*/
|
||||
function isValidPricingEntry(entry) {
|
||||
if (!entry || typeof entry !== 'object') return false;
|
||||
if (
|
||||
typeof entry.input !== 'number' ||
|
||||
typeof entry.cache !== 'number' ||
|
||||
typeof entry.output !== 'number'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const { input, cache, output } = entry;
|
||||
if (!Number.isFinite(input) || input < 0 || input > 10000) return false;
|
||||
if (!Number.isFinite(cache) || cache < 0 || cache > 10000) return false;
|
||||
if (!Number.isFinite(output) || output < 0 || output > 10000) return false;
|
||||
if (input === 0 && output === 0) return false;
|
||||
if (typeof entry.short !== 'string' || !entry.short.trim()) return false;
|
||||
if (typeof entry.family !== 'string' || !entry.family.trim()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单条枚举占位符映射是否合法。
|
||||
*/
|
||||
function isValidPlaceholderEntry(entry) {
|
||||
if (!entry || typeof entry !== 'object') return false;
|
||||
if (typeof entry.modelId !== 'string' || !entry.modelId.trim()) return false;
|
||||
if (typeof entry.label !== 'string' || !entry.label.trim()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清洗并校验来自本地或云端的 `pricing-catalog.json` 原始对象。
|
||||
* 任何格式不合法的单条记录会被自动过滤,防止异常数据污染内存价格表。
|
||||
*
|
||||
* @param {object} raw
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function sanitizeCatalogPayload(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const pricing = {};
|
||||
let validPricingCount = 0;
|
||||
if (raw.pricing && typeof raw.pricing === 'object') {
|
||||
for (const [k, v] of Object.entries(raw.pricing)) {
|
||||
const key = String(k || '').trim();
|
||||
if (!key || !isValidPricingEntry(v)) continue;
|
||||
pricing[key] = {
|
||||
input: v.input,
|
||||
cache: v.cache,
|
||||
output: v.output,
|
||||
short: String(v.short).trim(),
|
||||
family: String(v.family).trim(),
|
||||
};
|
||||
validPricingCount++;
|
||||
}
|
||||
}
|
||||
|
||||
const placeholders = {};
|
||||
let validPlaceholderCount = 0;
|
||||
if (raw.placeholders && typeof raw.placeholders === 'object') {
|
||||
for (const [k, v] of Object.entries(raw.placeholders)) {
|
||||
const key = String(k || '').trim();
|
||||
if (!key || !isValidPlaceholderEntry(v)) continue;
|
||||
placeholders[key] = {
|
||||
modelId: String(v.modelId).trim(),
|
||||
label: String(v.label).trim(),
|
||||
};
|
||||
validPlaceholderCount++;
|
||||
}
|
||||
}
|
||||
|
||||
const rawLatestVer =
|
||||
typeof raw.latestPluginVersion === 'string' ? raw.latestPluginVersion.trim() : '';
|
||||
const latestPluginVersion = isValidSemver(rawLatestVer)
|
||||
? rawLatestVer.replace(/^v/i, '')
|
||||
: null;
|
||||
if (validPricingCount === 0 && validPlaceholderCount === 0 && !latestPluginVersion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: Number(raw.schemaVersion || 1),
|
||||
catalogVersion:
|
||||
typeof raw.catalogVersion === 'string' && raw.catalogVersion.trim()
|
||||
? raw.catalogVersion.trim()
|
||||
: null,
|
||||
updatedAt:
|
||||
typeof raw.updatedAt === 'string' && raw.updatedAt.trim() ? raw.updatedAt.trim() : null,
|
||||
latestPluginVersion,
|
||||
releaseUrl: sanitizeTrustedGithubUrl(raw.releaseUrl, DEFAULT_RELEASE_URL),
|
||||
downloadUrl: sanitizeTrustedGithubUrl(raw.downloadUrl, DEFAULT_DOWNLOAD_URL),
|
||||
archiveFallbackUrl: sanitizeTrustedGithubUrl(
|
||||
raw.archiveFallbackUrl,
|
||||
DEFAULT_ARCHIVE_FALLBACK_URL
|
||||
),
|
||||
fetchedAtMs: Number(raw.fetchedAtMs || 0),
|
||||
sourceUrl: typeof raw.sourceUrl === 'string' ? raw.sourceUrl : '',
|
||||
pricing,
|
||||
placeholders,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按「内置保底 -> 本地目录 -> 云端缓存(按 `updatedAt` 新旧自动裁决优先级)」三级合并重建内存价格表。
|
||||
*/
|
||||
export function rebuildActiveCatalog() {
|
||||
const localRaw = loadJson(LOCAL_CATALOG_FILE, null);
|
||||
const remoteRaw = loadJson(REMOTE_CATALOG_CACHE_FILE, null);
|
||||
const localCat = sanitizeCatalogPayload(localRaw);
|
||||
const remoteCat = sanitizeCatalogPayload(remoteRaw);
|
||||
|
||||
const localUpdatedMs = parseIsoMs(localCat?.updatedAt);
|
||||
const remoteUpdatedMs = parseIsoMs(remoteCat?.updatedAt);
|
||||
|
||||
const layers = [];
|
||||
if (localCat && remoteCat) {
|
||||
if (localUpdatedMs > remoteUpdatedMs) {
|
||||
layers.push({ kind: 'remote', cat: remoteCat }, { kind: 'local', cat: localCat });
|
||||
} else {
|
||||
layers.push({ kind: 'local', cat: localCat }, { kind: 'remote', cat: remoteCat });
|
||||
}
|
||||
} else if (remoteCat) {
|
||||
layers.push({ kind: 'remote', cat: remoteCat });
|
||||
} else if (localCat) {
|
||||
layers.push({ kind: 'local', cat: localCat });
|
||||
}
|
||||
|
||||
const nextPricing = { ...BUILTIN_MODEL_PRICING };
|
||||
const nextPlaceholders = { ...BUILTIN_PLACEHOLDER_MAP };
|
||||
let activeSource = 'builtin';
|
||||
let catalogVersion = 'builtin';
|
||||
let updatedAt = null;
|
||||
const installedVersion = readInstalledPluginVersion();
|
||||
let latestPluginVersion = installedVersion;
|
||||
let releaseUrl = DEFAULT_RELEASE_URL;
|
||||
let downloadUrl = DEFAULT_DOWNLOAD_URL;
|
||||
let archiveFallbackUrl = DEFAULT_ARCHIVE_FALLBACK_URL;
|
||||
|
||||
for (const { kind, cat } of layers) {
|
||||
Object.assign(nextPricing, cat.pricing);
|
||||
Object.assign(nextPlaceholders, cat.placeholders);
|
||||
activeSource = kind;
|
||||
if (cat.catalogVersion) catalogVersion = cat.catalogVersion;
|
||||
if (cat.updatedAt) updatedAt = cat.updatedAt;
|
||||
if (cat.latestPluginVersion) {
|
||||
// 以当前更高优先级层的 latestPluginVersion 为准,但永不低于本地已安装版本
|
||||
latestPluginVersion =
|
||||
compareSemver(cat.latestPluginVersion, installedVersion) > 0
|
||||
? cat.latestPluginVersion
|
||||
: installedVersion;
|
||||
}
|
||||
if (cat.releaseUrl) releaseUrl = cat.releaseUrl;
|
||||
if (cat.downloadUrl) downloadUrl = cat.downloadUrl;
|
||||
if (cat.archiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl;
|
||||
}
|
||||
|
||||
for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k];
|
||||
Object.assign(MODEL_PRICING, nextPricing);
|
||||
|
||||
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
|
||||
Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
|
||||
|
||||
cloudSyncState.source = activeSource;
|
||||
cloudSyncState.catalogVersion = catalogVersion;
|
||||
cloudSyncState.updatedAt = updatedAt;
|
||||
cloudSyncState.fetchedAtMs = remoteCat?.fetchedAtMs || cloudSyncState.fetchedAtMs || 0;
|
||||
cloudSyncState.sourceUrl = remoteCat?.sourceUrl || cloudSyncState.sourceUrl || '';
|
||||
cloudSyncState.latestPluginVersion = latestPluginVersion;
|
||||
cloudSyncState.releaseUrl = releaseUrl;
|
||||
cloudSyncState.downloadUrl = downloadUrl;
|
||||
cloudSyncState.archiveFallbackUrl = archiveFallbackUrl;
|
||||
}
|
||||
|
||||
// 模块初始化时立即构建一次当前生效的价格目录
|
||||
rebuildActiveCatalog();
|
||||
|
||||
/**
|
||||
* 获取供前端展示的云端价格目录状态与插件更新状态快照。
|
||||
*/
|
||||
export function getCloudStatus() {
|
||||
const currentPluginVersion = readInstalledPluginVersion();
|
||||
const rawLatest = cloudSyncState.latestPluginVersion || currentPluginVersion;
|
||||
const latestPluginVersion =
|
||||
compareSemver(rawLatest, currentPluginVersion) > 0 ? rawLatest : currentPluginVersion;
|
||||
const updateAvailable = compareSemver(latestPluginVersion, currentPluginVersion) > 0;
|
||||
return {
|
||||
currentPluginVersion,
|
||||
latestPluginVersion,
|
||||
updateAvailable,
|
||||
installMode: existsSync(join(PLUGIN_ROOT, '.git')) ? 'git' : 'zip',
|
||||
releaseUrl: cloudSyncState.releaseUrl || DEFAULT_RELEASE_URL,
|
||||
downloadUrl: cloudSyncState.downloadUrl || DEFAULT_DOWNLOAD_URL,
|
||||
catalogVersion: cloudSyncState.catalogVersion || 'builtin',
|
||||
catalogUpdatedAt: cloudSyncState.updatedAt || null,
|
||||
lastSyncedAtMs: cloudSyncState.fetchedAtMs || 0,
|
||||
source: cloudSyncState.source || 'builtin',
|
||||
modelCount: Object.keys(MODEL_PRICING).length,
|
||||
placeholderCount: Object.keys(PLACEHOLDER_MAP).length,
|
||||
isSyncing: Boolean(cloudSyncState.isSyncing),
|
||||
lastSyncError: cloudSyncState.lastError || null,
|
||||
isUpdating: Boolean(pluginUpdateState.isUpdating),
|
||||
lastUpdateResult: pluginUpdateState.lastResult || null,
|
||||
lastUpdateError: pluginUpdateState.lastError || null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
/**
|
||||
* @fileoverview 官方配额桶归一化、周期窗口识别与多模型池(Gemini / Argon / Claude & GPT)构建。
|
||||
*
|
||||
* 处理所有已知的 Antigravity 服务端配额形态:
|
||||
* - Google AI Ultra:Argon 与 Flash 共享同一个 Gemini Models 配额池;
|
||||
* - Google AI Pro(形态 1):`RetrieveUserQuotaSummary` 返回独立的 `Gemini 4 Argon` 组;
|
||||
* - Google AI Pro(形态 2):`Gemini Models` 组内嵌套独立的 `argon-weekly` 桶;
|
||||
* - Google AI Pro(形态 3):`GetUserStatus` 的 `clientModelConfigs.quotaInfo` 为 Argon 报告了与标准 Gemini 不同的独立剩余比例;
|
||||
* - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略但存在有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。
|
||||
*/
|
||||
|
||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
||||
import { isArgonModelIdentifier, resolveModelInfo } from './model-pricing.mjs';
|
||||
|
||||
/**
|
||||
* 将原始配额对象(来自 `RetrieveUserQuotaSummary` 桶或 `clientModelConfigs.quotaInfo`)归一化为百分比结构。
|
||||
*
|
||||
* @param {object} rawObj
|
||||
* @returns {{
|
||||
* remainingFraction: number,
|
||||
* remainingPct: number,
|
||||
* remainingIntPct: number,
|
||||
* usedPct: number,
|
||||
* resetTime: string|null,
|
||||
* description: string
|
||||
* } | null}
|
||||
*/
|
||||
export function normalizeQuotaFraction(rawObj) {
|
||||
if (!rawObj || typeof rawObj !== 'object') return null;
|
||||
let remFrac = null;
|
||||
if (rawObj.disabled === true) {
|
||||
remFrac = 0;
|
||||
} else if (
|
||||
rawObj.remainingFraction !== undefined &&
|
||||
rawObj.remainingFraction !== null &&
|
||||
Number.isFinite(Number(rawObj.remainingFraction))
|
||||
) {
|
||||
remFrac = Math.max(0, Math.min(1, Number(rawObj.remainingFraction)));
|
||||
} else if (typeof rawObj.resetTime === 'string' && rawObj.resetTime.trim().length > 0) {
|
||||
// Proto3 在配额完全耗尽(0.0)时会省略默认数值字段,此时凭有效 resetTime 判定为剩余 0
|
||||
remFrac = 0;
|
||||
}
|
||||
if (remFrac === null) return null;
|
||||
const usedFrac = Math.max(0, Math.min(1, 1 - remFrac));
|
||||
return {
|
||||
remainingFraction: remFrac,
|
||||
remainingPct: +(remFrac * 100).toFixed(1),
|
||||
remainingIntPct: Math.floor(remFrac * 100 + 1e-6),
|
||||
usedPct: +(usedFrac * 100).toFixed(1),
|
||||
resetTime: rawObj.resetTime || null,
|
||||
description: rawObj.description || '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别官方配额桶所属的时间窗口类型(`'5h'` 或 `'weekly'`)。
|
||||
*
|
||||
* @param {object} bucket
|
||||
* @param {number} [groupBucketCount=1] 所属分组内的桶总数
|
||||
* @param {number} [nowMs=Date.now()] 当前毫秒时间戳
|
||||
* @returns {'5h'|'weekly'}
|
||||
*/
|
||||
export function classifyOfficialBucketWindow(bucket, groupBucketCount = 1, nowMs = Date.now()) {
|
||||
const w = String(bucket?.window || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const idAndName = `${bucket?.bucketId || ''} ${bucket?.displayName || ''}`.toLowerCase();
|
||||
if (
|
||||
w === '5h' ||
|
||||
/(?:^|[-_\s])5h(?:$|[-_\s])|five[-_\s]?hour/.test(w) ||
|
||||
/(?:^|[-_\s])5h(?:$|[-_\s])|five[-_\s]?hour/.test(idAndName)
|
||||
) {
|
||||
return '5h';
|
||||
}
|
||||
if (w === 'weekly' || w === '7d' || /week/.test(w) || /week/.test(idAndName)) {
|
||||
return 'weekly';
|
||||
}
|
||||
const resetMs = parseIsoMs(bucket?.resetTime);
|
||||
if (resetMs > nowMs + 6 * 3600 * 1000 || groupBucketCount === 1) {
|
||||
return 'weekly';
|
||||
}
|
||||
return '5h';
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Claude & GPT`)。
|
||||
*
|
||||
* @param {{ groupName?: string, groupDesc?: string, bucketId?: string, bucketName?: string }} params
|
||||
* @returns {{ poolKey: string, poolLabel: string, poolName: string }}
|
||||
*/
|
||||
export function classifyQuotaPoolIdentity({
|
||||
groupName = '',
|
||||
groupDesc = '',
|
||||
bucketId = '',
|
||||
bucketName = '',
|
||||
}) {
|
||||
const bId = String(bucketId || '');
|
||||
const bName = String(bucketName || '');
|
||||
const gName = String(groupName || '');
|
||||
const gDesc = String(groupDesc || '');
|
||||
if (
|
||||
/argon/i.test(bId) ||
|
||||
/argon/i.test(bName) ||
|
||||
/argon/i.test(gName) ||
|
||||
(/\bargon\b/i.test(gDesc) &&
|
||||
!/\bflash\b/i.test(gDesc) &&
|
||||
!/^gemini models$/i.test(gName.trim()))
|
||||
) {
|
||||
return {
|
||||
poolKey: 'Argon',
|
||||
poolLabel: 'Gemini 4 Argon',
|
||||
poolName: 'Gemini 4 Argon 模型池',
|
||||
};
|
||||
}
|
||||
if (/gemini/i.test(`${bId} ${bName} ${gName} ${gDesc}`)) {
|
||||
return {
|
||||
poolKey: 'Gemini',
|
||||
poolLabel: 'Gemini',
|
||||
poolName: 'Gemini 模型池',
|
||||
};
|
||||
}
|
||||
if (/3p|claude|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) {
|
||||
return {
|
||||
poolKey: 'Claude & GPT',
|
||||
poolLabel: 'Claude & GPT',
|
||||
poolName: 'Claude & GPT 模型池',
|
||||
};
|
||||
}
|
||||
const cleanLabel = (gName || bId || 'Other').trim();
|
||||
return {
|
||||
poolKey: cleanLabel,
|
||||
poolLabel: cleanLabel,
|
||||
poolName: `${cleanLabel} 模型池`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断两个归一化配额快照是否代表同一个共享配额桶(剩余比例误差 <= 1.5% 且重置时间相差 <= 2 分钟)。
|
||||
*
|
||||
* @param {ReturnType<typeof normalizeQuotaFraction>} a
|
||||
* @param {ReturnType<typeof normalizeQuotaFraction>} b
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function quotaFractionsMatch(a, b) {
|
||||
if (!a || !b) return false;
|
||||
if (Math.abs(a.remainingFraction - b.remainingFraction) > 0.015) return false;
|
||||
if (a.resetTime && b.resetTime) {
|
||||
const diffMs = Math.abs(parseIsoMs(a.resetTime) - parseIsoMs(b.resetTime));
|
||||
if (diffMs > 120_000) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 综合 `RetrieveUserQuotaSummary` 与 `GetUserStatus.clientModelConfigs`,构建动态模型映射表、
|
||||
* 分模型配额列表及聚合配额池映射表 (`quotaPoolsMap`)。
|
||||
*
|
||||
* @param {object|null} officialQuota 来自 `RetrieveUserQuotaSummary` 的响应体
|
||||
* @param {object[]} clientConfigs 来自 `GetUserStatus` 的客户端模型配置数组
|
||||
* @returns {{
|
||||
* dynamicModelMap: Map<string, object>,
|
||||
* quotaPoolsMap: Map<string, object>,
|
||||
* modelQuotas: object[]
|
||||
* }}
|
||||
*/
|
||||
export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
||||
const dynamicModelMap = new Map();
|
||||
const nowForQuotaMs = Date.now();
|
||||
const officialBuckets = new Map();
|
||||
const poolBuilders = new Map();
|
||||
|
||||
function ensurePoolBuilder({ poolKey, poolLabel, poolName }) {
|
||||
if (!poolBuilders.has(poolKey)) {
|
||||
poolBuilders.set(poolKey, {
|
||||
poolKey,
|
||||
poolLabel,
|
||||
poolName,
|
||||
bucket5h: null,
|
||||
bucketWeekly: null,
|
||||
fallback5h: null,
|
||||
models: [],
|
||||
});
|
||||
}
|
||||
return poolBuilders.get(poolKey);
|
||||
}
|
||||
|
||||
const rawGroups = Array.isArray(officialQuota?.groups) ? [...officialQuota.groups] : [];
|
||||
if (
|
||||
Array.isArray(officialQuota?.buckets) &&
|
||||
officialQuota.buckets.length > 0 &&
|
||||
rawGroups.length === 0
|
||||
) {
|
||||
rawGroups.push({ displayName: '', description: '', buckets: officialQuota.buckets });
|
||||
}
|
||||
|
||||
for (const grp of rawGroups) {
|
||||
const grpBuckets = Array.isArray(grp?.buckets) ? grp.buckets : [];
|
||||
for (const b of grpBuckets) {
|
||||
const norm = normalizeQuotaFraction(b);
|
||||
if (!norm) continue;
|
||||
const ident = classifyQuotaPoolIdentity({
|
||||
groupName: grp?.displayName,
|
||||
groupDesc: grp?.description,
|
||||
bucketId: b?.bucketId,
|
||||
bucketName: b?.displayName,
|
||||
});
|
||||
const win = classifyOfficialBucketWindow(b, grpBuckets.length, nowForQuotaMs);
|
||||
const entry = {
|
||||
...norm,
|
||||
bucketId: b?.bucketId || '',
|
||||
groupName: grp?.displayName || ident.poolLabel,
|
||||
window: win,
|
||||
};
|
||||
if (b?.bucketId) {
|
||||
officialBuckets.set(b.bucketId, entry);
|
||||
}
|
||||
const builder = ensurePoolBuilder(ident);
|
||||
if (win === '5h' && !builder.bucket5h) {
|
||||
builder.bucket5h = entry;
|
||||
} else if (win === 'weekly' && !builder.bucketWeekly) {
|
||||
builder.bucketWeekly = entry;
|
||||
} else if (!builder.bucketWeekly) {
|
||||
builder.bucketWeekly = entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 注册动态模型字典,并采样 Argon 与标准 Gemini 的单模型 quotaInfo
|
||||
let sampleArgonCfgQuota = null;
|
||||
let sampleStdGeminiCfgQuota = null;
|
||||
|
||||
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 cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
|
||||
if (!cfgQuota || info.family !== 'Gemini') continue;
|
||||
if (isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) {
|
||||
if (!sampleArgonCfgQuota) sampleArgonCfgQuota = cfgQuota;
|
||||
} else if (!sampleStdGeminiCfgQuota) {
|
||||
sampleStdGeminiCfgQuota = cfgQuota;
|
||||
}
|
||||
}
|
||||
|
||||
// Pro 账号回退检测:若 RetrieveUserQuotaSummary 未单独列出 Argon 分组,
|
||||
// 但 GetUserStatus 中 Argon 模型的 quotaInfo 与标准 Gemini 明显分离,则合成独立 Argon 周限池
|
||||
if (!poolBuilders.has('Argon') && sampleArgonCfgQuota) {
|
||||
const geminiBuilder = poolBuilders.get('Gemini');
|
||||
const hasGeminiBaseline = Boolean(
|
||||
sampleStdGeminiCfgQuota || geminiBuilder?.bucket5h || geminiBuilder?.bucketWeekly
|
||||
);
|
||||
const matchesSharedGemini =
|
||||
quotaFractionsMatch(sampleArgonCfgQuota, sampleStdGeminiCfgQuota) ||
|
||||
quotaFractionsMatch(sampleArgonCfgQuota, geminiBuilder?.bucket5h) ||
|
||||
quotaFractionsMatch(sampleArgonCfgQuota, geminiBuilder?.bucketWeekly);
|
||||
|
||||
if (hasGeminiBaseline && !matchesSharedGemini) {
|
||||
const argonBuilder = ensurePoolBuilder({
|
||||
poolKey: 'Argon',
|
||||
poolLabel: 'Gemini 4 Argon',
|
||||
poolName: 'Gemini 4 Argon 模型池',
|
||||
});
|
||||
argonBuilder.bucketWeekly = {
|
||||
...sampleArgonCfgQuota,
|
||||
bucketId: 'argon-weekly-inferred',
|
||||
groupName: 'Gemini 4 Argon',
|
||||
window: 'weekly',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const hasDedicatedArgonPool = poolBuilders.has('Argon');
|
||||
const modelQuotas = [];
|
||||
|
||||
for (const cfg of clientConfigs) {
|
||||
const rawKey = cfg?.modelOrAlias?.model;
|
||||
const info = resolveModelInfo(rawKey, dynamicModelMap);
|
||||
const isArgon = isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId);
|
||||
const isGemini = info.family === 'Gemini';
|
||||
const targetIdent =
|
||||
isArgon && hasDedicatedArgonPool
|
||||
? { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', poolName: 'Gemini 4 Argon 模型池' }
|
||||
: isGemini
|
||||
? { poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' }
|
||||
: { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', poolName: 'Claude & GPT 模型池' };
|
||||
|
||||
const builder = ensurePoolBuilder(targetIdent);
|
||||
if (cfg?.label && !builder.models.includes(cfg.label)) {
|
||||
builder.models.push(cfg.label);
|
||||
}
|
||||
|
||||
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
|
||||
if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
|
||||
if (targetIdent.poolKey === 'Argon') {
|
||||
builder.bucketWeekly = cfgQuota;
|
||||
} else {
|
||||
builder.fallback5h = cfgQuota;
|
||||
}
|
||||
}
|
||||
|
||||
const eff5h = builder.bucket5h || (!builder.bucketWeekly ? cfgQuota : null);
|
||||
const effWk = builder.bucketWeekly;
|
||||
const hasValid5h = Boolean(eff5h);
|
||||
modelQuotas.push({
|
||||
label: cfg.label,
|
||||
modelId: cfg.modelId,
|
||||
rawKey,
|
||||
family: targetIdent.poolKey,
|
||||
isAvailable: Boolean(eff5h || effWk || cfgQuota),
|
||||
remainingPct: hasValid5h ? eff5h.remainingPct : null,
|
||||
remainingIntPct: hasValid5h ? eff5h.remainingIntPct : null,
|
||||
usedPct: hasValid5h ? eff5h.usedPct : null,
|
||||
resetTime: hasValid5h ? eff5h.resetTime : null,
|
||||
weeklyRemainingPct: effWk?.remainingPct ?? null,
|
||||
weeklyRemainingIntPct: effWk?.remainingIntPct ?? null,
|
||||
weeklyUsedPct: effWk?.usedPct ?? null,
|
||||
weeklyResetTime: effWk?.resetTime || null,
|
||||
});
|
||||
}
|
||||
|
||||
// 确保基础的 Gemini 与 Claude & GPT 模型池始终存在
|
||||
ensurePoolBuilder({ poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' });
|
||||
ensurePoolBuilder({
|
||||
poolKey: 'Claude & GPT',
|
||||
poolLabel: 'Claude & GPT',
|
||||
poolName: 'Claude & GPT 模型池',
|
||||
});
|
||||
|
||||
const quotaPoolsMap = new Map();
|
||||
for (const [poolKey, builder] of poolBuilders.entries()) {
|
||||
const b5h = builder.bucket5h || builder.fallback5h || null;
|
||||
const bWk = builder.bucketWeekly || null;
|
||||
quotaPoolsMap.set(poolKey, {
|
||||
poolKey,
|
||||
poolLabel: builder.poolLabel,
|
||||
poolName: builder.poolName,
|
||||
family: poolKey,
|
||||
isAvailable: Boolean(b5h || bWk),
|
||||
has5h: Boolean(b5h),
|
||||
hasWeekly: Boolean(bWk),
|
||||
remainingPct: b5h?.remainingPct ?? null,
|
||||
remainingIntPct: b5h?.remainingIntPct ?? null,
|
||||
usedPct: b5h?.usedPct ?? null,
|
||||
resetTime: b5h?.resetTime || null,
|
||||
weeklyRemainingPct: bWk?.remainingPct ?? null,
|
||||
weeklyRemainingIntPct: bWk?.remainingIntPct ?? null,
|
||||
weeklyUsedPct: bWk?.usedPct ?? null,
|
||||
weeklyResetTime: bWk?.resetTime || null,
|
||||
models: builder.models,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
dynamicModelMap,
|
||||
quotaPoolsMap,
|
||||
modelQuotas,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
/**
|
||||
* @fileoverview 遥测载荷组装器与并发请求合并入口。
|
||||
*
|
||||
* 将原来超过 1,000 行的 `buildTelemetryPayloadInternal` 拆解为清晰的子阶段:
|
||||
* 1. 拉取用户状态、轨迹摘要与官方实时配额摘要(含账号切换自动穿透缓存);
|
||||
* 2. 调用 `buildOfficialQuotaPools` 构建动态模型映射与多模型配额池;
|
||||
* 3. 调用 `enumerateAndSyncConversations` 枚举会话并增量更新轨迹缓存;
|
||||
* 4. 调用 `enrichActiveConversationSteps` 与 `extractActiveContextTelemetry` 计算当前活跃会话指标与上下文拆解;
|
||||
* 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装最终前端遥测 JSON。
|
||||
*/
|
||||
|
||||
import { statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
parseIsoMs,
|
||||
speedMetric,
|
||||
summarizeSpeed,
|
||||
summarizeTtft,
|
||||
} from '../speed-metrics.mjs';
|
||||
import {
|
||||
HERE,
|
||||
inFlightRequests,
|
||||
loadSettings,
|
||||
quotaSummaryCache,
|
||||
roundMetric,
|
||||
trajectoryCache,
|
||||
} from './config.mjs';
|
||||
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
||||
import { callLsRpc, diagnostics, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||
import {
|
||||
computeStepCost,
|
||||
isArgonModelIdentifier,
|
||||
resolveModelInfo,
|
||||
} from './model-pricing.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import {
|
||||
aggregateMultiWindowUsage,
|
||||
getNextMondayResetIso,
|
||||
} from './usage-aggregator.mjs';
|
||||
|
||||
/**
|
||||
* 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标。
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {Map<string, object>} dynamicModelMap 动态模型字典
|
||||
*/
|
||||
export function enrichActiveConversationSteps(activeSteps, dynamicModelMap) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
let sessionCostUsd = 0;
|
||||
let sessionUnpricedCalls = 0;
|
||||
let sessionInputTokens = 0;
|
||||
let sessionCacheReadTokens = 0;
|
||||
|
||||
// 记录已知的 modelKey -> 最近观测到的上游 responseModel,避免正在生成的步骤因尚未收到 generatorMetadata 而闪烁
|
||||
const knownUpstreamByModelKey = new Map();
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
for (const s of entry?.steps || []) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const s of activeSteps) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
}
|
||||
}
|
||||
|
||||
const enrichedActiveSteps = activeSteps.map((st) => {
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const costUsd = computeStepCost(st, mInfo.pricing);
|
||||
const metric = speedMetric(st);
|
||||
|
||||
sessionCostUsd += costUsd ?? 0;
|
||||
if (costUsd === null) sessionUnpricedCalls++;
|
||||
sessionInputTokens += st.inputTokens;
|
||||
sessionCacheReadTokens += st.cacheReadTokens;
|
||||
|
||||
const tokPerSec = metric.value;
|
||||
const totalPrompt = st.inputTokens + st.cacheReadTokens;
|
||||
const cacheHitPct = totalPrompt > 0 ? (st.cacheReadTokens / totalPrompt) * 100 : 0;
|
||||
|
||||
const inCostUsd = mInfo.pricing ? (st.inputTokens / 1_000_000) * mInfo.pricing.input : null;
|
||||
const cacheCostUsd = mInfo.pricing
|
||||
? (st.cacheReadTokens / 1_000_000) * mInfo.pricing.cache
|
||||
: null;
|
||||
const outCostUsd = mInfo.pricing ? (st.outputTokens / 1_000_000) * mInfo.pricing.output : null;
|
||||
const resolvedResponseModel =
|
||||
st.responseModel ||
|
||||
(st.modelKey && st.modelKey !== 'unknown'
|
||||
? knownUpstreamByModelKey.get(st.modelKey) || ''
|
||||
: '');
|
||||
const rawUpstreamModel =
|
||||
resolvedResponseModel ||
|
||||
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName);
|
||||
const modelUpstream = st.isCompactionStep ? `${rawUpstreamModel}·压缩` : rawUpstreamModel;
|
||||
|
||||
return {
|
||||
...st,
|
||||
responseModel: st.responseModel || '',
|
||||
modelUpstream,
|
||||
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
|
||||
modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
|
||||
family: mInfo.family,
|
||||
tokPerSec: roundMetric(tokPerSec),
|
||||
selectedSpeedReason: metric.reason,
|
||||
ttftSec: st.nativeTtftSec,
|
||||
cacheHitPct: +cacheHitPct.toFixed(1),
|
||||
costUsd: costUsd === null ? null : +costUsd.toFixed(4),
|
||||
inCostUsd: inCostUsd === null ? null : +inCostUsd.toFixed(4),
|
||||
cacheCostUsd: cacheCostUsd === null ? null : +cacheCostUsd.toFixed(4),
|
||||
outCostUsd: outCostUsd === null ? null : +outCostUsd.toFixed(4),
|
||||
contextTokens: st.inputTokens + st.cacheReadTokens + st.outputTokens,
|
||||
};
|
||||
});
|
||||
|
||||
const latestEnriched =
|
||||
enrichedActiveSteps.length > 0 ? enrichedActiveSteps[enrichedActiveSteps.length - 1] : null;
|
||||
const sessionAvgTokPerSec = roundMetric(sessionSpeed.avgTokPerSec);
|
||||
|
||||
return {
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionSpeed,
|
||||
sessionTtft,
|
||||
sessionAvgTokPerSec,
|
||||
sessionCostUsd,
|
||||
sessionUnpricedCalls,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从当前活跃会话的最新步骤提取上下文 6 维拆解、自动压缩水位与缓存命中率。
|
||||
*
|
||||
* @param {object[]} enrichedActiveSteps
|
||||
* @param {object|null} latestEnriched
|
||||
* @param {number} sessionInputTokens
|
||||
* @param {number} sessionCacheReadTokens
|
||||
*/
|
||||
export function extractActiveContextTelemetry(
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens
|
||||
) {
|
||||
let latestBreakdown = latestEnriched?.contextBreakdown || null;
|
||||
if (!latestBreakdown) {
|
||||
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
||||
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
||||
latestBreakdown = enrichedActiveSteps[i].contextBreakdown;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const ctxMessages = Number(latestBreakdown?.messagesTokens || 0);
|
||||
const ctxSystemTools = Number(latestBreakdown?.systemToolsTokens || 0);
|
||||
const ctxMcpTools = Number(latestBreakdown?.mcpToolsTokens || 0);
|
||||
const ctxSkills = Number(latestBreakdown?.skillsTokens || 0);
|
||||
const ctxSystemPrompt = Number(latestBreakdown?.systemPromptTokens || 0);
|
||||
const ctxUserRules = Number(latestBreakdown?.userRulesTokens || 0);
|
||||
const ctxBreakdownTotal =
|
||||
ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules;
|
||||
|
||||
const ctxCached = latestEnriched?.cacheReadTokens || 0;
|
||||
const ctxFreshInput = latestEnriched?.inputTokens || 0;
|
||||
const ctxThinking = latestEnriched?.thinkingTokens || 0;
|
||||
const ctxResponse = latestEnriched?.responseTokens || 0;
|
||||
const ctxTotal =
|
||||
ctxBreakdownTotal > 0 ? ctxBreakdownTotal : ctxCached + ctxFreshInput + ctxThinking + ctxResponse;
|
||||
const compactionLimitTokens = Number(latestEnriched?.maxContextBudgetTokens || 256000);
|
||||
const compactionUsedTokens = Number(
|
||||
latestEnriched?.estimatedContextTokens || ctxBreakdownTotal || ctxCached + ctxFreshInput
|
||||
);
|
||||
const compactionUsedPct =
|
||||
compactionLimitTokens > 0
|
||||
? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1))
|
||||
: 0;
|
||||
|
||||
const ctxLimit = compactionLimitTokens;
|
||||
const ctxPct = ctxLimit > 0 ? Math.min(100, +((ctxTotal / ctxLimit) * 100).toFixed(1)) : 0;
|
||||
|
||||
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;
|
||||
|
||||
return {
|
||||
latestCacheHitPct,
|
||||
sessionCacheHitPct,
|
||||
context: {
|
||||
totalTokens: ctxTotal,
|
||||
limitTokens: ctxLimit,
|
||||
usedPct: ctxPct,
|
||||
compactionUsedTokens,
|
||||
compactionLimitTokens,
|
||||
compactionUsedPct,
|
||||
messagesTokens: ctxMessages,
|
||||
systemToolsTokens: ctxSystemTools,
|
||||
mcpToolsTokens: ctxMcpTools,
|
||||
skillsTokens: ctxSkills,
|
||||
systemPromptTokens: ctxSystemPrompt,
|
||||
userRulesTokens: ctxUserRules,
|
||||
cachedTokens: ctxCached,
|
||||
freshInputTokens: ctxFreshInput,
|
||||
thinkingTokens: ctxThinking,
|
||||
responseTokens: ctxResponse,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。
|
||||
*
|
||||
* @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话)
|
||||
* @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额 10 秒缓存
|
||||
* @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function buildTelemetryPayloadInternal(
|
||||
requestedConvId,
|
||||
forceQuotaRefresh = false,
|
||||
filterOpts = {}
|
||||
) {
|
||||
const settings = loadSettings();
|
||||
const [userStatusRes, allTrajRes, initialOfficialQuotaInfo] = await Promise.all([
|
||||
callLsRpc('GetUserStatus', {}).catch(() => ({})),
|
||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||
getOfficialQuotaSummary(forceQuotaRefresh),
|
||||
]);
|
||||
|
||||
const userStatus = userStatusRes?.userStatus || {};
|
||||
const currentAccountName = userStatus?.email || userStatus?.name || '';
|
||||
let officialQuotaInfo = initialOfficialQuotaInfo;
|
||||
|
||||
// 若检测到登录账号在 10 秒缓存期内发生切换,立即强制刷新配额摘要
|
||||
if (
|
||||
currentAccountName &&
|
||||
quotaSummaryCache.accountName &&
|
||||
quotaSummaryCache.accountName !== currentAccountName
|
||||
) {
|
||||
officialQuotaInfo = await getOfficialQuotaSummary(true);
|
||||
}
|
||||
if (currentAccountName && officialQuotaInfo?.data) {
|
||||
quotaSummaryCache.accountName = currentAccountName;
|
||||
}
|
||||
|
||||
const officialQuota = officialQuotaInfo?.data || null;
|
||||
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
|
||||
|
||||
// 1. 构建官方实时配额池与动态模型目录
|
||||
const { dynamicModelMap, quotaPoolsMap, modelQuotas } = buildOfficialQuotaPools(
|
||||
officialQuota,
|
||||
clientConfigs
|
||||
);
|
||||
|
||||
// 2. 枚举本地与 LS 会话,并增量同步历史轨迹步骤
|
||||
const { conversations, activeConvSummary, activeCascadeId } =
|
||||
await enumerateAndSyncConversations({
|
||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
||||
currentAccountName,
|
||||
requestedConvId,
|
||||
});
|
||||
|
||||
// 3. 计算当前活跃会话的步骤指标与上下文拆解
|
||||
const activeEntry = activeCascadeId ? trajectoryCache[activeCascadeId] : null;
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
const {
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionSpeed,
|
||||
sessionTtft,
|
||||
sessionAvgTokPerSec,
|
||||
sessionCostUsd,
|
||||
sessionUnpricedCalls,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens,
|
||||
} = enrichActiveConversationSteps(activeSteps, dynamicModelMap);
|
||||
|
||||
const { latestCacheHitPct, sessionCacheHitPct, context } = extractActiveContextTelemetry(
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens
|
||||
);
|
||||
|
||||
// 4. 识别当前活跃会话绑定的模型池及其官方 5h / 周限重置锚点
|
||||
const latestIsArgon = latestEnriched
|
||||
? isArgonModelIdentifier(
|
||||
latestEnriched.modelKey,
|
||||
latestEnriched.responseModel,
|
||||
latestEnriched.modelUpstream,
|
||||
latestEnriched.modelLabel
|
||||
)
|
||||
: false;
|
||||
const rawActiveFamily = latestEnriched?.family || 'Other';
|
||||
const activePoolKey =
|
||||
latestIsArgon && quotaPoolsMap.has('Argon')
|
||||
? 'Argon'
|
||||
: rawActiveFamily === 'Gemini'
|
||||
? 'Gemini'
|
||||
: ['Claude', 'GPT'].includes(rawActiveFamily)
|
||||
? 'Claude & GPT'
|
||||
: 'Unknown';
|
||||
const matchedActivePool = quotaPoolsMap.get(activePoolKey) || null;
|
||||
const activeLive5h = matchedActivePool?.has5h
|
||||
? {
|
||||
remainingPct: matchedActivePool.remainingPct,
|
||||
remainingIntPct: matchedActivePool.remainingIntPct,
|
||||
usedPct: matchedActivePool.usedPct,
|
||||
resetTime: matchedActivePool.resetTime,
|
||||
}
|
||||
: null;
|
||||
const activeLiveWeekly = matchedActivePool?.hasWeekly
|
||||
? {
|
||||
remainingPct: matchedActivePool.weeklyRemainingPct,
|
||||
remainingIntPct: matchedActivePool.weeklyRemainingIntPct,
|
||||
usedPct: matchedActivePool.weeklyUsedPct,
|
||||
resetTime: matchedActivePool.weeklyResetTime,
|
||||
}
|
||||
: null;
|
||||
const cycleAnchors = {
|
||||
fiveHourResetMs: parseIsoMs(activeLive5h?.resetTime),
|
||||
weeklyResetMs: parseIsoMs(activeLiveWeekly?.resetTime),
|
||||
};
|
||||
|
||||
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 12 段趋势 + 月序列 + 来源与模型拆解)
|
||||
const {
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
trendEndMs,
|
||||
finalizedSelectedSession,
|
||||
finalizedSelectedAccount,
|
||||
finalizedPresets,
|
||||
trendSeries,
|
||||
sourcesBreakdown,
|
||||
currentYear,
|
||||
monthlySeries,
|
||||
todayBucket,
|
||||
weekBucket,
|
||||
modelBreakdown,
|
||||
} = aggregateMultiWindowUsage({
|
||||
filterOpts,
|
||||
cycleAnchors,
|
||||
currentAccountName,
|
||||
activeCascadeId,
|
||||
dynamicModelMap,
|
||||
});
|
||||
|
||||
// 6. 组装当前活跃配额池与每周限额视图数据
|
||||
const familyPoolQuota = quotaPoolsMap.get(activePoolKey);
|
||||
const activePoolLabel = familyPoolQuota?.poolLabel || activePoolKey;
|
||||
const activePoolQuota = familyPoolQuota || {
|
||||
poolKey: activePoolKey,
|
||||
poolLabel: activePoolKey === 'Unknown' ? '未知' : activePoolKey,
|
||||
poolName:
|
||||
activePoolKey === 'Argon'
|
||||
? 'Gemini 4 Argon 模型池'
|
||||
: activePoolKey === 'Gemini'
|
||||
? 'Gemini 模型池'
|
||||
: activePoolKey === 'Claude & GPT'
|
||||
? 'Claude & GPT 模型池'
|
||||
: '模型池未知',
|
||||
family: activePoolKey,
|
||||
isAvailable: Boolean(activeLive5h || activeLiveWeekly),
|
||||
has5h: Boolean(activeLive5h),
|
||||
hasWeekly: Boolean(activeLiveWeekly),
|
||||
remainingPct: activeLive5h?.remainingPct ?? null,
|
||||
remainingIntPct: activeLive5h?.remainingIntPct ?? null,
|
||||
usedPct: activeLive5h?.usedPct ?? null,
|
||||
resetTime: activeLive5h?.resetTime || null,
|
||||
weeklyRemainingPct: activeLiveWeekly?.remainingPct ?? null,
|
||||
weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? null,
|
||||
weeklyUsedPct: activeLiveWeekly?.usedPct ?? null,
|
||||
weeklyResetTime: activeLiveWeekly?.resetTime || null,
|
||||
models: [],
|
||||
};
|
||||
|
||||
const fallbackWeeklyPct =
|
||||
settings.weeklyLimitMode === 'custom_cost' || settings.weeklyLimitMode === 'cost'
|
||||
? weekBucket.unpricedCalls > 0
|
||||
? null
|
||||
: Math.min(
|
||||
100,
|
||||
+((weekBucket.costUsd / Math.max(1, settings.weeklyCostBudget)) * 100).toFixed(1)
|
||||
)
|
||||
: Math.min(
|
||||
100,
|
||||
+((weekBucket.totalTokens / Math.max(1000, settings.weeklyTokenBudget)) * 100).toFixed(1)
|
||||
);
|
||||
|
||||
const isCustomWeeklyMode =
|
||||
settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost';
|
||||
const useOfficialWeekly = Boolean(activeLiveWeekly) && !isCustomWeeklyMode;
|
||||
|
||||
const weeklyUsedPct = useOfficialWeekly
|
||||
? activeLiveWeekly.usedPct
|
||||
: isCustomWeeklyMode
|
||||
? fallbackWeeklyPct
|
||||
: null;
|
||||
const weeklyRemainingPct = useOfficialWeekly
|
||||
? activeLiveWeekly.remainingPct
|
||||
: isCustomWeeklyMode && fallbackWeeklyPct !== null
|
||||
? +(100 - fallbackWeeklyPct).toFixed(1)
|
||||
: null;
|
||||
const weeklyRemainingIntPct = useOfficialWeekly
|
||||
? activeLiveWeekly.remainingIntPct
|
||||
: isCustomWeeklyMode && fallbackWeeklyPct !== null
|
||||
? Math.max(0, Math.floor(100 - fallbackWeeklyPct))
|
||||
: null;
|
||||
|
||||
// 提取真实的 Google One AI Credits(忽略旧版硬编码的 500 prompt credits)
|
||||
const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find(
|
||||
(c) => c?.creditType === 'GOOGLE_ONE_AI'
|
||||
);
|
||||
const realAiCredits = Number(g1CreditEntry?.creditAmount || 0);
|
||||
|
||||
let uiBundleVersion = 0;
|
||||
try {
|
||||
uiBundleVersion = statSync(join(HERE, 'app.js')).mtimeMs || 0;
|
||||
} catch {
|
||||
// 忽略 stat 异常
|
||||
}
|
||||
|
||||
return {
|
||||
timestamp: new Date().toISOString(),
|
||||
uiBundleVersion,
|
||||
settings,
|
||||
cloudStatus: getCloudStatus(),
|
||||
diagnostics: diagnostics.status(),
|
||||
account: {
|
||||
name: userStatus?.name || '',
|
||||
tierName: userStatus?.userTier?.name || 'Google AI',
|
||||
planName: userStatus?.planStatus?.planInfo?.planName || 'Pro',
|
||||
aiCredits: realAiCredits > 0 ? realAiCredits : null,
|
||||
totalConversations: conversations.length,
|
||||
},
|
||||
conversations: conversations.slice(0, 30),
|
||||
activeConversation: {
|
||||
cascadeId: activeCascadeId,
|
||||
title: activeConvSummary?.title || '当前会话',
|
||||
isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
avgTokPerSec: sessionAvgTokPerSec,
|
||||
speedSummary: sessionSpeed,
|
||||
ttftSummary: sessionTtft,
|
||||
latestStepCostUsd: latestEnriched?.costUsd ?? null,
|
||||
sessionCostUsd: +sessionCostUsd.toFixed(2),
|
||||
sessionUnpricedCalls,
|
||||
latestCacheHitPct,
|
||||
sessionCacheHitPct,
|
||||
activeModelShort: latestEnriched?.modelShort || '模型未知',
|
||||
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
||||
context,
|
||||
recentSteps: enrichedActiveSteps.slice().reverse(),
|
||||
},
|
||||
consumption: {
|
||||
selectedRange: {
|
||||
key: selectedWindow.key,
|
||||
label: selectedWindow.label,
|
||||
startMs: trendStartMs,
|
||||
endMs: trendEndMs,
|
||||
},
|
||||
session: finalizedSelectedSession,
|
||||
sessionAllTime: finalizedPresets.all.session,
|
||||
account: finalizedSelectedAccount,
|
||||
accountAllTime: finalizedPresets.all.account,
|
||||
presets: finalizedPresets,
|
||||
trendSeries,
|
||||
sourcesBreakdown,
|
||||
monthlyYear: currentYear,
|
||||
monthlySeries,
|
||||
},
|
||||
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,
|
||||
pools: Array.from(quotaPoolsMap.values()).sort((a, b) => {
|
||||
const order = { Gemini: 0, Argon: 1, 'Claude & GPT': 2 };
|
||||
return (order[a.family] ?? 99) - (order[b.family] ?? 99);
|
||||
}),
|
||||
models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))),
|
||||
weekly: {
|
||||
isOfficial: useOfficialWeekly,
|
||||
poolFamily: activePoolKey,
|
||||
title: isCustomWeeklyMode
|
||||
? '每周限额 (自定义本机)'
|
||||
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
|
||||
calls: weekBucket.calls,
|
||||
tokens: weekBucket.totalTokens,
|
||||
costUsd: weekBucket.costUsd,
|
||||
unpricedCalls: weekBucket.unpricedCalls,
|
||||
usedPct: weeklyUsedPct,
|
||||
remainingPct: weeklyRemainingPct,
|
||||
remainingIntPct: weeklyRemainingIntPct,
|
||||
resetTime: useOfficialWeekly
|
||||
? activeLiveWeekly.resetTime
|
||||
: isCustomWeeklyMode
|
||||
? getNextMondayResetIso()
|
||||
: null,
|
||||
},
|
||||
today: {
|
||||
calls: todayBucket.calls,
|
||||
tokens: todayBucket.totalTokens,
|
||||
costUsd: todayBucket.costUsd,
|
||||
unpricedCalls: todayBucket.unpricedCalls,
|
||||
},
|
||||
},
|
||||
modelBreakdown,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 带并发请求合并(In-Flight Deduplication)的遥测载荷构建入口。
|
||||
* 当相同会话、刷新模式与时间范围的请求正在处理中时,直接复用同一个 Promise。
|
||||
*
|
||||
* @param {string} requestedConvId
|
||||
* @param {boolean} [forceQuotaRefresh=false]
|
||||
* @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}]
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export function buildTelemetryPayload(
|
||||
requestedConvId,
|
||||
forceQuotaRefresh = false,
|
||||
filterOpts = {}
|
||||
) {
|
||||
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
|
||||
const key = `${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`;
|
||||
if (inFlightRequests.has(key)) {
|
||||
return inFlightRequests.get(key);
|
||||
}
|
||||
const p = buildTelemetryPayloadInternal(requestedConvId, forceQuotaRefresh, filterOpts).finally(
|
||||
() => {
|
||||
inFlightRequests.delete(key);
|
||||
}
|
||||
);
|
||||
inFlightRequests.set(key, p);
|
||||
return p;
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
/**
|
||||
* @fileoverview 多时间窗口解析、用量桶累加、12 段趋势序列、月度序列与分模型/分来源聚合引擎。
|
||||
*
|
||||
* 负责将内存缓存 (`trajectoryCache`) 与外部深层统计缓存 (`loadExternalDeepStatsCache`)
|
||||
* 中的所有步骤按预设窗口(`all`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口
|
||||
* 进行一次遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。
|
||||
*/
|
||||
|
||||
import {
|
||||
accumulateSpeed,
|
||||
createSpeedAccumulator,
|
||||
finishSpeed,
|
||||
} from '../speed-metrics.mjs';
|
||||
import { roundMetric, trajectoryCache } from './config.mjs';
|
||||
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
||||
import { computeStepCost, resolveModelInfo } from './model-pricing.mjs';
|
||||
|
||||
/**
|
||||
* 获取本地当日 00:00:00.000 的毫秒时间戳。
|
||||
*
|
||||
* @param {Date|number} [now=new Date()]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function getStartOfLocalDayMs(now = new Date()) {
|
||||
const d = new Date(now);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本地下一个周一 00:00:00.000 的 ISO 时间字符串(用于自定义本机周限额重置倒计时)。
|
||||
*
|
||||
* @param {Date|number} [now=new Date()]
|
||||
* @returns {string}
|
||||
*/
|
||||
export 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本地本周一 00:00:00.000 的毫秒时间戳。
|
||||
*
|
||||
* @param {Date|number} [now=new Date()]
|
||||
* @returns {number}
|
||||
*/
|
||||
export 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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据时间范围键名 (`rangeKey`) 与官方配额重置锚点 (`cycleAnchors`) 解析起止毫秒时间戳。
|
||||
*
|
||||
* @param {string} [rangeKey='all']
|
||||
* @param {number} [customStartMs=0]
|
||||
* @param {number} [customEndMs=0]
|
||||
* @param {number} [nowMs=Date.now()]
|
||||
* @param {{ fiveHourResetMs?: number, weeklyResetMs?: number }} [cycleAnchors={}]
|
||||
* @returns {{ key: string, label: string, startMs: number, endMs: number }}
|
||||
*/
|
||||
export function resolveTimeWindow(
|
||||
rangeKey = 'all',
|
||||
customStartMs = 0,
|
||||
customEndMs = 0,
|
||||
nowMs = Date.now(),
|
||||
cycleAnchors = {}
|
||||
) {
|
||||
const now = new Date(nowMs);
|
||||
switch (rangeKey) {
|
||||
case '5h': {
|
||||
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':
|
||||
return { key: 'today', label: '今日', startMs: getStartOfLocalDayMs(now), endMs: nowMs };
|
||||
case '24h':
|
||||
return { key: '24h', label: '近 24 小时', startMs: nowMs - 24 * 3600 * 1000, endMs: nowMs };
|
||||
case 'week': {
|
||||
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':
|
||||
return { key: '7d', label: '近 7 天', startMs: nowMs - 7 * 24 * 3600 * 1000, endMs: nowMs };
|
||||
case '14d':
|
||||
return {
|
||||
key: '14d',
|
||||
label: '近 14 天',
|
||||
startMs: nowMs - 14 * 24 * 3600 * 1000,
|
||||
endMs: nowMs,
|
||||
};
|
||||
case '30d':
|
||||
return {
|
||||
key: '30d',
|
||||
label: '近 30 天',
|
||||
startMs: nowMs - 30 * 24 * 3600 * 1000,
|
||||
endMs: nowMs,
|
||||
};
|
||||
case 'custom': {
|
||||
const s = Number(customStartMs) > 0 ? Number(customStartMs) : 0;
|
||||
const e = Number(customEndMs) > 0 ? Number(customEndMs) : nowMs;
|
||||
return {
|
||||
key: 'custom',
|
||||
label: '自定义时段',
|
||||
startMs: Math.min(s, e),
|
||||
endMs: Math.max(s, e),
|
||||
};
|
||||
}
|
||||
case 'all':
|
||||
default:
|
||||
return { key: 'all', label: '全部时间', startMs: 0, endMs: Infinity };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个空的用量统计累加桶。
|
||||
*/
|
||||
export function createUsageBucket() {
|
||||
return {
|
||||
calls: 0,
|
||||
conversationsSet: new Set(),
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
savedCostUsd: 0,
|
||||
geminiTokens: 0,
|
||||
geminiCostUsd: 0,
|
||||
geminiCalls: 0,
|
||||
claudeGptTokens: 0,
|
||||
claudeGptCostUsd: 0,
|
||||
claudeGptCalls: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单个模型步骤的 Token 与成本累加至目标统计桶。
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
* @param {object} st 步骤对象
|
||||
* @param {ReturnType<typeof resolveModelInfo>} mInfo 模型信息
|
||||
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
||||
* @param {string} cascadeId 会话标识
|
||||
*/
|
||||
export function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) {
|
||||
const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens;
|
||||
const savedCost = mInfo.pricing
|
||||
? (st.cacheReadTokens / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||
: 0;
|
||||
if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||
const resolvedCost = stepCost ?? 0;
|
||||
bucket.calls += 1;
|
||||
if (cascadeId) bucket.conversationsSet.add(cascadeId);
|
||||
bucket.inputTokens += st.inputTokens;
|
||||
bucket.cacheReadTokens += st.cacheReadTokens;
|
||||
bucket.outputTokens += st.outputTokens;
|
||||
bucket.thinkingTokens += st.thinkingTokens || 0;
|
||||
bucket.responseTokens += st.responseTokens || 0;
|
||||
bucket.totalTokens += stepTotalTokens;
|
||||
bucket.costUsd += resolvedCost;
|
||||
bucket.savedCostUsd += savedCost;
|
||||
|
||||
if (mInfo.family === 'Gemini') {
|
||||
bucket.geminiTokens += stepTotalTokens;
|
||||
bucket.geminiCostUsd += resolvedCost;
|
||||
bucket.geminiCalls += 1;
|
||||
} else if (mInfo.family === 'Claude' || mInfo.family === 'GPT') {
|
||||
bucket.claudeGptTokens += stepTotalTokens;
|
||||
bucket.claudeGptCostUsd += resolvedCost;
|
||||
bucket.claudeGptCalls += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将累加完成的用量桶定型为可序列化的前端统计结构(计算缓存命中率并舍入金额)。
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
*/
|
||||
export function finalizeUsageBucket(bucket) {
|
||||
const promptTokens = bucket.inputTokens + bucket.cacheReadTokens;
|
||||
const cacheHitPct =
|
||||
promptTokens > 0 ? +((bucket.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0;
|
||||
return {
|
||||
calls: bucket.calls,
|
||||
conversationsCount: bucket.conversationsSet.size,
|
||||
inputTokens: bucket.inputTokens,
|
||||
cacheReadTokens: bucket.cacheReadTokens,
|
||||
outputTokens: bucket.outputTokens,
|
||||
thinkingTokens: bucket.thinkingTokens,
|
||||
responseTokens: bucket.responseTokens,
|
||||
totalTokens: bucket.totalTokens,
|
||||
costUsd: +bucket.costUsd.toFixed(2),
|
||||
unpricedCalls: bucket.unpricedCalls || 0,
|
||||
savedCostUsd: +bucket.savedCostUsd.toFixed(2),
|
||||
cacheHitPct,
|
||||
geminiTokens: bucket.geminiTokens,
|
||||
geminiCostUsd: +bucket.geminiCostUsd.toFixed(2),
|
||||
geminiCalls: bucket.geminiCalls,
|
||||
claudeGptTokens: bucket.claudeGptTokens,
|
||||
claudeGptCostUsd: +bucket.claudeGptCostUsd.toFixed(2),
|
||||
claudeGptCalls: bucket.claudeGptCalls,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合所有预设时间窗口、当前选定窗口、12 段趋势图、年度月序列、来源占比与分模型统计。
|
||||
*
|
||||
* @param {{
|
||||
* filterOpts?: { range?: string, startMs?: number, endMs?: number },
|
||||
* cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number },
|
||||
* currentAccountName?: string,
|
||||
* activeCascadeId?: string|null,
|
||||
* dynamicModelMap: Map<string, object>
|
||||
* }} params
|
||||
*/
|
||||
export function aggregateMultiWindowUsage({
|
||||
filterOpts = {},
|
||||
cycleAnchors = {},
|
||||
currentAccountName = '',
|
||||
activeCascadeId = null,
|
||||
dynamicModelMap,
|
||||
}) {
|
||||
const nowMs = Date.now();
|
||||
const selectedWindow = resolveTimeWindow(
|
||||
filterOpts.range || 'all',
|
||||
filterOpts.startMs,
|
||||
filterOpts.endMs,
|
||||
nowMs,
|
||||
cycleAnchors
|
||||
);
|
||||
|
||||
const presetKeys = ['all', '5h', 'today', '24h', 'week', '7d', '14d', '30d'];
|
||||
const presetWindows = {};
|
||||
const accountBuckets = {};
|
||||
const sessionBuckets = {};
|
||||
|
||||
for (const k of presetKeys) {
|
||||
presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors);
|
||||
accountBuckets[k] = createUsageBucket();
|
||||
sessionBuckets[k] = createUsageBucket();
|
||||
}
|
||||
const selectedAccountBucket = createUsageBucket();
|
||||
const selectedSessionBucket = createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
const selectedWindowSteps = [];
|
||||
let earliestSelectedStepMs = Infinity;
|
||||
|
||||
const currentYear = new Date(nowMs).getFullYear();
|
||||
const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({
|
||||
month: idx + 1,
|
||||
label: `${idx + 1}月`,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
responseTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
}));
|
||||
|
||||
const SOURCE_LABELS = {
|
||||
standalone: 'Antigravity App',
|
||||
ide: 'Antigravity IDE',
|
||||
cli: 'Antigravity CLI',
|
||||
};
|
||||
const perSourceStats = new Map();
|
||||
const externalConvos = loadExternalDeepStatsCache();
|
||||
const allEntriesToAggregate = [];
|
||||
|
||||
for (const [cascadeId, entry] of Object.entries(trajectoryCache)) {
|
||||
if (
|
||||
entry?.accountName &&
|
||||
currentAccountName &&
|
||||
entry.accountName !== currentAccountName &&
|
||||
cascadeId !== activeCascadeId
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId,
|
||||
appSource: entry?.appSource || 'standalone',
|
||||
steps: entry?.steps || [],
|
||||
isCurrentConv: cascadeId === activeCascadeId,
|
||||
});
|
||||
}
|
||||
|
||||
for (const ext of externalConvos.values()) {
|
||||
const liveEntry = trajectoryCache[ext.cascadeId];
|
||||
if (
|
||||
ext.appSource === 'standalone' &&
|
||||
liveEntry &&
|
||||
(liveEntry.steps?.length || 0) >= ext.steps.length
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId: `${ext.appSource}:${ext.cascadeId}`,
|
||||
appSource: ext.appSource || 'ide',
|
||||
steps: ext.steps || [],
|
||||
isCurrentConv: ext.cascadeId === activeCascadeId && !liveEntry,
|
||||
});
|
||||
}
|
||||
|
||||
for (const entry of allEntriesToAggregate) {
|
||||
const { cascadeId, isCurrentConv } = entry;
|
||||
const srcKey = entry.appSource || 'standalone';
|
||||
const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
|
||||
|
||||
for (const st of entry.steps || []) {
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens;
|
||||
const stepCost = computeStepCost(st, mInfo.pricing);
|
||||
const unpriced = stepCost === null ? 1 : 0;
|
||||
const tMs = st.createdAtMs || 0;
|
||||
|
||||
if (tMs > 0) {
|
||||
const stepDate = new Date(tMs);
|
||||
if (stepDate.getFullYear() === currentYear) {
|
||||
const mBucket = monthlySeries[stepDate.getMonth()];
|
||||
if (mBucket) {
|
||||
mBucket.calls += 1;
|
||||
mBucket.inputTokens += st.inputTokens || 0;
|
||||
mBucket.cacheReadTokens += st.cacheReadTokens || 0;
|
||||
mBucket.responseTokens += st.responseTokens || 0;
|
||||
mBucket.thinkingTokens += st.thinkingTokens || 0;
|
||||
mBucket.totalTokens += stepTotalTokens;
|
||||
mBucket.costUsd = +(mBucket.costUsd + (stepCost ?? 0)).toFixed(4);
|
||||
mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const k of presetKeys) {
|
||||
const w = presetWindows[k];
|
||||
if (k === 'all' || (tMs >= w.startMs && tMs <= w.endMs)) {
|
||||
accumulateStepIntoBucket(accountBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const inSelectedWindow =
|
||||
selectedWindow.key === 'all' ||
|
||||
(tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
||||
|
||||
if (inSelectedWindow) {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, st, mInfo, stepCost, cascadeId);
|
||||
}
|
||||
if (tMs > 0) {
|
||||
if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs;
|
||||
selectedWindowSteps.push({
|
||||
tMs,
|
||||
tokens: stepTotalTokens,
|
||||
costUsd: stepCost ?? 0,
|
||||
unpricedCalls: unpriced,
|
||||
});
|
||||
}
|
||||
|
||||
if (!perSourceStats.has(srcKey)) {
|
||||
perSourceStats.set(srcKey, {
|
||||
name: srcName,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
responseTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
});
|
||||
}
|
||||
const sAgg = perSourceStats.get(srcKey);
|
||||
sAgg.calls += 1;
|
||||
sAgg.inputTokens += st.inputTokens || 0;
|
||||
sAgg.cacheReadTokens += st.cacheReadTokens || 0;
|
||||
sAgg.responseTokens += st.responseTokens || 0;
|
||||
sAgg.thinkingTokens += st.thinkingTokens || 0;
|
||||
sAgg.totalTokens += stepTotalTokens;
|
||||
sAgg.costUsd += stepCost ?? 0;
|
||||
sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced;
|
||||
|
||||
const modelGroupKey = mInfo.baseLabel || mInfo.label;
|
||||
if (!perModelStats.has(modelGroupKey)) {
|
||||
perModelStats.set(modelGroupKey, {
|
||||
label: modelGroupKey,
|
||||
shortName: mInfo.shortName,
|
||||
fallbackModelId: mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : '',
|
||||
upstreamModelCounts: new Map(),
|
||||
family: mInfo.family,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(modelGroupKey);
|
||||
if (st.responseModel) {
|
||||
agg.upstreamModelCounts.set(
|
||||
st.responseModel,
|
||||
(agg.upstreamModelCounts.get(st.responseModel) || 0) + 1
|
||||
);
|
||||
}
|
||||
accumulateSpeed(agg.speedAccumulator, st);
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += st.inputTokens;
|
||||
agg.cacheReadTokens += st.cacheReadTokens;
|
||||
agg.outputTokens += st.outputTokens;
|
||||
agg.thinkingTokens += st.thinkingTokens || 0;
|
||||
agg.responseTokens += st.responseTokens || 0;
|
||||
agg.totalTokens += stepTotalTokens;
|
||||
agg.costUsd += stepCost ?? 0;
|
||||
agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 构建当前选定时间窗口的 12 段等宽趋势序列 (trendSeries)
|
||||
const trendSlotsCount = 12;
|
||||
const trendEndMs = Number.isFinite(selectedWindow.endMs) ? selectedWindow.endMs : nowMs;
|
||||
const rawTrendStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? Number.isFinite(earliestSelectedStepMs)
|
||||
? earliestSelectedStepMs
|
||||
: nowMs - 24 * 3600 * 1000
|
||||
: selectedWindow.startMs;
|
||||
const trendStartMs = Math.min(rawTrendStartMs, trendEndMs - 60 * 1000);
|
||||
const trendSpanMs = Math.max(60 * 1000, trendEndMs - trendStartMs);
|
||||
const slotWidthMs = trendSpanMs / trendSlotsCount;
|
||||
const isShortSpan = trendSpanMs <= 36 * 3600 * 1000;
|
||||
const pad2 = (n) => String(n).padStart(2, '0');
|
||||
const formatTrendLabel = (ms) => {
|
||||
const d = new Date(ms);
|
||||
if (isShortSpan) {
|
||||
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
||||
}
|
||||
return `${d.getMonth() + 1}/${d.getDate()}`;
|
||||
};
|
||||
|
||||
const trendSeries = Array.from({ length: trendSlotsCount }, (_, idx) => {
|
||||
const sMs = trendStartMs + idx * slotWidthMs;
|
||||
return {
|
||||
index: idx,
|
||||
label: formatTrendLabel(sMs),
|
||||
tokens: 0,
|
||||
costUsd: 0,
|
||||
calls: 0,
|
||||
};
|
||||
});
|
||||
|
||||
for (const item of selectedWindowSteps) {
|
||||
const rawIdx = Math.floor((item.tMs - trendStartMs) / slotWidthMs);
|
||||
const idx = Math.max(0, Math.min(trendSlotsCount - 1, rawIdx));
|
||||
trendSeries[idx].tokens += item.tokens;
|
||||
trendSeries[idx].costUsd = +(trendSeries[idx].costUsd + item.costUsd).toFixed(4);
|
||||
trendSeries[idx].unpricedCalls = (trendSeries[idx].unpricedCalls || 0) + item.unpricedCalls;
|
||||
trendSeries[idx].calls += 1;
|
||||
}
|
||||
|
||||
const finalizedPresets = {};
|
||||
for (const k of presetKeys) {
|
||||
finalizedPresets[k] = {
|
||||
label: presetWindows[k].label,
|
||||
session: finalizeUsageBucket(sessionBuckets[k]),
|
||||
account: finalizeUsageBucket(accountBuckets[k]),
|
||||
};
|
||||
}
|
||||
|
||||
const finalizedSelectedSession = finalizeUsageBucket(selectedSessionBucket);
|
||||
const finalizedSelectedAccount = finalizeUsageBucket(selectedAccountBucket);
|
||||
|
||||
const sourcesBreakdown = Array.from(perSourceStats.values())
|
||||
.filter((s) => s.totalTokens > 0 || s.calls > 0)
|
||||
.map((s) => ({
|
||||
...s,
|
||||
costUsd: +s.costUsd.toFixed(2),
|
||||
}))
|
||||
.sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls);
|
||||
|
||||
const todayBucket = finalizedPresets.today.account;
|
||||
const weekBucket = finalizedPresets.week.account;
|
||||
|
||||
const modelBreakdown = Array.from(perModelStats.values())
|
||||
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
||||
.map(({ speedAccumulator, upstreamModelCounts, fallbackModelId, ...m }) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([name]) => name);
|
||||
const primaryUpstream =
|
||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(3),
|
||||
avgTokPerSec: roundMetric(finishSpeed(speedAccumulator).avgTokPerSec),
|
||||
speedSummary: finishSpeed(speedAccumulator),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
trendEndMs,
|
||||
finalizedSelectedSession,
|
||||
finalizedSelectedAccount,
|
||||
finalizedPresets,
|
||||
trendSeries,
|
||||
sourcesBreakdown,
|
||||
currentYear,
|
||||
monthlySeries,
|
||||
todayBucket,
|
||||
weekBucket,
|
||||
modelBreakdown,
|
||||
};
|
||||
}
|
||||
@@ -3,12 +3,12 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>测速与额度监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1793385657276">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1793683297213">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1793385657276"></script>
|
||||
<script src="/app.js?v=1793683297213"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+125
-1745
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "usage-monitor-panel",
|
||||
"version": "1.3.1",
|
||||
"version": "1.4.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||
|
||||
@@ -14,7 +14,10 @@ const cssOrder = [
|
||||
'src/styles/tokens.css',
|
||||
'src/styles/base.css',
|
||||
'src/styles/animations.css',
|
||||
'src/styles/components.css',
|
||||
'src/styles/controls.css',
|
||||
'src/styles/views-overview.css',
|
||||
'src/styles/views-consumption.css',
|
||||
'src/styles/views-tables.css',
|
||||
];
|
||||
|
||||
const cssBundle =
|
||||
@@ -41,6 +44,8 @@ const jsOrder = [
|
||||
'src/components/ui/CustomScrollbar.js',
|
||||
'src/components/ui/SegmentedControl.js',
|
||||
'src/components/ui/ContextSegmentMeter.js',
|
||||
'src/components/ui/FourSegmentBar.js',
|
||||
'src/components/charts/TrendAreaChart.js',
|
||||
'src/components/layout/TopSessionHeader.js',
|
||||
'src/views/LiveOverviewView.js',
|
||||
'src/views/ConsumptionView.js',
|
||||
|
||||
@@ -2,16 +2,16 @@
|
||||
"command": "node",
|
||||
"args": ["main.mjs"],
|
||||
"restart_policy": "always",
|
||||
"display_name": "测速与额度监控",
|
||||
"description": "实时显示 tok/s 速度、首字耗时、缓存率、上下文占用、5h 限额与周消耗统计。",
|
||||
"display_name": "用量监控",
|
||||
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史消耗。",
|
||||
"has_web_ui": true,
|
||||
"ui_config": {
|
||||
"display_name": "测速与额度监控",
|
||||
"display_name": "用量监控",
|
||||
"views": [
|
||||
{
|
||||
"path": "/",
|
||||
"entrypoint": "SIDECAR_UI_ENTRYPOINT_AUX_PANE",
|
||||
"title": "测速与额度监控"
|
||||
"title": "用量监控"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+554
-118
@@ -1,62 +1,174 @@
|
||||
// Client-observed request throughput, including waiting and thinking.
|
||||
// One formula for text and tools; no rate-based clipping or denominator changes.
|
||||
/**
|
||||
* 客户端观测请求级吞吐率(TPS)、首字延迟(TTFT)、上下文构成拆解与模型身份归因计算模块。
|
||||
*
|
||||
* 核心设计原则:
|
||||
* 1. 采用客户端观测到的端到端请求耗时(包含排队等待、思考与工具调用生成),对纯文本生成与工具调用采用统一公式计算。
|
||||
* 2. 严禁基于速率上限裁剪异常值或动态篡改分母(如扣除思考时间或仅取流式片段耗时),保证统计口径客观一致。
|
||||
*/
|
||||
|
||||
/** 速度测量口径版本号;当耗时或样本过滤算法变更时递增,用于触发旧版缓存测量字段失效重算 */
|
||||
export const MEASUREMENT_VERSION = 4;
|
||||
|
||||
/** 模型身份归因版本号;当模型识别优先级或占位符清洗策略变更时递增 */
|
||||
export const MODEL_IDENTITY_VERSION = 1;
|
||||
|
||||
/** 纳入有效测速的最小请求总耗时阈值(0.5 秒),过滤极短请求因时钟抖动导致的速率失真 */
|
||||
export const MIN_SPEED_DURATION_SECONDS = 0.5;
|
||||
|
||||
/** 纳入平均吞吐率(Mean TPS)统计的最小输出 Token 数阈值(50 Tokens),避免短回复被首字延迟主导 */
|
||||
export const MIN_MEAN_OUTPUT_TOKENS = 50;
|
||||
|
||||
/**
|
||||
* 解析 ISO-8601 时间戳字符串为亚毫秒精度的浮点毫秒时间戳。
|
||||
* 标准 `Date.parse` 仅保留到整数毫秒,本函数额外提取小数部分以保留亚毫秒精度。
|
||||
*
|
||||
* @param {unknown} value ISO-8601 时间戳字符串
|
||||
* @returns {number} 毫秒时间戳(含小数部分),解析失败时返回 0
|
||||
*/
|
||||
export function parseIsoMs(value) {
|
||||
if (typeof value !== 'string' || !value) return 0;
|
||||
if (typeof value !== 'string' || !value) {
|
||||
return 0;
|
||||
}
|
||||
const ms = Date.parse(value);
|
||||
if (!Number.isFinite(ms)) return 0;
|
||||
if (!Number.isFinite(ms)) {
|
||||
return 0;
|
||||
}
|
||||
const fraction = value.match(/\.(\d+)Z$/);
|
||||
return fraction ? Math.floor(ms / 1000) * 1000 + Number(`0.${fraction[1]}`) * 1000 : ms;
|
||||
if (!fraction) {
|
||||
return ms;
|
||||
}
|
||||
return Math.floor(ms / 1000) * 1000 + Number(`0.${fraction[1]}`) * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Protobuf Duration 格式字符串(如 `"0.85s"`)为非负秒数。
|
||||
*
|
||||
* @param {unknown} value 原始耗时字符串
|
||||
* @returns {number | null} 非负秒数(浮点数),无效时返回 null
|
||||
*/
|
||||
function duration(value) {
|
||||
if (typeof value !== 'string' || !/^\d+(?:\.\d+)?s$/.test(value)) return null;
|
||||
if (typeof value !== 'string' || !/^\d+(?:\.\d+)?s$/.test(value)) {
|
||||
return null;
|
||||
}
|
||||
const n = Number(value.slice(0, -1));
|
||||
return Number.isFinite(n) && n >= 0 ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验输入值是否为合法的非负安全整数计数值(支持数字或纯数字字符串)。
|
||||
*
|
||||
* @param {unknown} value 待校验的 Token 计数值
|
||||
* @returns {boolean} 是否为合法非负安全整数
|
||||
*/
|
||||
function validCount(value) {
|
||||
return (typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) &&
|
||||
Number.isSafeInteger(Number(value)) && Number(value) >= 0;
|
||||
const isNumericType =
|
||||
typeof value === 'number' ||
|
||||
(typeof value === 'string' && /^\d+$/.test(value));
|
||||
if (!isNumericType) {
|
||||
return false;
|
||||
}
|
||||
const num = Number(value);
|
||||
return Number.isSafeInteger(num) && num >= 0;
|
||||
}
|
||||
|
||||
// Subtract timestamps before converting to Number so epoch-sized floats do not
|
||||
// round a 499,999,999 ns request up across the 0.5 second validity threshold.
|
||||
/**
|
||||
* 将 ISO-8601 时间戳解析为纳秒级 `BigInt` 时间戳。
|
||||
*
|
||||
* 为什么必须使用 `BigInt` 纳秒而非 `Number` 浮点数:
|
||||
* Unix 纪元纳秒时间戳数量级约为 `1.7e18`,已超出 IEEE-754 双精度浮点数 `Number.MAX_SAFE_INTEGER`(`9e15`)的精确表示范围。
|
||||
* 若直接转为 `Number` 或在毫秒级做四舍五入,原本 `499,999,999 ns`(499.999999ms)的请求会被舍入为 `0.500s`,
|
||||
* 从而错误跨过 `MIN_SPEED_DURATION_SECONDS`(0.5s)的有效性阈值。先以 `BigInt` 精确存储纳秒并做差,再将小差值转为 `Number`,可彻底消除精度丢失。
|
||||
*
|
||||
* @param {unknown} value ISO-8601 时间戳字符串
|
||||
* @returns {bigint | null} 纳秒级 BigInt 时间戳,格式不合法时返回 null
|
||||
*/
|
||||
function timestampNs(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const match = value.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/);
|
||||
if (!match) return null;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const match = value.match(
|
||||
/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/
|
||||
);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const ms = Date.parse(match[1] + match[3]);
|
||||
return Number.isFinite(ms) ? BigInt(ms) * 1_000_000n + BigInt((match[2] || '').padEnd(9, '0')) : null;
|
||||
if (!Number.isFinite(ms)) {
|
||||
return null;
|
||||
}
|
||||
const nanosPart = BigInt((match[2] || '').padEnd(9, '0'));
|
||||
return BigInt(ms) * 1_000_000n + nanosPart;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算请求开始与结束时间戳之间的精确秒数耗时。
|
||||
* 先在 `BigInt` 纳秒域内执行减法(`end - start`),再除以 `1e9` 转为浮点秒数,防止毫秒级舍入把 499.999ms 请求误判跨过 0.5s 阈值。
|
||||
*
|
||||
* @param {unknown} startValue 请求开始时间(`createdAt`)
|
||||
* @param {unknown} endValue 请求结束时间(`finishedGeneratingAt` 或 `completedAt`)
|
||||
* @returns {number | null} 精确到纳秒的请求耗时秒数,时间戳缺失或倒挂时返回 null
|
||||
*/
|
||||
function requestDuration(startValue, endValue) {
|
||||
const start = timestampNs(startValue), end = timestampNs(endValue);
|
||||
return start !== null && end !== null && start > 0n && end >= start
|
||||
? Number(end - start) / 1e9 : null;
|
||||
const start = timestampNs(startValue);
|
||||
const end = timestampNs(endValue);
|
||||
if (start === null || end === null || start <= 0n || end < start) {
|
||||
return null;
|
||||
}
|
||||
return Number(end - start) / 1e9;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两个毫秒时间戳之间的経過秒数。
|
||||
*
|
||||
* @param {number} start 起始毫秒时间戳
|
||||
* @param {number} end 结束毫秒时间戳
|
||||
* @returns {number | null} 経過秒数,无效时返回 null
|
||||
*/
|
||||
function elapsed(start, end) {
|
||||
return start > 0 && end >= start ? (end - start) / 1000 : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于 UTF-8 字节长度估算文本的 Token 数量(经验比例:约每 3 个 UTF-8 字节折合 1 个 Token,向上取整)。
|
||||
*
|
||||
* @param {unknown} text 待估算的原始文本
|
||||
* @returns {number} 估算的 Token 数量
|
||||
*/
|
||||
function estimateUtf8Tokens(text) {
|
||||
if (typeof text !== 'string' || !text) return 0;
|
||||
if (typeof text !== 'string' || !text) {
|
||||
return 0;
|
||||
}
|
||||
return Math.ceil(Buffer.byteLength(text, 'utf8') / 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据系统提示词分块(Prompt Section)的名称或标题将其归类到具体的上下文子桶。
|
||||
*
|
||||
* @param {unknown} name 分块名称或标题
|
||||
* @returns {'skills' | 'userRules' | 'mcpTools' | 'systemPrompt'} 归属的上下文分类键名
|
||||
*/
|
||||
function classifyPromptSection(name) {
|
||||
const key = String(name || '').trim().toLowerCase();
|
||||
if (key === 'skills' || key === 'skill') return 'skills';
|
||||
if (key === 'user_rules' || key === 'user_rule' || key === 'rules') return 'userRules';
|
||||
if (key === 'mcp_servers' || key === 'mcp' || key.startsWith('mcp_')) return 'mcpTools';
|
||||
if (key === 'skills' || key === 'skill') {
|
||||
return 'skills';
|
||||
}
|
||||
if (key === 'user_rules' || key === 'user_rule' || key === 'rules') {
|
||||
return 'userRules';
|
||||
}
|
||||
if (key === 'mcp_servers' || key === 'mcp' || key.startsWith('mcp_')) {
|
||||
return 'mcpTools';
|
||||
}
|
||||
return 'systemPrompt';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断某个工具项是否属于 MCP(Model Context Protocol)扩展工具或资源调用工具。
|
||||
*
|
||||
* @param {unknown} name 工具名称
|
||||
* @param {unknown} [source=''] 工具来源标识
|
||||
* @param {unknown} [type=''] 工具类型标识
|
||||
* @returns {boolean} 是否归属于 MCP 工具分类
|
||||
*/
|
||||
function isMcpToolItem(name, source = '', type = '') {
|
||||
const n = String(name || '').trim().toLowerCase();
|
||||
const src = String(source || '').toUpperCase();
|
||||
@@ -72,15 +184,59 @@ function isMcpToolItem(name, source = '', type = '') {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `chatModel` 元数据中提取并拆解 6 大上下文 Token 构成分类:
|
||||
* - `messagesTokens`:对话历史消息
|
||||
* - `systemToolsTokens`:内置系统工具定义
|
||||
* - `mcpToolsTokens`:MCP 外部服务器工具与资源定义
|
||||
* - `skillsTokens`:已注入的 Skills 指令说明
|
||||
* - `systemPromptTokens`:核心系统提示词
|
||||
* - `userRulesTokens`:用户自定义全局/工作区规则
|
||||
*
|
||||
* 提取算法分为两个阶段:
|
||||
* 1. **第一阶段(优先采用原生 `contextWindowMetadata.tokenBreakdown.groups`)**:
|
||||
* 遍历服务端提供的精确 Token 分组树:
|
||||
* - 针对 `TOKEN_TYPE_SYSTEM_PROMPT` 分组:遍历其 `children`,通过 `classifyPromptSection` 精细拆分为
|
||||
* `skills`、`userRules`、`mcpTools` 与 `systemPrompt`;若父组 `gTokens` 大于子项之和,差额归入 `systemPromptTokens`。
|
||||
* - 针对 `TOKEN_TYPE_TOOLS` 或含 `MCP` 标识的分组:遍历其 `children`,通过 `isMcpToolItem` 区分内置系统工具(`systemToolsTokens`)
|
||||
* 与 MCP 工具(`mcpToolsTokens`);未拆分子项的余量同样按 `isMcpToolItem` 归属。
|
||||
* - 针对 `TOKEN_TYPE_CHAT_MESSAGES` 分组:优先累加分组总 `gTokens`,若为 0 则累加其 `children` 的 Token 数至 `messagesTokens`。
|
||||
* 2. **第二阶段(缺失分组时的结构化字段回退估算)**:
|
||||
* 当第一阶段未覆盖某类分组(`!hasPromptGroup` / `!hasToolsGroup` / `!hasMessagesGroup`)时,
|
||||
* 分别回退遍历 `chat.promptSections`、`chat.tools`、`chat.messagePrompts`:
|
||||
* 优先读取条目自带的 `numTokens`,若缺失则按 UTF-8 字节长度除以 3(`byteLength / 3` 向上取整)进行估算。
|
||||
*
|
||||
* @param {object} chat `generatorMetadata.chatModel` 对象
|
||||
* @returns {{
|
||||
* messagesTokens: number,
|
||||
* systemToolsTokens: number,
|
||||
* mcpToolsTokens: number,
|
||||
* skillsTokens: number,
|
||||
* systemPromptTokens: number,
|
||||
* userRulesTokens: number,
|
||||
* totalTokens: number
|
||||
* } | null} 上下文 Token 构成明细,无任何可用元数据时返回 null
|
||||
*/
|
||||
export function extractContextBreakdown(chat) {
|
||||
if (!chat || typeof chat !== 'object') return null;
|
||||
if (!chat || typeof chat !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const tb = chat?.chatStartMetadata?.contextWindowMetadata?.tokenBreakdown;
|
||||
const groups = Array.isArray(tb?.groups) ? tb.groups : [];
|
||||
const promptSections = Array.isArray(chat?.promptSections) ? chat.promptSections : [];
|
||||
const promptSections = Array.isArray(chat?.promptSections)
|
||||
? chat.promptSections
|
||||
: [];
|
||||
const tools = Array.isArray(chat?.tools) ? chat.tools : [];
|
||||
const messagePrompts = Array.isArray(chat?.messagePrompts) ? chat.messagePrompts : [];
|
||||
const messagePrompts = Array.isArray(chat?.messagePrompts)
|
||||
? chat.messagePrompts
|
||||
: [];
|
||||
|
||||
if (!groups.length && !promptSections.length && !tools.length && !messagePrompts.length) {
|
||||
if (
|
||||
!groups.length &&
|
||||
!promptSections.length &&
|
||||
!tools.length &&
|
||||
!messagePrompts.length
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -95,6 +251,7 @@ export function extractContextBreakdown(chat) {
|
||||
let hasToolsGroup = false;
|
||||
let hasMessagesGroup = false;
|
||||
|
||||
// 第一阶段:从原生 tokenBreakdown.groups 树状结构中提取并拆分 6 大上下文分类
|
||||
for (const g of groups) {
|
||||
const gType = String(g?.type || '').toUpperCase();
|
||||
const gName = String(g?.name || '').trim().toLowerCase();
|
||||
@@ -110,10 +267,15 @@ export function extractContextBreakdown(chat) {
|
||||
const tok = Math.max(0, Number(c?.numTokens || 0));
|
||||
childSum += tok;
|
||||
const bucket = classifyPromptSection(c?.name ?? c?.title);
|
||||
if (bucket === 'skills') skillsTokens += tok;
|
||||
else if (bucket === 'userRules') userRulesTokens += tok;
|
||||
else if (bucket === 'mcpTools') mcpToolsTokens += tok;
|
||||
else systemPromptTokens += tok;
|
||||
if (bucket === 'skills') {
|
||||
skillsTokens += tok;
|
||||
} else if (bucket === 'userRules') {
|
||||
userRulesTokens += tok;
|
||||
} else if (bucket === 'mcpTools') {
|
||||
mcpToolsTokens += tok;
|
||||
} else {
|
||||
systemPromptTokens += tok;
|
||||
}
|
||||
}
|
||||
if (gTokens > childSum) {
|
||||
systemPromptTokens += gTokens - childSum;
|
||||
@@ -133,15 +295,20 @@ export function extractContextBreakdown(chat) {
|
||||
for (const c of children) {
|
||||
const tok = Math.max(0, Number(c?.numTokens || 0));
|
||||
childSum += tok;
|
||||
if (isMcpToolItem(c?.name, c?.source || g?.source, c?.type || g?.type)) {
|
||||
if (
|
||||
isMcpToolItem(c?.name, c?.source || g?.source, c?.type || g?.type)
|
||||
) {
|
||||
mcpToolsTokens += tok;
|
||||
} else {
|
||||
systemToolsTokens += tok;
|
||||
}
|
||||
}
|
||||
if (gTokens > childSum) {
|
||||
if (isMcpToolItem(g?.name, g?.source, g?.type)) mcpToolsTokens += gTokens - childSum;
|
||||
else systemToolsTokens += gTokens - childSum;
|
||||
if (isMcpToolItem(g?.name, g?.source, g?.type)) {
|
||||
mcpToolsTokens += gTokens - childSum;
|
||||
} else {
|
||||
systemToolsTokens += gTokens - childSum;
|
||||
}
|
||||
}
|
||||
} else if (isMcpToolItem(g?.name, g?.source, g?.type)) {
|
||||
mcpToolsTokens += gTokens;
|
||||
@@ -164,6 +331,7 @@ export function extractContextBreakdown(chat) {
|
||||
}
|
||||
}
|
||||
|
||||
// 第二阶段(A):当 groups 缺失系统提示词分组时,回退到 promptSections 按显式 token 或 UTF-8 字节数(byteLength / 3)估算
|
||||
if (!hasPromptGroup && promptSections.length > 0) {
|
||||
for (const s of promptSections) {
|
||||
const tok =
|
||||
@@ -171,13 +339,19 @@ export function extractContextBreakdown(chat) {
|
||||
? Number(s.numTokens)
|
||||
: estimateUtf8Tokens(s?.content ?? s?.text ?? '');
|
||||
const bucket = classifyPromptSection(s?.title ?? s?.name);
|
||||
if (bucket === 'skills') skillsTokens += tok;
|
||||
else if (bucket === 'userRules') userRulesTokens += tok;
|
||||
else if (bucket === 'mcpTools') mcpToolsTokens += tok;
|
||||
else systemPromptTokens += tok;
|
||||
if (bucket === 'skills') {
|
||||
skillsTokens += tok;
|
||||
} else if (bucket === 'userRules') {
|
||||
userRulesTokens += tok;
|
||||
} else if (bucket === 'mcpTools') {
|
||||
mcpToolsTokens += tok;
|
||||
} else {
|
||||
systemPromptTokens += tok;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 第二阶段(B):当 groups 缺失工具分组时,回退到 tools 列表拼接名称、描述与 JSON Schema 估算
|
||||
if (!hasToolsGroup && tools.length > 0) {
|
||||
for (const t of tools) {
|
||||
const rawText = `${t?.name || ''}${t?.description || ''}${t?.jsonSchemaString || ''}`;
|
||||
@@ -193,6 +367,7 @@ export function extractContextBreakdown(chat) {
|
||||
}
|
||||
}
|
||||
|
||||
// 第二阶段(C):当 groups 缺失对话消息分组时,回退到 messagePrompts 列表按文本字节数估算
|
||||
if (!hasMessagesGroup && messagePrompts.length > 0) {
|
||||
for (const m of messagePrompts) {
|
||||
const tok =
|
||||
@@ -222,95 +397,204 @@ export function extractContextBreakdown(chat) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从原始轨迹步骤数组与生成器元数据中提取标准化模型步骤指标。
|
||||
*
|
||||
* 核心处理流程说明:
|
||||
* 1. **模型身份 5 级证据链优先级(由高到低)**:
|
||||
* 依次检查本请求自身的 5 个字段来源,取首个非空且非占位符(排除 `0`、`unknown`、`MODEL_UNSPECIFIED`、`MODEL_UNKNOWN`)的值:
|
||||
* - 优先级 1:`usage.model`(步骤内 `modelUsage` 或 `retryInfos[0].usage` 记录的模型标识)
|
||||
* - 优先级 2:`chat.usage.model`(关联 `generatorMetadata.chatModel.usage` 记录的模型标识)
|
||||
* - 优先级 3:`chat.model`(`chatModel` 请求级模型标识)
|
||||
* - 优先级 4:`metadata.generatorModel`(步骤 `metadata` 顶层记录的生成模型)
|
||||
* - 优先级 5:`chat.responseModel`(上游返回的具体响应模型名)
|
||||
* 2. **5 种测速过滤与排除原因(`timingReason` / `speedReason`)**:
|
||||
* - `'incomplete_or_invalid_timing'`:步骤状态未完成(非 `CORTEX_STEP_STATUS_DONE`)或总耗时 `totalDurationSec` 缺失/非正数;
|
||||
* - `'invalid_output_tokens'`:`outputTokens` 不是合法的非负安全整数;
|
||||
* - `'short_timing'`:请求总耗时低于 `MIN_SPEED_DURATION_SECONDS`(0.5s),易受计时器粒度噪声干扰;
|
||||
* - `'inconsistent_timing'`:原生首字延迟 `nativeTtftSec` 大于请求总耗时 `totalDurationSec + 0.01s`(时钟或元数据自相矛盾);
|
||||
* - `'compaction'` / `'short_sample'`:单步吞吐率可计算,但属于上下文压缩检查点步骤(`CORTEX_STEP_TYPE_CHECKPOINT`)
|
||||
* 或输出不足 `MIN_MEAN_OUTPUT_TOKENS`(50 Tokens),因此从平均速度样本(`speedSampleEligible`)中剔除。
|
||||
* 3. **末尾步骤上下文回填逻辑**:
|
||||
* 若轨迹最后一个模型步骤本身未携带 `contextBreakdown`(例如末尾步骤为轻量更新或缺少内联 `chatModel`),
|
||||
* 但整条轨迹的 `generatorMetadata` 中存在最近的 `latestBreakdownChat`,则将该上下文构成与最大预算回填至末尾步骤,
|
||||
* 确保面板展示的当前会话上下文水位不丢失。
|
||||
*
|
||||
* @param {Array<object>} [rawSteps=[]] 原始 Cortex 步骤数组
|
||||
* @param {Array<object>} [generatorMetadata=[]] 轨迹级生成器元数据列表
|
||||
* @returns {Array<object>} 标准化并完成压缩步骤模型推断的步骤指标列表
|
||||
*/
|
||||
export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const genByStep = new Map();
|
||||
let latestBreakdownChat = null;
|
||||
|
||||
for (const gm of generatorMetadata || []) {
|
||||
if (!gm?.chatModel) continue;
|
||||
for (const index of gm?.stepIndices || []) genByStep.set(Number(index), gm);
|
||||
if (!gm?.chatModel) {
|
||||
continue;
|
||||
}
|
||||
for (const index of gm?.stepIndices || []) {
|
||||
genByStep.set(Number(index), gm);
|
||||
}
|
||||
if (extractContextBreakdown(gm.chatModel)) {
|
||||
latestBreakdownChat = gm.chatModel;
|
||||
}
|
||||
}
|
||||
|
||||
const result = [];
|
||||
|
||||
rawSteps.forEach((s, index) => {
|
||||
const m = s?.metadata;
|
||||
const u = m?.modelUsage || m?.retryInfos?.[0]?.usage;
|
||||
if (!u) return;
|
||||
if (!u) {
|
||||
return;
|
||||
}
|
||||
|
||||
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
||||
const inlineChat = Array.isArray(m.generatorMetadata) ? m.generatorMetadata.find(g => g?.chatModel) : null;
|
||||
const inlineChat = Array.isArray(m.generatorMetadata)
|
||||
? m.generatorMetadata.find((g) => g?.chatModel)
|
||||
: null;
|
||||
const gm = inlineChat || genByStep.get(Number(stepIndex));
|
||||
const chat = gm?.chatModel;
|
||||
const p = s.plannerResponse || {};
|
||||
const isCompactionStep = s.type === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
|
||||
const inputTokens = Number(u.inputTokens || 0);
|
||||
const cacheReadTokens = Number(u.cacheReadTokens || 0);
|
||||
const outputTokens = Number(u.outputTokens || 0);
|
||||
const thinkingTokens = Number(p.thinkingTokens ?? u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens ?? 0);
|
||||
const responseTokens = Number(p.responseTokens ?? u.responseOutputTokens ?? chat?.usage?.responseOutputTokens ?? Math.max(0, outputTokens - thinkingTokens));
|
||||
const thinkingTokens = Number(
|
||||
p.thinkingTokens ??
|
||||
u.thinkingOutputTokens ??
|
||||
chat?.usage?.thinkingOutputTokens ??
|
||||
0
|
||||
);
|
||||
const responseTokens = Number(
|
||||
p.responseTokens ??
|
||||
u.responseOutputTokens ??
|
||||
chat?.usage?.responseOutputTokens ??
|
||||
Math.max(0, outputTokens - thinkingTokens)
|
||||
);
|
||||
|
||||
const start = parseIsoMs(m.createdAt);
|
||||
const measuredDuration = requestDuration(m.createdAt, m.finishedGeneratingAt || m.completedAt);
|
||||
const explicitlyIncomplete = Boolean(s.status && s.status !== 'CORTEX_STEP_STATUS_DONE');
|
||||
const measuredDuration = requestDuration(
|
||||
m.createdAt,
|
||||
m.finishedGeneratingAt || m.completedAt
|
||||
);
|
||||
const explicitlyIncomplete = Boolean(
|
||||
s.status && s.status !== 'CORTEX_STEP_STATUS_DONE'
|
||||
);
|
||||
const complete = !explicitlyIncomplete && measuredDuration !== null;
|
||||
const totalDurationSec = complete ? measuredDuration : null;
|
||||
const nativeTtftSec = duration(chat?.timeToFirstToken);
|
||||
// These phase timers remain diagnostic only: buffered tools can make them
|
||||
// tiny, so neither is used as a divisor or subtracted from request time.
|
||||
|
||||
// 阶段计时器(streamingDuration / thinkingDuration)仅作诊断展示:
|
||||
// 缓冲式工具调用会导致 streamingDuration 极小,因此绝不能将其作为速度分母或从总耗时中扣除
|
||||
const nativeStreamSec = duration(chat?.streamingDuration);
|
||||
const thinkingDurationSec = duration(p.thinkingDuration);
|
||||
|
||||
// 5 种测速过滤原因判定:先校验耗时与 Token 合法性(timingReason),再判定压缩步与短样本(speedReason)
|
||||
let timingReason = null;
|
||||
if (!complete || !(totalDurationSec > 0)) timingReason = 'incomplete_or_invalid_timing';
|
||||
else if (!validCount(u.outputTokens)) timingReason = 'invalid_output_tokens';
|
||||
else if (totalDurationSec < MIN_SPEED_DURATION_SECONDS) timingReason = 'short_timing';
|
||||
else if (nativeTtftSec !== null && nativeTtftSec > totalDurationSec + 0.01) timingReason = 'inconsistent_timing';
|
||||
const totalTokPerSec = timingReason === null ? outputTokens / totalDurationSec : null;
|
||||
const shortOutputSample = totalTokPerSec !== null && outputTokens < MIN_MEAN_OUTPUT_TOKENS;
|
||||
const speedReason = timingReason || (isCompactionStep ? 'compaction' : shortOutputSample ? 'short_sample' : null);
|
||||
if (!complete || !(totalDurationSec > 0)) {
|
||||
timingReason = 'incomplete_or_invalid_timing';
|
||||
} else if (!validCount(u.outputTokens)) {
|
||||
timingReason = 'invalid_output_tokens';
|
||||
} else if (totalDurationSec < MIN_SPEED_DURATION_SECONDS) {
|
||||
timingReason = 'short_timing';
|
||||
} else if (
|
||||
nativeTtftSec !== null &&
|
||||
nativeTtftSec > totalDurationSec + 0.01
|
||||
) {
|
||||
timingReason = 'inconsistent_timing';
|
||||
}
|
||||
|
||||
const totalTokPerSec =
|
||||
timingReason === null ? outputTokens / totalDurationSec : null;
|
||||
const shortOutputSample =
|
||||
totalTokPerSec !== null && outputTokens < MIN_MEAN_OUTPUT_TOKENS;
|
||||
const speedReason =
|
||||
timingReason ||
|
||||
(isCompactionStep
|
||||
? 'compaction'
|
||||
: shortOutputSample
|
||||
? 'short_sample'
|
||||
: null);
|
||||
|
||||
const context = chat?.chatStartMetadata?.contextWindowMetadata;
|
||||
const contextBreakdown = extractContextBreakdown(chat);
|
||||
// Only use model evidence belonging to this request first. If a checkpoint
|
||||
// omits model metadata, inferCompactionStepModels will fall back to the
|
||||
// nearest explicit step in the same trajectory with a compatible provider.
|
||||
|
||||
// 模型身份 5 级证据链优先级:仅采信当前请求自身的显式字段;
|
||||
// 若 Checkpoint 压缩步骤缺失模型字段,稍后由 inferCompactionStepModels 从同轨迹邻居步骤回退推断
|
||||
const isValidModelValue = (value) =>
|
||||
typeof value === 'string' && value.trim() &&
|
||||
typeof value === 'string' &&
|
||||
value.trim() &&
|
||||
!/^(?:0|unknown|MODEL_(?:UNSPECIFIED|UNKNOWN))$/i.test(value.trim());
|
||||
|
||||
const modelCandidates = [
|
||||
['usage.model', u.model], ['chat.usage.model', chat?.usage?.model],
|
||||
['chat.model', chat?.model], ['metadata.generatorModel', m.generatorModel],
|
||||
['usage.model', u.model],
|
||||
['chat.usage.model', chat?.usage?.model],
|
||||
['chat.model', chat?.model],
|
||||
['metadata.generatorModel', m.generatorModel],
|
||||
['chat.responseModel', chat?.responseModel],
|
||||
];
|
||||
const identity = modelCandidates.find(([, value]) => isValidModelValue(value));
|
||||
const rawResponseModel = [chat?.responseModel, u?.responseModel, m?.responseModel]
|
||||
.find(isValidModelValue);
|
||||
const identity = modelCandidates.find(([, value]) =>
|
||||
isValidModelValue(value)
|
||||
);
|
||||
const rawResponseModel = [
|
||||
chat?.responseModel,
|
||||
u?.responseModel,
|
||||
m?.responseModel,
|
||||
].find(isValidModelValue);
|
||||
|
||||
result.push({
|
||||
stepIndex, isCompactionStep,
|
||||
stepIndex,
|
||||
isCompactionStep,
|
||||
modelKey: identity ? identity[1].trim() : 'unknown',
|
||||
modelSource: identity?.[0] || 'unavailable',
|
||||
responseModel: rawResponseModel ? rawResponseModel.trim() : '',
|
||||
modelIdentityVersion: MODEL_IDENTITY_VERSION,
|
||||
modelDisplayName: chat?.modelDisplayName || '',
|
||||
apiProvider: u.apiProvider || chat?.usage?.apiProvider || '',
|
||||
createdAt: m.createdAt || null, createdAtMs: Math.floor(start),
|
||||
hasVisibleText: String(p.modifiedResponse || p.response || '').trim().length > 0,
|
||||
createdAt: m.createdAt || null,
|
||||
createdAtMs: Math.floor(start),
|
||||
hasVisibleText:
|
||||
String(p.modifiedResponse || p.response || '').trim().length > 0,
|
||||
hasToolCalls: Array.isArray(p.toolCalls) && p.toolCalls.length > 0,
|
||||
inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens,
|
||||
estimatedContextTokens: Number(context?.estimatedTokensUsed || contextBreakdown?.totalTokens || 0),
|
||||
inputTokens,
|
||||
cacheReadTokens,
|
||||
outputTokens,
|
||||
thinkingTokens,
|
||||
responseTokens,
|
||||
estimatedContextTokens: Number(
|
||||
context?.estimatedTokensUsed || contextBreakdown?.totalTokens || 0
|
||||
),
|
||||
maxContextBudgetTokens: Number(context?.maxContextTokens || 256000),
|
||||
contextBreakdown,
|
||||
measurementVersion: MEASUREMENT_VERSION,
|
||||
isComplete: complete, nativeTtftSec, nativeStreamSec,
|
||||
isComplete: complete,
|
||||
nativeTtftSec,
|
||||
nativeStreamSec,
|
||||
viewableDelaySec: elapsed(start, parseIsoMs(m.viewableAt)),
|
||||
ttftSec: nativeTtftSec, ttftSource: nativeTtftSec === null ? 'unavailable' : 'native',
|
||||
thinkingDurationSec, totalDurationSec, totalTokPerSec,
|
||||
ttftSec: nativeTtftSec,
|
||||
ttftSource: nativeTtftSec === null ? 'unavailable' : 'native',
|
||||
thinkingDurationSec,
|
||||
totalDurationSec,
|
||||
totalTokPerSec,
|
||||
speedBasis: totalTokPerSec === null ? 'unavailable' : 'request_total',
|
||||
speedSampleEligible: totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
|
||||
speedSampleEligible:
|
||||
totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
|
||||
speedReason,
|
||||
});
|
||||
});
|
||||
if (result.length > 0 && !result[result.length - 1].contextBreakdown && latestBreakdownChat) {
|
||||
|
||||
// 末尾步骤上下文回填:若最后一个步骤缺少 contextBreakdown,则使用同轨迹最近一次有效的 generatorMetadata 补齐
|
||||
if (
|
||||
result.length > 0 &&
|
||||
!result[result.length - 1].contextBreakdown &&
|
||||
latestBreakdownChat
|
||||
) {
|
||||
const lastStep = result[result.length - 1];
|
||||
const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat);
|
||||
const fallbackCtx = latestBreakdownChat?.chatStartMetadata?.contextWindowMetadata;
|
||||
const fallbackCtx =
|
||||
latestBreakdownChat?.chatStartMetadata?.contextWindowMetadata;
|
||||
lastStep.contextBreakdown = fallbackBreakdown;
|
||||
if (!lastStep.estimatedContextTokens) {
|
||||
lastStep.estimatedContextTokens = Number(
|
||||
@@ -321,35 +605,64 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
lastStep.maxContextBudgetTokens = Number(fallbackCtx.maxContextTokens);
|
||||
}
|
||||
}
|
||||
|
||||
return inferCompactionStepModels(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为缺失显式模型标识的上下文压缩步骤(`isCompactionStep`)推断归属模型。
|
||||
*
|
||||
* 4 轮前后向邻居回退推断规则(仅选取拥有真实显式模型身份 `isExplicitDonor` 的步骤作为捐赠者):
|
||||
* - **第 1 轮(前向同 Provider 优先)**:从当前位置向前(`idx - 1 -> 0`)查找首个 `apiProvider` 兼容的显式模型步骤;
|
||||
* - **第 2 轮(后向同 Provider 次之)**:若前向未找到,从当前位置向后(`idx + 1 -> steps.length - 1`)查找首个 `apiProvider` 兼容的显式模型步骤;
|
||||
* - **第 3 轮(前向任意显式模型回退)**:若仍未找到,忽略 Provider 限制,向前查找最近的任意显式模型步骤;
|
||||
* - **第 4 轮(后向任意显式模型兜底)**:最后向后查找最近的任意显式模型步骤。
|
||||
*
|
||||
* 命中后将 `modelKey` 补齐并将 `modelSource` 标记为 `'inferred_compaction'`,同时补齐缺失的 `responseModel` 与 `modelDisplayName`。
|
||||
*
|
||||
* @param {Array<object>} steps 已提取的步骤列表
|
||||
* @returns {Array<object>} 补齐压缩步骤模型归属后的步骤列表
|
||||
*/
|
||||
export function inferCompactionStepModels(steps) {
|
||||
if (!Array.isArray(steps) || steps.length < 2) return steps;
|
||||
if (!Array.isArray(steps) || steps.length < 2) {
|
||||
return steps;
|
||||
}
|
||||
|
||||
const isExplicitDonor = (step) =>
|
||||
Boolean(
|
||||
step &&
|
||||
step.modelKey &&
|
||||
step.modelKey !== 'unknown' &&
|
||||
step.modelSource !== 'inferred_compaction' &&
|
||||
step.modelSource !== 'legacy_unverified'
|
||||
step.modelKey &&
|
||||
step.modelKey !== 'unknown' &&
|
||||
step.modelSource !== 'inferred_compaction' &&
|
||||
step.modelSource !== 'legacy_unverified'
|
||||
);
|
||||
|
||||
const isProviderCompatible = (target, donor) =>
|
||||
!target.apiProvider || !donor.apiProvider || target.apiProvider === donor.apiProvider;
|
||||
!target.apiProvider ||
|
||||
!donor.apiProvider ||
|
||||
target.apiProvider === donor.apiProvider;
|
||||
|
||||
return steps.map((step, idx) => {
|
||||
if (!step?.isCompactionStep) return step;
|
||||
if (!step?.isCompactionStep) {
|
||||
return step;
|
||||
}
|
||||
const needsModel = !step.modelKey || step.modelKey === 'unknown';
|
||||
const needsUpstream = step.modelSource === 'inferred_compaction' && !step.responseModel;
|
||||
if (!needsModel && !needsUpstream) return step;
|
||||
const needsUpstream =
|
||||
step.modelSource === 'inferred_compaction' && !step.responseModel;
|
||||
if (!needsModel && !needsUpstream) {
|
||||
return step;
|
||||
}
|
||||
|
||||
let donor = null;
|
||||
|
||||
// 第 1 轮:前向查找同 API Provider 的最近显式模型步骤
|
||||
for (let j = idx - 1; j >= 0; j--) {
|
||||
if (isExplicitDonor(steps[j]) && isProviderCompatible(step, steps[j])) {
|
||||
donor = steps[j];
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 第 2 轮:后向查找同 API Provider 的最近显式模型步骤
|
||||
if (!donor) {
|
||||
for (let j = idx + 1; j < steps.length; j++) {
|
||||
if (isExplicitDonor(steps[j]) && isProviderCompatible(step, steps[j])) {
|
||||
@@ -358,6 +671,7 @@ export function inferCompactionStepModels(steps) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 第 3 轮:前向查找任意最近显式模型步骤
|
||||
if (!donor) {
|
||||
for (let j = idx - 1; j >= 0; j--) {
|
||||
if (isExplicitDonor(steps[j])) {
|
||||
@@ -366,6 +680,7 @@ export function inferCompactionStepModels(steps) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 第 4 轮:后向查找任意最近显式模型步骤
|
||||
if (!donor) {
|
||||
for (let j = idx + 1; j < steps.length; j++) {
|
||||
if (isExplicitDonor(steps[j])) {
|
||||
@@ -374,7 +689,10 @@ export function inferCompactionStepModels(steps) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!donor) return step;
|
||||
|
||||
if (!donor) {
|
||||
return step;
|
||||
}
|
||||
|
||||
return {
|
||||
...step,
|
||||
@@ -386,51 +704,128 @@ export function inferCompactionStepModels(steps) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化并迁移从磁盘缓存加载的历史步骤对象。
|
||||
*
|
||||
* 迁移与歧义清理规则:
|
||||
* 1. **旧版 `v9` 缓存 `MODEL_PLACEHOLDER_M418` 歧义清理**:
|
||||
* 旧版 `v9` 缓存既把真实的 Argon 模型请求记为 `MODEL_PLACEHOLDER_M418`,又把缺失模型元数据的默认回退值硬编码为 `MODEL_PLACEHOLDER_M418`。
|
||||
* 在缺乏原始轨迹证据时两者无法区分,因此迁移时保留 Token 用量与时间信息,将 `MODEL_PLACEHOLDER_M418`(及空模型名)
|
||||
* 统一重置为 `modelKey: 'unknown'`、`modelSource: 'legacy_unverified'`,并把原值保存在 `legacyModelKey` 中,交由后续全量重载从原始轨迹恢复真实身份。
|
||||
* 2. **跨测量版本速度字段失效保护**:
|
||||
* 若缓存步骤的 `measurementVersion` 与当前 `MEASUREMENT_VERSION` 不一致,保留计费 Token 数据以防重载失败丢失账单,
|
||||
* 但将所有派生速度与阶段耗时字段清空并标记 `speedReason: 'legacy_cache'`,防止旧口径算出的失真速率混入当前统计。
|
||||
*
|
||||
* @param {object} step 缓存中的步骤对象
|
||||
* @returns {object} 迁移并清洗后的步骤对象
|
||||
*/
|
||||
export function normalizeCachedStep(step) {
|
||||
if (step.modelIdentityVersion !== MODEL_IDENTITY_VERSION) {
|
||||
// v9 wrote M418 both for real Argon calls and as the missing-model default.
|
||||
// Without raw evidence they are indistinguishable; keep usage and timing,
|
||||
// mark the identity unresolved, and let the schema reload recover it.
|
||||
const ambiguous = !step.modelKey || step.modelKey === 'MODEL_PLACEHOLDER_M418';
|
||||
const ambiguous =
|
||||
!step.modelKey || step.modelKey === 'MODEL_PLACEHOLDER_M418';
|
||||
step = {
|
||||
...step, modelIdentityVersion: MODEL_IDENTITY_VERSION,
|
||||
...(ambiguous ? {
|
||||
legacyModelKey: step.modelKey || null, modelKey: 'unknown',
|
||||
modelDisplayName: '', modelSource: 'legacy_unverified',
|
||||
} : { modelSource: 'legacy_explicit' }),
|
||||
...step,
|
||||
modelIdentityVersion: MODEL_IDENTITY_VERSION,
|
||||
...(ambiguous
|
||||
? {
|
||||
legacyModelKey: step.modelKey || null,
|
||||
modelKey: 'unknown',
|
||||
modelDisplayName: '',
|
||||
modelSource: 'legacy_unverified',
|
||||
}
|
||||
: { modelSource: 'legacy_explicit' }),
|
||||
};
|
||||
}
|
||||
if (step.measurementVersion === MEASUREMENT_VERSION) return step;
|
||||
// Keep billing through failed reloads, but never show old derived speeds as
|
||||
// current measurements. Raw trajectories rebuild measurements after migration.
|
||||
|
||||
if (step.measurementVersion === MEASUREMENT_VERSION) {
|
||||
return step;
|
||||
}
|
||||
|
||||
return {
|
||||
...step, measurementVersion: null, isComplete: false,
|
||||
nativeTtftSec: null, nativeStreamSec: null, viewableDelaySec: null,
|
||||
ttftSec: null, ttftSource: 'unavailable', thinkingDurationSec: null,
|
||||
totalDurationSec: null, totalTokPerSec: null,
|
||||
phaseDurationSec: null, phaseTokPerSec: null, phaseReason: 'legacy_cache', answerStartDelaySec: null,
|
||||
streamDurationSec: null, streamTokens: null, streamTokPerSec: null,
|
||||
speedBasis: 'unavailable', speedSampleEligible: false, speedReason: 'legacy_cache',
|
||||
...step,
|
||||
measurementVersion: null,
|
||||
isComplete: false,
|
||||
nativeTtftSec: null,
|
||||
nativeStreamSec: null,
|
||||
viewableDelaySec: null,
|
||||
ttftSec: null,
|
||||
ttftSource: 'unavailable',
|
||||
thinkingDurationSec: null,
|
||||
totalDurationSec: null,
|
||||
totalTokPerSec: null,
|
||||
phaseDurationSec: null,
|
||||
phaseTokPerSec: null,
|
||||
phaseReason: 'legacy_cache',
|
||||
answerStartDelaySec: null,
|
||||
streamDurationSec: null,
|
||||
streamTokens: null,
|
||||
streamTokPerSec: null,
|
||||
speedBasis: 'unavailable',
|
||||
speedSampleEligible: false,
|
||||
speedReason: 'legacy_cache',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取单个步骤的速度度量摘要及其是否具备纳入平均速度统计的资格。
|
||||
*
|
||||
* @param {object} step 标准化步骤对象
|
||||
* @returns {{ value: number | null, tokens: number, seconds: number, eligible: boolean, reason: string | null }}
|
||||
*/
|
||||
export function speedMetric(step) {
|
||||
const missing = (reason) => ({ value: null, tokens: 0, seconds: 0, eligible: false, reason });
|
||||
if (step.measurementVersion !== MEASUREMENT_VERSION) return missing('legacy_cache');
|
||||
if (!step.isComplete || !Number.isFinite(step.totalTokPerSec) ||
|
||||
!(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS)) {
|
||||
const missing = (reason) => ({
|
||||
value: null,
|
||||
tokens: 0,
|
||||
seconds: 0,
|
||||
eligible: false,
|
||||
reason,
|
||||
});
|
||||
|
||||
if (step.measurementVersion !== MEASUREMENT_VERSION) {
|
||||
return missing('legacy_cache');
|
||||
}
|
||||
if (
|
||||
!step.isComplete ||
|
||||
!Number.isFinite(step.totalTokPerSec) ||
|
||||
!(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS)
|
||||
) {
|
||||
return missing(step.speedReason || 'incomplete_or_invalid_timing');
|
||||
}
|
||||
return { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec,
|
||||
eligible: step.speedSampleEligible === true && !step.isCompactionStep, reason: step.speedReason };
|
||||
|
||||
return {
|
||||
value: step.totalTokPerSec,
|
||||
tokens: step.outputTokens,
|
||||
seconds: step.totalDurationSec,
|
||||
eligible: step.speedSampleEligible === true && !step.isCompactionStep,
|
||||
reason: step.speedReason,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建用于聚合多步骤吞吐率的累加器初始状态。
|
||||
*
|
||||
* @returns {{ tokens: number, seconds: number, sampleCount: number, excludedCount: number, excludedReasons: Record<string, number> }}
|
||||
*/
|
||||
export function createSpeedAccumulator() {
|
||||
return { tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {} };
|
||||
return {
|
||||
tokens: 0,
|
||||
seconds: 0,
|
||||
sampleCount: 0,
|
||||
excludedCount: 0,
|
||||
excludedReasons: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单个步骤的速度指标累加到汇总累加器中(自动跳过上下文压缩步骤)。
|
||||
*
|
||||
* @param {ReturnType<typeof createSpeedAccumulator>} acc 速度累加器
|
||||
* @param {object} step 标准化步骤对象
|
||||
*/
|
||||
export function accumulateSpeed(acc, step) {
|
||||
if (step.isCompactionStep) return;
|
||||
if (step.isCompactionStep) {
|
||||
return;
|
||||
}
|
||||
const metric = speedMetric(step);
|
||||
if (metric.eligible) {
|
||||
acc.tokens += metric.tokens;
|
||||
@@ -438,24 +833,65 @@ export function accumulateSpeed(acc, step) {
|
||||
acc.sampleCount++;
|
||||
} else {
|
||||
acc.excludedCount++;
|
||||
acc.excludedReasons[metric.reason] = (acc.excludedReasons[metric.reason] || 0) + 1;
|
||||
acc.excludedReasons[metric.reason] =
|
||||
(acc.excludedReasons[metric.reason] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 完成速度累加并计算加权平均吞吐率(`总输出 Tokens / 总有效耗时秒数`)。
|
||||
*
|
||||
* @param {ReturnType<typeof createSpeedAccumulator>} acc 速度累加器
|
||||
* @returns {ReturnType<typeof createSpeedAccumulator> & { avgTokPerSec: number | null }}
|
||||
*/
|
||||
export function finishSpeed(acc) {
|
||||
return { ...acc, avgTokPerSec: acc.seconds > 0 ? acc.tokens / acc.seconds : null };
|
||||
return {
|
||||
...acc,
|
||||
avgTokPerSec: acc.seconds > 0 ? acc.tokens / acc.seconds : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次性汇总一组步骤的整体吞吐率指标。
|
||||
*
|
||||
* @param {Array<object>} steps 步骤列表
|
||||
* @returns {ReturnType<typeof finishSpeed>}
|
||||
*/
|
||||
export function summarizeSpeed(steps) {
|
||||
const acc = createSpeedAccumulator();
|
||||
for (const step of steps) accumulateSpeed(acc, step);
|
||||
for (const step of steps) {
|
||||
accumulateSpeed(acc, step);
|
||||
}
|
||||
return finishSpeed(acc);
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总一组步骤的平均原生首字延迟(TTFT)。
|
||||
* 仅纳入非压缩、当前测量版本、已完成且 `0 <= nativeTtftSec <= totalDurationSec + 0.01` 的有效样本。
|
||||
*
|
||||
* @param {Array<object>} steps 步骤列表
|
||||
* @returns {{ sampleCount: number, avgSec: number | null }}
|
||||
*/
|
||||
export function summarizeTtft(steps) {
|
||||
const values = steps.filter(s => !s.isCompactionStep && s.measurementVersion === MEASUREMENT_VERSION &&
|
||||
s.isComplete && Number.isFinite(s.totalDurationSec) &&
|
||||
Number.isFinite(s.nativeTtftSec) && s.nativeTtftSec >= 0 &&
|
||||
s.nativeTtftSec <= s.totalDurationSec + 0.01).map(s => s.nativeTtftSec);
|
||||
return { sampleCount: values.length, avgSec: values.length ? values.reduce((a,b) => a+b,0) / values.length : null };
|
||||
const values = steps
|
||||
.filter(
|
||||
(s) =>
|
||||
!s.isCompactionStep &&
|
||||
s.measurementVersion === MEASUREMENT_VERSION &&
|
||||
s.isComplete &&
|
||||
Number.isFinite(s.totalDurationSec) &&
|
||||
Number.isFinite(s.nativeTtftSec) &&
|
||||
s.nativeTtftSec >= 0 &&
|
||||
s.nativeTtftSec <= s.totalDurationSec + 0.01
|
||||
)
|
||||
.map((s) => s.nativeTtftSec);
|
||||
|
||||
const avgSec = values.length
|
||||
? values.reduce((a, b) => a + b, 0) / values.length
|
||||
: null;
|
||||
|
||||
return {
|
||||
sampleCount: values.length,
|
||||
avgSec,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* @fileoverview 纯 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
|
||||
* 负责将按时间分桶的 Token 消耗序列渲染为带垂直渐变填充、虚线参考网格、
|
||||
* 峰值描点与自适应防溢出的顶部峰值胶囊标签的面积图。
|
||||
*/
|
||||
|
||||
import { h, patchAttr, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
|
||||
/**
|
||||
* 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。
|
||||
* 控制点沿 X 轴取相邻点间距的 `0.45` 张力系数,Y 轴与各自端点齐平,
|
||||
* 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。
|
||||
*
|
||||
* @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组
|
||||
* @returns {string} SVG `<path>` 的 `d` 属性字符串
|
||||
*/
|
||||
function buildSmoothSplinePath(points) {
|
||||
if (!points.length) return '';
|
||||
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
|
||||
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
|
||||
for (let i = 0; i < points.length - 1; i++) {
|
||||
const p0 = points[i];
|
||||
const p1 = points[i + 1];
|
||||
const cpx1 = p0.x + (p1.x - p0.x) * 0.45;
|
||||
const cpx2 = p1.x - (p1.x - p0.x) * 0.45;
|
||||
d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 SVG 历史趋势平滑面积图组件。
|
||||
*
|
||||
* SVG 视口坐标系 (`viewBox="0 0 460 116"`) 布局约定:
|
||||
* - 水平绘图区:`leftX = 12` 至 `rightX = 448`(总跨度 `spanX = 436`),左右预留边距容纳端点圆点描边;
|
||||
* - 垂直绘图区:顶部峰值线 `topY = 26` 至底部零基线 `bottomY = 98`(总跨度 `spanY = 72`),
|
||||
* 顶部预留 26px 空间给 HTML 峰值胶囊 (`.trend-peak-pill`)。
|
||||
*
|
||||
* @returns {{
|
||||
* el: HTMLElement,
|
||||
* update: (series?: Array<{ label: string, tokens: number }>) => void
|
||||
* }} 图表容器节点与序列更新方法
|
||||
*/
|
||||
export function createTrendAreaChart() {
|
||||
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 460 116');
|
||||
svg.setAttribute('class', 'trend-svg');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
|
||||
// 垂直线性渐变:由顶部 36% 不透明度的主题色平滑衰减至底部全透明
|
||||
const defs = document.createElementNS(SVG_NS, 'defs');
|
||||
const grad = document.createElementNS(SVG_NS, 'linearGradient');
|
||||
grad.setAttribute('id', 'trend-area-grad');
|
||||
grad.setAttribute('x1', '0');
|
||||
grad.setAttribute('y1', '0');
|
||||
grad.setAttribute('x2', '0');
|
||||
grad.setAttribute('y2', '1');
|
||||
|
||||
const stop1 = document.createElementNS(SVG_NS, 'stop');
|
||||
stop1.setAttribute('offset', '0%');
|
||||
stop1.setAttribute('stop-color', 'var(--ctx-cached)');
|
||||
stop1.setAttribute('stop-opacity', '0.36');
|
||||
|
||||
const stop2 = document.createElementNS(SVG_NS, 'stop');
|
||||
stop2.setAttribute('offset', '100%');
|
||||
stop2.setAttribute('stop-color', 'var(--ctx-cached)');
|
||||
stop2.setAttribute('stop-opacity', '0.0');
|
||||
|
||||
grad.appendChild(stop1);
|
||||
grad.appendChild(stop2);
|
||||
defs.appendChild(grad);
|
||||
svg.appendChild(defs);
|
||||
|
||||
// 背景辅助参考网格线:3 条水平分位线 + 3 条垂直时间锚点分割线
|
||||
const gridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
gridGroup.setAttribute('class', 'trend-grid');
|
||||
for (const y of [26, 62, 98]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', '10');
|
||||
line.setAttribute('y1', String(y));
|
||||
line.setAttribute('x2', '450');
|
||||
line.setAttribute('y2', String(y));
|
||||
gridGroup.appendChild(line);
|
||||
}
|
||||
for (const x of [118, 230, 342]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', String(x));
|
||||
line.setAttribute('y1', '16');
|
||||
line.setAttribute('x2', String(x));
|
||||
line.setAttribute('y2', '98');
|
||||
gridGroup.appendChild(line);
|
||||
}
|
||||
svg.appendChild(gridGroup);
|
||||
|
||||
const areaPath = document.createElementNS(SVG_NS, 'path');
|
||||
areaPath.setAttribute('fill', 'url(#trend-area-grad)');
|
||||
svg.appendChild(areaPath);
|
||||
|
||||
const linePath = document.createElementNS(SVG_NS, 'path');
|
||||
linePath.setAttribute('class', 'trend-line');
|
||||
linePath.setAttribute('fill', 'none');
|
||||
svg.appendChild(linePath);
|
||||
|
||||
const peakDot = document.createElementNS(SVG_NS, 'circle');
|
||||
peakDot.setAttribute('r', '3');
|
||||
peakDot.setAttribute('class', 'trend-peak-dot');
|
||||
svg.appendChild(peakDot);
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]);
|
||||
|
||||
let lastLineD = '';
|
||||
|
||||
/**
|
||||
* 根据最新时间分桶序列重绘平滑曲线、闭合渐变区域以及最高峰标记位置。
|
||||
*/
|
||||
function update(series = []) {
|
||||
const slots = series.length >= 2 ? series : [
|
||||
{ label: '00:00', tokens: 0 },
|
||||
{ label: '06:00', tokens: 0 },
|
||||
{ label: '12:00', tokens: 0 },
|
||||
];
|
||||
let maxTokens = 0;
|
||||
let peakIdx = 0;
|
||||
for (let i = 0; i < slots.length; i++) {
|
||||
const t = Number(slots[i].tokens || 0);
|
||||
if (t >= maxTokens) {
|
||||
maxTokens = t;
|
||||
peakIdx = i;
|
||||
}
|
||||
}
|
||||
|
||||
// SVG 绘图区边界与跨度参数(Y 轴向下递增,因此数值越大对应的 y 坐标越小)
|
||||
const leftX = 12;
|
||||
const rightX = 448;
|
||||
const topY = 26;
|
||||
const bottomY = 98;
|
||||
const spanX = rightX - leftX;
|
||||
const spanY = bottomY - topY;
|
||||
const denom = Math.max(1, maxTokens);
|
||||
|
||||
const pts = slots.map((s, idx) => {
|
||||
const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX;
|
||||
const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0;
|
||||
const y = bottomY - ratio * spanY;
|
||||
return { x, y };
|
||||
});
|
||||
|
||||
// 仅在曲线路径发生变化时更新 DOM 属性,避免无意义的 SVG 重绘
|
||||
const lineD = buildSmoothSplinePath(pts);
|
||||
if (lineD !== lastLineD) {
|
||||
lastLineD = lineD;
|
||||
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`;
|
||||
patchAttr(linePath, 'd', lineD);
|
||||
patchAttr(areaPath, 'd', areaD);
|
||||
}
|
||||
|
||||
// 定位峰值圆点,并将顶部峰值气泡水平位置钳制在 [8%, 92%] 区间内以防贴边裁切
|
||||
const peakPt = pts[peakIdx] || { x: 230, y: bottomY };
|
||||
patchAttr(peakDot, 'cx', peakPt.x.toFixed(1));
|
||||
patchAttr(peakDot, 'cy', peakPt.y.toFixed(1));
|
||||
|
||||
patchText(peakPill, formatTokensPrecise(maxTokens));
|
||||
const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100));
|
||||
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
||||
}
|
||||
|
||||
return { el: chartWrap, update };
|
||||
}
|
||||
@@ -7,7 +7,8 @@
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { fetchTelemetry, telemetryStore } from '../../store/telemetryStore.js';
|
||||
import { fetchTelemetry, telemetryStore, triggerPluginUpdate } from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||
|
||||
export const TopSessionHeader = defineComponent({
|
||||
@@ -16,14 +17,50 @@ export const TopSessionHeader = defineComponent({
|
||||
const convSelect = CustomSelect({
|
||||
modelValue: telemetryStore.getState().selectedConversationId,
|
||||
icon: 'bolt',
|
||||
placeholder: '自动跟随最新会话',
|
||||
options: [{ value: '', label: '自动跟随最新会话' }],
|
||||
placeholder: '跟随最新会话',
|
||||
options: [{ value: '', label: '跟随最新会话' }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
||||
fetchTelemetry({ force: false });
|
||||
},
|
||||
});
|
||||
|
||||
const updateBtnIcon = createSvgIcon('arrow-down', { size: 11 });
|
||||
const updateBtnText = h('span', { text: '有新版本' });
|
||||
let isHeaderUpdating = false;
|
||||
const updateBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'update-badge-btn',
|
||||
hidden: true,
|
||||
'aria-label': '发现新版本,点击升级',
|
||||
onClick: async () => {
|
||||
if (isHeaderUpdating) return;
|
||||
isHeaderUpdating = true;
|
||||
patchText(updateBtnText, '升级中…');
|
||||
patchAttr(updateBtn, 'disabled', true);
|
||||
try {
|
||||
const res = await triggerPluginUpdate();
|
||||
if (!res?.ok) {
|
||||
uiStore.setState({ activeView: 'settings' });
|
||||
}
|
||||
} catch {
|
||||
uiStore.setState({ activeView: 'settings' });
|
||||
} finally {
|
||||
isHeaderUpdating = false;
|
||||
patchAttr(updateBtn, 'disabled', false);
|
||||
const cs = telemetryStore.getState().telemetry?.cloudStatus;
|
||||
patchText(
|
||||
updateBtnText,
|
||||
cs?.latestPluginVersion ? `升级 v${cs.latestPluginVersion}` : '有新版本'
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
[updateBtnIcon, updateBtnText]
|
||||
);
|
||||
|
||||
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
||||
const statusText = h('span', { text: '实时 2s' });
|
||||
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
||||
@@ -33,7 +70,7 @@ export const TopSessionHeader = defineComponent({
|
||||
{
|
||||
type: 'button',
|
||||
className: 'icon-btn',
|
||||
'aria-label': '立即刷新额度与测速数据',
|
||||
'aria-label': '刷新数据',
|
||||
onClick: () => fetchTelemetry({ force: true }),
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 13 })]
|
||||
@@ -41,7 +78,7 @@ export const TopSessionHeader = defineComponent({
|
||||
|
||||
const headerEl = h('header', { className: 'session-header' }, [
|
||||
h('div', { className: 'session-left' }, [convSelect.el]),
|
||||
h('div', { className: 'session-right' }, [statusTag, refreshBtn]),
|
||||
h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]),
|
||||
]);
|
||||
|
||||
const unsubTelemetry = telemetryStore.subscribe(
|
||||
@@ -51,10 +88,11 @@ export const TopSessionHeader = defineComponent({
|
||||
conversations: st.telemetry?.conversations,
|
||||
isRunning: st.telemetry?.activeConversation?.isRunning,
|
||||
quotaMeta: st.telemetry?.quotas?.meta,
|
||||
cloudStatus: st.telemetry?.cloudStatus,
|
||||
}),
|
||||
(slice) => {
|
||||
const convs = slice.conversations || [];
|
||||
const latestTitle = convs[0]?.title ? `自动跟随 (${convs[0].title})` : '自动跟随最新会话';
|
||||
const latestTitle = convs[0]?.title ? `最新 (${convs[0].title})` : '跟随最新会话';
|
||||
const options = [
|
||||
{ value: '', label: latestTitle, meta: convs[0] ? `${convs[0].stepCount}步` : '' },
|
||||
...convs.map((c) => ({
|
||||
@@ -68,6 +106,17 @@ export const TopSessionHeader = defineComponent({
|
||||
options,
|
||||
});
|
||||
|
||||
const hasUpdate = Boolean(slice.cloudStatus?.updateAvailable);
|
||||
patchAttr(updateBtn, 'hidden', !hasUpdate);
|
||||
if (hasUpdate && !isHeaderUpdating) {
|
||||
patchText(
|
||||
updateBtnText,
|
||||
slice.cloudStatus?.latestPluginVersion
|
||||
? `升级 v${slice.cloudStatus.latestPluginVersion}`
|
||||
: '有新版本'
|
||||
);
|
||||
}
|
||||
|
||||
const isSyncing = slice.syncState === 'syncing';
|
||||
const isSynced = slice.syncState === 'synced';
|
||||
const isError = slice.syncState === 'error';
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @fileoverview 通用 4 段式 Token 构成比例条组件 (FourSegmentBar).
|
||||
* 用于在消费概览、热门模型明细及数据来源明细中直观展示:
|
||||
* 直接输入 (Input)、缓存读取 (Cached)、内容生成 (Output) 与思考推理 (Thinking) 的 Token 占比。
|
||||
*/
|
||||
|
||||
import { h, patchStyleVar } from '../../core/domPatch.js';
|
||||
|
||||
/**
|
||||
* 创建 4 段式水平比例进度条实例。
|
||||
* 通过动态更新各分段节点的 `--seg-w` CSS 变量实现零重排平滑过渡。
|
||||
*
|
||||
* @returns {{
|
||||
* el: HTMLElement,
|
||||
* update: (metrics: {
|
||||
* inputTokens?: number,
|
||||
* cacheReadTokens?: number,
|
||||
* responseTokens?: number,
|
||||
* thinkingTokens?: number
|
||||
* }) => void
|
||||
* }} 组件根元素与增量更新方法
|
||||
*/
|
||||
export function createFourSegmentBar() {
|
||||
const segInput = h('div', { className: 'progress-seg seg-input' });
|
||||
const segCached = h('div', { className: 'progress-seg seg-cached' });
|
||||
const segOutput = h('div', { className: 'progress-seg seg-output' });
|
||||
const segThinking = h('div', { className: 'progress-seg seg-thinking' });
|
||||
const el = h('div', { className: 'progress-track cons-seg-bar' }, [
|
||||
segInput,
|
||||
segCached,
|
||||
segOutput,
|
||||
segThinking,
|
||||
]);
|
||||
|
||||
/**
|
||||
* 根据四类 Token 数量重新计算并写入各分段百分比宽度。
|
||||
*/
|
||||
function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0 }) {
|
||||
const total = Math.max(1, inputTokens + cacheReadTokens + responseTokens + thinkingTokens);
|
||||
patchStyleVar(segInput, '--seg-w', `${((inputTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segOutput, '--seg-w', `${((responseTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / total) * 100).toFixed(2)}%`);
|
||||
}
|
||||
|
||||
return { el, update };
|
||||
}
|
||||
@@ -50,13 +50,13 @@ export function formatUsd(amount, { precise = false, estimated = false, unpriced
|
||||
|
||||
export function speedReasonText(reason) {
|
||||
return ({
|
||||
compaction: '上下文自动压缩,不纳入均速',
|
||||
incomplete_or_invalid_timing: '未完成或计时缺失',
|
||||
invalid_output_tokens: '输出 Token 数异常',
|
||||
inconsistent_timing: '首字节响应与总耗时数据不一致',
|
||||
short_timing: '计时过短,暂不测速',
|
||||
short_sample: '样本太少,暂不计入均速',
|
||||
legacy_cache: '缓存已过期,等待刷新',
|
||||
compaction: '自动压缩步骤,不计入均速',
|
||||
incomplete_or_invalid_timing: '生成未完成',
|
||||
invalid_output_tokens: '无有效输出',
|
||||
inconsistent_timing: '耗时数据异常',
|
||||
short_timing: '耗时过短,不计入',
|
||||
short_sample: '输出过短,不计入均速',
|
||||
legacy_cache: '旧版缓存记录',
|
||||
})[reason] || '';
|
||||
}
|
||||
|
||||
|
||||
@@ -27,12 +27,36 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (!prev || !next) return false;
|
||||
if (prev === next) return true;
|
||||
|
||||
// 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关)
|
||||
const pAct = prev.activeConversation;
|
||||
const nAct = next.activeConversation;
|
||||
if (prev.settings?.showUpstreamModel !== next.settings?.showUpstreamModel) return false;
|
||||
if (prev.settings?.weeklyLimitMode !== next.settings?.weeklyLimitMode) return false;
|
||||
if (prev.settings?.weeklyTokenBudget !== next.settings?.weeklyTokenBudget) return false;
|
||||
if (prev.settings?.weeklyCostBudget !== next.settings?.weeklyCostBudget) return false;
|
||||
if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false;
|
||||
|
||||
// 2. 比对云端状态(插件当前/最新版本、价格表版本与模型数量、同步/更新执行状态及错误信息)
|
||||
const pCloud = prev.cloudStatus;
|
||||
const nCloud = next.cloudStatus;
|
||||
if (
|
||||
pCloud?.currentPluginVersion !== nCloud?.currentPluginVersion ||
|
||||
pCloud?.latestPluginVersion !== nCloud?.latestPluginVersion ||
|
||||
pCloud?.updateAvailable !== nCloud?.updateAvailable ||
|
||||
pCloud?.catalogVersion !== nCloud?.catalogVersion ||
|
||||
pCloud?.source !== nCloud?.source ||
|
||||
pCloud?.lastSyncedAtMs !== nCloud?.lastSyncedAtMs ||
|
||||
pCloud?.modelCount !== nCloud?.modelCount ||
|
||||
pCloud?.isSyncing !== nCloud?.isSyncing ||
|
||||
pCloud?.isUpdating !== nCloud?.isUpdating ||
|
||||
pCloud?.lastSyncError !== nCloud?.lastSyncError ||
|
||||
pCloud?.lastUpdateError !== nCloud?.lastUpdateError ||
|
||||
pCloud?.lastUpdateResult?.updatedAtMs !== nCloud?.lastUpdateResult?.updatedAtMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、运行状态、TPS、TTFT、当前模型标识与单步费用)
|
||||
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
||||
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
||||
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
||||
@@ -40,6 +64,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false;
|
||||
if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false;
|
||||
if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false;
|
||||
|
||||
// 4. 比对 6 通道上下文窗口构成(总 Token 与消息/系统工具/MCP/Skill/系统提示词/用户规则)及近期步骤明细
|
||||
const pCtx = pAct?.context;
|
||||
const nCtx = nAct?.context;
|
||||
if (pCtx?.totalTokens !== nCtx?.totalTokens) return false;
|
||||
@@ -57,6 +83,7 @@ function isEquivalentTelemetry(prev, next) {
|
||||
before.modelSource !== after.modelSource || before.costUsd !== after.costUsd) return false;
|
||||
}
|
||||
|
||||
// 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费
|
||||
const pRange = prev.consumption?.selectedRange;
|
||||
const nRange = next.consumption?.selectedRange;
|
||||
if (pRange?.key !== nRange?.key) return false;
|
||||
@@ -77,6 +104,7 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (pAcct?.costUsd !== nAcct?.costUsd) return false;
|
||||
if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false;
|
||||
|
||||
// 6. 比对历史趋势时间分桶序列
|
||||
const pTrend = prev.consumption?.trendSeries || [];
|
||||
const nTrend = next.consumption?.trendSeries || [];
|
||||
if (pTrend.length !== nTrend.length) return false;
|
||||
@@ -86,6 +114,7 @@ function isEquivalentTelemetry(prev, next) {
|
||||
}
|
||||
}
|
||||
|
||||
// 7. 比对按模型汇总明细与数据来源汇总明细
|
||||
const pModels = prev.modelBreakdown || [];
|
||||
const nModels = next.modelBreakdown || [];
|
||||
if (pModels.length !== nModels.length) return false;
|
||||
@@ -118,6 +147,7 @@ function isEquivalentTelemetry(prev, next) {
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 比对账号订阅档位与动态多配额池(活跃池、周汇总及各配额池的 5h/周限额进度与重置时间)
|
||||
if (prev.account?.tierName !== next.account?.tierName || prev.account?.planName !== next.account?.planName) {
|
||||
return false;
|
||||
}
|
||||
@@ -263,6 +293,25 @@ export async function saveSettingsPatch(patch) {
|
||||
await fetchTelemetry({ force: true });
|
||||
}
|
||||
|
||||
export async function triggerCloudSync() {
|
||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function triggerPluginUpdate() {
|
||||
const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} });
|
||||
if (res?.ok && res?.restarting) {
|
||||
await new Promise((r) => setTimeout(r, 1100));
|
||||
if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') {
|
||||
window.location.reload();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
|
||||
export function startAsyncTelemetryLoop(intervalMs = 2000) {
|
||||
stopAsyncTelemetryLoop();
|
||||
let active = true;
|
||||
|
||||
@@ -6,9 +6,9 @@ import { createReactiveStore } from '../core/reactive.js';
|
||||
|
||||
export const VIEW_TABS = Object.freeze([
|
||||
{ value: 'overview', label: '实时监控', icon: 'pulse' },
|
||||
{ value: 'consumption', label: '消耗统计', icon: 'chart-bar' },
|
||||
{ value: 'steps', label: '步骤明细', icon: 'table' },
|
||||
{ value: 'settings', label: '系统设置', icon: 'sliders' },
|
||||
{ value: 'consumption', label: '用量统计', icon: 'chart-bar' },
|
||||
{ value: 'steps', label: '调用明细', icon: 'table' },
|
||||
{ value: 'settings', label: '偏好设置', icon: 'sliders' },
|
||||
]);
|
||||
|
||||
export const uiStore = createReactiveStore({
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,686 @@
|
||||
/*
|
||||
* 通用交互控件与顶栏导航样式表 (controls.css).
|
||||
* 包含:
|
||||
* 1. 顶部会话控制栏 (.session-header, .status-tag, .icon-btn, .update-badge-btn)
|
||||
* 2. 顶部唯一长药丸导航栏 (.long-pill-nav, .pill-glider, .pill-tab)
|
||||
* 3. 定制下拉选择器 (.custom-select)
|
||||
* 4. 定制步进数字输入框 (.number-input)
|
||||
* 5. 定制日期时间选择器 (.datetime-picker)
|
||||
* 6. 微边框分段控制器 (.segmented)
|
||||
* 7. 独立轨道槽自定义滚动条 (.custom-scroll-host)
|
||||
* 8. 设置表单行与主次操作按钮 (.form-row, .btn-primary, .btn-secondary, .cloud-actions-row)
|
||||
*/
|
||||
|
||||
/* --- 1. 顶部会话控制栏 (Top Session Control Header) --- */
|
||||
.session-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 5px var(--space-3);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.session-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.session-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-ok) 32%, var(--border-hairline));
|
||||
background: var(--metric-ok-soft);
|
||||
color: var(--metric-ok);
|
||||
}
|
||||
|
||||
.status-tag.state-running {
|
||||
color: var(--metric-speed);
|
||||
background: var(--metric-speed-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-speed) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
.status-tag.state-synced {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
.status-tag.state-warn {
|
||||
color: var(--metric-warn);
|
||||
background: var(--metric-warn-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-warn) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
height: 24px;
|
||||
min-width: 24px;
|
||||
padding: 0 6px;
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast),
|
||||
transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.icon-btn:hover {
|
||||
background: var(--surface-hover);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.icon-btn:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
|
||||
.icon-btn.is-active {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
/* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */
|
||||
.long-pill-nav {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(var(--pill-count, 4), 1fr);
|
||||
align-items: center;
|
||||
padding: 3px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-pill);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.pill-glider {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
bottom: 3px;
|
||||
left: 3px;
|
||||
width: calc((100% - 6px) / var(--pill-count, 4));
|
||||
background: var(--accent-primary-soft);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
border-radius: var(--radius-pill);
|
||||
transform: translate3d(calc(var(--active-index, 0) * 100%), 0, 0);
|
||||
transition: transform var(--dur-fast) var(--ease-fast);
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.pill-tab {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
height: 26px;
|
||||
padding: 0 var(--space-2);
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
border-radius: var(--radius-pill);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.pill-tab .svg-icon {
|
||||
display: block;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
stroke-width: 1.65;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.pill-tab-label,
|
||||
.pill-tab-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 14px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.pill-tab-badge {
|
||||
margin-left: -2px;
|
||||
font-size: 11.5px;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.pill-tab:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.pill-tab.is-active {
|
||||
color: var(--accent-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.pill-tab.is-active .svg-icon {
|
||||
color: var(--accent-primary);
|
||||
stroke-width: 1.8;
|
||||
}
|
||||
|
||||
.pill-tab.is-active .pill-tab-badge {
|
||||
color: var(--accent-primary);
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
/* --- 3. 定制下拉选择器 (Bespoke Custom Select,零原生 <select>) --- */
|
||||
.custom-select {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.select-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
height: 24px;
|
||||
padding: 0 6px;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-trigger:hover,
|
||||
.custom-select.is-open .select-trigger {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.select-label {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.select-menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
min-width: 210px;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
background: var(--surface-panel);
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
box-shadow: var(--shadow-popover);
|
||||
padding: 4px;
|
||||
z-index: 60;
|
||||
animation: popover-in var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
padding: 5px var(--space-2);
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.select-option:hover,
|
||||
.select-option.is-focused {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.select-option.is-selected {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.select-option-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- 4. 定制步进数字框 (Bespoke Custom Number Input,零原生 <input type="number">) --- */
|
||||
.number-input {
|
||||
display: inline-flex;
|
||||
align-items: stretch;
|
||||
height: 28px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.number-input:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.num-step-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
border: none;
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast), color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.num-step-btn:hover {
|
||||
background: var(--surface-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.num-step-btn:active {
|
||||
background: var(--surface-active);
|
||||
}
|
||||
|
||||
.num-field {
|
||||
flex: 1;
|
||||
min-width: 90px;
|
||||
padding: 0 var(--space-3);
|
||||
border: none;
|
||||
border-left: 1px solid var(--border-hairline);
|
||||
border-right: 1px solid var(--border-hairline);
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* --- 5. 定制日期时间选择器 (Bespoke Custom DateTime Picker) --- */
|
||||
.datetime-picker {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex: 1;
|
||||
min-width: 145px;
|
||||
}
|
||||
|
||||
.dt-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
height: 26px;
|
||||
padding: 0 var(--space-2);
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: 11.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dt-trigger:hover {
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.dt-popover {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
left: 0;
|
||||
width: 248px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-xs);
|
||||
box-shadow: var(--shadow-popover);
|
||||
padding: var(--space-3);
|
||||
z-index: 70;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
animation: popover-in var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.dt-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.dt-weekdays,
|
||||
.dt-days {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
gap: 2px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.dt-weekday {
|
||||
font-size: 10.5px;
|
||||
color: var(--text-secondary);
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.dt-day {
|
||||
height: 22px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 11px;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dt-day:hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.dt-day.is-selected {
|
||||
background: var(--accent-primary);
|
||||
color: var(--text-inverse);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.dt-day.is-outside {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.dt-time-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding-top: var(--space-2);
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
.dt-time-controls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.dt-mini-step {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
padding: 1px 3px;
|
||||
}
|
||||
|
||||
.dt-mini-btn {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
padding: 1px 3px;
|
||||
}
|
||||
|
||||
.dt-mini-btn:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* --- 6. 微边框分段控制器 (Micro-Bezel Segmented Control) --- */
|
||||
.segmented {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.seg-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.seg-btn:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.seg-btn.is-active {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */
|
||||
.custom-scroll-host {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
gap: 5px;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.custom-scroll-host[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.custom-scroll-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
|
||||
.custom-scroll-content::-webkit-scrollbar {
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.scrollbar-rail {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 5px;
|
||||
margin: 2px 0;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--border-hairline) 35%, transparent);
|
||||
z-index: 15;
|
||||
opacity: 0.85;
|
||||
transition: opacity var(--dur-fast) var(--ease-fast), background-color var(--dur-fast) var(--ease-fast);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.custom-scroll-host:hover .scrollbar-rail,
|
||||
.scrollbar-rail.is-dragging {
|
||||
opacity: 1;
|
||||
background: color-mix(in srgb, var(--border-hairline) 65%, transparent);
|
||||
}
|
||||
|
||||
.scrollbar-rail.is-inactive {
|
||||
display: none !important;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.scrollbar-thumb {
|
||||
width: 100%;
|
||||
height: var(--thumb-h, 0px);
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
||||
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
||||
will-change: transform, height;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.scrollbar-rail:hover .scrollbar-thumb,
|
||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
||||
}
|
||||
|
||||
/* --- 8. 设置表单与按钮控件 (Settings Form & Buttons) --- */
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 11.5px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
padding: 0 var(--space-5);
|
||||
background: var(--accent-primary);
|
||||
color: var(--text-inverse);
|
||||
border: 1px solid var(--accent-primary);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.btn-primary:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
padding: 0 var(--space-4);
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast), border-color var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--surface-hover);
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
.btn-secondary:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.btn-primary:disabled,
|
||||
.btn-secondary:disabled,
|
||||
.update-badge-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.cloud-actions-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.update-badge-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.update-badge-btn[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.update-badge-btn:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.update-badge-btn:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
/*
|
||||
* 全景消耗统计视图样式表 (views-consumption.css).
|
||||
* 包含:
|
||||
* 1. 消费概览顶栏与 3+2 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-*, .cons-col)
|
||||
* 2. 4 段比例条与圆点色块 (.dot-swatch, .cons-seg-bar)
|
||||
* 3. 热门模型与数据来源列表项样式 (.cons-row-*, .cons-share-pill, .cons-item-*)
|
||||
* 4. 历史趋势纯 SVG 平滑曲线图与峰值胶囊 (.trend-*)
|
||||
* 5. 12 个月垂直堆叠柱状图与月度图例 (.monthly-*, .month-*)
|
||||
*/
|
||||
|
||||
/* --- 1. 消费概览顶栏与 3+2 组合指标矩阵 (Consumption Overview Matrix) --- */
|
||||
.cons-overview-head {
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cons-badge {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cons-box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
}
|
||||
|
||||
.cons-unified-matrix {
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
border-bottom: 1px solid var(--border-hairline);
|
||||
border-radius: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cons-split-3 {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
|
||||
.cons-split-2 {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.cons-matrix-bottom {
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.cons-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
padding: 8px 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-col:first-child {
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.cons-col:last-child {
|
||||
padding-right: 0;
|
||||
}
|
||||
|
||||
.cons-col.is-bordered-col,
|
||||
.cons-col.is-right-col {
|
||||
border-left: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.cons-baseline {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 5px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.cons-hero-num {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-hero-cost {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
color: var(--accent-primary);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-hero-cache {
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
color: var(--ctx-cached);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-mid-num {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* --- 2. 4 段比例条与圆点色块 (Four-Segment Bar & Dot Swatches) --- */
|
||||
.dot-swatch {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: var(--radius-pill);
|
||||
display: inline-block;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.dot-swatch.seg-input { background: var(--ctx-input); }
|
||||
.dot-swatch.seg-cached { background: var(--ctx-cached); }
|
||||
.dot-swatch.seg-output { background: var(--ctx-output); }
|
||||
.dot-swatch.seg-thinking { background: var(--ctx-thinking); }
|
||||
|
||||
/* --- 3. 热门模型与数据来源行头部对齐 (Popular Models & Sources Row Header) --- */
|
||||
.cons-row-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-row-metrics {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.cons-share-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
padding: 0 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--metric-ok);
|
||||
background: color-mix(in srgb, var(--metric-ok) 11%, transparent);
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.cons-row-tok {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cons-row-cost {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-seg-bar {
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
/* --- 4. 历史趋势 SVG 平滑曲线图 (Historical Trend SVG Chart) --- */
|
||||
.trend-chart-wrap {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.trend-svg {
|
||||
width: 100%;
|
||||
height: 112px;
|
||||
display: block;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.trend-grid line {
|
||||
stroke: var(--border-hairline);
|
||||
stroke-width: 1;
|
||||
stroke-dasharray: 2 3;
|
||||
}
|
||||
|
||||
.trend-line {
|
||||
stroke: var(--ctx-cached);
|
||||
stroke-width: 2;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
|
||||
.trend-peak-dot {
|
||||
fill: var(--ctx-cached);
|
||||
stroke: var(--surface-panel);
|
||||
stroke-width: 1.5;
|
||||
}
|
||||
|
||||
.trend-peak-pill {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: var(--peak-x, 50%);
|
||||
transform: translateX(-50%);
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
padding: 1px 6px;
|
||||
color: var(--text-primary);
|
||||
background: color-mix(in srgb, var(--ctx-cached) 16%, var(--surface-panel));
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.trend-anchors {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
padding-top: 2px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.trend-anchor-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.trend-anchor-col.is-center {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.trend-anchor-col.is-end {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
/* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */
|
||||
.cons-item-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.cons-item-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cons-item-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 10px;
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cons-item-foot strong {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
|
||||
.monthly-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(12, 1fr);
|
||||
gap: 3px;
|
||||
align-items: end;
|
||||
padding-top: var(--space-2);
|
||||
}
|
||||
|
||||
.month-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.month-cost {
|
||||
font-size: 9.5px;
|
||||
color: var(--text-secondary);
|
||||
min-height: 14px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.month-bar-well {
|
||||
width: 100%;
|
||||
height: 82px;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.month-stack {
|
||||
width: 72%;
|
||||
max-width: 20px;
|
||||
height: var(--bar-h, 0%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: 2px 2px 0 0;
|
||||
overflow: hidden;
|
||||
transition: height var(--dur-normal) var(--ease-fast);
|
||||
}
|
||||
|
||||
.month-seg {
|
||||
width: 100%;
|
||||
height: var(--seg-h, 0%);
|
||||
}
|
||||
|
||||
.month-seg.seg-input { background: var(--ctx-input); }
|
||||
.month-seg.seg-cached { background: var(--ctx-cached); }
|
||||
.month-seg.seg-output { background: var(--ctx-output); }
|
||||
.month-seg.seg-thinking { background: var(--ctx-thinking); }
|
||||
|
||||
.month-zero-dot {
|
||||
width: 3px;
|
||||
height: 3px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--border-strong);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.month-label {
|
||||
font-size: 10px;
|
||||
color: var(--text-secondary);
|
||||
padding: 1px 3px;
|
||||
border-radius: var(--radius-xs);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.month-label.is-current {
|
||||
color: var(--ctx-cached);
|
||||
background: color-mix(in srgb, var(--ctx-cached) 14%, transparent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.month-tok {
|
||||
font-size: 9px;
|
||||
color: var(--text-muted);
|
||||
min-height: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.monthly-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-4);
|
||||
padding-top: var(--space-2);
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* 实时概览视图与通用面板卡片样式表 (views-overview.css).
|
||||
* 包含:
|
||||
* 1. 通用面板容器与标题头 (.panel, .panel-header, .panel-title, .panel-meta)
|
||||
* 2. 4 格实时测速指标矩阵 (.telemetry-matrix, .matrix-cell, .cell-*)
|
||||
* 3. 6 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill)
|
||||
* 4. 上下文双列图例网格与色块 (.ctx-legend-grid, .legend-*, .swatch)
|
||||
* 5. 双栏布局网格与窄屏响应式断点 (.dual-grid)
|
||||
*/
|
||||
|
||||
/* --- 1. 通用微边框面板卡片 (Architectural Precision Panels) --- */
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4) var(--space-5);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.panel-meta {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11.5px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* --- 2. 4 格实时测速指标矩阵 (4-Cell Telemetry Matrix) --- */
|
||||
.telemetry-matrix {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--border-hairline);
|
||||
gap: 1px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.matrix-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 7px 9px;
|
||||
background: var(--surface-panel);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cell-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cell-value {
|
||||
font-size: 14.5px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cell-value.accent-speed {
|
||||
color: var(--metric-speed);
|
||||
}
|
||||
|
||||
.cell-value.accent-ok {
|
||||
color: var(--metric-ok);
|
||||
}
|
||||
|
||||
.cell-sub {
|
||||
font-size: 10.5px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* --- 3. 6 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */
|
||||
.progress-track {
|
||||
width: 100%;
|
||||
height: 6px;
|
||||
background: var(--surface-track);
|
||||
border-radius: var(--radius-xs);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.progress-seg {
|
||||
height: 100%;
|
||||
width: var(--seg-w, 0%);
|
||||
transition: width var(--dur-normal) var(--ease-fast);
|
||||
}
|
||||
|
||||
.progress-seg.seg-messages {
|
||||
background: var(--ctx-messages);
|
||||
}
|
||||
.progress-seg.seg-system-tools {
|
||||
background: var(--ctx-system-tools);
|
||||
}
|
||||
.progress-seg.seg-mcp-tools {
|
||||
background: var(--ctx-mcp-tools);
|
||||
}
|
||||
.progress-seg.seg-skills {
|
||||
background: var(--ctx-skills);
|
||||
}
|
||||
.progress-seg.seg-system-prompt {
|
||||
background: var(--ctx-system-prompt);
|
||||
}
|
||||
.progress-seg.seg-user-rules {
|
||||
background: var(--ctx-user-rules);
|
||||
}
|
||||
.progress-seg.seg-cached {
|
||||
background: var(--ctx-cached);
|
||||
}
|
||||
.progress-seg.seg-input {
|
||||
background: var(--ctx-input);
|
||||
}
|
||||
.progress-seg.seg-thinking {
|
||||
background: var(--ctx-thinking);
|
||||
}
|
||||
.progress-seg.seg-output {
|
||||
background: var(--ctx-output);
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
width: var(--fill-w, 0%);
|
||||
background: var(--accent-primary);
|
||||
transition: width var(--dur-normal) var(--ease-fast);
|
||||
}
|
||||
|
||||
.progress-fill.tone-warn {
|
||||
background: var(--metric-warn);
|
||||
}
|
||||
|
||||
.progress-fill.tone-danger {
|
||||
background: var(--metric-danger);
|
||||
}
|
||||
|
||||
/* --- 4. 上下文双列图例网格 (Context 6-Channel Legend Grid) --- */
|
||||
.ctx-legend-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 5px var(--space-4);
|
||||
padding: 2px 0 0 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.legend-left {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.swatch {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 1px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.swatch.seg-messages { background: var(--ctx-messages); }
|
||||
.swatch.seg-system-tools { background: var(--ctx-system-tools); }
|
||||
.swatch.seg-mcp-tools { background: var(--ctx-mcp-tools); }
|
||||
.swatch.seg-skills { background: var(--ctx-skills); }
|
||||
.swatch.seg-system-prompt { background: var(--ctx-system-prompt); }
|
||||
.swatch.seg-user-rules { background: var(--ctx-user-rules); }
|
||||
.swatch.seg-cached { background: var(--ctx-cached); }
|
||||
.swatch.seg-input { background: var(--ctx-input); }
|
||||
.swatch.seg-thinking { background: var(--ctx-thinking); }
|
||||
.swatch.seg-output { background: var(--ctx-output); }
|
||||
|
||||
/* --- 5. 双栏网格与窄视口响应式折叠 (Dual Grid & Responsive Breakpoints) --- */
|
||||
.dual-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
@media (max-width: 390px) {
|
||||
.telemetry-matrix {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
.dual-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 步骤明细与模型汇总数据表样式表 (views-tables.css).
|
||||
* 包含:
|
||||
* 1. 表格专属自定义滚动容器修饰 (.table-scroll-host)
|
||||
* 2. 表格滚动视口 (.table-viewport)
|
||||
* 3. 粘性表头与紧凑高密度数据表 (.data-table)
|
||||
*/
|
||||
|
||||
/* --- 1. 表格专属滚动容器与视口 (Table Scroll Host & Viewport) --- */
|
||||
.table-scroll-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
gap: 4px;
|
||||
padding-top: 2px;
|
||||
padding-right: 0;
|
||||
border: none;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
border-radius: 0;
|
||||
background: var(--surface-panel);
|
||||
}
|
||||
|
||||
.table-viewport {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
background: var(--surface-panel);
|
||||
}
|
||||
|
||||
/* --- 2. 粘性表头数据表 (Sticky-Header Data Table) --- */
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.data-table th,
|
||||
.data-table td {
|
||||
padding: 5px 4px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--border-hairline);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-table th:first-child,
|
||||
.data-table td:first-child {
|
||||
padding-left: 7px;
|
||||
}
|
||||
|
||||
.data-table th:last-child,
|
||||
.data-table td:last-child {
|
||||
text-align: right;
|
||||
padding-right: 10px;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.data-table tbody tr:hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
/**
|
||||
* @fileoverview View 2: ConsumptionView (全景消耗统计视图).
|
||||
* Implements the 5-part analytics layout:
|
||||
* 1. 用量概览 (Total Tokens k/M/B, USD + CNY approx, Input/Output split, Cache Hit % + Saved Cost badge, 4-color bar)
|
||||
* 2. 历史趋势 (Pure SVG smooth cubic-bezier spline area chart with peak callout and 3 time anchors)
|
||||
* 3. 热门模型 (Per-model share badge, 4-segment bar, and Input/Cache/Output/Thinking breakdown)
|
||||
* 4. 数据来源 (SOURCES breakdown with 4-segment bar)
|
||||
* 5. 按月细分 (12-month stacked vertical bar chart with cost, stacked bars, and k/M/B totals)
|
||||
* 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗:
|
||||
* 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+2 组合矩阵展示总 Token/调用次数、
|
||||
* USD/CNY 预估费用、缓存命中率与命中量、输入/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。
|
||||
* 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡与首/中/末三时间锚点。
|
||||
* 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。
|
||||
* 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。
|
||||
* 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
@@ -23,13 +24,16 @@ import {
|
||||
formatTokensPrecise,
|
||||
formatUsd,
|
||||
} from '../core/formatters.js';
|
||||
import { createSvgIcon, SVG_NS } from '../icons/SvgIcon.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { createTrendAreaChart } from '../components/charts/TrendAreaChart.js';
|
||||
import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
|
||||
/** 消耗统计顶栏支持的时间范围预设项 */
|
||||
const TIME_RANGE_OPTIONS = [
|
||||
{ value: 'today', label: '今天' },
|
||||
{ value: '24h', label: '1天' },
|
||||
@@ -40,167 +44,10 @@ const TIME_RANGE_OPTIONS = [
|
||||
{ value: 'custom', label: '自定义' },
|
||||
];
|
||||
|
||||
function createFourSegmentBar() {
|
||||
const segInput = h('div', { className: 'progress-seg seg-input' });
|
||||
const segCached = h('div', { className: 'progress-seg seg-cached' });
|
||||
const segOutput = h('div', { className: 'progress-seg seg-output' });
|
||||
const segThinking = h('div', { className: 'progress-seg seg-thinking' });
|
||||
const el = h('div', { className: 'progress-track cons-seg-bar' }, [
|
||||
segInput,
|
||||
segCached,
|
||||
segOutput,
|
||||
segThinking,
|
||||
]);
|
||||
|
||||
function update({ inputTokens = 0, cacheReadTokens = 0, responseTokens = 0, thinkingTokens = 0 }) {
|
||||
const total = Math.max(1, inputTokens + cacheReadTokens + responseTokens + thinkingTokens);
|
||||
patchStyleVar(segInput, '--seg-w', `${((inputTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segCached, '--seg-w', `${((cacheReadTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segOutput, '--seg-w', `${((responseTokens / total) * 100).toFixed(2)}%`);
|
||||
patchStyleVar(segThinking, '--seg-w', `${((thinkingTokens / total) * 100).toFixed(2)}%`);
|
||||
}
|
||||
|
||||
return { el, update };
|
||||
}
|
||||
|
||||
function buildSmoothSplinePath(points) {
|
||||
if (!points.length) return '';
|
||||
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
|
||||
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
|
||||
for (let i = 0; i < points.length - 1; i++) {
|
||||
const p0 = points[i];
|
||||
const p1 = points[i + 1];
|
||||
const cpx1 = p0.x + (p1.x - p0.x) * 0.45;
|
||||
const cpx2 = p1.x - (p1.x - p0.x) * 0.45;
|
||||
d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
function createTrendAreaChart() {
|
||||
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 460 116');
|
||||
svg.setAttribute('class', 'trend-svg');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
|
||||
const defs = document.createElementNS(SVG_NS, 'defs');
|
||||
const grad = document.createElementNS(SVG_NS, 'linearGradient');
|
||||
grad.setAttribute('id', 'trend-area-grad');
|
||||
grad.setAttribute('x1', '0');
|
||||
grad.setAttribute('y1', '0');
|
||||
grad.setAttribute('x2', '0');
|
||||
grad.setAttribute('y2', '1');
|
||||
|
||||
const stop1 = document.createElementNS(SVG_NS, 'stop');
|
||||
stop1.setAttribute('offset', '0%');
|
||||
stop1.setAttribute('stop-color', 'var(--ctx-cached)');
|
||||
stop1.setAttribute('stop-opacity', '0.36');
|
||||
|
||||
const stop2 = document.createElementNS(SVG_NS, 'stop');
|
||||
stop2.setAttribute('offset', '100%');
|
||||
stop2.setAttribute('stop-color', 'var(--ctx-cached)');
|
||||
stop2.setAttribute('stop-opacity', '0.0');
|
||||
|
||||
grad.appendChild(stop1);
|
||||
grad.appendChild(stop2);
|
||||
defs.appendChild(grad);
|
||||
svg.appendChild(defs);
|
||||
|
||||
// Subtle grid lines
|
||||
const gridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
gridGroup.setAttribute('class', 'trend-grid');
|
||||
for (const y of [26, 62, 98]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', '10');
|
||||
line.setAttribute('y1', String(y));
|
||||
line.setAttribute('x2', '450');
|
||||
line.setAttribute('y2', String(y));
|
||||
gridGroup.appendChild(line);
|
||||
}
|
||||
for (const x of [118, 230, 342]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', String(x));
|
||||
line.setAttribute('y1', '16');
|
||||
line.setAttribute('x2', String(x));
|
||||
line.setAttribute('y2', '98');
|
||||
gridGroup.appendChild(line);
|
||||
}
|
||||
svg.appendChild(gridGroup);
|
||||
|
||||
const areaPath = document.createElementNS(SVG_NS, 'path');
|
||||
areaPath.setAttribute('fill', 'url(#trend-area-grad)');
|
||||
svg.appendChild(areaPath);
|
||||
|
||||
const linePath = document.createElementNS(SVG_NS, 'path');
|
||||
linePath.setAttribute('class', 'trend-line');
|
||||
linePath.setAttribute('fill', 'none');
|
||||
svg.appendChild(linePath);
|
||||
|
||||
const peakDot = document.createElementNS(SVG_NS, 'circle');
|
||||
peakDot.setAttribute('r', '3');
|
||||
peakDot.setAttribute('class', 'trend-peak-dot');
|
||||
svg.appendChild(peakDot);
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]);
|
||||
|
||||
let lastLineD = '';
|
||||
|
||||
function update(series = []) {
|
||||
const slots = series.length >= 2 ? series : [
|
||||
{ label: '00:00', tokens: 0 },
|
||||
{ label: '06:00', tokens: 0 },
|
||||
{ label: '12:00', tokens: 0 },
|
||||
];
|
||||
let maxTokens = 0;
|
||||
let peakIdx = 0;
|
||||
for (let i = 0; i < slots.length; i++) {
|
||||
const t = Number(slots[i].tokens || 0);
|
||||
if (t >= maxTokens) {
|
||||
maxTokens = t;
|
||||
peakIdx = i;
|
||||
}
|
||||
}
|
||||
|
||||
const leftX = 12;
|
||||
const rightX = 448;
|
||||
const topY = 26;
|
||||
const bottomY = 98;
|
||||
const spanX = rightX - leftX;
|
||||
const spanY = bottomY - topY;
|
||||
const denom = Math.max(1, maxTokens);
|
||||
|
||||
const pts = slots.map((s, idx) => {
|
||||
const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX;
|
||||
const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0;
|
||||
const y = bottomY - ratio * spanY;
|
||||
return { x, y };
|
||||
});
|
||||
|
||||
const lineD = buildSmoothSplinePath(pts);
|
||||
if (lineD !== lastLineD) {
|
||||
lastLineD = lineD;
|
||||
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`;
|
||||
patchAttr(linePath, 'd', lineD);
|
||||
patchAttr(areaPath, 'd', areaD);
|
||||
}
|
||||
|
||||
const peakPt = pts[peakIdx] || { x: 230, y: bottomY };
|
||||
patchAttr(peakDot, 'cx', peakPt.x.toFixed(1));
|
||||
patchAttr(peakDot, 'cy', peakPt.y.toFixed(1));
|
||||
|
||||
patchText(peakPill, formatTokensPrecise(maxTokens));
|
||||
const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100));
|
||||
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
||||
}
|
||||
|
||||
return { el: chartWrap, update };
|
||||
}
|
||||
|
||||
export const ConsumptionView = defineComponent({
|
||||
name: 'ConsumptionView',
|
||||
setup({ onCleanup }) {
|
||||
// Default to 'today' if store is on initial 'all' or keep user's selection
|
||||
// --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 ---
|
||||
const timeFilterSwitch = SegmentedControl({
|
||||
ariaLabel: '消耗统计时间范围',
|
||||
modelValue: telemetryStore.getState().selectedTimeRange,
|
||||
@@ -254,10 +101,10 @@ export const ConsumptionView = defineComponent({
|
||||
]
|
||||
);
|
||||
|
||||
// --- Section 1: 用量概览 (Compact Integrated Overview) ---
|
||||
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 2 列输入/输出拆分 + 底部 4 段比例条) ---
|
||||
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' });
|
||||
const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' });
|
||||
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 调用' });
|
||||
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' });
|
||||
const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' });
|
||||
const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '≈ ¥0' });
|
||||
|
||||
@@ -266,18 +113,18 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '直接输入 0 · 缓存读取 0' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '新输入 0 · 缓存 0' });
|
||||
|
||||
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '内容生成 0 · 思考推理 0' });
|
||||
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '回复 0 · 思考 0' });
|
||||
|
||||
const overviewSegBar = createFourSegmentBar();
|
||||
|
||||
const overviewPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header cons-overview-head' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
h('span', { text: '用量概览' }),
|
||||
h('span', { text: '用量总览' }),
|
||||
dateSpanBadge,
|
||||
]),
|
||||
timeFilterSwitch.el,
|
||||
@@ -286,7 +133,7 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-box cons-unified-matrix' }, [
|
||||
h('div', { className: 'cons-split-3' }, [
|
||||
h('div', { className: 'cons-col' }, [
|
||||
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token 数' }),
|
||||
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token' }),
|
||||
h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]),
|
||||
]),
|
||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||
@@ -329,7 +176,7 @@ export const ConsumptionView = defineComponent({
|
||||
overviewSegBar.el,
|
||||
]);
|
||||
|
||||
// --- Section 2: 历史趋势 (Historical Trend SVG Spline Area Chart) ---
|
||||
// --- Section 2: 历史趋势 (SVG 三次贝塞尔平滑曲线图 + 首/中/末三时间锚点) ---
|
||||
const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' });
|
||||
const trendChart = createTrendAreaChart();
|
||||
const anchorStartTime = h('span', { className: 'text-muted text-mono', text: '00:00' });
|
||||
@@ -341,7 +188,7 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
const trendPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '历史趋势' }),
|
||||
h('span', { className: 'panel-title', text: '用量趋势' }),
|
||||
trendRangeBadge,
|
||||
]),
|
||||
trendChart.el,
|
||||
@@ -352,25 +199,25 @@ export const ConsumptionView = defineComponent({
|
||||
]),
|
||||
]);
|
||||
|
||||
// --- Section 3: 热门模型 (Popular Models Breakdown) ---
|
||||
// --- Section 3: 模型排行列表 ---
|
||||
const modelsListEl = h('div', { className: 'cons-item-list' });
|
||||
const modelsPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '热门模型' }),
|
||||
h('span', { className: 'panel-title', text: '模型排行' }),
|
||||
]),
|
||||
modelsListEl,
|
||||
]);
|
||||
|
||||
// --- Section 4: 数据来源 ---
|
||||
// --- Section 4: 客户端来源列表 ---
|
||||
const sourcesListEl = h('div', { className: 'cons-item-list' });
|
||||
const sourcesPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '数据来源' }),
|
||||
h('span', { className: 'panel-title', text: '客户端来源' }),
|
||||
]),
|
||||
sourcesListEl,
|
||||
]);
|
||||
|
||||
// --- Section 5: 按月细分 (12-Month Stacked Bar Chart) ---
|
||||
// --- Section 5: 按月细分 (12 个月垂直 4 段堆叠柱状图) ---
|
||||
const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' });
|
||||
const monthlyCols = Array.from({ length: 12 }, (_, idx) => {
|
||||
const costText = h('span', { className: 'month-cost text-mono', text: '' });
|
||||
@@ -410,7 +257,7 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
const monthlyPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '按月细分' }),
|
||||
h('span', { className: 'panel-title', text: '月度统计' }),
|
||||
monthlyYearBadge,
|
||||
]),
|
||||
h(
|
||||
@@ -457,6 +304,9 @@ export const ConsumptionView = defineComponent({
|
||||
className: 'view-pane',
|
||||
});
|
||||
|
||||
/**
|
||||
* 创建热门模型或数据来源的通用单行 DOM 结构(含标题、占比胶囊、总量、费用、4 段条与底部分项脚标)。
|
||||
*/
|
||||
function createBreakdownItemRow() {
|
||||
const nameEl = h('strong', { className: 'cons-row-title' });
|
||||
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
|
||||
@@ -514,6 +364,9 @@ export const ConsumptionView = defineComponent({
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。
|
||||
*/
|
||||
function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) {
|
||||
patchText(refs.nameEl, item.label || item.name || item.shortName || '—');
|
||||
const total = Number(item.totalTokens || 0);
|
||||
@@ -546,6 +399,9 @@ export const ConsumptionView = defineComponent({
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
|
||||
/**
|
||||
* 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。
|
||||
*/
|
||||
function renderConsumptionData(slice) {
|
||||
if (!slice) return;
|
||||
timeFilterSwitch.setValue(slice.range);
|
||||
@@ -561,7 +417,7 @@ export const ConsumptionView = defineComponent({
|
||||
const acct = preset?.account || cons.account || {};
|
||||
const rangeInfo = cons.selectedRange || {};
|
||||
|
||||
// 1. Overview
|
||||
// 1. 同步用量概览矩阵与顶部 4 段比例条
|
||||
patchText(dateSpanBadge, formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs));
|
||||
const totalTokens = Number(acct.totalTokens || 0);
|
||||
const inputTokens = Number(acct.inputTokens || 0);
|
||||
@@ -572,7 +428,7 @@ export const ConsumptionView = defineComponent({
|
||||
const costUsd = Number(acct.costUsd || 0);
|
||||
|
||||
patchText(heroTotalTokens, formatTokensPrecise(totalTokens));
|
||||
patchText(heroTotalCalls, `${acct.calls || 0} 调用`);
|
||||
patchText(heroTotalCalls, `${acct.calls || 0} 次`);
|
||||
patchText(heroCostUsd, formatUsd(costUsd, { unpricedCalls: acct.unpricedCalls }));
|
||||
patchText(heroCostCny, acct.unpricedCalls > 0 ? `${acct.unpricedCalls} 步费用待定` : formatCnyApprox(costUsd));
|
||||
|
||||
@@ -585,14 +441,14 @@ export const ConsumptionView = defineComponent({
|
||||
patchText(inputMainTokens, formatTokensPrecise(inputTokens));
|
||||
patchText(
|
||||
inputSubText,
|
||||
`直接输入 ${formatTokensPrecise(inputTokens)} · 缓存读取 ${formatTokensPrecise(cacheTokens)}`
|
||||
`新输入 ${formatTokensPrecise(inputTokens)} · 缓存 ${formatTokensPrecise(cacheTokens)}`
|
||||
);
|
||||
|
||||
patchText(outputSharePct, `${outPct}%`);
|
||||
patchText(outputMainTokens, formatTokensPrecise(outputTokens));
|
||||
patchText(
|
||||
outputSubText,
|
||||
`内容生成 ${formatTokensPrecise(responseTokens)} · 思考推理 ${formatTokensPrecise(thinkingTokens)}`
|
||||
`回复 ${formatTokensPrecise(responseTokens)} · 思考 ${formatTokensPrecise(thinkingTokens)}`
|
||||
);
|
||||
|
||||
overviewSegBar.update({
|
||||
@@ -602,7 +458,7 @@ export const ConsumptionView = defineComponent({
|
||||
thinkingTokens,
|
||||
});
|
||||
|
||||
// 2. Historical Trend
|
||||
// 2. 同步历史趋势 SVG 面积图与首/中/末三时间锚点
|
||||
patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间');
|
||||
const trendSeries = cons.trendSeries || [];
|
||||
trendChart.update(trendSeries);
|
||||
@@ -618,7 +474,7 @@ export const ConsumptionView = defineComponent({
|
||||
patchText(anchorEndVal, formatTokensPrecise(last.tokens));
|
||||
}
|
||||
|
||||
// 3. Popular Models
|
||||
// 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账)
|
||||
const models = (slice.modelBreakdown || [])
|
||||
.slice()
|
||||
.sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0));
|
||||
@@ -632,7 +488,7 @@ export const ConsumptionView = defineComponent({
|
||||
updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true),
|
||||
});
|
||||
|
||||
// 4. Sources Breakdown
|
||||
// 4. 同步数据来源列表
|
||||
const sources = cons.sourcesBreakdown || [];
|
||||
const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0);
|
||||
patchKeyedList(sourcesListEl, sources, {
|
||||
@@ -642,7 +498,7 @@ export const ConsumptionView = defineComponent({
|
||||
updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true),
|
||||
});
|
||||
|
||||
// 5. Monthly Breakdown
|
||||
// 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度)
|
||||
const monthlyYear = cons.monthlyYear || new Date().getFullYear();
|
||||
const currentMonthIdx = new Date().getMonth();
|
||||
patchText(monthlyYearBadge, String(monthlyYear));
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
/**
|
||||
* @fileoverview View 1: LiveOverviewView (实时监控视图).
|
||||
* Displays real-time TPS, TTFT, weighted mean speed, 4-channel Context Window
|
||||
* breakdown automatically anchored to the current model's compaction baseline,
|
||||
* and official 5h/weekly quota pools for both Gemini and Claude & GPT.
|
||||
* 负责展示当前活跃会话的核心实时遥测指标:
|
||||
* 1. 4 格实时测速矩阵:实时吞吐 (TPS)、首 Token 延迟 (TTFT)、会话有效加权均速与本步费用/缓存命中率;
|
||||
* 2. 6 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`),
|
||||
* 通过 6 段进度条与双列图例展示消息、系统工具、MCP 工具、Skill、系统提示词与用户规则的 Token 占用;
|
||||
* 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon 周配额池、Claude & GPT 等动态配额池,
|
||||
* 自动适配 5h/每周双窗口或单窗口模式,并展示本机周累计消耗与 AI 积分脚标。
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
@@ -31,7 +34,7 @@ import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
export const LiveOverviewView = defineComponent({
|
||||
name: 'LiveOverviewView',
|
||||
setup({ onCleanup }) {
|
||||
// 1. 4-Cell Real-time Telemetry Matrix
|
||||
// --- 1. 4 格实时测速矩阵 (实时吞吐 / 首Token / 会话均速 / 本步消费) ---
|
||||
const tpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' });
|
||||
const tpsSub = h('span', { className: 'cell-sub', text: '模型未知' });
|
||||
const pulseDot = createSvgIcon('dot', { size: 10 });
|
||||
@@ -45,15 +48,15 @@ export const LiveOverviewView = defineComponent({
|
||||
const costVal = h('strong', { className: 'cell-value', text: '$0.000' });
|
||||
const cacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累计 $0.00' });
|
||||
|
||||
const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '核心测速指标' }, [
|
||||
const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '实时指标' }, [
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('div', { className: 'cell-label' }, [h('span', { text: '实时吞吐' }), pulseDot]),
|
||||
h('div', { className: 'cell-label' }, [h('span', { text: '输出速度' }), pulseDot]),
|
||||
tpsVal,
|
||||
tpsSub,
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('div', { className: 'cell-label' }, [
|
||||
h('span', { text: '首Token' }),
|
||||
h('span', { text: '首字延迟' }),
|
||||
createSvgIcon('clock', { size: 11 }),
|
||||
]),
|
||||
ttftVal,
|
||||
@@ -61,7 +64,7 @@ export const LiveOverviewView = defineComponent({
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('div', { className: 'cell-label' }, [
|
||||
h('span', { text: '会话均速' }),
|
||||
h('span', { text: '平均速度' }),
|
||||
createSvgIcon('pulse', { size: 11 }),
|
||||
]),
|
||||
avgVal,
|
||||
@@ -69,7 +72,7 @@ export const LiveOverviewView = defineComponent({
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('div', { className: 'cell-label' }, [
|
||||
h('span', { text: '本步消费' }),
|
||||
h('span', { text: '本次费用' }),
|
||||
createSvgIcon('bolt', { size: 11 }),
|
||||
]),
|
||||
costVal,
|
||||
@@ -77,7 +80,7 @@ export const LiveOverviewView = defineComponent({
|
||||
]),
|
||||
]);
|
||||
|
||||
// 2. Context Window 6-Segment Panel (Auto Compaction Baseline)
|
||||
// --- 2. 6 段上下文窗口构成面板(自动锚定模型上下文压缩基线) ---
|
||||
const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' });
|
||||
const ctxSegmentBar = ContextSegmentMeter({ context: {} });
|
||||
|
||||
@@ -92,7 +95,7 @@ export const LiveOverviewView = defineComponent({
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('layers', { size: 13 }),
|
||||
h('span', { text: '上下文窗口构成' }),
|
||||
h('span', { text: '上下文占用' }),
|
||||
]),
|
||||
h('span', { className: 'panel-meta' }, [ctxSummaryText]),
|
||||
]),
|
||||
@@ -143,10 +146,13 @@ export const LiveOverviewView = defineComponent({
|
||||
]),
|
||||
]);
|
||||
|
||||
// 3. Official 5h & Weekly Quotas Panel (Dynamic Pools: Gemini, Argon on Pro, Claude & GPT, etc.)
|
||||
// --- 3. 官方动态多配额池监控面板 (Gemini / Pro 独立 Argon 池 / Claude & GPT) ---
|
||||
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
||||
const poolsListEl = h('div', { style: 'display: flex; flex-direction: column; gap: 0;' });
|
||||
|
||||
/**
|
||||
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
|
||||
*/
|
||||
function createPoolQuotaRow() {
|
||||
const title5h = h('span', { text: '5h 限额' });
|
||||
const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' });
|
||||
@@ -175,14 +181,14 @@ export const LiveOverviewView = defineComponent({
|
||||
};
|
||||
}
|
||||
|
||||
const wkFootLeft = h('span', { className: 'text-muted', text: '本周本机: 0 ($0.00)' });
|
||||
const wkFootLeft = h('span', { className: 'text-muted', text: '本周累计: 0 ($0.00)' });
|
||||
const wkFootRight = h('span', { className: 'text-muted', text: '' });
|
||||
|
||||
const quotaPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('pulse', { size: 13 }),
|
||||
h('span', { text: '官方配额与周期监控' }),
|
||||
h('span', { text: '可用额度' }),
|
||||
]),
|
||||
tierBadge,
|
||||
]),
|
||||
@@ -205,6 +211,12 @@ export const LiveOverviewView = defineComponent({
|
||||
className: 'view-pane',
|
||||
});
|
||||
|
||||
/**
|
||||
* 同步单个配额池行的 5h 与每周窗口状态:
|
||||
* - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行;
|
||||
* - 对于仅有 5h 限额的配额池自动隐藏每周行;
|
||||
* - 若两个窗口均无数据(如首次拉取失败),则同时保留两行并显示“获取失败 (--%)”占位提示。
|
||||
*/
|
||||
function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
||||
const { poolData, poolLabel, fallbackWeekly, isActivePool } = item;
|
||||
patchAttr(
|
||||
@@ -229,8 +241,7 @@ export const LiveOverviewView = defineComponent({
|
||||
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
|
||||
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
|
||||
|
||||
// Hide non-applicable window on weekly-only pools (e.g. Pro Argon pool or Plus tier)
|
||||
// or 5h-only pools, while still showing both rows with error state if both failed.
|
||||
// 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口
|
||||
const hide5h = !has5h && hasWk;
|
||||
const hideWk = !hasWk && has5h;
|
||||
refs.row5h.hidden = hide5h;
|
||||
@@ -272,13 +283,16 @@ export const LiveOverviewView = defineComponent({
|
||||
let latestData = null;
|
||||
let isDirty = false;
|
||||
|
||||
/**
|
||||
* 将最新遥测载荷渲染至 4 格测速矩阵、6 段上下文进度条与动态配额池列表。
|
||||
*/
|
||||
function renderData(data) {
|
||||
if (!data) return;
|
||||
const active = data.activeConversation || {};
|
||||
const ctx = active.context || {};
|
||||
const quotas = data.quotas || {};
|
||||
|
||||
// 1. Matrix
|
||||
// 1. 更新 4 格实时测速矩阵
|
||||
patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) });
|
||||
patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s'));
|
||||
const reason = speedReasonText(active.latestSpeedReason);
|
||||
@@ -300,7 +314,7 @@ export const LiveOverviewView = defineComponent({
|
||||
`缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}`
|
||||
);
|
||||
|
||||
// 2. Context (Auto Compaction Baseline)
|
||||
// 2. 更新 6 段上下文窗口构成(优先使用模型自动压缩基线 compactionLimitTokens)
|
||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTokens = Number(ctx.totalTokens || 0);
|
||||
const usedPct =
|
||||
@@ -317,7 +331,7 @@ export const LiveOverviewView = defineComponent({
|
||||
patchText(bdSystemPrompt, formatTokens(ctx.systemPromptTokens || 0));
|
||||
patchText(bdUserRules, formatTokens(ctx.userRulesTokens || 0));
|
||||
|
||||
// 3. Quotas (Dynamic Pools: Gemini, Argon on Pro, Claude & GPT, etc.)
|
||||
// 3. 更新动态配额池列表(支持 Gemini、Pro 独立 Argon 池、Claude & GPT 等)
|
||||
patchText(
|
||||
tierBadge,
|
||||
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
|
||||
@@ -359,13 +373,13 @@ export const LiveOverviewView = defineComponent({
|
||||
|
||||
patchText(
|
||||
wkFootLeft,
|
||||
`本周本机: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0, { unpricedCalls: weekly.unpricedCalls })})`
|
||||
`本周累计: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0, { unpricedCalls: weekly.unpricedCalls })})`
|
||||
);
|
||||
patchText(
|
||||
wkFootRight,
|
||||
data.account?.aiCredits > 0
|
||||
? `AI 积分: ${data.account.aiCredits}`
|
||||
: `本机调用: ${weekly.calls || 0} 步`
|
||||
: `本周调用: ${weekly.calls || 0} 次`
|
||||
);
|
||||
|
||||
viewScrollbar.refresh();
|
||||
|
||||
@@ -1,50 +1,81 @@
|
||||
/**
|
||||
* @fileoverview View 4: SettingsView (系统设置视图).
|
||||
* Replaces all native form controls (<select>, <input type="number">) with
|
||||
* bespoke CustomSelect and CustomNumberInput components.
|
||||
* 采用定制的 `CustomSelect` 与 `CustomNumberInput` 替代所有原生表单控件,分为两个设置面板:
|
||||
* 1. 本地配额监控与预算表单:配置模型名称显示方式(内部代号/实际模型名)、周用量计算模式及自定义 Token/USD 预算;
|
||||
* 2. 云端价格同步与插件更新面板:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
import { h, patchText } from '../core/domPatch.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import {
|
||||
saveSettingsPatch,
|
||||
telemetryStore,
|
||||
triggerCloudSync,
|
||||
triggerPluginUpdate,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { CustomNumberInput } from '../components/ui/CustomNumberInput.js';
|
||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
|
||||
/** 每周配额计算模式可选项 */
|
||||
const WEEKLY_MODE_OPTIONS = [
|
||||
{ value: 'official', label: '官方周限额 (自动同步)' },
|
||||
{ value: 'custom_tokens', label: '自定义 Token 预算' },
|
||||
{ value: 'custom_cost', label: '自定义费用预算 (USD)' },
|
||||
{ value: 'official', label: '跟随官方额度' },
|
||||
{ value: 'custom_tokens', label: '自定义 Token 上限' },
|
||||
{ value: 'custom_cost', label: '自定义费用上限 (USD)' },
|
||||
];
|
||||
|
||||
/** 步骤明细表中的模型名称显示方式可选项 */
|
||||
const STEP_MODEL_DISPLAY_OPTIONS = [
|
||||
{ value: 'short', label: 'Antigravity 内部代号 (如 argon-4-high / flash-3.8-high)' },
|
||||
{ value: 'upstream', label: '模型实际名称 (如 gemini-4-argon / gemini-3.8-flash-n)' },
|
||||
{ value: 'short', label: '精简代号 (如 argon-4-high)' },
|
||||
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
||||
];
|
||||
|
||||
/** 插件版本更新策略可选项 */
|
||||
const AUTO_UPDATE_OPTIONS = [
|
||||
{ value: 'manual', label: '仅提示新版本,手动更新 (推荐)' },
|
||||
{ value: 'auto', label: '后台自动安装新版本' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 格式化云端价格目录的最近同步时间或版本日期文本。
|
||||
*/
|
||||
function formatSyncTimeText(tsMs, updatedAt) {
|
||||
if (Number(tsMs) > 0) {
|
||||
const d = new Date(Number(tsMs));
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `更新于 ${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
if (updatedAt) {
|
||||
return `发布于 ${String(updatedAt).slice(0, 10)}`;
|
||||
}
|
||||
return '默认价格';
|
||||
}
|
||||
|
||||
export const SettingsView = defineComponent({
|
||||
name: 'SettingsView',
|
||||
setup({ onCleanup }) {
|
||||
// --- 面板 1:本地配额监控与预算表单状态与控件 ---
|
||||
let draftMode = 'official';
|
||||
let draftTokens = 150000000;
|
||||
let draftCost = 100;
|
||||
let draftShowUpstreamModel = false;
|
||||
let draftAutoUpdatePlugin = false;
|
||||
let statusTimer = null;
|
||||
let cloudTimer = null;
|
||||
let lastSyncedSettingsSig = '';
|
||||
|
||||
const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
|
||||
/** 在本地预算面板右上角展示短暂的保存状态提示 */
|
||||
function showSaveFeedback(text) {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
patchText(saveStatusText, text);
|
||||
if (text === '设置已生效') {
|
||||
if (text === '已保存') {
|
||||
statusTimer = setTimeout(() => {
|
||||
statusTimer = null;
|
||||
patchText(saveStatusText, '');
|
||||
@@ -52,6 +83,21 @@ export const SettingsView = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
/** 在云端同步面板右上角展示同步或更新进度提示 */
|
||||
function showCloudFeedback(text, autoClearMs = 3500) {
|
||||
if (cloudTimer) {
|
||||
clearTimeout(cloudTimer);
|
||||
cloudTimer = null;
|
||||
}
|
||||
patchText(cloudStatusMsg, text);
|
||||
if (autoClearMs > 0) {
|
||||
cloudTimer = setTimeout(() => {
|
||||
cloudTimer = null;
|
||||
patchText(cloudStatusMsg, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
const modeSelect = CustomSelect({
|
||||
modelValue: draftMode,
|
||||
icon: 'sliders',
|
||||
@@ -61,6 +107,7 @@ export const SettingsView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
// 模型名显示方式切换后立即持久化并刷新遥测数据
|
||||
const stepModelSelect = CustomSelect({
|
||||
modelValue: 'short',
|
||||
icon: 'table',
|
||||
@@ -73,11 +120,32 @@ export const SettingsView = defineComponent({
|
||||
showUpstreamModel: draftShowUpstreamModel,
|
||||
});
|
||||
}
|
||||
showSaveFeedback('正在保存…');
|
||||
showSaveFeedback('保存中…');
|
||||
await saveSettingsPatch({
|
||||
showUpstreamModel: draftShowUpstreamModel,
|
||||
});
|
||||
showSaveFeedback('设置已生效');
|
||||
showSaveFeedback('已保存');
|
||||
},
|
||||
});
|
||||
|
||||
// 插件自动更新策略切换后立即保存至后端
|
||||
const autoUpdateSelect = CustomSelect({
|
||||
modelValue: 'manual',
|
||||
icon: 'refresh',
|
||||
options: AUTO_UPDATE_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
draftAutoUpdatePlugin = val === 'auto';
|
||||
if (latestSettings) {
|
||||
lastSyncedSettingsSig = settingsSig({
|
||||
...latestSettings,
|
||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
||||
});
|
||||
}
|
||||
showCloudFeedback('保存中…', 0);
|
||||
await saveSettingsPatch({
|
||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
||||
});
|
||||
showCloudFeedback('已保存', 1800);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -107,58 +175,174 @@ export const SettingsView = defineComponent({
|
||||
type: 'button',
|
||||
className: 'btn-primary',
|
||||
onClick: async () => {
|
||||
showSaveFeedback('正在保存…');
|
||||
showSaveFeedback('保存中…');
|
||||
await saveSettingsPatch({
|
||||
weeklyLimitMode: draftMode,
|
||||
weeklyTokenBudget: draftTokens,
|
||||
weeklyCostBudget: draftCost,
|
||||
showUpstreamModel: draftShowUpstreamModel,
|
||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
||||
});
|
||||
showSaveFeedback('设置已生效');
|
||||
showSaveFeedback('已保存');
|
||||
},
|
||||
},
|
||||
[createSvgIcon('check', { size: 13 }), h('span', { text: '保存参数设置' })]
|
||||
[createSvgIcon('check', { size: 13 }), h('span', { text: '保存设置' })]
|
||||
);
|
||||
|
||||
const budgetPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
h('span', { text: '配额监控与预算设置' }),
|
||||
h('span', { text: '常规设置' }),
|
||||
]),
|
||||
saveStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '步骤表中的模型名显示方式' }),
|
||||
h('span', { className: 'form-label', text: '模型名称格式' }),
|
||||
stepModelSelect.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '每周用量的计算方式' }),
|
||||
h('span', { className: 'form-label', text: '周额度基准' }),
|
||||
modeSelect.el,
|
||||
]),
|
||||
h('div', { className: 'dual-grid' }, [
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '每周 Token 预算 (每次调整 1M)' }),
|
||||
h('span', { className: 'form-label', text: '每周 Token 上限' }),
|
||||
tokenBudgetInput.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '每周费用预算 (每次调整 $5)' }),
|
||||
h('span', { className: 'form-label', text: '每周费用上限 ($)' }),
|
||||
costBudgetInput.el,
|
||||
]),
|
||||
]),
|
||||
h('div', { style: 'display: flex; justify-content: flex-end;' }, [saveBtn]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'view-pane' }, [budgetPanel]);
|
||||
// --- 面板 2:版本更新面板 ---
|
||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.0' });
|
||||
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
|
||||
|
||||
const syncPricingBtnText = h('span', { text: '更新价格表' });
|
||||
const syncPricingBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(syncPricingBtn, 'disabled', true);
|
||||
patchText(syncPricingBtnText, '更新中…');
|
||||
showCloudFeedback('正在同步价格表…', 0);
|
||||
try {
|
||||
const res = await triggerCloudSync();
|
||||
const cs = res?.cloudStatus;
|
||||
if (res?.ok && cs) {
|
||||
showCloudFeedback(`价格表已更新 (${cs.modelCount} 个模型)`, 3500);
|
||||
} else {
|
||||
showCloudFeedback(cs?.lastSyncError || '连接超时,使用本地价格表', 4500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || '同步失败,使用本地价格表', 4500);
|
||||
} finally {
|
||||
patchAttr(syncPricingBtn, 'disabled', false);
|
||||
patchText(syncPricingBtnText, '更新价格表');
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 12 }), syncPricingBtnText]
|
||||
);
|
||||
|
||||
const updatePluginBtnText = h('span', { text: '检查更新' });
|
||||
const updatePluginBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(updatePluginBtn, 'disabled', true);
|
||||
try {
|
||||
if (!latestCloudStatus?.updateAvailable) {
|
||||
patchText(updatePluginBtnText, '检查中…');
|
||||
showCloudFeedback('正在检查新版本…', 0);
|
||||
const syncRes = await triggerCloudSync();
|
||||
const cs = syncRes?.cloudStatus || latestCloudStatus;
|
||||
if (cs) {
|
||||
latestCloudStatus = cs;
|
||||
renderCloudStatus(cs);
|
||||
}
|
||||
if (!syncRes?.ok && cs?.lastSyncError) {
|
||||
showCloudFeedback(`检查失败:${cs.lastSyncError}`, 5000);
|
||||
return;
|
||||
}
|
||||
if (!cs?.updateAvailable) {
|
||||
const curVer = cs?.currentPluginVersion || '1.4.0';
|
||||
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
|
||||
return;
|
||||
}
|
||||
}
|
||||
patchText(updatePluginBtnText, '更新中…');
|
||||
showCloudFeedback('正在下载更新…', 0);
|
||||
const res = await triggerPluginUpdate();
|
||||
if (res?.cloudStatus) {
|
||||
latestCloudStatus = res.cloudStatus;
|
||||
}
|
||||
if (res?.ok) {
|
||||
showCloudFeedback(res.message || '更新完成,正在重启面板…', 5000);
|
||||
} else {
|
||||
showCloudFeedback(res?.message || '未执行更新', 5500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || '更新失败', 5000);
|
||||
} finally {
|
||||
patchAttr(updatePluginBtn, 'disabled', false);
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText]
|
||||
);
|
||||
|
||||
const cloudPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('bolt', { size: 13 }),
|
||||
h('span', { text: '版本更新' }),
|
||||
]),
|
||||
cloudStatusMsg,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '自动更新' }),
|
||||
autoUpdateSelect.el,
|
||||
]),
|
||||
h('div', { className: 'dual-grid' }, [
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('span', { className: 'cell-label', text: '价格表' }),
|
||||
pricingCountVal,
|
||||
pricingSyncSub,
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('span', { className: 'cell-label', text: '当前版本' }),
|
||||
versionVal,
|
||||
versionSub,
|
||||
]),
|
||||
]),
|
||||
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'view-pane' }, [budgetPanel, cloudPanel]);
|
||||
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
let isDirty = false;
|
||||
|
||||
/** 生成设置项签名,避免轮询返回相同配置时覆盖用户正在编辑的草稿值 */
|
||||
function settingsSig(s) {
|
||||
if (!s) return '';
|
||||
return `${s.weeklyLimitMode}:${s.weeklyTokenBudget}:${s.weeklyCostBudget}:${Boolean(s.showUpstreamModel)}`;
|
||||
return `${s.weeklyLimitMode}:${s.weeklyTokenBudget}:${s.weeklyCostBudget}:${Boolean(s.showUpstreamModel)}:${Boolean(s.autoUpdatePlugin)}`;
|
||||
}
|
||||
|
||||
/** 将后端返回的最新设置同步至表单控件 */
|
||||
function renderSettings(settings) {
|
||||
if (!settings) return;
|
||||
const nextSig = settingsSig(settings);
|
||||
@@ -172,22 +356,65 @@ export const SettingsView = defineComponent({
|
||||
draftTokens = Number(settings.weeklyTokenBudget || 150000000);
|
||||
draftCost = Number(settings.weeklyCostBudget || 100);
|
||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||
draftAutoUpdatePlugin = Boolean(settings.autoUpdatePlugin);
|
||||
modeSelect.setValue(draftMode);
|
||||
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
||||
autoUpdateSelect.setValue(draftAutoUpdatePlugin ? 'auto' : 'manual');
|
||||
tokenBudgetInput.setValue(draftTokens);
|
||||
costBudgetInput.setValue(draftCost);
|
||||
}
|
||||
|
||||
/** 将云端价格表统计与插件版本对比状态同步至云端面板 */
|
||||
function renderCloudStatus(cs) {
|
||||
if (!cs) return;
|
||||
const srcLabel =
|
||||
cs.source === 'remote'
|
||||
? '云端同步'
|
||||
: cs.source === 'local'
|
||||
? '本地文件'
|
||||
: '内置默认';
|
||||
patchText(pricingCountVal, `${cs.modelCount || 0} 个模型`);
|
||||
patchText(
|
||||
pricingSyncSub,
|
||||
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||
);
|
||||
|
||||
const curVer = cs.currentPluginVersion || '1.4.0';
|
||||
const latVer = cs.latestPluginVersion || curVer;
|
||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||
patchText(versionVal, `v${curVer}`);
|
||||
if (cs.updateAvailable) {
|
||||
patchText(versionSub, `可升级至 v${latVer} (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': true });
|
||||
patchText(updatePluginBtnText, `升级至 v${latVer}`);
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false });
|
||||
} else {
|
||||
patchText(versionSub, `已是最新 (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(updatePluginBtnText, '检查更新');
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
}
|
||||
|
||||
if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) {
|
||||
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
||||
}
|
||||
}
|
||||
|
||||
const unsub = telemetryStore.subscribe(
|
||||
(st) => st.telemetry?.settings,
|
||||
(settings) => {
|
||||
latestSettings = settings;
|
||||
(st) => ({
|
||||
settings: st.telemetry?.settings,
|
||||
cloudStatus: st.telemetry?.cloudStatus,
|
||||
}),
|
||||
(slice) => {
|
||||
latestSettings = slice.settings;
|
||||
latestCloudStatus = slice.cloudStatus;
|
||||
if (uiStore.getState().activeView !== 'settings') {
|
||||
isDirty = true;
|
||||
return;
|
||||
}
|
||||
isDirty = false;
|
||||
renderSettings(settings);
|
||||
renderSettings(slice.settings);
|
||||
renderCloudStatus(slice.cloudStatus);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -196,26 +423,27 @@ export const SettingsView = defineComponent({
|
||||
(activeView) => {
|
||||
if (activeView === 'settings' && isDirty) {
|
||||
isDirty = false;
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
if (statusTimer) clearTimeout(statusTimer);
|
||||
if (cloudTimer) clearTimeout(cloudTimer);
|
||||
unsub();
|
||||
unsubView();
|
||||
modeSelect.destroy();
|
||||
stepModelSelect.destroy();
|
||||
autoUpdateSelect.destroy();
|
||||
tokenBudgetInput.destroy();
|
||||
costBudgetInput.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: { modeSelect, stepModelSelect, tokenBudgetInput, costBudgetInput },
|
||||
refs: { modeSelect, stepModelSelect, autoUpdateSelect, tokenBudgetInput, costBudgetInput },
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* @fileoverview View 3: StepsDetailView (步骤明细与按模型汇总视图).
|
||||
* Uses patchKeyedList for incremental row reconciliation without innerHTML resets,
|
||||
* wraps tables in bespoke CustomScrollbar (zero native OS scrollbars), and provides
|
||||
* a live row inspector bar replacing native browser title tooltips.
|
||||
* 提供“单步测速”与“按模型汇总”双子表切换:
|
||||
* - 采用 `patchKeyedList` 实现行级 DOM 增量对账与就地复用,彻底避免全表 `innerHTML` 重建引发的闪烁;
|
||||
* - 两个表格各自包裹在独立的 `CustomScrollbar` 容器中,兼具粘性表头与零原生滚动条体验;
|
||||
* - 支持在内部代号 (`modelShort`) 与实际响应模型名 (`modelUpstream`) 之间无缝切换显示。
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
@@ -29,11 +30,12 @@ import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
export const StepsDetailView = defineComponent({
|
||||
name: 'StepsDetailView',
|
||||
setup({ onCleanup }) {
|
||||
// 顶部子表分段切换器:在“按步查看”与“按模型汇总”之间切换
|
||||
const subTabSwitch = SegmentedControl({
|
||||
ariaLabel: '明细表视图切换',
|
||||
modelValue: uiStore.getState().stepsSubTab,
|
||||
options: [
|
||||
{ value: 'steps', label: '单步测速 (0步)' },
|
||||
{ value: 'steps', label: '按步查看 (0)' },
|
||||
{ value: 'models', label: '按模型汇总' },
|
||||
],
|
||||
onUpdateModelValue: (nextTab) => {
|
||||
@@ -41,18 +43,19 @@ export const StepsDetailView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
// --- 子表 1:单步明细表(列定义:步序、模型、吞吐速度、首字延迟、上下文/输出、缓存命中率、单步费用) ---
|
||||
const stepsTbody = h('tbody');
|
||||
const stepsTablePane = h('div', { className: 'table-viewport' }, [
|
||||
h('table', { className: 'data-table' }, [
|
||||
h('thead', {}, [
|
||||
h('tr', {}, [
|
||||
h('th', { text: '步' }),
|
||||
h('th', { text: '步序' }),
|
||||
h('th', { text: '模型' }),
|
||||
h('th', { text: '速度' }),
|
||||
h('th', { text: '首Token' }),
|
||||
h('th', { text: '上下文/输出' }),
|
||||
h('th', { text: '首字' }),
|
||||
h('th', { text: '上下文 / 输出' }),
|
||||
h('th', { text: '缓存' }),
|
||||
h('th', { text: '消费' }),
|
||||
h('th', { text: '费用' }),
|
||||
]),
|
||||
]),
|
||||
stepsTbody,
|
||||
@@ -63,6 +66,7 @@ export const StepsDetailView = defineComponent({
|
||||
className: 'table-scroll-host',
|
||||
});
|
||||
|
||||
// --- 子表 2:按模型汇总表(列定义:模型名称、调用次数、有效均速、总 Token、费用) ---
|
||||
const modelsTbody = h('tbody');
|
||||
const modelsTablePane = h('div', { className: 'table-viewport' }, [
|
||||
h('table', { className: 'data-table' }, [
|
||||
@@ -72,7 +76,7 @@ export const StepsDetailView = defineComponent({
|
||||
h('th', { text: '次数' }),
|
||||
h('th', { text: '均速' }),
|
||||
h('th', { text: '总 Token' }),
|
||||
h('th', { text: '预估费用' }),
|
||||
h('th', { text: '费用' }),
|
||||
]),
|
||||
]),
|
||||
modelsTbody,
|
||||
@@ -94,7 +98,7 @@ export const StepsDetailView = defineComponent({
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('table', { size: 13 }),
|
||||
h('span', { text: '速度与费用明细' }),
|
||||
h('span', { text: '调用记录' }),
|
||||
]),
|
||||
subTabSwitch.el,
|
||||
]),
|
||||
@@ -119,6 +123,9 @@ export const StepsDetailView = defineComponent({
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
|
||||
/**
|
||||
* 对单步测速表和按模型汇总表执行基于 `patchKeyedList` 的键值增量对账与行更新。
|
||||
*/
|
||||
function renderStepsData(slice) {
|
||||
if (!slice) return;
|
||||
const steps = slice.recentSteps || [];
|
||||
@@ -127,11 +134,12 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
subTabSwitch.setProps({
|
||||
options: [
|
||||
{ value: 'steps', label: `单步测速 (${steps.length}步)` },
|
||||
{ value: 'steps', label: `按步查看 (${steps.length})` },
|
||||
{ value: 'models', label: `按模型汇总 (${slice.rangeLabel})` },
|
||||
],
|
||||
});
|
||||
|
||||
// 1. 单步测速表增量对账:以 `<cascadeId>-<stepIndex>` 为稳定行键,仅在签名变化时刷新单元格
|
||||
patchKeyedList(stepsTbody, steps, {
|
||||
keyFn: (st) => `${slice.cascadeId || 'conv'}-${st.stepIndex}`,
|
||||
sigFn: (st) =>
|
||||
@@ -203,6 +211,7 @@ export const StepsDetailView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
// 2. 按模型汇总表增量对账:以模型标识为稳定行键,展示调用次数、加权均速、有效样本比与总费用
|
||||
patchKeyedList(modelsTbody, models, {
|
||||
keyFn: (m) => m.label || m.shortName,
|
||||
sigFn: (m) =>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+237
-184
@@ -243,16 +243,21 @@ input {
|
||||
animation: anim-pulse-dot 950ms ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* --- src/styles/components.css --- */
|
||||
/* --- src/styles/controls.css --- */
|
||||
/*
|
||||
* Component Stylesheet for Antigravity Usage & Speed Monitor Monitor.
|
||||
* Enforces:
|
||||
* 1. Top Long-Pill Navigation Bar (--radius-pill)
|
||||
* 2. Internal 2px-4px micro-bezel precision grid (--radius-xs / --radius-sm)
|
||||
* 3. Zero hardcoded colors (all tokens from tokens.css)
|
||||
* 通用交互控件与顶栏导航样式表 (controls.css).
|
||||
* 包含:
|
||||
* 1. 顶部会话控制栏 (.session-header, .status-tag, .icon-btn, .update-badge-btn)
|
||||
* 2. 顶部唯一长药丸导航栏 (.long-pill-nav, .pill-glider, .pill-tab)
|
||||
* 3. 定制下拉选择器 (.custom-select)
|
||||
* 4. 定制步进数字输入框 (.number-input)
|
||||
* 5. 定制日期时间选择器 (.datetime-picker)
|
||||
* 6. 微边框分段控制器 (.segmented)
|
||||
* 7. 独立轨道槽自定义滚动条 (.custom-scroll-host)
|
||||
* 8. 设置表单行与主次操作按钮 (.form-row, .btn-primary, .btn-secondary, .cloud-actions-row)
|
||||
*/
|
||||
|
||||
/* --- Row 1: Top Session Control Header --- */
|
||||
/* --- 1. 顶部会话控制栏 (Top Session Control Header) --- */
|
||||
.session-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -347,7 +352,7 @@ input {
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
/* --- Row 2: Top Long-Pill Navigation Bar (唯一长药丸功能分割顶栏) --- */
|
||||
/* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */
|
||||
.long-pill-nav {
|
||||
position: relative;
|
||||
display: grid;
|
||||
@@ -437,7 +442,7 @@ input {
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
/* --- Bespoke Custom Select (零原生 <select>) --- */
|
||||
/* --- 3. 定制下拉选择器 (Bespoke Custom Select,零原生 <select>) --- */
|
||||
.custom-select {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
@@ -530,7 +535,7 @@ input {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- Bespoke Custom Number Input (零原生 <input type="number">) --- */
|
||||
/* --- 4. 定制步进数字框 (Bespoke Custom Number Input,零原生 <input type="number">) --- */
|
||||
.number-input {
|
||||
display: inline-flex;
|
||||
align-items: stretch;
|
||||
@@ -580,7 +585,7 @@ input {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* --- Bespoke Custom DateTime Picker (零原生 <input type="datetime-local">) --- */
|
||||
/* --- 5. 定制日期时间选择器 (Bespoke Custom DateTime Picker) --- */
|
||||
.datetime-picker {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
@@ -709,7 +714,7 @@ input {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* --- Micro-Bezel Segmented Control --- */
|
||||
/* --- 6. 微边框分段控制器 (Micro-Bezel Segmented Control) --- */
|
||||
.segmented {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -748,7 +753,196 @@ input {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- Architectural Precision Panels & Metric Matrices --- */
|
||||
/* --- 7. 独立槽位自定义滚动条 (Bespoke Custom Scrollbar) --- */
|
||||
.custom-scroll-host {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
gap: 5px;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.custom-scroll-host[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.custom-scroll-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
|
||||
.custom-scroll-content::-webkit-scrollbar {
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.scrollbar-rail {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 5px;
|
||||
margin: 2px 0;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--border-hairline) 35%, transparent);
|
||||
z-index: 15;
|
||||
opacity: 0.85;
|
||||
transition: opacity var(--dur-fast) var(--ease-fast), background-color var(--dur-fast) var(--ease-fast);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.custom-scroll-host:hover .scrollbar-rail,
|
||||
.scrollbar-rail.is-dragging {
|
||||
opacity: 1;
|
||||
background: color-mix(in srgb, var(--border-hairline) 65%, transparent);
|
||||
}
|
||||
|
||||
.scrollbar-rail.is-inactive {
|
||||
display: none !important;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.scrollbar-thumb {
|
||||
width: 100%;
|
||||
height: var(--thumb-h, 0px);
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
||||
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
||||
will-change: transform, height;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.scrollbar-rail:hover .scrollbar-thumb,
|
||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
||||
}
|
||||
|
||||
/* --- 8. 设置表单与按钮控件 (Settings Form & Buttons) --- */
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 11.5px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
padding: 0 var(--space-5);
|
||||
background: var(--accent-primary);
|
||||
color: var(--text-inverse);
|
||||
border: 1px solid var(--accent-primary);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.btn-primary:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
padding: 0 var(--space-4);
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast), border-color var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--surface-hover);
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
.btn-secondary:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.btn-primary:disabled,
|
||||
.btn-secondary:disabled,
|
||||
.update-badge-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.cloud-actions-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.update-badge-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.update-badge-btn[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.update-badge-btn:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.update-badge-btn:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
|
||||
/* --- src/styles/views-overview.css --- */
|
||||
/*
|
||||
* 实时概览视图与通用面板卡片样式表 (views-overview.css).
|
||||
* 包含:
|
||||
* 1. 通用面板容器与标题头 (.panel, .panel-header, .panel-title, .panel-meta)
|
||||
* 2. 4 格实时测速指标矩阵 (.telemetry-matrix, .matrix-cell, .cell-*)
|
||||
* 3. 6 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill)
|
||||
* 4. 上下文双列图例网格与色块 (.ctx-legend-grid, .legend-*, .swatch)
|
||||
* 5. 双栏布局网格与窄屏响应式断点 (.dual-grid)
|
||||
*/
|
||||
|
||||
/* --- 1. 通用微边框面板卡片 (Architectural Precision Panels) --- */
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -784,7 +978,7 @@ input {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* 4-Cell Telemetry Matrix */
|
||||
/* --- 2. 4 格实时测速指标矩阵 (4-Cell Telemetry Matrix) --- */
|
||||
.telemetry-matrix {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
@@ -838,7 +1032,7 @@ input {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* Context Segment Meter & Progress Bars */
|
||||
/* --- 3. 6 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */
|
||||
.progress-track {
|
||||
width: 100%;
|
||||
height: 6px;
|
||||
@@ -900,6 +1094,7 @@ input {
|
||||
background: var(--metric-danger);
|
||||
}
|
||||
|
||||
/* --- 4. 上下文双列图例网格 (Context 6-Channel Legend Grid) --- */
|
||||
.ctx-legend-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
@@ -942,7 +1137,7 @@ input {
|
||||
.swatch.seg-thinking { background: var(--ctx-thinking); }
|
||||
.swatch.seg-output { background: var(--ctx-output); }
|
||||
|
||||
/* Dual Consumption Comparison Grid */
|
||||
/* --- 5. 双栏网格与窄视口响应式折叠 (Dual Grid & Responsive Breakpoints) --- */
|
||||
.dual-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
@@ -958,63 +1153,18 @@ input {
|
||||
}
|
||||
}
|
||||
|
||||
.ledger-box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
}
|
||||
/* --- src/styles/views-consumption.css --- */
|
||||
/*
|
||||
* 全景消耗统计视图样式表 (views-consumption.css).
|
||||
* 包含:
|
||||
* 1. 消费概览顶栏与 3+2 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-*, .cons-col)
|
||||
* 2. 4 段比例条与圆点色块 (.dot-swatch, .cons-seg-bar)
|
||||
* 3. 热门模型与数据来源列表项样式 (.cons-row-*, .cons-share-pill, .cons-item-*)
|
||||
* 4. 历史趋势纯 SVG 平滑曲线图与峰值胶囊 (.trend-*)
|
||||
* 5. 12 个月垂直堆叠柱状图与月度图例 (.monthly-*, .month-*)
|
||||
*/
|
||||
|
||||
.ledger-box.is-primary {
|
||||
background: color-mix(in srgb, var(--accent-primary) 4%, var(--surface-panel));
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
.ledger-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.ledger-tag {
|
||||
font-size: 10.5px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.ledger-main {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.ledger-tokens {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.ledger-cost {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--metric-speed);
|
||||
}
|
||||
|
||||
.ledger-foot {
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
padding-top: 4px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
/* --- Rich Consumption Analytics Dashboard (5-Section Layout) --- */
|
||||
/* --- 1. 消费概览顶栏与 3+2 组合指标矩阵 (Consumption Overview Matrix) --- */
|
||||
.cons-overview-head {
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
@@ -1118,6 +1268,7 @@ input {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* --- 2. 4 段比例条与圆点色块 (Four-Segment Bar & Dot Swatches) --- */
|
||||
.dot-swatch {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
@@ -1131,7 +1282,7 @@ input {
|
||||
.dot-swatch.seg-output { background: var(--ctx-output); }
|
||||
.dot-swatch.seg-thinking { background: var(--ctx-thinking); }
|
||||
|
||||
/* Uniform 12px / 20px Row Header Alignment for Popular Models & Sources */
|
||||
/* --- 3. 热门模型与数据来源行头部对齐 (Popular Models & Sources Row Header) --- */
|
||||
.cons-row-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -1189,7 +1340,7 @@ input {
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
/* Historical Trend SVG Chart */
|
||||
/* --- 4. 历史趋势 SVG 平滑曲线图 (Historical Trend SVG Chart) --- */
|
||||
.trend-chart-wrap {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
@@ -1258,7 +1409,7 @@ input {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
/* Popular Models & Sources Rows */
|
||||
/* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */
|
||||
.cons-item-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -1285,7 +1436,7 @@ input {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 12-Month Stacked Bar Chart */
|
||||
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
|
||||
.monthly-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(12, 1fr);
|
||||
@@ -1377,21 +1528,16 @@ input {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* --- Bespoke Custom Scrollbar (Dedicated Layout Gutter, Never Overlaps Content) --- */
|
||||
.custom-scroll-host {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
gap: 5px;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.custom-scroll-host[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
/* --- src/styles/views-tables.css --- */
|
||||
/*
|
||||
* 步骤明细与模型汇总数据表样式表 (views-tables.css).
|
||||
* 包含:
|
||||
* 1. 表格专属自定义滚动容器修饰 (.table-scroll-host)
|
||||
* 2. 表格滚动视口 (.table-viewport)
|
||||
* 3. 粘性表头与紧凑高密度数据表 (.data-table)
|
||||
*/
|
||||
|
||||
/* --- 1. 表格专属滚动容器与视口 (Table Scroll Host & Viewport) --- */
|
||||
.table-scroll-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -1404,62 +1550,6 @@ input {
|
||||
background: var(--surface-panel);
|
||||
}
|
||||
|
||||
.custom-scroll-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
|
||||
.custom-scroll-content::-webkit-scrollbar {
|
||||
width: 0 !important;
|
||||
height: 0 !important;
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.scrollbar-rail {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 5px;
|
||||
margin: 2px 0;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--border-hairline) 35%, transparent);
|
||||
z-index: 15;
|
||||
opacity: 0.85;
|
||||
transition: opacity var(--dur-fast) var(--ease-fast), background-color var(--dur-fast) var(--ease-fast);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.custom-scroll-host:hover .scrollbar-rail,
|
||||
.scrollbar-rail.is-dragging {
|
||||
opacity: 1;
|
||||
background: color-mix(in srgb, var(--border-hairline) 65%, transparent);
|
||||
}
|
||||
|
||||
.scrollbar-rail.is-inactive {
|
||||
display: none !important;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.scrollbar-thumb {
|
||||
width: 100%;
|
||||
height: var(--thumb-h, 0px);
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 32%, transparent);
|
||||
transform: translate3d(0, var(--thumb-y, 0px), 0);
|
||||
will-change: transform, height;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.scrollbar-rail:hover .scrollbar-thumb,
|
||||
.scrollbar-rail.is-dragging .scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--accent-primary) 72%, transparent);
|
||||
}
|
||||
|
||||
.table-viewport {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -1468,6 +1558,7 @@ input {
|
||||
background: var(--surface-panel);
|
||||
}
|
||||
|
||||
/* --- 2. 粘性表头数据表 (Sticky-Header Data Table) --- */
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -1505,41 +1596,3 @@ input {
|
||||
.data-table tbody tr:hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
/* Settings Form Layout */
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 11.5px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
padding: 0 var(--space-5);
|
||||
background: var(--accent-primary);
|
||||
color: var(--text-inverse);
|
||||
border: 1px solid var(--accent-primary);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
opacity: 0.92;
|
||||
}
|
||||
|
||||
.btn-primary:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
@@ -3,24 +3,98 @@ import path from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import * as metrics from '../speed-metrics.mjs';
|
||||
|
||||
export function backendHarness({cache={},settings={},trajectories={},summaries={},userStatus={},quotaSummary={groups:[]},sourceText=null,metricsImplementation=metrics}={}) {
|
||||
const source=(sourceText ?? fs.readFileSync(new URL('../main.mjs',import.meta.url),'utf8'))
|
||||
.replace(/^import .*;\r?\n/gm,'').replaceAll('import.meta.url',JSON.stringify('file:///test/main.mjs'));
|
||||
const state={calls:[],errors:[],saves:[],trajectories,userStatus,quotaSummary};
|
||||
const BACKEND_MODULE_FILES = [
|
||||
'../backend/config.mjs',
|
||||
'../backend/pricing-catalog.mjs',
|
||||
'../backend/plugin-updater.mjs',
|
||||
'../backend/ls-rpc.mjs',
|
||||
'../backend/model-pricing.mjs',
|
||||
'../backend/quota-pools.mjs',
|
||||
'../backend/local-scanner.mjs',
|
||||
'../backend/usage-aggregator.mjs',
|
||||
'../backend/telemetry-builder.mjs',
|
||||
'../main.mjs',
|
||||
];
|
||||
|
||||
function loadCombinedBackendSource() {
|
||||
return BACKEND_MODULE_FILES.map((relPath) =>
|
||||
fs.readFileSync(new URL(relPath, import.meta.url), 'utf8')
|
||||
).join('\n');
|
||||
}
|
||||
|
||||
function stripEsmSyntax(rawSource, mainUrl) {
|
||||
return rawSource
|
||||
.replace(/^\s*import\s+[\s\S]*?from\s+['"][^'"]+['"];?\r?\n/gm, '')
|
||||
.replace(/^\s*export\s+(?=(?:async\s+)?function\b|const\b|let\b|class\b)/gm, '')
|
||||
.replaceAll('import.meta.url', JSON.stringify(mainUrl));
|
||||
}
|
||||
|
||||
export function backendHarness({
|
||||
cache={},
|
||||
settings={},
|
||||
trajectories={},
|
||||
summaries={},
|
||||
userStatus={},
|
||||
quotaSummary={groups:[]},
|
||||
localCatalog=null,
|
||||
remoteCatalog=null,
|
||||
pluginManifest=null,
|
||||
hasGitDir=false,
|
||||
pluginRootPath=null,
|
||||
remoteFetch=null,
|
||||
execFileImpl=null,
|
||||
sourceText=null,
|
||||
metricsImplementation=metrics,
|
||||
}={}) {
|
||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],trajectories,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal,
|
||||
process:{env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
...metricsImplementation, URL, AbortSignal, Buffer,
|
||||
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
console:{error:m=>state.errors.push(m)},
|
||||
existsSync:p=>p.endsWith('settings.json') || p.endsWith('trajectory_usage_cache.json'),
|
||||
cpSync:()=>{},
|
||||
rmSync:()=>{},
|
||||
execFile:execFileImpl || ((cmd,args,opts,cb)=>{
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
fn(new Error('execFile not mocked'));
|
||||
}),
|
||||
existsSync:p=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
if (norm.endsWith('settings.json') || norm.endsWith('trajectory_usage_cache.json')) return true;
|
||||
if (norm.endsWith('pricing-catalog.json')) return Boolean(state.localCatalog);
|
||||
if (norm.endsWith('remote_pricing_cache.json')) return Boolean(state.remoteCatalog);
|
||||
if (norm.endsWith('plugin.json')) return Boolean(state.pluginManifest);
|
||||
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir);
|
||||
return false;
|
||||
},
|
||||
mkdirSync:()=>{},readdirSync:()=>[],statSync:()=>({mtimeMs:0}),
|
||||
readFileSync:p=>JSON.stringify(p.endsWith('settings.json')?settings:cache),
|
||||
writeFileSync:(p,s)=>state.saves.push({path:p,data:JSON.parse(s)}),
|
||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,fileURLToPath:()=>'/test/main.mjs',
|
||||
readFileSync:p=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(settings);
|
||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
||||
if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
||||
return JSON.stringify(cache);
|
||||
},
|
||||
writeFileSync:(p,s)=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
const parsed = typeof s === 'string' ? JSON.parse(s) : s;
|
||||
state.saves.push({path:p,data:parsed});
|
||||
if (norm.endsWith('remote_pricing_cache.json')) {
|
||||
state.remoteCatalog = parsed;
|
||||
}
|
||||
},
|
||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,fileURLToPath:()=>mainPath,
|
||||
Response:class {constructor(body,options){this.body=body;this.options=options;}},
|
||||
SidecarApp:class {page(){} api(){} run(){}},
|
||||
StreamDiagnostics:class {status(){return {enabled:false};} start(){}},
|
||||
fetch:async(url,options)=>{
|
||||
const method=url.split('/').pop(); const body=JSON.parse(options.body);state.calls.push({method,body});
|
||||
fetch:async(url,options={})=>{
|
||||
if (/^https?:\/\/(?!test\.invalid)/i.test(String(url)) && remoteFetch) {
|
||||
return remoteFetch(url, options);
|
||||
}
|
||||
const method=url.split('/').pop(); const body=options.body ? JSON.parse(options.body) : {};state.calls.push({method,body});
|
||||
if(method==='GetCascadeTrajectory') {
|
||||
const data=state.trajectories[body.cascadeId];
|
||||
if(data instanceof Error) throw data;
|
||||
@@ -34,6 +108,6 @@ export function backendHarness({cache={},settings={},trajectories={},summaries={
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,compareSemver,performPluginUpdate};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
|
||||
const createdAtMs = Date.now() - 20_000;
|
||||
function makeStep(index, modelKey, responseModel = '') {
|
||||
return {
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
sourceTrajectoryStepInfo: { stepIndex: index },
|
||||
createdAt: new Date(createdAtMs).toISOString(),
|
||||
completedAt: new Date(createdAtMs + 5_000).toISOString(),
|
||||
modelUsage: {
|
||||
model: modelKey,
|
||||
...(responseModel ? { responseModel } : {}),
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: '100000',
|
||||
cacheReadTokens: '400000',
|
||||
outputTokens: '50000',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs, and preserves valid pricing', () => {
|
||||
const { sanitizeCatalogPayload } = backendHarness();
|
||||
assert.equal(sanitizeCatalogPayload(null), null);
|
||||
assert.equal(sanitizeCatalogPayload({ pricing: {} }), null);
|
||||
|
||||
const sanitized = sanitizeCatalogPayload({
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.03.9',
|
||||
updatedAt: '2026-11-03T15:00:00Z',
|
||||
latestPluginVersion: '1.5.0',
|
||||
downloadUrl: 'https://evil.example.com/malware.zip',
|
||||
pricing: {
|
||||
'gemini-4.5-ultra': { input: 3.5, cache: 0.35, output: 15.0, short: 'ultra-4.5', family: 'Gemini' },
|
||||
'broken-negative': { input: -1, cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-nan': { input: 'NaN', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-null': { input: null, cache: null, output: null, short: 'bad', family: 'Gemini' },
|
||||
'broken-zero': { input: 0, cache: 0, output: 0, short: 'bad', family: 'Gemini' },
|
||||
'broken-string-num': { input: '1.5', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-missing-short': { input: 1, cache: 0.1, output: 5, short: '', family: 'Gemini' },
|
||||
},
|
||||
placeholders: {
|
||||
MODEL_PLACEHOLDER_M999: { modelId: 'gemini-4.5-ultra', label: 'Gemini 4.5 Ultra' },
|
||||
MODEL_BROKEN: { modelId: '', label: 'Broken' },
|
||||
},
|
||||
});
|
||||
|
||||
assert.ok(sanitized);
|
||||
assert.equal(sanitized.catalogVersion, '2026.11.03.9');
|
||||
assert.equal(sanitized.latestPluginVersion, '1.5.0');
|
||||
assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan2498281558/'));
|
||||
assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']);
|
||||
assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']);
|
||||
});
|
||||
|
||||
test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newly pushed models', async () => {
|
||||
const step = makeStep(1, 'MODEL_PLACEHOLDER_M888');
|
||||
let fetchedUrl = '';
|
||||
|
||||
const h = backendHarness({
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
summaries: { conv1: { stepCount: 1 } },
|
||||
trajectories: { conv1: { trajectory: { steps: [step] } } },
|
||||
remoteFetch: async (url) => {
|
||||
fetchedUrl = String(url);
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.03.2',
|
||||
updatedAt: '2026-11-03T16:00:00Z',
|
||||
latestPluginVersion: '1.5.0',
|
||||
pricing: {
|
||||
'gemini-5-nova': { input: 4.0, cache: 0.4, output: 20.0, short: 'nova-5', family: 'Gemini' },
|
||||
},
|
||||
placeholders: {
|
||||
MODEL_PLACEHOLDER_M888: { modelId: 'gemini-5-nova', label: 'Gemini 5 Nova' },
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// Before cloud sync: M888 is unknown and unpriced
|
||||
const before = await h.buildTelemetryPayloadInternal('conv1');
|
||||
assert.equal(before.activeConversation.activeModelShort, 'MODEL_PLACEHOLDER_M888');
|
||||
assert.equal(before.activeConversation.latestStepCostUsd, null);
|
||||
assert.equal(before.consumption.account.unpricedCalls, 1);
|
||||
assert.equal(before.cloudStatus.updateAvailable, false);
|
||||
|
||||
// Sync cloud catalog from GitHub
|
||||
const syncStatus = await h.syncCloudCatalog({ force: true });
|
||||
assert.ok(fetchedUrl.startsWith('https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json'));
|
||||
assert.equal(syncStatus.source, 'remote');
|
||||
assert.equal(syncStatus.catalogVersion, '2026.11.03.2');
|
||||
assert.equal(syncStatus.latestPluginVersion, '1.5.0');
|
||||
assert.equal(syncStatus.updateAvailable, true);
|
||||
|
||||
// Immediately re-evaluate payload: M888 is now resolved and priced without clearing trajectoryCache
|
||||
const after = await h.buildTelemetryPayloadInternal('conv1');
|
||||
assert.equal(after.activeConversation.activeModelShort, 'nova-5');
|
||||
assert.equal(after.activeConversation.activeModelLabel, 'Gemini 5 Nova');
|
||||
// Cost = 0.1M * $4.0 + 0.4M * $0.4 + 0.05M * $20.0 = 0.4 + 0.16 + 1.0 = $1.56
|
||||
assert.equal(after.activeConversation.latestStepCostUsd, 1.56);
|
||||
assert.equal(after.consumption.account.unpricedCalls, 0);
|
||||
assert.equal(after.consumption.account.costUsd, 1.56);
|
||||
});
|
||||
|
||||
test('resolveModelInfo falls back to responseModel when placeholder enum is unmapped', async () => {
|
||||
const step = makeStep(1, 'MODEL_PLACEHOLDER_M777', 'gemini-4-argon-high');
|
||||
const h = backendHarness({
|
||||
summaries: { conv1: { stepCount: 1 } },
|
||||
trajectories: { conv1: { trajectory: { steps: [step] } } },
|
||||
});
|
||||
const p = await h.buildTelemetryPayloadInternal('conv1');
|
||||
assert.equal(p.activeConversation.activeModelShort, 'argon-4-high');
|
||||
assert.equal(p.consumption.account.unpricedCalls, 0);
|
||||
assert.ok(p.activeConversation.latestStepCostUsd > 0);
|
||||
});
|
||||
|
||||
test('performPluginUpdate blocks overwriting dirty worktrees (including untracked ?? files) without stashing', async () => {
|
||||
for (const [rootPath, porcelainOutput] of [
|
||||
['/workspace/antigravity-usage-monitor', ' M sidecars/panel/main.mjs\n'],
|
||||
['/Users/test/.gemini/config/plugins/usage-monitor', '?? sidecars/panel/backend/config.mjs\n'],
|
||||
]) {
|
||||
const gitCalls = [];
|
||||
const h = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: rootPath,
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
gitCalls.push(args);
|
||||
if (args.includes('status')) {
|
||||
assert(!args.includes('--untracked-files=no'), 'must inspect untracked files too');
|
||||
fn(null, porcelainOutput, '');
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await h.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.skipped, true);
|
||||
assert.equal(res.reason, 'dirty_worktree');
|
||||
assert.equal(gitCalls.length, 1);
|
||||
assert(!gitCalls.some((args) => args.includes('stash')));
|
||||
}
|
||||
});
|
||||
|
||||
test('performPluginUpdate blocks non-main branches and diverged git history', async () => {
|
||||
const branchH = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'fix/humanize-copy-strings\n', '');
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
const branchRes = await branchH.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(branchRes.ok, false);
|
||||
assert.equal(branchRes.reason, 'not_on_main_branch');
|
||||
|
||||
const divergedH = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.3.0' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'main\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('show')) {
|
||||
fn(null, JSON.stringify({ name: 'usage-monitor', version: '1.4.0' }), '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('merge-base')) {
|
||||
fn(new Error('not ancestor'));
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
const divRes = await divergedH.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(divRes.ok, false);
|
||||
assert.equal(divRes.reason, 'diverged_worktree');
|
||||
});
|
||||
|
||||
test('performPluginUpdate refuses to downgrade or pull when remote version is older, equal, or unreadable', async () => {
|
||||
for (const showOutput of [
|
||||
JSON.stringify({ name: 'usage-monitor', version: '1.2.0' }),
|
||||
JSON.stringify({ name: 'usage-monitor', version: '1.4.0' }),
|
||||
'', // git show failed or empty — must NOT fall back to cloudSyncState.latestPluginVersion
|
||||
]) {
|
||||
const gitCalls = [];
|
||||
const h = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
remoteCatalog: {
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.03.9',
|
||||
updatedAt: '2026-11-03T18:00:00Z',
|
||||
latestPluginVersion: '1.9.0',
|
||||
pricing: { 'gemini-4-argon': { input: 2, cache: 0.1, output: 10, short: 'argon-4', family: 'Gemini' } },
|
||||
},
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
gitCalls.push(args);
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'main\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('show')) {
|
||||
if (!showOutput) {
|
||||
fn(new Error('fatal: Path plugin.json does not exist'));
|
||||
return;
|
||||
}
|
||||
fn(null, showOutput, '');
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await h.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.skipped, true);
|
||||
assert.equal(res.upToDate, true);
|
||||
assert.equal(res.reason, 'already_up_to_date');
|
||||
assert.equal(res.currentVersion, '1.4.0');
|
||||
assert(!gitCalls.some((args) => args.includes('pull')));
|
||||
}
|
||||
});
|
||||
|
||||
test('performPluginUpdate pulls fast-forward when git worktree is clean, on main, ancestor, and remote version is newer', async () => {
|
||||
const gitCalls = [];
|
||||
const h = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.3.1' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
gitCalls.push(args);
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'main\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('show')) {
|
||||
fn(null, JSON.stringify({ name: 'usage-monitor', version: '1.4.0' }), '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('pull')) {
|
||||
h.state.pluginManifest = { name: 'usage-monitor', version: '1.4.0' };
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await h.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.mode, 'git');
|
||||
assert.equal(res.previousVersion, '1.3.1');
|
||||
assert.equal(res.currentVersion, '1.4.0');
|
||||
assert.equal(gitCalls.length, 6); // status, rev-parse, fetch, show, merge-base, pull
|
||||
});
|
||||
Reference in New Issue
Block a user