mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): restore IDE mount compatibility, add composer dock mode, and refine chart tooltips
This commit is contained in:
@@ -51,7 +51,7 @@ The dashboard is organized into four tabs, with a top header to switch conversat
|
|||||||
- **Preferences**
|
- **Preferences**
|
||||||
- **Mount Mode**: Dual-mount (Top Bar + Sidebar) or Sidebar only.
|
- **Mount Mode**: Dual-mount (Top Bar + Sidebar) or Sidebar only.
|
||||||
- **Top-Bar Customization**: Independently toggle the live running-sessions indicator, and customize the content and left-to-right order of the three metric slots in the capsule.
|
- **Top-Bar Customization**: Independently toggle the live running-sessions indicator, and customize the content and left-to-right order of the three metric slots in the capsule.
|
||||||
- **Model Name Format**: Compact short alias (e.g. `argon-4-high`) or raw upstream model ID (e.g. `gemini-3.8-flash-n`).
|
- **Model Name Format**: Compact short alias (e.g. `argon-4-high`) or raw upstream model ID (e.g. `gemini-3.8-flash-n`), plus an independent Orchestrator series ID selector (`orchestrator-argon` / `worker-agy-hydrogen` compact mode by default, or full annotated IDs).
|
||||||
- **Version Updates & Pricing Sync**: Dynamically sync [`pricing-catalog.json`](pricing-catalog.json) from GitHub, with three update modes: *Notify only, manual update* (default), *Auto update*, and *Off*.
|
- **Version Updates & Pricing Sync**: Dynamically sync [`pricing-catalog.json`](pricing-catalog.json) from GitHub, with three update modes: *Notify only, manual update* (default), *Auto update*, and *Off*.
|
||||||
|
|
||||||
## Model Identification & Cost Accounting
|
## Model Identification & Cost Accounting
|
||||||
@@ -98,8 +98,10 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
|||||||
## Enabling & Opening the Panel
|
## Enabling & Opening the Panel
|
||||||
|
|
||||||
1. Open **Customizations** in the left sidebar, switch to the **Installed** tab, locate `usage-monitor`, and toggle it on.
|
1. Open **Customizations** in the left sidebar, switch to the **Installed** tab, locate `usage-monitor`, and toggle it on.
|
||||||
2. **Top-Bar Floating Capsule (enabled by default)**: Once enabled, the background sidecar mounts a live status & metric capsule in the top-right bar of the main chat window (hover for quick overview, left-click to expand the full 4-tab panel, right-click to force refresh) without modifying `app.asar`. To disable the top-bar capsule, switch **Mount Mode** to *Sidebar only* in Preferences.
|
2. **Top-Bar Floating Capsule (enabled by default on both Antigravity 2.0 & Antigravity IDE)**:
|
||||||
3. **Right-Hand Sidebar Panel**: Click `⋮` in the top-right corner of the chat pane -> **Extensions** -> **Usage & Speed Monitor** (or **用量监控**) to dock the panel in the auxiliary sidebar.
|
- **Antigravity 2.0 App**: Immediately mounts a live status & metric capsule in the top-right bar of the main chat window (hover for quick overview, left-click to expand the full 4-tab panel, right-click to force refresh) without modifying `app.asar`.
|
||||||
|
- **Antigravity IDE**: On first enable, the background sidecar automatically adds `"remote-debugging-port": "0"` to `~/.antigravity-ide/argv.json` (preserving comments and existing settings). **Restart Antigravity IDE once**, and the capsule will dock into the top-right IDE window titlebar on every launch. Because Antigravity IDE does not currently expose the right-hand UI Sidecar auxiliary pane, keep **Mount Mode** set to *Dual-mount* in IDE and click the top-bar capsule to open the 4-tab dashboard.
|
||||||
|
3. **Right-Hand Sidebar Panel (Antigravity 2.0)**: Open the auxiliary sidebar menu in the chat window to dock **Usage & Speed Monitor** on the right, or switch **Mount Mode** between *Top Bar + Sidebar* and *Sidebar only* in Preferences.
|
||||||
|
|
||||||
## Updating
|
## Updating
|
||||||
|
|
||||||
|
|||||||
+5
-3
@@ -51,7 +51,7 @@
|
|||||||
- **偏好设置**
|
- **偏好设置**
|
||||||
- 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。
|
- 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。
|
||||||
- 顶部栏定制:独立开关实时运行会话入口,并自由定义右侧三个指标槽位的显示内容与排列顺序。
|
- 顶部栏定制:独立开关实时运行会话入口,并自由定义右侧三个指标槽位的显示内容与排列顺序。
|
||||||
- 选择模型名称格式:精简代号或原始模型 ID。
|
- 选择模型名称格式:精简代号或原始模型 ID,并可独立设置 Orchestrator 系列显示精简代号(如 `orchestrator-argon`、`worker-agy-hydrogen`)或原始完整 ID。
|
||||||
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并提供「仅提示新版本,手动更新」(默认)、「自动更新」与「关闭更新」三档更新方式。
|
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并提供「仅提示新版本,手动更新」(默认)、「自动更新」与「关闭更新」三档更新方式。
|
||||||
|
|
||||||
## 模型识别与费用口径
|
## 模型识别与费用口径
|
||||||
@@ -98,8 +98,10 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
|||||||
## 启用与打开面板
|
## 启用与打开面板
|
||||||
|
|
||||||
1. 打开左侧边栏的 **Customizations**,进入 **Installed** 标签页,找到 `usage-monitor` 并开启。
|
1. 打开左侧边栏的 **Customizations**,进入 **Installed** 标签页,找到 `usage-monitor` 并开启。
|
||||||
2. **顶部栏胶囊悬浮面板(默认双栖开启)**:开启插件后,后台 Sidecar 会自动在主对话窗口右上角顶部栏挂载实时状态与指标胶囊(悬停查看速览,左键展开完整四标签面板,右键强制刷新),全程不修改宿主 `app.asar`。如需关闭顶部栏胶囊,可在 **偏好设置 -> 面板挂载方式** 中切换为「仅侧边栏」。
|
2. **顶部栏胶囊悬浮面板(默认开启,兼容 Antigravity 2.0 与 Antigravity IDE)**:
|
||||||
3. **右侧辅助栏面板**:点击对话窗口右上角 `⋮` -> **Extensions** -> **用量监控**,在右侧辅助栏展开面板;或在对话中输入「打开用量监控面板」通过快捷入口唤起。
|
- **Antigravity 2.0 桌面端**:开启插件后即自动在主对话窗口右上角顶部栏挂载实时状态与指标胶囊(悬停查看速览,左键展开完整四标签面板,右键强制刷新),全程不修改宿主 `app.asar`。
|
||||||
|
- **Antigravity IDE**:首次启用插件时,后台 Sidecar 会自动在 `~/.antigravity-ide/argv.json` 中补齐 `"remote-debugging-port": "0"`(保留原有注释与配置)。**完整重启一次 Antigravity IDE** 后,胶囊会自动停靠在 IDE 窗口最上方标题栏右侧。由于 Antigravity IDE 宿主暂未开放右侧 UI Sidecar 辅助栏,在 IDE 中请保持「双栖挂载」并直接点击顶部栏胶囊打开四标签面板。
|
||||||
|
3. **右侧辅助栏面板(Antigravity 2.0)**:在 Antigravity 2.0 对话窗口点击右上角菜单打开右侧辅助栏中的 **用量监控**,或在 **偏好设置 -> 面板挂载方式** 中按需切换「顶部栏 + 侧边栏」与「仅侧边栏」。
|
||||||
|
|
||||||
## 更新
|
## 更新
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"host": {
|
||||||
|
"command": "node",
|
||||||
|
"args": [
|
||||||
|
"${PLUGIN_ROOT}/sidecars/panel/mcp-entry.mjs"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"USAGE_MONITOR_PLUGIN_DATA": "${PLUGIN_DATA}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+49
-12
@@ -1,12 +1,16 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"catalogVersion": "2026.11.11.4",
|
"catalogVersion": "2026.11.14.1",
|
||||||
"updatedAt": "2026-11-11T23:20:00+09:00",
|
"updatedAt": "2026-11-14T16:40:00+09:00",
|
||||||
"latestPluginVersion": "1.4.4",
|
"latestPluginVersion": "1.4.4",
|
||||||
"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",
|
||||||
"pricing": {
|
"pricing": {
|
||||||
|
"gemini-pro-orchestrator": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" },
|
||||||
|
"orchestrator-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" },
|
||||||
|
"gemini-pro-orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini" },
|
||||||
|
"orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini" },
|
||||||
"gemini-4-carbon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-high", "family": "Gemini" },
|
"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-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-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-low", "family": "Gemini" },
|
||||||
@@ -14,17 +18,22 @@
|
|||||||
"gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini" },
|
"gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini" },
|
||||||
"gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
"gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
||||||
"gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini" },
|
"gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini" },
|
||||||
|
"gemini-4-argon-f": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
||||||
|
"gemini-4-argon-disabled": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
||||||
"gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
"gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
||||||
"gemini-4-hydrogen-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen-4-high", "family": "Gemini" },
|
"gemini-4-hydrogen-xhigh": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4-xhigh", "family": "Gemini" },
|
||||||
"gemini-4-hydrogen-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen-4", "family": "Gemini" },
|
"gemini-4-hydrogen-high": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4-high", "family": "Gemini" },
|
||||||
"gemini-4-hydrogen-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "hydrogen-4-low", "family": "Gemini" },
|
"gemini-4-hydrogen-medium": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4", "family": "Gemini" },
|
||||||
"gemini-4-hydrogen-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen-4", "family": "Gemini" },
|
"gemini-4-hydrogen-low": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4-low", "family": "Gemini" },
|
||||||
"gemini-4-hydrogen": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen-4", "family": "Gemini" },
|
"gemini-4-hydrogen-tiered": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4", "family": "Gemini" },
|
||||||
"gemini-hydrogen-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen-high", "family": "Gemini" },
|
"gemini-4-hydrogen": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4", "family": "Gemini" },
|
||||||
"gemini-hydrogen-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen", "family": "Gemini" },
|
"gemini-flash-worker-agy": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4", "family": "Gemini" },
|
||||||
"gemini-hydrogen-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "hydrogen-low", "family": "Gemini" },
|
"gemini-hydrogen-xhigh": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-xhigh", "family": "Gemini" },
|
||||||
"gemini-hydrogen-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen", "family": "Gemini" },
|
"gemini-hydrogen-high": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-high", "family": "Gemini" },
|
||||||
"gemini-hydrogen": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "hydrogen", "family": "Gemini" },
|
"gemini-hydrogen-medium": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen", "family": "Gemini" },
|
||||||
|
"gemini-hydrogen-low": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-low", "family": "Gemini" },
|
||||||
|
"gemini-hydrogen-tiered": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen", "family": "Gemini" },
|
||||||
|
"gemini-hydrogen": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen", "family": "Gemini" },
|
||||||
"gemini-4-helix-high": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "helix-4-high", "family": "Gemini" },
|
"gemini-4-helix-high": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "helix-4-high", "family": "Gemini" },
|
||||||
"gemini-4-helix-medium": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "helix-4", "family": "Gemini" },
|
"gemini-4-helix-medium": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "helix-4", "family": "Gemini" },
|
||||||
"gemini-4-helix-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "helix-4-low", "family": "Gemini" },
|
"gemini-4-helix-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "helix-4-low", "family": "Gemini" },
|
||||||
@@ -37,11 +46,13 @@
|
|||||||
"gemini-3.8-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "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-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-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" },
|
||||||
|
"gemini-3.8-flash-n": { "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.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-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-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-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-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" },
|
||||||
|
"gemini-3.7-flash-safety-le": { "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.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-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-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini" },
|
||||||
@@ -52,6 +63,10 @@
|
|||||||
"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-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-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": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5", "family": "Gemini" },
|
||||||
|
"gemini-3-flash-a": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5", "family": "Gemini" },
|
||||||
|
"gemini-3-flash-b": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5", "family": "Gemini" },
|
||||||
|
"gemini-3-flash-d": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5", "family": "Gemini" },
|
||||||
|
"gemini-3-flash-agent": { "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.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-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": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1-low", "family": "Gemini" },
|
||||||
@@ -59,11 +74,15 @@
|
|||||||
"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": { "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-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-pro": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1", "family": "Gemini" },
|
||||||
|
"gemini-pro-default": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1", "family": "Gemini" },
|
||||||
|
"gemini-pro-agent": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1", "family": "Gemini" },
|
||||||
|
"gemini-pro-b": { "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-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-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-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.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-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" },
|
||||||
|
"gemini-3-flash-c": { "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-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-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-pro": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "pro-2.5", "family": "Gemini" },
|
||||||
@@ -128,7 +147,17 @@
|
|||||||
"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_M667": { "modelId": "gemini-pro-orchestrator", "label": "Orchestrator (Carbon)" },
|
||||||
|
"MODEL_PLACEHOLDER_M681": { "modelId": "gemini-pro-orchestrator-argon", "label": "Orchestrator (Argon)" },
|
||||||
|
"MODEL_PLACEHOLDER_M669": { "modelId": "gemini-flash-worker-agy", "label": "Orchestrator Worker (Hydrogen)" },
|
||||||
"MODEL_PLACEHOLDER_M429": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" },
|
"MODEL_PLACEHOLDER_M429": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" },
|
||||||
|
"MODEL_PLACEHOLDER_M427": { "modelId": "gemini-4-carbon-high", "label": "Gemini 4 Carbon (High)" },
|
||||||
|
"MODEL_PLACEHOLDER_M437": { "modelId": "gemini-4-carbon-medium", "label": "Gemini 4 Carbon (Medium)" },
|
||||||
|
"MODEL_PLACEHOLDER_M438": { "modelId": "gemini-4-carbon-low", "label": "Gemini 4 Carbon (Low)" },
|
||||||
|
"MODEL_PLACEHOLDER_M528": { "modelId": "gemini-4-hydrogen-xhigh", "label": "Gemini 4 Hydrogen (XHigh)" },
|
||||||
|
"MODEL_PLACEHOLDER_M525": { "modelId": "gemini-4-hydrogen-high", "label": "Gemini 4 Hydrogen (High)" },
|
||||||
|
"MODEL_PLACEHOLDER_M526": { "modelId": "gemini-4-hydrogen-medium", "label": "Gemini 4 Hydrogen (Medium)" },
|
||||||
|
"MODEL_PLACEHOLDER_M527": { "modelId": "gemini-4-hydrogen-low", "label": "Gemini 4 Hydrogen (Low)" },
|
||||||
"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)" },
|
||||||
@@ -140,24 +169,32 @@
|
|||||||
"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)" },
|
||||||
"MODEL_PLACEHOLDER_M301": { "modelId": "gemini-3.7-flash-tiered", "label": "Gemini 3.7 Flash (Tiered)" },
|
"MODEL_PLACEHOLDER_M301": { "modelId": "gemini-3.7-flash-tiered", "label": "Gemini 3.7 Flash (Tiered)" },
|
||||||
|
"MODEL_PLACEHOLDER_M264": { "modelId": "gemini-3.6-flash-high", "label": "Gemini 3.6 Flash (High)" },
|
||||||
"MODEL_PLACEHOLDER_M71": { "modelId": "gemini-3.6-flash-high", "label": "Gemini 3.6 Flash (High)" },
|
"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_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-high", "label": "Gemini 3.5 Flash (High)" },
|
"MODEL_PLACEHOLDER_M149": { "modelId": "gemini-3.5-flash-high", "label": "Gemini 3.5 Flash (High)" },
|
||||||
|
"MODEL_PLACEHOLDER_M132": { "modelId": "gemini-3.5-flash-high", "label": "Gemini 3.5 Flash (High)" },
|
||||||
|
"MODEL_PLACEHOLDER_M84": { "modelId": "gemini-3.5-flash-high", "label": "Gemini 3.5 Flash (High)" },
|
||||||
|
"MODEL_PLACEHOLDER_M15": { "modelId": "gemini-3.5-flash-high", "label": "Gemini 3.5 Flash (High)" },
|
||||||
|
"MODEL_PLACEHOLDER_M133": { "modelId": "gemini-3.5-flash", "label": "Gemini 3.5 Flash" },
|
||||||
"MODEL_PLACEHOLDER_M20": { "modelId": "gemini-3.5-flash", "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)" },
|
||||||
|
"MODEL_PLACEHOLDER_M16": { "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_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_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_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_M21": { "modelId": "gemini-3.1-flash-image", "label": "Gemini 3.1 Flash Image" },
|
||||||
|
"MODEL_PLACEHOLDER_M47": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" },
|
||||||
"MODEL_PLACEHOLDER_M18": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" },
|
"MODEL_PLACEHOLDER_M18": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" },
|
||||||
"MODEL_PLACEHOLDER_M9": { "modelId": "gemini-3-pro-image", "label": "Gemini 3 Pro Image" },
|
"MODEL_PLACEHOLDER_M9": { "modelId": "gemini-3-pro-image", "label": "Gemini 3 Pro Image" },
|
||||||
"MODEL_GOOGLE_GEMINI_2_5_PRO": { "modelId": "gemini-2.5-pro", "label": "Gemini 2.5 Pro" },
|
"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": { "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_THINKING": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash (Thinking)" },
|
||||||
|
"MODEL_PLACEHOLDER_M330": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" },
|
||||||
"MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" },
|
"MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" },
|
||||||
"MODEL_PLACEHOLDER_M406": { "modelId": "claude-opus-5-5-max", "label": "Claude Opus 5.5 (Max)" },
|
"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_M402": { "modelId": "claude-opus-5-5-high", "label": "Claude Opus 5.5 (High)" },
|
||||||
|
|||||||
+5570
-328
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,310 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Sidecar Webview 与主窗口双栖桥接共享的 API 路由分发与运行时引导层。
|
||||||
|
*
|
||||||
|
* 与 `sidecar_sdk` 完全解耦,使同一套遥测聚合、偏好持久化、云端目录同步与自更新逻辑可同时服务于:
|
||||||
|
* 1. Antigravity 2.0 客户端右侧辅助栏 (`main.mjs` -> `SidecarApp`);
|
||||||
|
* 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import {
|
||||||
|
HERE,
|
||||||
|
SETTINGS_FILE,
|
||||||
|
cloudSyncState,
|
||||||
|
computeRuntimeCodeVersion,
|
||||||
|
isPlainObject,
|
||||||
|
loadSettings,
|
||||||
|
lsRuntimeEndpoint,
|
||||||
|
normalizeOrchestratorIdMode,
|
||||||
|
normalizePluginUpdateMode,
|
||||||
|
normalizeTopbarCapsuleSlots,
|
||||||
|
normalizeWeeklyLimitMode,
|
||||||
|
normalizeWindowMountMode,
|
||||||
|
saveJson,
|
||||||
|
} from './config.mjs';
|
||||||
|
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||||
|
import {
|
||||||
|
performPluginUpdate,
|
||||||
|
scheduleSidecarRestart,
|
||||||
|
syncCloudCatalog,
|
||||||
|
} from './plugin-updater.mjs';
|
||||||
|
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||||
|
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
||||||
|
import {
|
||||||
|
notifyWindowOverlaySetting,
|
||||||
|
startDefaultWindowBridge,
|
||||||
|
} from './window-bridge.mjs';
|
||||||
|
|
||||||
|
export const bootBundleVersion = computeRuntimeCodeVersion();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||||
|
*
|
||||||
|
* @param {string} relPath 相对路径
|
||||||
|
* @returns {Promise<string>}
|
||||||
|
*/
|
||||||
|
export const readLocalAsync = async (relPath) => {
|
||||||
|
const fullPath = join(HERE, relPath);
|
||||||
|
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
||||||
|
return fsPromises.readFile(fullPath, 'utf8');
|
||||||
|
}
|
||||||
|
return readFileSync(fullPath, 'utf8');
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||||
|
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||||
|
*
|
||||||
|
* @param {object} req
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isLocalHostRequest(req) {
|
||||||
|
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();
|
||||||
|
if (secFetchSite === 'cross-site') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (origin) {
|
||||||
|
const originMatch = origin.match(
|
||||||
|
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||||
|
);
|
||||||
|
if (!originMatch) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (hostMatch) {
|
||||||
|
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||||
|
const originPort = originMatch[3] || defaultPort;
|
||||||
|
const hostPort = hostMatch[2] || defaultPort;
|
||||||
|
if (originPort !== hostPort) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
||||||
|
|
||||||
|
function sanitizePositiveFiniteMs(val) {
|
||||||
|
const num = Number(val);
|
||||||
|
return Number.isFinite(num) && num > 0 && num <= MAX_SAFE_DATE_MS ? Math.floor(num) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||||
|
const rawConvId = String(
|
||||||
|
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
||||||
|
).trim();
|
||||||
|
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
|
||||||
|
const force = data?.force === '1' || data?.force === true;
|
||||||
|
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||||
|
if (!lsRuntimeEndpoint.baseUrl) {
|
||||||
|
await ensureLsEndpointDiscovered({ force: false });
|
||||||
|
}
|
||||||
|
if (lsRuntimeEndpoint.baseUrl) {
|
||||||
|
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
|
||||||
|
await Promise.race([
|
||||||
|
syncCloudCatalog({ force: true }).catch(() => {}),
|
||||||
|
new Promise((r) => setTimeout(r, 1200)),
|
||||||
|
]);
|
||||||
|
} else {
|
||||||
|
syncCloudCatalog({ force: false }).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const filterOpts = {
|
||||||
|
range: data?.range || 'all',
|
||||||
|
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||||
|
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
||||||
|
};
|
||||||
|
const payload = await buildTelemetryPayload(convId, force, filterOpts);
|
||||||
|
if (
|
||||||
|
bootBundleVersion &&
|
||||||
|
payload.uiBundleVersion &&
|
||||||
|
String(payload.uiBundleVersion) !== String(bootBundleVersion)
|
||||||
|
) {
|
||||||
|
if (typeof onRestart === 'function') {
|
||||||
|
onRestart();
|
||||||
|
} else {
|
||||||
|
scheduleSidecarRestart(150);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizePositiveSettingNumber(val, fallback) {
|
||||||
|
const num = Number(val);
|
||||||
|
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function executeSettingsAction(data) {
|
||||||
|
const current = loadSettings();
|
||||||
|
const payload = isPlainObject(data) ? data : {};
|
||||||
|
const nextPluginUpdateMode =
|
||||||
|
payload.pluginUpdateMode !== undefined
|
||||||
|
? normalizePluginUpdateMode(payload.pluginUpdateMode)
|
||||||
|
: typeof payload.autoUpdatePlugin === 'boolean'
|
||||||
|
? payload.autoUpdatePlugin
|
||||||
|
? 'auto'
|
||||||
|
: 'manual'
|
||||||
|
: normalizePluginUpdateMode(current.pluginUpdateMode, current.autoUpdatePlugin);
|
||||||
|
const nextWindowMountMode =
|
||||||
|
payload.windowMountMode !== undefined
|
||||||
|
? normalizeWindowMountMode(payload.windowMountMode)
|
||||||
|
: typeof payload.enableWindowOverlay === 'boolean'
|
||||||
|
? payload.enableWindowOverlay
|
||||||
|
? current.windowMountMode === 'composer'
|
||||||
|
? 'composer'
|
||||||
|
: 'dual'
|
||||||
|
: 'sidebar'
|
||||||
|
: normalizeWindowMountMode(current.windowMountMode, current.enableWindowOverlay);
|
||||||
|
const updated = {
|
||||||
|
weeklyTokenBudget: sanitizePositiveSettingNumber(
|
||||||
|
payload.weeklyTokenBudget ?? payload.weeklyTokenLimit,
|
||||||
|
current.weeklyTokenBudget
|
||||||
|
),
|
||||||
|
weeklyCostBudget: sanitizePositiveSettingNumber(
|
||||||
|
payload.weeklyCostBudget,
|
||||||
|
current.weeklyCostBudget
|
||||||
|
),
|
||||||
|
weeklyLimitMode:
|
||||||
|
payload.weeklyLimitMode !== undefined
|
||||||
|
? normalizeWeeklyLimitMode(payload.weeklyLimitMode)
|
||||||
|
: current.weeklyLimitMode,
|
||||||
|
showUpstreamModel:
|
||||||
|
typeof payload.showUpstreamModel === 'boolean'
|
||||||
|
? payload.showUpstreamModel
|
||||||
|
: Boolean(current.showUpstreamModel),
|
||||||
|
orchestratorIdMode:
|
||||||
|
payload.orchestratorIdMode !== undefined
|
||||||
|
? normalizeOrchestratorIdMode(payload.orchestratorIdMode)
|
||||||
|
: normalizeOrchestratorIdMode(current.orchestratorIdMode),
|
||||||
|
pluginUpdateMode: nextPluginUpdateMode,
|
||||||
|
autoUpdatePlugin: nextPluginUpdateMode === 'auto',
|
||||||
|
windowMountMode: nextWindowMountMode,
|
||||||
|
enableWindowOverlay: nextWindowMountMode !== 'sidebar',
|
||||||
|
showTopbarMultiSession:
|
||||||
|
typeof payload.showTopbarMultiSession === 'boolean'
|
||||||
|
? payload.showTopbarMultiSession
|
||||||
|
: current.showTopbarMultiSession !== false,
|
||||||
|
topbarCapsuleSlots:
|
||||||
|
payload.topbarCapsuleSlots !== undefined
|
||||||
|
? normalizeTopbarCapsuleSlots(payload.topbarCapsuleSlots)
|
||||||
|
: normalizeTopbarCapsuleSlots(current.topbarCapsuleSlots),
|
||||||
|
};
|
||||||
|
if (!saveJson(SETTINGS_FILE, updated)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
contentType: 'application/json',
|
||||||
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
body: JSON.stringify({ ok: false, error: 'Failed to persist settings' }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const prevMountMode = normalizeWindowMountMode(
|
||||||
|
current.windowMountMode,
|
||||||
|
current.enableWindowOverlay
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||||
|
updated.windowMountMode !== prevMountMode
|
||||||
|
) {
|
||||||
|
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
updated,
|
||||||
|
body: JSON.stringify(updated),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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() }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
|
||||||
|
if (pathname === '/api/telemetry' && method === 'GET') {
|
||||||
|
return executeTelemetryAction(data, opts);
|
||||||
|
}
|
||||||
|
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' }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动进程级双栖窗口桥接器(兼容 Sidecar 环境与独立后台守护进程环境)。
|
||||||
|
*
|
||||||
|
* @param {{ allowDynamicLs?: boolean, onRestart?: () => void }} [options]
|
||||||
|
*/
|
||||||
|
export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = null } = {}) {
|
||||||
|
if (lsRuntimeEndpoint.addr === 'test.invalid') return null;
|
||||||
|
if (!allowDynamicLs && !lsRuntimeEndpoint.addr) return null;
|
||||||
|
|
||||||
|
const triggerRestart =
|
||||||
|
typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150);
|
||||||
|
|
||||||
|
if (lsRuntimeEndpoint.baseUrl) {
|
||||||
|
syncCloudCatalog({ force: false }).catch(() => {});
|
||||||
|
} else {
|
||||||
|
ensureLsEndpointDiscovered({ force: false })
|
||||||
|
.then((ok) => {
|
||||||
|
if (ok) {
|
||||||
|
syncCloudCatalog({ force: false }).catch(() => {});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return startDefaultWindowBridge({
|
||||||
|
handleApiRequest: (pathname, method, data) =>
|
||||||
|
dispatchBridgeApiRequest(pathname, method, data, { onRestart: triggerRestart }),
|
||||||
|
readAssetFn: readLocalAsync,
|
||||||
|
bootBundleVersion,
|
||||||
|
onVersionDrift: triggerRestart,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@@ -26,10 +26,33 @@ export const PLUGIN_MANIFEST_FILE = join(PLUGIN_ROOT, 'plugin.json');
|
|||||||
export const LOCAL_CATALOG_FILE = join(PLUGIN_ROOT, 'pricing-catalog.json');
|
export const LOCAL_CATALOG_FILE = join(PLUGIN_ROOT, 'pricing-catalog.json');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor`)。
|
* 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor/panel/data`)。
|
||||||
* 存放用户偏好设置、历史轨迹缓存及云端价格表缓存,插件升级不会清除此目录。
|
* 当通过插件 `mcp_config.json` 在 Antigravity IDE 中后台启动且未注入 `ANTIGRAVITY_EXECUTABLE_DATA_DIR` 时,
|
||||||
|
* 自动对齐至同一 `sidecar_data` 目录,确保双端共享同一份设置、历史轨迹缓存与窗口桥接租约。
|
||||||
*/
|
*/
|
||||||
export const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data');
|
function resolveDefaultDataDir() {
|
||||||
|
if (process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR) {
|
||||||
|
return process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR;
|
||||||
|
}
|
||||||
|
if (String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid') {
|
||||||
|
return join(HERE, '.data');
|
||||||
|
}
|
||||||
|
const antigravityRoot = join(homedir(), '.gemini', 'antigravity');
|
||||||
|
const panelDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'panel', 'data');
|
||||||
|
const legacyDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'data');
|
||||||
|
if (existsSync(panelDataDir)) return panelDataDir;
|
||||||
|
if (existsSync(legacyDataDir)) return legacyDataDir;
|
||||||
|
if (existsSync(antigravityRoot)) return panelDataDir;
|
||||||
|
if (
|
||||||
|
process.env.USAGE_MONITOR_PLUGIN_DATA &&
|
||||||
|
!process.env.USAGE_MONITOR_PLUGIN_DATA.includes('${')
|
||||||
|
) {
|
||||||
|
return process.env.USAGE_MONITOR_PLUGIN_DATA;
|
||||||
|
}
|
||||||
|
return join(HERE, '.data');
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DATA_DIR = resolveDefaultDataDir();
|
||||||
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
|
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
|
||||||
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
|
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
|
||||||
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
|
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
|
||||||
@@ -46,7 +69,7 @@ export const DEEP_STATS_CACHE_CANDIDATES = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(自动剥离重复协议前缀与尾部斜杠)。
|
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(支持环境变量静态注入与进程动态发现)。
|
||||||
*/
|
*/
|
||||||
const rawLsAddr = String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim();
|
const rawLsAddr = String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim();
|
||||||
const LS_PROTOCOL = /^https:\/\//i.test(rawLsAddr) ? 'https' : 'http';
|
const LS_PROTOCOL = /^https:\/\//i.test(rawLsAddr) ? 'https' : 'http';
|
||||||
@@ -54,6 +77,27 @@ export const LS_ADDR = rawLsAddr.replace(/^https?:\/\//i, '').replace(/\/+$/, ''
|
|||||||
export const LS_BASE_URL = LS_ADDR ? `${LS_PROTOCOL}://${LS_ADDR}` : '';
|
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;
|
||||||
|
|
||||||
|
export const lsRuntimeEndpoint = {
|
||||||
|
addr: LS_ADDR,
|
||||||
|
baseUrl: LS_BASE_URL,
|
||||||
|
csrfToken: CSRF_TOKEN || '',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 动态更新运行时 Language Server / Hub RPC 连接端点与 CSRF 令牌。
|
||||||
|
*
|
||||||
|
* @param {string} nextAddr
|
||||||
|
* @param {string} nextCsrfToken
|
||||||
|
*/
|
||||||
|
export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken) {
|
||||||
|
const raw = String(nextAddr || '').trim();
|
||||||
|
const proto = /^https:\/\//i.test(raw) ? 'https' : 'http';
|
||||||
|
const cleanAddr = raw.replace(/^https?:\/\//i, '').replace(/\/+$/, '');
|
||||||
|
lsRuntimeEndpoint.addr = cleanAddr;
|
||||||
|
lsRuntimeEndpoint.baseUrl = cleanAddr ? `${proto}://${cleanAddr}` : '';
|
||||||
|
lsRuntimeEndpoint.csrfToken = String(nextCsrfToken || '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GitHub 官方云端价格目录与插件发布包地址配置。
|
* GitHub 官方云端价格目录与插件发布包地址配置。
|
||||||
*/
|
*/
|
||||||
@@ -91,6 +135,38 @@ export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto
|
|||||||
|
|
||||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
||||||
|
|
||||||
|
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
||||||
|
|
||||||
|
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化面板挂载方式枚举(`'dual'` 顶部栏+侧边栏 | `'composer'` 输入框+侧边栏 | `'sidebar'` 仅侧边栏),
|
||||||
|
* 兼容历史 `enableWindowOverlay` 布尔开关,默认 `'dual'`。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @param {unknown} [legacyEnableOverlay]
|
||||||
|
* @returns {'dual'|'composer'|'sidebar'}
|
||||||
|
*/
|
||||||
|
export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
|
||||||
|
const m = String(mode ?? '').trim().toLowerCase();
|
||||||
|
if (m === 'composer' || m === 'input') return 'composer';
|
||||||
|
if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar';
|
||||||
|
if (m === 'dual' || m === 'topbar') return 'dual';
|
||||||
|
if (legacyEnableOverlay === false) return 'sidebar';
|
||||||
|
return 'dual';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @returns {'compact'|'full'}
|
||||||
|
*/
|
||||||
|
export function normalizeOrchestratorIdMode(mode) {
|
||||||
|
const m = String(mode ?? '').trim().toLowerCase();
|
||||||
|
return m === 'full' ? 'full' : 'compact';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||||
*
|
*
|
||||||
@@ -131,9 +207,11 @@ const DEFAULT_SETTINGS = {
|
|||||||
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 名称
|
||||||
|
orchestratorIdMode: 'compact', // 'compact' | 'full'(Orchestrator 系列显示精简 ID 或完整 ID)
|
||||||
pluginUpdateMode: 'manual', // 'off' | 'manual' | 'auto'(默认仅提示新版本,手动更新)
|
pluginUpdateMode: 'manual', // 'off' | 'manual' | 'auto'(默认仅提示新版本,手动更新)
|
||||||
autoUpdatePlugin: false, // 派生自 pluginUpdateMode === 'auto',保留底层兼容
|
autoUpdatePlugin: false, // 派生自 pluginUpdateMode === 'auto',保留底层兼容
|
||||||
enableWindowOverlay: true, // 是否启用双栖模式(自动通过 CDP 在主窗口顶栏挂载胶囊与悬浮面板)
|
windowMountMode: 'dual', // 'dual' | 'composer' | 'sidebar'(顶部栏 / 输入框 Auto 左侧 / 仅侧边栏)
|
||||||
|
enableWindowOverlay: true, // 派生自 windowMountMode !== 'sidebar',控制主窗口 CDP 注入启停
|
||||||
showTopbarMultiSession: true, // 是否在顶栏左侧显示实时运行会话入口
|
showTopbarMultiSession: true, // 是否在顶栏左侧显示实时运行会话入口
|
||||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], // 顶栏右侧胶囊三槽位指标与顺序
|
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], // 顶栏右侧胶囊三槽位指标与顺序
|
||||||
};
|
};
|
||||||
@@ -218,6 +296,10 @@ export function loadSettings() {
|
|||||||
safeRaw.pluginUpdateMode,
|
safeRaw.pluginUpdateMode,
|
||||||
safeRaw.autoUpdatePlugin
|
safeRaw.autoUpdatePlugin
|
||||||
);
|
);
|
||||||
|
const windowMountMode = normalizeWindowMountMode(
|
||||||
|
safeRaw.windowMountMode,
|
||||||
|
safeRaw.enableWindowOverlay
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
weeklyTokenBudget: sanitizeSettingNumber(
|
weeklyTokenBudget: sanitizeSettingNumber(
|
||||||
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit ?? merged.weeklyTokenBudget,
|
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit ?? merged.weeklyTokenBudget,
|
||||||
@@ -229,9 +311,11 @@ export function loadSettings() {
|
|||||||
),
|
),
|
||||||
weeklyLimitMode: normalizeWeeklyLimitMode(merged.weeklyLimitMode),
|
weeklyLimitMode: normalizeWeeklyLimitMode(merged.weeklyLimitMode),
|
||||||
showUpstreamModel: merged.showUpstreamModel === true,
|
showUpstreamModel: merged.showUpstreamModel === true,
|
||||||
|
orchestratorIdMode: normalizeOrchestratorIdMode(merged.orchestratorIdMode),
|
||||||
pluginUpdateMode,
|
pluginUpdateMode,
|
||||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||||
enableWindowOverlay: merged.enableWindowOverlay !== false,
|
windowMountMode,
|
||||||
|
enableWindowOverlay: windowMountMode !== 'sidebar',
|
||||||
showTopbarMultiSession: merged.showTopbarMultiSession !== false,
|
showTopbarMultiSession: merged.showTopbarMultiSession !== false,
|
||||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
||||||
};
|
};
|
||||||
@@ -258,7 +342,10 @@ export function computeRuntimeCodeVersion() {
|
|||||||
join(HERE, 'app.js'),
|
join(HERE, 'app.js'),
|
||||||
join(HERE, 'styles.css'),
|
join(HERE, 'styles.css'),
|
||||||
join(HERE, 'main.mjs'),
|
join(HERE, 'main.mjs'),
|
||||||
|
join(HERE, 'bridge-daemon.mjs'),
|
||||||
|
join(HERE, 'mcp-entry.mjs'),
|
||||||
join(HERE, 'speed-metrics.mjs'),
|
join(HERE, 'speed-metrics.mjs'),
|
||||||
|
LOCAL_CATALOG_FILE,
|
||||||
];
|
];
|
||||||
const backendDir = join(HERE, 'backend');
|
const backendDir = join(HERE, 'backend');
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import {
|
|||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
import { callLsRpc } from './ls-rpc.mjs';
|
import { callLsRpc } from './ls-rpc.mjs';
|
||||||
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
||||||
|
import { PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 扫描本地 `conversations` 目录,返回 `cascadeId -> 最新磁盘修改时间 (mtimeMs)` 映射表。
|
* 扫描本地 `conversations` 目录,返回 `cascadeId -> 最新磁盘修改时间 (mtimeMs)` 映射表。
|
||||||
@@ -99,9 +100,23 @@ export function loadExternalDeepStatsCache() {
|
|||||||
|
|
||||||
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 || []) {
|
||||||
|
const intrinsicDisplay =
|
||||||
|
PLACEHOLDER_MAP[e?.modelRuntimeId]?.label ||
|
||||||
|
formatGenericModelSlug(e?.modelCanonicalId || e?.model);
|
||||||
|
const isSessionDisplayAgg = /^session-display:/i.test(String(e?.modelAggregationId || ''));
|
||||||
|
const usableDisplayHint =
|
||||||
|
e?.modelDisplayName &&
|
||||||
|
!(
|
||||||
|
isSessionDisplayAgg &&
|
||||||
|
intrinsicDisplay &&
|
||||||
|
getBaseModelLabel(e.modelDisplayName) !== getBaseModelLabel(intrinsicDisplay)
|
||||||
|
)
|
||||||
|
? e.modelDisplayName
|
||||||
|
: '';
|
||||||
const display =
|
const display =
|
||||||
e?.modelDisplayName ||
|
usableDisplayHint ||
|
||||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId);
|
intrinsicDisplay ||
|
||||||
|
formatGenericModelSlug(e?.modelAggregationId);
|
||||||
if (!display) continue;
|
if (!display) continue;
|
||||||
const base = getBaseModelLabel(display);
|
const base = getBaseModelLabel(display);
|
||||||
if (e?.modelRuntimeId && !runtimeDisplayMap.has(e.modelRuntimeId)) {
|
if (e?.modelRuntimeId && !runtimeDisplayMap.has(e.modelRuntimeId)) {
|
||||||
@@ -140,18 +155,41 @@ export function loadExternalDeepStatsCache() {
|
|||||||
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;
|
||||||
if (createdAtMs > lastModifiedMs) lastModifiedMs = createdAtMs;
|
if (createdAtMs > lastModifiedMs) lastModifiedMs = createdAtMs;
|
||||||
|
const stepIntrinsicLabel =
|
||||||
|
PLACEHOLDER_MAP[e?.modelRuntimeId]?.label ||
|
||||||
|
formatGenericModelSlug(e?.modelCanonicalId || e?.model);
|
||||||
|
const isSessionDisplayAgg = /^session-display:/i.test(String(e?.modelAggregationId || ''));
|
||||||
|
const safeStepDisplayName =
|
||||||
|
e?.modelDisplayName &&
|
||||||
|
!(
|
||||||
|
isSessionDisplayAgg &&
|
||||||
|
stepIntrinsicLabel &&
|
||||||
|
getBaseModelLabel(e.modelDisplayName) !== getBaseModelLabel(stepIntrinsicLabel)
|
||||||
|
)
|
||||||
|
? e.modelDisplayName
|
||||||
|
: '';
|
||||||
const resolvedDisplay =
|
const resolvedDisplay =
|
||||||
e?.modelDisplayName ||
|
safeStepDisplayName ||
|
||||||
|
stepIntrinsicLabel ||
|
||||||
runtimeDisplayMap.get(e?.model) ||
|
runtimeDisplayMap.get(e?.model) ||
|
||||||
runtimeDisplayMap.get(e?.modelRuntimeId) ||
|
runtimeDisplayMap.get(e?.modelRuntimeId) ||
|
||||||
formatGenericModelSlug(e?.modelCanonicalId || e?.model || e?.modelAggregationId) ||
|
formatGenericModelSlug(e?.modelAggregationId) ||
|
||||||
'';
|
'';
|
||||||
|
const rawUpstreamCandidate = String(e?.model || e?.modelCanonicalId || '').trim();
|
||||||
|
const inferredResponseModel =
|
||||||
|
/^session:/i.test(String(e?.modelAggregationId || '')) &&
|
||||||
|
rawUpstreamCandidate &&
|
||||||
|
!/^MODEL_/i.test(rawUpstreamCandidate) &&
|
||||||
|
!/\s/.test(rawUpstreamCandidate)
|
||||||
|
? rawUpstreamCandidate
|
||||||
|
: '';
|
||||||
steps.push({
|
steps.push({
|
||||||
stepIndex: idx + 1,
|
stepIndex: idx + 1,
|
||||||
createdAt: e?.ts || '',
|
createdAt: e?.ts || '',
|
||||||
createdAtMs,
|
createdAtMs,
|
||||||
modelKey: e?.modelCanonicalId || e?.model || e?.modelRuntimeId || 'unknown',
|
modelKey: e?.modelCanonicalId || e?.model || e?.modelRuntimeId || 'unknown',
|
||||||
modelDisplayName: resolvedDisplay,
|
modelDisplayName: resolvedDisplay,
|
||||||
|
...(inferredResponseModel ? { responseModel: inferredResponseModel } : {}),
|
||||||
apiProvider: e?.provider || '',
|
apiProvider: e?.provider || '',
|
||||||
appSource,
|
appSource,
|
||||||
inputTokens,
|
inputTokens,
|
||||||
|
|||||||
@@ -0,0 +1,342 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Antigravity Hub / Language Server 本地进程自动发现器。
|
||||||
|
*
|
||||||
|
* 当插件通过 `mcp_config.json` 在 Antigravity IDE 中以后台守护方式启动时,
|
||||||
|
* 宿主可能未在环境变量中直接注入 `ANTIGRAVITY_LS_ADDRESS` 与 `ANTIGRAVITY_CSRF_TOKEN`。
|
||||||
|
* 本模块跨平台(Windows / macOS / Linux)枚举当前用户的 `agy --hub` 或 `language_server` 进程,
|
||||||
|
* 优先匹配父进程 `process.ppid`,并经 `GetUserStatus` 实测握手验证后写入 `lsRuntimeEndpoint`。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||||
|
import { lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs';
|
||||||
|
|
||||||
|
const LS_DISC_COOLDOWN_MS = 4000;
|
||||||
|
|
||||||
|
const lsDiscoveryState = {
|
||||||
|
inFlight: null,
|
||||||
|
lastAttemptMs: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 `agy --hub` 或 `language_server` 命令行字符串中提取端口号与 CSRF 令牌。
|
||||||
|
*
|
||||||
|
* @param {string} commandLine
|
||||||
|
* @returns {{ hubPort: number|null, csrfToken: string, isHub: boolean, isLanguageServer: boolean }}
|
||||||
|
*/
|
||||||
|
export function parseLsArgsFromCommandLine(commandLine) {
|
||||||
|
const cmd = String(commandLine || '').trim();
|
||||||
|
if (!cmd) {
|
||||||
|
return { hubPort: null, csrfToken: '', isHub: false, isLanguageServer: false };
|
||||||
|
}
|
||||||
|
const isHub = /(?:^|[\s/\\"'])agy(?:\.exe)?(?:["'\s]|$)/i.test(cmd) && /--hub\b/i.test(cmd);
|
||||||
|
const isLanguageServer = /language_server/i.test(cmd);
|
||||||
|
|
||||||
|
let hubPort = null;
|
||||||
|
const portMatch = cmd.match(/--hub[-_]port(?:=|\s+)["']?(\d{1,5})["']?(?=\s|$)/i);
|
||||||
|
if (portMatch) {
|
||||||
|
const num = Number(portMatch[1]);
|
||||||
|
if (Number.isInteger(num) && num > 0 && num <= 65535) {
|
||||||
|
hubPort = num;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let csrfToken = '';
|
||||||
|
const csrfMatch = cmd.match(/--csrf[-_]token(?:=|\s+)(?:"([^"]+)"|'([^']+)'|([^\s"']+))/i);
|
||||||
|
if (csrfMatch) {
|
||||||
|
csrfToken = String(csrfMatch[1] || csrfMatch[2] || csrfMatch[3] || '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
hubPort,
|
||||||
|
csrfToken,
|
||||||
|
isHub,
|
||||||
|
isLanguageServer,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function execLsDiscoveryCmd(file, args, timeoutMs = 5000) {
|
||||||
|
const cpMod = await import('node:child_process');
|
||||||
|
const execFileFn = cpMod.execFile || cpMod.default?.execFile;
|
||||||
|
if (typeof execFileFn !== 'function') {
|
||||||
|
throw new Error('child_process.execFile unavailable');
|
||||||
|
}
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
execFileFn(
|
||||||
|
file,
|
||||||
|
args,
|
||||||
|
{ windowsHide: true, timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024 },
|
||||||
|
(err, stdout) => {
|
||||||
|
if (err) {
|
||||||
|
reject(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resolve(String(stdout || ''));
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function readLinuxProcCandidates() {
|
||||||
|
if (!existsSync('/proc')) return [];
|
||||||
|
const results = [];
|
||||||
|
try {
|
||||||
|
for (const entry of readdirSync('/proc')) {
|
||||||
|
if (!/^\d+$/.test(entry)) continue;
|
||||||
|
const pid = Number(entry);
|
||||||
|
try {
|
||||||
|
const rawCmd = readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
||||||
|
if (!rawCmd) continue;
|
||||||
|
const commandLine = rawCmd.replace(/\0+/g, ' ').trim();
|
||||||
|
if (!/agy|language_server/i.test(commandLine)) continue;
|
||||||
|
let ppid = 0;
|
||||||
|
try {
|
||||||
|
const statRaw = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||||
|
const afterComm = statRaw.slice(statRaw.lastIndexOf(')') + 1).trim();
|
||||||
|
const parts = afterComm.split(/\s+/);
|
||||||
|
ppid = Number(parts[1]) || 0;
|
||||||
|
} catch {
|
||||||
|
// 忽略单进程 stat 读取失败
|
||||||
|
}
|
||||||
|
results.push({ pid, ppid, commandLine });
|
||||||
|
} catch {
|
||||||
|
// 忽略退出中的瞬态进程
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listCandidateOsProcesses(platform, execCmdFn) {
|
||||||
|
if (platform === 'win32') {
|
||||||
|
const psScript =
|
||||||
|
"Get-CimInstance Win32_Process -Filter \"Name LIKE 'agy%' OR Name LIKE 'language_server%'\" | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress";
|
||||||
|
const out = await execCmdFn('powershell.exe', [
|
||||||
|
'-NoProfile',
|
||||||
|
'-NonInteractive',
|
||||||
|
'-Command',
|
||||||
|
psScript,
|
||||||
|
]);
|
||||||
|
const trimmed = out.trim();
|
||||||
|
if (!trimmed) return [];
|
||||||
|
const parsed = JSON.parse(trimmed);
|
||||||
|
const items = Array.isArray(parsed) ? parsed : [parsed];
|
||||||
|
return items
|
||||||
|
.filter((it) => it && typeof it === 'object')
|
||||||
|
.map((it) => ({
|
||||||
|
pid: Number(it.ProcessId) || 0,
|
||||||
|
ppid: Number(it.ParentProcessId) || 0,
|
||||||
|
commandLine: String(it.CommandLine || ''),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platform === 'linux') {
|
||||||
|
const procList = readLinuxProcCandidates();
|
||||||
|
if (procList.length > 0) return procList;
|
||||||
|
}
|
||||||
|
|
||||||
|
const psArgs =
|
||||||
|
platform === 'darwin' ? ['-ax', '-o', 'pid=,ppid=,command='] : ['-ax', '-o', 'pid=,ppid=,args='];
|
||||||
|
const out = await execCmdFn('ps', psArgs);
|
||||||
|
const results = [];
|
||||||
|
for (const line of out.split(/\r?\n/)) {
|
||||||
|
const m = line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/);
|
||||||
|
if (!m) continue;
|
||||||
|
const cmdLine = m[3];
|
||||||
|
if (!/agy|language_server/i.test(cmdLine)) continue;
|
||||||
|
results.push({
|
||||||
|
pid: Number(m[1]) || 0,
|
||||||
|
ppid: Number(m[2]) || 0,
|
||||||
|
commandLine: cmdLine,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findListeningPortsForPid(pid, platform, execCmdFn) {
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) return [];
|
||||||
|
try {
|
||||||
|
if (platform === 'win32') {
|
||||||
|
const out = await execCmdFn('powershell.exe', [
|
||||||
|
'-NoProfile',
|
||||||
|
'-NonInteractive',
|
||||||
|
'-Command',
|
||||||
|
`Get-NetTCPConnection -OwningProcess ${pid} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty LocalPort | ConvertTo-Json -Compress`,
|
||||||
|
]);
|
||||||
|
const trimmed = out.trim();
|
||||||
|
if (!trimmed) return [];
|
||||||
|
const parsed = JSON.parse(trimmed);
|
||||||
|
const rawPorts = Array.isArray(parsed) ? parsed : [parsed];
|
||||||
|
return Array.from(
|
||||||
|
new Set(
|
||||||
|
rawPorts
|
||||||
|
.map(Number)
|
||||||
|
.filter((p) => Number.isInteger(p) && p > 0 && p <= 65535)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const out = await execCmdFn('lsof', ['-Pan', '-p', String(pid), '-iTCP', '-sTCP:LISTEN']);
|
||||||
|
const ports = new Set();
|
||||||
|
for (const line of out.split(/\r?\n/)) {
|
||||||
|
const m = line.match(/:(\d{1,5})\s+\(LISTEN\)/i);
|
||||||
|
if (m) {
|
||||||
|
const p = Number(m[1]);
|
||||||
|
if (p > 0 && p <= 65535) ports.add(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(ports);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function probeLsCandidate(port, csrfToken, fetchFn) {
|
||||||
|
for (const proto of ['http', 'https']) {
|
||||||
|
try {
|
||||||
|
const addr = `127.0.0.1:${port}`;
|
||||||
|
const baseUrl = `${proto}://${addr}`;
|
||||||
|
const res = await fetchFn(
|
||||||
|
`${baseUrl}/exa.language_server_pb.LanguageServerService/GetUserStatus`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'x-codeium-csrf-token': csrfToken,
|
||||||
|
},
|
||||||
|
body: '{}',
|
||||||
|
signal: AbortSignal.timeout(1500),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (res?.ok) {
|
||||||
|
return { addr: proto === 'https' ? `https://${addr}` : addr, baseUrl, csrfToken };
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 继续尝试下一候选协议或端口
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动探测并握手验证本机正在运行的 Antigravity Hub / Language Server RPC 端点。
|
||||||
|
*
|
||||||
|
* @param {{
|
||||||
|
* ppid?: number,
|
||||||
|
* ancestorPids?: number[],
|
||||||
|
* platform?: string,
|
||||||
|
* execCmdFn?: (file: string, args: string[]) => Promise<string>,
|
||||||
|
* fetchFn?: typeof fetch
|
||||||
|
* }} [options]
|
||||||
|
* @returns {Promise<{ addr: string, baseUrl: string, csrfToken: string, pid: number } | null>}
|
||||||
|
*/
|
||||||
|
export async function discoverAntigravityLsEndpoint(options = {}) {
|
||||||
|
const {
|
||||||
|
ppid = Number(process?.ppid || 0),
|
||||||
|
ancestorPids = [],
|
||||||
|
platform = process?.platform || 'win32',
|
||||||
|
execCmdFn = execLsDiscoveryCmd,
|
||||||
|
fetchFn = typeof fetch === 'function' ? fetch : null,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
if (typeof fetchFn !== 'function') return null;
|
||||||
|
|
||||||
|
const preferredPids = new Set(
|
||||||
|
[ppid, ...(Array.isArray(ancestorPids) ? ancestorPids : [])]
|
||||||
|
.map(Number)
|
||||||
|
.filter((n) => Number.isInteger(n) && n > 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
let rawProcs = [];
|
||||||
|
try {
|
||||||
|
rawProcs = await listCandidateOsProcesses(platform, execCmdFn);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!rawProcs.length) return null;
|
||||||
|
|
||||||
|
const parsedCandidates = [];
|
||||||
|
for (const proc of rawProcs) {
|
||||||
|
const info = parseLsArgsFromCommandLine(proc.commandLine);
|
||||||
|
if (!info.csrfToken || (!info.isHub && !info.isLanguageServer)) continue;
|
||||||
|
let priority = 50;
|
||||||
|
if (preferredPids.has(proc.pid)) {
|
||||||
|
priority = 100;
|
||||||
|
} else if (preferredPids.has(proc.ppid)) {
|
||||||
|
priority = 90;
|
||||||
|
} else if (info.isHub && info.hubPort) {
|
||||||
|
priority = 80;
|
||||||
|
}
|
||||||
|
parsedCandidates.push({
|
||||||
|
pid: proc.pid,
|
||||||
|
priority,
|
||||||
|
hubPort: info.hubPort,
|
||||||
|
csrfToken: info.csrfToken,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedCandidates.sort((a, b) => b.priority - a.priority || b.pid - a.pid);
|
||||||
|
|
||||||
|
for (const cand of parsedCandidates) {
|
||||||
|
const ports = cand.hubPort
|
||||||
|
? [cand.hubPort]
|
||||||
|
: await findListeningPortsForPid(cand.pid, platform, execCmdFn);
|
||||||
|
for (const port of ports) {
|
||||||
|
const verified = await probeLsCandidate(port, cand.csrfToken, fetchFn);
|
||||||
|
if (verified) {
|
||||||
|
return { ...verified, pid: cand.pid };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 确保 `lsRuntimeEndpoint` 已就绪(具备并发去重与失败冷却保护)。
|
||||||
|
*
|
||||||
|
* @param {{ force?: boolean, ancestorPids?: number[] }} [options]
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
export async function ensureLsEndpointDiscovered({ force = false, ancestorPids = [] } = {}) {
|
||||||
|
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!force && lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.csrfToken) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (lsDiscoveryState.inFlight) {
|
||||||
|
return lsDiscoveryState.inFlight;
|
||||||
|
}
|
||||||
|
const now = Date.now();
|
||||||
|
if (
|
||||||
|
!force &&
|
||||||
|
lsDiscoveryState.lastAttemptMs > 0 &&
|
||||||
|
now - lsDiscoveryState.lastAttemptMs < LS_DISC_COOLDOWN_MS
|
||||||
|
) {
|
||||||
|
return Boolean(lsRuntimeEndpoint.baseUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
const envHintPids = String(process?.env?.USAGE_MONITOR_HOST_PPID || '')
|
||||||
|
.split(',')
|
||||||
|
.map((s) => Number(s.trim()))
|
||||||
|
.filter((n) => Number.isInteger(n) && n > 0);
|
||||||
|
|
||||||
|
lsDiscoveryState.lastAttemptMs = now;
|
||||||
|
lsDiscoveryState.inFlight = (async () => {
|
||||||
|
try {
|
||||||
|
const found = await discoverAntigravityLsEndpoint({
|
||||||
|
ancestorPids: [...envHintPids, ...ancestorPids],
|
||||||
|
});
|
||||||
|
if (found && found.addr && found.csrfToken) {
|
||||||
|
setLsRuntimeEndpoint(found.addr, found.csrfToken);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return Boolean(lsRuntimeEndpoint.baseUrl);
|
||||||
|
} finally {
|
||||||
|
lsDiscoveryState.inFlight = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return lsDiscoveryState.inFlight;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -7,13 +7,26 @@
|
|||||||
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。
|
* 并在缓存过期或强制刷新时穿透 `language_server.exe` 内部 3 分钟陈旧缓存)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CSRF_TOKEN, LS_BASE_URL, quotaSummaryCache } from './config.mjs';
|
import { lsRuntimeEndpoint, quotaSummaryCache } from './config.mjs';
|
||||||
|
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||||
|
|
||||||
const QUOTA_CACHE_TTL_MS = 10_000;
|
const QUOTA_CACHE_TTL_MS = 10_000;
|
||||||
const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
||||||
|
|
||||||
|
async function postLsRpcOnce(baseUrl, csrfToken, method, body, timeoutMs) {
|
||||||
|
return fetch(`${baseUrl}/exa.language_server_pb.LanguageServerService/${method}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'x-codeium-csrf-token': csrfToken || '',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 调用本地 `LanguageServerService` 的指定 RPC 方法。
|
* 调用本地 `LanguageServerService` 的指定 RPC 方法(支持按需发现与宿主重启重连)。
|
||||||
*
|
*
|
||||||
* @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`)
|
* @param {string} method RPC 方法名(如 `'GetUserStatus'`、`'GetCascadeTrajectory'`)
|
||||||
* @param {object} [body={}] 请求 JSON 载荷
|
* @param {object} [body={}] 请求 JSON 载荷
|
||||||
@@ -21,21 +34,62 @@ const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
|||||||
* @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) {
|
if (!lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||||
|
await ensureLsEndpointDiscovered({ force: false });
|
||||||
|
}
|
||||||
|
if (!lsRuntimeEndpoint.baseUrl) {
|
||||||
throw new Error('Language Server address (ANTIGRAVITY_LS_ADDRESS) is not configured');
|
throw new Error('Language Server address (ANTIGRAVITY_LS_ADDRESS) is not configured');
|
||||||
}
|
}
|
||||||
const res = await fetch(
|
|
||||||
`${LS_BASE_URL}/exa.language_server_pb.LanguageServerService/${method}`,
|
const prevAddr = lsRuntimeEndpoint.addr;
|
||||||
{
|
const prevToken = lsRuntimeEndpoint.csrfToken;
|
||||||
method: 'POST',
|
let res;
|
||||||
headers: {
|
try {
|
||||||
'Content-Type': 'application/json',
|
res = await postLsRpcOnce(
|
||||||
'x-codeium-csrf-token': CSRF_TOKEN || '',
|
lsRuntimeEndpoint.baseUrl,
|
||||||
},
|
lsRuntimeEndpoint.csrfToken,
|
||||||
body: JSON.stringify(body),
|
method,
|
||||||
signal: AbortSignal.timeout(timeoutMs),
|
body,
|
||||||
}
|
timeoutMs
|
||||||
);
|
);
|
||||||
|
} catch (netErr) {
|
||||||
|
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||||
|
const refreshed = await ensureLsEndpointDiscovered({ force: true });
|
||||||
|
if (
|
||||||
|
refreshed &&
|
||||||
|
(lsRuntimeEndpoint.addr !== prevAddr || lsRuntimeEndpoint.csrfToken !== prevToken)
|
||||||
|
) {
|
||||||
|
res = await postLsRpcOnce(
|
||||||
|
lsRuntimeEndpoint.baseUrl,
|
||||||
|
lsRuntimeEndpoint.csrfToken,
|
||||||
|
method,
|
||||||
|
body,
|
||||||
|
timeoutMs
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
throw netErr;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw netErr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok && (res.status === 401 || res.status === 403) && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||||
|
const refreshed = await ensureLsEndpointDiscovered({ force: true });
|
||||||
|
if (
|
||||||
|
refreshed &&
|
||||||
|
(lsRuntimeEndpoint.addr !== prevAddr || lsRuntimeEndpoint.csrfToken !== prevToken)
|
||||||
|
) {
|
||||||
|
res = await postLsRpcOnce(
|
||||||
|
lsRuntimeEndpoint.baseUrl,
|
||||||
|
lsRuntimeEndpoint.csrfToken,
|
||||||
|
method,
|
||||||
|
body,
|
||||||
|
timeoutMs
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => '');
|
const text = await res.text().catch(() => '');
|
||||||
throw new Error(`RPC ${method} failed (${res.status}): ${text}`);
|
throw new Error(`RPC ${method} failed (${res.status}): ${text}`);
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide
|
|||||||
combined.includes('CARBON') ||
|
combined.includes('CARBON') ||
|
||||||
combined.includes('ARGON') ||
|
combined.includes('ARGON') ||
|
||||||
combined.includes('HYDROGEN') ||
|
combined.includes('HYDROGEN') ||
|
||||||
|
combined.includes('ORCHESTRATOR') ||
|
||||||
combined.includes('HELIX') ||
|
combined.includes('HELIX') ||
|
||||||
combined.includes('FLASH') ||
|
combined.includes('FLASH') ||
|
||||||
combined.includes('GOOGLE')
|
combined.includes('GOOGLE')
|
||||||
@@ -59,29 +60,42 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 枚举)。
|
* 判断一组模型标识字段是否指向 Gemini 4 Argon 系列模型(含 M417/M418/M419 及 M681 Orchestrator (Argon))。
|
||||||
*
|
*
|
||||||
* @param {...string} parts 待检测的标识片段
|
* @param {...string} parts 待检测的标识片段
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function isArgonModelIdentifier(...parts) {
|
export function isArgonModelIdentifier(...parts) {
|
||||||
return /argon|MODEL_PLACEHOLDER_M41[789]\b/i.test(parts.filter(Boolean).join(' '));
|
const text = parts.filter(Boolean).join(' ');
|
||||||
|
if (
|
||||||
|
/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text) &&
|
||||||
|
!/\bargon\b|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return /argon|MODEL_PLACEHOLDER_M(?:41[789]|681)\b/i.test(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M429 枚举)。
|
* 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型(含 M427/M429/M437/M438 及 M667 Orchestrator (Carbon))。
|
||||||
*
|
*
|
||||||
* @param {...string} parts 待检测的标识片段
|
* @param {...string} parts 待检测的标识片段
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export function isCarbonModelIdentifier(...parts) {
|
export function isCarbonModelIdentifier(...parts) {
|
||||||
return /\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M429\b/i.test(
|
const text = parts.filter(Boolean).join(' ');
|
||||||
parts.filter(Boolean).join(' ')
|
if (/\bcarbon\b|gemini-4-carbon|MODEL_PLACEHOLDER_M(?:42[79]|43[78]|667)\b/i.test(text)) {
|
||||||
);
|
return true;
|
||||||
|
}
|
||||||
|
if (/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(text)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return /\bgemini-pro-orchestrator\b(?!-argon)/i.test(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 剥离模型展示名称末尾的思考档位后缀(如 `(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。
|
* 剥离模型展示名称末尾的思考档位后缀(如 `(XHigh)`、`(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。
|
||||||
|
* 保留 `(Carbon)` / `(Argon)` 后缀,以便 `Orchestrator (Carbon)` 与 `Orchestrator (Argon)` 在汇总表中保持分列。
|
||||||
*
|
*
|
||||||
* @param {string} [label='']
|
* @param {string} [label='']
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
@@ -89,13 +103,23 @@ export function isCarbonModelIdentifier(...parts) {
|
|||||||
export function getBaseModelLabel(label = '') {
|
export function getBaseModelLabel(label = '') {
|
||||||
return (
|
return (
|
||||||
String(label || '')
|
String(label || '')
|
||||||
.replace(/\s*\((?:Max|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
|
.replace(/\bFlash-Lite\b/gi, 'Flash Lite')
|
||||||
|
.replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered|Preview)\)\s*$/i, '')
|
||||||
.trim() || String(label || 'Unknown Model')
|
.trim() || String(label || 'Unknown Model')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SLUG_TIER_LABELS = {
|
||||||
|
xhigh: 'XHigh',
|
||||||
|
high: 'High',
|
||||||
|
medium: 'Medium',
|
||||||
|
low: 'Low',
|
||||||
|
'extra-low': 'Extra Low',
|
||||||
|
tiered: 'Tiered',
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将严格匹配的 `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` 或已知内部路由别名转为人类可读标签。
|
||||||
* 使用行尾锚点 `$` 防止未收录新后缀(如 `gemini-3.1-pro-ultra-v2`)被静默截断伪装成旧模型获取错误定价。
|
* 使用行尾锚点 `$` 防止未收录新后缀(如 `gemini-3.1-pro-ultra-v2`)被静默截断伪装成旧模型获取错误定价。
|
||||||
*
|
*
|
||||||
* @param {string} [slug='']
|
* @param {string} [slug='']
|
||||||
@@ -106,14 +130,22 @@ 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 '';
|
||||||
|
if (/^gemini-4-argon-(?:f|disabled)$/i.test(s)) return 'Gemini 4 Argon';
|
||||||
|
if (/^gemini-3\.8-flash-n$/i.test(s)) return 'Gemini 3.8 Flash';
|
||||||
|
if (/^gemini-3\.7-flash-safety-le$/i.test(s)) return 'Gemini 3.7 Flash';
|
||||||
|
if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash';
|
||||||
|
if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash';
|
||||||
|
if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro';
|
||||||
const m = s.match(
|
const m = s.match(
|
||||||
/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|hydrogen|helix)(?:-(lite))?$/i
|
/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/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();
|
||||||
const lite = m[3] ? ' Lite' : '';
|
const lite = m[3] ? ' Lite' : '';
|
||||||
return `Gemini ${ver} ${tier}${lite}`;
|
const suffixKey = m[4] ? m[4].toLowerCase() : '';
|
||||||
|
const tierSuffix = SLUG_TIER_LABELS[suffixKey] ? ` (${SLUG_TIER_LABELS[suffixKey]})` : '';
|
||||||
|
return `Gemini ${ver} ${tier}${lite}${tierSuffix}`;
|
||||||
}
|
}
|
||||||
const codenameMatch = s.match(/^gemini-(hydrogen|helix)$/i);
|
const codenameMatch = s.match(/^gemini-(hydrogen|helix)$/i);
|
||||||
if (codenameMatch) {
|
if (codenameMatch) {
|
||||||
@@ -121,6 +153,9 @@ export function formatGenericModelSlug(slug = '') {
|
|||||||
codenameMatch[1].charAt(0).toUpperCase() + codenameMatch[1].slice(1).toLowerCase();
|
codenameMatch[1].charAt(0).toUpperCase() + codenameMatch[1].slice(1).toLowerCase();
|
||||||
return `Gemini ${codename}`;
|
return `Gemini ${codename}`;
|
||||||
}
|
}
|
||||||
|
if (/^gemini-flash-worker-agy$/i.test(s)) {
|
||||||
|
return 'Orchestrator Worker (Hydrogen)';
|
||||||
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,8 +191,24 @@ export function resolveModelInfo(
|
|||||||
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 isWorkerSlot =
|
||||||
|
rawModelKey === 'MODEL_PLACEHOLDER_M669' ||
|
||||||
|
/^gemini-flash-worker-agy$/i.test(cleanResponseModel);
|
||||||
|
const isVagueGenericDisplay = Boolean(
|
||||||
|
modelDisplayName &&
|
||||||
|
(/^gemini\s+(?:flash|pro)(?:\s+worker)?$/i.test(modelDisplayName.trim()) ||
|
||||||
|
(isWorkerSlot && /^gemini\s+4\s+hydrogen$/i.test(modelDisplayName.trim())))
|
||||||
|
);
|
||||||
|
const effectiveDisplayName =
|
||||||
|
modelDisplayName &&
|
||||||
|
((mergedLabel &&
|
||||||
|
(/\borchestrator\b/i.test(modelDisplayName) || isVagueGenericDisplay) &&
|
||||||
|
!/\borchestrator\b/i.test(mergedLabel)) ||
|
||||||
|
(isVagueGenericDisplay && /^gemini-flash-worker-agy$/i.test(cleanResponseModel)))
|
||||||
|
? ''
|
||||||
|
: modelDisplayName;
|
||||||
const derivedDisplay =
|
const derivedDisplay =
|
||||||
modelDisplayName ||
|
effectiveDisplayName ||
|
||||||
mergedLabel ||
|
mergedLabel ||
|
||||||
formatGenericModelSlug(rawModelKey) ||
|
formatGenericModelSlug(rawModelKey) ||
|
||||||
formatGenericModelSlug(cleanResponseModel) ||
|
formatGenericModelSlug(cleanResponseModel) ||
|
||||||
@@ -181,14 +232,22 @@ export function resolveModelInfo(
|
|||||||
(rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel) ||
|
(rawModelKey && rawModelKey !== 'unknown' ? rawModelKey : cleanResponseModel) ||
|
||||||
'unknown';
|
'unknown';
|
||||||
|
|
||||||
|
const isOpaqueOrchestratorResp = Boolean(
|
||||||
|
cleanResponseModel && /\borchestrator\b/i.test(cleanResponseModel)
|
||||||
|
);
|
||||||
const explicitPricing =
|
const explicitPricing =
|
||||||
MODEL_PRICING[modelId] ||
|
MODEL_PRICING[modelId] ||
|
||||||
MODEL_PRICING[rawModelKey] ||
|
MODEL_PRICING[rawModelKey] ||
|
||||||
(cleanResponseModel ? MODEL_PRICING[cleanResponseModel] : null) ||
|
(cleanResponseModel && !isOpaqueOrchestratorResp
|
||||||
|
? MODEL_PRICING[cleanResponseModel]
|
||||||
|
: null) ||
|
||||||
MODEL_PRICING[tieredSlug] ||
|
MODEL_PRICING[tieredSlug] ||
|
||||||
MODEL_PRICING[tieredDashedSlug] ||
|
MODEL_PRICING[tieredDashedSlug] ||
|
||||||
MODEL_PRICING[canonicalSlug] ||
|
MODEL_PRICING[canonicalSlug] ||
|
||||||
MODEL_PRICING[dashedSlug];
|
MODEL_PRICING[dashedSlug] ||
|
||||||
|
(cleanResponseModel && isOpaqueOrchestratorResp
|
||||||
|
? MODEL_PRICING[cleanResponseModel]
|
||||||
|
: null);
|
||||||
|
|
||||||
if (explicitPricing) {
|
if (explicitPricing) {
|
||||||
return {
|
return {
|
||||||
@@ -216,6 +275,36 @@ export function resolveModelInfo(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为不透明的 Orchestrator 路由模型 ID 补充底层实际模型代号标注(如 `gemini-pro-orchestrator (carbon-4)`),
|
||||||
|
* 普通透明上游模型 ID(如 `gemini-3.8-flash-n`、`gemini-4-hydrogen`)原样返回。
|
||||||
|
*
|
||||||
|
* @param {string} [rawUpstream='']
|
||||||
|
* @param {ReturnType<typeof resolveModelInfo>|null} [mInfo=null]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function formatUpstreamModelId(rawUpstream = '', mInfo = null) {
|
||||||
|
const s = String(rawUpstream || '').trim();
|
||||||
|
if (!s || !/(?:orchestrator|-worker-agy\b)/i.test(s) || /\([^)]+\)\s*$/.test(s)) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
const metaText = `${mInfo?.rawModel || ''} ${mInfo?.modelId || ''} ${mInfo?.shortName || ''} ${mInfo?.label || ''} ${s}`;
|
||||||
|
if (
|
||||||
|
/\bhydrogen\b|\bgemini-flash-worker-agy\b|MODEL_PLACEHOLDER_M(?:669|52[5678])\b/i.test(
|
||||||
|
metaText
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return `${s} (hydrogen-4)`;
|
||||||
|
}
|
||||||
|
if (isArgonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) {
|
||||||
|
return `${s} (argon-4)`;
|
||||||
|
}
|
||||||
|
if (isCarbonModelIdentifier(mInfo?.rawModel, mInfo?.modelId, mInfo?.label, s)) {
|
||||||
|
return `${s} (carbon-4)`;
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 计算单个步骤的 API 等效美元成本;若模型未定价(`pricing === null`)则返回 `null`。
|
* 计算单个步骤的 API 等效美元成本;若模型未定价(`pricing === null`)则返回 `null`。
|
||||||
* 对负数、NaN 或非有限数值统一安全钳制为 0。
|
* 对负数、NaN 或非有限数值统一安全钳制为 0。
|
||||||
|
|||||||
@@ -26,12 +26,12 @@ import {
|
|||||||
DATA_DIR,
|
DATA_DIR,
|
||||||
DEFAULT_ARCHIVE_FALLBACK_URL,
|
DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||||
DEFAULT_DOWNLOAD_URL,
|
DEFAULT_DOWNLOAD_URL,
|
||||||
LS_ADDR,
|
|
||||||
PLUGIN_ROOT,
|
PLUGIN_ROOT,
|
||||||
REMOTE_CATALOG_CACHE_FILE,
|
REMOTE_CATALOG_CACHE_FILE,
|
||||||
cloudSyncState,
|
cloudSyncState,
|
||||||
loadJson,
|
loadJson,
|
||||||
loadSettings,
|
loadSettings,
|
||||||
|
lsRuntimeEndpoint,
|
||||||
pluginUpdateState,
|
pluginUpdateState,
|
||||||
saveJson,
|
saveJson,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
@@ -76,7 +76,13 @@ function runExecFile(cmd, args, opts = {}) {
|
|||||||
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
||||||
*/
|
*/
|
||||||
export function scheduleSidecarRestart(delayMs = 350) {
|
export function scheduleSidecarRestart(delayMs = 350) {
|
||||||
if (!LS_ADDR || LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return;
|
if (
|
||||||
|
!lsRuntimeEndpoint.addr ||
|
||||||
|
lsRuntimeEndpoint.addr === 'test.invalid' ||
|
||||||
|
typeof process?.exit !== 'function'
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
try {
|
try {
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
@@ -164,10 +170,12 @@ function pruneExtraneousFiles(targetDir, referenceDir) {
|
|||||||
* @param {string} rootDir 插件根目录或解压目录
|
* @param {string} rootDir 插件根目录或解压目录
|
||||||
*/
|
*/
|
||||||
async function verifyPluginJsSyntax(rootDir) {
|
async function verifyPluginJsSyntax(rootDir) {
|
||||||
if (!LS_ADDR || LS_ADDR === 'test.invalid') return;
|
if (!lsRuntimeEndpoint.addr || lsRuntimeEndpoint.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'),
|
||||||
|
join(rootDir, 'sidecars', 'panel', 'bridge-daemon.mjs'),
|
||||||
|
join(rootDir, 'sidecars', 'panel', 'mcp-entry.mjs'),
|
||||||
join(rootDir, 'sidecars', 'panel', 'app.js'),
|
join(rootDir, 'sidecars', 'panel', 'app.js'),
|
||||||
];
|
];
|
||||||
for (const file of filesToCheck) {
|
for (const file of filesToCheck) {
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
|||||||
import { callLsRpc, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
import { callLsRpc, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||||
import {
|
import {
|
||||||
computeStepCost,
|
computeStepCost,
|
||||||
|
formatUpstreamModelId,
|
||||||
isArgonModelIdentifier,
|
isArgonModelIdentifier,
|
||||||
isCarbonModelIdentifier,
|
isCarbonModelIdentifier,
|
||||||
resolveModelInfo,
|
resolveModelInfo,
|
||||||
@@ -135,7 +136,10 @@ function enrichActiveConversationSteps(
|
|||||||
const rawUpstreamModel =
|
const rawUpstreamModel =
|
||||||
resolvedResponseModel ||
|
resolvedResponseModel ||
|
||||||
(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 annotatedUpstreamModel = formatUpstreamModelId(rawUpstreamModel, mInfo);
|
||||||
|
const modelUpstream = st.isCompactionStep
|
||||||
|
? `${annotatedUpstreamModel}·压缩`
|
||||||
|
: annotatedUpstreamModel;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
viewableDelaySec: _viewableDelaySec,
|
viewableDelaySec: _viewableDelaySec,
|
||||||
@@ -705,7 +709,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
weeklyResetMs: accountWeeklyResetMs || parseIsoMs(activeLiveWeekly?.resetTime),
|
weeklyResetMs: accountWeeklyResetMs || parseIsoMs(activeLiveWeekly?.resetTime),
|
||||||
};
|
};
|
||||||
|
|
||||||
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解)
|
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解 + 各配额池独立周期统计)
|
||||||
const {
|
const {
|
||||||
selectedWindow,
|
selectedWindow,
|
||||||
trendStartMs,
|
trendStartMs,
|
||||||
@@ -719,6 +723,8 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
monthlySeries,
|
monthlySeries,
|
||||||
weekBucket,
|
weekBucket,
|
||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
|
poolCycleStats,
|
||||||
|
poolsWeeklySummary,
|
||||||
} = aggregateMultiWindowUsage({
|
} = aggregateMultiWindowUsage({
|
||||||
filterOpts,
|
filterOpts,
|
||||||
cycleAnchors,
|
cycleAnchors,
|
||||||
@@ -726,8 +732,24 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
activeCascadeId,
|
activeCascadeId,
|
||||||
activeFamilyCascadeIds,
|
activeFamilyCascadeIds,
|
||||||
dynamicModelMap,
|
dynamicModelMap,
|
||||||
|
quotaPoolsMap,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const emptyCycleSummary = () => ({
|
||||||
|
calls: 0,
|
||||||
|
tokens: 0,
|
||||||
|
inputTokens: 0,
|
||||||
|
cacheReadTokens: 0,
|
||||||
|
outputTokens: 0,
|
||||||
|
costUsd: 0,
|
||||||
|
unpricedCalls: 0,
|
||||||
|
});
|
||||||
|
for (const [pk, poolObj] of quotaPoolsMap.entries()) {
|
||||||
|
const pStats = poolCycleStats?.get(pk);
|
||||||
|
poolObj.cycle5h = pStats?.cycle5h || emptyCycleSummary();
|
||||||
|
poolObj.cycleWeekly = pStats?.cycleWeekly || emptyCycleSummary();
|
||||||
|
}
|
||||||
|
|
||||||
// 6. 组装当前活跃配额池与每周限额视图数据
|
// 6. 组装当前活跃配额池与每周限额视图数据
|
||||||
const familyPoolQuota = quotaPoolsMap.get(activePoolKey);
|
const familyPoolQuota = quotaPoolsMap.get(activePoolKey);
|
||||||
const activePoolLabel = familyPoolQuota?.poolLabel || activePoolKey;
|
const activePoolLabel = familyPoolQuota?.poolLabel || activePoolKey;
|
||||||
@@ -756,6 +778,8 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? null,
|
weeklyRemainingIntPct: activeLiveWeekly?.remainingIntPct ?? null,
|
||||||
weeklyUsedPct: activeLiveWeekly?.usedPct ?? null,
|
weeklyUsedPct: activeLiveWeekly?.usedPct ?? null,
|
||||||
weeklyResetTime: activeLiveWeekly?.resetTime || null,
|
weeklyResetTime: activeLiveWeekly?.resetTime || null,
|
||||||
|
cycle5h: emptyCycleSummary(),
|
||||||
|
cycleWeekly: emptyCycleSummary(),
|
||||||
models: [],
|
models: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -898,10 +922,11 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
? knownUpstreamByModelKey.get(bestMetricStep.modelKey) || ''
|
? knownUpstreamByModelKey.get(bestMetricStep.modelKey) || ''
|
||||||
: '');
|
: '');
|
||||||
modelShort = mInfo.shortName || '';
|
modelShort = mInfo.shortName || '';
|
||||||
modelUpstream =
|
const rawQuickUpstream =
|
||||||
resolvedResp ||
|
resolvedResp ||
|
||||||
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName) ||
|
(mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : mInfo.shortName) ||
|
||||||
'';
|
'';
|
||||||
|
modelUpstream = formatUpstreamModelId(rawQuickUpstream, mInfo);
|
||||||
latestTokPerSec = roundMetric(speedMetric(bestMetricStep).value);
|
latestTokPerSec = roundMetric(speedMetric(bestMetricStep).value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1151,10 +1176,19 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
title: isCustomWeeklyMode
|
title: isCustomWeeklyMode
|
||||||
? '每周限额 (自定义本机)'
|
? '每周限额 (自定义本机)'
|
||||||
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
|
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
|
||||||
calls: weekBucket.calls,
|
calls: !isCustomWeeklyMode && poolsWeeklySummary ? poolsWeeklySummary.calls : weekBucket.calls,
|
||||||
tokens: weekBucket.totalTokens,
|
tokens:
|
||||||
costUsd: weekBucket.costUsd,
|
!isCustomWeeklyMode && poolsWeeklySummary
|
||||||
unpricedCalls: weekBucket.unpricedCalls,
|
? poolsWeeklySummary.tokens
|
||||||
|
: weekBucket.totalTokens,
|
||||||
|
costUsd:
|
||||||
|
!isCustomWeeklyMode && poolsWeeklySummary
|
||||||
|
? poolsWeeklySummary.costUsd
|
||||||
|
: weekBucket.costUsd,
|
||||||
|
unpricedCalls:
|
||||||
|
!isCustomWeeklyMode && poolsWeeklySummary
|
||||||
|
? poolsWeeklySummary.unpricedCalls
|
||||||
|
: weekBucket.unpricedCalls,
|
||||||
usedPct: weeklyUsedPct,
|
usedPct: weeklyUsedPct,
|
||||||
remainingPct: weeklyRemainingPct,
|
remainingPct: weeklyRemainingPct,
|
||||||
remainingIntPct: weeklyRemainingIntPct,
|
remainingIntPct: weeklyRemainingIntPct,
|
||||||
|
|||||||
@@ -7,13 +7,21 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
MEASUREMENT_VERSION,
|
||||||
accumulateSpeed,
|
accumulateSpeed,
|
||||||
createSpeedAccumulator,
|
createSpeedAccumulator,
|
||||||
finishSpeed,
|
finishSpeed,
|
||||||
|
parseIsoMs,
|
||||||
} from '../speed-metrics.mjs';
|
} from '../speed-metrics.mjs';
|
||||||
import { roundMetric, trajectoryCache } from './config.mjs';
|
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,
|
||||||
|
formatUpstreamModelId,
|
||||||
|
isArgonModelIdentifier,
|
||||||
|
isCarbonModelIdentifier,
|
||||||
|
resolveModelInfo,
|
||||||
|
} from './model-pricing.mjs';
|
||||||
|
|
||||||
function safeTok(val) {
|
function safeTok(val) {
|
||||||
const n = Number(val);
|
const n = Number(val);
|
||||||
@@ -260,7 +268,10 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
|||||||
perModelStats.set(modelGroupKey, {
|
perModelStats.set(modelGroupKey, {
|
||||||
label: modelGroupKey,
|
label: modelGroupKey,
|
||||||
shortName: mInfo.shortName,
|
shortName: mInfo.shortName,
|
||||||
fallbackModelId: mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : '',
|
fallbackModelId:
|
||||||
|
mInfo.modelId && mInfo.modelId !== 'unknown'
|
||||||
|
? formatUpstreamModelId(mInfo.modelId, mInfo)
|
||||||
|
: '',
|
||||||
upstreamModelCounts: new Map(),
|
upstreamModelCounts: new Map(),
|
||||||
family: mInfo.family,
|
family: mInfo.family,
|
||||||
calls: 0,
|
calls: 0,
|
||||||
@@ -271,17 +282,32 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
|||||||
responseTokens: 0,
|
responseTokens: 0,
|
||||||
totalTokens: 0,
|
totalTokens: 0,
|
||||||
costUsd: 0,
|
costUsd: 0,
|
||||||
|
ttftSumSec: 0,
|
||||||
|
ttftSampleCount: 0,
|
||||||
speedAccumulator: createSpeedAccumulator(),
|
speedAccumulator: createSpeedAccumulator(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const agg = perModelStats.get(modelGroupKey);
|
const agg = perModelStats.get(modelGroupKey);
|
||||||
if (st.responseModel) {
|
if (st.responseModel) {
|
||||||
|
const formattedResp = formatUpstreamModelId(st.responseModel, mInfo);
|
||||||
agg.upstreamModelCounts.set(
|
agg.upstreamModelCounts.set(
|
||||||
st.responseModel,
|
formattedResp,
|
||||||
(agg.upstreamModelCounts.get(st.responseModel) || 0) + 1
|
(agg.upstreamModelCounts.get(formattedResp) || 0) + 1
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
accumulateSpeed(agg.speedAccumulator, st);
|
accumulateSpeed(agg.speedAccumulator, st);
|
||||||
|
if (
|
||||||
|
!st.isCompactionStep &&
|
||||||
|
st.measurementVersion === MEASUREMENT_VERSION &&
|
||||||
|
st.isComplete &&
|
||||||
|
Number.isFinite(st.totalDurationSec) &&
|
||||||
|
Number.isFinite(st.nativeTtftSec) &&
|
||||||
|
st.nativeTtftSec >= 0 &&
|
||||||
|
st.nativeTtftSec <= st.totalDurationSec + 0.01
|
||||||
|
) {
|
||||||
|
agg.ttftSumSec += st.nativeTtftSec;
|
||||||
|
agg.ttftSampleCount += 1;
|
||||||
|
}
|
||||||
|
|
||||||
agg.calls += 1;
|
agg.calls += 1;
|
||||||
agg.inputTokens += inTok;
|
agg.inputTokens += inTok;
|
||||||
@@ -303,22 +329,39 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
|||||||
function finalizeModelBreakdownMap(perModelStats) {
|
function finalizeModelBreakdownMap(perModelStats) {
|
||||||
return Array.from(perModelStats.values())
|
return Array.from(perModelStats.values())
|
||||||
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
||||||
.map(({ speedAccumulator, upstreamModelCounts, fallbackModelId, ...m }) => {
|
.map(
|
||||||
|
({
|
||||||
|
speedAccumulator,
|
||||||
|
upstreamModelCounts,
|
||||||
|
fallbackModelId,
|
||||||
|
ttftSumSec,
|
||||||
|
ttftSampleCount,
|
||||||
|
...m
|
||||||
|
}) => {
|
||||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||||
.sort((a, b) => b[1] - a[1])
|
.sort((a, b) => b[1] - a[1])
|
||||||
.map(([name]) => name);
|
.map(([name]) => name);
|
||||||
const primaryUpstream =
|
const primaryUpstream =
|
||||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||||
const finishedSpeed = finishSpeed(speedAccumulator);
|
const finishedSpeed = finishSpeed(speedAccumulator);
|
||||||
|
const promptTokens = m.inputTokens + m.cacheReadTokens;
|
||||||
|
const cacheHitPct =
|
||||||
|
promptTokens > 0 ? +((m.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0;
|
||||||
|
const avgTtftSec =
|
||||||
|
ttftSampleCount > 0 ? roundMetric(ttftSumSec / ttftSampleCount) : null;
|
||||||
return {
|
return {
|
||||||
...m,
|
...m,
|
||||||
upstreamName: primaryUpstream,
|
upstreamName: primaryUpstream,
|
||||||
upstreamModels: sortedUpstream,
|
upstreamModels: sortedUpstream,
|
||||||
costUsd: +m.costUsd.toFixed(3),
|
costUsd: +m.costUsd.toFixed(6),
|
||||||
|
cacheHitPct,
|
||||||
|
avgTtftSec,
|
||||||
|
ttftSampleCount,
|
||||||
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
||||||
speedSummary: finishedSpeed,
|
speedSummary: finishedSpeed,
|
||||||
};
|
};
|
||||||
});
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -364,6 +407,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
activeCascadeId = null,
|
activeCascadeId = null,
|
||||||
activeFamilyCascadeIds = null,
|
activeFamilyCascadeIds = null,
|
||||||
dynamicModelMap = new Map(),
|
dynamicModelMap = new Map(),
|
||||||
|
quotaPoolsMap = null,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
const rawFamilyIds =
|
const rawFamilyIds =
|
||||||
activeFamilyCascadeIds instanceof Set
|
activeFamilyCascadeIds instanceof Set
|
||||||
@@ -391,6 +435,32 @@ export function aggregateMultiWindowUsage({
|
|||||||
accountBuckets[k] = createUsageBucket();
|
accountBuckets[k] = createUsageBucket();
|
||||||
sessionBuckets[k] = createUsageBucket();
|
sessionBuckets[k] = createUsageBucket();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口)
|
||||||
|
const poolCycleBuckets = new Map();
|
||||||
|
if (quotaPoolsMap instanceof Map && quotaPoolsMap.size > 0) {
|
||||||
|
const weekFallbackStartMs = getStartOfCurrentWeekMs(new Date(nowMs));
|
||||||
|
for (const [poolKey, poolObj] of quotaPoolsMap.entries()) {
|
||||||
|
const reset5hMs = parseIsoMs(poolObj?.resetTime) || 0;
|
||||||
|
const start5hMs =
|
||||||
|
reset5hMs > nowMs
|
||||||
|
? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000)
|
||||||
|
: nowMs - 5 * 3600 * 1000;
|
||||||
|
const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0;
|
||||||
|
const startWkMs =
|
||||||
|
resetWkMs > nowMs
|
||||||
|
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
|
||||||
|
: weekFallbackStartMs;
|
||||||
|
poolCycleBuckets.set(poolKey, {
|
||||||
|
start5hMs,
|
||||||
|
startWkMs,
|
||||||
|
b5h: createUsageBucket(),
|
||||||
|
bWk: createUsageBucket(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||||
|
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||||
const selectedAccountBucket = createUsageBucket();
|
const selectedAccountBucket = createUsageBucket();
|
||||||
const selectedSessionBucket = createUsageBucket();
|
const selectedSessionBucket = createUsageBucket();
|
||||||
const perModelStats = new Map();
|
const perModelStats = new Map();
|
||||||
@@ -543,6 +613,43 @@ export function aggregateMultiWindowUsage({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
|
||||||
|
const stepPoolKey =
|
||||||
|
hasDedicatedCarbonPool &&
|
||||||
|
isCarbonModelIdentifier(
|
||||||
|
st.modelKey,
|
||||||
|
st.responseModel,
|
||||||
|
mInfo.modelId,
|
||||||
|
mInfo.label,
|
||||||
|
st.modelDisplayName
|
||||||
|
)
|
||||||
|
? 'Carbon'
|
||||||
|
: hasDedicatedArgonPool &&
|
||||||
|
isArgonModelIdentifier(
|
||||||
|
st.modelKey,
|
||||||
|
st.responseModel,
|
||||||
|
mInfo.modelId,
|
||||||
|
mInfo.label,
|
||||||
|
st.modelDisplayName
|
||||||
|
)
|
||||||
|
? 'Argon'
|
||||||
|
: mInfo.family === 'Gemini' && poolCycleBuckets.has('Gemini')
|
||||||
|
? 'Gemini'
|
||||||
|
: ['Claude', 'GPT', 'Other'].includes(mInfo.family) &&
|
||||||
|
poolCycleBuckets.has('Claude & GPT')
|
||||||
|
? 'Claude & GPT'
|
||||||
|
: null;
|
||||||
|
const poolBucketEntry = stepPoolKey ? poolCycleBuckets.get(stepPoolKey) : null;
|
||||||
|
if (poolBucketEntry) {
|
||||||
|
if (tMs >= poolBucketEntry.start5hMs) {
|
||||||
|
accumulateStepIntoBucket(poolBucketEntry.b5h, st, mInfo, stepCost, cascadeId);
|
||||||
|
}
|
||||||
|
if (tMs >= poolBucketEntry.startWkMs) {
|
||||||
|
accumulateStepIntoBucket(poolBucketEntry.bWk, st, mInfo, stepCost, cascadeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const inSelectedWindow =
|
const inSelectedWindow =
|
||||||
selectedWindow.key === 'all' ||
|
selectedWindow.key === 'all' ||
|
||||||
(tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
(tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
||||||
@@ -711,26 +818,24 @@ export function aggregateMultiWindowUsage({
|
|||||||
dayStarts.unshift(prev.getTime());
|
dayStarts.unshift(prev.getTime());
|
||||||
}
|
}
|
||||||
|
|
||||||
const stepDays = dayStarts.length > 60 ? Math.ceil(dayStarts.length / 45) : 1;
|
const firstYear = new Date(dayStarts[0]).getFullYear();
|
||||||
let bucketIdx = 0;
|
const lastYear = new Date(dayStarts[dayStarts.length - 1]).getFullYear();
|
||||||
for (let i = 0; i < dayStarts.length; i += stepDays) {
|
const showFullYear = firstYear !== lastYear || dayStarts.length > 90;
|
||||||
|
|
||||||
|
for (let i = 0; i < dayStarts.length; i++) {
|
||||||
const sMs = dayStarts[i];
|
const sMs = dayStarts[i];
|
||||||
const endDayStartMs = dayStarts[Math.min(dayStarts.length - 1, i + stepDays - 1)];
|
const endCursor = new Date(sMs);
|
||||||
const endCursor = new Date(endDayStartMs);
|
|
||||||
endCursor.setDate(endCursor.getDate() + 1);
|
endCursor.setDate(endCursor.getDate() + 1);
|
||||||
endCursor.setHours(0, 0, 0, 0);
|
endCursor.setHours(0, 0, 0, 0);
|
||||||
const eMs = endCursor.getTime();
|
const eMs = endCursor.getTime();
|
||||||
|
|
||||||
const sd = new Date(sMs);
|
const sd = new Date(sMs);
|
||||||
const ed = new Date(endDayStartMs);
|
|
||||||
const axisLabel = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`;
|
const axisLabel = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`;
|
||||||
const fullLabel =
|
const datePrefix = showFullYear ? `${sd.getFullYear()}年` : '';
|
||||||
stepDays === 1
|
const fullLabel = `${datePrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${WEEKDAY_NAMES[sd.getDay()]})`;
|
||||||
? `${sd.getMonth() + 1}月${sd.getDate()}日 (${WEEKDAY_NAMES[sd.getDay()]})`
|
|
||||||
: `${sd.getMonth() + 1}月${sd.getDate()}日 - ${ed.getMonth() + 1}月${ed.getDate()}日`;
|
|
||||||
|
|
||||||
trendSeries.push({
|
trendSeries.push({
|
||||||
index: bucketIdx++,
|
index: i,
|
||||||
startMs: sMs,
|
startMs: sMs,
|
||||||
endMs: eMs,
|
endMs: eMs,
|
||||||
granularity: 'day',
|
granularity: 'day',
|
||||||
@@ -809,6 +914,44 @@ export function aggregateMultiWindowUsage({
|
|||||||
const weekBucket = finalizedPresets.week.account;
|
const weekBucket = finalizedPresets.week.account;
|
||||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||||
|
|
||||||
|
const formatCycleSummary = (b) => {
|
||||||
|
const fin = finalizeUsageBucket(b);
|
||||||
|
return {
|
||||||
|
calls: fin.calls,
|
||||||
|
tokens: fin.totalTokens,
|
||||||
|
inputTokens: fin.inputTokens,
|
||||||
|
cacheReadTokens: fin.cacheReadTokens,
|
||||||
|
outputTokens: fin.outputTokens,
|
||||||
|
costUsd: fin.costUsd,
|
||||||
|
unpricedCalls: fin.unpricedCalls,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const poolCycleStats = new Map();
|
||||||
|
let rawPoolsWeeklyCalls = 0;
|
||||||
|
let rawPoolsWeeklyTokens = 0;
|
||||||
|
let rawPoolsWeeklyCostUsd = 0;
|
||||||
|
let rawPoolsWeeklyUnpricedCalls = 0;
|
||||||
|
for (const [poolKey, entry] of poolCycleBuckets.entries()) {
|
||||||
|
poolCycleStats.set(poolKey, {
|
||||||
|
cycle5h: formatCycleSummary(entry.b5h),
|
||||||
|
cycleWeekly: formatCycleSummary(entry.bWk),
|
||||||
|
});
|
||||||
|
rawPoolsWeeklyCalls += entry.bWk.calls;
|
||||||
|
rawPoolsWeeklyTokens += entry.bWk.totalTokens;
|
||||||
|
rawPoolsWeeklyCostUsd += entry.bWk.costUsd;
|
||||||
|
rawPoolsWeeklyUnpricedCalls += entry.bWk.unpricedCalls || 0;
|
||||||
|
}
|
||||||
|
const poolsWeeklySummary =
|
||||||
|
poolCycleBuckets.size > 0
|
||||||
|
? {
|
||||||
|
calls: rawPoolsWeeklyCalls,
|
||||||
|
tokens: rawPoolsWeeklyTokens,
|
||||||
|
costUsd: +rawPoolsWeeklyCostUsd.toFixed(2),
|
||||||
|
unpricedCalls: rawPoolsWeeklyUnpricedCalls,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
selectedWindow,
|
selectedWindow,
|
||||||
trendStartMs,
|
trendStartMs,
|
||||||
@@ -823,5 +966,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
todayBucket,
|
todayBucket,
|
||||||
weekBucket,
|
weekBucket,
|
||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
|
poolCycleStats,
|
||||||
|
poolsWeeklySummary,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Antigravity IDE / 2.0 独立后台双栖窗口桥接守护进程 (`bridge-daemon.mjs`)。
|
||||||
|
*
|
||||||
|
* 由 `mcp-entry.mjs` 托管拉起,负责:
|
||||||
|
* 1. 动态探测本机运行中的 `agy --hub` / `language_server` 端点与 `DevToolsActivePort`;
|
||||||
|
* 2. 启动本地回环桥接服务并通过 CDP 将顶栏/输入框监控胶囊热挂载至 Antigravity IDE 与 2.0 窗口;
|
||||||
|
* 3. 收到父进程 `SHUTDOWN_DISPOSE` 指令或终止信号时,主动清理窗口浮层并平滑退出。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { bootWindowBridgeRuntime } from './backend/api-actions.mjs';
|
||||||
|
|
||||||
|
export function startBridgeDaemon() {
|
||||||
|
let shuttingDown = false;
|
||||||
|
let sawShutdownDispose = false;
|
||||||
|
let stdinBuf = '';
|
||||||
|
|
||||||
|
const controller = bootWindowBridgeRuntime({
|
||||||
|
allowDynamicLs: true,
|
||||||
|
onRestart: () => {
|
||||||
|
void shutdown({ disposeWindows: false, exitCode: 0 });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
async function shutdown({ disposeWindows = false, exitCode = 0 } = {}) {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
const forceTimer = setTimeout(() => {
|
||||||
|
process.exit(exitCode);
|
||||||
|
}, 1500);
|
||||||
|
forceTimer.unref?.();
|
||||||
|
try {
|
||||||
|
await controller?.stop?.({ disposeWindows });
|
||||||
|
} catch {
|
||||||
|
// 忽略退出清理异常
|
||||||
|
} finally {
|
||||||
|
clearTimeout(forceTimer);
|
||||||
|
process.exit(exitCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
process.stdin.setEncoding('utf8');
|
||||||
|
process.stdin.on('data', (chunk) => {
|
||||||
|
stdinBuf += String(chunk || '');
|
||||||
|
if (stdinBuf.includes('SHUTDOWN_DISPOSE')) {
|
||||||
|
sawShutdownDispose = true;
|
||||||
|
void shutdown({ disposeWindows: true, exitCode: 0 });
|
||||||
|
} else if (stdinBuf.length > 4096) {
|
||||||
|
stdinBuf = stdinBuf.slice(-1024);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
process.stdin.on('end', () => {
|
||||||
|
void shutdown({ disposeWindows: sawShutdownDispose, exitCode: 0 });
|
||||||
|
});
|
||||||
|
process.stdin.on('close', () => {
|
||||||
|
void shutdown({ disposeWindows: sawShutdownDispose, exitCode: 0 });
|
||||||
|
});
|
||||||
|
process.on('SIGTERM', () => {
|
||||||
|
void shutdown({ disposeWindows: true, exitCode: 0 });
|
||||||
|
});
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
void shutdown({ disposeWindows: true, exitCode: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
process.stdin.resume();
|
||||||
|
return controller;
|
||||||
|
}
|
||||||
|
|
||||||
|
const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
||||||
|
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
||||||
|
startBridgeDaemon();
|
||||||
|
}
|
||||||
@@ -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=1794408541340">
|
<link rel="stylesheet" href="/styles.css?v=1794653465857">
|
||||||
<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=1794408541340"></script>
|
<script src="/app.js?v=1794653465857"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+11
-247
@@ -8,103 +8,22 @@
|
|||||||
* - `POST /api/settings`:保存用户偏好设置(写入失败时返回 HTTP 500);
|
* - `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 双通道);
|
||||||
* - 所有核心业务逻辑均已模块化拆分至 `./backend/*.mjs`。
|
* - 所有核心业务逻辑与双栖桥接引导均委托至 `./backend/api-actions.mjs`。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
|
||||||
import { join } from 'node:path';
|
|
||||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||||
import {
|
import {
|
||||||
HERE,
|
bootWindowBridgeRuntime,
|
||||||
LS_ADDR,
|
executeCloudSyncAction,
|
||||||
SETTINGS_FILE,
|
executePluginUpdateAction,
|
||||||
cloudSyncState,
|
executeSettingsAction,
|
||||||
computeRuntimeCodeVersion,
|
executeTelemetryAction,
|
||||||
isPlainObject,
|
isLocalHostRequest,
|
||||||
loadSettings,
|
readLocalAsync,
|
||||||
normalizePluginUpdateMode,
|
} from './backend/api-actions.mjs';
|
||||||
normalizeTopbarCapsuleSlots,
|
|
||||||
normalizeWeeklyLimitMode,
|
|
||||||
saveJson,
|
|
||||||
} from './backend/config.mjs';
|
|
||||||
import {
|
|
||||||
performPluginUpdate,
|
|
||||||
scheduleSidecarRestart,
|
|
||||||
syncCloudCatalog,
|
|
||||||
} from './backend/plugin-updater.mjs';
|
|
||||||
import { getCloudStatus } from './backend/pricing-catalog.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 = computeRuntimeCodeVersion();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
|
||||||
*
|
|
||||||
* @param {string} relPath 相对路径
|
|
||||||
* @returns {Promise<string>}
|
|
||||||
*/
|
|
||||||
const readLocalAsync = async (relPath) => {
|
|
||||||
const fullPath = join(HERE, relPath);
|
|
||||||
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
|
||||||
return fsPromises.readFile(fullPath, 'utf8');
|
|
||||||
}
|
|
||||||
return readFileSync(fullPath, 'utf8');
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
|
||||||
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
|
||||||
*
|
|
||||||
* @param {object} req
|
|
||||||
* @returns {boolean}
|
|
||||||
*/
|
|
||||||
export function isLocalHostRequest(req) {
|
|
||||||
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();
|
|
||||||
if (secFetchSite === 'cross-site') {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (origin) {
|
|
||||||
const originMatch = origin.match(
|
|
||||||
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
|
||||||
);
|
|
||||||
if (!originMatch) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (hostMatch) {
|
|
||||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
|
||||||
const originPort = originMatch[3] || defaultPort;
|
|
||||||
const hostPort = hostMatch[2] || defaultPort;
|
|
||||||
if (originPort !== hostPort) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
|
||||||
|
|
||||||
function sanitizePositiveFiniteMs(val) {
|
|
||||||
const num = Number(val);
|
|
||||||
return Number.isFinite(num) && num > 0 && num <= MAX_SAFE_DATE_MS ? Math.floor(num) : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate' };
|
const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate' };
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -139,156 +58,9 @@ app.page(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 业务数据与控制 API 路由(辅助栏 Sidecar Webview 与主窗口双栖桥接共享同一套处理函数)
|
// 业务数据与控制 API 路由
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
async function executeTelemetryAction(data) {
|
|
||||||
const rawConvId = String(
|
|
||||||
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
|
||||||
).trim();
|
|
||||||
const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : '';
|
|
||||||
const force = data?.force === '1' || data?.force === true;
|
|
||||||
if (LS_ADDR && LS_ADDR !== 'test.invalid') {
|
|
||||||
if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) {
|
|
||||||
await Promise.race([
|
|
||||||
syncCloudCatalog({ force: true }).catch(() => {}),
|
|
||||||
new Promise((r) => setTimeout(r, 1200)),
|
|
||||||
]);
|
|
||||||
} else {
|
|
||||||
syncCloudCatalog({ force: false }).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const filterOpts = {
|
|
||||||
range: data?.range || 'all',
|
|
||||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
|
||||||
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
|
||||||
};
|
|
||||||
const payload = await buildTelemetryPayload(convId, force, filterOpts);
|
|
||||||
if (
|
|
||||||
bootBundleVersion &&
|
|
||||||
payload.uiBundleVersion &&
|
|
||||||
String(payload.uiBundleVersion) !== String(bootBundleVersion)
|
|
||||||
) {
|
|
||||||
scheduleSidecarRestart(150);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
status: 200,
|
|
||||||
contentType: 'application/json',
|
|
||||||
headers: { 'Cache-Control': 'no-store' },
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function sanitizePositiveSettingNumber(val, fallback) {
|
|
||||||
const num = Number(val);
|
|
||||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
function executeSettingsAction(data) {
|
|
||||||
const current = loadSettings();
|
|
||||||
const payload = isPlainObject(data) ? data : {};
|
|
||||||
const nextPluginUpdateMode =
|
|
||||||
payload.pluginUpdateMode !== undefined
|
|
||||||
? normalizePluginUpdateMode(payload.pluginUpdateMode)
|
|
||||||
: typeof payload.autoUpdatePlugin === 'boolean'
|
|
||||||
? payload.autoUpdatePlugin
|
|
||||||
? 'auto'
|
|
||||||
: 'manual'
|
|
||||||
: normalizePluginUpdateMode(current.pluginUpdateMode, current.autoUpdatePlugin);
|
|
||||||
const updated = {
|
|
||||||
weeklyTokenBudget: sanitizePositiveSettingNumber(
|
|
||||||
payload.weeklyTokenBudget ?? payload.weeklyTokenLimit,
|
|
||||||
current.weeklyTokenBudget
|
|
||||||
),
|
|
||||||
weeklyCostBudget: sanitizePositiveSettingNumber(
|
|
||||||
payload.weeklyCostBudget,
|
|
||||||
current.weeklyCostBudget
|
|
||||||
),
|
|
||||||
weeklyLimitMode:
|
|
||||||
payload.weeklyLimitMode !== undefined
|
|
||||||
? normalizeWeeklyLimitMode(payload.weeklyLimitMode)
|
|
||||||
: current.weeklyLimitMode,
|
|
||||||
showUpstreamModel:
|
|
||||||
typeof payload.showUpstreamModel === 'boolean'
|
|
||||||
? payload.showUpstreamModel
|
|
||||||
: Boolean(current.showUpstreamModel),
|
|
||||||
pluginUpdateMode: nextPluginUpdateMode,
|
|
||||||
autoUpdatePlugin: nextPluginUpdateMode === 'auto',
|
|
||||||
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),
|
|
||||||
};
|
|
||||||
if (!saveJson(SETTINGS_FILE, 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(
|
app.api(
|
||||||
'/api/telemetry',
|
'/api/telemetry',
|
||||||
async (data, req) => {
|
async (data, req) => {
|
||||||
@@ -357,12 +129,4 @@ app.api('/api/plugin-update', async (_data, req) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.run();
|
app.run();
|
||||||
if (LS_ADDR && LS_ADDR !== 'test.invalid') {
|
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||||
syncCloudCatalog({ force: false }).catch(() => {});
|
|
||||||
startDefaultWindowBridge({
|
|
||||||
handleApiRequest: dispatchBridgeApiRequest,
|
|
||||||
readAssetFn: readLocalAsync,
|
|
||||||
bootBundleVersion,
|
|
||||||
onVersionDrift: () => scheduleSidecarRestart(150),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,300 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 零工具开销的轻量 MCP Stdio 宿主保活入口 (`mcp_config.json`)。
|
||||||
|
*
|
||||||
|
* 设计原因:
|
||||||
|
* Antigravity IDE 默认关闭了 UI Sidecar 管理器 (`enable-sidecars = false`),不会启动 `sidecar.json`。
|
||||||
|
* 通过将本文件注册为插件内置的 0 工具 MCP Stdio 服务:
|
||||||
|
* 1. `agy --hub` 启动或启用插件时会自动拉起本进程,从而托管启动 `bridge-daemon.mjs` 将胶囊挂载至 IDE 顶栏;
|
||||||
|
* 2. `tools/list` 返回空数组 `[]`,不注入任何工具定义,消耗 0 个上下文 Token;
|
||||||
|
* 3. 用户在 Customizations 中关闭插件开关或退出 IDE 时,`agy --hub` 关闭 `stdin`,
|
||||||
|
* 本进程立即通知 `bridge-daemon.mjs` 卸载窗口顶栏组件并干净退出。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
|
import { dirname, join, resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const PANEL_DIR = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const PLUGIN_MANIFEST_PATH = join(dirname(dirname(PANEL_DIR)), 'plugin.json');
|
||||||
|
const DAEMON_SCRIPT_PATH = join(PANEL_DIR, 'bridge-daemon.mjs');
|
||||||
|
|
||||||
|
const SUPPORTED_MCP_VERSIONS = new Set([
|
||||||
|
'2025-11-25',
|
||||||
|
'2025-06-18',
|
||||||
|
'2025-03-26',
|
||||||
|
'2024-11-05',
|
||||||
|
]);
|
||||||
|
const DEFAULT_MCP_VERSION = '2025-03-26';
|
||||||
|
|
||||||
|
export function readMcpServerVersion() {
|
||||||
|
try {
|
||||||
|
if (existsSync(PLUGIN_MANIFEST_PATH)) {
|
||||||
|
const parsed = JSON.parse(readFileSync(PLUGIN_MANIFEST_PATH, 'utf8'));
|
||||||
|
if (typeof parsed?.version === 'string' && parsed.version.trim()) {
|
||||||
|
return parsed.version.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略清单读取失败
|
||||||
|
}
|
||||||
|
return '1.4.4';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 纯函数处理单条 MCP JSON-RPC 2.0 消息;通知类消息(无 `id`)返回 `null`。
|
||||||
|
*
|
||||||
|
* @param {object} msg
|
||||||
|
* @param {string} [serverVersion='1.4.4']
|
||||||
|
* @returns {object|null}
|
||||||
|
*/
|
||||||
|
export function handleMcpJsonRpcMessage(msg, serverVersion = '1.4.4') {
|
||||||
|
if (!msg || typeof msg !== 'object') return null;
|
||||||
|
const hasId = Object.prototype.hasOwnProperty.call(msg, 'id') && msg.id !== undefined;
|
||||||
|
if (!hasId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const id = msg.id;
|
||||||
|
const method = String(msg.method || '');
|
||||||
|
|
||||||
|
if (method === 'initialize') {
|
||||||
|
const requested = String(msg.params?.protocolVersion || '').trim();
|
||||||
|
const protocolVersion = SUPPORTED_MCP_VERSIONS.has(requested)
|
||||||
|
? requested
|
||||||
|
: DEFAULT_MCP_VERSION;
|
||||||
|
return {
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id,
|
||||||
|
result: {
|
||||||
|
protocolVersion,
|
||||||
|
capabilities: {
|
||||||
|
tools: {},
|
||||||
|
},
|
||||||
|
serverInfo: {
|
||||||
|
name: 'usage-monitor-host',
|
||||||
|
version: serverVersion,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'ping') {
|
||||||
|
return { jsonrpc: '2.0', id, result: {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'tools/list') {
|
||||||
|
return { jsonrpc: '2.0', id, result: { tools: [] } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'resources/list') {
|
||||||
|
return { jsonrpc: '2.0', id, result: { resources: [] } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'resources/templates/list') {
|
||||||
|
return { jsonrpc: '2.0', id, result: { resourceTemplates: [] } };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'prompts/list') {
|
||||||
|
return { jsonrpc: '2.0', id, result: { prompts: [] } };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id,
|
||||||
|
error: {
|
||||||
|
code: -32601,
|
||||||
|
message: `Method not found: ${method}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function startMcpHostSupervisor() {
|
||||||
|
const serverVersion = readMcpServerVersion();
|
||||||
|
let shuttingDown = false;
|
||||||
|
let daemonChild = null;
|
||||||
|
let respawnTimer = null;
|
||||||
|
let rapidCrashCount = 0;
|
||||||
|
let lastSpawnMs = 0;
|
||||||
|
|
||||||
|
function spawnDaemon() {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
lastSpawnMs = Date.now();
|
||||||
|
const child = spawn(process.execPath, [DAEMON_SCRIPT_PATH], {
|
||||||
|
cwd: PANEL_DIR,
|
||||||
|
windowsHide: true,
|
||||||
|
stdio: ['pipe', 'ignore', 'pipe'],
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
USAGE_MONITOR_HOST_PPID: `${process.ppid || 0},${process.pid || 0}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
daemonChild = child;
|
||||||
|
|
||||||
|
child.stderr?.on('data', (chunk) => {
|
||||||
|
try {
|
||||||
|
process.stderr.write(chunk);
|
||||||
|
} catch {
|
||||||
|
// 忽略日志转发异常
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('exit', (code) => {
|
||||||
|
if (daemonChild === child) {
|
||||||
|
daemonChild = null;
|
||||||
|
}
|
||||||
|
if (shuttingDown) return;
|
||||||
|
|
||||||
|
const ranDurationMs = Date.now() - lastSpawnMs;
|
||||||
|
let delayMs = 350;
|
||||||
|
if (code !== 0 && ranDurationMs < 10_000) {
|
||||||
|
rapidCrashCount += 1;
|
||||||
|
delayMs = Math.min(30_000, 1000 * 2 ** Math.min(rapidCrashCount - 1, 5));
|
||||||
|
} else {
|
||||||
|
rapidCrashCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (respawnTimer) clearTimeout(respawnTimer);
|
||||||
|
respawnTimer = setTimeout(() => {
|
||||||
|
respawnTimer = null;
|
||||||
|
spawnDaemon();
|
||||||
|
}, delayMs);
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('error', () => {
|
||||||
|
// 交由 exit 回调或退避重试统一处理
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function shutdownSupervisor() {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
if (respawnTimer) {
|
||||||
|
clearTimeout(respawnTimer);
|
||||||
|
respawnTimer = null;
|
||||||
|
}
|
||||||
|
const child = daemonChild;
|
||||||
|
if (!child) {
|
||||||
|
process.exit(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const forceExitTimer = setTimeout(() => {
|
||||||
|
try {
|
||||||
|
child.kill();
|
||||||
|
} catch {
|
||||||
|
// 忽略强杀异常
|
||||||
|
}
|
||||||
|
process.exit(0);
|
||||||
|
}, 1800);
|
||||||
|
forceExitTimer.unref?.();
|
||||||
|
|
||||||
|
child.once('exit', () => {
|
||||||
|
clearTimeout(forceExitTimer);
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
child.stdin?.write('SHUTDOWN_DISPOSE\n');
|
||||||
|
child.stdin?.end();
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
child.kill();
|
||||||
|
} catch {
|
||||||
|
// 忽略异常
|
||||||
|
}
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let framingMode = 'line';
|
||||||
|
let rawBuffer = Buffer.alloc(0);
|
||||||
|
|
||||||
|
function writeJsonRpcResponse(payload, mode) {
|
||||||
|
const serialized = JSON.stringify(payload);
|
||||||
|
if (mode === 'lsp') {
|
||||||
|
const byteLen = Buffer.byteLength(serialized, 'utf8');
|
||||||
|
process.stdout.write(`Content-Length: ${byteLen}\r\n\r\n${serialized}`);
|
||||||
|
} else {
|
||||||
|
process.stdout.write(`${serialized}\n`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dispatchParsedPayload(parsed, mode) {
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
const batchOut = parsed
|
||||||
|
.map((item) => handleMcpJsonRpcMessage(item, serverVersion))
|
||||||
|
.filter(Boolean);
|
||||||
|
if (batchOut.length > 0) {
|
||||||
|
writeJsonRpcResponse(batchOut, mode);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const response = handleMcpJsonRpcMessage(parsed, serverVersion);
|
||||||
|
if (response) {
|
||||||
|
writeJsonRpcResponse(response, mode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function drainInputBuffer() {
|
||||||
|
while (rawBuffer.length > 0) {
|
||||||
|
const preview = rawBuffer.subarray(0, Math.min(rawBuffer.length, 64)).toString('utf8');
|
||||||
|
if (/^Content-Length:/i.test(preview.trimStart())) {
|
||||||
|
framingMode = 'lsp';
|
||||||
|
const sepIdx = rawBuffer.indexOf('\r\n\r\n');
|
||||||
|
const lfSepIdx = sepIdx < 0 ? rawBuffer.indexOf('\n\n') : -1;
|
||||||
|
const headerEnd = sepIdx >= 0 ? sepIdx : lfSepIdx;
|
||||||
|
const sepLen = sepIdx >= 0 ? 4 : 2;
|
||||||
|
if (headerEnd < 0) return;
|
||||||
|
|
||||||
|
const headerStr = rawBuffer.subarray(0, headerEnd).toString('utf8');
|
||||||
|
const lenMatch = headerStr.match(/Content-Length:\s*(\d+)/i);
|
||||||
|
if (!lenMatch) {
|
||||||
|
rawBuffer = rawBuffer.subarray(headerEnd + sepLen);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const contentLen = Number(lenMatch[1]);
|
||||||
|
const totalFrameLen = headerEnd + sepLen + contentLen;
|
||||||
|
if (rawBuffer.length < totalFrameLen) return;
|
||||||
|
|
||||||
|
const bodyStr = rawBuffer.subarray(headerEnd + sepLen, totalFrameLen).toString('utf8');
|
||||||
|
rawBuffer = rawBuffer.subarray(totalFrameLen);
|
||||||
|
try {
|
||||||
|
dispatchParsedPayload(JSON.parse(bodyStr), 'lsp');
|
||||||
|
} catch {
|
||||||
|
// 忽略损坏帧
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nlIdx = rawBuffer.indexOf(0x0a);
|
||||||
|
if (nlIdx < 0) return;
|
||||||
|
const lineStr = rawBuffer.subarray(0, nlIdx).toString('utf8').trim();
|
||||||
|
rawBuffer = rawBuffer.subarray(nlIdx + 1);
|
||||||
|
if (!lineStr) continue;
|
||||||
|
try {
|
||||||
|
dispatchParsedPayload(JSON.parse(lineStr), framingMode);
|
||||||
|
} catch {
|
||||||
|
// 忽略非 JSON 行
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
process.stdin.on('data', (chunk) => {
|
||||||
|
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
|
||||||
|
rawBuffer = rawBuffer.length === 0 ? buf : Buffer.concat([rawBuffer, buf]);
|
||||||
|
drainInputBuffer();
|
||||||
|
});
|
||||||
|
|
||||||
|
process.stdin.on('end', shutdownSupervisor);
|
||||||
|
process.stdin.on('close', shutdownSupervisor);
|
||||||
|
process.on('SIGTERM', shutdownSupervisor);
|
||||||
|
process.on('SIGINT', shutdownSupervisor);
|
||||||
|
process.stdin.resume();
|
||||||
|
|
||||||
|
spawnDaemon();
|
||||||
|
}
|
||||||
|
|
||||||
|
const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
||||||
|
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
||||||
|
startMcpHostSupervisor();
|
||||||
|
}
|
||||||
|
|
||||||
@@ -466,6 +466,7 @@ export function buildBundle() {
|
|||||||
'src/components/ui/ContextSegmentMeter.js',
|
'src/components/ui/ContextSegmentMeter.js',
|
||||||
'src/components/ui/FourSegmentBar.js',
|
'src/components/ui/FourSegmentBar.js',
|
||||||
'src/components/charts/TrendAreaChart.js',
|
'src/components/charts/TrendAreaChart.js',
|
||||||
|
'src/components/charts/SessionStepCharts.js',
|
||||||
'src/components/layout/TopSessionHeader.js',
|
'src/components/layout/TopSessionHeader.js',
|
||||||
'src/views/LiveOverviewView.js',
|
'src/views/LiveOverviewView.js',
|
||||||
'src/views/ConsumptionView.js',
|
'src/views/ConsumptionView.js',
|
||||||
|
|||||||
@@ -573,10 +573,24 @@ export function extractContextBreakdown(chat) {
|
|||||||
*/
|
*/
|
||||||
export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||||
const genByStep = new Map();
|
const genByStep = new Map();
|
||||||
|
const orchestratorExecModels = new Set();
|
||||||
|
const collectOrchestratorExecModel = (pc) => {
|
||||||
|
const execModel = pc?.planExecuteConfig?.executionModel;
|
||||||
|
if (
|
||||||
|
typeof execModel === 'string' &&
|
||||||
|
execModel.trim() &&
|
||||||
|
/orchestrator|MODEL_PLACEHOLDER_M(?:667|681)\b/i.test(
|
||||||
|
`${pc?.modelName || ''} ${pc?.planModel || ''}`
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
orchestratorExecModels.add(execModel.trim());
|
||||||
|
}
|
||||||
|
};
|
||||||
let latestBreakdownChat = null;
|
let latestBreakdownChat = null;
|
||||||
let latestBreakdownStepIdx = -1;
|
let latestBreakdownStepIdx = -1;
|
||||||
|
|
||||||
for (const gm of generatorMetadata || []) {
|
for (const gm of generatorMetadata || []) {
|
||||||
|
collectOrchestratorExecModel(gm?.plannerConfig);
|
||||||
if (!gm?.chatModel) {
|
if (!gm?.chatModel) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -605,6 +619,11 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
||||||
|
if (Array.isArray(m.generatorMetadata)) {
|
||||||
|
for (const g of m.generatorMetadata) {
|
||||||
|
collectOrchestratorExecModel(g?.plannerConfig);
|
||||||
|
}
|
||||||
|
}
|
||||||
const inlineChat = Array.isArray(m.generatorMetadata)
|
const inlineChat = Array.isArray(m.generatorMetadata)
|
||||||
? m.generatorMetadata.find((g) => g?.chatModel)
|
? m.generatorMetadata.find((g) => g?.chatModel)
|
||||||
: null;
|
: null;
|
||||||
@@ -708,14 +727,27 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
m?.responseModel,
|
m?.responseModel,
|
||||||
].find(isValidModelValue);
|
].find(isValidModelValue);
|
||||||
|
|
||||||
|
const resolvedModelKey = identity ? identity[1].trim() : 'unknown';
|
||||||
|
const rawDisplayName = chat?.modelDisplayName || '';
|
||||||
|
const isGenericWorkerDisplay =
|
||||||
|
!rawDisplayName ||
|
||||||
|
/\borchestrator\b/i.test(rawDisplayName) ||
|
||||||
|
/^gemini\s+(?:flash|pro)(?:\s+worker)?$/i.test(rawDisplayName.trim());
|
||||||
|
const resolvedDisplayName =
|
||||||
|
(orchestratorExecModels.has(resolvedModelKey) ||
|
||||||
|
/^gemini-flash-worker-agy$/i.test(rawResponseModel || '')) &&
|
||||||
|
isGenericWorkerDisplay
|
||||||
|
? 'Orchestrator Worker (Hydrogen)'
|
||||||
|
: rawDisplayName;
|
||||||
|
|
||||||
result.push({
|
result.push({
|
||||||
stepIndex,
|
stepIndex,
|
||||||
isCompactionStep,
|
isCompactionStep,
|
||||||
modelKey: identity ? identity[1].trim() : 'unknown',
|
modelKey: resolvedModelKey,
|
||||||
modelSource: identity?.[0] || 'unavailable',
|
modelSource: identity?.[0] || 'unavailable',
|
||||||
responseModel: rawResponseModel ? rawResponseModel.trim() : '',
|
responseModel: rawResponseModel ? rawResponseModel.trim() : '',
|
||||||
modelIdentityVersion: MODEL_IDENTITY_VERSION,
|
modelIdentityVersion: MODEL_IDENTITY_VERSION,
|
||||||
modelDisplayName: chat?.modelDisplayName || '',
|
modelDisplayName: resolvedDisplayName,
|
||||||
apiProvider: u.apiProvider || chat?.usage?.apiProvider || '',
|
apiProvider: u.apiProvider || chat?.usage?.apiProvider || '',
|
||||||
createdAt: m.createdAt || null,
|
createdAt: m.createdAt || null,
|
||||||
createdAtMs: Math.floor(start),
|
createdAtMs: Math.floor(start),
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,18 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 交互式 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
|
* @fileoverview 交互式历史用量趋势图组件 (TrendAreaChart).
|
||||||
* 支持:
|
* 支持双模式自适应切换:
|
||||||
* 1. 自适应整点小时(<=72h)与自然日(>72h)高精度分桶序列渲染;
|
* 1. <= 90 天(或整点小时分桶):渲染三次贝塞尔平滑曲线面积图、峰值气泡与对齐多刻度时间轴;
|
||||||
* 2. 鼠标悬停/滑动十字准星探针、高亮圆点与自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数);
|
* 2. > 90 天(自然日分桶):自动切换为类 GitHub 贡献日历的小格子热力排列(一格一天,7 行星期 × 周列、月份刻度、分位数 5 档热力色阶与底部图例);
|
||||||
* 3. 与 SVG 垂直网格线像素级对齐的多刻度底部时间轴(彻底告别首/中/末简单对半切分)。
|
* 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||||
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';
|
||||||
|
|
||||||
|
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
|
||||||
|
export const HEATMAP_DAYS_THRESHOLD = 90;
|
||||||
|
|
||||||
let chartUidCounter = 0;
|
let chartUidCounter = 0;
|
||||||
|
|
||||||
function safeSlotTokens(v) {
|
function safeSlotTokens(v) {
|
||||||
@@ -60,7 +63,128 @@ function computeTickIndices(slots) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建交互式 SVG 历史趋势平滑面积图组件。
|
* 基于非零活跃日的分位数阈值计算热力图 5 档色阶(0 ~ 4),避免单日极端峰值压缩其余活跃日的层次对比。
|
||||||
|
*
|
||||||
|
* @param {number[]} nonZeroValues 已升序排列的正数 Token 列表
|
||||||
|
* @param {number} maxTokens
|
||||||
|
* @returns {{ q1: number, q2: number, q3: number, maxTokens: number, count: number }}
|
||||||
|
*/
|
||||||
|
function computeHeatmapThresholds(nonZeroValues, maxTokens) {
|
||||||
|
const n = nonZeroValues.length;
|
||||||
|
if (n === 0 || maxTokens <= 0) {
|
||||||
|
return { q1: 0, q2: 0, q3: 0, maxTokens: 0, count: 0 };
|
||||||
|
}
|
||||||
|
if (n < 4) {
|
||||||
|
return {
|
||||||
|
q1: maxTokens * 0.25,
|
||||||
|
q2: maxTokens * 0.5,
|
||||||
|
q3: maxTokens * 0.75,
|
||||||
|
maxTokens,
|
||||||
|
count: n,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
q1: nonZeroValues[Math.floor((n - 1) * 0.25)],
|
||||||
|
q2: nonZeroValues[Math.floor((n - 1) * 0.5)],
|
||||||
|
q3: nonZeroValues[Math.floor((n - 1) * 0.75)],
|
||||||
|
maxTokens,
|
||||||
|
count: n,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveHeatmapLevel(tokens, thresholds) {
|
||||||
|
if (tokens <= 0 || thresholds.maxTokens <= 0) return 0;
|
||||||
|
if (tokens >= thresholds.maxTokens || tokens > thresholds.q3) return 4;
|
||||||
|
if (tokens > thresholds.q2) return 3;
|
||||||
|
if (tokens > thresholds.q1) return 2;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析日期槽位的年份与月份信息(兼容真实时间戳 `startMs` 与测试简写 `label`)。
|
||||||
|
*
|
||||||
|
* @param {object} slot
|
||||||
|
* @returns {{ year: number, month: number, day: number }}
|
||||||
|
*/
|
||||||
|
function parseSlotCalendarParts(slot) {
|
||||||
|
const sMs = Number(slot?.startMs);
|
||||||
|
if (Number.isFinite(sMs) && sMs > 0) {
|
||||||
|
const d = new Date(sMs);
|
||||||
|
return { year: d.getFullYear(), month: d.getMonth() + 1, day: d.getDate() };
|
||||||
|
}
|
||||||
|
const m = String(slot?.label || '').match(/^(\d{1,2})\/(\d{1,2})$/);
|
||||||
|
if (m) {
|
||||||
|
return { year: new Date().getFullYear(), month: Number(m[1]), day: Number(m[2]) };
|
||||||
|
}
|
||||||
|
return { year: new Date().getFullYear(), month: 0, day: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建热力图顶部与周列对齐的月份刻度标签(自动跳过首尾过窄残月,防止相邻月份文字重叠)。
|
||||||
|
*
|
||||||
|
* @param {Array<object>} slots
|
||||||
|
* @param {number} firstDow 首日对应的星期行索引(0 = 周一 .. 6 = 周日)
|
||||||
|
* @param {number} totalWeeks 总周列数
|
||||||
|
* @returns {Array<{ col: number, text: string }>}
|
||||||
|
*/
|
||||||
|
function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) {
|
||||||
|
if (!slots.length || totalWeeks <= 0) return [];
|
||||||
|
const firstParts = parseSlotCalendarParts(slots[0]);
|
||||||
|
const lastParts = parseSlotCalendarParts(slots[slots.length - 1]);
|
||||||
|
const crossYear = firstParts.year !== lastParts.year;
|
||||||
|
|
||||||
|
const candidates = [];
|
||||||
|
let prevMonthKey = '';
|
||||||
|
|
||||||
|
for (let col = 0; col < totalWeeks; col++) {
|
||||||
|
let chosenParts = null;
|
||||||
|
for (let row = 0; row < 7; row++) {
|
||||||
|
const idx = col * 7 + row - firstDow;
|
||||||
|
if (idx < 0 || idx >= slots.length) continue;
|
||||||
|
const parts = parseSlotCalendarParts(slots[idx]);
|
||||||
|
if (!parts.month) continue;
|
||||||
|
const mKey = `${parts.year}-${parts.month}`;
|
||||||
|
if (col === 0 && !chosenParts) {
|
||||||
|
chosenParts = parts;
|
||||||
|
prevMonthKey = mKey;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (mKey !== prevMonthKey) {
|
||||||
|
chosenParts = parts;
|
||||||
|
prevMonthKey = mKey;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (chosenParts && chosenParts.month > 0) {
|
||||||
|
candidates.push({ col, year: chosenParts.year, month: chosenParts.month });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseMinGap = totalWeeks > 40 ? 4 : 3;
|
||||||
|
if (
|
||||||
|
candidates.length >= 2 &&
|
||||||
|
candidates[0].col === 0 &&
|
||||||
|
candidates[1].col - candidates[0].col < baseMinGap
|
||||||
|
) {
|
||||||
|
candidates.shift();
|
||||||
|
}
|
||||||
|
|
||||||
|
const ticks = [];
|
||||||
|
let nextAllowedCol = 0;
|
||||||
|
for (let i = 0; i < candidates.length; i++) {
|
||||||
|
const c = candidates[i];
|
||||||
|
if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue;
|
||||||
|
if (ticks.length > 0 && c.col < nextAllowedCol) continue;
|
||||||
|
const showYear = crossYear && (c.month === 1 || ticks.length === 0);
|
||||||
|
const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`;
|
||||||
|
ticks.push({ col: c.col, text });
|
||||||
|
nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap);
|
||||||
|
}
|
||||||
|
return ticks;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建交互式历史趋势组件(<=90 天为 SVG 平滑曲线图,>90 天自动切换为类 GitHub 每日小格子热力图)。
|
||||||
*
|
*
|
||||||
* @returns {{
|
* @returns {{
|
||||||
* el: HTMLElement,
|
* el: HTMLElement,
|
||||||
@@ -68,17 +192,22 @@ function computeTickIndices(slots) {
|
|||||||
* }}
|
* }}
|
||||||
*/
|
*/
|
||||||
export function createTrendAreaChart() {
|
export function createTrendAreaChart() {
|
||||||
const VIEW_W = 460;
|
const DEFAULT_VIEW_W = 460;
|
||||||
const VIEW_H = 120;
|
const VIEW_H = 120;
|
||||||
const LEFT_X = 14;
|
|
||||||
const RIGHT_X = 446;
|
|
||||||
const TOP_Y = 24;
|
const TOP_Y = 24;
|
||||||
const BOTTOM_Y = 102;
|
const BOTTOM_Y = 102;
|
||||||
const SPAN_X = RIGHT_X - LEFT_X;
|
|
||||||
const SPAN_Y = BOTTOM_Y - TOP_Y;
|
const SPAN_Y = BOTTOM_Y - TOP_Y;
|
||||||
|
|
||||||
|
let viewW = DEFAULT_VIEW_W;
|
||||||
|
|
||||||
|
function resolvePlotBounds(w) {
|
||||||
|
const leftX = 1;
|
||||||
|
const rightX = Math.max(leftX + 20, w - 1);
|
||||||
|
return { leftX, rightX, spanX: rightX - leftX };
|
||||||
|
}
|
||||||
|
|
||||||
const svg = document.createElementNS(SVG_NS, 'svg');
|
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||||
svg.setAttribute('viewBox', `0 0 ${VIEW_W} ${VIEW_H}`);
|
svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`);
|
||||||
svg.setAttribute('class', 'trend-svg');
|
svg.setAttribute('class', 'trend-svg');
|
||||||
svg.setAttribute('aria-hidden', 'true');
|
svg.setAttribute('aria-hidden', 'true');
|
||||||
|
|
||||||
@@ -107,16 +236,18 @@ export function createTrendAreaChart() {
|
|||||||
defs.appendChild(grad);
|
defs.appendChild(grad);
|
||||||
svg.appendChild(defs);
|
svg.appendChild(defs);
|
||||||
|
|
||||||
// 背景水平与垂直参考网格线
|
// 背景水平与垂直参考网格线(水平网格全宽贴边铺满 0..viewW)
|
||||||
const hGridGroup = document.createElementNS(SVG_NS, 'g');
|
const hGridGroup = document.createElementNS(SVG_NS, 'g');
|
||||||
hGridGroup.setAttribute('class', 'trend-grid');
|
hGridGroup.setAttribute('class', 'trend-grid');
|
||||||
|
const hGridLines = [];
|
||||||
for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) {
|
for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) {
|
||||||
const line = document.createElementNS(SVG_NS, 'line');
|
const line = document.createElementNS(SVG_NS, 'line');
|
||||||
line.setAttribute('x1', String(LEFT_X));
|
line.setAttribute('x1', '0');
|
||||||
line.setAttribute('y1', String(y));
|
line.setAttribute('y1', String(y));
|
||||||
line.setAttribute('x2', String(RIGHT_X));
|
line.setAttribute('x2', String(viewW));
|
||||||
line.setAttribute('y2', String(y));
|
line.setAttribute('y2', String(y));
|
||||||
hGridGroup.appendChild(line);
|
hGridGroup.appendChild(line);
|
||||||
|
hGridLines.push(line);
|
||||||
}
|
}
|
||||||
svg.appendChild(hGridGroup);
|
svg.appendChild(hGridGroup);
|
||||||
|
|
||||||
@@ -158,7 +289,7 @@ export function createTrendAreaChart() {
|
|||||||
|
|
||||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||||
|
|
||||||
// 悬停详情浮层卡片
|
// 共享悬停详情浮层卡片(曲线图与热力格子图共用)
|
||||||
const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' });
|
const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' });
|
||||||
const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' });
|
const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' });
|
||||||
const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' });
|
const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' });
|
||||||
@@ -175,38 +306,56 @@ export function createTrendAreaChart() {
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
// 底部对齐刻度轴
|
// 底部对齐刻度轴(曲线模式)
|
||||||
const xAxisEl = h('div', { className: 'trend-x-axis' });
|
const xAxisEl = h('div', { className: 'trend-x-axis' });
|
||||||
|
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]);
|
||||||
|
|
||||||
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, tooltipEl, svg]);
|
// 类 GitHub 每日小格子热力图容器(> 90 天模式)
|
||||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [plotStage, xAxisEl]);
|
const weekdayLabels = ['一', '', '三', '', '五', '', '日'];
|
||||||
|
const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [
|
||||||
|
h('span', { className: 'trend-hm-month-spacer' }),
|
||||||
|
...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })),
|
||||||
|
]);
|
||||||
|
const hmMonthsEl = h('div', { className: 'trend-hm-months' });
|
||||||
|
const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' });
|
||||||
|
const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]);
|
||||||
|
const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]);
|
||||||
|
const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]);
|
||||||
|
|
||||||
|
const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' });
|
||||||
|
const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [
|
||||||
|
h('span', { text: '少' }),
|
||||||
|
h('span', { className: 'trend-hm-swatch lv-0' }),
|
||||||
|
h('span', { className: 'trend-hm-swatch lv-1' }),
|
||||||
|
h('span', { className: 'trend-hm-swatch lv-2' }),
|
||||||
|
h('span', { className: 'trend-hm-swatch lv-3' }),
|
||||||
|
h('span', { className: 'trend-hm-swatch lv-4' }),
|
||||||
|
h('span', { text: '多' }),
|
||||||
|
]);
|
||||||
|
const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]);
|
||||||
|
const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [
|
||||||
|
hmBodyEl,
|
||||||
|
hmFooterEl,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [
|
||||||
|
plotStage,
|
||||||
|
xAxisEl,
|
||||||
|
heatmapStage,
|
||||||
|
tooltipEl,
|
||||||
|
]);
|
||||||
|
|
||||||
let currentSlots = [];
|
let currentSlots = [];
|
||||||
let currentPts = [];
|
let currentPts = [];
|
||||||
|
let currentIsHeatmap = false;
|
||||||
|
let currentHeatmapWeeks = 0;
|
||||||
|
let currentCellEls = [];
|
||||||
let tickElsByIdx = new Map();
|
let tickElsByIdx = new Map();
|
||||||
let hoveredIdx = -1;
|
let hoveredIdx = -1;
|
||||||
|
let hoveredCellEl = null;
|
||||||
let lastRenderSig = '';
|
let lastRenderSig = '';
|
||||||
|
|
||||||
function showHoverAtIndex(idx) {
|
function populateTooltipContent(slot) {
|
||||||
if (idx < 0 || idx >= currentSlots.length || !currentPts[idx]) {
|
|
||||||
clearHover();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
hoveredIdx = idx;
|
|
||||||
const slot = currentSlots[idx];
|
|
||||||
const pt = currentPts[idx];
|
|
||||||
|
|
||||||
patchAttr(hoverLine, 'hidden', false);
|
|
||||||
patchAttr(hoverLine, 'x1', pt.x.toFixed(1));
|
|
||||||
patchAttr(hoverLine, 'x2', pt.x.toFixed(1));
|
|
||||||
|
|
||||||
patchAttr(hoverDot, 'hidden', false);
|
|
||||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
|
||||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
|
||||||
|
|
||||||
patchAttr(peakPill, 'hidden', true);
|
|
||||||
patchAttr(tooltipEl, 'hidden', false);
|
|
||||||
|
|
||||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||||
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`);
|
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`);
|
||||||
const slotTok = safeSlotTokens(slot.tokens);
|
const slotTok = safeSlotTokens(slot.tokens);
|
||||||
@@ -231,47 +380,219 @@ export function createTrendAreaChart() {
|
|||||||
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}`
|
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const rawPct = (pt.x / VIEW_W) * 100;
|
function showLineHoverAtIndex(idx) {
|
||||||
const clampedPct = Math.max(2, Math.min(98, rawPct));
|
if (currentIsHeatmap || idx < 0 || idx >= currentSlots.length || !currentPts[idx]) {
|
||||||
const shiftX = rawPct < 28 ? '0%' : rawPct > 72 ? '-100%' : '-50%';
|
clearHover();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hoveredIdx = idx;
|
||||||
|
const slot = currentSlots[idx];
|
||||||
|
const pt = currentPts[idx];
|
||||||
|
|
||||||
|
patchAttr(hoverLine, 'hidden', false);
|
||||||
|
patchAttr(hoverLine, 'x1', pt.x.toFixed(1));
|
||||||
|
patchAttr(hoverLine, 'x2', pt.x.toFixed(1));
|
||||||
|
|
||||||
|
patchAttr(hoverDot, 'hidden', false);
|
||||||
|
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||||
|
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||||
|
|
||||||
|
patchAttr(peakPill, 'hidden', true);
|
||||||
|
patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false });
|
||||||
|
patchAttr(tooltipEl, 'hidden', false);
|
||||||
|
populateTooltipContent(slot);
|
||||||
|
|
||||||
|
const rawPct = (pt.x / viewW) * 100;
|
||||||
|
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||||
patchStyleVar(tooltipEl, '--tip-shift', shiftX);
|
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||||
|
|
||||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function showHeatmapHoverAtIndex(idx, cellEl) {
|
||||||
|
if (!currentIsHeatmap || idx < 0 || idx >= currentSlots.length) {
|
||||||
|
clearHover();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const targetCell = cellEl || currentCellEls[idx] || null;
|
||||||
|
if (!targetCell) {
|
||||||
|
clearHover();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hoveredIdx = idx;
|
||||||
|
if (hoveredCellEl && hoveredCellEl !== targetCell) {
|
||||||
|
patchClasses(hoveredCellEl, { 'is-hovered': false });
|
||||||
|
}
|
||||||
|
hoveredCellEl = targetCell;
|
||||||
|
patchClasses(targetCell, { 'is-hovered': true });
|
||||||
|
|
||||||
|
const slot = currentSlots[idx];
|
||||||
|
const row = Number(targetCell.getAttribute('data-hm-row') || 0);
|
||||||
|
const col = Number(targetCell.getAttribute('data-hm-col') || 0);
|
||||||
|
|
||||||
|
// 上半区(周一~周四)浮层停靠底部,下半区(周五~周日)停靠顶部,互不遮挡被悬停格子且永不越界裁剪
|
||||||
|
patchClasses(tooltipEl, {
|
||||||
|
'is-hm-bottom': row <= 3,
|
||||||
|
'is-hm-top': row > 3,
|
||||||
|
});
|
||||||
|
patchAttr(tooltipEl, 'hidden', false);
|
||||||
|
populateTooltipContent(slot);
|
||||||
|
|
||||||
|
const wrapRect = chartWrap.getBoundingClientRect();
|
||||||
|
const cellRect = targetCell.getBoundingClientRect();
|
||||||
|
let rawPct = 50;
|
||||||
|
if (
|
||||||
|
wrapRect &&
|
||||||
|
wrapRect.width > 0 &&
|
||||||
|
cellRect &&
|
||||||
|
cellRect.width > 0 &&
|
||||||
|
cellRect.width < wrapRect.width
|
||||||
|
) {
|
||||||
|
rawPct = ((cellRect.left + cellRect.width / 2 - wrapRect.left) / wrapRect.width) * 100;
|
||||||
|
} else if (currentHeatmapWeeks > 0) {
|
||||||
|
rawPct = ((col + 0.5) / currentHeatmapWeeks) * 100;
|
||||||
|
}
|
||||||
|
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||||
|
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||||
|
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||||
|
}
|
||||||
|
|
||||||
function clearHover() {
|
function clearHover() {
|
||||||
hoveredIdx = -1;
|
hoveredIdx = -1;
|
||||||
patchAttr(hoverLine, 'hidden', true);
|
patchAttr(hoverLine, 'hidden', true);
|
||||||
patchAttr(hoverDot, 'hidden', true);
|
patchAttr(hoverDot, 'hidden', true);
|
||||||
patchAttr(tooltipEl, 'hidden', true);
|
patchAttr(tooltipEl, 'hidden', true);
|
||||||
|
patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false });
|
||||||
|
if (!currentIsHeatmap) {
|
||||||
patchAttr(peakPill, 'hidden', false);
|
patchAttr(peakPill, 'hidden', false);
|
||||||
|
}
|
||||||
|
if (hoveredCellEl) {
|
||||||
|
patchClasses(hoveredCellEl, { 'is-hovered': false });
|
||||||
|
hoveredCellEl = null;
|
||||||
|
}
|
||||||
for (const el of tickElsByIdx.values()) {
|
for (const el of tickElsByIdx.values()) {
|
||||||
patchClasses(el, { 'is-hovered': false });
|
patchClasses(el, { 'is-hovered': false });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function syncViewWidth() {
|
||||||
|
const measured = Math.round(
|
||||||
|
plotStage.clientWidth ||
|
||||||
|
svg.clientWidth ||
|
||||||
|
plotStage.getBoundingClientRect?.()?.width ||
|
||||||
|
0
|
||||||
|
);
|
||||||
|
if (measured >= 160 && measured !== viewW) {
|
||||||
|
viewW = measured;
|
||||||
|
svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`);
|
||||||
|
for (const line of hGridLines) {
|
||||||
|
line.setAttribute('x1', '0');
|
||||||
|
line.setAttribute('x2', String(viewW));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
function handlePointerMove(e) {
|
function handlePointerMove(e) {
|
||||||
if (!currentSlots.length) return;
|
if (currentIsHeatmap || !currentSlots.length) return;
|
||||||
const rect = svg.getBoundingClientRect();
|
const rect = svg.getBoundingClientRect();
|
||||||
if (!rect || rect.width <= 0) return;
|
if (!rect || rect.width <= 0) return;
|
||||||
const relX = ((e.clientX - rect.left) / rect.width) * VIEW_W;
|
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||||
const ratio = (relX - LEFT_X) / Math.max(1, SPAN_X);
|
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||||
|
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||||
const idx = Math.max(
|
const idx = Math.max(
|
||||||
0,
|
0,
|
||||||
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
||||||
);
|
);
|
||||||
showHoverAtIndex(idx);
|
showLineHoverAtIndex(idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findHeatmapCellFromEvent(e) {
|
||||||
|
let cur = e?.target || null;
|
||||||
|
while (cur && cur !== hmGridEl) {
|
||||||
|
const idxAttr = cur.getAttribute?.('data-slot-idx');
|
||||||
|
if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') {
|
||||||
|
return { idx: Number(idxAttr), cellEl: cur };
|
||||||
|
}
|
||||||
|
cur = cur.parentNode || null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleHeatmapPointer(e) {
|
||||||
|
if (!currentIsHeatmap || !currentSlots.length) return;
|
||||||
|
const hit = findHeatmapCellFromEvent(e);
|
||||||
|
if (!hit || !Number.isFinite(hit.idx)) {
|
||||||
|
clearHover();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (hit.idx !== hoveredIdx || hit.cellEl !== hoveredCellEl) {
|
||||||
|
showHeatmapHoverAtIndex(hit.idx, hit.cellEl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleHeatmapWheel(e) {
|
||||||
|
if (!currentIsHeatmap) return;
|
||||||
|
const maxScrollLeft = (hmScrollEl.scrollWidth || 0) - (hmScrollEl.clientWidth || 0);
|
||||||
|
if (maxScrollLeft <= 2) return;
|
||||||
|
const dy = Number(e.deltaY || 0);
|
||||||
|
const dx = Number(e.deltaX || 0);
|
||||||
|
if (Math.abs(dy) > Math.abs(dx) && dy !== 0) {
|
||||||
|
const prev = hmScrollEl.scrollLeft || 0;
|
||||||
|
const next = Math.max(0, Math.min(maxScrollLeft, prev + dy));
|
||||||
|
if (next !== prev) {
|
||||||
|
hmScrollEl.scrollLeft = next;
|
||||||
|
e.preventDefault?.();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
plotStage.addEventListener('mousemove', handlePointerMove);
|
plotStage.addEventListener('mousemove', handlePointerMove);
|
||||||
plotStage.addEventListener('mouseleave', clearHover);
|
plotStage.addEventListener('mouseleave', clearHover);
|
||||||
|
|
||||||
|
hmGridEl.addEventListener('mouseover', handleHeatmapPointer);
|
||||||
|
hmGridEl.addEventListener('mousemove', handleHeatmapPointer);
|
||||||
|
hmGridEl.addEventListener('click', handleHeatmapPointer);
|
||||||
|
hmGridEl.addEventListener('mouseleave', clearHover);
|
||||||
|
hmScrollEl.addEventListener('wheel', handleHeatmapWheel);
|
||||||
|
|
||||||
|
let resizeObs = null;
|
||||||
|
let onWinResize = null;
|
||||||
|
if (typeof ResizeObserver === 'function') {
|
||||||
|
resizeObs = new ResizeObserver(() => {
|
||||||
|
if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) {
|
||||||
|
lastRenderSig = '';
|
||||||
|
update(currentSlots);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
resizeObs.observe(plotStage);
|
||||||
|
} else if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
|
||||||
|
onWinResize = () => {
|
||||||
|
if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) {
|
||||||
|
lastRenderSig = '';
|
||||||
|
update(currentSlots);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener('resize', onWinResize);
|
||||||
|
}
|
||||||
|
|
||||||
|
function destroy() {
|
||||||
|
resizeObs?.disconnect();
|
||||||
|
resizeObs = null;
|
||||||
|
if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
|
||||||
|
window.removeEventListener('resize', onWinResize);
|
||||||
|
onWinResize = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据最新时间分桶序列重绘平滑曲线、渐变区域、峰值气泡与底部对齐刻度。
|
* 根据最新时间分桶序列重绘平滑曲线(<=90天/小时级)或类 GitHub 每日小格子热力图(>90天)。
|
||||||
*/
|
*/
|
||||||
function update(series = []) {
|
function update(series = []) {
|
||||||
const slots =
|
const slots =
|
||||||
@@ -285,39 +606,155 @@ export function createTrendAreaChart() {
|
|||||||
];
|
];
|
||||||
currentSlots = slots;
|
currentSlots = slots;
|
||||||
|
|
||||||
|
const isHourly =
|
||||||
|
slots[0]?.granularity === 'hour' || String(slots[0]?.label || '').includes(':');
|
||||||
|
const useHeatmap = !isHourly && slots.length > HEATMAP_DAYS_THRESHOLD;
|
||||||
|
const modeChanged = useHeatmap !== currentIsHeatmap;
|
||||||
|
currentIsHeatmap = useHeatmap;
|
||||||
|
|
||||||
|
if (modeChanged) {
|
||||||
|
clearHover();
|
||||||
|
}
|
||||||
|
patchClasses(chartWrap, { 'is-heatmap': useHeatmap });
|
||||||
|
patchAttr(plotStage, 'hidden', useHeatmap);
|
||||||
|
patchAttr(xAxisEl, 'hidden', useHeatmap);
|
||||||
|
patchAttr(heatmapStage, 'hidden', !useHeatmap);
|
||||||
|
|
||||||
|
if (!useHeatmap) {
|
||||||
|
syncViewWidth();
|
||||||
|
}
|
||||||
|
|
||||||
let maxTokens = 0;
|
let maxTokens = 0;
|
||||||
let peakIdx = 0;
|
let peakIdx = 0;
|
||||||
|
let activeDays = 0;
|
||||||
|
const nonZeroVals = [];
|
||||||
|
|
||||||
for (let i = 0; i < slots.length; i++) {
|
for (let i = 0; i < slots.length; i++) {
|
||||||
const t = safeSlotTokens(slots[i]?.tokens);
|
const t = safeSlotTokens(slots[i]?.tokens);
|
||||||
|
if (t > 0) {
|
||||||
|
activeDays++;
|
||||||
|
nonZeroVals.push(t);
|
||||||
|
}
|
||||||
if (t >= maxTokens) {
|
if (t >= maxTokens) {
|
||||||
maxTokens = t;
|
maxTokens = t;
|
||||||
peakIdx = i;
|
peakIdx = i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sig =
|
||||||
|
`${useHeatmap ? 'hm' : `line:${viewW}`}|` +
|
||||||
|
slots
|
||||||
|
.map(
|
||||||
|
(s) =>
|
||||||
|
`${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`
|
||||||
|
)
|
||||||
|
.join('|');
|
||||||
|
|
||||||
|
if (useHeatmap) {
|
||||||
|
currentPts = [];
|
||||||
|
if (sig !== lastRenderSig) {
|
||||||
|
lastRenderSig = sig;
|
||||||
|
nonZeroVals.sort((a, b) => a - b);
|
||||||
|
const thresholds = computeHeatmapThresholds(nonZeroVals, maxTokens);
|
||||||
|
|
||||||
|
const firstStartMs = Number(slots[0]?.startMs);
|
||||||
|
const firstDow =
|
||||||
|
Number.isFinite(firstStartMs) && firstStartMs > 0
|
||||||
|
? (new Date(firstStartMs).getDay() + 6) % 7
|
||||||
|
: 0;
|
||||||
|
const totalCells = firstDow + slots.length;
|
||||||
|
const totalWeeks = Math.max(1, Math.ceil(totalCells / 7));
|
||||||
|
currentHeatmapWeeks = totalWeeks;
|
||||||
|
|
||||||
|
patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks));
|
||||||
|
patchStyleVar(hmBodyEl, '--hm-gap', totalWeeks > 42 ? '1.5px' : '2px');
|
||||||
|
|
||||||
|
// 重建顶部对齐月份标签
|
||||||
|
while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild);
|
||||||
|
const monthTicks = buildHeatmapMonthTicks(slots, firstDow, totalWeeks);
|
||||||
|
for (const mt of monthTicks) {
|
||||||
|
const mEl = h('span', { className: 'trend-hm-month text-mono', text: mt.text });
|
||||||
|
patchStyleVar(mEl, '--hm-col', String(mt.col));
|
||||||
|
hmMonthsEl.appendChild(mEl);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重建 7 行 × N 周列的每日小格子(一格一天)
|
||||||
|
while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild);
|
||||||
|
hoveredCellEl = null;
|
||||||
|
currentCellEls = new Array(slots.length);
|
||||||
|
|
||||||
|
for (let pad = 0; pad < firstDow; pad++) {
|
||||||
|
hmGridEl.appendChild(
|
||||||
|
h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 0; i < slots.length; i++) {
|
||||||
|
const slot = slots[i];
|
||||||
|
const tok = safeSlotTokens(slot?.tokens);
|
||||||
|
const lv = resolveHeatmapLevel(tok, thresholds);
|
||||||
|
const gridPos = firstDow + i;
|
||||||
|
const col = Math.floor(gridPos / 7);
|
||||||
|
const row = gridPos % 7;
|
||||||
|
const cellEl = h('span', {
|
||||||
|
className: `trend-hm-cell lv-${lv}`,
|
||||||
|
'data-slot-idx': String(i),
|
||||||
|
'data-hm-col': String(col),
|
||||||
|
'data-hm-row': String(row),
|
||||||
|
role: 'gridcell',
|
||||||
|
});
|
||||||
|
hmGridEl.appendChild(cellEl);
|
||||||
|
currentCellEls[i] = cellEl;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof requestAnimationFrame === 'function') {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (hmScrollEl.scrollWidth > hmScrollEl.clientWidth) {
|
||||||
|
hmScrollEl.scrollLeft = hmScrollEl.scrollWidth;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const peakSlot = slots[peakIdx];
|
||||||
|
const summaryText =
|
||||||
|
maxTokens > 0 && peakSlot?.label
|
||||||
|
? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
||||||
|
: `活跃 0/${slots.length} 天`;
|
||||||
|
patchText(hmSummaryEl, summaryText);
|
||||||
|
|
||||||
|
if (hoveredIdx >= slots.length) {
|
||||||
|
clearHover();
|
||||||
|
} else if (hoveredIdx >= 0) {
|
||||||
|
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx]);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- <= 90 天(或整点小时级):渲染平滑面积曲线图(1:1 贴边对齐) ---
|
||||||
|
currentCellEls = [];
|
||||||
|
const { leftX, rightX, spanX } = resolvePlotBounds(viewW);
|
||||||
const denom = Math.max(1, maxTokens);
|
const denom = Math.max(1, maxTokens);
|
||||||
const isSingle = slots.length === 1;
|
const isSingle = slots.length === 1;
|
||||||
const pts = slots.map((s, idx) => {
|
const pts = slots.map((s, idx) => {
|
||||||
const tok = safeSlotTokens(s?.tokens);
|
const tok = safeSlotTokens(s?.tokens);
|
||||||
const x = isSingle ? (LEFT_X + RIGHT_X) / 2 : LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
|
const x = isSingle
|
||||||
|
? (leftX + rightX) / 2
|
||||||
|
: leftX + (idx / Math.max(1, slots.length - 1)) * spanX;
|
||||||
const ratio = maxTokens > 0 ? tok / denom : 0;
|
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: tok };
|
return { x, y, tokens: tok };
|
||||||
});
|
});
|
||||||
currentPts = pts;
|
currentPts = pts;
|
||||||
|
|
||||||
const sig = slots
|
|
||||||
.map((s) => `${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`)
|
|
||||||
.join('|');
|
|
||||||
|
|
||||||
if (sig !== lastRenderSig) {
|
if (sig !== lastRenderSig) {
|
||||||
lastRenderSig = sig;
|
lastRenderSig = sig;
|
||||||
let lineD;
|
let lineD;
|
||||||
let areaD;
|
let areaD;
|
||||||
if (isSingle) {
|
if (isSingle) {
|
||||||
const yStr = pts[0].y.toFixed(1);
|
const yStr = pts[0].y.toFixed(1);
|
||||||
lineD = `M ${LEFT_X.toFixed(1)} ${yStr} L ${RIGHT_X.toFixed(1)} ${yStr}`;
|
lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`;
|
||||||
areaD = `${lineD} L ${RIGHT_X.toFixed(1)} ${BOTTOM_Y} L ${LEFT_X.toFixed(1)} ${BOTTOM_Y} Z`;
|
areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||||
} else {
|
} else {
|
||||||
lineD = buildSmoothSplinePath(pts);
|
lineD = buildSmoothSplinePath(pts);
|
||||||
areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||||
@@ -325,7 +762,7 @@ export function createTrendAreaChart() {
|
|||||||
patchAttr(linePath, 'd', lineD);
|
patchAttr(linePath, 'd', lineD);
|
||||||
patchAttr(areaPath, 'd', areaD);
|
patchAttr(areaPath, 'd', areaD);
|
||||||
|
|
||||||
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签
|
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边)
|
||||||
const tickIndices = computeTickIndices(slots);
|
const tickIndices = computeTickIndices(slots);
|
||||||
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
|
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
|
||||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||||
@@ -348,14 +785,14 @@ export function createTrendAreaChart() {
|
|||||||
|
|
||||||
const isFirst = !isSingle && i === 0;
|
const isFirst = !isSingle && i === 0;
|
||||||
const isLast = !isSingle && i === tickIndices.length - 1;
|
const isLast = !isSingle && i === tickIndices.length - 1;
|
||||||
const pct = (pt.x / VIEW_W) * 100;
|
const pct = isFirst ? 0 : isLast ? 100 : (pt.x / viewW) * 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' : ''}`,
|
||||||
text: slot.label || '',
|
text: slot.label || '',
|
||||||
title: slot.fullLabel || slot.label || '',
|
title: slot.fullLabel || slot.label || '',
|
||||||
});
|
});
|
||||||
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
|
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
|
||||||
tickEl.onclick = () => showHoverAtIndex(tIdx);
|
tickEl.onclick = () => showLineHoverAtIndex(tIdx);
|
||||||
xAxisEl.appendChild(tickEl);
|
xAxisEl.appendChild(tickEl);
|
||||||
tickElsByIdx.set(tIdx, tickEl);
|
tickElsByIdx.set(tIdx, tickEl);
|
||||||
}
|
}
|
||||||
@@ -375,7 +812,7 @@ export function createTrendAreaChart() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const peakPt = pts[peakIdx] || { x: 230, y: BOTTOM_Y };
|
const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y };
|
||||||
patchAttr(peakDot, 'cx', peakPt.x.toFixed(1));
|
patchAttr(peakDot, 'cx', peakPt.x.toFixed(1));
|
||||||
patchAttr(peakDot, 'cy', peakPt.y.toFixed(1));
|
patchAttr(peakDot, 'cy', peakPt.y.toFixed(1));
|
||||||
|
|
||||||
@@ -385,15 +822,15 @@ export function createTrendAreaChart() {
|
|||||||
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
||||||
: formatTokensPrecise(maxTokens);
|
: formatTokensPrecise(maxTokens);
|
||||||
patchText(peakPill, peakText);
|
patchText(peakPill, peakText);
|
||||||
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100));
|
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100));
|
||||||
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
||||||
|
|
||||||
if (hoveredIdx >= slots.length) {
|
if (hoveredIdx >= slots.length) {
|
||||||
clearHover();
|
clearHover();
|
||||||
} else if (hoveredIdx >= 0) {
|
} else if (hoveredIdx >= 0) {
|
||||||
showHoverAtIndex(hoveredIdx);
|
showLineHoverAtIndex(hoveredIdx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { el: chartWrap, update };
|
return { el: chartWrap, update, destroy };
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview Bespoke CustomSelect dropdown component replacing native <select> / <option>.
|
* @fileoverview Bespoke CustomSelect dropdown component replacing native <select> / <option>.
|
||||||
* Supports incremental option patching while open without losing focus or closing the menu.
|
* Supports both single-select and multi-select (`multiple: true`) modes, with incremental
|
||||||
|
* option patching while open without losing focus or closing the menu.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { defineComponent } from '../../core/component.js';
|
import { defineComponent } from '../../core/component.js';
|
||||||
@@ -14,6 +15,40 @@ import {
|
|||||||
} from '../../core/domPatch.js';
|
} from '../../core/domPatch.js';
|
||||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
|
|
||||||
|
function normalizeMultiSelection(rawValue, options = [], allValue = '') {
|
||||||
|
const arr = Array.isArray(rawValue)
|
||||||
|
? rawValue
|
||||||
|
: rawValue !== undefined && rawValue !== null && rawValue !== ''
|
||||||
|
? [rawValue]
|
||||||
|
: [];
|
||||||
|
const clean = [];
|
||||||
|
const seen = new Set();
|
||||||
|
for (const item of arr) {
|
||||||
|
const str = String(item ?? '');
|
||||||
|
if (!str || seen.has(str)) continue;
|
||||||
|
seen.add(str);
|
||||||
|
clean.push(str);
|
||||||
|
}
|
||||||
|
if (allValue && (clean.length === 0 || clean.includes(allValue))) {
|
||||||
|
return [allValue];
|
||||||
|
}
|
||||||
|
if (options.length > 0) {
|
||||||
|
const validSet = new Set(options.map((o) => String(o.value)));
|
||||||
|
const filtered = clean.filter((v) => validSet.has(v));
|
||||||
|
if (filtered.length > 0) return filtered;
|
||||||
|
return allValue ? [allValue] : [];
|
||||||
|
}
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameStringArray(a, b) {
|
||||||
|
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
if (a[i] !== b[i]) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
export const CustomSelect = defineComponent({
|
export const CustomSelect = defineComponent({
|
||||||
name: 'CustomSelect',
|
name: 'CustomSelect',
|
||||||
setup({ getProps, setProps, emit, onCleanup }) {
|
setup({ getProps, setProps, emit, onCleanup }) {
|
||||||
@@ -49,9 +84,23 @@ export const CustomSelect = defineComponent({
|
|||||||
hidden: true,
|
hidden: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const initialClass = ['custom-select', getProps().className].filter(Boolean).join(' ');
|
const initialClass = [
|
||||||
|
'custom-select',
|
||||||
|
getProps().multiple ? 'is-multi' : '',
|
||||||
|
getProps().className,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ');
|
||||||
const rootEl = h('div', { className: initialClass }, [triggerBtn, menuEl]);
|
const rootEl = h('div', { className: initialClass }, [triggerBtn, menuEl]);
|
||||||
|
|
||||||
|
function getSelectedSet() {
|
||||||
|
const { multiple, modelValue, options = [], allValue = '' } = getProps();
|
||||||
|
if (!multiple) {
|
||||||
|
return new Set(modelValue !== undefined && modelValue !== null ? [modelValue] : []);
|
||||||
|
}
|
||||||
|
return new Set(normalizeMultiSelection(modelValue, options, allValue));
|
||||||
|
}
|
||||||
|
|
||||||
function toggleOpen(nextOpen) {
|
function toggleOpen(nextOpen) {
|
||||||
isOpen = Boolean(nextOpen);
|
isOpen = Boolean(nextOpen);
|
||||||
patchClasses(rootEl, { 'is-open': isOpen });
|
patchClasses(rootEl, { 'is-open': isOpen });
|
||||||
@@ -60,10 +109,10 @@ export const CustomSelect = defineComponent({
|
|||||||
patchSvgIcon(chevronIcon, isOpen ? 'chevron-up' : 'chevron-down');
|
patchSvgIcon(chevronIcon, isOpen ? 'chevron-up' : 'chevron-down');
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
const opts = getProps().options || [];
|
const opts = getProps().options || [];
|
||||||
const currentVal = getProps().modelValue;
|
const selSet = getSelectedSet();
|
||||||
focusedIndex = Math.max(
|
focusedIndex = Math.max(
|
||||||
0,
|
0,
|
||||||
opts.findIndex((o) => o.value === currentVal)
|
opts.findIndex((o) => selSet.has(o.value))
|
||||||
);
|
);
|
||||||
renderMenuOptions();
|
renderMenuOptions();
|
||||||
}
|
}
|
||||||
@@ -71,12 +120,48 @@ export const CustomSelect = defineComponent({
|
|||||||
|
|
||||||
function chooseOption(option) {
|
function chooseOption(option) {
|
||||||
if (!option) return;
|
if (!option) return;
|
||||||
|
const { multiple, options = [], allValue = '', collapseAll = false } = getProps();
|
||||||
|
if (!multiple) {
|
||||||
const prevVal = getProps().modelValue;
|
const prevVal = getProps().modelValue;
|
||||||
toggleOpen(false);
|
toggleOpen(false);
|
||||||
if (option.value !== prevVal) {
|
if (option.value !== prevVal) {
|
||||||
setProps({ modelValue: option.value });
|
setProps({ modelValue: option.value });
|
||||||
emit('update:modelValue', option.value);
|
emit('update:modelValue', option.value);
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevList = normalizeMultiSelection(getProps().modelValue, options, allValue);
|
||||||
|
const val = String(option.value);
|
||||||
|
let nextList;
|
||||||
|
if (allValue && val === allValue) {
|
||||||
|
nextList = [allValue];
|
||||||
|
} else {
|
||||||
|
const base = prevList.filter((v) => v !== allValue);
|
||||||
|
if (base.includes(val)) {
|
||||||
|
const rest = base.filter((v) => v !== val);
|
||||||
|
nextList = rest.length > 0 ? rest : allValue ? [allValue] : [val];
|
||||||
|
} else {
|
||||||
|
const addedSet = new Set([...base, val]);
|
||||||
|
const ordered = options
|
||||||
|
.filter((o) => String(o.value) !== allValue && addedSet.has(String(o.value)))
|
||||||
|
.map((o) => String(o.value));
|
||||||
|
nextList = ordered.length > 0 ? ordered : [...base, val];
|
||||||
|
if (collapseAll && allValue) {
|
||||||
|
const nonAllTotal = options.filter((o) => String(o.value) !== allValue).length;
|
||||||
|
if (nonAllTotal > 0 && nextList.length >= nonAllTotal) {
|
||||||
|
nextList = [allValue];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sameStringArray(prevList, nextList)) {
|
||||||
|
setProps({ modelValue: nextList });
|
||||||
|
emit('update:modelValue', nextList);
|
||||||
|
} else {
|
||||||
|
renderMenuOptions();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleKeydown(e) {
|
function handleKeydown(e) {
|
||||||
@@ -101,7 +186,7 @@ export const CustomSelect = defineComponent({
|
|||||||
renderMenuOptions();
|
renderMenuOptions();
|
||||||
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||||
}
|
}
|
||||||
} else if (e.key === 'Enter' && isOpen) {
|
} else if ((e.key === 'Enter' || (e.key === ' ' && isOpen && getProps().multiple)) && isOpen) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const target = opts[focusedIndex];
|
const target = opts[focusedIndex];
|
||||||
if (target) chooseOption(target);
|
if (target) chooseOption(target);
|
||||||
@@ -112,14 +197,20 @@ export const CustomSelect = defineComponent({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderMenuOptions() {
|
function renderMenuOptions() {
|
||||||
const { options = [], modelValue } = getProps();
|
const { options = [], multiple = false } = getProps();
|
||||||
|
const selSet = getSelectedSet();
|
||||||
|
patchAttr(menuEl, 'aria-multiselectable', multiple ? 'true' : null);
|
||||||
patchKeyedList(menuEl, options, {
|
patchKeyedList(menuEl, options, {
|
||||||
keyFn: (opt) => opt.value,
|
keyFn: (opt) => opt.value,
|
||||||
sigFn: (opt, idx) =>
|
sigFn: (opt, idx) =>
|
||||||
`${opt.value}::${opt.label}::${opt.meta || ''}::${opt.value === modelValue}::${idx === focusedIndex}`,
|
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
|
||||||
createRow: (opt) => {
|
createRow: (opt) => {
|
||||||
|
const checkboxIcon = createSvgIcon('check', { size: 10 });
|
||||||
|
const checkboxBox = h('span', { className: 'select-checkbox', hidden: true }, [
|
||||||
|
checkboxIcon,
|
||||||
|
]);
|
||||||
const textSpan = h('span', { className: 'select-option-text' });
|
const textSpan = h('span', { className: 'select-option-text' });
|
||||||
const metaSpan = h('span', { className: 'text-muted' });
|
const metaSpan = h('span', { className: 'text-muted select-option-meta' });
|
||||||
const checkIcon = createSvgIcon('check', { size: 12 });
|
const checkIcon = createSvgIcon('check', { size: 12 });
|
||||||
const btn = h(
|
const btn = h(
|
||||||
'button',
|
'button',
|
||||||
@@ -129,21 +220,26 @@ export const CustomSelect = defineComponent({
|
|||||||
className: 'select-option',
|
className: 'select-option',
|
||||||
onClick: (e) => {
|
onClick: (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
const latestOpt = (getProps().options || []).find((o) => o.value === opt.value) || opt;
|
const latestOpt =
|
||||||
|
(getProps().options || []).find((o) => o.value === opt.value) || opt;
|
||||||
chooseOption(latestOpt);
|
chooseOption(latestOpt);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
[textSpan, metaSpan, checkIcon]
|
[checkboxBox, textSpan, metaSpan, checkIcon]
|
||||||
);
|
);
|
||||||
return { el: btn, refs: { textSpan, metaSpan, checkIcon } };
|
return { el: btn, refs: { checkboxBox, checkboxIcon, textSpan, metaSpan, checkIcon } };
|
||||||
},
|
},
|
||||||
updateRow: (refs, opt, idx, el) => {
|
updateRow: (refs, opt, idx, el) => {
|
||||||
const selected = opt.value === modelValue;
|
const isMulti = Boolean(getProps().multiple);
|
||||||
|
const selected = selSet.has(opt.value);
|
||||||
const focused = idx === focusedIndex;
|
const focused = idx === focusedIndex;
|
||||||
|
patchAttr(refs.checkboxBox, 'hidden', !isMulti);
|
||||||
|
patchClasses(refs.checkboxBox, { 'is-checked': selected });
|
||||||
|
patchAttr(refs.checkboxIcon, 'hidden', !selected);
|
||||||
patchText(refs.textSpan, opt.label);
|
patchText(refs.textSpan, opt.label);
|
||||||
patchText(refs.metaSpan, opt.meta || '');
|
patchText(refs.metaSpan, opt.meta || '');
|
||||||
patchAttr(refs.metaSpan, 'hidden', !opt.meta);
|
patchAttr(refs.metaSpan, 'hidden', !opt.meta);
|
||||||
patchAttr(refs.checkIcon, 'hidden', !selected);
|
patchAttr(refs.checkIcon, 'hidden', isMulti || !selected);
|
||||||
patchClasses(el, {
|
patchClasses(el, {
|
||||||
'is-selected': selected,
|
'is-selected': selected,
|
||||||
'is-focused': focused,
|
'is-focused': focused,
|
||||||
@@ -155,17 +251,51 @@ export const CustomSelect = defineComponent({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function syncTriggerAndMenu() {
|
function syncTriggerAndMenu() {
|
||||||
const { options = [], modelValue, placeholder = '请选择', icon } = getProps();
|
const {
|
||||||
|
options = [],
|
||||||
|
modelValue,
|
||||||
|
placeholder = '请选择',
|
||||||
|
icon,
|
||||||
|
multiple = false,
|
||||||
|
allValue = '',
|
||||||
|
multiUnit = '项',
|
||||||
|
} = getProps();
|
||||||
|
patchClasses(rootEl, { 'is-multi': Boolean(multiple) });
|
||||||
patchAttr(leadIcon, 'hidden', !icon);
|
patchAttr(leadIcon, 'hidden', !icon);
|
||||||
if (icon) {
|
if (icon) {
|
||||||
patchSvgIcon(leadIcon, icon);
|
patchSvgIcon(leadIcon, icon);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let labelText = placeholder;
|
||||||
|
let titleText = placeholder;
|
||||||
|
|
||||||
|
if (multiple) {
|
||||||
|
const vals = normalizeMultiSelection(modelValue, options, allValue);
|
||||||
|
if ((allValue && vals.includes(allValue)) || vals.length === 0) {
|
||||||
|
const allOpt = options.find((o) => String(o.value) === allValue);
|
||||||
|
labelText = allOpt ? allOpt.label : placeholder;
|
||||||
|
titleText = labelText;
|
||||||
|
} else if (vals.length === 1) {
|
||||||
|
const singleOpt = options.find((o) => String(o.value) === vals[0]);
|
||||||
|
labelText = singleOpt ? singleOpt.label : vals[0];
|
||||||
|
titleText = labelText;
|
||||||
|
} else {
|
||||||
|
const names = vals.map((v) => options.find((o) => String(o.value) === v)?.label || v);
|
||||||
|
labelText = `已选 ${vals.length} ${multiUnit}`;
|
||||||
|
titleText = `已选 (${vals.length}):${names.join('、')}`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
const matchedOpt = options.find((o) => o.value === modelValue);
|
const matchedOpt = options.find((o) => o.value === modelValue);
|
||||||
const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined);
|
const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined);
|
||||||
const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder;
|
const fallbackText = modelValue
|
||||||
const labelText = selectedOpt ? selectedOpt.label : fallbackText;
|
? `${placeholder} (${String(modelValue).slice(0, 8)})`
|
||||||
|
: placeholder;
|
||||||
|
labelText = selectedOpt ? selectedOpt.label : fallbackText;
|
||||||
|
titleText = labelText;
|
||||||
|
}
|
||||||
|
|
||||||
patchText(triggerLabel, labelText);
|
patchText(triggerLabel, labelText);
|
||||||
patchAttr(triggerBtn, 'title', labelText);
|
patchAttr(triggerBtn, 'title', titleText);
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
renderMenuOptions();
|
renderMenuOptions();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,9 @@ export function formatCnyApprox(usdAmount, rate = 7.2) {
|
|||||||
export function formatDateSpanBadge(startMs, endMs) {
|
export function formatDateSpanBadge(startMs, endMs) {
|
||||||
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
|
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
|
||||||
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date();
|
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date();
|
||||||
|
if (s.getFullYear() !== e.getFullYear()) {
|
||||||
|
return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`;
|
||||||
|
}
|
||||||
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
|
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,3 +103,267 @@ export function formatElapsedSec(seconds) {
|
|||||||
const remM = m % 60;
|
const remM = m % 60;
|
||||||
return `${h}h ${remM}m`;
|
return `${h}h ${remM}m`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @returns {'compact'|'full'}
|
||||||
|
*/
|
||||||
|
export function normalizeOrchestratorIdDisplayMode(mode) {
|
||||||
|
return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。
|
||||||
|
*
|
||||||
|
* 规则:
|
||||||
|
* - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`gemini-flash-worker-agy` / `M669`)
|
||||||
|
* 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `worker-agy-hydrogen`;
|
||||||
|
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型“精简代号 / 原始模型 ID”切换影响;
|
||||||
|
* - 其余普通模型继续按 `showUpstreamModel` 与视图选项切换。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} target
|
||||||
|
* @param {{ showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings]
|
||||||
|
* @param {{ preferLabelInShort?: boolean, fallback?: string }} [options]
|
||||||
|
* @returns {{ text: string, title: string, isOrchestratorSeries: boolean }}
|
||||||
|
*/
|
||||||
|
export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||||
|
const showUpstream =
|
||||||
|
typeof settings === 'boolean' ? settings : Boolean(settings?.showUpstreamModel);
|
||||||
|
const orchestratorMode = normalizeOrchestratorIdDisplayMode(
|
||||||
|
typeof settings === 'object' && settings ? settings.orchestratorIdMode : 'compact'
|
||||||
|
);
|
||||||
|
const preferLabelInShort = Boolean(options?.preferLabelInShort);
|
||||||
|
const fallback = options?.fallback ?? '模型未知';
|
||||||
|
|
||||||
|
if (!target || typeof target !== 'object') {
|
||||||
|
return { text: fallback, title: fallback, isOrchestratorSeries: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const shortText = String(
|
||||||
|
target.activeModelShort ?? target.modelShort ?? target.shortName ?? ''
|
||||||
|
).trim();
|
||||||
|
const labelText = String(
|
||||||
|
target.activeModelLabel ?? target.modelLabel ?? target.label ?? ''
|
||||||
|
).trim();
|
||||||
|
const upstreamText = String(
|
||||||
|
target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamName ?? ''
|
||||||
|
).trim();
|
||||||
|
const responseText = String(target.responseModel ?? '').trim();
|
||||||
|
const modelKeyText = String(target.modelKey ?? '').trim();
|
||||||
|
|
||||||
|
const isCompaction =
|
||||||
|
Boolean(target.isCompactionStep) ||
|
||||||
|
/·压缩\s*$/.test(shortText) ||
|
||||||
|
/·压缩\s*$/.test(upstreamText) ||
|
||||||
|
/·压缩\s*$/.test(labelText);
|
||||||
|
|
||||||
|
const combined = `${modelKeyText} ${shortText} ${labelText} ${upstreamText} ${responseText}`;
|
||||||
|
const isOrchWorker =
|
||||||
|
/\bMODEL_PLACEHOLDER_M669\b|\b[a-z0-9.-]*worker-agy\b|\bworker-agy-hydrogen\b|\bOrchestrator\s+Worker\b/i.test(
|
||||||
|
combined
|
||||||
|
);
|
||||||
|
const isOrchSeries =
|
||||||
|
isOrchWorker ||
|
||||||
|
/\bgemini-pro-orchestrator(?:-argon)?\b|\borchestrator-(?:carbon|argon)\b|\borch-(?:carbon|argon)(?:·压缩)?(?=\s|$)|Orchestrator\s*\((?:Carbon|Argon)\)|\bMODEL_PLACEHOLDER_M(?:667|681)\b/i.test(
|
||||||
|
combined
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isOrchSeries) {
|
||||||
|
let compactId = 'orchestrator-carbon';
|
||||||
|
let fullId = 'gemini-pro-orchestrator (carbon-4)';
|
||||||
|
if (isOrchWorker) {
|
||||||
|
compactId = 'worker-agy-hydrogen';
|
||||||
|
fullId = 'gemini-flash-worker-agy (hydrogen-4)';
|
||||||
|
} else if (/\bargon\b|\bMODEL_PLACEHOLDER_M681\b|\borch-argon\b/i.test(combined)) {
|
||||||
|
compactId = 'orchestrator-argon';
|
||||||
|
fullId = 'gemini-pro-orchestrator-argon (argon-4)';
|
||||||
|
}
|
||||||
|
const suffix = isCompaction ? '·压缩' : '';
|
||||||
|
const text = `${orchestratorMode === 'full' ? fullId : compactId}${suffix}`;
|
||||||
|
const multiUpstream =
|
||||||
|
Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
|
||||||
|
? target.upstreamModels.join(' / ')
|
||||||
|
: '';
|
||||||
|
const title = multiUpstream || `${fullId}${suffix}`;
|
||||||
|
return { text, title, isOrchestratorSeries: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const standardText =
|
||||||
|
(showUpstream
|
||||||
|
? upstreamText || responseText || shortText || labelText
|
||||||
|
: preferLabelInShort
|
||||||
|
? labelText || shortText
|
||||||
|
: shortText || labelText) || fallback;
|
||||||
|
const standardTitle =
|
||||||
|
showUpstream && Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
|
||||||
|
? target.upstreamModels.join(' / ')
|
||||||
|
: standardText;
|
||||||
|
return { text: standardText, title: standardTitle, isOrchestratorSeries: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按当前显示策略 (`resolveModelDisplayInfo`) 解析出的最终展示名称对模型统计列表执行二次去重归并,
|
||||||
|
* 确保当多个外层模型槽位映射到同一展示名(例如切换至“原始模型 ID”后共享同一 `upstreamName`)时,
|
||||||
|
* 不会在排行榜或总览中出现重复同名行,同时完整累加 Token、调用次数、未定价计数与速度/首字加权均值。
|
||||||
|
*
|
||||||
|
* @param {object[]} [models=[]]
|
||||||
|
* @param {object|boolean} [settings={}]
|
||||||
|
* @param {{ preferLabelInShort?: boolean, fallback?: string }} [options={}]
|
||||||
|
* @returns {object[]}
|
||||||
|
*/
|
||||||
|
export function mergeModelsByDisplayName(models = [], settings = {}, options = {}) {
|
||||||
|
if (!Array.isArray(models) || models.length === 0) return [];
|
||||||
|
const showUpstream =
|
||||||
|
typeof settings === 'boolean' ? settings : Boolean(settings?.showUpstreamModel);
|
||||||
|
const byDisplay = new Map();
|
||||||
|
|
||||||
|
for (const m of models) {
|
||||||
|
if (!m || typeof m !== 'object') continue;
|
||||||
|
const disp = resolveModelDisplayInfo(m, settings, options);
|
||||||
|
const key = String(disp.text || options?.fallback || '—').trim() || '—';
|
||||||
|
|
||||||
|
const calls = Math.max(0, Number(m.calls || 0));
|
||||||
|
const inTok = Math.max(0, Number(m.inputTokens || 0));
|
||||||
|
const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0));
|
||||||
|
const outTok = Math.max(0, Number(m.outputTokens || 0));
|
||||||
|
const thinkTok = Math.max(0, Number(m.thinkingTokens || 0));
|
||||||
|
const respTok =
|
||||||
|
m.responseTokens != null
|
||||||
|
? Math.max(0, Number(m.responseTokens))
|
||||||
|
: Math.max(0, outTok - thinkTok);
|
||||||
|
const totTok = Math.max(0, Number(m.totalTokens ?? inTok + cacheTok + outTok));
|
||||||
|
const costUsd = Number.isFinite(Number(m.costUsd)) ? Math.max(0, Number(m.costUsd)) : 0;
|
||||||
|
const unpricedCalls = Math.max(0, Number(m.unpricedCalls || 0));
|
||||||
|
|
||||||
|
const speedSampleCount = Math.max(0, Number(m.speedSummary?.sampleCount || 0));
|
||||||
|
const speedExcludedCount = Math.max(0, Number(m.speedSummary?.excludedCount || 0));
|
||||||
|
const speedWeight = speedSampleCount > 0 ? speedSampleCount : Math.max(1, outTok || calls || 1);
|
||||||
|
const hasSpeed = m.avgTokPerSec != null && Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0;
|
||||||
|
|
||||||
|
const ttftSampleCount = Math.max(0, Number(m.ttftSampleCount || 0));
|
||||||
|
const ttftWeight = ttftSampleCount > 0 ? ttftSampleCount : Math.max(1, calls || 1);
|
||||||
|
const hasTtft = m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0;
|
||||||
|
|
||||||
|
let acc = byDisplay.get(key);
|
||||||
|
if (!acc) {
|
||||||
|
acc = {
|
||||||
|
baseItem: m,
|
||||||
|
mergedCount: 1,
|
||||||
|
displayText: key,
|
||||||
|
firstTitle: disp.title || key,
|
||||||
|
titleSet: new Set(disp.title ? [disp.title] : []),
|
||||||
|
upstreamSet: new Set(
|
||||||
|
Array.isArray(m.upstreamModels) ? m.upstreamModels.filter(Boolean) : []
|
||||||
|
),
|
||||||
|
sourceLabels: m.label ? [m.label] : [],
|
||||||
|
calls,
|
||||||
|
inputTokens: inTok,
|
||||||
|
cacheReadTokens: cacheTok,
|
||||||
|
outputTokens: outTok,
|
||||||
|
thinkingTokens: thinkTok,
|
||||||
|
responseTokens: respTok,
|
||||||
|
totalTokens: totTok,
|
||||||
|
costUsd,
|
||||||
|
unpricedCalls,
|
||||||
|
speedWeightedSum: hasSpeed ? Number(m.avgTokPerSec) * speedWeight : 0,
|
||||||
|
speedWeight: hasSpeed ? speedWeight : 0,
|
||||||
|
speedSampleCount,
|
||||||
|
speedExcludedCount,
|
||||||
|
ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0,
|
||||||
|
ttftWeight: hasTtft ? ttftWeight : 0,
|
||||||
|
ttftSampleCount,
|
||||||
|
};
|
||||||
|
if (m.upstreamName) acc.upstreamSet.add(m.upstreamName);
|
||||||
|
byDisplay.set(key, acc);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
acc.mergedCount += 1;
|
||||||
|
if (disp.title) acc.titleSet.add(disp.title);
|
||||||
|
if (Array.isArray(m.upstreamModels)) {
|
||||||
|
for (const u of m.upstreamModels) {
|
||||||
|
if (u) acc.upstreamSet.add(u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (m.upstreamName) acc.upstreamSet.add(m.upstreamName);
|
||||||
|
if (m.label && !acc.sourceLabels.includes(m.label)) {
|
||||||
|
acc.sourceLabels.push(m.label);
|
||||||
|
}
|
||||||
|
|
||||||
|
acc.calls += calls;
|
||||||
|
acc.inputTokens += inTok;
|
||||||
|
acc.cacheReadTokens += cacheTok;
|
||||||
|
acc.outputTokens += outTok;
|
||||||
|
acc.thinkingTokens += thinkTok;
|
||||||
|
acc.responseTokens += respTok;
|
||||||
|
acc.totalTokens += totTok;
|
||||||
|
acc.costUsd += costUsd;
|
||||||
|
acc.unpricedCalls += unpricedCalls;
|
||||||
|
|
||||||
|
if (hasSpeed) {
|
||||||
|
acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight;
|
||||||
|
acc.speedWeight += speedWeight;
|
||||||
|
}
|
||||||
|
acc.speedSampleCount += speedSampleCount;
|
||||||
|
acc.speedExcludedCount += speedExcludedCount;
|
||||||
|
|
||||||
|
if (hasTtft) {
|
||||||
|
acc.ttftWeightedSum += Number(m.avgTtftSec) * ttftWeight;
|
||||||
|
acc.ttftWeight += ttftWeight;
|
||||||
|
}
|
||||||
|
acc.ttftSampleCount += ttftSampleCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Array.from(byDisplay.values()).map((acc) => {
|
||||||
|
if (acc.mergedCount === 1) {
|
||||||
|
return {
|
||||||
|
...acc.baseItem,
|
||||||
|
displayText: acc.displayText,
|
||||||
|
displayTitle: acc.firstTitle,
|
||||||
|
sourceLabels: acc.sourceLabels,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const promptTok = acc.inputTokens + acc.cacheReadTokens;
|
||||||
|
const cacheHitPct = promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0;
|
||||||
|
const avgTokPerSec =
|
||||||
|
acc.speedWeight > 0 ? +(acc.speedWeightedSum / acc.speedWeight).toFixed(1) : null;
|
||||||
|
const avgTtftSec =
|
||||||
|
acc.ttftWeight > 0 ? +(acc.ttftWeightedSum / acc.ttftWeight).toFixed(1) : null;
|
||||||
|
const upstreamModels = Array.from(acc.upstreamSet);
|
||||||
|
const displayTitle =
|
||||||
|
showUpstream && upstreamModels.length > 1
|
||||||
|
? upstreamModels.join(' / ')
|
||||||
|
: Array.from(acc.titleSet).join(' / ') || acc.displayText;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...acc.baseItem,
|
||||||
|
calls: acc.calls,
|
||||||
|
inputTokens: acc.inputTokens,
|
||||||
|
cacheReadTokens: acc.cacheReadTokens,
|
||||||
|
outputTokens: acc.outputTokens,
|
||||||
|
thinkingTokens: acc.thinkingTokens,
|
||||||
|
responseTokens: acc.responseTokens,
|
||||||
|
totalTokens: acc.totalTokens,
|
||||||
|
costUsd: +acc.costUsd.toFixed(6),
|
||||||
|
unpricedCalls: acc.unpricedCalls,
|
||||||
|
cacheHitPct,
|
||||||
|
avgTokPerSec,
|
||||||
|
avgTtftSec,
|
||||||
|
ttftSampleCount: acc.ttftSampleCount,
|
||||||
|
speedSummary: acc.baseItem.speedSummary
|
||||||
|
? {
|
||||||
|
...acc.baseItem.speedSummary,
|
||||||
|
sampleCount: acc.speedSampleCount,
|
||||||
|
excludedCount: acc.speedExcludedCount,
|
||||||
|
avgTokPerSec,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
upstreamModels,
|
||||||
|
displayText: acc.displayText,
|
||||||
|
displayTitle,
|
||||||
|
sourceLabels: acc.sourceLabels,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,8 +6,13 @@
|
|||||||
import { createReactiveStore } from '../core/reactive.js';
|
import { createReactiveStore } from '../core/reactive.js';
|
||||||
import { callSidecarApi, isWindowOverlayMode } from '../core/httpClient.js';
|
import { callSidecarApi, isWindowOverlayMode } from '../core/httpClient.js';
|
||||||
|
|
||||||
|
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在主窗口双栖模式下,从宿主页面路径 `/c/<uuid>` 提取当前正在浏览的会话 ID。
|
* 在主窗口双栖模式下,提取当前正在浏览的会话 ID:
|
||||||
|
* 1. 优先解析 Antigravity 2.0 路由路径 `/c/<uuid>`;
|
||||||
|
* 2. 在 Antigravity IDE (`workbench.html`) 无路径路由时,回退读取活跃对话视图
|
||||||
|
* `[data-testid="conversation-view"][data-cascade-id]` 或侧栏选中项。
|
||||||
*
|
*
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
@@ -15,7 +20,63 @@ export function extractHostRouteCascadeId() {
|
|||||||
if (typeof window === 'undefined' || !isWindowOverlayMode()) return '';
|
if (typeof window === 'undefined' || !isWindowOverlayMode()) return '';
|
||||||
const pathname = String(window.location?.pathname || '');
|
const pathname = String(window.location?.pathname || '');
|
||||||
const m = pathname.match(/^\/c\/([a-f0-9-]{36})(?:\/|$)/i);
|
const m = pathname.match(/^\/c\/([a-f0-9-]{36})(?:\/|$)/i);
|
||||||
return m ? m[1] : '';
|
if (m && CASCADE_UUID_RE.test(m[1])) {
|
||||||
|
return m[1];
|
||||||
|
}
|
||||||
|
const extBridgeRouteId = String(window.__AGUsageMonitorBridge?.hostRouteCascadeId || '').trim();
|
||||||
|
if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) {
|
||||||
|
return extBridgeRouteId;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
const selectedRow = document.querySelector(
|
||||||
|
'[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]'
|
||||||
|
);
|
||||||
|
const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim();
|
||||||
|
|
||||||
|
if (typeof document.querySelectorAll === 'function') {
|
||||||
|
const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]');
|
||||||
|
const visibleIds = [];
|
||||||
|
let focusedId = '';
|
||||||
|
const activeEl = document.activeElement || null;
|
||||||
|
for (const viewEl of views) {
|
||||||
|
const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim();
|
||||||
|
if (!CASCADE_UUID_RE.test(cid)) continue;
|
||||||
|
if (viewEl.hasAttribute?.('hidden')) continue;
|
||||||
|
if (viewEl.getBoundingClientRect) {
|
||||||
|
const r = viewEl.getBoundingClientRect();
|
||||||
|
if (r.width <= 0 && r.height <= 0) continue;
|
||||||
|
}
|
||||||
|
visibleIds.push(cid);
|
||||||
|
if (activeEl && viewEl.contains?.(activeEl)) {
|
||||||
|
focusedId = cid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (focusedId) return focusedId;
|
||||||
|
if (
|
||||||
|
selectedRowId &&
|
||||||
|
CASCADE_UUID_RE.test(selectedRowId) &&
|
||||||
|
visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase())
|
||||||
|
) {
|
||||||
|
return selectedRowId;
|
||||||
|
}
|
||||||
|
if (visibleIds.length > 0) return visibleIds[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]');
|
||||||
|
const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim();
|
||||||
|
if (CASCADE_UUID_RE.test(singleViewId)) {
|
||||||
|
return singleViewId;
|
||||||
|
}
|
||||||
|
if (CASCADE_UUID_RE.test(selectedRowId)) {
|
||||||
|
return selectedRowId;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略宿主 DOM 查询异常
|
||||||
|
}
|
||||||
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
const initialConversationId =
|
const initialConversationId =
|
||||||
@@ -88,19 +149,67 @@ export function normalizeClientUpdateMode(mode, legacyAutoUpdate) {
|
|||||||
return 'manual';
|
return 'manual';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function normalizeClientOrchestratorIdMode(mode) {
|
||||||
|
return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化前端面板挂载方式(`'dual'` | `'composer'` | `'sidebar'`),兼容旧版 `enableWindowOverlay` 布尔字段。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @param {unknown} [legacyEnableOverlay]
|
||||||
|
* @returns {'dual'|'composer'|'sidebar'}
|
||||||
|
*/
|
||||||
|
export function normalizeClientWindowMountMode(mode, legacyEnableOverlay) {
|
||||||
|
const m = String(mode ?? '').trim().toLowerCase();
|
||||||
|
if (m === 'composer' || m === 'input') return 'composer';
|
||||||
|
if (m === 'sidebar' || m === 'off') return 'sidebar';
|
||||||
|
if (m === 'dual' || m === 'topbar') return 'dual';
|
||||||
|
if (legacyEnableOverlay === false) return 'sidebar';
|
||||||
|
return 'dual';
|
||||||
|
}
|
||||||
|
|
||||||
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. 比对系统设置项(模型显示策略、Orchestrator ID 显示风格、周预算模式与额度、插件更新策略、双栖与顶栏槽位配置)
|
||||||
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;
|
||||||
|
const prevOrchIdMode = String(prev.settings?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
||||||
|
const nextOrchIdMode = String(next.settings?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
||||||
|
if (prevOrchIdMode !== nextOrchIdMode) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (prev.settings?.weeklyLimitMode !== next.settings?.weeklyLimitMode) return false;
|
if (prev.settings?.weeklyLimitMode !== next.settings?.weeklyLimitMode) return false;
|
||||||
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?.pluginUpdateMode ?? '') !== (next.settings?.pluginUpdateMode ?? '')) return false;
|
if ((prev.settings?.pluginUpdateMode ?? '') !== (next.settings?.pluginUpdateMode ?? '')) return false;
|
||||||
if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false;
|
if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false;
|
||||||
|
const rawPrevMount = String(prev.settings?.windowMountMode ?? '').trim().toLowerCase();
|
||||||
|
const prevMountMode =
|
||||||
|
rawPrevMount === 'composer' || rawPrevMount === 'input'
|
||||||
|
? 'composer'
|
||||||
|
: rawPrevMount === 'sidebar' || rawPrevMount === 'off'
|
||||||
|
? 'sidebar'
|
||||||
|
: rawPrevMount === 'dual' || rawPrevMount === 'topbar'
|
||||||
|
? 'dual'
|
||||||
|
: prev.settings?.enableWindowOverlay === false
|
||||||
|
? 'sidebar'
|
||||||
|
: 'dual';
|
||||||
|
const rawNextMount = String(next.settings?.windowMountMode ?? '').trim().toLowerCase();
|
||||||
|
const nextMountMode =
|
||||||
|
rawNextMount === 'composer' || rawNextMount === 'input'
|
||||||
|
? 'composer'
|
||||||
|
: rawNextMount === 'sidebar' || rawNextMount === 'off'
|
||||||
|
? 'sidebar'
|
||||||
|
: rawNextMount === 'dual' || rawNextMount === 'topbar'
|
||||||
|
? 'dual'
|
||||||
|
: next.settings?.enableWindowOverlay === false
|
||||||
|
? 'sidebar'
|
||||||
|
: 'dual';
|
||||||
|
if (prevMountMode !== nextMountMode) return false;
|
||||||
if (prev.settings?.enableWindowOverlay !== next.settings?.enableWindowOverlay) return false;
|
if (prev.settings?.enableWindowOverlay !== next.settings?.enableWindowOverlay) return false;
|
||||||
if ((prev.settings?.showTopbarMultiSession !== false) !== (next.settings?.showTopbarMultiSession !== false)) {
|
if ((prev.settings?.showTopbarMultiSession !== false) !== (next.settings?.showTopbarMultiSession !== false)) {
|
||||||
return false;
|
return false;
|
||||||
@@ -250,8 +359,12 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
bs?.tokPerSec !== as?.tokPerSec ||
|
bs?.tokPerSec !== as?.tokPerSec ||
|
||||||
bs?.ttftSec !== as?.ttftSec ||
|
bs?.ttftSec !== as?.ttftSec ||
|
||||||
bs?.outputTokens !== as?.outputTokens ||
|
bs?.outputTokens !== as?.outputTokens ||
|
||||||
|
bs?.thinkingTokens !== as?.thinkingTokens ||
|
||||||
|
bs?.responseTokens !== as?.responseTokens ||
|
||||||
bs?.inputTokens !== as?.inputTokens ||
|
bs?.inputTokens !== as?.inputTokens ||
|
||||||
bs?.cacheReadTokens !== as?.cacheReadTokens ||
|
bs?.cacheReadTokens !== as?.cacheReadTokens ||
|
||||||
|
bs?.contextTokens !== as?.contextTokens ||
|
||||||
|
bs?.cacheHitPct !== as?.cacheHitPct ||
|
||||||
bs?.selectedSpeedReason !== as?.selectedSpeedReason
|
bs?.selectedSpeedReason !== as?.selectedSpeedReason
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
@@ -290,8 +403,12 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
before.tokPerSec !== after.tokPerSec ||
|
before.tokPerSec !== after.tokPerSec ||
|
||||||
before.ttftSec !== after.ttftSec ||
|
before.ttftSec !== after.ttftSec ||
|
||||||
before.outputTokens !== after.outputTokens ||
|
before.outputTokens !== after.outputTokens ||
|
||||||
|
before.thinkingTokens !== after.thinkingTokens ||
|
||||||
|
before.responseTokens !== after.responseTokens ||
|
||||||
before.inputTokens !== after.inputTokens ||
|
before.inputTokens !== after.inputTokens ||
|
||||||
before.cacheReadTokens !== after.cacheReadTokens ||
|
before.cacheReadTokens !== after.cacheReadTokens ||
|
||||||
|
before.contextTokens !== after.contextTokens ||
|
||||||
|
before.cacheHitPct !== after.cacheHitPct ||
|
||||||
before.selectedSpeedReason !== after.selectedSpeedReason
|
before.selectedSpeedReason !== after.selectedSpeedReason
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
@@ -428,7 +545,13 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
pPools[i]?.resetTime !== nPools[i]?.resetTime ||
|
pPools[i]?.resetTime !== nPools[i]?.resetTime ||
|
||||||
pPools[i]?.weeklyUsedPct !== nPools[i]?.weeklyUsedPct ||
|
pPools[i]?.weeklyUsedPct !== nPools[i]?.weeklyUsedPct ||
|
||||||
pPools[i]?.weeklyRemainingPct !== nPools[i]?.weeklyRemainingPct ||
|
pPools[i]?.weeklyRemainingPct !== nPools[i]?.weeklyRemainingPct ||
|
||||||
pPools[i]?.weeklyResetTime !== nPools[i]?.weeklyResetTime
|
pPools[i]?.weeklyResetTime !== nPools[i]?.weeklyResetTime ||
|
||||||
|
pPools[i]?.cycle5h?.tokens !== nPools[i]?.cycle5h?.tokens ||
|
||||||
|
pPools[i]?.cycle5h?.costUsd !== nPools[i]?.cycle5h?.costUsd ||
|
||||||
|
pPools[i]?.cycle5h?.calls !== nPools[i]?.cycle5h?.calls ||
|
||||||
|
pPools[i]?.cycleWeekly?.tokens !== nPools[i]?.cycleWeekly?.tokens ||
|
||||||
|
pPools[i]?.cycleWeekly?.costUsd !== nPools[i]?.cycleWeekly?.costUsd ||
|
||||||
|
pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -613,6 +736,20 @@ export async function saveSettingsPatch(patch) {
|
|||||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
|
||||||
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
|
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
|
||||||
}
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) {
|
||||||
|
safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode);
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'windowMountMode')) {
|
||||||
|
const normMount = normalizeClientWindowMountMode(
|
||||||
|
safePatch.windowMountMode,
|
||||||
|
safePatch.enableWindowOverlay
|
||||||
|
);
|
||||||
|
safePatch.windowMountMode = normMount;
|
||||||
|
safePatch.enableWindowOverlay = normMount !== 'sidebar';
|
||||||
|
} else if (Object.prototype.hasOwnProperty.call(safePatch, 'enableWindowOverlay')) {
|
||||||
|
safePatch.enableWindowOverlay = Boolean(safePatch.enableWindowOverlay);
|
||||||
|
safePatch.windowMountMode = safePatch.enableWindowOverlay ? 'dual' : 'sidebar';
|
||||||
|
}
|
||||||
const prevTelemetry = telemetryStore.getState().telemetry;
|
const prevTelemetry = telemetryStore.getState().telemetry;
|
||||||
if (prevTelemetry?.settings) {
|
if (prevTelemetry?.settings) {
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
|
|||||||
@@ -52,10 +52,10 @@ input {
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 560px;
|
max-width: none;
|
||||||
height: 100dvh;
|
height: 100dvh;
|
||||||
max-height: 100dvh;
|
max-height: 100dvh;
|
||||||
margin: 0 auto;
|
margin: 0;
|
||||||
padding: var(--space-3) var(--space-4);
|
padding: var(--space-3) var(--space-4);
|
||||||
gap: var(--space-3);
|
gap: var(--space-3);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
|||||||
@@ -29,7 +29,8 @@
|
|||||||
border-radius: var(--radius-sm);
|
border-radius: var(--radius-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
.steps-inline-scope-select .select-menu {
|
.steps-inline-scope-select .select-menu,
|
||||||
|
.steps-inline-model-select .select-menu {
|
||||||
left: auto;
|
left: auto;
|
||||||
right: 0;
|
right: 0;
|
||||||
min-width: 220px;
|
min-width: 220px;
|
||||||
@@ -212,6 +213,10 @@
|
|||||||
flex: 1;
|
flex: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.custom-select[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
.select-trigger {
|
.select-trigger {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -296,6 +301,41 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.select-option-meta {
|
||||||
|
font-size: 11px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-checkbox {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 13px;
|
||||||
|
height: 13px;
|
||||||
|
border-radius: 3px;
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-inverse);
|
||||||
|
flex-shrink: 0;
|
||||||
|
transition:
|
||||||
|
background-color var(--dur-instant) var(--ease-fast),
|
||||||
|
border-color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-checkbox[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-checkbox.is-checked {
|
||||||
|
background: var(--accent-primary);
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-checkbox .svg-icon {
|
||||||
|
stroke-width: 2.4;
|
||||||
|
}
|
||||||
|
|
||||||
/* --- 4. 定制步进数字框 (Bespoke Custom Number Input,零原生 <input type="number">) --- */
|
/* --- 4. 定制步进数字框 (Bespoke Custom Number Input,零原生 <input type="number">) --- */
|
||||||
.number-input {
|
.number-input {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
|
|||||||
@@ -32,6 +32,44 @@
|
|||||||
margin-right: 4px;
|
margin-right: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="composer"]) {
|
||||||
|
position: relative;
|
||||||
|
height: 26px;
|
||||||
|
gap: 4px;
|
||||||
|
margin-right: 4px;
|
||||||
|
align-self: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="composer"][data-composer-push="1"]) {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="composer"]) .wm-multi-btn,
|
||||||
|
:host(.wm-capsule-host[data-dock="composer"]) .wm-capsule-btn {
|
||||||
|
height: 26px;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="composer"]) .wm-multi-btn {
|
||||||
|
padding: 0 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="composer"]) .wm-capsule-btn {
|
||||||
|
padding: 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="ide-titlebar"]) {
|
||||||
|
position: relative;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: 8px;
|
||||||
|
z-index: 2501;
|
||||||
|
--text-primary: var(
|
||||||
|
--vscode-titleBar-activeForeground,
|
||||||
|
var(--foreground, var(--vscode-foreground, hsl(215 22% 15%)))
|
||||||
|
);
|
||||||
|
--text-secondary: color-mix(in srgb, var(--text-primary) 78%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
:host(.wm-capsule-host[data-dock="fixed"]) {
|
:host(.wm-capsule-host[data-dock="fixed"]) {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
top: 6px;
|
top: 6px;
|
||||||
@@ -449,11 +487,22 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@keyframes wm-popover-in-up {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(3px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.wm-popover-panel {
|
.wm-popover-panel {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
top: 42px;
|
top: 42px;
|
||||||
left: 12px;
|
left: 12px;
|
||||||
width: min(492px, calc(100vw - 24px));
|
width: min(522px, calc(100vw - 24px));
|
||||||
height: min(588px, calc(100vh - 54px));
|
height: min(588px, calc(100vh - 54px));
|
||||||
max-height: calc(100vh - 54px);
|
max-height: calc(100vh - 54px);
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -481,7 +530,7 @@
|
|||||||
position: fixed;
|
position: fixed;
|
||||||
top: 42px;
|
top: 42px;
|
||||||
left: 12px;
|
left: 12px;
|
||||||
width: min(492px, calc(100vw - 24px));
|
width: min(522px, calc(100vw - 24px));
|
||||||
max-height: calc(100vh - 54px);
|
max-height: calc(100vh - 54px);
|
||||||
padding: var(--space-3) var(--space-4);
|
padding: var(--space-3) var(--space-4);
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -505,7 +554,7 @@
|
|||||||
position: fixed;
|
position: fixed;
|
||||||
top: 42px;
|
top: 42px;
|
||||||
left: 12px;
|
left: 12px;
|
||||||
width: min(484px, calc(100vw - 24px));
|
width: min(464px, calc(100vw - 24px));
|
||||||
max-height: calc(100vh - 54px);
|
max-height: calc(100vh - 54px);
|
||||||
padding: 14px 16px;
|
padding: 14px 16px;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -526,6 +575,21 @@
|
|||||||
animation: wm-popover-in var(--dur-instant) var(--ease-fast);
|
animation: wm-popover-in var(--dur-instant) var(--ease-fast);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.wm-popover-panel.is-above {
|
||||||
|
transform-origin: bottom right;
|
||||||
|
animation-name: wm-popover-in-up;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-hover-tip.is-above {
|
||||||
|
transform-origin: bottom right;
|
||||||
|
animation-name: wm-popover-in-up;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wm-multi-panel.is-above {
|
||||||
|
transform-origin: bottom left;
|
||||||
|
animation-name: wm-popover-in-up;
|
||||||
|
}
|
||||||
|
|
||||||
.wm-popover-panel.is-instant,
|
.wm-popover-panel.is-instant,
|
||||||
.wm-hover-tip.is-instant,
|
.wm-hover-tip.is-instant,
|
||||||
.wm-multi-panel.is-instant {
|
.wm-multi-panel.is-instant {
|
||||||
|
|||||||
@@ -11,26 +11,48 @@
|
|||||||
--radius-sm: 4px;
|
--radius-sm: 4px;
|
||||||
--radius-xs: 2px;
|
--radius-xs: 2px;
|
||||||
|
|
||||||
/* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode & safe dark fallback) */
|
/* Host-Bridged Surfaces (Antigravity 2.0 + Antigravity IDE --vscode-* + safe fallback) */
|
||||||
--surface-bg: var(--background, hsl(0 0% 100%));
|
--surface-bg: var(--background, var(--vscode-sideBar-background, var(--vscode-editor-background, hsl(0 0% 100%))));
|
||||||
--surface-panel: var(--card, var(--background, hsl(0 0% 100%)));
|
--surface-panel: var(
|
||||||
|
--card,
|
||||||
|
var(
|
||||||
|
--background,
|
||||||
|
var(--vscode-editorWidget-background, var(--vscode-sideBar-background, var(--vscode-editor-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-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));
|
||||||
|
|
||||||
/* 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,
|
||||||
|
var(
|
||||||
|
--vscode-widget-border,
|
||||||
|
var(
|
||||||
|
--vscode-panel-border,
|
||||||
|
var(--vscode-contrastBorder, color-mix(in srgb, var(--text-primary) 18%, var(--surface-panel)))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
) 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%);
|
||||||
|
|
||||||
/* Typography Hierarchy */
|
/* Typography Hierarchy */
|
||||||
--text-primary: var(--foreground, hsl(215 22% 15%));
|
--text-primary: var(--foreground, var(--vscode-foreground, var(--vscode-editor-foreground, hsl(215 22% 15%))));
|
||||||
--text-secondary: var(--muted-foreground, hsl(215 12% 44%));
|
--text-secondary: var(--muted-foreground, var(--vscode-descriptionForeground, hsl(215 12% 44%)));
|
||||||
--text-muted: color-mix(in srgb, var(--text-secondary) 74%, var(--surface-panel) 26%);
|
--text-muted: color-mix(in srgb, var(--text-secondary) 74%, var(--surface-panel) 26%);
|
||||||
--text-inverse: var(--surface-panel);
|
--text-inverse: var(--surface-panel);
|
||||||
|
|
||||||
/* Semantic Telemetry Accents */
|
/* Semantic Telemetry Accents */
|
||||||
--accent-primary: var(--primary, hsl(217 82% 51%));
|
--accent-primary: var(
|
||||||
|
--primary,
|
||||||
|
var(--vscode-textLink-foreground, var(--vscode-button-background, hsl(217 82% 51%)))
|
||||||
|
);
|
||||||
--accent-primary-soft: color-mix(in srgb, var(--accent-primary) 13%, transparent);
|
--accent-primary-soft: color-mix(in srgb, var(--accent-primary) 13%, transparent);
|
||||||
--accent-primary-border: color-mix(in srgb, var(--accent-primary) 38%, var(--border-hairline));
|
--accent-primary-border: color-mix(in srgb, var(--accent-primary) 38%, var(--border-hairline));
|
||||||
|
|
||||||
@@ -43,7 +65,7 @@
|
|||||||
--metric-warn: hsl(34 86% 44%);
|
--metric-warn: hsl(34 86% 44%);
|
||||||
--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, var(--vscode-errorForeground, hsl(0 74% 50%)));
|
||||||
|
|
||||||
/* Context Window 10-Channel Palette */
|
/* Context Window 10-Channel Palette */
|
||||||
--ctx-assistant: hsl(217 82% 54%);
|
--ctx-assistant: hsl(217 82% 54%);
|
||||||
|
|||||||
@@ -238,7 +238,7 @@
|
|||||||
|
|
||||||
.trend-svg {
|
.trend-svg {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 118px;
|
height: 120px;
|
||||||
display: block;
|
display: block;
|
||||||
overflow: visible;
|
overflow: visible;
|
||||||
}
|
}
|
||||||
@@ -304,9 +304,10 @@
|
|||||||
top: 0;
|
top: 0;
|
||||||
left: var(--tip-x, 50%);
|
left: var(--tip-x, 50%);
|
||||||
transform: translateX(var(--tip-shift, -50%));
|
transform: translateX(var(--tip-shift, -50%));
|
||||||
min-width: 148px;
|
width: max-content;
|
||||||
max-width: 240px;
|
min-width: 152px;
|
||||||
padding: 5px 8px;
|
max-width: min(300px, calc(100% - 8px));
|
||||||
|
padding: 5px 9px;
|
||||||
background: var(--surface-panel);
|
background: var(--surface-panel);
|
||||||
border: 1px solid var(--border-strong);
|
border: 1px solid var(--border-strong);
|
||||||
border-radius: var(--radius-sm);
|
border-radius: var(--radius-sm);
|
||||||
@@ -322,7 +323,7 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: 8px;
|
gap: 10px;
|
||||||
font-size: 10.5px;
|
font-size: 10.5px;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
}
|
}
|
||||||
@@ -331,42 +332,62 @@
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-calls {
|
.trend-tip-calls {
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
max-width: 190px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-main {
|
.trend-tip-main {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: baseline;
|
align-items: baseline;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: 8px;
|
gap: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-tokens {
|
.trend-tip-tokens {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--accent-primary);
|
color: var(--accent-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-cost {
|
.trend-tip-cost {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-sub {
|
.trend-tip-sub {
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
border-top: 1px solid var(--border-hairline);
|
border-top: 1px solid var(--border-hairline);
|
||||||
padding-top: 2px;
|
padding-top: 2px;
|
||||||
margin-top: 1px;
|
margin-top: 1px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.trend-tooltip.is-hm-top {
|
||||||
|
top: 0;
|
||||||
|
bottom: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-tooltip.is-hm-bottom {
|
||||||
|
top: auto;
|
||||||
|
bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.trend-x-axis {
|
.trend-x-axis {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -401,6 +422,177 @@
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- 4b. 类 GitHub 每日小格子热力图 (> 90 天自动启用,一格一天) --- */
|
||||||
|
.trend-heatmap-stage {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
padding-top: 2px;
|
||||||
|
width: 100%;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-heatmap-body {
|
||||||
|
--hm-weeks: 26;
|
||||||
|
--hm-gap: 2px;
|
||||||
|
--hm-cell: 9px;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 4px;
|
||||||
|
width: 100%;
|
||||||
|
container-type: inline-size;
|
||||||
|
}
|
||||||
|
|
||||||
|
@supports (width: 1cqi) {
|
||||||
|
.trend-heatmap-body {
|
||||||
|
--hm-cell: clamp(
|
||||||
|
6.5px,
|
||||||
|
calc((100cqi - 18px - (var(--hm-weeks) - 1) * var(--hm-gap)) / var(--hm-weeks)),
|
||||||
|
18px
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-weekdays {
|
||||||
|
display: grid;
|
||||||
|
grid-template-rows: 15px repeat(7, var(--hm-cell));
|
||||||
|
row-gap: var(--hm-gap);
|
||||||
|
width: 14px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-month-spacer {
|
||||||
|
height: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-wday {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-start;
|
||||||
|
font-size: 9px;
|
||||||
|
line-height: 1;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-scroll {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow-x: auto;
|
||||||
|
overflow-y: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-track {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--hm-gap);
|
||||||
|
min-width: max-content;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-months {
|
||||||
|
position: relative;
|
||||||
|
height: 15px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-month {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: calc(var(--hm-col, 0) * (var(--hm-cell) + var(--hm-gap)));
|
||||||
|
font-size: 9.5px;
|
||||||
|
line-height: 14px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-rows: repeat(7, var(--hm-cell));
|
||||||
|
grid-auto-flow: column;
|
||||||
|
grid-auto-columns: var(--hm-cell);
|
||||||
|
gap: var(--hm-gap);
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell {
|
||||||
|
width: var(--hm-cell);
|
||||||
|
height: var(--hm-cell);
|
||||||
|
border-radius: 2px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell.is-pad {
|
||||||
|
visibility: hidden;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell.lv-0,
|
||||||
|
.trend-hm-swatch.lv-0 {
|
||||||
|
background: color-mix(in srgb, var(--text-primary) 6.5%, var(--surface-panel));
|
||||||
|
border: 1px solid color-mix(in srgb, var(--border-hairline) 55%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell.lv-1,
|
||||||
|
.trend-hm-swatch.lv-1 {
|
||||||
|
background: color-mix(in srgb, var(--ctx-cached) 24%, var(--surface-panel));
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell.lv-2,
|
||||||
|
.trend-hm-swatch.lv-2 {
|
||||||
|
background: color-mix(in srgb, var(--ctx-cached) 46%, var(--surface-panel));
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell.lv-3,
|
||||||
|
.trend-hm-swatch.lv-3 {
|
||||||
|
background: color-mix(in srgb, var(--ctx-cached) 70%, var(--surface-panel));
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell.lv-4,
|
||||||
|
.trend-hm-swatch.lv-4 {
|
||||||
|
background: color-mix(in srgb, var(--ctx-cached) 94%, var(--surface-panel));
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-cell.is-hovered {
|
||||||
|
outline: 1.5px solid var(--text-primary);
|
||||||
|
outline-offset: 0.5px;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-footer {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 10px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
min-height: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-summary {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-legend {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 3px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 9.5px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.trend-hm-swatch {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 2px;
|
||||||
|
display: inline-block;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
/* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */
|
/* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */
|
||||||
.cons-item-list {
|
.cons-item-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -423,6 +615,10 @@
|
|||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cons-item-foot > .legend-left:last-child {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
.cons-item-foot strong {
|
.cons-item-foot strong {
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
|||||||
@@ -53,6 +53,46 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 配额池窗口行头:标题 + 周期用量内联(窄栏自适应截断,零额外纵向行高) */
|
||||||
|
.quota-win-head {
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-win-left {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 5px;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-win-title {
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-win-usage {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-size: 10.5px;
|
||||||
|
font-weight: 400;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-win-meta {
|
||||||
|
font-size: 11px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
/* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */
|
/* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */
|
||||||
.live-activity-list {
|
.live-activity-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -44,13 +44,13 @@
|
|||||||
|
|
||||||
.data-table th:first-child,
|
.data-table th:first-child,
|
||||||
.data-table td:first-child {
|
.data-table td:first-child {
|
||||||
padding-left: 7px;
|
padding-left: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.data-table th:last-child,
|
.data-table th:last-child,
|
||||||
.data-table td:last-child {
|
.data-table td:last-child {
|
||||||
text-align: right;
|
text-align: right;
|
||||||
padding-right: 10px;
|
padding-right: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.data-table th {
|
.data-table th {
|
||||||
@@ -88,13 +88,15 @@
|
|||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.steps-inline-scope-select {
|
.steps-inline-scope-select,
|
||||||
flex: 0 1 180px;
|
.steps-inline-model-select {
|
||||||
|
flex: 0 1 165px;
|
||||||
min-width: 72px;
|
min-width: 72px;
|
||||||
max-width: 190px;
|
max-width: 175px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.steps-inline-scope-select .select-trigger {
|
.steps-inline-scope-select .select-trigger,
|
||||||
|
.steps-inline-model-select .select-trigger {
|
||||||
height: 22px;
|
height: 22px;
|
||||||
padding: 0 6px;
|
padding: 0 6px;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
@@ -104,3 +106,473 @@
|
|||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
background: var(--surface-subtle);
|
background: var(--surface-subtle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- 3. 按模型汇总分析视图:双趋势图与极简模型总览 (Models Analytics Pane) --- */
|
||||||
|
.models-analytics-pane {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
padding: var(--space-3) 0 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
padding: var(--space-3) var(--space-4);
|
||||||
|
background: var(--surface-panel);
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-card-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-card-title-group {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-card-title {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-card .seg-btn {
|
||||||
|
padding: 2px 6px;
|
||||||
|
font-size: 10.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-controls {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-model-select {
|
||||||
|
min-width: 96px;
|
||||||
|
max-width: 176px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-model-select .select-trigger {
|
||||||
|
height: 22px;
|
||||||
|
padding: 0 6px;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
font-size: 10.5px;
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
background: var(--surface-subtle);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-chart-wrap {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-plot-stage {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
padding-top: 4px;
|
||||||
|
cursor: crosshair;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-svg {
|
||||||
|
width: 100%;
|
||||||
|
height: 106px;
|
||||||
|
display: block;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-svg {
|
||||||
|
height: 136px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-sci-grid line {
|
||||||
|
stroke: var(--border-hairline);
|
||||||
|
stroke-width: 0.9;
|
||||||
|
stroke-dasharray: 2 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-axis-spine {
|
||||||
|
stroke: var(--border-strong);
|
||||||
|
stroke-width: 1;
|
||||||
|
shape-rendering: crispEdges;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-axis-tick {
|
||||||
|
stroke: var(--border-strong);
|
||||||
|
stroke-width: 1;
|
||||||
|
shape-rendering: crispEdges;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-axis-label {
|
||||||
|
fill: var(--text-muted);
|
||||||
|
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
||||||
|
font-size: 9.5px;
|
||||||
|
user-select: none;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-axis-label.is-y-inline {
|
||||||
|
paint-order: stroke;
|
||||||
|
stroke: var(--surface-panel);
|
||||||
|
stroke-width: 2.5px;
|
||||||
|
stroke-linejoin: round;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-line-card .trend-line {
|
||||||
|
stroke: var(--sstep-accent, var(--ctx-cached));
|
||||||
|
stroke-width: 1.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-multi-area {
|
||||||
|
fill: var(--sstep-series-color, var(--ctx-cached));
|
||||||
|
fill-opacity: 0.08;
|
||||||
|
stroke: none;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-series-single-dot {
|
||||||
|
fill: var(--sstep-series-color, var(--ctx-cached));
|
||||||
|
stroke: var(--surface-panel);
|
||||||
|
stroke-width: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-svg .trend-hover-dot {
|
||||||
|
stroke: var(--hover-dot-color, var(--sstep-accent, var(--accent-primary)));
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-line-card .trend-peak-pill {
|
||||||
|
background: color-mix(in srgb, var(--sstep-accent, var(--ctx-cached)) 14%, var(--surface-panel));
|
||||||
|
border-color: color-mix(in srgb, var(--sstep-accent, var(--ctx-cached)) 30%, var(--border-hairline));
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-node-dot {
|
||||||
|
fill: var(--surface-panel);
|
||||||
|
stroke: var(--dot-stroke, var(--sstep-accent, var(--ctx-cached)));
|
||||||
|
stroke-width: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-node-dot.is-skipped {
|
||||||
|
fill: transparent;
|
||||||
|
stroke: var(--border-strong);
|
||||||
|
stroke-width: 1;
|
||||||
|
stroke-dasharray: 1.5 1.5;
|
||||||
|
opacity: 0.65;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-ci-band {
|
||||||
|
fill: var(--sstep-fit-accent, var(--ctx-cached));
|
||||||
|
fill-opacity: 0.14;
|
||||||
|
stroke: var(--sstep-fit-accent, var(--ctx-cached));
|
||||||
|
stroke-opacity: 0.24;
|
||||||
|
stroke-width: 0.75;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-ci-band.is-multi {
|
||||||
|
fill-opacity: 0.1;
|
||||||
|
stroke-opacity: 0.18;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-line {
|
||||||
|
stroke: var(--sstep-fit-accent, var(--ctx-cached));
|
||||||
|
stroke-width: 2;
|
||||||
|
stroke-linecap: round;
|
||||||
|
stroke-linejoin: round;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-ols-line {
|
||||||
|
stroke: color-mix(in srgb, var(--text-secondary) 72%, var(--surface-panel));
|
||||||
|
stroke-width: 1.1;
|
||||||
|
stroke-dasharray: 3.5 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-scatter-dot {
|
||||||
|
fill: color-mix(in srgb, var(--sstep-fit-accent, var(--ctx-cached)) 48%, var(--text-secondary) 52%);
|
||||||
|
fill-opacity: 0.42;
|
||||||
|
stroke: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-scatter-dot.is-multi {
|
||||||
|
fill: var(--sstep-fit-accent, var(--ctx-cached));
|
||||||
|
fill-opacity: 0.48;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-svg .trend-hover-dot {
|
||||||
|
stroke: var(--hover-dot-color, var(--accent-primary));
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-hover-raw-dot {
|
||||||
|
fill: var(--surface-panel);
|
||||||
|
stroke: var(--text-primary);
|
||||||
|
stroke-width: 1.6;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-empty-hint {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 11px;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-model-legend {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px 10px;
|
||||||
|
padding-top: 2px;
|
||||||
|
font-size: 10px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-legend-item {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-legend-dot {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
background: var(--swatch-bg, var(--ctx-cached));
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-legend-line {
|
||||||
|
width: 11px;
|
||||||
|
height: 2px;
|
||||||
|
border-radius: 1px;
|
||||||
|
background: var(--swatch-bg, var(--ctx-cached));
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-legend[hidden],
|
||||||
|
.sstep-model-legend[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-foot {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px 8px;
|
||||||
|
padding-top: 2px;
|
||||||
|
font-size: 10px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-legend {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-legend-ols {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-legend-ols[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-swatch {
|
||||||
|
display: inline-block;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-swatch.is-scatter {
|
||||||
|
width: 5.5px;
|
||||||
|
height: 5.5px;
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
background: color-mix(in srgb, var(--sstep-fit-accent, var(--ctx-cached)) 48%, var(--text-secondary) 52%);
|
||||||
|
opacity: 0.68;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-swatch.is-curve {
|
||||||
|
width: 11px;
|
||||||
|
height: 2px;
|
||||||
|
border-radius: 1px;
|
||||||
|
background: var(--sstep-fit-accent, var(--ctx-cached));
|
||||||
|
margin-left: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-swatch.is-ci {
|
||||||
|
width: 10px;
|
||||||
|
height: 6.5px;
|
||||||
|
border-radius: 1px;
|
||||||
|
background: color-mix(in srgb, var(--sstep-fit-accent, var(--ctx-cached)) 22%, var(--surface-panel));
|
||||||
|
border: 0.75px solid color-mix(in srgb, var(--sstep-fit-accent, var(--ctx-cached)) 42%, transparent);
|
||||||
|
margin-left: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-swatch.is-ols {
|
||||||
|
width: 10px;
|
||||||
|
height: 0;
|
||||||
|
border-top: 1.2px dashed color-mix(in srgb, var(--text-secondary) 75%, var(--surface-panel));
|
||||||
|
margin-left: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sstep-fit-delta {
|
||||||
|
font-size: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 4. 极简高密度模型总览列表 (Minimalist Session Model Summary Cards) --- */
|
||||||
|
.smodel-section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-section-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 2px 1px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-empty {
|
||||||
|
padding: var(--space-5) var(--space-3);
|
||||||
|
text-align: center;
|
||||||
|
font-size: 11px;
|
||||||
|
border: 1px dashed var(--border-hairline);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 5px;
|
||||||
|
padding: 7px 10px;
|
||||||
|
background: var(--surface-panel);
|
||||||
|
border: 1px solid var(--border-hairline);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
cursor: pointer;
|
||||||
|
transition:
|
||||||
|
background var(--dur-instant) var(--ease-fast),
|
||||||
|
border-color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-card:hover {
|
||||||
|
background: var(--surface-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-card.is-fit-active {
|
||||||
|
border-color: var(--accent-primary-border);
|
||||||
|
background: color-mix(in srgb, var(--accent-primary) 4.5%, var(--surface-panel));
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-ident {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-name {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-calls-pill {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 500;
|
||||||
|
padding: 1px 5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
background: var(--surface-track);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-totals {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-tok {
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-cost {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-seg-bar {
|
||||||
|
height: 3.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-foot {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 2px 10px;
|
||||||
|
font-size: 10.5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-perf {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smodel-split {
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|||||||
@@ -23,11 +23,16 @@ import {
|
|||||||
formatDateSpanBadge,
|
formatDateSpanBadge,
|
||||||
formatTokensPrecise,
|
formatTokensPrecise,
|
||||||
formatUsd,
|
formatUsd,
|
||||||
|
mergeModelsByDisplayName,
|
||||||
|
normalizeOrchestratorIdDisplayMode,
|
||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||||
import { uiStore } from '../store/uiStore.js';
|
import { uiStore } from '../store/uiStore.js';
|
||||||
import { createTrendAreaChart } from '../components/charts/TrendAreaChart.js';
|
import {
|
||||||
|
createTrendAreaChart,
|
||||||
|
HEATMAP_DAYS_THRESHOLD,
|
||||||
|
} from '../components/charts/TrendAreaChart.js';
|
||||||
import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js';
|
import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js';
|
||||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||||
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||||
@@ -411,13 +416,24 @@ export const ConsumptionView = defineComponent({
|
|||||||
* 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。
|
* 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。
|
||||||
*/
|
*/
|
||||||
function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) {
|
function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) {
|
||||||
patchText(refs.nameEl, item.label || item.name || item.shortName || '—');
|
const displayLabel = item.label || item.name || item.shortName || '—';
|
||||||
|
patchText(refs.nameEl, displayLabel);
|
||||||
|
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
|
||||||
const total = Number(item.totalTokens || 0);
|
const total = Number(item.totalTokens || 0);
|
||||||
const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0;
|
const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0;
|
||||||
patchText(refs.pctBadge, `${share.toFixed(1)}%`);
|
patchText(refs.pctBadge, `${share.toFixed(1)}%`);
|
||||||
patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : '');
|
patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : '');
|
||||||
patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader);
|
patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader);
|
||||||
patchText(refs.costEl, formatUsd(item.costUsd || 0));
|
const costVal = Number(item.costUsd || 0);
|
||||||
|
const callsCount = Number(item.calls || 0);
|
||||||
|
const isAllUnpriced =
|
||||||
|
callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0);
|
||||||
|
patchText(
|
||||||
|
refs.costEl,
|
||||||
|
formatUsd(isAllUnpriced ? null : costVal, {
|
||||||
|
precise: costVal > 0 && costVal < 0.1,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
const responseTok =
|
const responseTok =
|
||||||
item.responseTokens != null
|
item.responseTokens != null
|
||||||
@@ -530,36 +546,40 @@ export const ConsumptionView = defineComponent({
|
|||||||
thinkingTokens,
|
thinkingTokens,
|
||||||
});
|
});
|
||||||
|
|
||||||
// 2. 同步历史趋势交互式 SVG 面积图与粒度提示
|
// 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与粒度提示
|
||||||
patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间');
|
patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间');
|
||||||
const trendSeries = cons.trendSeries || [];
|
const trendSeries = cons.trendSeries || [];
|
||||||
const isHourlyTrend =
|
const isHourlyTrend =
|
||||||
trendSeries[0]?.granularity === 'hour' ||
|
trendSeries[0]?.granularity === 'hour' ||
|
||||||
(trendSeries[0]?.label || '').includes(':');
|
(trendSeries[0]?.label || '').includes(':');
|
||||||
|
const isHeatmapTrend = !isHourlyTrend && trendSeries.length > HEATMAP_DAYS_THRESHOLD;
|
||||||
patchText(
|
patchText(
|
||||||
trendGranularityHint,
|
trendGranularityHint,
|
||||||
`${isHourlyTrend ? '按小时' : '按日'} (${trendSeries.length || 0}点) · 悬停查看`
|
isHeatmapTrend
|
||||||
|
? `按日 (${trendSeries.length}天) · 悬停查看`
|
||||||
|
: `${isHourlyTrend ? '按小时' : '按日'} (${trendSeries.length || 0}点) · 悬停查看`
|
||||||
);
|
);
|
||||||
trendChart.update(trendSeries);
|
trendChart.update(trendSeries);
|
||||||
|
|
||||||
// 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账,遵循模型名称显示格式设置)
|
// 3. 同步热门模型列表(按最终展示名称去重归并后按总 Token 数降序排列并执行键值增量对账)
|
||||||
const showUpstream = Boolean(slice.showUpstreamModel);
|
const displaySettings = {
|
||||||
const models = (slice.modelBreakdown || [])
|
showUpstreamModel: Boolean(slice.showUpstreamModel),
|
||||||
.slice()
|
orchestratorIdMode: slice.orchestratorIdMode,
|
||||||
.sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0));
|
};
|
||||||
|
const models = mergeModelsByDisplayName(slice.modelBreakdown || [], displaySettings, {
|
||||||
|
preferLabelInShort: true,
|
||||||
|
}).sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0));
|
||||||
const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0);
|
const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0);
|
||||||
|
|
||||||
patchKeyedList(modelsListEl, models, {
|
patchKeyedList(modelsListEl, models, {
|
||||||
keyFn: (m) => m.label || m.shortName,
|
keyFn: (m) => m.displayText || m.label || m.shortName,
|
||||||
sigFn: (m) =>
|
sigFn: (m) =>
|
||||||
`${showUpstream}:${m.label}:${m.upstreamName || ''}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
`${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
||||||
createRow: createBreakdownItemRow,
|
createRow: createBreakdownItemRow,
|
||||||
updateRow: (refs, m) =>
|
updateRow: (refs, m) =>
|
||||||
updateBreakdownItemRow(
|
updateBreakdownItemRow(
|
||||||
refs,
|
refs,
|
||||||
showUpstream
|
{ ...m, label: m.displayText, title: m.displayTitle },
|
||||||
? { ...m, label: m.upstreamName || m.label || m.shortName }
|
|
||||||
: m,
|
|
||||||
modelsTotalTok,
|
modelsTotalTok,
|
||||||
true
|
true
|
||||||
),
|
),
|
||||||
@@ -632,6 +652,9 @@ export const ConsumptionView = defineComponent({
|
|||||||
consumption: st.telemetry?.consumption,
|
consumption: st.telemetry?.consumption,
|
||||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||||
|
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
|
||||||
|
st.telemetry?.settings?.orchestratorIdMode
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
(slice) => {
|
(slice) => {
|
||||||
latestSlice = slice;
|
latestSlice = slice;
|
||||||
@@ -659,6 +682,7 @@ export const ConsumptionView = defineComponent({
|
|||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
unsub();
|
unsub();
|
||||||
unsubView();
|
unsubView();
|
||||||
|
trendChart.destroy?.();
|
||||||
timeFilterSwitch.destroy();
|
timeFilterSwitch.destroy();
|
||||||
startPicker.destroy();
|
startPicker.destroy();
|
||||||
endPicker.destroy();
|
endPicker.destroy();
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import {
|
|||||||
formatMetric,
|
formatMetric,
|
||||||
formatTokens,
|
formatTokens,
|
||||||
formatUsd,
|
formatUsd,
|
||||||
|
resolveModelDisplayInfo,
|
||||||
sampleSummary,
|
sampleSummary,
|
||||||
speedReasonText,
|
speedReasonText,
|
||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
@@ -176,22 +177,27 @@ export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
|
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条,
|
||||||
|
* 并在窗口标题右侧内联展示该配额池自身的周期消耗统计(零额外纵向行高)。
|
||||||
*/
|
*/
|
||||||
export function createPoolQuotaRow() {
|
export function createPoolQuotaRow() {
|
||||||
const title5h = h('span', { text: '5h 限额' });
|
const title5h = h('span', { className: 'quota-win-title', text: '5h' });
|
||||||
const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' });
|
const usage5h = h('span', { className: 'quota-win-usage', hidden: true, text: '' });
|
||||||
|
const left5h = h('span', { className: 'quota-win-left' }, [title5h, usage5h]);
|
||||||
|
const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' });
|
||||||
const fill5h = h('div', { className: 'progress-fill' });
|
const fill5h = h('div', { className: 'progress-fill' });
|
||||||
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||||
h('div', { className: 'panel-header' }, [title5h, meta5h]),
|
h('div', { className: 'panel-header quota-win-head' }, [left5h, meta5h]),
|
||||||
h('div', { className: 'progress-track' }, [fill5h]),
|
h('div', { className: 'progress-track' }, [fill5h]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const titleWk = h('span', { text: '每周限额' });
|
const titleWk = h('span', { className: 'quota-win-title', text: '周限' });
|
||||||
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
|
const usageWk = h('span', { className: 'quota-win-usage', hidden: true, text: '' });
|
||||||
|
const leftWk = h('span', { className: 'quota-win-left' }, [titleWk, usageWk]);
|
||||||
|
const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' });
|
||||||
const fillWk = h('div', { className: 'progress-fill' });
|
const fillWk = h('div', { className: 'progress-fill' });
|
||||||
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||||
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
|
h('div', { className: 'panel-header quota-win-head' }, [leftWk, metaWk]),
|
||||||
h('div', { className: 'progress-track' }, [fillWk]),
|
h('div', { className: 'progress-track' }, [fillWk]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -202,10 +208,41 @@ export function createPoolQuotaRow() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
el,
|
el,
|
||||||
refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk },
|
refs: {
|
||||||
|
row5h,
|
||||||
|
left5h,
|
||||||
|
title5h,
|
||||||
|
usage5h,
|
||||||
|
meta5h,
|
||||||
|
fill5h,
|
||||||
|
rowWk,
|
||||||
|
leftWk,
|
||||||
|
titleWk,
|
||||||
|
usageWk,
|
||||||
|
metaWk,
|
||||||
|
fillWk,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化可用额度面板底部的汇总行文案(官方配额模式下展示各池周期合计,自定义预算模式下展示自然周累计)。
|
||||||
|
*/
|
||||||
|
export function formatQuotaSummaryFooter(quotas, account) {
|
||||||
|
const weekly = quotas?.weekly || {};
|
||||||
|
const isCustomLocal = weekly.isOfficial === false;
|
||||||
|
const prefix = isCustomLocal ? '本周' : '周期';
|
||||||
|
const leftText = `${prefix}累计: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0)})`;
|
||||||
|
const rightText =
|
||||||
|
Number(account?.aiCredits) > 0
|
||||||
|
? `AI 积分: ${account.aiCredits}`
|
||||||
|
: `${prefix}调用: ${weekly.calls || 0} 次`;
|
||||||
|
const tooltip = isCustomLocal
|
||||||
|
? '按本机自然周(周一 00:00 起)统计'
|
||||||
|
: '按各配额池独立周限重置周期分别统计并汇总';
|
||||||
|
return { leftText, rightText, tooltip };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 同步单个配额池行的 5h 与每周窗口状态:
|
* 同步单个配额池行的 5h 与每周窗口状态:
|
||||||
* - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行;
|
* - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行;
|
||||||
@@ -250,7 +287,24 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
|||||||
|
|
||||||
const fallbackMetaText = isPending ? '读取中...' : '获取失败 (--%)';
|
const fallbackMetaText = isPending ? '读取中...' : '获取失败 (--%)';
|
||||||
|
|
||||||
patchText(refs.title5h, `5h 限额 (${poolLabel})`);
|
patchText(refs.title5h, `5h (${poolLabel})`);
|
||||||
|
const c5h = poolData?.cycle5h;
|
||||||
|
if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) {
|
||||||
|
const tok5h = formatTokens(c5h.tokens || 0);
|
||||||
|
const cost5h = formatUsd(c5h.costUsd || 0);
|
||||||
|
const calls5h = Number(c5h.calls || 0);
|
||||||
|
refs.usage5h.hidden = false;
|
||||||
|
patchText(refs.usage5h, `· ${tok5h} (${cost5h})`);
|
||||||
|
patchAttr(
|
||||||
|
refs.left5h,
|
||||||
|
'title',
|
||||||
|
`当前 5h 周期累计 (${poolLabel}):${tok5h} Tokens · ${cost5h} · ${calls5h} 次调用`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
refs.usage5h.hidden = true;
|
||||||
|
patchText(refs.usage5h, '');
|
||||||
|
patchAttr(refs.left5h, 'title', null);
|
||||||
|
}
|
||||||
patchText(
|
patchText(
|
||||||
refs.meta5h,
|
refs.meta5h,
|
||||||
has5h
|
has5h
|
||||||
@@ -264,10 +318,27 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const customTitle =
|
const customTitle =
|
||||||
isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
|
useCustomWeekly && fallbackWeekly?.title ? fallbackWeekly.title : `周限 (${poolLabel})`;
|
||||||
? fallbackWeekly.title
|
|
||||||
: `每周限额 (${poolLabel})`;
|
|
||||||
patchText(refs.titleWk, customTitle);
|
patchText(refs.titleWk, customTitle);
|
||||||
|
const cWk = useCustomWeekly
|
||||||
|
? fallbackWeekly
|
||||||
|
: poolData?.cycleWeekly || (isActivePool ? fallbackWeekly : null);
|
||||||
|
if (!isPending && hasWk && cWk && (cWk.tokens != null || cWk.costUsd != null)) {
|
||||||
|
const tokWk = formatTokens(cWk.tokens || 0);
|
||||||
|
const costWk = formatUsd(cWk.costUsd || 0);
|
||||||
|
const callsWk = Number(cWk.calls || 0);
|
||||||
|
refs.usageWk.hidden = false;
|
||||||
|
patchText(refs.usageWk, `· ${tokWk} (${costWk})`);
|
||||||
|
patchAttr(
|
||||||
|
refs.leftWk,
|
||||||
|
'title',
|
||||||
|
`${useCustomWeekly ? '本周自然周累计' : `当前周限周期累计 (${poolLabel})`}:${tokWk} Tokens · ${costWk} · ${callsWk} 次调用`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
refs.usageWk.hidden = true;
|
||||||
|
patchText(refs.usageWk, '');
|
||||||
|
patchAttr(refs.leftWk, 'title', null);
|
||||||
|
}
|
||||||
patchText(
|
patchText(
|
||||||
refs.metaWk,
|
refs.metaWk,
|
||||||
hasWk
|
hasWk
|
||||||
@@ -282,7 +353,10 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function quotaPoolRowSig(item, idx) {
|
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}`;
|
const c5h = item.poolData?.cycle5h;
|
||||||
|
const cWk = item.poolData?.cycleWeekly;
|
||||||
|
const fw = item.fallbackWeekly;
|
||||||
|
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}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LiveOverviewView = defineComponent({
|
export const LiveOverviewView = defineComponent({
|
||||||
@@ -561,7 +635,7 @@ 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;' });
|
||||||
|
|
||||||
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: '' });
|
||||||
|
|
||||||
const quotaPanel = h('section', { className: 'panel' }, [
|
const quotaPanel = h('section', { className: 'panel' }, [
|
||||||
@@ -860,12 +934,10 @@ export const LiveOverviewView = defineComponent({
|
|||||||
ensureLiveTicker();
|
ensureLiveTicker();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标,遵循模型名称格式设置)
|
// 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标,遵循模型名称格式与 Orchestrator ID 格式设置)
|
||||||
const showUpstream = Boolean(data.settings?.showUpstreamModel);
|
const activeModelDisplay = resolveModelDisplayInfo(active, data.settings, {
|
||||||
const activeModelDisplay =
|
fallback: '模型未知',
|
||||||
(showUpstream
|
}).text;
|
||||||
? 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);
|
||||||
@@ -914,9 +986,9 @@ 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 =
|
const agModelDisplay = resolveModelDisplayInfo(ag, data.settings, {
|
||||||
(showUpstream ? ag.activeModelUpstream || ag.activeModelShort : ag.activeModelShort) ||
|
fallback: '模型未知',
|
||||||
'模型未知';
|
}).text;
|
||||||
return {
|
return {
|
||||||
key: ag.agentId,
|
key: ag.agentId,
|
||||||
label: `${ag.badgeText || ag.shortLabel} ${agPct}%`,
|
label: `${ag.badgeText || ag.shortLabel} ${agPct}%`,
|
||||||
@@ -1038,7 +1110,6 @@ 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 weekly = quotas.weekly || {};
|
|
||||||
const minuteTick = Math.floor(Date.now() / 30000);
|
const minuteTick = Math.floor(Date.now() / 30000);
|
||||||
const poolItems = buildQuotaPoolItems(quotas, minuteTick);
|
const poolItems = buildQuotaPoolItems(quotas, minuteTick);
|
||||||
|
|
||||||
@@ -1049,16 +1120,11 @@ export const LiveOverviewView = defineComponent({
|
|||||||
updateRow: syncPoolQuotaRow,
|
updateRow: syncPoolQuotaRow,
|
||||||
});
|
});
|
||||||
|
|
||||||
patchText(
|
const footSummary = formatQuotaSummaryFooter(quotas, data.account);
|
||||||
wkFootLeft,
|
patchText(wkFootLeft, footSummary.leftText);
|
||||||
`本周累计: ${formatTokens(weekly.tokens || 0)} (${formatUsd(weekly.costUsd || 0)})`
|
patchText(wkFootRight, footSummary.rightText);
|
||||||
);
|
patchAttr(wkFootLeft, 'title', footSummary.tooltip);
|
||||||
patchText(
|
patchAttr(wkFootRight, 'title', footSummary.tooltip);
|
||||||
wkFootRight,
|
|
||||||
data.account?.aiCredits > 0
|
|
||||||
? `AI 积分: ${data.account.aiCredits}`
|
|
||||||
: `本周调用: ${weekly.calls || 0} 次`
|
|
||||||
);
|
|
||||||
|
|
||||||
ensureCountdownTicker();
|
ensureCountdownTicker();
|
||||||
viewScrollbar.refresh();
|
viewScrollbar.refresh();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview View 4: SettingsView (系统设置视图).
|
* @fileoverview View 4: SettingsView (系统设置视图).
|
||||||
* 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板:
|
* 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板:
|
||||||
* 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)与模型名称格式(精简代号 / 原始模型 ID);
|
* 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)、模型名称格式(精简代号 / 原始模型 ID)与 Orchestrator 系列 ID 格式;
|
||||||
* 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序;
|
* 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序;
|
||||||
* 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
* 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
||||||
*/
|
*/
|
||||||
@@ -11,8 +11,10 @@ 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,
|
DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||||
|
normalizeClientOrchestratorIdMode,
|
||||||
normalizeClientTopbarSlots,
|
normalizeClientTopbarSlots,
|
||||||
normalizeClientUpdateMode,
|
normalizeClientUpdateMode,
|
||||||
|
normalizeClientWindowMountMode,
|
||||||
saveSettingsPatch,
|
saveSettingsPatch,
|
||||||
telemetryStore,
|
telemetryStore,
|
||||||
triggerCloudSync,
|
triggerCloudSync,
|
||||||
@@ -29,9 +31,16 @@ const STEP_MODEL_DISPLAY_OPTIONS = [
|
|||||||
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
||||||
];
|
];
|
||||||
|
|
||||||
/** 面板挂载模式可选项(顶部栏 + 侧边栏 vs 仅侧边栏) */
|
/** Orchestrator 系列模型 ID 显示方式可选项(独立于普通模型名称格式) */
|
||||||
|
const ORCHESTRATOR_ID_DISPLAY_OPTIONS = [
|
||||||
|
{ value: 'compact', label: '精简代号 (如 orchestrator-argon)' },
|
||||||
|
{ value: 'full', label: '原始完整 ID (如 gemini-pro-orchestrator)' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 面板挂载模式可选项(顶部栏 + 侧边栏 / 输入框 + 侧边栏 / 仅侧边栏) */
|
||||||
const WINDOW_MOUNT_OPTIONS = [
|
const WINDOW_MOUNT_OPTIONS = [
|
||||||
{ value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' },
|
{ value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' },
|
||||||
|
{ value: 'composer', label: '输入框挂载 (输入框 + 侧边栏)' },
|
||||||
{ value: 'sidebar', label: '仅侧边栏' },
|
{ value: 'sidebar', label: '仅侧边栏' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -81,7 +90,9 @@ export const SettingsView = defineComponent({
|
|||||||
name: 'SettingsView',
|
name: 'SettingsView',
|
||||||
setup({ onCleanup }) {
|
setup({ onCleanup }) {
|
||||||
let draftShowUpstreamModel = false;
|
let draftShowUpstreamModel = false;
|
||||||
|
let draftOrchestratorIdMode = 'compact';
|
||||||
let draftPluginUpdateMode = 'manual';
|
let draftPluginUpdateMode = 'manual';
|
||||||
|
let draftWindowMountMode = 'dual';
|
||||||
let draftEnableWindowOverlay = true;
|
let draftEnableWindowOverlay = true;
|
||||||
let draftShowTopbarMulti = true;
|
let draftShowTopbarMulti = true;
|
||||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||||
@@ -144,12 +155,15 @@ export const SettingsView = defineComponent({
|
|||||||
icon: 'dock',
|
icon: 'dock',
|
||||||
options: WINDOW_MOUNT_OPTIONS,
|
options: WINDOW_MOUNT_OPTIONS,
|
||||||
onUpdateModelValue: async (val) => {
|
onUpdateModelValue: async (val) => {
|
||||||
const nextEnable = val !== 'sidebar';
|
const nextMode = normalizeClientWindowMountMode(val);
|
||||||
|
const nextEnable = nextMode !== 'sidebar';
|
||||||
|
draftWindowMountMode = nextMode;
|
||||||
draftEnableWindowOverlay = nextEnable;
|
draftEnableWindowOverlay = nextEnable;
|
||||||
windowMountSelect.setValue(nextEnable ? 'dual' : 'sidebar');
|
windowMountSelect.setValue(nextMode);
|
||||||
showSaveFeedback('保存中…');
|
showSaveFeedback('保存中…');
|
||||||
try {
|
try {
|
||||||
await saveSettingsPatch({
|
await saveSettingsPatch({
|
||||||
|
windowMountMode: nextMode,
|
||||||
enableWindowOverlay: nextEnable,
|
enableWindowOverlay: nextEnable,
|
||||||
});
|
});
|
||||||
showSaveFeedback('已保存');
|
showSaveFeedback('已保存');
|
||||||
@@ -185,6 +199,29 @@ export const SettingsView = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const orchestratorIdSelect = CustomSelect({
|
||||||
|
modelValue: 'compact',
|
||||||
|
icon: 'layers',
|
||||||
|
options: ORCHESTRATOR_ID_DISPLAY_OPTIONS,
|
||||||
|
onUpdateModelValue: async (val) => {
|
||||||
|
const nextMode = normalizeClientOrchestratorIdMode(val);
|
||||||
|
draftOrchestratorIdMode = nextMode;
|
||||||
|
orchestratorIdSelect.setValue(nextMode);
|
||||||
|
showSaveFeedback('保存中…');
|
||||||
|
try {
|
||||||
|
await saveSettingsPatch({
|
||||||
|
orchestratorIdMode: nextMode,
|
||||||
|
});
|
||||||
|
showSaveFeedback('已保存');
|
||||||
|
} catch {
|
||||||
|
if (latestSettings) {
|
||||||
|
renderSettings(latestSettings);
|
||||||
|
}
|
||||||
|
showSaveFeedback('保存失败');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const generalPanel = h('section', { className: 'panel' }, [
|
const generalPanel = h('section', { className: 'panel' }, [
|
||||||
h('div', { className: 'panel-header' }, [
|
h('div', { className: 'panel-header' }, [
|
||||||
h('span', { className: 'panel-title' }, [
|
h('span', { className: 'panel-title' }, [
|
||||||
@@ -201,6 +238,10 @@ export const SettingsView = defineComponent({
|
|||||||
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: 'Orchestrator 系列 ID' }),
|
||||||
|
orchestratorIdSelect.el,
|
||||||
|
]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) ---
|
// --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) ---
|
||||||
@@ -532,16 +573,22 @@ export const SettingsView = defineComponent({
|
|||||||
function renderSettings(settings) {
|
function renderSettings(settings) {
|
||||||
if (!settings) return;
|
if (!settings) return;
|
||||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||||
|
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
|
||||||
draftPluginUpdateMode = normalizeClientUpdateMode(
|
draftPluginUpdateMode = normalizeClientUpdateMode(
|
||||||
settings.pluginUpdateMode,
|
settings.pluginUpdateMode,
|
||||||
settings.autoUpdatePlugin
|
settings.autoUpdatePlugin
|
||||||
);
|
);
|
||||||
draftEnableWindowOverlay = settings.enableWindowOverlay !== false;
|
draftWindowMountMode = normalizeClientWindowMountMode(
|
||||||
|
settings.windowMountMode,
|
||||||
|
settings.enableWindowOverlay
|
||||||
|
);
|
||||||
|
draftEnableWindowOverlay = draftWindowMountMode !== 'sidebar';
|
||||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||||
|
|
||||||
windowMountSelect.setValue(draftEnableWindowOverlay ? 'dual' : 'sidebar');
|
windowMountSelect.setValue(draftWindowMountMode);
|
||||||
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
||||||
|
orchestratorIdSelect.setValue(draftOrchestratorIdMode);
|
||||||
autoUpdateSelect.setValue(draftPluginUpdateMode);
|
autoUpdateSelect.setValue(draftPluginUpdateMode);
|
||||||
syncTopbarControls();
|
syncTopbarControls();
|
||||||
viewScrollbar.refresh();
|
viewScrollbar.refresh();
|
||||||
@@ -623,6 +670,7 @@ export const SettingsView = defineComponent({
|
|||||||
unsubView();
|
unsubView();
|
||||||
windowMountSelect.destroy();
|
windowMountSelect.destroy();
|
||||||
stepModelSelect.destroy();
|
stepModelSelect.destroy();
|
||||||
|
orchestratorIdSelect.destroy();
|
||||||
multiSessionToggle.destroy();
|
multiSessionToggle.destroy();
|
||||||
for (const sel of slotSelects) {
|
for (const sel of slotSelects) {
|
||||||
sel.destroy();
|
sel.destroy();
|
||||||
@@ -636,6 +684,7 @@ export const SettingsView = defineComponent({
|
|||||||
refs: {
|
refs: {
|
||||||
windowMountSelect,
|
windowMountSelect,
|
||||||
stepModelSelect,
|
stepModelSelect,
|
||||||
|
orchestratorIdSelect,
|
||||||
multiSessionToggle,
|
multiSessionToggle,
|
||||||
slotSelects,
|
slotSelects,
|
||||||
resetTopbarBtn,
|
resetTopbarBtn,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+860
-26
File diff suppressed because it is too large
Load Diff
@@ -70,7 +70,7 @@ test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as
|
|||||||
const m20 = h.resolveModelInfo('MODEL_PLACEHOLDER_M20', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
const m20 = h.resolveModelInfo('MODEL_PLACEHOLDER_M20', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
||||||
assert.equal(m20.modelId, 'gemini-3.5-flash');
|
assert.equal(m20.modelId, 'gemini-3.5-flash');
|
||||||
|
|
||||||
// Gemini Hydrogen (3.8 Flash pricing) & Helix (3.5 Flash Lite pricing), shared Gemini pool
|
// Gemini Hydrogen ($1.50/$0.15/$7.50 unified pricing) & Helix (3.5 Flash Lite pricing), shared Gemini pool
|
||||||
const dynHydrogenMap = new Map([
|
const dynHydrogenMap = new Map([
|
||||||
['MODEL_PLACEHOLDER_M480', { modelId: '', label: 'Gemini 4 Hydrogen (High)' }],
|
['MODEL_PLACEHOLDER_M480', { modelId: '', label: 'Gemini 4 Hydrogen (High)' }],
|
||||||
['MODEL_PLACEHOLDER_M481', { modelId: '', label: 'Gemini 4 Hydrogen (Low)' }],
|
['MODEL_PLACEHOLDER_M481', { modelId: '', label: 'Gemini 4 Hydrogen (Low)' }],
|
||||||
@@ -81,18 +81,19 @@ test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as
|
|||||||
assert.equal(hydroHigh.shortName, 'hydrogen-4-high');
|
assert.equal(hydroHigh.shortName, 'hydrogen-4-high');
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
{ i: hydroHigh.pricing?.input, c: hydroHigh.pricing?.cache, o: hydroHigh.pricing?.output },
|
{ i: hydroHigh.pricing?.input, c: hydroHigh.pricing?.cache, o: hydroHigh.pricing?.output },
|
||||||
{ i: 0.75, c: 0.075, o: 3.75 }
|
{ i: 1.5, c: 0.15, o: 7.5 }
|
||||||
);
|
);
|
||||||
const hydroLow = h.resolveModelInfo('MODEL_PLACEHOLDER_M481', dynHydrogenMap);
|
const hydroLow = h.resolveModelInfo('MODEL_PLACEHOLDER_M481', dynHydrogenMap);
|
||||||
assert.equal(hydroLow.shortName, 'hydrogen-4-low');
|
assert.equal(hydroLow.shortName, 'hydrogen-4-low');
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
{ i: hydroLow.pricing?.input, c: hydroLow.pricing?.cache, o: hydroLow.pricing?.output },
|
{ i: hydroLow.pricing?.input, c: hydroLow.pricing?.cache, o: hydroLow.pricing?.output },
|
||||||
{ i: 0.3, c: 0.03, o: 2.5 }
|
{ i: 1.5, c: 0.15, o: 7.5 }
|
||||||
);
|
);
|
||||||
const hydroCodename = h.resolveModelInfo('gemini-hydrogen');
|
const hydroCodename = h.resolveModelInfo('gemini-hydrogen');
|
||||||
assert.equal(hydroCodename.family, 'Gemini');
|
assert.equal(hydroCodename.family, 'Gemini');
|
||||||
assert.equal(hydroCodename.label, 'Gemini Hydrogen');
|
assert.equal(hydroCodename.label, 'Gemini Hydrogen');
|
||||||
assert.equal(hydroCodename.pricing?.input, 0.75);
|
assert.equal(hydroCodename.pricing?.input, 1.5);
|
||||||
|
assert.equal(hydroCodename.pricing?.output, 7.5);
|
||||||
|
|
||||||
const helixInfo = h.resolveModelInfo('MODEL_PLACEHOLDER_M482', dynHydrogenMap);
|
const helixInfo = h.resolveModelInfo('MODEL_PLACEHOLDER_M482', dynHydrogenMap);
|
||||||
assert.equal(helixInfo.family, 'Gemini');
|
assert.equal(helixInfo.family, 'Gemini');
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ const DEFAULT_BUNDLED_CATALOG = {
|
|||||||
|
|
||||||
const BACKEND_MODULE_FILES = [
|
const BACKEND_MODULE_FILES = [
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
|
'../backend/ls-discovery.mjs',
|
||||||
'../backend/pricing-catalog.mjs',
|
'../backend/pricing-catalog.mjs',
|
||||||
'../backend/plugin-updater.mjs',
|
'../backend/plugin-updater.mjs',
|
||||||
'../backend/ls-rpc.mjs',
|
'../backend/ls-rpc.mjs',
|
||||||
@@ -24,6 +25,7 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../backend/usage-aggregator.mjs',
|
'../backend/usage-aggregator.mjs',
|
||||||
'../backend/telemetry-builder.mjs',
|
'../backend/telemetry-builder.mjs',
|
||||||
'../backend/window-bridge.mjs',
|
'../backend/window-bridge.mjs',
|
||||||
|
'../backend/api-actions.mjs',
|
||||||
'../main.mjs',
|
'../main.mjs',
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -144,6 +146,6 @@ export function backendHarness({
|
|||||||
return {ok:true,json:async()=>data};
|
return {ok:true,json:async()=>data};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
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,loadSettings,executeSettingsAction};',ctx);
|
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,loadSettings,executeSettingsAction};',ctx);
|
||||||
return {...ctx.api,state};
|
return {...ctx.api,state};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -542,3 +542,229 @@ test('supports Gemini 4 Carbon pricing/pool and resolves all newly added languag
|
|||||||
assert.equal(p.quotas.activePool.poolKey, 'Carbon');
|
assert.equal(p.quotas.activePool.poolKey, 'Carbon');
|
||||||
assert.equal(p.quotas.activePool.weeklyRemainingIntPct, 65);
|
assert.equal(p.quotas.activePool.weeklyRemainingIntPct, 65);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('trendSeries preserves 1-day-per-slot granularity for >90 day spans and recentSteps separates thinking vs response tokens', async () => {
|
||||||
|
const nowMs = Date.now();
|
||||||
|
const oldStartMs = nowMs - 120 * 24 * 3600 * 1000;
|
||||||
|
const oldStartIso = new Date(oldStartMs).toISOString();
|
||||||
|
const oldEndIso = new Date(oldStartMs + 6000).toISOString();
|
||||||
|
const recentStartIso = new Date(nowMs - 8000).toISOString();
|
||||||
|
const recentEndIso = new Date(nowMs - 1000).toISOString();
|
||||||
|
|
||||||
|
const h = backendHarness({
|
||||||
|
trajectories: {
|
||||||
|
cLong: {
|
||||||
|
trajectory: {
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||||
|
createdAt: oldStartIso,
|
||||||
|
finishedGeneratingAt: oldEndIso,
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M429',
|
||||||
|
inputTokens: '10000',
|
||||||
|
cacheReadTokens: '20000',
|
||||||
|
outputTokens: '700',
|
||||||
|
thinkingOutputTokens: '420',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'early step' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 2 },
|
||||||
|
createdAt: recentStartIso,
|
||||||
|
finishedGeneratingAt: recentEndIso,
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M429',
|
||||||
|
inputTokens: '5000',
|
||||||
|
cacheReadTokens: '32115',
|
||||||
|
outputTokens: '685',
|
||||||
|
thinkingOutputTokens: '420',
|
||||||
|
responseOutputTokens: '265',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'recent step' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
summaries: {
|
||||||
|
cLong: { stepCount: 2, lastModifiedTime: recentEndIso, status: 'IDLE' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const pAll = await h.buildTelemetryPayloadInternal('cLong', false, { range: 'all' });
|
||||||
|
const trendAll = pAll.consumption.trendSeries;
|
||||||
|
assert.ok(trendAll.length >= 120 && trendAll.length <= 122, `Expected ~121 daily slots, got ${trendAll.length}`);
|
||||||
|
assert.equal(trendAll[0].granularity, 'day');
|
||||||
|
assert.match(trendAll[0].fullLabel, /^\d{4}年\d+月\d+日 \(周[日一二三四五六]\)$/);
|
||||||
|
assert.equal(trendAll.reduce((sum, b) => sum + b.tokens, 0), 30700 + 37800);
|
||||||
|
assert.equal(trendAll.reduce((sum, b) => sum + b.calls, 0), 2);
|
||||||
|
|
||||||
|
const steps = pAll.activeConversation.recentSteps;
|
||||||
|
assert.equal(steps.length, 2);
|
||||||
|
// recentSteps is reversed (newest first)
|
||||||
|
assert.equal(steps[0].contextTokens, 37800);
|
||||||
|
assert.equal(steps[0].thinkingTokens, 420);
|
||||||
|
assert.equal(steps[0].responseTokens, 265);
|
||||||
|
assert.equal(steps[1].thinkingTokens, 420);
|
||||||
|
assert.equal(steps[1].responseTokens, 280);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
|
||||||
|
const {
|
||||||
|
computeLinearFit,
|
||||||
|
computeLoessFit,
|
||||||
|
computePublicationFit,
|
||||||
|
getStepModelGroupKey,
|
||||||
|
toChronologicalSteps,
|
||||||
|
} = await import('../src/components/charts/SessionStepCharts.js');
|
||||||
|
|
||||||
|
// 1. Verify OLS + publication LOESS + 95% CI confidence band & [0, 100] cache bounds
|
||||||
|
const olsExact = computeLinearFit([10, 20, 30, 40]);
|
||||||
|
assert.ok(Math.abs(olsExact.slope - 10) < 1e-9);
|
||||||
|
assert.ok(Math.abs(olsExact.r - 1) < 1e-9);
|
||||||
|
assert.ok(Math.abs(olsExact.r2 - 1) < 1e-9);
|
||||||
|
assert.deepEqual(
|
||||||
|
olsExact.values.map((v) => +v.toFixed(4)),
|
||||||
|
[10, 20, 30, 40]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify bimodal / high-peak TPS series is NOT crushed flat by Bisquare and builds valid 95% CI band
|
||||||
|
const waveXs = Array.from({ length: 20 }, (_, idx) => idx * 5 + 1);
|
||||||
|
const waveYs = [
|
||||||
|
22, 26, 48, 78, 92, 85, 64, 34, 24, 28,
|
||||||
|
55, 84, 76, 42, 25, 22, 26, 32, 38, 44,
|
||||||
|
];
|
||||||
|
const pubWave = computePublicationFit(waveXs, waveYs, { minVal: 0 });
|
||||||
|
assert.equal(pubWave.method, 'LOESS');
|
||||||
|
assert.equal(pubWave.grid.length, 64);
|
||||||
|
assert.ok(
|
||||||
|
pubWave.grid.every((g) => g.ciLow <= g.fit + 1e-9 && g.fit <= g.ciHigh + 1e-9),
|
||||||
|
'Every grid point satisfies ciLow <= fit <= ciHigh'
|
||||||
|
);
|
||||||
|
// Around peak x ~ 21 (index 4), fitted conditional expectation must rise well above overall mean (~47)
|
||||||
|
assert.ok(pubWave.sampleFits[4] > 55, `Expected peak conditional mean > 55, got ${pubWave.sampleFits[4]}`);
|
||||||
|
|
||||||
|
// Warmup cache curve stays clamped within [0, 100]
|
||||||
|
const cacheSeries = [0, 90, 92, 93, 94, 95, 95];
|
||||||
|
const loessCache = computeLoessFit(cacheSeries, { minVal: 0, maxVal: 100 });
|
||||||
|
assert.equal(loessCache.length, cacheSeries.length);
|
||||||
|
assert.ok(
|
||||||
|
loessCache.every((v) => v >= 0 && v <= 100),
|
||||||
|
'Fitted cache values must stay clamped within [0, 100]'
|
||||||
|
);
|
||||||
|
assert.ok(loessCache[6] > 90, 'Tail fit tracks steady warm cache region');
|
||||||
|
|
||||||
|
// Group key strips [自动压缩] and thinking tier suffixes
|
||||||
|
assert.equal(getStepModelGroupKey({ modelLabel: 'Gemini 3.1 Pro (High) [自动压缩]' }), 'Gemini 3.1 Pro');
|
||||||
|
assert.equal(getStepModelGroupKey({ modelLabel: 'Orchestrator (Carbon)' }), 'Orchestrator (Carbon)');
|
||||||
|
|
||||||
|
const chrono = toChronologicalSteps(
|
||||||
|
[
|
||||||
|
{ stepIndex: 3, createdAtMs: 3000 },
|
||||||
|
{ stepIndex: 1, createdAtMs: 1000 },
|
||||||
|
{ stepIndex: 2, createdAtMs: 2000 },
|
||||||
|
],
|
||||||
|
true
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
chrono.map((s) => s.stepIndex),
|
||||||
|
[1, 2, 3]
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. Verify backend modelBreakdown enriches avgTtftSec and cacheHitPct for main & subagents
|
||||||
|
const h = backendHarness({
|
||||||
|
trajectories: {
|
||||||
|
'root-fit': {
|
||||||
|
trajectory: {
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: '2026-06-01T00:00:00Z',
|
||||||
|
finishedGeneratingAt: '2026-06-01T00:00:10Z',
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
inputTokens: '1000',
|
||||||
|
cacheReadTokens: '9000',
|
||||||
|
outputTokens: '500',
|
||||||
|
thinkingOutputTokens: '100',
|
||||||
|
responseOutputTokens: '400',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'main step 1' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: { createdAt: '2026-06-01T00:00:12Z' },
|
||||||
|
invokeSubagent: {
|
||||||
|
subagents: [{ typeName: 'research', role: 'Fast Researcher' }],
|
||||||
|
results: [{ conversationId: 'sub-fit' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
generatorMetadata: [
|
||||||
|
{ stepIndices: [0], chatModel: { timeToFirstToken: '2.4s', streamingDuration: '7.6s' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'sub-fit': {
|
||||||
|
trajectory: {
|
||||||
|
metadata: { parentConversationId: 'root-fit', subagentSpec: { typeName: 'research' } },
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: '2026-06-01T00:00:15Z',
|
||||||
|
finishedGeneratingAt: '2026-06-01T00:00:20Z',
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M18',
|
||||||
|
inputTokens: '2000',
|
||||||
|
cacheReadTokens: '6000',
|
||||||
|
outputTokens: '400',
|
||||||
|
thinkingOutputTokens: '50',
|
||||||
|
responseOutputTokens: '350',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'sub step 1' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
generatorMetadata: [
|
||||||
|
{ stepIndices: [0], chatModel: { timeToFirstToken: '0.8s', streamingDuration: '4.2s' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
summaries: {
|
||||||
|
'root-fit': { stepCount: 2, lastModifiedTime: '2026-06-01T00:00:12Z', status: 'IDLE' },
|
||||||
|
'sub-fit': {
|
||||||
|
stepCount: 1,
|
||||||
|
lastModifiedTime: '2026-06-01T00:00:20Z',
|
||||||
|
status: 'IDLE',
|
||||||
|
trajectoryMetadata: { parentConversationId: 'root-fit' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = await h.buildTelemetryPayloadInternal('root-fit');
|
||||||
|
const mainMb = payload.activeConversation.modelBreakdown;
|
||||||
|
assert.equal(mainMb.length, 1);
|
||||||
|
assert.equal(mainMb[0].avgTtftSec, 2.4);
|
||||||
|
assert.equal(mainMb[0].ttftSampleCount, 1);
|
||||||
|
assert.equal(mainMb[0].cacheHitPct, 90);
|
||||||
|
|
||||||
|
const subMb = payload.activeConversation.agents[1].modelBreakdown;
|
||||||
|
assert.equal(subMb.length, 1);
|
||||||
|
assert.equal(subMb[0].avgTtftSec, 0.8);
|
||||||
|
assert.equal(subMb[0].cacheHitPct, 75);
|
||||||
|
|
||||||
|
const aggMb = payload.activeConversation.aggregated.modelBreakdown;
|
||||||
|
assert.equal(aggMb.length, 2);
|
||||||
|
});
|
||||||
|
|||||||
@@ -3,7 +3,11 @@ import assert from 'node:assert/strict';
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import vm from 'node:vm';
|
import vm from 'node:vm';
|
||||||
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs';
|
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs';
|
||||||
import { formatUsd } from '../src/core/formatters.js';
|
import {
|
||||||
|
formatUsd,
|
||||||
|
mergeModelsByDisplayName,
|
||||||
|
resolveModelDisplayInfo,
|
||||||
|
} from '../src/core/formatters.js';
|
||||||
import { backendHarness } from './backend-harness.mjs';
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
|
|
||||||
const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418';
|
const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418';
|
||||||
@@ -195,3 +199,500 @@ test('frontend considers a model-only correction a real telemetry update', () =>
|
|||||||
const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model';
|
const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model';
|
||||||
assert.equal(ctx.compare(a,b),false); assert.equal(ctx.compare(a,structuredClone(a)),true);
|
assert.equal(ctx.compare(a,b),false); assert.equal(ctx.compare(a,structuredClone(a)),true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
|
||||||
|
const ORCH_ARGON = 'MODEL_PLACEHOLDER_M681';
|
||||||
|
const ORCH_EXEC_HYDROGEN = 'MODEL_PLACEHOLDER_M669';
|
||||||
|
|
||||||
|
test('Orchestrator (Carbon) direct/planning and inferred compaction steps resolve to orch-carbon and annotate upstream ID', async () => {
|
||||||
|
const rows = [step(1, ORCH_CARBON), step(2, undefined, true), step(3, ORCH_CARBON)];
|
||||||
|
const raw = {
|
||||||
|
trajectory: {
|
||||||
|
steps: rows,
|
||||||
|
generatorMetadata: [
|
||||||
|
{
|
||||||
|
stepIndices: [1],
|
||||||
|
chatModel: {
|
||||||
|
model: ORCH_CARBON,
|
||||||
|
responseModel: 'gemini-pro-orchestrator',
|
||||||
|
modelDisplayName: 'Orchestrator (Carbon)',
|
||||||
|
},
|
||||||
|
plannerConfig: {
|
||||||
|
planModel: ORCH_CARBON,
|
||||||
|
modelName: 'gemini-pro-orchestrator',
|
||||||
|
planExecuteConfig: { executionModel: ORCH_EXEC_HYDROGEN },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stepIndices: [3],
|
||||||
|
chatModel: {
|
||||||
|
model: ORCH_CARBON,
|
||||||
|
responseModel: 'gemini-pro-orchestrator',
|
||||||
|
modelDisplayName: 'Orchestrator (Carbon)',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const p = await payload(rows, { trajectories: { test: raw } });
|
||||||
|
const s1 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 1);
|
||||||
|
const cp = p.activeConversation.recentSteps.find((s) => s.stepIndex === 2);
|
||||||
|
|
||||||
|
assert.equal(s1.modelShort, 'orch-carbon');
|
||||||
|
assert.equal(s1.modelUpstream, 'gemini-pro-orchestrator (carbon-4)');
|
||||||
|
assert.equal(s1.costUsd, 0.0129);
|
||||||
|
assert.equal(cp.modelKey, ORCH_CARBON);
|
||||||
|
assert.equal(cp.modelSource, 'inferred_compaction');
|
||||||
|
assert.equal(cp.modelShort, 'orch-carbon·压缩');
|
||||||
|
assert.equal(cp.modelUpstream, 'gemini-pro-orchestrator (carbon-4)·压缩');
|
||||||
|
assert.equal(p.activeConversation.activeModelShort, 'orch-carbon');
|
||||||
|
assert.equal(p.activeConversation.activeModelUpstream, 'gemini-pro-orchestrator (carbon-4)');
|
||||||
|
assert.equal(p.consumption.account.unpricedCalls, 0);
|
||||||
|
assert.equal(p.modelBreakdown.length, 1);
|
||||||
|
assert.equal(p.modelBreakdown[0].label, 'Orchestrator (Carbon)');
|
||||||
|
assert.equal(p.modelBreakdown[0].upstreamName, 'gemini-pro-orchestrator (carbon-4)');
|
||||||
|
assert.equal(p.modelBreakdown[0].calls, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Orchestrator (Argon) resolves to orch-argon, annotates upstream ID, and is not misclassified as Carbon', async () => {
|
||||||
|
const h = backendHarness({
|
||||||
|
summaries: { test: { stepCount: 1 } },
|
||||||
|
trajectories: {
|
||||||
|
test: {
|
||||||
|
trajectory: {
|
||||||
|
steps: [step(1, ORCH_ARGON)],
|
||||||
|
generatorMetadata: [
|
||||||
|
{
|
||||||
|
stepIndices: [1],
|
||||||
|
chatModel: {
|
||||||
|
model: ORCH_ARGON,
|
||||||
|
responseModel: 'gemini-pro-orchestrator-argon',
|
||||||
|
modelDisplayName: 'Orchestrator (Argon)',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const p = await h.buildTelemetryPayloadInternal('test');
|
||||||
|
const s1 = p.activeConversation.recentSteps[0];
|
||||||
|
assert.equal(s1.modelShort, 'orch-argon');
|
||||||
|
assert.equal(s1.modelUpstream, 'gemini-pro-orchestrator-argon (argon-4)');
|
||||||
|
assert.equal(s1.costUsd, 0.0129);
|
||||||
|
assert.equal(p.modelBreakdown[0].label, 'Orchestrator (Argon)');
|
||||||
|
assert.equal(p.modelBreakdown[0].upstreamName, 'gemini-pro-orchestrator-argon (argon-4)');
|
||||||
|
assert.equal(h.isArgonModelIdentifier(ORCH_ARGON, 'gemini-pro-orchestrator-argon', 'Orchestrator (Argon)'), true);
|
||||||
|
assert.equal(h.isCarbonModelIdentifier(ORCH_ARGON, 'gemini-pro-orchestrator-argon', 'Orchestrator (Argon)'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('real-world M669 worker steps (responseModel gemini-flash-worker-agy, displayName Gemini Flash) and uncatalogued executionModel resolve to Hydrogen', async () => {
|
||||||
|
const FUTURE_EXEC_PH = 'MODEL_PLACEHOLDER_M799';
|
||||||
|
const rows = [step(1, ORCH_CARBON), step(2, ORCH_EXEC_HYDROGEN), step(3, FUTURE_EXEC_PH)];
|
||||||
|
const raw = {
|
||||||
|
trajectory: {
|
||||||
|
steps: rows,
|
||||||
|
generatorMetadata: [
|
||||||
|
{
|
||||||
|
stepIndices: [1],
|
||||||
|
chatModel: {
|
||||||
|
model: ORCH_CARBON,
|
||||||
|
responseModel: 'gemini-pro-orchestrator',
|
||||||
|
modelDisplayName: 'Orchestrator (Carbon)',
|
||||||
|
},
|
||||||
|
plannerConfig: {
|
||||||
|
planModel: ORCH_CARBON,
|
||||||
|
modelName: 'gemini-pro-orchestrator',
|
||||||
|
planExecuteConfig: { executionModel: FUTURE_EXEC_PH },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stepIndices: [2],
|
||||||
|
chatModel: {
|
||||||
|
model: ORCH_EXEC_HYDROGEN,
|
||||||
|
responseModel: 'gemini-flash-worker-agy',
|
||||||
|
modelDisplayName: 'Gemini Flash',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stepIndices: [3],
|
||||||
|
chatModel: {
|
||||||
|
model: FUTURE_EXEC_PH,
|
||||||
|
responseModel: 'gemini-flash-worker-agy',
|
||||||
|
modelDisplayName: 'Gemini Flash',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const p = await payload(rows, { trajectories: { test: raw } });
|
||||||
|
const s1 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 1);
|
||||||
|
const s2 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 2);
|
||||||
|
const s3 = p.activeConversation.recentSteps.find((s) => s.stepIndex === 3);
|
||||||
|
|
||||||
|
assert.equal(s1.modelShort, 'orch-carbon');
|
||||||
|
assert.equal(s1.modelUpstream, 'gemini-pro-orchestrator (carbon-4)');
|
||||||
|
assert.equal(s1.costUsd, 0.0129);
|
||||||
|
|
||||||
|
assert.equal(s2.modelShort, 'hydrogen-4');
|
||||||
|
assert.equal(s2.modelLabel, 'Orchestrator Worker (Hydrogen)');
|
||||||
|
assert.equal(s2.modelUpstream, 'gemini-flash-worker-agy (hydrogen-4)');
|
||||||
|
assert.equal(s2.costUsd, 0.0103);
|
||||||
|
|
||||||
|
assert.equal(s3.modelShort, 'hydrogen-4');
|
||||||
|
assert.equal(s3.modelLabel, 'Orchestrator Worker (Hydrogen)');
|
||||||
|
assert.equal(s3.modelUpstream, 'gemini-flash-worker-agy (hydrogen-4)');
|
||||||
|
assert.equal(s3.costUsd, 0.0103);
|
||||||
|
|
||||||
|
assert.equal(p.consumption.account.unpricedCalls, 0);
|
||||||
|
const orchRow = p.modelBreakdown.find((m) => m.label === 'Orchestrator (Carbon)');
|
||||||
|
const hydroRow = p.modelBreakdown.find((m) => m.label === 'Orchestrator Worker (Hydrogen)');
|
||||||
|
assert.ok(orchRow && hydroRow, 'modelBreakdown keeps orchestrator planning separate from Hydrogen worker');
|
||||||
|
assert.equal(p.modelBreakdown.some((m) => m.label === 'Gemini Flash'), false);
|
||||||
|
assert.equal(orchRow.calls, 1);
|
||||||
|
assert.equal(hydroRow.calls, 2);
|
||||||
|
assert.equal(hydroRow.upstreamName, 'gemini-flash-worker-agy (hydrogen-4)');
|
||||||
|
|
||||||
|
// Also verify already-cached M669 worker steps carrying vague "Gemini Flash" or transitional "Gemini 4 Hydrogen" resolve cleanly
|
||||||
|
const cachedStep = {
|
||||||
|
...extractModelSteps([step(10, ORCH_EXEC_HYDROGEN)])[0],
|
||||||
|
responseModel: 'gemini-flash-worker-agy',
|
||||||
|
modelDisplayName: 'Gemini Flash',
|
||||||
|
};
|
||||||
|
const cachedTransitionalDirect = {
|
||||||
|
...extractModelSteps([step(11, 'MODEL_PLACEHOLDER_M528')])[0],
|
||||||
|
modelDisplayName: 'Gemini 4 Hydrogen (XHigh)',
|
||||||
|
};
|
||||||
|
const hCached = backendHarness({
|
||||||
|
cache: { test: { signature: 'v13-clean:2:', steps: [cachedStep, cachedTransitionalDirect] } },
|
||||||
|
trajectories: { test: new Error('offline') },
|
||||||
|
});
|
||||||
|
const pCached = await hCached.buildTelemetryPayloadInternal('test');
|
||||||
|
assert.equal(pCached.activeConversation.activeModelShort, 'hydrogen-4-xhigh');
|
||||||
|
assert.equal(
|
||||||
|
pCached.modelBreakdown.find((m) => m.label === 'Orchestrator Worker (Hydrogen)')?.upstreamName,
|
||||||
|
'gemini-flash-worker-agy (hydrogen-4)'
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
pCached.modelBreakdown.find((m) => m.label === 'Gemini 4 Hydrogen'),
|
||||||
|
'direct Gemini 4 Hydrogen remains in its own breakdown bucket separate from worker-agy'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('new Carbon (M427/M437/M438) and Hydrogen XHigh/High/Medium/Low (M525-M528) placeholders resolve and group cleanly', () => {
|
||||||
|
const { resolveModelInfo, getBaseModelLabel } = backendHarness();
|
||||||
|
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M427').shortName, 'carbon-4-high');
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M437').shortName, 'carbon-4');
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M438').shortName, 'carbon-4-low');
|
||||||
|
|
||||||
|
const xhigh = resolveModelInfo('MODEL_PLACEHOLDER_M528');
|
||||||
|
assert.equal(xhigh.shortName, 'hydrogen-4-xhigh');
|
||||||
|
assert.equal(xhigh.baseLabel, 'Gemini 4 Hydrogen');
|
||||||
|
assert.equal(xhigh.pricing.input, 1.5);
|
||||||
|
assert.equal(xhigh.pricing.cache, 0.15);
|
||||||
|
assert.equal(xhigh.pricing.output, 7.5);
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M525').shortName, 'hydrogen-4-high');
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M526').shortName, 'hydrogen-4');
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M527').shortName, 'hydrogen-4-low');
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M527').pricing.input, 1.5);
|
||||||
|
assert.equal(resolveModelInfo('MODEL_PLACEHOLDER_M527').pricing.output, 7.5);
|
||||||
|
|
||||||
|
assert.equal(getBaseModelLabel('Orchestrator (Carbon)'), 'Orchestrator (Carbon)');
|
||||||
|
assert.equal(getBaseModelLabel('Orchestrator (Argon)'), 'Orchestrator (Argon)');
|
||||||
|
assert.equal(getBaseModelLabel('Orchestrator Worker (Hydrogen)'), 'Orchestrator Worker (Hydrogen)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('orchestratorIdMode defaults to compact, persists via settings action, and controls Orchestrator series independently of showUpstreamModel', () => {
|
||||||
|
const h = backendHarness();
|
||||||
|
assert.equal(h.loadSettings().orchestratorIdMode, 'compact');
|
||||||
|
|
||||||
|
const resFull = h.executeSettingsAction({ orchestratorIdMode: 'full' });
|
||||||
|
assert.equal(resFull.ok, true);
|
||||||
|
assert.equal(resFull.updated.orchestratorIdMode, 'full');
|
||||||
|
|
||||||
|
const resInvalid = h.executeSettingsAction({ orchestratorIdMode: 'unexpected' });
|
||||||
|
assert.equal(resInvalid.updated.orchestratorIdMode, 'compact');
|
||||||
|
|
||||||
|
const orchCarbon = {
|
||||||
|
modelKey: ORCH_CARBON,
|
||||||
|
modelShort: 'orch-carbon',
|
||||||
|
modelLabel: 'Orchestrator (Carbon)',
|
||||||
|
modelUpstream: 'gemini-pro-orchestrator (carbon-4)',
|
||||||
|
responseModel: 'gemini-pro-orchestrator',
|
||||||
|
};
|
||||||
|
const orchArgon = {
|
||||||
|
modelKey: ORCH_ARGON,
|
||||||
|
modelShort: 'orch-argon',
|
||||||
|
modelLabel: 'Orchestrator (Argon)',
|
||||||
|
modelUpstream: 'gemini-pro-orchestrator-argon (argon-4)',
|
||||||
|
responseModel: 'gemini-pro-orchestrator-argon',
|
||||||
|
};
|
||||||
|
const orchWorkerCompaction = {
|
||||||
|
modelKey: ORCH_EXEC_HYDROGEN,
|
||||||
|
modelShort: 'hydrogen-4·压缩',
|
||||||
|
modelLabel: 'Orchestrator Worker (Hydrogen) [自动压缩]',
|
||||||
|
modelUpstream: 'gemini-flash-worker-agy (hydrogen-4)·压缩',
|
||||||
|
responseModel: 'gemini-flash-worker-agy',
|
||||||
|
isCompactionStep: true,
|
||||||
|
};
|
||||||
|
const directHydrogen = {
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M528',
|
||||||
|
modelShort: 'hydrogen-4-xhigh',
|
||||||
|
modelLabel: 'Gemini 4 Hydrogen (XHigh)',
|
||||||
|
modelUpstream: 'gemini-4-hydrogen-xhigh',
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const showUpstreamModel of [false, true]) {
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(orchCarbon, { showUpstreamModel, orchestratorIdMode: 'compact' }).text,
|
||||||
|
'orchestrator-carbon'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'compact' }).text,
|
||||||
|
'orchestrator-argon'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'compact' }).text,
|
||||||
|
'worker-agy-hydrogen·压缩'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(orchCarbon, { showUpstreamModel, orchestratorIdMode: 'full' }).text,
|
||||||
|
'gemini-pro-orchestrator (carbon-4)'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(orchArgon, { showUpstreamModel, orchestratorIdMode: 'full' }).text,
|
||||||
|
'gemini-pro-orchestrator-argon (argon-4)'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(orchWorkerCompaction, { showUpstreamModel, orchestratorIdMode: 'full' }).text,
|
||||||
|
'gemini-flash-worker-agy (hydrogen-4)·压缩'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Non-Orchestrator direct Hydrogen still follows showUpstreamModel regardless of orchestratorIdMode
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(directHydrogen, { showUpstreamModel: false, orchestratorIdMode: 'compact' }).text,
|
||||||
|
'hydrogen-4-xhigh'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(directHydrogen, { showUpstreamModel: true, orchestratorIdMode: 'compact' }).text,
|
||||||
|
'gemini-4-hydrogen-xhigh'
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
resolveModelDisplayInfo(directHydrogen, { showUpstreamModel: false, orchestratorIdMode: 'full' }, { preferLabelInShort: true }).text,
|
||||||
|
'Gemini 4 Hydrogen (XHigh)'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('historical placeholders (M15/M16/M47/M84/M132/M133/M264/M330) and verified internal routing slugs resolve and price accurately without wildcarding unknown slugs', () => {
|
||||||
|
const { resolveModelInfo } = backendHarness();
|
||||||
|
|
||||||
|
const expectedPlaceholders = [
|
||||||
|
['MODEL_PLACEHOLDER_M84', 'flash-3.5-high', 1.5, 9.0],
|
||||||
|
['MODEL_PLACEHOLDER_M15', 'flash-3.5-high', 1.5, 9.0],
|
||||||
|
['MODEL_PLACEHOLDER_M132', 'flash-3.5-high', 1.5, 9.0],
|
||||||
|
['MODEL_PLACEHOLDER_M133', 'flash-3.5', 1.5, 9.0],
|
||||||
|
['MODEL_PLACEHOLDER_M47', 'flash-3', 0.5, 3.0],
|
||||||
|
['MODEL_PLACEHOLDER_M16', 'pro-3.1-high', 2.0, 12.0],
|
||||||
|
['MODEL_PLACEHOLDER_M264', 'flash-3.6-high', 0.75, 3.75],
|
||||||
|
['MODEL_PLACEHOLDER_M330', 'flash-2.5-lite', 0.1, 0.4],
|
||||||
|
];
|
||||||
|
for (const [ph, shortName, inputPrice, outputPrice] of expectedPlaceholders) {
|
||||||
|
const info = resolveModelInfo(ph);
|
||||||
|
assert.equal(info.shortName, shortName, `${ph} shortName`);
|
||||||
|
assert.ok(info.pricing, `${ph} should have pricing`);
|
||||||
|
assert.equal(info.pricing.input, inputPrice, `${ph} input price`);
|
||||||
|
assert.equal(info.pricing.output, outputPrice, `${ph} output price`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedSlugs = [
|
||||||
|
['gemini-3-flash-a', 'flash-3.5', 1.5, 9.0],
|
||||||
|
['gemini-3-flash-b', 'flash-3.5', 1.5, 9.0],
|
||||||
|
['gemini-3-flash-c', 'flash-3', 0.5, 3.0],
|
||||||
|
['gemini-3-flash-d', 'flash-3.5', 1.5, 9.0],
|
||||||
|
['gemini-3-flash-agent', 'flash-3.5', 1.5, 9.0],
|
||||||
|
['gemini-pro-default', 'pro-3.1', 2.0, 12.0],
|
||||||
|
['gemini-pro-agent', 'pro-3.1', 2.0, 12.0],
|
||||||
|
['gemini-pro-b', 'pro-3.1', 2.0, 12.0],
|
||||||
|
['gemini-3.7-flash-safety-le', 'flash-3.7', 0.75, 3.75],
|
||||||
|
['gemini-3.8-flash-n', 'flash-3.8', 0.75, 3.75],
|
||||||
|
['gemini-4-argon-f', 'argon-4', 2.0, 10.0],
|
||||||
|
['gemini-4-argon-disabled', 'argon-4', 2.0, 10.0],
|
||||||
|
];
|
||||||
|
for (const [slug, shortName, inputPrice, outputPrice] of expectedSlugs) {
|
||||||
|
const info = resolveModelInfo(slug);
|
||||||
|
assert.equal(info.shortName, shortName, `${slug} shortName`);
|
||||||
|
assert.ok(info.pricing, `${slug} should have pricing`);
|
||||||
|
assert.equal(info.pricing.input, inputPrice, `${slug} input price`);
|
||||||
|
assert.equal(info.pricing.output, outputPrice, `${slug} output price`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unverified future variant must still remain unpriced (no reckless prefix fallback)
|
||||||
|
const unknownVariant = resolveModelInfo('gemini-3.1-pro-ultra-v2');
|
||||||
|
assert.equal(unknownVariant.pricing, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deep_stats session-display mislabeling is ignored when step-intrinsic model differs, and micro-costs preserve 6-decimal precision', async () => {
|
||||||
|
const nowIso = new Date(Date.now() - 5_000).toISOString();
|
||||||
|
const h = backendHarness({
|
||||||
|
summaries: {
|
||||||
|
ide_convo: { stepCount: 1 },
|
||||||
|
},
|
||||||
|
trajectories: {
|
||||||
|
ide_convo: {
|
||||||
|
trajectory: {
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||||
|
createdAt: nowIso,
|
||||||
|
completedAt: new Date(Date.now() - 4_000).toISOString(),
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE',
|
||||||
|
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
inputTokens: '1900',
|
||||||
|
cacheReadTokens: '0',
|
||||||
|
outputTokens: '107',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
deepStats: {
|
||||||
|
perConvo: {
|
||||||
|
'standalone:11111111-2222-3333-4444-555555555555': {
|
||||||
|
appSource: 'standalone',
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
ts: nowIso,
|
||||||
|
model: 'gemini-2.5-flash-lite',
|
||||||
|
modelCanonicalId: 'gemini-2.5-flash-lite',
|
||||||
|
modelAggregationId: 'session-display:gemini-3-5-flash-lite',
|
||||||
|
modelDisplayName: 'Gemini 3.5 Flash Lite',
|
||||||
|
provider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
inp: 12300,
|
||||||
|
cache: 0,
|
||||||
|
out: 154,
|
||||||
|
reasoning: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ts: nowIso,
|
||||||
|
model: 'gemini-3-flash-a',
|
||||||
|
modelCanonicalId: 'gemini-3-flash-a',
|
||||||
|
modelAggregationId: 'session:gemini-3-flash-a',
|
||||||
|
provider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
inp: 3320000,
|
||||||
|
cache: 32730000,
|
||||||
|
out: 120000,
|
||||||
|
reasoning: 195500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const p = await h.buildTelemetryPayloadInternal('ide_convo');
|
||||||
|
const consumptionModels = p.modelBreakdown;
|
||||||
|
|
||||||
|
// Both gemini-2.5-flash-lite calls (IDE + standalone with session-display:gemini-3-5-flash-lite) merge into one Gemini 2.5 Flash Lite bucket!
|
||||||
|
const flash25Rows = consumptionModels.filter((m) => /2\.5 Flash Lite/i.test(m.label));
|
||||||
|
assert.equal(flash25Rows.length, 1);
|
||||||
|
assert.equal(
|
||||||
|
consumptionModels.some((m) => /3\.5 Flash Lite/i.test(m.label)),
|
||||||
|
false,
|
||||||
|
'mismatched session-display:gemini-3-5-flash-lite should not create a bogus Gemini 3.5 Flash Lite bucket'
|
||||||
|
);
|
||||||
|
assert.equal(flash25Rows[0].calls, 2);
|
||||||
|
assert.equal(flash25Rows[0].unpricedCalls, 0);
|
||||||
|
// 14,200 input * $0.10/M + 261 output * $0.40/M = $0.0015244 -> 0.001524 (> 0, not truncated to 0!)
|
||||||
|
assert.equal(flash25Rows[0].costUsd, 0.001524);
|
||||||
|
|
||||||
|
// Also check single-step micro-cost (< $0.001) on activeConversation.modelBreakdown
|
||||||
|
const sessionFlash25 = p.activeConversation.modelBreakdown.find((m) => /2\.5 Flash Lite/i.test(m.label));
|
||||||
|
assert.ok(sessionFlash25);
|
||||||
|
// 1,900 * $0.10/M + 107 * $0.40/M = $0.0002328 -> 0.000233
|
||||||
|
assert.equal(sessionFlash25.costUsd, 0.000233);
|
||||||
|
assert.equal(formatUsd(sessionFlash25.costUsd, { precise: true }), '<$0.001');
|
||||||
|
assert.equal(formatUsd(flash25Rows[0].costUsd, { precise: true }), '$0.002');
|
||||||
|
|
||||||
|
// Standalone session:gemini-3-flash-a entry preserves responseModel & prices cleanly
|
||||||
|
const flash35Row = consumptionModels.find((m) => m.label === 'Gemini 3.5 Flash');
|
||||||
|
assert.ok(flash35Row);
|
||||||
|
assert.equal(flash35Row.upstreamName, 'gemini-3-flash-a');
|
||||||
|
assert.equal(flash35Row.unpricedCalls, 0);
|
||||||
|
assert.ok(flash35Row.costUsd > 12);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mergeModelsByDisplayName collapses distinct backend buckets that share the same rendered display text', () => {
|
||||||
|
const rawModels = [
|
||||||
|
{
|
||||||
|
label: 'Gemini 3.8 Flash',
|
||||||
|
shortName: 'flash-3.8',
|
||||||
|
upstreamName: 'gemini-3-flash-a',
|
||||||
|
upstreamModels: ['gemini-3-flash-a', 'gemini-3.8-flash'],
|
||||||
|
calls: 7063,
|
||||||
|
inputTokens: 91_800_000,
|
||||||
|
cacheReadTokens: 674_810_000,
|
||||||
|
outputTokens: 5_510_000,
|
||||||
|
thinkingTokens: 3_130_000,
|
||||||
|
responseTokens: 2_380_000,
|
||||||
|
totalTokens: 772_120_000,
|
||||||
|
costUsd: 286.2,
|
||||||
|
unpricedCalls: 0,
|
||||||
|
avgTokPerSec: 120,
|
||||||
|
speedSummary: { sampleCount: 100, excludedCount: 5, avgTokPerSec: 120 },
|
||||||
|
avgTtftSec: 2.0,
|
||||||
|
ttftSampleCount: 100,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Gemini 3.5 Flash',
|
||||||
|
shortName: 'flash-3.5',
|
||||||
|
upstreamName: 'gemini-3-flash-a',
|
||||||
|
upstreamModels: ['gemini-3-flash-a'],
|
||||||
|
calls: 449,
|
||||||
|
inputTokens: 3_320_000,
|
||||||
|
cacheReadTokens: 32_730_000,
|
||||||
|
outputTokens: 315_500,
|
||||||
|
thinkingTokens: 195_500,
|
||||||
|
responseTokens: 120_000,
|
||||||
|
totalTokens: 36_365_500,
|
||||||
|
costUsd: 12.73,
|
||||||
|
unpricedCalls: 0,
|
||||||
|
avgTokPerSec: 80,
|
||||||
|
speedSummary: { sampleCount: 100, excludedCount: 2, avgTokPerSec: 80 },
|
||||||
|
avgTtftSec: 4.0,
|
||||||
|
ttftSampleCount: 100,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// In upstream mode, both resolve to 'gemini-3-flash-a' -> merged into 1 row!
|
||||||
|
const mergedUpstream = mergeModelsByDisplayName(
|
||||||
|
rawModels,
|
||||||
|
{ showUpstreamModel: true },
|
||||||
|
{ preferLabelInShort: true }
|
||||||
|
);
|
||||||
|
assert.equal(mergedUpstream.length, 1);
|
||||||
|
assert.equal(mergedUpstream[0].displayText, 'gemini-3-flash-a');
|
||||||
|
assert.equal(mergedUpstream[0].calls, 7512);
|
||||||
|
assert.equal(mergedUpstream[0].totalTokens, 808_485_500);
|
||||||
|
assert.equal(mergedUpstream[0].costUsd, 298.93);
|
||||||
|
assert.equal(mergedUpstream[0].avgTokPerSec, 100);
|
||||||
|
assert.equal(mergedUpstream[0].avgTtftSec, 3);
|
||||||
|
assert.deepEqual(mergedUpstream[0].sourceLabels, ['Gemini 3.8 Flash', 'Gemini 3.5 Flash']);
|
||||||
|
|
||||||
|
// In friendly label mode, 'Gemini 3.8 Flash' and 'Gemini 3.5 Flash' stay distinct!
|
||||||
|
const mergedShort = mergeModelsByDisplayName(
|
||||||
|
rawModels,
|
||||||
|
{ showUpstreamModel: false },
|
||||||
|
{ preferLabelInShort: true }
|
||||||
|
);
|
||||||
|
assert.equal(mergedShort.length, 2);
|
||||||
|
});
|
||||||
|
|||||||
@@ -308,6 +308,12 @@ test('telemetryStore isEquivalentTelemetry detects quota changes in non-active p
|
|||||||
b.quotas.pools[1].weeklyUsedPct = 55;
|
b.quotas.pools[1].weeklyUsedPct = 55;
|
||||||
b.quotas.pools[1].weeklyRemainingPct = 45;
|
b.quotas.pools[1].weeklyRemainingPct = 45;
|
||||||
assert.equal(ctx.compare(a, b), false);
|
assert.equal(ctx.compare(a, b), false);
|
||||||
|
const c = structuredClone(a);
|
||||||
|
c.quotas.pools[0].cycleWeekly = { tokens: 120_000, costUsd: 0.35, calls: 4 };
|
||||||
|
assert.equal(ctx.compare(a, c), false, 'Pool cycleWeekly change must trigger store update');
|
||||||
|
const d = structuredClone(a);
|
||||||
|
d.quotas.pools[0].cycle5h = { tokens: 50_000, costUsd: 0.15, calls: 2 };
|
||||||
|
assert.equal(ctx.compare(a, d), false, 'Pool cycle5h change must trigger store update');
|
||||||
assert.equal(ctx.compare(a, structuredClone(a)), true);
|
assert.equal(ctx.compare(a, structuredClone(a)), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -395,3 +401,228 @@ test('switching accounts within 10s immediately invalidates quotaSummaryCache',
|
|||||||
);
|
);
|
||||||
assert.equal(second.quotas.pools[0].weeklyRemainingPct, 8.7);
|
assert.equal(second.quotas.pools[0].weeklyRemainingPct, 8.7);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Orchestrator quota pool binding follows active phase: Carbon/Argon while planning, Gemini when offloaded to Hydrogen', async () => {
|
||||||
|
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
|
||||||
|
const ORCH_ARGON = 'MODEL_PLACEHOLDER_M681';
|
||||||
|
const ORCH_EXEC_HYDROGEN = 'MODEL_PLACEHOLDER_M669';
|
||||||
|
const geminiReset = new Date(Date.now() + 24 * 3600_000).toISOString();
|
||||||
|
const argonReset = new Date(Date.now() + 48 * 3600_000).toISOString();
|
||||||
|
const carbonReset = new Date(Date.now() + 72 * 3600_000).toISOString();
|
||||||
|
const fiveHourReset = new Date(Date.now() + 2 * 3600_000).toISOString();
|
||||||
|
|
||||||
|
const h = backendHarness({
|
||||||
|
summaries: {
|
||||||
|
orchCarbonPlan: { stepCount: 1 },
|
||||||
|
orchArgonPlan: { stepCount: 1 },
|
||||||
|
orchHydrogenExec: { stepCount: 2 },
|
||||||
|
},
|
||||||
|
trajectories: {
|
||||||
|
orchCarbonPlan: { trajectory: { steps: [makeStep(1, ORCH_CARBON)] } },
|
||||||
|
orchArgonPlan: { trajectory: { steps: [makeStep(1, ORCH_ARGON)] } },
|
||||||
|
orchHydrogenExec: {
|
||||||
|
trajectory: { steps: [makeStep(1, ORCH_CARBON), makeStep(2, ORCH_EXEC_HYDROGEN)] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
userStatus: {
|
||||||
|
userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' },
|
||||||
|
cascadeModelConfigData: {
|
||||||
|
clientModelConfigs: [
|
||||||
|
{
|
||||||
|
label: 'Orchestrator (Carbon)',
|
||||||
|
modelId: 'gemini-pro-orchestrator',
|
||||||
|
modelOrAlias: { model: ORCH_CARBON },
|
||||||
|
quotaInfo: { remainingFraction: 0.4, resetTime: carbonReset },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Orchestrator (Argon)',
|
||||||
|
modelId: 'gemini-pro-orchestrator-argon',
|
||||||
|
modelOrAlias: { model: ORCH_ARGON },
|
||||||
|
quotaInfo: { remainingFraction: 0.6, resetTime: argonReset },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Gemini 3.8 Flash (High)',
|
||||||
|
modelId: 'gemini-3.8-flash-high',
|
||||||
|
modelOrAlias: { model: FLASH },
|
||||||
|
quotaInfo: { remainingFraction: 0.9, resetTime: geminiReset },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
quotaSummary: {
|
||||||
|
groups: [
|
||||||
|
{
|
||||||
|
displayName: 'Gemini Models',
|
||||||
|
buckets: [
|
||||||
|
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.95, resetTime: fiveHourReset },
|
||||||
|
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.9, resetTime: geminiReset },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayName: 'Gemini 4 Argon',
|
||||||
|
buckets: [
|
||||||
|
{ bucketId: 'argon-weekly', window: 'weekly', remainingFraction: 0.6, resetTime: argonReset },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayName: 'Gemini 4 Carbon',
|
||||||
|
buckets: [
|
||||||
|
{ bucketId: 'carbon-weekly', window: 'weekly', remainingFraction: 0.4, resetTime: carbonReset },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const pCarbon = await h.buildTelemetryPayloadInternal('orchCarbonPlan');
|
||||||
|
assert.equal(pCarbon.quotas.activePool.family, 'Carbon');
|
||||||
|
assert.equal(pCarbon.quotas.weekly.poolFamily, 'Carbon');
|
||||||
|
assert.equal(pCarbon.quotas.weekly.remainingPct, 40);
|
||||||
|
|
||||||
|
const pArgon = await h.buildTelemetryPayloadInternal('orchArgonPlan');
|
||||||
|
assert.equal(pArgon.quotas.activePool.family, 'Argon');
|
||||||
|
assert.equal(pArgon.quotas.weekly.poolFamily, 'Argon');
|
||||||
|
assert.equal(pArgon.quotas.weekly.remainingPct, 60);
|
||||||
|
|
||||||
|
const pExec = await h.buildTelemetryPayloadInternal('orchHydrogenExec');
|
||||||
|
assert.equal(pExec.quotas.activePool.family, 'Gemini');
|
||||||
|
assert.equal(pExec.quotas.weekly.poolFamily, 'Gemini');
|
||||||
|
assert.equal(pExec.quotas.weekly.remainingPct, 90);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('per-pool cycle5h and cycleWeekly isolate each pool by its own reset window and sum into quotas.weekly', async () => {
|
||||||
|
const now = Date.now();
|
||||||
|
const CLAUDE_SONNET = 'MODEL_CLAUDE_4_5_SONNET';
|
||||||
|
// Gemini weekly cycle started 1d ago (resets in +6d); 5h cycle started 1h ago (resets in +4h)
|
||||||
|
const geminiWkReset = new Date(now + 6 * 24 * 3600_000).toISOString();
|
||||||
|
const gemini5hReset = new Date(now + 4 * 3600_000).toISOString();
|
||||||
|
// Argon weekly cycle started 5d ago (resets in +2d)
|
||||||
|
const argonWkReset = new Date(now + 2 * 24 * 3600_000).toISOString();
|
||||||
|
// Claude & GPT weekly cycle started 6d ago (resets in +1d); 5h cycle started 4h ago (resets in +1h)
|
||||||
|
const claudeWkReset = new Date(now + 1 * 24 * 3600_000).toISOString();
|
||||||
|
const claude5hReset = new Date(now + 1 * 3600_000).toISOString();
|
||||||
|
|
||||||
|
const makeTimedStep = (idx, model, ageMs, provider = 'API_PROVIDER_GOOGLE_GEMINI', tok = 10_000) => {
|
||||||
|
const t = now - ageMs;
|
||||||
|
return {
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: idx },
|
||||||
|
createdAt: new Date(t).toISOString(),
|
||||||
|
completedAt: new Date(t + 2_000).toISOString(),
|
||||||
|
modelUsage: {
|
||||||
|
model,
|
||||||
|
apiProvider: provider,
|
||||||
|
inputTokens: String(tok),
|
||||||
|
cacheReadTokens: '0',
|
||||||
|
outputTokens: '1000',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const h = backendHarness({
|
||||||
|
summaries: { multiCycleConv: { stepCount: 6 } },
|
||||||
|
trajectories: {
|
||||||
|
multiCycleConv: {
|
||||||
|
trajectory: {
|
||||||
|
steps: [
|
||||||
|
// 1. Gemini Flash 30m ago -> inside Gemini 5h (1h ago) & Gemini weekly (1d ago)
|
||||||
|
makeTimedStep(1, FLASH, 30 * 60_000, 'API_PROVIDER_GOOGLE_GEMINI', 10_000),
|
||||||
|
// 2. Gemini Flash 3h ago -> OUTSIDE Gemini 5h (started 1h ago), INSIDE Gemini weekly (1d ago)
|
||||||
|
makeTimedStep(2, FLASH, 3 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 20_000),
|
||||||
|
// 3. Gemini Flash 3d ago -> OUTSIDE Gemini weekly (started 1d ago)!
|
||||||
|
makeTimedStep(3, FLASH, 3 * 24 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 99_000),
|
||||||
|
// 4. Argon 3d ago -> INSIDE Argon weekly (started 5d ago)!
|
||||||
|
makeTimedStep(4, ARGON, 3 * 24 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 40_000),
|
||||||
|
// 5. Claude 3h ago -> INSIDE Claude 5h (started 4h ago) & Claude weekly (started 6d ago)
|
||||||
|
makeTimedStep(5, CLAUDE_SONNET, 3 * 3600_000, 'API_PROVIDER_ANTHROPIC', 30_000),
|
||||||
|
// 6. Claude 4d ago -> OUTSIDE Claude 5h, INSIDE Claude weekly (started 6d ago)
|
||||||
|
makeTimedStep(6, CLAUDE_SONNET, 4 * 24 * 3600_000, 'API_PROVIDER_ANTHROPIC', 50_000),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
userStatus: {
|
||||||
|
userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' },
|
||||||
|
cascadeModelConfigData: {
|
||||||
|
clientModelConfigs: [
|
||||||
|
{
|
||||||
|
label: 'Gemini 3.8 Flash (High)',
|
||||||
|
modelId: 'gemini-3.8-flash-high',
|
||||||
|
modelOrAlias: { model: FLASH },
|
||||||
|
quotaInfo: { remainingFraction: 0.85, resetTime: gemini5hReset },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Gemini 4 Argon (High)',
|
||||||
|
modelId: 'gemini-4-argon-high',
|
||||||
|
modelOrAlias: { model: ARGON },
|
||||||
|
quotaInfo: { remainingFraction: 0.6, resetTime: argonWkReset },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Claude 4.5 Sonnet',
|
||||||
|
modelId: 'claude-sonnet-4-5',
|
||||||
|
modelOrAlias: { model: CLAUDE_SONNET },
|
||||||
|
quotaInfo: { remainingFraction: 0.7, resetTime: claude5hReset },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
quotaSummary: {
|
||||||
|
groups: [
|
||||||
|
{
|
||||||
|
displayName: 'Gemini Models',
|
||||||
|
buckets: [
|
||||||
|
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.85, resetTime: gemini5hReset },
|
||||||
|
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.8, resetTime: geminiWkReset },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayName: 'Gemini 4 Argon',
|
||||||
|
buckets: [
|
||||||
|
{ bucketId: 'argon-weekly', window: 'weekly', remainingFraction: 0.6, resetTime: argonWkReset },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
displayName: 'Claude and GPT models',
|
||||||
|
buckets: [
|
||||||
|
{ bucketId: '3p-5h', window: '5h', remainingFraction: 0.7, resetTime: claude5hReset },
|
||||||
|
{ bucketId: '3p-weekly', window: 'weekly', remainingFraction: 0.5, resetTime: claudeWkReset },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const p = await h.buildTelemetryPayloadInternal('multiCycleConv');
|
||||||
|
const byKey = new Map(p.quotas.pools.map((pool) => [pool.poolKey, pool]));
|
||||||
|
|
||||||
|
const geminiPool = byKey.get('Gemini');
|
||||||
|
const argonPool = byKey.get('Argon');
|
||||||
|
const claudePool = byKey.get('Claude & GPT');
|
||||||
|
|
||||||
|
// Gemini: step 1 (11,000) in 5h; steps 1+2 (32,000) in weekly; step 3 (3d ago) excluded!
|
||||||
|
assert.equal(geminiPool.cycle5h.calls, 1);
|
||||||
|
assert.equal(geminiPool.cycle5h.tokens, 11_000);
|
||||||
|
assert.equal(geminiPool.cycleWeekly.calls, 2);
|
||||||
|
assert.equal(geminiPool.cycleWeekly.tokens, 32_000);
|
||||||
|
|
||||||
|
// Argon: step 4 (41,000) in weekly (3d ago < 5d window)
|
||||||
|
assert.equal(argonPool.cycleWeekly.calls, 1);
|
||||||
|
assert.equal(argonPool.cycleWeekly.tokens, 41_000);
|
||||||
|
|
||||||
|
// Claude & GPT: step 5 (31,000) in 5h; steps 5+6 (82,000) in weekly (4d ago < 6d window, not clipped by Gemini's 1d window!)
|
||||||
|
assert.equal(claudePool.cycle5h.calls, 1);
|
||||||
|
assert.equal(claudePool.cycle5h.tokens, 31_000);
|
||||||
|
assert.equal(claudePool.cycleWeekly.calls, 2);
|
||||||
|
assert.equal(claudePool.cycleWeekly.tokens, 82_000);
|
||||||
|
|
||||||
|
// Global quotas.weekly equals the exact sum across all pools' weekly cycles (2 + 1 + 2 = 5 calls; 32k + 41k + 82k = 155k tokens)
|
||||||
|
assert.equal(p.quotas.weekly.calls, 5);
|
||||||
|
assert.equal(p.quotas.weekly.tokens, 155_000);
|
||||||
|
assert.equal(
|
||||||
|
p.quotas.weekly.costUsd,
|
||||||
|
+(geminiPool.cycleWeekly.costUsd + argonPool.cycleWeekly.costUsd + claudePool.cycleWeekly.costUsd).toFixed(2)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user