mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
Merge pull request #8 from yuhuan2498281558/release/v1.4.3
feat(panel): dual-mount topbar capsule, live multi-session HUD, and customizable topbar metrics (v1.4.3)
This commit is contained in:
+1
-8
@@ -1,13 +1,6 @@
|
|||||||
.data/
|
.data/
|
||||||
node_modules/
|
node_modules/
|
||||||
test/
|
plan/
|
||||||
**/test/
|
|
||||||
*.test.*
|
|
||||||
*-harness.*
|
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
# Keep regression tests in source control.
|
|
||||||
!sidecars/panel/test/
|
|
||||||
!sidecars/panel/test/**
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Antigravity Usage & Speed Monitor
|
# Antigravity Usage & Speed Monitor
|
||||||
|
|
||||||
Antigravity 侧边栏插件,用于查看当前会话的生成速度、上下文占用、官方配额余量以及本地历史 Token 消耗。
|
Antigravity 双栖监控插件(支持主窗口顶栏胶囊悬浮面板与右侧辅助栏共存),用于查看当前会话的生成速度、上下文占用、官方配额余量以及本地历史 Token 消耗。
|
||||||
|
|
||||||
下载最新版本:[Releases](https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases) · [usage-monitor.zip](https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip)
|
下载最新版本:[Releases](https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases) · [usage-monitor.zip](https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip)
|
||||||
|
|
||||||
@@ -11,16 +11,17 @@ Antigravity 侧边栏插件,用于查看当前会话的生成速度、上下
|
|||||||
- **实时监控**
|
- **实时监控**
|
||||||
- 核心指标:输出速度、首字延迟、平均速度、本次费用与会话累计费用(支持主代理与子代理独立或汇总查看)。
|
- 核心指标:输出速度、首字延迟、平均速度、本次费用与会话累计费用(支持主代理与子代理独立或汇总查看)。
|
||||||
- 上下文窗口:支持按代理独立切换查看当前上下文窗口,并拆分为模型回复、工具结果、用户消息、子代理通知、压缩摘要、系统提示词、系统工具、MCP 工具、Skill 与用户规则十类来源(按占用量从大到小动态排列)。
|
- 上下文窗口:支持按代理独立切换查看当前上下文窗口,并拆分为模型回复、工具结果、用户消息、子代理通知、压缩摘要、系统提示词、系统工具、MCP 工具、Skill 与用户规则十类来源(按占用量从大到小动态排列)。
|
||||||
- 额度概览:同步展示 `Gemini`、`Gemini 4 Argon`(Pro 账号独立池)与 `Claude & GPT` 模型池的 5 小时限额、每周限额及重置倒计时。
|
- 额度概览:同步展示 `Gemini`、`Gemini 4 Argon`、`Gemini 4 Carbon`(Pro 账号独立池)与 `Claude & GPT` 模型池的 5 小时限额、每周限额及重置倒计时。
|
||||||
- **用量统计**
|
- **用量统计**
|
||||||
- 支持按今天、1天、7天、14天、30天、全部或自定义时间段过滤。
|
- 支持按今天、1天、7天、14天、30天、全部或自定义时间段过滤。
|
||||||
- 汇总所选时段的总 Token、折算费用、缓存命中率与缓存节省金额。
|
- 汇总所选时段的总 Token、折算费用与缓存命中率,并分列展示新输入、缓存读取(含缓存节省金额)与输出用量。
|
||||||
- 包含用量趋势曲线、模型排行、客户端来源以及月度统计柱状图。
|
- 包含用量趋势曲线、模型排行、客户端来源以及月度统计柱状图。
|
||||||
- **调用明细**
|
- **调用明细**
|
||||||
- 按步查看:列出当前会话全部步骤的模型、输出速度、首字延迟、上下文/输出 Token、缓存命中率与单步费用。
|
- 按步查看:列出当前会话全部步骤的模型、输出速度、首字延迟、上下文/输出 Token、缓存命中率与单步费用。
|
||||||
- 按模型汇总:按当前所选时间范围统计各模型的调用次数、均速、总 Token 与费用。
|
- 按模型汇总:按当前所选会话(及所选主/子代理范围)统计各模型的调用次数、均速、总 Token 与费用。
|
||||||
- **偏好设置**
|
- **偏好设置**
|
||||||
- 选择周额度基准:跟随官方额度,或按自定义每周 Token / 费用上限计算百分比。
|
- 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。
|
||||||
|
- 顶部栏定制:独立开关实时运行会话入口,并自由定义右侧三个指标槽位的显示内容与排列顺序。
|
||||||
- 选择模型名称格式:精简代号或原始模型 ID。
|
- 选择模型名称格式:精简代号或原始模型 ID。
|
||||||
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并支持在面板内一键检查更新或开启后台自动安装新版本。
|
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并支持在面板内一键检查更新或开启后台自动安装新版本。
|
||||||
|
|
||||||
@@ -68,7 +69,8 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
|||||||
## 启用与打开面板
|
## 启用与打开面板
|
||||||
|
|
||||||
1. 打开左侧边栏的 **Customizations**,进入 **Installed** 标签页,找到 `usage-monitor` 并开启。
|
1. 打开左侧边栏的 **Customizations**,进入 **Installed** 标签页,找到 `usage-monitor` 并开启。
|
||||||
2. 点击对话窗口右上角 `⋮` -> **Extensions** -> **用量监控**,在右侧辅助栏展开面板;或在对话中输入「打开用量监控面板」通过快捷入口唤起。
|
2. **顶部栏胶囊悬浮面板(默认双栖开启)**:开启插件后,后台 Sidecar 会自动在主对话窗口右上角顶部栏挂载实时状态与指标胶囊(悬停查看速览,左键展开完整四标签面板,右键强制刷新),全程不修改宿主 `app.asar`。如需关闭顶部栏胶囊,可在 **偏好设置 -> 面板挂载方式** 中切换为「仅侧边栏」。
|
||||||
|
3. **右侧辅助栏面板**:点击对话窗口右上角 `⋮` -> **Extensions** -> **用量监控**,在右侧辅助栏展开面板;或在对话中输入「打开用量监控面板」通过快捷入口唤起。
|
||||||
|
|
||||||
## 更新
|
## 更新
|
||||||
|
|
||||||
@@ -88,7 +90,7 @@ git -C "$env:USERPROFILE\.gemini\config\plugins\usage-monitor" pull --ff-only
|
|||||||
git -C ~/.gemini/config/plugins/usage-monitor pull --ff-only
|
git -C ~/.gemini/config/plugins/usage-monitor pull --ff-only
|
||||||
```
|
```
|
||||||
|
|
||||||
通过压缩包安装时,下载新版 `usage-monitor.zip` 覆盖解压到原目录后重新开关插件即可。本地缓存与设置存放在 `~/.gemini/antigravity/sidecar_data/usage-monitor/`,更新插件不会清除历史数据。
|
通过压缩包安装时,下载新版 `usage-monitor.zip` 覆盖解压到原目录后重新开关插件即可。在 Antigravity 宿主内运行时,本地缓存与设置存放在 `~/.gemini/antigravity/sidecar_data/usage-monitor/`(独立启动且未传入 `ANTIGRAVITY_EXECUTABLE_DATA_DIR` 时回退至 `sidecars/panel/.data/`),更新插件不会清除历史数据。
|
||||||
|
|
||||||
## 本地构建
|
## 本地构建
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "usage-monitor",
|
"name": "usage-monitor",
|
||||||
"displayName": "Usage & Speed Monitor",
|
"displayName": "Usage & Speed Monitor",
|
||||||
"version": "1.4.2",
|
"version": "1.4.3",
|
||||||
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
||||||
"logo": "assets/logo.svg",
|
"logo": "assets/logo.svg",
|
||||||
"suggestedPrompts": [
|
"suggestedPrompts": [
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"catalogVersion": "2026.11.11.1",
|
"catalogVersion": "2026.11.11.2",
|
||||||
"updatedAt": "2026-11-11T00:30:00+09:00",
|
"updatedAt": "2026-11-11T17:25:00+09:00",
|
||||||
"latestPluginVersion": "1.4.2",
|
"latestPluginVersion": "1.4.3",
|
||||||
"releaseUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest",
|
"releaseUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest",
|
||||||
"downloadUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
|
"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",
|
"archiveFallbackUrl": "https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main",
|
||||||
@@ -110,13 +110,14 @@
|
|||||||
"gpt-oss-120b-medium": { "input": 0.80, "cache": 0.10, "output": 2.40, "short": "gpt-oss", "family": "GPT" }
|
"gpt-oss-120b-medium": { "input": 0.80, "cache": 0.10, "output": 2.40, "short": "gpt-oss", "family": "GPT" }
|
||||||
},
|
},
|
||||||
"placeholders": {
|
"placeholders": {
|
||||||
|
"MODEL_PLACEHOLDER_M429": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" },
|
||||||
"MODEL_PLACEHOLDER_M417": { "modelId": "gemini-4-argon-high", "label": "Gemini 4 Argon (High)" },
|
"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_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_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_M318": { "modelId": "gemini-3.8-flash-high", "label": "Gemini 3.8 Flash (High)" },
|
||||||
"MODEL_PLACEHOLDER_M319": { "modelId": "gemini-3.8-flash-medium", "label": "Gemini 3.8 Flash (Medium)" },
|
"MODEL_PLACEHOLDER_M319": { "modelId": "gemini-3.8-flash-medium", "label": "Gemini 3.8 Flash (Medium)" },
|
||||||
"MODEL_PLACEHOLDER_M320": { "modelId": "gemini-3.8-flash-low", "label": "Gemini 3.8 Flash (Low)" },
|
"MODEL_PLACEHOLDER_M320": { "modelId": "gemini-3.8-flash-low", "label": "Gemini 3.8 Flash (Low)" },
|
||||||
"MODEL_PLACEHOLDER_M322": { "modelId": "gemini-3.8-flash", "label": "Gemini 3.8 Flash (Tiered)" },
|
"MODEL_PLACEHOLDER_M322": { "modelId": "gemini-3.8-flash-tiered", "label": "Gemini 3.8 Flash (Tiered)" },
|
||||||
"MODEL_PLACEHOLDER_M298": { "modelId": "gemini-3.7-flash-high", "label": "Gemini 3.7 Flash (High)" },
|
"MODEL_PLACEHOLDER_M298": { "modelId": "gemini-3.7-flash-high", "label": "Gemini 3.7 Flash (High)" },
|
||||||
"MODEL_PLACEHOLDER_M299": { "modelId": "gemini-3.7-flash-medium", "label": "Gemini 3.7 Flash (Medium)" },
|
"MODEL_PLACEHOLDER_M299": { "modelId": "gemini-3.7-flash-medium", "label": "Gemini 3.7 Flash (Medium)" },
|
||||||
"MODEL_PLACEHOLDER_M300": { "modelId": "gemini-3.7-flash-low", "label": "Gemini 3.7 Flash (Low)" },
|
"MODEL_PLACEHOLDER_M300": { "modelId": "gemini-3.7-flash-low", "label": "Gemini 3.7 Flash (Low)" },
|
||||||
@@ -125,8 +126,8 @@
|
|||||||
"MODEL_PLACEHOLDER_M72": { "modelId": "gemini-3.6-flash-medium", "label": "Gemini 3.6 Flash (Medium)" },
|
"MODEL_PLACEHOLDER_M72": { "modelId": "gemini-3.6-flash-medium", "label": "Gemini 3.6 Flash (Medium)" },
|
||||||
"MODEL_PLACEHOLDER_M73": { "modelId": "gemini-3.6-flash-low", "label": "Gemini 3.6 Flash (Low)" },
|
"MODEL_PLACEHOLDER_M73": { "modelId": "gemini-3.6-flash-low", "label": "Gemini 3.6 Flash (Low)" },
|
||||||
"MODEL_PLACEHOLDER_M196": { "modelId": "gemini-3.6-flash", "label": "Gemini 3.6 Flash" },
|
"MODEL_PLACEHOLDER_M196": { "modelId": "gemini-3.6-flash", "label": "Gemini 3.6 Flash" },
|
||||||
"MODEL_PLACEHOLDER_M149": { "modelId": "gemini-3.5-flash", "label": "Gemini 3.5 Flash (High)" },
|
"MODEL_PLACEHOLDER_M149": { "modelId": "gemini-3.5-flash-high", "label": "Gemini 3.5 Flash (High)" },
|
||||||
"MODEL_PLACEHOLDER_M20": { "modelId": "gemini-3.5-flash-low", "label": "Gemini 3.5 Flash" },
|
"MODEL_PLACEHOLDER_M20": { "modelId": "gemini-3.5-flash", "label": "Gemini 3.5 Flash" },
|
||||||
"MODEL_PLACEHOLDER_M187": { "modelId": "gemini-3.5-flash-extra-low", "label": "Gemini 3.5 Flash (Extra Low)" },
|
"MODEL_PLACEHOLDER_M187": { "modelId": "gemini-3.5-flash-extra-low", "label": "Gemini 3.5 Flash (Extra Low)" },
|
||||||
"MODEL_PLACEHOLDER_M198": { "modelId": "gemini-3.5-flash-lite", "label": "Gemini 3.5 Flash Lite" },
|
"MODEL_PLACEHOLDER_M198": { "modelId": "gemini-3.5-flash-lite", "label": "Gemini 3.5 Flash Lite" },
|
||||||
"MODEL_PLACEHOLDER_M37": { "modelId": "gemini-3.1-pro-high", "label": "Gemini 3.1 Pro (High)" },
|
"MODEL_PLACEHOLDER_M37": { "modelId": "gemini-3.1-pro-high", "label": "Gemini 3.1 Pro (High)" },
|
||||||
|
|||||||
+3646
-747
File diff suppressed because it is too large
Load Diff
@@ -3,12 +3,12 @@
|
|||||||
*
|
*
|
||||||
* 负责统一管理:
|
* 负责统一管理:
|
||||||
* 1. 插件根目录 (`PLUGIN_ROOT`)、面板目录 (`HERE`) 与持久化数据目录 (`DATA_DIR`) 的路径解析;
|
* 1. 插件根目录 (`PLUGIN_ROOT`)、面板目录 (`HERE`) 与持久化数据目录 (`DATA_DIR`) 的路径解析;
|
||||||
* 2. Language Server RPC 连接参数 (`LS_ADDR` / `CSRF_TOKEN`) 与 GitHub 云端价格表地址;
|
* 2. Language Server RPC 连接参数 (`LS_ADDR` / `LS_BASE_URL` / `CSRF_TOKEN`) 与 GitHub 云端价格表地址;
|
||||||
* 3. 安全的 JSON 读写封装 (`loadJson` / `saveJson`) 与用户设置合并 (`loadSettings`);
|
* 3. 安全的 JSON 读写封装 (`loadJson` / `saveJson`) 与用户设置合并 (`loadSettings`);
|
||||||
* 4. 跨子系统共享的内存态缓存容器(采用对象属性就地更新设计,兼容 ES Module 与 VM 沙箱)。
|
* 4. 跨子系统共享的内存态缓存容器(采用对象属性就地更新设计,兼容 ES Module 与 VM 沙箱)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
@@ -46,9 +46,12 @@ export const DEEP_STATS_CACHE_CANDIDATES = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token。
|
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(自动剥离重复协议前缀与尾部斜杠)。
|
||||||
*/
|
*/
|
||||||
export const LS_ADDR = process.env.ANTIGRAVITY_LS_ADDRESS;
|
const rawLsAddr = String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim();
|
||||||
|
const LS_PROTOCOL = /^https:\/\//i.test(rawLsAddr) ? 'https' : 'http';
|
||||||
|
export const LS_ADDR = rawLsAddr.replace(/^https?:\/\//i, '').replace(/\/+$/, '');
|
||||||
|
export const LS_BASE_URL = LS_ADDR ? `${LS_PROTOCOL}://${LS_ADDR}` : '';
|
||||||
export const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN;
|
export const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -68,21 +71,69 @@ export const DEFAULT_ARCHIVE_FALLBACK_URL =
|
|||||||
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
||||||
export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 顶栏右侧精简胶囊三槽位允许配置的指标枚举与默认顺序。
|
||||||
|
*/
|
||||||
|
export const TOPBAR_SLOT_KEYS = Object.freeze([
|
||||||
|
'context',
|
||||||
|
'tps',
|
||||||
|
'ttft',
|
||||||
|
'cost',
|
||||||
|
'quota_auto',
|
||||||
|
'gemini_5h',
|
||||||
|
'gemini_weekly',
|
||||||
|
'claude_5h',
|
||||||
|
'claude_weekly',
|
||||||
|
'none',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化顶栏三槽位配置数组,兜底非法枚举值并保证至少保留一个可见槽位。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {[string, string, string]}
|
||||||
|
*/
|
||||||
|
export function normalizeTopbarCapsuleSlots(raw) {
|
||||||
|
const arr = Array.isArray(raw) ? raw : [];
|
||||||
|
const slots = [0, 1, 2].map((idx) => {
|
||||||
|
const val = String(arr[idx] ?? '').trim();
|
||||||
|
return TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_TOPBAR_SLOTS[idx];
|
||||||
|
});
|
||||||
|
if (slots.every((s) => s === 'none')) {
|
||||||
|
slots[0] = 'context';
|
||||||
|
}
|
||||||
|
return /** @type {[string, string, string]} */ (slots);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户可配置项的默认值。
|
* 用户可配置项的默认值。
|
||||||
*/
|
*/
|
||||||
export const DEFAULT_SETTINGS = {
|
const DEFAULT_SETTINGS = {
|
||||||
contextWindowLimit: 256000, // 默认 256k 自动压缩上下文预算基准
|
weeklyTokenBudget: 150000000, // 自定义每周 Token 预算默认值 (150M,保留底层兼容)
|
||||||
weeklyTokenBudget: 150000000, // 自定义每周 Token 预算默认值 (150M)
|
weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100,保留底层兼容)
|
||||||
weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100)
|
|
||||||
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
||||||
showUpstreamModel: false, // 步骤明细表是否显示上游真实 responseModel 名称
|
showUpstreamModel: false, // 是否显示上游真实 responseModel 名称
|
||||||
autoUpdatePlugin: false, // 发现新版本且本地工作区干净时是否在后台自动更新插件
|
autoUpdatePlugin: false, // 发现新版本且本地工作区干净时是否在后台自动更新插件
|
||||||
|
enableWindowOverlay: true, // 是否启用双栖模式(自动通过 CDP 在主窗口顶栏挂载胶囊与悬浮面板)
|
||||||
|
showTopbarMultiSession: true, // 是否在顶栏左侧显示实时运行会话入口
|
||||||
|
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], // 顶栏右侧胶囊三槽位指标与顺序
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
||||||
export const CACHE_SCHEMA_VERSION = 'v10-model-identity';
|
export const CACHE_SCHEMA_VERSION = 'v10-model-identity';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断输入值是否为非数组普通对象(Plain Object)。
|
||||||
|
*
|
||||||
|
* @param {unknown} v
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isPlainObject(v) {
|
||||||
|
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 安全读取并解析本地 JSON 文件;文件不存在或解析失败时返回 `fallback`。
|
* 安全读取并解析本地 JSON 文件;文件不存在或解析失败时返回 `fallback`。
|
||||||
*
|
*
|
||||||
@@ -119,7 +170,18 @@ export function saveJson(filePath, data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const VALID_WEEKLY_MODES = new Set(['official', 'tokens', 'cost']);
|
/**
|
||||||
|
* 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @returns {'official'|'custom_tokens'|'custom_cost'}
|
||||||
|
*/
|
||||||
|
export function normalizeWeeklyLimitMode(mode) {
|
||||||
|
const m = String(mode || '').trim().toLowerCase();
|
||||||
|
if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens';
|
||||||
|
if (m === 'custom_cost' || m === 'cost') return 'custom_cost';
|
||||||
|
return 'official';
|
||||||
|
}
|
||||||
|
|
||||||
function sanitizeSettingNumber(val, fallback) {
|
function sanitizeSettingNumber(val, fallback) {
|
||||||
const num = Number(val);
|
const num = Number(val);
|
||||||
@@ -127,33 +189,29 @@ function sanitizeSettingNumber(val, fallback) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段 `speedMode` 并兜底非法数值。
|
* 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段并兜底非法数值。
|
||||||
*
|
*
|
||||||
* @returns {typeof DEFAULT_SETTINGS}
|
* @returns {typeof DEFAULT_SETTINGS}
|
||||||
*/
|
*/
|
||||||
export function loadSettings() {
|
export function loadSettings() {
|
||||||
const raw = loadJson(SETTINGS_FILE, {});
|
const raw = loadJson(SETTINGS_FILE, {});
|
||||||
const { speedMode: _legacySpeedMode, ...settings } =
|
const safeRaw = isPlainObject(raw) ? raw : {};
|
||||||
raw && typeof raw === 'object' ? raw : {};
|
const merged = { ...DEFAULT_SETTINGS, ...safeRaw };
|
||||||
const merged = { ...DEFAULT_SETTINGS, ...settings };
|
|
||||||
const mode = String(merged.weeklyLimitMode || '').trim();
|
|
||||||
return {
|
return {
|
||||||
...merged,
|
|
||||||
contextWindowLimit: sanitizeSettingNumber(
|
|
||||||
merged.contextWindowLimit,
|
|
||||||
DEFAULT_SETTINGS.contextWindowLimit
|
|
||||||
),
|
|
||||||
weeklyTokenBudget: sanitizeSettingNumber(
|
weeklyTokenBudget: sanitizeSettingNumber(
|
||||||
merged.weeklyTokenBudget,
|
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit ?? merged.weeklyTokenBudget,
|
||||||
DEFAULT_SETTINGS.weeklyTokenBudget
|
DEFAULT_SETTINGS.weeklyTokenBudget
|
||||||
),
|
),
|
||||||
weeklyCostBudget: sanitizeSettingNumber(
|
weeklyCostBudget: sanitizeSettingNumber(
|
||||||
merged.weeklyCostBudget,
|
merged.weeklyCostBudget,
|
||||||
DEFAULT_SETTINGS.weeklyCostBudget
|
DEFAULT_SETTINGS.weeklyCostBudget
|
||||||
),
|
),
|
||||||
weeklyLimitMode: VALID_WEEKLY_MODES.has(mode) ? mode : DEFAULT_SETTINGS.weeklyLimitMode,
|
weeklyLimitMode: normalizeWeeklyLimitMode(merged.weeklyLimitMode),
|
||||||
showUpstreamModel: merged.showUpstreamModel === true,
|
showUpstreamModel: merged.showUpstreamModel === true,
|
||||||
autoUpdatePlugin: merged.autoUpdatePlugin === true,
|
autoUpdatePlugin: merged.autoUpdatePlugin === true,
|
||||||
|
enableWindowOverlay: merged.enableWindowOverlay !== false,
|
||||||
|
showTopbarMultiSession: merged.showTopbarMultiSession !== false,
|
||||||
|
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,20 +225,70 @@ export function roundMetric(value) {
|
|||||||
return Number.isFinite(value) ? +value.toFixed(1) : null;
|
return Number.isFinite(value) ? +value.toFixed(1) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算前端产物与后端源码文件的最大修改时间戳,用于插件热更新后触发客户端重载。
|
||||||
|
*
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function computeRuntimeCodeVersion() {
|
||||||
|
let maxMtime = 0;
|
||||||
|
const candidates = [
|
||||||
|
join(HERE, 'app.js'),
|
||||||
|
join(HERE, 'styles.css'),
|
||||||
|
join(HERE, 'main.mjs'),
|
||||||
|
join(HERE, 'speed-metrics.mjs'),
|
||||||
|
];
|
||||||
|
const backendDir = join(HERE, 'backend');
|
||||||
|
try {
|
||||||
|
if (existsSync(backendDir)) {
|
||||||
|
for (const name of readdirSync(backendDir)) {
|
||||||
|
if (name.endsWith('.mjs') || name.endsWith('.js')) {
|
||||||
|
candidates.push(join(backendDir, name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略目录列举异常
|
||||||
|
}
|
||||||
|
for (const file of candidates) {
|
||||||
|
try {
|
||||||
|
if (existsSync(file)) {
|
||||||
|
const mtime = Math.floor(statSync(file).mtimeMs || 0);
|
||||||
|
if (mtime > maxMtime) maxMtime = mtime;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略单文件 stat 异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return String(maxMtime || Date.now());
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 跨模块共享运行时状态容器(启动时自动完成历史轨迹缓存迁移)
|
// 跨模块共享运行时状态容器(启动时自动完成历史轨迹缓存迁移与损坏结构防御)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const loadedTrajectoryCache = loadJson(CACHE_FILE, {});
|
const loadedTrajectoryCache = loadJson(CACHE_FILE, {});
|
||||||
let initialCacheMigrated = false;
|
let initialCacheMigrated =
|
||||||
|
loadedTrajectoryCache !== null &&
|
||||||
|
loadedTrajectoryCache !== undefined &&
|
||||||
|
!isPlainObject(loadedTrajectoryCache);
|
||||||
|
|
||||||
/**
|
const safeCacheEntries = [];
|
||||||
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
|
if (isPlainObject(loadedTrajectoryCache)) {
|
||||||
*/
|
for (const [id, entry] of Object.entries(loadedTrajectoryCache)) {
|
||||||
export const trajectoryCache = Object.fromEntries(
|
if (!id || !isPlainObject(entry)) {
|
||||||
Object.entries(loadedTrajectoryCache).map(([id, entry]) => {
|
initialCacheMigrated = true;
|
||||||
const rawSteps = Array.isArray(entry?.steps) ? entry.steps : [];
|
continue;
|
||||||
const normalizedSteps = rawSteps.map((s) => {
|
}
|
||||||
|
const rawSteps = Array.isArray(entry.steps) ? entry.steps : [];
|
||||||
|
if (!Array.isArray(entry.steps)) {
|
||||||
|
initialCacheMigrated = true;
|
||||||
|
}
|
||||||
|
const objectSteps = rawSteps.filter((s) => isPlainObject(s));
|
||||||
|
if (objectSteps.length !== rawSteps.length) {
|
||||||
|
initialCacheMigrated = true;
|
||||||
|
}
|
||||||
|
const normalizedSteps = objectSteps.map((s) => {
|
||||||
const norm = normalizeCachedStep(s);
|
const norm = normalizeCachedStep(s);
|
||||||
if (norm !== s) initialCacheMigrated = true;
|
if (norm !== s) initialCacheMigrated = true;
|
||||||
return norm;
|
return norm;
|
||||||
@@ -192,15 +300,20 @@ export const trajectoryCache = Object.fromEntries(
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return [
|
safeCacheEntries.push([
|
||||||
id,
|
id,
|
||||||
{
|
{
|
||||||
...entry,
|
...entry,
|
||||||
steps: finalSteps,
|
steps: finalSteps,
|
||||||
},
|
},
|
||||||
];
|
]);
|
||||||
})
|
}
|
||||||
);
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
|
||||||
|
*/
|
||||||
|
export const trajectoryCache = Object.fromEntries(safeCacheEntries);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 缓存状态与外部深层统计缓存 Memo。
|
* 缓存状态与外部深层统计缓存 Memo。
|
||||||
@@ -217,9 +330,10 @@ export const externalDeepStatsMemo = {
|
|||||||
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
||||||
export const inFlightRequests = new Map();
|
export const inFlightRequests = new Map();
|
||||||
|
|
||||||
/** 官方配额摘要 10 秒短期缓存。 */
|
/** 官方配额摘要 10 秒短期缓存与失败退避冷却记录。 */
|
||||||
export const quotaSummaryCache = {
|
export const quotaSummaryCache = {
|
||||||
ts: 0,
|
ts: 0,
|
||||||
|
lastAttemptTs: 0,
|
||||||
accountName: '',
|
accountName: '',
|
||||||
data: null,
|
data: null,
|
||||||
error: null,
|
error: null,
|
||||||
@@ -245,6 +359,7 @@ export const cloudSyncState = {
|
|||||||
/** 插件自更新执行状态。 */
|
/** 插件自更新执行状态。 */
|
||||||
export const pluginUpdateState = {
|
export const pluginUpdateState = {
|
||||||
isUpdating: false,
|
isUpdating: false,
|
||||||
|
inFlightIsAuto: false,
|
||||||
lastAutoAttemptVersion: '',
|
lastAutoAttemptVersion: '',
|
||||||
lastResult: null,
|
lastResult: null,
|
||||||
lastError: null,
|
lastError: null,
|
||||||
|
|||||||
@@ -3,14 +3,19 @@
|
|||||||
*
|
*
|
||||||
* 负责:
|
* 负责:
|
||||||
* 1. 扫描 `~/.gemini/antigravity/conversations` 下的本地 `.db` / `.pb` / `.db-wal` 会话文件及修改时间;
|
* 1. 扫描 `~/.gemini/antigravity/conversations` 下的本地 `.db` / `.pb` / `.db-wal` 会话文件及修改时间;
|
||||||
* 2. 读取跨端共享的 `.deep_stats_cache.json`(兼容 IDE / CLI / Standalone 多端步骤数据合并);
|
* 2. 读取跨端共享的 `.deep_stats_cache.json`(兼容 IDE / CLI / Standalone 多端步骤数据合并与账号归属隔离);
|
||||||
* 3. 将 Language Server 摘要、本地磁盘文件与内存缓存三方会话列表对齐,并以受控并发(最多 4 路)
|
* 3. 将 Language Server 摘要、本地磁盘文件与内存缓存三方会话列表按大小写不敏感键对齐,并以受控并发(最多 4 路)
|
||||||
* 拉取新增或 Schema 过期的会话轨迹步骤,持久化至 `trajectory_usage_cache.json`。
|
* 拉取新增或 Schema 过期的会话轨迹步骤,持久化至 `trajectory_usage_cache.json`。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { extractLiveActivity, extractModelSteps, parseIsoMs } from '../speed-metrics.mjs';
|
import {
|
||||||
|
extractLiveActivity,
|
||||||
|
extractModelSteps,
|
||||||
|
getMaxMeaningfulStepIndex,
|
||||||
|
parseIsoMs,
|
||||||
|
} from '../speed-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
BRAIN_DIR,
|
BRAIN_DIR,
|
||||||
CACHE_FILE,
|
CACHE_FILE,
|
||||||
@@ -31,7 +36,7 @@ import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
|||||||
*
|
*
|
||||||
* @returns {Map<string, number>}
|
* @returns {Map<string, number>}
|
||||||
*/
|
*/
|
||||||
export function discoverLocalConversationFiles() {
|
function discoverLocalConversationFiles() {
|
||||||
const map = new Map();
|
const map = new Map();
|
||||||
if (!existsSync(CONVERSATIONS_DIR)) return map;
|
if (!existsSync(CONVERSATIONS_DIR)) return map;
|
||||||
try {
|
try {
|
||||||
@@ -61,7 +66,7 @@ export function discoverLocalConversationFiles() {
|
|||||||
* 加载并解析跨端(IDE / Standalone / JetBrains)写入的 `.deep_stats_cache.json` 缓存。
|
* 加载并解析跨端(IDE / Standalone / JetBrains)写入的 `.deep_stats_cache.json` 缓存。
|
||||||
* 使用文件签名 (`mtimeMs + size`) 进行 Memoize,文件未变化时直接返回内存 Map。
|
* 使用文件签名 (`mtimeMs + size`) 进行 Memoize,文件未变化时直接返回内存 Map。
|
||||||
*
|
*
|
||||||
* @returns {Map<string, {cascadeId: string, appSource: string, title: string, lastModifiedMs: number, steps: object[]}>}
|
* @returns {Map<string, {cascadeId: string, appSource: string, accountName: string, title: string, lastModifiedMs: number, steps: object[]}>}
|
||||||
*/
|
*/
|
||||||
export function loadExternalDeepStatsCache() {
|
export function loadExternalDeepStatsCache() {
|
||||||
const sigParts = [];
|
const sigParts = [];
|
||||||
@@ -90,6 +95,7 @@ export function loadExternalDeepStatsCache() {
|
|||||||
for (const filePath of existingFiles) {
|
for (const filePath of existingFiles) {
|
||||||
const raw = loadJson(filePath, null);
|
const raw = loadJson(filePath, null);
|
||||||
if (!raw || typeof raw.perConvo !== 'object' || !raw.perConvo) continue;
|
if (!raw || typeof raw.perConvo !== 'object' || !raw.perConvo) continue;
|
||||||
|
const fileAccountName = String(raw.accountName || raw.email || '').trim();
|
||||||
|
|
||||||
for (const item of Object.values(raw.perConvo)) {
|
for (const item of Object.values(raw.perConvo)) {
|
||||||
for (const e of item?.entries || []) {
|
for (const e of item?.entries || []) {
|
||||||
@@ -118,14 +124,18 @@ export function loadExternalDeepStatsCache() {
|
|||||||
const existing = convos.get(mapKey);
|
const existing = convos.get(mapKey);
|
||||||
if (existing && existing.steps.length >= rawEntries.length) continue;
|
if (existing && existing.steps.length >= rawEntries.length) continue;
|
||||||
|
|
||||||
|
const itemAccountName = String(
|
||||||
|
item?.accountName || item?.email || fileAccountName || ''
|
||||||
|
).trim();
|
||||||
|
|
||||||
const steps = [];
|
const steps = [];
|
||||||
let lastModifiedMs = 0;
|
let lastModifiedMs = 0;
|
||||||
for (let idx = 0; idx < rawEntries.length; idx++) {
|
for (let idx = 0; idx < rawEntries.length; idx++) {
|
||||||
const e = rawEntries[idx];
|
const e = rawEntries[idx];
|
||||||
const inputTokens = Math.max(0, Number(e?.inp) || 0);
|
const inputTokens = Math.max(0, Math.floor(Number(e?.inp) || 0));
|
||||||
const cacheReadTokens = Math.max(0, Number(e?.cache) || 0);
|
const cacheReadTokens = Math.max(0, Math.floor(Number(e?.cache) || 0));
|
||||||
const responseTokens = Math.max(0, Number(e?.out) || 0);
|
const responseTokens = Math.max(0, Math.floor(Number(e?.out) || 0));
|
||||||
const thinkingTokens = Math.max(0, Number(e?.reasoning) || 0);
|
const thinkingTokens = Math.max(0, Math.floor(Number(e?.reasoning) || 0));
|
||||||
const outputTokens = responseTokens + thinkingTokens;
|
const outputTokens = responseTokens + thinkingTokens;
|
||||||
if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0) continue;
|
if (inputTokens === 0 && cacheReadTokens === 0 && outputTokens === 0) continue;
|
||||||
const createdAtMs = e?.ts ? Date.parse(e.ts) || 0 : 0;
|
const createdAtMs = e?.ts ? Date.parse(e.ts) || 0 : 0;
|
||||||
@@ -155,6 +165,7 @@ export function loadExternalDeepStatsCache() {
|
|||||||
convos.set(mapKey, {
|
convos.set(mapKey, {
|
||||||
cascadeId,
|
cascadeId,
|
||||||
appSource,
|
appSource,
|
||||||
|
accountName: itemAccountName,
|
||||||
title: titleMap[fullKey] || titleMap[cascadeId] || cascadeId.slice(0, 8),
|
title: titleMap[fullKey] || titleMap[cascadeId] || cascadeId.slice(0, 8),
|
||||||
lastModifiedMs,
|
lastModifiedMs,
|
||||||
steps,
|
steps,
|
||||||
@@ -172,6 +183,7 @@ const MAX_CONCURRENT_RPC = 4;
|
|||||||
const LEGACY_MIGRATION_BATCH_SIZE = 8;
|
const LEGACY_MIGRATION_BATCH_SIZE = 8;
|
||||||
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
||||||
const FAILED_RPC_COOLDOWN_MS = 60_000;
|
const FAILED_RPC_COOLDOWN_MS = 60_000;
|
||||||
|
const ACTIVE_FAILED_RPC_COOLDOWN_MS = 15_000;
|
||||||
const TRANSCRIPT_TAIL_MAX_BYTES = 96 * 1024;
|
const TRANSCRIPT_TAIL_MAX_BYTES = 96 * 1024;
|
||||||
const MAX_TRANSCRIPT_MEMO_ENTRIES = 64;
|
const MAX_TRANSCRIPT_MEMO_ENTRIES = 64;
|
||||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
@@ -277,6 +289,9 @@ function readTranscriptTailSteps(cascadeId, maxLines = 24) {
|
|||||||
function scoreLiveActivitySpecificity(act) {
|
function scoreLiveActivitySpecificity(act) {
|
||||||
if (!act || typeof act !== 'object') return 0;
|
if (!act || typeof act !== 'object') return 0;
|
||||||
const sig = String(act.signature || '');
|
const sig = String(act.signature || '');
|
||||||
|
if (sig.startsWith('compacting:') || sig.startsWith('compacting-done:')) {
|
||||||
|
return 5;
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
sig.startsWith('planner-tool:') ||
|
sig.startsWith('planner-tool:') ||
|
||||||
sig.startsWith('step-run:') ||
|
sig.startsWith('step-run:') ||
|
||||||
@@ -285,7 +300,6 @@ function scoreLiveActivitySpecificity(act) {
|
|||||||
return 4;
|
return 4;
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
sig.startsWith('compacting:') ||
|
|
||||||
sig.startsWith('responding:') ||
|
sig.startsWith('responding:') ||
|
||||||
sig.startsWith('thinking:') ||
|
sig.startsWith('thinking:') ||
|
||||||
sig.startsWith('responding-done:') ||
|
sig.startsWith('responding-done:') ||
|
||||||
@@ -302,37 +316,35 @@ function scoreLiveActivitySpecificity(act) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
function extractActivityStepOrd(act) {
|
|
||||||
const m = String(act?.signature || '').match(/^[a-z0-9-]+:(\d+)(?::|$)/i);
|
|
||||||
return m ? Number(m[1]) : -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) {
|
function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) {
|
||||||
if (!isRunning) return null;
|
if (!isRunning) return null;
|
||||||
const rpcAct =
|
const hasRpcSteps = Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0;
|
||||||
Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0
|
const rpcAct = hasRpcSteps ? extractLiveActivity(rpcRawSteps, true, fallbackMs) : null;
|
||||||
? extractLiveActivity(rpcRawSteps, true, fallbackMs)
|
|
||||||
: null;
|
|
||||||
const transcriptSteps = readTranscriptTailSteps(cascadeId);
|
const transcriptSteps = readTranscriptTailSteps(cascadeId);
|
||||||
const transcriptAct =
|
const transcriptAct =
|
||||||
transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null;
|
transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null;
|
||||||
|
|
||||||
if (rpcAct && transcriptAct) {
|
if (rpcAct && transcriptAct) {
|
||||||
const rpcMs = Number(rpcAct.startedAtMs || 0);
|
// 1. 先按真实 Cortex 步骤序号对齐比较:尚未刷入 transcript.jsonl 的新步骤(如正在进行的 CHECKPOINT 压缩或流式回复)优先采用 RPC
|
||||||
const transMs = Number(transcriptAct.startedAtMs || 0);
|
const rpcStepIdx = getMaxMeaningfulStepIndex(rpcRawSteps);
|
||||||
if (rpcMs > 0 && transMs > 0 && rpcMs !== transMs) {
|
const transStepIdx = getMaxMeaningfulStepIndex(transcriptSteps);
|
||||||
return rpcMs > transMs ? rpcAct : transcriptAct;
|
if (rpcStepIdx >= 0 && transStepIdx >= 0 && rpcStepIdx !== transStepIdx) {
|
||||||
}
|
return rpcStepIdx > transStepIdx ? rpcAct : transcriptAct;
|
||||||
const rpcOrd = extractActivityStepOrd(rpcAct);
|
|
||||||
const transOrd = extractActivityStepOrd(transcriptAct);
|
|
||||||
if (rpcOrd >= 0 && transOrd >= 0 && rpcOrd !== transOrd) {
|
|
||||||
return rpcOrd > transOrd ? rpcAct : transcriptAct;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2. 同一步骤序号下优先采用语义更明确的状态(上下文压缩 > 工具执行 > 流式生成 > 工具后置思考)
|
||||||
const rpcScore = scoreLiveActivitySpecificity(rpcAct);
|
const rpcScore = scoreLiveActivitySpecificity(rpcAct);
|
||||||
const transScore = scoreLiveActivitySpecificity(transcriptAct);
|
const transScore = scoreLiveActivitySpecificity(transcriptAct);
|
||||||
if (transScore > rpcScore) return transcriptAct;
|
if (rpcScore !== transScore) {
|
||||||
if (rpcScore > transScore) return rpcAct;
|
return rpcScore > transScore ? rpcAct : transcriptAct;
|
||||||
// 同步骤、同优先级下优先采用包含完整 tool_calls 参数的 transcript.jsonl 解析结果
|
}
|
||||||
|
|
||||||
|
// 3. 同一步骤且均为压缩态时,优先采用携带精确完成时刻的 RPC 状态;常规步骤则优先采用含完整参数的 transcript.jsonl
|
||||||
|
const rpcMs = Number(rpcAct.startedAtMs || 0);
|
||||||
|
const transMs = Number(transcriptAct.startedAtMs || 0);
|
||||||
|
if (rpcAct.phase === 'compacting' && rpcMs !== transMs) {
|
||||||
|
return rpcMs >= transMs ? rpcAct : transcriptAct;
|
||||||
|
}
|
||||||
return transcriptAct;
|
return transcriptAct;
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
@@ -377,13 +389,11 @@ function mergeSubagentSpecs(primary, secondary) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 从主/父会话的原始轨迹步骤 (`CORTEX_STEP_TYPE_INVOKE_SUBAGENT`) 中提取派生子代理列表。
|
* 从主/父会话的原始轨迹步骤 (`CORTEX_STEP_TYPE_INVOKE_SUBAGENT`) 中提取派生子代理列表。
|
||||||
* Antigravity 重启后 `GetAllCascadeTrajectories` 不再返回历史子代理摘要,
|
|
||||||
* 通过解析父轨迹内的 `invokeSubagent` 步骤即可完整找回所有子代理及其角色名称与启动顺序。
|
|
||||||
*
|
*
|
||||||
* @param {object[]} [rawSteps=[]]
|
* @param {object[]} [rawSteps=[]]
|
||||||
* @returns {Array<{ cascadeId: string, role: string, typeName: string, createdTimeMs: number, spawnOrder: number }>}
|
* @returns {Array<{ cascadeId: string, role: string, typeName: string, createdTimeMs: number, spawnOrder: number }>}
|
||||||
*/
|
*/
|
||||||
export function extractSubagentRefsFromSteps(rawSteps = []) {
|
function extractSubagentRefsFromSteps(rawSteps = []) {
|
||||||
const refsMap = new Map();
|
const refsMap = new Map();
|
||||||
let orderCounter = 0;
|
let orderCounter = 0;
|
||||||
for (const st of rawSteps || []) {
|
for (const st of rawSteps || []) {
|
||||||
@@ -482,9 +492,10 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
|
|||||||
* 选定当前活跃会话,并以最多 4 路并发增量同步更新了的会话轨迹。
|
* 选定当前活跃会话,并以最多 4 路并发增量同步更新了的会话轨迹。
|
||||||
*
|
*
|
||||||
* @param {{
|
* @param {{
|
||||||
* summariesObj: Record<string, object>,
|
* summariesObj?: Record<string, object>,
|
||||||
* currentAccountName: string,
|
* currentAccountName?: string,
|
||||||
* requestedConvId: string
|
* requestedConvId?: string,
|
||||||
|
* forceRefresh?: boolean
|
||||||
* }} params
|
* }} params
|
||||||
* @returns {Promise<{
|
* @returns {Promise<{
|
||||||
* conversations: object[],
|
* conversations: object[],
|
||||||
@@ -496,34 +507,87 @@ export async function enumerateAndSyncConversations({
|
|||||||
summariesObj = {},
|
summariesObj = {},
|
||||||
currentAccountName = '',
|
currentAccountName = '',
|
||||||
requestedConvId = '',
|
requestedConvId = '',
|
||||||
|
forceRefresh = false,
|
||||||
}) {
|
}) {
|
||||||
const nowSweepMs = Date.now();
|
const nowSweepMs = Date.now();
|
||||||
for (const [k, ts] of failedFetchCooldownMap.entries()) {
|
if (forceRefresh) {
|
||||||
if (nowSweepMs - ts >= FAILED_RPC_COOLDOWN_MS) {
|
failedFetchCooldownMap.clear();
|
||||||
|
} else {
|
||||||
|
for (const [k, rec] of failedFetchCooldownMap.entries()) {
|
||||||
|
const failedAt = typeof rec === 'number' ? rec : rec?.failedAt || 0;
|
||||||
|
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec?.cooldownMs || FAILED_RPC_COOLDOWN_MS;
|
||||||
|
if (nowSweepMs - failedAt >= cooldownMs) {
|
||||||
failedFetchCooldownMap.delete(k);
|
failedFetchCooldownMap.delete(k);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cacheDirty = cacheState.needsSave;
|
||||||
const diskConvMap = discoverLocalConversationFiles();
|
const diskConvMap = discoverLocalConversationFiles();
|
||||||
const allCascadeIds = new Set([
|
|
||||||
...Object.keys(summariesObj),
|
// 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC)
|
||||||
...diskConvMap.keys(),
|
const canonicalIdByLower = new Map();
|
||||||
...Object.keys(trajectoryCache),
|
const summariesByLower = new Map();
|
||||||
]);
|
for (const [rawId, summary] of Object.entries(summariesObj || {})) {
|
||||||
const existingLowerIds = new Set(Array.from(allCascadeIds, (id) => id.toLowerCase()));
|
const lower = String(rawId || '').trim().toLowerCase();
|
||||||
for (const entry of Object.values(trajectoryCache)) {
|
if (!lower) continue;
|
||||||
|
canonicalIdByLower.set(lower, rawId);
|
||||||
|
summariesByLower.set(lower, summary);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const rawCacheKey of Object.keys(trajectoryCache)) {
|
||||||
|
const lower = String(rawCacheKey || '').trim().toLowerCase();
|
||||||
|
if (!lower) continue;
|
||||||
|
const existingCanon = canonicalIdByLower.get(lower);
|
||||||
|
if (!existingCanon) {
|
||||||
|
// 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目
|
||||||
|
const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey;
|
||||||
|
if (normalizedKey !== rawCacheKey) {
|
||||||
|
trajectoryCache[normalizedKey] = trajectoryCache[rawCacheKey];
|
||||||
|
delete trajectoryCache[rawCacheKey];
|
||||||
|
cacheDirty = true;
|
||||||
|
}
|
||||||
|
canonicalIdByLower.set(lower, normalizedKey);
|
||||||
|
} else if (existingCanon !== rawCacheKey) {
|
||||||
|
const targetEntry = trajectoryCache[existingCanon];
|
||||||
|
const dupEntry = trajectoryCache[rawCacheKey];
|
||||||
|
if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) {
|
||||||
|
trajectoryCache[existingCanon] = dupEntry;
|
||||||
|
}
|
||||||
|
delete trajectoryCache[rawCacheKey];
|
||||||
|
cacheDirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const diskLowerId of diskConvMap.keys()) {
|
||||||
|
if (!canonicalIdByLower.has(diskLowerId)) {
|
||||||
|
canonicalIdByLower.set(diskLowerId, diskLowerId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表
|
||||||
|
for (const [cacheKey, entry] of Object.entries(trajectoryCache)) {
|
||||||
|
const cacheKeyLower = String(cacheKey || '').toLowerCase();
|
||||||
|
if (
|
||||||
|
entry?.accountName &&
|
||||||
|
currentAccountName &&
|
||||||
|
entry.accountName !== currentAccountName &&
|
||||||
|
!summariesByLower.has(cacheKeyLower)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
for (const ref of entry?.subagentRefs || []) {
|
for (const ref of entry?.subagentRefs || []) {
|
||||||
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||||
if (refCid && !existingLowerIds.has(refCid)) {
|
if (refCid && !canonicalIdByLower.has(refCid)) {
|
||||||
allCascadeIds.add(refCid);
|
canonicalIdByLower.set(refCid, refCid);
|
||||||
existingLowerIds.add(refCid);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
||||||
const rawConversations = [];
|
const rawConversations = [];
|
||||||
for (const cascadeId of allCascadeIds) {
|
for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) {
|
||||||
const item = summariesObj[cascadeId];
|
const item = summariesByLower.get(cidLower);
|
||||||
const cached = trajectoryCache[cascadeId];
|
const cached = trajectoryCache[cascadeId];
|
||||||
if (
|
if (
|
||||||
cached?.accountName &&
|
cached?.accountName &&
|
||||||
@@ -533,7 +597,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
) {
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const diskMtimeMs = diskConvMap.get(cascadeId) || 0;
|
const diskMtimeMs = diskConvMap.get(cidLower) || 0;
|
||||||
const rawMeta = item?.trajectoryMetadata || item?.metadata || {};
|
const rawMeta = item?.trajectoryMetadata || item?.metadata || {};
|
||||||
const parentConversationId = String(
|
const parentConversationId = String(
|
||||||
rawMeta.parentConversationId || cached?.parentConversationId || ''
|
rawMeta.parentConversationId || cached?.parentConversationId || ''
|
||||||
@@ -549,7 +613,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null;
|
const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null;
|
||||||
const isSubagent =
|
const isSubagent =
|
||||||
Boolean(parentConversationId) ||
|
Boolean(parentConversationId) ||
|
||||||
Boolean(rootConversationId && rootConversationId !== cascadeId.toLowerCase());
|
Boolean(rootConversationId && rootConversationId !== cidLower);
|
||||||
|
|
||||||
if (item) {
|
if (item) {
|
||||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||||
@@ -627,7 +691,6 @@ export async function enumerateAndSyncConversations({
|
|||||||
|
|
||||||
rawConversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);
|
rawConversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);
|
||||||
|
|
||||||
let cacheDirty = cacheState.needsSave;
|
|
||||||
const attemptedFetchIds = new Set();
|
const attemptedFetchIds = new Set();
|
||||||
const nowPollMs = Date.now();
|
const nowPollMs = Date.now();
|
||||||
|
|
||||||
@@ -638,12 +701,13 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function isFetchInCooldown(conv, sig) {
|
function isFetchInCooldown(conv, sig) {
|
||||||
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') return false;
|
if (forceRefresh) return false;
|
||||||
if (reqLower && conv.cascadeId.toLowerCase() === reqLower) return false;
|
|
||||||
const key = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
const key = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||||
const failedAt = failedFetchCooldownMap.get(key);
|
const rec = failedFetchCooldownMap.get(key);
|
||||||
if (!failedAt) return false;
|
if (!rec) return false;
|
||||||
if (nowPollMs - failedAt >= FAILED_RPC_COOLDOWN_MS) {
|
const failedAt = typeof rec === 'number' ? rec : rec.failedAt;
|
||||||
|
const cooldownMs = typeof rec === 'number' ? FAILED_RPC_COOLDOWN_MS : rec.cooldownMs;
|
||||||
|
if (nowPollMs - failedAt >= cooldownMs) {
|
||||||
failedFetchCooldownMap.delete(key);
|
failedFetchCooldownMap.delete(key);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -690,7 +754,10 @@ export async function enumerateAndSyncConversations({
|
|||||||
const sig = buildConvSig(conv);
|
const sig = buildConvSig(conv);
|
||||||
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||||
|
const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower);
|
||||||
const prev = trajectoryCache[conv.cascadeId];
|
const prev = trajectoryCache[conv.cascadeId];
|
||||||
|
let partialTailSteps = [];
|
||||||
|
let hasTailStepInfo = false;
|
||||||
try {
|
try {
|
||||||
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
||||||
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
||||||
@@ -698,6 +765,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
const rawSteps = trajRes.trajectory.steps;
|
const rawSteps = trajRes.trajectory.steps;
|
||||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) {
|
if (Number(trajRes.numTotalSteps) > rawSteps.length) {
|
||||||
|
if (rawSteps.length > 0) {
|
||||||
|
partialTailSteps = rawSteps;
|
||||||
|
const tailIdx =
|
||||||
|
rawSteps[rawSteps.length - 1]?.metadata?.sourceTrajectoryStepInfo?.stepIndex;
|
||||||
|
hasTailStepInfo = Number.isFinite(Number(tailIdx));
|
||||||
|
}
|
||||||
throw new Error('Incomplete trajectory; retaining cached usage');
|
throw new Error('Incomplete trajectory; retaining cached usage');
|
||||||
}
|
}
|
||||||
failedFetchCooldownMap.delete(cooldownKey);
|
failedFetchCooldownMap.delete(cooldownKey);
|
||||||
@@ -777,13 +850,17 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
||||||
|
if (!(isRunning && hasTailStepInfo)) {
|
||||||
|
const cooldownMs =
|
||||||
|
isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS;
|
||||||
|
failedFetchCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs });
|
||||||
|
}
|
||||||
if (!isRunning) {
|
if (!isRunning) {
|
||||||
failedFetchCooldownMap.set(cooldownKey, nowPollMs);
|
|
||||||
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
liveActivityMemo.delete(conv.cascadeId.toLowerCase());
|
||||||
} else {
|
} else {
|
||||||
const fallbackLive = resolveBestLiveActivity(
|
const fallbackLive = resolveBestLiveActivity(
|
||||||
conv.cascadeId,
|
conv.cascadeId,
|
||||||
[],
|
partialTailSteps,
|
||||||
true,
|
true,
|
||||||
conv.lastModifiedMs || conv.createdTimeMs || 0
|
conv.lastModifiedMs || conv.createdTimeMs || 0
|
||||||
);
|
);
|
||||||
@@ -859,15 +936,17 @@ export async function enumerateAndSyncConversations({
|
|||||||
const subCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
const subCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||||
if (!subCid || subCid === parentId) continue;
|
if (!subCid || subCid === parentId) continue;
|
||||||
|
|
||||||
|
const canonSubId = canonicalIdByLower.get(subCid) || subCid;
|
||||||
|
canonicalIdByLower.set(subCid, canonSubId);
|
||||||
let subConv = byLowerId.get(subCid);
|
let subConv = byLowerId.get(subCid);
|
||||||
const subCached = trajectoryCache[subConv?.cascadeId || subCid];
|
const subCached = trajectoryCache[subConv?.cascadeId || canonSubId];
|
||||||
if (!subConv) {
|
if (!subConv) {
|
||||||
const diskMtimeMs = diskConvMap.get(subCid) || 0;
|
const diskMtimeMs = diskConvMap.get(subCid) || 0;
|
||||||
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
||||||
const stepCount = Number(subCached?.steps?.length || 0);
|
const stepCount = Number(subCached?.steps?.length || 0);
|
||||||
subConv = {
|
subConv = {
|
||||||
cascadeId: subCid,
|
cascadeId: canonSubId,
|
||||||
title: ref.role || subCached?.title || subCid.slice(0, 8),
|
title: ref.role || subCached?.title || canonSubId.slice(0, 8),
|
||||||
stepCount,
|
stepCount,
|
||||||
rawStepCount: stepCount,
|
rawStepCount: stepCount,
|
||||||
status: 'IDLE',
|
status: 'IDLE',
|
||||||
@@ -1037,7 +1116,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下
|
// 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下;孤儿子代理绝不提升为顶层根会话
|
||||||
const subagentsByRoot = new Map();
|
const subagentsByRoot = new Map();
|
||||||
const conversations = [];
|
const conversations = [];
|
||||||
|
|
||||||
@@ -1045,11 +1124,13 @@ export async function enumerateAndSyncConversations({
|
|||||||
const cid = conv.cascadeId.toLowerCase();
|
const cid = conv.cascadeId.toLowerCase();
|
||||||
const rootId = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase();
|
const rootId = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase();
|
||||||
const rootTarget = byId.get(rootId);
|
const rootTarget = byId.get(rootId);
|
||||||
if (conv.isSubagent && rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) {
|
if (conv.isSubagent) {
|
||||||
|
if (rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) {
|
||||||
if (!subagentsByRoot.has(rootId)) {
|
if (!subagentsByRoot.has(rootId)) {
|
||||||
subagentsByRoot.set(rootId, []);
|
subagentsByRoot.set(rootId, []);
|
||||||
}
|
}
|
||||||
subagentsByRoot.get(rootId).push(conv);
|
subagentsByRoot.get(rootId).push(conv);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
conversations.push(conv);
|
conversations.push(conv);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,22 +3,14 @@
|
|||||||
*
|
*
|
||||||
* 负责:
|
* 负责:
|
||||||
* 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
|
* 1. 向本地 Language Server 发起带 CSRF 鉴权与超时保护的 Connect RPC 调用 (`callLsRpc`);
|
||||||
* 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存,
|
* 2. 拉取并缓存 `RetrieveUserQuotaSummary` 官方实时配额摘要(常规轮询使用 10 秒短期缓存与失败退避冷却,
|
||||||
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存);
|
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。
|
||||||
* 3. 维护全局 `StreamDiagnostics` 实例以采样流式事件时序。
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { StreamDiagnostics } from '../stream-diagnostics.mjs';
|
import { CSRF_TOKEN, LS_BASE_URL, quotaSummaryCache } from './config.mjs';
|
||||||
import { CSRF_TOKEN, DATA_DIR, LS_ADDR, quotaSummaryCache } from './config.mjs';
|
|
||||||
|
|
||||||
/**
|
const QUOTA_CACHE_TTL_MS = 10_000;
|
||||||
* 全局流式传输诊断采样器实例。
|
const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
||||||
*/
|
|
||||||
export const diagnostics = new StreamDiagnostics({
|
|
||||||
dataDir: DATA_DIR,
|
|
||||||
lsAddress: LS_ADDR,
|
|
||||||
csrfToken: CSRF_TOKEN,
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 调用本地 `LanguageServerService` 的指定 RPC 方法。
|
* 调用本地 `LanguageServerService` 的指定 RPC 方法。
|
||||||
@@ -29,13 +21,16 @@ export const diagnostics = new StreamDiagnostics({
|
|||||||
* @returns {Promise<object>}
|
* @returns {Promise<object>}
|
||||||
*/
|
*/
|
||||||
export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
||||||
|
if (!LS_BASE_URL) {
|
||||||
|
throw new Error('Language Server address (ANTIGRAVITY_LS_ADDRESS) is not configured');
|
||||||
|
}
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`http://${LS_ADDR}/exa.language_server_pb.LanguageServerService/${method}`,
|
`${LS_BASE_URL}/exa.language_server_pb.LanguageServerService/${method}`,
|
||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'x-codeium-csrf-token': CSRF_TOKEN,
|
'x-codeium-csrf-token': CSRF_TOKEN || '',
|
||||||
},
|
},
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
signal: AbortSignal.timeout(timeoutMs),
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
@@ -53,38 +48,63 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
|||||||
*
|
*
|
||||||
* 缓存策略:
|
* 缓存策略:
|
||||||
* - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口;
|
* - 常规轮询在 10 秒内直接复用内存缓存,避免高频打满上游接口;
|
||||||
* - 当超过 10 秒或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时,
|
* - 常规轮询发生网络失败或空载荷时进入 5 秒冷却退避,避免每 2 秒重复超时阻塞;
|
||||||
|
* - 当超过 TTL 或传入 `forceRefresh = true`(如手动刷新或检测到账号切换)时,
|
||||||
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
|
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
|
||||||
*
|
*
|
||||||
* @param {boolean} [forceRefresh=false] 是否强制穿透本地 10 秒缓存
|
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
|
||||||
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null}>}
|
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
|
||||||
*/
|
*/
|
||||||
export async function getOfficialQuotaSummary(forceRefresh = false) {
|
export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < 10000) {
|
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) {
|
||||||
return {
|
return {
|
||||||
data: quotaSummaryCache.data,
|
data: quotaSummaryCache.data,
|
||||||
fetchedAtMs: quotaSummaryCache.ts,
|
fetchedAtMs: quotaSummaryCache.ts,
|
||||||
isStale: false,
|
isStale: false,
|
||||||
refreshFailed: false,
|
refreshFailed: false,
|
||||||
error: null,
|
error: null,
|
||||||
|
fromCache: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
!forceRefresh &&
|
||||||
|
quotaSummaryCache.lastAttemptTs > 0 &&
|
||||||
|
now - quotaSummaryCache.lastAttemptTs < QUOTA_RETRY_COOLDOWN_MS &&
|
||||||
|
quotaSummaryCache.error
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
data: quotaSummaryCache.data,
|
||||||
|
fetchedAtMs: quotaSummaryCache.ts || 0,
|
||||||
|
isStale: Boolean(quotaSummaryCache.data),
|
||||||
|
refreshFailed: true,
|
||||||
|
error: quotaSummaryCache.error,
|
||||||
|
fromCache: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
quotaSummaryCache.lastAttemptTs = now;
|
||||||
try {
|
try {
|
||||||
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
|
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
|
||||||
const payload = res?.response || res;
|
const payload = res?.response !== undefined ? res.response : res;
|
||||||
if (Array.isArray(payload?.groups) || Array.isArray(payload?.buckets)) {
|
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
||||||
|
const normalized =
|
||||||
|
Array.isArray(payload.groups) || Array.isArray(payload.buckets)
|
||||||
|
? payload
|
||||||
|
: { ...payload, groups: [] };
|
||||||
quotaSummaryCache.ts = now;
|
quotaSummaryCache.ts = now;
|
||||||
quotaSummaryCache.data = payload;
|
quotaSummaryCache.data = normalized;
|
||||||
quotaSummaryCache.error = null;
|
quotaSummaryCache.error = null;
|
||||||
return {
|
return {
|
||||||
data: payload,
|
data: normalized,
|
||||||
fetchedAtMs: now,
|
fetchedAtMs: now,
|
||||||
isStale: false,
|
isStale: false,
|
||||||
refreshFailed: false,
|
refreshFailed: false,
|
||||||
error: null,
|
error: null,
|
||||||
|
fromCache: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
quotaSummaryCache.error = 'Quota summary empty';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
|
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
|
||||||
quotaSummaryCache.error = err.message;
|
quotaSummaryCache.error = err.message;
|
||||||
@@ -95,5 +115,6 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
|
|||||||
isStale: Boolean(quotaSummaryCache.data),
|
isStale: Boolean(quotaSummaryCache.data),
|
||||||
refreshFailed: true,
|
refreshFailed: true,
|
||||||
error: quotaSummaryCache.error || 'Quota RPC unavailable',
|
error: quotaSummaryCache.error || 'Quota RPC unavailable',
|
||||||
|
fromCache: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
* @fileoverview 模型身份识别、展示名称规范化与单步 API 等效成本计算。
|
* @fileoverview 模型身份识别、展示名称规范化与单步 API 等效成本计算。
|
||||||
*
|
*
|
||||||
* 核心原则:
|
* 核心原则:
|
||||||
* 1. 优先信任服务端下发的动态模型目录 (`dynamicModelMap`) 与真实响应模型 (`responseModel`),
|
* 1. 优先融合服务端下发的动态模型目录 (`dynamicModelMap`)、静态占位符表 (`PLACEHOLDER_MAP`)
|
||||||
* 其次匹配本地/云端 `PLACEHOLDER_MAP` 与 `MODEL_PRICING`;
|
* 与真实响应模型 (`responseModel`),并优先匹配含档位后缀的精确价格条目;
|
||||||
* 2. 价格未知或模型身份无法确认时,严格返回 `pricing: null` 与 `costUsd: null`,
|
* 2. 价格未知或模型身份无法确认时,严格返回 `pricing: null` 与 `costUsd: null`,
|
||||||
* 绝不借用其他模型单价伪造费用。
|
* 绝不借用其他模型单价伪造费用。
|
||||||
*/
|
*/
|
||||||
@@ -12,29 +12,23 @@ import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据 API 提供商枚举或模型标识符推断所属模型家族(`'Gemini'` | `'Claude'` | `'GPT'` | `'Other'`)。
|
* 根据 API 提供商枚举或模型标识符推断所属模型家族(`'Gemini'` | `'Claude'` | `'GPT'` | `'Other'`)。
|
||||||
|
* 注意:先匹配更具体的 `ANTHROPIC`/`CLAUDE` 与 `OPENAI`/`GPT`(含 `o1`/`o3`/`o4` 系列),
|
||||||
|
* 防止 `API_PROVIDER_GOOGLE_VERTEX_ANTHROPIC` 被宽泛的 `GOOGLE` 子串抢先误判为 `'Gemini'`。
|
||||||
*
|
*
|
||||||
* @param {string} [rawModelKey=''] 原始模型键名或占位符
|
* @param {string} [rawModelKey=''] 原始模型键名或占位符
|
||||||
* @param {string} [modelId=''] 规范化模型 ID
|
* @param {string} [modelId=''] 规范化模型 ID
|
||||||
* @param {string} [apiProvider=''] 上游 API 提供商枚举字符串
|
* @param {string} [apiProvider=''] 上游 API 提供商枚举字符串
|
||||||
* @returns {'Gemini'|'Claude'|'GPT'|'Other'}
|
* @returns {'Gemini'|'Claude'|'GPT'|'Other'}
|
||||||
*/
|
*/
|
||||||
export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvider = '') {
|
function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvider = '') {
|
||||||
const prov = String(apiProvider || '').toUpperCase();
|
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('ANTHROPIC') || prov.includes('CLAUDE')) return 'Claude';
|
||||||
if (prov.includes('OPENAI') || prov.includes('GPT')) return 'GPT';
|
if (prov.includes('OPENAI') || prov.includes('GPT')) return 'GPT';
|
||||||
|
if (prov.includes('GEMINI') || prov.includes('GOOGLE')) return 'Gemini';
|
||||||
|
|
||||||
const combined = `${rawModelKey} ${modelId}`.toUpperCase();
|
const combined = `${rawModelKey} ${modelId}`.toUpperCase();
|
||||||
if (
|
if (
|
||||||
combined.includes('GEMINI') ||
|
combined.includes('ANTHROPIC') ||
|
||||||
combined.includes('CARBON') ||
|
|
||||||
combined.includes('ARGON') ||
|
|
||||||
combined.includes('FLASH') ||
|
|
||||||
combined.includes('GOOGLE')
|
|
||||||
) {
|
|
||||||
return 'Gemini';
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
combined.includes('CLAUDE') ||
|
combined.includes('CLAUDE') ||
|
||||||
combined.includes('FABLE') ||
|
combined.includes('FABLE') ||
|
||||||
combined.includes('SONNET') ||
|
combined.includes('SONNET') ||
|
||||||
@@ -43,9 +37,22 @@ export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', api
|
|||||||
) {
|
) {
|
||||||
return 'Claude';
|
return 'Claude';
|
||||||
}
|
}
|
||||||
if (combined.includes('GPT') || combined.includes('OPENAI')) {
|
if (
|
||||||
|
combined.includes('GPT') ||
|
||||||
|
combined.includes('OPENAI') ||
|
||||||
|
/\bO[134](?:[-_\s]|$)/.test(combined)
|
||||||
|
) {
|
||||||
return 'GPT';
|
return 'GPT';
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
combined.includes('GEMINI') ||
|
||||||
|
combined.includes('CARBON') ||
|
||||||
|
combined.includes('ARGON') ||
|
||||||
|
combined.includes('FLASH') ||
|
||||||
|
combined.includes('GOOGLE')
|
||||||
|
) {
|
||||||
|
return 'Gemini';
|
||||||
|
}
|
||||||
return 'Other';
|
return 'Other';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,13 +67,15 @@ export function isArgonModelIdentifier(...parts) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型。
|
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M429 枚举)。
|
||||||
*
|
*
|
||||||
* @param {...string} parts 待检测的标识片段
|
* @param {...string} parts 待检测的标识片段
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function isCarbonModelIdentifier(...parts) {
|
export function isCarbonModelIdentifier(...parts) {
|
||||||
return /\bcarbon\b|gemini-4-carbon/i.test(parts.filter(Boolean).join(' '));
|
return /\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M429\b/i.test(
|
||||||
|
parts.filter(Boolean).join(' ')
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -84,7 +93,8 @@ export function getBaseModelLabel(label = '') {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将形如 `gemini-3.1-pro`、`gemini-3.5-flash-lite` 或 `gemini-4-carbon` 的通用模型 Slug 转为人类可读标签。
|
* 将严格匹配的 `gemini-3.1-pro`、`gemini-3.5-flash-lite` 或 `gemini-4-carbon` 通用模型 Slug 转为人类可读标签。
|
||||||
|
* 使用行尾锚点 `$` 防止未收录新后缀(如 `gemini-3.1-pro-ultra-v2`)被静默截断伪装成旧模型获取错误定价。
|
||||||
*
|
*
|
||||||
* @param {string} [slug='']
|
* @param {string} [slug='']
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
@@ -94,7 +104,7 @@ export function formatGenericModelSlug(slug = '') {
|
|||||||
.trim()
|
.trim()
|
||||||
.replace(/^session-display:/i, '');
|
.replace(/^session-display:/i, '');
|
||||||
if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return '';
|
if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return '';
|
||||||
const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon)(?:-(lite))?/i);
|
const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon)(?:-(lite))?$/i);
|
||||||
if (m) {
|
if (m) {
|
||||||
const ver = m[1];
|
const ver = m[1];
|
||||||
const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase();
|
const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase();
|
||||||
@@ -107,54 +117,69 @@ export function formatGenericModelSlug(slug = '') {
|
|||||||
/**
|
/**
|
||||||
* 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与单价配置。
|
* 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与单价配置。
|
||||||
*
|
*
|
||||||
* @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M318`)
|
* @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`)
|
||||||
* @param {Map<string, {modelId: string, label: string, quotaInfo?: object}>} dynamicModelMap 从 `GetUserStatus` 提取的动态模型表
|
* @param {Map<string, {modelId: string, label: string, quotaInfo?: object}>} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表
|
||||||
* @param {string} [apiProvider=''] API 提供商枚举
|
* @param {string} [apiProvider=''] API 提供商枚举
|
||||||
* @param {string} [modelDisplayName=''] 已知的模型展示名称
|
* @param {string} [modelDisplayName=''] 已知的模型展示名称
|
||||||
* @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`)
|
* @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(
|
export function resolveModelInfo(
|
||||||
rawModelKey,
|
rawModelKey,
|
||||||
dynamicModelMap,
|
dynamicModelMap = new Map(),
|
||||||
apiProvider = '',
|
apiProvider = '',
|
||||||
modelDisplayName = '',
|
modelDisplayName = '',
|
||||||
responseModel = ''
|
responseModel = ''
|
||||||
) {
|
) {
|
||||||
const dyn = dynamicModelMap.get(rawModelKey) || PLACEHOLDER_MAP[rawModelKey];
|
const dynEntry =
|
||||||
|
dynamicModelMap && typeof dynamicModelMap.get === 'function'
|
||||||
|
? dynamicModelMap.get(rawModelKey)
|
||||||
|
: null;
|
||||||
|
const staticPh = PLACEHOLDER_MAP[rawModelKey] || null;
|
||||||
|
|
||||||
|
// 若 GetUserStatus 仅下发了 label 而未下发真实 modelId(或被填成占位符自身),继续合并静态 PLACEHOLDER_MAP 的精确 modelId
|
||||||
|
const dynValidModelId =
|
||||||
|
dynEntry?.modelId && dynEntry.modelId !== rawModelKey ? dynEntry.modelId : '';
|
||||||
|
const mergedModelId = dynValidModelId || staticPh?.modelId || dynEntry?.modelId || '';
|
||||||
|
const mergedLabel = dynEntry?.label || staticPh?.label || '';
|
||||||
|
|
||||||
const cleanResponseModel =
|
const cleanResponseModel =
|
||||||
responseModel && responseModel !== 'unknown' ? String(responseModel).trim() : '';
|
responseModel && responseModel !== 'unknown' ? String(responseModel).trim() : '';
|
||||||
const cleanRawFallback =
|
const cleanRawFallback =
|
||||||
rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel;
|
rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel;
|
||||||
const derivedDisplay =
|
const derivedDisplay =
|
||||||
modelDisplayName ||
|
modelDisplayName ||
|
||||||
dyn?.label ||
|
mergedLabel ||
|
||||||
formatGenericModelSlug(rawModelKey) ||
|
formatGenericModelSlug(rawModelKey) ||
|
||||||
formatGenericModelSlug(cleanResponseModel) ||
|
formatGenericModelSlug(cleanResponseModel) ||
|
||||||
cleanRawFallback ||
|
cleanRawFallback ||
|
||||||
'模型未知';
|
'模型未知';
|
||||||
|
|
||||||
|
// 先生成保留档位后缀的精确 Slug(如 "Gemini 3.8 Flash (Low)" -> "gemini-3.8-flash-low"),防止被基础族名定价覆盖
|
||||||
|
const tieredSlug = derivedDisplay
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[()]/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.replace(/[^a-z0-9.]+/g, '-')
|
||||||
|
.replace(/^-+|-+$/g, '');
|
||||||
|
const tieredDashedSlug = tieredSlug.replace(/\./g, '-');
|
||||||
|
|
||||||
const baseLabel = getBaseModelLabel(derivedDisplay);
|
const baseLabel = getBaseModelLabel(derivedDisplay);
|
||||||
const canonicalSlug = baseLabel.toLowerCase().replace(/\s+/g, '-');
|
const canonicalSlug = baseLabel.toLowerCase().replace(/\s+/g, '-');
|
||||||
const dashedSlug = canonicalSlug.replace(/\./g, '-');
|
const dashedSlug = canonicalSlug.replace(/\./g, '-');
|
||||||
const modelId =
|
const modelId =
|
||||||
dyn?.modelId ||
|
mergedModelId ||
|
||||||
(rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel) ||
|
(rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel) ||
|
||||||
'unknown';
|
'unknown';
|
||||||
|
|
||||||
const explicitPricing =
|
const explicitPricing =
|
||||||
MODEL_PRICING[modelId] ||
|
MODEL_PRICING[modelId] ||
|
||||||
MODEL_PRICING[rawModelKey] ||
|
MODEL_PRICING[rawModelKey] ||
|
||||||
(cleanResponseModel ? MODEL_PRICING[cleanResponseModel] : null) ||
|
(cleanResponseModel ? MODEL_PRICING[cleanResponseModel] : null) ||
|
||||||
|
MODEL_PRICING[tieredSlug] ||
|
||||||
|
MODEL_PRICING[tieredDashedSlug] ||
|
||||||
MODEL_PRICING[canonicalSlug] ||
|
MODEL_PRICING[canonicalSlug] ||
|
||||||
MODEL_PRICING[dashedSlug];
|
MODEL_PRICING[dashedSlug];
|
||||||
|
|
||||||
if (explicitPricing) {
|
if (explicitPricing) {
|
||||||
return {
|
return {
|
||||||
rawModel: rawModelKey,
|
rawModel: rawModelKey,
|
||||||
@@ -173,7 +198,7 @@ export function resolveModelInfo(
|
|||||||
rawModel: rawModelKey,
|
rawModel: rawModelKey,
|
||||||
modelId,
|
modelId,
|
||||||
label: derivedDisplay,
|
label: derivedDisplay,
|
||||||
baseLabel: getBaseModelLabel(derivedDisplay),
|
baseLabel,
|
||||||
shortName: derivedDisplay,
|
shortName: derivedDisplay,
|
||||||
family: inferredFamily,
|
family: inferredFamily,
|
||||||
pricing: null,
|
pricing: null,
|
||||||
@@ -183,6 +208,7 @@ export function resolveModelInfo(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 计算单个步骤的 API 等效美元成本;若模型未定价(`pricing === null`)则返回 `null`。
|
* 计算单个步骤的 API 等效美元成本;若模型未定价(`pricing === null`)则返回 `null`。
|
||||||
|
* 对负数、NaN 或非有限数值统一安全钳制为 0。
|
||||||
*
|
*
|
||||||
* @param {{ inputTokens: number, cacheReadTokens: number, outputTokens: number }} step
|
* @param {{ inputTokens: number, cacheReadTokens: number, outputTokens: number }} step
|
||||||
* @param {{ input: number, cache: number, output: number } | null} pricing
|
* @param {{ input: number, cache: number, output: number } | null} pricing
|
||||||
@@ -190,8 +216,12 @@ export function resolveModelInfo(
|
|||||||
*/
|
*/
|
||||||
export function computeStepCost(step, pricing) {
|
export function computeStepCost(step, pricing) {
|
||||||
if (!pricing) return null;
|
if (!pricing) return null;
|
||||||
const inCost = (step.inputTokens / 1_000_000) * pricing.input;
|
const safeTok = (v) => {
|
||||||
const cacheCost = (step.cacheReadTokens / 1_000_000) * pricing.cache;
|
const n = Number(v);
|
||||||
const outCost = (step.outputTokens / 1_000_000) * pricing.output;
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||||
|
};
|
||||||
|
const inCost = (safeTok(step?.inputTokens) / 1_000_000) * pricing.input;
|
||||||
|
const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * pricing.cache;
|
||||||
|
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * pricing.output;
|
||||||
return inCost + cacheCost + outCost;
|
return inCost + cacheCost + outCost;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,15 +5,15 @@
|
|||||||
* 1. `syncCloudCatalog`:定期或手动从 GitHub 主干拉取最新 `pricing-catalog.json`,
|
* 1. `syncCloudCatalog`:定期或手动从 GitHub 主干拉取最新 `pricing-catalog.json`,
|
||||||
* 经 Schema 与可信域名白名单清洗后落盘至 `DATA_DIR/remote_pricing_cache.json` 并热更新内存价格字典;
|
* 经 Schema 与可信域名白名单清洗后落盘至 `DATA_DIR/remote_pricing_cache.json` 并热更新内存价格字典;
|
||||||
* 2. `performPluginUpdate` 严格执行以下防降级与防损坏门禁:
|
* 2. `performPluginUpdate` 严格执行以下防降级与防损坏门禁:
|
||||||
* - 开发仓库自动更新隔离:非 `.gemini/config/plugins/` 目录一律禁止后台自动更新(`dev_repo_auto_disabled`);
|
* - 开发仓库自动更新隔离:非 `.gemini/config/plugins/` 目录一律禁止后台自动更新(`dev_repo_auto_disabled`),
|
||||||
|
* 且若手动更新撞上正在进行的后台自动检查,等待自动检查结束后再执行手动更新;
|
||||||
* - 全量工作区干净度门禁(含未跟踪文件):执行 `git status --porcelain`(不带 `--untracked-files=no`),
|
* - 全量工作区干净度门禁(含未跟踪文件):执行 `git status --porcelain`(不带 `--untracked-files=no`),
|
||||||
* 只要存在任何已修改或未跟踪文件(`??`),立即终止(`dirty_worktree`),绝不执行 `git stash`;
|
* 只要存在任何已修改或未跟踪文件(`??`),立即终止(`dirty_worktree`),绝不执行 `git stash`;
|
||||||
* - 分支门禁:通过 `git rev-parse --abbrev-ref HEAD` 校验当前必须处于 `main` 分支(`not_on_main_branch`),防止污染特性分支或游离 HEAD;
|
* - 分支门禁:仅允许 `main` 或 `release/*` 发布分支执行快进更新(`not_on_main_branch`),防止污染特性分支或游离 HEAD;
|
||||||
* - 强制远端版本门禁(Git 通道):必须且只能从 `git show origin/main:plugin.json` 解析出合法 SemVer,
|
* - 强制远端版本门禁(Git 通道):必须且只能从 `git show origin/<branch>:plugin.json` 解析出合法 SemVer,
|
||||||
* 严禁回退使用缓存的 `cloudSyncState.latestPluginVersion`;仅当 `remoteVersion > previousVersion` 时才继续;
|
* 严禁回退使用缓存的 `cloudSyncState.latestPluginVersion`;仅当 `remoteVersion > previousVersion` 时才继续;
|
||||||
* - 提交拓扑与核心文件门禁:通过 `git merge-base --is-ancestor HEAD origin/main` 确认本地无分叉提交(`diverged_worktree`);
|
* - 提交拓扑与核心文件门禁:通过 `git merge-base --is-ancestor HEAD origin/<branch>` 确认本地无分叉提交(`diverged_worktree`);
|
||||||
* - ZIP 通道安全覆盖:下载前与解压后双重校验 `compareSemver > 0`,覆盖前对 `main.mjs`/`app.js` 执行 `node --check` 语法预检,
|
* - ZIP 通道安全覆盖与多余旧文件裁剪:覆盖前备份关键文件,覆盖后清理新版已删除的旧源码文件,异常回滚时同步删除残留新文件。
|
||||||
* 使用 `cpSync` 过滤器严格保护 `.git`/`.data`/`node_modules`,并在覆盖前备份关键文件以支持异常回滚。
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { execFile } from 'node:child_process';
|
import { execFile } from 'node:child_process';
|
||||||
@@ -52,7 +52,7 @@ import {
|
|||||||
* @param {object} [opts] `execFile` 附加选项
|
* @param {object} [opts] `execFile` 附加选项
|
||||||
* @returns {Promise<{stdout: string, stderr: string}>}
|
* @returns {Promise<{stdout: string, stderr: string}>}
|
||||||
*/
|
*/
|
||||||
export function runExecFile(cmd, args, opts = {}) {
|
function runExecFile(cmd, args, opts = {}) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if (typeof execFile !== 'function') {
|
if (typeof execFile !== 'function') {
|
||||||
reject(new Error('execFile unavailable in current environment'));
|
reject(new Error('execFile unavailable in current environment'));
|
||||||
@@ -71,12 +71,12 @@ export function runExecFile(cmd, args, opts = {}) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新完成后调度 Sidecar 进程平滑退出,让宿主进程监督器自动重启新代码。
|
* 更新完成后调度 Sidecar 进程平滑退出,让宿主进程监督器自动重启新代码。
|
||||||
* 在单元测试环境(`LS_ADDR === 'test.invalid'`)下自动跳过。
|
* 在单元测试环境(`!LS_ADDR || LS_ADDR === 'test.invalid'`)下自动跳过。
|
||||||
*
|
*
|
||||||
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
||||||
*/
|
*/
|
||||||
export function scheduleSidecarRestart(delayMs = 350) {
|
export function scheduleSidecarRestart(delayMs = 350) {
|
||||||
if (LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return;
|
if (!LS_ADDR || LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
try {
|
try {
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
@@ -92,7 +92,7 @@ export function scheduleSidecarRestart(delayMs = 350) {
|
|||||||
* @param {string} extractDir 解压目标目录
|
* @param {string} extractDir 解压目标目录
|
||||||
* @returns {string|null}
|
* @returns {string|null}
|
||||||
*/
|
*/
|
||||||
export function locateExtractedPluginRoot(extractDir) {
|
function locateExtractedPluginRoot(extractDir) {
|
||||||
if (existsSync(join(extractDir, 'plugin.json'))) return extractDir;
|
if (existsSync(join(extractDir, 'plugin.json'))) return extractDir;
|
||||||
try {
|
try {
|
||||||
for (const name of readdirSync(extractDir)) {
|
for (const name of readdirSync(extractDir)) {
|
||||||
@@ -108,7 +108,7 @@ export function locateExtractedPluginRoot(extractDir) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `cpSync` 安全过滤函数:严格禁止覆盖 `.git`、`.data`、`node_modules` 或临时更新目录。
|
* `cpSync` 安全过滤函数:严格禁止覆盖 `.git`、`.data`、`node_modules`、`plan` 或临时更新目录。
|
||||||
*
|
*
|
||||||
* @param {string} srcPath
|
* @param {string} srcPath
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
@@ -119,6 +119,7 @@ function isSafeCopyPath(srcPath) {
|
|||||||
name === '.git' ||
|
name === '.git' ||
|
||||||
name === '.data' ||
|
name === '.data' ||
|
||||||
name === 'node_modules' ||
|
name === 'node_modules' ||
|
||||||
|
name === 'plan' ||
|
||||||
name.startsWith('.update-staging-')
|
name.startsWith('.update-staging-')
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
@@ -126,13 +127,44 @@ function isSafeCopyPath(srcPath) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 递归清理 `targetDir` 中在 `referenceDir` 已不存在的多余文件/目录(保护 `.git`/`.data`/`node_modules`/`plan`)。
|
||||||
|
* 用于 ZIP 升级后清理旧版废弃源码文件,以及在覆盖中途异常回滚时清除半途写入的新增文件。
|
||||||
|
*
|
||||||
|
* @param {string} targetDir
|
||||||
|
* @param {string} referenceDir
|
||||||
|
*/
|
||||||
|
function pruneExtraneousFiles(targetDir, referenceDir) {
|
||||||
|
if (!existsSync(targetDir) || !existsSync(referenceDir)) return;
|
||||||
|
let names = [];
|
||||||
|
try {
|
||||||
|
names = readdirSync(targetDir);
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const name of names) {
|
||||||
|
const targetChild = join(targetDir, name);
|
||||||
|
if (!isSafeCopyPath(targetChild)) continue;
|
||||||
|
const refChild = join(referenceDir, name);
|
||||||
|
if (!existsSync(refChild)) {
|
||||||
|
try {
|
||||||
|
rmSync(targetChild, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// 忽略单项删除异常
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
pruneExtraneousFiles(targetChild, refChild);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在真实运行环境下对目标目录的核心 JS 文件执行 `node --check` 语法预检。
|
* 在真实运行环境下对目标目录的核心 JS 文件执行 `node --check` 语法预检。
|
||||||
*
|
*
|
||||||
* @param {string} rootDir 插件根目录或解压目录
|
* @param {string} rootDir 插件根目录或解压目录
|
||||||
*/
|
*/
|
||||||
async function verifyPluginJsSyntax(rootDir) {
|
async function verifyPluginJsSyntax(rootDir) {
|
||||||
if (LS_ADDR === 'test.invalid') return;
|
if (!LS_ADDR || LS_ADDR === 'test.invalid') return;
|
||||||
const nodeBin = process?.execPath || 'node';
|
const nodeBin = process?.execPath || 'node';
|
||||||
const filesToCheck = [
|
const filesToCheck = [
|
||||||
join(rootDir, 'sidecars', 'panel', 'main.mjs'),
|
join(rootDir, 'sidecars', 'panel', 'main.mjs'),
|
||||||
@@ -152,7 +184,18 @@ async function verifyPluginJsSyntax(rootDir) {
|
|||||||
* @returns {Promise<object>} 更新结果对象
|
* @returns {Promise<object>} 更新结果对象
|
||||||
*/
|
*/
|
||||||
export async function performPluginUpdate({ isAuto = false } = {}) {
|
export async function performPluginUpdate({ isAuto = false } = {}) {
|
||||||
if (pluginUpdateState.inFlight) return pluginUpdateState.inFlight;
|
if (pluginUpdateState.inFlight) {
|
||||||
|
if (isAuto || !pluginUpdateState.inFlightIsAuto) {
|
||||||
|
return pluginUpdateState.inFlight;
|
||||||
|
}
|
||||||
|
// 若用户点击手动更新时恰好有一轮后台自动更新检查正在运行,等待其收尾后再按手动模式继续执行
|
||||||
|
await pluginUpdateState.inFlight.catch(() => {});
|
||||||
|
if (pluginUpdateState.inFlight) {
|
||||||
|
return pluginUpdateState.inFlight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pluginUpdateState.inFlightIsAuto = Boolean(isAuto);
|
||||||
pluginUpdateState.inFlight = (async () => {
|
pluginUpdateState.inFlight = (async () => {
|
||||||
pluginUpdateState.isUpdating = true;
|
pluginUpdateState.isUpdating = true;
|
||||||
pluginUpdateState.lastError = null;
|
pluginUpdateState.lastError = null;
|
||||||
@@ -201,7 +244,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
return pluginUpdateState.lastResult;
|
return pluginUpdateState.lastResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 分支检查:仅当处于 main 分支时才允许拉取 origin/main,防止污染特性分支或游离 HEAD
|
// 2. 分支检查:仅当处于 main 或 release/* 发布分支时才允许快进拉取,防止污染特性分支或游离 HEAD
|
||||||
const branchRes = await runExecFile('git', [
|
const branchRes = await runExecFile('git', [
|
||||||
'-C',
|
'-C',
|
||||||
PLUGIN_ROOT,
|
PLUGIN_ROOT,
|
||||||
@@ -210,7 +253,11 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
'HEAD',
|
'HEAD',
|
||||||
]);
|
]);
|
||||||
const currentBranch = branchRes.stdout.trim();
|
const currentBranch = branchRes.stdout.trim();
|
||||||
if (currentBranch && currentBranch !== 'main') {
|
const isAllowedBranch =
|
||||||
|
!currentBranch ||
|
||||||
|
currentBranch === 'main' ||
|
||||||
|
/^release\/[0-9A-Za-z._-]+$/.test(currentBranch);
|
||||||
|
if (!isAllowedBranch) {
|
||||||
const msg = `当前分支为 ${currentBranch},已跳过更新`;
|
const msg = `当前分支为 ${currentBranch},已跳过更新`;
|
||||||
pluginUpdateState.lastError = isAuto ? null : msg;
|
pluginUpdateState.lastError = isAuto ? null : msg;
|
||||||
pluginUpdateState.lastResult = {
|
pluginUpdateState.lastResult = {
|
||||||
@@ -227,8 +274,11 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
return pluginUpdateState.lastResult;
|
return pluginUpdateState.lastResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 只读拉取远端分支引用,并严格从 origin/main:plugin.json 读取远端版本号(严禁回退使用缓存版本)
|
const targetBranch = currentBranch || 'main';
|
||||||
await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', 'main', '--tags']);
|
const remoteRef = `origin/${targetBranch}`;
|
||||||
|
|
||||||
|
// 3. 只读拉取远端分支引用,并严格从 origin/<branch>:plugin.json 读取远端版本号(严禁回退使用缓存版本)
|
||||||
|
await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', targetBranch, '--tags']);
|
||||||
|
|
||||||
let remoteVersion = '';
|
let remoteVersion = '';
|
||||||
try {
|
try {
|
||||||
@@ -236,7 +286,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
'-C',
|
'-C',
|
||||||
PLUGIN_ROOT,
|
PLUGIN_ROOT,
|
||||||
'show',
|
'show',
|
||||||
'origin/main:plugin.json',
|
`${remoteRef}:plugin.json`,
|
||||||
]);
|
]);
|
||||||
const parsedManifest = JSON.parse(showRes.stdout || '{}');
|
const parsedManifest = JSON.parse(showRes.stdout || '{}');
|
||||||
const rawVer =
|
const rawVer =
|
||||||
@@ -267,7 +317,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 提交拓扑预检:确保当前 HEAD 是 origin/main 的祖先提交(无本地超前或分叉提交)
|
// 5. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交)
|
||||||
try {
|
try {
|
||||||
await runExecFile('git', [
|
await runExecFile('git', [
|
||||||
'-C',
|
'-C',
|
||||||
@@ -275,7 +325,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
'merge-base',
|
'merge-base',
|
||||||
'--is-ancestor',
|
'--is-ancestor',
|
||||||
'HEAD',
|
'HEAD',
|
||||||
'origin/main',
|
remoteRef,
|
||||||
]);
|
]);
|
||||||
} catch {
|
} catch {
|
||||||
const msg = '本地分支存在未推送提交,已跳过更新';
|
const msg = '本地分支存在未推送提交,已跳过更新';
|
||||||
@@ -294,7 +344,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 6. 确认全部门禁通过后,执行快进合并并校验 JS 语法
|
// 6. 确认全部门禁通过后,执行快进合并并校验 JS 语法
|
||||||
await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', 'main']);
|
await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', targetBranch]);
|
||||||
await verifyPluginJsSyntax(PLUGIN_ROOT);
|
await verifyPluginJsSyntax(PLUGIN_ROOT);
|
||||||
rebuildActiveCatalog();
|
rebuildActiveCatalog();
|
||||||
const currentVersion = readInstalledPluginVersion();
|
const currentVersion = readInstalledPluginVersion();
|
||||||
@@ -406,7 +456,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
// 覆盖前先对解压目录执行 JS 语法预检,防止损坏代码覆盖现有安装
|
// 覆盖前先对解压目录执行 JS 语法预检,防止损坏代码覆盖现有安装
|
||||||
await verifyPluginJsSyntax(extractedRoot);
|
await verifyPluginJsSyntax(extractedRoot);
|
||||||
|
|
||||||
// 备份当前插件根目录关键文件,若覆盖途中异常则自动回滚
|
// 备份当前插件根目录关键文件,覆盖后清理已废弃旧文件;若覆盖途中异常则完整回滚并移除残留新文件
|
||||||
mkdirSync(backupDir, { recursive: true });
|
mkdirSync(backupDir, { recursive: true });
|
||||||
cpSync(PLUGIN_ROOT, backupDir, { recursive: true, force: true, filter: isSafeCopyPath });
|
cpSync(PLUGIN_ROOT, backupDir, { recursive: true, force: true, filter: isSafeCopyPath });
|
||||||
try {
|
try {
|
||||||
@@ -415,6 +465,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
force: true,
|
force: true,
|
||||||
filter: isSafeCopyPath,
|
filter: isSafeCopyPath,
|
||||||
});
|
});
|
||||||
|
pruneExtraneousFiles(PLUGIN_ROOT, extractedRoot);
|
||||||
} catch (copyErr) {
|
} catch (copyErr) {
|
||||||
try {
|
try {
|
||||||
cpSync(backupDir, PLUGIN_ROOT, {
|
cpSync(backupDir, PLUGIN_ROOT, {
|
||||||
@@ -422,6 +473,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
force: true,
|
force: true,
|
||||||
filter: isSafeCopyPath,
|
filter: isSafeCopyPath,
|
||||||
});
|
});
|
||||||
|
pruneExtraneousFiles(PLUGIN_ROOT, backupDir);
|
||||||
} catch {
|
} catch {
|
||||||
// 忽略回滚二级异常
|
// 忽略回滚二级异常
|
||||||
}
|
}
|
||||||
@@ -473,6 +525,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
|
|||||||
return result;
|
return result;
|
||||||
} finally {
|
} finally {
|
||||||
pluginUpdateState.isUpdating = false;
|
pluginUpdateState.isUpdating = false;
|
||||||
|
pluginUpdateState.inFlightIsAuto = false;
|
||||||
pluginUpdateState.inFlight = null;
|
pluginUpdateState.inFlight = null;
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 内置模型价格与占位符字典、Schema 安全清洗及三级目录合并(内置 + 本地 + 云端)。
|
* @fileoverview 模型价格与占位符目录加载、Schema 安全清洗及本地/云端目录合并。
|
||||||
*
|
*
|
||||||
* 价格口径与安全原则:
|
* 价格口径与安全原则:
|
||||||
* - 所有单价单位均为 USD / 1M Tokens(`input`: 未命中缓存输入, `cache`: 缓存读取, `output`: 输出与思考);
|
* - 所有单价单位均为 USD / 1M Tokens(`input`: 未命中缓存输入, `cache`: 缓存读取, `output`: 输出与思考);
|
||||||
* - 价格仅用于本地 API 等效成本折算,不代表订阅配额的扣减比例;
|
* - 价格仅用于本地 API 等效成本折算,不代表订阅配额的扣减比例;
|
||||||
|
* - 离线基准统一从随包发布的 `pricing-catalog.json` 读取,避免在 JS 源码中重复维护双份硬编码字典;
|
||||||
* - 未收录或身份未知的模型严格保持未定价状态(`null`),绝不借用其他模型价格,也绝不允许 `null`/`0` 伪价格混入;
|
* - 未收录或身份未知的模型严格保持未定价状态(`null`),绝不借用其他模型价格,也绝不允许 `null`/`0` 伪价格混入;
|
||||||
* - 版本号与更新包 URL 均经过严格格式与可信 GitHub 域名白名单校验。
|
* - 版本号(遵循 SemVer 2.0)与更新包 URL 均经过严格格式与可信 GitHub 域名白名单校验。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync } from 'node:fs';
|
||||||
@@ -24,194 +25,23 @@ import {
|
|||||||
pluginUpdateState,
|
pluginUpdateState,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
|
|
||||||
/**
|
|
||||||
* 代码内置兜底模型价格字典(当本地与云端目录均不可用时的离线基准)。
|
|
||||||
*/
|
|
||||||
export const BUILTIN_MODEL_PRICING = {
|
|
||||||
// Gemini 4 (Carbon & Argon) & 3.x & 2.5 官方目录价格 (USD / 1M tokens)
|
|
||||||
'gemini-4-carbon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4-high', family: 'Gemini' },
|
|
||||||
'gemini-4-carbon-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4', family: 'Gemini' },
|
|
||||||
'gemini-4-carbon-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4-low', family: 'Gemini' },
|
|
||||||
'gemini-4-carbon': { input: 2.00, cache: 0.10, output: 10.0, short: 'carbon-4', family: 'Gemini' },
|
|
||||||
'gemini-4-argon-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'argon-4-high', family: 'Gemini' },
|
|
||||||
'gemini-4-argon-medium': { input: 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-tiered': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.8', 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-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7-high', family: 'Gemini' },
|
|
||||||
'gemini-3.7-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', family: 'Gemini' },
|
|
||||||
'gemini-3.7-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.7-low', family: 'Gemini' },
|
|
||||||
'gemini-3.7-flash-tiered': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.7', 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-high': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6-high', family: 'Gemini' },
|
|
||||||
'gemini-3.6-flash-medium': { input: 0.75, cache: 0.075, output: 3.75, short: 'flash-3.6', family: 'Gemini' },
|
|
||||||
'gemini-3.6-flash-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.6-low', 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-high': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5-high', family: 'Gemini' },
|
|
||||||
'gemini-3.5-flash-medium': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5', family: 'Gemini' },
|
|
||||||
'gemini-3.5-flash-low': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5-low', family: 'Gemini' },
|
|
||||||
'gemini-3.5-flash-extra-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-xlow', 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-high': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-high', family: 'Gemini' },
|
|
||||||
'gemini-3.1-pro-low': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' },
|
|
||||||
'gemini-3.1-pro-low-thinking': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' },
|
|
||||||
'gemini-3.1-pro-preview': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' },
|
|
||||||
'gemini-3.1-pro-preview-customtools': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', 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-preview': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' },
|
|
||||||
'gemini-3.1-flash-lite': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' },
|
|
||||||
'gemini-for-google-3.1-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1', family: 'Gemini' },
|
|
||||||
'gemini-3.1-flash-image': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1-img', family: 'Gemini' },
|
|
||||||
'gemini-3-flash-preview': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' },
|
|
||||||
'gemini-3-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' },
|
|
||||||
'gemini-3-pro-image': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3-img', 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-2-max': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-max', family: 'Claude' },
|
|
||||||
'claude-fable-5-2-high': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-high', family: 'Claude' },
|
|
||||||
'claude-fable-5-2-medium': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' },
|
|
||||||
'claude-fable-5-2-low': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-low', family: 'Claude' },
|
|
||||||
'claude-fable-5-2': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' },
|
|
||||||
'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-max': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-max', family: 'Claude' },
|
|
||||||
'claude-opus-5-5-high': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-high', family: 'Claude' },
|
|
||||||
'claude-opus-5-5-medium': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' },
|
|
||||||
'claude-opus-5-5-low': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-low', 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-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', 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-max': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-max', family: 'Claude' },
|
|
||||||
'claude-sonnet-5-5-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-high', family: 'Claude' },
|
|
||||||
'claude-sonnet-5-5-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' },
|
|
||||||
'claude-sonnet-5-5-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-low', 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-thinking': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', 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.1-terra': { input: 1.00, cache: 0.05, output: 5.00, short: 'gpt-6.1-terra', 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 = {
|
|
||||||
// Gemini 4 Argon
|
|
||||||
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)' },
|
|
||||||
// Gemini 3.8 Flash
|
|
||||||
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)' },
|
|
||||||
// Gemini 3.7 Flash
|
|
||||||
MODEL_PLACEHOLDER_M298: { modelId: 'gemini-3.7-flash-high', label: 'Gemini 3.7 Flash (High)' },
|
|
||||||
MODEL_PLACEHOLDER_M299: { modelId: 'gemini-3.7-flash-medium', label: 'Gemini 3.7 Flash (Medium)' },
|
|
||||||
MODEL_PLACEHOLDER_M300: { modelId: 'gemini-3.7-flash-low', label: 'Gemini 3.7 Flash (Low)' },
|
|
||||||
MODEL_PLACEHOLDER_M301: { modelId: 'gemini-3.7-flash-tiered', label: 'Gemini 3.7 Flash (Tiered)' },
|
|
||||||
// Gemini 3.6 Flash
|
|
||||||
MODEL_PLACEHOLDER_M71: { modelId: 'gemini-3.6-flash-high', label: 'Gemini 3.6 Flash (High)' },
|
|
||||||
MODEL_PLACEHOLDER_M72: { modelId: 'gemini-3.6-flash-medium', label: 'Gemini 3.6 Flash (Medium)' },
|
|
||||||
MODEL_PLACEHOLDER_M73: { modelId: 'gemini-3.6-flash-low', label: 'Gemini 3.6 Flash (Low)' },
|
|
||||||
MODEL_PLACEHOLDER_M196: { modelId: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash' },
|
|
||||||
// Gemini 3.5 Flash & Lite
|
|
||||||
MODEL_PLACEHOLDER_M149: { modelId: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash (High)' },
|
|
||||||
MODEL_PLACEHOLDER_M20: { modelId: 'gemini-3.5-flash-low', label: 'Gemini 3.5 Flash' },
|
|
||||||
MODEL_PLACEHOLDER_M187: { modelId: 'gemini-3.5-flash-extra-low', label: 'Gemini 3.5 Flash (Extra Low)' },
|
|
||||||
MODEL_PLACEHOLDER_M198: { modelId: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash Lite' },
|
|
||||||
// Gemini 3.1 & 3.0
|
|
||||||
MODEL_PLACEHOLDER_M37: { modelId: 'gemini-3.1-pro-high', label: 'Gemini 3.1 Pro (High)' },
|
|
||||||
MODEL_PLACEHOLDER_M36: { modelId: 'gemini-3.1-pro-low', label: 'Gemini 3.1 Pro (Low)' },
|
|
||||||
MODEL_PLACEHOLDER_M50: { modelId: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' },
|
|
||||||
MODEL_PLACEHOLDER_M59: { modelId: 'gemini-for-google-3.1-flash', label: 'Gemini for Google 3.1 Flash' },
|
|
||||||
MODEL_PLACEHOLDER_M21: { modelId: 'gemini-3.1-flash-image', label: 'Gemini 3.1 Flash Image' },
|
|
||||||
MODEL_PLACEHOLDER_M18: { modelId: 'gemini-3-flash', label: 'Gemini 3 Flash' },
|
|
||||||
MODEL_PLACEHOLDER_M9: { modelId: 'gemini-3-pro-image', label: 'Gemini 3 Pro Image' },
|
|
||||||
// Gemini 2.5
|
|
||||||
MODEL_GOOGLE_GEMINI_2_5_PRO: { modelId: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
|
|
||||||
MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
|
|
||||||
MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (Thinking)' },
|
|
||||||
MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' },
|
|
||||||
// Claude 5.5 / 4.8 / 4.6 / 4.5
|
|
||||||
MODEL_PLACEHOLDER_M406: { modelId: 'claude-opus-5-5-max', label: 'Claude Opus 5.5 (Max)' },
|
|
||||||
MODEL_PLACEHOLDER_M402: { modelId: 'claude-opus-5-5-high', label: 'Claude Opus 5.5 (High)' },
|
|
||||||
MODEL_PLACEHOLDER_M401: { modelId: 'claude-opus-5-5-medium', label: 'Claude Opus 5.5 (Medium)' },
|
|
||||||
MODEL_PLACEHOLDER_M400: { modelId: 'claude-opus-5-5-low', label: 'Claude Opus 5.5 (Low)' },
|
|
||||||
MODEL_PLACEHOLDER_M368: { modelId: 'claude-opus-5-5', label: 'Claude Opus 5.5' },
|
|
||||||
MODEL_PLACEHOLDER_M407: { modelId: 'claude-sonnet-5-5-max', label: 'Claude Sonnet 5.5 (Max)' },
|
|
||||||
MODEL_PLACEHOLDER_M405: { modelId: 'claude-sonnet-5-5-high', label: 'Claude Sonnet 5.5 (High)' },
|
|
||||||
MODEL_PLACEHOLDER_M404: { modelId: 'claude-sonnet-5-5-medium', label: 'Claude Sonnet 5.5 (Medium)' },
|
|
||||||
MODEL_PLACEHOLDER_M403: { modelId: 'claude-sonnet-5-5-low', label: 'Claude Sonnet 5.5 (Low)' },
|
|
||||||
MODEL_PLACEHOLDER_M254: { modelId: 'claude-opus-4-8', label: 'Claude Opus 4.8' },
|
|
||||||
MODEL_PLACEHOLDER_M26: { modelId: 'claude-opus-4-6-thinking', label: 'Claude Opus 4.6 (Thinking)' },
|
|
||||||
MODEL_PLACEHOLDER_M35: { modelId: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6 (Thinking)' },
|
|
||||||
MODEL_PLACEHOLDER_M12: { modelId: 'claude-opus-4-5-thinking', label: 'Claude Opus 4.5 (Thinking)' },
|
|
||||||
MODEL_PLACEHOLDER_M11: { modelId: 'claude-opus-4-5', label: 'Claude Opus 4.5' },
|
|
||||||
MODEL_CLAUDE_4_5_SONNET_THINKING: { modelId: 'claude-sonnet-4-5-thinking', label: 'Claude Sonnet 4.5 (Thinking)' },
|
|
||||||
MODEL_CLAUDE_4_5_SONNET: { modelId: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' },
|
|
||||||
// OpenAI
|
|
||||||
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 MODEL_PRICING = {};
|
||||||
export const PLACEHOLDER_MAP = { ...BUILTIN_PLACEHOLDER_MAP };
|
export const PLACEHOLDER_MAP = {};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 校验字符串是否为合法的 `X.Y.Z` 语义化版本号格式。
|
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
|
||||||
*
|
*
|
||||||
* @param {*} v
|
* @param {*} v
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function isValidSemver(v) {
|
export function isValidSemver(v) {
|
||||||
return typeof v === 'string' && /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.trim());
|
return (
|
||||||
|
typeof v === 'string' &&
|
||||||
|
/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(v.trim())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor';
|
const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor';
|
||||||
@@ -223,7 +53,7 @@ const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor';
|
|||||||
* @param {string} fallbackUrl
|
* @param {string} fallbackUrl
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) {
|
function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) {
|
||||||
if (typeof rawUrl !== 'string' || !rawUrl.trim()) return fallbackUrl;
|
if (typeof rawUrl !== 'string' || !rawUrl.trim()) return fallbackUrl;
|
||||||
try {
|
try {
|
||||||
const parsed = new URL(rawUrl.trim());
|
const parsed = new URL(rawUrl.trim());
|
||||||
@@ -247,7 +77,7 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 比较两个语义化版本号(如 `'1.5.0'` vs `'1.4.0'`,支持 `-beta.1` 预发布后缀比较)。
|
* 按 SemVer 2.0 规范(§10 忽略 `+build` 元数据,§11.4 按 ASCII 码序与纯数字段逐级比较预发布标签)比较两个版本号。
|
||||||
*
|
*
|
||||||
* @param {string} a
|
* @param {string} a
|
||||||
* @param {string} b
|
* @param {string} b
|
||||||
@@ -256,7 +86,10 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) {
|
|||||||
export function compareSemver(a, b) {
|
export function compareSemver(a, b) {
|
||||||
if (!isValidSemver(a) || !isValidSemver(b)) return 0;
|
if (!isValidSemver(a) || !isValidSemver(b)) return 0;
|
||||||
const parse = (v) => {
|
const parse = (v) => {
|
||||||
const cleaned = String(v || '').trim().replace(/^v/i, '');
|
const cleaned = String(v || '')
|
||||||
|
.trim()
|
||||||
|
.replace(/^v/i, '')
|
||||||
|
.replace(/\+.*$/, '');
|
||||||
const dashIdx = cleaned.indexOf('-');
|
const dashIdx = cleaned.indexOf('-');
|
||||||
const coreStr = dashIdx >= 0 ? cleaned.slice(0, dashIdx) : cleaned;
|
const coreStr = dashIdx >= 0 ? cleaned.slice(0, dashIdx) : cleaned;
|
||||||
const preStr = dashIdx >= 0 ? cleaned.slice(dashIdx + 1) : '';
|
const preStr = dashIdx >= 0 ? cleaned.slice(dashIdx + 1) : '';
|
||||||
@@ -278,7 +111,30 @@ export function compareSemver(a, b) {
|
|||||||
if (!pa.pre && !pb.pre) return 0;
|
if (!pa.pre && !pb.pre) return 0;
|
||||||
if (!pa.pre && pb.pre) return 1;
|
if (!pa.pre && pb.pre) return 1;
|
||||||
if (pa.pre && !pb.pre) return -1;
|
if (pa.pre && !pb.pre) return -1;
|
||||||
return pa.pre.localeCompare(pb.pre, undefined, { numeric: true });
|
|
||||||
|
const idsA = pa.pre.split('.');
|
||||||
|
const idsB = pb.pre.split('.');
|
||||||
|
const minLen = Math.min(idsA.length, idsB.length);
|
||||||
|
for (let i = 0; i < minLen; i++) {
|
||||||
|
const idA = idsA[i];
|
||||||
|
const idB = idsB[i];
|
||||||
|
if (idA === idB) continue;
|
||||||
|
const numA = /^\d+$/.test(idA);
|
||||||
|
const numB = /^\d+$/.test(idB);
|
||||||
|
if (numA && numB) {
|
||||||
|
const bigA = BigInt(idA);
|
||||||
|
const bigB = BigInt(idB);
|
||||||
|
if (bigA !== bigB) return bigA > bigB ? 1 : -1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// SemVer 2.0 §11.4.1:纯数字标识符的优先级始终低于含字母标识符
|
||||||
|
if (numA && !numB) return -1;
|
||||||
|
if (!numA && numB) return 1;
|
||||||
|
// SemVer 2.0 §11.4.2:含字母标识符按 ASCII 字节序比较
|
||||||
|
return idA < idB ? -1 : 1;
|
||||||
|
}
|
||||||
|
if (idsA.length === idsB.length) return 0;
|
||||||
|
return idsA.length > idsB.length ? 1 : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -289,7 +145,17 @@ export function compareSemver(a, b) {
|
|||||||
export function readInstalledPluginVersion() {
|
export function readInstalledPluginVersion() {
|
||||||
const manifest = loadJson(PLUGIN_MANIFEST_FILE, null);
|
const manifest = loadJson(PLUGIN_MANIFEST_FILE, null);
|
||||||
const ver = typeof manifest?.version === 'string' ? manifest.version.trim() : '';
|
const ver = typeof manifest?.version === 'string' ? manifest.version.trim() : '';
|
||||||
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.2';
|
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.3';
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeModelFamily(rawFamily) {
|
||||||
|
const f = String(rawFamily || '').trim();
|
||||||
|
const lower = f.toLowerCase();
|
||||||
|
if (lower === 'gemini' || lower === 'google') return 'Gemini';
|
||||||
|
if (lower === 'claude' || lower === 'anthropic') return 'Claude';
|
||||||
|
if (lower === 'gpt' || lower === 'openai') return 'GPT';
|
||||||
|
if (lower === 'other') return 'Other';
|
||||||
|
return f;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -347,7 +213,7 @@ export function sanitizeCatalogPayload(raw) {
|
|||||||
cache: v.cache,
|
cache: v.cache,
|
||||||
output: v.output,
|
output: v.output,
|
||||||
short: String(v.short).trim(),
|
short: String(v.short).trim(),
|
||||||
family: String(v.family).trim(),
|
family: normalizeModelFamily(v.family),
|
||||||
};
|
};
|
||||||
validPricingCount++;
|
validPricingCount++;
|
||||||
}
|
}
|
||||||
@@ -376,6 +242,10 @@ export function sanitizeCatalogPayload(raw) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const explicitReleaseUrl = sanitizeTrustedGithubUrl(raw.releaseUrl, '');
|
||||||
|
const explicitDownloadUrl = sanitizeTrustedGithubUrl(raw.downloadUrl, '');
|
||||||
|
const explicitArchiveUrl = sanitizeTrustedGithubUrl(raw.archiveFallbackUrl, '');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
schemaVersion: Number(raw.schemaVersion || 1),
|
schemaVersion: Number(raw.schemaVersion || 1),
|
||||||
catalogVersion:
|
catalogVersion:
|
||||||
@@ -385,12 +255,12 @@ export function sanitizeCatalogPayload(raw) {
|
|||||||
updatedAt:
|
updatedAt:
|
||||||
typeof raw.updatedAt === 'string' && raw.updatedAt.trim() ? raw.updatedAt.trim() : null,
|
typeof raw.updatedAt === 'string' && raw.updatedAt.trim() ? raw.updatedAt.trim() : null,
|
||||||
latestPluginVersion,
|
latestPluginVersion,
|
||||||
releaseUrl: sanitizeTrustedGithubUrl(raw.releaseUrl, DEFAULT_RELEASE_URL),
|
releaseUrl: explicitReleaseUrl || DEFAULT_RELEASE_URL,
|
||||||
downloadUrl: sanitizeTrustedGithubUrl(raw.downloadUrl, DEFAULT_DOWNLOAD_URL),
|
downloadUrl: explicitDownloadUrl || DEFAULT_DOWNLOAD_URL,
|
||||||
archiveFallbackUrl: sanitizeTrustedGithubUrl(
|
archiveFallbackUrl: explicitArchiveUrl || DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||||
raw.archiveFallbackUrl,
|
hasReleaseUrl: Boolean(explicitReleaseUrl),
|
||||||
DEFAULT_ARCHIVE_FALLBACK_URL
|
hasDownloadUrl: Boolean(explicitDownloadUrl),
|
||||||
),
|
hasArchiveFallbackUrl: Boolean(explicitArchiveUrl),
|
||||||
fetchedAtMs: Number(raw.fetchedAtMs || 0),
|
fetchedAtMs: Number(raw.fetchedAtMs || 0),
|
||||||
sourceUrl: typeof raw.sourceUrl === 'string' ? raw.sourceUrl : '',
|
sourceUrl: typeof raw.sourceUrl === 'string' ? raw.sourceUrl : '',
|
||||||
pricing,
|
pricing,
|
||||||
@@ -399,7 +269,7 @@ export function sanitizeCatalogPayload(raw) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按「内置保底 -> 本地目录 -> 云端缓存(按 `updatedAt` 新旧自动裁决优先级)」三级合并重建内存价格表。
|
* 按「随包本地目录 -> 云端缓存(按 `updatedAt` 新旧自动裁决优先级)」合并重建内存价格表。
|
||||||
*/
|
*/
|
||||||
export function rebuildActiveCatalog() {
|
export function rebuildActiveCatalog() {
|
||||||
const localRaw = loadJson(LOCAL_CATALOG_FILE, null);
|
const localRaw = loadJson(LOCAL_CATALOG_FILE, null);
|
||||||
@@ -423,8 +293,8 @@ export function rebuildActiveCatalog() {
|
|||||||
layers.push({ kind: 'local', cat: localCat });
|
layers.push({ kind: 'local', cat: localCat });
|
||||||
}
|
}
|
||||||
|
|
||||||
const nextPricing = { ...BUILTIN_MODEL_PRICING };
|
const nextPricing = {};
|
||||||
const nextPlaceholders = { ...BUILTIN_PLACEHOLDER_MAP };
|
const nextPlaceholders = {};
|
||||||
let activeSource = 'builtin';
|
let activeSource = 'builtin';
|
||||||
let catalogVersion = 'builtin';
|
let catalogVersion = 'builtin';
|
||||||
let updatedAt = null;
|
let updatedAt = null;
|
||||||
@@ -437,7 +307,9 @@ export function rebuildActiveCatalog() {
|
|||||||
for (const { kind, cat } of layers) {
|
for (const { kind, cat } of layers) {
|
||||||
Object.assign(nextPricing, cat.pricing);
|
Object.assign(nextPricing, cat.pricing);
|
||||||
Object.assign(nextPlaceholders, cat.placeholders);
|
Object.assign(nextPlaceholders, cat.placeholders);
|
||||||
|
if (kind === 'remote' || cat.catalogVersion || cat.updatedAt) {
|
||||||
activeSource = kind;
|
activeSource = kind;
|
||||||
|
}
|
||||||
if (cat.catalogVersion) catalogVersion = cat.catalogVersion;
|
if (cat.catalogVersion) catalogVersion = cat.catalogVersion;
|
||||||
if (cat.updatedAt) updatedAt = cat.updatedAt;
|
if (cat.updatedAt) updatedAt = cat.updatedAt;
|
||||||
if (cat.latestPluginVersion) {
|
if (cat.latestPluginVersion) {
|
||||||
@@ -447,9 +319,9 @@ export function rebuildActiveCatalog() {
|
|||||||
? cat.latestPluginVersion
|
? cat.latestPluginVersion
|
||||||
: installedVersion;
|
: installedVersion;
|
||||||
}
|
}
|
||||||
if (cat.releaseUrl) releaseUrl = cat.releaseUrl;
|
if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl;
|
||||||
if (cat.downloadUrl) downloadUrl = cat.downloadUrl;
|
if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl;
|
||||||
if (cat.archiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl;
|
if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k];
|
for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k];
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 官方配额桶归一化、周期窗口识别与多模型池(Gemini / Argon / Claude & GPT)构建。
|
* @fileoverview 官方配额桶归一化、周期窗口识别与多模型池(Gemini / Argon / Carbon / Claude & GPT)构建。
|
||||||
*
|
*
|
||||||
* 处理所有已知的 Antigravity 服务端配额形态:
|
* 处理所有已知的 Antigravity 服务端配额形态:
|
||||||
* - Google AI Ultra:Argon 与 Flash 共享同一个 Gemini Models 配额池;
|
* - Google AI Ultra:Argon / Carbon 与 Flash 共享同一个 Gemini Models 配额池;
|
||||||
* - Google AI Pro(形态 1):`RetrieveUserQuotaSummary` 返回独立的 `Gemini 4 Argon` 组;
|
* - Google AI Pro(形态 1):`RetrieveUserQuotaSummary` 返回独立的 `Gemini 4 Argon` / `Gemini 4 Carbon` 组;
|
||||||
* - Google AI Pro(形态 2):`Gemini Models` 组内嵌套独立的 `argon-weekly` 桶;
|
* - Google AI Pro(形态 2):`Gemini Models` 组内嵌套独立的 `argon-weekly` / `carbon-weekly` 桶;
|
||||||
* - Google AI Pro(形态 3):`GetUserStatus` 的 `clientModelConfigs.quotaInfo` 为 Argon 报告了与标准 Gemini 不同的独立剩余比例;
|
* - Google AI Pro(形态 3):`GetUserStatus` 的 `clientModelConfigs.quotaInfo` 为 Argon / Carbon 报告了与标准 Gemini 不同的独立剩余比例;
|
||||||
* - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略但存在有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。
|
* - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略且存在尚未过期的有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
import { parseIsoMs } from '../speed-metrics.mjs';
|
||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
* 将原始配额对象(来自 `RetrieveUserQuotaSummary` 桶或 `clientModelConfigs.quotaInfo`)归一化为百分比结构。
|
* 将原始配额对象(来自 `RetrieveUserQuotaSummary` 桶或 `clientModelConfigs.quotaInfo`)归一化为百分比结构。
|
||||||
*
|
*
|
||||||
* @param {object} rawObj
|
* @param {object} rawObj
|
||||||
|
* @param {number} [nowMs=Date.now()]
|
||||||
* @returns {{
|
* @returns {{
|
||||||
* remainingFraction: number,
|
* remainingFraction: number,
|
||||||
* remainingPct: number,
|
* remainingPct: number,
|
||||||
@@ -29,7 +30,7 @@ import {
|
|||||||
* description: string
|
* description: string
|
||||||
* } | null}
|
* } | null}
|
||||||
*/
|
*/
|
||||||
export function normalizeQuotaFraction(rawObj) {
|
function normalizeQuotaFraction(rawObj, nowMs = Date.now()) {
|
||||||
if (!rawObj || typeof rawObj !== 'object') return null;
|
if (!rawObj || typeof rawObj !== 'object') return null;
|
||||||
let remFrac = null;
|
let remFrac = null;
|
||||||
if (rawObj.disabled === true) {
|
if (rawObj.disabled === true) {
|
||||||
@@ -41,9 +42,12 @@ export function normalizeQuotaFraction(rawObj) {
|
|||||||
) {
|
) {
|
||||||
remFrac = Math.max(0, Math.min(1, Number(rawObj.remainingFraction)));
|
remFrac = Math.max(0, Math.min(1, Number(rawObj.remainingFraction)));
|
||||||
} else if (typeof rawObj.resetTime === 'string' && rawObj.resetTime.trim().length > 0) {
|
} else if (typeof rawObj.resetTime === 'string' && rawObj.resetTime.trim().length > 0) {
|
||||||
// Proto3 在配额完全耗尽(0.0)时会省略默认数值字段,此时凭有效 resetTime 判定为剩余 0
|
// Proto3 在配额完全耗尽(0.0)时会省略默认数值字段;仅当 resetTime 是未来有效时间戳时才判定为 0% 剩余
|
||||||
|
const resetMs = parseIsoMs(rawObj.resetTime);
|
||||||
|
if (resetMs > nowMs) {
|
||||||
remFrac = 0;
|
remFrac = 0;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (remFrac === null) return null;
|
if (remFrac === null) return null;
|
||||||
const usedFrac = Math.max(0, Math.min(1, 1 - remFrac));
|
const usedFrac = Math.max(0, Math.min(1, 1 - remFrac));
|
||||||
return {
|
return {
|
||||||
@@ -60,11 +64,11 @@ export function normalizeQuotaFraction(rawObj) {
|
|||||||
* 识别官方配额桶所属的时间窗口类型(`'5h'` 或 `'weekly'`)。
|
* 识别官方配额桶所属的时间窗口类型(`'5h'` 或 `'weekly'`)。
|
||||||
*
|
*
|
||||||
* @param {object} bucket
|
* @param {object} bucket
|
||||||
* @param {number} [groupBucketCount=1] 所属分组内的桶总数
|
* @param {number} [_groupBucketCount=1] 所属分组内的桶总数(保留参数签名兼容)
|
||||||
* @param {number} [nowMs=Date.now()] 当前毫秒时间戳
|
* @param {number} [nowMs=Date.now()] 当前毫秒时间戳
|
||||||
* @returns {'5h'|'weekly'}
|
* @returns {'5h'|'weekly'}
|
||||||
*/
|
*/
|
||||||
export function classifyOfficialBucketWindow(bucket, groupBucketCount = 1, nowMs = Date.now()) {
|
function classifyOfficialBucketWindow(bucket, _groupBucketCount = 1, nowMs = Date.now()) {
|
||||||
const w = String(bucket?.window || '')
|
const w = String(bucket?.window || '')
|
||||||
.trim()
|
.trim()
|
||||||
.toLowerCase();
|
.toLowerCase();
|
||||||
@@ -80,19 +84,23 @@ export function classifyOfficialBucketWindow(bucket, groupBucketCount = 1, nowMs
|
|||||||
return 'weekly';
|
return 'weekly';
|
||||||
}
|
}
|
||||||
const resetMs = parseIsoMs(bucket?.resetTime);
|
const resetMs = parseIsoMs(bucket?.resetTime);
|
||||||
if (resetMs > nowMs + 6 * 3600 * 1000 || groupBucketCount === 1) {
|
if (resetMs > 0 && resetMs <= nowMs + 6 * 3600 * 1000) {
|
||||||
return 'weekly';
|
|
||||||
}
|
|
||||||
return '5h';
|
return '5h';
|
||||||
}
|
}
|
||||||
|
return 'weekly';
|
||||||
|
}
|
||||||
|
|
||||||
|
const THIRD_PARTY_POOL_RE =
|
||||||
|
/3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Claude & GPT`)。
|
* 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Carbon` / `Claude & GPT`)。
|
||||||
|
* 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。
|
||||||
*
|
*
|
||||||
* @param {{ groupName?: string, groupDesc?: string, bucketId?: string, bucketName?: string }} params
|
* @param {{ groupName?: string, groupDesc?: string, bucketId?: string, bucketName?: string }} params
|
||||||
* @returns {{ poolKey: string, poolLabel: string, poolName: string }}
|
* @returns {{ poolKey: string, poolLabel: string, poolName: string }}
|
||||||
*/
|
*/
|
||||||
export function classifyQuotaPoolIdentity({
|
function classifyQuotaPoolIdentity({
|
||||||
groupName = '',
|
groupName = '',
|
||||||
groupDesc = '',
|
groupDesc = '',
|
||||||
bucketId = '',
|
bucketId = '',
|
||||||
@@ -102,6 +110,8 @@ export function classifyQuotaPoolIdentity({
|
|||||||
const bName = String(bucketName || '');
|
const bName = String(bucketName || '');
|
||||||
const gName = String(groupName || '');
|
const gName = String(groupName || '');
|
||||||
const gDesc = String(groupDesc || '');
|
const gDesc = String(groupDesc || '');
|
||||||
|
const primaryText = `${bId} ${bName} ${gName}`;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
/carbon/i.test(bId) ||
|
/carbon/i.test(bId) ||
|
||||||
/carbon/i.test(bName) ||
|
/carbon/i.test(bName) ||
|
||||||
@@ -130,20 +140,23 @@ export function classifyQuotaPoolIdentity({
|
|||||||
poolName: 'Gemini 4 Argon 模型池',
|
poolName: 'Gemini 4 Argon 模型池',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (/gemini/i.test(`${bId} ${bName} ${gName} ${gDesc}`)) {
|
if (
|
||||||
return {
|
THIRD_PARTY_POOL_RE.test(primaryText) ||
|
||||||
poolKey: 'Gemini',
|
(!/gemini/i.test(primaryText) && THIRD_PARTY_POOL_RE.test(gDesc))
|
||||||
poolLabel: 'Gemini',
|
) {
|
||||||
poolName: 'Gemini 模型池',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (/3p|claude|fable|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) {
|
|
||||||
return {
|
return {
|
||||||
poolKey: 'Claude & GPT',
|
poolKey: 'Claude & GPT',
|
||||||
poolLabel: 'Claude & GPT',
|
poolLabel: 'Claude & GPT',
|
||||||
poolName: 'Claude & GPT 模型池',
|
poolName: 'Claude & GPT 模型池',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if (/gemini/i.test(`${primaryText} ${gDesc}`)) {
|
||||||
|
return {
|
||||||
|
poolKey: 'Gemini',
|
||||||
|
poolLabel: 'Gemini',
|
||||||
|
poolName: 'Gemini 模型池',
|
||||||
|
};
|
||||||
|
}
|
||||||
const cleanLabel = (gName || bId || 'Other').trim();
|
const cleanLabel = (gName || bId || 'Other').trim();
|
||||||
return {
|
return {
|
||||||
poolKey: cleanLabel,
|
poolKey: cleanLabel,
|
||||||
@@ -159,7 +172,7 @@ export function classifyQuotaPoolIdentity({
|
|||||||
* @param {ReturnType<typeof normalizeQuotaFraction>} b
|
* @param {ReturnType<typeof normalizeQuotaFraction>} b
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function quotaFractionsMatch(a, b) {
|
function quotaFractionsMatch(a, b) {
|
||||||
if (!a || !b) return false;
|
if (!a || !b) return false;
|
||||||
if (Math.abs(a.remainingFraction - b.remainingFraction) > 0.015) return false;
|
if (Math.abs(a.remainingFraction - b.remainingFraction) > 0.015) return false;
|
||||||
if (a.resetTime && b.resetTime) {
|
if (a.resetTime && b.resetTime) {
|
||||||
@@ -213,7 +226,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
|||||||
for (const grp of rawGroups) {
|
for (const grp of rawGroups) {
|
||||||
const grpBuckets = Array.isArray(grp?.buckets) ? grp.buckets : [];
|
const grpBuckets = Array.isArray(grp?.buckets) ? grp.buckets : [];
|
||||||
for (const b of grpBuckets) {
|
for (const b of grpBuckets) {
|
||||||
const norm = normalizeQuotaFraction(b);
|
const norm = normalizeQuotaFraction(b, nowForQuotaMs);
|
||||||
if (!norm) continue;
|
if (!norm) continue;
|
||||||
const ident = classifyQuotaPoolIdentity({
|
const ident = classifyQuotaPoolIdentity({
|
||||||
groupName: grp?.displayName,
|
groupName: grp?.displayName,
|
||||||
@@ -229,17 +242,27 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
|||||||
window: win,
|
window: win,
|
||||||
};
|
};
|
||||||
const builder = ensurePoolBuilder(ident);
|
const builder = ensurePoolBuilder(ident);
|
||||||
if (win === '5h' && !builder.bucket5h) {
|
if (win === '5h') {
|
||||||
|
if (!builder.bucket5h) {
|
||||||
builder.bucket5h = entry;
|
builder.bucket5h = entry;
|
||||||
} else if (win === 'weekly' && !builder.bucketWeekly) {
|
} else if (!builder.bucketWeekly) {
|
||||||
builder.bucketWeekly = entry;
|
// 当同池两个无显式标签桶都处于 <6h 临近重置期时,按重置时间早晚区分 5h 与周限桶
|
||||||
} else if (win !== '5h' && !builder.bucketWeekly) {
|
const prevResetMs = parseIsoMs(builder.bucket5h.resetTime);
|
||||||
|
const nextResetMs = parseIsoMs(entry.resetTime);
|
||||||
|
if (prevResetMs > 0 && nextResetMs > 0 && nextResetMs < prevResetMs) {
|
||||||
|
builder.bucketWeekly = { ...builder.bucket5h, window: 'weekly' };
|
||||||
|
builder.bucket5h = entry;
|
||||||
|
} else {
|
||||||
|
builder.bucketWeekly = { ...entry, window: 'weekly' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (!builder.bucketWeekly) {
|
||||||
builder.bucketWeekly = entry;
|
builder.bucketWeekly = entry;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 注册动态模型字典,并采样 Carbon / Argon 与标准 Gemini 的单模型 quotaInfo
|
// 注册动态模型字典(不把占位符 rawKey 污染进 modelId),并采样 Carbon / Argon 与标准 Gemini 的单模型 quotaInfo
|
||||||
let sampleCarbonCfgQuota = null;
|
let sampleCarbonCfgQuota = null;
|
||||||
let sampleArgonCfgQuota = null;
|
let sampleArgonCfgQuota = null;
|
||||||
let sampleStdGeminiCfgQuota = null;
|
let sampleStdGeminiCfgQuota = null;
|
||||||
@@ -248,13 +271,13 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
|||||||
const rawKey = cfg?.modelOrAlias?.model;
|
const rawKey = cfg?.modelOrAlias?.model;
|
||||||
if (rawKey) {
|
if (rawKey) {
|
||||||
dynamicModelMap.set(rawKey, {
|
dynamicModelMap.set(rawKey, {
|
||||||
modelId: cfg.modelId || rawKey,
|
modelId: cfg.modelId || '',
|
||||||
label: cfg.label || cfg.modelId || rawKey,
|
label: cfg.label || cfg.modelId || rawKey,
|
||||||
quotaInfo: cfg.quotaInfo || null,
|
quotaInfo: cfg.quotaInfo || null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const info = resolveModelInfo(rawKey, dynamicModelMap);
|
const info = resolveModelInfo(rawKey, dynamicModelMap);
|
||||||
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
|
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs);
|
||||||
if (!cfgQuota || info.family !== 'Gemini') continue;
|
if (!cfgQuota || info.family !== 'Gemini') continue;
|
||||||
if (isCarbonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) {
|
if (isCarbonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) {
|
||||||
if (!sampleCarbonCfgQuota) sampleCarbonCfgQuota = cfgQuota;
|
if (!sampleCarbonCfgQuota) sampleCarbonCfgQuota = cfgQuota;
|
||||||
@@ -348,7 +371,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
|||||||
builder.models.push(cfg.label);
|
builder.models.push(cfg.label);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
|
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs);
|
||||||
if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
|
if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
|
||||||
if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') {
|
if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') {
|
||||||
builder.bucketWeekly = cfgQuota;
|
builder.bucketWeekly = cfgQuota;
|
||||||
@@ -362,7 +385,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
|||||||
const hasValid5h = Boolean(eff5h);
|
const hasValid5h = Boolean(eff5h);
|
||||||
modelQuotas.push({
|
modelQuotas.push({
|
||||||
label: cfg.label,
|
label: cfg.label,
|
||||||
modelId: cfg.modelId,
|
modelId: cfg.modelId || info.modelId,
|
||||||
rawKey,
|
rawKey,
|
||||||
family: targetIdent.poolKey,
|
family: targetIdent.poolKey,
|
||||||
isAvailable: Boolean(eff5h || effWk || cfgQuota),
|
isAvailable: Boolean(eff5h || effWk || cfgQuota),
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 遥测载荷组装器与并发请求合并入口。
|
* @fileoverview 遥测载荷组装器与并发请求合并入口。
|
||||||
*
|
*
|
||||||
* 将原来超过 1,000 行的 `buildTelemetryPayloadInternal` 拆解为清晰的子阶段:
|
* 将遥测构建拆解为清晰的子阶段:
|
||||||
* 1. 拉取用户状态、轨迹摘要与官方实时配额摘要(含账号切换自动穿透缓存);
|
* 1. 拉取用户状态、轨迹摘要与官方实时配额摘要(含账号切换缓存校验);
|
||||||
* 2. 调用 `buildOfficialQuotaPools` 构建动态模型映射与多模型配额池;
|
* 2. 调用 `buildOfficialQuotaPools` 构建动态模型映射与多模型配额池;
|
||||||
* 3. 调用 `enumerateAndSyncConversations` 枚举会话并增量更新轨迹缓存;
|
* 3. 调用 `enumerateAndSyncConversations` 枚举会话并增量更新轨迹缓存;
|
||||||
* 4. 调用 `enrichActiveConversationSteps` 与 `extractActiveContextTelemetry` 计算当前活跃会话指标与上下文拆解;
|
* 4. 调用 `enrichActiveConversationSteps` 与 `extractActiveContextTelemetry` 计算当前活跃会话指标与 10 通道上下文拆解;
|
||||||
* 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装最终前端遥测 JSON。
|
* 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装精简的前端遥测 JSON。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { statSync } from 'node:fs';
|
|
||||||
import { join } from 'node:path';
|
|
||||||
import {
|
import {
|
||||||
extractLiveActivity,
|
extractLiveActivity,
|
||||||
parseIsoMs,
|
parseIsoMs,
|
||||||
@@ -19,7 +17,7 @@ import {
|
|||||||
summarizeTtft,
|
summarizeTtft,
|
||||||
} from '../speed-metrics.mjs';
|
} from '../speed-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
HERE,
|
computeRuntimeCodeVersion,
|
||||||
inFlightRequests,
|
inFlightRequests,
|
||||||
loadSettings,
|
loadSettings,
|
||||||
quotaSummaryCache,
|
quotaSummaryCache,
|
||||||
@@ -27,7 +25,7 @@ import {
|
|||||||
trajectoryCache,
|
trajectoryCache,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
||||||
import { callLsRpc, diagnostics, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
import { callLsRpc, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||||
import {
|
import {
|
||||||
computeStepCost,
|
computeStepCost,
|
||||||
isArgonModelIdentifier,
|
isArgonModelIdentifier,
|
||||||
@@ -43,6 +41,22 @@ import {
|
|||||||
} from './usage-aggregator.mjs';
|
} from './usage-aggregator.mjs';
|
||||||
|
|
||||||
const MAX_RECENT_CONVERSATIONS = 30;
|
const MAX_RECENT_CONVERSATIONS = 30;
|
||||||
|
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
|
||||||
|
|
||||||
|
function roundSessionCost(val) {
|
||||||
|
if (!Number.isFinite(val) || val <= 0) return 0;
|
||||||
|
return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findTrajectoryCacheEntry(cascadeId) {
|
||||||
|
if (!cascadeId) return null;
|
||||||
|
if (trajectoryCache[cascadeId]) return trajectoryCache[cascadeId];
|
||||||
|
const targetLower = String(cascadeId).toLowerCase();
|
||||||
|
for (const [k, v] of Object.entries(trajectoryCache)) {
|
||||||
|
if (k.toLowerCase() === targetLower) return v;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。
|
* 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。
|
||||||
@@ -62,15 +76,16 @@ function buildKnownUpstreamModelMap() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标。
|
* 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标,
|
||||||
|
* 并剔除前端未使用的冗余诊断字段以减小 JSON 体积。
|
||||||
*
|
*
|
||||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||||
* @param {Map<string, object>} dynamicModelMap 动态模型字典
|
* @param {Map<string, object>} [dynamicModelMap=new Map()] 动态模型字典
|
||||||
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表
|
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表
|
||||||
*/
|
*/
|
||||||
export function enrichActiveConversationSteps(
|
function enrichActiveConversationSteps(
|
||||||
activeSteps,
|
activeSteps,
|
||||||
dynamicModelMap,
|
dynamicModelMap = new Map(),
|
||||||
sharedUpstreamMap = null
|
sharedUpstreamMap = null
|
||||||
) {
|
) {
|
||||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||||
@@ -80,7 +95,6 @@ export function enrichActiveConversationSteps(
|
|||||||
let sessionInputTokens = 0;
|
let sessionInputTokens = 0;
|
||||||
let sessionCacheReadTokens = 0;
|
let sessionCacheReadTokens = 0;
|
||||||
|
|
||||||
// 记录已知的 modelKey -> 最近观测到的上游 responseModel,避免正在生成的步骤因尚未收到 generatorMetadata 而闪烁
|
|
||||||
const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap();
|
const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap();
|
||||||
for (const s of activeSteps) {
|
for (const s of activeSteps) {
|
||||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||||
@@ -123,8 +137,15 @@ export function enrichActiveConversationSteps(
|
|||||||
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName);
|
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName);
|
||||||
const modelUpstream = st.isCompactionStep ? `${rawUpstreamModel}·压缩` : rawUpstreamModel;
|
const modelUpstream = st.isCompactionStep ? `${rawUpstreamModel}·压缩` : rawUpstreamModel;
|
||||||
|
|
||||||
|
const {
|
||||||
|
viewableDelaySec: _viewableDelaySec,
|
||||||
|
ttftSource: _ttftSource,
|
||||||
|
speedBasis: _speedBasis,
|
||||||
|
...serializedStep
|
||||||
|
} = st;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...st,
|
...serializedStep,
|
||||||
responseModel: st.responseModel || '',
|
responseModel: st.responseModel || '',
|
||||||
modelUpstream,
|
modelUpstream,
|
||||||
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
|
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
|
||||||
@@ -160,22 +181,25 @@ export function enrichActiveConversationSteps(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从当前活跃会话的最新步骤提取上下文 6 维拆解、自动压缩水位与缓存命中率。
|
* 从当前活跃会话的最新步骤提取上下文 10 通道拆解、自动压缩水位与缓存命中率。
|
||||||
*
|
*
|
||||||
* @param {object[]} enrichedActiveSteps
|
* @param {object[]} enrichedActiveSteps
|
||||||
* @param {object|null} latestEnriched
|
* @param {object|null} latestEnriched
|
||||||
* @param {number} sessionInputTokens
|
* @param {number} sessionInputTokens
|
||||||
* @param {number} sessionCacheReadTokens
|
* @param {number} sessionCacheReadTokens
|
||||||
*/
|
*/
|
||||||
export function extractActiveContextTelemetry(
|
function extractActiveContextTelemetry(
|
||||||
enrichedActiveSteps,
|
enrichedActiveSteps,
|
||||||
latestEnriched,
|
latestEnriched,
|
||||||
sessionInputTokens,
|
sessionInputTokens,
|
||||||
sessionCacheReadTokens
|
sessionCacheReadTokens
|
||||||
) {
|
) {
|
||||||
let latestBreakdown = latestEnriched?.contextBreakdown || null;
|
let latestBreakdown = latestEnriched?.contextBreakdown || null;
|
||||||
if (!latestBreakdown) {
|
if (!latestBreakdown && !latestEnriched?.isCompactionStep) {
|
||||||
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
||||||
|
if (enrichedActiveSteps[i]?.isCompactionStep) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
||||||
latestBreakdown = enrichedActiveSteps[i].contextBreakdown;
|
latestBreakdown = enrichedActiveSteps[i].contextBreakdown;
|
||||||
break;
|
break;
|
||||||
@@ -221,10 +245,10 @@ export function extractActiveContextTelemetry(
|
|||||||
|
|
||||||
const latestPromptTokens = ctxCached + ctxFreshInput;
|
const latestPromptTokens = ctxCached + ctxFreshInput;
|
||||||
const latestCacheHitPct =
|
const latestCacheHitPct =
|
||||||
latestPromptTokens > 0 ? Math.round((ctxCached / latestPromptTokens) * 100) : 0;
|
latestPromptTokens > 0 ? +((ctxCached / latestPromptTokens) * 100).toFixed(1) : 0;
|
||||||
const sessionPromptTokens = sessionCacheReadTokens + sessionInputTokens;
|
const sessionPromptTokens = sessionCacheReadTokens + sessionInputTokens;
|
||||||
const sessionCacheHitPct =
|
const sessionCacheHitPct =
|
||||||
sessionPromptTokens > 0 ? Math.round((sessionCacheReadTokens / sessionPromptTokens) * 100) : 0;
|
sessionPromptTokens > 0 ? +((sessionCacheReadTokens / sessionPromptTokens) * 100).toFixed(1) : 0;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
latestCacheHitPct,
|
latestCacheHitPct,
|
||||||
@@ -256,7 +280,7 @@ export function extractActiveContextTelemetry(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建单个代理(主代理或子代理)的标准遥测单元对象,消除主/子代理 25 字段重复组装。
|
* 构建单个代理(主代理或子代理)的标准遥测单元对象。
|
||||||
*/
|
*/
|
||||||
function buildAgentUnitTelemetry({
|
function buildAgentUnitTelemetry({
|
||||||
agentId,
|
agentId,
|
||||||
@@ -330,12 +354,16 @@ function buildAgentUnitTelemetry({
|
|||||||
speedSummary: enrichedRes.sessionSpeed,
|
speedSummary: enrichedRes.sessionSpeed,
|
||||||
ttftSummary: enrichedRes.sessionTtft,
|
ttftSummary: enrichedRes.sessionTtft,
|
||||||
latestStepCostUsd: enrichedRes.latestEnriched?.costUsd ?? null,
|
latestStepCostUsd: enrichedRes.latestEnriched?.costUsd ?? null,
|
||||||
sessionCostUsd: +enrichedRes.sessionCostUsd.toFixed(2),
|
sessionCostUsd: roundSessionCost(enrichedRes.sessionCostUsd),
|
||||||
sessionUnpricedCalls: enrichedRes.sessionUnpricedCalls,
|
sessionUnpricedCalls: enrichedRes.sessionUnpricedCalls,
|
||||||
latestCacheHitPct: ctxRes.latestCacheHitPct,
|
latestCacheHitPct: ctxRes.latestCacheHitPct,
|
||||||
sessionCacheHitPct: ctxRes.sessionCacheHitPct,
|
sessionCacheHitPct: ctxRes.sessionCacheHitPct,
|
||||||
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
|
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
|
||||||
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
|
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
|
||||||
|
activeModelUpstream:
|
||||||
|
enrichedRes.latestEnriched?.modelUpstream ||
|
||||||
|
enrichedRes.latestEnriched?.modelShort ||
|
||||||
|
'模型未知',
|
||||||
context: ctxRes.context,
|
context: ctxRes.context,
|
||||||
...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}),
|
...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}),
|
||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
@@ -348,7 +376,7 @@ function buildAgentUnitTelemetry({
|
|||||||
* 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。
|
* 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。
|
||||||
*
|
*
|
||||||
* @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话)
|
* @param {string} requestedConvId 请求指定的会话 ID(为空时自动选定最近活跃会话)
|
||||||
* @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额 10 秒缓存
|
* @param {boolean} [forceQuotaRefresh=false] 是否强制穿透官方配额缓存与失败退避
|
||||||
* @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项
|
* @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}] 时间范围筛选选项
|
||||||
* @returns {Promise<object>}
|
* @returns {Promise<object>}
|
||||||
*/
|
*/
|
||||||
@@ -368,17 +396,24 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const currentAccountName = userStatus?.email || userStatus?.name || '';
|
const currentAccountName = userStatus?.email || userStatus?.name || '';
|
||||||
let officialQuotaInfo = initialOfficialQuotaInfo;
|
let officialQuotaInfo = initialOfficialQuotaInfo;
|
||||||
|
|
||||||
// 若检测到登录账号在 10 秒缓存期内发生切换,先清空旧账号配额缓存再立即强制刷新,防止刷新失败时串号
|
// 若检测到账号发生切换:仅当并发的 initialOfficialQuotaInfo 命中了旧账号本地缓存 (fromCache === true) 时才需清空并重刷;
|
||||||
|
// 若本轮已经实时穿透请求了上游 RPC (fromCache === false),直接更新归属账号即可,避免二次重复 RPC
|
||||||
const accountChanged = Boolean(
|
const accountChanged = Boolean(
|
||||||
currentAccountName &&
|
currentAccountName &&
|
||||||
quotaSummaryCache.accountName &&
|
quotaSummaryCache.accountName &&
|
||||||
quotaSummaryCache.accountName !== currentAccountName
|
quotaSummaryCache.accountName !== currentAccountName
|
||||||
);
|
);
|
||||||
if (accountChanged) {
|
if (accountChanged) {
|
||||||
|
if (initialOfficialQuotaInfo?.fromCache) {
|
||||||
quotaSummaryCache.data = null;
|
quotaSummaryCache.data = null;
|
||||||
quotaSummaryCache.ts = 0;
|
quotaSummaryCache.ts = 0;
|
||||||
|
quotaSummaryCache.lastAttemptTs = 0;
|
||||||
|
quotaSummaryCache.error = null;
|
||||||
quotaSummaryCache.accountName = currentAccountName;
|
quotaSummaryCache.accountName = currentAccountName;
|
||||||
officialQuotaInfo = await getOfficialQuotaSummary(true);
|
officialQuotaInfo = await getOfficialQuotaSummary(true);
|
||||||
|
} else {
|
||||||
|
quotaSummaryCache.accountName = currentAccountName;
|
||||||
|
}
|
||||||
} else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) {
|
} else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) {
|
||||||
quotaSummaryCache.accountName = currentAccountName;
|
quotaSummaryCache.accountName = currentAccountName;
|
||||||
}
|
}
|
||||||
@@ -387,7 +422,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
|
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
|
||||||
|
|
||||||
// 1. 构建官方实时配额池与动态模型目录
|
// 1. 构建官方实时配额池与动态模型目录
|
||||||
const { dynamicModelMap, quotaPoolsMap, modelQuotas } = buildOfficialQuotaPools(
|
const { dynamicModelMap, quotaPoolsMap } = buildOfficialQuotaPools(
|
||||||
officialQuota,
|
officialQuota,
|
||||||
clientConfigs
|
clientConfigs
|
||||||
);
|
);
|
||||||
@@ -398,11 +433,12 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
summariesObj: allTrajRes?.trajectorySummaries || {},
|
||||||
currentAccountName,
|
currentAccountName,
|
||||||
requestedConvId,
|
requestedConvId,
|
||||||
|
forceRefresh: forceQuotaRefresh,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、6 通道上下文拆解与按模型汇总
|
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
||||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap();
|
const knownUpstreamByModelKey = buildKnownUpstreamModelMap();
|
||||||
const activeEntry = activeCascadeId ? trajectoryCache[activeCascadeId] : null;
|
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
||||||
const activeSteps = activeEntry?.steps || [];
|
const activeSteps = activeEntry?.steps || [];
|
||||||
const mainUnit = buildAgentUnitTelemetry({
|
const mainUnit = buildAgentUnitTelemetry({
|
||||||
agentId: 'main',
|
agentId: 'main',
|
||||||
@@ -420,7 +456,6 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
||||||
dynamicModelMap,
|
dynamicModelMap,
|
||||||
knownUpstreamByModelKey,
|
knownUpstreamByModelKey,
|
||||||
// 主代理步骤通过 activeConversation.recentSteps 下发一次,避免 JSON 重复序列化
|
|
||||||
includeRecentSteps: false,
|
includeRecentSteps: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -452,7 +487,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const subSum = subagentSummaries[idx];
|
const subSum = subagentSummaries[idx];
|
||||||
const subCid = subSum.cascadeId;
|
const subCid = subSum.cascadeId;
|
||||||
activeFamilyCascadeIds.add(String(subCid || '').toLowerCase());
|
activeFamilyCascadeIds.add(String(subCid || '').toLowerCase());
|
||||||
const subEntry = trajectoryCache[subCid] || null;
|
const subEntry = findTrajectoryCacheEntry(subCid);
|
||||||
const subRawSteps = subEntry?.steps || [];
|
const subRawSteps = subEntry?.steps || [];
|
||||||
allCombinedRawSteps.push(...subRawSteps);
|
allCombinedRawSteps.push(...subRawSteps);
|
||||||
|
|
||||||
@@ -520,7 +555,6 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||||
mainAgentTelemetry;
|
mainAgentTelemetry;
|
||||||
|
|
||||||
// 若刚启动的子代理尚无已完成步骤 (stepCount === 0),实时速率与上下文回退取最近有步骤的代理,避免闪现空白
|
|
||||||
const agentsWithSteps = allAgents.filter((a) => a.stepCount > 0);
|
const agentsWithSteps = allAgents.filter((a) => a.stepCount > 0);
|
||||||
const latestMetricAgent =
|
const latestMetricAgent =
|
||||||
latestActiveAgent.stepCount > 0
|
latestActiveAgent.stepCount > 0
|
||||||
@@ -531,7 +565,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||||
latestActiveAgent;
|
latestActiveAgent;
|
||||||
|
|
||||||
const totalCostUsd = +totalRawSessionCostUsd.toFixed(2);
|
const totalCostUsd = roundSessionCost(totalRawSessionCostUsd);
|
||||||
const totalUnpricedCalls = allAgents.reduce(
|
const totalUnpricedCalls = allAgents.reduce(
|
||||||
(sum, a) => sum + (a.sessionUnpricedCalls || 0),
|
(sum, a) => sum + (a.sessionUnpricedCalls || 0),
|
||||||
0
|
0
|
||||||
@@ -539,7 +573,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const totalFamilyPromptTokens = totalFamilyInputTokens + totalFamilyCacheReadTokens;
|
const totalFamilyPromptTokens = totalFamilyInputTokens + totalFamilyCacheReadTokens;
|
||||||
const combinedSessionCacheHitPct =
|
const combinedSessionCacheHitPct =
|
||||||
totalFamilyPromptTokens > 0
|
totalFamilyPromptTokens > 0
|
||||||
? Math.round((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100)
|
? +((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100).toFixed(1)
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
const runningSubs = subAgentTelemetries.filter((a) => a.isRunning);
|
const runningSubs = subAgentTelemetries.filter((a) => a.isRunning);
|
||||||
@@ -591,18 +625,22 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
sessionCacheHitPct: combinedSessionCacheHitPct,
|
sessionCacheHitPct: combinedSessionCacheHitPct,
|
||||||
activeModelShort: latestMetricAgent.activeModelShort,
|
activeModelShort: latestMetricAgent.activeModelShort,
|
||||||
activeModelLabel: latestMetricAgent.activeModelLabel,
|
activeModelLabel: latestMetricAgent.activeModelLabel,
|
||||||
|
activeModelUpstream: latestMetricAgent.activeModelUpstream,
|
||||||
context: latestMetricAgent.context,
|
context: latestMetricAgent.context,
|
||||||
modelBreakdown: combinedModelBreakdown,
|
modelBreakdown: combinedModelBreakdown,
|
||||||
lastModifiedMs: latestActiveAgent.lastModifiedMs,
|
lastModifiedMs: latestActiveAgent.lastModifiedMs,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 识别当前活跃会话家族绑定的模型池及其官方 5h / 周限重置锚点
|
// 4. 识别当前活跃会话家族绑定的模型池(与 quota-pools.mjs 保持一致,将 Other 第三方模型归入 Claude & GPT)
|
||||||
const latestFamilyStep =
|
const latestFamilyStep =
|
||||||
allCombinedEnrichedSteps.length > 0
|
allCombinedEnrichedSteps.length > 0
|
||||||
? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1]
|
? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1]
|
||||||
: latestEnriched;
|
: latestEnriched;
|
||||||
const latestIsCarbon = latestFamilyStep
|
const hasResolvedStepModel = Boolean(
|
||||||
|
latestFamilyStep && latestFamilyStep.modelKey && latestFamilyStep.modelKey !== 'unknown'
|
||||||
|
);
|
||||||
|
const latestIsCarbon = hasResolvedStepModel
|
||||||
? isCarbonModelIdentifier(
|
? isCarbonModelIdentifier(
|
||||||
latestFamilyStep.modelKey,
|
latestFamilyStep.modelKey,
|
||||||
latestFamilyStep.responseModel,
|
latestFamilyStep.responseModel,
|
||||||
@@ -610,7 +648,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
latestFamilyStep.modelLabel
|
latestFamilyStep.modelLabel
|
||||||
)
|
)
|
||||||
: false;
|
: false;
|
||||||
const latestIsArgon = latestFamilyStep
|
const latestIsArgon = hasResolvedStepModel
|
||||||
? isArgonModelIdentifier(
|
? isArgonModelIdentifier(
|
||||||
latestFamilyStep.modelKey,
|
latestFamilyStep.modelKey,
|
||||||
latestFamilyStep.responseModel,
|
latestFamilyStep.responseModel,
|
||||||
@@ -619,14 +657,15 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
)
|
)
|
||||||
: false;
|
: false;
|
||||||
const rawActiveFamily = latestFamilyStep?.family || 'Other';
|
const rawActiveFamily = latestFamilyStep?.family || 'Other';
|
||||||
const activePoolKey =
|
const activePoolKey = !hasResolvedStepModel
|
||||||
latestIsCarbon && quotaPoolsMap.has('Carbon')
|
? 'Unknown'
|
||||||
|
: latestIsCarbon && quotaPoolsMap.has('Carbon')
|
||||||
? 'Carbon'
|
? 'Carbon'
|
||||||
: latestIsArgon && quotaPoolsMap.has('Argon')
|
: latestIsArgon && quotaPoolsMap.has('Argon')
|
||||||
? 'Argon'
|
? 'Argon'
|
||||||
: rawActiveFamily === 'Gemini'
|
: rawActiveFamily === 'Gemini'
|
||||||
? 'Gemini'
|
? 'Gemini'
|
||||||
: ['Claude', 'GPT'].includes(rawActiveFamily)
|
: ['Claude', 'GPT', 'Other'].includes(rawActiveFamily)
|
||||||
? 'Claude & GPT'
|
? 'Claude & GPT'
|
||||||
: 'Unknown';
|
: 'Unknown';
|
||||||
const matchedActivePool = quotaPoolsMap.get(activePoolKey) || null;
|
const matchedActivePool = quotaPoolsMap.get(activePoolKey) || null;
|
||||||
@@ -646,12 +685,27 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
resetTime: matchedActivePool.weeklyResetTime,
|
resetTime: matchedActivePool.weeklyResetTime,
|
||||||
}
|
}
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
// 全局账号周期锚点采用稳定的配额池优先级(Gemini -> Argon -> Carbon -> Claude & GPT),
|
||||||
|
// 防止切换不同会话时全局消费统计(consumption.presets.week / 5h)因重置时间偏移而突变
|
||||||
|
let accountFiveHourResetMs = 0;
|
||||||
|
let accountWeeklyResetMs = 0;
|
||||||
|
for (const pk of POOL_PRIORITY_ORDER) {
|
||||||
|
const pool = quotaPoolsMap.get(pk);
|
||||||
|
if (!pool) continue;
|
||||||
|
if (!accountFiveHourResetMs && pool.resetTime) {
|
||||||
|
accountFiveHourResetMs = parseIsoMs(pool.resetTime);
|
||||||
|
}
|
||||||
|
if (!accountWeeklyResetMs && pool.weeklyResetTime) {
|
||||||
|
accountWeeklyResetMs = parseIsoMs(pool.weeklyResetTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
const cycleAnchors = {
|
const cycleAnchors = {
|
||||||
fiveHourResetMs: parseIsoMs(activeLive5h?.resetTime),
|
fiveHourResetMs: accountFiveHourResetMs || parseIsoMs(activeLive5h?.resetTime),
|
||||||
weeklyResetMs: parseIsoMs(activeLiveWeekly?.resetTime),
|
weeklyResetMs: accountWeeklyResetMs || parseIsoMs(activeLiveWeekly?.resetTime),
|
||||||
};
|
};
|
||||||
|
|
||||||
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 12 段趋势 + 月序列 + 来源与模型拆解)
|
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解)
|
||||||
const {
|
const {
|
||||||
selectedWindow,
|
selectedWindow,
|
||||||
trendStartMs,
|
trendStartMs,
|
||||||
@@ -663,7 +717,6 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
sourcesBreakdown,
|
sourcesBreakdown,
|
||||||
currentYear,
|
currentYear,
|
||||||
monthlySeries,
|
monthlySeries,
|
||||||
todayBucket,
|
|
||||||
weekBucket,
|
weekBucket,
|
||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
} = aggregateMultiWindowUsage({
|
} = aggregateMultiWindowUsage({
|
||||||
@@ -707,7 +760,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
};
|
};
|
||||||
|
|
||||||
const fallbackWeeklyPct =
|
const fallbackWeeklyPct =
|
||||||
settings.weeklyLimitMode === 'custom_cost' || settings.weeklyLimitMode === 'cost'
|
settings.weeklyLimitMode === 'custom_cost'
|
||||||
? weekBucket.unpricedCalls > 0
|
? weekBucket.unpricedCalls > 0
|
||||||
? null
|
? null
|
||||||
: Math.min(
|
: Math.min(
|
||||||
@@ -739,18 +792,132 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
? Math.max(0, Math.floor(100 - fallbackWeeklyPct))
|
? Math.max(0, Math.floor(100 - fallbackWeeklyPct))
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
// 提取真实的 Google One AI Credits(忽略旧版硬编码的 500 prompt credits)
|
|
||||||
const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find(
|
const g1CreditEntry = (userStatus?.userTier?.availableCredits || []).find(
|
||||||
(c) => c?.creditType === 'GOOGLE_ONE_AI'
|
(c) => c?.creditType === 'GOOGLE_ONE_AI'
|
||||||
);
|
);
|
||||||
const realAiCredits = Number(g1CreditEntry?.creditAmount || 0);
|
const realAiCredits = Number(g1CreditEntry?.creditAmount || 0);
|
||||||
|
const uiBundleVersion = computeRuntimeCodeVersion();
|
||||||
|
|
||||||
let uiBundleVersion = 0;
|
const rawTierName = userStatus?.userTier?.name || '';
|
||||||
try {
|
const inferredPlanFallback = /\bfree\b/i.test(rawTierName)
|
||||||
uiBundleVersion = statSync(join(HERE, 'app.js')).mtimeMs || 0;
|
? 'Free'
|
||||||
} catch {
|
: /\bultra\b/i.test(rawTierName)
|
||||||
// 忽略 stat 异常
|
? 'Ultra'
|
||||||
|
: 'Pro';
|
||||||
|
const resolvedPlanName = userStatus?.planStatus?.planInfo?.planName || inferredPlanFallback;
|
||||||
|
|
||||||
|
// 预计算近期会话与运行中会话的轻量缓存速览指标(零额外 RPC 开销)
|
||||||
|
const quickStatsMemo = new Map();
|
||||||
|
const getConversationQuickStats = (rootConv) => {
|
||||||
|
const cidKey = String(rootConv?.cascadeId || '').toLowerCase();
|
||||||
|
if (cidKey && quickStatsMemo.has(cidKey)) {
|
||||||
|
return quickStatsMemo.get(cidKey);
|
||||||
}
|
}
|
||||||
|
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId);
|
||||||
|
const rootSteps = rootEntry?.steps || [];
|
||||||
|
const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : [];
|
||||||
|
|
||||||
|
let totalCost = 0;
|
||||||
|
let unpricedCalls = 0;
|
||||||
|
const accumulateStepsCost = (steps) => {
|
||||||
|
for (const st of steps) {
|
||||||
|
const mInfo = resolveModelInfo(
|
||||||
|
st.modelKey,
|
||||||
|
dynamicModelMap,
|
||||||
|
st.apiProvider,
|
||||||
|
st.modelDisplayName,
|
||||||
|
st.responseModel
|
||||||
|
);
|
||||||
|
const c = computeStepCost(st, mInfo.pricing);
|
||||||
|
if (c === null) unpricedCalls += 1;
|
||||||
|
else totalCost += c;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
accumulateStepsCost(rootSteps);
|
||||||
|
|
||||||
|
const lastRootStep = rootSteps.length > 0 ? rootSteps[rootSteps.length - 1] : null;
|
||||||
|
let bestMetricStep = lastRootStep;
|
||||||
|
let bestMetricRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING' && Boolean(lastRootStep);
|
||||||
|
|
||||||
|
for (const subSum of rawSubs) {
|
||||||
|
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId);
|
||||||
|
const subSteps = subEntry?.steps || [];
|
||||||
|
if (subSteps.length === 0) continue;
|
||||||
|
accumulateStepsCost(subSteps);
|
||||||
|
const lastSub = subSteps[subSteps.length - 1];
|
||||||
|
const subRunning = subSum?.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||||
|
if (
|
||||||
|
!bestMetricStep ||
|
||||||
|
(subRunning && !bestMetricRunning) ||
|
||||||
|
(subRunning === bestMetricRunning &&
|
||||||
|
(lastSub.createdAtMs || 0) >= (bestMetricStep.createdAtMs || 0))
|
||||||
|
) {
|
||||||
|
bestMetricStep = lastSub;
|
||||||
|
bestMetricRunning = subRunning;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let contextUsedPct = null;
|
||||||
|
if (lastRootStep) {
|
||||||
|
const limitTokens = Number(lastRootStep.maxContextBudgetTokens || 256000);
|
||||||
|
const cb = lastRootStep.contextBreakdown;
|
||||||
|
const cbTotal = cb
|
||||||
|
? Number(cb.messagesTokens || 0) +
|
||||||
|
Number(cb.systemToolsTokens || 0) +
|
||||||
|
Number(cb.mcpToolsTokens || 0) +
|
||||||
|
Number(cb.skillsTokens || 0) +
|
||||||
|
Number(cb.systemPromptTokens || 0) +
|
||||||
|
Number(cb.userRulesTokens || 0)
|
||||||
|
: 0;
|
||||||
|
const fallbackTotal =
|
||||||
|
Number(lastRootStep.inputTokens || 0) +
|
||||||
|
Number(lastRootStep.cacheReadTokens || 0) +
|
||||||
|
Number(lastRootStep.thinkingTokens || 0) +
|
||||||
|
Number(lastRootStep.responseTokens || 0);
|
||||||
|
const usedTokens = Number(
|
||||||
|
cbTotal > 0 ? cbTotal : lastRootStep.estimatedContextTokens || fallbackTotal
|
||||||
|
);
|
||||||
|
contextUsedPct =
|
||||||
|
limitTokens > 0 ? Math.min(100, +((usedTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let modelShort = '';
|
||||||
|
let modelUpstream = '';
|
||||||
|
let latestTokPerSec = null;
|
||||||
|
if (bestMetricStep) {
|
||||||
|
const mInfo = resolveModelInfo(
|
||||||
|
bestMetricStep.modelKey,
|
||||||
|
dynamicModelMap,
|
||||||
|
bestMetricStep.apiProvider,
|
||||||
|
bestMetricStep.modelDisplayName,
|
||||||
|
bestMetricStep.responseModel
|
||||||
|
);
|
||||||
|
const resolvedResp =
|
||||||
|
bestMetricStep.responseModel ||
|
||||||
|
(bestMetricStep.modelKey && bestMetricStep.modelKey !== 'unknown'
|
||||||
|
? knownUpstreamByModelKey.get(bestMetricStep.modelKey) || ''
|
||||||
|
: '');
|
||||||
|
modelShort = mInfo.shortName || '';
|
||||||
|
modelUpstream =
|
||||||
|
resolvedResp ||
|
||||||
|
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName) ||
|
||||||
|
'';
|
||||||
|
latestTokPerSec = roundMetric(speedMetric(bestMetricStep).value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const stats = {
|
||||||
|
modelShort,
|
||||||
|
modelUpstream,
|
||||||
|
latestTokPerSec,
|
||||||
|
contextUsedPct,
|
||||||
|
sessionCostUsd: roundSessionCost(totalCost),
|
||||||
|
sessionUnpricedCalls: unpricedCalls,
|
||||||
|
};
|
||||||
|
if (cidKey) {
|
||||||
|
quickStatsMemo.set(cidKey, stats);
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
};
|
||||||
|
|
||||||
// 7. 构建所有正在运行的主进程(根会话)及其子代理缩略状态列表
|
// 7. 构建所有正在运行的主进程(根会话)及其子代理缩略状态列表
|
||||||
const runningConversations = [];
|
const runningConversations = [];
|
||||||
@@ -762,13 +929,13 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootEntry = trajectoryCache[rootConv.cascadeId] || null;
|
const rootEntry = findTrajectoryCacheEntry(rootConv.cascadeId);
|
||||||
const rootFallbackMs =
|
const rootFallbackMs =
|
||||||
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
||||||
|
|
||||||
const subItems = rawSubs.map((subSum, idx) => {
|
const subItems = rawSubs.map((subSum, idx) => {
|
||||||
const subCid = subSum.cascadeId;
|
const subCid = subSum.cascadeId;
|
||||||
const subEntry = trajectoryCache[subCid] || null;
|
const subEntry = findTrajectoryCacheEntry(subCid);
|
||||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||||
const rawRole =
|
const rawRole =
|
||||||
subSpec?.role ||
|
subSpec?.role ||
|
||||||
@@ -812,7 +979,6 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
? rootConv.liveActivity || extractLiveActivity([], true, rootFallbackMs)
|
? rootConv.liveActivity || extractLiveActivity([], true, rootFallbackMs)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
// 若主代理正在调用 invoke_subagent 但新子代理轨迹尚未出现在 rawSubs 中,生成临时子代理占位项
|
|
||||||
const runningSubCount = subItems.filter((s) => s.isRunning).length;
|
const runningSubCount = subItems.filter((s) => s.isRunning).length;
|
||||||
if (
|
if (
|
||||||
isMainRunning &&
|
isMainRunning &&
|
||||||
@@ -857,6 +1023,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
}
|
}
|
||||||
: extractLiveActivity([], true, rootFallbackMs));
|
: extractLiveActivity([], true, rootFallbackMs));
|
||||||
|
|
||||||
|
const qStats = getConversationQuickStats(rootConv);
|
||||||
runningConversations.push({
|
runningConversations.push({
|
||||||
cascadeId: rootConv.cascadeId,
|
cascadeId: rootConv.cascadeId,
|
||||||
title: rootConv.title || rootConv.cascadeId.slice(0, 8),
|
title: rootConv.title || rootConv.cascadeId.slice(0, 8),
|
||||||
@@ -873,6 +1040,12 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
subagentCount: subItems.length,
|
subagentCount: subItems.length,
|
||||||
runningSubagentCount: runningSubList.length,
|
runningSubagentCount: runningSubList.length,
|
||||||
subagents: subItems,
|
subagents: subItems,
|
||||||
|
modelShort: qStats.modelShort,
|
||||||
|
modelUpstream: qStats.modelUpstream,
|
||||||
|
latestTokPerSec: qStats.latestTokPerSec,
|
||||||
|
contextUsedPct: qStats.contextUsedPct,
|
||||||
|
sessionCostUsd: qStats.sessionCostUsd,
|
||||||
|
sessionUnpricedCalls: qStats.sessionUnpricedCalls,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -881,25 +1054,37 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
uiBundleVersion,
|
uiBundleVersion,
|
||||||
settings,
|
settings,
|
||||||
cloudStatus: getCloudStatus(),
|
cloudStatus: getCloudStatus(),
|
||||||
diagnostics: diagnostics.status(),
|
|
||||||
account: {
|
account: {
|
||||||
name: userStatus?.name || '',
|
name: userStatus?.name || '',
|
||||||
tierName: userStatus?.userTier?.name || 'Google AI',
|
tierName: rawTierName || 'Google AI',
|
||||||
planName: userStatus?.planStatus?.planInfo?.planName || 'Pro',
|
planName: resolvedPlanName,
|
||||||
aiCredits: realAiCredits > 0 ? realAiCredits : null,
|
aiCredits: realAiCredits > 0 ? realAiCredits : null,
|
||||||
totalConversations: conversations.length,
|
totalConversations: conversations.length,
|
||||||
},
|
},
|
||||||
runningConversations,
|
runningConversations,
|
||||||
conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => ({
|
conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => {
|
||||||
|
const qStats = getConversationQuickStats(c);
|
||||||
|
const rawSubs = Array.isArray(c.subagents) ? c.subagents : [];
|
||||||
|
const runningSubCount = rawSubs.filter((s) => s.status === 'CASCADE_RUN_STATUS_RUNNING').length;
|
||||||
|
return {
|
||||||
cascadeId: c.cascadeId,
|
cascadeId: c.cascadeId,
|
||||||
title: c.title,
|
title: c.title,
|
||||||
stepCount: c.stepCount,
|
stepCount: c.stepCount,
|
||||||
subagentCount: c.subagentCount || 0,
|
subagentCount: c.subagentCount || 0,
|
||||||
|
runningSubagentCount: runningSubCount,
|
||||||
totalStepCount: c.totalStepCount || c.stepCount || 0,
|
totalStepCount: c.totalStepCount || c.stepCount || 0,
|
||||||
|
isRunning: c.status === 'CASCADE_RUN_STATUS_RUNNING' || runningSubCount > 0,
|
||||||
status: c.status,
|
status: c.status,
|
||||||
lastModifiedTime: c.lastModifiedTime,
|
lastModifiedTime: c.lastModifiedTime,
|
||||||
lastModifiedMs: c.lastModifiedMs,
|
lastModifiedMs: c.groupLastModifiedMs || c.lastModifiedMs,
|
||||||
})),
|
modelShort: qStats.modelShort,
|
||||||
|
modelUpstream: qStats.modelUpstream,
|
||||||
|
latestTokPerSec: qStats.latestTokPerSec,
|
||||||
|
contextUsedPct: qStats.contextUsedPct,
|
||||||
|
sessionCostUsd: qStats.sessionCostUsd,
|
||||||
|
sessionUnpricedCalls: qStats.sessionUnpricedCalls,
|
||||||
|
};
|
||||||
|
}),
|
||||||
activeConversation: {
|
activeConversation: {
|
||||||
cascadeId: activeCascadeId,
|
cascadeId: activeCascadeId,
|
||||||
title: activeConvSummary?.title || '当前会话',
|
title: activeConvSummary?.title || '当前会话',
|
||||||
@@ -917,12 +1102,14 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
speedSummary: sessionSpeed,
|
speedSummary: sessionSpeed,
|
||||||
ttftSummary: sessionTtft,
|
ttftSummary: sessionTtft,
|
||||||
latestStepCostUsd: latestEnriched?.costUsd ?? null,
|
latestStepCostUsd: latestEnriched?.costUsd ?? null,
|
||||||
sessionCostUsd: +sessionCostUsd.toFixed(2),
|
sessionCostUsd: roundSessionCost(sessionCostUsd),
|
||||||
sessionUnpricedCalls,
|
sessionUnpricedCalls,
|
||||||
latestCacheHitPct,
|
latestCacheHitPct,
|
||||||
sessionCacheHitPct,
|
sessionCacheHitPct,
|
||||||
activeModelShort: latestEnriched?.modelShort || '模型未知',
|
activeModelShort: latestEnriched?.modelShort || '模型未知',
|
||||||
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
||||||
|
activeModelUpstream:
|
||||||
|
latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知',
|
||||||
context,
|
context,
|
||||||
recentSteps: enrichedActiveSteps.slice().reverse(),
|
recentSteps: enrichedActiveSteps.slice().reverse(),
|
||||||
modelBreakdown: mainModelBreakdown,
|
modelBreakdown: mainModelBreakdown,
|
||||||
@@ -937,9 +1124,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
endMs: trendEndMs,
|
endMs: trendEndMs,
|
||||||
},
|
},
|
||||||
session: finalizedSelectedSession,
|
session: finalizedSelectedSession,
|
||||||
sessionAllTime: finalizedPresets.all.session,
|
|
||||||
account: finalizedSelectedAccount,
|
account: finalizedSelectedAccount,
|
||||||
accountAllTime: finalizedPresets.all.account,
|
|
||||||
presets: finalizedPresets,
|
presets: finalizedPresets,
|
||||||
trendSeries,
|
trendSeries,
|
||||||
sourcesBreakdown,
|
sourcesBreakdown,
|
||||||
@@ -960,7 +1145,6 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 };
|
const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 };
|
||||||
return (order[a.family] ?? 99) - (order[b.family] ?? 99);
|
return (order[a.family] ?? 99) - (order[b.family] ?? 99);
|
||||||
}),
|
}),
|
||||||
models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))),
|
|
||||||
weekly: {
|
weekly: {
|
||||||
isOfficial: useOfficialWeekly,
|
isOfficial: useOfficialWeekly,
|
||||||
poolFamily: activePoolKey,
|
poolFamily: activePoolKey,
|
||||||
@@ -980,12 +1164,6 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
? getNextMondayResetIso()
|
? getNextMondayResetIso()
|
||||||
: null,
|
: null,
|
||||||
},
|
},
|
||||||
today: {
|
|
||||||
calls: todayBucket.calls,
|
|
||||||
tokens: todayBucket.totalTokens,
|
|
||||||
costUsd: todayBucket.costUsd,
|
|
||||||
unpricedCalls: todayBucket.unpricedCalls,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
};
|
};
|
||||||
@@ -993,7 +1171,6 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 带并发请求合并(In-Flight Deduplication)的遥测载荷构建入口。
|
* 带并发请求合并(In-Flight Deduplication)的遥测载荷构建入口。
|
||||||
* 当相同会话、刷新模式与时间范围的请求正在处理中时,直接复用同一个 Promise。
|
|
||||||
*
|
*
|
||||||
* @param {string} requestedConvId
|
* @param {string} requestedConvId
|
||||||
* @param {boolean} [forceQuotaRefresh=false]
|
* @param {boolean} [forceQuotaRefresh=false]
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 多时间窗口解析、用量桶累加、12 段趋势序列、月度序列与分模型/分来源聚合引擎。
|
* @fileoverview 多时间窗口解析、用量桶累加、趋势序列、月度序列与分模型/分来源聚合引擎。
|
||||||
*
|
*
|
||||||
* 负责将内存缓存 (`trajectoryCache`) 与外部深层统计缓存 (`loadExternalDeepStatsCache`)
|
* 负责将内存缓存 (`trajectoryCache`) 与外部深层统计缓存 (`loadExternalDeepStatsCache`)
|
||||||
* 中的所有步骤按预设窗口(`all`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口
|
* 中的所有步骤按预设窗口(`all`, `5h`, `today`, `24h`, `week`, `7d`, `14d`, `30d`)与当前选定窗口
|
||||||
* 进行一次遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。
|
* 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -15,18 +15,30 @@ import { roundMetric, trajectoryCache } from './config.mjs';
|
|||||||
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
||||||
import { computeStepCost, resolveModelInfo } from './model-pricing.mjs';
|
import { computeStepCost, resolveModelInfo } from './model-pricing.mjs';
|
||||||
|
|
||||||
|
function safeTok(val) {
|
||||||
|
const n = Number(val);
|
||||||
|
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取本地当日 00:00:00.000 的毫秒时间戳。
|
* 获取本地当日 00:00:00.000 的毫秒时间戳。
|
||||||
*
|
*
|
||||||
* @param {Date|number} [now=new Date()]
|
* @param {Date|number} [now=new Date()]
|
||||||
* @returns {number}
|
* @returns {number}
|
||||||
*/
|
*/
|
||||||
export function getStartOfLocalDayMs(now = new Date()) {
|
function getStartOfLocalDayMs(now = new Date()) {
|
||||||
const d = new Date(now);
|
const d = new Date(now);
|
||||||
d.setHours(0, 0, 0, 0);
|
d.setHours(0, 0, 0, 0);
|
||||||
return d.getTime();
|
return d.getTime();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getStartOfLocalOffsetDaysMs(nowMs, offsetDays) {
|
||||||
|
const d = new Date(nowMs);
|
||||||
|
d.setDate(d.getDate() - offsetDays);
|
||||||
|
d.setHours(0, 0, 0, 0);
|
||||||
|
return d.getTime();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取本地下一个周一 00:00:00.000 的 ISO 时间字符串(用于自定义本机周限额重置倒计时)。
|
* 获取本地下一个周一 00:00:00.000 的 ISO 时间字符串(用于自定义本机周限额重置倒计时)。
|
||||||
*
|
*
|
||||||
@@ -48,7 +60,7 @@ export function getNextMondayResetIso(now = new Date()) {
|
|||||||
* @param {Date|number} [now=new Date()]
|
* @param {Date|number} [now=new Date()]
|
||||||
* @returns {number}
|
* @returns {number}
|
||||||
*/
|
*/
|
||||||
export function getStartOfCurrentWeekMs(now = new Date()) {
|
function getStartOfCurrentWeekMs(now = new Date()) {
|
||||||
const d = new Date(now);
|
const d = new Date(now);
|
||||||
const day = d.getDay(); // 0 = Sun, 1 = Mon
|
const day = d.getDay(); // 0 = Sun, 1 = Mon
|
||||||
const diffToMon = day === 0 ? -6 : 1 - day;
|
const diffToMon = day === 0 ? -6 : 1 - day;
|
||||||
@@ -67,7 +79,7 @@ export function getStartOfCurrentWeekMs(now = new Date()) {
|
|||||||
* @param {{ fiveHourResetMs?: number, weeklyResetMs?: number }} [cycleAnchors={}]
|
* @param {{ fiveHourResetMs?: number, weeklyResetMs?: number }} [cycleAnchors={}]
|
||||||
* @returns {{ key: string, label: string, startMs: number, endMs: number }}
|
* @returns {{ key: string, label: string, startMs: number, endMs: number }}
|
||||||
*/
|
*/
|
||||||
export function resolveTimeWindow(
|
function resolveTimeWindow(
|
||||||
rangeKey = 'all',
|
rangeKey = 'all',
|
||||||
customStartMs = 0,
|
customStartMs = 0,
|
||||||
customEndMs = 0,
|
customEndMs = 0,
|
||||||
@@ -79,7 +91,9 @@ export function resolveTimeWindow(
|
|||||||
case '5h': {
|
case '5h': {
|
||||||
const reset5hMs = cycleAnchors.fiveHourResetMs || 0;
|
const reset5hMs = cycleAnchors.fiveHourResetMs || 0;
|
||||||
const start5hMs =
|
const start5hMs =
|
||||||
reset5hMs > nowMs ? reset5hMs - 5 * 3600 * 1000 : nowMs - 5 * 3600 * 1000;
|
reset5hMs > nowMs
|
||||||
|
? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000)
|
||||||
|
: nowMs - 5 * 3600 * 1000;
|
||||||
return {
|
return {
|
||||||
key: '5h',
|
key: '5h',
|
||||||
label: reset5hMs > nowMs ? '当前 5h 周期' : '近 5 小时',
|
label: reset5hMs > nowMs ? '当前 5h 周期' : '近 5 小时',
|
||||||
@@ -94,7 +108,9 @@ export function resolveTimeWindow(
|
|||||||
case 'week': {
|
case 'week': {
|
||||||
const resetWkMs = cycleAnchors.weeklyResetMs || 0;
|
const resetWkMs = cycleAnchors.weeklyResetMs || 0;
|
||||||
const startWkMs =
|
const startWkMs =
|
||||||
resetWkMs > nowMs ? resetWkMs - 7 * 24 * 3600 * 1000 : getStartOfCurrentWeekMs(now);
|
resetWkMs > nowMs
|
||||||
|
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
|
||||||
|
: getStartOfCurrentWeekMs(now);
|
||||||
return {
|
return {
|
||||||
key: 'week',
|
key: 'week',
|
||||||
label: resetWkMs > nowMs ? '当前周限周期' : '本周',
|
label: resetWkMs > nowMs ? '当前周限周期' : '本周',
|
||||||
@@ -103,19 +119,24 @@ export function resolveTimeWindow(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
case '7d':
|
case '7d':
|
||||||
return { key: '7d', label: '近 7 天', startMs: nowMs - 7 * 24 * 3600 * 1000, endMs: nowMs };
|
return {
|
||||||
|
key: '7d',
|
||||||
|
label: '近 7 天',
|
||||||
|
startMs: getStartOfLocalOffsetDaysMs(nowMs, 7),
|
||||||
|
endMs: nowMs,
|
||||||
|
};
|
||||||
case '14d':
|
case '14d':
|
||||||
return {
|
return {
|
||||||
key: '14d',
|
key: '14d',
|
||||||
label: '近 14 天',
|
label: '近 14 天',
|
||||||
startMs: nowMs - 14 * 24 * 3600 * 1000,
|
startMs: getStartOfLocalOffsetDaysMs(nowMs, 14),
|
||||||
endMs: nowMs,
|
endMs: nowMs,
|
||||||
};
|
};
|
||||||
case '30d':
|
case '30d':
|
||||||
return {
|
return {
|
||||||
key: '30d',
|
key: '30d',
|
||||||
label: '近 30 天',
|
label: '近 30 天',
|
||||||
startMs: nowMs - 30 * 24 * 3600 * 1000,
|
startMs: getStartOfLocalOffsetDaysMs(nowMs, 30),
|
||||||
endMs: nowMs,
|
endMs: nowMs,
|
||||||
};
|
};
|
||||||
case 'custom': {
|
case 'custom': {
|
||||||
@@ -137,7 +158,7 @@ export function resolveTimeWindow(
|
|||||||
/**
|
/**
|
||||||
* 创建一个空的用量统计累加桶。
|
* 创建一个空的用量统计累加桶。
|
||||||
*/
|
*/
|
||||||
export function createUsageBucket() {
|
function createUsageBucket() {
|
||||||
return {
|
return {
|
||||||
calls: 0,
|
calls: 0,
|
||||||
conversationsSet: new Set(),
|
conversationsSet: new Set(),
|
||||||
@@ -149,12 +170,6 @@ export function createUsageBucket() {
|
|||||||
totalTokens: 0,
|
totalTokens: 0,
|
||||||
costUsd: 0,
|
costUsd: 0,
|
||||||
savedCostUsd: 0,
|
savedCostUsd: 0,
|
||||||
geminiTokens: 0,
|
|
||||||
geminiCostUsd: 0,
|
|
||||||
geminiCalls: 0,
|
|
||||||
claudeGptTokens: 0,
|
|
||||||
claudeGptCostUsd: 0,
|
|
||||||
claudeGptCalls: 0,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,33 +182,32 @@ export function createUsageBucket() {
|
|||||||
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
||||||
* @param {string} cascadeId 会话标识
|
* @param {string} cascadeId 会话标识
|
||||||
*/
|
*/
|
||||||
export function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) {
|
function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) {
|
||||||
const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens;
|
const inTok = safeTok(st?.inputTokens);
|
||||||
const savedCost = mInfo.pricing
|
const cacheTok = safeTok(st?.cacheReadTokens);
|
||||||
? (st.cacheReadTokens / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
const outTok = safeTok(st?.outputTokens);
|
||||||
|
const thinkTok = safeTok(st?.thinkingTokens);
|
||||||
|
const respTok =
|
||||||
|
st?.responseTokens !== undefined && st?.responseTokens !== null
|
||||||
|
? safeTok(st.responseTokens)
|
||||||
|
: Math.max(0, outTok - thinkTok);
|
||||||
|
|
||||||
|
const stepTotalTokens = inTok + cacheTok + outTok;
|
||||||
|
const savedCost = mInfo?.pricing
|
||||||
|
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||||
: 0;
|
: 0;
|
||||||
if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||||
const resolvedCost = stepCost ?? 0;
|
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||||
bucket.calls += 1;
|
bucket.calls += 1;
|
||||||
if (cascadeId) bucket.conversationsSet.add(cascadeId);
|
if (cascadeId) bucket.conversationsSet.add(cascadeId);
|
||||||
bucket.inputTokens += st.inputTokens;
|
bucket.inputTokens += inTok;
|
||||||
bucket.cacheReadTokens += st.cacheReadTokens;
|
bucket.cacheReadTokens += cacheTok;
|
||||||
bucket.outputTokens += st.outputTokens;
|
bucket.outputTokens += outTok;
|
||||||
bucket.thinkingTokens += st.thinkingTokens || 0;
|
bucket.thinkingTokens += thinkTok;
|
||||||
bucket.responseTokens += st.responseTokens || 0;
|
bucket.responseTokens += respTok;
|
||||||
bucket.totalTokens += stepTotalTokens;
|
bucket.totalTokens += stepTotalTokens;
|
||||||
bucket.costUsd += resolvedCost;
|
bucket.costUsd += resolvedCost;
|
||||||
bucket.savedCostUsd += savedCost;
|
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -201,7 +215,7 @@ export function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId)
|
|||||||
*
|
*
|
||||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||||
*/
|
*/
|
||||||
export function finalizeUsageBucket(bucket) {
|
function finalizeUsageBucket(bucket) {
|
||||||
const promptTokens = bucket.inputTokens + bucket.cacheReadTokens;
|
const promptTokens = bucket.inputTokens + bucket.cacheReadTokens;
|
||||||
const cacheHitPct =
|
const cacheHitPct =
|
||||||
promptTokens > 0 ? +((bucket.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0;
|
promptTokens > 0 ? +((bucket.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0;
|
||||||
@@ -218,12 +232,6 @@ export function finalizeUsageBucket(bucket) {
|
|||||||
unpricedCalls: bucket.unpricedCalls || 0,
|
unpricedCalls: bucket.unpricedCalls || 0,
|
||||||
savedCostUsd: +bucket.savedCostUsd.toFixed(2),
|
savedCostUsd: +bucket.savedCostUsd.toFixed(2),
|
||||||
cacheHitPct,
|
cacheHitPct,
|
||||||
geminiTokens: bucket.geminiTokens,
|
|
||||||
geminiCostUsd: +bucket.geminiCostUsd.toFixed(2),
|
|
||||||
geminiCalls: bucket.geminiCalls,
|
|
||||||
claudeGptTokens: bucket.claudeGptTokens,
|
|
||||||
claudeGptCostUsd: +bucket.claudeGptCostUsd.toFixed(2),
|
|
||||||
claudeGptCalls: bucket.claudeGptCalls,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,8 +244,15 @@ export function finalizeUsageBucket(bucket) {
|
|||||||
* @param {number|null} stepCost
|
* @param {number|null} stepCost
|
||||||
*/
|
*/
|
||||||
function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||||
const stepTotalTokens =
|
const inTok = safeTok(st?.inputTokens);
|
||||||
(st.inputTokens || 0) + (st.cacheReadTokens || 0) + (st.outputTokens || 0);
|
const cacheTok = safeTok(st?.cacheReadTokens);
|
||||||
|
const outTok = safeTok(st?.outputTokens);
|
||||||
|
const thinkTok = safeTok(st?.thinkingTokens);
|
||||||
|
const respTok =
|
||||||
|
st?.responseTokens !== undefined && st?.responseTokens !== null
|
||||||
|
? safeTok(st.responseTokens)
|
||||||
|
: Math.max(0, outTok - thinkTok);
|
||||||
|
const stepTotalTokens = inTok + cacheTok + outTok;
|
||||||
const unpriced = stepCost === null ? 1 : 0;
|
const unpriced = stepCost === null ? 1 : 0;
|
||||||
const modelGroupKey = mInfo.baseLabel || mInfo.label;
|
const modelGroupKey = mInfo.baseLabel || mInfo.label;
|
||||||
|
|
||||||
@@ -269,13 +284,13 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
|||||||
accumulateSpeed(agg.speedAccumulator, st);
|
accumulateSpeed(agg.speedAccumulator, st);
|
||||||
|
|
||||||
agg.calls += 1;
|
agg.calls += 1;
|
||||||
agg.inputTokens += st.inputTokens || 0;
|
agg.inputTokens += inTok;
|
||||||
agg.cacheReadTokens += st.cacheReadTokens || 0;
|
agg.cacheReadTokens += cacheTok;
|
||||||
agg.outputTokens += st.outputTokens || 0;
|
agg.outputTokens += outTok;
|
||||||
agg.thinkingTokens += st.thinkingTokens || 0;
|
agg.thinkingTokens += thinkTok;
|
||||||
agg.responseTokens += st.responseTokens || 0;
|
agg.responseTokens += respTok;
|
||||||
agg.totalTokens += stepTotalTokens;
|
agg.totalTokens += stepTotalTokens;
|
||||||
agg.costUsd += stepCost ?? 0;
|
agg.costUsd += Number.isFinite(stepCost) ? stepCost : 0;
|
||||||
agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced;
|
agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,13 +324,14 @@ function finalizeModelBreakdownMap(perModelStats) {
|
|||||||
/**
|
/**
|
||||||
* 针对给定步骤数组构建按模型聚合的统计列表(供单代理、主+子汇总及全局时间范围复用)。
|
* 针对给定步骤数组构建按模型聚合的统计列表(供单代理、主+子汇总及全局时间范围复用)。
|
||||||
*
|
*
|
||||||
* @param {object[]} steps
|
* @param {object[]} [steps=[]]
|
||||||
* @param {Map<string, object>} dynamicModelMap
|
* @param {Map<string, object>} [dynamicModelMap=new Map()]
|
||||||
* @returns {object[]}
|
* @returns {object[]}
|
||||||
*/
|
*/
|
||||||
export function buildScopedModelBreakdown(steps = [], dynamicModelMap) {
|
export function buildScopedModelBreakdown(steps = [], dynamicModelMap = new Map()) {
|
||||||
const perModelStats = new Map();
|
const perModelStats = new Map();
|
||||||
for (const st of steps) {
|
for (const st of steps) {
|
||||||
|
if (!st || typeof st !== 'object') continue;
|
||||||
const mInfo = resolveModelInfo(
|
const mInfo = resolveModelInfo(
|
||||||
st.modelKey,
|
st.modelKey,
|
||||||
dynamicModelMap,
|
dynamicModelMap,
|
||||||
@@ -330,7 +346,7 @@ export function buildScopedModelBreakdown(steps = [], dynamicModelMap) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 聚合所有预设时间窗口、当前选定窗口、12 段趋势图、年度月序列、来源占比与分模型统计。
|
* 聚合所有预设时间窗口、当前选定窗口、趋势图、年度月序列、来源占比与分模型统计。
|
||||||
*
|
*
|
||||||
* @param {{
|
* @param {{
|
||||||
* filterOpts?: { range?: string, startMs?: number, endMs?: number },
|
* filterOpts?: { range?: string, startMs?: number, endMs?: number },
|
||||||
@@ -338,7 +354,7 @@ export function buildScopedModelBreakdown(steps = [], dynamicModelMap) {
|
|||||||
* currentAccountName?: string,
|
* currentAccountName?: string,
|
||||||
* activeCascadeId?: string|null,
|
* activeCascadeId?: string|null,
|
||||||
* activeFamilyCascadeIds?: Set<string>|null,
|
* activeFamilyCascadeIds?: Set<string>|null,
|
||||||
* dynamicModelMap: Map<string, object>
|
* dynamicModelMap?: Map<string, object>
|
||||||
* }} params
|
* }} params
|
||||||
*/
|
*/
|
||||||
export function aggregateMultiWindowUsage({
|
export function aggregateMultiWindowUsage({
|
||||||
@@ -347,8 +363,8 @@ export function aggregateMultiWindowUsage({
|
|||||||
currentAccountName = '',
|
currentAccountName = '',
|
||||||
activeCascadeId = null,
|
activeCascadeId = null,
|
||||||
activeFamilyCascadeIds = null,
|
activeFamilyCascadeIds = null,
|
||||||
dynamicModelMap,
|
dynamicModelMap = new Map(),
|
||||||
}) {
|
} = {}) {
|
||||||
const rawFamilyIds =
|
const rawFamilyIds =
|
||||||
activeFamilyCascadeIds instanceof Set
|
activeFamilyCascadeIds instanceof Set
|
||||||
? Array.from(activeFamilyCascadeIds)
|
? Array.from(activeFamilyCascadeIds)
|
||||||
@@ -401,10 +417,41 @@ export function aggregateMultiWindowUsage({
|
|||||||
};
|
};
|
||||||
const perSourceStats = new Map();
|
const perSourceStats = new Map();
|
||||||
const externalConvos = loadExternalDeepStatsCache();
|
const externalConvos = loadExternalDeepStatsCache();
|
||||||
|
|
||||||
|
// 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费
|
||||||
|
const allLiveByLower = new Map();
|
||||||
|
for (const [rawId, entry] of Object.entries(trajectoryCache)) {
|
||||||
|
const cidLower = String(rawId || '').toLowerCase();
|
||||||
|
if (!cidLower || !entry || typeof entry !== 'object') continue;
|
||||||
|
const prev = allLiveByLower.get(cidLower);
|
||||||
|
if (!prev || (entry.steps?.length || 0) > (prev.steps?.length || 0)) {
|
||||||
|
allLiveByLower.set(cidLower, entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const externalByCid = new Map();
|
||||||
|
for (const ext of externalConvos.values()) {
|
||||||
|
const extCidLower = String(ext?.cascadeId || '').toLowerCase();
|
||||||
|
if (!extCidLower) continue;
|
||||||
|
const knownLive = allLiveByLower.get(extCidLower);
|
||||||
|
const ownerAccount = ext.accountName || knownLive?.accountName || '';
|
||||||
|
if (
|
||||||
|
ownerAccount &&
|
||||||
|
currentAccountName &&
|
||||||
|
ownerAccount !== currentAccountName &&
|
||||||
|
!familySet.has(extCidLower)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const prevExt = externalByCid.get(extCidLower);
|
||||||
|
if (!prevExt || (ext.steps?.length || 0) > (prevExt.steps?.length || 0)) {
|
||||||
|
externalByCid.set(extCidLower, ext);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const allEntriesToAggregate = [];
|
const allEntriesToAggregate = [];
|
||||||
|
|
||||||
for (const [cascadeId, entry] of Object.entries(trajectoryCache)) {
|
for (const [cidLower, entry] of allLiveByLower.entries()) {
|
||||||
const cidLower = String(cascadeId || '').toLowerCase();
|
|
||||||
if (
|
if (
|
||||||
entry?.accountName &&
|
entry?.accountName &&
|
||||||
currentAccountName &&
|
currentAccountName &&
|
||||||
@@ -413,12 +460,12 @@ export function aggregateMultiWindowUsage({
|
|||||||
) {
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const extMatch = externalConvos.get(cascadeId) || externalConvos.get(cidLower);
|
const extMatch = externalByCid.get(cidLower);
|
||||||
if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) {
|
if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const groupCascadeId = String(
|
const groupCascadeId = String(
|
||||||
entry?.rootConversationId || entry?.parentConversationId || cascadeId
|
entry?.rootConversationId || entry?.parentConversationId || cidLower
|
||||||
).toLowerCase();
|
).toLowerCase();
|
||||||
allEntriesToAggregate.push({
|
allEntriesToAggregate.push({
|
||||||
cascadeId: groupCascadeId,
|
cascadeId: groupCascadeId,
|
||||||
@@ -428,14 +475,13 @@ export function aggregateMultiWindowUsage({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const ext of externalConvos.values()) {
|
for (const [extCidLower, ext] of externalByCid.entries()) {
|
||||||
const extCidLower = String(ext.cascadeId || '').toLowerCase();
|
const liveEntry = allLiveByLower.get(extCidLower);
|
||||||
const liveEntry = trajectoryCache[ext.cascadeId] || trajectoryCache[extCidLower];
|
|
||||||
if (liveEntry && (liveEntry.steps?.length || 0) >= (ext.steps?.length || 0)) {
|
if (liveEntry && (liveEntry.steps?.length || 0) >= (ext.steps?.length || 0)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
allEntriesToAggregate.push({
|
allEntriesToAggregate.push({
|
||||||
cascadeId: `${ext.appSource}:${extCidLower}`,
|
cascadeId: extCidLower,
|
||||||
appSource: ext.appSource || 'ide',
|
appSource: ext.appSource || 'ide',
|
||||||
steps: ext.steps || [],
|
steps: ext.steps || [],
|
||||||
isCurrentConv: familySet.has(extCidLower),
|
isCurrentConv: familySet.has(extCidLower),
|
||||||
@@ -448,6 +494,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
|
const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
|
||||||
|
|
||||||
for (const st of entry.steps || []) {
|
for (const st of entry.steps || []) {
|
||||||
|
if (!st || typeof st !== 'object') continue;
|
||||||
const mInfo = resolveModelInfo(
|
const mInfo = resolveModelInfo(
|
||||||
st.modelKey,
|
st.modelKey,
|
||||||
dynamicModelMap,
|
dynamicModelMap,
|
||||||
@@ -455,10 +502,19 @@ export function aggregateMultiWindowUsage({
|
|||||||
st.modelDisplayName,
|
st.modelDisplayName,
|
||||||
st.responseModel
|
st.responseModel
|
||||||
);
|
);
|
||||||
const stepTotalTokens = st.inputTokens + st.cacheReadTokens + st.outputTokens;
|
const inTok = safeTok(st.inputTokens);
|
||||||
|
const cacheTok = safeTok(st.cacheReadTokens);
|
||||||
|
const outTok = safeTok(st.outputTokens);
|
||||||
|
const thinkTok = safeTok(st.thinkingTokens);
|
||||||
|
const respTok =
|
||||||
|
st.responseTokens !== undefined && st.responseTokens !== null
|
||||||
|
? safeTok(st.responseTokens)
|
||||||
|
: Math.max(0, outTok - thinkTok);
|
||||||
|
const stepTotalTokens = inTok + cacheTok + outTok;
|
||||||
const stepCost = computeStepCost(st, mInfo.pricing);
|
const stepCost = computeStepCost(st, mInfo.pricing);
|
||||||
|
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||||
const unpriced = stepCost === null ? 1 : 0;
|
const unpriced = stepCost === null ? 1 : 0;
|
||||||
const tMs = st.createdAtMs || 0;
|
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
|
||||||
|
|
||||||
if (tMs > 0) {
|
if (tMs > 0) {
|
||||||
const stepDate = new Date(tMs);
|
const stepDate = new Date(tMs);
|
||||||
@@ -466,12 +522,12 @@ export function aggregateMultiWindowUsage({
|
|||||||
const mBucket = monthlySeries[stepDate.getMonth()];
|
const mBucket = monthlySeries[stepDate.getMonth()];
|
||||||
if (mBucket) {
|
if (mBucket) {
|
||||||
mBucket.calls += 1;
|
mBucket.calls += 1;
|
||||||
mBucket.inputTokens += st.inputTokens || 0;
|
mBucket.inputTokens += inTok;
|
||||||
mBucket.cacheReadTokens += st.cacheReadTokens || 0;
|
mBucket.cacheReadTokens += cacheTok;
|
||||||
mBucket.responseTokens += st.responseTokens || 0;
|
mBucket.responseTokens += respTok;
|
||||||
mBucket.thinkingTokens += st.thinkingTokens || 0;
|
mBucket.thinkingTokens += thinkTok;
|
||||||
mBucket.totalTokens += stepTotalTokens;
|
mBucket.totalTokens += stepTotalTokens;
|
||||||
mBucket.costUsd = +(mBucket.costUsd + (stepCost ?? 0)).toFixed(4);
|
mBucket.costUsd += resolvedCost;
|
||||||
mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced;
|
mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -479,7 +535,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
|
|
||||||
for (const k of presetKeys) {
|
for (const k of presetKeys) {
|
||||||
const w = presetWindows[k];
|
const w = presetWindows[k];
|
||||||
if (k === 'all' || (tMs >= w.startMs && tMs <= w.endMs)) {
|
if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) {
|
||||||
accumulateStepIntoBucket(accountBuckets[k], st, mInfo, stepCost, cascadeId);
|
accumulateStepIntoBucket(accountBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||||
if (isCurrentConv) {
|
if (isCurrentConv) {
|
||||||
accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId);
|
accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||||
@@ -489,7 +545,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
|
|
||||||
const inSelectedWindow =
|
const inSelectedWindow =
|
||||||
selectedWindow.key === 'all' ||
|
selectedWindow.key === 'all' ||
|
||||||
(tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
(tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
||||||
|
|
||||||
if (inSelectedWindow) {
|
if (inSelectedWindow) {
|
||||||
accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId);
|
accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId);
|
||||||
@@ -501,11 +557,10 @@ export function aggregateMultiWindowUsage({
|
|||||||
selectedWindowSteps.push({
|
selectedWindowSteps.push({
|
||||||
tMs,
|
tMs,
|
||||||
tokens: stepTotalTokens,
|
tokens: stepTotalTokens,
|
||||||
inputTokens: st.inputTokens || 0,
|
inputTokens: inTok,
|
||||||
cacheReadTokens: st.cacheReadTokens || 0,
|
cacheReadTokens: cacheTok,
|
||||||
outputTokens:
|
outputTokens: outTok,
|
||||||
(st.responseTokens || 0) + (st.thinkingTokens || 0) || st.outputTokens || 0,
|
costUsd: resolvedCost,
|
||||||
costUsd: stepCost ?? 0,
|
|
||||||
unpricedCalls: unpriced,
|
unpricedCalls: unpriced,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -524,12 +579,12 @@ export function aggregateMultiWindowUsage({
|
|||||||
}
|
}
|
||||||
const sAgg = perSourceStats.get(srcKey);
|
const sAgg = perSourceStats.get(srcKey);
|
||||||
sAgg.calls += 1;
|
sAgg.calls += 1;
|
||||||
sAgg.inputTokens += st.inputTokens || 0;
|
sAgg.inputTokens += inTok;
|
||||||
sAgg.cacheReadTokens += st.cacheReadTokens || 0;
|
sAgg.cacheReadTokens += cacheTok;
|
||||||
sAgg.responseTokens += st.responseTokens || 0;
|
sAgg.responseTokens += respTok;
|
||||||
sAgg.thinkingTokens += st.thinkingTokens || 0;
|
sAgg.thinkingTokens += thinkTok;
|
||||||
sAgg.totalTokens += stepTotalTokens;
|
sAgg.totalTokens += stepTotalTokens;
|
||||||
sAgg.costUsd += stepCost ?? 0;
|
sAgg.costUsd += resolvedCost;
|
||||||
sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced;
|
sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced;
|
||||||
|
|
||||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||||
@@ -537,6 +592,10 @@ export function aggregateMultiWindowUsage({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const mBucket of monthlySeries) {
|
||||||
|
mBucket.costUsd = +mBucket.costUsd.toFixed(4);
|
||||||
|
}
|
||||||
|
|
||||||
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
|
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
|
||||||
const MAX_SAFE_MS = 8_640_000_000_000_000;
|
const MAX_SAFE_MS = 8_640_000_000_000_000;
|
||||||
const safeMs = (val, fallback) =>
|
const safeMs = (val, fallback) =>
|
||||||
@@ -717,10 +776,13 @@ export function aggregateMultiWindowUsage({
|
|||||||
bucket.inputTokens += item.inputTokens || 0;
|
bucket.inputTokens += item.inputTokens || 0;
|
||||||
bucket.cacheReadTokens += item.cacheReadTokens || 0;
|
bucket.cacheReadTokens += item.cacheReadTokens || 0;
|
||||||
bucket.outputTokens += item.outputTokens || 0;
|
bucket.outputTokens += item.outputTokens || 0;
|
||||||
bucket.costUsd = +(bucket.costUsd + item.costUsd).toFixed(4);
|
bucket.costUsd += item.costUsd;
|
||||||
bucket.unpricedCalls = (bucket.unpricedCalls || 0) + item.unpricedCalls;
|
bucket.unpricedCalls = (bucket.unpricedCalls || 0) + item.unpricedCalls;
|
||||||
bucket.calls += 1;
|
bucket.calls += 1;
|
||||||
}
|
}
|
||||||
|
for (const b of trendSeries) {
|
||||||
|
b.costUsd = +b.costUsd.toFixed(4);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalizedPresets = {};
|
const finalizedPresets = {};
|
||||||
|
|||||||
@@ -0,0 +1,826 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 双栖模式(Window Overlay)本地回环桥接服务与 CDP 多窗口自动挂载调度器。
|
||||||
|
*
|
||||||
|
* 职责边界:
|
||||||
|
* 1. 在 Sidecar 进程内维护仅绑定 `127.0.0.1` 随机端口的受保护 HTTP 桥接端点,
|
||||||
|
* 通过一次性 256-bit 随机令牌 (`X-Usage-Monitor-Token`)、严格 `Origin` 校验与 Private Network CORS 头,
|
||||||
|
* 为主窗口 Shadow DOM 内的悬浮面板提供与辅助栏完全一致的 `/api/*` 遥测与控制接口;
|
||||||
|
* 2. 周期性探测本机 `Antigravity/DevToolsActivePort`,发现所有打开的主聊天窗口(支持多窗口并存),
|
||||||
|
* 按需将最新的 `styles.css` 与 `app.js` 热挂载至窗口顶栏,并在用户关闭双栖开关时立即清理卸载;
|
||||||
|
* 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import {
|
||||||
|
DATA_DIR,
|
||||||
|
computeRuntimeCodeVersion,
|
||||||
|
loadJson,
|
||||||
|
loadSettings,
|
||||||
|
saveJson,
|
||||||
|
} from './config.mjs';
|
||||||
|
|
||||||
|
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
||||||
|
const ALLOWED_BRIDGE_PATHS = new Set([
|
||||||
|
'/api/telemetry',
|
||||||
|
'/api/settings',
|
||||||
|
'/api/cloud-sync',
|
||||||
|
'/api/plugin-update',
|
||||||
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析各操作系统下 Antigravity 写入 `DevToolsActivePort` 的候选路径列表。
|
||||||
|
*
|
||||||
|
* @param {Record<string, string|undefined>} [env=process.env]
|
||||||
|
* @param {string} [platform=process.platform]
|
||||||
|
* @param {string} [homeDir=homedir()]
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function resolveDevToolsPortCandidates(
|
||||||
|
env = process.env,
|
||||||
|
platform = process.platform,
|
||||||
|
homeDir = homedir()
|
||||||
|
) {
|
||||||
|
const explicitFile = String(env?.ANTIGRAVITY_DEVTOOLS_PORT_FILE || '').trim();
|
||||||
|
if (explicitFile) {
|
||||||
|
return [explicitFile];
|
||||||
|
}
|
||||||
|
if (platform === 'win32') {
|
||||||
|
const appData = env?.APPDATA || join(homeDir, 'AppData', 'Roaming');
|
||||||
|
const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local');
|
||||||
|
return [
|
||||||
|
join(appData, 'Antigravity', 'DevToolsActivePort'),
|
||||||
|
join(localAppData, 'Antigravity', 'DevToolsActivePort'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (platform === 'darwin') {
|
||||||
|
return [join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort')];
|
||||||
|
}
|
||||||
|
const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config');
|
||||||
|
return [join(configHome, 'Antigravity', 'DevToolsActivePort')];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 `DevToolsActivePort` 文件文本首行提取合法的本地调试端口号。
|
||||||
|
*
|
||||||
|
* @param {string} rawText
|
||||||
|
* @returns {number|null}
|
||||||
|
*/
|
||||||
|
export function parseDevToolsPortFile(rawText) {
|
||||||
|
if (typeof rawText !== 'string' || !rawText) return null;
|
||||||
|
const firstLine = rawText.split(/\r?\n/)[0]?.trim() || '';
|
||||||
|
if (!/^\d+$/.test(firstLine)) return null;
|
||||||
|
const port = Number(firstLine);
|
||||||
|
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断 CDP `/json/list` 返回的目标是否为 Antigravity 主聊天窗口页面,
|
||||||
|
* 严格排除 `vscode-webview://` 子视图、DevTools 面板与非本机回环地址。
|
||||||
|
*
|
||||||
|
* @param {object} target
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isAntigravityMainPageTarget(target) {
|
||||||
|
if (!target || typeof target !== 'object') return false;
|
||||||
|
if (target.type !== 'page') return false;
|
||||||
|
const url = String(target.url || '').trim();
|
||||||
|
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
|
||||||
|
if (!/^https:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+(?:\/|$)/i.test(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!/^ws:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+\//i.test(wsUrl)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验桥接请求的 `Origin` 是否来自本机 Antigravity 主窗口 HTTPS 回环源。
|
||||||
|
*
|
||||||
|
* @param {unknown} origin
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isAllowedBridgeOrigin(origin) {
|
||||||
|
const text = String(origin || '').trim();
|
||||||
|
return /^https:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+$/i.test(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 固定时间比较两个等长 ASCII 令牌字符串,避免时序侧信道泄露。
|
||||||
|
*
|
||||||
|
* @param {string} actual
|
||||||
|
* @param {string} expected
|
||||||
|
* @param {typeof import('node:crypto').timingSafeEqual|null} [timingSafeEqualFn=null]
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function verifyBridgeToken(actual, expected, timingSafeEqualFn = null) {
|
||||||
|
if (typeof actual !== 'string' || typeof expected !== 'string' || !expected) return false;
|
||||||
|
if (actual.length !== expected.length) return false;
|
||||||
|
if (typeof timingSafeEqualFn === 'function') {
|
||||||
|
return timingSafeEqualFn(Buffer.from(actual, 'utf8'), Buffer.from(expected, 'utf8'));
|
||||||
|
}
|
||||||
|
let diff = 0;
|
||||||
|
for (let i = 0; i < expected.length; i++) {
|
||||||
|
diff |= actual.charCodeAt(i) ^ expected.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return diff === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建双栖模式桥接与 CDP 热挂载控制器实例。
|
||||||
|
*
|
||||||
|
* @param {{
|
||||||
|
* handleApiRequest: (pathname: string, method: string, data: Record<string, any>) => Promise<{ status: number, contentType?: string, headers?: Record<string, string>, body: string }>,
|
||||||
|
* readAssetFn: (relPath: string) => Promise<string>,
|
||||||
|
* getSettingsFn?: () => { enableWindowOverlay?: boolean },
|
||||||
|
* getBundleVersionFn?: () => string,
|
||||||
|
* env?: Record<string, string|undefined>,
|
||||||
|
* platform?: string,
|
||||||
|
* homeDir?: string,
|
||||||
|
* pollIntervalMs?: number,
|
||||||
|
* cdpTimeoutMs?: number,
|
||||||
|
* WebSocketImpl?: typeof WebSocket,
|
||||||
|
* }} options
|
||||||
|
*/
|
||||||
|
export function createWindowBridgeController(options) {
|
||||||
|
const {
|
||||||
|
handleApiRequest,
|
||||||
|
readAssetFn,
|
||||||
|
getSettingsFn = loadSettings,
|
||||||
|
getBundleVersionFn = computeRuntimeCodeVersion,
|
||||||
|
env = process.env,
|
||||||
|
platform = process.platform,
|
||||||
|
homeDir = homedir(),
|
||||||
|
pollIntervalMs = 3000,
|
||||||
|
fastPollIntervalMs = 1500,
|
||||||
|
cdpTimeoutMs = 3500,
|
||||||
|
bootBundleVersion = '',
|
||||||
|
onVersionDrift = null,
|
||||||
|
leaseFilePath = '',
|
||||||
|
WebSocketImpl = globalThis.WebSocket,
|
||||||
|
} = options || {};
|
||||||
|
|
||||||
|
function isPidAlive(pid) {
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
||||||
|
if (pid === process.pid) return true;
|
||||||
|
try {
|
||||||
|
process.kill(pid, 0);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
return err?.code === 'EPERM';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let server = null;
|
||||||
|
let serverStartPromise = null;
|
||||||
|
let bridgePort = 0;
|
||||||
|
let bridgeToken = '';
|
||||||
|
let pollTimer = null;
|
||||||
|
let initialTimer = null;
|
||||||
|
let stopped = false;
|
||||||
|
let syncInFlight = null;
|
||||||
|
let hadInjectedTargets = false;
|
||||||
|
let cdpFallbackActive = false;
|
||||||
|
let nodeDepsPromise = null;
|
||||||
|
|
||||||
|
async function loadNodeDeps() {
|
||||||
|
if (!nodeDepsPromise) {
|
||||||
|
nodeDepsPromise = Promise.all([import('node:http'), import('node:crypto')]).then(
|
||||||
|
([httpMod, cryptoMod]) => ({
|
||||||
|
http: httpMod.default || httpMod,
|
||||||
|
crypto: cryptoMod.default || cryptoMod,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return nodeDepsPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyCorsHeaders(res, origin) {
|
||||||
|
res.setHeader('Access-Control-Allow-Origin', origin);
|
||||||
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
||||||
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Usage-Monitor-Token');
|
||||||
|
res.setHeader('Access-Control-Allow-Private-Network', 'true');
|
||||||
|
res.setHeader('Access-Control-Max-Age', '600');
|
||||||
|
res.setHeader('Vary', 'Origin');
|
||||||
|
res.setHeader('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeRpcBatch(rpcBatch) {
|
||||||
|
const responses = [];
|
||||||
|
for (const item of rpcBatch) {
|
||||||
|
const reqId = String(item?.id || '');
|
||||||
|
if (!reqId) continue;
|
||||||
|
try {
|
||||||
|
const parsedUrl = new URL(String(item.path || '/'), 'http://127.0.0.1');
|
||||||
|
if (!ALLOWED_BRIDGE_PATHS.has(parsedUrl.pathname)) {
|
||||||
|
responses.push({ id: reqId, ok: false, status: 404, error: 'Not found' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const method = String(item.method || 'GET').toUpperCase();
|
||||||
|
const reqData =
|
||||||
|
method === 'GET'
|
||||||
|
? Object.fromEntries(parsedUrl.searchParams.entries())
|
||||||
|
: item.body && typeof item.body === 'object'
|
||||||
|
? item.body
|
||||||
|
: {};
|
||||||
|
const out = await handleApiRequest(parsedUrl.pathname, method, reqData);
|
||||||
|
const status = Number(out?.status || 200);
|
||||||
|
const parsedBody = out?.body ? JSON.parse(out.body) : {};
|
||||||
|
if (status >= 200 && status < 300) {
|
||||||
|
responses.push({ id: reqId, ok: true, status, data: parsedBody });
|
||||||
|
} else {
|
||||||
|
responses.push({
|
||||||
|
id: reqId,
|
||||||
|
ok: false,
|
||||||
|
status,
|
||||||
|
error: parsedBody?.error || `HTTP ${status}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
responses.push({
|
||||||
|
id: reqId,
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
error: err?.message || 'Internal bridge error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return responses;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureBridgeServer() {
|
||||||
|
if (server && bridgePort > 0) {
|
||||||
|
return { port: bridgePort, token: bridgeToken };
|
||||||
|
}
|
||||||
|
if (serverStartPromise) {
|
||||||
|
return serverStartPromise;
|
||||||
|
}
|
||||||
|
serverStartPromise = (async () => {
|
||||||
|
const { http, crypto } = await loadNodeDeps();
|
||||||
|
if (!bridgeToken) {
|
||||||
|
bridgeToken = crypto.randomBytes(32).toString('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
const srv = http.createServer((req, res) => {
|
||||||
|
// 注意:主窗口为 https://127.0.0.1,桥接为 http://127.0.0.1,跨协议请求在 Chromium 中必然携带
|
||||||
|
// Sec-Fetch-Site: cross-site;此处通过严格 Origin 白名单 + Host 校验 + 256-bit 随机令牌保障回环安全。
|
||||||
|
const origin = String(req.headers.origin || '').trim();
|
||||||
|
if (!isAllowedBridgeOrigin(origin)) {
|
||||||
|
res.writeHead(403, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Forbidden origin' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hostHeader = String(req.headers.host || '').trim().toLowerCase();
|
||||||
|
if (
|
||||||
|
hostHeader &&
|
||||||
|
hostHeader !== `127.0.0.1:${bridgePort}` &&
|
||||||
|
hostHeader !== `localhost:${bridgePort}` &&
|
||||||
|
hostHeader !== `[::1]:${bridgePort}`
|
||||||
|
) {
|
||||||
|
res.writeHead(403, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Forbidden host' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
applyCorsHeaders(res, origin);
|
||||||
|
|
||||||
|
const method = String(req.method || 'GET').toUpperCase();
|
||||||
|
if (method === 'OPTIONS') {
|
||||||
|
res.writeHead(204);
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsedUrl;
|
||||||
|
try {
|
||||||
|
parsedUrl = new URL(req.url || '/', `http://127.0.0.1:${bridgePort}`);
|
||||||
|
} catch {
|
||||||
|
res.writeHead(400, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Malformed URL' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ALLOWED_BRIDGE_PATHS.has(parsedUrl.pathname)) {
|
||||||
|
res.writeHead(404, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Not found' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const headerToken = String(req.headers['x-usage-monitor-token'] || '');
|
||||||
|
if (!verifyBridgeToken(headerToken, bridgeToken, crypto.timingSafeEqual)) {
|
||||||
|
res.writeHead(403, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Invalid bridge token' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'GET') {
|
||||||
|
const queryData = Object.fromEntries(parsedUrl.searchParams.entries());
|
||||||
|
Promise.resolve(handleApiRequest(parsedUrl.pathname, 'GET', queryData))
|
||||||
|
.then((out) => {
|
||||||
|
const hdrs = {
|
||||||
|
'Content-Type': out.contentType || 'application/json',
|
||||||
|
...(out.headers || {}),
|
||||||
|
};
|
||||||
|
res.writeHead(out.status || 200, hdrs);
|
||||||
|
res.end(out.body);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.writeHead(500, { 'Content-Type': 'application/json' });
|
||||||
|
}
|
||||||
|
res.end(JSON.stringify({ error: 'Internal bridge error' }));
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method !== 'POST') {
|
||||||
|
res.writeHead(405, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Method not allowed' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunks = [];
|
||||||
|
let totalBytes = 0;
|
||||||
|
let aborted = false;
|
||||||
|
req.on('data', (chunk) => {
|
||||||
|
totalBytes += chunk.length;
|
||||||
|
if (totalBytes > BRIDGE_MAX_BODY_BYTES) {
|
||||||
|
aborted = true;
|
||||||
|
res.writeHead(413, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Payload too large' }));
|
||||||
|
req.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
req.on('end', () => {
|
||||||
|
if (aborted) return;
|
||||||
|
let bodyObj = {};
|
||||||
|
try {
|
||||||
|
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
||||||
|
bodyObj = raw ? JSON.parse(raw) : {};
|
||||||
|
} catch {
|
||||||
|
res.writeHead(400, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Promise.resolve(handleApiRequest(parsedUrl.pathname, 'POST', bodyObj))
|
||||||
|
.then((out) => {
|
||||||
|
const hdrs = {
|
||||||
|
'Content-Type': out.contentType || 'application/json',
|
||||||
|
...(out.headers || {}),
|
||||||
|
};
|
||||||
|
res.writeHead(out.status || 200, hdrs);
|
||||||
|
res.end(out.body);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!res.headersSent) {
|
||||||
|
res.writeHead(500, { 'Content-Type': 'application/json' });
|
||||||
|
}
|
||||||
|
res.end(JSON.stringify({ error: 'Internal bridge error' }));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
srv.once('error', reject);
|
||||||
|
srv.listen(0, '127.0.0.1', () => {
|
||||||
|
srv.removeListener('error', reject);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
srv.unref?.();
|
||||||
|
const addr = srv.address();
|
||||||
|
bridgePort = typeof addr === 'object' && addr ? Number(addr.port || 0) : 0;
|
||||||
|
server = srv;
|
||||||
|
return { port: bridgePort, token: bridgeToken };
|
||||||
|
})().finally(() => {
|
||||||
|
serverStartPromise = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
return serverStartPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findActiveDevToolsPort() {
|
||||||
|
const candidates = resolveDevToolsPortCandidates(env, platform, homeDir);
|
||||||
|
for (const filePath of candidates) {
|
||||||
|
try {
|
||||||
|
if (!existsSync(filePath)) continue;
|
||||||
|
const port = parseDevToolsPortFile(readFileSync(filePath, 'utf8'));
|
||||||
|
if (port) return port;
|
||||||
|
} catch {
|
||||||
|
// 忽略不可读候选文件
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listMainWindowTargets(cdpPort) {
|
||||||
|
const { http } = await loadNodeDeps();
|
||||||
|
const rawBody = await new Promise((resolve, reject) => {
|
||||||
|
const req = http.get(`http://127.0.0.1:${cdpPort}/json/list`, (res) => {
|
||||||
|
if (res.statusCode !== 200) {
|
||||||
|
res.resume();
|
||||||
|
reject(new Error(`CDP HTTP ${res.statusCode}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let text = '';
|
||||||
|
res.setEncoding('utf8');
|
||||||
|
res.on('data', (chunk) => {
|
||||||
|
text += chunk;
|
||||||
|
});
|
||||||
|
res.on('end', () => resolve(text));
|
||||||
|
});
|
||||||
|
req.setTimeout(1500, () => req.destroy(new Error('CDP list timeout')));
|
||||||
|
req.on('error', reject);
|
||||||
|
});
|
||||||
|
const parsed = JSON.parse(rawBody);
|
||||||
|
if (!Array.isArray(parsed)) return [];
|
||||||
|
return parsed.filter(isAntigravityMainPageTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function evaluateOnTarget(wsUrl, expression) {
|
||||||
|
const WS = WebSocketImpl || globalThis.WebSocket;
|
||||||
|
if (typeof WS !== 'function') {
|
||||||
|
throw new Error('WebSocket runtime unavailable');
|
||||||
|
}
|
||||||
|
let ws = null;
|
||||||
|
let timer = null;
|
||||||
|
try {
|
||||||
|
ws = new WS(wsUrl);
|
||||||
|
const evalResult = await new Promise((resolve, reject) => {
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
reject(new Error('CDP Runtime.evaluate timeout'));
|
||||||
|
}, cdpTimeoutMs);
|
||||||
|
|
||||||
|
const onOpen = () => {
|
||||||
|
try {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
id: 1,
|
||||||
|
method: 'Runtime.evaluate',
|
||||||
|
params: {
|
||||||
|
expression,
|
||||||
|
returnByValue: true,
|
||||||
|
awaitPromise: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onMessage = (ev) => {
|
||||||
|
try {
|
||||||
|
const raw = typeof ev?.data === 'string' ? ev.data : String(ev?.data || '');
|
||||||
|
const msg = JSON.parse(raw);
|
||||||
|
if (msg && msg.id === 1) {
|
||||||
|
resolve(msg);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略无关事件帧
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onError = (err) => {
|
||||||
|
reject(err instanceof Error ? err : new Error('CDP WebSocket error'));
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.addEventListener('open', onOpen, { once: true });
|
||||||
|
ws.addEventListener('message', onMessage);
|
||||||
|
ws.addEventListener('error', onError, { once: true });
|
||||||
|
});
|
||||||
|
return evalResult;
|
||||||
|
} finally {
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
if (ws) {
|
||||||
|
try {
|
||||||
|
ws.close();
|
||||||
|
} catch {
|
||||||
|
// 忽略关闭异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runSyncInternal({ forceReinject = false } = {}) {
|
||||||
|
if (stopped) return { ok: false, reason: 'stopped' };
|
||||||
|
const bundleVersion = String(getBundleVersionFn() || '');
|
||||||
|
if (bootBundleVersion && bundleVersion && bundleVersion !== String(bootBundleVersion)) {
|
||||||
|
onVersionDrift?.();
|
||||||
|
return { ok: false, reason: 'version_drift_restarting', injected: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const enabled = Boolean(getSettingsFn()?.enableWindowOverlay !== false);
|
||||||
|
if (enabled && leaseFilePath && !forceReinject) {
|
||||||
|
const lease = loadJson(leaseFilePath, null);
|
||||||
|
const leasePid = Number(lease?.pid || 0);
|
||||||
|
const leaseAgeMs = Date.now() - Number(lease?.updatedAtMs || 0);
|
||||||
|
if (leasePid > 0 && leasePid !== process.pid && leaseAgeMs >= 0 && leaseAgeMs < 9000 && isPidAlive(leasePid)) {
|
||||||
|
const leaseVerNum = Number(lease?.bundleVersion) || 0;
|
||||||
|
const myVerNum = Number(bundleVersion) || 0;
|
||||||
|
if (leaseVerNum > myVerNum) {
|
||||||
|
onVersionDrift?.();
|
||||||
|
return { ok: false, enabled: true, reason: 'older_than_leader', injected: 0 };
|
||||||
|
}
|
||||||
|
if (leaseVerNum === myVerNum || String(lease?.bundleVersion || '') === bundleVersion) {
|
||||||
|
return { ok: true, enabled: true, reason: 'follower_yield', leaderPid: leasePid, injected: 0 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
saveJson(leaseFilePath, {
|
||||||
|
pid: process.pid,
|
||||||
|
bundleVersion,
|
||||||
|
updatedAtMs: Date.now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const cdpPort = findActiveDevToolsPort();
|
||||||
|
if (!cdpPort) {
|
||||||
|
return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
let targets = [];
|
||||||
|
try {
|
||||||
|
targets = await listMainWindowTargets(cdpPort);
|
||||||
|
} catch {
|
||||||
|
return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 };
|
||||||
|
}
|
||||||
|
if (!targets.length) {
|
||||||
|
return { ok: true, enabled, reason: 'no_targets', injected: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!enabled) {
|
||||||
|
if (!hadInjectedTargets && !forceReinject) {
|
||||||
|
return { ok: true, enabled: false, removed: 0 };
|
||||||
|
}
|
||||||
|
const disposeExpr = `(() => {
|
||||||
|
try {
|
||||||
|
const existed = Boolean(window.__AGUsageMonitorOverlay || window.__AGUsageMonitorBridge);
|
||||||
|
window.__AGUsageMonitorOverlay?.dispose?.();
|
||||||
|
delete window.__AGUsageMonitorOverlay;
|
||||||
|
delete window.__AGUsageMonitorBridge;
|
||||||
|
return existed;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})()`;
|
||||||
|
let removed = 0;
|
||||||
|
for (const target of targets) {
|
||||||
|
try {
|
||||||
|
const res = await evaluateOnTarget(target.webSocketDebuggerUrl, disposeExpr);
|
||||||
|
if (res?.result?.result?.value === true) removed += 1;
|
||||||
|
} catch {
|
||||||
|
// 单窗口不可达不阻塞其余窗口卸载
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hadInjectedTargets = false;
|
||||||
|
return { ok: true, enabled: false, removed };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { port, token } = await ensureBridgeServer();
|
||||||
|
const probeExpr = `(() => {
|
||||||
|
try {
|
||||||
|
const ov = window.__AGUsageMonitorOverlay;
|
||||||
|
const br = window.__AGUsageMonitorBridge;
|
||||||
|
const alive = Boolean(ov && typeof ov.ensureAlive === 'function' && ov.ensureAlive());
|
||||||
|
const rpcBatch = Array.isArray(br?.rpcQueue) && br.rpcQueue.length > 0
|
||||||
|
? br.rpcQueue.splice(0, 8)
|
||||||
|
: [];
|
||||||
|
return {
|
||||||
|
alive,
|
||||||
|
bundleVersion: String(ov?.bundleVersion || ''),
|
||||||
|
bridgePort: Number(br?.port || 0),
|
||||||
|
hasToken: Boolean(br?.token),
|
||||||
|
transportMode: String(br?.transportMode || 'http'),
|
||||||
|
rpcBatch,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { alive: false, bundleVersion: '', bridgePort: 0, hasToken: false, transportMode: 'http', rpcBatch: [] };
|
||||||
|
}
|
||||||
|
})()`;
|
||||||
|
|
||||||
|
let cachedAssets = null;
|
||||||
|
let injected = 0;
|
||||||
|
let aliveCount = 0;
|
||||||
|
let relayedRpcCount = 0;
|
||||||
|
let sawCdpTransport = false;
|
||||||
|
|
||||||
|
for (const target of targets) {
|
||||||
|
try {
|
||||||
|
if (!forceReinject) {
|
||||||
|
const probeRes = await evaluateOnTarget(target.webSocketDebuggerUrl, probeExpr);
|
||||||
|
const snap = probeRes?.result?.result?.value;
|
||||||
|
if (snap && snap.alive === true) {
|
||||||
|
const snapVerNum = Number(snap.bundleVersion) || 0;
|
||||||
|
const curVerNum = Number(bundleVersion) || 0;
|
||||||
|
if (snapVerNum > 0 && curVerNum > 0 && snapVerNum > curVerNum) {
|
||||||
|
onVersionDrift?.();
|
||||||
|
aliveCount += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (snap.bundleVersion === bundleVersion) {
|
||||||
|
if (snap.bridgePort !== port || snap.hasToken !== true) {
|
||||||
|
const rebindExpr = `window.__AGUsageMonitorOverlay?.updateBridge?.(${JSON.stringify({ port, token })})`;
|
||||||
|
await evaluateOnTarget(target.webSocketDebuggerUrl, rebindExpr);
|
||||||
|
}
|
||||||
|
aliveCount += 1;
|
||||||
|
hadInjectedTargets = true;
|
||||||
|
if (snap.transportMode === 'cdp') {
|
||||||
|
sawCdpTransport = true;
|
||||||
|
}
|
||||||
|
if (Array.isArray(snap.rpcBatch) && snap.rpcBatch.length > 0) {
|
||||||
|
sawCdpTransport = true;
|
||||||
|
const rpcResults = await executeRpcBatch(snap.rpcBatch);
|
||||||
|
relayedRpcCount += rpcResults.length;
|
||||||
|
const deliverExpr = `window.__AGUsageMonitorOverlay?.deliverRpc?.(${JSON.stringify(rpcResults)})`;
|
||||||
|
await evaluateOnTarget(target.webSocketDebuggerUrl, deliverExpr);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cachedAssets) {
|
||||||
|
const [stylesCss, appJs] = await Promise.all([
|
||||||
|
readAssetFn('styles.css'),
|
||||||
|
readAssetFn('app.js'),
|
||||||
|
]);
|
||||||
|
cachedAssets = { stylesCss, appJs };
|
||||||
|
}
|
||||||
|
|
||||||
|
let initialTelemetry = null;
|
||||||
|
try {
|
||||||
|
const routeMatch = String(target.url || '').match(/\/c\/([a-f0-9-]{36})(?:\/|$)/i);
|
||||||
|
const targetConvId = routeMatch ? routeMatch[1] : '';
|
||||||
|
const initOut = await handleApiRequest('/api/telemetry', 'GET', {
|
||||||
|
conversationId: targetConvId,
|
||||||
|
range: 'today',
|
||||||
|
});
|
||||||
|
if (Number(initOut?.status || 200) === 200 && initOut?.body) {
|
||||||
|
initialTelemetry = JSON.parse(initOut.body);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 预取首帧遥测异常不阻塞注入本身
|
||||||
|
}
|
||||||
|
|
||||||
|
const bridgeConfigJson = JSON.stringify({
|
||||||
|
port,
|
||||||
|
token,
|
||||||
|
bundleVersion,
|
||||||
|
stylesCss: cachedAssets.stylesCss,
|
||||||
|
initialTelemetry,
|
||||||
|
});
|
||||||
|
const injectionScript = `(() => {\nwindow.__AGUsageMonitorBridge = ${bridgeConfigJson};\n})();\n${cachedAssets.appJs}\nBoolean(window.__AGUsageMonitorOverlay && window.__AGUsageMonitorOverlay.ensureAlive && window.__AGUsageMonitorOverlay.ensureAlive());`;
|
||||||
|
|
||||||
|
const evalRes = await evaluateOnTarget(target.webSocketDebuggerUrl, injectionScript);
|
||||||
|
if (
|
||||||
|
evalRes &&
|
||||||
|
!evalRes.error &&
|
||||||
|
!evalRes.result?.exceptionDetails &&
|
||||||
|
evalRes.result?.result?.value === true
|
||||||
|
) {
|
||||||
|
injected += 1;
|
||||||
|
aliveCount += 1;
|
||||||
|
hadInjectedTargets = true;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 单个窗口注入异常不阻断其他窗口
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cdpFallbackActive = sawCdpTransport;
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
enabled: true,
|
||||||
|
port,
|
||||||
|
targets: targets.length,
|
||||||
|
injected,
|
||||||
|
aliveCount,
|
||||||
|
relayedRpcCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncAllWindows(opts = {}) {
|
||||||
|
if (syncInFlight) {
|
||||||
|
return syncInFlight.then(() => runSyncInternal(opts));
|
||||||
|
}
|
||||||
|
syncInFlight = runSyncInternal(opts).finally(() => {
|
||||||
|
syncInFlight = null;
|
||||||
|
});
|
||||||
|
return syncInFlight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleNextPoll() {
|
||||||
|
if (stopped) return;
|
||||||
|
if (pollTimer) clearTimeout(pollTimer);
|
||||||
|
const delayMs = cdpFallbackActive ? fastPollIntervalMs : pollIntervalMs;
|
||||||
|
pollTimer = setTimeout(() => {
|
||||||
|
pollTimer = null;
|
||||||
|
syncAllWindows()
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => {
|
||||||
|
scheduleNextPoll();
|
||||||
|
});
|
||||||
|
}, delayMs);
|
||||||
|
pollTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
function start() {
|
||||||
|
stopped = false;
|
||||||
|
if (initialTimer) clearTimeout(initialTimer);
|
||||||
|
if (pollTimer) clearTimeout(pollTimer);
|
||||||
|
|
||||||
|
initialTimer = setTimeout(() => {
|
||||||
|
initialTimer = null;
|
||||||
|
syncAllWindows()
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => {
|
||||||
|
scheduleNextPoll();
|
||||||
|
});
|
||||||
|
}, 350);
|
||||||
|
initialTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stop({ disposeWindows = false } = {}) {
|
||||||
|
if (initialTimer) {
|
||||||
|
clearTimeout(initialTimer);
|
||||||
|
initialTimer = null;
|
||||||
|
}
|
||||||
|
if (pollTimer) {
|
||||||
|
clearTimeout(pollTimer);
|
||||||
|
pollTimer = null;
|
||||||
|
}
|
||||||
|
if (disposeWindows && hadInjectedTargets) {
|
||||||
|
const prevStopped = stopped;
|
||||||
|
stopped = false;
|
||||||
|
try {
|
||||||
|
const cdpPort = findActiveDevToolsPort();
|
||||||
|
if (cdpPort) {
|
||||||
|
const targets = await listMainWindowTargets(cdpPort).catch(() => []);
|
||||||
|
const disposeExpr = `(() => { try { window.__AGUsageMonitorOverlay?.dispose?.(); delete window.__AGUsageMonitorOverlay; delete window.__AGUsageMonitorBridge; return true; } catch { return false; } })()`;
|
||||||
|
for (const t of targets) {
|
||||||
|
await evaluateOnTarget(t.webSocketDebuggerUrl, disposeExpr).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
stopped = prevStopped;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stopped = true;
|
||||||
|
hadInjectedTargets = false;
|
||||||
|
if (server) {
|
||||||
|
const srv = server;
|
||||||
|
server = null;
|
||||||
|
bridgePort = 0;
|
||||||
|
await new Promise((resolve) => srv.close(() => resolve()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifySettingChanged(enabled) {
|
||||||
|
if (!enabled) {
|
||||||
|
hadInjectedTargets = true;
|
||||||
|
}
|
||||||
|
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ensureBridgeServer,
|
||||||
|
syncAllWindows,
|
||||||
|
notifySettingChanged,
|
||||||
|
start,
|
||||||
|
stop,
|
||||||
|
getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let defaultBridgeController = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动进程级默认的双栖窗口桥接控制器(幂等)。
|
||||||
|
*
|
||||||
|
* @param {Parameters<typeof createWindowBridgeController>[0]} options
|
||||||
|
*/
|
||||||
|
export function startDefaultWindowBridge(options) {
|
||||||
|
if (!defaultBridgeController) {
|
||||||
|
defaultBridgeController = createWindowBridgeController({
|
||||||
|
leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'),
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
defaultBridgeController.start();
|
||||||
|
}
|
||||||
|
return defaultBridgeController;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在用户保存设置切换 `enableWindowOverlay` 时立即同步所有打开的主窗口挂载状态。
|
||||||
|
*
|
||||||
|
* @param {boolean} enabled
|
||||||
|
*/
|
||||||
|
export function notifyWindowOverlaySetting(enabled) {
|
||||||
|
if (!defaultBridgeController) return Promise.resolve({ ok: false });
|
||||||
|
return defaultBridgeController.notifySettingChanged(enabled);
|
||||||
|
}
|
||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1794327174121">
|
<link rel="stylesheet" href="/styles.css?v=1794385831041">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1794327174121"></script>
|
<script src="/app.js?v=1794385831041"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+181
-113
@@ -3,16 +3,15 @@
|
|||||||
*
|
*
|
||||||
* 职责边界:
|
* 职责边界:
|
||||||
* - 提供前端静态资产路由(`/`、`/app.js`、`/styles.css`);
|
* - 提供前端静态资产路由(`/`、`/app.js`、`/styles.css`);
|
||||||
* - 提供本地 Loopback 受保护的 JSON API 路由:
|
* - 提供严格同端口 Loopback 受保护的 JSON API 路由:
|
||||||
* - `GET /api/telemetry`:获取实时配额、当前会话指标与历史聚合遥测数据;
|
* - `GET /api/telemetry`:获取实时配额、当前会话指标与历史聚合遥测数据;
|
||||||
* - `POST /api/settings`:保存用户偏好设置;
|
* - `POST /api/settings`:保存用户偏好设置(写入失败时返回 HTTP 500);
|
||||||
* - `POST /api/cloud-sync`:立即从 GitHub 同步最新云端价格目录与版本信息;
|
* - `POST /api/cloud-sync`:立即从 GitHub 同步最新云端价格目录与版本信息;
|
||||||
* - `POST /api/plugin-update`:一键执行插件自更新(Git / Release ZIP 双通道);
|
* - `POST /api/plugin-update`:一键执行插件自更新(Git / Release ZIP 双通道);
|
||||||
* - `GET / POST /api/diagnostics`:查询或配置流式传输诊断采样器;
|
|
||||||
* - 所有核心业务逻辑均已模块化拆分至 `./backend/*.mjs`。
|
* - 所有核心业务逻辑均已模块化拆分至 `./backend/*.mjs`。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { readFileSync, statSync, promises as fsPromises } from 'node:fs';
|
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||||
import {
|
import {
|
||||||
@@ -20,10 +19,13 @@ import {
|
|||||||
LS_ADDR,
|
LS_ADDR,
|
||||||
SETTINGS_FILE,
|
SETTINGS_FILE,
|
||||||
cloudSyncState,
|
cloudSyncState,
|
||||||
|
computeRuntimeCodeVersion,
|
||||||
|
isPlainObject,
|
||||||
loadSettings,
|
loadSettings,
|
||||||
|
normalizeTopbarCapsuleSlots,
|
||||||
|
normalizeWeeklyLimitMode,
|
||||||
saveJson,
|
saveJson,
|
||||||
} from './backend/config.mjs';
|
} from './backend/config.mjs';
|
||||||
import { diagnostics } from './backend/ls-rpc.mjs';
|
|
||||||
import {
|
import {
|
||||||
performPluginUpdate,
|
performPluginUpdate,
|
||||||
scheduleSidecarRestart,
|
scheduleSidecarRestart,
|
||||||
@@ -31,16 +33,14 @@ import {
|
|||||||
} from './backend/plugin-updater.mjs';
|
} from './backend/plugin-updater.mjs';
|
||||||
import { getCloudStatus } from './backend/pricing-catalog.mjs';
|
import { getCloudStatus } from './backend/pricing-catalog.mjs';
|
||||||
import { buildTelemetryPayload } from './backend/telemetry-builder.mjs';
|
import { buildTelemetryPayload } from './backend/telemetry-builder.mjs';
|
||||||
|
import {
|
||||||
|
notifyWindowOverlaySetting,
|
||||||
|
startDefaultWindowBridge,
|
||||||
|
} from './backend/window-bridge.mjs';
|
||||||
|
|
||||||
const app = new SidecarApp();
|
const app = new SidecarApp();
|
||||||
|
|
||||||
const bootBundleVersion = (() => {
|
const bootBundleVersion = computeRuntimeCodeVersion();
|
||||||
try {
|
|
||||||
return statSync(join(HERE, 'app.js')).mtimeMs || 0;
|
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||||
@@ -57,31 +57,43 @@ const readLocalAsync = async (relPath) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 校验请求是否来自本机回环地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||||
* 防止跨站 DNS Rebinding 或局域网未授权访问。
|
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||||
*
|
*
|
||||||
* @param {object} req
|
* @param {object} req
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
function isLocalHostRequest(req) {
|
export function isLocalHostRequest(req) {
|
||||||
if (!req?.headers) return true;
|
if (!req?.headers) return true;
|
||||||
|
const host = String(req.headers.host || '').trim().toLowerCase();
|
||||||
|
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
||||||
|
if (host && !hostMatch) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
||||||
|
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
||||||
if (secFetchSite === 'cross-site') {
|
if (secFetchSite === 'cross-site') {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const host = String(req.headers.host || '').toLowerCase();
|
if (origin) {
|
||||||
if (host && !/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host)) {
|
const originMatch = origin.match(
|
||||||
|
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||||
|
);
|
||||||
|
if (!originMatch) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const origin = String(req.headers.origin || '').toLowerCase();
|
if (hostMatch) {
|
||||||
if (
|
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||||
origin &&
|
const originPort = originMatch[3] || defaultPort;
|
||||||
!/^(?:https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?|vscode-webview:\/\/[a-z0-9._-]+)$/.test(
|
const hostPort = hostMatch[2] || defaultPort;
|
||||||
origin
|
if (originPort !== hostPort) {
|
||||||
)
|
|
||||||
) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,35 +128,26 @@ app.page(
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
app.api(
|
app.page(
|
||||||
'/styles.css',
|
'/styles.css',
|
||||||
async () =>
|
async () =>
|
||||||
new Response(await readLocalAsync('styles.css'), {
|
new Response(await readLocalAsync('styles.css'), {
|
||||||
contentType: 'text/css; charset=utf-8',
|
contentType: 'text/css; charset=utf-8',
|
||||||
headers: NO_STORE_HEADERS,
|
headers: NO_STORE_HEADERS,
|
||||||
}),
|
})
|
||||||
'GET'
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 业务数据与控制 API 路由
|
// 业务数据与控制 API 路由(辅助栏 Sidecar Webview 与主窗口双栖桥接共享同一套处理函数)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
app.api(
|
async function executeTelemetryAction(data) {
|
||||||
'/api/telemetry',
|
|
||||||
async (data, req) => {
|
|
||||||
if (!isLocalHostRequest(req)) {
|
|
||||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
|
||||||
status: 403,
|
|
||||||
contentType: 'application/json',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const rawConvId = String(
|
const rawConvId = String(
|
||||||
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
||||||
).trim();
|
).trim();
|
||||||
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
|
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
|
||||||
const force = data?.force === '1' || data?.force === true;
|
const force = data?.force === '1' || data?.force === true;
|
||||||
if (LS_ADDR !== 'test.invalid') {
|
if (LS_ADDR && LS_ADDR !== 'test.invalid') {
|
||||||
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
|
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
|
||||||
await Promise.race([
|
await Promise.race([
|
||||||
syncCloudCatalog({ force: true }).catch(() => {}),
|
syncCloudCatalog({ force: true }).catch(() => {}),
|
||||||
@@ -161,53 +164,41 @@ app.api(
|
|||||||
};
|
};
|
||||||
const payload = await buildTelemetryPayload(convId, force, filterOpts);
|
const payload = await buildTelemetryPayload(convId, force, filterOpts);
|
||||||
if (
|
if (
|
||||||
bootBundleVersion > 0 &&
|
bootBundleVersion &&
|
||||||
payload.uiBundleVersion > 0 &&
|
payload.uiBundleVersion &&
|
||||||
payload.uiBundleVersion !== bootBundleVersion
|
String(payload.uiBundleVersion) !== String(bootBundleVersion)
|
||||||
) {
|
) {
|
||||||
scheduleSidecarRestart(150);
|
scheduleSidecarRestart(150);
|
||||||
}
|
}
|
||||||
return new Response(JSON.stringify(payload), {
|
return {
|
||||||
status: 200,
|
status: 200,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
headers: { 'Cache-Control': 'no-store' },
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
});
|
body: JSON.stringify(payload),
|
||||||
},
|
};
|
||||||
'GET'
|
}
|
||||||
);
|
|
||||||
|
|
||||||
const VALID_WEEKLY_LIMIT_MODES = new Set(['official', 'tokens', 'cost']);
|
|
||||||
|
|
||||||
function sanitizePositiveSettingNumber(val, fallback) {
|
function sanitizePositiveSettingNumber(val, fallback) {
|
||||||
const num = Number(val);
|
const num = Number(val);
|
||||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
app.api('/api/settings', (data, req) => {
|
function executeSettingsAction(data) {
|
||||||
if (!isLocalHostRequest(req)) {
|
|
||||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
|
||||||
status: 403,
|
|
||||||
contentType: 'application/json',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const current = loadSettings();
|
const current = loadSettings();
|
||||||
const payload = data && typeof data === 'object' ? data : {};
|
const payload = isPlainObject(data) ? data : {};
|
||||||
const rawMode = String(payload.weeklyLimitMode || '').trim();
|
|
||||||
const updated = {
|
const updated = {
|
||||||
...current,
|
|
||||||
contextWindowLimit: sanitizePositiveSettingNumber(
|
|
||||||
payload.contextWindowLimit,
|
|
||||||
current.contextWindowLimit
|
|
||||||
),
|
|
||||||
weeklyTokenBudget: sanitizePositiveSettingNumber(
|
weeklyTokenBudget: sanitizePositiveSettingNumber(
|
||||||
payload.weeklyTokenBudget,
|
payload.weeklyTokenBudget ?? payload.weeklyTokenLimit,
|
||||||
current.weeklyTokenBudget
|
current.weeklyTokenBudget
|
||||||
),
|
),
|
||||||
weeklyCostBudget: sanitizePositiveSettingNumber(
|
weeklyCostBudget: sanitizePositiveSettingNumber(
|
||||||
payload.weeklyCostBudget,
|
payload.weeklyCostBudget,
|
||||||
current.weeklyCostBudget
|
current.weeklyCostBudget
|
||||||
),
|
),
|
||||||
weeklyLimitMode: VALID_WEEKLY_LIMIT_MODES.has(rawMode) ? rawMode : current.weeklyLimitMode,
|
weeklyLimitMode:
|
||||||
|
payload.weeklyLimitMode !== undefined
|
||||||
|
? normalizeWeeklyLimitMode(payload.weeklyLimitMode)
|
||||||
|
: current.weeklyLimitMode,
|
||||||
showUpstreamModel:
|
showUpstreamModel:
|
||||||
typeof payload.showUpstreamModel === 'boolean'
|
typeof payload.showUpstreamModel === 'boolean'
|
||||||
? payload.showUpstreamModel
|
? payload.showUpstreamModel
|
||||||
@@ -216,9 +207,116 @@ app.api('/api/settings', (data, req) => {
|
|||||||
typeof payload.autoUpdatePlugin === 'boolean'
|
typeof payload.autoUpdatePlugin === 'boolean'
|
||||||
? payload.autoUpdatePlugin
|
? payload.autoUpdatePlugin
|
||||||
: Boolean(current.autoUpdatePlugin),
|
: Boolean(current.autoUpdatePlugin),
|
||||||
|
enableWindowOverlay:
|
||||||
|
typeof payload.enableWindowOverlay === 'boolean'
|
||||||
|
? payload.enableWindowOverlay
|
||||||
|
: current.enableWindowOverlay !== false,
|
||||||
|
showTopbarMultiSession:
|
||||||
|
typeof payload.showTopbarMultiSession === 'boolean'
|
||||||
|
? payload.showTopbarMultiSession
|
||||||
|
: current.showTopbarMultiSession !== false,
|
||||||
|
topbarCapsuleSlots:
|
||||||
|
payload.topbarCapsuleSlots !== undefined
|
||||||
|
? normalizeTopbarCapsuleSlots(payload.topbarCapsuleSlots)
|
||||||
|
: normalizeTopbarCapsuleSlots(current.topbarCapsuleSlots),
|
||||||
};
|
};
|
||||||
saveJson(SETTINGS_FILE, updated);
|
if (!saveJson(SETTINGS_FILE, updated)) {
|
||||||
return updated;
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
contentType: 'application/json',
|
||||||
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
body: JSON.stringify({ ok: false, error: 'Failed to persist settings' }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (updated.enableWindowOverlay !== (current.enableWindowOverlay !== false)) {
|
||||||
|
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
updated,
|
||||||
|
body: JSON.stringify(updated),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeCloudSyncAction() {
|
||||||
|
const cloudStatus = await syncCloudCatalog({ force: true });
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
body: JSON.stringify({ ok: !cloudStatus.lastSyncError, cloudStatus }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executePluginUpdateAction() {
|
||||||
|
const result = await performPluginUpdate({ isAuto: false });
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
body: JSON.stringify({ ...result, cloudStatus: getCloudStatus() }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dispatchBridgeApiRequest(pathname, method, data) {
|
||||||
|
if (pathname === '/api/telemetry' && method === 'GET') {
|
||||||
|
return executeTelemetryAction(data);
|
||||||
|
}
|
||||||
|
if (pathname === '/api/settings' && method === 'POST') {
|
||||||
|
return executeSettingsAction(data);
|
||||||
|
}
|
||||||
|
if (pathname === '/api/cloud-sync' && method === 'POST') {
|
||||||
|
return executeCloudSyncAction();
|
||||||
|
}
|
||||||
|
if (pathname === '/api/plugin-update' && method === 'POST') {
|
||||||
|
return executePluginUpdateAction();
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: 404,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ error: 'Not found' }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
app.api(
|
||||||
|
'/api/telemetry',
|
||||||
|
async (data, req) => {
|
||||||
|
if (!isLocalHostRequest(req)) {
|
||||||
|
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||||
|
status: 403,
|
||||||
|
contentType: 'application/json',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const out = await executeTelemetryAction(data);
|
||||||
|
return new Response(out.body, {
|
||||||
|
status: out.status,
|
||||||
|
contentType: out.contentType,
|
||||||
|
headers: out.headers,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
'GET'
|
||||||
|
);
|
||||||
|
|
||||||
|
app.api('/api/settings', (data, req) => {
|
||||||
|
if (!isLocalHostRequest(req)) {
|
||||||
|
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||||
|
status: 403,
|
||||||
|
contentType: 'application/json',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const out = executeSettingsAction(data);
|
||||||
|
if (!out.ok) {
|
||||||
|
return new Response(out.body, {
|
||||||
|
status: out.status,
|
||||||
|
contentType: out.contentType,
|
||||||
|
headers: out.headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out.updated;
|
||||||
});
|
});
|
||||||
|
|
||||||
app.api('/api/cloud-sync', async (_data, req) => {
|
app.api('/api/cloud-sync', async (_data, req) => {
|
||||||
@@ -228,11 +326,11 @@ app.api('/api/cloud-sync', async (_data, req) => {
|
|||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const cloudStatus = await syncCloudCatalog({ force: true });
|
const out = await executeCloudSyncAction();
|
||||||
return new Response(JSON.stringify({ ok: !cloudStatus.lastSyncError, cloudStatus }), {
|
return new Response(out.body, {
|
||||||
status: 200,
|
status: out.status,
|
||||||
contentType: 'application/json',
|
contentType: out.contentType,
|
||||||
headers: { 'Cache-Control': 'no-store' },
|
headers: out.headers,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -243,51 +341,21 @@ app.api('/api/plugin-update', async (_data, req) => {
|
|||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const result = await performPluginUpdate({ isAuto: false });
|
const out = await executePluginUpdateAction();
|
||||||
return new Response(JSON.stringify({ ...result, cloudStatus: getCloudStatus() }), {
|
return new Response(out.body, {
|
||||||
status: 200,
|
status: out.status,
|
||||||
contentType: 'application/json',
|
contentType: out.contentType,
|
||||||
headers: { 'Cache-Control': 'no-store' },
|
headers: out.headers,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.api(
|
|
||||||
'/api/diagnostics',
|
|
||||||
(_data, req) => {
|
|
||||||
if (!isLocalHostRequest(req)) return new Response('Forbidden host or origin', { status: 403 });
|
|
||||||
return new Response(JSON.stringify(diagnostics.status()), {
|
|
||||||
contentType: 'application/json',
|
|
||||||
headers: { 'Cache-Control': 'no-store' },
|
|
||||||
});
|
|
||||||
},
|
|
||||||
'GET'
|
|
||||||
);
|
|
||||||
|
|
||||||
app.api('/api/diagnostics', (data, req) => {
|
|
||||||
if (!isLocalHostRequest(req)) return new Response('Forbidden host or origin', { status: 403 });
|
|
||||||
try {
|
|
||||||
return diagnostics.configure({
|
|
||||||
enabled: data?.enabled,
|
|
||||||
conversationId: data?.conversationId || '',
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
error:
|
|
||||||
error.message === 'invalid_diagnostic_config'
|
|
||||||
? 'Invalid diagnostic settings'
|
|
||||||
: 'Could not save diagnostic settings',
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: error.message === 'invalid_diagnostic_config' ? 400 : 500,
|
|
||||||
contentType: 'application/json',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.run();
|
app.run();
|
||||||
diagnostics.start();
|
if (LS_ADDR && LS_ADDR !== 'test.invalid') {
|
||||||
if (LS_ADDR !== 'test.invalid') {
|
|
||||||
syncCloudCatalog({ force: false }).catch(() => {});
|
syncCloudCatalog({ force: false }).catch(() => {});
|
||||||
|
startDefaultWindowBridge({
|
||||||
|
handleApiRequest: dispatchBridgeApiRequest,
|
||||||
|
readAssetFn: readLocalAsync,
|
||||||
|
bootBundleVersion,
|
||||||
|
onVersionDrift: () => scheduleSidecarRestart(150),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "usage-monitor-panel",
|
"name": "usage-monitor-panel",
|
||||||
"version": "1.4.2",
|
"version": "1.4.3",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||||
|
|||||||
@@ -5,11 +5,430 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join, resolve } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
const PANEL_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
const PANEL_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||||
|
|
||||||
|
const REGEX_PRECEDING_KEYWORDS = new Set([
|
||||||
|
'return',
|
||||||
|
'typeof',
|
||||||
|
'void',
|
||||||
|
'delete',
|
||||||
|
'throw',
|
||||||
|
'case',
|
||||||
|
'in',
|
||||||
|
'of',
|
||||||
|
'instanceof',
|
||||||
|
'new',
|
||||||
|
'yield',
|
||||||
|
'await',
|
||||||
|
]);
|
||||||
|
|
||||||
|
function isIdentStart(ch) {
|
||||||
|
if (!ch) return false;
|
||||||
|
const code = ch.charCodeAt(0);
|
||||||
|
return (
|
||||||
|
(code >= 65 && code <= 90) ||
|
||||||
|
(code >= 97 && code <= 122) ||
|
||||||
|
ch === '_' ||
|
||||||
|
ch === '$' ||
|
||||||
|
code > 127
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isIdentPart(ch) {
|
||||||
|
if (!ch) return false;
|
||||||
|
const code = ch.charCodeAt(0);
|
||||||
|
return isIdentStart(ch) || (code >= 48 && code <= 57);
|
||||||
|
}
|
||||||
|
|
||||||
|
function skipSimpleString(source, startIdx) {
|
||||||
|
const quote = source[startIdx];
|
||||||
|
let idx = startIdx + 1;
|
||||||
|
while (idx < source.length) {
|
||||||
|
const ch = source[idx];
|
||||||
|
if (ch === '\\') {
|
||||||
|
idx += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === quote) return idx + 1;
|
||||||
|
idx += 1;
|
||||||
|
}
|
||||||
|
return source.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function skipSpacesAndComments(source, startIdx) {
|
||||||
|
let idx = startIdx;
|
||||||
|
while (idx < source.length) {
|
||||||
|
const ch = source[idx];
|
||||||
|
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
|
||||||
|
idx += 1;
|
||||||
|
} else if (ch === '/' && source[idx + 1] === '/') {
|
||||||
|
idx += 2;
|
||||||
|
while (idx < source.length && source[idx] !== '\n') idx += 1;
|
||||||
|
} else if (ch === '/' && source[idx + 1] === '*') {
|
||||||
|
idx += 2;
|
||||||
|
while (idx < source.length && !(source[idx] === '*' && source[idx + 1] === '/')) idx += 1;
|
||||||
|
idx = Math.min(source.length, idx + 2);
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
function consumeTrailingStatementEnd(source, startIdx) {
|
||||||
|
let idx = startIdx;
|
||||||
|
while (idx < source.length && (source[idx] === ' ' || source[idx] === '\t')) idx += 1;
|
||||||
|
if (source[idx] === ';') {
|
||||||
|
idx += 1;
|
||||||
|
while (idx < source.length && (source[idx] === ' ' || source[idx] === '\t')) idx += 1;
|
||||||
|
}
|
||||||
|
if (source[idx] === '\r' && source[idx + 1] === '\n') {
|
||||||
|
idx += 2;
|
||||||
|
} else if (source[idx] === '\n') {
|
||||||
|
idx += 1;
|
||||||
|
}
|
||||||
|
return idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
function scanImportDeclarationEnd(source, afterImportIdx) {
|
||||||
|
let idx = afterImportIdx;
|
||||||
|
let braceDepth = 0;
|
||||||
|
let sawModuleSpecifierString = false;
|
||||||
|
while (idx < source.length) {
|
||||||
|
const ch = source[idx];
|
||||||
|
if (ch === "'" || ch === '"') {
|
||||||
|
idx = skipSimpleString(source, idx);
|
||||||
|
if (braceDepth === 0) {
|
||||||
|
sawModuleSpecifierString = true;
|
||||||
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '/' && source[idx + 1] === '/') {
|
||||||
|
idx += 2;
|
||||||
|
while (idx < source.length && source[idx] !== '\n') idx += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '/' && source[idx + 1] === '*') {
|
||||||
|
idx += 2;
|
||||||
|
while (idx < source.length && !(source[idx] === '*' && source[idx + 1] === '/')) idx += 1;
|
||||||
|
idx = Math.min(source.length, idx + 2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '{') braceDepth += 1;
|
||||||
|
else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1);
|
||||||
|
else if (ch === ';' && braceDepth === 0) {
|
||||||
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
|
} else if (ch === '\n' && braceDepth === 0 && sawModuleSpecifierString) {
|
||||||
|
return idx + 1;
|
||||||
|
}
|
||||||
|
idx += 1;
|
||||||
|
}
|
||||||
|
return source.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
function scanExportClauseEnd(source, afterExportIdx) {
|
||||||
|
let idx = afterExportIdx;
|
||||||
|
if (source[idx] === '{') {
|
||||||
|
let depth = 1;
|
||||||
|
idx += 1;
|
||||||
|
while (idx < source.length && depth > 0) {
|
||||||
|
const ch = source[idx];
|
||||||
|
if (ch === "'" || ch === '"') {
|
||||||
|
idx = skipSimpleString(source, idx);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '/' && source[idx + 1] === '/') {
|
||||||
|
idx += 2;
|
||||||
|
while (idx < source.length && source[idx] !== '\n') idx += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '/' && source[idx + 1] === '*') {
|
||||||
|
idx += 2;
|
||||||
|
while (idx < source.length && !(source[idx] === '*' && source[idx + 1] === '/')) idx += 1;
|
||||||
|
idx = Math.min(source.length, idx + 2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '{') depth += 1;
|
||||||
|
else if (ch === '}') depth -= 1;
|
||||||
|
idx += 1;
|
||||||
|
}
|
||||||
|
} else if (source[idx] === '*') {
|
||||||
|
idx += 1;
|
||||||
|
idx = skipSpacesAndComments(source, idx);
|
||||||
|
if (source.startsWith('as', idx) && !isIdentPart(source[idx + 2])) {
|
||||||
|
idx = skipSpacesAndComments(source, idx + 2);
|
||||||
|
while (idx < source.length && isIdentPart(source[idx])) idx += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const peekFrom = skipSpacesAndComments(source, idx);
|
||||||
|
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
||||||
|
const specIdx = skipSpacesAndComments(source, peekFrom + 4);
|
||||||
|
if (source[specIdx] === "'" || source[specIdx] === '"') {
|
||||||
|
idx = skipSimpleString(source, specIdx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lexical ES module syntax stripper that skips comments, single/double-quoted
|
||||||
|
* strings, template literals (including nested `${...}` expressions), and regex
|
||||||
|
* literals, removing only true top-level `import` / `export` syntax.
|
||||||
|
*
|
||||||
|
* @param {string} source
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function stripModuleSyntax(source) {
|
||||||
|
const len = source.length;
|
||||||
|
let out = '';
|
||||||
|
let i = 0;
|
||||||
|
let braceDepth = 0;
|
||||||
|
let parenDepth = 0;
|
||||||
|
const tplBraceStack = [];
|
||||||
|
let canStartRegex = true;
|
||||||
|
let prevNonWsChar = '';
|
||||||
|
|
||||||
|
function scanTemplateChunk(startAfterBacktickOrBrace) {
|
||||||
|
let idx = startAfterBacktickOrBrace;
|
||||||
|
while (idx < len) {
|
||||||
|
const ch = source[idx];
|
||||||
|
if (ch === '\\') {
|
||||||
|
idx += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '`') {
|
||||||
|
out += source.slice(startAfterBacktickOrBrace, idx + 1);
|
||||||
|
canStartRegex = false;
|
||||||
|
prevNonWsChar = '`';
|
||||||
|
return idx + 1;
|
||||||
|
}
|
||||||
|
if (ch === '$' && source[idx + 1] === '{') {
|
||||||
|
out += source.slice(startAfterBacktickOrBrace, idx + 2);
|
||||||
|
tplBraceStack.push(braceDepth);
|
||||||
|
braceDepth += 1;
|
||||||
|
canStartRegex = true;
|
||||||
|
prevNonWsChar = '{';
|
||||||
|
return idx + 2;
|
||||||
|
}
|
||||||
|
idx += 1;
|
||||||
|
}
|
||||||
|
out += source.slice(startAfterBacktickOrBrace);
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < len) {
|
||||||
|
const ch = source[i];
|
||||||
|
|
||||||
|
// Whitespace
|
||||||
|
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
|
||||||
|
out += ch;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Line comment
|
||||||
|
if (ch === '/' && source[i + 1] === '/') {
|
||||||
|
let end = i + 2;
|
||||||
|
while (end < len && source[end] !== '\n') end += 1;
|
||||||
|
out += source.slice(i, end);
|
||||||
|
i = end;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block comment
|
||||||
|
if (ch === '/' && source[i + 1] === '*') {
|
||||||
|
let end = i + 2;
|
||||||
|
while (end < len && !(source[end] === '*' && source[end + 1] === '/')) end += 1;
|
||||||
|
end = Math.min(len, end + 2);
|
||||||
|
out += source.slice(i, end);
|
||||||
|
i = end;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Single or double quoted string
|
||||||
|
if (ch === "'" || ch === '"') {
|
||||||
|
const end = skipSimpleString(source, i);
|
||||||
|
out += source.slice(i, end);
|
||||||
|
canStartRegex = false;
|
||||||
|
prevNonWsChar = ch;
|
||||||
|
i = end;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Template literal start
|
||||||
|
if (ch === '`') {
|
||||||
|
out += '`';
|
||||||
|
i = scanTemplateChunk(i + 1);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regex literal
|
||||||
|
if (ch === '/' && canStartRegex) {
|
||||||
|
let end = i + 1;
|
||||||
|
let inClass = false;
|
||||||
|
while (end < len) {
|
||||||
|
const rc = source[end];
|
||||||
|
if (rc === '\\') {
|
||||||
|
end += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (rc === '[') inClass = true;
|
||||||
|
else if (rc === ']') inClass = false;
|
||||||
|
else if (rc === '/' && !inClass) {
|
||||||
|
end += 1;
|
||||||
|
while (end < len && /[a-z]/i.test(source[end])) end += 1;
|
||||||
|
break;
|
||||||
|
} else if (rc === '\n') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
end += 1;
|
||||||
|
}
|
||||||
|
out += source.slice(i, end);
|
||||||
|
canStartRegex = false;
|
||||||
|
prevNonWsChar = '/';
|
||||||
|
i = end;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Braces & template expression resume
|
||||||
|
if (ch === '{') {
|
||||||
|
braceDepth += 1;
|
||||||
|
out += ch;
|
||||||
|
canStartRegex = true;
|
||||||
|
prevNonWsChar = ch;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ch === '}') {
|
||||||
|
if (tplBraceStack.length > 0 && braceDepth === tplBraceStack[tplBraceStack.length - 1] + 1) {
|
||||||
|
braceDepth -= 1;
|
||||||
|
tplBraceStack.pop();
|
||||||
|
out += '}';
|
||||||
|
i = scanTemplateChunk(i + 1);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
braceDepth = Math.max(0, braceDepth - 1);
|
||||||
|
out += ch;
|
||||||
|
canStartRegex = true;
|
||||||
|
prevNonWsChar = ch;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ch === '(') {
|
||||||
|
parenDepth += 1;
|
||||||
|
out += ch;
|
||||||
|
canStartRegex = true;
|
||||||
|
prevNonWsChar = ch;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ch === ')') {
|
||||||
|
parenDepth = Math.max(0, parenDepth - 1);
|
||||||
|
out += ch;
|
||||||
|
canStartRegex = false;
|
||||||
|
prevNonWsChar = ch;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identifier / keyword
|
||||||
|
if (isIdentStart(ch)) {
|
||||||
|
let end = i + 1;
|
||||||
|
while (end < len && isIdentPart(source[end])) end += 1;
|
||||||
|
const word = source.slice(i, end);
|
||||||
|
|
||||||
|
const isTrueTopLevel =
|
||||||
|
braceDepth === 0 &&
|
||||||
|
parenDepth === 0 &&
|
||||||
|
tplBraceStack.length === 0 &&
|
||||||
|
prevNonWsChar !== '.';
|
||||||
|
|
||||||
|
if (isTrueTopLevel && word === 'import') {
|
||||||
|
const afterImport = skipSpacesAndComments(source, end);
|
||||||
|
const nextCh = source[afterImport];
|
||||||
|
// Exclude `import.meta` and dynamic `import(...)`
|
||||||
|
if (nextCh && nextCh !== '.' && nextCh !== '(') {
|
||||||
|
i = scanImportDeclarationEnd(source, afterImport);
|
||||||
|
canStartRegex = true;
|
||||||
|
prevNonWsChar = ';';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTrueTopLevel && word === 'export') {
|
||||||
|
const afterExport = skipSpacesAndComments(source, end);
|
||||||
|
const nextCh = source[afterExport];
|
||||||
|
if (nextCh === '{' || nextCh === '*') {
|
||||||
|
i = scanExportClauseEnd(source, afterExport);
|
||||||
|
canStartRegex = true;
|
||||||
|
prevNonWsChar = ';';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// `export default ...`
|
||||||
|
if (source.startsWith('default', afterExport) && !isIdentPart(source[afterExport + 7])) {
|
||||||
|
const afterDefault = skipSpacesAndComments(source, afterExport + 7);
|
||||||
|
const isDecl =
|
||||||
|
(source.startsWith('function', afterDefault) && !isIdentPart(source[afterDefault + 8])) ||
|
||||||
|
(source.startsWith('class', afterDefault) && !isIdentPart(source[afterDefault + 5])) ||
|
||||||
|
(source.startsWith('async', afterDefault) && !isIdentPart(source[afterDefault + 5]));
|
||||||
|
if (isDecl) {
|
||||||
|
i = afterDefault;
|
||||||
|
canStartRegex = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out += 'void ';
|
||||||
|
i = afterDefault;
|
||||||
|
canStartRegex = true;
|
||||||
|
prevNonWsChar = 'd';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// `export const|let|var|function|class|async ...`
|
||||||
|
if (
|
||||||
|
(source.startsWith('const', afterExport) && !isIdentPart(source[afterExport + 5])) ||
|
||||||
|
(source.startsWith('let', afterExport) && !isIdentPart(source[afterExport + 3])) ||
|
||||||
|
(source.startsWith('var', afterExport) && !isIdentPart(source[afterExport + 3])) ||
|
||||||
|
(source.startsWith('function', afterExport) && !isIdentPart(source[afterExport + 8])) ||
|
||||||
|
(source.startsWith('class', afterExport) && !isIdentPart(source[afterExport + 5])) ||
|
||||||
|
(source.startsWith('async', afterExport) && !isIdentPart(source[afterExport + 5]))
|
||||||
|
) {
|
||||||
|
i = afterExport;
|
||||||
|
canStartRegex = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out += word;
|
||||||
|
canStartRegex = REGEX_PRECEDING_KEYWORDS.has(word);
|
||||||
|
prevNonWsChar = word[word.length - 1];
|
||||||
|
i = end;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Numbers & other punctuation
|
||||||
|
out += ch;
|
||||||
|
if (/[0-9\]`]/.test(ch)) {
|
||||||
|
canStartRegex = false;
|
||||||
|
} else if (/[,=:[!&|?;+\-*%~^<>]/.test(ch)) {
|
||||||
|
canStartRegex = true;
|
||||||
|
} else {
|
||||||
|
canStartRegex = false;
|
||||||
|
}
|
||||||
|
prevNonWsChar = ch;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildBundle() {
|
||||||
const cssOrder = [
|
const cssOrder = [
|
||||||
'src/styles/tokens.css',
|
'src/styles/tokens.css',
|
||||||
'src/styles/base.css',
|
'src/styles/base.css',
|
||||||
@@ -18,6 +437,7 @@ const cssOrder = [
|
|||||||
'src/styles/views-overview.css',
|
'src/styles/views-overview.css',
|
||||||
'src/styles/views-consumption.css',
|
'src/styles/views-consumption.css',
|
||||||
'src/styles/views-tables.css',
|
'src/styles/views-tables.css',
|
||||||
|
'src/styles/overlay.css',
|
||||||
];
|
];
|
||||||
|
|
||||||
const cssBundle =
|
const cssBundle =
|
||||||
@@ -52,19 +472,19 @@ const jsOrder = [
|
|||||||
'src/views/StepsDetailView.js',
|
'src/views/StepsDetailView.js',
|
||||||
'src/views/SettingsView.js',
|
'src/views/SettingsView.js',
|
||||||
'src/App.js',
|
'src/App.js',
|
||||||
|
'src/components/layout/WindowOverlayShell.js',
|
||||||
'src/main.js',
|
'src/main.js',
|
||||||
];
|
];
|
||||||
|
|
||||||
const jsBundle =
|
const innerModules = jsOrder
|
||||||
jsOrder
|
|
||||||
.map((rel) => {
|
.map((rel) => {
|
||||||
const raw = readFileSync(join(PANEL_DIR, rel), 'utf8');
|
const raw = readFileSync(join(PANEL_DIR, rel), 'utf8');
|
||||||
const stripped = raw
|
const stripped = stripModuleSyntax(raw);
|
||||||
.replace(/^import\s+[\s\S]*?from\s+['"].*?['"];?\r?\n/gm, '')
|
|
||||||
.replace(/^export\s+(?=(?:async\s+)?function|const|let|class)/gm, '');
|
|
||||||
return `// --- ${rel} ---\n${stripped.trim()}`;
|
return `// --- ${rel} ---\n${stripped.trim()}`;
|
||||||
})
|
})
|
||||||
.join('\n\n') + '\n';
|
.join('\n\n');
|
||||||
|
|
||||||
|
const jsBundle = `(() => {\n'use strict';\n\n${innerModules}\n})();\n`;
|
||||||
|
|
||||||
writeFileSync(join(PANEL_DIR, 'app.js'), jsBundle, 'utf8');
|
writeFileSync(join(PANEL_DIR, 'app.js'), jsBundle, 'utf8');
|
||||||
|
|
||||||
@@ -80,3 +500,8 @@ if (existsSync(indexHtmlPath)) {
|
|||||||
console.log(
|
console.log(
|
||||||
`Built styles.css (${cssBundle.length} bytes) and app.js (${jsBundle.length} bytes) [v=${ver}]`
|
`Built styles.css (${cssBundle.length} bytes) and app.js (${jsBundle.length} bytes) [v=${ver}]`
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
buildBundle();
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"args": ["main.mjs"],
|
"args": ["main.mjs"],
|
||||||
"restart_policy": "always",
|
"restart_policy": "always",
|
||||||
"display_name": "用量监控",
|
"display_name": "用量监控",
|
||||||
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史消耗。",
|
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
||||||
"has_web_ui": true,
|
"has_web_ui": true,
|
||||||
"ui_config": {
|
"ui_config": {
|
||||||
"display_name": "用量监控",
|
"display_name": "用量监控",
|
||||||
|
|||||||
@@ -71,6 +71,28 @@ function validCount(value) {
|
|||||||
return Number.isSafeInteger(num) && num >= 0;
|
return Number.isSafeInteger(num) && num >= 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将原始 Token 计数值安全归一化为非负整数;对负数、NaN、Infinity、空数组/对象或非法字符串统一回退为 0。
|
||||||
|
*
|
||||||
|
* @param {unknown} value
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
function safeTokenCount(value) {
|
||||||
|
if (validCount(value)) {
|
||||||
|
return Number(value);
|
||||||
|
}
|
||||||
|
if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {
|
||||||
|
return Math.floor(value);
|
||||||
|
}
|
||||||
|
if (typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value.trim())) {
|
||||||
|
const num = Number(value.trim());
|
||||||
|
if (Number.isFinite(num) && num >= 0) {
|
||||||
|
return Math.floor(num);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将 ISO-8601 时间戳解析为纳秒级 `BigInt` 时间戳。
|
* 将 ISO-8601 时间戳解析为纳秒级 `BigInt` 时间戳。
|
||||||
*
|
*
|
||||||
@@ -213,6 +235,30 @@ function classifyChatMessageChild(child) {
|
|||||||
return 'toolResults';
|
return 'toolResults';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据 `messagePrompts` 条目的来源与内容特征将其归类到对话上下文的 5 个细分通道。
|
||||||
|
*
|
||||||
|
* @param {object} m
|
||||||
|
* @returns {'toolResults'|'checkpoint'|'subagent'|'assistant'|'userInput'}
|
||||||
|
*/
|
||||||
|
function classifyMessagePrompt(m) {
|
||||||
|
const text = String(m?.prompt ?? m?.content ?? '');
|
||||||
|
const src = String(m?.source || '').toUpperCase();
|
||||||
|
if (src.includes('TOOL')) {
|
||||||
|
return 'toolResults';
|
||||||
|
}
|
||||||
|
if (text.startsWith('<CONTEXT_SUMMARY>')) {
|
||||||
|
return 'checkpoint';
|
||||||
|
}
|
||||||
|
if (text.includes('<SYSTEM_MESSAGE>')) {
|
||||||
|
return 'subagent';
|
||||||
|
}
|
||||||
|
if (src.includes('SYSTEM') || src.includes('ASSISTANT') || src.includes('MODEL')) {
|
||||||
|
return 'assistant';
|
||||||
|
}
|
||||||
|
return 'userInput';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从 `chatModel` 元数据中提取并拆解 10 大上下文 Token 构成分类:
|
* 从 `chatModel` 元数据中提取并拆解 10 大上下文 Token 构成分类:
|
||||||
* - `systemPromptTokens`:核心系统提示词
|
* - `systemPromptTokens`:核心系统提示词
|
||||||
@@ -358,6 +404,50 @@ export function extractContextBreakdown(chat) {
|
|||||||
if (gTokens > childSum) {
|
if (gTokens > childSum) {
|
||||||
userInputTokens += gTokens - childSum;
|
userInputTokens += gTokens - childSum;
|
||||||
}
|
}
|
||||||
|
} else if (messagePrompts.length > 0) {
|
||||||
|
const mpBuckets = {
|
||||||
|
userInput: 0,
|
||||||
|
assistant: 0,
|
||||||
|
toolResults: 0,
|
||||||
|
subagent: 0,
|
||||||
|
checkpoint: 0,
|
||||||
|
};
|
||||||
|
let mpSum = 0;
|
||||||
|
for (const m of messagePrompts) {
|
||||||
|
const text = String(m?.prompt ?? m?.content ?? '');
|
||||||
|
const tok =
|
||||||
|
Number.isFinite(Number(m?.numTokens)) && Number(m?.numTokens) >= 0
|
||||||
|
? Number(m.numTokens)
|
||||||
|
: estimateUtf8Tokens(text);
|
||||||
|
const bucketKey = classifyMessagePrompt(m);
|
||||||
|
mpBuckets[bucketKey] += tok;
|
||||||
|
mpSum += tok;
|
||||||
|
}
|
||||||
|
if (gTokens > 0 && mpSum > 0) {
|
||||||
|
const keys = ['userInput', 'assistant', 'toolResults', 'subagent', 'checkpoint'];
|
||||||
|
const scaled = {};
|
||||||
|
let assigned = 0;
|
||||||
|
let largestKey = 'userInput';
|
||||||
|
for (const k of keys) {
|
||||||
|
if (mpBuckets[k] > mpBuckets[largestKey]) largestKey = k;
|
||||||
|
scaled[k] = mpBuckets[k] > 0 ? Math.floor((mpBuckets[k] * gTokens) / mpSum) : 0;
|
||||||
|
assigned += scaled[k];
|
||||||
|
}
|
||||||
|
scaled[largestKey] += Math.max(0, gTokens - assigned);
|
||||||
|
userInputTokens += scaled.userInput;
|
||||||
|
assistantTokens += scaled.assistant;
|
||||||
|
toolResultsTokens += scaled.toolResults;
|
||||||
|
subagentTokens += scaled.subagent;
|
||||||
|
checkpointTokens += scaled.checkpoint;
|
||||||
|
} else if (mpSum > 0) {
|
||||||
|
userInputTokens += mpBuckets.userInput;
|
||||||
|
assistantTokens += mpBuckets.assistant;
|
||||||
|
toolResultsTokens += mpBuckets.toolResults;
|
||||||
|
subagentTokens += mpBuckets.subagent;
|
||||||
|
checkpointTokens += mpBuckets.checkpoint;
|
||||||
|
} else if (gTokens > 0) {
|
||||||
|
userInputTokens += gTokens;
|
||||||
|
}
|
||||||
} else if (gTokens > 0) {
|
} else if (gTokens > 0) {
|
||||||
userInputTokens += gTokens;
|
userInputTokens += gTokens;
|
||||||
}
|
}
|
||||||
@@ -408,15 +498,15 @@ export function extractContextBreakdown(chat) {
|
|||||||
Number.isFinite(Number(m?.numTokens)) && Number(m?.numTokens) >= 0
|
Number.isFinite(Number(m?.numTokens)) && Number(m?.numTokens) >= 0
|
||||||
? Number(m.numTokens)
|
? Number(m.numTokens)
|
||||||
: estimateUtf8Tokens(text);
|
: estimateUtf8Tokens(text);
|
||||||
const src = String(m?.source || '').toUpperCase();
|
const bucketKey = classifyMessagePrompt(m);
|
||||||
if (src.includes('TOOL')) {
|
if (bucketKey === 'toolResults') {
|
||||||
toolResultsTokens += tok;
|
toolResultsTokens += tok;
|
||||||
} else if (src.includes('SYSTEM') || src.includes('ASSISTANT') || src.includes('MODEL')) {
|
} else if (bucketKey === 'checkpoint') {
|
||||||
assistantTokens += tok;
|
|
||||||
} else if (text.startsWith('<CONTEXT_SUMMARY>')) {
|
|
||||||
checkpointTokens += tok;
|
checkpointTokens += tok;
|
||||||
} else if (text.includes('<SYSTEM_MESSAGE>')) {
|
} else if (bucketKey === 'subagent') {
|
||||||
subagentTokens += tok;
|
subagentTokens += tok;
|
||||||
|
} else if (bucketKey === 'assistant') {
|
||||||
|
assistantTokens += tok;
|
||||||
} else {
|
} else {
|
||||||
userInputTokens += tok;
|
userInputTokens += tok;
|
||||||
}
|
}
|
||||||
@@ -484,20 +574,28 @@ export function extractContextBreakdown(chat) {
|
|||||||
export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||||
const genByStep = new Map();
|
const genByStep = new Map();
|
||||||
let latestBreakdownChat = null;
|
let latestBreakdownChat = null;
|
||||||
|
let latestBreakdownStepIdx = -1;
|
||||||
|
|
||||||
for (const gm of generatorMetadata || []) {
|
for (const gm of generatorMetadata || []) {
|
||||||
if (!gm?.chatModel) {
|
if (!gm?.chatModel) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
let gmMaxIdx = -1;
|
||||||
for (const index of gm?.stepIndices || []) {
|
for (const index of gm?.stepIndices || []) {
|
||||||
genByStep.set(Number(index), gm);
|
const numIdx = Number(index);
|
||||||
|
genByStep.set(numIdx, gm);
|
||||||
|
if (Number.isFinite(numIdx) && numIdx > gmMaxIdx) {
|
||||||
|
gmMaxIdx = numIdx;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (extractContextBreakdown(gm.chatModel)) {
|
if (extractContextBreakdown(gm.chatModel)) {
|
||||||
latestBreakdownChat = gm.chatModel;
|
latestBreakdownChat = gm.chatModel;
|
||||||
|
latestBreakdownStepIdx = gmMaxIdx;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = [];
|
const result = [];
|
||||||
|
let lastCompactionStepIdx = -1;
|
||||||
|
|
||||||
rawSteps.forEach((s, index) => {
|
rawSteps.forEach((s, index) => {
|
||||||
const m = s?.metadata;
|
const m = s?.metadata;
|
||||||
@@ -513,23 +611,32 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
const gm = inlineChat || genByStep.get(Number(stepIndex));
|
const gm = inlineChat || genByStep.get(Number(stepIndex));
|
||||||
const chat = gm?.chatModel;
|
const chat = gm?.chatModel;
|
||||||
const p = s.plannerResponse || {};
|
const p = s.plannerResponse || {};
|
||||||
const isCompactionStep = s.type === 'CORTEX_STEP_TYPE_CHECKPOINT';
|
const isCompactionStep = isCheckpointStep(s);
|
||||||
|
if (isCompactionStep && Number.isFinite(Number(stepIndex))) {
|
||||||
|
lastCompactionStepIdx = Math.max(lastCompactionStepIdx, Number(stepIndex));
|
||||||
|
}
|
||||||
|
|
||||||
const inputTokens = Number(u.inputTokens || 0);
|
const inputTokens = safeTokenCount(u.inputTokens);
|
||||||
const cacheReadTokens = Number(u.cacheReadTokens || 0);
|
const cacheReadTokens = safeTokenCount(u.cacheReadTokens);
|
||||||
const outputTokens = Number(u.outputTokens || 0);
|
const outputTokens = safeTokenCount(u.outputTokens);
|
||||||
const thinkingTokens = Number(
|
const rawThinkingTok = safeTokenCount(
|
||||||
p.thinkingTokens ??
|
p.thinkingTokens ??
|
||||||
u.thinkingOutputTokens ??
|
u.thinkingOutputTokens ??
|
||||||
chat?.usage?.thinkingOutputTokens ??
|
chat?.usage?.thinkingOutputTokens ??
|
||||||
0
|
0
|
||||||
);
|
);
|
||||||
const responseTokens = Number(
|
const rawResponseTok =
|
||||||
p.responseTokens ??
|
p.responseTokens ??
|
||||||
u.responseOutputTokens ??
|
u.responseOutputTokens ??
|
||||||
chat?.usage?.responseOutputTokens ??
|
chat?.usage?.responseOutputTokens;
|
||||||
Math.max(0, outputTokens - thinkingTokens)
|
const thinkingTokens =
|
||||||
);
|
rawResponseTok !== undefined && rawResponseTok !== null
|
||||||
|
? rawThinkingTok
|
||||||
|
: Math.min(outputTokens, rawThinkingTok);
|
||||||
|
const responseTokens =
|
||||||
|
rawResponseTok !== undefined && rawResponseTok !== null
|
||||||
|
? safeTokenCount(rawResponseTok)
|
||||||
|
: Math.max(0, outputTokens - thinkingTokens);
|
||||||
|
|
||||||
const start = parseIsoMs(m.createdAt);
|
const start = parseIsoMs(m.createdAt);
|
||||||
const measuredDuration = requestDuration(
|
const measuredDuration = requestDuration(
|
||||||
@@ -642,11 +749,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// 末尾步骤上下文回填:若最后一个步骤缺少 contextBreakdown,则使用同轨迹最近一次有效的 generatorMetadata 补齐
|
// 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐
|
||||||
if (
|
if (
|
||||||
result.length > 0 &&
|
result.length > 0 &&
|
||||||
|
!result[result.length - 1].isCompactionStep &&
|
||||||
!result[result.length - 1].contextBreakdown &&
|
!result[result.length - 1].contextBreakdown &&
|
||||||
latestBreakdownChat
|
latestBreakdownChat &&
|
||||||
|
(lastCompactionStepIdx < 0 || latestBreakdownStepIdx > lastCompactionStepIdx)
|
||||||
) {
|
) {
|
||||||
const lastStep = result[result.length - 1];
|
const lastStep = result[result.length - 1];
|
||||||
const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat);
|
const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat);
|
||||||
@@ -675,7 +784,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
* - **第 3 轮(前向任意显式模型回退)**:若仍未找到,忽略 Provider 限制,向前查找最近的任意显式模型步骤;
|
* - **第 3 轮(前向任意显式模型回退)**:若仍未找到,忽略 Provider 限制,向前查找最近的任意显式模型步骤;
|
||||||
* - **第 4 轮(后向任意显式模型兜底)**:最后向后查找最近的任意显式模型步骤。
|
* - **第 4 轮(后向任意显式模型兜底)**:最后向后查找最近的任意显式模型步骤。
|
||||||
*
|
*
|
||||||
* 命中后将 `modelKey` 补齐并将 `modelSource` 标记为 `'inferred_compaction'`,同时补齐缺失的 `responseModel` 与 `modelDisplayName`。
|
* 命中后将 `modelKey` 补齐并将 `modelSource` 标记为 `'inferred_compaction'`,同时补齐同模型的 `responseModel` 与 `modelDisplayName`。
|
||||||
*
|
*
|
||||||
* @param {Array<object>} steps 已提取的步骤列表
|
* @param {Array<object>} steps 已提取的步骤列表
|
||||||
* @returns {Array<object>} 补齐压缩步骤模型归属后的步骤列表
|
* @returns {Array<object>} 补齐压缩步骤模型归属后的步骤列表
|
||||||
@@ -710,11 +819,19 @@ export function inferCompactionStepModels(steps) {
|
|||||||
return step;
|
return step;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const canDonate = (cand) => {
|
||||||
|
if (!isExplicitDonor(cand)) return false;
|
||||||
|
if (!needsModel) {
|
||||||
|
return cand.modelKey === step.modelKey && Boolean(cand.responseModel);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
let donor = null;
|
let donor = null;
|
||||||
|
|
||||||
// 第 1 轮:前向查找同 API Provider 的最近显式模型步骤
|
// 第 1 轮:前向查找同 API Provider 的最近显式模型步骤
|
||||||
for (let j = idx - 1; j >= 0; j--) {
|
for (let j = idx - 1; j >= 0; j--) {
|
||||||
if (isExplicitDonor(steps[j]) && isProviderCompatible(step, steps[j])) {
|
if (canDonate(steps[j]) && isProviderCompatible(step, steps[j])) {
|
||||||
donor = steps[j];
|
donor = steps[j];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -722,7 +839,7 @@ export function inferCompactionStepModels(steps) {
|
|||||||
// 第 2 轮:后向查找同 API Provider 的最近显式模型步骤
|
// 第 2 轮:后向查找同 API Provider 的最近显式模型步骤
|
||||||
if (!donor) {
|
if (!donor) {
|
||||||
for (let j = idx + 1; j < steps.length; j++) {
|
for (let j = idx + 1; j < steps.length; j++) {
|
||||||
if (isExplicitDonor(steps[j]) && isProviderCompatible(step, steps[j])) {
|
if (canDonate(steps[j]) && isProviderCompatible(step, steps[j])) {
|
||||||
donor = steps[j];
|
donor = steps[j];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -731,7 +848,7 @@ export function inferCompactionStepModels(steps) {
|
|||||||
// 第 3 轮:前向查找任意最近显式模型步骤
|
// 第 3 轮:前向查找任意最近显式模型步骤
|
||||||
if (!donor) {
|
if (!donor) {
|
||||||
for (let j = idx - 1; j >= 0; j--) {
|
for (let j = idx - 1; j >= 0; j--) {
|
||||||
if (isExplicitDonor(steps[j])) {
|
if (canDonate(steps[j])) {
|
||||||
donor = steps[j];
|
donor = steps[j];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -740,7 +857,7 @@ export function inferCompactionStepModels(steps) {
|
|||||||
// 第 4 轮:后向查找任意最近显式模型步骤
|
// 第 4 轮:后向查找任意最近显式模型步骤
|
||||||
if (!donor) {
|
if (!donor) {
|
||||||
for (let j = idx + 1; j < steps.length; j++) {
|
for (let j = idx + 1; j < steps.length; j++) {
|
||||||
if (isExplicitDonor(steps[j])) {
|
if (canDonate(steps[j])) {
|
||||||
donor = steps[j];
|
donor = steps[j];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -751,12 +868,29 @@ export function inferCompactionStepModels(steps) {
|
|||||||
return step;
|
return step;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const nextModelKey = needsModel ? donor.modelKey : step.modelKey;
|
||||||
|
const nextModelSource = needsModel ? 'inferred_compaction' : step.modelSource;
|
||||||
|
const donorSameModel = donor.modelKey === nextModelKey;
|
||||||
|
const nextResponseModel =
|
||||||
|
step.responseModel || (donorSameModel ? donor.responseModel || '' : '');
|
||||||
|
const nextDisplayName =
|
||||||
|
step.modelDisplayName || (donorSameModel ? donor.modelDisplayName || '' : '');
|
||||||
|
|
||||||
|
if (
|
||||||
|
nextModelKey === step.modelKey &&
|
||||||
|
nextModelSource === step.modelSource &&
|
||||||
|
nextResponseModel === (step.responseModel || '') &&
|
||||||
|
nextDisplayName === (step.modelDisplayName || '')
|
||||||
|
) {
|
||||||
|
return step;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...step,
|
...step,
|
||||||
modelKey: needsModel ? donor.modelKey : step.modelKey,
|
modelKey: nextModelKey,
|
||||||
modelSource: needsModel ? 'inferred_compaction' : step.modelSource,
|
modelSource: nextModelSource,
|
||||||
responseModel: step.responseModel || donor.responseModel || '',
|
responseModel: nextResponseModel,
|
||||||
modelDisplayName: step.modelDisplayName || donor.modelDisplayName || '',
|
modelDisplayName: nextDisplayName,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -777,6 +911,9 @@ export function inferCompactionStepModels(steps) {
|
|||||||
* @returns {object} 迁移并清洗后的步骤对象
|
* @returns {object} 迁移并清洗后的步骤对象
|
||||||
*/
|
*/
|
||||||
export function normalizeCachedStep(step) {
|
export function normalizeCachedStep(step) {
|
||||||
|
if (!step || typeof step !== 'object' || Array.isArray(step)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
if (step.modelIdentityVersion !== MODEL_IDENTITY_VERSION) {
|
if (step.modelIdentityVersion !== MODEL_IDENTITY_VERSION) {
|
||||||
const ambiguous =
|
const ambiguous =
|
||||||
!step.modelKey || step.modelKey === 'MODEL_PLACEHOLDER_M418';
|
!step.modelKey || step.modelKey === 'MODEL_PLACEHOLDER_M418';
|
||||||
@@ -811,6 +948,32 @@ export function normalizeCachedStep(step) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const safeIn = safeTokenCount(step.inputTokens);
|
||||||
|
const safeCache = safeTokenCount(step.cacheReadTokens);
|
||||||
|
const safeOut = safeTokenCount(step.outputTokens);
|
||||||
|
const safeThink = safeTokenCount(step.thinkingTokens);
|
||||||
|
const safeResp =
|
||||||
|
step.responseTokens !== undefined && step.responseTokens !== null
|
||||||
|
? safeTokenCount(step.responseTokens)
|
||||||
|
: Math.max(0, safeOut - safeThink);
|
||||||
|
|
||||||
|
if (
|
||||||
|
step.inputTokens !== safeIn ||
|
||||||
|
step.cacheReadTokens !== safeCache ||
|
||||||
|
step.outputTokens !== safeOut ||
|
||||||
|
step.thinkingTokens !== safeThink ||
|
||||||
|
step.responseTokens !== safeResp
|
||||||
|
) {
|
||||||
|
step = {
|
||||||
|
...step,
|
||||||
|
inputTokens: safeIn,
|
||||||
|
cacheReadTokens: safeCache,
|
||||||
|
outputTokens: safeOut,
|
||||||
|
thinkingTokens: safeThink,
|
||||||
|
responseTokens: safeResp,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (step.measurementVersion === MEASUREMENT_VERSION) {
|
if (step.measurementVersion === MEASUREMENT_VERSION) {
|
||||||
return step;
|
return step;
|
||||||
}
|
}
|
||||||
@@ -1190,7 +1353,23 @@ function isPlannerStep(step) {
|
|||||||
|
|
||||||
function isCheckpointStep(step) {
|
function isCheckpointStep(step) {
|
||||||
const t = String(step?.type || '').toUpperCase();
|
const t = String(step?.type || '').toUpperCase();
|
||||||
return t === 'CORTEX_STEP_TYPE_CHECKPOINT' || t === 'CHECKPOINT';
|
if (
|
||||||
|
t === 'CORTEX_STEP_TYPE_CHECKPOINT' ||
|
||||||
|
t === 'CHECKPOINT' ||
|
||||||
|
t.includes('CHECKPOINT') ||
|
||||||
|
Boolean(step?.checkpoint && typeof step.checkpoint === 'object')
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (t.includes('SYSTEM') && typeof step?.content === 'string') {
|
||||||
|
return /^\s*#\s*Resuming from a compaction\b/i.test(step.content);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAuxiliaryMetaStep(step) {
|
||||||
|
const t = String(step?.type || '').toUpperCase();
|
||||||
|
return t.includes('MEMENTO') || t.includes('EPHEMERAL');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1538,6 +1717,16 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
* signature: string
|
* signature: string
|
||||||
* } | null}
|
* } | null}
|
||||||
*/
|
*/
|
||||||
|
export function getMaxMeaningfulStepIndex(rawSteps = []) {
|
||||||
|
if (!Array.isArray(rawSteps) || rawSteps.length === 0) return -1;
|
||||||
|
let idx = rawSteps.length - 1;
|
||||||
|
while (idx > 0 && isAuxiliaryMetaStep(rawSteps[idx]) && isRawStepComplete(rawSteps[idx])) {
|
||||||
|
idx--;
|
||||||
|
}
|
||||||
|
const numId = Number(getStepStableId(rawSteps[idx], idx));
|
||||||
|
return Number.isFinite(numId) ? numId : idx;
|
||||||
|
}
|
||||||
|
|
||||||
export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackStartMs = 0) {
|
export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackStartMs = 0) {
|
||||||
if (!isRunning) return null;
|
if (!isRunning) return null;
|
||||||
if (!Array.isArray(rawSteps) || rawSteps.length === 0) {
|
if (!Array.isArray(rawSteps) || rawSteps.length === 0) {
|
||||||
@@ -1556,26 +1745,39 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
|
|
||||||
let lastPlannerIdx = -1;
|
let lastPlannerIdx = -1;
|
||||||
let lastUserIdx = -1;
|
let lastUserIdx = -1;
|
||||||
|
let lastCheckpointIdx = -1;
|
||||||
for (let i = rawSteps.length - 1; i >= 0; i--) {
|
for (let i = rawSteps.length - 1; i >= 0; i--) {
|
||||||
const st = rawSteps[i];
|
const st = rawSteps[i];
|
||||||
const t = String(st?.type || '').toUpperCase();
|
const t = String(st?.type || '').toUpperCase();
|
||||||
|
if (lastCheckpointIdx === -1 && isCheckpointStep(st)) {
|
||||||
|
lastCheckpointIdx = i;
|
||||||
|
}
|
||||||
if (lastPlannerIdx === -1 && isPlannerStep(st)) {
|
if (lastPlannerIdx === -1 && isPlannerStep(st)) {
|
||||||
lastPlannerIdx = i;
|
lastPlannerIdx = i;
|
||||||
}
|
}
|
||||||
if (lastUserIdx === -1 && t.includes('USER_INPUT')) {
|
if (lastUserIdx === -1 && t.includes('USER_INPUT')) {
|
||||||
lastUserIdx = i;
|
lastUserIdx = i;
|
||||||
}
|
}
|
||||||
if (lastPlannerIdx !== -1 && lastUserIdx !== -1) break;
|
if (lastPlannerIdx !== -1 && lastUserIdx !== -1 && lastCheckpointIdx !== -1) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
const lastIdx = rawSteps.length - 1;
|
// 忽略末尾已完成的辅助元数据步骤(如 MEMENTO / EPHEMERAL_MESSAGE),避免掩盖正在运行或刚完成的压缩/工具步骤
|
||||||
|
let lastIdx = rawSteps.length - 1;
|
||||||
|
while (lastIdx > 0 && isAuxiliaryMetaStep(rawSteps[lastIdx]) && isRawStepComplete(rawSteps[lastIdx])) {
|
||||||
|
lastIdx--;
|
||||||
|
}
|
||||||
const lastStep = rawSteps[lastIdx];
|
const lastStep = rawSteps[lastIdx];
|
||||||
const lastStepId = getStepStableId(lastStep, lastIdx);
|
const lastStepId = getStepStableId(lastStep, lastIdx);
|
||||||
const lastComplete = isRawStepComplete(lastStep);
|
const lastComplete = isRawStepComplete(lastStep);
|
||||||
|
|
||||||
// 情况 A:最后一个步骤本身尚未完成(正在流式生成或正在执行该步骤)
|
// 情况 A:最后一个有效步骤本身尚未完成(正在流式生成、正在上下文压缩或正在执行工具)
|
||||||
if (!lastComplete) {
|
if (!lastComplete) {
|
||||||
const startMs = getRawStepStartMs(lastStep) || Math.floor(fallbackStartMs || 0);
|
const prevStepEndMs =
|
||||||
|
lastIdx > 0
|
||||||
|
? getRawStepFinishMs(rawSteps[lastIdx - 1]) || getRawStepEndMs(rawSteps[lastIdx - 1])
|
||||||
|
: 0;
|
||||||
|
const startMs =
|
||||||
|
getRawStepStartMs(lastStep) || prevStepEndMs || Math.floor(fallbackStartMs || 0);
|
||||||
|
|
||||||
if (isCheckpointStep(lastStep)) {
|
if (isCheckpointStep(lastStep)) {
|
||||||
return {
|
return {
|
||||||
@@ -1643,10 +1845,10 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 末尾是未完成的工具执行步骤
|
// 末尾是未完成的工具执行步骤(仅关联压缩边界之后的最近一轮 PLANNER_RESPONSE)
|
||||||
let matchedPlannerTool = null;
|
let matchedPlannerTool = null;
|
||||||
let stepProgress = '';
|
let stepProgress = '';
|
||||||
if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx) {
|
if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx && lastPlannerIdx > lastCheckpointIdx) {
|
||||||
const pTools = getStepPlannerToolCalls(rawSteps[lastPlannerIdx]);
|
const pTools = getStepPlannerToolCalls(rawSteps[lastPlannerIdx]);
|
||||||
const toolStepsAfterPlanner = [];
|
const toolStepsAfterPlanner = [];
|
||||||
for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) {
|
for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) {
|
||||||
@@ -1669,8 +1871,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
stepProgress = '';
|
stepProgress = '';
|
||||||
}
|
}
|
||||||
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser;
|
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser;
|
||||||
const prevEndMs = lastIdx > 0 ? getRawStepFinishMs(rawSteps[lastIdx - 1]) : 0;
|
const resolvedStartMs = startMs || prevStepEndMs || 0;
|
||||||
const resolvedStartMs = startMs || prevEndMs || 0;
|
|
||||||
const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label;
|
const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1683,8 +1884,49 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 情况 B:末尾步骤已是完成态 (DONE),但整个会话仍处于 RUNNING 状态
|
// 情况 A2:最新关键里程碑是已完成态 (DONE) 的上下文压缩步骤(如 transcript.jsonl 写入的 CHECKPOINT
|
||||||
if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx) {
|
// 或 RPC 压缩刚完成正组装压缩后上下文准备下一轮推理),严禁穿透回溯到压缩前的旧工具操作
|
||||||
|
if (lastCheckpointIdx >= 0 && lastCheckpointIdx > lastPlannerIdx && lastCheckpointIdx > lastUserIdx) {
|
||||||
|
let hasPostCheckpointToolStep = false;
|
||||||
|
for (let k = lastCheckpointIdx + 1; k <= lastIdx; k++) {
|
||||||
|
const kt = String(rawSteps[k]?.type || '').toUpperCase();
|
||||||
|
if (
|
||||||
|
!isCheckpointStep(rawSteps[k]) &&
|
||||||
|
!isAuxiliaryMetaStep(rawSteps[k]) &&
|
||||||
|
!kt.includes('GENERIC') &&
|
||||||
|
!kt.includes('SYSTEM')
|
||||||
|
) {
|
||||||
|
hasPostCheckpointToolStep = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasPostCheckpointToolStep) {
|
||||||
|
const cpStep = rawSteps[lastCheckpointIdx];
|
||||||
|
const cpStepId = getStepStableId(cpStep, lastCheckpointIdx);
|
||||||
|
const prevBeforeCpMs =
|
||||||
|
lastCheckpointIdx > 0
|
||||||
|
? getRawStepFinishMs(rawSteps[lastCheckpointIdx - 1]) ||
|
||||||
|
getRawStepEndMs(rawSteps[lastCheckpointIdx - 1])
|
||||||
|
: 0;
|
||||||
|
const cpFinishMs = getRawStepFinishMs(cpStep);
|
||||||
|
const cpStartMs =
|
||||||
|
cpFinishMs ||
|
||||||
|
getRawStepStartMs(cpStep) ||
|
||||||
|
prevBeforeCpMs ||
|
||||||
|
Math.floor(fallbackStartMs || 0);
|
||||||
|
return {
|
||||||
|
phase: 'compacting',
|
||||||
|
label: '上下文压缩',
|
||||||
|
detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '',
|
||||||
|
stepProgress: '',
|
||||||
|
startedAtMs: cpStartMs,
|
||||||
|
signature: cpFinishMs > 0 ? `compacting-done:${cpStepId}` : `compacting:${cpStepId}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 情况 B:末尾步骤已是完成态 (DONE),但整个会话仍处于 RUNNING 状态(仅在压缩边界之后匹配上一轮 PLANNER_RESPONSE)
|
||||||
|
if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx && lastPlannerIdx > lastCheckpointIdx) {
|
||||||
const plannerStep = rawSteps[lastPlannerIdx];
|
const plannerStep = rawSteps[lastPlannerIdx];
|
||||||
const plannerStepId = getStepStableId(plannerStep, lastPlannerIdx);
|
const plannerStepId = getStepStableId(plannerStep, lastPlannerIdx);
|
||||||
const pTools = getStepPlannerToolCalls(plannerStep);
|
const pTools = getStepPlannerToolCalls(plannerStep);
|
||||||
|
|||||||
+19
-14
@@ -51,6 +51,22 @@ export const App = defineComponent({
|
|||||||
stageEl,
|
stageEl,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
function syncStepsBadge() {
|
||||||
|
const uiSt = uiStore.getState();
|
||||||
|
const scopeForBadge = uiSt.activeView === 'steps' ? uiSt.selectedAgentScope : 'all';
|
||||||
|
const { scopedConv } = resolveScopedConversation(
|
||||||
|
telemetryStore.getState().telemetry,
|
||||||
|
scopeForBadge,
|
||||||
|
uiSt.ctxInspectorAgentId
|
||||||
|
);
|
||||||
|
const stepCount = scopedConv?.stepCount ?? 0;
|
||||||
|
topPillNav.setProps({
|
||||||
|
items: VIEW_TABS.map((t) =>
|
||||||
|
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const unsubUi = uiStore.subscribe(
|
const unsubUi = uiStore.subscribe(
|
||||||
(st) => st.activeView,
|
(st) => st.activeView,
|
||||||
(activeView) => {
|
(activeView) => {
|
||||||
@@ -65,24 +81,13 @@ export const App = defineComponent({
|
|||||||
} else if (activeView === 'steps') {
|
} else if (activeView === 'steps') {
|
||||||
stepsView.refs?.stepsScroll?.refresh();
|
stepsView.refs?.stepsScroll?.refresh();
|
||||||
stepsView.refs?.modelsScroll?.refresh();
|
stepsView.refs?.modelsScroll?.refresh();
|
||||||
|
} else if (activeView === 'settings') {
|
||||||
|
settingsView.refs?.viewScrollbar?.refresh();
|
||||||
}
|
}
|
||||||
|
syncStepsBadge();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
function syncStepsBadge() {
|
|
||||||
const { scopedConv } = resolveScopedConversation(
|
|
||||||
telemetryStore.getState().telemetry,
|
|
||||||
uiStore.getState().selectedAgentScope,
|
|
||||||
uiStore.getState().ctxInspectorAgentId
|
|
||||||
);
|
|
||||||
const stepCount = scopedConv?.stepCount ?? 0;
|
|
||||||
topPillNav.setProps({
|
|
||||||
items: VIEW_TABS.map((t) =>
|
|
||||||
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const unsubStepCount = telemetryStore.subscribe(
|
const unsubStepCount = telemetryStore.subscribe(
|
||||||
(st) => ({
|
(st) => ({
|
||||||
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
|
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
|
||||||
|
|||||||
@@ -10,17 +10,22 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core
|
|||||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||||
|
|
||||||
|
let chartUidCounter = 0;
|
||||||
|
|
||||||
|
function safeSlotTokens(v) {
|
||||||
|
const n = Number(v);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。
|
* 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。
|
||||||
* 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平,
|
* 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平,
|
||||||
* 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。
|
* 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。
|
||||||
*
|
*
|
||||||
* @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组
|
* @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组(长度 >= 2)
|
||||||
* @returns {string} SVG `<path>` 的 `d` 属性字符串
|
* @returns {string} SVG `<path>` 的 `d` 属性字符串
|
||||||
*/
|
*/
|
||||||
function buildSmoothSplinePath(points) {
|
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)}`;
|
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
|
||||||
for (let i = 0; i < points.length - 1; i++) {
|
for (let i = 0; i < points.length - 1; i++) {
|
||||||
const p0 = points[i];
|
const p0 = points[i];
|
||||||
@@ -77,10 +82,11 @@ export function createTrendAreaChart() {
|
|||||||
svg.setAttribute('class', 'trend-svg');
|
svg.setAttribute('class', 'trend-svg');
|
||||||
svg.setAttribute('aria-hidden', 'true');
|
svg.setAttribute('aria-hidden', 'true');
|
||||||
|
|
||||||
// 垂直线性渐变
|
// 垂直线性渐变(每实例独立 ID,避免多图表挂载时 SVG url(#...) 冲突)
|
||||||
|
const gradId = `trend-area-grad-${++chartUidCounter}`;
|
||||||
const defs = document.createElementNS(SVG_NS, 'defs');
|
const defs = document.createElementNS(SVG_NS, 'defs');
|
||||||
const grad = document.createElementNS(SVG_NS, 'linearGradient');
|
const grad = document.createElementNS(SVG_NS, 'linearGradient');
|
||||||
grad.setAttribute('id', 'trend-area-grad');
|
grad.setAttribute('id', gradId);
|
||||||
grad.setAttribute('x1', '0');
|
grad.setAttribute('x1', '0');
|
||||||
grad.setAttribute('y1', '0');
|
grad.setAttribute('y1', '0');
|
||||||
grad.setAttribute('x2', '0');
|
grad.setAttribute('x2', '0');
|
||||||
@@ -119,7 +125,7 @@ export function createTrendAreaChart() {
|
|||||||
svg.appendChild(vGridGroup);
|
svg.appendChild(vGridGroup);
|
||||||
|
|
||||||
const areaPath = document.createElementNS(SVG_NS, 'path');
|
const areaPath = document.createElementNS(SVG_NS, 'path');
|
||||||
areaPath.setAttribute('fill', 'url(#trend-area-grad)');
|
areaPath.setAttribute('fill', `url(#${gradId})`);
|
||||||
svg.appendChild(areaPath);
|
svg.appendChild(areaPath);
|
||||||
|
|
||||||
const linePath = document.createElementNS(SVG_NS, 'path');
|
const linePath = document.createElementNS(SVG_NS, 'path');
|
||||||
@@ -202,18 +208,20 @@ export function createTrendAreaChart() {
|
|||||||
patchAttr(tooltipEl, 'hidden', false);
|
patchAttr(tooltipEl, 'hidden', false);
|
||||||
|
|
||||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||||
patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`);
|
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`);
|
||||||
patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`);
|
const slotTok = safeSlotTokens(slot.tokens);
|
||||||
|
patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`);
|
||||||
|
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
|
||||||
patchText(
|
patchText(
|
||||||
tipCostEl,
|
tipCostEl,
|
||||||
formatUsd(Number(slot.costUsd || 0), {
|
formatUsd(slotCost, {
|
||||||
unpricedCalls: slot.unpricedCalls,
|
unpricedCalls: slot.unpricedCalls,
|
||||||
precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1,
|
precise: slotCost > 0 && slotCost < 0.1,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
const hasSubBreakdown =
|
const hasSubBreakdown =
|
||||||
Number(slot.tokens || 0) > 0 &&
|
slotTok > 0 &&
|
||||||
(slot.inputTokens !== undefined ||
|
(slot.inputTokens !== undefined ||
|
||||||
slot.cacheReadTokens !== undefined ||
|
slot.cacheReadTokens !== undefined ||
|
||||||
slot.outputTokens !== undefined);
|
slot.outputTokens !== undefined);
|
||||||
@@ -221,7 +229,7 @@ export function createTrendAreaChart() {
|
|||||||
if (hasSubBreakdown) {
|
if (hasSubBreakdown) {
|
||||||
patchText(
|
patchText(
|
||||||
tipSubEl,
|
tipSubEl,
|
||||||
`入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}`
|
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,7 +276,7 @@ export function createTrendAreaChart() {
|
|||||||
*/
|
*/
|
||||||
function update(series = []) {
|
function update(series = []) {
|
||||||
const slots =
|
const slots =
|
||||||
Array.isArray(series) && series.length >= 2
|
Array.isArray(series) && series.length >= 1
|
||||||
? series
|
? series
|
||||||
: [
|
: [
|
||||||
{ label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 },
|
{ label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 },
|
||||||
@@ -281,7 +289,7 @@ export function createTrendAreaChart() {
|
|||||||
let maxTokens = 0;
|
let maxTokens = 0;
|
||||||
let peakIdx = 0;
|
let peakIdx = 0;
|
||||||
for (let i = 0; i < slots.length; i++) {
|
for (let i = 0; i < slots.length; i++) {
|
||||||
const t = Number(slots[i].tokens || 0);
|
const t = safeSlotTokens(slots[i]?.tokens);
|
||||||
if (t >= maxTokens) {
|
if (t >= maxTokens) {
|
||||||
maxTokens = t;
|
maxTokens = t;
|
||||||
peakIdx = i;
|
peakIdx = i;
|
||||||
@@ -289,22 +297,32 @@ export function createTrendAreaChart() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const denom = Math.max(1, maxTokens);
|
const denom = Math.max(1, maxTokens);
|
||||||
|
const isSingle = slots.length === 1;
|
||||||
const pts = slots.map((s, idx) => {
|
const pts = slots.map((s, idx) => {
|
||||||
const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
|
const tok = safeSlotTokens(s?.tokens);
|
||||||
const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0;
|
const x = isSingle ? (LEFT_X + RIGHT_X) / 2 : LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
|
||||||
|
const ratio = maxTokens > 0 ? tok / denom : 0;
|
||||||
const y = BOTTOM_Y - ratio * SPAN_Y;
|
const y = BOTTOM_Y - ratio * SPAN_Y;
|
||||||
return { x, y, tokens: Number(s.tokens || 0) };
|
return { x, y, tokens: tok };
|
||||||
});
|
});
|
||||||
currentPts = pts;
|
currentPts = pts;
|
||||||
|
|
||||||
const sig = slots
|
const sig = slots
|
||||||
.map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`)
|
.map((s) => `${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`)
|
||||||
.join('|');
|
.join('|');
|
||||||
|
|
||||||
if (sig !== lastRenderSig) {
|
if (sig !== lastRenderSig) {
|
||||||
lastRenderSig = sig;
|
lastRenderSig = sig;
|
||||||
const lineD = buildSmoothSplinePath(pts);
|
let lineD;
|
||||||
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
let areaD;
|
||||||
|
if (isSingle) {
|
||||||
|
const yStr = pts[0].y.toFixed(1);
|
||||||
|
lineD = `M ${LEFT_X.toFixed(1)} ${yStr} L ${RIGHT_X.toFixed(1)} ${yStr}`;
|
||||||
|
areaD = `${lineD} L ${RIGHT_X.toFixed(1)} ${BOTTOM_Y} L ${LEFT_X.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||||
|
} else {
|
||||||
|
lineD = buildSmoothSplinePath(pts);
|
||||||
|
areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||||
|
}
|
||||||
patchAttr(linePath, 'd', lineD);
|
patchAttr(linePath, 'd', lineD);
|
||||||
patchAttr(areaPath, 'd', areaD);
|
patchAttr(areaPath, 'd', areaD);
|
||||||
|
|
||||||
@@ -329,8 +347,8 @@ export function createTrendAreaChart() {
|
|||||||
vGridGroup.appendChild(vLine);
|
vGridGroup.appendChild(vLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
const isFirst = i === 0;
|
const isFirst = !isSingle && i === 0;
|
||||||
const isLast = i === tickIndices.length - 1;
|
const isLast = !isSingle && i === tickIndices.length - 1;
|
||||||
const pct = (pt.x / VIEW_W) * 100;
|
const pct = (pt.x / VIEW_W) * 100;
|
||||||
const tickEl = h('span', {
|
const tickEl = h('span', {
|
||||||
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
|
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
|
||||||
@@ -371,7 +389,9 @@ export function createTrendAreaChart() {
|
|||||||
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100));
|
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100));
|
||||||
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
||||||
|
|
||||||
if (hoveredIdx >= 0 && hoveredIdx < slots.length) {
|
if (hoveredIdx >= slots.length) {
|
||||||
|
clearHover();
|
||||||
|
} else if (hoveredIdx >= 0) {
|
||||||
showHoverAtIndex(hoveredIdx);
|
showHoverAtIndex(hoveredIdx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,22 +113,64 @@ export const TopSessionHeader = defineComponent({
|
|||||||
lastActiveCascadeId = currentCascadeId;
|
lastActiveCascadeId = currentCascadeId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const actConv = telemetry?.activeConversation;
|
||||||
const convs = telemetry?.conversations || [];
|
const convs = telemetry?.conversations || [];
|
||||||
const latestTitle = convs[0]?.title ? `最新 (${convs[0].title})` : '跟随最新会话';
|
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||||
|
const hostMatchedConv = hostRouteId
|
||||||
|
? convs.find((c) => c.cascadeId === hostRouteId) ||
|
||||||
|
(actConv?.cascadeId === hostRouteId ? actConv : null)
|
||||||
|
: null;
|
||||||
|
const defaultOptLabel = hostRouteId
|
||||||
|
? hostMatchedConv?.title
|
||||||
|
? `当前窗口 (${hostMatchedConv.title})`
|
||||||
|
: `当前窗口 (${hostRouteId.slice(0, 8)})`
|
||||||
|
: convs[0]?.title
|
||||||
|
? `最新 (${convs[0].title})`
|
||||||
|
: '跟随最新会话';
|
||||||
|
const defaultOptMeta = hostRouteId
|
||||||
|
? hostMatchedConv
|
||||||
|
? formatConvOptionMeta({
|
||||||
|
stepCount: hostMatchedConv.stepCount,
|
||||||
|
subagentCount: hostMatchedConv.subagentCount,
|
||||||
|
totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents,
|
||||||
|
})
|
||||||
|
: ''
|
||||||
|
: convs[0]
|
||||||
|
? formatConvOptionMeta(convs[0])
|
||||||
|
: '';
|
||||||
const options = [
|
const options = [
|
||||||
{ value: '', label: latestTitle, meta: convs[0] ? formatConvOptionMeta(convs[0]) : '' },
|
{ value: '', label: defaultOptLabel, meta: defaultOptMeta },
|
||||||
...convs.map((c) => ({
|
...convs.map((c) => ({
|
||||||
value: c.cascadeId,
|
value: c.cascadeId,
|
||||||
label: c.title || c.cascadeId.slice(0, 8),
|
label: c.title || c.cascadeId.slice(0, 8),
|
||||||
meta: formatConvOptionMeta(c),
|
meta: formatConvOptionMeta(c),
|
||||||
})),
|
})),
|
||||||
];
|
];
|
||||||
|
const lockedId = telSt.selectedConversationId;
|
||||||
|
if (lockedId && !convs.some((c) => c.cascadeId === lockedId)) {
|
||||||
|
const isLoadedLocked = actConv?.cascadeId === lockedId;
|
||||||
|
const lockedTitle =
|
||||||
|
isLoadedLocked && actConv?.title
|
||||||
|
? actConv.title
|
||||||
|
: `已锁定会话 (${String(lockedId).slice(0, 8)})`;
|
||||||
|
const lockedMeta = isLoadedLocked
|
||||||
|
? formatConvOptionMeta({
|
||||||
|
stepCount: actConv.stepCount,
|
||||||
|
subagentCount: actConv.subagentCount,
|
||||||
|
totalStepCount: actConv.totalStepsAllAgents,
|
||||||
|
})
|
||||||
|
: '已锁定';
|
||||||
|
options.splice(1, 0, {
|
||||||
|
value: lockedId,
|
||||||
|
label: lockedTitle,
|
||||||
|
meta: lockedMeta,
|
||||||
|
});
|
||||||
|
}
|
||||||
convSelect.setProps({
|
convSelect.setProps({
|
||||||
modelValue: telSt.selectedConversationId,
|
modelValue: telSt.selectedConversationId,
|
||||||
options,
|
options,
|
||||||
});
|
});
|
||||||
|
|
||||||
const actConv = telemetry?.activeConversation;
|
|
||||||
const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0);
|
const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0);
|
||||||
const aggregated = actConv?.aggregated;
|
const aggregated = actConv?.aggregated;
|
||||||
|
|
||||||
@@ -211,6 +253,7 @@ export const TopSessionHeader = defineComponent({
|
|||||||
const unsubTelemetry = telemetryStore.subscribe(
|
const unsubTelemetry = telemetryStore.subscribe(
|
||||||
(st) => ({
|
(st) => ({
|
||||||
selectedConversationId: st.selectedConversationId,
|
selectedConversationId: st.selectedConversationId,
|
||||||
|
hostRouteConversationId: st.hostRouteConversationId,
|
||||||
syncState: st.syncState,
|
syncState: st.syncState,
|
||||||
telemetry: st.telemetry,
|
telemetry: st.telemetry,
|
||||||
}),
|
}),
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,14 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { defineComponent } from '../../core/component.js';
|
import { defineComponent } from '../../core/component.js';
|
||||||
import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js';
|
import {
|
||||||
|
h,
|
||||||
|
isEventInside,
|
||||||
|
patchAttr,
|
||||||
|
patchClasses,
|
||||||
|
patchKeyedList,
|
||||||
|
patchText,
|
||||||
|
} from '../../core/domPatch.js';
|
||||||
import { formatCompactDateTime } from '../../core/formatters.js';
|
import { formatCompactDateTime } from '../../core/formatters.js';
|
||||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
|
|
||||||
@@ -118,9 +125,9 @@ export const CustomDateTimePicker = defineComponent({
|
|||||||
function adjustTime(part, delta) {
|
function adjustTime(part, delta) {
|
||||||
const cur = new Date(getProps().modelValue || Date.now());
|
const cur = new Date(getProps().modelValue || Date.now());
|
||||||
if (part === 'hour') {
|
if (part === 'hour') {
|
||||||
cur.setHours((cur.getHours() + delta + 24) % 24);
|
cur.setHours(cur.getHours() + delta);
|
||||||
} else {
|
} else {
|
||||||
cur.setMinutes((cur.getMinutes() + delta + 60) % 60);
|
cur.setMinutes(cur.getMinutes() + delta);
|
||||||
}
|
}
|
||||||
const nextMs = cur.getTime();
|
const nextMs = cur.getTime();
|
||||||
viewYear = cur.getFullYear();
|
viewYear = cur.getFullYear();
|
||||||
@@ -251,7 +258,7 @@ export const CustomDateTimePicker = defineComponent({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleDocClick = (e) => {
|
const handleDocClick = (e) => {
|
||||||
if (isOpen && !rootEl.contains(e.target)) {
|
if (isOpen && !isEventInside(e, rootEl)) {
|
||||||
togglePopover(false);
|
togglePopover(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -267,16 +274,6 @@ export const CustomDateTimePicker = defineComponent({
|
|||||||
el: rootEl,
|
el: rootEl,
|
||||||
refs: { triggerBtn, triggerText, popoverEl, daysGrid, hourValSpan, minValSpan },
|
refs: { triggerBtn, triggerText, popoverEl, daysGrid, hourValSpan, minValSpan },
|
||||||
onPropsChange: syncDisplay,
|
onPropsChange: syncDisplay,
|
||||||
getValue: () => Number(getProps().modelValue || 0),
|
|
||||||
methods: {
|
|
||||||
open: () => togglePopover(true),
|
|
||||||
close: () => togglePopover(false),
|
|
||||||
selectDayByOffset: (daysDelta) => {
|
|
||||||
const cur = new Date(getProps().modelValue || Date.now());
|
|
||||||
cur.setDate(cur.getDate() + daysDelta);
|
|
||||||
emit('update:modelValue', cur.getTime());
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { createSvgIcon } from '../../icons/SvgIcon.js';
|
|||||||
|
|
||||||
export const CustomNumberInput = defineComponent({
|
export const CustomNumberInput = defineComponent({
|
||||||
name: 'CustomNumberInput',
|
name: 'CustomNumberInput',
|
||||||
setup({ getProps, emit }) {
|
setup({ getProps, setProps, emit }) {
|
||||||
function clampValue(raw) {
|
function clampValue(raw) {
|
||||||
const { min = -Infinity, max = Infinity, precision = 0 } = getProps();
|
const { min = -Infinity, max = Infinity, precision = 0 } = getProps();
|
||||||
const num = Number(raw);
|
const num = Number(raw);
|
||||||
@@ -27,6 +27,7 @@ export const CustomNumberInput = defineComponent({
|
|||||||
const next = clampValue(current + direction * step * multiplier);
|
const next = clampValue(current + direction * step * multiplier);
|
||||||
syncFieldDisplay(next);
|
syncFieldDisplay(next);
|
||||||
if (next !== current) {
|
if (next !== current) {
|
||||||
|
setProps({ modelValue: next });
|
||||||
emit('update:modelValue', next);
|
emit('update:modelValue', next);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -80,11 +81,22 @@ export const CustomNumberInput = defineComponent({
|
|||||||
});
|
});
|
||||||
|
|
||||||
function commitManualInput() {
|
function commitManualInput() {
|
||||||
const rawText = String(textField.value || '').replace(/[^0-9.-]/g, '');
|
const raw = String(textField.value ?? '').trim();
|
||||||
const next = clampValue(rawText);
|
if (!raw || !/\d/.test(raw)) {
|
||||||
|
syncFieldDisplay(getProps().modelValue);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const cleaned = raw.replace(/[^0-9.-]/g, '');
|
||||||
|
const parsed = Number(cleaned);
|
||||||
|
if (!Number.isFinite(parsed)) {
|
||||||
|
syncFieldDisplay(getProps().modelValue);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const next = clampValue(parsed);
|
||||||
const prev = Number(getProps().modelValue);
|
const prev = Number(getProps().modelValue);
|
||||||
syncFieldDisplay(next);
|
syncFieldDisplay(next);
|
||||||
if (next !== prev) {
|
if (next !== prev) {
|
||||||
|
setProps({ modelValue: next });
|
||||||
emit('update:modelValue', next);
|
emit('update:modelValue', next);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -107,10 +119,8 @@ export const CustomNumberInput = defineComponent({
|
|||||||
el: rootEl,
|
el: rootEl,
|
||||||
refs: { decBtn, incBtn, textField },
|
refs: { decBtn, incBtn, textField },
|
||||||
onPropsChange: () => syncFieldDisplay(),
|
onPropsChange: () => syncFieldDisplay(),
|
||||||
getValue: () => clampValue(textField.value),
|
|
||||||
methods: {
|
methods: {
|
||||||
stepUp: (mult = 1) => applyStep(1, mult),
|
commit: () => commitManualInput(),
|
||||||
stepDown: (mult = 1) => applyStep(-1, mult),
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview Bespoke custom scrollbar component (零原生滚动条).
|
* @fileoverview Bespoke custom scrollbar component (零原生滚动条).
|
||||||
* Hides native OS scrollbars completely and renders a precision 4px floating
|
* Hides native OS scrollbars completely and renders a precision 4px floating
|
||||||
* rail + GPU-translated thumb with drag, track-jump, and modelValue ratio emit.
|
* rail + GPU-translated thumb with drag and track-jump support.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { defineComponent } from '../../core/component.js';
|
import { defineComponent } from '../../core/component.js';
|
||||||
@@ -9,7 +9,7 @@ import { h, patchClasses, patchStyleVar } from '../../core/domPatch.js';
|
|||||||
|
|
||||||
export const CustomScrollbar = defineComponent({
|
export const CustomScrollbar = defineComponent({
|
||||||
name: 'CustomScrollbar',
|
name: 'CustomScrollbar',
|
||||||
setup({ getProps, emit, onCleanup }) {
|
setup({ getProps, onCleanup }) {
|
||||||
const contentEl = getProps().contentEl || h('div');
|
const contentEl = getProps().contentEl || h('div');
|
||||||
contentEl.classList.add('custom-scroll-content');
|
contentEl.classList.add('custom-scroll-content');
|
||||||
|
|
||||||
@@ -61,11 +61,6 @@ export const CustomScrollbar = defineComponent({
|
|||||||
|
|
||||||
function onContentScroll() {
|
function onContentScroll() {
|
||||||
syncThumb();
|
syncThumb();
|
||||||
const overflow = (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0);
|
|
||||||
if (overflow > 1) {
|
|
||||||
const ratio = +Math.max(0, Math.min(1, (contentEl.scrollTop || 0) / overflow)).toFixed(3);
|
|
||||||
emit('update:modelValue', ratio);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onDocMouseMove(e) {
|
function onDocMouseMove(e) {
|
||||||
@@ -163,12 +158,6 @@ export const CustomScrollbar = defineComponent({
|
|||||||
refresh() {
|
refresh() {
|
||||||
scheduleSyncThumb();
|
scheduleSyncThumb();
|
||||||
},
|
},
|
||||||
scrollToRatio(ratio) {
|
|
||||||
const r = Math.max(0, Math.min(1, Number(ratio || 0)));
|
|
||||||
const overflow = Math.max(0, (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0));
|
|
||||||
contentEl.scrollTop = Math.round(r * overflow);
|
|
||||||
syncThumb();
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -4,12 +4,19 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { defineComponent } from '../../core/component.js';
|
import { defineComponent } from '../../core/component.js';
|
||||||
import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js';
|
import {
|
||||||
|
h,
|
||||||
|
isEventInside,
|
||||||
|
patchAttr,
|
||||||
|
patchClasses,
|
||||||
|
patchKeyedList,
|
||||||
|
patchText,
|
||||||
|
} from '../../core/domPatch.js';
|
||||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
|
|
||||||
export const CustomSelect = defineComponent({
|
export const CustomSelect = defineComponent({
|
||||||
name: 'CustomSelect',
|
name: 'CustomSelect',
|
||||||
setup({ getProps, emit, onCleanup }) {
|
setup({ getProps, setProps, emit, onCleanup }) {
|
||||||
let isOpen = false;
|
let isOpen = false;
|
||||||
let focusedIndex = -1;
|
let focusedIndex = -1;
|
||||||
|
|
||||||
@@ -67,6 +74,7 @@ export const CustomSelect = defineComponent({
|
|||||||
const prevVal = getProps().modelValue;
|
const prevVal = getProps().modelValue;
|
||||||
toggleOpen(false);
|
toggleOpen(false);
|
||||||
if (option.value !== prevVal) {
|
if (option.value !== prevVal) {
|
||||||
|
setProps({ modelValue: option.value });
|
||||||
emit('update:modelValue', option.value);
|
emit('update:modelValue', option.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,6 +90,7 @@ export const CustomSelect = defineComponent({
|
|||||||
} else {
|
} else {
|
||||||
focusedIndex = (focusedIndex + 1) % opts.length;
|
focusedIndex = (focusedIndex + 1) % opts.length;
|
||||||
renderMenuOptions();
|
renderMenuOptions();
|
||||||
|
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||||
}
|
}
|
||||||
} else if (e.key === 'ArrowUp') {
|
} else if (e.key === 'ArrowUp') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -90,6 +99,7 @@ export const CustomSelect = defineComponent({
|
|||||||
} else {
|
} else {
|
||||||
focusedIndex = (focusedIndex - 1 + opts.length) % opts.length;
|
focusedIndex = (focusedIndex - 1 + opts.length) % opts.length;
|
||||||
renderMenuOptions();
|
renderMenuOptions();
|
||||||
|
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||||
}
|
}
|
||||||
} else if (e.key === 'Enter' && isOpen) {
|
} else if (e.key === 'Enter' && isOpen) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -150,17 +160,17 @@ export const CustomSelect = defineComponent({
|
|||||||
if (icon) {
|
if (icon) {
|
||||||
patchSvgIcon(leadIcon, icon);
|
patchSvgIcon(leadIcon, icon);
|
||||||
}
|
}
|
||||||
const selectedOpt =
|
const matchedOpt = options.find((o) => o.value === modelValue);
|
||||||
options.find((o) => o.value === modelValue) ||
|
const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined);
|
||||||
(!modelValue ? options[0] : undefined);
|
const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder;
|
||||||
patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder);
|
patchText(triggerLabel, selectedOpt ? selectedOpt.label : fallbackText);
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
renderMenuOptions();
|
renderMenuOptions();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleDocClick = (e) => {
|
const handleDocClick = (e) => {
|
||||||
if (isOpen && !rootEl.contains(e.target)) {
|
if (isOpen && !isEventInside(e, rootEl)) {
|
||||||
toggleOpen(false);
|
toggleOpen(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -176,14 +186,8 @@ export const CustomSelect = defineComponent({
|
|||||||
el: rootEl,
|
el: rootEl,
|
||||||
refs: { triggerBtn, triggerLabel, menuEl },
|
refs: { triggerBtn, triggerLabel, menuEl },
|
||||||
onPropsChange: syncTriggerAndMenu,
|
onPropsChange: syncTriggerAndMenu,
|
||||||
getValue: () => getProps().modelValue,
|
|
||||||
methods: {
|
methods: {
|
||||||
open: () => toggleOpen(true),
|
|
||||||
close: () => toggleOpen(false),
|
close: () => toggleOpen(false),
|
||||||
selectByValue: (val) => {
|
|
||||||
const found = (getProps().options || []).find((o) => o.value === val);
|
|
||||||
if (found) chooseOption(found);
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../cor
|
|||||||
|
|
||||||
export const SegmentedControl = defineComponent({
|
export const SegmentedControl = defineComponent({
|
||||||
name: 'SegmentedControl',
|
name: 'SegmentedControl',
|
||||||
setup({ getProps, emit }) {
|
setup({ getProps, setProps, emit }) {
|
||||||
const rootEl = h('div', {
|
const rootEl = h('div', {
|
||||||
className: 'segmented',
|
className: 'segmented',
|
||||||
role: 'group',
|
role: 'group',
|
||||||
@@ -27,6 +27,7 @@ export const SegmentedControl = defineComponent({
|
|||||||
onClick: (e) => {
|
onClick: (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (getProps().modelValue !== opt.value) {
|
if (getProps().modelValue !== opt.value) {
|
||||||
|
setProps({ modelValue: opt.value });
|
||||||
emit('update:modelValue', opt.value);
|
emit('update:modelValue', opt.value);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,15 +8,6 @@ export function defineComponent({ name, setup }) {
|
|||||||
return function createInstance(initialProps = {}) {
|
return function createInstance(initialProps = {}) {
|
||||||
let props = { ...initialProps };
|
let props = { ...initialProps };
|
||||||
const cleanups = [];
|
const cleanups = [];
|
||||||
const eventHandlers = new Map();
|
|
||||||
|
|
||||||
function on(event, fn) {
|
|
||||||
if (!eventHandlers.has(event)) {
|
|
||||||
eventHandlers.set(event, new Set());
|
|
||||||
}
|
|
||||||
eventHandlers.get(event).add(fn);
|
|
||||||
return () => eventHandlers.get(event)?.delete(fn);
|
|
||||||
}
|
|
||||||
|
|
||||||
function emit(event, payload) {
|
function emit(event, payload) {
|
||||||
// Support Vue-style onUpdateModelValue / onChange prop callbacks
|
// Support Vue-style onUpdateModelValue / onChange prop callbacks
|
||||||
@@ -28,12 +19,6 @@ export function defineComponent({ name, setup }) {
|
|||||||
props.onChange(payload);
|
props.onChange(payload);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const handlers = eventHandlers.get(event);
|
|
||||||
if (handlers) {
|
|
||||||
for (const fn of handlers) {
|
|
||||||
fn(payload);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onCleanup(fn) {
|
function onCleanup(fn) {
|
||||||
@@ -42,15 +27,11 @@ export function defineComponent({ name, setup }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const setupResult = setup({
|
let setupResult = null;
|
||||||
getProps: () => props,
|
|
||||||
emit,
|
|
||||||
onCleanup,
|
|
||||||
});
|
|
||||||
|
|
||||||
function setProps(nextProps = {}) {
|
function setProps(nextProps = {}) {
|
||||||
props = { ...props, ...nextProps };
|
props = { ...props, ...nextProps };
|
||||||
if (typeof setupResult.onPropsChange === 'function') {
|
if (setupResult && typeof setupResult.onPropsChange === 'function') {
|
||||||
setupResult.onPropsChange(props);
|
setupResult.onPropsChange(props);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -59,11 +40,12 @@ export function defineComponent({ name, setup }) {
|
|||||||
setProps({ modelValue: nextValue });
|
setProps({ modelValue: nextValue });
|
||||||
}
|
}
|
||||||
|
|
||||||
function getValue() {
|
setupResult = setup({
|
||||||
return typeof setupResult.getValue === 'function'
|
getProps: () => props,
|
||||||
? setupResult.getValue()
|
setProps,
|
||||||
: props.modelValue;
|
emit,
|
||||||
}
|
onCleanup,
|
||||||
|
});
|
||||||
|
|
||||||
function destroy() {
|
function destroy() {
|
||||||
for (const fn of cleanups.splice(0)) {
|
for (const fn of cleanups.splice(0)) {
|
||||||
@@ -73,7 +55,6 @@ export function defineComponent({ name, setup }) {
|
|||||||
console.error(`[${name}] cleanup error:`, err);
|
console.error(`[${name}] cleanup error:`, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
eventHandlers.clear();
|
|
||||||
if (setupResult.el?.parentNode) {
|
if (setupResult.el?.parentNode) {
|
||||||
setupResult.el.parentNode.removeChild(setupResult.el);
|
setupResult.el.parentNode.removeChild(setupResult.el);
|
||||||
}
|
}
|
||||||
@@ -83,11 +64,8 @@ export function defineComponent({ name, setup }) {
|
|||||||
name,
|
name,
|
||||||
el: setupResult.el,
|
el: setupResult.el,
|
||||||
refs: setupResult.refs || {},
|
refs: setupResult.refs || {},
|
||||||
on,
|
|
||||||
emit,
|
|
||||||
setProps,
|
setProps,
|
||||||
setValue,
|
setValue,
|
||||||
getValue,
|
|
||||||
destroy,
|
destroy,
|
||||||
...setupResult.methods,
|
...setupResult.methods,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -53,18 +53,28 @@ export function patchText(el, nextValue) {
|
|||||||
export function patchAttr(el, attrName, nextValue) {
|
export function patchAttr(el, attrName, nextValue) {
|
||||||
if (!el) return false;
|
if (!el) return false;
|
||||||
if (nextValue === null || nextValue === undefined || nextValue === false) {
|
if (nextValue === null || nextValue === undefined || nextValue === false) {
|
||||||
if (!el.hasAttribute(attrName)) {
|
let mutated = false;
|
||||||
return false;
|
if (el.hasAttribute(attrName)) {
|
||||||
}
|
|
||||||
el.removeAttribute(attrName);
|
el.removeAttribute(attrName);
|
||||||
return true;
|
mutated = true;
|
||||||
|
}
|
||||||
|
if (attrName === 'value' && 'value' in el && el.value !== '') {
|
||||||
|
el.value = '';
|
||||||
|
mutated = true;
|
||||||
|
}
|
||||||
|
return mutated;
|
||||||
}
|
}
|
||||||
const strVal = nextValue === true ? '' : String(nextValue);
|
const strVal = nextValue === true ? '' : String(nextValue);
|
||||||
if (el.getAttribute(attrName) === strVal) {
|
let mutated = false;
|
||||||
return false;
|
if (el.getAttribute(attrName) !== strVal) {
|
||||||
}
|
|
||||||
el.setAttribute(attrName, strVal);
|
el.setAttribute(attrName, strVal);
|
||||||
return true;
|
mutated = true;
|
||||||
|
}
|
||||||
|
if (attrName === 'value' && 'value' in el && el.value !== strVal) {
|
||||||
|
el.value = strVal;
|
||||||
|
mutated = true;
|
||||||
|
}
|
||||||
|
return mutated;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function patchClasses(el, classMap) {
|
export function patchClasses(el, classMap) {
|
||||||
@@ -72,13 +82,16 @@ export function patchClasses(el, classMap) {
|
|||||||
let mutated = false;
|
let mutated = false;
|
||||||
for (const [cls, active] of Object.entries(classMap)) {
|
for (const [cls, active] of Object.entries(classMap)) {
|
||||||
if (!cls) continue;
|
if (!cls) continue;
|
||||||
const has = el.classList.contains(cls);
|
|
||||||
const shouldHave = Boolean(active);
|
const shouldHave = Boolean(active);
|
||||||
|
const tokens = String(cls).split(/\s+/).filter(Boolean);
|
||||||
|
for (const tok of tokens) {
|
||||||
|
const has = el.classList.contains(tok);
|
||||||
if (has !== shouldHave) {
|
if (has !== shouldHave) {
|
||||||
el.classList.toggle(cls, shouldHave);
|
el.classList.toggle(tok, shouldHave);
|
||||||
mutated = true;
|
mutated = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return mutated;
|
return mutated;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +106,25 @@ export function patchStyleVar(el, varName, nextValue) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断事件是否发生在目标节点内部(兼容 Shadow DOM 的 `composedPath()` 穿透)。
|
||||||
|
*
|
||||||
|
* @param {Event|null|undefined} event
|
||||||
|
* @param {Node|null|undefined} element
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isEventInside(event, element) {
|
||||||
|
if (!event || !element) return false;
|
||||||
|
if (typeof event.composedPath === 'function') {
|
||||||
|
const path = event.composedPath();
|
||||||
|
if (Array.isArray(path) && path.includes(element)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const target = event.target;
|
||||||
|
return Boolean(target && typeof element.contains === 'function' && element.contains(target));
|
||||||
|
}
|
||||||
|
|
||||||
const keyedListState = new WeakMap();
|
const keyedListState = new WeakMap();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -108,11 +140,15 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda
|
|||||||
}
|
}
|
||||||
|
|
||||||
const nextKeys = new Set();
|
const nextKeys = new Set();
|
||||||
|
const seenInPass = new Map();
|
||||||
const orderedNodes = [];
|
const orderedNodes = [];
|
||||||
|
|
||||||
for (let i = 0; i < items.length; i++) {
|
for (let i = 0; i < items.length; i++) {
|
||||||
const item = items[i];
|
const item = items[i];
|
||||||
const key = String(keyFn(item, i));
|
const rawKey = String(keyFn(item, i));
|
||||||
|
const dupIdx = seenInPass.get(rawKey) || 0;
|
||||||
|
seenInPass.set(rawKey, dupIdx + 1);
|
||||||
|
const key = dupIdx === 0 ? rawKey : `${rawKey}__dup_${dupIdx}`;
|
||||||
const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item);
|
const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item);
|
||||||
nextKeys.add(key);
|
nextKeys.add(key);
|
||||||
|
|
||||||
|
|||||||
@@ -37,15 +37,15 @@ export function formatDateSpanBadge(startMs, endMs) {
|
|||||||
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
|
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatUsd(amount, { precise = false, estimated = false, unpricedCalls = 0 } = {}) {
|
export function formatUsd(amount, { precise = false, unpricedCalls = 0, compactPending = false } = {}) {
|
||||||
if (amount == null || !Number.isFinite(Number(amount))) return '待定';
|
if (amount == null || !Number.isFinite(Number(amount))) return '待定';
|
||||||
const val = Number(amount || 0);
|
const val = Number(amount || 0);
|
||||||
const prefix = estimated ? '≈$' : '$';
|
const suffix = unpricedCalls > 0 ? (compactPending ? '+' : ' + 待定') : '';
|
||||||
const suffix = unpricedCalls > 0 ? ' + 待定' : '';
|
|
||||||
if (precise) {
|
if (precise) {
|
||||||
return (val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`) + suffix;
|
if (val > 0 && val < 0.001) return `<$0.001${suffix}`;
|
||||||
|
return (val >= 1 ? `$${val.toFixed(2)}` : `$${val.toFixed(3)}`) + suffix;
|
||||||
}
|
}
|
||||||
return `${prefix}${val.toFixed(2)}${suffix}`;
|
return `$${val.toFixed(2)}${suffix}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function speedReasonText(reason) {
|
export function speedReasonText(reason) {
|
||||||
@@ -53,6 +53,7 @@ export function speedReasonText(reason) {
|
|||||||
incomplete_or_invalid_timing: '生成未完成',
|
incomplete_or_invalid_timing: '生成未完成',
|
||||||
invalid_output_tokens: '无有效输出',
|
invalid_output_tokens: '无有效输出',
|
||||||
inconsistent_timing: '耗时数据异常',
|
inconsistent_timing: '耗时数据异常',
|
||||||
|
short_timing: '耗时过短 (<0.5s)',
|
||||||
legacy_cache: '旧版缓存记录',
|
legacy_cache: '旧版缓存记录',
|
||||||
})[reason] || '';
|
})[reason] || '';
|
||||||
}
|
}
|
||||||
@@ -66,9 +67,10 @@ export function sampleSummary(summary) {
|
|||||||
export function formatCountdown(isoTime, nowMs = Date.now()) {
|
export function formatCountdown(isoTime, nowMs = Date.now()) {
|
||||||
if (!isoTime) return '未知重置时间';
|
if (!isoTime) return '未知重置时间';
|
||||||
const targetMs = Date.parse(isoTime);
|
const targetMs = Date.parse(isoTime);
|
||||||
if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间';
|
if (!Number.isFinite(targetMs) || targetMs <= 0) return '未知重置时间';
|
||||||
const diffMs = targetMs - nowMs;
|
const diffMs = targetMs - nowMs;
|
||||||
if (diffMs <= 0) return '即将重置';
|
if (diffMs <= 0) return '即将重置';
|
||||||
|
if (diffMs < 60_000) return '<1分钟后重置';
|
||||||
|
|
||||||
const totalMinutes = Math.floor(diffMs / 60000);
|
const totalMinutes = Math.floor(diffMs / 60000);
|
||||||
const days = Math.floor(totalMinutes / (60 * 24));
|
const days = Math.floor(totalMinutes / (60 * 24));
|
||||||
|
|||||||
@@ -1,11 +1,123 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview Async HTTP client with AbortController cancellation for stale
|
* @fileoverview Async HTTP client with AbortController cancellation for stale
|
||||||
* polling requests and concurrent GET deduplication.
|
* polling requests, concurrent GET deduplication, and dual-mode transport
|
||||||
|
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const inFlightGets = new Map();
|
const inFlightGets = new Map();
|
||||||
const activeControllers = new Map();
|
const activeControllers = new Map();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
|
||||||
|
*
|
||||||
|
* @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null}
|
||||||
|
*/
|
||||||
|
export function getWindowBridgeConfig() {
|
||||||
|
if (typeof window === 'undefined') return null;
|
||||||
|
const br = window.__AGUsageMonitorBridge;
|
||||||
|
const port = Number(br?.port || 0);
|
||||||
|
if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) {
|
||||||
|
return br;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断当前脚本是否以双栖悬浮模式运行在宿主主聊天窗口内(而非右侧辅助栏 Webview)。
|
||||||
|
*
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isWindowOverlayMode() {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
if (window.sidecar?.fetch) return false;
|
||||||
|
return Boolean(getWindowBridgeConfig());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接收 Sidecar 通过 CDP `Runtime.evaluate` 批量投递的 RPC 响应,完成因 CSP/代理解除 HTTP 直连时的兜底请求。
|
||||||
|
*
|
||||||
|
* @param {Array<{ id: string, ok: boolean, status?: number, data?: any, error?: string }>} responses
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
export function deliverCdpBridgeResponses(responses) {
|
||||||
|
const br = getWindowBridgeConfig();
|
||||||
|
if (!br || !(br.rpcPending instanceof Map) || !Array.isArray(responses)) return 0;
|
||||||
|
let delivered = 0;
|
||||||
|
for (const item of responses) {
|
||||||
|
const entry = br.rpcPending.get(item?.id);
|
||||||
|
if (!entry) continue;
|
||||||
|
br.rpcPending.delete(item.id);
|
||||||
|
delivered += 1;
|
||||||
|
if (item.ok) {
|
||||||
|
entry.resolve(item.data);
|
||||||
|
} else {
|
||||||
|
entry.reject(new Error(item.error || `HTTP ${item.status || 500}`));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return delivered;
|
||||||
|
}
|
||||||
|
|
||||||
|
function callViaCdpBridge(bridge, path, { method, body, signal }) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (signal?.aborted) {
|
||||||
|
const abortErr = new Error('Request aborted');
|
||||||
|
abortErr.name = 'AbortError';
|
||||||
|
reject(abortErr);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!Array.isArray(bridge.rpcQueue)) bridge.rpcQueue = [];
|
||||||
|
if (!(bridge.rpcPending instanceof Map)) bridge.rpcPending = new Map();
|
||||||
|
|
||||||
|
const reqId = `rpc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
const cleanupQueueItem = () => {
|
||||||
|
if (!Array.isArray(bridge.rpcQueue)) return;
|
||||||
|
const idx = bridge.rpcQueue.findIndex((item) => item?.id === reqId);
|
||||||
|
if (idx >= 0) bridge.rpcQueue.splice(idx, 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const timeoutId = setTimeout(() => {
|
||||||
|
bridge.rpcPending.delete(reqId);
|
||||||
|
cleanupQueueItem();
|
||||||
|
reject(new Error('CDP bridge timeout'));
|
||||||
|
}, 8000);
|
||||||
|
|
||||||
|
const onAbort = () => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
bridge.rpcPending.delete(reqId);
|
||||||
|
cleanupQueueItem();
|
||||||
|
const abortErr = new Error('Request aborted');
|
||||||
|
abortErr.name = 'AbortError';
|
||||||
|
reject(abortErr);
|
||||||
|
};
|
||||||
|
if (signal) {
|
||||||
|
signal.addEventListener('abort', onAbort, { once: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
bridge.rpcPending.set(reqId, {
|
||||||
|
resolve: (data) => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
if (signal) signal.removeEventListener('abort', onAbort);
|
||||||
|
resolve(data);
|
||||||
|
},
|
||||||
|
reject: (err) => {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
if (signal) signal.removeEventListener('abort', onAbort);
|
||||||
|
reject(err);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (bridge.rpcQueue.length >= 16) {
|
||||||
|
const dropped = bridge.rpcQueue.shift();
|
||||||
|
if (dropped?.id) {
|
||||||
|
const stale = bridge.rpcPending.get(dropped.id);
|
||||||
|
bridge.rpcPending.delete(dropped.id);
|
||||||
|
stale?.reject(new Error('CDP queue superseded'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bridge.rpcQueue.push({ id: reqId, path, method, body });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
|
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
|
||||||
const upperMethod = method.toUpperCase();
|
const upperMethod = method.toUpperCase();
|
||||||
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
||||||
@@ -28,16 +140,41 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
|||||||
|
|
||||||
const runRequest = async () => {
|
const runRequest = async () => {
|
||||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||||
|
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
|
||||||
const fetchFn = sidecar?.fetch
|
const fetchFn = sidecar?.fetch
|
||||||
? sidecar.fetch.bind(sidecar)
|
? sidecar.fetch.bind(sidecar)
|
||||||
|
: typeof window !== 'undefined' && typeof window.fetch === 'function'
|
||||||
|
? window.fetch.bind(window)
|
||||||
: globalThis.fetch.bind(globalThis);
|
: globalThis.fetch.bind(globalThis);
|
||||||
|
|
||||||
const res = await fetchFn(path, {
|
const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path;
|
||||||
|
const headers = {};
|
||||||
|
if (body !== undefined || !bridge) {
|
||||||
|
headers['Content-Type'] = 'application/json';
|
||||||
|
}
|
||||||
|
if (bridge) {
|
||||||
|
headers['X-Usage-Monitor-Token'] = bridge.token;
|
||||||
|
if (bridge.transportMode === 'cdp') {
|
||||||
|
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetchFn(requestUrl, {
|
||||||
method: upperMethod,
|
method: upperMethod,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers,
|
||||||
body: body === undefined ? undefined : JSON.stringify(body),
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
signal,
|
signal,
|
||||||
});
|
});
|
||||||
|
} catch (fetchErr) {
|
||||||
|
if (!bridge || signal?.aborted || fetchErr?.name === 'AbortError') {
|
||||||
|
throw fetchErr;
|
||||||
|
}
|
||||||
|
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
|
||||||
|
bridge.transportMode = 'cdp';
|
||||||
|
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
|
||||||
|
}
|
||||||
if (signal?.aborted) {
|
if (signal?.aborted) {
|
||||||
const abortErr = new Error('Request aborted');
|
const abortErr = new Error('Request aborted');
|
||||||
abortErr.name = 'AbortError';
|
abortErr.name = 'AbortError';
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
const pendingJobs = new Set();
|
const pendingJobs = new Set();
|
||||||
let isFlushPending = false;
|
let isFlushPending = false;
|
||||||
|
|
||||||
export function scheduleAsyncJob(job) {
|
function scheduleAsyncJob(job) {
|
||||||
pendingJobs.add(job);
|
pendingJobs.add(job);
|
||||||
if (!isFlushPending) {
|
if (!isFlushPending) {
|
||||||
isFlushPending = true;
|
isFlushPending = true;
|
||||||
@@ -14,7 +14,7 @@ export function scheduleAsyncJob(job) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function flushAsyncJobs() {
|
function flushAsyncJobs() {
|
||||||
isFlushPending = false;
|
isFlushPending = false;
|
||||||
const jobs = Array.from(pendingJobs);
|
const jobs = Array.from(pendingJobs);
|
||||||
pendingJobs.clear();
|
pendingJobs.clear();
|
||||||
@@ -23,7 +23,7 @@ export function flushAsyncJobs() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isShallowEqual(a, b) {
|
function isShallowEqual(a, b) {
|
||||||
if (Object.is(a, b)) return true;
|
if (Object.is(a, b)) return true;
|
||||||
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
|
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
|
||||||
return false;
|
return false;
|
||||||
@@ -55,6 +55,19 @@ export function createReactiveStore(initialState) {
|
|||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function notifyAll() {
|
||||||
|
for (const sub of Array.from(subscribers)) {
|
||||||
|
if (!subscribers.has(sub)) continue;
|
||||||
|
const nextSlice = sub.selector(state);
|
||||||
|
const equal = sub.compare(sub.lastSlice, nextSlice);
|
||||||
|
if (!equal) {
|
||||||
|
const prevSlice = sub.lastSlice;
|
||||||
|
sub.lastSlice = nextSlice;
|
||||||
|
sub.listener(nextSlice, prevSlice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function setState(patchOrUpdater, { sync = false } = {}) {
|
function setState(patchOrUpdater, { sync = false } = {}) {
|
||||||
const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater;
|
const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater;
|
||||||
if (!patch || typeof patch !== 'object') return;
|
if (!patch || typeof patch !== 'object') return;
|
||||||
@@ -72,18 +85,6 @@ export function createReactiveStore(initialState) {
|
|||||||
}
|
}
|
||||||
state = nextState;
|
state = nextState;
|
||||||
|
|
||||||
const notifyAll = () => {
|
|
||||||
for (const sub of subscribers) {
|
|
||||||
const nextSlice = sub.selector(state);
|
|
||||||
const equal = sub.compare(sub.lastSlice, nextSlice);
|
|
||||||
if (!equal) {
|
|
||||||
const prevSlice = sub.lastSlice;
|
|
||||||
sub.lastSlice = nextSlice;
|
|
||||||
sub.listener(nextSlice, prevSlice);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (sync) {
|
if (sync) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -73,9 +73,17 @@ export const SVG_ICON_DEFS = Object.freeze({
|
|||||||
{ tag: 'path', attrs: { d: 'M3.5 8h9' } },
|
{ tag: 'path', attrs: { d: 'M3.5 8h9' } },
|
||||||
],
|
],
|
||||||
dot: [
|
dot: [
|
||||||
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '3.2', fill: 'currentColor', stroke: 'none' } },
|
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '5', fill: 'currentColor', stroke: 'none' } },
|
||||||
],
|
],
|
||||||
'arrow-down': [
|
'arrow-down': [
|
||||||
{ tag: 'path', attrs: { d: 'M8 2.8v10.4M4.2 9.4L8 13.2l3.8-3.8' } },
|
{ tag: 'path', attrs: { d: 'M8 2.8v10.4M4.2 9.4L8 13.2l3.8-3.8' } },
|
||||||
],
|
],
|
||||||
|
dock: [
|
||||||
|
{ tag: 'rect', attrs: { x: '1.8', y: '2.5', width: '12.4', height: '11', rx: '1.5' } },
|
||||||
|
{ tag: 'path', attrs: { d: 'M1.8 6h12.4' } },
|
||||||
|
{ tag: 'path', attrs: { d: 'M9.2 4.25h3.2' } },
|
||||||
|
],
|
||||||
|
close: [
|
||||||
|
{ tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } },
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview Async entry point for Antigravity Usage & Speed Monitor.
|
* @fileoverview Async entry point for Antigravity Usage & Speed Monitor.
|
||||||
|
* Automatically branches between Auxiliary Sidebar Webview mode (`#app-root`)
|
||||||
|
* and Main Window Dual-Mount Overlay mode (`window.__AGUsageMonitorBridge`).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { App } from './App.js';
|
import { App } from './App.js';
|
||||||
|
import { mountWindowOverlay } from './components/layout/WindowOverlayShell.js';
|
||||||
|
import { isWindowOverlayMode } from './core/httpClient.js';
|
||||||
import { startAsyncTelemetryLoop } from './store/telemetryStore.js';
|
import { startAsyncTelemetryLoop } from './store/telemetryStore.js';
|
||||||
|
|
||||||
export async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
||||||
if (!mountTarget) return null;
|
if (!mountTarget) return null;
|
||||||
const appInstance = App();
|
const appInstance = App();
|
||||||
mountTarget.appendChild(appInstance.el);
|
mountTarget.appendChild(appInstance.el);
|
||||||
@@ -16,14 +20,22 @@ export async function bootstrapApp(mountTarget = document.getElementById('app-ro
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function init() {
|
function startEntry() {
|
||||||
|
if (isWindowOverlayMode()) {
|
||||||
|
mountWindowOverlay();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bootstrapApp();
|
||||||
|
}
|
||||||
|
|
||||||
|
function init() {
|
||||||
if (typeof document === 'undefined') return;
|
if (typeof document === 'undefined') return;
|
||||||
if (document.readyState === 'loading' && typeof document.addEventListener === 'function') {
|
if (document.readyState === 'loading' && typeof document.addEventListener === 'function') {
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
bootstrapApp();
|
startEntry();
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
bootstrapApp();
|
startEntry();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,17 +4,31 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { createReactiveStore } from '../core/reactive.js';
|
import { createReactiveStore } from '../core/reactive.js';
|
||||||
import { callSidecarApi } from '../core/httpClient.js';
|
import { callSidecarApi, isWindowOverlayMode } from '../core/httpClient.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在主窗口双栖模式下,从宿主页面路径 `/c/<uuid>` 提取当前正在浏览的会话 ID。
|
||||||
|
*
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function extractHostRouteCascadeId() {
|
||||||
|
if (typeof window === 'undefined' || !isWindowOverlayMode()) return '';
|
||||||
|
const pathname = String(window.location?.pathname || '');
|
||||||
|
const m = pathname.match(/^\/c\/([a-f0-9-]{36})(?:\/|$)/i);
|
||||||
|
return m ? m[1] : '';
|
||||||
|
}
|
||||||
|
|
||||||
const initialConversationId =
|
const initialConversationId =
|
||||||
(typeof window !== 'undefined' && window.sidecar?.conversationId) || '';
|
(typeof window !== 'undefined' && window.sidecar?.conversationId) || '';
|
||||||
|
|
||||||
export const telemetryStore = createReactiveStore({
|
export const telemetryStore = createReactiveStore({
|
||||||
selectedConversationId: initialConversationId,
|
selectedConversationId: initialConversationId,
|
||||||
|
hostRouteConversationId: extractHostRouteCascadeId(),
|
||||||
selectedTimeRange: 'today',
|
selectedTimeRange: 'today',
|
||||||
customStartMs: Date.now() - 24 * 3600 * 1000,
|
customStartMs: Date.now() - 24 * 3600 * 1000,
|
||||||
customEndMs: Date.now(),
|
customEndMs: Date.now(),
|
||||||
syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error'
|
syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error'
|
||||||
|
minuteTick: 0,
|
||||||
telemetry: null,
|
telemetry: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -22,12 +36,49 @@ let pollTimer = null;
|
|||||||
let feedbackTimer = null;
|
let feedbackTimer = null;
|
||||||
let activeBundleVersion = 0;
|
let activeBundleVersion = 0;
|
||||||
let latestRequestSeq = 0;
|
let latestRequestSeq = 0;
|
||||||
|
let activeForceCount = 0;
|
||||||
|
let loopActive = false;
|
||||||
|
let loopIntervalMs = 2000;
|
||||||
|
let loopTickFn = null;
|
||||||
|
|
||||||
|
export const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([
|
||||||
|
'context',
|
||||||
|
'tps',
|
||||||
|
'ttft',
|
||||||
|
'cost',
|
||||||
|
'quota_auto',
|
||||||
|
'gemini_5h',
|
||||||
|
'gemini_weekly',
|
||||||
|
'claude_5h',
|
||||||
|
'claude_weekly',
|
||||||
|
'none',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化前端顶栏胶囊三槽位配置数组,非法项回退默认值,且禁止三项同时为 `none`。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {[string, string, string]}
|
||||||
|
*/
|
||||||
|
export function normalizeClientTopbarSlots(raw) {
|
||||||
|
const arr = Array.isArray(raw) ? raw : [];
|
||||||
|
const slots = [0, 1, 2].map((idx) => {
|
||||||
|
const val = String(arr[idx] ?? '').trim();
|
||||||
|
return CLIENT_TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_CLIENT_TOPBAR_SLOTS[idx];
|
||||||
|
});
|
||||||
|
if (slots.every((s) => s === 'none')) {
|
||||||
|
slots[0] = 'context';
|
||||||
|
}
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
|
||||||
function isEquivalentTelemetry(prev, next) {
|
function isEquivalentTelemetry(prev, next) {
|
||||||
if (!prev || !next) return false;
|
if (!prev || !next) return false;
|
||||||
if (prev === next) return true;
|
if (prev === next) return true;
|
||||||
|
|
||||||
// 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关)
|
// 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关、双栖与顶栏槽位配置)
|
||||||
const pAct = prev.activeConversation;
|
const pAct = prev.activeConversation;
|
||||||
const nAct = next.activeConversation;
|
const nAct = next.activeConversation;
|
||||||
if (prev.settings?.showUpstreamModel !== next.settings?.showUpstreamModel) return false;
|
if (prev.settings?.showUpstreamModel !== next.settings?.showUpstreamModel) return false;
|
||||||
@@ -35,14 +86,28 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if (prev.settings?.weeklyTokenBudget !== next.settings?.weeklyTokenBudget) return false;
|
if (prev.settings?.weeklyTokenBudget !== next.settings?.weeklyTokenBudget) return false;
|
||||||
if (prev.settings?.weeklyCostBudget !== next.settings?.weeklyCostBudget) return false;
|
if (prev.settings?.weeklyCostBudget !== next.settings?.weeklyCostBudget) return false;
|
||||||
if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false;
|
if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false;
|
||||||
|
if (prev.settings?.enableWindowOverlay !== next.settings?.enableWindowOverlay) return false;
|
||||||
|
if ((prev.settings?.showTopbarMultiSession !== false) !== (next.settings?.showTopbarMultiSession !== false)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const pTopSlots = prev.settings?.topbarCapsuleSlots;
|
||||||
|
const nTopSlots = next.settings?.topbarCapsuleSlots;
|
||||||
|
if (
|
||||||
|
(pTopSlots?.[0] ?? 'context') !== (nTopSlots?.[0] ?? 'context') ||
|
||||||
|
(pTopSlots?.[1] ?? 'tps') !== (nTopSlots?.[1] ?? 'tps') ||
|
||||||
|
(pTopSlots?.[2] ?? 'quota_auto') !== (nTopSlots?.[2] ?? 'quota_auto')
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// 2. 比对云端状态(插件当前/最新版本、价格表版本与模型数量、同步/更新执行状态及错误信息)
|
// 2. 比对云端状态(插件当前/最新版本、安装模式、价格表版本与模型数量、同步/更新执行状态及错误信息)
|
||||||
const pCloud = prev.cloudStatus;
|
const pCloud = prev.cloudStatus;
|
||||||
const nCloud = next.cloudStatus;
|
const nCloud = next.cloudStatus;
|
||||||
if (
|
if (
|
||||||
pCloud?.currentPluginVersion !== nCloud?.currentPluginVersion ||
|
pCloud?.currentPluginVersion !== nCloud?.currentPluginVersion ||
|
||||||
pCloud?.latestPluginVersion !== nCloud?.latestPluginVersion ||
|
pCloud?.latestPluginVersion !== nCloud?.latestPluginVersion ||
|
||||||
pCloud?.updateAvailable !== nCloud?.updateAvailable ||
|
pCloud?.updateAvailable !== nCloud?.updateAvailable ||
|
||||||
|
pCloud?.installMode !== nCloud?.installMode ||
|
||||||
pCloud?.catalogVersion !== nCloud?.catalogVersion ||
|
pCloud?.catalogVersion !== nCloud?.catalogVersion ||
|
||||||
pCloud?.source !== nCloud?.source ||
|
pCloud?.source !== nCloud?.source ||
|
||||||
pCloud?.lastSyncedAtMs !== nCloud?.lastSyncedAtMs ||
|
pCloud?.lastSyncedAtMs !== nCloud?.lastSyncedAtMs ||
|
||||||
@@ -56,15 +121,25 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与单步费用)
|
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与费用)
|
||||||
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
||||||
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
||||||
if (pAct?.subagentCount !== nAct?.subagentCount) return false;
|
if (pAct?.subagentCount !== nAct?.subagentCount) return false;
|
||||||
if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false;
|
if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false;
|
||||||
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
||||||
if (pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature) return false;
|
if (
|
||||||
|
pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature ||
|
||||||
|
pAct?.liveActivity?.startedAtMs !== nAct?.liveActivity?.startedAtMs
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false;
|
if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false;
|
||||||
if (pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature) return false;
|
if (
|
||||||
|
pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature ||
|
||||||
|
pAct?.aggregated?.liveActivity?.startedAtMs !== nAct?.aggregated?.liveActivity?.startedAtMs
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false;
|
if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false;
|
||||||
if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false;
|
if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false;
|
||||||
if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false;
|
if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false;
|
||||||
@@ -73,17 +148,34 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false;
|
if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false;
|
||||||
if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false;
|
if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false;
|
||||||
if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false;
|
if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false;
|
||||||
|
if (pAct?.aggregated?.sessionUnpricedCalls !== nAct?.aggregated?.sessionUnpricedCalls) return false;
|
||||||
|
if (pAct?.aggregated?.sessionCacheHitPct !== nAct?.aggregated?.sessionCacheHitPct) return false;
|
||||||
if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false;
|
if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false;
|
||||||
|
if (pAct?.aggregated?.activeModelUpstream !== nAct?.aggregated?.activeModelUpstream) return false;
|
||||||
if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false;
|
if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false;
|
||||||
if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false;
|
if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false;
|
||||||
if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false;
|
if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false;
|
||||||
if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false;
|
if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false;
|
||||||
|
if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false;
|
||||||
if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false;
|
if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false;
|
||||||
|
if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false;
|
||||||
if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false;
|
if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false;
|
||||||
if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false;
|
if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false;
|
||||||
if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false;
|
if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false;
|
||||||
if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false;
|
if (
|
||||||
if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false;
|
pAct?.activeModelShort !== nAct?.activeModelShort ||
|
||||||
|
pAct?.activeModelLabel !== nAct?.activeModelLabel ||
|
||||||
|
pAct?.activeModelUpstream !== nAct?.activeModelUpstream
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd ||
|
||||||
|
pAct?.sessionCostUsd !== nAct?.sessionCostUsd ||
|
||||||
|
pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
const pAgents = pAct?.agents || [];
|
const pAgents = pAct?.agents || [];
|
||||||
const nAgents = nAct?.agents || [];
|
const nAgents = nAct?.agents || [];
|
||||||
@@ -91,8 +183,6 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
for (let i = 0; i < pAgents.length; i++) {
|
for (let i = 0; i < pAgents.length; i++) {
|
||||||
const pa = pAgents[i];
|
const pa = pAgents[i];
|
||||||
const na = nAgents[i];
|
const na = nAgents[i];
|
||||||
const pLastStep = pa?.recentSteps?.[0];
|
|
||||||
const nLastStep = na?.recentSteps?.[0];
|
|
||||||
if (
|
if (
|
||||||
pa?.agentId !== na?.agentId ||
|
pa?.agentId !== na?.agentId ||
|
||||||
pa?.role !== na?.role ||
|
pa?.role !== na?.role ||
|
||||||
@@ -103,11 +193,16 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
pa?.latestTtftSec !== na?.latestTtftSec ||
|
pa?.latestTtftSec !== na?.latestTtftSec ||
|
||||||
pa?.avgTokPerSec !== na?.avgTokPerSec ||
|
pa?.avgTokPerSec !== na?.avgTokPerSec ||
|
||||||
pa?.latestCacheHitPct !== na?.latestCacheHitPct ||
|
pa?.latestCacheHitPct !== na?.latestCacheHitPct ||
|
||||||
|
pa?.sessionCacheHitPct !== na?.sessionCacheHitPct ||
|
||||||
pa?.latestSpeedReason !== na?.latestSpeedReason ||
|
pa?.latestSpeedReason !== na?.latestSpeedReason ||
|
||||||
pa?.latestStepCostUsd !== na?.latestStepCostUsd ||
|
pa?.latestStepCostUsd !== na?.latestStepCostUsd ||
|
||||||
pa?.sessionCostUsd !== na?.sessionCostUsd ||
|
pa?.sessionCostUsd !== na?.sessionCostUsd ||
|
||||||
|
pa?.sessionUnpricedCalls !== na?.sessionUnpricedCalls ||
|
||||||
pa?.activeModelShort !== na?.activeModelShort ||
|
pa?.activeModelShort !== na?.activeModelShort ||
|
||||||
|
pa?.activeModelUpstream !== na?.activeModelUpstream ||
|
||||||
pa?.context?.totalTokens !== na?.context?.totalTokens ||
|
pa?.context?.totalTokens !== na?.context?.totalTokens ||
|
||||||
|
pa?.context?.compactionLimitTokens !== na?.context?.compactionLimitTokens ||
|
||||||
|
pa?.context?.limitTokens !== na?.context?.limitTokens ||
|
||||||
pa?.context?.messagesTokens !== na?.context?.messagesTokens ||
|
pa?.context?.messagesTokens !== na?.context?.messagesTokens ||
|
||||||
pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens ||
|
pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens ||
|
||||||
pa?.context?.assistantTokens !== na?.context?.assistantTokens ||
|
pa?.context?.assistantTokens !== na?.context?.assistantTokens ||
|
||||||
@@ -118,21 +213,43 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens ||
|
pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens ||
|
||||||
pa?.context?.skillsTokens !== na?.context?.skillsTokens ||
|
pa?.context?.skillsTokens !== na?.context?.skillsTokens ||
|
||||||
pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens ||
|
pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens ||
|
||||||
pa?.context?.userRulesTokens !== na?.context?.userRulesTokens ||
|
pa?.context?.userRulesTokens !== na?.context?.userRulesTokens
|
||||||
pLastStep?.tokPerSec !== nLastStep?.tokPerSec ||
|
|
||||||
pLastStep?.ttftSec !== nLastStep?.ttftSec ||
|
|
||||||
pLastStep?.outputTokens !== nLastStep?.outputTokens ||
|
|
||||||
pLastStep?.modelUpstream !== nLastStep?.modelUpstream ||
|
|
||||||
pLastStep?.costUsd !== nLastStep?.costUsd
|
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
const paSteps = pa?.recentSteps || [];
|
||||||
|
const naSteps = na?.recentSteps || [];
|
||||||
|
if (paSteps.length !== naSteps.length) return false;
|
||||||
|
for (let j = 0; j < paSteps.length; j++) {
|
||||||
|
const bs = paSteps[j];
|
||||||
|
const as = naSteps[j];
|
||||||
|
if (
|
||||||
|
bs?.stepIndex !== as?.stepIndex ||
|
||||||
|
bs?.modelKey !== as?.modelKey ||
|
||||||
|
bs?.modelShort !== as?.modelShort ||
|
||||||
|
bs?.modelLabel !== as?.modelLabel ||
|
||||||
|
bs?.modelUpstream !== as?.modelUpstream ||
|
||||||
|
bs?.responseModel !== as?.responseModel ||
|
||||||
|
bs?.modelSource !== as?.modelSource ||
|
||||||
|
bs?.costUsd !== as?.costUsd ||
|
||||||
|
bs?.tokPerSec !== as?.tokPerSec ||
|
||||||
|
bs?.ttftSec !== as?.ttftSec ||
|
||||||
|
bs?.outputTokens !== as?.outputTokens ||
|
||||||
|
bs?.inputTokens !== as?.inputTokens ||
|
||||||
|
bs?.cacheReadTokens !== as?.cacheReadTokens ||
|
||||||
|
bs?.selectedSpeedReason !== as?.selectedSpeedReason
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 比对 10 通道上下文窗口构成及近期步骤明细
|
// 4. 比对 10 通道上下文窗口构成及近期步骤明细
|
||||||
const pCtx = pAct?.context;
|
const pCtx = pAct?.context;
|
||||||
const nCtx = nAct?.context;
|
const nCtx = nAct?.context;
|
||||||
if (pCtx?.totalTokens !== nCtx?.totalTokens) return false;
|
if (pCtx?.totalTokens !== nCtx?.totalTokens) return false;
|
||||||
|
if (pCtx?.compactionLimitTokens !== nCtx?.compactionLimitTokens) return false;
|
||||||
|
if (pCtx?.limitTokens !== nCtx?.limitTokens) return false;
|
||||||
if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false;
|
if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false;
|
||||||
if (pCtx?.assistantTokens !== nCtx?.assistantTokens) return false;
|
if (pCtx?.assistantTokens !== nCtx?.assistantTokens) return false;
|
||||||
if (pCtx?.toolResultsTokens !== nCtx?.toolResultsTokens) return false;
|
if (pCtx?.toolResultsTokens !== nCtx?.toolResultsTokens) return false;
|
||||||
@@ -150,6 +267,7 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if (
|
if (
|
||||||
before.modelKey !== after.modelKey ||
|
before.modelKey !== after.modelKey ||
|
||||||
before.modelShort !== after.modelShort ||
|
before.modelShort !== after.modelShort ||
|
||||||
|
before.modelLabel !== after.modelLabel ||
|
||||||
before.modelUpstream !== after.modelUpstream ||
|
before.modelUpstream !== after.modelUpstream ||
|
||||||
before.responseModel !== after.responseModel ||
|
before.responseModel !== after.responseModel ||
|
||||||
before.modelSource !== after.modelSource ||
|
before.modelSource !== after.modelSource ||
|
||||||
@@ -158,7 +276,8 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
before.ttftSec !== after.ttftSec ||
|
before.ttftSec !== after.ttftSec ||
|
||||||
before.outputTokens !== after.outputTokens ||
|
before.outputTokens !== after.outputTokens ||
|
||||||
before.inputTokens !== after.inputTokens ||
|
before.inputTokens !== after.inputTokens ||
|
||||||
before.cacheReadTokens !== after.cacheReadTokens
|
before.cacheReadTokens !== after.cacheReadTokens ||
|
||||||
|
before.selectedSpeedReason !== after.selectedSpeedReason
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -181,8 +300,13 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
const pAcct = prev.consumption?.account;
|
const pAcct = prev.consumption?.account;
|
||||||
const nAcct = next.consumption?.account;
|
const nAcct = next.consumption?.account;
|
||||||
if (pAcct?.totalTokens !== nAcct?.totalTokens) return false;
|
if (pAcct?.totalTokens !== nAcct?.totalTokens) return false;
|
||||||
|
if (pAcct?.inputTokens !== nAcct?.inputTokens) return false;
|
||||||
|
if (pAcct?.cacheReadTokens !== nAcct?.cacheReadTokens) return false;
|
||||||
|
if (pAcct?.outputTokens !== nAcct?.outputTokens) return false;
|
||||||
if (pAcct?.calls !== nAcct?.calls) return false;
|
if (pAcct?.calls !== nAcct?.calls) return false;
|
||||||
if (pAcct?.costUsd !== nAcct?.costUsd) return false;
|
if (pAcct?.costUsd !== nAcct?.costUsd) return false;
|
||||||
|
if (pAcct?.savedCostUsd !== nAcct?.savedCostUsd) return false;
|
||||||
|
if (pAcct?.cacheHitPct !== nAcct?.cacheHitPct) return false;
|
||||||
if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false;
|
if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false;
|
||||||
|
|
||||||
// 6. 比对历史趋势时间分桶序列与年度分月序列
|
// 6. 比对历史趋势时间分桶序列与年度分月序列
|
||||||
@@ -268,6 +392,7 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if (pQuot?.usedPct !== nQuot?.usedPct) return false;
|
if (pQuot?.usedPct !== nQuot?.usedPct) return false;
|
||||||
if (pQuot?.remainingPct !== nQuot?.remainingPct) return false;
|
if (pQuot?.remainingPct !== nQuot?.remainingPct) return false;
|
||||||
if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false;
|
if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false;
|
||||||
|
if (pQuot?.weeklyRemainingPct !== nQuot?.weeklyRemainingPct) return false;
|
||||||
if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false;
|
if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false;
|
||||||
if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false;
|
if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false;
|
||||||
if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false;
|
if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false;
|
||||||
@@ -323,7 +448,8 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
pr?.isMainRunning !== nr?.isMainRunning ||
|
pr?.isMainRunning !== nr?.isMainRunning ||
|
||||||
pr?.subagentCount !== nr?.subagentCount ||
|
pr?.subagentCount !== nr?.subagentCount ||
|
||||||
pr?.runningSubagentCount !== nr?.runningSubagentCount ||
|
pr?.runningSubagentCount !== nr?.runningSubagentCount ||
|
||||||
pr?.mainActivity?.signature !== nr?.mainActivity?.signature
|
pr?.mainActivity?.signature !== nr?.mainActivity?.signature ||
|
||||||
|
pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -336,7 +462,8 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
pSubs[j]?.role !== nSubs[j]?.role ||
|
pSubs[j]?.role !== nSubs[j]?.role ||
|
||||||
pSubs[j]?.isRunning !== nSubs[j]?.isRunning ||
|
pSubs[j]?.isRunning !== nSubs[j]?.isRunning ||
|
||||||
pSubs[j]?.stepCount !== nSubs[j]?.stepCount ||
|
pSubs[j]?.stepCount !== nSubs[j]?.stepCount ||
|
||||||
pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature
|
pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature ||
|
||||||
|
pSubs[j]?.liveActivity?.startedAtMs !== nSubs[j]?.liveActivity?.startedAtMs
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -347,25 +474,46 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchTelemetry({ force = false } = {}) {
|
export async function fetchTelemetry({ force = false } = {}) {
|
||||||
|
if (!force && activeForceCount > 0) {
|
||||||
|
return telemetryStore.getState().telemetry;
|
||||||
|
}
|
||||||
|
|
||||||
const st = telemetryStore.getState();
|
const st = telemetryStore.getState();
|
||||||
const reqSeq = ++latestRequestSeq;
|
const reqSeq = ++latestRequestSeq;
|
||||||
const startMs = Date.now();
|
const startMs = Date.now();
|
||||||
|
|
||||||
if (force) {
|
if (force) {
|
||||||
|
activeForceCount += 1;
|
||||||
|
if (pollTimer) {
|
||||||
|
clearTimeout(pollTimer);
|
||||||
|
pollTimer = null;
|
||||||
|
}
|
||||||
telemetryStore.setState({ syncState: 'syncing' });
|
telemetryStore.setState({ syncState: 'syncing' });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (isWindowOverlayMode()) {
|
||||||
|
const liveRouteId = extractHostRouteCascadeId();
|
||||||
|
if (liveRouteId !== st.hostRouteConversationId) {
|
||||||
|
const patch = { hostRouteConversationId: liveRouteId };
|
||||||
|
if (liveRouteId && st.selectedConversationId && st.selectedConversationId !== liveRouteId) {
|
||||||
|
patch.selectedConversationId = '';
|
||||||
|
}
|
||||||
|
telemetryStore.setState(patch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const curSt = telemetryStore.getState();
|
||||||
|
const effectiveConvId = curSt.selectedConversationId || curSt.hostRouteConversationId || '';
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (st.selectedConversationId) {
|
if (effectiveConvId) {
|
||||||
params.set('conversationId', st.selectedConversationId);
|
params.set('conversationId', effectiveConvId);
|
||||||
}
|
}
|
||||||
if (st.selectedTimeRange) {
|
if (curSt.selectedTimeRange) {
|
||||||
params.set('range', st.selectedTimeRange);
|
params.set('range', curSt.selectedTimeRange);
|
||||||
}
|
}
|
||||||
if (st.selectedTimeRange === 'custom') {
|
if (curSt.selectedTimeRange === 'custom') {
|
||||||
if (st.customStartMs > 0) params.set('startMs', String(st.customStartMs));
|
if (curSt.customStartMs > 0) params.set('startMs', String(curSt.customStartMs));
|
||||||
if (st.customEndMs > 0) params.set('endMs', String(st.customEndMs));
|
if (curSt.customEndMs > 0) params.set('endMs', String(curSt.customEndMs));
|
||||||
}
|
}
|
||||||
if (force) {
|
if (force) {
|
||||||
params.set('force', '1');
|
params.set('force', '1');
|
||||||
@@ -373,7 +521,7 @@ export async function fetchTelemetry({ force = false } = {}) {
|
|||||||
const qs = params.toString();
|
const qs = params.toString();
|
||||||
const payload = await callSidecarApi(`/api/telemetry${qs ? `?${qs}` : ''}`, {
|
const payload = await callSidecarApi(`/api/telemetry${qs ? `?${qs}` : ''}`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
abortKey: 'telemetry-poll',
|
abortKey: force ? 'telemetry-force' : 'telemetry-poll',
|
||||||
});
|
});
|
||||||
|
|
||||||
if (reqSeq !== latestRequestSeq) {
|
if (reqSeq !== latestRequestSeq) {
|
||||||
@@ -382,7 +530,11 @@ export async function fetchTelemetry({ force = false } = {}) {
|
|||||||
|
|
||||||
if (payload?.uiBundleVersion) {
|
if (payload?.uiBundleVersion) {
|
||||||
if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) {
|
if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) {
|
||||||
if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') {
|
if (
|
||||||
|
!isWindowOverlayMode() &&
|
||||||
|
typeof window !== 'undefined' &&
|
||||||
|
typeof window.location?.reload === 'function'
|
||||||
|
) {
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
@@ -402,6 +554,7 @@ export async function fetchTelemetry({ force = false } = {}) {
|
|||||||
if (feedbackTimer) clearTimeout(feedbackTimer);
|
if (feedbackTimer) clearTimeout(feedbackTimer);
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
telemetry: payload,
|
telemetry: payload,
|
||||||
|
minuteTick: Math.floor(Date.now() / 30000),
|
||||||
syncState: 'synced',
|
syncState: 'synced',
|
||||||
});
|
});
|
||||||
feedbackTimer = setTimeout(() => {
|
feedbackTimer = setTimeout(() => {
|
||||||
@@ -413,6 +566,7 @@ export async function fetchTelemetry({ force = false } = {}) {
|
|||||||
const nextTelemetry = isSame ? latestSt.telemetry : payload;
|
const nextTelemetry = isSame ? latestSt.telemetry : payload;
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
telemetry: nextTelemetry,
|
telemetry: nextTelemetry,
|
||||||
|
minuteTick: Math.floor(Date.now() / 30000),
|
||||||
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -421,37 +575,46 @@ export async function fetchTelemetry({ force = false } = {}) {
|
|||||||
if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null;
|
if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null;
|
||||||
telemetryStore.setState({ syncState: 'error' });
|
telemetryStore.setState({ syncState: 'error' });
|
||||||
return null;
|
return null;
|
||||||
|
} finally {
|
||||||
|
if (force) {
|
||||||
|
activeForceCount = Math.max(0, activeForceCount - 1);
|
||||||
|
if (activeForceCount === 0 && loopActive && loopTickFn && !pollTimer) {
|
||||||
|
pollTimer = setTimeout(loopTickFn, loopIntervalMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveSettingsPatch(patch) {
|
export async function saveSettingsPatch(patch) {
|
||||||
|
const safePatch = patch && typeof patch === 'object' ? { ...patch } : {};
|
||||||
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||||
|
const mode = safePatch.weeklyLimitMode;
|
||||||
|
safePatch.weeklyLimitMode =
|
||||||
|
mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official';
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) {
|
||||||
|
safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession);
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
|
||||||
|
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
|
||||||
|
}
|
||||||
const prevTelemetry = telemetryStore.getState().telemetry;
|
const prevTelemetry = telemetryStore.getState().telemetry;
|
||||||
if (prevTelemetry?.settings) {
|
if (prevTelemetry?.settings) {
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
telemetry: {
|
telemetry: {
|
||||||
...prevTelemetry,
|
...prevTelemetry,
|
||||||
settings: { ...prevTelemetry.settings, ...patch },
|
settings: { ...prevTelemetry.settings, ...safePatch },
|
||||||
activeConversation: patch.contextWindowLimit
|
|
||||||
? {
|
|
||||||
...prevTelemetry.activeConversation,
|
|
||||||
context: {
|
|
||||||
...prevTelemetry.activeConversation?.context,
|
|
||||||
limitTokens: patch.contextWindowLimit,
|
|
||||||
usedPct: Math.min(
|
|
||||||
100,
|
|
||||||
Math.round(
|
|
||||||
((prevTelemetry.activeConversation?.context?.totalTokens || 0) /
|
|
||||||
Math.max(1, patch.contextWindowLimit)) *
|
|
||||||
100
|
|
||||||
)
|
|
||||||
),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: prevTelemetry.activeConversation,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
await callSidecarApi('/api/settings', { method: 'POST', body: patch });
|
try {
|
||||||
|
await callSidecarApi('/api/settings', { method: 'POST', body: safePatch });
|
||||||
|
} catch (err) {
|
||||||
|
if (prevTelemetry) {
|
||||||
|
telemetryStore.setState({ telemetry: prevTelemetry });
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
await fetchTelemetry({ force: true });
|
await fetchTelemetry({ force: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -465,7 +628,11 @@ export async function triggerPluginUpdate() {
|
|||||||
const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} });
|
const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} });
|
||||||
if (res?.ok && res?.restarting) {
|
if (res?.ok && res?.restarting) {
|
||||||
await new Promise((r) => setTimeout(r, 1100));
|
await new Promise((r) => setTimeout(r, 1100));
|
||||||
if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') {
|
if (
|
||||||
|
!isWindowOverlayMode() &&
|
||||||
|
typeof window !== 'undefined' &&
|
||||||
|
typeof window.location?.reload === 'function'
|
||||||
|
) {
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -476,27 +643,44 @@ export async function triggerPluginUpdate() {
|
|||||||
|
|
||||||
export function startAsyncTelemetryLoop(intervalMs = 2000) {
|
export function startAsyncTelemetryLoop(intervalMs = 2000) {
|
||||||
stopAsyncTelemetryLoop();
|
stopAsyncTelemetryLoop();
|
||||||
let active = true;
|
loopActive = true;
|
||||||
|
loopIntervalMs = intervalMs;
|
||||||
|
|
||||||
|
const resolveNextDelay = () => {
|
||||||
|
if (isWindowOverlayMode() && typeof document !== 'undefined' && document.hidden) {
|
||||||
|
return Math.max(loopIntervalMs, 8000);
|
||||||
|
}
|
||||||
|
return loopIntervalMs;
|
||||||
|
};
|
||||||
|
|
||||||
const tick = async () => {
|
const tick = async () => {
|
||||||
if (!active) return;
|
pollTimer = null;
|
||||||
|
if (!loopActive) return;
|
||||||
await fetchTelemetry({ force: false });
|
await fetchTelemetry({ force: false });
|
||||||
if (!active) return;
|
if (!loopActive || activeForceCount > 0) return;
|
||||||
pollTimer = setTimeout(tick, intervalMs);
|
if (!pollTimer) {
|
||||||
|
pollTimer = setTimeout(tick, resolveNextDelay());
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
loopTickFn = tick;
|
||||||
|
|
||||||
tick();
|
tick();
|
||||||
return () => {
|
return () => {
|
||||||
active = false;
|
|
||||||
stopAsyncTelemetryLoop();
|
stopAsyncTelemetryLoop();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function stopAsyncTelemetryLoop() {
|
export function stopAsyncTelemetryLoop() {
|
||||||
|
loopActive = false;
|
||||||
|
loopTickFn = null;
|
||||||
if (pollTimer) {
|
if (pollTimer) {
|
||||||
clearTimeout(pollTimer);
|
clearTimeout(pollTimer);
|
||||||
pollTimer = null;
|
pollTimer = null;
|
||||||
}
|
}
|
||||||
|
if (feedbackTimer) {
|
||||||
|
clearTimeout(feedbackTimer);
|
||||||
|
feedbackTimer = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -14,12 +14,10 @@
|
|||||||
@keyframes anim-pulse-dot {
|
@keyframes anim-pulse-dot {
|
||||||
0%,
|
0%,
|
||||||
100% {
|
100% {
|
||||||
transform: scale(1);
|
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
50% {
|
50% {
|
||||||
transform: scale(1.22);
|
opacity: 0.22;
|
||||||
opacity: 0.62;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,6 +40,11 @@ button,
|
|||||||
input {
|
input {
|
||||||
font-family: inherit;
|
font-family: inherit;
|
||||||
font-size: inherit;
|
font-size: inherit;
|
||||||
|
font-stretch: inherit;
|
||||||
|
font-variation-settings: inherit;
|
||||||
|
line-height: inherit;
|
||||||
|
letter-spacing: inherit;
|
||||||
|
font-variant-numeric: inherit;
|
||||||
color: inherit;
|
color: inherit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -523,10 +523,6 @@
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.custom-scroll-host[hidden] {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-scroll-content {
|
.custom-scroll-content {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -678,10 +674,6 @@
|
|||||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
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 {
|
.update-badge-btn:hover {
|
||||||
opacity: 0.9;
|
opacity: 0.9;
|
||||||
}
|
}
|
||||||
@@ -689,3 +681,130 @@
|
|||||||
.update-badge-btn:active {
|
.update-badge-btn:active {
|
||||||
transform: scale(0.96);
|
transform: scale(0.96);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- 9. 顶部栏定制面板专属表单与排序槽位控件 (Topbar Customization Controls) --- */
|
||||||
|
.settings-inline-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-3);
|
||||||
|
min-height: 26px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-header-right {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost-sm {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 20px;
|
||||||
|
padding: 0 6px;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
transition:
|
||||||
|
background-color var(--dur-instant) var(--ease-fast),
|
||||||
|
color var(--dur-instant) var(--ease-fast),
|
||||||
|
border-color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost-sm:hover:not(:disabled) {
|
||||||
|
background: var(--surface-hover);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border-color: var(--border-strong);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost-sm:disabled {
|
||||||
|
opacity: 0.42;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-slot-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-slot-row {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 2px 4px 2px 6px;
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
background: transparent;
|
||||||
|
transition: border-color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-slot-row:focus-within,
|
||||||
|
.topbar-slot-row:has(.is-open) {
|
||||||
|
z-index: 30;
|
||||||
|
border-color: var(--border-strong);
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-slot-row .select-menu {
|
||||||
|
max-height: 216px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-index-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
font-size: 10.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-order-btns {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 2px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-move-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
cursor: pointer;
|
||||||
|
transition:
|
||||||
|
background-color var(--dur-instant) var(--ease-fast),
|
||||||
|
color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-move-btn:hover:not(:disabled) {
|
||||||
|
background: var(--surface-hover);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-move-btn:active:not(:disabled) {
|
||||||
|
transform: scale(0.94);
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-move-btn:disabled {
|
||||||
|
opacity: 0.28;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,589 @@
|
|||||||
|
/*
|
||||||
|
* 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css).
|
||||||
|
* 严格遵循单层微边框与语义变量规范(零硬编码色值、零 Emoji、硬件加速合成层动画)。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */
|
||||||
|
:host(.wm-capsule-host) {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
height: 28px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
vertical-align: middle;
|
||||||
|
-webkit-app-region: no-drag;
|
||||||
|
pointer-events: auto;
|
||||||
|
user-select: none;
|
||||||
|
font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 450;
|
||||||
|
font-stretch: 100%;
|
||||||
|
font-variation-settings: normal;
|
||||||
|
line-height: 18px;
|
||||||
|
letter-spacing: 0.015em;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
color: var(--text-primary);
|
||||||
|
z-index: 2147482900;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="flow"]) {
|
||||||
|
position: relative;
|
||||||
|
margin-right: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="fixed"]) {
|
||||||
|
position: fixed;
|
||||||
|
top: 6px;
|
||||||
|
right: 144px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes wm-dot-pulse {
|
||||||
|
0%, 100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.38;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 左侧多会话实时状态触发器(无边框、与宿主顶栏按钮同高 28px、整数行高防压扁) */
|
||||||
|
.wm-multi-btn {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0 8px;
|
||||||
|
margin: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
box-shadow: none;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 450;
|
||||||
|
line-height: 18px;
|
||||||
|
letter-spacing: 0.015em;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
cursor: pointer;
|
||||||
|
-webkit-app-region: no-drag;
|
||||||
|
white-space: nowrap;
|
||||||
|
contain: layout style;
|
||||||
|
transition:
|
||||||
|
background-color var(--dur-instant) var(--ease-fast),
|
||||||
|
color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-btn[hidden],
|
||||||
|
.wm-cap-slot[hidden],
|
||||||
|
.wm-sep[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-btn:hover {
|
||||||
|
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-btn.is-open {
|
||||||
|
background: color-mix(in srgb, var(--text-primary) 11%, transparent);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
background: color-mix(in srgb, var(--text-secondary) 44%, transparent);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-btn.is-running .wm-multi-dot {
|
||||||
|
background: var(--accent-primary);
|
||||||
|
animation: wm-dot-pulse 1.5s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-btn.is-waiting .wm-multi-dot {
|
||||||
|
background: var(--metric-warn);
|
||||||
|
animation: wm-dot-pulse 1.5s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-label {
|
||||||
|
display: inline-block;
|
||||||
|
min-width: 46px;
|
||||||
|
line-height: 18px;
|
||||||
|
text-align: left;
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-btn.is-running .wm-multi-label,
|
||||||
|
.wm-multi-btn.is-waiting .wm-multi-label {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-capsule-btn {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0 9px;
|
||||||
|
margin: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
box-shadow: none;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 450;
|
||||||
|
line-height: 18px;
|
||||||
|
letter-spacing: 0.015em;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
cursor: pointer;
|
||||||
|
-webkit-app-region: no-drag;
|
||||||
|
white-space: nowrap;
|
||||||
|
contain: layout style;
|
||||||
|
transition:
|
||||||
|
background-color var(--dur-instant) var(--ease-fast),
|
||||||
|
color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-capsule-btn:hover {
|
||||||
|
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-capsule-btn.is-open {
|
||||||
|
background: color-mix(in srgb, var(--text-primary) 11%, transparent);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 右侧胶囊通用槽位容器与按指标预占定宽(严格防止动态数值跳动,保留舒展字间距) */
|
||||||
|
.wm-cap-slot {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 18px;
|
||||||
|
line-height: 18px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-slot-text {
|
||||||
|
display: inline-block;
|
||||||
|
line-height: 18px;
|
||||||
|
letter-spacing: 0.015em;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */
|
||||||
|
.wm-ctx-seg {
|
||||||
|
justify-content: center;
|
||||||
|
gap: 5px;
|
||||||
|
width: 50px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-ring-svg {
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
transform: rotate(-90deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-ring-track {
|
||||||
|
fill: none;
|
||||||
|
stroke: color-mix(in srgb, var(--text-secondary) 24%, transparent);
|
||||||
|
stroke-width: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-ring-fill {
|
||||||
|
fill: none;
|
||||||
|
stroke: var(--accent-primary);
|
||||||
|
stroke-width: 2;
|
||||||
|
stroke-linecap: round;
|
||||||
|
transition:
|
||||||
|
stroke-dashoffset var(--dur-normal) var(--ease-fast),
|
||||||
|
stroke var(--dur-fast) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-ring-fill.tone-warn {
|
||||||
|
stroke: var(--metric-warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-ring-fill.tone-danger {
|
||||||
|
stroke: var(--metric-danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-ctx-pct {
|
||||||
|
min-width: 27px;
|
||||||
|
max-width: 31px;
|
||||||
|
text-align: left;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-sep {
|
||||||
|
width: 1px;
|
||||||
|
height: 12px;
|
||||||
|
background: color-mix(in srgb, var(--text-secondary) 26%, transparent);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 速度槽位(固定预占宽度 58px 居中对齐) */
|
||||||
|
.wm-seg-speed {
|
||||||
|
width: 58px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-speed-text {
|
||||||
|
width: 58px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-seg-speed.state-running {
|
||||||
|
color: var(--metric-speed);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 首字延迟槽位(固定预占宽度 46px 居中对齐,覆盖 0.85s ~ 105s) */
|
||||||
|
.wm-seg-ttft {
|
||||||
|
width: 46px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-ttft-text {
|
||||||
|
width: 46px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 本次费用槽位(固定预占宽度 52px 居中对齐,覆盖 <$0.001 ~ $99.99) */
|
||||||
|
.wm-seg-cost {
|
||||||
|
width: 52px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-cost-text {
|
||||||
|
width: 52px;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 配额槽位(固定预占宽度 52px 居中对齐,完整容纳 余 100% / 余 --% 且在任意槽位对称) */
|
||||||
|
.wm-seg-quota {
|
||||||
|
width: 52px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-quota-text {
|
||||||
|
width: 52px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-cap-slot.tone-warn,
|
||||||
|
.wm-cap-slot.tone-warn .wm-slot-text {
|
||||||
|
color: var(--metric-warn);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-cap-slot.tone-danger,
|
||||||
|
.wm-cap-slot.tone-danger .wm-slot-text {
|
||||||
|
color: var(--metric-danger);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 右上角绝对定位更新圆点,不参与文档流,零宽度抖动 */
|
||||||
|
.wm-update-dot {
|
||||||
|
position: absolute;
|
||||||
|
top: 3px;
|
||||||
|
right: 3px;
|
||||||
|
width: 5px;
|
||||||
|
height: 5px;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
background: var(--metric-ok);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 与分隔线次序 data-sep-for-rank 动态折叠) */
|
||||||
|
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="3"],
|
||||||
|
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="2"],
|
||||||
|
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="3"],
|
||||||
|
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="2"],
|
||||||
|
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="3"],
|
||||||
|
:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-label {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-btn,
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-btn {
|
||||||
|
padding: 0 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="2"],
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="3"],
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="2"],
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="3"],
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct,
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-capsule-btn {
|
||||||
|
padding: 0 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg {
|
||||||
|
width: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 2. 顶层浮层传送门宿主 (Body Portal Host: Multi-Session HUD, Tooltip & Full 4-Tab Popover) --- */
|
||||||
|
:host(.wm-portal-host) {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
width: 0;
|
||||||
|
height: 0;
|
||||||
|
overflow: visible;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 2147483000;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.4;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes wm-popover-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-3px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-popover-panel {
|
||||||
|
position: fixed;
|
||||||
|
top: 42px;
|
||||||
|
left: 12px;
|
||||||
|
width: min(492px, calc(100vw - 24px));
|
||||||
|
height: min(588px, calc(100vh - 54px));
|
||||||
|
max-height: calc(100vh - 54px);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--surface-bg);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
box-shadow: var(--shadow-overlay);
|
||||||
|
pointer-events: auto;
|
||||||
|
overflow: hidden;
|
||||||
|
-webkit-app-region: no-drag;
|
||||||
|
transform-origin: top right;
|
||||||
|
animation: wm-popover-in var(--dur-fast) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-popover-panel .app-shell {
|
||||||
|
height: 100%;
|
||||||
|
max-height: 100%;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 顶栏胶囊悬停全景概览浮层(复用实时概览三卡片架构,全槽位预占,仅就地更新节点不跳动) */
|
||||||
|
.wm-hover-tip {
|
||||||
|
position: fixed;
|
||||||
|
top: 42px;
|
||||||
|
left: 12px;
|
||||||
|
width: min(492px, calc(100vw - 24px));
|
||||||
|
max-height: calc(100vh - 54px);
|
||||||
|
padding: var(--space-3) var(--space-4);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
background: var(--surface-bg);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
box-shadow: var(--shadow-overlay);
|
||||||
|
pointer-events: none;
|
||||||
|
overflow: hidden;
|
||||||
|
contain: layout style;
|
||||||
|
z-index: 2147483001;
|
||||||
|
transform-origin: top right;
|
||||||
|
animation: wm-popover-in var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 左侧在线多会话实时看板浮层(单层无套娃细线卡片,仅显示在线运行会话,留足呼吸感) */
|
||||||
|
.wm-multi-panel {
|
||||||
|
position: fixed;
|
||||||
|
top: 42px;
|
||||||
|
left: 12px;
|
||||||
|
width: min(484px, calc(100vw - 24px));
|
||||||
|
max-height: calc(100vh - 54px);
|
||||||
|
padding: 14px 16px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0;
|
||||||
|
background: var(--surface-bg);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
box-shadow: var(--shadow-overlay);
|
||||||
|
pointer-events: auto;
|
||||||
|
overflow-x: hidden;
|
||||||
|
overflow-y: auto;
|
||||||
|
-webkit-app-region: no-drag;
|
||||||
|
contain: layout style;
|
||||||
|
z-index: 2147483002;
|
||||||
|
transform-origin: top left;
|
||||||
|
animation: wm-popover-in var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-popover-panel.is-instant,
|
||||||
|
.wm-hover-tip.is-instant,
|
||||||
|
.wm-multi-panel.is-instant {
|
||||||
|
animation: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-hover-tip .cell-label,
|
||||||
|
.wm-hover-tip .legend-item,
|
||||||
|
.wm-hover-tip .legend-left,
|
||||||
|
.wm-hover-tip .panel-header > span {
|
||||||
|
white-space: nowrap;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-hover-tip .panel-header > span:first-child:not(.panel-title) {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-hover-quota-pools {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-hover-quota-foot {
|
||||||
|
font-size: 11px;
|
||||||
|
padding-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-pin-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 16px;
|
||||||
|
padding: 0 5px;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--accent-primary);
|
||||||
|
background: var(--accent-primary-soft);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-session-tag {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 16px;
|
||||||
|
padding: 0 4px;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-session-tag.is-here {
|
||||||
|
color: var(--accent-primary);
|
||||||
|
background: var(--accent-primary-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-task-metrics {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-header {
|
||||||
|
padding-bottom: 10px;
|
||||||
|
border-bottom: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 多会话单层面板内去除重复边框与底色,留足行距与段落呼吸感,仅靠左侧圆点闪烁表达状态 */
|
||||||
|
.wm-multi-panel .live-activity-list {
|
||||||
|
gap: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-panel .live-task-card {
|
||||||
|
gap: 8px;
|
||||||
|
padding: 12px 2px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 0;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-panel .live-task-card:first-child {
|
||||||
|
padding-top: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-panel .live-task-card:last-child {
|
||||||
|
padding-bottom: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-panel .live-task-card + .live-task-card {
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-panel .live-task-title {
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-empty {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-3);
|
||||||
|
min-height: 36px;
|
||||||
|
padding: 12px 2px 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-empty-left {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-idle-dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
background: color-mix(in srgb, var(--text-secondary) 38%, transparent);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-empty-hint {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
@@ -4,26 +4,24 @@
|
|||||||
* eliminating hardcoded hex colors across components and views.
|
* eliminating hardcoded hex colors across components and views.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
:root {
|
:root,
|
||||||
|
:host {
|
||||||
/* Architectural Geometry: Only Top Nav uses --radius-pill */
|
/* Architectural Geometry: Only Top Nav uses --radius-pill */
|
||||||
--radius-pill: 999px;
|
--radius-pill: 999px;
|
||||||
--radius-sm: 4px;
|
--radius-sm: 4px;
|
||||||
--radius-xs: 2px;
|
--radius-xs: 2px;
|
||||||
|
|
||||||
/* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode) */
|
/* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode & safe dark fallback) */
|
||||||
--surface-bg: var(--background, hsl(0 0% 100%));
|
--surface-bg: var(--background, hsl(0 0% 100%));
|
||||||
--surface-panel: var(--card, hsl(0 0% 100%));
|
--surface-panel: var(--card, var(--background, hsl(0 0% 100%)));
|
||||||
--surface-subtle: color-mix(in srgb, var(--surface-panel) 97%, var(--text-primary) 3%);
|
--surface-subtle: color-mix(in srgb, var(--surface-panel) 97%, var(--text-primary) 3%);
|
||||||
--surface-track: color-mix(in srgb, var(--border-hairline) 42%, var(--surface-panel));
|
--surface-track: color-mix(in srgb, var(--border-hairline) 42%, var(--surface-panel));
|
||||||
--surface-elevated: var(--surface-panel);
|
|
||||||
--surface-hover: color-mix(in srgb, var(--accent-primary) 6%, var(--surface-panel));
|
--surface-hover: color-mix(in srgb, var(--accent-primary) 6%, var(--surface-panel));
|
||||||
--surface-active: color-mix(in srgb, var(--accent-primary) 12%, var(--surface-panel));
|
--surface-active: color-mix(in srgb, var(--accent-primary) 12%, var(--surface-panel));
|
||||||
--surface-backdrop: color-mix(in srgb, var(--surface-bg) 78%, transparent);
|
|
||||||
|
|
||||||
/* Crisp 1px Hairline Borders */
|
/* Crisp 1px Hairline Borders */
|
||||||
--border-hairline: color-mix(in srgb, var(--border, hsl(214 18% 88%)) 82%, var(--surface-panel));
|
--border-hairline: color-mix(in srgb, var(--border, hsl(214 18% 88%)) 82%, var(--surface-panel));
|
||||||
--border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%);
|
--border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%);
|
||||||
--border-focus: var(--accent-primary);
|
|
||||||
|
|
||||||
/* Typography Hierarchy */
|
/* Typography Hierarchy */
|
||||||
--text-primary: var(--foreground, hsl(215 22% 15%));
|
--text-primary: var(--foreground, hsl(215 22% 15%));
|
||||||
@@ -46,10 +44,8 @@
|
|||||||
--metric-warn-soft: color-mix(in srgb, var(--metric-warn) 15%, transparent);
|
--metric-warn-soft: color-mix(in srgb, var(--metric-warn) 15%, transparent);
|
||||||
|
|
||||||
--metric-danger: var(--destructive, hsl(0 74% 50%));
|
--metric-danger: var(--destructive, hsl(0 74% 50%));
|
||||||
--metric-danger-soft: color-mix(in srgb, var(--metric-danger) 15%, transparent);
|
|
||||||
|
|
||||||
/* Context Window 10-Channel Palette */
|
/* Context Window 10-Channel Palette */
|
||||||
--ctx-messages: hsl(217 82% 51%);
|
|
||||||
--ctx-assistant: hsl(217 82% 54%);
|
--ctx-assistant: hsl(217 82% 54%);
|
||||||
--ctx-tool-results: hsl(192 82% 43%);
|
--ctx-tool-results: hsl(192 82% 43%);
|
||||||
--ctx-user-input: hsl(245 72% 62%);
|
--ctx-user-input: hsl(245 72% 62%);
|
||||||
@@ -69,7 +65,7 @@
|
|||||||
|
|
||||||
/* Elevation & Shadows */
|
/* Elevation & Shadows */
|
||||||
--shadow-popover: 0 4px 12px rgb(0 0 0 / 0.22);
|
--shadow-popover: 0 4px 12px rgb(0 0 0 / 0.22);
|
||||||
--shadow-glider: 0 1px 2px rgb(0 0 0 / 0.14);
|
--shadow-overlay: 0 16px 38px rgb(0 0 0 / 0.38), 0 3px 10px rgb(0 0 0 / 0.22);
|
||||||
|
|
||||||
/* Fast Hardware-Accelerated Motion Tokens */
|
/* Fast Hardware-Accelerated Motion Tokens */
|
||||||
--ease-fast: cubic-bezier(0.22, 1, 0.36, 1);
|
--ease-fast: cubic-bezier(0.22, 1, 0.36, 1);
|
||||||
@@ -78,10 +74,8 @@
|
|||||||
--dur-normal: 180ms;
|
--dur-normal: 180ms;
|
||||||
|
|
||||||
/* Spacing & Density */
|
/* Spacing & Density */
|
||||||
--space-1: 4px;
|
|
||||||
--space-2: 6px;
|
--space-2: 6px;
|
||||||
--space-3: 8px;
|
--space-3: 8px;
|
||||||
--space-4: 10px;
|
--space-4: 10px;
|
||||||
--space-5: 12px;
|
--space-5: 12px;
|
||||||
--space-6: 14px;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
* 全景消耗统计视图样式表 (views-consumption.css).
|
* 全景消耗统计视图样式表 (views-consumption.css).
|
||||||
* 包含:
|
* 包含:
|
||||||
* 1. 消费概览顶栏与 3+2 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-*, .cons-col)
|
* 1. 消费概览顶栏与 3+3 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-3, .cons-col)
|
||||||
* 2. 4 段比例条与圆点色块 (.dot-swatch, .cons-seg-bar)
|
* 2. 4 段比例条与圆点色块 (.dot-swatch, .cons-seg-bar)
|
||||||
* 3. 热门模型与数据来源列表项样式 (.cons-row-*, .cons-share-pill, .cons-item-*)
|
* 3. 热门模型与数据来源列表项样式 (.cons-row-*, .cons-share-pill, .cons-item-*)
|
||||||
* 4. 历史趋势纯 SVG 平滑曲线图与峰值胶囊 (.trend-*)
|
* 4. 历史趋势纯 SVG 平滑曲线图与峰值胶囊 (.trend-*)
|
||||||
* 5. 12 个月垂直堆叠柱状图与月度图例 (.monthly-*, .month-*)
|
* 5. 12 个月垂直堆叠柱状图与月度图例 (.monthly-*, .month-*)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* --- 1. 消费概览顶栏与 3+2 组合指标矩阵 (Consumption Overview Matrix) --- */
|
/* --- 1. 消费概览顶栏与 3+3 组合指标矩阵 (Consumption Overview Matrix) --- */
|
||||||
.cons-overview-head {
|
.cons-overview-head {
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: 6px;
|
gap: 6px;
|
||||||
@@ -48,15 +48,28 @@
|
|||||||
grid-template-columns: repeat(3, 1fr);
|
grid-template-columns: repeat(3, 1fr);
|
||||||
}
|
}
|
||||||
|
|
||||||
.cons-split-2 {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: 1fr 1fr;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cons-matrix-bottom {
|
.cons-matrix-bottom {
|
||||||
border-top: 1px solid var(--border-hairline);
|
border-top: 1px solid var(--border-hairline);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cons-matrix-bottom .cons-col {
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 350px) {
|
||||||
|
.cons-matrix-bottom.cons-split-3 {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.cons-matrix-bottom .cons-col {
|
||||||
|
padding-left: 0;
|
||||||
|
padding-right: 0;
|
||||||
|
}
|
||||||
|
.cons-matrix-bottom .cons-col.is-bordered-col {
|
||||||
|
border-left: none;
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.cons-col {
|
.cons-col {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -105,10 +118,34 @@
|
|||||||
letter-spacing: -0.02em;
|
letter-spacing: -0.02em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.cons-mid-num {
|
.cons-sub-head {
|
||||||
font-size: 13px;
|
display: flex;
|
||||||
font-weight: 700;
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cons-sub-head > span {
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cons-sub-label {
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 600;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cons-mid-num {
|
||||||
|
font-size: 14.5px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.25;
|
||||||
|
color: var(--text-primary);
|
||||||
|
letter-spacing: -0.015em;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- 2. 4 段比例条与圆点色块 (Four-Segment Bar & Dot Swatches) --- */
|
/* --- 2. 4 段比例条与圆点色块 (Four-Segment Bar & Dot Swatches) --- */
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
* 包含:
|
* 包含:
|
||||||
* 1. 通用面板容器与标题头 (.panel, .panel-header, .panel-title, .panel-meta)
|
* 1. 通用面板容器与标题头 (.panel, .panel-header, .panel-title, .panel-meta)
|
||||||
* 2. 4 格实时测速指标矩阵 (.telemetry-matrix, .matrix-cell, .cell-*)
|
* 2. 4 格实时测速指标矩阵 (.telemetry-matrix, .matrix-cell, .cell-*)
|
||||||
* 3. 6 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill)
|
* 3. 10 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill)
|
||||||
* 4. 上下文双列图例网格与色块 (.ctx-legend-grid, .legend-*, .swatch)
|
* 4. 上下文双列图例网格与色块 (.ctx-legend-grid, .legend-*, .swatch)
|
||||||
* 5. 双栏布局网格与窄屏响应式断点 (.dual-grid)
|
* 5. 双栏布局网格与窄屏响应式断点 (.dual-grid)
|
||||||
*/
|
*/
|
||||||
@@ -57,50 +57,42 @@
|
|||||||
.live-activity-list {
|
.live-activity-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 6px;
|
gap: 8px;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-activity-list[hidden] {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.live-task-card {
|
.live-task-card {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 5px;
|
gap: 7px;
|
||||||
padding: 7px 10px;
|
padding: 10px 12px;
|
||||||
border: 1px solid var(--accent-primary-border);
|
border: 1px solid var(--border-hairline);
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
background: color-mix(in srgb, var(--accent-primary) 5%, var(--surface-panel));
|
background: var(--surface-panel);
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-task-card.is-waiting {
|
|
||||||
border-color: color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline));
|
|
||||||
background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel));
|
|
||||||
}
|
|
||||||
|
|
||||||
.live-task-header {
|
.live-task-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: var(--space-2);
|
gap: var(--space-3);
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-task-title-wrap {
|
.live-task-title-wrap {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 7px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-task-title {
|
.live-task-title {
|
||||||
font-size: 11.5px;
|
font-size: 12px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
line-height: 1.45;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
@@ -116,7 +108,7 @@
|
|||||||
.live-task-header-right {
|
.live-task-header-right {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 6px;
|
gap: 8px;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,16 +143,13 @@
|
|||||||
background: var(--accent-primary-soft);
|
background: var(--accent-primary-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-sub-toggle[hidden] {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.live-task-main-row {
|
.live-task-main-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 6px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding-left: 1px;
|
padding-left: 18px;
|
||||||
|
line-height: 1.45;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-activity-dot {
|
.live-activity-dot {
|
||||||
@@ -174,37 +163,37 @@
|
|||||||
color: var(--metric-warn);
|
color: var(--metric-warn);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.live-task-card.is-compacting .live-activity-dot {
|
||||||
|
color: var(--ctx-checkpoint);
|
||||||
|
}
|
||||||
|
|
||||||
.live-activity-phase {
|
.live-activity-phase {
|
||||||
font-size: 11px;
|
font-size: 11.5px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-task-card.is-waiting .live-activity-phase {
|
|
||||||
color: var(--metric-warn);
|
|
||||||
}
|
|
||||||
|
|
||||||
.live-activity-progress {
|
.live-activity-progress {
|
||||||
font-size: 10px;
|
font-size: 10.5px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--accent-primary);
|
color: var(--accent-primary);
|
||||||
background: var(--accent-primary-soft);
|
background: var(--accent-primary-soft);
|
||||||
padding: 0 4px;
|
padding: 0 5px;
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-activity-sep {
|
.live-activity-sep {
|
||||||
font-size: 11px;
|
font-size: 11.5px;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-activity-detail {
|
.live-activity-detail {
|
||||||
font-size: 11px;
|
font-size: 11.5px;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
@@ -214,38 +203,35 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.live-activity-elapsed {
|
.live-activity-elapsed {
|
||||||
font-size: 11px;
|
font-size: 11.5px;
|
||||||
font-weight: 600;
|
font-weight: 500;
|
||||||
color: var(--accent-primary);
|
color: var(--text-secondary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
min-width: 28px;
|
||||||
|
text-align: right;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-task-card.is-waiting .live-activity-elapsed {
|
|
||||||
color: var(--metric-warn);
|
|
||||||
}
|
|
||||||
|
|
||||||
.live-sub-list {
|
.live-sub-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 4px;
|
gap: 8px;
|
||||||
padding-top: 5px;
|
padding-top: 9px;
|
||||||
margin-top: 1px;
|
margin-top: 3px;
|
||||||
|
margin-left: 18px;
|
||||||
border-top: 1px dashed var(--border-hairline);
|
border-top: 1px dashed var(--border-hairline);
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-sub-list[hidden] {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.live-sub-row {
|
.live-sub-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: var(--space-2);
|
gap: 10px;
|
||||||
|
min-height: 22px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
font-size: 10.5px;
|
font-size: 11.5px;
|
||||||
|
line-height: 1.45;
|
||||||
}
|
}
|
||||||
|
|
||||||
.live-sub-row.is-done {
|
.live-sub-row.is-done {
|
||||||
@@ -255,7 +241,7 @@
|
|||||||
.live-sub-left {
|
.live-sub-left {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 7px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
}
|
}
|
||||||
@@ -266,7 +252,7 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
max-width: 110px;
|
max-width: 148px;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,9 +266,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.live-sub-elapsed {
|
.live-sub-elapsed {
|
||||||
font-size: 10.5px;
|
font-size: 11px;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
min-width: 28px;
|
||||||
|
text-align: right;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,7 +327,7 @@
|
|||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- 3. 6 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */
|
/* --- 3. 10 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */
|
||||||
.progress-track {
|
.progress-track {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 6px;
|
height: 6px;
|
||||||
@@ -444,6 +432,7 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.swatch {
|
.swatch {
|
||||||
@@ -463,10 +452,6 @@
|
|||||||
.swatch.seg-skills { background: var(--ctx-skills); }
|
.swatch.seg-skills { background: var(--ctx-skills); }
|
||||||
.swatch.seg-system-prompt { background: var(--ctx-system-prompt); }
|
.swatch.seg-system-prompt { background: var(--ctx-system-prompt); }
|
||||||
.swatch.seg-user-rules { background: var(--ctx-user-rules); }
|
.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) --- */
|
/* --- 5. 双栏网格与窄视口响应式折叠 (Dual Grid & Responsive Breakpoints) --- */
|
||||||
.dual-grid {
|
.dual-grid {
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview View 2: ConsumptionView (全景消耗统计视图).
|
* @fileoverview View 2: ConsumptionView (全景消耗统计视图).
|
||||||
* 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗:
|
* 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗:
|
||||||
* 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+2 组合矩阵展示总 Token/调用次数、
|
* 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+3 组合矩阵展示总 Token/调用次数、
|
||||||
* USD/CNY 预估费用、缓存命中率与命中量、输入/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。
|
* USD/CNY 预估费用、缓存命中率与命中量、新输入/缓存读取(含节省费用)/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。
|
||||||
* 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡与首/中/末三时间锚点。
|
* 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡、对齐多刻度时间轴与悬停详情浮层。
|
||||||
* 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。
|
* 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。
|
||||||
* 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。
|
* 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。
|
||||||
* 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。
|
* 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。
|
||||||
@@ -48,27 +48,45 @@ export const ConsumptionView = defineComponent({
|
|||||||
name: 'ConsumptionView',
|
name: 'ConsumptionView',
|
||||||
setup({ onCleanup }) {
|
setup({ onCleanup }) {
|
||||||
// --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 ---
|
// --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 ---
|
||||||
|
let draftStartMs = telemetryStore.getState().customStartMs;
|
||||||
|
let draftEndMs = telemetryStore.getState().customEndMs;
|
||||||
|
let hasUncommittedCustomDraft = false;
|
||||||
|
|
||||||
const timeFilterSwitch = SegmentedControl({
|
const timeFilterSwitch = SegmentedControl({
|
||||||
ariaLabel: '消耗统计时间范围',
|
ariaLabel: '消耗统计时间范围',
|
||||||
modelValue: telemetryStore.getState().selectedTimeRange,
|
modelValue: telemetryStore.getState().selectedTimeRange,
|
||||||
options: TIME_RANGE_OPTIONS,
|
options: TIME_RANGE_OPTIONS,
|
||||||
onUpdateModelValue: (nextRange) => {
|
onUpdateModelValue: (nextRange) => {
|
||||||
|
if (nextRange === 'custom') {
|
||||||
|
const st = telemetryStore.getState();
|
||||||
|
draftStartMs = st.customStartMs;
|
||||||
|
draftEndMs = st.customEndMs;
|
||||||
|
hasUncommittedCustomDraft = false;
|
||||||
|
startPicker.setValue(draftStartMs);
|
||||||
|
endPicker.setValue(draftEndMs);
|
||||||
|
} else {
|
||||||
|
hasUncommittedCustomDraft = false;
|
||||||
|
}
|
||||||
telemetryStore.setState({ selectedTimeRange: nextRange });
|
telemetryStore.setState({ selectedTimeRange: nextRange });
|
||||||
fetchTelemetry({ force: false });
|
fetchTelemetry({ force: false });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const startPicker = CustomDateTimePicker({
|
const startPicker = CustomDateTimePicker({
|
||||||
modelValue: telemetryStore.getState().customStartMs,
|
modelValue: draftStartMs,
|
||||||
onUpdateModelValue: (ms) => {
|
onUpdateModelValue: (ms) => {
|
||||||
telemetryStore.setState({ customStartMs: ms });
|
draftStartMs = ms;
|
||||||
|
hasUncommittedCustomDraft = true;
|
||||||
|
startPicker.setValue(ms);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const endPicker = CustomDateTimePicker({
|
const endPicker = CustomDateTimePicker({
|
||||||
modelValue: telemetryStore.getState().customEndMs,
|
modelValue: draftEndMs,
|
||||||
onUpdateModelValue: (ms) => {
|
onUpdateModelValue: (ms) => {
|
||||||
telemetryStore.setState({ customEndMs: ms });
|
draftEndMs = ms;
|
||||||
|
hasUncommittedCustomDraft = true;
|
||||||
|
endPicker.setValue(ms);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -79,20 +97,20 @@ export const ConsumptionView = defineComponent({
|
|||||||
className: 'btn-primary',
|
className: 'btn-primary',
|
||||||
style: 'height: 26px; padding: 0 10px;',
|
style: 'height: 26px; padding: 0 10px;',
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
const st = telemetryStore.getState();
|
const sMs = Number(draftStartMs || 0);
|
||||||
const sMs = Number(st.customStartMs || 0);
|
const eMs = Number(draftEndMs || 0);
|
||||||
const eMs = Number(st.customEndMs || 0);
|
const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs;
|
||||||
if (sMs > 0 && eMs > 0 && sMs > eMs) {
|
const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs;
|
||||||
startPicker.setValue(eMs);
|
draftStartMs = minMs;
|
||||||
endPicker.setValue(sMs);
|
draftEndMs = maxMs;
|
||||||
|
hasUncommittedCustomDraft = false;
|
||||||
|
startPicker.setValue(minMs);
|
||||||
|
endPicker.setValue(maxMs);
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
selectedTimeRange: 'custom',
|
selectedTimeRange: 'custom',
|
||||||
customStartMs: eMs,
|
customStartMs: minMs,
|
||||||
customEndMs: sMs,
|
customEndMs: maxMs,
|
||||||
});
|
});
|
||||||
} else {
|
|
||||||
telemetryStore.setState({ selectedTimeRange: 'custom' });
|
|
||||||
}
|
|
||||||
fetchTelemetry({ force: true });
|
fetchTelemetry({ force: true });
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -114,7 +132,7 @@ export const ConsumptionView = defineComponent({
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 2 列输入/输出拆分 + 底部 4 段比例条) ---
|
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) ---
|
||||||
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' });
|
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' });
|
||||||
const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' });
|
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 次' });
|
||||||
@@ -126,7 +144,11 @@ 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 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 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: '未命中缓存输入' });
|
||||||
|
|
||||||
|
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||||
|
const cacheMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||||
|
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '节省 $0.00' });
|
||||||
|
|
||||||
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '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 outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||||
@@ -161,27 +183,38 @@ export const ConsumptionView = defineComponent({
|
|||||||
h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]),
|
h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]),
|
||||||
]),
|
]),
|
||||||
]),
|
]),
|
||||||
h('div', { className: 'cons-split-2 cons-matrix-bottom' }, [
|
h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [
|
||||||
h('div', { className: 'cons-col' }, [
|
h('div', { className: 'cons-col' }, [
|
||||||
h('div', { className: 'panel-header' }, [
|
h('div', { className: 'cons-sub-head' }, [
|
||||||
h('span', { className: 'legend-left' }, [
|
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||||
h('span', { className: 'dot-swatch seg-input' }),
|
h('span', { className: 'dot-swatch seg-input' }),
|
||||||
h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输入用量' }),
|
h('span', { text: '新输入' }),
|
||||||
inputMainTokens,
|
|
||||||
]),
|
]),
|
||||||
inputSharePct,
|
inputSharePct,
|
||||||
]),
|
]),
|
||||||
|
inputMainTokens,
|
||||||
inputSubText,
|
inputSubText,
|
||||||
]),
|
]),
|
||||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||||
h('div', { className: 'panel-header' }, [
|
h('div', { className: 'cons-sub-head' }, [
|
||||||
h('span', { className: 'legend-left' }, [
|
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||||
|
h('span', { className: 'dot-swatch seg-cached' }),
|
||||||
|
h('span', { text: '缓存读取' }),
|
||||||
|
]),
|
||||||
|
cacheSharePct,
|
||||||
|
]),
|
||||||
|
cacheMainTokens,
|
||||||
|
cacheSubText,
|
||||||
|
]),
|
||||||
|
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||||
|
h('div', { className: 'cons-sub-head' }, [
|
||||||
|
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||||
h('span', { className: 'dot-swatch seg-output' }),
|
h('span', { className: 'dot-swatch seg-output' }),
|
||||||
h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输出用量' }),
|
h('span', { text: '输出用量' }),
|
||||||
outputMainTokens,
|
|
||||||
]),
|
]),
|
||||||
outputSharePct,
|
outputSharePct,
|
||||||
]),
|
]),
|
||||||
|
outputMainTokens,
|
||||||
outputSubText,
|
outputSubText,
|
||||||
]),
|
]),
|
||||||
]),
|
]),
|
||||||
@@ -416,8 +449,12 @@ export const ConsumptionView = defineComponent({
|
|||||||
if (!slice) return;
|
if (!slice) return;
|
||||||
timeFilterSwitch.setValue(slice.range);
|
timeFilterSwitch.setValue(slice.range);
|
||||||
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
|
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
|
||||||
startPicker.setValue(slice.customStartMs);
|
if (!hasUncommittedCustomDraft) {
|
||||||
endPicker.setValue(slice.customEndMs);
|
draftStartMs = slice.customStartMs;
|
||||||
|
draftEndMs = slice.customEndMs;
|
||||||
|
startPicker.setValue(draftStartMs);
|
||||||
|
endPicker.setValue(draftEndMs);
|
||||||
|
}
|
||||||
|
|
||||||
const cons = slice.consumption || {};
|
const cons = slice.consumption || {};
|
||||||
const preset =
|
const preset =
|
||||||
@@ -436,6 +473,7 @@ export const ConsumptionView = defineComponent({
|
|||||||
const responseTokens = Number(acct.responseTokens || 0);
|
const responseTokens = Number(acct.responseTokens || 0);
|
||||||
const thinkingTokens = Number(acct.thinkingTokens || 0);
|
const thinkingTokens = Number(acct.thinkingTokens || 0);
|
||||||
const costUsd = Number(acct.costUsd || 0);
|
const costUsd = Number(acct.costUsd || 0);
|
||||||
|
const savedCostUsd = Number(acct.savedCostUsd || 0);
|
||||||
|
|
||||||
patchText(heroTotalTokens, formatTokensPrecise(totalTokens));
|
patchText(heroTotalTokens, formatTokensPrecise(totalTokens));
|
||||||
patchText(heroTotalCalls, `${acct.calls || 0} 次`);
|
patchText(heroTotalCalls, `${acct.calls || 0} 次`);
|
||||||
@@ -445,13 +483,37 @@ export const ConsumptionView = defineComponent({
|
|||||||
patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`);
|
patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`);
|
||||||
patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`);
|
patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`);
|
||||||
|
|
||||||
const inPct = totalTokens > 0 ? +((inputTokens / totalTokens) * 100).toFixed(1) : 0;
|
let inPct = 0;
|
||||||
const outPct = totalTokens > 0 ? +((outputTokens / totalTokens) * 100).toFixed(1) : 0;
|
let cachePct = 0;
|
||||||
|
let outPct = 0;
|
||||||
|
if (totalTokens > 0) {
|
||||||
|
const rawTenths = [
|
||||||
|
(inputTokens / totalTokens) * 1000,
|
||||||
|
(cacheTokens / totalTokens) * 1000,
|
||||||
|
(outputTokens / totalTokens) * 1000,
|
||||||
|
];
|
||||||
|
const floored = rawTenths.map((v) => Math.max(0, Math.floor(v)));
|
||||||
|
const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2]));
|
||||||
|
const order = [0, 1, 2].sort(
|
||||||
|
(a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a])
|
||||||
|
);
|
||||||
|
for (let k = 0; k < rem && k < 3; k++) {
|
||||||
|
floored[order[k]] += 1;
|
||||||
|
}
|
||||||
|
inPct = +(floored[0] / 10).toFixed(1);
|
||||||
|
cachePct = +(floored[1] / 10).toFixed(1);
|
||||||
|
outPct = +(floored[2] / 10).toFixed(1);
|
||||||
|
}
|
||||||
|
|
||||||
patchText(inputSharePct, `${inPct}%`);
|
patchText(inputSharePct, `${inPct}%`);
|
||||||
patchText(inputMainTokens, formatTokensPrecise(inputTokens));
|
patchText(inputMainTokens, formatTokensPrecise(inputTokens));
|
||||||
|
patchText(inputSubText, '未命中缓存输入');
|
||||||
|
|
||||||
|
patchText(cacheSharePct, `${cachePct}%`);
|
||||||
|
patchText(cacheMainTokens, formatTokensPrecise(cacheTokens));
|
||||||
patchText(
|
patchText(
|
||||||
inputSubText,
|
cacheSubText,
|
||||||
`新输入 ${formatTokensPrecise(inputTokens)} · 缓存 ${formatTokensPrecise(cacheTokens)}`
|
`节省 ${formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 })}`
|
||||||
);
|
);
|
||||||
|
|
||||||
patchText(outputSharePct, `${outPct}%`);
|
patchText(outputSharePct, `${outPct}%`);
|
||||||
@@ -480,7 +542,8 @@ export const ConsumptionView = defineComponent({
|
|||||||
);
|
);
|
||||||
trendChart.update(trendSeries);
|
trendChart.update(trendSeries);
|
||||||
|
|
||||||
// 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账)
|
// 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账,遵循模型名称显示格式设置)
|
||||||
|
const showUpstream = Boolean(slice.showUpstreamModel);
|
||||||
const models = (slice.modelBreakdown || [])
|
const models = (slice.modelBreakdown || [])
|
||||||
.slice()
|
.slice()
|
||||||
.sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0));
|
.sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0));
|
||||||
@@ -489,9 +552,17 @@ export const ConsumptionView = defineComponent({
|
|||||||
patchKeyedList(modelsListEl, models, {
|
patchKeyedList(modelsListEl, models, {
|
||||||
keyFn: (m) => m.label || m.shortName,
|
keyFn: (m) => m.label || m.shortName,
|
||||||
sigFn: (m) =>
|
sigFn: (m) =>
|
||||||
`${m.label}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
`${showUpstream}:${m.label}:${m.upstreamName || ''}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
||||||
createRow: createBreakdownItemRow,
|
createRow: createBreakdownItemRow,
|
||||||
updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true),
|
updateRow: (refs, m) =>
|
||||||
|
updateBreakdownItemRow(
|
||||||
|
refs,
|
||||||
|
showUpstream
|
||||||
|
? { ...m, label: m.upstreamName || m.label || m.shortName }
|
||||||
|
: m,
|
||||||
|
modelsTotalTok,
|
||||||
|
true
|
||||||
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
// 4. 同步数据来源列表
|
// 4. 同步数据来源列表
|
||||||
@@ -529,8 +600,14 @@ export const ConsumptionView = defineComponent({
|
|||||||
patchText(col.tokText, '');
|
patchText(col.tokText, '');
|
||||||
} else {
|
} else {
|
||||||
const cVal = Number(m.costUsd || 0);
|
const cVal = Number(m.costUsd || 0);
|
||||||
patchText(col.costText, m.unpricedCalls > 0 ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls })
|
patchText(
|
||||||
: cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`);
|
col.costText,
|
||||||
|
m.unpricedCalls > 0
|
||||||
|
? formatUsd(cVal, { unpricedCalls: m.unpricedCalls, compactPending: true })
|
||||||
|
: cVal >= 10
|
||||||
|
? `$${Math.round(cVal)}`
|
||||||
|
: `$${cVal.toFixed(2)}`
|
||||||
|
);
|
||||||
patchText(col.tokText, formatTokensPrecise(mTot));
|
patchText(col.tokText, formatTokensPrecise(mTot));
|
||||||
|
|
||||||
const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100));
|
const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100));
|
||||||
@@ -558,6 +635,7 @@ export const ConsumptionView = defineComponent({
|
|||||||
customEndMs: st.customEndMs,
|
customEndMs: st.customEndMs,
|
||||||
consumption: st.telemetry?.consumption,
|
consumption: st.telemetry?.consumption,
|
||||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||||
|
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||||
}),
|
}),
|
||||||
(slice) => {
|
(slice) => {
|
||||||
latestSlice = slice;
|
latestSlice = slice;
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
* @fileoverview View 1: LiveOverviewView (实时监控视图).
|
* @fileoverview View 1: LiveOverviewView (实时监控视图).
|
||||||
* 负责展示当前活跃会话的核心实时遥测指标:
|
* 负责展示当前活跃会话的核心实时遥测指标:
|
||||||
* 1. 4 格实时测速矩阵:实时吞吐 (TPS)、首 Token 延迟 (TTFT)、会话有效加权均速与本步费用/缓存命中率;
|
* 1. 4 格实时测速矩阵:实时吞吐 (TPS)、首 Token 延迟 (TTFT)、会话有效加权均速与本步费用/缓存命中率;
|
||||||
* 2. 6 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`),
|
* 2. 10 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`),
|
||||||
* 通过 6 段进度条与双列图例展示消息、系统工具、MCP 工具、Skill、系统提示词与用户规则的 Token 占用;
|
* 通过 10 段进度条与双列图例展示模型回复、工具结果、用户消息、子代理通知、压缩摘要及系统提示词/工具/MCP/Skill/规则的 Token 占用;
|
||||||
* 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon 周配额池、Claude & GPT 等动态配额池,
|
* 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon/Carbon 周配额池、Claude & GPT 等动态配额池,
|
||||||
* 自动适配 5h/每周双窗口或单窗口模式,并展示本机周累计消耗与 AI 积分脚标。
|
* 自动适配 5h/每周双窗口或单窗口模式,并展示本机周累计消耗与 AI 积分脚标。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -52,211 +52,10 @@ function estPillWidth(text) {
|
|||||||
return Math.ceil(w);
|
return Math.ceil(w);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LiveOverviewView = defineComponent({
|
/**
|
||||||
name: 'LiveOverviewView',
|
* 10 通道上下文窗口构成定义(供实时监控主视图与主窗口顶栏悬停概览卡共享)。
|
||||||
setup({ onCleanup }) {
|
*/
|
||||||
// --- 0. 可用额度下方的多任务实时运行卡片列表 (展示所有正在运行的主进程 + 默认主代理缩略 + 可折叠子代理列表) ---
|
export const CTX_CHANNEL_DEFS = [
|
||||||
const liveActivityBar = h('div', {
|
|
||||||
className: 'live-activity-list',
|
|
||||||
hidden: true,
|
|
||||||
'aria-live': 'polite',
|
|
||||||
});
|
|
||||||
|
|
||||||
const expandedTaskConvIds = new Set();
|
|
||||||
const activityTimersMap = new Map();
|
|
||||||
let liveTickTimer = null;
|
|
||||||
|
|
||||||
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
|
||||||
const now = Date.now();
|
|
||||||
const prev = activityTimersMap.get(timerKey);
|
|
||||||
let startMs = prev?.startMs || 0;
|
|
||||||
if (!prev || prev.sig !== sig) {
|
|
||||||
const validRaw = Number(rawStartMs || 0);
|
|
||||||
startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now;
|
|
||||||
} else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) {
|
|
||||||
startMs = Number(rawStartMs);
|
|
||||||
}
|
|
||||||
activityTimersMap.set(timerKey, { sig, startMs, el: targetEl });
|
|
||||||
const elapsedSec = Math.max(0, (now - startMs) / 1000);
|
|
||||||
patchText(targetEl, formatElapsedSec(elapsedSec));
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateLiveElapsedDisplay() {
|
|
||||||
const now = Date.now();
|
|
||||||
for (const entry of activityTimersMap.values()) {
|
|
||||||
if (!entry?.el) continue;
|
|
||||||
const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0;
|
|
||||||
patchText(entry.el, formatElapsedSec(elapsedSec));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopLiveTicker() {
|
|
||||||
if (liveTickTimer) {
|
|
||||||
clearInterval(liveTickTimer);
|
|
||||||
liveTickTimer = null;
|
|
||||||
}
|
|
||||||
activityTimersMap.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ensureLiveTicker() {
|
|
||||||
if (!liveTickTimer) {
|
|
||||||
liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function createLiveTaskCard() {
|
|
||||||
const dotIcon = createSvgIcon('dot', { size: 9 });
|
|
||||||
patchClasses(dotIcon, { 'is-pulsing': true });
|
|
||||||
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
|
|
||||||
const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' });
|
|
||||||
const subToggleBtn = h('button', {
|
|
||||||
type: 'button',
|
|
||||||
className: 'live-sub-toggle',
|
|
||||||
hidden: true,
|
|
||||||
text: '子代理 (0) ▸',
|
|
||||||
});
|
|
||||||
const elapsedEl = h('span', {
|
|
||||||
className: 'live-activity-elapsed text-mono',
|
|
||||||
text: '0s',
|
|
||||||
});
|
|
||||||
|
|
||||||
const headerEl = h('div', { className: 'live-task-header' }, [
|
|
||||||
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]),
|
|
||||||
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const mainBadge = h('span', { className: 'agent-badge badge-main', text: '主' });
|
|
||||||
const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' });
|
|
||||||
const mainProgress = h('span', {
|
|
||||||
className: 'live-activity-progress text-mono',
|
|
||||||
hidden: true,
|
|
||||||
text: '',
|
|
||||||
});
|
|
||||||
const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' });
|
|
||||||
const mainDetail = h('span', {
|
|
||||||
className: 'live-activity-detail',
|
|
||||||
hidden: true,
|
|
||||||
text: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
const mainRowEl = h('div', { className: 'live-task-main-row' }, [
|
|
||||||
mainBadge,
|
|
||||||
mainPhase,
|
|
||||||
mainProgress,
|
|
||||||
mainSep,
|
|
||||||
mainDetail,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
|
|
||||||
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
el: cardEl,
|
|
||||||
refs: {
|
|
||||||
cardEl,
|
|
||||||
dotIcon,
|
|
||||||
titleEl,
|
|
||||||
subToggleBtn,
|
|
||||||
elapsedEl,
|
|
||||||
mainPhase,
|
|
||||||
mainProgress,
|
|
||||||
mainSep,
|
|
||||||
mainDetail,
|
|
||||||
subListEl,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createLiveSubRow() {
|
|
||||||
const subBadge = h('span', { className: 'agent-badge badge-sub-1', text: '子1' });
|
|
||||||
const subRole = h('span', { className: 'live-sub-role', text: '子代理' });
|
|
||||||
const subSummary = h('span', { className: 'live-sub-summary', text: '' });
|
|
||||||
const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' });
|
|
||||||
|
|
||||||
const rowEl = h('div', { className: 'live-sub-row' }, [
|
|
||||||
h('div', { className: 'live-sub-left' }, [
|
|
||||||
subBadge,
|
|
||||||
subRole,
|
|
||||||
subSummary,
|
|
||||||
]),
|
|
||||||
subElapsed,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
el: rowEl,
|
|
||||||
refs: {
|
|
||||||
rowEl,
|
|
||||||
subBadge,
|
|
||||||
subRole,
|
|
||||||
subSummary,
|
|
||||||
subElapsed,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 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 });
|
|
||||||
|
|
||||||
const ttftVal = h('strong', { className: 'cell-value', text: '—' });
|
|
||||||
const ttftSub = h('span', { className: 'cell-sub', text: '均值 —' });
|
|
||||||
|
|
||||||
const avgVal = h('strong', { className: 'cell-value', text: '—' });
|
|
||||||
const avgSub = h('span', { className: 'cell-sub', text: '有效样本 0/0 步' });
|
|
||||||
|
|
||||||
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': '实时指标' }, [
|
|
||||||
h('div', { className: 'matrix-cell' }, [
|
|
||||||
h('div', { className: 'cell-label' }, [h('span', { text: '输出速度' }), pulseDot]),
|
|
||||||
tpsVal,
|
|
||||||
tpsSub,
|
|
||||||
]),
|
|
||||||
h('div', { className: 'matrix-cell' }, [
|
|
||||||
h('div', { className: 'cell-label' }, [
|
|
||||||
h('span', { text: '首字延迟' }),
|
|
||||||
createSvgIcon('clock', { size: 11 }),
|
|
||||||
]),
|
|
||||||
ttftVal,
|
|
||||||
ttftSub,
|
|
||||||
]),
|
|
||||||
h('div', { className: 'matrix-cell' }, [
|
|
||||||
h('div', { className: 'cell-label' }, [
|
|
||||||
h('span', { text: '平均速度' }),
|
|
||||||
createSvgIcon('pulse', { size: 11 }),
|
|
||||||
]),
|
|
||||||
avgVal,
|
|
||||||
avgSub,
|
|
||||||
]),
|
|
||||||
h('div', { className: 'matrix-cell' }, [
|
|
||||||
h('div', { className: 'cell-label' }, [
|
|
||||||
h('span', { text: '本次费用' }),
|
|
||||||
createSvgIcon('bolt', { size: 11 }),
|
|
||||||
]),
|
|
||||||
costVal,
|
|
||||||
cacheSub,
|
|
||||||
]),
|
|
||||||
]);
|
|
||||||
|
|
||||||
// --- 2. 6 段上下文窗口构成面板(自动锚定模型上下文压缩基线 + 方案 B 内嵌独立 256k 窗口检视条) ---
|
|
||||||
const ctxAgentBadge = h('span', {
|
|
||||||
className: 'agent-badge badge-main',
|
|
||||||
hidden: true,
|
|
||||||
text: '主代理',
|
|
||||||
});
|
|
||||||
const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' });
|
|
||||||
const ctxSegmentBar = ContextSegmentMeter({ context: {} });
|
|
||||||
|
|
||||||
const ctxPillGroup = h('div', { className: 'ctx-pill-group' });
|
|
||||||
const ctxInspectorBar = h(
|
|
||||||
'div',
|
|
||||||
{ className: 'ctx-inspector-bar', hidden: true },
|
|
||||||
[ctxPillGroup]
|
|
||||||
);
|
|
||||||
|
|
||||||
const ctxChannels = [
|
|
||||||
{
|
{
|
||||||
key: 'assistant',
|
key: 'assistant',
|
||||||
label: '模型回复',
|
label: '模型回复',
|
||||||
@@ -327,7 +126,405 @@ export const LiveOverviewView = defineComponent({
|
|||||||
title: '全局与工作区自定义规则 (user_rules)',
|
title: '全局与工作区自定义规则 (user_rules)',
|
||||||
getValue: (c) => Number(c.userRulesTokens || 0),
|
getValue: (c) => Number(c.userRulesTokens || 0),
|
||||||
},
|
},
|
||||||
].map((ch, idx) => {
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} quotas
|
||||||
|
* @param {number} minuteTick
|
||||||
|
* @param {{ isPending?: boolean }} [options]
|
||||||
|
* @returns {Array<object>}
|
||||||
|
*/
|
||||||
|
export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) {
|
||||||
|
const safeQuotas = quotas || {};
|
||||||
|
const activePool = safeQuotas.activePool || {};
|
||||||
|
const rawPools =
|
||||||
|
Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0
|
||||||
|
? safeQuotas.pools
|
||||||
|
: [
|
||||||
|
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
|
||||||
|
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
|
||||||
|
];
|
||||||
|
const weekly = safeQuotas.weekly || {};
|
||||||
|
const poolItems = rawPools.map((p) => {
|
||||||
|
const key = p.poolKey || p.family || p.poolLabel || 'Other';
|
||||||
|
const poolLabel = p.poolLabel || p.family || key;
|
||||||
|
const isActivePool =
|
||||||
|
Boolean(activePool.family) &&
|
||||||
|
(activePool.poolKey === key ||
|
||||||
|
activePool.family === p.family ||
|
||||||
|
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
poolLabel,
|
||||||
|
poolData: p,
|
||||||
|
fallbackWeekly: weekly,
|
||||||
|
isActivePool,
|
||||||
|
minuteTick,
|
||||||
|
isPending,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
weekly?.isOfficial === false &&
|
||||||
|
poolItems.length > 0 &&
|
||||||
|
!poolItems.some((item) => item.isActivePool)
|
||||||
|
) {
|
||||||
|
poolItems[0].isActivePool = true;
|
||||||
|
}
|
||||||
|
return poolItems;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
|
||||||
|
*/
|
||||||
|
export function createPoolQuotaRow() {
|
||||||
|
const title5h = h('span', { text: '5h 限额' });
|
||||||
|
const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' });
|
||||||
|
const fill5h = h('div', { className: 'progress-fill' });
|
||||||
|
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||||
|
h('div', { className: 'panel-header' }, [title5h, meta5h]),
|
||||||
|
h('div', { className: 'progress-track' }, [fill5h]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const titleWk = h('span', { text: '每周限额' });
|
||||||
|
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
|
||||||
|
const fillWk = h('div', { className: 'progress-fill' });
|
||||||
|
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||||
|
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
|
||||||
|
h('div', { className: 'progress-track' }, [fillWk]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
|
||||||
|
row5h,
|
||||||
|
rowWk,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
el,
|
||||||
|
refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步单个配额池行的 5h 与每周窗口状态:
|
||||||
|
* - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行;
|
||||||
|
* - 对于仅有 5h 限额的配额池自动隐藏每周行;
|
||||||
|
* - 若两个窗口均无数据(首次加载或拉取失败),同时保留两行以维持预占高度不跳动。
|
||||||
|
*/
|
||||||
|
export function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
||||||
|
const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item;
|
||||||
|
patchAttr(
|
||||||
|
rowEl,
|
||||||
|
'style',
|
||||||
|
idx === 0
|
||||||
|
? 'display: flex; flex-direction: column; gap: 8px;'
|
||||||
|
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
|
||||||
|
);
|
||||||
|
|
||||||
|
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
|
||||||
|
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
|
||||||
|
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
|
||||||
|
|
||||||
|
const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false);
|
||||||
|
const wkUsedRaw = useCustomWeekly
|
||||||
|
? fallbackWeekly?.usedPct
|
||||||
|
: poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
|
||||||
|
const wkRemRaw = useCustomWeekly
|
||||||
|
? fallbackWeekly?.remainingPct
|
||||||
|
: poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
|
||||||
|
const wkResetRaw = useCustomWeekly
|
||||||
|
? fallbackWeekly?.resetTime || poolData?.weeklyResetTime
|
||||||
|
: poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
|
||||||
|
const hasWk = wkUsedRaw != null && wkRemRaw != null;
|
||||||
|
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
|
||||||
|
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
|
||||||
|
|
||||||
|
// 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口
|
||||||
|
const hide5h = !has5h && hasWk;
|
||||||
|
const hideWk = !hasWk && has5h;
|
||||||
|
refs.row5h.hidden = hide5h;
|
||||||
|
refs.row5h.style.display = hide5h ? 'none' : 'flex';
|
||||||
|
refs.rowWk.hidden = hideWk;
|
||||||
|
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
|
||||||
|
|
||||||
|
const fallbackMetaText = isPending ? '读取中...' : '获取失败 (--%)';
|
||||||
|
|
||||||
|
patchText(refs.title5h, `5h 限额 (${poolLabel})`);
|
||||||
|
patchText(
|
||||||
|
refs.meta5h,
|
||||||
|
has5h
|
||||||
|
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
|
||||||
|
: fallbackMetaText
|
||||||
|
);
|
||||||
|
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
|
||||||
|
patchClasses(refs.fill5h, {
|
||||||
|
'tone-warn': used5hVal >= 60 && used5hVal < 85,
|
||||||
|
'tone-danger': used5hVal >= 85,
|
||||||
|
});
|
||||||
|
|
||||||
|
const customTitle =
|
||||||
|
isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
|
||||||
|
? fallbackWeekly.title
|
||||||
|
: `每周限额 (${poolLabel})`;
|
||||||
|
patchText(refs.titleWk, customTitle);
|
||||||
|
patchText(
|
||||||
|
refs.metaWk,
|
||||||
|
hasWk
|
||||||
|
? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)`
|
||||||
|
: fallbackMetaText
|
||||||
|
);
|
||||||
|
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
|
||||||
|
patchClasses(refs.fillWk, {
|
||||||
|
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
|
||||||
|
'tone-danger': usedWkVal >= 85,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function quotaPoolRowSig(item, idx) {
|
||||||
|
return `${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.remainingPct}:${item.fallbackWeekly?.resetTime}:${item.fallbackWeekly?.title}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LiveOverviewView = defineComponent({
|
||||||
|
name: 'LiveOverviewView',
|
||||||
|
setup({ onCleanup }) {
|
||||||
|
// --- 0. 可用额度下方的多任务实时运行卡片列表 (展示所有正在运行的主进程 + 默认主代理缩略 + 可折叠子代理列表) ---
|
||||||
|
const liveActivityBar = h('div', {
|
||||||
|
className: 'live-activity-list',
|
||||||
|
hidden: true,
|
||||||
|
'aria-live': 'polite',
|
||||||
|
});
|
||||||
|
|
||||||
|
const expandedTaskConvIds = new Set();
|
||||||
|
const activityTimersMap = new Map();
|
||||||
|
let liveTickTimer = null;
|
||||||
|
let countdownTickTimer = null;
|
||||||
|
|
||||||
|
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
||||||
|
const now = Date.now();
|
||||||
|
const prev = activityTimersMap.get(timerKey);
|
||||||
|
let startMs = prev?.startMs || 0;
|
||||||
|
if (!prev || prev.sig !== sig) {
|
||||||
|
const validRaw = Number(rawStartMs || 0);
|
||||||
|
startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now;
|
||||||
|
} else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) {
|
||||||
|
startMs = Number(rawStartMs);
|
||||||
|
}
|
||||||
|
activityTimersMap.set(timerKey, { sig, startMs, el: targetEl });
|
||||||
|
const elapsedSec = Math.max(0, (now - startMs) / 1000);
|
||||||
|
patchText(targetEl, formatElapsedSec(elapsedSec));
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLiveElapsedDisplay() {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const entry of activityTimersMap.values()) {
|
||||||
|
if (!entry?.el) continue;
|
||||||
|
const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0;
|
||||||
|
patchText(entry.el, formatElapsedSec(elapsedSec));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function pauseLiveTicker() {
|
||||||
|
if (liveTickTimer) {
|
||||||
|
clearInterval(liveTickTimer);
|
||||||
|
liveTickTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopLiveTicker() {
|
||||||
|
pauseLiveTicker();
|
||||||
|
activityTimersMap.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureLiveTicker() {
|
||||||
|
if (uiStore.getState().activeView !== 'overview' || activityTimersMap.size === 0) {
|
||||||
|
pauseLiveTicker();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!liveTickTimer) {
|
||||||
|
liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopCountdownTicker() {
|
||||||
|
if (countdownTickTimer) {
|
||||||
|
clearInterval(countdownTickTimer);
|
||||||
|
countdownTickTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureCountdownTicker() {
|
||||||
|
if (uiStore.getState().activeView !== 'overview') {
|
||||||
|
stopCountdownTicker();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!countdownTickTimer) {
|
||||||
|
countdownTickTimer = setInterval(() => {
|
||||||
|
if (uiStore.getState().activeView === 'overview' && latestData) {
|
||||||
|
renderData(latestData);
|
||||||
|
}
|
||||||
|
}, 30_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createLiveTaskCard() {
|
||||||
|
const dotIcon = createSvgIcon('dot', { size: 11 });
|
||||||
|
patchClasses(dotIcon, { 'is-pulsing': true });
|
||||||
|
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
|
||||||
|
const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' });
|
||||||
|
const subToggleBtn = h('button', {
|
||||||
|
type: 'button',
|
||||||
|
className: 'live-sub-toggle',
|
||||||
|
hidden: true,
|
||||||
|
text: '子代理 (0) ▸',
|
||||||
|
});
|
||||||
|
const elapsedEl = h('span', {
|
||||||
|
className: 'live-activity-elapsed text-mono',
|
||||||
|
text: '0s',
|
||||||
|
});
|
||||||
|
|
||||||
|
const headerEl = h('div', { className: 'live-task-header' }, [
|
||||||
|
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]),
|
||||||
|
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const mainBadge = h('span', {
|
||||||
|
className: 'agent-badge badge-main',
|
||||||
|
hidden: true,
|
||||||
|
text: '主',
|
||||||
|
});
|
||||||
|
const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' });
|
||||||
|
const mainProgress = h('span', {
|
||||||
|
className: 'live-activity-progress text-mono',
|
||||||
|
hidden: true,
|
||||||
|
text: '',
|
||||||
|
});
|
||||||
|
const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' });
|
||||||
|
const mainDetail = h('span', {
|
||||||
|
className: 'live-activity-detail',
|
||||||
|
hidden: true,
|
||||||
|
text: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const mainRowEl = h('div', { className: 'live-task-main-row' }, [
|
||||||
|
mainBadge,
|
||||||
|
mainPhase,
|
||||||
|
mainProgress,
|
||||||
|
mainSep,
|
||||||
|
mainDetail,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
|
||||||
|
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
el: cardEl,
|
||||||
|
refs: {
|
||||||
|
cardEl,
|
||||||
|
dotIcon,
|
||||||
|
titleEl,
|
||||||
|
subToggleBtn,
|
||||||
|
elapsedEl,
|
||||||
|
mainBadge,
|
||||||
|
mainPhase,
|
||||||
|
mainProgress,
|
||||||
|
mainSep,
|
||||||
|
mainDetail,
|
||||||
|
subListEl,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createLiveSubRow() {
|
||||||
|
const subBadge = h('span', { className: 'agent-badge badge-sub-1', text: '子1' });
|
||||||
|
const subRole = h('span', { className: 'live-sub-role', text: '子代理' });
|
||||||
|
const subSummary = h('span', { className: 'live-sub-summary', text: '' });
|
||||||
|
const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' });
|
||||||
|
|
||||||
|
const rowEl = h('div', { className: 'live-sub-row' }, [
|
||||||
|
h('div', { className: 'live-sub-left' }, [
|
||||||
|
subBadge,
|
||||||
|
subRole,
|
||||||
|
subSummary,
|
||||||
|
]),
|
||||||
|
subElapsed,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
el: rowEl,
|
||||||
|
refs: {
|
||||||
|
rowEl,
|
||||||
|
subBadge,
|
||||||
|
subRole,
|
||||||
|
subSummary,
|
||||||
|
subElapsed,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 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 });
|
||||||
|
|
||||||
|
const ttftVal = h('strong', { className: 'cell-value', text: '—' });
|
||||||
|
const ttftSub = h('span', { className: 'cell-sub', text: '均值 —' });
|
||||||
|
|
||||||
|
const avgVal = h('strong', { className: 'cell-value', text: '—' });
|
||||||
|
const avgSub = h('span', { className: 'cell-sub', text: '有效样本 0/0 步' });
|
||||||
|
|
||||||
|
const costVal = h('strong', { className: 'cell-value', text: '—' });
|
||||||
|
const cacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累计 $0.00' });
|
||||||
|
|
||||||
|
const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '实时指标' }, [
|
||||||
|
h('div', { className: 'matrix-cell' }, [
|
||||||
|
h('div', { className: 'cell-label' }, [h('span', { text: '输出速度' }), pulseDot]),
|
||||||
|
tpsVal,
|
||||||
|
tpsSub,
|
||||||
|
]),
|
||||||
|
h('div', { className: 'matrix-cell' }, [
|
||||||
|
h('div', { className: 'cell-label' }, [
|
||||||
|
h('span', { text: '首字延迟' }),
|
||||||
|
createSvgIcon('clock', { size: 11 }),
|
||||||
|
]),
|
||||||
|
ttftVal,
|
||||||
|
ttftSub,
|
||||||
|
]),
|
||||||
|
h('div', { className: 'matrix-cell' }, [
|
||||||
|
h('div', { className: 'cell-label' }, [
|
||||||
|
h('span', { text: '平均速度' }),
|
||||||
|
createSvgIcon('pulse', { size: 11 }),
|
||||||
|
]),
|
||||||
|
avgVal,
|
||||||
|
avgSub,
|
||||||
|
]),
|
||||||
|
h('div', { className: 'matrix-cell' }, [
|
||||||
|
h('div', { className: 'cell-label' }, [
|
||||||
|
h('span', { text: '本次费用' }),
|
||||||
|
createSvgIcon('bolt', { size: 11 }),
|
||||||
|
]),
|
||||||
|
costVal,
|
||||||
|
cacheSub,
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// --- 2. 6 段上下文窗口构成面板(自动锚定模型上下文压缩基线 + 方案 B 内嵌独立 256k 窗口检视条) ---
|
||||||
|
const ctxAgentBadge = h('span', {
|
||||||
|
className: 'agent-badge badge-main',
|
||||||
|
hidden: true,
|
||||||
|
text: '主代理',
|
||||||
|
});
|
||||||
|
const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' });
|
||||||
|
const ctxSegmentBar = ContextSegmentMeter({ context: {} });
|
||||||
|
|
||||||
|
const ctxPillGroup = h('div', { className: 'ctx-pill-group' });
|
||||||
|
const ctxInspectorBar = h(
|
||||||
|
'div',
|
||||||
|
{ className: 'ctx-inspector-bar', hidden: true },
|
||||||
|
[ctxPillGroup]
|
||||||
|
);
|
||||||
|
|
||||||
|
const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => {
|
||||||
const valEl = h('strong', { className: 'text-mono', text: '0' });
|
const valEl = h('strong', { className: 'text-mono', text: '0' });
|
||||||
const itemEl = h('div', { className: 'legend-item', title: ch.title }, [
|
const itemEl = h('div', { className: 'legend-item', title: ch.title }, [
|
||||||
h('span', { className: 'legend-left' }, [
|
h('span', { className: 'legend-left' }, [
|
||||||
@@ -364,37 +561,6 @@ export const LiveOverviewView = defineComponent({
|
|||||||
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
||||||
const poolsListEl = h('div', { style: 'display: flex; flex-direction: column; gap: 0;' });
|
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: '--' });
|
|
||||||
const fill5h = h('div', { className: 'progress-fill' });
|
|
||||||
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
|
||||||
h('div', { className: 'panel-header' }, [title5h, meta5h]),
|
|
||||||
h('div', { className: 'progress-track' }, [fill5h]),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const titleWk = h('span', { text: '每周限额' });
|
|
||||||
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
|
|
||||||
const fillWk = h('div', { className: 'progress-fill' });
|
|
||||||
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
|
||||||
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
|
|
||||||
h('div', { className: 'progress-track' }, [fillWk]),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
|
|
||||||
row5h,
|
|
||||||
rowWk,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
el,
|
|
||||||
refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
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 wkFootRight = h('span', { className: 'text-muted', text: '' });
|
||||||
|
|
||||||
@@ -425,75 +591,6 @@ export const LiveOverviewView = defineComponent({
|
|||||||
className: 'view-pane',
|
className: 'view-pane',
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* 同步单个配额池行的 5h 与每周窗口状态:
|
|
||||||
* - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行;
|
|
||||||
* - 对于仅有 5h 限额的配额池自动隐藏每周行;
|
|
||||||
* - 若两个窗口均无数据(如首次拉取失败),则同时保留两行并显示“获取失败 (--%)”占位提示。
|
|
||||||
*/
|
|
||||||
function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
|
||||||
const { poolData, poolLabel, fallbackWeekly, isActivePool } = item;
|
|
||||||
patchAttr(
|
|
||||||
rowEl,
|
|
||||||
'style',
|
|
||||||
idx === 0
|
|
||||||
? 'display: flex; flex-direction: column; gap: 8px;'
|
|
||||||
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
|
|
||||||
);
|
|
||||||
|
|
||||||
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
|
|
||||||
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
|
|
||||||
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
|
|
||||||
|
|
||||||
const wkUsedRaw =
|
|
||||||
poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
|
|
||||||
const wkRemRaw =
|
|
||||||
poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
|
|
||||||
const wkResetRaw =
|
|
||||||
poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
|
|
||||||
const hasWk = wkUsedRaw != null && wkRemRaw != null;
|
|
||||||
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
|
|
||||||
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
|
|
||||||
|
|
||||||
// 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口
|
|
||||||
const hide5h = !has5h && hasWk;
|
|
||||||
const hideWk = !hasWk && has5h;
|
|
||||||
refs.row5h.hidden = hide5h;
|
|
||||||
refs.row5h.style.display = hide5h ? 'none' : 'flex';
|
|
||||||
refs.rowWk.hidden = hideWk;
|
|
||||||
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
|
|
||||||
|
|
||||||
patchText(refs.title5h, `5h 限额 (${poolLabel})`);
|
|
||||||
patchText(
|
|
||||||
refs.meta5h,
|
|
||||||
has5h
|
|
||||||
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
|
|
||||||
: '获取失败 (--%)'
|
|
||||||
);
|
|
||||||
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
|
|
||||||
patchClasses(refs.fill5h, {
|
|
||||||
'tone-warn': used5hVal >= 60 && used5hVal < 85,
|
|
||||||
'tone-danger': used5hVal >= 85,
|
|
||||||
});
|
|
||||||
|
|
||||||
const customTitle =
|
|
||||||
isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
|
|
||||||
? fallbackWeekly.title
|
|
||||||
: `每周限额 (${poolLabel})`;
|
|
||||||
patchText(refs.titleWk, customTitle);
|
|
||||||
patchText(
|
|
||||||
refs.metaWk,
|
|
||||||
hasWk
|
|
||||||
? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)`
|
|
||||||
: '获取失败 (--%)'
|
|
||||||
);
|
|
||||||
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
|
|
||||||
patchClasses(refs.fillWk, {
|
|
||||||
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
|
|
||||||
'tone-danger': usedWkVal >= 85,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let latestData = null;
|
let latestData = null;
|
||||||
let isDirty = false;
|
let isDirty = false;
|
||||||
let ctxPillsExpanded = false;
|
let ctxPillsExpanded = false;
|
||||||
@@ -605,10 +702,10 @@ export const LiveOverviewView = defineComponent({
|
|||||||
const subSig = (item.subagents || [])
|
const subSig = (item.subagents || [])
|
||||||
.map(
|
.map(
|
||||||
(s) =>
|
(s) =>
|
||||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}`
|
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||||
)
|
)
|
||||||
.join('|');
|
.join('|');
|
||||||
return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${subSig}`;
|
return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||||
},
|
},
|
||||||
createRow: createLiveTaskCard,
|
createRow: createLiveTaskCard,
|
||||||
updateRow: (refs, item) => {
|
updateRow: (refs, item) => {
|
||||||
@@ -622,7 +719,11 @@ export const LiveOverviewView = defineComponent({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const isWaiting = act.phase === 'waiting';
|
const isWaiting = act.phase === 'waiting';
|
||||||
patchClasses(refs.cardEl, { 'is-waiting': isWaiting });
|
const isCompacting = act.phase === 'compacting';
|
||||||
|
patchClasses(refs.cardEl, {
|
||||||
|
'is-waiting': isWaiting,
|
||||||
|
'is-compacting': isCompacting,
|
||||||
|
});
|
||||||
patchClasses(refs.dotIcon, { 'is-pulsing': true });
|
patchClasses(refs.dotIcon, { 'is-pulsing': true });
|
||||||
|
|
||||||
const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话';
|
const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话';
|
||||||
@@ -639,6 +740,7 @@ export const LiveOverviewView = defineComponent({
|
|||||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||||
const isExpanded = expandedTaskConvIds.has(item.cascadeId);
|
const isExpanded = expandedTaskConvIds.has(item.cascadeId);
|
||||||
|
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
||||||
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
||||||
if (subCount > 0) {
|
if (subCount > 0) {
|
||||||
const arrow = isExpanded ? '▾' : '▸';
|
const arrow = isExpanded ? '▾' : '▸';
|
||||||
@@ -758,14 +860,19 @@ export const LiveOverviewView = defineComponent({
|
|||||||
ensureLiveTicker();
|
ensureLiveTicker();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标)
|
// 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标,遵循模型名称格式设置)
|
||||||
|
const showUpstream = Boolean(data.settings?.showUpstreamModel);
|
||||||
|
const activeModelDisplay =
|
||||||
|
(showUpstream
|
||||||
|
? active.activeModelUpstream || active.activeModelShort
|
||||||
|
: active.activeModelShort) || '模型未知';
|
||||||
patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) });
|
patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) });
|
||||||
patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s'));
|
patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s'));
|
||||||
const reason = speedReasonText(active.latestSpeedReason);
|
const reason = speedReasonText(active.latestSpeedReason);
|
||||||
const modelAndAgent =
|
const modelAndAgent =
|
||||||
hasSubagents && active.activeAgentBadge
|
hasSubagents && active.activeAgentBadge
|
||||||
? `[${active.activeAgentBadge}] ${active.activeModelShort || '模型未知'}`
|
? `[${active.activeAgentBadge}] ${activeModelDisplay}`
|
||||||
: active.activeModelShort || '模型未知';
|
: activeModelDisplay;
|
||||||
patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent);
|
patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent);
|
||||||
|
|
||||||
patchText(ttftVal, formatMetric(active.latestTtftSec, 's'));
|
patchText(ttftVal, formatMetric(active.latestTtftSec, 's'));
|
||||||
@@ -775,7 +882,11 @@ export const LiveOverviewView = defineComponent({
|
|||||||
patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`);
|
patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`);
|
||||||
|
|
||||||
const stepCost = active.latestStepCostUsd;
|
const stepCost = active.latestStepCostUsd;
|
||||||
patchText(costVal, formatUsd(stepCost, { precise: true }));
|
const hasAnySteps = Number(active.stepCount || 0) > 0;
|
||||||
|
patchText(
|
||||||
|
costVal,
|
||||||
|
!hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true })
|
||||||
|
);
|
||||||
patchText(
|
patchText(
|
||||||
cacheSub,
|
cacheSub,
|
||||||
`缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}`
|
`缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}`
|
||||||
@@ -803,10 +914,13 @@ export const LiveOverviewView = defineComponent({
|
|||||||
|
|
||||||
const allAgentPills = agents.map((ag) => {
|
const allAgentPills = agents.map((ag) => {
|
||||||
const agPct = ag.context?.usedPct ?? 0;
|
const agPct = ag.context?.usedPct ?? 0;
|
||||||
|
const agModelDisplay =
|
||||||
|
(showUpstream ? ag.activeModelUpstream || ag.activeModelShort : ag.activeModelShort) ||
|
||||||
|
'模型未知';
|
||||||
return {
|
return {
|
||||||
key: ag.agentId,
|
key: ag.agentId,
|
||||||
label: `${ag.badgeText || ag.shortLabel} ${agPct}%`,
|
label: `${ag.badgeText || ag.shortLabel} ${agPct}%`,
|
||||||
title: `${formatAgentLabel(ag)} (${ag.activeModelShort || '模型未知'} · ${ag.stepCount || 0}步)`,
|
title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${ag.stepCount || 0}步)`,
|
||||||
isActive: effectiveCtxScope === ag.agentId,
|
isActive: effectiveCtxScope === ag.agentId,
|
||||||
mode: 'ctx-only',
|
mode: 'ctx-only',
|
||||||
};
|
};
|
||||||
@@ -888,12 +1002,8 @@ export const LiveOverviewView = defineComponent({
|
|||||||
if (item.mode === 'toggle-expand') {
|
if (item.mode === 'toggle-expand') {
|
||||||
ctxPillsExpanded = !ctxPillsExpanded;
|
ctxPillsExpanded = !ctxPillsExpanded;
|
||||||
renderData(latestData);
|
renderData(latestData);
|
||||||
} else if (item.mode === 'ctx-only') {
|
|
||||||
uiStore.setState({ ctxInspectorAgentId: item.key });
|
|
||||||
} else if (item.key === 'all') {
|
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
|
||||||
} else {
|
} else {
|
||||||
uiStore.setState({ selectedAgentScope: item.key });
|
uiStore.setState({ ctxInspectorAgentId: item.key });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
@@ -928,37 +1038,13 @@ export const LiveOverviewView = defineComponent({
|
|||||||
tierBadge,
|
tierBadge,
|
||||||
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
|
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
|
||||||
);
|
);
|
||||||
const activePool = quotas.activePool || {};
|
|
||||||
const rawPools = Array.isArray(quotas.pools) && quotas.pools.length > 0
|
|
||||||
? quotas.pools
|
|
||||||
: [
|
|
||||||
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
|
|
||||||
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
|
|
||||||
];
|
|
||||||
const weekly = quotas.weekly || {};
|
const weekly = quotas.weekly || {};
|
||||||
const minuteTick = Math.floor(Date.now() / 30000);
|
const minuteTick = Math.floor(Date.now() / 30000);
|
||||||
const poolItems = rawPools.map((p) => {
|
const poolItems = buildQuotaPoolItems(quotas, minuteTick);
|
||||||
const key = p.poolKey || p.family || p.poolLabel || 'Other';
|
|
||||||
const poolLabel = p.poolLabel || p.family || key;
|
|
||||||
const isActivePool =
|
|
||||||
Boolean(activePool.family) &&
|
|
||||||
(activePool.poolKey === key ||
|
|
||||||
activePool.family === p.family ||
|
|
||||||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
|
|
||||||
return {
|
|
||||||
key,
|
|
||||||
poolLabel,
|
|
||||||
poolData: p,
|
|
||||||
fallbackWeekly: weekly,
|
|
||||||
isActivePool,
|
|
||||||
minuteTick,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
patchKeyedList(poolsListEl, poolItems, {
|
patchKeyedList(poolsListEl, poolItems, {
|
||||||
keyFn: (item) => item.key,
|
keyFn: (item) => item.key,
|
||||||
sigFn: (item, idx) =>
|
sigFn: quotaPoolRowSig,
|
||||||
`${idx}:${item.poolLabel}:${item.isActivePool}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.title}`,
|
|
||||||
createRow: createPoolQuotaRow,
|
createRow: createPoolQuotaRow,
|
||||||
updateRow: syncPoolQuotaRow,
|
updateRow: syncPoolQuotaRow,
|
||||||
});
|
});
|
||||||
@@ -974,12 +1060,13 @@ export const LiveOverviewView = defineComponent({
|
|||||||
: `本周调用: ${weekly.calls || 0} 次`
|
: `本周调用: ${weekly.calls || 0} 次`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
ensureCountdownTicker();
|
||||||
viewScrollbar.refresh();
|
viewScrollbar.refresh();
|
||||||
}
|
}
|
||||||
|
|
||||||
const unsub = telemetryStore.subscribe(
|
const unsub = telemetryStore.subscribe(
|
||||||
(st) => st.telemetry,
|
(st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }),
|
||||||
(data) => {
|
({ telemetry: data }) => {
|
||||||
latestData = data;
|
latestData = data;
|
||||||
if (uiStore.getState().activeView !== 'overview') {
|
if (uiStore.getState().activeView !== 'overview') {
|
||||||
const stillRunning =
|
const stillRunning =
|
||||||
@@ -1011,12 +1098,18 @@ export const LiveOverviewView = defineComponent({
|
|||||||
prevCtxTarget = slice.ctxInspectorAgentId;
|
prevCtxTarget = slice.ctxInspectorAgentId;
|
||||||
|
|
||||||
if (slice.activeView !== 'overview') {
|
if (slice.activeView !== 'overview') {
|
||||||
|
pauseLiveTicker();
|
||||||
|
stopCountdownTicker();
|
||||||
if (scopeChanged) isDirty = true;
|
if (scopeChanged) isDirty = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
ensureCountdownTicker();
|
||||||
if ((isDirty || scopeChanged) && latestData) {
|
if ((isDirty || scopeChanged) && latestData) {
|
||||||
isDirty = false;
|
isDirty = false;
|
||||||
renderData(latestData);
|
renderData(latestData);
|
||||||
|
} else if (activityTimersMap.size > 0) {
|
||||||
|
updateLiveElapsedDisplay();
|
||||||
|
ensureLiveTicker();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -1039,6 +1132,7 @@ export const LiveOverviewView = defineComponent({
|
|||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
stopLiveTicker();
|
stopLiveTicker();
|
||||||
|
stopCountdownTicker();
|
||||||
unsub();
|
unsub();
|
||||||
unsubView();
|
unsubView();
|
||||||
if (ro) ro.disconnect();
|
if (ro) ro.disconnect();
|
||||||
|
|||||||
@@ -1,29 +1,26 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview View 4: SettingsView (系统设置视图).
|
* @fileoverview View 4: SettingsView (系统设置视图).
|
||||||
* 采用定制的 `CustomSelect` 与 `CustomNumberInput` 替代所有原生表单控件,分为两个设置面板:
|
* 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板:
|
||||||
* 1. 本地配额监控与预算表单:配置模型名称显示方式(内部代号/实际模型名)、周用量计算模式及自定义 Token/USD 预算;
|
* 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)与模型名称格式(精简代号 / 原始模型 ID);
|
||||||
* 2. 云端价格同步与插件更新面板:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
* 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序;
|
||||||
|
* 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { defineComponent } from '../core/component.js';
|
import { defineComponent } from '../core/component.js';
|
||||||
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
|
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
|
||||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||||
import {
|
import {
|
||||||
|
DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||||
|
normalizeClientTopbarSlots,
|
||||||
saveSettingsPatch,
|
saveSettingsPatch,
|
||||||
telemetryStore,
|
telemetryStore,
|
||||||
triggerCloudSync,
|
triggerCloudSync,
|
||||||
triggerPluginUpdate,
|
triggerPluginUpdate,
|
||||||
} from '../store/telemetryStore.js';
|
} from '../store/telemetryStore.js';
|
||||||
import { uiStore } from '../store/uiStore.js';
|
import { uiStore } from '../store/uiStore.js';
|
||||||
import { CustomNumberInput } from '../components/ui/CustomNumberInput.js';
|
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||||
|
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||||
/** 每周配额计算模式可选项 */
|
|
||||||
const WEEKLY_MODE_OPTIONS = [
|
|
||||||
{ value: 'official', label: '跟随官方额度' },
|
|
||||||
{ value: 'custom_tokens', label: '自定义 Token 上限' },
|
|
||||||
{ value: 'custom_cost', label: '自定义费用上限 (USD)' },
|
|
||||||
];
|
|
||||||
|
|
||||||
/** 步骤明细表中的模型名称显示方式可选项 */
|
/** 步骤明细表中的模型名称显示方式可选项 */
|
||||||
const STEP_MODEL_DISPLAY_OPTIONS = [
|
const STEP_MODEL_DISPLAY_OPTIONS = [
|
||||||
@@ -31,6 +28,32 @@ const STEP_MODEL_DISPLAY_OPTIONS = [
|
|||||||
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** 面板挂载模式可选项(顶部栏 + 侧边栏 vs 仅侧边栏) */
|
||||||
|
const WINDOW_MOUNT_OPTIONS = [
|
||||||
|
{ value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' },
|
||||||
|
{ value: 'sidebar', label: '仅侧边栏' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 顶栏左侧实时运行会话入口显隐选项 */
|
||||||
|
const TOPBAR_MULTI_TOGGLE_OPTIONS = [
|
||||||
|
{ value: 'show', label: '显示' },
|
||||||
|
{ value: 'hide', label: '隐藏' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 顶栏右侧精简胶囊三槽位可选指标项 */
|
||||||
|
const TOPBAR_SLOT_OPTIONS = [
|
||||||
|
{ value: 'context', label: '上下文占用 (%)' },
|
||||||
|
{ value: 'tps', label: '输出速度 (TPS)' },
|
||||||
|
{ value: 'ttft', label: '首字延迟 (TTFT)' },
|
||||||
|
{ value: 'cost', label: '本次费用 ($)' },
|
||||||
|
{ value: 'quota_auto', label: '自动紧俏额度' },
|
||||||
|
{ value: 'gemini_5h', label: 'Gemini 5h 额度' },
|
||||||
|
{ value: 'gemini_weekly', label: 'Gemini 周额度' },
|
||||||
|
{ value: 'claude_5h', label: 'Claude 5h 额度' },
|
||||||
|
{ value: 'claude_weekly', label: 'Claude 周额度' },
|
||||||
|
{ value: 'none', label: '不显示' },
|
||||||
|
];
|
||||||
|
|
||||||
/** 插件版本更新策略可选项 */
|
/** 插件版本更新策略可选项 */
|
||||||
const AUTO_UPDATE_OPTIONS = [
|
const AUTO_UPDATE_OPTIONS = [
|
||||||
{ value: 'manual', label: '仅提示新版本,手动更新 (推荐)' },
|
{ value: 'manual', label: '仅提示新版本,手动更新 (推荐)' },
|
||||||
@@ -55,20 +78,20 @@ function formatSyncTimeText(tsMs, updatedAt) {
|
|||||||
export const SettingsView = defineComponent({
|
export const SettingsView = defineComponent({
|
||||||
name: 'SettingsView',
|
name: 'SettingsView',
|
||||||
setup({ onCleanup }) {
|
setup({ onCleanup }) {
|
||||||
// --- 面板 1:本地配额监控与预算表单状态与控件 ---
|
|
||||||
let draftMode = 'official';
|
|
||||||
let draftTokens = 150000000;
|
|
||||||
let draftCost = 100;
|
|
||||||
let draftShowUpstreamModel = false;
|
let draftShowUpstreamModel = false;
|
||||||
let draftAutoUpdatePlugin = false;
|
let draftAutoUpdatePlugin = false;
|
||||||
|
let draftEnableWindowOverlay = true;
|
||||||
|
let draftShowTopbarMulti = true;
|
||||||
|
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||||
let statusTimer = null;
|
let statusTimer = null;
|
||||||
|
let topbarTimer = null;
|
||||||
let cloudTimer = null;
|
let cloudTimer = null;
|
||||||
let lastSyncedSettingsSig = '';
|
|
||||||
|
|
||||||
const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||||
|
const topbarStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||||
const cloudStatusMsg = 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) {
|
function showSaveFeedback(text) {
|
||||||
if (statusTimer) {
|
if (statusTimer) {
|
||||||
clearTimeout(statusTimer);
|
clearTimeout(statusTimer);
|
||||||
@@ -83,6 +106,21 @@ export const SettingsView = defineComponent({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 在顶部栏定制面板右上角展示短暂的状态提示 */
|
||||||
|
function showTopbarFeedback(text, autoClearMs = 1500) {
|
||||||
|
if (topbarTimer) {
|
||||||
|
clearTimeout(topbarTimer);
|
||||||
|
topbarTimer = null;
|
||||||
|
}
|
||||||
|
patchText(topbarStatusText, text);
|
||||||
|
if (autoClearMs > 0) {
|
||||||
|
topbarTimer = setTimeout(() => {
|
||||||
|
topbarTimer = null;
|
||||||
|
patchText(topbarStatusText, '');
|
||||||
|
}, autoClearMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 在云端同步面板右上角展示同步或更新进度提示 */
|
/** 在云端同步面板右上角展示同步或更新进度提示 */
|
||||||
function showCloudFeedback(text, autoClearMs = 3500) {
|
function showCloudFeedback(text, autoClearMs = 3500) {
|
||||||
if (cloudTimer) {
|
if (cloudTimer) {
|
||||||
@@ -98,110 +136,54 @@ export const SettingsView = defineComponent({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const modeSelect = CustomSelect({
|
// --- 面板 1:常规设置 ---
|
||||||
modelValue: draftMode,
|
const windowMountSelect = CustomSelect({
|
||||||
icon: 'sliders',
|
modelValue: 'dual',
|
||||||
options: WEEKLY_MODE_OPTIONS,
|
icon: 'dock',
|
||||||
onUpdateModelValue: (val) => {
|
options: WINDOW_MOUNT_OPTIONS,
|
||||||
draftMode = val;
|
onUpdateModelValue: async (val) => {
|
||||||
|
const nextEnable = val !== 'sidebar';
|
||||||
|
draftEnableWindowOverlay = nextEnable;
|
||||||
|
windowMountSelect.setValue(nextEnable ? 'dual' : 'sidebar');
|
||||||
|
showSaveFeedback('保存中…');
|
||||||
|
try {
|
||||||
|
await saveSettingsPatch({
|
||||||
|
enableWindowOverlay: nextEnable,
|
||||||
|
});
|
||||||
|
showSaveFeedback('已保存');
|
||||||
|
} catch {
|
||||||
|
if (latestSettings) {
|
||||||
|
renderSettings(latestSettings);
|
||||||
|
}
|
||||||
|
showSaveFeedback('保存失败');
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// 模型名显示方式切换后立即持久化并刷新遥测数据
|
|
||||||
const stepModelSelect = CustomSelect({
|
const stepModelSelect = CustomSelect({
|
||||||
modelValue: 'short',
|
modelValue: 'short',
|
||||||
icon: 'table',
|
icon: 'table',
|
||||||
options: STEP_MODEL_DISPLAY_OPTIONS,
|
options: STEP_MODEL_DISPLAY_OPTIONS,
|
||||||
onUpdateModelValue: async (val) => {
|
onUpdateModelValue: async (val) => {
|
||||||
draftShowUpstreamModel = val === 'upstream';
|
const nextUpstream = val === 'upstream';
|
||||||
if (latestSettings) {
|
draftShowUpstreamModel = nextUpstream;
|
||||||
lastSyncedSettingsSig = settingsSig({
|
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
|
||||||
...latestSettings,
|
|
||||||
showUpstreamModel: draftShowUpstreamModel,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
showSaveFeedback('保存中…');
|
showSaveFeedback('保存中…');
|
||||||
try {
|
try {
|
||||||
await saveSettingsPatch({
|
await saveSettingsPatch({
|
||||||
showUpstreamModel: draftShowUpstreamModel,
|
showUpstreamModel: nextUpstream,
|
||||||
});
|
});
|
||||||
showSaveFeedback('已保存');
|
showSaveFeedback('已保存');
|
||||||
} catch {
|
} catch {
|
||||||
|
if (latestSettings) {
|
||||||
|
renderSettings(latestSettings);
|
||||||
|
}
|
||||||
showSaveFeedback('保存失败');
|
showSaveFeedback('保存失败');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// 插件自动更新策略切换后立即保存至后端
|
const generalPanel = h('section', { className: 'panel' }, [
|
||||||
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);
|
|
||||||
try {
|
|
||||||
await saveSettingsPatch({
|
|
||||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
|
||||||
});
|
|
||||||
showCloudFeedback('已保存', 1800);
|
|
||||||
} catch {
|
|
||||||
showCloudFeedback('保存失败', 2500);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const tokenBudgetInput = CustomNumberInput({
|
|
||||||
modelValue: draftTokens,
|
|
||||||
min: 100000,
|
|
||||||
max: 10000000000,
|
|
||||||
step: 1000000,
|
|
||||||
onUpdateModelValue: (val) => {
|
|
||||||
draftTokens = val;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const costBudgetInput = CustomNumberInput({
|
|
||||||
modelValue: draftCost,
|
|
||||||
min: 1,
|
|
||||||
max: 100000,
|
|
||||||
step: 5,
|
|
||||||
onUpdateModelValue: (val) => {
|
|
||||||
draftCost = val;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const saveBtn = h(
|
|
||||||
'button',
|
|
||||||
{
|
|
||||||
type: 'button',
|
|
||||||
className: 'btn-primary',
|
|
||||||
onClick: async () => {
|
|
||||||
showSaveFeedback('保存中…');
|
|
||||||
try {
|
|
||||||
await saveSettingsPatch({
|
|
||||||
weeklyLimitMode: draftMode,
|
|
||||||
weeklyTokenBudget: draftTokens,
|
|
||||||
weeklyCostBudget: draftCost,
|
|
||||||
showUpstreamModel: draftShowUpstreamModel,
|
|
||||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
|
||||||
});
|
|
||||||
showSaveFeedback('已保存');
|
|
||||||
} catch {
|
|
||||||
showSaveFeedback('保存失败');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
[createSvgIcon('check', { size: 13 }), h('span', { text: '保存设置' })]
|
|
||||||
);
|
|
||||||
|
|
||||||
const budgetPanel = h('section', { className: 'panel' }, [
|
|
||||||
h('div', { className: 'panel-header' }, [
|
h('div', { className: 'panel-header' }, [
|
||||||
h('span', { className: 'panel-title' }, [
|
h('span', { className: 'panel-title' }, [
|
||||||
createSvgIcon('sliders', { size: 13 }),
|
createSvgIcon('sliders', { size: 13 }),
|
||||||
@@ -209,31 +191,211 @@ export const SettingsView = defineComponent({
|
|||||||
]),
|
]),
|
||||||
saveStatusText,
|
saveStatusText,
|
||||||
]),
|
]),
|
||||||
|
h('div', { className: 'form-row' }, [
|
||||||
|
h('span', { className: 'form-label', text: '面板挂载方式' }),
|
||||||
|
windowMountSelect.el,
|
||||||
|
]),
|
||||||
h('div', { className: 'form-row' }, [
|
h('div', { className: 'form-row' }, [
|
||||||
h('span', { className: 'form-label', text: '模型名称格式' }),
|
h('span', { className: 'form-label', text: '模型名称格式' }),
|
||||||
stepModelSelect.el,
|
stepModelSelect.el,
|
||||||
]),
|
]),
|
||||||
h('div', { className: 'form-row' }, [
|
|
||||||
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 上限' }),
|
|
||||||
tokenBudgetInput.el,
|
|
||||||
]),
|
|
||||||
h('div', { className: 'form-row' }, [
|
|
||||||
h('span', { className: 'form-label', text: '每周费用上限 ($)' }),
|
|
||||||
costBudgetInput.el,
|
|
||||||
]),
|
|
||||||
]),
|
|
||||||
h('div', { style: 'display: flex; justify-content: flex-end;' }, [saveBtn]),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// --- 面板 2:版本更新面板 ---
|
// --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) ---
|
||||||
|
const multiSessionToggle = SegmentedControl({
|
||||||
|
ariaLabel: '实时运行会话开关',
|
||||||
|
modelValue: 'show',
|
||||||
|
options: TOPBAR_MULTI_TOGGLE_OPTIONS,
|
||||||
|
onUpdateModelValue: async (val) => {
|
||||||
|
const nextShow = val !== 'hide';
|
||||||
|
draftShowTopbarMulti = nextShow;
|
||||||
|
syncTopbarControls();
|
||||||
|
showTopbarFeedback('保存中…', 0);
|
||||||
|
try {
|
||||||
|
await saveSettingsPatch({
|
||||||
|
showTopbarMultiSession: nextShow,
|
||||||
|
});
|
||||||
|
showTopbarFeedback('已保存', 1500);
|
||||||
|
} catch {
|
||||||
|
if (latestSettings) {
|
||||||
|
renderSettings(latestSettings);
|
||||||
|
}
|
||||||
|
showTopbarFeedback('保存失败', 2500);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
async function persistTopbarSlots(nextRawSlots, noticeText = '') {
|
||||||
|
const normalized = normalizeClientTopbarSlots(nextRawSlots);
|
||||||
|
draftTopbarSlots = normalized;
|
||||||
|
syncTopbarControls();
|
||||||
|
showTopbarFeedback(noticeText || '保存中…', 0);
|
||||||
|
try {
|
||||||
|
await saveSettingsPatch({
|
||||||
|
topbarCapsuleSlots: normalized,
|
||||||
|
});
|
||||||
|
showTopbarFeedback(noticeText || '已保存', noticeText ? 2000 : 1500);
|
||||||
|
} catch {
|
||||||
|
if (latestSettings) {
|
||||||
|
renderSettings(latestSettings);
|
||||||
|
}
|
||||||
|
showTopbarFeedback('保存失败', 2500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSlotMetricChange(slotIndex, nextVal) {
|
||||||
|
const candidate = [...draftTopbarSlots];
|
||||||
|
candidate[slotIndex] = nextVal;
|
||||||
|
const wouldAllBeHidden = candidate.every((item) => item === 'none');
|
||||||
|
void persistTopbarSlots(
|
||||||
|
candidate,
|
||||||
|
wouldAllBeHidden ? '至少保留 1 项显示' : ''
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function swapTopbarSlots(idxA, idxB) {
|
||||||
|
if (idxA < 0 || idxA > 2 || idxB < 0 || idxB > 2 || idxA === idxB) return;
|
||||||
|
const candidate = [...draftTopbarSlots];
|
||||||
|
const temp = candidate[idxA];
|
||||||
|
candidate[idxA] = candidate[idxB];
|
||||||
|
candidate[idxB] = temp;
|
||||||
|
void persistTopbarSlots(candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
const slotSelects = [0, 1, 2].map((idx) =>
|
||||||
|
CustomSelect({
|
||||||
|
modelValue: draftTopbarSlots[idx],
|
||||||
|
options: TOPBAR_SLOT_OPTIONS,
|
||||||
|
onUpdateModelValue: (val) => handleSlotMetricChange(idx, val),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const slotRows = [0, 1, 2].map((idx) => {
|
||||||
|
const upBtn = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'slot-move-btn',
|
||||||
|
disabled: idx === 0,
|
||||||
|
'aria-label': `槽位 ${idx + 1} 左移`,
|
||||||
|
title: idx === 0 ? '已在最左' : '上移 (在顶栏靠左)',
|
||||||
|
onClick: (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
swapTopbarSlots(idx, idx - 1);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[createSvgIcon('chevron-up', { size: 12 })]
|
||||||
|
);
|
||||||
|
|
||||||
|
const downBtn = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'slot-move-btn',
|
||||||
|
disabled: idx === 2,
|
||||||
|
'aria-label': `槽位 ${idx + 1} 右移`,
|
||||||
|
title: idx === 2 ? '已在最右' : '下移 (在顶栏靠右)',
|
||||||
|
onClick: (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
swapTopbarSlots(idx, idx + 1);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[createSvgIcon('chevron-down', { size: 12 })]
|
||||||
|
);
|
||||||
|
|
||||||
|
return h('div', { className: 'topbar-slot-row', 'data-slot-row': String(idx) }, [
|
||||||
|
h('span', { className: 'slot-index-badge', text: String(idx + 1) }),
|
||||||
|
slotSelects[idx].el,
|
||||||
|
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn]),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
const resetTopbarBtn = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'btn-ghost-sm',
|
||||||
|
disabled: true,
|
||||||
|
onClick: async () => {
|
||||||
|
draftShowTopbarMulti = true;
|
||||||
|
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||||
|
syncTopbarControls();
|
||||||
|
showTopbarFeedback('保存中…', 0);
|
||||||
|
try {
|
||||||
|
await saveSettingsPatch({
|
||||||
|
showTopbarMultiSession: true,
|
||||||
|
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||||
|
});
|
||||||
|
showTopbarFeedback('已恢复默认', 1600);
|
||||||
|
} catch {
|
||||||
|
if (latestSettings) {
|
||||||
|
renderSettings(latestSettings);
|
||||||
|
}
|
||||||
|
showTopbarFeedback('保存失败', 2500);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[h('span', { text: '恢复默认' })]
|
||||||
|
);
|
||||||
|
|
||||||
|
function syncTopbarControls() {
|
||||||
|
multiSessionToggle.setValue(draftShowTopbarMulti ? 'show' : 'hide');
|
||||||
|
for (let i = 0; i < 3; i += 1) {
|
||||||
|
slotSelects[i].setValue(draftTopbarSlots[i]);
|
||||||
|
}
|
||||||
|
const isDefault =
|
||||||
|
draftShowTopbarMulti === true &&
|
||||||
|
draftTopbarSlots[0] === DEFAULT_CLIENT_TOPBAR_SLOTS[0] &&
|
||||||
|
draftTopbarSlots[1] === DEFAULT_CLIENT_TOPBAR_SLOTS[1] &&
|
||||||
|
draftTopbarSlots[2] === DEFAULT_CLIENT_TOPBAR_SLOTS[2];
|
||||||
|
patchAttr(resetTopbarBtn, 'disabled', isDefault);
|
||||||
|
}
|
||||||
|
|
||||||
|
const topbarPanel = h('section', { className: 'panel topbar-config-panel' }, [
|
||||||
|
h('div', { className: 'panel-header' }, [
|
||||||
|
h('span', { className: 'panel-title' }, [
|
||||||
|
createSvgIcon('dock', { size: 13 }),
|
||||||
|
h('span', { text: '顶部栏定制' }),
|
||||||
|
]),
|
||||||
|
h('span', { className: 'topbar-header-right' }, [topbarStatusText, resetTopbarBtn]),
|
||||||
|
]),
|
||||||
|
h('div', { className: 'settings-inline-row' }, [
|
||||||
|
h('span', { className: 'form-label', text: '实时运行会话' }),
|
||||||
|
multiSessionToggle.el,
|
||||||
|
]),
|
||||||
|
h('div', { className: 'form-row' }, [
|
||||||
|
h('span', { className: 'form-label', text: '胶囊数值与顺序 (左 → 右)' }),
|
||||||
|
h('div', { className: 'topbar-slot-list' }, slotRows),
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// --- 面板 3:版本更新面板 ---
|
||||||
|
const autoUpdateSelect = CustomSelect({
|
||||||
|
modelValue: 'manual',
|
||||||
|
icon: 'refresh',
|
||||||
|
options: AUTO_UPDATE_OPTIONS,
|
||||||
|
onUpdateModelValue: async (val) => {
|
||||||
|
const nextAuto = val === 'auto';
|
||||||
|
draftAutoUpdatePlugin = nextAuto;
|
||||||
|
autoUpdateSelect.setValue(nextAuto ? 'auto' : 'manual');
|
||||||
|
showCloudFeedback('保存中…', 0);
|
||||||
|
try {
|
||||||
|
await saveSettingsPatch({
|
||||||
|
autoUpdatePlugin: nextAuto,
|
||||||
|
});
|
||||||
|
showCloudFeedback('已保存', 1800);
|
||||||
|
} catch {
|
||||||
|
if (latestSettings) {
|
||||||
|
renderSettings(latestSettings);
|
||||||
|
}
|
||||||
|
showCloudFeedback('保存失败', 2500);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
|
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
|
||||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.1' });
|
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.3' });
|
||||||
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
|
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
|
||||||
|
|
||||||
const syncPricingBtnText = h('span', { text: '更新价格表' });
|
const syncPricingBtnText = h('span', { text: '更新价格表' });
|
||||||
@@ -288,7 +450,7 @@ export const SettingsView = defineComponent({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!cs?.updateAvailable) {
|
if (!cs?.updateAvailable) {
|
||||||
const curVer = cs?.currentPluginVersion || '1.4.1';
|
const curVer = cs?.currentPluginVersion || '1.4.3';
|
||||||
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
|
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -342,38 +504,35 @@ export const SettingsView = defineComponent({
|
|||||||
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const rootEl = h('div', { className: 'view-pane' }, [budgetPanel, cloudPanel]);
|
const settingsInner = h(
|
||||||
|
'div',
|
||||||
|
{
|
||||||
|
style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;',
|
||||||
|
},
|
||||||
|
[generalPanel, topbarPanel, cloudPanel]
|
||||||
|
);
|
||||||
|
const viewScrollbar = CustomScrollbar({
|
||||||
|
contentEl: settingsInner,
|
||||||
|
className: 'view-pane',
|
||||||
|
});
|
||||||
|
|
||||||
let latestSettings = null;
|
let latestSettings = null;
|
||||||
let latestCloudStatus = null;
|
let latestCloudStatus = null;
|
||||||
let isDirty = false;
|
|
||||||
|
|
||||||
/** 生成设置项签名,避免轮询返回相同配置时覆盖用户正在编辑的草稿值 */
|
|
||||||
function settingsSig(s) {
|
|
||||||
if (!s) return '';
|
|
||||||
return `${s.weeklyLimitMode}:${s.weeklyTokenBudget}:${s.weeklyCostBudget}:${Boolean(s.showUpstreamModel)}:${Boolean(s.autoUpdatePlugin)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 将后端返回的最新设置同步至表单控件 */
|
/** 将后端返回的最新设置同步至表单控件 */
|
||||||
function renderSettings(settings) {
|
function renderSettings(settings) {
|
||||||
if (!settings) return;
|
if (!settings) return;
|
||||||
const nextSig = settingsSig(settings);
|
|
||||||
if (nextSig === lastSyncedSettingsSig) return;
|
|
||||||
lastSyncedSettingsSig = nextSig;
|
|
||||||
draftMode =
|
|
||||||
settings.weeklyLimitMode === 'custom_tokens' ||
|
|
||||||
settings.weeklyLimitMode === 'custom_cost'
|
|
||||||
? settings.weeklyLimitMode
|
|
||||||
: 'official';
|
|
||||||
draftTokens = Number(settings.weeklyTokenBudget || 150000000);
|
|
||||||
draftCost = Number(settings.weeklyCostBudget || 100);
|
|
||||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||||
draftAutoUpdatePlugin = Boolean(settings.autoUpdatePlugin);
|
draftAutoUpdatePlugin = Boolean(settings.autoUpdatePlugin);
|
||||||
modeSelect.setValue(draftMode);
|
draftEnableWindowOverlay = settings.enableWindowOverlay !== false;
|
||||||
|
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||||
|
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||||
|
|
||||||
|
windowMountSelect.setValue(draftEnableWindowOverlay ? 'dual' : 'sidebar');
|
||||||
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
||||||
autoUpdateSelect.setValue(draftAutoUpdatePlugin ? 'auto' : 'manual');
|
autoUpdateSelect.setValue(draftAutoUpdatePlugin ? 'auto' : 'manual');
|
||||||
tokenBudgetInput.setValue(draftTokens);
|
syncTopbarControls();
|
||||||
costBudgetInput.setValue(draftCost);
|
viewScrollbar.refresh();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 将云端价格表统计与插件版本对比状态同步至云端面板 */
|
/** 将云端价格表统计与插件版本对比状态同步至云端面板 */
|
||||||
@@ -391,7 +550,7 @@ export const SettingsView = defineComponent({
|
|||||||
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||||
);
|
);
|
||||||
|
|
||||||
const curVer = cs.currentPluginVersion || '1.4.1';
|
const curVer = cs.currentPluginVersion || '1.4.3';
|
||||||
const latVer = cs.latestPluginVersion || curVer;
|
const latVer = cs.latestPluginVersion || curVer;
|
||||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||||
patchText(versionVal, `v${curVer}`);
|
patchText(versionVal, `v${curVer}`);
|
||||||
@@ -410,6 +569,7 @@ export const SettingsView = defineComponent({
|
|||||||
if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) {
|
if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) {
|
||||||
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
||||||
}
|
}
|
||||||
|
viewScrollbar.refresh();
|
||||||
}
|
}
|
||||||
|
|
||||||
const unsub = telemetryStore.subscribe(
|
const unsub = telemetryStore.subscribe(
|
||||||
@@ -420,42 +580,51 @@ export const SettingsView = defineComponent({
|
|||||||
(slice) => {
|
(slice) => {
|
||||||
latestSettings = slice.settings;
|
latestSettings = slice.settings;
|
||||||
latestCloudStatus = slice.cloudStatus;
|
latestCloudStatus = slice.cloudStatus;
|
||||||
if (uiStore.getState().activeView !== 'settings') {
|
|
||||||
isDirty = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
isDirty = false;
|
|
||||||
renderSettings(slice.settings);
|
renderSettings(slice.settings);
|
||||||
|
if (uiStore.getState().activeView === 'settings') {
|
||||||
renderCloudStatus(slice.cloudStatus);
|
renderCloudStatus(slice.cloudStatus);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const unsubView = uiStore.subscribe(
|
const unsubView = uiStore.subscribe(
|
||||||
(st) => st.activeView,
|
(st) => st.activeView,
|
||||||
(activeView) => {
|
(activeView) => {
|
||||||
if (activeView === 'settings' && isDirty) {
|
if (activeView === 'settings') {
|
||||||
isDirty = false;
|
|
||||||
if (latestSettings) renderSettings(latestSettings);
|
if (latestSettings) renderSettings(latestSettings);
|
||||||
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
||||||
|
viewScrollbar.refresh();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
if (statusTimer) clearTimeout(statusTimer);
|
if (statusTimer) clearTimeout(statusTimer);
|
||||||
|
if (topbarTimer) clearTimeout(topbarTimer);
|
||||||
if (cloudTimer) clearTimeout(cloudTimer);
|
if (cloudTimer) clearTimeout(cloudTimer);
|
||||||
unsub();
|
unsub();
|
||||||
unsubView();
|
unsubView();
|
||||||
modeSelect.destroy();
|
windowMountSelect.destroy();
|
||||||
stepModelSelect.destroy();
|
stepModelSelect.destroy();
|
||||||
|
multiSessionToggle.destroy();
|
||||||
|
for (const sel of slotSelects) {
|
||||||
|
sel.destroy();
|
||||||
|
}
|
||||||
autoUpdateSelect.destroy();
|
autoUpdateSelect.destroy();
|
||||||
tokenBudgetInput.destroy();
|
viewScrollbar.destroy();
|
||||||
costBudgetInput.destroy();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
el: rootEl,
|
el: viewScrollbar.el,
|
||||||
refs: { modeSelect, stepModelSelect, autoUpdateSelect, tokenBudgetInput, costBudgetInput },
|
refs: {
|
||||||
|
windowMountSelect,
|
||||||
|
stepModelSelect,
|
||||||
|
multiSessionToggle,
|
||||||
|
slotSelects,
|
||||||
|
resetTopbarBtn,
|
||||||
|
autoUpdateSelect,
|
||||||
|
viewScrollbar,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -349,7 +349,7 @@ export const StepsDetailView = defineComponent({
|
|||||||
patchText(refs.speedMain, formatMetric(m.avgTokPerSec, ' tok/s'));
|
patchText(refs.speedMain, formatMetric(m.avgTokPerSec, ' tok/s'));
|
||||||
patchText(refs.speedSub, `有效 ${sampleSummary(m.speedSummary)}`);
|
patchText(refs.speedSub, `有效 ${sampleSummary(m.speedSummary)}`);
|
||||||
patchText(refs.tdTokens, formatTokens(m.totalTokens || 0));
|
patchText(refs.tdTokens, formatTokens(m.totalTokens || 0));
|
||||||
patchText(refs.tdCost, formatUsd(m.costUsd, { estimated: m.isEstimatedPrice, unpricedCalls: m.unpricedCalls }));
|
patchText(refs.tdCost, formatUsd(m.costUsd, { unpricedCalls: m.unpricedCalls }));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -367,7 +367,6 @@ export const StepsDetailView = defineComponent({
|
|||||||
recentSteps: st.telemetry?.activeConversation?.recentSteps,
|
recentSteps: st.telemetry?.activeConversation?.recentSteps,
|
||||||
sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown,
|
sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown,
|
||||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||||
rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间',
|
|
||||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||||
}),
|
}),
|
||||||
(slice) => {
|
(slice) => {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+819
-90
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,533 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import vm from 'node:vm';
|
||||||
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
|
import {
|
||||||
|
extractContextBreakdown,
|
||||||
|
extractModelSteps,
|
||||||
|
normalizeCachedStep,
|
||||||
|
} from '../speed-metrics.mjs';
|
||||||
|
import {
|
||||||
|
formatCountdown,
|
||||||
|
formatUsd,
|
||||||
|
speedReasonText,
|
||||||
|
} from '../src/core/formatters.js';
|
||||||
|
import { createReactiveStore } from '../src/core/reactive.js';
|
||||||
|
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||||
|
|
||||||
|
const nowMs = Date.now();
|
||||||
|
const nowIso = new Date(nowMs - 5_000).toISOString();
|
||||||
|
const doneIso = new Date(nowMs - 3_000).toISOString();
|
||||||
|
|
||||||
|
test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as Gemini, and M429/M322/M149/M20 resolve accurately', () => {
|
||||||
|
const h = backendHarness({
|
||||||
|
userStatus: {
|
||||||
|
cascadeModelConfigData: {
|
||||||
|
clientModelConfigs: [
|
||||||
|
{
|
||||||
|
modelOrAlias: { model: 'MODEL_CLAUDE_PROXY' },
|
||||||
|
label: 'Claude Opus 4.6 (Google Vertex)',
|
||||||
|
quotaInfo: { remainingFraction: 0.75, resetTime: new Date(nowMs + 3600_000).toISOString() },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const infoClaude = h.resolveModelInfo('claude-opus-4-6', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
||||||
|
assert.equal(infoClaude.family, 'Claude');
|
||||||
|
const infoO3 = h.resolveModelInfo('o3-mini', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
||||||
|
assert.equal(infoO3.family, 'GPT');
|
||||||
|
|
||||||
|
// Calling resolveModelInfo with omitted dynamicModelMap must not throw (BUG-03)
|
||||||
|
const infoDefaultMap = h.resolveModelInfo('MODEL_PLACEHOLDER_M320');
|
||||||
|
assert.equal(infoDefaultMap.modelId, 'gemini-3.8-flash-low');
|
||||||
|
assert.equal(infoDefaultMap.pricing?.input, 0.3);
|
||||||
|
|
||||||
|
const m429 = h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
||||||
|
assert.equal(m429.modelId, 'gemini-4-carbon-high');
|
||||||
|
assert.equal(m429.shortName, 'carbon-4-high');
|
||||||
|
|
||||||
|
const m322 = h.resolveModelInfo('MODEL_PLACEHOLDER_M322', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
||||||
|
assert.equal(m322.modelId, 'gemini-3.8-flash-tiered');
|
||||||
|
assert.equal(
|
||||||
|
h.computeStepCost(
|
||||||
|
{
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M322',
|
||||||
|
inputTokens: 1_000_000,
|
||||||
|
cacheReadTokens: 0,
|
||||||
|
outputTokens: 0,
|
||||||
|
},
|
||||||
|
m322.pricing
|
||||||
|
),
|
||||||
|
0.75
|
||||||
|
);
|
||||||
|
|
||||||
|
const m149 = h.resolveModelInfo('MODEL_PLACEHOLDER_M149', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
||||||
|
assert.equal(m149.modelId, 'gemini-3.5-flash-high');
|
||||||
|
|
||||||
|
const m20 = h.resolveModelInfo('MODEL_PLACEHOLDER_M20', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
||||||
|
assert.equal(m20.modelId, 'gemini-3.5-flash');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('BUG-02 & BUG-11: ide:<uuid> external sessions do not double-count live conversations, cross-account entries are isolated, and orphan subagents never leak to top-level list', async () => {
|
||||||
|
const stepObj = {
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||||
|
createdAt: nowIso,
|
||||||
|
completedAt: doneIso,
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M318',
|
||||||
|
inputTokens: '10000',
|
||||||
|
cacheReadTokens: '20000',
|
||||||
|
outputTokens: '5000',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const h = backendHarness({
|
||||||
|
userStatus: { email: 'alice@example.com' },
|
||||||
|
deepStats: {
|
||||||
|
accountName: 'alice@example.com',
|
||||||
|
perConvo: {
|
||||||
|
// Same conversation ID as live 'abcd-1234' (case-insensitive, prefixed with 'ide:') -> must deduplicate!
|
||||||
|
'ide:AbCd-1234': {
|
||||||
|
accountName: 'alice@example.com',
|
||||||
|
appSource: 'ide',
|
||||||
|
entries: [
|
||||||
|
{ ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 },
|
||||||
|
{ ts: doneIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
// Different account -> must be excluded when logged in as alice@example.com!
|
||||||
|
'ide:bob-conv': {
|
||||||
|
accountName: 'bob@example.com',
|
||||||
|
appSource: 'ide',
|
||||||
|
entries: [
|
||||||
|
{ ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 99000, cache: 0, out: 1000, reasoning: 0 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cache: {
|
||||||
|
'orphan-sub': {
|
||||||
|
accountName: 'bob@example.com',
|
||||||
|
isSubagent: true,
|
||||||
|
parentCascadeId: 'deleted-parent',
|
||||||
|
signature: 'v10-model-identity:sub',
|
||||||
|
steps: extractModelSteps([stepObj]),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
summaries: {
|
||||||
|
'abcd-1234': { stepCount: 1, lastModifiedTime: doneIso, status: 'IDLE' },
|
||||||
|
},
|
||||||
|
trajectories: {
|
||||||
|
'abcd-1234': { trajectory: { steps: [stepObj] } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const p = await h.buildTelemetryPayloadInternal('abcd-1234', false, { range: 'all' });
|
||||||
|
// ide:AbCd-1234 has 2 entries vs live abcd-1234's 1 step -> deduplicated (no 1 + 2 = 3 double counting!), bob excluded!
|
||||||
|
assert.equal(p.consumption.account.conversationsCount, 1);
|
||||||
|
assert.equal(p.consumption.account.calls, 2);
|
||||||
|
assert.equal(p.consumption.account.totalTokens, 70_000);
|
||||||
|
assert.equal(
|
||||||
|
p.conversations.some((c) => c.cascadeId === 'orphan-sub'),
|
||||||
|
false,
|
||||||
|
'orphan subagent must not appear in top-level conversation dropdown'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd rounding, and dynamicModelMap default', async () => {
|
||||||
|
const badStep = {
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||||
|
createdAt: nowIso,
|
||||||
|
completedAt: doneIso,
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M318',
|
||||||
|
inputTokens: '-5000',
|
||||||
|
cacheReadTokens: 'NaN',
|
||||||
|
outputTokens: '1000',
|
||||||
|
thinkingOutputTokens: '2500',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const extracted = extractModelSteps([badStep]);
|
||||||
|
assert.equal(extracted[0].inputTokens, 0);
|
||||||
|
assert.equal(extracted[0].cacheReadTokens, 0);
|
||||||
|
assert.equal(extracted[0].outputTokens, 1000);
|
||||||
|
assert.equal(extracted[0].thinkingTokens, 1000);
|
||||||
|
assert.equal(extracted[0].responseTokens, 0);
|
||||||
|
assert.equal(normalizeCachedStep({ ...extracted[0], inputTokens: -99 }).inputTokens, 0);
|
||||||
|
assert.equal(normalizeCachedStep(null), null);
|
||||||
|
|
||||||
|
// Micro-steps: 100 steps * (1067 output * $3.75 / 1M = $0.00400125) = $0.40 (previously rounded per-step to $0.00 -> $0.00!)
|
||||||
|
const microSteps = Array.from({ length: 100 }, (_, idx) => ({
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: idx + 1 },
|
||||||
|
createdAt: nowIso,
|
||||||
|
completedAt: doneIso,
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M318', // gemini-3.8-flash-high: $0.75/1M input, $3.75/1M output
|
||||||
|
inputTokens: '0',
|
||||||
|
cacheReadTokens: '0',
|
||||||
|
outputTokens: '1067',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
const h = backendHarness({
|
||||||
|
summaries: { micro: { stepCount: 100, lastModifiedTime: doneIso, status: 'IDLE' } },
|
||||||
|
trajectories: { micro: { trajectory: { steps: microSteps } } },
|
||||||
|
});
|
||||||
|
const p = await h.buildTelemetryPayloadInternal('micro', false, { range: 'today' });
|
||||||
|
assert.equal(p.consumption.account.costUsd, 0.4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('BUG-04 & BUG-10: failed RUNNING trajectory fetch enters cooldown instead of hammering RPC every poll, cleared by forceRefresh', async () => {
|
||||||
|
const h = backendHarness({
|
||||||
|
summaries: { run1: { stepCount: 2, lastModifiedTime: doneIso, status: 'CASCADE_RUN_STATUS_RUNNING' } },
|
||||||
|
trajectories: { run1: new Error('LS timeout') },
|
||||||
|
quotaSummary: new Error('Quota RPC down'),
|
||||||
|
});
|
||||||
|
|
||||||
|
await h.buildTelemetryPayloadInternal('run1', false);
|
||||||
|
const callsAfterFirst = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length;
|
||||||
|
const quotaCallsAfterFirst = h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length;
|
||||||
|
assert.equal(callsAfterFirst, 1);
|
||||||
|
assert.equal(quotaCallsAfterFirst, 1);
|
||||||
|
|
||||||
|
// Immediate second background poll must respect cooldown for both trajectory and quota RPC
|
||||||
|
await h.buildTelemetryPayloadInternal('run1', false);
|
||||||
|
assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 1);
|
||||||
|
assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 1);
|
||||||
|
|
||||||
|
// Manual forceRefresh=true bypasses cooldown immediately
|
||||||
|
await h.buildTelemetryPayloadInternal('run1', true);
|
||||||
|
assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 2);
|
||||||
|
assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('BUG-09, BUG-14 & BUG-15: SemVer 2.0 prerelease/build ordering, future-only exhausted quota inference, and <6h dual-bucket classification', async () => {
|
||||||
|
const h = backendHarness({
|
||||||
|
quotaSummary: {
|
||||||
|
groups: [
|
||||||
|
{
|
||||||
|
displayName: 'Gemini',
|
||||||
|
buckets: [
|
||||||
|
{
|
||||||
|
// Omitted remainingFraction with epoch-0 resetTime must NOT falsely report 0% remaining!
|
||||||
|
resetTime: '1970-01-01T00:00:00Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayName: 'Claude & GPT',
|
||||||
|
buckets: [
|
||||||
|
{
|
||||||
|
remainingFraction: 0.4,
|
||||||
|
resetTime: new Date(nowMs + 2 * 3600_000).toISOString(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
remainingFraction: 0.8,
|
||||||
|
// Weekly bucket that happens to be 4h away from resetting!
|
||||||
|
resetTime: new Date(nowMs + 4 * 3600_000).toISOString(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(h.compareSemver('1.4.2+20261110', '1.4.2'), 0);
|
||||||
|
assert.equal(h.compareSemver('1.5.0-beta.2', '1.5.0-alpha.10'), 1);
|
||||||
|
assert.equal(h.compareSemver('1.5.0-alpha.1', '1.5.0-alpha.beta'), -1);
|
||||||
|
|
||||||
|
const p = await h.buildTelemetryPayloadInternal('');
|
||||||
|
const geminiPool = p.quotas.pools.find((x) => x.poolKey === 'Gemini');
|
||||||
|
assert.ok(geminiPool);
|
||||||
|
assert.equal(geminiPool.isAvailable, false, 'epoch-0 omitted remainingFraction must not create fake 0% exhausted pool');
|
||||||
|
assert.equal(geminiPool.remainingPct, null);
|
||||||
|
assert.equal(geminiPool.usedPct, null);
|
||||||
|
|
||||||
|
const claudePool = p.quotas.pools.find((x) => x.poolKey === 'Claude & GPT');
|
||||||
|
assert.ok(claudePool);
|
||||||
|
assert.equal(claudePool.remainingPct, 40);
|
||||||
|
assert.equal(claudePool.weeklyRemainingPct, 80);
|
||||||
|
|
||||||
|
assert.equal(formatCountdown(new Date(nowMs + 30_000).toISOString(), nowMs), '<1分钟后重置');
|
||||||
|
assert.equal(formatCountdown('1969-12-31T23:59:59Z', nowMs), '未知重置时间');
|
||||||
|
assert.equal(formatUsd(0.0004, { precise: true }), '<$0.001');
|
||||||
|
assert.equal(formatUsd(12.34, { unpricedCalls: 1, compactPending: true }), '$12.34+');
|
||||||
|
assert.equal(speedReasonText('short_timing'), '耗时过短 (<0.5s)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('BUG-17 & CANCEL-06: extractContextBreakdown classifies messagePrompts when children are empty and blocks post-compaction carryover', () => {
|
||||||
|
const ctx = extractContextBreakdown({
|
||||||
|
chatStartMetadata: {
|
||||||
|
contextWindowMetadata: {
|
||||||
|
estimatedTokensUsed: 10000,
|
||||||
|
tokenBreakdown: {
|
||||||
|
groups: [
|
||||||
|
{ type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 2000 },
|
||||||
|
{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 8000, children: [] },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
messagePrompts: [
|
||||||
|
{ source: 'CHAT_MESSAGE_SOURCE_USER', prompt: '<USER_REQUEST>hello world</USER_REQUEST>' },
|
||||||
|
{ source: 'CHAT_MESSAGE_SOURCE_MODEL', prompt: 'Assistant reply content here!' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
assert.ok(ctx);
|
||||||
|
assert.equal(ctx.systemPromptTokens, 2000);
|
||||||
|
assert.ok(ctx.userInputTokens > 0);
|
||||||
|
assert.ok(ctx.assistantTokens > 0);
|
||||||
|
assert.equal(ctx.userInputTokens + ctx.assistantTokens, 8000);
|
||||||
|
|
||||||
|
const stepsWithTrailingCheckpoint = extractModelSteps(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||||
|
createdAt: nowIso,
|
||||||
|
completedAt: doneIso,
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '500' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 2 },
|
||||||
|
createdAt: nowIso,
|
||||||
|
completedAt: doneIso,
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '1200' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
stepIndices: [1],
|
||||||
|
chatModel: {
|
||||||
|
chatStartMetadata: {
|
||||||
|
contextWindowMetadata: {
|
||||||
|
estimatedTokensUsed: 180_000,
|
||||||
|
tokenBreakdown: {
|
||||||
|
groups: [{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 180_000 }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert.equal(stepsWithTrailingCheckpoint.length, 2);
|
||||||
|
assert.equal(stepsWithTrailingCheckpoint[1].isCompactionStep, true);
|
||||||
|
assert.equal(
|
||||||
|
stepsWithTrailingCheckpoint[1].contextBreakdown,
|
||||||
|
null,
|
||||||
|
'compaction checkpoint must not inherit pre-compaction 180k contextBreakdown'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('BUG-20 & BUG-24: reactive store microtask deduplication, stripModuleSyntax safety, and IIFE bundle isolation', async () => {
|
||||||
|
const store = createReactiveStore({ a: 1, b: 2 });
|
||||||
|
let calls = 0;
|
||||||
|
store.subscribe((s) => s.a + s.b, () => {
|
||||||
|
calls += 1;
|
||||||
|
}, { immediate: false });
|
||||||
|
|
||||||
|
store.setState({ a: 10 });
|
||||||
|
store.setState({ b: 20 });
|
||||||
|
await new Promise((r) => queueMicrotask(r));
|
||||||
|
assert.equal(calls, 1, 'multiple setState calls in same microtask must batch into 1 subscriber flush');
|
||||||
|
|
||||||
|
const trickyModule = [
|
||||||
|
"import './side-effect.js';",
|
||||||
|
"import { foo,\n bar } from './multi.js';",
|
||||||
|
'const tpl = `\nimport { keepMe } from "tpl";\nexport const KEEP_ME = 42;\n`;',
|
||||||
|
'export async function runTask() { return tpl; }',
|
||||||
|
'export { runTask };',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
const stripped = stripModuleSyntax(trickyModule);
|
||||||
|
assert.ok(stripped.includes('import { keepMe } from "tpl"'));
|
||||||
|
assert.ok(stripped.includes('export const KEEP_ME = 42'));
|
||||||
|
assert.equal(/^\s*import\s/m.test(stripped.replace(/`[\s\S]*?`/g, '')), false);
|
||||||
|
assert.doesNotThrow(() => new vm.Script(stripped));
|
||||||
|
|
||||||
|
const appBundle = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
|
||||||
|
assert.ok(appBundle.startsWith('(() => {\n\'use strict\';'));
|
||||||
|
assert.ok(appBundle.trimEnd().endsWith('})();'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => {
|
||||||
|
const convId = '4432b724-3e1e-4421-a375-c6855a7b7b37';
|
||||||
|
|
||||||
|
// Pre-compaction steps (matching real-world step 0..2: planner edit_file x2 + 2 completed tool results)
|
||||||
|
const rpcPreCompactionSteps = [
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: '2026-11-11T02:18:21Z',
|
||||||
|
finishedGeneratingAt: '2026-11-11T02:18:35Z',
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M318',
|
||||||
|
inputTokens: '2918',
|
||||||
|
cacheReadTokens: '252465',
|
||||||
|
outputTokens: '814',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plannerResponse: {
|
||||||
|
toolCalls: [
|
||||||
|
{ name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/backend-harness.mjs' }) },
|
||||||
|
{ name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/04-post-fix-verify.mjs' }) },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_CODE_ACTION',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:38Z' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_CODE_ACTION',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:40Z' },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// transcript.jsonl still ends at step_index 2 (since CHECKPOINT only flushes to transcript.jsonl when DONE)
|
||||||
|
const transcriptPreFlush = [
|
||||||
|
{
|
||||||
|
step_index: 0,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'PLANNER_RESPONSE',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-11T02:18:21Z',
|
||||||
|
tool_calls: [
|
||||||
|
{ name: 'edit_file', args: { Path: '"f:\\\\repo\\\\backend-harness.mjs"' } },
|
||||||
|
{ name: 'edit_file', args: { Path: '"f:\\\\repo\\\\04-post-fix-verify.mjs"' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_index: 1,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'GENERIC',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-11T02:18:35Z',
|
||||||
|
content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:38+09:00\nMade 1 replacement',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_index: 2,
|
||||||
|
source: 'MODEL',
|
||||||
|
type: 'GENERIC',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-11T02:18:35Z',
|
||||||
|
content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:40+09:00\nMade 1 replacement',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// Phase 1: In-progress CORTEX_STEP_TYPE_CHECKPOINT in RPC WITHOUT metadata.createdAt yet + trailing MEMENTO
|
||||||
|
const h = backendHarness({
|
||||||
|
summaries: {
|
||||||
|
[convId]: {
|
||||||
|
stepCount: 4,
|
||||||
|
lastModifiedTime: '2026-11-11T02:18:35Z',
|
||||||
|
status: 'CASCADE_RUN_STATUS_RUNNING',
|
||||||
|
annotations: { title: 'Audit & Fix Session' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
trajectories: {
|
||||||
|
[convId]: {
|
||||||
|
trajectory: {
|
||||||
|
steps: [
|
||||||
|
...rpcPreCompactionSteps,
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
||||||
|
status: 'CORTEX_STEP_STATUS_RUNNING',
|
||||||
|
metadata: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_MEMENTO',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: { createdAt: '2026-11-11T02:18:40Z' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
transcripts: {
|
||||||
|
[convId]: transcriptPreFlush,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const pCompacting = await h.buildTelemetryPayloadInternal(convId);
|
||||||
|
assert.equal(pCompacting.activeConversation.liveActivity.phase, 'compacting');
|
||||||
|
assert.equal(pCompacting.activeConversation.liveActivity.label, '上下文压缩');
|
||||||
|
assert.equal(
|
||||||
|
pCompacting.activeConversation.liveActivity.startedAtMs,
|
||||||
|
Date.parse('2026-11-11T02:18:40Z'),
|
||||||
|
'uses previous tool completion timestamp when in-progress CHECKPOINT lacks createdAt'
|
||||||
|
);
|
||||||
|
assert.equal(pCompacting.runningConversations[0].mainActivity.phase, 'compacting');
|
||||||
|
assert.equal(pCompacting.runningConversations[0].mainActivity.label, '上下文压缩');
|
||||||
|
|
||||||
|
// Phase 2: CHECKPOINT finishes (status=DONE in both RPC & transcript.jsonl) while resuming before next PLANNER_RESPONSE
|
||||||
|
h.state.trajectories[convId] = {
|
||||||
|
trajectory: {
|
||||||
|
steps: [
|
||||||
|
...rpcPreCompactionSteps,
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: '2026-11-11T02:18:40Z',
|
||||||
|
finishedGeneratingAt: '2026-11-11T02:19:33Z',
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M318',
|
||||||
|
inputTokens: '3082',
|
||||||
|
cacheReadTokens: '254224',
|
||||||
|
outputTokens: '4627',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
h.state.transcripts[convId] = [
|
||||||
|
...transcriptPreFlush,
|
||||||
|
{
|
||||||
|
step_index: 3,
|
||||||
|
source: 'SYSTEM',
|
||||||
|
type: 'CHECKPOINT',
|
||||||
|
status: 'DONE',
|
||||||
|
created_at: '2026-11-11T02:18:40Z',
|
||||||
|
content: '# Resuming from a compaction\n...',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
h.state.transcriptMtimeMs = 2;
|
||||||
|
|
||||||
|
const pResuming = await h.buildTelemetryPayloadInternal(convId);
|
||||||
|
assert.equal(pResuming.activeConversation.liveActivity.phase, 'compacting');
|
||||||
|
assert.equal(pResuming.activeConversation.liveActivity.label, '上下文压缩');
|
||||||
|
assert.equal(pResuming.activeConversation.liveActivity.detail, '已完成压缩,正在恢复推理');
|
||||||
|
assert.equal(
|
||||||
|
pResuming.activeConversation.liveActivity.startedAtMs,
|
||||||
|
Date.parse('2026-11-11T02:19:33Z')
|
||||||
|
);
|
||||||
|
|
||||||
|
// Phase 3: Even when RPC fails/cools down and ONLY transcript.jsonl (with status="DONE" CHECKPOINT) is available,
|
||||||
|
// it STILL detects compaction instead of regressing to pre-compaction "修改文件"
|
||||||
|
h.state.trajectories[convId] = new Error('temporary RPC timeout');
|
||||||
|
const pTranscriptOnly = await h.buildTelemetryPayloadInternal(convId, true);
|
||||||
|
assert.equal(pTranscriptOnly.activeConversation.liveActivity.phase, 'compacting');
|
||||||
|
assert.equal(pTranscriptOnly.activeConversation.liveActivity.label, '上下文压缩');
|
||||||
|
});
|
||||||
@@ -2,6 +2,16 @@ import fs from 'node:fs';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import vm from 'node:vm';
|
import vm from 'node:vm';
|
||||||
import * as metrics from '../speed-metrics.mjs';
|
import * as metrics from '../speed-metrics.mjs';
|
||||||
|
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||||
|
|
||||||
|
const REAL_CATALOG_RAW = JSON.parse(
|
||||||
|
fs.readFileSync(new URL('../../../pricing-catalog.json', import.meta.url), 'utf8')
|
||||||
|
);
|
||||||
|
const DEFAULT_BUNDLED_CATALOG = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
pricing: REAL_CATALOG_RAW.pricing,
|
||||||
|
placeholders: REAL_CATALOG_RAW.placeholders,
|
||||||
|
};
|
||||||
|
|
||||||
const BACKEND_MODULE_FILES = [
|
const BACKEND_MODULE_FILES = [
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
@@ -13,6 +23,7 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../backend/local-scanner.mjs',
|
'../backend/local-scanner.mjs',
|
||||||
'../backend/usage-aggregator.mjs',
|
'../backend/usage-aggregator.mjs',
|
||||||
'../backend/telemetry-builder.mjs',
|
'../backend/telemetry-builder.mjs',
|
||||||
|
'../backend/window-bridge.mjs',
|
||||||
'../main.mjs',
|
'../main.mjs',
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -23,20 +34,19 @@ function loadCombinedBackendSource() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function stripEsmSyntax(rawSource, mainUrl) {
|
function stripEsmSyntax(rawSource, mainUrl) {
|
||||||
return rawSource
|
return stripModuleSyntax(rawSource).replaceAll('import.meta.url', JSON.stringify(mainUrl));
|
||||||
.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({
|
export function backendHarness({
|
||||||
cache={},
|
cache={},
|
||||||
|
deepStats=null,
|
||||||
|
transcripts={},
|
||||||
settings={},
|
settings={},
|
||||||
trajectories={},
|
trajectories={},
|
||||||
summaries={},
|
summaries={},
|
||||||
userStatus={},
|
userStatus={},
|
||||||
quotaSummary={groups:[]},
|
quotaSummary={groups:[]},
|
||||||
localCatalog=null,
|
localCatalog=DEFAULT_BUNDLED_CATALOG,
|
||||||
remoteCatalog=null,
|
remoteCatalog=null,
|
||||||
pluginManifest=null,
|
pluginManifest=null,
|
||||||
hasGitDir=false,
|
hasGitDir=false,
|
||||||
@@ -49,7 +59,7 @@ export function backendHarness({
|
|||||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
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 mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||||
const state={calls:[],errors:[],saves:[],trajectories,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir};
|
const state={calls:[],errors:[],saves:[],trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
||||||
const ctx={
|
const ctx={
|
||||||
...metricsImplementation, URL, AbortSignal, Buffer,
|
...metricsImplementation, URL, AbortSignal, Buffer,
|
||||||
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||||
@@ -63,16 +73,42 @@ export function backendHarness({
|
|||||||
existsSync:p=>{
|
existsSync:p=>{
|
||||||
const norm = String(p).replace(/\\/g, '/');
|
const norm = String(p).replace(/\\/g, '/');
|
||||||
if (norm.endsWith('settings.json') || norm.endsWith('trajectory_usage_cache.json')) return true;
|
if (norm.endsWith('settings.json') || norm.endsWith('trajectory_usage_cache.json')) return true;
|
||||||
|
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return Boolean(state.deepStats);
|
||||||
if (norm.endsWith('pricing-catalog.json')) return Boolean(state.localCatalog);
|
if (norm.endsWith('pricing-catalog.json')) return Boolean(state.localCatalog);
|
||||||
if (norm.endsWith('remote_pricing_cache.json')) return Boolean(state.remoteCatalog);
|
if (norm.endsWith('remote_pricing_cache.json')) return Boolean(state.remoteCatalog);
|
||||||
if (norm.endsWith('plugin.json')) return Boolean(state.pluginManifest);
|
if (norm.endsWith('plugin.json')) return Boolean(state.pluginManifest);
|
||||||
|
if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) {
|
||||||
|
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||||
|
return Boolean(m && state.transcripts?.[m[1]]);
|
||||||
|
}
|
||||||
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir);
|
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir);
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
mkdirSync:()=>{},readdirSync:()=>[],statSync:()=>({mtimeMs:0}),
|
mkdirSync:()=>{},readdirSync:()=>[],
|
||||||
|
statSync:p=>{
|
||||||
|
const norm = String(p).replace(/\\/g, '/');
|
||||||
|
if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) {
|
||||||
|
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||||
|
const lines = m && state.transcripts?.[m[1]];
|
||||||
|
if (lines) {
|
||||||
|
const text = Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines);
|
||||||
|
return {mtimeMs:state.transcriptMtimeMs,size:Buffer.byteLength(text,'utf8')};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json') && state.deepStats) {
|
||||||
|
return {mtimeMs:state.deepStatsMtimeMs,size:JSON.stringify(state.deepStats).length};
|
||||||
|
}
|
||||||
|
return {mtimeMs:0,size:0};
|
||||||
|
},
|
||||||
readFileSync:p=>{
|
readFileSync:p=>{
|
||||||
const norm = String(p).replace(/\\/g, '/');
|
const norm = String(p).replace(/\\/g, '/');
|
||||||
|
if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) {
|
||||||
|
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||||
|
const lines = m && state.transcripts?.[m[1]];
|
||||||
|
return Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines || '');
|
||||||
|
}
|
||||||
if (norm.endsWith('settings.json')) return JSON.stringify(settings);
|
if (norm.endsWith('settings.json')) return JSON.stringify(settings);
|
||||||
|
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return JSON.stringify(state.deepStats);
|
||||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
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('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||||
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
||||||
@@ -89,7 +125,6 @@ export function backendHarness({
|
|||||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,fileURLToPath:()=>mainPath,
|
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;}},
|
Response:class {constructor(body,options){this.body=body;this.options=options;}},
|
||||||
SidecarApp:class {page(){} api(){} run(){}},
|
SidecarApp:class {page(){} api(){} run(){}},
|
||||||
StreamDiagnostics:class {status(){return {enabled:false};} start(){}},
|
|
||||||
fetch:async(url,options={})=>{
|
fetch:async(url,options={})=>{
|
||||||
if (/^https?:\/\/(?!test\.invalid)/i.test(String(url)) && remoteFetch) {
|
if (/^https?:\/\/(?!test\.invalid)/i.test(String(url)) && remoteFetch) {
|
||||||
return remoteFetch(url, options);
|
return remoteFetch(url, options);
|
||||||
@@ -101,13 +136,14 @@ export function backendHarness({
|
|||||||
return {ok:true,json:async()=>data||{}};
|
return {ok:true,json:async()=>data||{}};
|
||||||
}
|
}
|
||||||
if(method==='RetrieveUserQuotaSummary') {
|
if(method==='RetrieveUserQuotaSummary') {
|
||||||
if(state.quotaSummary instanceof Error) throw state.quotaSummary;
|
const qs=state.quotaSummary;
|
||||||
return {ok:true,json:async()=>({response:state.quotaSummary})};
|
if(qs instanceof Error) throw qs;
|
||||||
|
return {ok:true,json:async()=>({response:qs})};
|
||||||
}
|
}
|
||||||
const data={GetUserStatus:{userStatus:state.userStatus},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method];
|
const data={GetUserStatus:{userStatus:state.userStatus},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method];
|
||||||
return {ok:true,json:async()=>data};
|
return {ok:true,json:async()=>data};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,compareSemver,performPluginUpdate};',ctx);
|
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isCarbonModelIdentifier,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate};',ctx);
|
||||||
return {...ctx.api,state};
|
return {...ctx.api,state};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ test('old ambiguous Argon cache is persisted as unresolved while retaining moder
|
|||||||
await h.buildTelemetryPayloadInternal('test');
|
await h.buildTelemetryPayloadInternal('test');
|
||||||
assert.equal(h.state.saves.length,1,'do not rewrite identical migrated cache every poll');
|
assert.equal(h.state.saves.length,1,'do not rewrite identical migrated cache every poll');
|
||||||
h.state.trajectories.test = {trajectory:{steps:[step(211,FLASH,true)]}};
|
h.state.trajectories.test = {trajectory:{steps:[step(211,FLASH,true)]}};
|
||||||
const restored = await h.buildTelemetryPayloadInternal('test');
|
const restored = await h.buildTelemetryPayloadInternal('test', true);
|
||||||
assert.equal(restored.activeConversation.activeModelShort,'flash-3.8-high·压缩');
|
assert.equal(restored.activeConversation.activeModelShort,'flash-3.8-high·压缩');
|
||||||
assert.equal(restored.consumption.account.unpricedCalls,0);
|
assert.equal(restored.consumption.account.unpricedCalls,0);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,194 +0,0 @@
|
|||||||
import test from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
|
||||||
import { tmpdir } from 'node:os';
|
|
||||||
import { dirname, join, resolve } from 'node:path';
|
|
||||||
import { ConnectJsonDecoder, StreamObservation, StreamDiagnostics, encodeConnectJson } from '../stream-diagnostics.mjs';
|
|
||||||
|
|
||||||
const ID = '12345678-1234-1234-1234-123456789abc';
|
|
||||||
const CREATED = '2026-10-15T01:00:00.000Z';
|
|
||||||
const FINISHED = '2026-10-15T01:00:08.000Z';
|
|
||||||
const event = (ms, batch = ms) => ({ elapsedMs: ms, receiveBatch: batch, receivedAt: CREATED });
|
|
||||||
const model = (p = {}, done = false, extra = {}) => ({
|
|
||||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', status: done ? 'CORTEX_STEP_STATUS_DONE' : 'CORTEX_STEP_STATUS_STREAMING',
|
|
||||||
metadata: { createdAt: CREATED, ...(done ? { finishedGeneratingAt: FINISHED, modelUsage: { outputTokens: '400' } } : {}) },
|
|
||||||
plannerResponse: p, ...extra,
|
|
||||||
});
|
|
||||||
const update = (indices, steps, totalLength, more = {}) => ({ update: { conversationId: ID,
|
|
||||||
mainTrajectoryUpdate: { stepsUpdate: { indices, steps, totalLength }, ...more } } });
|
|
||||||
function observer() {
|
|
||||||
const records = [];
|
|
||||||
const observation = new StreamObservation({ conversationId: ID, connectedWallMs: Date.parse(CREATED) - 1000, emit: r => records.push(r) });
|
|
||||||
return { records, observation };
|
|
||||||
}
|
|
||||||
|
|
||||||
test('Connect decoder reconstructs fragmented headers/UTF-8 and keeps coalesced messages separate', () => {
|
|
||||||
const a = { update: { text: '中文🙂' } };
|
|
||||||
const b = { update: { text: 'second' } };
|
|
||||||
const bytes = Buffer.concat([encodeConnectJson(a), encodeConnectJson(b)]);
|
|
||||||
const decoder = new ConnectJsonDecoder();
|
|
||||||
const messages = [];
|
|
||||||
for (let i = 0; i < bytes.length; i += 3) messages.push(...decoder.push(bytes.subarray(i, i + 3)));
|
|
||||||
decoder.finish();
|
|
||||||
assert.deepEqual(messages.map(m => m.value), [a, b]);
|
|
||||||
const end = encodeConnectJson({}); end[0] = 2;
|
|
||||||
assert.equal(decoder.push(end)[0].end, true);
|
|
||||||
assert.throws(() => decoder.push(encodeConnectJson(a)), /data_after_end/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Connect decoder rejects oversized, compressed, malformed and truncated frames', () => {
|
|
||||||
const huge = Buffer.from([0, 0, 0, 1, 0]);
|
|
||||||
assert.throws(() => new ConnectJsonDecoder(100).push(huge), /frame_too_large/);
|
|
||||||
const compressed = encodeConnectJson({}); compressed[0] = 1;
|
|
||||||
assert.throws(() => new ConnectJsonDecoder().push(compressed), /unsupported_frame_flags/);
|
|
||||||
assert.throws(() => new ConnectJsonDecoder().push(Buffer.from([0, 0, 0, 0, 1, 120])), /invalid_frame_json/);
|
|
||||||
const decoder = new ConnectJsonDecoder(); decoder.push(Buffer.from([0, 0]));
|
|
||||||
assert.throws(() => decoder.finish(), /truncated_frame/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('history, delayed rehydration and status-only notifications never become live output', () => {
|
|
||||||
const { observation: o, records } = observer();
|
|
||||||
o.accept({ update: { conversationId: ID, status: 'IDLE' } }, event(0));
|
|
||||||
assert.equal(o.initialized, false);
|
|
||||||
o.accept(update([9], [model({ response: 'old response' }, true)], 10), event(1));
|
|
||||||
o.accept(update([4], [model({ response: 'late history' }, true)], 10), event(2));
|
|
||||||
assert.equal(o.contentEvents, 0);
|
|
||||||
assert.equal(o.recent.length, 0);
|
|
||||||
assert.deepEqual(records.map(r => r.kind), ['baseline']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('tool arguments, thinking and text are counted independently; receive batches are not tokens', () => {
|
|
||||||
const { observation: o, records } = observer();
|
|
||||||
o.accept(update([], [], 10), event(0));
|
|
||||||
o.accept(update([10], [model()], 11), event(10));
|
|
||||||
o.accept(update([10], [model({ thinking: 'hidden-secret', response: '中', toolCalls: [{ argumentsJson: '{', name: 'secret-tool' }] })], 11), event(20, 2));
|
|
||||||
o.accept(update([10], [model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"' }] })], 11), event(20, 2));
|
|
||||||
const full = model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"argument-secret"}' }] }, true);
|
|
||||||
o.accept(update([10], [full], 11), event(120, 3));
|
|
||||||
o.accept(update([10], [full], 11), event(300, 4));
|
|
||||||
o.accept(update([], [], 11, { generatorMetadatasUpdate: { generatorMetadatas: [{ stepIndices: [10], chatModel: {
|
|
||||||
usage: { outputTokens: '400', thinkingOutputTokens: '50', responseHeader: { authorization: 'credential-secret' } },
|
|
||||||
timeToFirstToken: '7.999s', streamingDuration: '0.001s', systemPrompt: 'prompt-secret',
|
|
||||||
} }] } }), event(400, 5));
|
|
||||||
const r = o.recent[0];
|
|
||||||
assert.equal(r.contentEvents, 3);
|
|
||||||
assert.equal(r.contentReceiveBatches, 2);
|
|
||||||
assert.equal(r.toolArgumentEvents, 3);
|
|
||||||
assert.equal(r.observedSpanMs, 100);
|
|
||||||
assert.equal(r.channels.text.bytes, 6);
|
|
||||||
assert.equal(r.channels.text.utf16Units, 2);
|
|
||||||
assert.equal(r.usage.outputTokens, 400);
|
|
||||||
assert.equal(r.nativeStreamSec, 0.001);
|
|
||||||
assert.equal(r.partialCapture, false);
|
|
||||||
const serialized = JSON.stringify([records, r]);
|
|
||||||
for (const secret of ['hidden-secret', 'argument-secret', 'secret-tool', 'credential-secret', 'prompt-secret', '中文']) assert.ok(!serialized.includes(secret));
|
|
||||||
assert.ok(!/tokPerSec|tps|firstTokenMs/i.test(serialized));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('same-batch delivery is not reported as a timed stream, even with several updates', () => {
|
|
||||||
const { observation: o } = observer();
|
|
||||||
o.accept(update([], [], 0), event(0));
|
|
||||||
o.accept(update([0], [model({ response: 'a' })], 1), event(5, 1));
|
|
||||||
o.accept(update([0], [model({ response: 'ab' }, true)], 1), event(5, 1));
|
|
||||||
assert.equal(o.recent[0].observation, 'single_receive_batch');
|
|
||||||
assert.equal(o.recent[0].observedSpanMs, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('rewrites, shrinking output and tool-only updates are retained as revisions', () => {
|
|
||||||
const { observation: o, records } = observer();
|
|
||||||
o.accept(update([], [], 0), event(0));
|
|
||||||
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'abcd' }] })], 1), event(10));
|
|
||||||
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wxyz' }] })], 1), event(20));
|
|
||||||
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wx' }] }, true)], 1), event(30));
|
|
||||||
assert.equal(o.recent[0].revisions, 2);
|
|
||||||
assert.equal(o.recent[0].toolArgumentEvents, 3);
|
|
||||||
assert.equal(records.at(-1).changes.toolArguments.deltaBytes, -2);
|
|
||||||
assert.equal(records.at(-1).changes.toolArguments.appendOnly, false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('joining during generation marks partial capture and excludes initial content from updates', () => {
|
|
||||||
const { observation: o } = observer();
|
|
||||||
o.accept(update([2], [model({ response: 'already there' })], 3), event(10));
|
|
||||||
o.accept(update([2], [model({ response: 'already there plus more' }, true)], 3), event(20));
|
|
||||||
assert.equal(o.recent[0].partialCapture, true);
|
|
||||||
assert.equal(o.recent[0].contentEvents, 1);
|
|
||||||
assert.equal(o.recent[0].observation, 'partial_capture');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('missing or earlier creation time never claims a complete observation', () => {
|
|
||||||
const { observation: o } = observer();
|
|
||||||
o.accept(update([], [], 0), event(0));
|
|
||||||
o.accept(update([0], [model({ response: 'arrived' }, true, { metadata: { finishedGeneratingAt: FINISHED } })], 1), event(20));
|
|
||||||
assert.equal(o.recent[0].partialCapture, true);
|
|
||||||
assert.throws(() => o.accept(update([], [model()], 2), event(25)), /invalid_step_indices/);
|
|
||||||
});
|
|
||||||
|
|
||||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
||||||
async function until(check) {
|
|
||||||
for (let i = 0; i < 100; i++) { if (check()) return; await sleep(10); }
|
|
||||||
assert.fail('timed out');
|
|
||||||
}
|
|
||||||
function temp(t) {
|
|
||||||
const dir = mkdtempSync(join(tmpdir(), 'usage-monitor-diag-test-'));
|
|
||||||
t.after(() => {
|
|
||||||
const absolute = resolve(dir);
|
|
||||||
assert.equal(dirname(absolute), resolve(tmpdir()));
|
|
||||||
assert.ok(absolute.startsWith(join(resolve(tmpdir()), 'usage-monitor-diag-test-')));
|
|
||||||
rmSync(absolute, { recursive: true, force: true });
|
|
||||||
});
|
|
||||||
return dir;
|
|
||||||
}
|
|
||||||
|
|
||||||
test('collector only subscribes to read APIs, persists counters and stops without touching billing', async t => {
|
|
||||||
const dir = temp(t);
|
|
||||||
const calls = [];
|
|
||||||
let streamController;
|
|
||||||
const fetchImpl = async (url, options) => {
|
|
||||||
calls.push({ url, options });
|
|
||||||
if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: { stepCount: 0, lastModifiedTime: CREATED } } }));
|
|
||||||
assert.ok(url.endsWith('StreamAgentStateUpdates'));
|
|
||||||
const request = new ConnectJsonDecoder().push(options.body)[0].value;
|
|
||||||
assert.equal(request.trajectoryVerbosity, 'CLIENT_TRAJECTORY_VERBOSITY_FULL');
|
|
||||||
const stream = new ReadableStream({ start(c) {
|
|
||||||
streamController = c;
|
|
||||||
c.enqueue(encodeConnectJson(update([], [], 0)));
|
|
||||||
options.signal.addEventListener('abort', () => c.error(new Error('aborted')), { once: true });
|
|
||||||
} });
|
|
||||||
return new Response(stream, { headers: { 'Content-Type': 'application/connect+json' } });
|
|
||||||
};
|
|
||||||
const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'secret-csrf', fetchImpl, pollMs: 60000 });
|
|
||||||
t.after(() => d.stop());
|
|
||||||
assert.equal(d.status().enabled, false);
|
|
||||||
d.configure({ enabled: true });
|
|
||||||
await until(() => d.status().phase === 'collecting');
|
|
||||||
streamController.enqueue(encodeConnectJson(update([0], [model({ toolCalls: [{ argumentsJson: 'private-arguments' }] }, true)], 1)));
|
|
||||||
await until(() => d.status().contentEvents === 1);
|
|
||||||
assert.equal(d.status().affectsTps, false);
|
|
||||||
d.configure({ enabled: false });
|
|
||||||
await sleep(10);
|
|
||||||
assert.equal(d.status().phase, 'disabled');
|
|
||||||
assert.equal(d.current, null);
|
|
||||||
const log = readFileSync(join(dir, 'stream-diagnostics', 'events.jsonl'), 'utf8');
|
|
||||||
assert.ok(!log.includes('secret-csrf'));
|
|
||||||
assert.ok(!log.includes('private-arguments'));
|
|
||||||
assert.ok(log.includes('step_update'));
|
|
||||||
assert.deepEqual(readdirSync(dir).sort(), ['stream-diagnostics', 'stream-diagnostics-config.json']);
|
|
||||||
assert.equal(calls.length, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('failed subscriptions back off and never expose the server error body', async t => {
|
|
||||||
const dir = temp(t);
|
|
||||||
let calls = 0;
|
|
||||||
const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'csrf', pollMs: 10, retryMs: 5000,
|
|
||||||
fetchImpl: async url => {
|
|
||||||
calls++;
|
|
||||||
if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: {} } }));
|
|
||||||
return new Response('private server error with credentials', { status: 403 });
|
|
||||||
} });
|
|
||||||
t.after(() => d.stop());
|
|
||||||
d.configure({ enabled: true });
|
|
||||||
await until(() => d.status().error === 'stream_http_403');
|
|
||||||
await sleep(40);
|
|
||||||
assert.equal(calls, 2);
|
|
||||||
assert.ok(!JSON.stringify(d.status()).includes('private'));
|
|
||||||
});
|
|
||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user