mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
Merge pull request #16 from yuhuan-dev/release/v1.5.0
feat(panel): Antigravity IDE/CLI & standalone mode, composer mount, modular preferences, and session charts (v1.5.0)
This commit is contained in:
@@ -2,5 +2,7 @@
|
||||
node_modules/
|
||||
plan/
|
||||
*.log
|
||||
*.dpapi
|
||||
.account-test-*
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
English | [简体中文](README.zh-CN.md)
|
||||
|
||||
**Real-time dual-mount monitor for Google Antigravity IDE.**
|
||||
Track token generation speed (TPS), time-to-first-token (TTFT), context window usage, official model quotas, subagent activity, and historical token consumption — across Windows, macOS, and Linux.
|
||||
**Real-time usage & speed monitor for Google Antigravity 2.0, IDE, and CLI.**<br>
|
||||
Track token generation speed (TPS), time-to-first-token (TTFT), context window usage, official model quotas, subagent activity, and historical token consumption — across Windows, macOS, Linux, and headless CLI servers.
|
||||
|
||||

|
||||
|
||||
@@ -49,9 +49,11 @@ The dashboard is organized into four tabs, with a top header to switch conversat
|
||||
- **By Step**: Lists every step in the selected conversation with its model, TPS, TTFT, context/output tokens, cache hit rate, and step cost.
|
||||
- **By Model**: Aggregates call counts, mean speed, total tokens, and cost per model within the current session and selected agent scope.
|
||||
- **Preferences**
|
||||
- **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.
|
||||
- **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).
|
||||
- **Mount Mode & Popover Width**: Choose Dual-mount (Top Bar + Sidebar), Composer mount, or Sidebar only; the floating popover defaults to **Auto Fit** (expanding automatically on wide step tables within viewport bounds to avoid horizontal scrolling) or accepts a custom fixed width (`440–1080 px`).
|
||||
- **Top-Bar & CLI Capsule Customization**: Independently toggle the live running-sessions indicator and the Antigravity CLI bottom status capsule (auto-provisioned via `~/.gemini/antigravity-cli/settings.json` `statusLine`), and customize 1 to 5 metric slots and their left-to-right order (defaulting to Output Speed, TTFT, and Context Usage).
|
||||
- **Call Details & Custom Token Combos**: Under **Structure -> Step Table**, independently toggle main/subagent badges, the turn rail (off by default), and **Speed Multi-Color** grading (off by default); keep the default `Ctx / Think / Reply` combo column, switch to the billing-aligned `In / Out / Cache` preset (with per-segment cost breakdown on hover), or enter a custom format string such as `context:new:cache` or `in:out:cache`.
|
||||
- **Model Name Format**: Choose among Compact short alias (e.g. `argon-4-high`), full raw upstream ID, or Trimmed raw ID (hiding `gemini-`, `claude-`, and `gpt-` prefixes to save single-line space, e.g. `3.8-flash-n`, `sonnet-4-6`, `5.4-mini`), with compaction suffixes (`·compact`) protected from ellipsis truncation; Orchestrator series IDs remain independently configurable.
|
||||
- **Per-model context windows**: In **Other → Model Context Settings**, choose a shared limit for all thinking levels of a model or select **Follow host settings**. The model list shows the saved limit and the most recent value reported by the host. At startup, the App / IDE window bridge reads the latest model catalog and reapplies saved limits to future messages. The CLI uses `AGY_CLI_AUTO_COMPACT_OVERRIDE`.
|
||||
- **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
|
||||
@@ -98,8 +100,23 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
||||
## Enabling & Opening the Panel
|
||||
|
||||
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.
|
||||
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.
|
||||
2. **Top-Bar Floating Capsule (enabled by default on both Antigravity 2.0 & Antigravity IDE)**:
|
||||
- **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.
|
||||
4. **Antigravity CLI Bottom Status Capsule & Headless Standalone Web Mode**:
|
||||
- **CLI Bottom Status Capsule (`statusLine`, enabled by default)**: When `~/.gemini/antigravity-cli` is present, the plugin automatically configures native `statusLine` in `settings.json` (any existing custom third-party `statusLine.command` is strictly preserved) to render a single-line transparent 24-bit ANSI status bar at the bottom of `agy` (keeping `? for shortcuts` on the left, live metrics such as `● 1 active 38.1 t/s | 0.85s | ◎ 17%` centered, and mode/model/effort on the right). Toggle it anytime via `/statusline` in the CLI or **Preferences -> Mount & Capsule Bar**.
|
||||
- **Offline Transcript Fallback & Auto-Upgrade**: On terminal-only machines or remote Linux servers, the backend automatically discovers `~/.gemini/antigravity-cli` (`daemon/hub_*.json`, SQLite `.db` trajectories, and `transcript.jsonl`). When `agy` is offline, historical sessions and token accounting still load from local records and automatically upgrade to full live RPC telemetry once `agy` starts.
|
||||
- **Manual launch (recommended with SSH port forwarding)**:
|
||||
```bash
|
||||
# On the remote server (binds strictly to 127.0.0.1:8787 by default)
|
||||
node ~/.gemini/config/plugins/usage-monitor/sidecars/panel/standalone.mjs --port 8787
|
||||
|
||||
# Forward from your local machine, then open http://localhost:8787
|
||||
ssh -L 8787:127.0.0.1:8787 user@your-server
|
||||
```
|
||||
- **Auto-host alongside `agy`**: Set `USAGE_MONITOR_STANDALONE_PORT=8787` or `"standalonePort": 8787` in `~/.gemini/antigravity-cli/sidecar_data/usage-monitor/panel/data/settings.json` to host the standalone Web UI automatically whenever the plugin's MCP supervisor starts.
|
||||
- **Token-protected non-loopback access**: Binding to `0.0.0.0` or a LAN IP requires `--token <secret>` (or `USAGE_MONITOR_STANDALONE_TOKEN`); unauthenticated non-loopback startup is refused.
|
||||
|
||||
## Updating
|
||||
|
||||
|
||||
+24
-7
@@ -2,8 +2,8 @@
|
||||
|
||||
[English](README.md) | 简体中文
|
||||
|
||||
**Google Antigravity IDE 实时双栖监控插件。**
|
||||
一站式查看生成速度(TPS)、首字延迟(TTFT)、十维上下文窗口占用、官方模型配额、子代理追踪与历史 Token 消耗(支持 Windows / macOS / Linux)。
|
||||
**Google Antigravity 2.0 / IDE / CLI 实时监控插件。**<br>
|
||||
一站式查看生成速度(TPS)、首字延迟(TTFT)、十维上下文窗口占用、官方模型配额、子代理追踪与历史 Token 消耗(支持 Windows / macOS / Linux 及无头服务器 CLI)。
|
||||
|
||||

|
||||
|
||||
@@ -49,9 +49,11 @@
|
||||
- 按步查看:列出当前会话全部步骤的模型、输出速度、首字延迟、上下文/输出 Token、缓存命中率与单步费用。
|
||||
- 按模型汇总:按当前所选会话(及所选主/子代理范围)统计各模型的调用次数、均速、总 Token 与费用。
|
||||
- **偏好设置**
|
||||
- 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。
|
||||
- 顶部栏定制:独立开关实时运行会话入口,并自由定义右侧三个指标槽位的显示内容与排列顺序。
|
||||
- 选择模型名称格式:精简代号或原始模型 ID,并可独立设置 Orchestrator 系列显示精简代号(如 `orchestrator-argon`、`worker-agy-hydrogen`)或原始完整 ID。
|
||||
- 选择面板挂载方式与悬浮窗宽度:支持双栖挂载(顶部栏 + 侧边栏)、输入框挂载与仅侧边栏;悬浮面板默认按表格内容自动适配增宽(免水平滚动且自动受窗口边界约束),也可手动指定 `440~1080 px` 固定宽度。
|
||||
- 顶部栏与 CLI 胶囊定制:独立开关实时运行会话入口与 Antigravity CLI 底部状态胶囊(自动写入 `~/.gemini/antigravity-cli/settings.json` 的 `statusLine`),并自由定义 1 至 5 个指标槽位的显示内容与排列顺序(默认为输出速度、首字延迟、上下文占用)。
|
||||
- 调用明细显示与自定义 Token 组合:在「界面编排 -> 调用明细字段」可独立开关主/子代理标识、对话轮次导轨(默认关闭)与输出速度多色分级(默认关闭);默认保留 `上下文 / 思考 / 正文` 组合列,同时提供对齐计费维度的 `输入 / 输出 / 缓存` 可选组合列(悬停显示对应三项费用拆解),并支持输入 `context:new:cache`、`in:out:cache` 等自定义格式字符串自由拼装单列指标。
|
||||
- 选择模型名称格式:提供精简代号(如 `argon-4-high`)、原始模型 ID 与去前缀原始 ID(自动隐藏 `gemini-` / `claude-` / `gpt-` 前缀以节省单行空间,如 `3.8-flash-n`、`sonnet-4-6`、`5.4-mini`)三档,且自动压缩尾标(`·压缩`)独立保护永不截断;Orchestrator 系列仍可独立设置精简或完整 ID。
|
||||
- 按模型设置上下文:在「其他 → 模型上下文设置」为同一模型的各推理档统一设置上限,或切回「跟随宿主设置」。列表右侧显示已设置的上限和宿主最近报告的数值。App / IDE 窗口桥接在插件启动时重新读取宿主模型目录并应用已保存的设置,适用于之后发送的消息。CLI 使用 `AGY_CLI_AUTO_COMPACT_OVERRIDE`。
|
||||
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并提供「仅提示新版本,手动更新」(默认)、「自动更新」与「关闭更新」三档更新方式。
|
||||
|
||||
## 模型识别与费用口径
|
||||
@@ -98,8 +100,23 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
||||
## 启用与打开面板
|
||||
|
||||
1. 打开左侧边栏的 **Customizations**,进入 **Installed** 标签页,找到 `usage-monitor` 并开启。
|
||||
2. **顶部栏胶囊悬浮面板(默认双栖开启)**:开启插件后,后台 Sidecar 会自动在主对话窗口右上角顶部栏挂载实时状态与指标胶囊(悬停查看速览,左键展开完整四标签面板,右键强制刷新),全程不修改宿主 `app.asar`。如需关闭顶部栏胶囊,可在 **偏好设置 -> 面板挂载方式** 中切换为「仅侧边栏」。
|
||||
3. **右侧辅助栏面板**:点击对话窗口右上角 `⋮` -> **Extensions** -> **用量监控**,在右侧辅助栏展开面板;或在对话中输入「打开用量监控面板」通过快捷入口唤起。
|
||||
2. **顶部栏胶囊悬浮面板(默认开启,兼容 Antigravity 2.0 与 Antigravity IDE)**:
|
||||
- **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 对话窗口点击右上角菜单打开右侧辅助栏中的 **用量监控**,或在 **偏好设置 -> 面板挂载方式** 中按需切换「顶部栏 + 侧边栏」与「仅侧边栏」。
|
||||
4. **Antigravity CLI 底部状态胶囊与独立 Web 模式**:
|
||||
- **CLI 底部状态胶囊(`statusLine`,默认开启)**:本机存在 `~/.gemini/antigravity-cli` 时,插件会自动配置原生 `statusLine`(若你已配置自定义脚本则原样保留,绝不覆盖),在 `agy` 终端底栏单行内联展示无背景色的多会话状态与监控指标(左侧保留 `? for shortcuts`,中间显示如 `● 1 运行中 38.1 t/s | 0.85s | ◎ 17%`,右侧保留模式与模型档位),也可在 CLI 内输入 `/statusline` 或在面板 **偏好设置 -> 挂载胶囊** 中随时开关。
|
||||
- **本地离线日志与自动重连**:在纯终端或远程 Linux 服务器上,插件会自动扫描 `~/.gemini/antigravity-cli`(含 `daemon/hub_*.json`、SQLite `.db` 对话轨迹与 `transcript.jsonl`);即使 `agy` 暂未运行,也会基于本地日志离线展示历史会话与 Token 消耗,并在 `agy` 启动后自动重连升级为完整遥测。
|
||||
- **手动启动(推荐配合 SSH 端口转发)**:
|
||||
```bash
|
||||
# 在远程服务器上启动(默认仅监听 127.0.0.1:8787)
|
||||
node ~/.gemini/config/plugins/usage-monitor/sidecars/panel/standalone.mjs --port 8787
|
||||
|
||||
# 在本地电脑转发端口后,浏览器打开 http://localhost:8787
|
||||
ssh -L 8787:127.0.0.1:8787 user@your-server
|
||||
```
|
||||
- **随 `agy` 后台自动托管**:设置环境变量 `USAGE_MONITOR_STANDALONE_PORT=8787`,或在 `~/.gemini/antigravity-cli/sidecar_data/usage-monitor/panel/data/settings.json` 中写入 `"standalonePort": 8787`,启用插件后即随 `agy` 自动监听该端口。
|
||||
- **非回环地址受保护访问**:若需显式绑定 `0.0.0.0` 或局域网地址,必须同时指定 `--token <密钥>`(或 `USAGE_MONITOR_STANDALONE_TOKEN`),未配置令牌时服务端会拒绝非回环启动。
|
||||
|
||||
## 更新
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"host": {
|
||||
"command": "node",
|
||||
"args": [
|
||||
"${PLUGIN_ROOT}/sidecars/panel/mcp-entry.mjs"
|
||||
],
|
||||
"env": {
|
||||
"USAGE_MONITOR_PLUGIN_DATA": "${PLUGIN_DATA}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "usage-monitor",
|
||||
"displayName": "Usage & Speed Monitor",
|
||||
"version": "1.4.5",
|
||||
"version": "1.5.0",
|
||||
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
||||
"logo": "assets/logo.svg",
|
||||
"suggestedPrompts": [
|
||||
|
||||
+23
-3
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"catalogVersion": "2026.11.13.3",
|
||||
"updatedAt": "2026-11-13T17:10:00+09:00",
|
||||
"latestPluginVersion": "1.4.5",
|
||||
"catalogVersion": "2026.11.15.1",
|
||||
"updatedAt": "2026-11-15T15:00:00+09:00",
|
||||
"latestPluginVersion": "1.5.0",
|
||||
"releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest",
|
||||
"downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
|
||||
"archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main",
|
||||
@@ -18,6 +18,8 @@
|
||||
"gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini" },
|
||||
"gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
||||
"gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini" },
|
||||
"gemini-4-argon-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-hydrogen-xhigh": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4-xhigh", "family": "Gemini" },
|
||||
"gemini-4-hydrogen-high": { "input": 1.50, "cache": 0.15, "output": 7.50, "short": "hydrogen-4-high", "family": "Gemini" },
|
||||
@@ -44,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-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-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.7-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7-high", "family": "Gemini" },
|
||||
"gemini-3.7-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" },
|
||||
"gemini-3.7-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.7-low", "family": "Gemini" },
|
||||
"gemini-3.7-flash-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" },
|
||||
"gemini-3.7-flash-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.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" },
|
||||
@@ -59,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-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-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.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" },
|
||||
@@ -66,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-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-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": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" },
|
||||
"gemini-for-google-3.1-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1", "family": "Gemini" },
|
||||
"gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1-img", "family": "Gemini" },
|
||||
"gemini-3-flash-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" },
|
||||
"gemini-3-flash-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-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" },
|
||||
@@ -157,24 +169,32 @@
|
||||
"MODEL_PLACEHOLDER_M299": { "modelId": "gemini-3.7-flash-medium", "label": "Gemini 3.7 Flash (Medium)" },
|
||||
"MODEL_PLACEHOLDER_M300": { "modelId": "gemini-3.7-flash-low", "label": "Gemini 3.7 Flash (Low)" },
|
||||
"MODEL_PLACEHOLDER_M301": { "modelId": "gemini-3.7-flash-tiered", "label": "Gemini 3.7 Flash (Tiered)" },
|
||||
"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_M72": { "modelId": "gemini-3.6-flash-medium", "label": "Gemini 3.6 Flash (Medium)" },
|
||||
"MODEL_PLACEHOLDER_M73": { "modelId": "gemini-3.6-flash-low", "label": "Gemini 3.6 Flash (Low)" },
|
||||
"MODEL_PLACEHOLDER_M196": { "modelId": "gemini-3.6-flash", "label": "Gemini 3.6 Flash" },
|
||||
"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_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_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_M50": { "modelId": "gemini-3.1-flash-lite", "label": "Gemini 3.1 Flash Lite" },
|
||||
"MODEL_PLACEHOLDER_M59": { "modelId": "gemini-for-google-3.1-flash", "label": "Gemini for Google 3.1 Flash" },
|
||||
"MODEL_PLACEHOLDER_M21": { "modelId": "gemini-3.1-flash-image", "label": "Gemini 3.1 Flash Image" },
|
||||
"MODEL_PLACEHOLDER_M47": { "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_GOOGLE_GEMINI_2_5_PRO": { "modelId": "gemini-2.5-pro", "label": "Gemini 2.5 Pro" },
|
||||
"MODEL_GOOGLE_GEMINI_2_5_FLASH": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash" },
|
||||
"MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash (Thinking)" },
|
||||
"MODEL_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_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)" },
|
||||
|
||||
+16499
-4148
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,204 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
|
||||
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
|
||||
$utf8 = [Console]::OutputEncoding
|
||||
|
||||
function Test-AccountFile($path) {
|
||||
if (-not (Test-Path -LiteralPath $path)) { return $false }
|
||||
$item = Get-Item -LiteralPath $path -Force
|
||||
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||
throw 'Invalid account file'
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
function Write-AccountFile($path, [byte[]]$bytes) {
|
||||
$temp = Join-Path ([IO.Path]::GetDirectoryName($path)) ([guid]::NewGuid().ToString() + '.tmp')
|
||||
try {
|
||||
[IO.File]::WriteAllBytes($temp, $bytes)
|
||||
if (Test-AccountFile $path) {
|
||||
[IO.File]::Replace($temp, $path, [NullString]::Value)
|
||||
} else {
|
||||
[IO.File]::Move($temp, $path)
|
||||
}
|
||||
} finally {
|
||||
[IO.File]::Delete($temp)
|
||||
}
|
||||
}
|
||||
|
||||
function Save-Vault($path, $vault) {
|
||||
$bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 4 -Compress))
|
||||
$encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
|
||||
[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
|
||||
Write-AccountFile $path $encrypted
|
||||
}
|
||||
|
||||
function Add-NativeCredentialType {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class NativeAccountCredential {
|
||||
private const uint Generic = 1;
|
||||
private const uint PersistLocalMachine = 2;
|
||||
private const int NotFound = 1168;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct Credential {
|
||||
public uint Flags, Type;
|
||||
public string TargetName, Comment;
|
||||
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
||||
public uint BlobSize;
|
||||
public IntPtr Blob;
|
||||
public uint Persist, AttributeCount;
|
||||
public IntPtr Attributes;
|
||||
public string TargetAlias, UserName;
|
||||
}
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CredReadW(string target, uint type, uint flags, out IntPtr credential);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CredWriteW(ref Credential credential, uint flags);
|
||||
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CredDeleteW(string target, uint type, uint flags);
|
||||
|
||||
[DllImport("advapi32.dll")]
|
||||
private static extern void CredFree(IntPtr buffer);
|
||||
|
||||
public static byte[] Read(string target) {
|
||||
IntPtr pointer;
|
||||
if (!CredReadW(target, Generic, 0, out pointer)) {
|
||||
int error = Marshal.GetLastWin32Error();
|
||||
if (error == NotFound) return null;
|
||||
throw new Win32Exception(error);
|
||||
}
|
||||
try {
|
||||
var credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
|
||||
var bytes = new byte[credential.BlobSize];
|
||||
if (bytes.Length > 0) Marshal.Copy(credential.Blob, bytes, 0, bytes.Length);
|
||||
return bytes;
|
||||
} finally {
|
||||
CredFree(pointer);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Write(string target, byte[] bytes) {
|
||||
var buffer = GCHandle.Alloc(bytes, GCHandleType.Pinned);
|
||||
try {
|
||||
var credential = new Credential {
|
||||
Type = Generic, Persist = PersistLocalMachine, TargetName = target,
|
||||
UserName = "antigravity", Blob = buffer.AddrOfPinnedObject(), BlobSize = (uint)bytes.Length
|
||||
};
|
||||
if (!CredWriteW(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
} finally {
|
||||
buffer.Free();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Restore(string target, byte[] bytes) {
|
||||
if (bytes != null) Write(target, bytes);
|
||||
else if (!CredDeleteW(target, Generic, 0)) {
|
||||
int error = Marshal.GetLastWin32Error();
|
||||
if (error != NotFound) throw new Win32Exception(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Invoke-AccountAction($request) {
|
||||
Add-Type -AssemblyName System.Security
|
||||
$vault = @{ entries = @(); selectedEmail = '' }
|
||||
if (Test-AccountFile $request.vault) {
|
||||
$plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($request.vault), $null, 'CurrentUser')
|
||||
$vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
|
||||
}
|
||||
$entry = $vault.entries | Where-Object { $_.email -eq $request.email } | Select-Object -First 1
|
||||
if ($null -ne $request.expectedCredential -and $entry.credential -cne $request.expectedCredential) {
|
||||
return @{ error = 'credentialChanged' }
|
||||
}
|
||||
|
||||
switch ($request.action) {
|
||||
'readCurrent' {
|
||||
Add-NativeCredentialType
|
||||
$bytes = [NativeAccountCredential]::Read($request.target)
|
||||
if (-not $bytes) {
|
||||
foreach ($path in $request.fallbacks) {
|
||||
if (Test-AccountFile $path) {
|
||||
$bytes = [IO.File]::ReadAllBytes($path)
|
||||
if ($bytes) { break }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
|
||||
return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
|
||||
}
|
||||
'read' {
|
||||
if (-not $entry) { return @{ error = 'notFound' } }
|
||||
return @{ credential = $entry.credential }
|
||||
}
|
||||
'save' {
|
||||
if ($entry) { $entry.credential = $request.credential }
|
||||
else { $vault.entries = @($vault.entries) + @(@{ email = $request.email; credential = $request.credential }) }
|
||||
Save-Vault $request.vault $vault
|
||||
}
|
||||
'switch' {
|
||||
if (-not $entry) { return @{ error = 'notFound' } }
|
||||
$replacement = $utf8.GetBytes($request.credential)
|
||||
if ($replacement.Length -gt 2560) { return @{ error = 'credentialTooLarge' } }
|
||||
Add-NativeCredentialType
|
||||
$previous = [NativeAccountCredential]::Read($request.target)
|
||||
$fallbacks = @(foreach ($path in $request.fallbacks) {
|
||||
if (Test-AccountFile $path) { @{ path = $path; original = [IO.File]::ReadAllBytes($path) } }
|
||||
})
|
||||
$written = @()
|
||||
[NativeAccountCredential]::Write($request.target, $replacement)
|
||||
try {
|
||||
foreach ($fallback in $fallbacks) {
|
||||
Write-AccountFile $fallback.path $replacement
|
||||
$written += $fallback
|
||||
}
|
||||
$entry.credential = $request.credential
|
||||
$vault.selectedEmail = $request.email
|
||||
Save-Vault $request.vault $vault
|
||||
} catch {
|
||||
$restored = $true
|
||||
try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
|
||||
foreach ($fallback in $written) {
|
||||
try { Write-AccountFile $fallback.path $fallback.original } catch { $restored = $false }
|
||||
}
|
||||
if (-not $restored) { return @{ error = 'rollbackFailed' } }
|
||||
throw
|
||||
}
|
||||
}
|
||||
'remove' {
|
||||
if (-not $entry) { return @{ error = 'notFound' } }
|
||||
$vault.entries = @($vault.entries | Where-Object { $_.email -ne $request.email })
|
||||
if ($vault.selectedEmail -eq $request.email) { $vault.selectedEmail = '' }
|
||||
Save-Vault $request.vault $vault
|
||||
}
|
||||
}
|
||||
return @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail }
|
||||
}
|
||||
|
||||
$mutex = $null
|
||||
$locked = $false
|
||||
try {
|
||||
$request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
|
||||
$mutex = [Threading.Mutex]::new($false, 'Local\AntigravityUsageMonitor.AccountCredentials')
|
||||
try { $locked = $mutex.WaitOne(4000) } catch [Threading.AbandonedMutexException] { $locked = $true }
|
||||
$result = if ($locked) { Invoke-AccountAction $request } else { @{ error = 'busy' } }
|
||||
} catch {
|
||||
$result = @{ error = 'storeFailed' }
|
||||
$nativeError = $_.Exception.InnerException
|
||||
if ($nativeError -is [ComponentModel.Win32Exception] -and $nativeError.NativeErrorCode -in 5, 1312) {
|
||||
$result.error = 'credentialAccessDenied'
|
||||
}
|
||||
} finally {
|
||||
if ($locked) { $mutex.ReleaseMutex() }
|
||||
if ($mutex) { $mutex.Dispose() }
|
||||
}
|
||||
[Console]::Write((ConvertTo-Json -InputObject $result -Compress))
|
||||
@@ -0,0 +1,178 @@
|
||||
/** @fileoverview Google OAuth identity and quota queries for saved Antigravity credentials. */
|
||||
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
|
||||
const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
|
||||
const OAUTH_USER_URL = 'https://www.googleapis.com/oauth2/v2/userinfo';
|
||||
const CLOUD_CODE_HOSTS = ['cloudcode-pa.googleapis.com', 'daily-cloudcode-pa.googleapis.com'];
|
||||
let nativeOAuthClients;
|
||||
|
||||
export function extractNativeOAuthClients(binary) {
|
||||
const pe = binary.length >= 64 && binary.readUInt16LE(0) === 0x5a4d ? binary.readUInt32LE(60) : 0;
|
||||
if (!pe || pe + 24 > binary.length || binary.readUInt32LE(pe) !== 0x4550 || binary.readUInt16LE(pe + 4) !== 0x8664) return [];
|
||||
const count = binary.readUInt16LE(pe + 6);
|
||||
const table = pe + 24 + binary.readUInt16LE(pe + 20);
|
||||
if (table + count * 40 > binary.length) return [];
|
||||
|
||||
const sections = Array.from({ length: count }, (_, i) => {
|
||||
const offset = table + i * 40;
|
||||
return {
|
||||
name: binary.toString('ascii', offset, offset + 8).replace(/\0+$/, ''),
|
||||
rva: binary.readUInt32LE(offset + 12),
|
||||
size: binary.readUInt32LE(offset + 16),
|
||||
start: binary.readUInt32LE(offset + 20),
|
||||
};
|
||||
});
|
||||
const text = sections.find(({ name }) => name === '.text');
|
||||
const rodata = sections.find(({ name }) => name === '.rdata');
|
||||
if (!text || !rodata || text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) return [];
|
||||
const machineCode = binary.subarray(text.start, text.start + text.size);
|
||||
|
||||
function readLiteral(displacementOffset, length) {
|
||||
const rva = text.rva + displacementOffset + 4 + machineCode.readInt32LE(displacementOffset);
|
||||
const offset = rva - rodata.rva;
|
||||
if (length > 100 || offset < 0 || offset + length > rodata.size) return '';
|
||||
return binary.toString('ascii', rodata.start + offset, rodata.start + offset + length);
|
||||
}
|
||||
|
||||
// Go's x64 OAuth config initializer sets ClientID and ClientSecret as two consecutive pointer/length pairs.
|
||||
const idLength = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
|
||||
const loadAndStoreId = Buffer.from([0x48, 0x8d, 0x0d]);
|
||||
const betweenLiterals = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
|
||||
const clients = new Map();
|
||||
for (let i = machineCode.indexOf(idLength); i >= 0 && i + 33 <= machineCode.length; i = machineCode.indexOf(idLength, i + 1)) {
|
||||
if (!machineCode.subarray(i + 8, i + 11).equals(loadAndStoreId) ||
|
||||
!machineCode.subarray(i + 15, i + 22).equals(betweenLiterals) ||
|
||||
!machineCode.subarray(i + 26, i + 29).equals(loadAndStoreId)) continue;
|
||||
const id = readLiteral(i + 11, machineCode.readUInt32LE(i + 4));
|
||||
const secret = readLiteral(i + 29, machineCode.readUInt32LE(i + 22));
|
||||
if (/^\d+-[\w-]+\.apps\.googleusercontent\.com$/.test(id) && /^GOCSPX-[\w-]+$/.test(secret)) {
|
||||
clients.set(id, { id, secret });
|
||||
}
|
||||
}
|
||||
return Array.from(clients.values()).reverse();
|
||||
}
|
||||
|
||||
async function loadNativeOAuthClients() {
|
||||
if (!nativeOAuthClients) {
|
||||
nativeOAuthClients = (async () => {
|
||||
const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
|
||||
const binaries = [
|
||||
join(local, 'Programs', 'Antigravity', 'resources', 'bin', 'language_server.exe'),
|
||||
join(homedir(), '.gemini', 'bin', 'agy.exe'),
|
||||
];
|
||||
for (const filename of binaries) {
|
||||
const binary = await readFile(filename).catch(() => null);
|
||||
const clients = binary ? extractNativeOAuthClients(binary) : [];
|
||||
if (clients.length) return clients;
|
||||
}
|
||||
return [];
|
||||
})();
|
||||
}
|
||||
const clients = await nativeOAuthClients;
|
||||
if (!clients.length) nativeOAuthClients = null;
|
||||
return clients;
|
||||
}
|
||||
|
||||
export async function resolveGoogleCredential(credential, { refresh = false, fetchFn = fetch, getClients = loadNativeOAuthClients } = {}) {
|
||||
let { access_token: accessToken, refresh_token: refreshToken, expiry } = credential.token;
|
||||
let idToken = credential.id_token;
|
||||
if (refresh || !accessToken || Date.parse(expiry) <= Date.now() + 60_000) {
|
||||
const clients = await getClients();
|
||||
if (!clients.length) throw new Error('oauthClientUnavailable');
|
||||
let refreshed = false;
|
||||
for (const { id, secret } of clients) {
|
||||
const response = await fetchFn(OAUTH_TOKEN_URL, {
|
||||
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(6000),
|
||||
body: new URLSearchParams({ client_id: id, client_secret: secret, grant_type: 'refresh_token', refresh_token: refreshToken }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) {
|
||||
if (['invalid_grant', 'invalid_client', 'unauthorized_client'].includes(result?.error)) continue;
|
||||
throw new Error('oauthUnavailable');
|
||||
}
|
||||
if (!result.access_token || !Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error('oauthUnavailable');
|
||||
accessToken = result.access_token;
|
||||
refreshToken = result.refresh_token || refreshToken;
|
||||
idToken = result.id_token;
|
||||
expiry = new Date(Date.now() + result.expires_in * 1000).toISOString();
|
||||
refreshed = true;
|
||||
break;
|
||||
}
|
||||
if (!refreshed) throw new Error('credentialRejected');
|
||||
}
|
||||
const userResponse = await fetchFn(OAUTH_USER_URL, {
|
||||
redirect: 'error', signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!userResponse.ok) throw new Error(userResponse.status === 401 ? 'credentialRejected' : 'oauthUnavailable');
|
||||
const user = await userResponse.json();
|
||||
if (!user.email || user.verified_email === false) throw new Error('credentialRejected');
|
||||
return {
|
||||
email: user.email,
|
||||
credential: {
|
||||
token: { access_token: accessToken, refresh_token: refreshToken, token_type: 'Bearer', expiry },
|
||||
auth_method: 'consumer',
|
||||
id_token_email: user.email,
|
||||
...(idToken ? { id_token: idToken } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
|
||||
async function post(method, data) {
|
||||
for (const host of CLOUD_CODE_HOSTS) {
|
||||
const response = await fetchFn(`https://${host}/v1internal:${method}`, {
|
||||
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4500),
|
||||
headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
}).catch(() => null);
|
||||
if (response?.ok) {
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (payload) return payload.response ?? payload;
|
||||
}
|
||||
if (response?.status === 401 || response?.status === 403) break;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const setup = await post('loadCodeAssist', { metadata: { ideType: 'ANTIGRAVITY' } });
|
||||
const project = setup?.cloudaicompanionProject?.id || setup?.cloudaicompanionProject;
|
||||
if (!setup) throw new Error('quotaUnavailable');
|
||||
const request = {
|
||||
project: typeof project === 'string' && project ? project : 'cloudaicompanion-enterprise',
|
||||
};
|
||||
const clientConfigs = setup.cascadeModelConfigData?.clientModelConfigs;
|
||||
const [summary, available] = await Promise.all([
|
||||
post('retrieveUserQuotaSummary', request),
|
||||
Array.isArray(clientConfigs) && clientConfigs.length ? null : post('fetchAvailableModels', request),
|
||||
]);
|
||||
const configs = Array.isArray(clientConfigs) && clientConfigs.length ? clientConfigs :
|
||||
Object.entries(available?.models || {}).filter(([, model]) => model?.quotaInfo && !model.disabled)
|
||||
.map(([modelId, model]) => ({ modelId, modelOrAlias: { model: modelId }, label: model.displayName, quotaInfo: model.quotaInfo }));
|
||||
const raw = summary?.quotaSummary ?? summary;
|
||||
if (!Array.isArray(raw?.groups) && !Array.isArray(raw?.buckets) && !configs.length) throw new Error('quotaUnavailable');
|
||||
const adaptBuckets = (buckets) => (Array.isArray(buckets) ? buckets : []).map((bucket) => ({
|
||||
...bucket,
|
||||
bucketId: bucket?.bucketId ?? bucket?.bucket_id,
|
||||
remainingFraction: bucket?.remainingFraction ?? bucket?.remaining_fraction,
|
||||
resetTime: bucket?.resetTime ?? bucket?.reset_time,
|
||||
}));
|
||||
const quota = {
|
||||
groups: (Array.isArray(raw?.groups) ? raw.groups : []).map((group) => ({
|
||||
...group, displayName: group?.displayName || group?.name, buckets: adaptBuckets(group?.buckets),
|
||||
})),
|
||||
buckets: adaptBuckets(raw?.buckets),
|
||||
};
|
||||
const { quotaPoolsMap } = buildOfficialQuotaPools(quota, configs);
|
||||
return Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
|
||||
poolKey: pool.poolKey,
|
||||
poolLabel: pool.poolLabel,
|
||||
remainingPct: pool.remainingPct,
|
||||
weeklyRemainingPct: pool.weeklyRemainingPct,
|
||||
resetTime: pool.resetTime,
|
||||
weeklyResetTime: pool.weeklyResetTime,
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/** @fileoverview Antigravity shared credentials and the plugin's Windows credential vault. */
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { resolveGoogleCredential, retrieveCredentialQuota } from './account-oauth.mjs';
|
||||
import { HERE } from './config.mjs';
|
||||
import { callLsRpc } from './ls-rpc.mjs';
|
||||
|
||||
const ACCOUNT_ERRORS = new Set([
|
||||
'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
|
||||
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
|
||||
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
|
||||
'oauthUnavailable', 'quotaUnavailable',
|
||||
]);
|
||||
|
||||
export function normalizeAccountEmail(value) {
|
||||
const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
||||
return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : '';
|
||||
}
|
||||
|
||||
export function normalizeAccountCredential(input) {
|
||||
if (typeof input !== 'string' || Buffer.byteLength(input, 'utf8') > 16384) return null;
|
||||
const text = input.trim();
|
||||
let source;
|
||||
try { source = JSON.parse(text); } catch {
|
||||
if (!/^1\/{1,2}[\w.-]{20,}$/.test(text)) return null;
|
||||
source = { refresh_token: text };
|
||||
}
|
||||
const token = source?.token || source;
|
||||
if (!token || (source.auth_method && source.auth_method !== 'consumer') ||
|
||||
typeof token.refresh_token !== 'string' || !token.refresh_token.trim() ||
|
||||
/\s/.test(token.refresh_token) || (token.token_type && !/^bearer$/i.test(token.token_type))) return null;
|
||||
const timestamp = token.expiry_date ?? (Number(token.expiry_timestamp) * 1000);
|
||||
const expiry = token.expiry || (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
|
||||
? new Date(timestamp).toISOString() : '1970-01-01T00:00:00Z');
|
||||
if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return null;
|
||||
const payload = {
|
||||
token: {
|
||||
access_token: typeof token.access_token === 'string' ? token.access_token : '',
|
||||
refresh_token: token.refresh_token,
|
||||
token_type: 'Bearer',
|
||||
expiry: new Date(expiry).toISOString(),
|
||||
},
|
||||
auth_method: 'consumer',
|
||||
};
|
||||
const idToken = source.id_token || token.id_token;
|
||||
if (typeof idToken === 'string' && idToken) payload.id_token = idToken;
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
export function runWindowsCredentialStore(request) {
|
||||
const script = readFileSync(join(HERE, 'backend', 'account-credentials.ps1'), 'utf8');
|
||||
const encoded = Buffer.from(script, 'utf16le').toString('base64');
|
||||
const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
||||
return new Promise((resolve, reject) => {
|
||||
// The helper exchanges private data over its pipes, keeping it out of process arguments.
|
||||
const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
|
||||
let output = '';
|
||||
child.stdout.setEncoding('utf8');
|
||||
child.stdout.on('data', (chunk) => { output += chunk; });
|
||||
child.on('error', reject);
|
||||
child.stdin.on('error', reject);
|
||||
child.on('close', (code) => {
|
||||
if (code !== 0) return reject(new Error('storeFailed'));
|
||||
try { resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); } catch { reject(new Error('storeFailed')); }
|
||||
});
|
||||
child.stdin.end(JSON.stringify(request), 'utf8');
|
||||
});
|
||||
}
|
||||
|
||||
function serializeHostCredential(credential) {
|
||||
let payload = JSON.stringify(credential);
|
||||
if (Buffer.byteLength(payload, 'utf8') > 2560 && credential.id_token) {
|
||||
const { id_token, ...compact } = credential;
|
||||
payload = JSON.stringify(compact);
|
||||
}
|
||||
if (Buffer.byteLength(payload, 'utf8') > 2560) throw new Error('credentialTooLarge');
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function confirmHostCredential(email, rpc) {
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
await rpc('GetAuthStatus', {}, 1200).catch(() => null);
|
||||
const status = await rpc('GetUserStatus', {}, 1200).catch(() => null);
|
||||
if (normalizeAccountEmail(status?.userStatus?.email) === email) return true;
|
||||
if (attempt < 2) await delay(300);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function handleAccountCredentialAction(data, {
|
||||
platform = process.platform,
|
||||
store = runWindowsCredentialStore,
|
||||
rpc = callLsRpc,
|
||||
resolveCredential = resolveGoogleCredential,
|
||||
getQuota = retrieveCredentialQuota,
|
||||
} = {}) {
|
||||
if (platform !== 'win32') return { supported: false, accounts: [], error: 'unsupported' };
|
||||
const action = data?.action || 'list';
|
||||
if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' };
|
||||
const email = normalizeAccountEmail(data?.email);
|
||||
if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' };
|
||||
const gemini = join(homedir(), '.gemini');
|
||||
const config = {
|
||||
target: 'gemini:antigravity',
|
||||
vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'),
|
||||
fallbacks: [join(gemini, 'jetski-standalone-oauth-token'), join(gemini, 'antigravity-cli', 'antigravity-oauth-token')],
|
||||
};
|
||||
async function runStore(fields) {
|
||||
const result = await store({ ...config, ...fields });
|
||||
if (!result || result.error) throw new Error(result?.error || 'storeFailed');
|
||||
return result;
|
||||
}
|
||||
|
||||
function publicList(result) {
|
||||
return {
|
||||
supported: true,
|
||||
accounts: (Array.isArray(result.accounts) ? result.accounts : []).map(normalizeAccountEmail).filter(Boolean),
|
||||
selectedEmail: normalizeAccountEmail(result.selectedEmail),
|
||||
};
|
||||
}
|
||||
|
||||
async function verifyCredential(raw, refresh = false) {
|
||||
const normalized = normalizeAccountCredential(raw);
|
||||
if (!normalized) throw new Error('invalidCredential');
|
||||
let result;
|
||||
try {
|
||||
result = await resolveCredential(JSON.parse(normalized), { refresh });
|
||||
} catch (error) {
|
||||
throw new Error(ACCOUNT_ERRORS.has(error?.message) ? error.message : 'oauthUnavailable');
|
||||
}
|
||||
result.email = normalizeAccountEmail(result.email);
|
||||
if (!result.email) throw new Error('credentialRejected');
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
if (action === 'list' || action === 'remove') return publicList(await runStore({ action, email }));
|
||||
if (action === 'save') {
|
||||
const verified = await verifyCredential(data.credential, true);
|
||||
return publicList(await runStore({ action, email: verified.email, credential: serializeHostCredential(verified.credential) }));
|
||||
}
|
||||
if (action === 'capture') {
|
||||
const status = await rpc('GetUserStatus', {}, 2000).catch(() => null);
|
||||
const activeEmail = normalizeAccountEmail(status?.userStatus?.email);
|
||||
if (!activeEmail) throw new Error('noCurrentCredential');
|
||||
const { credential } = await runStore({ action: 'readCurrent' });
|
||||
const verified = await verifyCredential(credential);
|
||||
if (verified.email !== activeEmail) throw new Error('identityMismatch');
|
||||
return publicList(await runStore({ action: 'save', email: activeEmail, credential: serializeHostCredential(verified.credential) }));
|
||||
}
|
||||
|
||||
const saved = await runStore({ action: 'read', email });
|
||||
const verified = await verifyCredential(saved.credential);
|
||||
if (verified.email !== email) throw new Error('identityMismatch');
|
||||
const credential = serializeHostCredential(verified.credential);
|
||||
if (action === 'quota') {
|
||||
if (credential !== saved.credential) {
|
||||
await runStore({ action: 'save', email, credential, expectedCredential: saved.credential });
|
||||
}
|
||||
const pools = await getQuota(verified.credential.token.access_token);
|
||||
return { email, pools };
|
||||
}
|
||||
const updated = await runStore({ action: 'switch', email, credential, expectedCredential: saved.credential });
|
||||
const confirmed = await confirmHostCredential(email, rpc);
|
||||
return { ...publicList(updated), confirmed };
|
||||
} catch (error) {
|
||||
return { error: ACCOUNT_ERRORS.has(error?.message) ? error.message : 'storeFailed' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
/**
|
||||
* @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 { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||
import {
|
||||
HERE,
|
||||
SETTINGS_FILE,
|
||||
clearRuntimeCaches,
|
||||
cloudSyncState,
|
||||
computeRuntimeCodeVersion,
|
||||
createDefaultSettingsObject,
|
||||
isPlainObject,
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
normalizeFullSettings,
|
||||
normalizeModelDisplayMode,
|
||||
normalizePluginUpdateMode,
|
||||
normalizeWindowMountMode,
|
||||
saveJson,
|
||||
} from './config.mjs';
|
||||
import {
|
||||
getContextWindowModels,
|
||||
getContextWindowGroups,
|
||||
isContextWindowSettingId,
|
||||
isContextWindowOption,
|
||||
resolveContextWindowOption,
|
||||
} from './context-windows.mjs';
|
||||
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||
import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
|
||||
import {
|
||||
performPluginUpdate,
|
||||
scheduleSidecarRestart,
|
||||
setSidecarRestartHandler,
|
||||
syncCloudCatalog,
|
||||
} from './plugin-updater.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
||||
import {
|
||||
notifyModelContextWindowsChanged,
|
||||
notifyWindowOverlaySetting,
|
||||
startDefaultWindowBridge,
|
||||
} from './window-bridge.mjs';
|
||||
import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
|
||||
|
||||
export const bootBundleVersion = computeRuntimeCodeVersion();
|
||||
|
||||
let standalonePortListener = null;
|
||||
|
||||
export function setStandalonePortListener(listener) {
|
||||
standalonePortListener = typeof listener === 'function' ? listener : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步读取 `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;
|
||||
}
|
||||
|
||||
function projectDisplayStep(st) {
|
||||
const {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
} = st;
|
||||
return {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
let lastDisplaySteps = null;
|
||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||
|
||||
function haveSameDisplaySteps(previous, current) {
|
||||
if (!previous || !current) return previous === current;
|
||||
if (previous.length !== current.length) return false;
|
||||
for (let i = 0; i < current.length; i++) {
|
||||
const before = previous[i];
|
||||
const after = current[i];
|
||||
for (const key of displayStepFields) {
|
||||
if (before[key] !== after[key]) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function projectDisplayTelemetry(payload, requestedRevision) {
|
||||
const active = payload.activeConversation;
|
||||
const agents = active.agents;
|
||||
const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)];
|
||||
let projected;
|
||||
let revision;
|
||||
if (typeof requestedRevision === 'string') {
|
||||
const scope = [
|
||||
payload.account?.status,
|
||||
payload.account?.email || payload.account?.name || '',
|
||||
active.cascadeId,
|
||||
...agents.map((agent) => agent.agentId),
|
||||
];
|
||||
const previous = lastDisplaySteps;
|
||||
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
||||
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
||||
haveSameDisplaySteps(previous.steps[index], steps))) {
|
||||
({ revision, steps: projected } = previous);
|
||||
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
||||
} else {
|
||||
revision = randomUUID();
|
||||
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
lastDisplaySteps = { scope, steps: projected, revision,
|
||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) };
|
||||
}
|
||||
}
|
||||
projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
const stepsUnchanged = revision !== undefined && requestedRevision === revision;
|
||||
return {
|
||||
...payload,
|
||||
...(revision ? { stepRevision: revision, stepsUnchanged } : {}),
|
||||
activeConversation: {
|
||||
...active,
|
||||
recentSteps: stepsUnchanged ? undefined : projected[0],
|
||||
agents: agents.map((agent, index) => projected[index + 1]
|
||||
? { ...agent, recentSteps: stepsUnchanged ? undefined : projected[index + 1] }
|
||||
: agent),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
let payload;
|
||||
try {
|
||||
payload = await buildTelemetryPayload(convId, force, filterOpts);
|
||||
} catch (err) {
|
||||
if (
|
||||
lsRuntimeEndpoint.addr !== 'test.invalid' &&
|
||||
bootBundleVersion &&
|
||||
String(computeRuntimeCodeVersion()) !== String(bootBundleVersion)
|
||||
) {
|
||||
if (typeof onRestart === 'function') {
|
||||
onRestart();
|
||||
} else {
|
||||
scheduleSidecarRestart(150);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (
|
||||
bootBundleVersion &&
|
||||
payload.uiBundleVersion &&
|
||||
String(payload.uiBundleVersion) !== String(bootBundleVersion)
|
||||
) {
|
||||
if (typeof onRestart === 'function') {
|
||||
onRestart();
|
||||
} else {
|
||||
scheduleSidecarRestart(150);
|
||||
}
|
||||
}
|
||||
const responsePayload = data?.stepDetails === 'display'
|
||||
? projectDisplayTelemetry(payload, data.stepRevision)
|
||||
: payload;
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(responsePayload),
|
||||
};
|
||||
}
|
||||
|
||||
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 nextModelDisplayMode =
|
||||
payload.modelDisplayMode !== undefined
|
||||
? normalizeModelDisplayMode(payload.modelDisplayMode)
|
||||
: typeof payload.showUpstreamModel === 'boolean'
|
||||
? payload.showUpstreamModel
|
||||
? 'upstream'
|
||||
: 'short'
|
||||
: normalizeModelDisplayMode(current.modelDisplayMode, current.showUpstreamModel);
|
||||
const updated = normalizeFullSettings({
|
||||
...current,
|
||||
...payload,
|
||||
modelContextWindows: current.modelContextWindows,
|
||||
weeklyTokenBudget: sanitizePositiveSettingNumber(
|
||||
payload.weeklyTokenBudget ?? payload.weeklyTokenLimit,
|
||||
current.weeklyTokenBudget
|
||||
),
|
||||
weeklyCostBudget: sanitizePositiveSettingNumber(
|
||||
payload.weeklyCostBudget,
|
||||
current.weeklyCostBudget
|
||||
),
|
||||
modelDisplayMode: nextModelDisplayMode,
|
||||
pluginUpdateMode: nextPluginUpdateMode,
|
||||
windowMountMode: nextWindowMountMode,
|
||||
});
|
||||
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);
|
||||
}
|
||||
if ((updated.enableCliStatusLine !== false) !== (current.enableCliStatusLine !== false)) {
|
||||
ensureCliStatusLineConfigured({ enabled: updated.enableCliStatusLine !== false });
|
||||
}
|
||||
if (
|
||||
typeof standalonePortListener === 'function' &&
|
||||
Number(updated.standalonePort || 0) !== Number(current.standalonePort || 0)
|
||||
) {
|
||||
try {
|
||||
standalonePortListener(Number(updated.standalonePort || 0));
|
||||
} catch {
|
||||
// 忽略独立端口热重载回调异常
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
updated,
|
||||
body: JSON.stringify(updated),
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeModelContextWindowAction(data) {
|
||||
const { modelId, option } = data || {};
|
||||
const respond = (status, payload) => ({
|
||||
status,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!isContextWindowSettingId(modelId) || (option !== null && !isContextWindowOption(option))) {
|
||||
return respond(400, { error: 'Invalid model context window' });
|
||||
}
|
||||
let group;
|
||||
try {
|
||||
const [{ userStatus }, catalog] = await Promise.all([callLsRpc('GetUserStatus'), getContextModelCatalog()]);
|
||||
const models = getContextWindowModels(userStatus?.cascadeModelConfigData?.clientModelConfigs, catalog);
|
||||
group = getContextWindowGroups(models).find(({ id }) => id === modelId);
|
||||
} catch {
|
||||
if (option !== null || modelId.startsWith('model:')) {
|
||||
return respond(503, { error: 'Unable to verify the host model configuration' });
|
||||
}
|
||||
}
|
||||
if (option !== null && (!group || resolveContextWindowOption(group, option) === null)) {
|
||||
return respond(400, { error: 'This context window is not available for the selected model' });
|
||||
}
|
||||
const current = loadSettings();
|
||||
for (const id of group?.members || []) delete current.modelContextWindows[id];
|
||||
if (option === null) {
|
||||
delete current.modelContextWindows[modelId];
|
||||
} else {
|
||||
current.modelContextWindows[modelId] = option;
|
||||
}
|
||||
if (!saveJson(SETTINGS_FILE, current)) {
|
||||
return respond(500, { error: 'Failed to persist model context window' });
|
||||
}
|
||||
void notifyModelContextWindowsChanged();
|
||||
return respond(200, { modelContextWindows: current.modelContextWindows });
|
||||
}
|
||||
|
||||
export function executeResetSettingsAction() {
|
||||
const current = loadSettings();
|
||||
const updated = createDefaultSettingsObject();
|
||||
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 reset settings' }),
|
||||
};
|
||||
}
|
||||
const prevMountMode = normalizeWindowMountMode(
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
);
|
||||
if (
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode
|
||||
) {
|
||||
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
|
||||
} else if (Object.keys(current.modelContextWindows).length) {
|
||||
void notifyModelContextWindowsChanged();
|
||||
}
|
||||
if ((updated.enableCliStatusLine !== false) !== (current.enableCliStatusLine !== false)) {
|
||||
ensureCliStatusLineConfigured({ enabled: updated.enableCliStatusLine !== false });
|
||||
}
|
||||
if (
|
||||
typeof standalonePortListener === 'function' &&
|
||||
Number(updated.standalonePort || 0) !== Number(current.standalonePort || 0)
|
||||
) {
|
||||
try {
|
||||
standalonePortListener(Number(updated.standalonePort || 0));
|
||||
} catch {
|
||||
// 忽略独立端口热重载回调异常
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
updated,
|
||||
body: JSON.stringify(updated),
|
||||
};
|
||||
}
|
||||
|
||||
export function executeRebuildCacheAction() {
|
||||
const ok = clearRuntimeCaches();
|
||||
if (!ok) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ok: true, clearedAt: Date.now() }),
|
||||
};
|
||||
}
|
||||
|
||||
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 executeAccountCredentialAction(data) {
|
||||
const result = await handleAccountCredentialAction(data);
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(result),
|
||||
};
|
||||
}
|
||||
|
||||
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/accounts' && method === 'GET') {
|
||||
return executeAccountCredentialAction();
|
||||
}
|
||||
if (pathname === '/api/accounts/update' && method === 'POST') {
|
||||
return executeAccountCredentialAction(data);
|
||||
}
|
||||
if (pathname === '/api/context-window' && method === 'POST') {
|
||||
return executeModelContextWindowAction(data);
|
||||
}
|
||||
if (pathname === '/api/settings/reset' && method === 'POST') {
|
||||
return executeResetSettingsAction();
|
||||
}
|
||||
if (pathname === '/api/cache/rebuild' && method === 'POST') {
|
||||
return executeRebuildCacheAction();
|
||||
}
|
||||
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;
|
||||
|
||||
ensureCliStatusLineConfigured({ enabled: loadSettings().enableCliStatusLine !== false });
|
||||
|
||||
const triggerRestart =
|
||||
typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150);
|
||||
if (typeof onRestart === 'function') {
|
||||
setSidecarRestartHandler(onRestart);
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,883 @@
|
||||
/**
|
||||
* @fileoverview 本地 Antigravity CLI / Desktop SQLite 会话轨迹与 Protobuf 文本标题解析器。
|
||||
*
|
||||
* 解决 `agy` CLI(进程内嵌随机端口 Language Server、无 `daemon/hub_*.json`、桌面 LS 无法跨目录读取
|
||||
* `~/.gemini/antigravity-cli`)下的完整遥测还原:
|
||||
* 1. 解析 `<product>/annotations/<cascadeId>.pbtxt` 中的真实会话标题(兼容 UTF-8 直出与八进制/十六进制字节转义);
|
||||
* 2. 通过 Node 22.5+ 内置 `node:sqlite` 只读扫描 `<product>/conversation_summaries.db`,获取标题、实时运行状态与父会话归属;
|
||||
* 3. 只读解码 `<product>/conversations/<cascadeId>.db` 的 `steps.metadata` 与 `gen_metadata.data` 轻量 Protobuf 字段
|
||||
* (跳过大体积提示词与工具载荷),完整还原纳秒级耗时、TTFT、思考/正文 Token 拆分、模型展示名与 10 通道上下文构成。
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
||||
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
|
||||
|
||||
let sqliteResolved = false;
|
||||
let sqliteDatabaseSyncCtor = null;
|
||||
|
||||
/**
|
||||
* 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器。
|
||||
* 首次加载时静默过滤 Node 22 的实验特性提示,避免污染 CLI 终端或 MCP 日志;不支持时返回 `null`。
|
||||
*
|
||||
* @returns {Function | null}
|
||||
*/
|
||||
export function getNodeSqliteDatabaseSync() {
|
||||
if (sqliteResolved) return sqliteDatabaseSyncCtor;
|
||||
sqliteResolved = true;
|
||||
if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const origEmitWarning = process.emitWarning;
|
||||
try {
|
||||
if (typeof origEmitWarning === 'function') {
|
||||
process.emitWarning = function filteredSqliteWarning(warning, ...rest) {
|
||||
const msg = typeof warning === 'string' ? warning : String(warning?.message || '');
|
||||
if (/SQLite is an experimental feature/i.test(msg)) return;
|
||||
return origEmitWarning.call(this, warning, ...rest);
|
||||
};
|
||||
}
|
||||
const mod = process.getBuiltinModule('node:sqlite');
|
||||
sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null;
|
||||
} catch {
|
||||
sqliteDatabaseSyncCtor = null;
|
||||
} finally {
|
||||
if (typeof origEmitWarning === 'function') {
|
||||
process.emitWarning = origEmitWarning;
|
||||
}
|
||||
}
|
||||
return sqliteDatabaseSyncCtor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前运行时是否具备内置 `node:sqlite` 读取能力。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function hasBuiltinNodeSqlite() {
|
||||
return Boolean(getNodeSqliteDatabaseSync());
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。
|
||||
*
|
||||
* @param {string} raw
|
||||
* @returns {string}
|
||||
*/
|
||||
function unescapePbtxtString(raw) {
|
||||
if (typeof raw !== 'string' || !raw) return '';
|
||||
if (!raw.includes('\\')) return raw;
|
||||
const bytes = [];
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const ch = raw[i];
|
||||
if (ch !== '\\' || i + 1 >= raw.length) {
|
||||
const encoded = Buffer.from(ch, 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
continue;
|
||||
}
|
||||
const next = raw[++i];
|
||||
if (next >= '0' && next <= '7') {
|
||||
let oct = next;
|
||||
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||
bytes.push(parseInt(oct, 8) & 0xff);
|
||||
} else if ((next === 'x' || next === 'X') && i + 2 < raw.length) {
|
||||
const hex = raw.slice(i + 1, i + 3);
|
||||
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
||||
bytes.push(parseInt(hex, 16));
|
||||
i += 2;
|
||||
} else {
|
||||
bytes.push(next.charCodeAt(0));
|
||||
}
|
||||
} else if (next === 'u' && i + 4 < raw.length) {
|
||||
const uHex = raw.slice(i + 1, i + 5);
|
||||
if (/^[0-9a-fA-F]{4}$/.test(uHex)) {
|
||||
const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
i += 4;
|
||||
} else {
|
||||
bytes.push(next.charCodeAt(0));
|
||||
}
|
||||
} else if (next === 'n') {
|
||||
bytes.push(0x0a);
|
||||
} else if (next === 'r') {
|
||||
bytes.push(0x0d);
|
||||
} else if (next === 't') {
|
||||
bytes.push(0x09);
|
||||
} else {
|
||||
const encoded = Buffer.from(next, 'utf8');
|
||||
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||
}
|
||||
}
|
||||
return Buffer.from(bytes).toString('utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `annotations/<cascadeId>.pbtxt` 文本内容中提取顶层 `title` 字段。
|
||||
*
|
||||
* @param {string} rawText
|
||||
* @returns {string}
|
||||
*/
|
||||
export function parseAnnotationPbtxtTitle(rawText) {
|
||||
if (typeof rawText !== 'string' || !rawText) return '';
|
||||
const dq = rawText.match(/(?:^|\r?\n)\s*title\s*:\s*"((?:\\.|[^"\\])*)"/);
|
||||
if (dq) {
|
||||
return unescapePbtxtString(dq[1]).trim();
|
||||
}
|
||||
const sq = rawText.match(/(?:^|\r?\n)\s*title\s*:\s*'((?:\\.|[^'\\])*)'/);
|
||||
if (sq) {
|
||||
return unescapePbtxtString(sq[1]).trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按会话 ID 在各产品目录的 `annotations/<cascadeId>.pbtxt` 中查找标题。
|
||||
*
|
||||
* @param {string} cascadeId
|
||||
* @param {string[]} [annotationDirs=ANNOTATION_DIRS]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function readAnnotationTitleForCascade(cascadeId, annotationDirs = ANNOTATION_DIRS) {
|
||||
const normId = String(cascadeId || '').trim().toLowerCase();
|
||||
if (!normId) return '';
|
||||
const dirs = Array.isArray(annotationDirs) ? annotationDirs : [];
|
||||
for (const dir of dirs) {
|
||||
if (!dir) continue;
|
||||
const filePath = join(dir, `${normId}.pbtxt`);
|
||||
if (!existsSync(filePath)) continue;
|
||||
try {
|
||||
const title = parseAnnotationPbtxtTitle(readFileSync(filePath, 'utf8'));
|
||||
if (title) return title;
|
||||
} catch {
|
||||
// 忽略单文件读取失败
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function normalizeSqliteIsoTime(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) return '';
|
||||
return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T');
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取并缓存各产品数据根目录下的 `conversation_summaries.db` 摘要索引。
|
||||
* 使用 `.db` 与 `.db-wal` 的 `mtimeMs + size` 组合签名做内存 Memoize,未发生写入时零 I/O 返回。
|
||||
*
|
||||
* @param {string[]} [productRoots=PRODUCT_DATA_ROOTS]
|
||||
* @returns {Map<string, {
|
||||
* cascadeId: string,
|
||||
* title: string,
|
||||
* status: string,
|
||||
* parentConversationId: string,
|
||||
* agentName: string,
|
||||
* stepCount: number,
|
||||
* lastModifiedTime: string,
|
||||
* lastModifiedMs: number,
|
||||
* appDataDir: string
|
||||
* }>}
|
||||
*/
|
||||
export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) {
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return new Map();
|
||||
const roots = Array.isArray(productRoots) ? productRoots : [];
|
||||
const sigParts = [];
|
||||
const targets = [];
|
||||
|
||||
for (const root of roots) {
|
||||
if (!root) continue;
|
||||
const dbPath = join(root, 'conversation_summaries.db');
|
||||
if (!existsSync(dbPath)) continue;
|
||||
try {
|
||||
const st = statSync(dbPath);
|
||||
let walPart = '0:0';
|
||||
const walPath = `${dbPath}-wal`;
|
||||
if (existsSync(walPath)) {
|
||||
try {
|
||||
const wst = statSync(walPath);
|
||||
walPart = `${wst.mtimeMs || 0}:${wst.size || 0}`;
|
||||
} catch {
|
||||
// 忽略并发清理的 wal 文件
|
||||
}
|
||||
}
|
||||
sigParts.push(`${dbPath}:${st.mtimeMs || 0}:${st.size || 0}:${walPart}`);
|
||||
targets.push({ rootName: basename(root).toLowerCase(), dbPath });
|
||||
} catch {
|
||||
// 忽略不可访问的摘要库
|
||||
}
|
||||
}
|
||||
|
||||
if (targets.length === 0) {
|
||||
localSummaryMemo.sig = '';
|
||||
localSummaryMemo.byId.clear();
|
||||
return localSummaryMemo.byId;
|
||||
}
|
||||
|
||||
const sig = sigParts.join('|');
|
||||
if (localSummaryMemo.sig === sig && localSummaryMemo.byId.size > 0) {
|
||||
return localSummaryMemo.byId;
|
||||
}
|
||||
|
||||
const nextMap = new Map();
|
||||
for (const { rootName, dbPath } of targets) {
|
||||
let db = null;
|
||||
try {
|
||||
db = new DatabaseSync(dbPath, { readOnly: true });
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT
|
||||
conversation_id,
|
||||
title,
|
||||
status,
|
||||
parent_conversation_id,
|
||||
agent_name,
|
||||
not_fully_idle,
|
||||
killed,
|
||||
step_count,
|
||||
last_modified_time,
|
||||
app_data_dir
|
||||
FROM conversation_summaries`
|
||||
)
|
||||
.all();
|
||||
for (const row of rows || []) {
|
||||
const cidLower = String(row?.conversation_id || '').trim().toLowerCase();
|
||||
if (!cidLower) continue;
|
||||
const appDataDir = String(row?.app_data_dir || '').trim().toLowerCase();
|
||||
const isNativeRootRow = Boolean(appDataDir && appDataDir === rootName);
|
||||
const lastModifiedTime = normalizeSqliteIsoTime(row?.last_modified_time);
|
||||
const lastModifiedMs = parseIsoMs(lastModifiedTime);
|
||||
const rawStatus = String(row?.status || '').trim();
|
||||
const isRunning =
|
||||
!Number(row?.killed) &&
|
||||
(rawStatus === 'CASCADE_RUN_STATUS_RUNNING' ||
|
||||
(Number(row?.not_fully_idle) > 0 && rawStatus !== 'CASCADE_RUN_STATUS_IDLE'));
|
||||
const entry = {
|
||||
cascadeId: cidLower,
|
||||
title: String(row?.title || '').trim(),
|
||||
status: isRunning ? 'CASCADE_RUN_STATUS_RUNNING' : rawStatus || 'CASCADE_RUN_STATUS_IDLE',
|
||||
parentConversationId: String(row?.parent_conversation_id || '').trim().toLowerCase(),
|
||||
agentName: String(row?.agent_name || '').trim(),
|
||||
stepCount: Math.max(0, Math.floor(Number(row?.step_count) || 0)),
|
||||
lastModifiedTime,
|
||||
lastModifiedMs,
|
||||
appDataDir,
|
||||
isNativeRootRow,
|
||||
};
|
||||
const prev = nextMap.get(cidLower);
|
||||
if (
|
||||
!prev ||
|
||||
(entry.isNativeRootRow && !prev.isNativeRootRow) ||
|
||||
(entry.isNativeRootRow === prev.isNativeRootRow &&
|
||||
entry.lastModifiedMs >= prev.lastModifiedMs)
|
||||
) {
|
||||
nextMap.set(cidLower, entry);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略正在初始化或损坏的 SQLite 文件
|
||||
} finally {
|
||||
if (db) {
|
||||
try {
|
||||
db.close();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
localSummaryMemo.sig = sig;
|
||||
localSummaryMemo.byId = nextMap;
|
||||
return nextMap;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 零依赖轻量 Protobuf Wire 解码器(仅提取指标字段,O(1) 跳过大体积 Prompt 载荷)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function readProtoVarint(buf, state) {
|
||||
let result = 0n;
|
||||
let shift = 0n;
|
||||
while (state.off < buf.length) {
|
||||
const byte = BigInt(buf[state.off++]);
|
||||
result |= (byte & 0x7fn) << shift;
|
||||
if ((byte & 0x80n) === 0n) return result;
|
||||
shift += 7n;
|
||||
if (shift > 70n) throw new Error('Invalid protobuf varint');
|
||||
}
|
||||
throw new Error('Unexpected EOF in protobuf varint');
|
||||
}
|
||||
|
||||
function skipProtoField(buf, state, wireType) {
|
||||
if (wireType === 0) {
|
||||
readProtoVarint(buf, state);
|
||||
} else if (wireType === 1) {
|
||||
state.off += 8;
|
||||
} else if (wireType === 2) {
|
||||
const len = Number(readProtoVarint(buf, state));
|
||||
state.off += len;
|
||||
} else if (wireType === 5) {
|
||||
state.off += 4;
|
||||
} else {
|
||||
throw new Error(`Unsupported protobuf wireType: ${wireType}`);
|
||||
}
|
||||
if (state.off > buf.length) {
|
||||
throw new Error('Protobuf field length out of bounds');
|
||||
}
|
||||
}
|
||||
|
||||
function decodeProtoTimestampIso(buf) {
|
||||
const st = { off: 0 };
|
||||
let seconds = 0n;
|
||||
let nanos = 0n;
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
seconds = BigInt.asIntN(64, readProtoVarint(buf, st));
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
nanos = BigInt.asIntN(32, readProtoVarint(buf, st));
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
if (seconds <= 0n) return '';
|
||||
const baseIso = new Date(Number(seconds) * 1000).toISOString();
|
||||
const prefix = baseIso.slice(0, 19);
|
||||
if (nanos > 0n && nanos < 1_000_000_000n) {
|
||||
const frac = String(nanos).padStart(9, '0').replace(/0+$/, '');
|
||||
return frac ? `${prefix}.${frac}Z` : `${prefix}Z`;
|
||||
}
|
||||
return `${prefix}Z`;
|
||||
}
|
||||
|
||||
function decodeProtoDurationStr(buf) {
|
||||
const st = { off: 0 };
|
||||
let seconds = 0n;
|
||||
let nanos = 0n;
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
seconds = BigInt.asIntN(64, readProtoVarint(buf, st));
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
nanos = BigInt.asIntN(32, readProtoVarint(buf, st));
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
if (seconds < 0n || nanos < 0n) return '';
|
||||
if (nanos === 0n) return `${seconds}s`;
|
||||
const frac = String(nanos).padStart(9, '0').replace(/0+$/, '');
|
||||
return frac ? `${seconds}.${frac}s` : `${seconds}s`;
|
||||
}
|
||||
|
||||
function decodeProtoModelEnumInt(val) {
|
||||
const n = Number(val);
|
||||
if (Number.isInteger(n) && n >= 1000 && n < 10000) {
|
||||
return `MODEL_PLACEHOLDER_M${n - 1000}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function decodeProtoTokenTypeEnum(val) {
|
||||
switch (Number(val)) {
|
||||
case 1:
|
||||
return 'TOKEN_TYPE_SYSTEM_PROMPT';
|
||||
case 2:
|
||||
return 'TOKEN_TYPE_TOOLS';
|
||||
case 3:
|
||||
return 'TOKEN_TYPE_RULES';
|
||||
case 4:
|
||||
return 'TOKEN_TYPE_MCP_TOOLS';
|
||||
case 5:
|
||||
return 'TOKEN_TYPE_SKILLS';
|
||||
case 6:
|
||||
return 'TOKEN_TYPE_SUBAGENTS';
|
||||
case 7:
|
||||
return 'TOKEN_TYPE_CHAT_MESSAGES';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function decodeProtoStepTypeEnum(val) {
|
||||
switch (Number(val)) {
|
||||
case 14:
|
||||
return 'CORTEX_STEP_TYPE_USER_INPUT';
|
||||
case 15:
|
||||
return 'CORTEX_STEP_TYPE_PLANNER_RESPONSE';
|
||||
case 17:
|
||||
return 'CORTEX_STEP_TYPE_ERROR_MESSAGE';
|
||||
case 23:
|
||||
return 'CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
case 101:
|
||||
return 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE';
|
||||
default:
|
||||
return 'CORTEX_STEP_TYPE_GENERIC';
|
||||
}
|
||||
}
|
||||
|
||||
function decodeProtoStepStatusEnum(val) {
|
||||
switch (Number(val)) {
|
||||
case 2:
|
||||
return 'CORTEX_STEP_STATUS_RUNNING';
|
||||
case 3:
|
||||
return 'CORTEX_STEP_STATUS_DONE';
|
||||
case 5:
|
||||
return 'CORTEX_STEP_STATUS_CLEARED';
|
||||
case 6:
|
||||
return 'CORTEX_STEP_STATUS_CANCELED';
|
||||
case 7:
|
||||
return 'CORTEX_STEP_STATUS_ERROR';
|
||||
case 8:
|
||||
return 'CORTEX_STEP_STATUS_GENERATING';
|
||||
default:
|
||||
return 'CORTEX_STEP_STATUS_DONE';
|
||||
}
|
||||
}
|
||||
|
||||
function decodeProtoModelUsage(buf) {
|
||||
const st = { off: 0 };
|
||||
let model = '';
|
||||
let inputTokens = 0;
|
||||
let outputTokens = 0;
|
||||
let cacheReadTokens = 0;
|
||||
let apiProviderNum = 0;
|
||||
let thinkingOutputTokens;
|
||||
let responseOutputTokens;
|
||||
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
model = decodeProtoModelEnumInt(readProtoVarint(buf, st));
|
||||
} else if (fn === 1 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
model = buf.subarray(st.off, st.off + len).toString('utf8');
|
||||
st.off += len;
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
inputTokens = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 3 && wt === 0) {
|
||||
outputTokens = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 5 && wt === 0) {
|
||||
cacheReadTokens = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 6 && wt === 0) {
|
||||
apiProviderNum = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 9 && wt === 0) {
|
||||
thinkingOutputTokens = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 10 && wt === 0) {
|
||||
responseOutputTokens = Number(readProtoVarint(buf, st));
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...(model ? { model } : {}),
|
||||
...(apiProviderNum === 24 ? { apiProvider: 'API_PROVIDER_GOOGLE_GEMINI' } : {}),
|
||||
inputTokens,
|
||||
cacheReadTokens,
|
||||
outputTokens,
|
||||
...(thinkingOutputTokens !== undefined ? { thinkingOutputTokens } : {}),
|
||||
...(responseOutputTokens !== undefined ? { responseOutputTokens } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoTokenBreakdownGroup(buf, depth = 0) {
|
||||
const st = { off: 0 };
|
||||
let name = '';
|
||||
let type = '';
|
||||
let numTokens = 0;
|
||||
const children = [];
|
||||
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
name = buf.subarray(st.off, st.off + len).toString('utf8');
|
||||
st.off += len;
|
||||
} else if (fn === 2 && wt === 0) {
|
||||
type = decodeProtoTokenTypeEnum(readProtoVarint(buf, st));
|
||||
} else if (fn === 4 && wt === 0) {
|
||||
numTokens = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 5 && wt === 2 && depth < 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
const sub = buf.subarray(st.off, st.off + len);
|
||||
st.off += len;
|
||||
children.push(decodeProtoTokenBreakdownGroup(sub, depth + 1));
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
...(type ? { type } : {}),
|
||||
numTokens,
|
||||
...(children.length > 0 ? { children } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoContextWindowMeta(buf) {
|
||||
const st = { off: 0 };
|
||||
let estimatedTokensUsed = 0;
|
||||
let maxContextTokens = 0;
|
||||
const groups = [];
|
||||
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 0) {
|
||||
estimatedTokensUsed = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 4 && wt === 0) {
|
||||
maxContextTokens = Number(readProtoVarint(buf, st));
|
||||
} else if (fn === 3 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
const tbBuf = buf.subarray(st.off, st.off + len);
|
||||
st.off += len;
|
||||
const tbSt = { off: 0 };
|
||||
while (tbSt.off < tbBuf.length) {
|
||||
const tbTag = Number(readProtoVarint(tbBuf, tbSt));
|
||||
const tbFn = tbTag >>> 3;
|
||||
const tbWt = tbTag & 7;
|
||||
if (tbFn === 1 && tbWt === 2) {
|
||||
const gLen = Number(readProtoVarint(tbBuf, tbSt));
|
||||
const gBuf = tbBuf.subarray(tbSt.off, tbSt.off + gLen);
|
||||
tbSt.off += gLen;
|
||||
groups.push(decodeProtoTokenBreakdownGroup(gBuf, 0));
|
||||
} else {
|
||||
skipProtoField(tbBuf, tbSt, tbWt);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...(estimatedTokensUsed > 0 ? { estimatedTokensUsed } : {}),
|
||||
...(maxContextTokens > 0 ? { maxContextTokens } : {}),
|
||||
...(groups.length > 0 ? { tokenBreakdown: { groups } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoMapStringEntry(buf) {
|
||||
const st = { off: 0 };
|
||||
let key = '';
|
||||
let val = '';
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
key = buf.subarray(st.off, st.off + len).toString('utf8');
|
||||
st.off += len;
|
||||
} else if (fn === 2 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
val = buf.subarray(st.off, st.off + len).toString('utf8');
|
||||
st.off += len;
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
return [key, val];
|
||||
}
|
||||
|
||||
function decodeProtoChatModelMeta(buf) {
|
||||
const st = { off: 0 };
|
||||
let model = '';
|
||||
let usage = null;
|
||||
let contextWindowMetadata = null;
|
||||
let timeToFirstToken = '';
|
||||
let streamingDuration = '';
|
||||
let responseModel = '';
|
||||
let modelDisplayName = '';
|
||||
const extraMeta = {};
|
||||
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 3 && wt === 0) {
|
||||
const enumStr = decodeProtoModelEnumInt(readProtoVarint(buf, st));
|
||||
if (enumStr && !model) model = enumStr;
|
||||
} else if (fn === 4 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
usage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 9 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
const csBuf = buf.subarray(st.off, st.off + len);
|
||||
st.off += len;
|
||||
const csSt = { off: 0 };
|
||||
while (csSt.off < csBuf.length) {
|
||||
const csTag = Number(readProtoVarint(csBuf, csSt));
|
||||
const csFn = csTag >>> 3;
|
||||
const csWt = csTag & 7;
|
||||
if (csFn === 10 && csWt === 2) {
|
||||
const cwLen = Number(readProtoVarint(csBuf, csSt));
|
||||
contextWindowMetadata = decodeProtoContextWindowMeta(
|
||||
csBuf.subarray(csSt.off, csSt.off + cwLen)
|
||||
);
|
||||
csSt.off += cwLen;
|
||||
} else {
|
||||
skipProtoField(csBuf, csSt, csWt);
|
||||
}
|
||||
}
|
||||
} else if (fn === 11 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
timeToFirstToken = decodeProtoDurationStr(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 12 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
streamingDuration = decodeProtoDurationStr(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 19 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
responseModel = buf.subarray(st.off, st.off + len).toString('utf8').trim();
|
||||
st.off += len;
|
||||
} else if (fn === 20 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
const [k, v] = decodeProtoMapStringEntry(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
if (k && v) extraMeta[k] = v;
|
||||
} else if (fn === 21 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
modelDisplayName = buf.subarray(st.off, st.off + len).toString('utf8').trim();
|
||||
st.off += len;
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
|
||||
if (extraMeta.model_enum) {
|
||||
model = extraMeta.model_enum.trim();
|
||||
if (usage && !usage.model) {
|
||||
usage.model = model;
|
||||
}
|
||||
}
|
||||
if (extraMeta.used_claude === 'true' && usage && !usage.apiProvider) {
|
||||
usage.apiProvider = 'API_PROVIDER_ANTHROPIC';
|
||||
}
|
||||
|
||||
return {
|
||||
chatModel: {
|
||||
...(model ? { model } : {}),
|
||||
...(usage ? { usage } : {}),
|
||||
...(contextWindowMetadata ? { chatStartMetadata: { contextWindowMetadata } } : {}),
|
||||
...(timeToFirstToken ? { timeToFirstToken } : {}),
|
||||
...(streamingDuration ? { streamingDuration } : {}),
|
||||
...(responseModel ? { responseModel } : {}),
|
||||
...(modelDisplayName ? { modelDisplayName } : {}),
|
||||
},
|
||||
extraMeta,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoGeneratorMeta(buf) {
|
||||
const st = { off: 0 };
|
||||
const stepIndices = [];
|
||||
let chatDecoded = null;
|
||||
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 2 && wt === 0) {
|
||||
stepIndices.push(Number(readProtoVarint(buf, st)));
|
||||
} else if (fn === 2 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
const end = st.off + len;
|
||||
while (st.off < end) {
|
||||
stepIndices.push(Number(readProtoVarint(buf, st)));
|
||||
}
|
||||
} else if (fn === 1 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
chatDecoded = decodeProtoChatModelMeta(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
|
||||
if (!chatDecoded) return null;
|
||||
return {
|
||||
stepIndices,
|
||||
chatModel: chatDecoded.chatModel,
|
||||
extraMeta: chatDecoded.extraMeta,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoStepMeta(buf, fallbackIdx) {
|
||||
const st = { off: 0 };
|
||||
let createdAt = '';
|
||||
let viewableAt = '';
|
||||
let finishedGeneratingAt = '';
|
||||
let completedAt = '';
|
||||
let modelUsage = null;
|
||||
let generatorModel = '';
|
||||
let stepIndex = fallbackIdx;
|
||||
|
||||
while (st.off < buf.length) {
|
||||
const tag = Number(readProtoVarint(buf, st));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 1 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
createdAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 6 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
viewableAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 7 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
finishedGeneratingAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 32 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
completedAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 9 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
modelUsage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len));
|
||||
st.off += len;
|
||||
} else if (fn === 11 && wt === 0) {
|
||||
generatorModel = decodeProtoModelEnumInt(readProtoVarint(buf, st));
|
||||
} else if (fn === 20 && wt === 2) {
|
||||
const len = Number(readProtoVarint(buf, st));
|
||||
const siBuf = buf.subarray(st.off, st.off + len);
|
||||
st.off += len;
|
||||
const siSt = { off: 0 };
|
||||
while (siSt.off < siBuf.length) {
|
||||
const siTag = Number(readProtoVarint(siBuf, siSt));
|
||||
const siFn = siTag >>> 3;
|
||||
const siWt = siTag & 7;
|
||||
if (siFn === 2 && siWt === 0) {
|
||||
stepIndex = Number(readProtoVarint(siBuf, siSt));
|
||||
} else {
|
||||
skipProtoField(siBuf, siSt, siWt);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
skipProtoField(buf, st, wt);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...(createdAt ? { createdAt } : {}),
|
||||
...(viewableAt ? { viewableAt } : {}),
|
||||
...(finishedGeneratingAt ? { finishedGeneratingAt } : {}),
|
||||
...(completedAt ? { completedAt } : {}),
|
||||
...(generatorModel ? { generatorModel } : {}),
|
||||
sourceTrajectoryStepInfo: { stepIndex },
|
||||
...(modelUsage ? { modelUsage } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从单个会话的本地 SQLite 数据库(`<product>/conversations/<cascadeId>.db`)提取步骤元数据与生成器元数据。
|
||||
* 严格只查询 `steps.metadata` 与 `gen_metadata.data`,不加载 `step_payload` 大字段。
|
||||
*
|
||||
* @param {string} dbFilePath
|
||||
* @returns {{
|
||||
* steps: Array<{ idx: number, type: string, status: string, metadata: object }>,
|
||||
* generatorMetadata: Array<{ stepIndices: number[], chatModel: object }>,
|
||||
* rootConversationId: string,
|
||||
* parentConversationId: string
|
||||
* } | null}
|
||||
*/
|
||||
export function readLocalSqliteTrajectory(dbFilePath) {
|
||||
if (!dbFilePath || !existsSync(dbFilePath)) return null;
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
|
||||
let db = null;
|
||||
try {
|
||||
db = new DatabaseSync(dbFilePath, { readOnly: true });
|
||||
const genRows = db.prepare('SELECT idx, data FROM gen_metadata ORDER BY idx ASC').all();
|
||||
const generatorMetadata = [];
|
||||
const genByStep = new Map();
|
||||
let rootConversationId = '';
|
||||
let parentConversationId = '';
|
||||
|
||||
for (const row of genRows || []) {
|
||||
if (!row?.data) continue;
|
||||
try {
|
||||
const decoded = decodeProtoGeneratorMeta(Buffer.from(row.data));
|
||||
if (!decoded) continue;
|
||||
const gmItem = {
|
||||
stepIndices: decoded.stepIndices,
|
||||
chatModel: decoded.chatModel,
|
||||
};
|
||||
generatorMetadata.push(gmItem);
|
||||
for (const sIdx of decoded.stepIndices) {
|
||||
genByStep.set(Number(sIdx), gmItem);
|
||||
}
|
||||
if (!rootConversationId && decoded.extraMeta?.root_cascade_id) {
|
||||
rootConversationId = String(decoded.extraMeta.root_cascade_id).trim().toLowerCase();
|
||||
}
|
||||
if (!parentConversationId && decoded.extraMeta?.parent_cascade_id) {
|
||||
parentConversationId = String(decoded.extraMeta.parent_cascade_id).trim().toLowerCase();
|
||||
}
|
||||
} catch {
|
||||
// 忽略单条损坏的 generatorMetadata
|
||||
}
|
||||
}
|
||||
|
||||
const stepRows = db
|
||||
.prepare('SELECT idx, step_type, status, metadata FROM steps ORDER BY idx ASC')
|
||||
.all();
|
||||
const steps = [];
|
||||
for (const row of stepRows || []) {
|
||||
const idx = Number.isFinite(Number(row?.idx)) ? Number(row.idx) : steps.length;
|
||||
const type = decodeProtoStepTypeEnum(row?.step_type);
|
||||
const status = decodeProtoStepStatusEnum(row?.status);
|
||||
let metadata = { sourceTrajectoryStepInfo: { stepIndex: idx } };
|
||||
if (row?.metadata && row.metadata.byteLength > 0) {
|
||||
try {
|
||||
metadata = decodeProtoStepMeta(Buffer.from(row.metadata), idx);
|
||||
} catch {
|
||||
// 忽略单步元数据解码异常
|
||||
}
|
||||
}
|
||||
const stepIdx = metadata.sourceTrajectoryStepInfo?.stepIndex ?? idx;
|
||||
const gm = genByStep.get(Number(stepIdx));
|
||||
if (metadata.modelUsage && gm?.chatModel?.model && !metadata.modelUsage.model) {
|
||||
metadata.modelUsage.model = gm.chatModel.model;
|
||||
}
|
||||
steps.push({ idx, type, status, metadata });
|
||||
}
|
||||
|
||||
if (steps.length === 0 && generatorMetadata.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
steps,
|
||||
generatorMetadata,
|
||||
rootConversationId,
|
||||
parentConversationId,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (db) {
|
||||
try {
|
||||
db.close();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,955 @@
|
||||
/**
|
||||
* @fileoverview Antigravity CLI (`agy`) 底部状态栏胶囊 (`statusLine`) 配置管理与终端 ANSI 渲染器。
|
||||
*
|
||||
* 负责两部分纯逻辑与安全落盘职责:
|
||||
* 1. 无损维护 `~/.gemini/antigravity-cli/settings.json` 中的 `statusLine` 配置:
|
||||
* - 仅当 `~/.gemini/antigravity-cli` 目录已存在时生效;
|
||||
* - 若用户已自行配置第三方 `statusLine.command`(非本插件 `cli-statusline.mjs`),严格原样保留绝不覆盖;
|
||||
* - 开启时默认以 `stack_with_default: false` 单行内联接管底栏(左侧保留 `? for shortcuts`,中间渲染无底色监控指标,右侧保留 `auto · Model · effort`);关闭时干净移除本插件托管项;
|
||||
* 2. 将 13 项胶囊槽位(`TOPBAR_SLOT_KEYS`)与多会话状态渲染为兼容 Windows `cmd.exe` (CP936) /
|
||||
* PowerShell / Windows Terminal / macOS / Linux 的单行无底色 24-bit ANSI 状态条(仅使用标准前景 CSI SGR,
|
||||
* 避免深色背景色块突兀及 OSC 序列干扰 Bubble Tea 宽度计算)。
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { delimiter, dirname, join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { HERE, lsRuntimeEndpoint, normalizeLanguageSetting, normalizeTopbarCapsuleSlots } from './config.mjs';
|
||||
|
||||
const CLI_STATUS_THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
||||
|
||||
// 24-bit ANSI 前景 SGR 调色板(透明底色,与桌面端四档语义色阶及 CLI 原生底栏色调对齐,无任何背景填充或非 SGR 控制符)
|
||||
const SGR_RESET = '\x1b[0m';
|
||||
const SGR_BOLD = '\x1b[1m';
|
||||
const SGR_FG_BRIGHT = '\x1b[38;2;226;232;240m';
|
||||
const SGR_FG_NORMAL = '\x1b[38;2;203;213;225m';
|
||||
const SGR_FG_MUTED = '\x1b[38;2;148;163;184m';
|
||||
const SGR_FG_DIM = '\x1b[38;2;120;133;155m';
|
||||
const SGR_FG_CHROME = '\x1b[38;2;136;142;150m';
|
||||
const SGR_FG_SEP = '\x1b[38;2;90;100;116m';
|
||||
const SGR_FG_DOT_IDLE = '\x1b[38;2;100;116;139m';
|
||||
const SGR_FG_ACCENT = '\x1b[38;2;96;165;250m';
|
||||
const SGR_FG_GOOD = '\x1b[38;2;52;211;153m';
|
||||
const SGR_FG_INFO = '\x1b[38;2;56;189;248m';
|
||||
const SGR_FG_WARN = '\x1b[38;2;251;191;36m';
|
||||
const SGR_FG_DANGER = '\x1b[38;2;248;113;113m';
|
||||
const SGR_FG_MODE_AUTO = '\x1b[38;2;234;179;8m';
|
||||
const SGR_FG_MODE_VIOLET = '\x1b[38;2;192;132;252m';
|
||||
|
||||
function isCliStatusPlainObject(v) {
|
||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 `~/.gemini/antigravity-cli/settings.json` 路径(支持 `ANTIGRAVITY_GEMINI_DIR` 覆盖)。
|
||||
*
|
||||
* @param {Record<string, string|undefined>} [env=process.env]
|
||||
* @param {string} [homeDir=homedir()]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function resolveCliSettingsPath(env = process.env, homeDir = homedir()) {
|
||||
const geminiBase = String(env?.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homeDir, '.gemini');
|
||||
return join(geminiBase, 'antigravity-cli', 'settings.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 优先解析本机已安装插件目录下的 `cli-statusline.mjs`,不存在时回退至当前运行目录 `HERE`。
|
||||
*
|
||||
* @param {{ env?: Record<string, string|undefined>, homeDir?: string, fallbackHere?: string }} [options]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function resolvePreferredCliStatusLineScriptPath({
|
||||
env = process.env,
|
||||
homeDir = homedir(),
|
||||
fallbackHere = HERE,
|
||||
} = {}) {
|
||||
const geminiBase = String(env?.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homeDir, '.gemini');
|
||||
const installedCandidate = join(
|
||||
geminiBase,
|
||||
'config',
|
||||
'plugins',
|
||||
'usage-monitor',
|
||||
'sidecars',
|
||||
'panel',
|
||||
'cli-statusline.mjs'
|
||||
);
|
||||
if (existsSync(installedCandidate)) {
|
||||
return installedCandidate;
|
||||
}
|
||||
return join(fallbackHere, 'cli-statusline.mjs');
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测当前环境变量 `PATH` 中是否可直接定位 `node` 可执行文件。
|
||||
*
|
||||
* @param {Record<string, string|undefined>} [env=process.env]
|
||||
* @param {string} [platform=process.platform]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function detectNodeOnSystemPath(env = process.env, platform = process.platform) {
|
||||
const rawPath = String(env?.PATH || env?.Path || env?.path || '').trim();
|
||||
if (!rawPath) return false;
|
||||
const binNames = platform === 'win32' ? ['node.exe', 'node.cmd', 'node'] : ['node'];
|
||||
const sep = platform === 'win32' ? ';' : delimiter;
|
||||
for (const rawDir of rawPath.split(sep)) {
|
||||
const cleanDir = rawDir.trim().replace(/^"+|"+$/g, '');
|
||||
if (!cleanDir) continue;
|
||||
for (const bin of binNames) {
|
||||
try {
|
||||
if (existsSync(join(cleanDir, bin))) return true;
|
||||
} catch {
|
||||
// 忽略无权限目录
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function toPercentEncodedFileUrl(winOrPosixPath) {
|
||||
const clean = String(winOrPosixPath || '').trim().replace(/\\/g, '/');
|
||||
if (/^[a-zA-Z]:\//.test(clean)) {
|
||||
const encoded = clean
|
||||
.split('/')
|
||||
.map((seg, idx) => (idx === 0 ? seg : encodeURIComponent(seg)))
|
||||
.join('/');
|
||||
return `file:///${encoded}#autorun`;
|
||||
}
|
||||
try {
|
||||
return `${pathToFileURL(clean).href}#autorun`;
|
||||
} catch {
|
||||
return `file://${encodeURI(clean)}#autorun`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造跨平台安全的 `statusLine.command` 字符串:
|
||||
* - Windows 下 `agy.exe` 通过 Go `exec.Command("cmd", "/c", command)` 执行:Go 的 `syscall.EscapeArg`
|
||||
* 会把 `command` 内的任何双引号 `"` 转义成 `\"`,而 `cmd.exe` 不消费 `\"` 会将其原样传给 `node.exe`,
|
||||
* 导致 `argv[1]` 混入字面量双引号而找不到模块。因此 Windows 下严格避免在 `command` 中出现双引号 `"`:
|
||||
* - 路径无空格时直接生成 `node C:/.../cli-statusline.mjs`;
|
||||
* - 路径含空格时生成零双引号、零空格参数的 `node --input-type=module -e import('file:///C:/...%20.../cli-statusline.mjs#autorun')`;
|
||||
* - macOS / Linux 下由 `sh -c` 解析,正常使用标准引号包裹。
|
||||
*
|
||||
* @param {string} scriptPath
|
||||
* @param {{ platform?: string, execPath?: string, nodeOnPath?: boolean }} [options]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function buildCliStatusLineCommand(
|
||||
scriptPath,
|
||||
{
|
||||
platform = process.platform,
|
||||
execPath = process.execPath,
|
||||
nodeOnPath = true,
|
||||
} = {}
|
||||
) {
|
||||
const normScript = String(scriptPath || '').trim().replace(/\\/g, '/');
|
||||
if (platform === 'win32') {
|
||||
const normExec = String(execPath || 'node').trim().replace(/\\/g, '/');
|
||||
const runner = nodeOnPath || /\s/.test(normExec) ? 'node' : normExec;
|
||||
if (!/\s/.test(normScript)) {
|
||||
return `${runner} ${normScript}`;
|
||||
}
|
||||
const fileUrl = toPercentEncodedFileUrl(normScript).replace(/'/g, '%27');
|
||||
return `${runner} --input-type=module -e import('${fileUrl}')`;
|
||||
}
|
||||
if (nodeOnPath) {
|
||||
return `node "${normScript.replace(/"/g, '\\"')}"`;
|
||||
}
|
||||
const escapedExec = String(execPath || 'node').replace(/"/g, '\\"');
|
||||
const escapedScript = normScript.replace(/"/g, '\\"');
|
||||
return `"${escapedExec}" "${escapedScript}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一条 `statusLine.command` 是否由本插件托管(指向 `cli-statusline.mjs`)。
|
||||
*
|
||||
* @param {unknown} cmd
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isManagedCliStatusLineCommand(cmd) {
|
||||
if (typeof cmd !== 'string') return false;
|
||||
const trimmed = cmd.trim();
|
||||
if (!trimmed) return false;
|
||||
return /(?:^|[\\/\s"'])cli-statusline\.mjs(?:#autorun)?(?:["')\s]|$)/i.test(trimmed);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在纯对象层面更新或移除本插件托管的 `statusLine` 配置,绝不覆盖用户自定义的第三方脚本。
|
||||
*
|
||||
* @param {unknown} rawObj
|
||||
* @param {{ enabled?: boolean, command?: string, stackWithDefault?: boolean }} [options]
|
||||
*/
|
||||
export function applyCliStatusLineToSettingsObject(
|
||||
rawObj,
|
||||
{ enabled = true, command = '', stackWithDefault = false } = {}
|
||||
) {
|
||||
const baseObj = isCliStatusPlainObject(rawObj) ? rawObj : {};
|
||||
const existing = baseObj.statusLine;
|
||||
|
||||
if (isCliStatusPlainObject(existing)) {
|
||||
const existingCmd = typeof existing.command === 'string' ? existing.command.trim() : '';
|
||||
if (existingCmd && !isManagedCliStatusLineCommand(existingCmd)) {
|
||||
return {
|
||||
changed: false,
|
||||
preservedCustom: true,
|
||||
reason: 'custom_command_preserved',
|
||||
object: baseObj,
|
||||
};
|
||||
}
|
||||
} else if (existing !== undefined && existing !== null) {
|
||||
return {
|
||||
changed: false,
|
||||
preservedCustom: true,
|
||||
reason: 'custom_statusline_preserved',
|
||||
object: baseObj,
|
||||
};
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
if (!Object.prototype.hasOwnProperty.call(baseObj, 'statusLine')) {
|
||||
return {
|
||||
changed: false,
|
||||
alreadyRemoved: true,
|
||||
object: baseObj,
|
||||
};
|
||||
}
|
||||
const nextObj = { ...baseObj };
|
||||
delete nextObj.statusLine;
|
||||
return {
|
||||
changed: true,
|
||||
removed: true,
|
||||
object: nextObj,
|
||||
};
|
||||
}
|
||||
|
||||
const cleanCmd = String(command || '').trim();
|
||||
if (!cleanCmd) {
|
||||
return {
|
||||
changed: false,
|
||||
reason: 'empty_command',
|
||||
object: baseObj,
|
||||
};
|
||||
}
|
||||
|
||||
const prevBlock = isCliStatusPlainObject(existing) ? existing : {};
|
||||
const desiredPadding =
|
||||
Number.isInteger(prevBlock.padding) && prevBlock.padding >= 0 ? prevBlock.padding : 0;
|
||||
const desiredStack = typeof stackWithDefault === 'boolean' ? stackWithDefault : false;
|
||||
|
||||
const nextStatusLine = {
|
||||
...prevBlock,
|
||||
type: 'command',
|
||||
command: cleanCmd,
|
||||
enabled: true,
|
||||
padding: desiredPadding,
|
||||
stack_with_default: desiredStack,
|
||||
};
|
||||
|
||||
const unchanged =
|
||||
isCliStatusPlainObject(existing) &&
|
||||
existing.type === nextStatusLine.type &&
|
||||
existing.command === nextStatusLine.command &&
|
||||
existing.enabled === nextStatusLine.enabled &&
|
||||
existing.padding === nextStatusLine.padding &&
|
||||
existing.stack_with_default === nextStatusLine.stack_with_default;
|
||||
|
||||
if (unchanged) {
|
||||
return {
|
||||
changed: false,
|
||||
alreadyConfigured: true,
|
||||
object: baseObj,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
changed: true,
|
||||
configured: true,
|
||||
object: {
|
||||
...baseObj,
|
||||
statusLine: nextStatusLine,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步本插件在 `~/.gemini/antigravity-cli/settings.json` 中的托管 `statusLine` 配置。
|
||||
*
|
||||
* @param {{
|
||||
* enabled?: boolean,
|
||||
* env?: Record<string, string|undefined>,
|
||||
* homeDir?: string,
|
||||
* scriptPath?: string,
|
||||
* platform?: string,
|
||||
* execPath?: string,
|
||||
* nodeOnPath?: boolean,
|
||||
* }} [options]
|
||||
*/
|
||||
export function ensureCliStatusLineConfigured({
|
||||
enabled = true,
|
||||
env = process.env,
|
||||
homeDir = homedir(),
|
||||
scriptPath = '',
|
||||
platform = process.platform,
|
||||
execPath = process.execPath,
|
||||
nodeOnPath,
|
||||
} = {}) {
|
||||
if (
|
||||
lsRuntimeEndpoint.addr === 'test.invalid' &&
|
||||
String(env?.USAGE_MONITOR_ALLOW_TEST_CLI_SETTINGS || '') !== '1'
|
||||
) {
|
||||
return { checked: false, updated: false, reason: 'test_sandbox_skipped' };
|
||||
}
|
||||
|
||||
const settingsPath = resolveCliSettingsPath(env, homeDir);
|
||||
try {
|
||||
const cliDir = dirname(settingsPath);
|
||||
if (!existsSync(cliDir)) {
|
||||
return { checked: true, updated: false, reason: 'cli_dir_missing', settingsPath };
|
||||
}
|
||||
|
||||
let currentObj = {};
|
||||
let eol = platform === 'win32' ? '\r\n' : '\n';
|
||||
if (existsSync(settingsPath)) {
|
||||
const rawText = readFileSync(settingsPath, 'utf8');
|
||||
if (rawText.includes('\r\n')) eol = '\r\n';
|
||||
else if (rawText.includes('\n')) eol = '\n';
|
||||
const trimmed = rawText.replace(/^\uFEFF/, '').trim();
|
||||
if (trimmed) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (!isCliStatusPlainObject(parsed)) {
|
||||
return { checked: true, updated: false, reason: 'non_object_json', settingsPath };
|
||||
}
|
||||
currentObj = parsed;
|
||||
} catch {
|
||||
return { checked: true, updated: false, reason: 'invalid_json', settingsPath };
|
||||
}
|
||||
}
|
||||
} else if (!enabled) {
|
||||
return { checked: true, updated: false, alreadyRemoved: true, settingsPath };
|
||||
}
|
||||
|
||||
const resolvedScript =
|
||||
scriptPath || resolvePreferredCliStatusLineScriptPath({ env, homeDir });
|
||||
const hasNodePath =
|
||||
typeof nodeOnPath === 'boolean' ? nodeOnPath : detectNodeOnSystemPath(env, platform);
|
||||
const command = buildCliStatusLineCommand(resolvedScript, {
|
||||
platform,
|
||||
execPath,
|
||||
nodeOnPath: hasNodePath,
|
||||
});
|
||||
|
||||
const applied = applyCliStatusLineToSettingsObject(currentObj, { enabled, command });
|
||||
if (!applied.changed) {
|
||||
return {
|
||||
checked: true,
|
||||
updated: false,
|
||||
...applied,
|
||||
command,
|
||||
settingsPath,
|
||||
};
|
||||
}
|
||||
|
||||
const serialized = `${JSON.stringify(applied.object, null, 2).replace(/\n/g, eol)}${eol}`;
|
||||
const tmpPath = `${settingsPath}.tmp-${process.pid}`;
|
||||
try {
|
||||
writeFileSync(tmpPath, serialized, 'utf8');
|
||||
renameSync(tmpPath, settingsPath);
|
||||
} catch {
|
||||
try {
|
||||
if (existsSync(tmpPath)) unlinkSync(tmpPath);
|
||||
} catch {
|
||||
// 忽略临时文件清理异常
|
||||
}
|
||||
writeFileSync(settingsPath, serialized, 'utf8');
|
||||
}
|
||||
|
||||
return {
|
||||
checked: true,
|
||||
updated: true,
|
||||
...applied,
|
||||
command,
|
||||
settingsPath,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
checked: true,
|
||||
updated: false,
|
||||
reason: 'io_error',
|
||||
error: err?.message || String(err),
|
||||
settingsPath,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 胶囊槽位纯格式化与终端 ANSI 渲染(与前端 `metricRegistry.js` 语义阈值 1:1 对齐)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function cliStatusSpeedSgr(tokPerSec) {
|
||||
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
||||
return SGR_FG_MUTED;
|
||||
}
|
||||
const v = Number(tokPerSec);
|
||||
if (v >= 60) return SGR_FG_GOOD;
|
||||
if (v >= 35) return SGR_FG_INFO;
|
||||
if (v >= 20) return SGR_FG_WARN;
|
||||
return SGR_FG_DANGER;
|
||||
}
|
||||
|
||||
function cliStatusCacheSgr(cacheHitPct, promptTokens = null) {
|
||||
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) return SGR_FG_MUTED;
|
||||
const v = Number(cacheHitPct);
|
||||
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) return SGR_FG_MUTED;
|
||||
if (v >= 85) return SGR_FG_GOOD;
|
||||
if (v >= 65) return SGR_FG_INFO;
|
||||
if (v >= 30) return SGR_FG_WARN;
|
||||
return SGR_FG_DANGER;
|
||||
}
|
||||
|
||||
function cliStatusCostSgr(costUsd) {
|
||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return SGR_FG_NORMAL;
|
||||
const v = Number(costUsd);
|
||||
if (v >= 0.3) return SGR_FG_DANGER;
|
||||
if (v >= 0.15) return SGR_FG_WARN;
|
||||
return SGR_FG_NORMAL;
|
||||
}
|
||||
|
||||
function cliStatusTtftSgr(ttftSec) {
|
||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) {
|
||||
return SGR_FG_MUTED;
|
||||
}
|
||||
const v = Number(ttftSec);
|
||||
if (v >= 30) return SGR_FG_DANGER;
|
||||
if (v >= 18) return SGR_FG_WARN;
|
||||
return SGR_FG_NORMAL;
|
||||
}
|
||||
|
||||
function cliFormatCompactCost(costUsd) {
|
||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
||||
const val = Math.max(0, Number(costUsd));
|
||||
if (val === 0) return '$0.00';
|
||||
if (val < 0.001) return '<$0.001';
|
||||
if (val < 1) return `$${val.toFixed(3)}`;
|
||||
if (val < 100) return `$${val.toFixed(2)}`;
|
||||
return `$${Math.round(val)}`;
|
||||
}
|
||||
|
||||
function cliFormatCompactTtft(ttftSec) {
|
||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
|
||||
const val = Number(ttftSec);
|
||||
if (val < 1) return `${val.toFixed(2)}s`;
|
||||
if (val < 100) return `${val.toFixed(1)}s`;
|
||||
return `${Math.round(val)}s`;
|
||||
}
|
||||
|
||||
function cliFormatTokens(num) {
|
||||
const n = Number(num || 0);
|
||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
||||
return String(Math.round(n));
|
||||
}
|
||||
|
||||
function cliResolveQuotaPct(quotas, slotKey) {
|
||||
if (!quotas || typeof quotas !== 'object') return null;
|
||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
||||
const activePool = quotas.activePool || null;
|
||||
const weekly = quotas.weekly || null;
|
||||
|
||||
if (slotKey === 'quota_auto') {
|
||||
const candidates = [];
|
||||
if (activePool && Number.isFinite(Number(activePool.remainingPct))) {
|
||||
candidates.push(Number(activePool.remainingPct));
|
||||
}
|
||||
if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) {
|
||||
candidates.push(Number(activePool.weeklyRemainingPct));
|
||||
}
|
||||
if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) {
|
||||
candidates.push(Number(weekly.remainingPct));
|
||||
}
|
||||
if (!candidates.length && pools.length > 0) {
|
||||
for (const p of pools) {
|
||||
if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct));
|
||||
if (p && Number.isFinite(Number(p.weeklyRemainingPct))) {
|
||||
candidates.push(Number(p.weeklyRemainingPct));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!candidates.length) return null;
|
||||
return Math.max(0, Math.min(100, Math.round(Math.min(...candidates))));
|
||||
}
|
||||
|
||||
const isClaude = slotKey.startsWith('claude_');
|
||||
const isWeekly = slotKey.endsWith('_weekly');
|
||||
let rawPct = null;
|
||||
|
||||
if (isClaude) {
|
||||
const claudePool =
|
||||
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
|
||||
pools.find((p) =>
|
||||
CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || ''))
|
||||
);
|
||||
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
||||
if (cand != null && Number.isFinite(Number(cand))) {
|
||||
rawPct = Number(cand);
|
||||
} else if (
|
||||
activePool &&
|
||||
CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
||||
}
|
||||
} else {
|
||||
const stdGemini =
|
||||
pools.find((p) => p?.poolKey === 'Gemini') ||
|
||||
pools.find(
|
||||
(p) =>
|
||||
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
|
||||
!/carbon|argon/i.test(String(p?.poolKey || ''))
|
||||
);
|
||||
const geminiFamilyPools = pools.filter((p) =>
|
||||
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
|
||||
);
|
||||
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
|
||||
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
|
||||
rawPct = Number(primaryCand);
|
||||
} else {
|
||||
const familyVals = geminiFamilyPools
|
||||
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
|
||||
.filter((v) => v != null && Number.isFinite(Number(v)))
|
||||
.map(Number);
|
||||
if (familyVals.length > 0) {
|
||||
rawPct = Math.min(...familyVals);
|
||||
} else if (
|
||||
activePool &&
|
||||
!CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(
|
||||
String(activePool.family || activePool.poolLabel || '')
|
||||
)
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
||||
}
|
||||
if (
|
||||
rawPct == null &&
|
||||
isWeekly &&
|
||||
weekly &&
|
||||
!CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(weekly.poolFamily || '')) &&
|
||||
weekly.remainingPct != null &&
|
||||
Number.isFinite(Number(weekly.remainingPct))
|
||||
) {
|
||||
rawPct = Number(weekly.remainingPct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
||||
return Math.max(0, Math.min(100, Math.round(rawPct)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算终端可见列宽(剥离 CSI SGR 转义序列,CJK 全角字符按 2 列、`●`/`◎`/`·` 与 ASCII 按 1 列计算)。
|
||||
*
|
||||
* @param {string} rawStr
|
||||
* @returns {number}
|
||||
*/
|
||||
export function cliDisplayWidth(rawStr) {
|
||||
const plain = String(rawStr || '').replace(/\x1b\[[0-9;]*m/g, '');
|
||||
let cols = 0;
|
||||
for (const ch of plain) {
|
||||
const cp = ch.codePointAt(0) || 0;
|
||||
if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0) || (cp >= 0x0300 && cp <= 0x036f)) {
|
||||
continue;
|
||||
}
|
||||
const isWide =
|
||||
(cp >= 0x1100 && cp <= 0x115f) ||
|
||||
(cp >= 0x2e80 && cp <= 0x303e) ||
|
||||
(cp >= 0x3040 && cp <= 0x33bf) ||
|
||||
(cp >= 0x3400 && cp <= 0x4dbf) ||
|
||||
(cp >= 0x4e00 && cp <= 0xa4cf) ||
|
||||
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
||||
(cp >= 0xf900 && cp <= 0xfaff) ||
|
||||
(cp >= 0xfe10 && cp <= 0xfe6f) ||
|
||||
(cp >= 0xff01 && cp <= 0xff60) ||
|
||||
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
||||
(cp >= 0x1f000 && cp <= 0x1faff) ||
|
||||
(cp >= 0x20000 && cp <= 0x3fffd);
|
||||
cols += isWide ? 2 : 1;
|
||||
}
|
||||
return cols;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拆分 CLI 模型显示名与推理档位(例如将 `"Gemini 4 Hydrogen (Medium)"` 拆为 `"Gemini 4 Hydrogen"` + `"medium"`,
|
||||
* 与 `agy` 原生 `stripEffortSuffix` 显示效果一致)。
|
||||
*
|
||||
* @param {unknown} rawModelName
|
||||
* @param {unknown} [rawEffort]
|
||||
* @returns {{ modelName: string, effort: string }}
|
||||
*/
|
||||
export function parseCliModelAndEffort(rawModelName, rawEffort = '') {
|
||||
const cleanModel = String(rawModelName || '').trim();
|
||||
let modelName = cleanModel;
|
||||
let inferredEffort = '';
|
||||
const suffixMatch = cleanModel.match(/^(.*?)\s*\((minimal|low|medium|high|max|xhigh)\)\s*$/i);
|
||||
if (suffixMatch) {
|
||||
modelName = suffixMatch[1].trim();
|
||||
inferredEffort = suffixMatch[2].toLowerCase();
|
||||
}
|
||||
const explicitEffort = String(rawEffort || '')
|
||||
.trim()
|
||||
.replace(/^EFFORT_/i, '')
|
||||
.toLowerCase();
|
||||
return {
|
||||
modelName,
|
||||
effort: explicitEffort || inferredEffort,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCliCycleMode(rawMode) {
|
||||
const trimmed = String(rawMode || '')
|
||||
.trim()
|
||||
.replace(/^(?:AGENT_MODE_|PERMISSION_MODE_)/i, '')
|
||||
.toLowerCase();
|
||||
if (!trimmed || trimmed === 'none' || trimmed === 'default' || trimmed === 'unspecified') {
|
||||
return '';
|
||||
}
|
||||
return trimmed.replace(/_/g, '-');
|
||||
}
|
||||
|
||||
function cliModeSgr(normMode) {
|
||||
if (normMode === 'auto') return SGR_FG_MODE_AUTO;
|
||||
if (normMode === 'plan') return SGR_FG_ACCENT;
|
||||
if (normMode === 'accept-edits' || normMode === 'edit') return SGR_FG_GOOD;
|
||||
if (normMode === 'best-of-n' || normMode === 'battle') return SGR_FG_MODE_VIOLET;
|
||||
return SGR_FG_CHROME;
|
||||
}
|
||||
|
||||
function cliBuildLeftSegment({ vimMode = '', short = false, useColor = true } = {}) {
|
||||
const cleanVim = String(vimMode || '').trim().toUpperCase();
|
||||
const baseText = short
|
||||
? '?'
|
||||
: cleanVim
|
||||
? `${cleanVim} · ? for shortcuts`
|
||||
: '? for shortcuts';
|
||||
if (!useColor) return baseText;
|
||||
return `${SGR_FG_CHROME}${baseText}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
function cliBuildRightSegment({
|
||||
cycleMode = '',
|
||||
modelDisplayName = '',
|
||||
modelEffort = '',
|
||||
includeEffort = true,
|
||||
useColor = true,
|
||||
} = {}) {
|
||||
const normMode = normalizeCliCycleMode(cycleMode);
|
||||
const { modelName, effort } = parseCliModelAndEffort(modelDisplayName, modelEffort);
|
||||
const plainParts = [];
|
||||
const styledParts = [];
|
||||
|
||||
if (normMode) {
|
||||
plainParts.push(normMode);
|
||||
styledParts.push(useColor ? `${cliModeSgr(normMode)}${normMode}${SGR_RESET}` : normMode);
|
||||
}
|
||||
if (modelName) {
|
||||
plainParts.push(modelName);
|
||||
styledParts.push(useColor ? `${SGR_FG_CHROME}${modelName}${SGR_RESET}` : modelName);
|
||||
}
|
||||
if (includeEffort && effort) {
|
||||
plainParts.push(effort);
|
||||
styledParts.push(useColor ? `${SGR_FG_CHROME}${effort}${SGR_RESET}` : effort);
|
||||
}
|
||||
if (plainParts.length === 0) return '';
|
||||
if (!useColor) return plainParts.join(' · ');
|
||||
const dotSep = `${SGR_FG_CHROME} · ${SGR_RESET}`;
|
||||
return styledParts.join(dotSep);
|
||||
}
|
||||
|
||||
function cliComposeBalancedThreeColumn(leftStr, centerStr, rightStr, maxWidth) {
|
||||
const lw = cliDisplayWidth(leftStr);
|
||||
const cw = cliDisplayWidth(centerStr);
|
||||
const rw = cliDisplayWidth(rightStr);
|
||||
if (leftStr && rightStr) {
|
||||
const free = maxWidth - lw - cw - rw;
|
||||
if (free < 4) return '';
|
||||
const leftGap = Math.floor(free / 2);
|
||||
const rightGap = free - leftGap;
|
||||
return `${leftStr}${' '.repeat(leftGap)}${centerStr}${' '.repeat(rightGap)}${rightStr}`;
|
||||
}
|
||||
if (leftStr && !rightStr) {
|
||||
if (lw + cw + 2 > maxWidth) return '';
|
||||
const idealCenterStart = Math.max(lw + 2, Math.floor((maxWidth - cw) / 2));
|
||||
const leftGap = Math.min(maxWidth - lw - cw, idealCenterStart - lw);
|
||||
return `${leftStr}${' '.repeat(leftGap)}${centerStr}`;
|
||||
}
|
||||
if (!leftStr && rightStr) {
|
||||
const free = maxWidth - cw - rw;
|
||||
if (free < 2) return '';
|
||||
return `${centerStr}${' '.repeat(free)}${rightStr}`;
|
||||
}
|
||||
return cw <= maxWidth ? centerStr : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单槽位指标格式化为纯文本与无背景前景语义 SGR 片段。
|
||||
*/
|
||||
function cliRenderSingleSlot(metricKey, slotCtx, { isEn = false, useColor = true, slotSet } = {}) {
|
||||
const hasTelemetry = slotCtx.hasTelemetry !== false;
|
||||
|
||||
if (metricKey === 'context') {
|
||||
const valid = hasTelemetry && slotCtx.usedPct != null && Number.isFinite(Number(slotCtx.usedPct));
|
||||
const pctNum = valid ? Math.max(0, Math.min(100, Math.round(Number(slotCtx.usedPct)))) : null;
|
||||
const textVal = pctNum != null ? `${pctNum}%` : '--%';
|
||||
if (!useColor) {
|
||||
return `◎ ${textVal}`;
|
||||
}
|
||||
const isDanger = pctNum != null && pctNum >= 88;
|
||||
const isWarn = !isDanger && pctNum != null && pctNum >= 70;
|
||||
const ringColor = isDanger
|
||||
? SGR_FG_DANGER
|
||||
: isWarn
|
||||
? SGR_FG_WARN
|
||||
: pctNum != null
|
||||
? SGR_FG_ACCENT
|
||||
: SGR_FG_MUTED;
|
||||
const valColor = isDanger
|
||||
? `${SGR_BOLD}${SGR_FG_DANGER}`
|
||||
: isWarn
|
||||
? `${SGR_BOLD}${SGR_FG_WARN}`
|
||||
: pctNum != null
|
||||
? `${SGR_BOLD}${SGR_FG_BRIGHT}`
|
||||
: SGR_FG_MUTED;
|
||||
return `${ringColor}◎ ${valColor}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
if (metricKey === 'tps') {
|
||||
const valid = hasTelemetry && Number.isFinite(Number(slotCtx.tps)) && Number(slotCtx.tps) > 0;
|
||||
const numVal = valid ? Number(slotCtx.tps) : 0;
|
||||
const textVal = valid
|
||||
? `${numVal >= 100 ? Math.round(numVal) : numVal.toFixed(1)} t/s`
|
||||
: slotCtx.isRunning
|
||||
? isEn
|
||||
? 'Gen...'
|
||||
: '生成中...'
|
||||
: isEn
|
||||
? 'Idle'
|
||||
: '空闲';
|
||||
if (!useColor) return textVal;
|
||||
const color = valid
|
||||
? `${SGR_BOLD}${cliStatusSpeedSgr(numVal)}`
|
||||
: slotCtx.isRunning
|
||||
? SGR_FG_INFO
|
||||
: SGR_FG_MUTED;
|
||||
return `${color}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
if (metricKey === 'avg_tps') {
|
||||
const valid =
|
||||
hasTelemetry && Number.isFinite(Number(slotCtx.avgTps)) && Number(slotCtx.avgTps) > 0;
|
||||
const numVal = valid ? Number(slotCtx.avgTps) : 0;
|
||||
const needPrefix = slotSet?.has('tps');
|
||||
const prefix = needPrefix ? (isEn ? 'avg ' : '均 ') : '';
|
||||
const textVal = valid
|
||||
? `${prefix}${numVal >= 100 ? Math.round(numVal) : numVal.toFixed(1)} t/s`
|
||||
: `${prefix}-- t/s`;
|
||||
if (!useColor) return textVal;
|
||||
const color = valid ? cliStatusSpeedSgr(numVal) : SGR_FG_MUTED;
|
||||
return `${color}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
if (metricKey === 'ttft') {
|
||||
const valid =
|
||||
hasTelemetry && slotCtx.ttft != null && Number.isFinite(Number(slotCtx.ttft)) && Number(slotCtx.ttft) >= 0;
|
||||
const textVal = valid ? cliFormatCompactTtft(Number(slotCtx.ttft)) : '--s';
|
||||
if (!useColor) return textVal;
|
||||
const color = valid ? cliStatusTtftSgr(Number(slotCtx.ttft)) : SGR_FG_MUTED;
|
||||
return `${color}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
if (metricKey === 'cost' || metricKey === 'session_cost') {
|
||||
const rawVal = !hasTelemetry
|
||||
? null
|
||||
: metricKey === 'session_cost'
|
||||
? slotCtx.sessionCost
|
||||
: slotCtx.stepCost;
|
||||
const needPrefix =
|
||||
metricKey === 'session_cost' && slotSet?.has('cost') ? (isEn ? 'sum ' : '总 ') : '';
|
||||
const textVal = `${needPrefix}${hasTelemetry ? cliFormatCompactCost(rawVal) : '--'}`;
|
||||
if (!useColor) return textVal;
|
||||
const color =
|
||||
metricKey === 'cost' && hasTelemetry && rawVal != null
|
||||
? cliStatusCostSgr(rawVal)
|
||||
: rawVal != null
|
||||
? SGR_FG_NORMAL
|
||||
: SGR_FG_MUTED;
|
||||
return `${color}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
if (metricKey === 'cache_hit') {
|
||||
const valid =
|
||||
hasTelemetry && slotCtx.cacheHitPct != null && Number.isFinite(Number(slotCtx.cacheHitPct));
|
||||
const numVal = valid ? Math.max(0, Math.min(100, Math.round(Number(slotCtx.cacheHitPct)))) : 0;
|
||||
const prefix = isEn ? 'cache ' : '缓 ';
|
||||
const textVal = valid ? `${prefix}${numVal}%` : `${prefix}--%`;
|
||||
if (!useColor) return textVal;
|
||||
const color = valid
|
||||
? cliStatusCacheSgr(Number(slotCtx.cacheHitPct), slotCtx.latestPromptTokens)
|
||||
: SGR_FG_MUTED;
|
||||
return `${color}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
if (metricKey === 'session_tokens') {
|
||||
const valid =
|
||||
hasTelemetry &&
|
||||
slotCtx.sessionTokens != null &&
|
||||
Number.isFinite(Number(slotCtx.sessionTokens)) &&
|
||||
Number(slotCtx.sessionTokens) >= 0;
|
||||
const textVal = valid ? `${cliFormatTokens(Number(slotCtx.sessionTokens))} tok` : '-- tok';
|
||||
if (!useColor) return textVal;
|
||||
return `${valid ? SGR_FG_NORMAL : SGR_FG_MUTED}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
const quotaPct = hasTelemetry ? cliResolveQuotaPct(slotCtx.quotas, metricKey) : null;
|
||||
const textVal =
|
||||
quotaPct != null
|
||||
? isEn
|
||||
? `${quotaPct}% left`
|
||||
: `余 ${quotaPct}%`
|
||||
: isEn
|
||||
? 'Quota --'
|
||||
: '余 --%';
|
||||
if (!useColor) return textVal;
|
||||
const isDanger = quotaPct != null && quotaPct <= 15;
|
||||
const isWarn = !isDanger && quotaPct != null && quotaPct <= 30;
|
||||
const color = isDanger
|
||||
? `${SGR_BOLD}${SGR_FG_DANGER}`
|
||||
: isWarn
|
||||
? `${SGR_BOLD}${SGR_FG_WARN}`
|
||||
: SGR_FG_MUTED;
|
||||
return `${color}${textVal}${SGR_RESET}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染单行无背景 CLI 底部状态条(传入 `terminalWidth > 0` 时自动合成「左快捷键提示 + 居中指标 + 右模式与模型」三栏单行布局)。
|
||||
*
|
||||
* @param {{
|
||||
* hasTelemetry?: boolean,
|
||||
* usedPct?: number|null,
|
||||
* isRunning?: boolean,
|
||||
* hasWaiting?: boolean,
|
||||
* runningCount?: number,
|
||||
* runningSubCount?: number,
|
||||
* tps?: number|null,
|
||||
* avgTps?: number|null,
|
||||
* ttft?: number|null,
|
||||
* stepCost?: number|null,
|
||||
* sessionCost?: number|null,
|
||||
* cacheHitPct?: number|null,
|
||||
* latestPromptTokens?: number|null,
|
||||
* sessionTokens?: number|null,
|
||||
* quotas?: object|null,
|
||||
* }} slotCtx
|
||||
* @param {{
|
||||
* slots?: string[],
|
||||
* showMultiSession?: boolean,
|
||||
* language?: string,
|
||||
* color?: boolean,
|
||||
* terminalWidth?: number,
|
||||
* cycleMode?: string,
|
||||
* modelDisplayName?: string,
|
||||
* modelEffort?: string,
|
||||
* vimMode?: string,
|
||||
* }} [options]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) {
|
||||
const slots = normalizeTopbarCapsuleSlots(options.slots);
|
||||
const showMulti = options.showMultiSession !== false;
|
||||
const normLang = normalizeLanguageSetting(options.language);
|
||||
const isEn = normLang === 'en-US';
|
||||
const useColor = options.color !== false;
|
||||
const slotSet = new Set(slots);
|
||||
|
||||
const runningCount = Math.max(0, Math.floor(Number(slotCtx.runningCount) || 0));
|
||||
const runningSubCount = Math.max(0, Math.floor(Number(slotCtx.runningSubCount) || 0));
|
||||
const hasWaiting = Boolean(slotCtx.hasWaiting);
|
||||
|
||||
let multiCore = '';
|
||||
if (showMulti) {
|
||||
const labelText =
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? isEn
|
||||
? `${runningCount} active · ${runningSubCount} sub`
|
||||
: `${runningCount} 运行中 · ${runningSubCount} 子`
|
||||
: isEn
|
||||
? `${runningCount} active`
|
||||
: `${runningCount} 运行中`
|
||||
: isEn
|
||||
? '0 active'
|
||||
: '0 运行中';
|
||||
if (!useColor) {
|
||||
multiCore = `● ${labelText}`;
|
||||
} else {
|
||||
const dotSgr =
|
||||
runningCount > 0
|
||||
? hasWaiting
|
||||
? SGR_FG_WARN
|
||||
: SGR_FG_GOOD
|
||||
: SGR_FG_DOT_IDLE;
|
||||
const textSgr = runningCount > 0 ? SGR_FG_NORMAL : SGR_FG_DIM;
|
||||
multiCore = `${dotSgr}● ${textSgr}${labelText}${SGR_RESET}`;
|
||||
}
|
||||
}
|
||||
|
||||
const renderedSlots = slots.map((key) =>
|
||||
cliRenderSingleSlot(key, slotCtx, { isEn, useColor, slotSet })
|
||||
);
|
||||
const sep = useColor ? `${SGR_FG_SEP} | ${SGR_RESET}` : ' | ';
|
||||
const slotsBody = renderedSlots.join(sep);
|
||||
const fullCapsule = multiCore ? `${multiCore} ${slotsBody}` : slotsBody;
|
||||
|
||||
const rawWidth = Number(options.terminalWidth);
|
||||
if (!Number.isFinite(rawWidth) || rawWidth <= 0) {
|
||||
return fullCapsule;
|
||||
}
|
||||
|
||||
// 预留右侧 1 列安全边距,与 `agy` 原生底栏右边缘对齐并避免 Windows `conhost`/`cmd.exe` 末列自动折行
|
||||
const maxWidth = Math.max(1, Math.floor(rawWidth) - 1);
|
||||
const compactCapsule = multiCore ? `${multiCore} ${slotsBody}` : slotsBody;
|
||||
const fullLeft = cliBuildLeftSegment({ vimMode: options.vimMode, short: false, useColor });
|
||||
const shortLeft = cliBuildLeftSegment({ vimMode: '', short: true, useColor });
|
||||
const fullRight = cliBuildRightSegment({
|
||||
cycleMode: options.cycleMode,
|
||||
modelDisplayName: options.modelDisplayName,
|
||||
modelEffort: options.modelEffort,
|
||||
includeEffort: true,
|
||||
useColor,
|
||||
});
|
||||
const compactRight = cliBuildRightSegment({
|
||||
cycleMode: options.cycleMode,
|
||||
modelDisplayName: options.modelDisplayName,
|
||||
modelEffort: options.modelEffort,
|
||||
includeEffort: false,
|
||||
useColor,
|
||||
});
|
||||
|
||||
const tier1 = cliComposeBalancedThreeColumn(fullLeft, fullCapsule, fullRight, maxWidth);
|
||||
if (tier1) return tier1;
|
||||
|
||||
const tier2 = cliComposeBalancedThreeColumn(shortLeft, fullCapsule, fullRight, maxWidth);
|
||||
if (tier2) return tier2;
|
||||
|
||||
const tier3 = cliComposeBalancedThreeColumn(shortLeft, compactCapsule, compactRight, maxWidth);
|
||||
if (tier3) return tier3;
|
||||
|
||||
const tier4 = cliComposeBalancedThreeColumn('', compactCapsule, compactRight, maxWidth);
|
||||
if (tier4) return tier4;
|
||||
|
||||
if (cliDisplayWidth(fullCapsule) <= maxWidth) {
|
||||
return fullCapsule;
|
||||
}
|
||||
return slotsBody;
|
||||
}
|
||||
+255
-144
@@ -13,6 +13,100 @@ import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
|
||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||
import {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_POPOVER_WIDTH,
|
||||
DEFAULT_SETTINGS_SCHEMA,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_POPOVER_WIDTH,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_POPOVER_WIDTH,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
MODEL_DISPLAY_MODES,
|
||||
ORCHESTRATOR_ID_MODES,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
PLUGIN_UPDATE_MODES,
|
||||
POPOVER_WIDTH_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
WINDOW_MOUNT_MODES,
|
||||
createDefaultSettingsObject,
|
||||
normalizeFontScale,
|
||||
normalizeFullSettings,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizePopoverWidth,
|
||||
normalizePopoverWidthMode,
|
||||
normalizeStandalonePort,
|
||||
normalizeStepTableColumns,
|
||||
normalizeStepTokenComboFormat,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
parseStepTokenComboSegments,
|
||||
} from './settings-schema.mjs';
|
||||
|
||||
export {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_POPOVER_WIDTH,
|
||||
DEFAULT_SETTINGS_SCHEMA,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_POPOVER_WIDTH,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_POPOVER_WIDTH,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
MODEL_DISPLAY_MODES,
|
||||
ORCHESTRATOR_ID_MODES,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
PLUGIN_UPDATE_MODES,
|
||||
POPOVER_WIDTH_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
WINDOW_MOUNT_MODES,
|
||||
createDefaultSettingsObject,
|
||||
normalizeFontScale,
|
||||
normalizeFullSettings,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizePopoverWidth,
|
||||
normalizePopoverWidthMode,
|
||||
normalizeStandalonePort,
|
||||
normalizeStepTableColumns,
|
||||
normalizeStepTokenComboFormat,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
parseStepTokenComboSegments,
|
||||
} from './settings-schema.mjs';
|
||||
|
||||
/**
|
||||
* 自适应解析 `sidecars/panel` 目录路径:
|
||||
@@ -25,34 +119,141 @@ export const PLUGIN_ROOT = dirname(dirname(HERE));
|
||||
export const PLUGIN_MANIFEST_FILE = join(PLUGIN_ROOT, 'plugin.json');
|
||||
export const LOCAL_CATALOG_FILE = join(PLUGIN_ROOT, 'pricing-catalog.json');
|
||||
|
||||
function resolveGeminiBaseDir() {
|
||||
const envGemini = String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim();
|
||||
return envGemini || join(homedir(), '.gemini');
|
||||
}
|
||||
|
||||
function dedupeDirCandidates(list) {
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of list) {
|
||||
const clean = String(item || '').trim();
|
||||
if (!clean) continue;
|
||||
const key = process.platform === 'win32' ? clean.toLowerCase() : clean;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(clean);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function resolveProductDataRoots() {
|
||||
const geminiBase = resolveGeminiBaseDir();
|
||||
const explicitAppDir = String(
|
||||
process.env.USAGE_MONITOR_APP_DATA_DIR || process.env.ANTIGRAVITY_APP_DATA_DIR || ''
|
||||
).trim();
|
||||
const customRoot = explicitAppDir
|
||||
? /[\\/]|^[a-zA-Z]:/.test(explicitAppDir)
|
||||
? explicitAppDir
|
||||
: join(geminiBase, explicitAppDir)
|
||||
: '';
|
||||
return dedupeDirCandidates([
|
||||
customRoot,
|
||||
join(geminiBase, 'antigravity'),
|
||||
join(geminiBase, 'antigravity-cli'),
|
||||
join(geminiBase, 'antigravity-ide'),
|
||||
join(geminiBase, 'antigravity-idea'),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor`)。
|
||||
* 存放用户偏好设置、历史轨迹缓存及云端价格表缓存,插件升级不会清除此目录。
|
||||
* 插件持久化数据目录(默认由 Antigravity 宿主注入 `~/.gemini/antigravity/sidecar_data/usage-monitor/panel/data`)。
|
||||
* 兼容桌面端、Antigravity IDE 与无头 `agy` CLI(`~/.gemini/antigravity-cli`):
|
||||
* 优先使用已存在的持久化目录,纯 CLI 服务器自动落入 `~/.gemini/antigravity-cli/sidecar_data/usage-monitor/panel/data`,
|
||||
* 避免落入插件源码目录而在自更新时丢失缓存与设置。
|
||||
*/
|
||||
export const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data');
|
||||
function resolveDefaultDataDir() {
|
||||
const explicitDataDir = String(process.env.USAGE_MONITOR_DATA_DIR || '').trim();
|
||||
if (explicitDataDir) {
|
||||
return explicitDataDir;
|
||||
}
|
||||
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 geminiBase = resolveGeminiBaseDir();
|
||||
const antigravityRoot = join(geminiBase, 'antigravity');
|
||||
const cliRoot = join(geminiBase, 'antigravity-cli');
|
||||
const panelDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'panel', 'data');
|
||||
const legacyDataDir = join(antigravityRoot, 'sidecar_data', 'usage-monitor', 'data');
|
||||
const cliPanelDataDir = join(cliRoot, 'sidecar_data', 'usage-monitor', 'panel', 'data');
|
||||
if (existsSync(panelDataDir)) return panelDataDir;
|
||||
if (existsSync(legacyDataDir)) return legacyDataDir;
|
||||
if (existsSync(cliPanelDataDir)) return cliPanelDataDir;
|
||||
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;
|
||||
}
|
||||
if (existsSync(cliRoot)) return cliPanelDataDir;
|
||||
return join(HERE, '.data');
|
||||
}
|
||||
|
||||
export const DATA_DIR = resolveDefaultDataDir();
|
||||
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
|
||||
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
|
||||
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
|
||||
export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json');
|
||||
|
||||
/**
|
||||
* 本地对话记录目录与跨端深层统计缓存路径候选列表。
|
||||
* 本地对话记录目录、脑图日志目录、守护发现目录与跨端深层统计缓存路径候选列表(联合覆盖 Desktop / CLI / IDE)。
|
||||
*/
|
||||
export const CONVERSATIONS_DIR = join(homedir(), '.gemini', 'antigravity', 'conversations');
|
||||
export const BRAIN_DIR = join(homedir(), '.gemini', 'antigravity', 'brain');
|
||||
export const DEEP_STATS_CACHE_CANDIDATES = [
|
||||
join(homedir(), '.gemini', 'antigravity-ide', 'brain', '.deep_stats_cache.json'),
|
||||
join(homedir(), '.gemini', 'antigravity', 'brain', '.deep_stats_cache.json'),
|
||||
join(homedir(), '.gemini', 'antigravity-idea', 'brain', '.deep_stats_cache.json'),
|
||||
];
|
||||
export const PRODUCT_DATA_ROOTS = resolveProductDataRoots();
|
||||
export const CONVERSATION_DIRS = PRODUCT_DATA_ROOTS.map((root) => join(root, 'conversations'));
|
||||
export const BRAIN_DIRS = PRODUCT_DATA_ROOTS.map((root) => join(root, 'brain'));
|
||||
export const ANNOTATION_DIRS = PRODUCT_DATA_ROOTS.map((root) => join(root, 'annotations'));
|
||||
export const DAEMON_DIRS = dedupeDirCandidates([
|
||||
join(resolveGeminiBaseDir(), 'antigravity-cli', 'daemon'),
|
||||
...PRODUCT_DATA_ROOTS.map((root) => join(root, 'daemon')),
|
||||
]);
|
||||
export const CONVERSATIONS_DIR = CONVERSATION_DIRS[0];
|
||||
export const BRAIN_DIR = BRAIN_DIRS[0];
|
||||
export const DEEP_STATS_CACHE_CANDIDATES = dedupeDirCandidates([
|
||||
join(resolveGeminiBaseDir(), 'antigravity-ide', 'brain', '.deep_stats_cache.json'),
|
||||
join(resolveGeminiBaseDir(), 'antigravity-cli', 'brain', '.deep_stats_cache.json'),
|
||||
join(resolveGeminiBaseDir(), 'antigravity', 'brain', '.deep_stats_cache.json'),
|
||||
join(resolveGeminiBaseDir(), 'antigravity-idea', 'brain', '.deep_stats_cache.json'),
|
||||
...BRAIN_DIRS.map((dir) => join(dir, '.deep_stats_cache.json')),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(自动剥离重复协议前缀与尾部斜杠)。
|
||||
* Antigravity 本地 Language Server Connect RPC 端点与鉴权 Token(支持环境变量静态注入与进程/守护文件动态发现)。
|
||||
*/
|
||||
const rawLsAddr = String(process.env.ANTIGRAVITY_LS_ADDRESS || '').trim();
|
||||
const LS_PROTOCOL = /^https:\/\//i.test(rawLsAddr) ? 'https' : 'http';
|
||||
export const LS_ADDR = rawLsAddr.replace(/^https?:\/\//i, '').replace(/\/+$/, '');
|
||||
export const LS_BASE_URL = LS_ADDR ? `${LS_PROTOCOL}://${LS_ADDR}` : '';
|
||||
export const CSRF_TOKEN = process.env.ANTIGRAVITY_CSRF_TOKEN;
|
||||
export const CSRF_TOKEN =
|
||||
process.env.ANTIGRAVITY_CSRF_TOKEN || process.env.ANTIGRAVITY_SERVER_CSRF_TOKEN;
|
||||
|
||||
export const lsRuntimeEndpoint = {
|
||||
addr: LS_ADDR,
|
||||
baseUrl: LS_BASE_URL,
|
||||
csrfToken: CSRF_TOKEN || '',
|
||||
isDynamic: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* 动态更新运行时 Language Server / Hub RPC 连接端点与 CSRF 令牌。
|
||||
*
|
||||
* @param {string} nextAddr
|
||||
* @param {string} nextCsrfToken
|
||||
* @param {{ isDynamic?: boolean }} [opts]
|
||||
*/
|
||||
export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken, { isDynamic = true } = {}) {
|
||||
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();
|
||||
lsRuntimeEndpoint.isDynamic = Boolean(cleanAddr && isDynamic);
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub 官方云端价格目录与插件发布包地址配置。
|
||||
@@ -75,87 +276,6 @@ export const DEFAULT_ARCHIVE_FALLBACK_URL =
|
||||
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
||||
export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 顶栏右侧精简胶囊三槽位允许配置的指标枚举与默认顺序。
|
||||
*/
|
||||
export const TOPBAR_SLOT_KEYS = Object.freeze([
|
||||
'context',
|
||||
'tps',
|
||||
'ttft',
|
||||
'cost',
|
||||
'quota_auto',
|
||||
'gemini_5h',
|
||||
'gemini_weekly',
|
||||
'claude_5h',
|
||||
'claude_weekly',
|
||||
'none',
|
||||
]);
|
||||
|
||||
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||
|
||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
||||
|
||||
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
||||
|
||||
/**
|
||||
* 归一化 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'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyAutoUpdate]
|
||||
* @returns {'off'|'manual'|'auto'}
|
||||
*/
|
||||
export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
||||
if (legacyAutoUpdate === true) return 'auto';
|
||||
return 'manual';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化顶栏三槽位配置数组,兜底非法枚举值并保证至少保留一个可见槽位。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {[string, string, string]}
|
||||
*/
|
||||
export function normalizeTopbarCapsuleSlots(raw) {
|
||||
const arr = Array.isArray(raw) ? raw : [];
|
||||
const slots = [0, 1, 2].map((idx) => {
|
||||
const val = String(arr[idx] ?? '').trim();
|
||||
return TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_TOPBAR_SLOTS[idx];
|
||||
});
|
||||
if (slots.every((s) => s === 'none')) {
|
||||
slots[0] = 'context';
|
||||
}
|
||||
return /** @type {[string, string, string]} */ (slots);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户可配置项的默认值。
|
||||
*/
|
||||
const DEFAULT_SETTINGS = {
|
||||
weeklyTokenBudget: 150000000, // 自定义每周 Token 预算默认值 (150M,保留底层兼容)
|
||||
weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100,保留底层兼容)
|
||||
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
||||
showUpstreamModel: false, // 是否显示上游真实 responseModel 名称
|
||||
orchestratorIdMode: 'compact', // 'compact' | 'full'(Orchestrator 系列显示精简 ID 或完整 ID)
|
||||
pluginUpdateMode: 'manual', // 'off' | 'manual' | 'auto'(默认仅提示新版本,手动更新)
|
||||
autoUpdatePlugin: false, // 派生自 pluginUpdateMode === 'auto',保留底层兼容
|
||||
enableWindowOverlay: true, // 是否启用双栖模式(自动通过 CDP 在主窗口顶栏挂载胶囊与悬浮面板)
|
||||
showTopbarMultiSession: true, // 是否在顶栏左侧显示实时运行会话入口
|
||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], // 顶栏右侧胶囊三槽位指标与顺序
|
||||
};
|
||||
|
||||
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
||||
export const CACHE_SCHEMA_VERSION = 'v10-model-identity';
|
||||
|
||||
@@ -194,10 +314,12 @@ export function loadJson(filePath, fallback) {
|
||||
*/
|
||||
export function saveJson(filePath, data) {
|
||||
try {
|
||||
mkdirSync(DATA_DIR, { recursive: true });
|
||||
const serialized =
|
||||
filePath === CACHE_FILE ? JSON.stringify(data) : JSON.stringify(data, null, 2);
|
||||
writeFileSync(filePath, serialized, 'utf8');
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
if (filePath === CACHE_FILE) {
|
||||
writeTrajectoryCacheFile(filePath, data);
|
||||
} else {
|
||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed writing ${filePath}: ${err.message}`);
|
||||
@@ -206,54 +328,10 @@ export function saveJson(filePath, data) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'official'|'custom_tokens'|'custom_cost'}
|
||||
*/
|
||||
export function normalizeWeeklyLimitMode(mode) {
|
||||
const m = String(mode || '').trim().toLowerCase();
|
||||
if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens';
|
||||
if (m === 'custom_cost' || m === 'cost') return 'custom_cost';
|
||||
return 'official';
|
||||
}
|
||||
|
||||
function sanitizeSettingNumber(val, fallback) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段并兜底非法数值。
|
||||
*
|
||||
* @returns {typeof DEFAULT_SETTINGS}
|
||||
* 读取用户设置并通过统一 Schema 归一化合并默认值,自动迁移旧版字段。
|
||||
*/
|
||||
export function loadSettings() {
|
||||
const raw = loadJson(SETTINGS_FILE, {});
|
||||
const safeRaw = isPlainObject(raw) ? raw : {};
|
||||
const merged = { ...DEFAULT_SETTINGS, ...safeRaw };
|
||||
const pluginUpdateMode = normalizePluginUpdateMode(
|
||||
safeRaw.pluginUpdateMode,
|
||||
safeRaw.autoUpdatePlugin
|
||||
);
|
||||
return {
|
||||
weeklyTokenBudget: sanitizeSettingNumber(
|
||||
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit ?? merged.weeklyTokenBudget,
|
||||
DEFAULT_SETTINGS.weeklyTokenBudget
|
||||
),
|
||||
weeklyCostBudget: sanitizeSettingNumber(
|
||||
merged.weeklyCostBudget,
|
||||
DEFAULT_SETTINGS.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(merged.weeklyLimitMode),
|
||||
showUpstreamModel: merged.showUpstreamModel === true,
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(merged.orchestratorIdMode),
|
||||
pluginUpdateMode,
|
||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||
enableWindowOverlay: merged.enableWindowOverlay !== false,
|
||||
showTopbarMultiSession: merged.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
||||
};
|
||||
return normalizeFullSettings(loadJson(SETTINGS_FILE, {}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -277,6 +355,10 @@ export function computeRuntimeCodeVersion() {
|
||||
join(HERE, 'app.js'),
|
||||
join(HERE, 'styles.css'),
|
||||
join(HERE, 'main.mjs'),
|
||||
join(HERE, 'standalone.mjs'),
|
||||
join(HERE, 'bridge-daemon.mjs'),
|
||||
join(HERE, 'mcp-entry.mjs'),
|
||||
join(HERE, 'cli-statusline.mjs'),
|
||||
join(HERE, 'speed-metrics.mjs'),
|
||||
LOCAL_CATALOG_FILE,
|
||||
];
|
||||
@@ -369,6 +451,11 @@ export const externalDeepStatsMemo = {
|
||||
convos: new Map(),
|
||||
};
|
||||
|
||||
export const localSummaryMemo = {
|
||||
sig: '',
|
||||
byId: new Map(),
|
||||
};
|
||||
|
||||
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
||||
export const inFlightRequests = new Map();
|
||||
|
||||
@@ -377,6 +464,7 @@ export const quotaSummaryCache = {
|
||||
ts: 0,
|
||||
lastAttemptTs: 0,
|
||||
accountName: '',
|
||||
accountGeneration: 0,
|
||||
data: null,
|
||||
error: null,
|
||||
};
|
||||
@@ -407,3 +495,26 @@ export const pluginUpdateState = {
|
||||
lastError: null,
|
||||
inFlight: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空内存态轨迹缓存、外部深层统计 Memo 与配额摘要短期缓存,并将磁盘缓存重置为空对象。
|
||||
*
|
||||
* @returns {boolean} 是否成功写回空白缓存文件
|
||||
*/
|
||||
export function clearRuntimeCaches() {
|
||||
for (const key of Object.keys(trajectoryCache)) {
|
||||
delete trajectoryCache[key];
|
||||
}
|
||||
cacheState.needsSave = false;
|
||||
externalDeepStatsMemo.sig = '';
|
||||
externalDeepStatsMemo.convos.clear();
|
||||
localSummaryMemo.sig = '';
|
||||
localSummaryMemo.byId.clear();
|
||||
quotaSummaryCache.ts = 0;
|
||||
quotaSummaryCache.lastAttemptTs = 0;
|
||||
quotaSummaryCache.accountName = '';
|
||||
quotaSummaryCache.accountGeneration += 1;
|
||||
quotaSummaryCache.data = null;
|
||||
quotaSummaryCache.error = null;
|
||||
return saveJson(CACHE_FILE, {});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
/** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */
|
||||
|
||||
export function isContextWindowModelId(value) {
|
||||
return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) &&
|
||||
value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN';
|
||||
}
|
||||
|
||||
export function isContextWindowSettingId(value) {
|
||||
return isContextWindowModelId(value) || (typeof value === 'string' && /^model:[a-z0-9][a-z0-9._-]{0,119}$/.test(value));
|
||||
}
|
||||
|
||||
export function isContextWindowOption(value) {
|
||||
return typeof value === 'string' && value.length > 0 && value.length <= 80 &&
|
||||
value.trim() === value && value.toLowerCase() !== 'default' && !/[\x00-\x1f\x7f]/.test(value);
|
||||
}
|
||||
|
||||
export function getContextWindowModels(clientConfigs, catalog) {
|
||||
const capacities = new Map();
|
||||
const upstreamIds = new Map();
|
||||
const thinkingLevels = new Set();
|
||||
for (const [key, info] of Object.entries(catalog || {})) {
|
||||
const { model, maxTokens, maxOutputTokens } = info || {};
|
||||
if (isContextWindowModelId(model)) upstreamIds.set(model, upstreamIds.has(model) ? '' : key);
|
||||
if (Number.isInteger(info?.thinkingLevel) && info.thinkingLevel > 0) thinkingLevels.add(model);
|
||||
if (!Number.isSafeInteger(maxTokens) || !Number.isSafeInteger(maxOutputTokens) ||
|
||||
maxOutputTokens <= 0 || maxTokens <= maxOutputTokens) continue;
|
||||
// 宿主校验压缩阈值时会从模型总窗口中扣除输出预算。
|
||||
const capacity = maxTokens - maxOutputTokens;
|
||||
capacities.set(model, Math.min(capacity, capacities.get(model) ?? capacity));
|
||||
}
|
||||
const models = new Map();
|
||||
for (const config of Array.isArray(clientConfigs) ? clientConfigs : []) {
|
||||
const id = config?.modelOrAlias?.model;
|
||||
if (!isContextWindowModelId(id) || config.disabled || models.has(id)) continue;
|
||||
const options = Array.isArray(config.contextWindowOptions) ? config.contextWindowOptions : [];
|
||||
const byName = new Map();
|
||||
for (const option of options) {
|
||||
if (!isContextWindowOption(option?.name) || byName.has(option.name)) continue;
|
||||
byName.set(option.name, {
|
||||
name: option.name,
|
||||
expensive: option.expensive === true,
|
||||
});
|
||||
}
|
||||
const reportedId = typeof config.modelId === 'string' ? config.modelId.trim() : '';
|
||||
const upstreamId = (reportedId && reportedId !== id ? reportedId : upstreamIds.get(id) || '').toLowerCase();
|
||||
const label = config.label || id;
|
||||
const effort = upstreamId.match(/-(low|medium|high|xhigh|extra-high|extra|max)$/);
|
||||
const labelEffort = typeof label === 'string' && label.match(/\s+\((low|medium|high|xhigh|extra[ -]high|extra|max)\)$/i);
|
||||
const isEffortVariant = effort && (thinkingLevels.has(id) ||
|
||||
labelEffort && effort[1].replace('-', '') === labelEffort[1].toLowerCase().replace(/[ -]/g, ''));
|
||||
const baseId = isEffortVariant ? upstreamId.slice(0, effort.index) : upstreamId;
|
||||
const groupId = `model:${baseId}`;
|
||||
models.set(id, {
|
||||
id,
|
||||
groupId: isContextWindowSettingId(groupId) ? groupId : id,
|
||||
label: isEffortVariant ? (labelEffort ? label.slice(0, labelEffort.index) : baseId) : label,
|
||||
capacity: capacities.get(id) || 0,
|
||||
options: [...byName.values()],
|
||||
});
|
||||
}
|
||||
return [...models.values()];
|
||||
}
|
||||
|
||||
export function getContextWindowGroups(models) {
|
||||
const byId = new Map();
|
||||
for (const model of models) {
|
||||
const group = byId.get(model.groupId);
|
||||
if (group) group.members.push(model);
|
||||
else byId.set(model.groupId, { id: model.groupId, label: model.label, members: [model] });
|
||||
}
|
||||
return [...byId.values()].map(({ id, label, members }) => {
|
||||
const options = members[0].options.filter(({ name }) =>
|
||||
members.every((member) => member.options.some((option) => option.name === name))
|
||||
).map(({ name }) => ({
|
||||
name,
|
||||
expensive: members.some(({ options }) => options.some((option) => option.name === name && option.expensive)),
|
||||
}));
|
||||
const capacity = Math.min(...members.map((member) => member.capacity));
|
||||
if (!options.length && capacity) {
|
||||
for (const tokens of new Set([128000, 256000, 512000, 768000, 900000, capacity])) {
|
||||
if (tokens <= capacity && !options.some(({ name }) => name === String(tokens))) {
|
||||
options.push({ name: String(tokens), tokens });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { id, label, members: members.map((member) => member.id), capacity, options };
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveContextWindowOption(model, value) {
|
||||
if (!value) return null;
|
||||
if (model.options.some(({ name, tokens }) => name === value && !tokens)) return value;
|
||||
const tokens = Number(value);
|
||||
return Number.isSafeInteger(tokens) && String(tokens) === value && tokens > 0 && tokens <= model.capacity ? tokens : null;
|
||||
}
|
||||
|
||||
export function resolveContextWindowRules(models, preferences) {
|
||||
const byId = new Map(models.map((model) => [model.id, model]));
|
||||
const rules = {};
|
||||
for (const group of getContextWindowGroups(models)) {
|
||||
const saved = preferences[group.id];
|
||||
// 不同推理档的旧设置有冲突时,保留各自的值,直到用户选定统一上限。
|
||||
const previous = new Set(group.members.map((id) => preferences[id]).filter(Boolean));
|
||||
const shared = saved || (previous.size === 1 ? previous.values().next().value : null);
|
||||
if (resolveContextWindowOption(group, shared) !== null) {
|
||||
for (const id of group.members) rules[id] = resolveContextWindowOption(byId.get(id), shared);
|
||||
} else if (!saved) {
|
||||
for (const id of group.members) {
|
||||
const option = resolveContextWindowOption(byId.get(id), preferences[id]);
|
||||
if (option !== null) rules[id] = option;
|
||||
}
|
||||
}
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
// 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。
|
||||
export async function syncHostContextWindows(rules, bootId) {
|
||||
const key = '__AGUsageMonitorContextWindows';
|
||||
let state = window[key];
|
||||
const appConfig = window.__APP_CONFIG__;
|
||||
const csrfToken = appConfig?.csrfToken;
|
||||
if (!Object.keys(rules).length || !csrfToken || appConfig.isRemoteControl) {
|
||||
state?.dispose();
|
||||
return;
|
||||
}
|
||||
if (state && (state.bootId !== bootId || !state.isAttached?.())) {
|
||||
state.dispose();
|
||||
state = null;
|
||||
}
|
||||
if (!state) {
|
||||
const servicePath = '/exa.language_server_pb.LanguageServerService/';
|
||||
const sendPath = servicePath + 'SendUserCascadeMessage';
|
||||
const nativeFetch = window.fetch;
|
||||
const wsProto = window.WebSocket?.prototype;
|
||||
const nativeSend = wsProto?.send;
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
function updatePayload(payload) {
|
||||
const config = payload?.cascadeConfig;
|
||||
const model = config?.plannerConfig?.planModel;
|
||||
if (typeof model !== 'string' || !Object.hasOwn(state.rules, model)) return false;
|
||||
const checkpoint = config.checkpointConfig ??= {};
|
||||
if (typeof checkpoint !== 'object' || Array.isArray(checkpoint)) return false;
|
||||
const option = state.rules[model];
|
||||
if (typeof option === 'number') {
|
||||
delete checkpoint.contextWindow;
|
||||
checkpoint.maxTokenLimit = option;
|
||||
} else {
|
||||
delete checkpoint.maxTokenLimit;
|
||||
checkpoint.contextWindow = option;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function rewriteBody(body, contentType) {
|
||||
if (contentType === 'application/json' && typeof body === 'string') {
|
||||
const json = JSON.parse(body);
|
||||
if (updatePayload(json)) return JSON.stringify(json);
|
||||
} else if (contentType === 'application/grpc-web+json' && body instanceof Uint8Array &&
|
||||
body.length >= 5 && body[0] === 0) {
|
||||
const header = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
||||
if (header.getUint32(1) !== body.length - 5) return body;
|
||||
const json = JSON.parse(decoder.decode(body.subarray(5)));
|
||||
if (!updatePayload(json)) return body;
|
||||
const message = encoder.encode(JSON.stringify(json));
|
||||
const frame = new Uint8Array(5 + message.length);
|
||||
new DataView(frame.buffer).setUint32(1, message.length);
|
||||
frame.set(message, 5);
|
||||
return frame;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function fetchWithContextWindow(input, init) {
|
||||
let nextInit = init;
|
||||
try {
|
||||
if (typeof input === 'string' && init?.method === 'POST') {
|
||||
const url = new URL(input, window.location.href);
|
||||
if (url.origin === window.location.origin && url.pathname === sendPath) {
|
||||
const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim();
|
||||
const body = rewriteBody(init.body, type);
|
||||
if (body !== init.body) nextInit = { ...init, body };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 未识别的请求格式交回宿主原样发送。
|
||||
}
|
||||
return nextInit === init
|
||||
? nativeFetch.apply(this, arguments)
|
||||
: nativeFetch.call(this, input, nextInit);
|
||||
}
|
||||
|
||||
function sendWithContextWindow(data) {
|
||||
let nextData = data;
|
||||
try {
|
||||
if (typeof data === 'string' && data.includes(sendPath)) {
|
||||
const url = new URL(this.url);
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
if (url.protocol === protocol && url.host === window.location.host &&
|
||||
url.pathname === '/connect-websocket') {
|
||||
const frame = JSON.parse(data);
|
||||
if (frame.type === 'start' && frame.stream === false && frame.procedure === sendPath &&
|
||||
updatePayload(frame.payload)) {
|
||||
nextData = JSON.stringify(frame);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 未识别的帧交回宿主原样发送。
|
||||
}
|
||||
return nativeSend.call(this, nextData);
|
||||
}
|
||||
|
||||
state = window[key] = {
|
||||
bootId,
|
||||
rules: {},
|
||||
serviceUrl: window.location.origin + servicePath,
|
||||
isAttached() {
|
||||
return (typeof nativeFetch !== 'function' || window.fetch === fetchWithContextWindow) &&
|
||||
(typeof nativeSend !== 'function' || wsProto.send === sendWithContextWindow);
|
||||
},
|
||||
dispose() {
|
||||
clearTimeout(state.timer);
|
||||
state.rules = {};
|
||||
if (window.fetch === fetchWithContextWindow) window.fetch = nativeFetch;
|
||||
if (wsProto?.send === sendWithContextWindow) wsProto.send = nativeSend;
|
||||
delete window[key];
|
||||
},
|
||||
};
|
||||
if (typeof nativeFetch === 'function') window.fetch = fetchWithContextWindow;
|
||||
if (typeof nativeSend === 'function') wsProto.send = sendWithContextWindow;
|
||||
}
|
||||
state.preferences = rules;
|
||||
clearTimeout(state.timer);
|
||||
state.timer = setTimeout(() => state.dispose(), 15000);
|
||||
|
||||
// App 和 IDE 同时打开时,各窗口只使用自身宿主上报的档位。
|
||||
if (state.csrfToken !== csrfToken || Date.now() >= state.refreshAt) {
|
||||
if (state.csrfToken !== csrfToken) state.rules = {};
|
||||
state.csrfToken = csrfToken;
|
||||
state.refreshAt = Date.now() + 10000;
|
||||
state.status = (async () => {
|
||||
try {
|
||||
const init = {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'x-codeium-csrf-token': csrfToken },
|
||||
body: '{}',
|
||||
signal: AbortSignal.timeout(1500),
|
||||
};
|
||||
const call = async (method) => {
|
||||
const response = await window.fetch(state.serviceUrl + method, init);
|
||||
return response.ok ? response.json() : null;
|
||||
};
|
||||
const [status, catalog] = await Promise.all([
|
||||
call('GetUserStatus'),
|
||||
call('GetAvailableModels').catch(() => null),
|
||||
]);
|
||||
const userStatus = status?.userStatus;
|
||||
const configs = userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
||||
return getContextWindowModels(configs, catalog?.response?.models);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
}
|
||||
const status = state.status;
|
||||
const models = await status;
|
||||
if (window[key] !== state || state.status !== status) return;
|
||||
state.rules = resolveContextWindowRules(models, state.preferences);
|
||||
}
|
||||
|
||||
export function createContextWindowSyncExpression(preferences, bootId) {
|
||||
return `(() => {
|
||||
${isContextWindowModelId.toString()}
|
||||
${isContextWindowSettingId.toString()}
|
||||
${isContextWindowOption.toString()}
|
||||
${getContextWindowModels.toString()}
|
||||
${getContextWindowGroups.toString()}
|
||||
${resolveContextWindowOption.toString()}
|
||||
${resolveContextWindowRules.toString()}
|
||||
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)});
|
||||
})()`;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,554 @@
|
||||
/**
|
||||
* @fileoverview Antigravity Hub / Language Server 本地守护文件与进程自动发现器。
|
||||
*
|
||||
* 兼容 Antigravity 2.0、Antigravity IDE、无头 `agy` CLI 与 `agy remote-control serve`:
|
||||
* 1. 优先读取 `~/.gemini/<product>/daemon/hub_*.json`(跨平台零外部命令依赖,毫秒级命中 `httpPort` + `csrfToken`);
|
||||
* 2. 回退枚举当前用户的 `agy` / `antigravity-cli` / `language_server` 进程;
|
||||
* 3. 在精简版无头 Linux 环境优先通过 `/proc/<pid>/fd` + `/proc/net/tcp{,6}` 与 `ss -H -lntp` 解析监听端口,不强依赖 `lsof`;
|
||||
* 4. 经 `GetUserStatus` 实测握手验证后写入 `lsRuntimeEndpoint`。
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { DAEMON_DIRS, lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs';
|
||||
|
||||
const LS_DISC_COOLDOWN_MS = 4000;
|
||||
|
||||
const lsDiscoveryState = {
|
||||
inFlight: null,
|
||||
lastAttemptMs: 0,
|
||||
};
|
||||
|
||||
function defaultIsLsPidAlive(pid) {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return true;
|
||||
if (typeof process?.kill !== 'function') return true;
|
||||
if (pid === process.pid) return true;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
return err?.code === 'EPERM';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `agy`(`--hub` / `remote-control` / CLI)或 `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 isAgyBinary = /(?:^|[\s/\\"'])(?:agy|antigravity-cli)(?:\.exe)?(?:["'\s]|$)/i.test(cmd);
|
||||
const isHub = isAgyBinary && /(?:--hub\b|\bremote-control\b|--csrf[-_]token\b)/i.test(cmd);
|
||||
const isLanguageServer = /language_server/i.test(cmd);
|
||||
|
||||
let hubPort = null;
|
||||
const portMatch = cmd.match(
|
||||
/--(?:hub[-_]port|http[-_]port|https[-_]server[-_]port|server[-_]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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Linux `/proc/net/tcp` 或 `/proc/net/tcp6` 内容,提取指定 socket inode 集合中处于 `0A` (LISTEN) 状态的本地端口。
|
||||
*
|
||||
* @param {string} tcpTableText
|
||||
* @param {Set<string>} socketInodes
|
||||
* @returns {number[]}
|
||||
*/
|
||||
export function parseLinuxProcNetTcpPorts(tcpTableText, socketInodes) {
|
||||
if (!tcpTableText || !(socketInodes instanceof Set) || socketInodes.size === 0) {
|
||||
return [];
|
||||
}
|
||||
const ports = new Set();
|
||||
for (const rawLine of String(tcpTableText).split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || /^sl\b/i.test(line)) continue;
|
||||
const cols = line.split(/\s+/);
|
||||
if (cols.length < 10) continue;
|
||||
const localAddr = cols[1] || '';
|
||||
const stateHex = (cols[3] || '').toUpperCase();
|
||||
const inode = cols[9] || '';
|
||||
if (stateHex !== '0A' || !socketInodes.has(inode)) continue;
|
||||
const colonIdx = localAddr.lastIndexOf(':');
|
||||
if (colonIdx < 0) continue;
|
||||
const port = Number.parseInt(localAddr.slice(colonIdx + 1), 16);
|
||||
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Linux `ss -H -lntp` 输出,提取归属于目标 `pid` 的监听端口。
|
||||
*
|
||||
* @param {string} ssOutput
|
||||
* @param {number} pid
|
||||
* @returns {number[]}
|
||||
*/
|
||||
export function parseSsListeningPorts(ssOutput, pid) {
|
||||
if (!ssOutput || !Number.isInteger(pid) || pid <= 0) return [];
|
||||
const pidTokenRe = new RegExp(`\\bpid=${pid}\\b`);
|
||||
const ports = new Set();
|
||||
for (const rawLine of String(ssOutput).split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || !pidTokenRe.test(line)) continue;
|
||||
const cols = line.split(/\s+/);
|
||||
const localCol = cols[3] || '';
|
||||
const m = localCol.match(/:(\d{1,5})$/);
|
||||
if (m) {
|
||||
const p = Number(m[1]);
|
||||
if (Number.isInteger(p) && p > 0 && p <= 65535) ports.add(p);
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
}
|
||||
|
||||
async function readLinuxProcListeningPorts(pid, customProcFs = null) {
|
||||
try {
|
||||
const fsMod = customProcFs || (await import('node:fs'));
|
||||
const readlinkFn = fsMod.readlinkSync || fsMod.default?.readlinkSync;
|
||||
const readdirFn = fsMod.readdirSync || fsMod.default?.readdirSync || readdirSync;
|
||||
const readFileFn = fsMod.readFileSync || fsMod.default?.readFileSync || readFileSync;
|
||||
const existsFn = fsMod.existsSync || fsMod.default?.existsSync || existsSync;
|
||||
if (typeof readlinkFn !== 'function') return [];
|
||||
|
||||
const fdDir = `/proc/${pid}/fd`;
|
||||
if (!existsFn(fdDir)) return [];
|
||||
const socketInodes = new Set();
|
||||
for (const fdName of readdirFn(fdDir)) {
|
||||
try {
|
||||
const target = String(readlinkFn(`${fdDir}/${fdName}`) || '');
|
||||
const m = target.match(/^socket:\[(\d+)\]$/);
|
||||
if (m) socketInodes.add(m[1]);
|
||||
} catch {
|
||||
// 忽略瞬态关闭的 fd
|
||||
}
|
||||
}
|
||||
if (socketInodes.size === 0) return [];
|
||||
|
||||
const ports = new Set();
|
||||
for (const netFile of [`/proc/${pid}/net/tcp`, `/proc/${pid}/net/tcp6`, '/proc/net/tcp', '/proc/net/tcp6']) {
|
||||
if (!existsFn(netFile)) continue;
|
||||
try {
|
||||
const raw = String(readFileFn(netFile, 'utf8') || '');
|
||||
for (const p of parseLinuxProcNetTcpPorts(raw, socketInodes)) {
|
||||
ports.add(p);
|
||||
}
|
||||
} catch {
|
||||
// 忽略不可读的 proc 网络表
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function readHubDaemonCandidates(daemonDirs, preferredPids, isPidAliveFn) {
|
||||
const candidates = [];
|
||||
const seenKeys = new Set();
|
||||
for (const dir of Array.isArray(daemonDirs) ? daemonDirs : []) {
|
||||
if (!dir || !existsSync(dir)) continue;
|
||||
let names = [];
|
||||
try {
|
||||
names = readdirSync(dir);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const name of names) {
|
||||
if (!/^hub_.*\.json$/i.test(name)) continue;
|
||||
const fullPath = join(dir, name);
|
||||
try {
|
||||
const st = statSync(fullPath);
|
||||
const parsed = JSON.parse(readFileSync(fullPath, 'utf8'));
|
||||
const csrfToken = String(parsed?.csrfToken || parsed?.csrf_token || '').trim();
|
||||
if (!csrfToken) continue;
|
||||
const pid = Number(parsed?.pid) || 0;
|
||||
if (pid > 0 && !isPidAliveFn(pid)) continue;
|
||||
const httpPort = Number(parsed?.httpPort || parsed?.port) || 0;
|
||||
const httpsPort = Number(parsed?.httpsPort) || 0;
|
||||
const targets = [];
|
||||
if (Number.isInteger(httpPort) && httpPort > 0 && httpPort <= 65535) {
|
||||
targets.push({ port: httpPort, protos: ['http', 'https'] });
|
||||
}
|
||||
if (
|
||||
Number.isInteger(httpsPort) &&
|
||||
httpsPort > 0 &&
|
||||
httpsPort <= 65535 &&
|
||||
httpsPort !== httpPort
|
||||
) {
|
||||
targets.push({ port: httpsPort, protos: ['https', 'http'] });
|
||||
}
|
||||
if (targets.length === 0) continue;
|
||||
const dedupKey = `${pid}:${httpPort}:${httpsPort}:${csrfToken}`;
|
||||
if (seenKeys.has(dedupKey)) continue;
|
||||
seenKeys.add(dedupKey);
|
||||
const priority = preferredPids.has(pid) ? 115 : 95;
|
||||
candidates.push({
|
||||
pid,
|
||||
priority,
|
||||
mtimeMs: Number(st?.mtimeMs || 0),
|
||||
csrfToken,
|
||||
targets,
|
||||
});
|
||||
} catch {
|
||||
// 忽略损坏或正在替换的 daemon 文件
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates.sort((a, b) => b.priority - a.priority || b.mtimeMs - a.mtimeMs || b.pid - a.pid);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
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|antigravity-cli|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 'antigravity-cli%' 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|antigravity-cli|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, procFs = null) {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return [];
|
||||
if (platform === 'win32') {
|
||||
try {
|
||||
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)
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
if (platform === 'linux') {
|
||||
const procPorts = await readLinuxProcListeningPorts(pid, procFs);
|
||||
if (procPorts.length > 0) return procPorts;
|
||||
try {
|
||||
const ssOut = await execCmdFn('ss', ['-H', '-lntp']);
|
||||
const ssPorts = parseSsListeningPorts(ssOut, pid);
|
||||
if (ssPorts.length > 0) return ssPorts;
|
||||
} catch {
|
||||
// 无 ss 或权限受限时继续回退至 lsof
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
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, protos = ['http', 'https']) {
|
||||
for (const proto of protos) {
|
||||
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,
|
||||
* daemonDirs?: string[],
|
||||
* isPidAliveFn?: (pid: number) => boolean,
|
||||
* procFs?: object|null,
|
||||
* 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',
|
||||
daemonDirs = options.execCmdFn ? [] : DAEMON_DIRS,
|
||||
isPidAliveFn = defaultIsLsPidAlive,
|
||||
procFs = null,
|
||||
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)
|
||||
);
|
||||
|
||||
// 1. 优先探测 ~/.gemini/<product>/daemon/hub_*.json 守护端点描述文件(零外部进程开销)
|
||||
const daemonCandidates = readHubDaemonCandidates(daemonDirs, preferredPids, isPidAliveFn);
|
||||
const probedDaemonKeys = new Set();
|
||||
for (const cand of daemonCandidates) {
|
||||
for (const target of cand.targets) {
|
||||
probedDaemonKeys.add(`${target.port}:${cand.csrfToken}`);
|
||||
const verified = await probeLsCandidate(target.port, cand.csrfToken, fetchFn, target.protos);
|
||||
if (verified) {
|
||||
return { ...verified, pid: cand.pid };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 回退枚举操作系统进程并解析监听端口
|
||||
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, procFs);
|
||||
for (const port of ports) {
|
||||
if (probedDaemonKeys.has(`${port}:${cand.csrfToken}`)) continue;
|
||||
const verified = await probeLsCandidate(port, cand.csrfToken, fetchFn);
|
||||
if (verified) {
|
||||
return { ...verified, pid: cand.pid };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保 `lsRuntimeEndpoint` 已就绪(具备并发去重、失败冷却与动态端点重连能力)。
|
||||
*
|
||||
* @param {{ force?: boolean, respectCooldown?: boolean, ancestorPids?: number[] }} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export async function ensureLsEndpointDiscovered({
|
||||
force = false,
|
||||
respectCooldown = 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 || respectCooldown) &&
|
||||
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, { isDynamic: true });
|
||||
return true;
|
||||
}
|
||||
return Boolean(lsRuntimeEndpoint.baseUrl);
|
||||
} finally {
|
||||
lsDiscoveryState.inFlight = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return lsDiscoveryState.inFlight;
|
||||
}
|
||||
|
||||
@@ -7,13 +7,41 @@
|
||||
* 并在缓存过期或强制刷新时穿透 `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_RETRY_COOLDOWN_MS = 5_000;
|
||||
let contextModelCatalog = null;
|
||||
|
||||
export function getContextModelCatalog() {
|
||||
const { baseUrl, csrfToken } = lsRuntimeEndpoint;
|
||||
if (!contextModelCatalog || contextModelCatalog.baseUrl !== baseUrl || contextModelCatalog.csrfToken !== csrfToken ||
|
||||
Date.now() >= contextModelCatalog.expiresAt) {
|
||||
contextModelCatalog = {
|
||||
baseUrl,
|
||||
csrfToken,
|
||||
expiresAt: Date.now() + 30000,
|
||||
promise: callLsRpc('GetAvailableModels', {}, 1500).then((data) => data?.response?.models).catch(() => null),
|
||||
};
|
||||
}
|
||||
return contextModelCatalog.promise;
|
||||
}
|
||||
|
||||
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 {object} [body={}] 请求 JSON 载荷
|
||||
@@ -21,21 +49,62 @@ const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
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');
|
||||
}
|
||||
const res = await fetch(
|
||||
`${LS_BASE_URL}/exa.language_server_pb.LanguageServerService/${method}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-codeium-csrf-token': CSRF_TOKEN || '',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
|
||||
const prevAddr = lsRuntimeEndpoint.addr;
|
||||
const prevToken = lsRuntimeEndpoint.csrfToken;
|
||||
let res;
|
||||
try {
|
||||
res = await postLsRpcOnce(
|
||||
lsRuntimeEndpoint.baseUrl,
|
||||
lsRuntimeEndpoint.csrfToken,
|
||||
method,
|
||||
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) {
|
||||
const text = await res.text().catch(() => '');
|
||||
throw new Error(`RPC ${method} failed (${res.status}): ${text}`);
|
||||
@@ -53,9 +122,21 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
|
||||
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
|
||||
*
|
||||
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
|
||||
* @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
|
||||
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
|
||||
*/
|
||||
export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') {
|
||||
if (quotaSummaryCache.accountName !== accountName) {
|
||||
Object.assign(quotaSummaryCache, {
|
||||
accountName,
|
||||
accountGeneration: quotaSummaryCache.accountGeneration + 1,
|
||||
ts: 0,
|
||||
lastAttemptTs: 0,
|
||||
data: null,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
const generation = quotaSummaryCache.accountGeneration;
|
||||
const now = Date.now();
|
||||
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) {
|
||||
return {
|
||||
@@ -86,6 +167,9 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||
quotaSummaryCache.lastAttemptTs = now;
|
||||
try {
|
||||
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
|
||||
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000);
|
||||
if ((userStatus?.email || userStatus?.name || '') !== accountName) return {};
|
||||
if (generation !== quotaSummaryCache.accountGeneration) return {};
|
||||
const payload = res?.response !== undefined ? res.response : res;
|
||||
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
|
||||
const normalized =
|
||||
@@ -106,6 +190,7 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
|
||||
}
|
||||
quotaSummaryCache.error = 'Quota summary empty';
|
||||
} catch (err) {
|
||||
if (generation !== quotaSummaryCache.accountGeneration) return {};
|
||||
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
|
||||
quotaSummaryCache.error = err.message;
|
||||
}
|
||||
|
||||
@@ -103,13 +103,23 @@ export function isCarbonModelIdentifier(...parts) {
|
||||
export function getBaseModelLabel(label = '') {
|
||||
return (
|
||||
String(label || '')
|
||||
.replace(/\s*\((?:Max|XHigh|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')
|
||||
);
|
||||
}
|
||||
|
||||
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`)被静默截断伪装成旧模型获取错误定价。
|
||||
*
|
||||
* @param {string} [slug='']
|
||||
@@ -120,14 +130,22 @@ export function formatGenericModelSlug(slug = '') {
|
||||
.trim()
|
||||
.replace(/^session-display:/i, '');
|
||||
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(
|
||||
/^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) {
|
||||
const ver = m[1];
|
||||
const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase();
|
||||
const lite = m[3] ? ' Lite' : '';
|
||||
return `Gemini ${ver} ${tier}${lite}`;
|
||||
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);
|
||||
if (codenameMatch) {
|
||||
@@ -257,6 +275,34 @@ export function resolveModelInfo(
|
||||
};
|
||||
}
|
||||
|
||||
/** 在单次遥测请求内复用同一模型身份与价格的解析结果。 */
|
||||
export function createStepModelResolver(dynamicModelMap) {
|
||||
const models = new Map();
|
||||
return (step) => {
|
||||
const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step;
|
||||
if (
|
||||
typeof modelKey !== 'string' ||
|
||||
typeof apiProvider !== 'string' ||
|
||||
typeof modelDisplayName !== 'string' ||
|
||||
typeof responseModel !== 'string'
|
||||
) {
|
||||
return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
}
|
||||
let providers = models.get(modelKey);
|
||||
if (!providers) models.set(modelKey, (providers = new Map()));
|
||||
let names = providers.get(apiProvider);
|
||||
if (!names) providers.set(apiProvider, (names = new Map()));
|
||||
let responses = names.get(modelDisplayName);
|
||||
if (!responses) names.set(modelDisplayName, (responses = new Map()));
|
||||
let info = responses.get(responseModel);
|
||||
if (!info) {
|
||||
info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
responses.set(responseModel, info);
|
||||
}
|
||||
return info;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为不透明的 Orchestrator 路由模型 ID 补充底层实际模型代号标注(如 `gemini-pro-orchestrator (carbon-4)`),
|
||||
* 普通透明上游模型 ID(如 `gemini-3.8-flash-n`、`gemini-4-hydrogen`)原样返回。
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
cloudSyncState,
|
||||
loadJson,
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
pluginUpdateState,
|
||||
saveJson,
|
||||
} from './config.mjs';
|
||||
@@ -71,14 +72,39 @@ function runExecFile(cmd, args, opts = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
let customSidecarRestartHandler = null;
|
||||
|
||||
/**
|
||||
* 更新完成后调度 Sidecar 进程平滑退出,让宿主进程监督器自动重启新代码。
|
||||
* 注册自定义运行时热重载回调(例如 `main.mjs` 的 `Worker` 热替换或 `bridge-daemon.mjs` 的平滑退出),
|
||||
* 避免直接调用 `process.exit(0)` 导致宿主 `SidecarApp` 固定端口失联。
|
||||
*
|
||||
* @param {(() => void)|null} handler
|
||||
*/
|
||||
export function setSidecarRestartHandler(handler) {
|
||||
customSidecarRestartHandler = typeof handler === 'function' ? handler : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新完成后调度 Sidecar 运行时热重载(若未注册自定义处理器,则回退平滑退出供父监督器拉起)。
|
||||
* 在单元测试环境(`!LS_ADDR || LS_ADDR === 'test.invalid'`)下自动跳过。
|
||||
*
|
||||
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
||||
*/
|
||||
export function scheduleSidecarRestart(delayMs = 350) {
|
||||
if (!LS_ADDR || LS_ADDR === 'test.invalid' || typeof process?.exit !== 'function') return;
|
||||
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
|
||||
if (!activeAddr || activeAddr === 'test.invalid') return;
|
||||
if (typeof customSidecarRestartHandler === 'function') {
|
||||
const fn = customSidecarRestartHandler;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
// 忽略自定义热重载回调异常
|
||||
}
|
||||
}, delayMs);
|
||||
return;
|
||||
}
|
||||
if (typeof process?.exit !== 'function') return;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.exit(0);
|
||||
@@ -191,10 +217,13 @@ export function resolveMigratedGitRemoteUrl(rawUrl) {
|
||||
* @param {string} rootDir 插件根目录或解压目录
|
||||
*/
|
||||
async function verifyPluginJsSyntax(rootDir) {
|
||||
if (!LS_ADDR || LS_ADDR === 'test.invalid') return;
|
||||
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
|
||||
if (!activeAddr || activeAddr === 'test.invalid') return;
|
||||
const nodeBin = process?.execPath || 'node';
|
||||
const filesToCheck = [
|
||||
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'),
|
||||
];
|
||||
for (const file of filesToCheck) {
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
*/
|
||||
export const MODEL_PRICING = {};
|
||||
export const PLACEHOLDER_MAP = {};
|
||||
export let pricingCatalogRevision = 0;
|
||||
|
||||
/**
|
||||
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
|
||||
@@ -361,6 +362,7 @@ export function rebuildActiveCatalog() {
|
||||
|
||||
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
|
||||
Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
|
||||
pricingCatalogRevision += 1;
|
||||
|
||||
cloudSyncState.source = activeSource;
|
||||
cloudSyncState.catalogVersion = catalogVersion;
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
/**
|
||||
* @fileoverview 用户偏好设置 Schema、枚举常量、默认值与无状态纯函数归一化器。
|
||||
*
|
||||
* 独立于文件系统与运行时状态,统一约束「常规 / 结构 / 其他」三栏偏好结构,
|
||||
* 并无缝兼容旧版 `settings.json`(如 3 槽固定数组中的 `'none'`、`enableWindowOverlay`、`autoUpdatePlugin` 等)。
|
||||
*/
|
||||
|
||||
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
|
||||
|
||||
export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']);
|
||||
|
||||
export const THEME_ACCENT_KEYS = Object.freeze([
|
||||
'host',
|
||||
'blue',
|
||||
'emerald',
|
||||
'amber',
|
||||
'violet',
|
||||
'cyan',
|
||||
'rose',
|
||||
]);
|
||||
|
||||
export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']);
|
||||
|
||||
export const TOPBAR_SLOT_KEYS = Object.freeze([
|
||||
'context',
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'cost',
|
||||
'session_cost',
|
||||
'cache_hit',
|
||||
'session_tokens',
|
||||
'quota_auto',
|
||||
'gemini_5h',
|
||||
'gemini_weekly',
|
||||
'claude_5h',
|
||||
'claude_weekly',
|
||||
]);
|
||||
|
||||
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
||||
export const MIN_TOPBAR_SLOTS = 1;
|
||||
export const MAX_TOPBAR_SLOTS = 5;
|
||||
|
||||
export const OVERVIEW_MODULE_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_OVERVIEW_MODULES = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
||||
|
||||
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'step_cost',
|
||||
'session_cost',
|
||||
'cache_hit',
|
||||
'session_tokens',
|
||||
'context_usage',
|
||||
'quota_tightest',
|
||||
]);
|
||||
|
||||
export const DEFAULT_OVERVIEW_METRICS = Object.freeze([
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'step_cost',
|
||||
]);
|
||||
|
||||
export const STEP_TABLE_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
'time',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'tokens_io_cache',
|
||||
'tokens_custom',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([
|
||||
'step',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'tokens_combo',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
||||
|
||||
export const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({
|
||||
context: 'context',
|
||||
ctx: 'context',
|
||||
'上下文': 'context',
|
||||
in: 'in',
|
||||
new: 'in',
|
||||
input: 'in',
|
||||
'输入': 'in',
|
||||
'新输入': 'in',
|
||||
out: 'out',
|
||||
output: 'out',
|
||||
'输出': 'out',
|
||||
'总输出': 'out',
|
||||
cache: 'cache',
|
||||
cached: 'cache',
|
||||
cache_read: 'cache',
|
||||
cacheread: 'cache',
|
||||
'缓存': 'cache',
|
||||
'缓存读': 'cache',
|
||||
think: 'think',
|
||||
thinking: 'think',
|
||||
'思考': 'think',
|
||||
reply: 'reply',
|
||||
body: 'reply',
|
||||
resp: 'reply',
|
||||
response: 'reply',
|
||||
text: 'reply',
|
||||
'正文': 'reply',
|
||||
'回复': 'reply',
|
||||
total: 'total',
|
||||
all: 'total',
|
||||
sum: 'total',
|
||||
'总计': 'total',
|
||||
'总token': 'total',
|
||||
});
|
||||
|
||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
||||
|
||||
export const MODEL_DISPLAY_MODES = Object.freeze(['short', 'upstream', 'upstream_compact']);
|
||||
|
||||
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
||||
|
||||
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
|
||||
|
||||
export const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']);
|
||||
export const MIN_POPOVER_WIDTH = 440;
|
||||
export const MAX_POPOVER_WIDTH = 1080;
|
||||
export const DEFAULT_POPOVER_WIDTH = 580;
|
||||
|
||||
function isSchemaPlainObject(v) {
|
||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||
}
|
||||
|
||||
function schemaSanitizePositiveNum(val, fallback) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化界面语言枚举(默认 `'zh-CN'`,保持与现有界面一致;同时支持 `'auto'` 与 `'en-US'`)。
|
||||
*
|
||||
* @param {unknown} lang
|
||||
* @returns {'auto'|'zh-CN'|'en-US'}
|
||||
*/
|
||||
export function normalizeLanguageSetting(lang) {
|
||||
const raw = String(lang ?? '').trim();
|
||||
if (!raw) return 'zh-CN';
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === 'auto' || lower === 'system') return 'auto';
|
||||
if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US';
|
||||
if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN';
|
||||
return 'zh-CN';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。
|
||||
*
|
||||
* @param {unknown} accent
|
||||
* @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'}
|
||||
*/
|
||||
export function normalizeThemeAccent(accent) {
|
||||
const clean = String(accent ?? '').trim().toLowerCase();
|
||||
return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化面板字号档位(默认 `'md'` 标准 100%)。
|
||||
*
|
||||
* @param {unknown} scale
|
||||
* @returns {'sm'|'md'|'lg'|'xl'}
|
||||
*/
|
||||
export function normalizeFontScale(scale) {
|
||||
const clean = String(scale ?? '').trim().toLowerCase();
|
||||
return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化面板挂载方式枚举(`'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';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化模型名称展示模式(`'short'` 精简代号 | `'upstream_compact'` 去前缀原始 ID | `'upstream'` 完整原始 ID),
|
||||
* 兼容历史 `showUpstreamModel` 布尔开关,默认 `'short'`。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyShowUpstream]
|
||||
* @returns {'short'|'upstream_compact'|'upstream'}
|
||||
*/
|
||||
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||
return 'upstream_compact';
|
||||
}
|
||||
if (m === 'short') return 'short';
|
||||
if (legacyShowUpstream === true) return 'upstream';
|
||||
return 'short';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 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';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化悬浮主面板宽度模式(`'auto'` 自适应内容宽度 | `'custom'` 指定像素宽度,默认 `'auto'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'auto'|'custom'}
|
||||
*/
|
||||
export function normalizePopoverWidthMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。
|
||||
*
|
||||
* @param {unknown} width
|
||||
* @returns {number}
|
||||
*/
|
||||
export function normalizePopoverWidth(width) {
|
||||
const num = Number(width);
|
||||
if (!Number.isFinite(num) || num <= 0) return DEFAULT_POPOVER_WIDTH;
|
||||
return Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(num)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析步骤表自定义 Token 组合表达式,支持 `:`、`/`、`,`、`|` 分隔与中英文别名(1~4 项不重复)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {Array<'context'|'in'|'out'|'cache'|'think'|'reply'|'total'>}
|
||||
*/
|
||||
export function parseStepTokenComboSegments(raw) {
|
||||
const str = String(raw ?? '').trim();
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
if (str) {
|
||||
for (const part of str.split(/[:/,|]+/)) {
|
||||
const key = part.trim().toLowerCase();
|
||||
if (!key) continue;
|
||||
const mapped = Object.prototype.hasOwnProperty.call(STEP_TOKEN_SEGMENT_ALIASES, key)
|
||||
? STEP_TOKEN_SEGMENT_ALIASES[key]
|
||||
: null;
|
||||
if (!mapped || seen.has(mapped)) continue;
|
||||
seen.add(mapped);
|
||||
out.push(/** @type {any} */ (mapped));
|
||||
if (out.length >= 4) break;
|
||||
}
|
||||
}
|
||||
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化步骤表自定义 Token 组合格式字符串(如 `'context:new:cache'` -> `'context:in:cache'`)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeStepTokenComboFormat(raw) {
|
||||
return parseStepTokenComboSegments(raw).join(':');
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyAutoUpdate]
|
||||
* @returns {'off'|'manual'|'auto'}
|
||||
*/
|
||||
export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
||||
if (legacyAutoUpdate === true) return 'auto';
|
||||
return 'manual';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'official'|'custom_tokens'|'custom_cost'}
|
||||
*/
|
||||
export function normalizeWeeklyLimitMode(mode) {
|
||||
const m = String(mode || '').trim().toLowerCase();
|
||||
if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens';
|
||||
if (m === 'custom_cost' || m === 'cost') return 'custom_cost';
|
||||
return 'official';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeTopbarCapsuleSlots(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_TOPBAR_SLOTS];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!val || val === 'none') continue;
|
||||
const mapped = val === 'step_cost' ? 'cost' : val;
|
||||
if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue;
|
||||
seen.add(mapped);
|
||||
out.push(mapped);
|
||||
if (out.length >= MAX_TOPBAR_SLOTS) break;
|
||||
}
|
||||
if (out.length < MIN_TOPBAR_SLOTS) {
|
||||
return ['context'];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeOverviewModules(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_OVERVIEW_MODULES];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||
}
|
||||
return out.length > 0 ? out : ['metrics'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeHoverModules(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_HOVER_MODULES];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeOverviewMetrics(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_OVERVIEW_METRICS];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const rawVal = String(item ?? '').trim();
|
||||
const val = rawVal === 'cost' ? 'step_cost' : rawVal;
|
||||
if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= 4) break;
|
||||
}
|
||||
return out.length > 0 ? out : ['tps'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化调用明细「按步查看」表格列配置与左右顺序(2~12 列,默认保留现有 7 列)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeStepTableColumns(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_STEP_TABLE_COLUMNS];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break;
|
||||
}
|
||||
if (out.length < 2) {
|
||||
for (const fallbackCol of ['step', 'model', 'tps']) {
|
||||
if (!seen.has(fallbackCol)) {
|
||||
seen.add(fallbackCol);
|
||||
out.push(fallbackCol);
|
||||
}
|
||||
if (out.length >= 2) break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeModelContextWindows(value) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(isSchemaPlainObject(value) ? value : {}).filter(
|
||||
([id, option]) => isContextWindowSettingId(id) && isContextWindowOption(option)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。
|
||||
*
|
||||
* @param {unknown} port
|
||||
* @returns {number}
|
||||
*/
|
||||
export function normalizeStandalonePort(port) {
|
||||
const num = Number(port);
|
||||
if (!Number.isInteger(num) || num <= 0) return 0;
|
||||
if (num >= 1024 && num <= 65535) return num;
|
||||
return 0;
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
language: 'zh-CN',
|
||||
themeAccent: 'host',
|
||||
fontScale: 'md',
|
||||
weeklyTokenBudget: 150000000,
|
||||
weeklyCostBudget: 100,
|
||||
weeklyLimitMode: 'official',
|
||||
modelDisplayMode: 'short',
|
||||
showUpstreamModel: false,
|
||||
orchestratorIdMode: 'compact',
|
||||
pluginUpdateMode: 'manual',
|
||||
autoUpdatePlugin: false,
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
popoverWidthMode: 'auto',
|
||||
popoverWidth: DEFAULT_POPOVER_WIDTH,
|
||||
enableCliStatusLine: true,
|
||||
standalonePort: 0,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: DEFAULT_TOPBAR_SLOTS,
|
||||
hoverModules: DEFAULT_HOVER_MODULES,
|
||||
overviewModules: DEFAULT_OVERVIEW_MODULES,
|
||||
overviewMetrics: DEFAULT_OVERVIEW_METRICS,
|
||||
showStepTurnRail: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepSpeedColor: false,
|
||||
stepTokenComboFormat: DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
|
||||
contextWindowRiskAccepted: false,
|
||||
modelContextWindows: Object.freeze({}),
|
||||
});
|
||||
|
||||
/**
|
||||
* 创建一份深拷贝的全新默认偏好设置对象。
|
||||
*/
|
||||
export function createDefaultSettingsObject() {
|
||||
return {
|
||||
language: DEFAULT_SETTINGS_SCHEMA.language,
|
||||
themeAccent: DEFAULT_SETTINGS_SCHEMA.themeAccent,
|
||||
fontScale: DEFAULT_SETTINGS_SCHEMA.fontScale,
|
||||
weeklyTokenBudget: DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget,
|
||||
weeklyCostBudget: DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget,
|
||||
weeklyLimitMode: DEFAULT_SETTINGS_SCHEMA.weeklyLimitMode,
|
||||
modelDisplayMode: DEFAULT_SETTINGS_SCHEMA.modelDisplayMode,
|
||||
showUpstreamModel: DEFAULT_SETTINGS_SCHEMA.showUpstreamModel,
|
||||
orchestratorIdMode: DEFAULT_SETTINGS_SCHEMA.orchestratorIdMode,
|
||||
pluginUpdateMode: DEFAULT_SETTINGS_SCHEMA.pluginUpdateMode,
|
||||
autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin,
|
||||
windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode,
|
||||
enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay,
|
||||
popoverWidthMode: DEFAULT_SETTINGS_SCHEMA.popoverWidthMode,
|
||||
popoverWidth: DEFAULT_SETTINGS_SCHEMA.popoverWidth,
|
||||
enableCliStatusLine: DEFAULT_SETTINGS_SCHEMA.enableCliStatusLine,
|
||||
standalonePort: DEFAULT_SETTINGS_SCHEMA.standalonePort,
|
||||
showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession,
|
||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
||||
hoverModules: [...DEFAULT_HOVER_MODULES],
|
||||
overviewModules: [...DEFAULT_OVERVIEW_MODULES],
|
||||
overviewMetrics: [...DEFAULT_OVERVIEW_METRICS],
|
||||
showStepTurnRail: DEFAULT_SETTINGS_SCHEMA.showStepTurnRail,
|
||||
showStepAgentBadge: DEFAULT_SETTINGS_SCHEMA.showStepAgentBadge,
|
||||
showStepSpeedColor: DEFAULT_SETTINGS_SCHEMA.showStepSpeedColor,
|
||||
stepTokenComboFormat: DEFAULT_SETTINGS_SCHEMA.stepTokenComboFormat,
|
||||
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
||||
contextWindowRiskAccepted: DEFAULT_SETTINGS_SCHEMA.contextWindowRiskAccepted,
|
||||
modelContextWindows: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将原始持久化对象或增量合并结果完整归一化为合法偏好对象。
|
||||
*
|
||||
* @param {unknown} rawInput
|
||||
*/
|
||||
export function normalizeFullSettings(rawInput) {
|
||||
const safeRaw = isSchemaPlainObject(rawInput) ? rawInput : {};
|
||||
const pluginUpdateMode = normalizePluginUpdateMode(
|
||||
safeRaw.pluginUpdateMode,
|
||||
safeRaw.autoUpdatePlugin
|
||||
);
|
||||
const windowMountMode = normalizeWindowMountMode(
|
||||
safeRaw.windowMountMode,
|
||||
safeRaw.enableWindowOverlay
|
||||
);
|
||||
const modelDisplayMode = normalizeModelDisplayMode(
|
||||
safeRaw.modelDisplayMode,
|
||||
safeRaw.showUpstreamModel
|
||||
);
|
||||
return {
|
||||
language: normalizeLanguageSetting(safeRaw.language),
|
||||
themeAccent: normalizeThemeAccent(safeRaw.themeAccent),
|
||||
fontScale: normalizeFontScale(safeRaw.fontScale),
|
||||
weeklyTokenBudget: schemaSanitizePositiveNum(
|
||||
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit,
|
||||
DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget
|
||||
),
|
||||
weeklyCostBudget: schemaSanitizePositiveNum(
|
||||
safeRaw.weeklyCostBudget,
|
||||
DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(safeRaw.weeklyLimitMode),
|
||||
modelDisplayMode,
|
||||
showUpstreamModel: modelDisplayMode !== 'short',
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(safeRaw.orchestratorIdMode),
|
||||
pluginUpdateMode,
|
||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||
windowMountMode,
|
||||
enableWindowOverlay: windowMountMode !== 'sidebar',
|
||||
popoverWidthMode: normalizePopoverWidthMode(safeRaw.popoverWidthMode),
|
||||
popoverWidth: normalizePopoverWidth(safeRaw.popoverWidth),
|
||||
enableCliStatusLine: safeRaw.enableCliStatusLine !== false,
|
||||
standalonePort: normalizeStandalonePort(safeRaw.standalonePort),
|
||||
showTopbarMultiSession: safeRaw.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
||||
hoverModules: normalizeHoverModules(safeRaw.hoverModules),
|
||||
overviewModules: normalizeOverviewModules(safeRaw.overviewModules),
|
||||
overviewMetrics: normalizeOverviewMetrics(safeRaw.overviewMetrics),
|
||||
showStepTurnRail: safeRaw.showStepTurnRail === true,
|
||||
showStepAgentBadge: safeRaw.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: safeRaw.showStepSpeedColor === true,
|
||||
stepTokenComboFormat: normalizeStepTokenComboFormat(safeRaw.stepTokenComboFormat),
|
||||
stepTableColumns: normalizeStepTableColumns(safeRaw.stepTableColumns),
|
||||
contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true,
|
||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @fileoverview Hot-reloadable backend Worker runtime (`sidecar-worker.mjs`) for `main.mjs`.
|
||||
*
|
||||
* Isolates all ESM backend modules (`api-actions.mjs`, `telemetry-builder.mjs`, `window-bridge.mjs`,
|
||||
* `pricing-catalog.mjs`, etc.) inside a dedicated V8 Worker isolate so plugin updates (in-app Git/ZIP
|
||||
* or external file overwrite while Antigravity is open) can tear down and respawn a fresh Worker
|
||||
* without ever exiting the parent `SidecarApp` process or losing its host-assigned HTTP port.
|
||||
*/
|
||||
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
import {
|
||||
bootBundleVersion,
|
||||
bootWindowBridgeRuntime,
|
||||
dispatchBridgeApiRequest,
|
||||
} from './api-actions.mjs';
|
||||
import { computeRuntimeCodeVersion } from './config.mjs';
|
||||
|
||||
let shuttingDown = false;
|
||||
let reloadRequested = false;
|
||||
|
||||
function requestWorkerReload() {
|
||||
if (shuttingDown || reloadRequested) return;
|
||||
reloadRequested = true;
|
||||
try {
|
||||
parentPort?.postMessage({ type: 'reload_request' });
|
||||
} catch {
|
||||
// Ignore postMessage errors if parent is already closing
|
||||
}
|
||||
}
|
||||
|
||||
const bridgeController = bootWindowBridgeRuntime({
|
||||
allowDynamicLs: true,
|
||||
onRestart: requestWorkerReload,
|
||||
});
|
||||
|
||||
const driftWatchTimer = setInterval(() => {
|
||||
if (shuttingDown || reloadRequested) return;
|
||||
try {
|
||||
const diskVersion = String(computeRuntimeCodeVersion() || '');
|
||||
if (bootBundleVersion && diskVersion && diskVersion !== String(bootBundleVersion)) {
|
||||
requestWorkerReload();
|
||||
}
|
||||
} catch {
|
||||
// Ignore transient file stat errors while files are being overwritten
|
||||
}
|
||||
}, 3000);
|
||||
driftWatchTimer.unref?.();
|
||||
|
||||
async function gracefulStop() {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
clearInterval(driftWatchTimer);
|
||||
try {
|
||||
await bridgeController?.stop?.({ disposeWindows: false });
|
||||
} catch {
|
||||
// Ignore shutdown errors
|
||||
}
|
||||
}
|
||||
|
||||
parentPort?.on('message', async (msg) => {
|
||||
if (!msg || typeof msg !== 'object') return;
|
||||
if (msg.type === 'shutdown') {
|
||||
await gracefulStop();
|
||||
try {
|
||||
parentPort?.postMessage({ type: 'shutdown_ack', id: msg.id });
|
||||
} catch {
|
||||
// Ignore closed channel
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'api') {
|
||||
const reqId = msg.id;
|
||||
try {
|
||||
const out = await dispatchBridgeApiRequest(
|
||||
String(msg.pathname || ''),
|
||||
String(msg.method || 'GET'),
|
||||
msg.data,
|
||||
{ onRestart: requestWorkerReload }
|
||||
);
|
||||
parentPort?.postMessage({
|
||||
type: 'api_result',
|
||||
id: reqId,
|
||||
ok: true,
|
||||
response: {
|
||||
status: out?.status || 200,
|
||||
contentType: out?.contentType || 'application/json',
|
||||
headers: out?.headers || { 'Cache-Control': 'no-store' },
|
||||
body: typeof out?.body === 'string' ? out.body : JSON.stringify(out?.body ?? {}),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
parentPort?.postMessage({
|
||||
type: 'api_result',
|
||||
id: reqId,
|
||||
ok: false,
|
||||
error: err?.message || 'Worker API execution failed',
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
parentPort?.postMessage({ type: 'ready', bundleVersion: bootBundleVersion });
|
||||
@@ -0,0 +1,641 @@
|
||||
/**
|
||||
* @fileoverview 无 `sidecar_sdk` 依赖的独立 Web 监控 HTTP 服务端 (`standalone-server.mjs`)。
|
||||
*
|
||||
* 面向无头 Linux CLI (`agy` / `agy remote-control serve`)、SSH 端口转发 (`ssh -L`) 与受保护远程访问场景:
|
||||
* 1. 默认严格绑定 `127.0.0.1`(本机浏览器或 `ssh -L` 零配置直连,校检回环地址与同端口 Host/Origin);
|
||||
* 2. 若显式绑定非回环地址(如 `0.0.0.0`、`::` 或局域网 IP),强制要求配置 `--token <secret>` 或
|
||||
* `USAGE_MONITOR_STANDALONE_TOKEN`,拒绝无鉴权公网/局域网裸奔启动;
|
||||
* 3. 完整托管四分页 Web 面板(`/`、`/app.js`、`/styles.css`、`/preload.js` 兼容桩)与 `/api/*` 路由。
|
||||
*/
|
||||
|
||||
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
||||
import http from 'node:http';
|
||||
import {
|
||||
dispatchBridgeApiRequest,
|
||||
isLocalHostRequest,
|
||||
readLocalAsync,
|
||||
} from './api-actions.mjs';
|
||||
import { loadSettings, lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs';
|
||||
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||
import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
|
||||
import { syncCloudCatalog } from './plugin-updater.mjs';
|
||||
|
||||
const MAX_JSON_BODY_BYTES = 1024 * 1024;
|
||||
const AUTH_COOKIE_NAME = 'ag_um_token';
|
||||
const NO_STORE_HEADERS = {
|
||||
'Cache-Control': 'no-store, no-cache, must-revalidate',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断绑定监听地址是否属于纯本机回环地址。
|
||||
*
|
||||
* @param {string} host
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isLoopbackBindHost(host) {
|
||||
const clean = String(host || '127.0.0.1')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[|\]$/g, '');
|
||||
if (!clean) return true;
|
||||
if (clean === 'localhost' || clean === '::1' || clean === '0:0:0:0:0:0:0:1') {
|
||||
return true;
|
||||
}
|
||||
return /^127\.(?:25[0-5]|2[0-4]\d|1?\d?\d)\.(?:25[0-5]|2[0-4]\d|1?\d?\d)\.(?:25[0-5]|2[0-4]\d|1?\d?\d)$/.test(
|
||||
clean
|
||||
);
|
||||
}
|
||||
|
||||
function isLoopbackRemoteAddress(remoteAddress) {
|
||||
const addr = String(remoteAddress || '').trim().toLowerCase();
|
||||
if (!addr) return true;
|
||||
if (addr === '::1' || addr === '127.0.0.1') return true;
|
||||
if (addr.startsWith('::ffff:')) {
|
||||
return isLoopbackBindHost(addr.slice(7));
|
||||
}
|
||||
return isLoopbackBindHost(addr);
|
||||
}
|
||||
|
||||
function sha256Buffer(value) {
|
||||
return createHash('sha256').update(String(value ?? ''), 'utf8').digest();
|
||||
}
|
||||
|
||||
function safeEqualSecret(candidate, expected) {
|
||||
if (typeof candidate !== 'string' || typeof expected !== 'string' || !expected) {
|
||||
return false;
|
||||
}
|
||||
return timingSafeEqual(sha256Buffer(candidate), sha256Buffer(expected));
|
||||
}
|
||||
|
||||
function deriveCookieValue(secret) {
|
||||
return createHmac('sha256', 'ag-usage-monitor-standalone-cookie-v1')
|
||||
.update(secret, 'utf8')
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
function parseCookies(cookieHeader) {
|
||||
const out = {};
|
||||
for (const part of String(cookieHeader || '').split(';')) {
|
||||
const idx = part.indexOf('=');
|
||||
if (idx <= 0) continue;
|
||||
const k = part.slice(0, idx).trim();
|
||||
const v = part.slice(idx + 1).trim();
|
||||
if (!k) continue;
|
||||
try {
|
||||
out[k] = decodeURIComponent(v);
|
||||
} catch {
|
||||
out[k] = v;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractBearerToken(authHeader) {
|
||||
const raw = String(authHeader || '').trim();
|
||||
const m = raw.match(/^Bearer\s+(.+)$/i);
|
||||
return m ? m[1].trim() : '';
|
||||
}
|
||||
|
||||
function renderTokenLoginHtml(hasError = false) {
|
||||
const errHtml = hasError
|
||||
? '<p class="err">访问令牌无效,请核对后重新输入。</p>'
|
||||
: '';
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控 · 访问验证</title>
|
||||
<style>
|
||||
:root { color-scheme: dark light; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", sans-serif;
|
||||
background: #131720;
|
||||
color: #e6ebf2;
|
||||
padding: 16px;
|
||||
}
|
||||
.card {
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
background: #1a202c;
|
||||
border: 1px solid #2b3445;
|
||||
border-radius: 6px;
|
||||
padding: 20px;
|
||||
}
|
||||
h1 { margin: 0 0 6px; font-size: 15px; font-weight: 600; }
|
||||
p { margin: 0 0 14px; font-size: 12px; color: #9aa6b8; line-height: 1.5; }
|
||||
p.err { color: #f06a6a; margin-bottom: 12px; }
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
font-size: 13px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #364156;
|
||||
background: #11151d;
|
||||
color: #e6ebf2;
|
||||
margin-bottom: 12px;
|
||||
outline: none;
|
||||
}
|
||||
input:focus { border-color: #3b82f6; }
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background: #2563eb;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { background: #1d4ed8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<form class="card" method="POST" action="/api/standalone-auth">
|
||||
<h1>Antigravity Usage Monitor</h1>
|
||||
<p>当前独立监控服务已启用访问令牌保护,请输入 Token 继续。</p>
|
||||
${errHtml}
|
||||
<input type="password" name="token" placeholder="输入 --token 访问密钥" autocomplete="current-password" required autofocus>
|
||||
<button type="submit">验证并进入面板</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析独立 Web 模式的命令行参数与环境变量。
|
||||
*
|
||||
* @param {string[]} [argv=[]]
|
||||
* @param {Record<string, string|undefined>} [env=process.env]
|
||||
* @param {{ defaultPort?: number }} [options]
|
||||
*/
|
||||
export function parseStandaloneCliArgs(argv = [], env = process.env, { defaultPort = 8787 } = {}) {
|
||||
const out = {
|
||||
help: false,
|
||||
standaloneFlag: false,
|
||||
host: String(env.USAGE_MONITOR_STANDALONE_HOST || '127.0.0.1').trim() || '127.0.0.1',
|
||||
port: null,
|
||||
portExplicit: false,
|
||||
token: String(env.USAGE_MONITOR_STANDALONE_TOKEN || '').trim(),
|
||||
lsAddr: String(env.ANTIGRAVITY_LS_ADDRESS || '').trim(),
|
||||
csrfToken: String(env.ANTIGRAVITY_CSRF_TOKEN || env.ANTIGRAVITY_SERVER_CSRF_TOKEN || '').trim(),
|
||||
dataDir: String(env.USAGE_MONITOR_DATA_DIR || '').trim(),
|
||||
appDataDir: String(env.USAGE_MONITOR_APP_DATA_DIR || env.ANTIGRAVITY_APP_DATA_DIR || '').trim(),
|
||||
geminiDir: String(env.ANTIGRAVITY_GEMINI_DIR || '').trim(),
|
||||
};
|
||||
|
||||
if (env.USAGE_MONITOR_STANDALONE_PORT !== undefined && String(env.USAGE_MONITOR_STANDALONE_PORT).trim() !== '') {
|
||||
const envPort = Number(env.USAGE_MONITOR_STANDALONE_PORT);
|
||||
if (Number.isInteger(envPort) && envPort >= 0 && envPort <= 65535) {
|
||||
out.port = envPort;
|
||||
out.portExplicit = true;
|
||||
}
|
||||
}
|
||||
|
||||
const args = Array.isArray(argv) ? argv : [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const raw = String(args[i] || '');
|
||||
if (!raw) continue;
|
||||
if (raw === '--help' || raw === '-h') {
|
||||
out.help = true;
|
||||
continue;
|
||||
}
|
||||
if (raw === '--standalone') {
|
||||
out.standaloneFlag = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
const eqIdx = raw.indexOf('=');
|
||||
const flag = eqIdx > 0 ? raw.slice(0, eqIdx) : raw;
|
||||
const readVal = () => {
|
||||
if (eqIdx > 0) return raw.slice(eqIdx + 1);
|
||||
if (i + 1 < args.length) {
|
||||
i += 1;
|
||||
return String(args[i] || '');
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
if (flag === '--port' || flag === '-p') {
|
||||
const num = Number(readVal().trim());
|
||||
if (!Number.isInteger(num) || num < 0 || num > 65535) {
|
||||
throw new Error(`Invalid --port value (expected 0..65535)`);
|
||||
}
|
||||
out.port = num;
|
||||
out.portExplicit = true;
|
||||
} else if (flag === '--host' || flag === '-H') {
|
||||
const val = readVal().trim();
|
||||
if (!val) throw new Error('Missing value for --host');
|
||||
out.host = val;
|
||||
} else if (flag === '--token') {
|
||||
out.token = readVal().trim();
|
||||
} else if (flag === '--ls-addr') {
|
||||
out.lsAddr = readVal().trim();
|
||||
} else if (flag === '--csrf-token') {
|
||||
out.csrfToken = readVal().trim();
|
||||
} else if (flag === '--data-dir') {
|
||||
out.dataDir = readVal().trim();
|
||||
} else if (flag === '--app-data-dir') {
|
||||
out.appDataDir = readVal().trim();
|
||||
} else if (flag === '--gemini-dir') {
|
||||
out.geminiDir = readVal().trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (out.port === null) {
|
||||
out.port = defaultPort;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function formatStandaloneHelpText() {
|
||||
return [
|
||||
'Antigravity Usage Monitor — Standalone Web Server (CLI / Remote Mode)',
|
||||
'',
|
||||
'Usage:',
|
||||
' node sidecars/panel/standalone.mjs [options]',
|
||||
'',
|
||||
'Options:',
|
||||
' -p, --port <port> HTTP listen port (default: 8787; 0 picks a random port)',
|
||||
' -H, --host <host> Bind address (default: 127.0.0.1)',
|
||||
' --token <secret> Access token (required when --host is non-loopback)',
|
||||
' --ls-addr <host:port> Explicit Language Server / Hub address override',
|
||||
' --csrf-token <token> Explicit Language Server CSRF token override',
|
||||
' --app-data-dir <dir> Additional product data dir (e.g. ~/.gemini/antigravity-cli)',
|
||||
' --data-dir <dir> Persistent cache & settings storage directory',
|
||||
' -h, --help Show this help message',
|
||||
'',
|
||||
'Examples:',
|
||||
' # 1) Recommended for headless Linux servers (use with ssh -L 8787:127.0.0.1:8787 user@host):',
|
||||
' node sidecars/panel/standalone.mjs --port 8787',
|
||||
'',
|
||||
' # 2) Direct LAN / reverse-proxy bind (requires --token):',
|
||||
' node sidecars/panel/standalone.mjs --host 0.0.0.0 --port 8787 --token <your-secret>',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function readRawBody(req, maxBytes = MAX_JSON_BODY_BYTES) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
let settled = false;
|
||||
req.on('data', (chunk) => {
|
||||
if (settled) return;
|
||||
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
|
||||
total += buf.length;
|
||||
if (total > maxBytes) {
|
||||
settled = true;
|
||||
const err = new Error('Payload too large');
|
||||
err.statusCode = 413;
|
||||
reject(err);
|
||||
req.resume();
|
||||
return;
|
||||
}
|
||||
chunks.push(buf);
|
||||
});
|
||||
req.on('end', () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(Buffer.concat(chunks).toString('utf8'));
|
||||
});
|
||||
req.on('error', (err) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isSameOriginPostRequest(req) {
|
||||
const secFetchSite = String(req.headers?.['sec-fetch-site'] || '').trim().toLowerCase();
|
||||
if (secFetchSite === 'cross-site') return false;
|
||||
const origin = String(req.headers?.origin || '').trim();
|
||||
if (!origin) return true;
|
||||
const host = String(req.headers?.host || '').trim().toLowerCase();
|
||||
if (!host) return false;
|
||||
try {
|
||||
const parsedOrigin = new URL(origin);
|
||||
return parsedOrigin.host.toLowerCase() === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建独立 Web 监控服务器控制器。
|
||||
*
|
||||
* @param {{
|
||||
* host?: string,
|
||||
* port?: number,
|
||||
* token?: string,
|
||||
* lsAddr?: string,
|
||||
* csrfToken?: string,
|
||||
* handleApiRequest?: typeof dispatchBridgeApiRequest,
|
||||
* readAssetFn?: typeof readLocalAsync,
|
||||
* onRestart?: (() => void) | null,
|
||||
* skipStartupDiscovery?: boolean
|
||||
* }} [options]
|
||||
*/
|
||||
export function createStandaloneWebServer(options = {}) {
|
||||
const host = String(options.host || '127.0.0.1').trim() || '127.0.0.1';
|
||||
const requestedPort = Number.isInteger(options.port) ? options.port : 8787;
|
||||
const token = String(options.token || '').trim();
|
||||
const loopbackHost = isLoopbackBindHost(host);
|
||||
|
||||
if (!loopbackHost && !token) {
|
||||
throw new Error(
|
||||
`Refusing to bind standalone server to non-loopback host "${host}" without --token <secret> (or USAGE_MONITOR_STANDALONE_TOKEN). Bind to 127.0.0.1 with SSH port forwarding (ssh -L), or configure an access token.`
|
||||
);
|
||||
}
|
||||
|
||||
if (options.lsAddr && options.csrfToken) {
|
||||
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken, { isDynamic: false });
|
||||
}
|
||||
|
||||
const expectedCookieVal = token ? deriveCookieValue(token) : '';
|
||||
const onRestart = typeof options.onRestart === 'function' ? options.onRestart : () => {};
|
||||
const handleApi =
|
||||
options.handleApiRequest ||
|
||||
((pathname, method, data) =>
|
||||
dispatchBridgeApiRequest(pathname, method, data, { onRestart }));
|
||||
const readAsset = options.readAssetFn || readLocalAsync;
|
||||
|
||||
let server = null;
|
||||
let boundPort = 0;
|
||||
|
||||
function sendResponse(res, status, contentType, body, extraHeaders = {}) {
|
||||
const payload = Buffer.isBuffer(body) ? body : Buffer.from(String(body ?? ''), 'utf8');
|
||||
res.writeHead(status, {
|
||||
'Content-Type': contentType,
|
||||
'Content-Length': payload.length,
|
||||
...NO_STORE_HEADERS,
|
||||
...extraHeaders,
|
||||
});
|
||||
res.end(payload);
|
||||
}
|
||||
|
||||
function checkRequestAuthorized(req, urlObj) {
|
||||
if (!token) {
|
||||
if (!isLoopbackRemoteAddress(req.socket?.remoteAddress)) {
|
||||
return { ok: false, status: 403, reason: 'Forbidden non-loopback client' };
|
||||
}
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return { ok: false, status: 403, reason: 'Forbidden host or origin' };
|
||||
}
|
||||
return { ok: true, viaQueryToken: false };
|
||||
}
|
||||
|
||||
const headerToken = String(req.headers?.['x-usage-monitor-token'] || '').trim();
|
||||
const bearerToken = extractBearerToken(req.headers?.authorization);
|
||||
const hasExplicitHeaderAuth =
|
||||
(headerToken && safeEqualSecret(headerToken, token)) ||
|
||||
(bearerToken && safeEqualSecret(bearerToken, token));
|
||||
|
||||
if (hasExplicitHeaderAuth) {
|
||||
return { ok: true, viaQueryToken: false };
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && !isSameOriginPostRequest(req)) {
|
||||
return { ok: false, status: 403, reason: 'Forbidden cross-origin request' };
|
||||
}
|
||||
|
||||
const cookies = parseCookies(req.headers?.cookie);
|
||||
if (cookies[AUTH_COOKIE_NAME] && safeEqualSecret(cookies[AUTH_COOKIE_NAME], expectedCookieVal)) {
|
||||
return { ok: true, viaQueryToken: false };
|
||||
}
|
||||
|
||||
if (req.method === 'GET' || req.method === 'HEAD') {
|
||||
const queryToken = urlObj.searchParams.get('token') || '';
|
||||
if (queryToken && safeEqualSecret(queryToken, token)) {
|
||||
return { ok: true, viaQueryToken: true };
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: false, status: 401, reason: 'Unauthorized: valid access token required' };
|
||||
}
|
||||
|
||||
async function handleHttpRequest(req, res) {
|
||||
try {
|
||||
const method = String(req.method || 'GET').toUpperCase();
|
||||
const rawUrl = String(req.url || '/');
|
||||
const urlObj = new URL(rawUrl, 'http://127.0.0.1');
|
||||
const pathname = urlObj.pathname || '/';
|
||||
|
||||
if (token && pathname === '/api/standalone-auth' && method === 'POST') {
|
||||
if (!isSameOriginPostRequest(req)) {
|
||||
sendResponse(res, 403, 'text/plain; charset=utf-8', 'Forbidden cross-origin request');
|
||||
return;
|
||||
}
|
||||
const formRaw = await readRawBody(req, 16 * 1024);
|
||||
const formParams = new URLSearchParams(formRaw);
|
||||
const submitted = String(formParams.get('token') || '').trim();
|
||||
if (!safeEqualSecret(submitted, token)) {
|
||||
sendResponse(res, 401, 'text/html; charset=utf-8', renderTokenLoginHtml(true));
|
||||
return;
|
||||
}
|
||||
res.writeHead(303, {
|
||||
Location: '/',
|
||||
'Set-Cookie': `${AUTH_COOKIE_NAME}=${expectedCookieVal}; HttpOnly; SameSite=Strict; Path=/`,
|
||||
...NO_STORE_HEADERS,
|
||||
});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const auth = checkRequestAuthorized(req, urlObj);
|
||||
if (!auth.ok) {
|
||||
if (auth.status === 401 && (pathname === '/' || pathname === '/index.html') && method === 'GET') {
|
||||
sendResponse(res, 401, 'text/html; charset=utf-8', renderTokenLoginHtml(false));
|
||||
return;
|
||||
}
|
||||
sendResponse(
|
||||
res,
|
||||
auth.status,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify({ error: auth.reason })
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (auth.viaQueryToken && (pathname === '/' || pathname === '/index.html') && method === 'GET') {
|
||||
urlObj.searchParams.delete('token');
|
||||
const cleanSearch = urlObj.searchParams.toString();
|
||||
const redirectTarget = cleanSearch ? `/?${cleanSearch}` : '/';
|
||||
res.writeHead(302, {
|
||||
Location: redirectTarget,
|
||||
'Set-Cookie': `${AUTH_COOKIE_NAME}=${expectedCookieVal}; HttpOnly; SameSite=Strict; Path=/`,
|
||||
...NO_STORE_HEADERS,
|
||||
});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'GET' || method === 'HEAD') {
|
||||
if (pathname === '/' || pathname === '/index.html') {
|
||||
const html = await readAsset('index.html');
|
||||
sendResponse(res, 200, 'text/html; charset=utf-8', method === 'HEAD' ? '' : html);
|
||||
return;
|
||||
}
|
||||
if (pathname === '/preload.js') {
|
||||
sendResponse(
|
||||
res,
|
||||
200,
|
||||
'application/javascript; charset=utf-8',
|
||||
method === 'HEAD' ? '' : '/* standalone web mode */\n'
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (pathname === '/app.js') {
|
||||
const js = await readAsset('app.js');
|
||||
sendResponse(res, 200, 'application/javascript; charset=utf-8', method === 'HEAD' ? '' : js);
|
||||
return;
|
||||
}
|
||||
if (pathname === '/styles.css') {
|
||||
const css = await readAsset('styles.css');
|
||||
sendResponse(res, 200, 'text/css; charset=utf-8', method === 'HEAD' ? '' : css);
|
||||
return;
|
||||
}
|
||||
if (pathname === '/favicon.ico') {
|
||||
res.writeHead(204, NO_STORE_HEADERS);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (pathname.startsWith('/api/')) {
|
||||
let data = undefined;
|
||||
if (method === 'GET') {
|
||||
data = Object.fromEntries(urlObj.searchParams.entries());
|
||||
delete data.token;
|
||||
} else if (method === 'POST') {
|
||||
const rawBody = await readRawBody(req, MAX_JSON_BODY_BYTES);
|
||||
if (rawBody.trim()) {
|
||||
try {
|
||||
data = JSON.parse(rawBody);
|
||||
} catch {
|
||||
sendResponse(
|
||||
res,
|
||||
400,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify({ error: 'Invalid JSON request body' })
|
||||
);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
data = {};
|
||||
}
|
||||
} else {
|
||||
sendResponse(
|
||||
res,
|
||||
405,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify({ error: 'Method not allowed' })
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const out = await handleApi(pathname, method, data);
|
||||
sendResponse(
|
||||
res,
|
||||
out?.status || 200,
|
||||
out?.contentType || 'application/json; charset=utf-8',
|
||||
out?.body ?? '{}',
|
||||
out?.headers || {}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
sendResponse(
|
||||
res,
|
||||
404,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify({ error: 'Not found' })
|
||||
);
|
||||
} catch (err) {
|
||||
const status = Number(err?.statusCode) || 500;
|
||||
sendResponse(
|
||||
res,
|
||||
status,
|
||||
'application/json; charset=utf-8',
|
||||
JSON.stringify({ error: err?.message || 'Internal server error' })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (server && boundPort > 0) {
|
||||
return getStatus();
|
||||
}
|
||||
if (!options.skipStartupDiscovery && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
ensureCliStatusLineConfigured({ enabled: loadSettings().enableCliStatusLine !== false });
|
||||
if (lsRuntimeEndpoint.baseUrl) {
|
||||
syncCloudCatalog({ force: false }).catch(() => {});
|
||||
} else {
|
||||
ensureLsEndpointDiscovered({ force: false })
|
||||
.then((ok) => {
|
||||
if (ok) syncCloudCatalog({ force: false }).catch(() => {});
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
const srv = http.createServer((req, res) => {
|
||||
void handleHttpRequest(req, res);
|
||||
});
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const onError = (err) => {
|
||||
srv.removeListener('listening', onListening);
|
||||
reject(err);
|
||||
};
|
||||
const onListening = () => {
|
||||
srv.removeListener('error', onError);
|
||||
resolve();
|
||||
};
|
||||
srv.once('error', onError);
|
||||
srv.once('listening', onListening);
|
||||
srv.listen(requestedPort, host);
|
||||
});
|
||||
|
||||
server = srv;
|
||||
const addrInfo = srv.address();
|
||||
boundPort = typeof addrInfo === 'object' && addrInfo ? Number(addrInfo.port || 0) : requestedPort;
|
||||
return getStatus();
|
||||
}
|
||||
|
||||
async function stop() {
|
||||
const srv = server;
|
||||
server = null;
|
||||
boundPort = 0;
|
||||
if (!srv) return;
|
||||
await new Promise((resolve) => {
|
||||
srv.close(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function getStatus() {
|
||||
const displayHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
|
||||
return {
|
||||
running: Boolean(server && boundPort > 0),
|
||||
host,
|
||||
port: boundPort,
|
||||
loopbackOnly: loopbackHost,
|
||||
tokenProtected: Boolean(token),
|
||||
url: boundPort > 0 ? `http://${displayHost}:${boundPort}` : '',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
start,
|
||||
stop,
|
||||
getStatus,
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
closeSync, fstatSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writevSync,
|
||||
} from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
let lastWrite = null;
|
||||
|
||||
function isSameFile(a, b) {
|
||||
return b.ino !== 0n && a.dev === b.dev && a.ino === b.ino &&
|
||||
a.size === b.size && a.mtimeNs === b.mtimeNs;
|
||||
}
|
||||
|
||||
function readReusableBytes(filePath, expected) {
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(filePath, 'r');
|
||||
const before = fstatSync(fd, { bigint: true });
|
||||
if (!isSameFile(before, expected) || before.ctimeNs !== expected.ctimeNs) return null;
|
||||
const bytes = readFileSync(fd);
|
||||
const after = fstatSync(fd, { bigint: true });
|
||||
return isSameFile(before, after) && before.ctimeNs === after.ctimeNs &&
|
||||
BigInt(bytes.length) === after.size ? bytes : null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
// 只复用上次确认写入的步骤字节。扫描器用新数组替换变更步骤,每次仍重新序列化会话元数据。
|
||||
export function writeTrajectoryCacheFile(filePath, data) {
|
||||
const previous = lastWrite?.filePath === filePath ? lastWrite : null;
|
||||
const bytes = previous ? readReusableBytes(filePath, previous.file) : null;
|
||||
const ranges = new WeakMap();
|
||||
const parts = [];
|
||||
let position = 0;
|
||||
function append(part) {
|
||||
const buffer = typeof part === 'string' ? Buffer.from(part) : part;
|
||||
parts.push(buffer);
|
||||
position += buffer.length;
|
||||
}
|
||||
|
||||
append('{');
|
||||
let separator = '';
|
||||
for (const [id, entry] of Object.entries(data)) {
|
||||
const { steps, ...metadata } = entry;
|
||||
const header = JSON.stringify(metadata);
|
||||
append(`${separator}${JSON.stringify(id)}:${header.slice(0, -1)}${header === '{}' ? '' : ','}"steps":`);
|
||||
const range = bytes && previous.ranges.get(steps);
|
||||
const start = position;
|
||||
append(range ? bytes.subarray(range.start, range.end) : JSON.stringify(steps));
|
||||
ranges.set(steps, { start, end: position });
|
||||
append('}');
|
||||
separator = ',';
|
||||
}
|
||||
append('}');
|
||||
|
||||
const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
const fd = openSync(temporaryPath, 'wx');
|
||||
try {
|
||||
// 按块写入,避免再复制一份完整缓存到连续缓冲区。
|
||||
const batchSize = 256;
|
||||
for (let i = 0; i < parts.length; i += batchSize) {
|
||||
const batch = parts.slice(i, i + batchSize);
|
||||
const length = batch.reduce((sum, part) => sum + part.length, 0);
|
||||
if (writevSync(fd, batch) !== length) throw new Error('Incomplete cache write');
|
||||
}
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
const written = statSync(temporaryPath, { bigint: true });
|
||||
renameSync(temporaryPath, filePath);
|
||||
const file = statSync(filePath, { bigint: true });
|
||||
lastWrite = isSameFile(written, file) ? { filePath, file, ranges } : null;
|
||||
} finally {
|
||||
try { unlinkSync(temporaryPath); } catch {}
|
||||
}
|
||||
}
|
||||
@@ -6,19 +6,25 @@
|
||||
* 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。
|
||||
*/
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import {
|
||||
MEASUREMENT_VERSION,
|
||||
accumulateSpeed,
|
||||
createSpeedAccumulator,
|
||||
finishSpeed,
|
||||
parseIsoMs,
|
||||
} from '../speed-metrics.mjs';
|
||||
import { roundMetric, trajectoryCache } from './config.mjs';
|
||||
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
||||
import {
|
||||
computeStepCost,
|
||||
formatUpstreamModelId,
|
||||
resolveModelInfo,
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
} from './model-pricing.mjs';
|
||||
|
||||
/** @typedef {ReturnType<import('./model-pricing.mjs').createStepModelResolver>} StepModelResolver */
|
||||
|
||||
function safeTok(val) {
|
||||
const n = Number(val);
|
||||
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
||||
@@ -181,27 +187,13 @@ function createUsageBucket() {
|
||||
* 将单个模型步骤的 Token 与成本累加至目标统计桶。
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
* @param {object} st 步骤对象
|
||||
* @param {ReturnType<typeof resolveModelInfo>} mInfo 模型信息
|
||||
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
||||
* @param {object} usage 已归一化的单步用量
|
||||
* @param {string} cascadeId 会话标识
|
||||
*/
|
||||
function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) {
|
||||
const inTok = safeTok(st?.inputTokens);
|
||||
const cacheTok = safeTok(st?.cacheReadTokens);
|
||||
const outTok = safeTok(st?.outputTokens);
|
||||
const thinkTok = safeTok(st?.thinkingTokens);
|
||||
const respTok =
|
||||
st?.responseTokens !== undefined && st?.responseTokens !== null
|
||||
? safeTok(st.responseTokens)
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
|
||||
const stepTotalTokens = inTok + cacheTok + outTok;
|
||||
const savedCost = mInfo?.pricing
|
||||
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||
: 0;
|
||||
if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||
function accumulateStepIntoBucket(bucket, usage, cascadeId) {
|
||||
const { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
|
||||
resolvedCost, savedCost, unpriced } = usage;
|
||||
if (unpriced) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||
bucket.calls += 1;
|
||||
if (cascadeId) bucket.conversationsSet.add(cascadeId);
|
||||
bucket.inputTokens += inTok;
|
||||
@@ -278,6 +270,8 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
ttftSumSec: 0,
|
||||
ttftSampleCount: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
@@ -290,6 +284,18 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
);
|
||||
}
|
||||
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.inputTokens += inTok;
|
||||
@@ -311,58 +317,139 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
function finalizeModelBreakdownMap(perModelStats) {
|
||||
return Array.from(perModelStats.values())
|
||||
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
||||
.map(({ speedAccumulator, upstreamModelCounts, fallbackModelId, ...m }) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([name]) => name);
|
||||
const primaryUpstream =
|
||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||
const finishedSpeed = finishSpeed(speedAccumulator);
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(3),
|
||||
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
||||
speedSummary: finishedSpeed,
|
||||
};
|
||||
});
|
||||
.map(
|
||||
({
|
||||
speedAccumulator,
|
||||
upstreamModelCounts,
|
||||
fallbackModelId,
|
||||
ttftSumSec,
|
||||
ttftSampleCount,
|
||||
...m
|
||||
}) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([name]) => name);
|
||||
const primaryUpstream =
|
||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||
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 {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(6),
|
||||
cacheHitPct,
|
||||
avgTtftSec,
|
||||
ttftSampleCount,
|
||||
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
||||
speedSummary: finishedSpeed,
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 针对给定步骤数组构建按模型聚合的统计列表(供单代理、主+子汇总及全局时间范围复用)。
|
||||
*
|
||||
* @param {object[]} [steps=[]]
|
||||
* @param {Map<string, object>} [dynamicModelMap=new Map()]
|
||||
* @param {StepModelResolver} resolveStepModel
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function buildScopedModelBreakdown(steps = [], dynamicModelMap = new Map()) {
|
||||
export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
||||
const perModelStats = new Map();
|
||||
for (const st of steps) {
|
||||
if (!st || typeof st !== 'object') continue;
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const mInfo = resolveStepModel(st);
|
||||
const stepCost = computeStepCost(st, mInfo.pricing);
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
}
|
||||
return finalizeModelBreakdownMap(perModelStats);
|
||||
}
|
||||
|
||||
let lastUsageSnapshot = null;
|
||||
const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000;
|
||||
|
||||
function planUsageTrend(window, nowMs, earliest, latest) {
|
||||
const safeMs = (value, fallback) =>
|
||||
Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback;
|
||||
const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest);
|
||||
const defaultStart = end - 24 * 3600 * 1000;
|
||||
const start = window.key === 'all'
|
||||
? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000)
|
||||
: Math.min(safeMs(window.startMs, defaultStart), end);
|
||||
const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' ||
|
||||
end - start <= 72 * 3600 * 1000;
|
||||
const first = new Date(start);
|
||||
const last = new Date(end);
|
||||
if (hourly) {
|
||||
first.setMinutes(0, 0, 0);
|
||||
last.setMinutes(0, 0, 0);
|
||||
} else {
|
||||
first.setHours(0, 0, 0, 0);
|
||||
last.setHours(0, 0, 0, 0);
|
||||
}
|
||||
return { start, end, hourly, first: first.getTime(), last: last.getTime() };
|
||||
}
|
||||
|
||||
function sameUsageEntries(previous, current) {
|
||||
return previous.length === current.length && current.every((entry, index) => {
|
||||
const before = previous[index];
|
||||
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
||||
entry.appSource === before.appSource && entry.isCurrentConv === before.isCurrentConv;
|
||||
});
|
||||
}
|
||||
|
||||
function sortedUsageTimestamps(entries) {
|
||||
const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0));
|
||||
let count = 0;
|
||||
for (const { steps } of entries) {
|
||||
for (const step of steps) {
|
||||
const date = Number(step?.createdAtMs);
|
||||
if (date > 0) dates[count++] = date;
|
||||
}
|
||||
}
|
||||
return dates.subarray(0, count).sort();
|
||||
}
|
||||
|
||||
function usageTimestampBoundary(dates, value, inclusive) {
|
||||
let start = 0;
|
||||
let end = dates.length;
|
||||
while (start < end) {
|
||||
const i = (start + end) >>> 1;
|
||||
if (dates[i] < value || (inclusive && dates[i] === value)) start = i + 1;
|
||||
else end = i;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
|
||||
function sameUsageWindows(previous, current, dates) {
|
||||
return previous.length === current.length && current.every((window, index) => {
|
||||
const before = previous[index];
|
||||
return before.key === window.key && before.label === window.label &&
|
||||
(before.startMs === window.startMs ||
|
||||
usageTimestampBoundary(dates, before.startMs, false) ===
|
||||
usageTimestampBoundary(dates, window.startMs, false)) &&
|
||||
(before.endMs === window.endMs ||
|
||||
usageTimestampBoundary(dates, before.endMs, true) ===
|
||||
usageTimestampBoundary(dates, window.endMs, true));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合所有预设时间窗口、当前选定窗口、趋势图、年度月序列、来源占比与分模型统计。
|
||||
*
|
||||
* @param {{
|
||||
* filterOpts?: { range?: string, startMs?: number, endMs?: number },
|
||||
* cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number },
|
||||
* currentAccountName?: string,
|
||||
* currentAccountName?: string|null,
|
||||
* activeCascadeId?: string|null,
|
||||
* activeFamilyCascadeIds?: Set<string>|null,
|
||||
* dynamicModelMap?: Map<string, object>
|
||||
* resolveStepModel: StepModelResolver
|
||||
* modelInputs?: { catalogRevision: number, dynamicModelMap: Map }
|
||||
* }} params
|
||||
*/
|
||||
export function aggregateMultiWindowUsage({
|
||||
@@ -371,8 +458,10 @@ export function aggregateMultiWindowUsage({
|
||||
currentAccountName = '',
|
||||
activeCascadeId = null,
|
||||
activeFamilyCascadeIds = null,
|
||||
dynamicModelMap = new Map(),
|
||||
} = {}) {
|
||||
resolveStepModel,
|
||||
quotaPoolsMap = null,
|
||||
modelInputs = null,
|
||||
}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
? Array.from(activeFamilyCascadeIds)
|
||||
@@ -399,11 +488,39 @@ export function aggregateMultiWindowUsage({
|
||||
accountBuckets[k] = createUsageBucket();
|
||||
sessionBuckets[k] = createUsageBucket();
|
||||
}
|
||||
const selectedAccountBucket = createUsageBucket();
|
||||
const selectedSessionBucket = 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 poolByModel = new Map();
|
||||
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
const selectedWindowSteps = [];
|
||||
let earliestSelectedStepMs = Infinity;
|
||||
let latestSelectedStepMs = 0;
|
||||
|
||||
const currentYear = new Date(nowMs).getFullYear();
|
||||
const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({
|
||||
@@ -445,9 +562,8 @@ export function aggregateMultiWindowUsage({
|
||||
const ownerAccount = ext.accountName || knownLive?.accountName || '';
|
||||
if (
|
||||
ownerAccount &&
|
||||
currentAccountName &&
|
||||
ownerAccount !== currentAccountName &&
|
||||
!familySet.has(extCidLower)
|
||||
currentAccountName !== '' &&
|
||||
ownerAccount !== currentAccountName
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -462,9 +578,8 @@ export function aggregateMultiWindowUsage({
|
||||
for (const [cidLower, entry] of allLiveByLower.entries()) {
|
||||
if (
|
||||
entry?.accountName &&
|
||||
currentAccountName &&
|
||||
entry.accountName !== currentAccountName &&
|
||||
!familySet.has(cidLower)
|
||||
currentAccountName !== '' &&
|
||||
entry.accountName !== currentAccountName
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -496,6 +611,33 @@ export function aggregateMultiWindowUsage({
|
||||
});
|
||||
}
|
||||
|
||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
||||
{ key: `${key}:5h`, startMs: start5hMs, endMs: nowMs },
|
||||
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
||||
]).flat();
|
||||
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
|
||||
const snapshot = lastUsageSnapshot;
|
||||
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
|
||||
currentYear === snapshot.currentYear && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
|
||||
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
|
||||
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
|
||||
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
|
||||
if (previous) {
|
||||
// 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。
|
||||
const trend = planUsageTrend(selectedWindow, nowMs, previous.earliest, previous.latest);
|
||||
if (
|
||||
trend.hourly === previous.trend.hourly && trend.first === previous.trend.first &&
|
||||
trend.last === previous.trend.last &&
|
||||
sameUsageWindows(previous.windows, windows,
|
||||
snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate))
|
||||
) {
|
||||
snapshot.ranges.delete(selectedWindow.key);
|
||||
snapshot.ranges.set(selectedWindow.key, previous);
|
||||
return { ...previous.result, selectedWindow, trendStartMs: trend.start, trendEndMs: trend.end };
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of allEntriesToAggregate) {
|
||||
const { cascadeId, isCurrentConv } = entry;
|
||||
const srcKey = entry.appSource || 'standalone';
|
||||
@@ -503,13 +645,7 @@ export function aggregateMultiWindowUsage({
|
||||
|
||||
for (const st of entry.steps || []) {
|
||||
if (!st || typeof st !== 'object') continue;
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const mInfo = resolveStepModel(st);
|
||||
const inTok = safeTok(st.inputTokens);
|
||||
const cacheTok = safeTok(st.cacheReadTokens);
|
||||
const outTok = safeTok(st.outputTokens);
|
||||
@@ -523,6 +659,11 @@ export function aggregateMultiWindowUsage({
|
||||
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||
const unpriced = stepCost === null ? 1 : 0;
|
||||
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
|
||||
const savedCost = mInfo.pricing
|
||||
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||
: 0;
|
||||
const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
|
||||
resolvedCost, savedCost, unpriced };
|
||||
|
||||
if (tMs > 0) {
|
||||
const stepDate = new Date(tMs);
|
||||
@@ -544,9 +685,36 @@ export function aggregateMultiWindowUsage({
|
||||
for (const k of presetKeys) {
|
||||
const w = presetWindows[k];
|
||||
if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) {
|
||||
accumulateStepIntoBucket(accountBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
|
||||
let cachedPool = poolByModel.get(mInfo);
|
||||
if (!cachedPool || cachedPool.key !== st.modelKey ||
|
||||
cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) {
|
||||
const ids = [st.modelKey, st.responseModel, mInfo.modelId, mInfo.label, st.modelDisplayName];
|
||||
let poolKey = null;
|
||||
if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon';
|
||||
else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon';
|
||||
else if (mInfo.family === 'Gemini') poolKey = 'Gemini';
|
||||
else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT';
|
||||
cachedPool = {
|
||||
key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName,
|
||||
bucket: poolCycleBuckets.get(poolKey),
|
||||
};
|
||||
poolByModel.set(mInfo, cachedPool);
|
||||
}
|
||||
const poolBucketEntry = cachedPool.bucket;
|
||||
if (poolBucketEntry) {
|
||||
if (tMs >= poolBucketEntry.start5hMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
|
||||
}
|
||||
if (tMs >= poolBucketEntry.startWkMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -556,12 +724,15 @@ export function aggregateMultiWindowUsage({
|
||||
(tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
||||
|
||||
if (inSelectedWindow) {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, st, mInfo, stepCost, cascadeId);
|
||||
if (selectedWindow.key === 'custom') {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
if (tMs > 0) {
|
||||
if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs;
|
||||
if (tMs > latestSelectedStepMs && tMs <= MAX_TREND_TIMESTAMP_MS) latestSelectedStepMs = tMs;
|
||||
selectedWindowSteps.push({
|
||||
tMs,
|
||||
tokens: stepTotalTokens,
|
||||
@@ -605,52 +776,15 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
|
||||
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
|
||||
const MAX_SAFE_MS = 8_640_000_000_000_000;
|
||||
const safeMs = (val, fallback) =>
|
||||
Number.isFinite(val) && val > 0 && val <= MAX_SAFE_MS ? val : fallback;
|
||||
let latestSelectedStepMs = 0;
|
||||
for (const item of selectedWindowSteps) {
|
||||
if (item.tMs > latestSelectedStepMs && item.tMs <= MAX_SAFE_MS) {
|
||||
latestSelectedStepMs = item.tMs;
|
||||
}
|
||||
}
|
||||
const baseEndMs = safeMs(selectedWindow.endMs, Math.max(nowMs, latestSelectedStepMs || nowMs));
|
||||
const trendEndMs = Math.max(baseEndMs, latestSelectedStepMs || 0);
|
||||
const rawTrendStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? safeMs(earliestSelectedStepMs, trendEndMs - 24 * 3600 * 1000)
|
||||
: safeMs(selectedWindow.startMs, trendEndMs - 24 * 3600 * 1000);
|
||||
const effectiveStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? Math.min(
|
||||
rawTrendStartMs,
|
||||
earliestSelectedStepMs < Infinity
|
||||
? safeMs(earliestSelectedStepMs, rawTrendStartMs)
|
||||
: rawTrendStartMs,
|
||||
trendEndMs - 3600 * 1000
|
||||
)
|
||||
: Math.min(rawTrendStartMs, trendEndMs);
|
||||
const trendStartMs = effectiveStartMs;
|
||||
const rawSpanMs = Math.max(3600 * 1000, trendEndMs - effectiveStartMs);
|
||||
const trend = planUsageTrend(selectedWindow, nowMs, earliestSelectedStepMs, latestSelectedStepMs);
|
||||
const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend;
|
||||
const pad2 = (n) => String(n).padStart(2, '0');
|
||||
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
||||
|
||||
// 72 小时(3 天)以内按自然整点小时分桶;超过 72 小时按本地自然日分桶
|
||||
const useHourly =
|
||||
selectedWindow.key === 'today' ||
|
||||
selectedWindow.key === '24h' ||
|
||||
selectedWindow.key === '5h' ||
|
||||
rawSpanMs <= 72 * 3600 * 1000;
|
||||
|
||||
const trendSeries = [];
|
||||
if (useHourly) {
|
||||
const startHourD = new Date(effectiveStartMs);
|
||||
startHourD.setMinutes(0, 0, 0);
|
||||
const endHourD = new Date(trendEndMs);
|
||||
endHourD.setMinutes(0, 0, 0);
|
||||
|
||||
let firstHourMs = startHourD.getTime();
|
||||
let lastHourMs = endHourD.getTime();
|
||||
let firstHourMs = trend.first;
|
||||
let lastHourMs = trend.last;
|
||||
if (selectedWindow.key === 'today') {
|
||||
const minTodayEndMs = firstHourMs + 5 * 3600 * 1000;
|
||||
if (lastHourMs < minTodayEndMs) {
|
||||
@@ -700,8 +834,8 @@ export function aggregateMultiWindowUsage({
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const firstDayMs = getStartOfLocalDayMs(effectiveStartMs);
|
||||
const lastDayMs = getStartOfLocalDayMs(trendEndMs);
|
||||
const firstDayMs = trend.first;
|
||||
const lastDayMs = trend.last;
|
||||
const dayStarts = [];
|
||||
const cursor = new Date(firstDayMs);
|
||||
cursor.setHours(0, 0, 0, 0);
|
||||
@@ -719,26 +853,24 @@ export function aggregateMultiWindowUsage({
|
||||
dayStarts.unshift(prev.getTime());
|
||||
}
|
||||
|
||||
const stepDays = dayStarts.length > 60 ? Math.ceil(dayStarts.length / 45) : 1;
|
||||
let bucketIdx = 0;
|
||||
for (let i = 0; i < dayStarts.length; i += stepDays) {
|
||||
const firstYear = new Date(dayStarts[0]).getFullYear();
|
||||
const lastYear = new Date(dayStarts[dayStarts.length - 1]).getFullYear();
|
||||
const showFullYear = firstYear !== lastYear || dayStarts.length > 90;
|
||||
|
||||
for (let i = 0; i < dayStarts.length; i++) {
|
||||
const sMs = dayStarts[i];
|
||||
const endDayStartMs = dayStarts[Math.min(dayStarts.length - 1, i + stepDays - 1)];
|
||||
const endCursor = new Date(endDayStartMs);
|
||||
const endCursor = new Date(sMs);
|
||||
endCursor.setDate(endCursor.getDate() + 1);
|
||||
endCursor.setHours(0, 0, 0, 0);
|
||||
const eMs = endCursor.getTime();
|
||||
|
||||
const sd = new Date(sMs);
|
||||
const ed = new Date(endDayStartMs);
|
||||
const axisLabel = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`;
|
||||
const fullLabel =
|
||||
stepDays === 1
|
||||
? `${sd.getMonth() + 1}月${sd.getDate()}日 (${WEEKDAY_NAMES[sd.getDay()]})`
|
||||
: `${sd.getMonth() + 1}月${sd.getDate()}日 - ${ed.getMonth() + 1}月${ed.getDate()}日`;
|
||||
const datePrefix = showFullYear ? `${sd.getFullYear()}年` : '';
|
||||
const fullLabel = `${datePrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${WEEKDAY_NAMES[sd.getDay()]})`;
|
||||
|
||||
trendSeries.push({
|
||||
index: bucketIdx++,
|
||||
index: i,
|
||||
startMs: sMs,
|
||||
endMs: eMs,
|
||||
granularity: 'day',
|
||||
@@ -758,10 +890,14 @@ export function aggregateMultiWindowUsage({
|
||||
if (trendSeries.length > 0) {
|
||||
const firstBucketStart = trendSeries[0].startMs;
|
||||
const lastIdx = trendSeries.length - 1;
|
||||
let previousBucketIndex = 0;
|
||||
for (const item of selectedWindowSteps) {
|
||||
let targetIdx = lastIdx;
|
||||
const previousBucket = trendSeries[previousBucketIndex];
|
||||
if (item.tMs <= firstBucketStart) {
|
||||
targetIdx = 0;
|
||||
} else if (item.tMs >= previousBucket.startMs && item.tMs < previousBucket.endMs) {
|
||||
targetIdx = previousBucketIndex;
|
||||
} else {
|
||||
// 二分查找匹配的时间桶 [startMs, endMs)
|
||||
let lo = 0;
|
||||
@@ -779,6 +915,7 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
}
|
||||
}
|
||||
previousBucketIndex = targetIdx;
|
||||
const bucket = trendSeries[targetIdx];
|
||||
bucket.tokens += item.tokens;
|
||||
bucket.inputTokens += item.inputTokens || 0;
|
||||
@@ -817,7 +954,45 @@ export function aggregateMultiWindowUsage({
|
||||
const weekBucket = finalizedPresets.week.account;
|
||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||
|
||||
return {
|
||||
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;
|
||||
|
||||
const result = {
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
trendEndMs,
|
||||
@@ -831,5 +1006,22 @@ export function aggregateMultiWindowUsage({
|
||||
todayBucket,
|
||||
weekBucket,
|
||||
modelBreakdown,
|
||||
poolCycleStats,
|
||||
poolsWeeklySummary,
|
||||
};
|
||||
if (modelInputs) {
|
||||
if (!sameSnapshot) {
|
||||
lastUsageSnapshot = {
|
||||
timeZone, modelInputs, currentYear, entries: allEntriesToAggregate, dates: null, ranges: new Map(),
|
||||
};
|
||||
}
|
||||
const { ranges } = lastUsageSnapshot;
|
||||
ranges.delete(selectedWindow.key);
|
||||
ranges.set(selectedWindow.key, {
|
||||
windows, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs,
|
||||
});
|
||||
// 侧栏和悬浮窗可同时查看不同范围,共用时间索引并最多保留两份聚合结果。
|
||||
if (ranges.size > 2) ranges.delete(ranges.keys().next().value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* @fileoverview Antigravity IDE / 2.0 / CLI 独立后台守护进程 (`bridge-daemon.mjs`)。
|
||||
*
|
||||
* 由 `mcp-entry.mjs` 托管拉起(亦支持命令行 `--standalone` 直接启动),负责:
|
||||
* 1. 动态探测本机运行中的 `agy` (`daemon/hub_*.json` / `--hub` / `remote-control`) 或 `language_server` 端点;
|
||||
* 2. 在桌面端 / IDE 环境启动本地回环桥接服务并通过 CDP 挂载监控胶囊;
|
||||
* 3. 当配置了 `USAGE_MONITOR_STANDALONE_PORT` 或 `settings.json` 中的 `standalonePort`(`1024..65535`)时,
|
||||
* 自动在后台托管独立 Web 监控端口,无需手工另开进程;
|
||||
* 4. 收到父进程 `SHUTDOWN_DISPOSE` 指令或终止信号时,主动清理窗口浮层与独立端口并平滑退出。
|
||||
*/
|
||||
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
bootBundleVersion,
|
||||
bootWindowBridgeRuntime,
|
||||
setStandalonePortListener,
|
||||
} from './backend/api-actions.mjs';
|
||||
import {
|
||||
computeRuntimeCodeVersion,
|
||||
loadSettings,
|
||||
normalizeStandalonePort,
|
||||
} from './backend/config.mjs';
|
||||
import {
|
||||
createStandaloneWebServer,
|
||||
parseStandaloneCliArgs,
|
||||
} from './backend/standalone-server.mjs';
|
||||
import { runStandaloneCli } from './standalone.mjs';
|
||||
|
||||
export function startBridgeDaemon() {
|
||||
let shuttingDown = false;
|
||||
let sawShutdownDispose = false;
|
||||
let stdinBuf = '';
|
||||
let standaloneController = null;
|
||||
let activeStandalonePort = 0;
|
||||
let reconcileChain = Promise.resolve();
|
||||
|
||||
const envArgs = parseStandaloneCliArgs([], process.env, { defaultPort: 0 });
|
||||
const envPinnedPort = envArgs.portExplicit ? normalizeStandalonePort(envArgs.port) : null;
|
||||
|
||||
const triggerRestart = () => {
|
||||
void shutdown({ disposeWindows: false, exitCode: 0 });
|
||||
};
|
||||
|
||||
const controller = bootWindowBridgeRuntime({
|
||||
allowDynamicLs: true,
|
||||
onRestart: triggerRestart,
|
||||
});
|
||||
|
||||
const driftWatchTimer = setInterval(() => {
|
||||
if (shuttingDown) return;
|
||||
try {
|
||||
const diskVersion = String(computeRuntimeCodeVersion() || '');
|
||||
if (bootBundleVersion && diskVersion && diskVersion !== String(bootBundleVersion)) {
|
||||
triggerRestart();
|
||||
}
|
||||
} catch {
|
||||
// 忽略文件覆盖期间瞬态 stat 异常
|
||||
}
|
||||
}, 3000);
|
||||
driftWatchTimer.unref?.();
|
||||
|
||||
function resolveDesiredStandalonePort(settingsOverride = null) {
|
||||
if (envPinnedPort !== null) {
|
||||
return envPinnedPort;
|
||||
}
|
||||
const settings = settingsOverride || loadSettings();
|
||||
return normalizeStandalonePort(settings?.standalonePort);
|
||||
}
|
||||
|
||||
function scheduleStandaloneReconcile(targetPort) {
|
||||
reconcileChain = reconcileChain
|
||||
.then(async () => {
|
||||
if (shuttingDown) return;
|
||||
const nextPort = normalizeStandalonePort(targetPort);
|
||||
if (nextPort === activeStandalonePort && standaloneController) {
|
||||
return;
|
||||
}
|
||||
if (standaloneController) {
|
||||
const prev = standaloneController;
|
||||
standaloneController = null;
|
||||
activeStandalonePort = 0;
|
||||
await prev.stop().catch(() => {});
|
||||
}
|
||||
if (nextPort <= 0 || shuttingDown) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const srv = createStandaloneWebServer({
|
||||
host: envArgs.host,
|
||||
port: nextPort,
|
||||
token: envArgs.token,
|
||||
onRestart: triggerRestart,
|
||||
skipStartupDiscovery: true,
|
||||
});
|
||||
const status = await srv.start();
|
||||
standaloneController = srv;
|
||||
activeStandalonePort = nextPort;
|
||||
console.error(`[usage-monitor] Auto-hosted standalone Web UI at ${status.url}`);
|
||||
} catch (err) {
|
||||
if (err?.code === 'EADDRINUSE') {
|
||||
console.error(
|
||||
`[usage-monitor] Standalone port ${nextPort} already in use; keeping existing listener.`
|
||||
);
|
||||
} else {
|
||||
console.error(`[usage-monitor] Auto-hosted standalone server skipped: ${err.message}`);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
setStandalonePortListener((updatedPort) => {
|
||||
if (envPinnedPort === null) {
|
||||
scheduleStandaloneReconcile(updatedPort);
|
||||
}
|
||||
});
|
||||
scheduleStandaloneReconcile(resolveDesiredStandalonePort());
|
||||
|
||||
async function shutdown({ disposeWindows = false, exitCode = 0 } = {}) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
clearInterval(driftWatchTimer);
|
||||
setStandalonePortListener(null);
|
||||
const forceTimer = setTimeout(() => {
|
||||
process.exit(exitCode);
|
||||
}, 1500);
|
||||
forceTimer.unref?.();
|
||||
try {
|
||||
await Promise.allSettled([
|
||||
controller?.stop?.({ disposeWindows }),
|
||||
standaloneController?.stop?.(),
|
||||
]);
|
||||
} 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)) {
|
||||
const cliArgs = process.argv.slice(2);
|
||||
if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) {
|
||||
void runStandaloneCli(cliArgs);
|
||||
} else {
|
||||
startBridgeDaemon();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
/**
|
||||
* @fileoverview Antigravity CLI (`agy`) 轻量底部状态栏入口 (`cli-statusline.mjs`)。
|
||||
*
|
||||
* 由 `agy` TUI 在会话状态变更时通过 `statusLine` 配置拉起(300ms 节流,stdin 传入 `StatusLineData` JSON):
|
||||
* 1. 秒级合并三路数据源:
|
||||
* - `stdin` 实时状态(`agent_state`、`context_window.used_percentage`、`cost`、`subagents`、`cwd`);
|
||||
* - `~/.gemini/antigravity-cli/conversations/<cid>.db` 最新一步的纳秒级 `TPS` / `TTFT` / 缓存命中率;
|
||||
* - `DATA_DIR/cli-status-snapshot.json` 中的官方配额池余量与跨端在线会话计数;
|
||||
* 2. 联动用户偏好设置中的胶囊槽位顺序(`topbarCapsuleSlots`)与开关(`enableCliStatusLine`),
|
||||
* 向 `stdout` 输出单行 24-bit ANSI 状态胶囊。
|
||||
*
|
||||
* 同时支持手动管理命令:
|
||||
* - `node sidecars/panel/cli-statusline.mjs --install`
|
||||
* - `node sidecars/panel/cli-statusline.mjs --uninstall`
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, statSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
extractModelSteps,
|
||||
speedMetric,
|
||||
summarizeSpeed,
|
||||
summarizeTtft,
|
||||
} from './speed-metrics.mjs';
|
||||
import {
|
||||
getNodeSqliteDatabaseSync,
|
||||
readLocalSqliteTrajectory,
|
||||
readLocalSummaryIndex,
|
||||
} from './backend/cli-sqlite-reader.mjs';
|
||||
import {
|
||||
ensureCliStatusLineConfigured,
|
||||
formatCliStatusLineCapsule,
|
||||
} from './backend/cli-statusline-config.mjs';
|
||||
import {
|
||||
CLI_STATUS_SNAPSHOT_FILE,
|
||||
loadJson,
|
||||
loadSettings,
|
||||
} from './backend/config.mjs';
|
||||
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
||||
|
||||
const CLI_RUNNING_STALE_MS = 10 * 60 * 1000;
|
||||
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
||||
const SNAPSHOT_QUOTA_TTL_MS = 6 * 3600 * 1000;
|
||||
|
||||
function loadFreshestCliStatusSnapshot(geminiBase) {
|
||||
if (String(process.env.USAGE_MONITOR_DATA_DIR || '').trim()) {
|
||||
return loadJson(CLI_STATUS_SNAPSHOT_FILE, null);
|
||||
}
|
||||
const candidates = [
|
||||
CLI_STATUS_SNAPSHOT_FILE,
|
||||
join(geminiBase, 'antigravity', 'sidecar_data', 'usage-monitor', 'panel', 'data', 'cli-status-snapshot.json'),
|
||||
join(geminiBase, 'antigravity-cli', 'sidecar_data', 'usage-monitor', 'panel', 'data', 'cli-status-snapshot.json'),
|
||||
];
|
||||
let best = null;
|
||||
let bestTs = -1;
|
||||
const seen = new Set();
|
||||
for (const file of candidates) {
|
||||
const key = process.platform === 'win32' ? file.toLowerCase() : file;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
const snap = loadJson(file, null);
|
||||
if (!snap || typeof snap !== 'object') continue;
|
||||
const ts = Number.isFinite(Number(snap.updatedAtMs)) ? Number(snap.updatedAtMs) : 0;
|
||||
if (!best || ts > bestTs) {
|
||||
best = snap;
|
||||
bestTs = ts;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function readStdinJsonWithTimeout(timeoutMs = 220) {
|
||||
if (process.stdin.isTTY) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
return new Promise((resolveDone) => {
|
||||
const chunks = [];
|
||||
let settled = false;
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
process.stdin.pause();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
||||
if (!raw) {
|
||||
resolveDone(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
resolveDone(parsed && typeof parsed === 'object' ? parsed : null);
|
||||
} catch {
|
||||
resolveDone(null);
|
||||
}
|
||||
};
|
||||
const timer = setTimeout(finish, timeoutMs);
|
||||
timer.unref?.();
|
||||
process.stdin.on('data', (chunk) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8'));
|
||||
});
|
||||
process.stdin.on('end', finish);
|
||||
process.stdin.on('error', finish);
|
||||
process.stdin.resume();
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePathForMatch(rawPath) {
|
||||
const clean = String(rawPath || '')
|
||||
.trim()
|
||||
.replace(/^file:\/\/\/?/i, '')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\/+$/, '');
|
||||
return process.platform === 'win32' ? clean.toLowerCase() : clean;
|
||||
}
|
||||
|
||||
function extractConversationIdFromStdin(stdinData) {
|
||||
if (!stdinData || typeof stdinData !== 'object') return '';
|
||||
const direct = String(
|
||||
stdinData.conversation_id ||
|
||||
stdinData.conversationId ||
|
||||
stdinData.session_id ||
|
||||
stdinData.sessionId ||
|
||||
process.env.ANTIGRAVITY_CONVERSATION_ID ||
|
||||
''
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(direct)) {
|
||||
return direct;
|
||||
}
|
||||
const transcriptPath = String(stdinData.transcript_path || stdinData.transcriptPath || '');
|
||||
const m = transcriptPath.match(
|
||||
/[\\/]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[\\/]/i
|
||||
);
|
||||
return m ? m[1].toLowerCase() : '';
|
||||
}
|
||||
|
||||
function findConversationIdByWorkspaceFts(cliRoot, cwd) {
|
||||
if (!cwd) return '';
|
||||
const summariesDbPath = join(cliRoot, 'conversation_summaries.db');
|
||||
if (!existsSync(summariesDbPath)) return '';
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return '';
|
||||
|
||||
const normCwd = normalizePathForMatch(cwd);
|
||||
if (!normCwd) return '';
|
||||
|
||||
let db = null;
|
||||
try {
|
||||
db = new DatabaseSync(summariesDbPath, { readOnly: true });
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT conversation_id, workspace, last_modified_time
|
||||
FROM conversations_fts
|
||||
WHERE chunk_index = -1
|
||||
ORDER BY last_modified_time DESC
|
||||
LIMIT 40`
|
||||
)
|
||||
.all();
|
||||
for (const row of rows || []) {
|
||||
const ws = normalizePathForMatch(row?.workspace);
|
||||
const cid = String(row?.conversation_id || '').trim().toLowerCase();
|
||||
if (cid && ws && ws === normCwd) {
|
||||
return cid;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略不存在 conversations_fts 表或读取失败
|
||||
} finally {
|
||||
if (db) {
|
||||
try {
|
||||
db.close();
|
||||
} catch {
|
||||
// 忽略关闭异常
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前 CLI 窗口对应的本地 `.db` 会话轨迹并计算最新测速、延迟、缓存与成本指标。
|
||||
*
|
||||
* @param {{ cliRoot: string, stdinData?: object|null, nowMs?: number }} params
|
||||
*/
|
||||
export function resolveCliLocalSessionMetrics({
|
||||
cliRoot,
|
||||
stdinData = null,
|
||||
nowMs = Date.now(),
|
||||
}) {
|
||||
const convDir = join(cliRoot, 'conversations');
|
||||
const summariesMap = existsSync(cliRoot) ? readLocalSummaryIndex([cliRoot]) : new Map();
|
||||
|
||||
let runningRootCount = 0;
|
||||
let runningSubCount = 0;
|
||||
for (const summary of summariesMap.values()) {
|
||||
const isFreshRunning =
|
||||
summary.status === 'CASCADE_RUN_STATUS_RUNNING' &&
|
||||
summary.lastModifiedMs > 0 &&
|
||||
nowMs - summary.lastModifiedMs <= CLI_RUNNING_STALE_MS;
|
||||
if (!isFreshRunning) continue;
|
||||
if (summary.parentConversationId) runningSubCount += 1;
|
||||
else runningRootCount += 1;
|
||||
}
|
||||
|
||||
if (!existsSync(convDir)) {
|
||||
return {
|
||||
found: false,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
};
|
||||
}
|
||||
|
||||
let targetCid = extractConversationIdFromStdin(stdinData);
|
||||
if (!targetCid && stdinData?.cwd) {
|
||||
const ftsCid = findConversationIdByWorkspaceFts(cliRoot, stdinData.cwd);
|
||||
if (ftsCid && existsSync(join(convDir, `${ftsCid}.db`))) {
|
||||
targetCid = ftsCid;
|
||||
}
|
||||
}
|
||||
|
||||
let dbPath = targetCid ? join(convDir, `${targetCid}.db`) : '';
|
||||
if (!dbPath || !existsSync(dbPath)) {
|
||||
let candidates = [];
|
||||
try {
|
||||
candidates = readdirSync(convDir)
|
||||
.filter((name) => name.endsWith('.db'))
|
||||
.map((name) => {
|
||||
const cid = name.slice(0, -3).toLowerCase();
|
||||
const full = join(convDir, name);
|
||||
let mtimeMs = 0;
|
||||
try {
|
||||
mtimeMs = statSync(full).mtimeMs || 0;
|
||||
} catch {
|
||||
// 忽略单文件 stat 异常
|
||||
}
|
||||
const summary = summariesMap.get(cid);
|
||||
return {
|
||||
cid,
|
||||
full,
|
||||
mtimeMs,
|
||||
isSubagent: Boolean(summary?.parentConversationId),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
||||
} catch {
|
||||
candidates = [];
|
||||
}
|
||||
|
||||
const picked = candidates.find((c) => !c.isSubagent) || candidates[0];
|
||||
if (picked) {
|
||||
targetCid = picked.cid;
|
||||
dbPath = picked.full;
|
||||
}
|
||||
}
|
||||
|
||||
if (!dbPath || !existsSync(dbPath)) {
|
||||
return {
|
||||
found: false,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
};
|
||||
}
|
||||
|
||||
let traj = readLocalSqliteTrajectory(dbPath);
|
||||
if (traj?.parentConversationId) {
|
||||
const rootDb = join(convDir, `${traj.rootConversationId || traj.parentConversationId}.db`);
|
||||
if (existsSync(rootDb)) {
|
||||
const rootTraj = readLocalSqliteTrajectory(rootDb);
|
||||
if (rootTraj) {
|
||||
targetCid = traj.rootConversationId || traj.parentConversationId;
|
||||
traj = rootTraj;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) {
|
||||
return {
|
||||
found: false,
|
||||
cascadeId: targetCid,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
};
|
||||
}
|
||||
|
||||
const steps = extractModelSteps(traj.steps, traj.generatorMetadata || []);
|
||||
if (steps.length === 0) {
|
||||
return {
|
||||
found: false,
|
||||
cascadeId: targetCid,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
};
|
||||
}
|
||||
|
||||
const resolveStepModel = createStepModelResolver(new Map());
|
||||
let totalInputTokens = 0;
|
||||
let totalCacheReadTokens = 0;
|
||||
let totalOutputTokens = 0;
|
||||
let sessionCostUsd = 0;
|
||||
let hasPricedStep = false;
|
||||
let latestStepCostUsd = null;
|
||||
let latestCacheHitPct = null;
|
||||
let latestPromptTokens = null;
|
||||
let latestContextTokens = 0;
|
||||
let latestLimitTokens = 0;
|
||||
let latestTps = null;
|
||||
let latestTtft = null;
|
||||
|
||||
for (const step of steps) {
|
||||
const inTok = Math.max(0, Number(step.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(step.cacheReadTokens || 0));
|
||||
const outTok = Math.max(0, Number(step.outputTokens || 0));
|
||||
const promptTok = inTok + cacheTok;
|
||||
|
||||
totalInputTokens += inTok;
|
||||
totalCacheReadTokens += cacheTok;
|
||||
totalOutputTokens += outTok;
|
||||
|
||||
const modelInfo = resolveStepModel(step);
|
||||
const stepUsd = computeStepCost(step, modelInfo?.pricing || null);
|
||||
if (stepUsd !== null && Number.isFinite(stepUsd)) {
|
||||
sessionCostUsd += stepUsd;
|
||||
latestStepCostUsd = stepUsd;
|
||||
hasPricedStep = true;
|
||||
} else {
|
||||
latestStepCostUsd = null;
|
||||
}
|
||||
|
||||
if (promptTok > 0) {
|
||||
latestCacheHitPct = +((cacheTok / promptTok) * 100).toFixed(1);
|
||||
}
|
||||
latestPromptTokens = promptTok;
|
||||
latestContextTokens =
|
||||
Number(step.estimatedContextTokens || 0) > 0
|
||||
? Number(step.estimatedContextTokens)
|
||||
: promptTok + outTok;
|
||||
if (Number(step.maxContextBudgetTokens || 0) > 0) {
|
||||
latestLimitTokens = Number(step.maxContextBudgetTokens);
|
||||
}
|
||||
|
||||
if (!step.isCompactionStep) {
|
||||
const sm = speedMetric(step);
|
||||
if (sm.value !== null && Number.isFinite(sm.value)) {
|
||||
latestTps = +sm.value.toFixed(1);
|
||||
}
|
||||
if (step.ttftSec !== null && Number.isFinite(step.ttftSec) && step.ttftSec >= 0) {
|
||||
latestTtft = step.ttftSec;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const speedSum = summarizeSpeed(steps);
|
||||
const ttftSum = summarizeTtft(steps);
|
||||
const totalPromptAll = totalInputTokens + totalCacheReadTokens;
|
||||
const sessionCacheHitPct =
|
||||
totalPromptAll > 0 ? +((totalCacheReadTokens / totalPromptAll) * 100).toFixed(1) : null;
|
||||
|
||||
return {
|
||||
found: true,
|
||||
cascadeId: targetCid,
|
||||
stepCount: steps.length,
|
||||
runningRootCount,
|
||||
runningSubCount,
|
||||
tps: latestTps,
|
||||
avgTps: speedSum?.avgTokPerSec != null ? +speedSum.avgTokPerSec.toFixed(1) : null,
|
||||
ttft: latestTtft ?? ttftSum?.avgSec ?? null,
|
||||
stepCost: latestStepCostUsd,
|
||||
sessionCost: hasPricedStep ? sessionCostUsd : null,
|
||||
cacheHitPct: latestCacheHitPct ?? sessionCacheHitPct,
|
||||
latestPromptTokens,
|
||||
sessionTokens: totalInputTokens + totalCacheReadTokens + totalOutputTokens,
|
||||
usedPct:
|
||||
latestLimitTokens > 0 && latestContextTokens > 0
|
||||
? Math.min(100, +((latestContextTokens / latestLimitTokens) * 100).toFixed(1))
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildStdinFallbackQuotas(stdinData) {
|
||||
const rawQuota = stdinData?.quota;
|
||||
if (!rawQuota || typeof rawQuota !== 'object' || Array.isArray(rawQuota)) {
|
||||
return null;
|
||||
}
|
||||
const pools = [];
|
||||
for (const [key, bucket] of Object.entries(rawQuota)) {
|
||||
if (!bucket || typeof bucket !== 'object' || bucket.disabled) continue;
|
||||
const frac = Number(bucket.remaining_fraction);
|
||||
if (!Number.isFinite(frac)) continue;
|
||||
const remainingPct = Math.max(0, Math.min(100, Math.round(frac * 100)));
|
||||
const isThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(key);
|
||||
pools.push({
|
||||
poolKey: isThirdParty ? 'Claude & GPT' : 'Gemini',
|
||||
poolLabel: key,
|
||||
family: isThirdParty ? 'claude' : 'gemini',
|
||||
remainingPct,
|
||||
});
|
||||
}
|
||||
if (pools.length === 0) return null;
|
||||
const modelStr = String(stdinData?.model?.id || stdinData?.model?.display_name || '');
|
||||
const activeIsThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(modelStr);
|
||||
const matchingPools = pools.filter((p) =>
|
||||
activeIsThirdParty ? p.poolKey === 'Claude & GPT' : p.poolKey === 'Gemini'
|
||||
);
|
||||
const activePool = (matchingPools.length > 0 ? matchingPools : pools).reduce((minP, cur) =>
|
||||
cur.remainingPct < minP.remainingPct ? cur : minP
|
||||
);
|
||||
return {
|
||||
activePool,
|
||||
pools,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 融合 `stdin` (`StatusLineData`)、本地 CLI SQLite 步骤指标与后台守护配额快照,生成胶囊上下文。
|
||||
*/
|
||||
export function buildMergedCliCapsuleContext({
|
||||
stdinData = null,
|
||||
localMetrics = null,
|
||||
snapshot = null,
|
||||
nowMs = Date.now(),
|
||||
} = {}) {
|
||||
const agentState = String(stdinData?.agent_state || '').trim().toLowerCase();
|
||||
const stdinIsRunning =
|
||||
agentState === 'running' ||
|
||||
agentState === 'streaming' ||
|
||||
agentState === 'executing' ||
|
||||
agentState === 'thinking';
|
||||
const stdinIsWaiting = agentState === 'waiting' || agentState === 'awaiting_approval';
|
||||
|
||||
const stdinSubagents = Array.isArray(stdinData?.subagents)
|
||||
? stdinData.subagents.filter((s) => {
|
||||
const st = String(s?.state || s?.status || '').toUpperCase();
|
||||
return !st.includes('KILLED') && !st.includes('DONE') && !st.includes('COMPLETED');
|
||||
}).length
|
||||
: 0;
|
||||
|
||||
const snapAgeMs =
|
||||
snapshot && Number.isFinite(Number(snapshot.updatedAtMs))
|
||||
? Math.max(0, nowMs - Number(snapshot.updatedAtMs))
|
||||
: Infinity;
|
||||
const snapLiveFresh = snapAgeMs <= SNAPSHOT_LIVE_RUNNING_TTL_MS;
|
||||
const snapQuotaFresh = snapAgeMs <= SNAPSHOT_QUOTA_TTL_MS;
|
||||
|
||||
const baseRunning = snapLiveFresh
|
||||
? Math.max(0, Number(snapshot?.runningCount || 0))
|
||||
: Math.max(0, Number(localMetrics?.runningRootCount || 0));
|
||||
const runningCount =
|
||||
stdinIsRunning || stdinIsWaiting ? Math.max(1, baseRunning) : baseRunning;
|
||||
|
||||
const baseSubRunning = snapLiveFresh
|
||||
? Math.max(0, Number(snapshot?.runningSubCount || 0))
|
||||
: Math.max(0, Number(localMetrics?.runningSubCount || 0));
|
||||
const runningSubCount = Math.max(stdinSubagents, baseSubRunning);
|
||||
const hasWaiting = stdinIsWaiting || Boolean(snapLiveFresh && snapshot?.hasWaiting);
|
||||
|
||||
const stdinUsedPct = stdinData?.context_window?.used_percentage;
|
||||
const usedPct =
|
||||
stdinUsedPct != null && Number.isFinite(Number(stdinUsedPct))
|
||||
? Math.max(0, Math.min(100, Number(stdinUsedPct)))
|
||||
: localMetrics?.usedPct ?? (snapLiveFresh ? snapshot?.activeConversation?.usedPct ?? null : null);
|
||||
|
||||
const stdinTotalUsd = stdinData?.cost?.total_usd;
|
||||
const sessionCost =
|
||||
localMetrics?.sessionCost != null
|
||||
? localMetrics.sessionCost
|
||||
: stdinTotalUsd != null && Number.isFinite(Number(stdinTotalUsd))
|
||||
? Number(stdinTotalUsd)
|
||||
: null;
|
||||
|
||||
const stdinInTok = Number(stdinData?.context_window?.total_input_tokens);
|
||||
const stdinOutTok = Number(stdinData?.context_window?.total_output_tokens);
|
||||
const stdinSessionTokens =
|
||||
Number.isFinite(stdinInTok) || Number.isFinite(stdinOutTok)
|
||||
? Math.max(0, (Number.isFinite(stdinInTok) ? stdinInTok : 0) + (Number.isFinite(stdinOutTok) ? stdinOutTok : 0))
|
||||
: null;
|
||||
|
||||
const snapActive =
|
||||
snapLiveFresh &&
|
||||
snapshot?.activeConversation &&
|
||||
(!localMetrics?.cascadeId || snapshot.activeConversation.cascadeId === localMetrics.cascadeId)
|
||||
? snapshot.activeConversation
|
||||
: null;
|
||||
|
||||
const mergedQuotas =
|
||||
(snapQuotaFresh && snapshot?.quotas) || buildStdinFallbackQuotas(stdinData) || null;
|
||||
|
||||
const hasTelemetry = Boolean(
|
||||
stdinData || localMetrics?.found || snapActive || mergedQuotas
|
||||
);
|
||||
|
||||
return {
|
||||
hasTelemetry,
|
||||
isRunning: stdinIsRunning || stdinIsWaiting,
|
||||
hasWaiting,
|
||||
runningCount,
|
||||
runningSubCount,
|
||||
usedPct,
|
||||
tps: localMetrics?.tps ?? snapActive?.latestTokPerSec ?? null,
|
||||
avgTps: localMetrics?.avgTps ?? snapActive?.avgTokPerSec ?? null,
|
||||
ttft: localMetrics?.ttft ?? snapActive?.latestTtftSec ?? null,
|
||||
stepCost: localMetrics?.stepCost ?? snapActive?.latestStepCostUsd ?? null,
|
||||
sessionCost: sessionCost ?? snapActive?.sessionCostUsd ?? null,
|
||||
cacheHitPct: localMetrics?.cacheHitPct ?? snapActive?.latestCacheHitPct ?? null,
|
||||
latestPromptTokens: localMetrics?.latestPromptTokens ?? snapActive?.latestPromptTokens ?? null,
|
||||
sessionTokens:
|
||||
localMetrics?.sessionTokens ?? stdinSessionTokens ?? snapActive?.totalTokens ?? null,
|
||||
quotas: mergedQuotas,
|
||||
};
|
||||
}
|
||||
|
||||
export async function runCliStatusLineMain(argv = process.argv.slice(2)) {
|
||||
if (argv.includes('--install')) {
|
||||
const res = ensureCliStatusLineConfigured({ enabled: true });
|
||||
process.stdout.write(`${JSON.stringify(res)}\n`);
|
||||
return;
|
||||
}
|
||||
if (argv.includes('--uninstall')) {
|
||||
const res = ensureCliStatusLineConfigured({ enabled: false });
|
||||
process.stdout.write(`${JSON.stringify(res)}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
const settings = loadSettings();
|
||||
if (settings?.enableCliStatusLine === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
const stdinData = await readStdinJsonWithTimeout(220);
|
||||
const nowMs = Date.now();
|
||||
const geminiBase =
|
||||
String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homedir(), '.gemini');
|
||||
const cliRoot = join(geminiBase, 'antigravity-cli');
|
||||
|
||||
const localMetrics = resolveCliLocalSessionMetrics({
|
||||
cliRoot,
|
||||
stdinData,
|
||||
nowMs,
|
||||
});
|
||||
const snapshot = loadFreshestCliStatusSnapshot(geminiBase);
|
||||
const slotCtx = buildMergedCliCapsuleContext({
|
||||
stdinData,
|
||||
localMetrics,
|
||||
snapshot,
|
||||
nowMs,
|
||||
});
|
||||
|
||||
const terminalWidth = Number(stdinData?.terminal_width);
|
||||
let modelDisplayName = String(
|
||||
stdinData?.model?.display_name || stdinData?.model?.id || ''
|
||||
).trim();
|
||||
if (!modelDisplayName && terminalWidth > 0) {
|
||||
const cliSettingsObj = loadJson(join(cliRoot, 'settings.json'), null);
|
||||
if (cliSettingsObj && typeof cliSettingsObj.model === 'string') {
|
||||
modelDisplayName = cliSettingsObj.model.trim();
|
||||
}
|
||||
}
|
||||
|
||||
const useColor =
|
||||
!Object.prototype.hasOwnProperty.call(process.env, 'NO_COLOR') ||
|
||||
String(process.env.NO_COLOR || '') === '';
|
||||
const line = formatCliStatusLineCapsule(slotCtx, {
|
||||
slots: settings?.topbarCapsuleSlots,
|
||||
showMultiSession: settings?.showTopbarMultiSession !== false,
|
||||
language: settings?.language,
|
||||
color: useColor,
|
||||
terminalWidth: Number.isFinite(terminalWidth) && terminalWidth > 0 ? terminalWidth : 0,
|
||||
cycleMode: typeof stdinData?.cycle_mode === 'string' ? stdinData.cycle_mode : '',
|
||||
modelDisplayName,
|
||||
modelEffort: typeof stdinData?.model?.effort === 'string' ? stdinData.model.effort : '',
|
||||
vimMode: typeof stdinData?.vim?.mode === 'string' ? stdinData.vim.mode : '',
|
||||
});
|
||||
|
||||
if (line) {
|
||||
process.stdout.write(`${line}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
||||
const isDirectEntry =
|
||||
(invokedPath && invokedPath === fileURLToPath(import.meta.url)) ||
|
||||
import.meta.url.endsWith('#autorun');
|
||||
if (isDirectEntry) {
|
||||
runCliStatusLineMain().catch(() => {
|
||||
// 严格保证静默退出 0,绝不触发 CLI 连续 30 次失败熔断器
|
||||
process.exitCode = 0;
|
||||
});
|
||||
}
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1794565164880">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794819376795">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794565164880"></script>
|
||||
<script src="/app.js?v=1794819376795"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+170
-314
@@ -2,111 +2,179 @@
|
||||
* @fileoverview Antigravity Usage Monitor 面板 Sidecar HTTP 服务入口。
|
||||
*
|
||||
* 职责边界:
|
||||
* - 提供前端静态资产路由(`/`、`/app.js`、`/styles.css`);
|
||||
* - 提供严格同端口 Loopback 受保护的 JSON API 路由:
|
||||
* - `GET /api/telemetry`:获取实时配额、当前会话指标与历史聚合遥测数据;
|
||||
* - `POST /api/settings`:保存用户偏好设置(写入失败时返回 HTTP 500);
|
||||
* - `POST /api/cloud-sync`:立即从 GitHub 同步最新云端价格目录与版本信息;
|
||||
* - `POST /api/plugin-update`:一键执行插件自更新(Git / Release ZIP 双通道);
|
||||
* - 所有核心业务逻辑均已模块化拆分至 `./backend/*.mjs`。
|
||||
* - 提供前端静态资产路由(`/`、`/app.js`、`/styles.css`,每次请求从磁盘读取最新产物);
|
||||
* - 提供严格同端口 Loopback 受保护的 JSON API 路由;
|
||||
* - 在真实宿主环境中通过 `node:worker_threads` 托管 `./backend/sidecar-worker.mjs`:
|
||||
* 当插件在客户端未关闭时执行自更新或外部覆盖文件,主进程保持常驻不退出(守护 `SidecarApp` 宿主端口不断连),
|
||||
* 仅在后台毫秒级平滑替换为全新 V8 Isolate 的 Worker 实例并复用桥接端口,彻底消除热更新后的「重试中」失联问题。
|
||||
*/
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||
import {
|
||||
HERE,
|
||||
LS_ADDR,
|
||||
SETTINGS_FILE,
|
||||
cloudSyncState,
|
||||
computeRuntimeCodeVersion,
|
||||
isPlainObject,
|
||||
loadSettings,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizePluginUpdateMode,
|
||||
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';
|
||||
bootWindowBridgeRuntime,
|
||||
dispatchBridgeApiRequest,
|
||||
isLocalHostRequest,
|
||||
readLocalAsync,
|
||||
} from './backend/api-actions.mjs';
|
||||
|
||||
const app = new SidecarApp();
|
||||
|
||||
const bootBundleVersion = computeRuntimeCodeVersion();
|
||||
const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate' };
|
||||
|
||||
/**
|
||||
* 异步读取 `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');
|
||||
};
|
||||
const isTestHarnessEnv =
|
||||
String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid' ||
|
||||
typeof Worker !== 'function';
|
||||
|
||||
/**
|
||||
* 校验请求是否来自本机回环同端口地址 (`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;
|
||||
// ---------------------------------------------------------------------------
|
||||
// 热可替换后端 Worker 监督器(仅在真实宿主运行时启用,测试沙箱直接走内存分发)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let activeWorker = null;
|
||||
let workerSwapPromise = null;
|
||||
let rpcSeq = 0;
|
||||
const pendingWorkerRpcs = new Map();
|
||||
|
||||
function createBackendWorkerInstance() {
|
||||
const workerUrl = new URL('./backend/sidecar-worker.mjs', import.meta.url);
|
||||
const worker = new Worker(workerUrl);
|
||||
|
||||
worker.on('message', (msg) => {
|
||||
if (!msg || typeof msg !== 'object') return;
|
||||
if (msg.type === 'reload_request') {
|
||||
if (worker === activeWorker) {
|
||||
void reloadBackendWorker();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (hostMatch) {
|
||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||
const originPort = originMatch[3] || defaultPort;
|
||||
const hostPort = hostMatch[2] || defaultPort;
|
||||
if (originPort !== hostPort) {
|
||||
return false;
|
||||
if (msg.type === 'api_result' || msg.type === 'shutdown_ack') {
|
||||
const pending = pendingWorkerRpcs.get(msg.id);
|
||||
if (!pending) return;
|
||||
pendingWorkerRpcs.delete(msg.id);
|
||||
clearTimeout(pending.timer);
|
||||
if (msg.type === 'shutdown_ack' || msg.ok) {
|
||||
pending.resolve(msg.response ?? true);
|
||||
} else {
|
||||
pending.reject(new Error(msg.error || 'Backend worker error'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
worker.on('exit', () => {
|
||||
for (const [id, entry] of pendingWorkerRpcs.entries()) {
|
||||
if (entry.worker === worker) {
|
||||
pendingWorkerRpcs.delete(id);
|
||||
clearTimeout(entry.timer);
|
||||
entry.reject(new Error('Backend worker exited during request'));
|
||||
}
|
||||
}
|
||||
if (activeWorker === worker) {
|
||||
activeWorker = null;
|
||||
if (!workerSwapPromise) {
|
||||
setTimeout(() => {
|
||||
if (!activeWorker && !workerSwapPromise) {
|
||||
activeWorker = createBackendWorkerInstance();
|
||||
}
|
||||
}, 120).unref?.();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
worker.on('error', () => {
|
||||
// 交由 exit 回调统一回收并拉起新实例
|
||||
});
|
||||
|
||||
return worker;
|
||||
}
|
||||
|
||||
function sendWorkerMessage(worker, payload, timeoutMs = 30000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++rpcSeq;
|
||||
const timer = setTimeout(() => {
|
||||
pendingWorkerRpcs.delete(id);
|
||||
reject(new Error('Backend worker request timeout'));
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
pendingWorkerRpcs.set(id, { worker, timer, resolve, reject });
|
||||
try {
|
||||
worker.postMessage({ ...payload, id });
|
||||
} catch (err) {
|
||||
pendingWorkerRpcs.delete(id);
|
||||
clearTimeout(timer);
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopWorkerGracefully(worker) {
|
||||
if (!worker) return;
|
||||
try {
|
||||
await sendWorkerMessage(worker, { type: 'shutdown' }, 1200);
|
||||
} catch {
|
||||
// 超时或通道已关闭时直接强制终止旧 Isolate
|
||||
}
|
||||
try {
|
||||
await worker.terminate();
|
||||
} catch {
|
||||
// 忽略重复终止异常
|
||||
}
|
||||
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;
|
||||
function reloadBackendWorker() {
|
||||
if (workerSwapPromise) return workerSwapPromise;
|
||||
workerSwapPromise = (async () => {
|
||||
const prev = activeWorker;
|
||||
activeWorker = null;
|
||||
await stopWorkerGracefully(prev);
|
||||
activeWorker = createBackendWorkerInstance();
|
||||
return activeWorker;
|
||||
})().finally(() => {
|
||||
workerSwapPromise = null;
|
||||
});
|
||||
return workerSwapPromise;
|
||||
}
|
||||
|
||||
const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate' };
|
||||
async function ensureActiveWorker() {
|
||||
if (workerSwapPromise) {
|
||||
return workerSwapPromise;
|
||||
}
|
||||
if (!activeWorker) {
|
||||
activeWorker = createBackendWorkerInstance();
|
||||
}
|
||||
return activeWorker;
|
||||
}
|
||||
|
||||
async function forwardApiCall(pathname, method, data) {
|
||||
if (isTestHarnessEnv) {
|
||||
return dispatchBridgeApiRequest(pathname, method, data);
|
||||
}
|
||||
const upperMethod = String(method || 'GET').toUpperCase();
|
||||
try {
|
||||
const worker = await ensureActiveWorker();
|
||||
return await sendWorkerMessage(worker, { type: 'api', pathname, method: upperMethod, data });
|
||||
} catch (err) {
|
||||
if (upperMethod === 'GET') {
|
||||
const retryWorker = await ensureActiveWorker();
|
||||
return sendWorkerMessage(retryWorker, { type: 'api', pathname, method: upperMethod, data });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleProtectedApi(pathname, method, data, req) {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await forwardApiCall(pathname, method, data);
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 静态页面与前端资产路由
|
||||
@@ -140,234 +208,22 @@ 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),
|
||||
orchestratorIdMode:
|
||||
payload.orchestratorIdMode !== undefined
|
||||
? normalizeOrchestratorIdMode(payload.orchestratorIdMode)
|
||||
: normalizeOrchestratorIdMode(current.orchestratorIdMode),
|
||||
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(
|
||||
'/api/telemetry',
|
||||
async (data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executeTelemetryAction(data);
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
},
|
||||
'GET'
|
||||
);
|
||||
|
||||
app.api('/api/settings', (data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = executeSettingsAction(data);
|
||||
if (!out.ok) {
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
}
|
||||
return out.updated;
|
||||
});
|
||||
|
||||
app.api('/api/cloud-sync', async (_data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executeCloudSyncAction();
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
});
|
||||
|
||||
app.api('/api/plugin-update', async (_data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executePluginUpdateAction();
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
});
|
||||
app.api('/api/telemetry', (data, req) => handleProtectedApi('/api/telemetry', 'GET', data, req), 'GET');
|
||||
app.api('/api/settings', (data, req) => handleProtectedApi('/api/settings', 'POST', data, req));
|
||||
app.api('/api/accounts', (_data, req) => handleProtectedApi('/api/accounts', 'GET', undefined, req), 'GET');
|
||||
app.api('/api/accounts/update', (data, req) => handleProtectedApi('/api/accounts/update', 'POST', data, req), 'POST');
|
||||
app.api('/api/context-window', (data, req) => handleProtectedApi('/api/context-window', 'POST', data, req));
|
||||
app.api('/api/settings/reset', (_data, req) => handleProtectedApi('/api/settings/reset', 'POST', undefined, req));
|
||||
app.api('/api/cache/rebuild', (_data, req) => handleProtectedApi('/api/cache/rebuild', 'POST', undefined, req));
|
||||
app.api('/api/cloud-sync', (_data, req) => handleProtectedApi('/api/cloud-sync', 'POST', undefined, req));
|
||||
app.api('/api/plugin-update', (_data, req) => handleProtectedApi('/api/plugin-update', 'POST', undefined, req));
|
||||
|
||||
app.run();
|
||||
if (LS_ADDR && LS_ADDR !== 'test.invalid') {
|
||||
syncCloudCatalog({ force: false }).catch(() => {});
|
||||
startDefaultWindowBridge({
|
||||
handleApiRequest: dispatchBridgeApiRequest,
|
||||
readAssetFn: readLocalAsync,
|
||||
bootBundleVersion,
|
||||
onVersionDrift: () => scheduleSidecarRestart(150),
|
||||
});
|
||||
if (isTestHarnessEnv) {
|
||||
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||
} else {
|
||||
void ensureActiveWorker();
|
||||
}
|
||||
|
||||
@@ -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 = code === 0 ? 120 : 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();
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"name": "usage-monitor-panel",
|
||||
"version": "1.4.5",
|
||||
"version": "1.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||
"scripts": {
|
||||
"build": "node scripts/build-bundle.mjs",
|
||||
"standalone": "node standalone.mjs",
|
||||
"test": "node --test test/*.test.mjs"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,6 +437,7 @@ export function buildBundle() {
|
||||
'src/styles/views-overview.css',
|
||||
'src/styles/views-consumption.css',
|
||||
'src/styles/views-tables.css',
|
||||
'src/styles/views-settings.css',
|
||||
'src/styles/overlay.css',
|
||||
];
|
||||
|
||||
@@ -451,6 +452,10 @@ export function buildBundle() {
|
||||
'src/icons/svgRegistry.js',
|
||||
'src/icons/SvgIcon.js',
|
||||
'src/core/reactive.js',
|
||||
'src/i18n/zh-CN.js',
|
||||
'src/i18n/en-US.js',
|
||||
'src/i18n/index.js',
|
||||
'src/core/appearance.js',
|
||||
'src/core/domPatch.js',
|
||||
'src/core/component.js',
|
||||
'src/core/formatters.js',
|
||||
@@ -466,6 +471,24 @@ export function buildBundle() {
|
||||
'src/components/ui/ContextSegmentMeter.js',
|
||||
'src/components/ui/FourSegmentBar.js',
|
||||
'src/components/charts/TrendAreaChart.js',
|
||||
'src/components/charts/SessionStepCharts.js',
|
||||
'src/registries/metricRegistry.js',
|
||||
'src/components/widgets/MetricMatrixWidget.js',
|
||||
'src/components/widgets/ContextWindowWidget.js',
|
||||
'src/components/widgets/QuotaPoolsWidget.js',
|
||||
'src/components/widgets/LiveActivityWidget.js',
|
||||
'src/registries/widgetRegistry.js',
|
||||
'src/registries/stepColumnRegistry.js',
|
||||
'src/components/widgets/CapsuleBarWidget.js',
|
||||
'src/components/widgets/StepTableWidget.js',
|
||||
'src/components/settings/structurePreviewMock.js',
|
||||
'src/components/settings/CollapsibleSection.js',
|
||||
'src/components/settings/EditableSlotList.js',
|
||||
'src/components/settings/ThemeColorPicker.js',
|
||||
'src/views/settings/SettingsGeneralTab.js',
|
||||
'src/views/settings/SettingsStructureTab.js',
|
||||
'src/views/settings/SettingsAccountTab.js',
|
||||
'src/views/settings/SettingsOtherTab.js',
|
||||
'src/components/layout/TopSessionHeader.js',
|
||||
'src/views/LiveOverviewView.js',
|
||||
'src/views/ConsumptionView.js',
|
||||
|
||||
@@ -169,15 +169,29 @@ function estimateUtf8Tokens(text) {
|
||||
* @param {unknown} name 分块名称或标题
|
||||
* @returns {'skills' | 'userRules' | 'mcpTools' | 'systemPrompt'} 归属的上下文分类键名
|
||||
*/
|
||||
function classifyPromptSection(name) {
|
||||
const key = String(name || '').trim().toLowerCase();
|
||||
function classifyPromptSection(name, type = '') {
|
||||
const key = String(name || type || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^token_type_/, '')
|
||||
.replace(/[\s-]+/g, '_');
|
||||
if (key === 'skills' || key === 'skill') {
|
||||
return 'skills';
|
||||
}
|
||||
if (key === 'user_rules' || key === 'user_rule' || key === 'rules') {
|
||||
if (
|
||||
key === 'user_rules' ||
|
||||
key === 'user_rule' ||
|
||||
key === 'rules' ||
|
||||
key === 'rule'
|
||||
) {
|
||||
return 'userRules';
|
||||
}
|
||||
if (key === 'mcp_servers' || key === 'mcp' || key.startsWith('mcp_')) {
|
||||
if (
|
||||
key === 'mcp_servers' ||
|
||||
key === 'mcp_tools' ||
|
||||
key === 'mcp' ||
|
||||
key.startsWith('mcp_')
|
||||
) {
|
||||
return 'mcpTools';
|
||||
}
|
||||
return 'systemPrompt';
|
||||
@@ -328,7 +342,7 @@ export function extractContextBreakdown(chat) {
|
||||
for (const c of children) {
|
||||
const tok = Math.max(0, Number(c?.numTokens || 0));
|
||||
childSum += tok;
|
||||
const bucket = classifyPromptSection(c?.name ?? c?.title);
|
||||
const bucket = classifyPromptSection(c?.name ?? c?.title, c?.type);
|
||||
if (bucket === 'skills') {
|
||||
skillsTokens += tok;
|
||||
} else if (bucket === 'userRules') {
|
||||
@@ -345,6 +359,32 @@ export function extractContextBreakdown(chat) {
|
||||
} else {
|
||||
systemPromptTokens += gTokens;
|
||||
}
|
||||
} else if (
|
||||
gType === 'TOKEN_TYPE_SKILLS' ||
|
||||
gName === 'skills' ||
|
||||
gName === 'skill'
|
||||
) {
|
||||
hasPromptGroup = true;
|
||||
skillsTokens += gTokens;
|
||||
} else if (
|
||||
gType === 'TOKEN_TYPE_RULES' ||
|
||||
gType === 'TOKEN_TYPE_USER_RULES' ||
|
||||
gName === 'rules' ||
|
||||
gName === 'user rules' ||
|
||||
gName === 'user_rules'
|
||||
) {
|
||||
hasPromptGroup = true;
|
||||
userRulesTokens += gTokens;
|
||||
} else if (
|
||||
gType === 'TOKEN_TYPE_SUBAGENTS' ||
|
||||
gType === 'TOKEN_TYPE_PLUGINS' ||
|
||||
gName === 'subagents' ||
|
||||
gName === 'plugins' ||
|
||||
gName === 'featured plugins' ||
|
||||
gName === 'featured_plugins'
|
||||
) {
|
||||
hasPromptGroup = true;
|
||||
systemPromptTokens += gTokens;
|
||||
} else if (
|
||||
gType === 'TOKEN_TYPE_TOOLS' ||
|
||||
gName === 'tools' ||
|
||||
@@ -451,6 +491,19 @@ export function extractContextBreakdown(chat) {
|
||||
} else if (gTokens > 0) {
|
||||
userInputTokens += gTokens;
|
||||
}
|
||||
} else if (gTokens > 0) {
|
||||
// 兜底接收未来新增的顶层提示词分组,确保 tokenBreakdown.groups 不丢任何分组
|
||||
hasPromptGroup = true;
|
||||
const fallbackBucket = classifyPromptSection(g?.name, g?.type);
|
||||
if (fallbackBucket === 'skills') {
|
||||
skillsTokens += gTokens;
|
||||
} else if (fallbackBucket === 'userRules') {
|
||||
userRulesTokens += gTokens;
|
||||
} else if (fallbackBucket === 'mcpTools') {
|
||||
mcpToolsTokens += gTokens;
|
||||
} else {
|
||||
systemPromptTokens += gTokens;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,8 +608,9 @@ export function extractContextBreakdown(chat) {
|
||||
* - 优先级 3:`chat.model`(`chatModel` 请求级模型标识)
|
||||
* - 优先级 4:`metadata.generatorModel`(步骤 `metadata` 顶层记录的生成模型)
|
||||
* - 优先级 5:`chat.responseModel`(上游返回的具体响应模型名)
|
||||
* 2. **5 种测速过滤与排除原因(`timingReason` / `speedReason`)**:
|
||||
* - `'incomplete_or_invalid_timing'`:步骤状态未完成(非 `CORTEX_STEP_STATUS_DONE`)或总耗时 `totalDurationSec` 缺失/非正数;
|
||||
* 2. **测速过滤与排除原因(`timingReason` / `speedReason`)**:
|
||||
* - `'canceled'`:生成已取消,保留用量但不参与测速;
|
||||
* - `'incomplete_or_invalid_timing'`:没有完成生成的证据,或总耗时 `totalDurationSec` 缺失/非正数;
|
||||
* - `'invalid_output_tokens'`:`outputTokens` 不是合法的非负安全整数;
|
||||
* - `'short_timing'`:请求总耗时低于 `MIN_SPEED_DURATION_SECONDS`(0.5s),易受计时器粒度噪声干扰;
|
||||
* - `'inconsistent_timing'`:原生首字延迟 `nativeTtftSec` 大于请求总耗时 `totalDurationSec + 0.01s`(时钟或元数据自相矛盾);
|
||||
@@ -610,14 +664,91 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
|
||||
const result = [];
|
||||
let lastCompactionStepIdx = -1;
|
||||
let turnCounter = 0;
|
||||
let activeTurnIndex = null;
|
||||
let pendingTurnPrompts = [];
|
||||
let hasUnconsumedTurn = false;
|
||||
|
||||
const isUserTurnBoundary = (step) => {
|
||||
if (!step || typeof step !== 'object') return false;
|
||||
const t = String(step.type || '').trim().toUpperCase();
|
||||
if (t === 'CORTEX_STEP_TYPE_USER_INPUT' || t === 'USER_INPUT') {
|
||||
return true;
|
||||
}
|
||||
return Boolean(step.userInput && typeof step.userInput === 'object');
|
||||
};
|
||||
|
||||
const extractUserTurnPrompt = (step) => {
|
||||
const ui = step?.userInput;
|
||||
let raw = '';
|
||||
if (typeof ui?.userResponse === 'string' && ui.userResponse.trim()) {
|
||||
raw = ui.userResponse;
|
||||
} else if (Array.isArray(ui?.items)) {
|
||||
raw = ui.items
|
||||
.map((it) => (typeof it?.text === 'string' ? it.text : ''))
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
} else if (typeof step?.content === 'string' && step.content.trim()) {
|
||||
const withoutSummary = step.content
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '');
|
||||
const reqMatches = [...withoutSummary.matchAll(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi)];
|
||||
raw =
|
||||
reqMatches.length > 0
|
||||
? reqMatches[reqMatches.length - 1][1]
|
||||
: withoutSummary.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||
}
|
||||
const cleaned = String(raw || '')
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.replace(/\s+/g, ' ').trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
const mediaArr = Array.isArray(ui?.media)
|
||||
? ui.media
|
||||
: Array.isArray(step?.media)
|
||||
? step.media
|
||||
: [];
|
||||
const hasMedia = mediaArr.length > 0;
|
||||
if (!cleaned) {
|
||||
return hasMedia ? '[图片/附件提问]' : '';
|
||||
}
|
||||
const withMedia = hasMedia ? `${cleaned} [附图]` : cleaned;
|
||||
return withMedia.length > 180 ? `${withMedia.slice(0, 179)}…` : withMedia;
|
||||
};
|
||||
|
||||
rawSteps.forEach((s, index) => {
|
||||
if (isUserTurnBoundary(s)) {
|
||||
const promptText = extractUserTurnPrompt(s);
|
||||
if (!hasUnconsumedTurn) {
|
||||
hasUnconsumedTurn = true;
|
||||
pendingTurnPrompts = promptText ? [promptText] : [];
|
||||
} else if (
|
||||
promptText &&
|
||||
pendingTurnPrompts[pendingTurnPrompts.length - 1] !== promptText
|
||||
) {
|
||||
pendingTurnPrompts.push(promptText);
|
||||
}
|
||||
}
|
||||
|
||||
const m = s?.metadata;
|
||||
const u = m?.modelUsage || m?.retryInfos?.[0]?.usage;
|
||||
if (!u) {
|
||||
return;
|
||||
}
|
||||
|
||||
let stepIsTurnStart = false;
|
||||
let stepTurnPrompt = '';
|
||||
if (hasUnconsumedTurn) {
|
||||
turnCounter += 1;
|
||||
activeTurnIndex = turnCounter;
|
||||
stepIsTurnStart = true;
|
||||
const joinedPrompt = pendingTurnPrompts.join('\n').trim();
|
||||
stepTurnPrompt =
|
||||
joinedPrompt.length > 180 ? `${joinedPrompt.slice(0, 179)}…` : joinedPrompt;
|
||||
hasUnconsumedTurn = false;
|
||||
pendingTurnPrompts = [];
|
||||
}
|
||||
|
||||
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
||||
if (Array.isArray(m.generatorMetadata)) {
|
||||
for (const g of m.generatorMetadata) {
|
||||
@@ -658,12 +789,14 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
: Math.max(0, outputTokens - thinkingTokens);
|
||||
|
||||
const start = parseIsoMs(m.createdAt);
|
||||
// 轨迹清理可把已生成的步骤改为 CLEARED;仍需原始生成结束时间,避免将清理时间计入测速。
|
||||
const isCleared = s.status === 'CORTEX_STEP_STATUS_CLEARED';
|
||||
const measuredDuration = requestDuration(
|
||||
m.createdAt,
|
||||
m.finishedGeneratingAt || m.completedAt
|
||||
m.finishedGeneratingAt || (isCleared ? null : m.completedAt)
|
||||
);
|
||||
const explicitlyIncomplete = Boolean(
|
||||
s.status && s.status !== 'CORTEX_STEP_STATUS_DONE'
|
||||
s.status && s.status !== 'CORTEX_STEP_STATUS_DONE' && !isCleared
|
||||
);
|
||||
const complete = !explicitlyIncomplete && measuredDuration !== null;
|
||||
const totalDurationSec = complete ? measuredDuration : null;
|
||||
@@ -674,9 +807,11 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const nativeStreamSec = duration(chat?.streamingDuration);
|
||||
const thinkingDurationSec = duration(p.thinkingDuration);
|
||||
|
||||
// 5 种测速过滤原因判定:先校验耗时与 Token 合法性(timingReason),再判定压缩步与短样本(speedReason)
|
||||
// 先校验状态、耗时与 Token 合法性,再判定压缩步与短样本。
|
||||
let timingReason = null;
|
||||
if (!complete || !(totalDurationSec > 0)) {
|
||||
if (s.status === 'CORTEX_STEP_STATUS_CANCELED') {
|
||||
timingReason = 'canceled';
|
||||
} else if (!complete || !(totalDurationSec > 0)) {
|
||||
timingReason = 'incomplete_or_invalid_timing';
|
||||
} else if (!validCount(u.outputTokens)) {
|
||||
timingReason = 'invalid_output_tokens';
|
||||
@@ -763,6 +898,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
context?.estimatedTokensUsed || contextBreakdown?.totalTokens || 0
|
||||
),
|
||||
maxContextBudgetTokens: Number(context?.maxContextTokens || 256000),
|
||||
...(context?.maxContextTokens > 0 ? { reportedContextLimitTokens: Number(context.maxContextTokens) } : {}),
|
||||
contextBreakdown,
|
||||
measurementVersion: MEASUREMENT_VERSION,
|
||||
isComplete: complete,
|
||||
@@ -778,6 +914,9 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
speedSampleEligible:
|
||||
totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
|
||||
speedReason,
|
||||
turnIndex: activeTurnIndex,
|
||||
isTurnStart: stepIsTurnStart,
|
||||
...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1051,7 +1190,10 @@ export function speedMetric(step) {
|
||||
!Number.isFinite(step.totalTokPerSec) ||
|
||||
!(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS)
|
||||
) {
|
||||
return missing(step.speedReason || 'incomplete_or_invalid_timing');
|
||||
const reason = step.speedReason || 'incomplete_or_invalid_timing';
|
||||
return missing(step.isCompactionStep && reason === 'incomplete_or_invalid_timing'
|
||||
? 'compaction_timing_unavailable'
|
||||
: reason);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -1161,10 +1303,12 @@ export function summarizeTtft(steps) {
|
||||
/** 标志着原始轨迹步骤已进入终态的状态枚举集合(兼容 Connect RPC 与 transcript.jsonl) */
|
||||
const LIVE_TERMINAL_STATUSES = new Set([
|
||||
'CORTEX_STEP_STATUS_DONE',
|
||||
'CORTEX_STEP_STATUS_CLEARED',
|
||||
'CORTEX_STEP_STATUS_ERROR',
|
||||
'CORTEX_STEP_STATUS_CANCELED',
|
||||
'CORTEX_STEP_STATUS_CANCELLED',
|
||||
'DONE',
|
||||
'CLEARED',
|
||||
'ERROR',
|
||||
'CANCELED',
|
||||
'CANCELLED',
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
|
||||
import { defineComponent } from './core/component.js';
|
||||
import { h, patchAttr } from './core/domPatch.js';
|
||||
import { i18nStore } from './i18n/index.js';
|
||||
import { resolveScopedConversation, telemetryStore } from './store/telemetryStore.js';
|
||||
import { uiStore, VIEW_TABS } from './store/uiStore.js';
|
||||
import { getViewTabs, uiStore } from './store/uiStore.js';
|
||||
import { TopSessionHeader } from './components/layout/TopSessionHeader.js';
|
||||
import { TopLongPillNav } from './components/ui/TopLongPillNav.js';
|
||||
import { LiveOverviewView } from './views/LiveOverviewView.js';
|
||||
@@ -21,7 +22,7 @@ export const App = defineComponent({
|
||||
const sessionHeader = TopSessionHeader();
|
||||
const topPillNav = TopLongPillNav({
|
||||
modelValue: uiStore.getState().activeView,
|
||||
items: VIEW_TABS,
|
||||
items: getViewTabs(),
|
||||
onUpdateModelValue: (nextView) => {
|
||||
uiStore.setState({ activeView: nextView });
|
||||
},
|
||||
@@ -61,8 +62,10 @@ export const App = defineComponent({
|
||||
);
|
||||
const stepCount = scopedConv?.stepCount ?? 0;
|
||||
topPillNav.setProps({
|
||||
items: VIEW_TABS.map((t) =>
|
||||
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
||||
items: getViewTabs().map((tabItem) =>
|
||||
tabItem.value === 'steps'
|
||||
? { ...tabItem, badge: stepCount > 0 ? stepCount : '' }
|
||||
: tabItem
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -102,10 +105,16 @@ export const App = defineComponent({
|
||||
() => syncStepsBadge()
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => syncStepsBadge()
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubUi();
|
||||
unsubStepCount();
|
||||
unsubScopeBadge();
|
||||
unsubI18n();
|
||||
sessionHeader.destroy();
|
||||
topPillNav.destroy();
|
||||
overviewView.destroy();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,15 +1,18 @@
|
||||
/**
|
||||
* @fileoverview 交互式 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart).
|
||||
* 支持:
|
||||
* 1. 自适应整点小时(<=72h)与自然日(>72h)高精度分桶序列渲染;
|
||||
* 2. 鼠标悬停/滑动十字准星探针、高亮圆点与自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数);
|
||||
* 3. 与 SVG 垂直网格线像素级对齐的多刻度底部时间轴(彻底告别首/中/末简单对半切分)。
|
||||
* @fileoverview 交互式历史用量趋势图组件 (TrendAreaChart).
|
||||
* 支持双模式自适应切换:
|
||||
* 1. <= 90 天(或整点小时分桶):渲染三次贝塞尔平滑曲线面积图、峰值气泡与对齐多刻度时间轴;
|
||||
* 2. > 90 天(自然日分桶):自动切换为类 GitHub 贡献日历的小格子热力排列(一格一天,7 行星期 × 周列、月份刻度、分位数 5 档热力色阶与底部图例);
|
||||
* 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。
|
||||
*/
|
||||
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
|
||||
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
|
||||
export const HEATMAP_DAYS_THRESHOLD = 90;
|
||||
|
||||
let chartUidCounter = 0;
|
||||
|
||||
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 {{
|
||||
* el: HTMLElement,
|
||||
@@ -68,17 +192,22 @@ function computeTickIndices(slots) {
|
||||
* }}
|
||||
*/
|
||||
export function createTrendAreaChart() {
|
||||
const VIEW_W = 460;
|
||||
const DEFAULT_VIEW_W = 460;
|
||||
const VIEW_H = 120;
|
||||
const LEFT_X = 14;
|
||||
const RIGHT_X = 446;
|
||||
const TOP_Y = 24;
|
||||
const BOTTOM_Y = 102;
|
||||
const SPAN_X = RIGHT_X - LEFT_X;
|
||||
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');
|
||||
svg.setAttribute('viewBox', `0 0 ${VIEW_W} ${VIEW_H}`);
|
||||
svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`);
|
||||
svg.setAttribute('class', 'trend-svg');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
|
||||
@@ -107,16 +236,18 @@ export function createTrendAreaChart() {
|
||||
defs.appendChild(grad);
|
||||
svg.appendChild(defs);
|
||||
|
||||
// 背景水平与垂直参考网格线
|
||||
// 背景水平与垂直参考网格线(水平网格全宽贴边铺满 0..viewW)
|
||||
const hGridGroup = document.createElementNS(SVG_NS, 'g');
|
||||
hGridGroup.setAttribute('class', 'trend-grid');
|
||||
const hGridLines = [];
|
||||
for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) {
|
||||
const line = document.createElementNS(SVG_NS, 'line');
|
||||
line.setAttribute('x1', String(LEFT_X));
|
||||
line.setAttribute('x1', '0');
|
||||
line.setAttribute('y1', String(y));
|
||||
line.setAttribute('x2', String(RIGHT_X));
|
||||
line.setAttribute('x2', String(viewW));
|
||||
line.setAttribute('y2', String(y));
|
||||
hGridGroup.appendChild(line);
|
||||
hGridLines.push(line);
|
||||
}
|
||||
svg.appendChild(hGridGroup);
|
||||
|
||||
@@ -158,7 +289,7 @@ export function createTrendAreaChart() {
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
|
||||
// 悬停详情浮层卡片
|
||||
// 共享悬停详情浮层卡片(曲线图与热力格子图共用)
|
||||
const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' });
|
||||
const tipCallsEl = h('span', { className: 'trend-tip-calls 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 plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]);
|
||||
|
||||
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, tooltipEl, svg]);
|
||||
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [plotStage, xAxisEl]);
|
||||
// 类 GitHub 每日小格子热力图容器(> 90 天模式)
|
||||
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 currentPts = [];
|
||||
let currentIsHeatmap = false;
|
||||
let currentHeatmapWeeks = 0;
|
||||
let currentCellEls = [];
|
||||
let tickElsByIdx = new Map();
|
||||
let hoveredIdx = -1;
|
||||
let hoveredCellEl = null;
|
||||
let lastRenderSig = '';
|
||||
|
||||
function showHoverAtIndex(idx) {
|
||||
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);
|
||||
|
||||
function populateTooltipContent(slot) {
|
||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`);
|
||||
const slotTok = safeSlotTokens(slot.tokens);
|
||||
@@ -231,47 +380,219 @@ export function createTrendAreaChart() {
|
||||
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const rawPct = (pt.x / VIEW_W) * 100;
|
||||
const clampedPct = Math.max(2, Math.min(98, rawPct));
|
||||
const shiftX = rawPct < 28 ? '0%' : rawPct > 72 ? '-100%' : '-50%';
|
||||
function showLineHoverAtIndex(idx) {
|
||||
if (currentIsHeatmap || 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);
|
||||
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-shift', shiftX);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
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() {
|
||||
hoveredIdx = -1;
|
||||
patchAttr(hoverLine, 'hidden', true);
|
||||
patchAttr(hoverDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
patchAttr(peakPill, 'hidden', false);
|
||||
patchClasses(tooltipEl, { 'is-hm-bottom': false, 'is-hm-top': false });
|
||||
if (!currentIsHeatmap) {
|
||||
patchAttr(peakPill, 'hidden', false);
|
||||
}
|
||||
if (hoveredCellEl) {
|
||||
patchClasses(hoveredCellEl, { 'is-hovered': false });
|
||||
hoveredCellEl = null;
|
||||
}
|
||||
for (const el of tickElsByIdx.values()) {
|
||||
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) {
|
||||
if (!currentSlots.length) return;
|
||||
if (currentIsHeatmap || !currentSlots.length) return;
|
||||
const rect = svg.getBoundingClientRect();
|
||||
if (!rect || rect.width <= 0) return;
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * VIEW_W;
|
||||
const ratio = (relX - LEFT_X) / Math.max(1, SPAN_X);
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||
const idx = Math.max(
|
||||
0,
|
||||
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('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 = []) {
|
||||
const slots =
|
||||
@@ -285,39 +606,155 @@ export function createTrendAreaChart() {
|
||||
];
|
||||
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 peakIdx = 0;
|
||||
let activeDays = 0;
|
||||
const nonZeroVals = [];
|
||||
|
||||
for (let i = 0; i < slots.length; i++) {
|
||||
const t = safeSlotTokens(slots[i]?.tokens);
|
||||
if (t > 0) {
|
||||
activeDays++;
|
||||
nonZeroVals.push(t);
|
||||
}
|
||||
if (t >= maxTokens) {
|
||||
maxTokens = t;
|
||||
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 isSingle = slots.length === 1;
|
||||
const pts = slots.map((s, idx) => {
|
||||
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 y = BOTTOM_Y - ratio * SPAN_Y;
|
||||
return { x, y, tokens: tok };
|
||||
});
|
||||
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) {
|
||||
lastRenderSig = sig;
|
||||
let lineD;
|
||||
let areaD;
|
||||
if (isSingle) {
|
||||
const yStr = pts[0].y.toFixed(1);
|
||||
lineD = `M ${LEFT_X.toFixed(1)} ${yStr} L ${RIGHT_X.toFixed(1)} ${yStr}`;
|
||||
areaD = `${lineD} L ${RIGHT_X.toFixed(1)} ${BOTTOM_Y} L ${LEFT_X.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`;
|
||||
areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
} else {
|
||||
lineD = buildSmoothSplinePath(pts);
|
||||
areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
@@ -325,7 +762,7 @@ export function createTrendAreaChart() {
|
||||
patchAttr(linePath, 'd', lineD);
|
||||
patchAttr(areaPath, 'd', areaD);
|
||||
|
||||
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签
|
||||
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边)
|
||||
const tickIndices = computeTickIndices(slots);
|
||||
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
|
||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||
@@ -348,14 +785,14 @@ export function createTrendAreaChart() {
|
||||
|
||||
const isFirst = !isSingle && i === 0;
|
||||
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', {
|
||||
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
|
||||
text: slot.label || '',
|
||||
title: slot.fullLabel || slot.label || '',
|
||||
});
|
||||
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
|
||||
tickEl.onclick = () => showHoverAtIndex(tIdx);
|
||||
tickEl.onclick = () => showLineHoverAtIndex(tIdx);
|
||||
xAxisEl.appendChild(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, 'cy', peakPt.y.toFixed(1));
|
||||
|
||||
@@ -385,15 +822,15 @@ export function createTrendAreaChart() {
|
||||
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
||||
: formatTokensPrecise(maxTokens);
|
||||
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)}%`);
|
||||
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showHoverAtIndex(hoveredIdx);
|
||||
showLineHoverAtIndex(hoveredIdx);
|
||||
}
|
||||
}
|
||||
|
||||
return { el: chartWrap, update };
|
||||
return { el: chartWrap, update, destroy };
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { i18nStore, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
@@ -20,9 +21,13 @@ function formatConvOptionMeta(c) {
|
||||
if (!c) return '';
|
||||
const subs = Number(c.subagentCount || 0);
|
||||
if (subs > 0) {
|
||||
return `主${c.stepCount || 0} · ${subs}子 (共${c.totalStepCount || c.stepCount || 0}步)`;
|
||||
return t('header.convMetaWithSubs', {
|
||||
main: c.stepCount || 0,
|
||||
subs,
|
||||
total: c.totalStepCount || c.stepCount || 0,
|
||||
});
|
||||
}
|
||||
return `${c.stepCount || 0}步`;
|
||||
return t('header.convMetaSteps', { count: c.stepCount || 0 });
|
||||
}
|
||||
|
||||
export const TopSessionHeader = defineComponent({
|
||||
@@ -30,8 +35,8 @@ export const TopSessionHeader = defineComponent({
|
||||
setup({ onCleanup }) {
|
||||
const convSelect = CustomSelect({
|
||||
modelValue: telemetryStore.getState().selectedConversationId,
|
||||
placeholder: '跟随最新会话',
|
||||
options: [{ value: '', label: '跟随最新会话' }],
|
||||
placeholder: t('header.followLatest'),
|
||||
options: [{ value: '', label: t('header.followLatest') }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
||||
@@ -40,7 +45,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
|
||||
const updateBtnIcon = createSvgIcon('arrow-down', { size: 11 });
|
||||
const updateBtnText = h('span', { text: '有新版本' });
|
||||
const updateBtnText = h('span', { text: t('header.hasUpdate') });
|
||||
let isHeaderUpdating = false;
|
||||
const updateBtn = h(
|
||||
'button',
|
||||
@@ -48,11 +53,11 @@ export const TopSessionHeader = defineComponent({
|
||||
type: 'button',
|
||||
className: 'update-badge-btn',
|
||||
hidden: true,
|
||||
'aria-label': '发现新版本,点击升级',
|
||||
'aria-label': t('header.ariaUpdate'),
|
||||
onClick: async () => {
|
||||
if (isHeaderUpdating) return;
|
||||
isHeaderUpdating = true;
|
||||
patchText(updateBtnText, '升级中…');
|
||||
patchText(updateBtnText, t('header.upgrading'));
|
||||
patchAttr(updateBtn, 'disabled', true);
|
||||
try {
|
||||
const res = await triggerPluginUpdate();
|
||||
@@ -67,7 +72,9 @@ export const TopSessionHeader = defineComponent({
|
||||
const cs = telemetryStore.getState().telemetry?.cloudStatus;
|
||||
patchText(
|
||||
updateBtnText,
|
||||
cs?.latestPluginVersion ? `升级 v${cs.latestPluginVersion}` : '有新版本'
|
||||
cs?.latestPluginVersion
|
||||
? t('header.upgradeToVer', { ver: cs.latestPluginVersion })
|
||||
: t('header.hasUpdate')
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -76,7 +83,7 @@ export const TopSessionHeader = defineComponent({
|
||||
);
|
||||
|
||||
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
||||
const statusText = h('span', { text: '实时 2s' });
|
||||
const statusText = h('span', { text: t('header.statusLive') });
|
||||
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
||||
|
||||
const refreshBtn = h(
|
||||
@@ -84,7 +91,7 @@ export const TopSessionHeader = defineComponent({
|
||||
{
|
||||
type: 'button',
|
||||
className: 'icon-btn',
|
||||
'aria-label': '刷新数据',
|
||||
'aria-label': t('header.ariaRefresh'),
|
||||
onClick: () => fetchTelemetry({ force: true }),
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 13 })]
|
||||
@@ -113,6 +120,10 @@ export const TopSessionHeader = defineComponent({
|
||||
} else if (currentCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
if (!uiSt.monitorVisible) return;
|
||||
|
||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
|
||||
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const convs = telemetry?.conversations || [];
|
||||
@@ -122,12 +133,12 @@ export const TopSessionHeader = defineComponent({
|
||||
(actConv?.cascadeId === hostRouteId ? actConv : null)
|
||||
: null;
|
||||
const defaultOptLabel = hostRouteId
|
||||
? hostMatchedConv?.title
|
||||
? `当前窗口 (${hostMatchedConv.title})`
|
||||
: `当前窗口 (${hostRouteId.slice(0, 8)})`
|
||||
? t('header.currentWindowNamed', {
|
||||
title: hostMatchedConv?.title || hostRouteId.slice(0, 8),
|
||||
})
|
||||
: convs[0]?.title
|
||||
? `最新 (${convs[0].title})`
|
||||
: '跟随最新会话';
|
||||
? t('header.latestNamed', { title: convs[0].title })
|
||||
: t('header.followLatest');
|
||||
const defaultOptMeta = hostRouteId
|
||||
? hostMatchedConv
|
||||
? formatConvOptionMeta({
|
||||
@@ -153,14 +164,14 @@ export const TopSessionHeader = defineComponent({
|
||||
const lockedTitle =
|
||||
isLoadedLocked && actConv?.title
|
||||
? actConv.title
|
||||
: `已锁定会话 (${String(lockedId).slice(0, 8)})`;
|
||||
: t('header.lockedSession', { id: String(lockedId).slice(0, 8) });
|
||||
const lockedMeta = isLoadedLocked
|
||||
? formatConvOptionMeta({
|
||||
stepCount: actConv.stepCount,
|
||||
subagentCount: actConv.subagentCount,
|
||||
totalStepCount: actConv.totalStepsAllAgents,
|
||||
})
|
||||
: '已锁定';
|
||||
: t('header.lockedMeta');
|
||||
options.splice(1, 0, {
|
||||
value: lockedId,
|
||||
label: lockedTitle,
|
||||
@@ -169,6 +180,7 @@ export const TopSessionHeader = defineComponent({
|
||||
}
|
||||
convSelect.setProps({
|
||||
modelValue: telSt.selectedConversationId,
|
||||
placeholder: t('header.followLatest'),
|
||||
options,
|
||||
});
|
||||
|
||||
@@ -186,8 +198,8 @@ export const TopSessionHeader = defineComponent({
|
||||
patchText(
|
||||
updateBtnText,
|
||||
cloudStatus?.latestPluginVersion
|
||||
? `升级 v${cloudStatus.latestPluginVersion}`
|
||||
: '有新版本'
|
||||
? t('header.upgradeToVer', { ver: cloudStatus.latestPluginVersion })
|
||||
: t('header.hasUpdate')
|
||||
);
|
||||
}
|
||||
|
||||
@@ -203,7 +215,7 @@ export const TopSessionHeader = defineComponent({
|
||||
|
||||
if (isSyncing) {
|
||||
patchSvgIcon(statusIcon, 'refresh');
|
||||
patchText(statusText, '同步中');
|
||||
patchText(statusText, t('header.statusSyncing'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
@@ -211,7 +223,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else if (isSynced) {
|
||||
patchSvgIcon(statusIcon, 'check');
|
||||
patchText(statusText, '已刷新');
|
||||
patchText(statusText, t('header.statusSynced'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
@@ -219,7 +231,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else if (isError) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, '重试中');
|
||||
patchText(statusText, t('header.statusRetrying'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
@@ -230,7 +242,7 @@ export const TopSessionHeader = defineComponent({
|
||||
const runSuffix =
|
||||
hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : '';
|
||||
patchSvgIcon(statusIcon, 'bolt');
|
||||
patchText(statusText, `生成中${runSuffix}`);
|
||||
patchText(statusText, t('header.statusGenerating', { suffix: runSuffix }));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': true,
|
||||
'state-synced': false,
|
||||
@@ -238,7 +250,10 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else if (quotaStale) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, quotaMeta?.hasOfficialData ? '额度缓存' : '额度离线');
|
||||
patchText(
|
||||
statusText,
|
||||
quotaMeta?.hasOfficialData ? t('header.statusQuotaCached') : t('header.statusQuotaOffline')
|
||||
);
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
@@ -246,7 +261,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else {
|
||||
patchSvgIcon(statusIcon, 'pulse');
|
||||
patchText(statusText, '实时 2s');
|
||||
patchText(statusText, t('header.statusLive'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
@@ -265,8 +280,22 @@ export const TopSessionHeader = defineComponent({
|
||||
() => renderHeaderState()
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => renderHeaderState()
|
||||
);
|
||||
const unsubVisibility = uiStore.subscribe(
|
||||
(st) => st.monitorVisible,
|
||||
(visible) => {
|
||||
if (visible) renderHeaderState();
|
||||
},
|
||||
{ immediate: false }
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubTelemetry();
|
||||
unsubI18n();
|
||||
unsubVisibility();
|
||||
convSelect.destroy();
|
||||
});
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* @fileoverview Reusable Section Card (`CollapsibleSection.js`)
|
||||
* for `SettingsStructureTab` — supports both accordion mode (`collapsible: true`)
|
||||
* and static 3rd-level pane card mode (`collapsible: false`).
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
export const CollapsibleSection = defineComponent({
|
||||
name: 'CollapsibleSection',
|
||||
setup({ props, onCleanup }) {
|
||||
const isCollapsible = props.collapsible !== false;
|
||||
let expanded = isCollapsible ? Boolean(props.defaultExpanded) : true;
|
||||
let statusTimer = null;
|
||||
|
||||
const chevronIcon = isCollapsible
|
||||
? createSvgIcon('chevron-right', {
|
||||
size: 12,
|
||||
className: 'collapsible-chevron',
|
||||
})
|
||||
: null;
|
||||
const sectionIcon = props.icon ? createSvgIcon(props.icon, { size: 13 }) : null;
|
||||
const titleTextEl = h('span', {
|
||||
className: 'collapsible-title-text',
|
||||
text: props.title || '',
|
||||
});
|
||||
|
||||
const triggerChildren = [];
|
||||
if (chevronIcon) triggerChildren.push(chevronIcon);
|
||||
if (sectionIcon) triggerChildren.push(sectionIcon);
|
||||
triggerChildren.push(titleTextEl);
|
||||
|
||||
const triggerBtn = isCollapsible
|
||||
? h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'collapsible-trigger',
|
||||
'aria-expanded': expanded ? 'true' : 'false',
|
||||
onClick: () => {
|
||||
setExpanded(!expanded);
|
||||
if (typeof props.onToggle === 'function') {
|
||||
props.onToggle(expanded);
|
||||
}
|
||||
},
|
||||
},
|
||||
triggerChildren
|
||||
)
|
||||
: h('div', { className: 'collapsible-title-static' }, triggerChildren);
|
||||
|
||||
const statusTextEl = h('span', { className: 'collapsible-status', text: '' });
|
||||
const badgeEl = h('span', {
|
||||
className: 'collapsible-badge text-mono',
|
||||
hidden: !props.badgeText,
|
||||
text: props.badgeText || '',
|
||||
});
|
||||
|
||||
const resetBtnText = h('span', { text: props.resetLabel || t('settings.resetBtn') });
|
||||
const resetBtn =
|
||||
typeof props.onReset === 'function'
|
||||
? h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm',
|
||||
disabled: props.resetDisabled !== false,
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
props.onReset();
|
||||
},
|
||||
},
|
||||
[resetBtnText]
|
||||
)
|
||||
: null;
|
||||
|
||||
const rightChildren = [statusTextEl, badgeEl];
|
||||
if (resetBtn) rightChildren.push(resetBtn);
|
||||
|
||||
const headerRow = h('div', { className: 'collapsible-header-row' }, [
|
||||
triggerBtn,
|
||||
h('span', { className: 'collapsible-right' }, rightChildren),
|
||||
]);
|
||||
|
||||
const bodyEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'collapsible-body',
|
||||
hidden: !expanded,
|
||||
},
|
||||
Array.isArray(props.children) ? props.children : []
|
||||
);
|
||||
|
||||
const sectionEl = h(
|
||||
'section',
|
||||
{
|
||||
className: `panel collapsible-section${expanded ? ' is-expanded' : ''}${isCollapsible ? '' : ' is-static-pane'}`,
|
||||
},
|
||||
[headerRow, bodyEl]
|
||||
);
|
||||
|
||||
function setExpanded(next) {
|
||||
if (!isCollapsible) return;
|
||||
expanded = Boolean(next);
|
||||
patchClasses(sectionEl, { 'is-expanded': expanded });
|
||||
patchAttr(triggerBtn, 'aria-expanded', expanded ? 'true' : 'false');
|
||||
patchAttr(bodyEl, 'hidden', !expanded);
|
||||
}
|
||||
|
||||
function setTitle(text) {
|
||||
patchText(titleTextEl, text || '');
|
||||
}
|
||||
|
||||
function setBadge(text) {
|
||||
patchAttr(badgeEl, 'hidden', !text);
|
||||
patchText(badgeEl, text || '');
|
||||
}
|
||||
|
||||
function setResetLabel(text) {
|
||||
if (resetBtn) {
|
||||
patchText(resetBtnText, text || t('settings.resetBtn'));
|
||||
}
|
||||
}
|
||||
|
||||
function setResetDisabled(disabled) {
|
||||
if (resetBtn) {
|
||||
patchAttr(resetBtn, 'disabled', Boolean(disabled));
|
||||
}
|
||||
}
|
||||
|
||||
function showStatus(text, autoClearMs = 1500) {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
patchText(statusTextEl, text || '');
|
||||
if (text && autoClearMs > 0) {
|
||||
statusTimer = setTimeout(() => {
|
||||
statusTimer = null;
|
||||
patchText(statusTextEl, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
el: sectionEl,
|
||||
refs: {
|
||||
triggerBtn,
|
||||
bodyEl,
|
||||
resetBtn,
|
||||
badgeEl,
|
||||
statusTextEl,
|
||||
setExpanded,
|
||||
setTitle,
|
||||
setBadge,
|
||||
setResetLabel,
|
||||
setResetDisabled,
|
||||
showStatus,
|
||||
isExpanded: () => expanded,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,446 @@
|
||||
/**
|
||||
* @fileoverview Reusable Drag-Sortable & `+` / `-` / `↑` / `↓` Dynamic Slot List (`EditableSlotList.js`).
|
||||
* Powers Topbar Capsule Slots (1..5), Hover Popup Modules (0..4),
|
||||
* Live Overview Modules (1..4), First-Row Metrics (1..4), and Step Table Columns (2..12).
|
||||
* Supports smooth pointer-based drag reordering with live preview callbacks (`onPreview`)
|
||||
* and single-commit persistence on drop (`onChange`).
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||
|
||||
function isNodeWithin(target, container) {
|
||||
let cur = target;
|
||||
while (cur) {
|
||||
if (cur === container) return true;
|
||||
cur = cur.parentNode || cur.host || null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function areSlotListsEqual(a, b) {
|
||||
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export const EditableSlotList = defineComponent({
|
||||
name: 'EditableSlotList',
|
||||
setup({ props, onCleanup }) {
|
||||
const minItems = Math.max(0, Number(props.minItems ?? 1));
|
||||
const maxItems = Math.max(minItems, Number(props.maxItems ?? 5));
|
||||
let currentItems = Array.isArray(props.items) ? [...props.items] : [];
|
||||
let currentOptions = Array.isArray(props.options) ? [...props.options] : [];
|
||||
let emptyHintText = String(props.emptyHintText || '');
|
||||
let addBtnTextFn = typeof props.addBtnTextFn === 'function' ? props.addBtnTextFn : null;
|
||||
let activeDrag = null;
|
||||
|
||||
const listEl = h('div', { className: 'editable-slot-list' });
|
||||
const emptyEl = h('div', {
|
||||
className: 'editable-slot-empty',
|
||||
hidden: true,
|
||||
text: emptyHintText,
|
||||
});
|
||||
|
||||
const addBtnLabel = h('span', { text: '' });
|
||||
const addBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-add-btn',
|
||||
onClick: () => {
|
||||
if (currentItems.length >= maxItems) return;
|
||||
const usedSet = new Set(currentItems);
|
||||
const nextOpt = currentOptions.find((opt) => !usedSet.has(opt.value));
|
||||
if (!nextOpt) return;
|
||||
emitChange([...currentItems, nextOpt.value]);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('plus', { size: 11 }), addBtnLabel]
|
||||
);
|
||||
|
||||
const footerEl = h('div', { className: 'editable-slot-footer' }, [addBtn]);
|
||||
const rootEl = h('div', { className: 'editable-slot-wrap' }, [emptyEl, listEl, footerEl]);
|
||||
|
||||
const rowPool = [];
|
||||
|
||||
function emitChange(nextItems) {
|
||||
currentItems = [...nextItems];
|
||||
syncRows();
|
||||
if (typeof props.onPreview === 'function') {
|
||||
props.onPreview([...currentItems]);
|
||||
}
|
||||
if (typeof props.onChange === 'function') {
|
||||
props.onChange([...currentItems]);
|
||||
}
|
||||
}
|
||||
|
||||
function teardownActiveDrag({ revert = false } = {}) {
|
||||
if (!activeDrag) return;
|
||||
const { startItems, hasMoved, cleanupListeners } = activeDrag;
|
||||
activeDrag = null;
|
||||
cleanupListeners();
|
||||
patchClasses(listEl, { 'is-dragging-list': false });
|
||||
for (const r of rowPool) {
|
||||
patchClasses(r.rowEl, { 'is-dragging': false });
|
||||
}
|
||||
if (revert && hasMoved && !areSlotListsEqual(startItems, currentItems)) {
|
||||
currentItems = [...startItems];
|
||||
syncRows();
|
||||
if (typeof props.onPreview === 'function') {
|
||||
props.onPreview([...currentItems]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function startPointerDrag(e, initialRowIdx) {
|
||||
if (e && e.button != null && e.button !== 0) return;
|
||||
if (currentItems.length <= 1) return;
|
||||
if (activeDrag) {
|
||||
teardownActiveDrag({ revert: false });
|
||||
}
|
||||
|
||||
const startY = Number(e?.clientY ?? 0);
|
||||
const startItems = [...currentItems];
|
||||
let dragIdx = initialRowIdx;
|
||||
let hasMoved = false;
|
||||
|
||||
const onPointerMove = (ev) => {
|
||||
if (!activeDrag) return;
|
||||
const clientY = Number(ev?.clientY ?? startY);
|
||||
if (!hasMoved) {
|
||||
if (Math.abs(clientY - startY) < 4) return;
|
||||
hasMoved = true;
|
||||
activeDrag.hasMoved = true;
|
||||
for (let k = 0; k < currentItems.length; k += 1) {
|
||||
rowPool[k]?.selectComp?.close?.();
|
||||
}
|
||||
patchClasses(listEl, { 'is-dragging-list': true });
|
||||
if (rowPool[dragIdx]) {
|
||||
patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': true });
|
||||
}
|
||||
}
|
||||
ev?.preventDefault?.();
|
||||
|
||||
let targetIdx = dragIdx;
|
||||
const count = currentItems.length;
|
||||
for (let i = 0; i < dragIdx; i += 1) {
|
||||
const rect = rowPool[i]?.rowEl?.getBoundingClientRect?.();
|
||||
if (rect && rect.height > 0 && clientY < rect.top + rect.height * 0.5) {
|
||||
targetIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetIdx === dragIdx) {
|
||||
for (let i = count - 1; i > dragIdx; i -= 1) {
|
||||
const rect = rowPool[i]?.rowEl?.getBoundingClientRect?.();
|
||||
if (rect && rect.height > 0 && clientY > rect.top + rect.height * 0.5) {
|
||||
targetIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targetIdx !== dragIdx) {
|
||||
if (rowPool[dragIdx]) {
|
||||
patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': false });
|
||||
}
|
||||
const next = [...currentItems];
|
||||
const [moved] = next.splice(dragIdx, 1);
|
||||
next.splice(targetIdx, 0, moved);
|
||||
dragIdx = targetIdx;
|
||||
activeDrag.dragIdx = dragIdx;
|
||||
currentItems = next;
|
||||
syncRows();
|
||||
if (rowPool[dragIdx]) {
|
||||
patchClasses(rowPool[dragIdx].rowEl, { 'is-dragging': true });
|
||||
}
|
||||
if (typeof props.onPreview === 'function') {
|
||||
props.onPreview([...currentItems]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const onPointerUp = () => {
|
||||
if (!activeDrag) return;
|
||||
const moved = activeDrag.hasMoved;
|
||||
const changed = !areSlotListsEqual(startItems, currentItems);
|
||||
teardownActiveDrag({ revert: false });
|
||||
if (moved && changed) {
|
||||
emitChange([...currentItems]);
|
||||
}
|
||||
};
|
||||
|
||||
const onPointerCancel = () => {
|
||||
teardownActiveDrag({ revert: true });
|
||||
};
|
||||
|
||||
const onKeyDown = (ev) => {
|
||||
if (ev?.key === 'Escape') {
|
||||
teardownActiveDrag({ revert: true });
|
||||
}
|
||||
};
|
||||
|
||||
const docTarget =
|
||||
typeof document !== 'undefined' && typeof document.addEventListener === 'function'
|
||||
? document
|
||||
: null;
|
||||
|
||||
if (docTarget) {
|
||||
docTarget.addEventListener('pointermove', onPointerMove);
|
||||
docTarget.addEventListener('pointerup', onPointerUp);
|
||||
docTarget.addEventListener('pointercancel', onPointerCancel);
|
||||
docTarget.addEventListener('keydown', onKeyDown);
|
||||
}
|
||||
|
||||
activeDrag = {
|
||||
startItems,
|
||||
dragIdx,
|
||||
hasMoved: false,
|
||||
cleanupListeners: () => {
|
||||
if (docTarget && typeof docTarget.removeEventListener === 'function') {
|
||||
docTarget.removeEventListener('pointermove', onPointerMove);
|
||||
docTarget.removeEventListener('pointerup', onPointerUp);
|
||||
docTarget.removeEventListener('pointercancel', onPointerCancel);
|
||||
docTarget.removeEventListener('keydown', onKeyDown);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createSlotRow() {
|
||||
let rowIndex = 0;
|
||||
const dragHandle = h(
|
||||
'span',
|
||||
{
|
||||
className: 'slot-drag-handle',
|
||||
'aria-hidden': 'true',
|
||||
onPointerdown: (e) => {
|
||||
e.preventDefault?.();
|
||||
e.stopPropagation?.();
|
||||
startPointerDrag(e, rowIndex);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('grip', { size: 12 })]
|
||||
);
|
||||
const indexBadge = h('span', { className: 'slot-index-badge text-mono', text: '1' });
|
||||
const selectComp = CustomSelect({
|
||||
modelValue: '',
|
||||
options: [],
|
||||
onUpdateModelValue: (nextVal) => {
|
||||
if (!nextVal || currentItems[rowIndex] === nextVal) return;
|
||||
if (currentItems.some((v, idx) => idx !== rowIndex && v === nextVal)) return;
|
||||
const next = [...currentItems];
|
||||
next[rowIndex] = nextVal;
|
||||
emitChange(next);
|
||||
},
|
||||
});
|
||||
|
||||
const upBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (rowIndex <= 0) return;
|
||||
const next = [...currentItems];
|
||||
const tmp = next[rowIndex - 1];
|
||||
next[rowIndex - 1] = next[rowIndex];
|
||||
next[rowIndex] = tmp;
|
||||
emitChange(next);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-up', { size: 12 })]
|
||||
);
|
||||
|
||||
const downBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (rowIndex >= currentItems.length - 1) return;
|
||||
const next = [...currentItems];
|
||||
const tmp = next[rowIndex + 1];
|
||||
next[rowIndex + 1] = next[rowIndex];
|
||||
next[rowIndex] = tmp;
|
||||
emitChange(next);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-down', { size: 12 })]
|
||||
);
|
||||
|
||||
const removeBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn slot-remove-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (currentItems.length <= minItems) return;
|
||||
const next = currentItems.filter((_, idx) => idx !== rowIndex);
|
||||
emitChange(next);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('minus', { size: 12 })]
|
||||
);
|
||||
|
||||
const orderBtnsEl = h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]);
|
||||
|
||||
const rowEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'editable-slot-row',
|
||||
onPointerdown: (e) => {
|
||||
if (isNodeWithin(e?.target, selectComp.el) || isNodeWithin(e?.target, orderBtnsEl)) {
|
||||
return;
|
||||
}
|
||||
startPointerDrag(e, rowIndex);
|
||||
},
|
||||
},
|
||||
[dragHandle, indexBadge, selectComp.el, orderBtnsEl]
|
||||
);
|
||||
|
||||
return {
|
||||
rowEl,
|
||||
dragHandle,
|
||||
indexBadge,
|
||||
selectComp,
|
||||
upBtn,
|
||||
downBtn,
|
||||
removeBtn,
|
||||
setIndex(idx) {
|
||||
rowIndex = idx;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncRows() {
|
||||
const count = currentItems.length;
|
||||
patchAttr(emptyEl, 'hidden', count > 0 || !emptyHintText);
|
||||
if (emptyHintText) {
|
||||
patchText(emptyEl, emptyHintText);
|
||||
}
|
||||
patchAttr(listEl, 'hidden', count === 0);
|
||||
|
||||
while (rowPool.length < count) {
|
||||
rowPool.push(createSlotRow());
|
||||
}
|
||||
|
||||
while (listEl.children && listEl.children.length > count) {
|
||||
const tailIdx = listEl.children.length - 1;
|
||||
const tailChild = listEl.children[tailIdx];
|
||||
tailChild?.remove?.();
|
||||
}
|
||||
|
||||
const canDrag = count > 1;
|
||||
const dragTitle = canDrag ? t('settings.slot.dragHint') : '';
|
||||
const canRemove = count > minItems;
|
||||
const removeTitle = canRemove
|
||||
? t('settings.slot.remove')
|
||||
: t('settings.slot.minReached', { min: minItems });
|
||||
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const entry = rowPool[i];
|
||||
const itemVal = currentItems[i];
|
||||
entry.setIndex(i);
|
||||
patchAttr(entry.rowEl, 'data-slot-row', String(i));
|
||||
patchText(entry.indexBadge, String(i + 1));
|
||||
patchClasses(entry.dragHandle, { 'is-disabled': !canDrag });
|
||||
patchAttr(entry.dragHandle, 'title', dragTitle || null);
|
||||
|
||||
const otherUsed = new Set(currentItems.filter((_, idx) => idx !== i));
|
||||
const rowOpts = currentOptions.map((opt) => {
|
||||
const isTaken = otherUsed.has(opt.value);
|
||||
return isTaken
|
||||
? {
|
||||
...opt,
|
||||
disabled: true,
|
||||
meta: t('settings.slot.alreadyAdded'),
|
||||
}
|
||||
: opt;
|
||||
});
|
||||
|
||||
entry.selectComp.setProps({
|
||||
modelValue: itemVal,
|
||||
options: rowOpts,
|
||||
});
|
||||
|
||||
patchAttr(entry.upBtn, 'disabled', i === 0);
|
||||
patchAttr(entry.upBtn, 'title', t('settings.slot.moveUp'));
|
||||
patchAttr(entry.upBtn, 'aria-label', t('settings.slot.moveUp'));
|
||||
|
||||
patchAttr(entry.downBtn, 'disabled', i === count - 1);
|
||||
patchAttr(entry.downBtn, 'title', t('settings.slot.moveDown'));
|
||||
patchAttr(entry.downBtn, 'aria-label', t('settings.slot.moveDown'));
|
||||
|
||||
patchAttr(entry.removeBtn, 'disabled', !canRemove);
|
||||
patchAttr(entry.removeBtn, 'title', removeTitle);
|
||||
patchAttr(entry.removeBtn, 'aria-label', removeTitle);
|
||||
|
||||
if (!listEl.children || listEl.children[i] !== entry.rowEl) {
|
||||
listEl.appendChild(entry.rowEl);
|
||||
}
|
||||
}
|
||||
|
||||
// Close any hidden pooled selects
|
||||
for (let j = count; j < rowPool.length; j += 1) {
|
||||
rowPool[j].selectComp.close();
|
||||
}
|
||||
|
||||
const usedAll = new Set(currentItems);
|
||||
const hasAvailableOption = currentOptions.some((opt) => !usedAll.has(opt.value));
|
||||
const disableAdd = count >= maxItems || !hasAvailableOption;
|
||||
patchAttr(addBtn, 'disabled', disableAdd);
|
||||
const addLabel = addBtnTextFn
|
||||
? addBtnTextFn(count, maxItems)
|
||||
: `+ (${count}/${maxItems})`;
|
||||
patchText(addBtnLabel, addLabel);
|
||||
}
|
||||
|
||||
function setProps(next = {}) {
|
||||
if (!activeDrag && Array.isArray(next.items)) {
|
||||
currentItems = [...next.items];
|
||||
}
|
||||
if (Array.isArray(next.options)) {
|
||||
currentOptions = [...next.options];
|
||||
}
|
||||
if (next.emptyHintText !== undefined) {
|
||||
emptyHintText = String(next.emptyHintText || '');
|
||||
}
|
||||
if (typeof next.addBtnTextFn === 'function') {
|
||||
addBtnTextFn = next.addBtnTextFn;
|
||||
}
|
||||
syncRows();
|
||||
}
|
||||
|
||||
syncRows();
|
||||
|
||||
onCleanup(() => {
|
||||
teardownActiveDrag({ revert: false });
|
||||
for (const entry of rowPool) {
|
||||
entry.selectComp.destroy();
|
||||
}
|
||||
rowPool.length = 0;
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
listEl,
|
||||
addBtn,
|
||||
emptyEl,
|
||||
setProps,
|
||||
getItems: () => [...currentItems],
|
||||
getSelects: () => rowPool.slice(0, currentItems.length).map((r) => r.selectComp),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* @fileoverview Host-aware Theme Accent Swatch Picker (`ThemeColorPicker.js`).
|
||||
* Provides the default "跟随宿主" (`host`) pill plus 6 curated color swatches.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
THEME_ACCENT_PRESETS,
|
||||
normalizeClientThemeAccent,
|
||||
} from '../../core/appearance.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
export const ThemeColorPicker = defineComponent({
|
||||
name: 'ThemeColorPicker',
|
||||
setup({ props }) {
|
||||
let currentKey = normalizeClientThemeAccent(props.modelValue);
|
||||
|
||||
const hostLabelEl = h('span', { text: t('settings.gen.accentHost') });
|
||||
const hostBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'theme-host-chip',
|
||||
'data-accent-key': 'host',
|
||||
onClick: () => selectAccent('host'),
|
||||
},
|
||||
[hostLabelEl]
|
||||
);
|
||||
|
||||
const swatchPresets = THEME_ACCENT_PRESETS.filter((p) => p.key !== 'host');
|
||||
const swatchEntries = swatchPresets.map((preset) => {
|
||||
const checkIcon = createSvgIcon('check', { size: 11 });
|
||||
const btn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'theme-swatch-btn',
|
||||
'data-accent-key': preset.key,
|
||||
title: t(preset.labelKey),
|
||||
'aria-label': t(preset.labelKey),
|
||||
onClick: () => selectAccent(preset.key),
|
||||
},
|
||||
[checkIcon]
|
||||
);
|
||||
patchStyleVar(btn, '--swatch-color', preset.cssColor);
|
||||
return { preset, btn, checkIcon };
|
||||
});
|
||||
|
||||
const swatchGroup = h(
|
||||
'span',
|
||||
{ className: 'theme-swatch-group' },
|
||||
swatchEntries.map((s) => s.btn)
|
||||
);
|
||||
|
||||
const rootEl = h('div', { className: 'theme-color-picker' }, [hostBtn, swatchGroup]);
|
||||
|
||||
function syncVisuals() {
|
||||
const isHost = currentKey === 'host';
|
||||
patchClasses(hostBtn, { 'is-active': isHost });
|
||||
patchAttr(hostBtn, 'aria-pressed', isHost ? 'true' : 'false');
|
||||
for (const entry of swatchEntries) {
|
||||
const active = entry.preset.key === currentKey;
|
||||
patchClasses(entry.btn, { 'is-active': active });
|
||||
patchAttr(entry.btn, 'aria-pressed', active ? 'true' : 'false');
|
||||
patchAttr(entry.checkIcon, 'hidden', !active);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshLabels() {
|
||||
patchText(hostLabelEl, t('settings.gen.accentHost'));
|
||||
for (const entry of swatchEntries) {
|
||||
const label = t(entry.preset.labelKey);
|
||||
patchAttr(entry.btn, 'title', label);
|
||||
patchAttr(entry.btn, 'aria-label', label);
|
||||
}
|
||||
}
|
||||
|
||||
function selectAccent(nextRaw) {
|
||||
const normalized = normalizeClientThemeAccent(nextRaw);
|
||||
if (normalized === currentKey) return;
|
||||
currentKey = normalized;
|
||||
syncVisuals();
|
||||
if (typeof props.onUpdateModelValue === 'function') {
|
||||
props.onUpdateModelValue(currentKey);
|
||||
}
|
||||
}
|
||||
|
||||
function setValue(nextRaw) {
|
||||
currentKey = normalizeClientThemeAccent(nextRaw);
|
||||
syncVisuals();
|
||||
}
|
||||
|
||||
syncVisuals();
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
hostBtn,
|
||||
swatchEntries,
|
||||
setValue,
|
||||
refreshLabels,
|
||||
getValue: () => currentKey,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,403 @@
|
||||
/**
|
||||
* @fileoverview Realistic Simulated Telemetry Builder (`structurePreviewMock.js`)
|
||||
* for `SettingsStructureTab` real-UI live previews.
|
||||
* Exercises all 13 capsule metrics, 8 overview metrics, 10 context channels + subagents,
|
||||
* multi-pool quotas, live running task + subagent, and 12 step table columns.
|
||||
*/
|
||||
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) {
|
||||
const anchorMinMs = Math.floor(Date.now() / 60000) * 60000;
|
||||
const reset5hIso = new Date(anchorMinMs + (2 * 60 + 42) * 60000).toISOString();
|
||||
const resetWkIso = new Date(anchorMinMs + (4 * 24 * 60 + 180) * 60000).toISOString();
|
||||
const resetClaude5hIso = new Date(anchorMinMs + (1 * 60 + 18) * 60000).toISOString();
|
||||
|
||||
const mergedSettings = {
|
||||
...(baseSettings && typeof baseSettings === 'object' ? baseSettings : {}),
|
||||
...draftOverrides,
|
||||
};
|
||||
|
||||
const sessionTitle = t('settings.mock.sessionTitle');
|
||||
const subRole = t('settings.mock.subRole');
|
||||
const promptLatest = t('settings.mock.turnPromptLatest');
|
||||
const promptPrev = t('settings.mock.turnPromptPrev');
|
||||
|
||||
const mainContext = {
|
||||
totalTokens: 142800,
|
||||
limitTokens: 256000,
|
||||
compactionLimitTokens: 256000,
|
||||
usedPct: 55.8,
|
||||
toolResultsTokens: 86400,
|
||||
assistantTokens: 24200,
|
||||
systemToolsTokens: 11800,
|
||||
checkpointTokens: 7600,
|
||||
systemPromptTokens: 5800,
|
||||
skillsTokens: 3100,
|
||||
userRulesTokens: 1900,
|
||||
userInputTokens: 1120,
|
||||
mcpToolsTokens: 540,
|
||||
subagentTokens: 340,
|
||||
};
|
||||
|
||||
const subContext = {
|
||||
totalTokens: 72704,
|
||||
limitTokens: 256000,
|
||||
compactionLimitTokens: 256000,
|
||||
usedPct: 28.4,
|
||||
toolResultsTokens: 51200,
|
||||
assistantTokens: 11400,
|
||||
systemToolsTokens: 5600,
|
||||
systemPromptTokens: 3400,
|
||||
userInputTokens: 1104,
|
||||
checkpointTokens: 0,
|
||||
skillsTokens: 0,
|
||||
userRulesTokens: 0,
|
||||
mcpToolsTokens: 0,
|
||||
subagentTokens: 0,
|
||||
};
|
||||
|
||||
const mockSteps = [
|
||||
{
|
||||
stepIndex: 24,
|
||||
agentCascadeId: 'mock-main',
|
||||
agentId: 'main',
|
||||
agentIndex: 0,
|
||||
isSubagent: false,
|
||||
agentBadge: '主',
|
||||
agentLabel: t('fmt.mainAgent'),
|
||||
modelLabel: 'Gemini 4 Carbon (High)',
|
||||
modelShort: 'carbon-4-high',
|
||||
rawModel: 'MODEL_PLACEHOLDER_M37',
|
||||
modelUpstream: 'gemini-4-carbon-high',
|
||||
upstreamModel: 'gemini-4-carbon-high',
|
||||
tokPerSec: 68.4,
|
||||
ttftSec: 1.15,
|
||||
totalDurationSec: 12.6,
|
||||
streamDurationSec: 11.45,
|
||||
contextTokens: 142800,
|
||||
inputTokens: 7800,
|
||||
cacheReadTokens: 133580,
|
||||
outputTokens: 1420,
|
||||
thinkingTokens: 860,
|
||||
responseTokens: 560,
|
||||
cacheHitPct: 94.5,
|
||||
costUsd: 0.042,
|
||||
inCostUsd: 0.0156,
|
||||
cacheCostUsd: 0.0134,
|
||||
outCostUsd: 0.0142,
|
||||
createdAtMs: anchorMinMs - 14_000,
|
||||
turnIndex: 2,
|
||||
rootTurnIndex: 2,
|
||||
isTurnStart: false,
|
||||
isRootTurnStart: false,
|
||||
isLatestTurn: true,
|
||||
isRootLatestTurn: true,
|
||||
turnPrompt: promptLatest,
|
||||
rootTurnPrompt: promptLatest,
|
||||
},
|
||||
{
|
||||
stepIndex: 8,
|
||||
agentCascadeId: 'mock-sub-1',
|
||||
agentId: 'sub-1',
|
||||
agentIndex: 1,
|
||||
isSubagent: true,
|
||||
agentBadge: '子1',
|
||||
agentRole: subRole,
|
||||
agentLabel: subRole,
|
||||
modelLabel: 'Gemini 3.8 Flash',
|
||||
modelShort: 'flash-3.8',
|
||||
rawModel: 'MODEL_PLACEHOLDER_M42',
|
||||
modelUpstream: 'gemini-3.8-flash-n',
|
||||
upstreamModel: 'gemini-3.8-flash-n',
|
||||
tokPerSec: 96.2,
|
||||
ttftSec: 0.68,
|
||||
totalDurationSec: 5.4,
|
||||
streamDurationSec: 4.72,
|
||||
contextTokens: 72704,
|
||||
inputTokens: 8600,
|
||||
cacheReadTokens: 63400,
|
||||
outputTokens: 704,
|
||||
thinkingTokens: 240,
|
||||
responseTokens: 464,
|
||||
cacheHitPct: 88.1,
|
||||
costUsd: 0.009,
|
||||
inCostUsd: 0.0065,
|
||||
cacheCostUsd: 0.0005,
|
||||
outCostUsd: 0.0026,
|
||||
createdAtMs: anchorMinMs - 42_000,
|
||||
turnIndex: 1,
|
||||
rootTurnIndex: 2,
|
||||
isTurnStart: true,
|
||||
isRootTurnStart: false,
|
||||
isLatestTurn: true,
|
||||
isRootLatestTurn: true,
|
||||
turnPrompt: promptLatest,
|
||||
rootTurnPrompt: promptLatest,
|
||||
},
|
||||
{
|
||||
stepIndex: 22,
|
||||
agentCascadeId: 'mock-main',
|
||||
agentId: 'main',
|
||||
agentIndex: 0,
|
||||
isSubagent: false,
|
||||
agentBadge: '主',
|
||||
agentLabel: t('fmt.mainAgent'),
|
||||
isCompactionStep: true,
|
||||
modelLabel: 'Gemini 4 Carbon (High) [自动压缩]',
|
||||
modelShort: 'carbon-4-high·压缩',
|
||||
rawModel: 'MODEL_PLACEHOLDER_M37',
|
||||
modelUpstream: 'gemini-4-carbon-high·压缩',
|
||||
upstreamModel: 'gemini-4-carbon-high',
|
||||
tokPerSec: 46.5,
|
||||
ttftSec: 3.4,
|
||||
totalDurationSec: 15.8,
|
||||
streamDurationSec: 12.4,
|
||||
contextTokens: 128400,
|
||||
inputTokens: 49200,
|
||||
cacheReadTokens: 78100,
|
||||
outputTokens: 1100,
|
||||
thinkingTokens: 720,
|
||||
responseTokens: 380,
|
||||
cacheHitPct: 61.4,
|
||||
costUsd: 0.068,
|
||||
inCostUsd: 0.0492,
|
||||
cacheCostUsd: 0.0078,
|
||||
outCostUsd: 0.011,
|
||||
createdAtMs: anchorMinMs - 88_000,
|
||||
turnIndex: 2,
|
||||
rootTurnIndex: 2,
|
||||
isTurnStart: true,
|
||||
isRootTurnStart: true,
|
||||
isLatestTurn: true,
|
||||
isRootLatestTurn: true,
|
||||
turnPrompt: promptLatest,
|
||||
rootTurnPrompt: promptLatest,
|
||||
},
|
||||
{
|
||||
stepIndex: 19,
|
||||
agentCascadeId: 'mock-main',
|
||||
agentId: 'main',
|
||||
agentIndex: 0,
|
||||
isSubagent: false,
|
||||
agentBadge: '主',
|
||||
agentLabel: t('fmt.mainAgent'),
|
||||
modelLabel: 'Gemini 4 Carbon (High)',
|
||||
modelShort: 'gemini-4-carbon',
|
||||
rawModel: 'MODEL_PLACEHOLDER_M37',
|
||||
upstreamModel: 'gemini-4-carbon-high',
|
||||
tokPerSec: 17.8,
|
||||
ttftSec: 19.4,
|
||||
totalDurationSec: 31.2,
|
||||
streamDurationSec: 11.8,
|
||||
contextTokens: 96200,
|
||||
inputTokens: 95400,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 800,
|
||||
thinkingTokens: 540,
|
||||
responseTokens: 260,
|
||||
cacheHitPct: 0,
|
||||
costUsd: 0.198,
|
||||
createdAtMs: anchorMinMs - 215_000,
|
||||
turnIndex: 1,
|
||||
rootTurnIndex: 1,
|
||||
isTurnStart: true,
|
||||
isRootTurnStart: true,
|
||||
isLatestTurn: false,
|
||||
isRootLatestTurn: false,
|
||||
turnPrompt: promptPrev,
|
||||
rootTurnPrompt: promptPrev,
|
||||
},
|
||||
];
|
||||
|
||||
const mainAgent = {
|
||||
agentId: 'main',
|
||||
cascadeId: 'mock-main',
|
||||
isMain: true,
|
||||
index: 0,
|
||||
badgeText: '主',
|
||||
role: t('fmt.mainAgent'),
|
||||
isRunning: true,
|
||||
stepCount: 16,
|
||||
speedSampleCount: 15,
|
||||
latestTokPerSec: 68.4,
|
||||
avgTokPerSec: 54.8,
|
||||
latestTtftSec: 1.15,
|
||||
avgTtftSec: 1.62,
|
||||
latestStepCostUsd: 0.042,
|
||||
sessionCostUsd: 1.16,
|
||||
latestCacheHitPct: 94.5,
|
||||
sessionCacheHitPct: 89.2,
|
||||
latestPromptTokens: 141380,
|
||||
inputTokens: 152400,
|
||||
cacheReadTokens: 1260000,
|
||||
outputTokens: 22100,
|
||||
totalTokens: 1434500,
|
||||
latestModelLabel: 'Gemini 4 Carbon (High)',
|
||||
latestModelShort: 'gemini-4-carbon',
|
||||
latestRawModel: 'MODEL_PLACEHOLDER_M37',
|
||||
latestUpstreamModel: 'gemini-4-carbon-high',
|
||||
activeModelLabel: 'Gemini 4 Carbon (High)',
|
||||
activeModelShort: 'gemini-4-carbon',
|
||||
context: mainContext,
|
||||
recentSteps: mockSteps.filter((s) => !s.isSubagent),
|
||||
};
|
||||
|
||||
const subAgent1 = {
|
||||
agentId: 'sub-1',
|
||||
cascadeId: 'mock-sub-1',
|
||||
isMain: false,
|
||||
index: 1,
|
||||
badgeText: '子1',
|
||||
shortLabel: `${t('fmt.subAgent')} #1`,
|
||||
role: subRole,
|
||||
isRunning: false,
|
||||
stepCount: 8,
|
||||
speedSampleCount: 8,
|
||||
latestTokPerSec: 96.2,
|
||||
avgTokPerSec: 88.5,
|
||||
latestTtftSec: 0.68,
|
||||
avgTtftSec: 0.82,
|
||||
latestStepCostUsd: 0.009,
|
||||
sessionCostUsd: 0.12,
|
||||
latestCacheHitPct: 88.1,
|
||||
sessionCacheHitPct: 86.4,
|
||||
latestPromptTokens: 72000,
|
||||
inputTokens: 34000,
|
||||
cacheReadTokens: 280000,
|
||||
outputTokens: 6300,
|
||||
totalTokens: 320300,
|
||||
latestModelLabel: 'Gemini 3.8 Flash',
|
||||
latestModelShort: 'gemini-3.8-flash',
|
||||
latestRawModel: 'MODEL_PLACEHOLDER_M42',
|
||||
latestUpstreamModel: 'gemini-3.8-flash-n',
|
||||
activeModelLabel: 'Gemini 3.8 Flash',
|
||||
activeModelShort: 'gemini-3.8-flash',
|
||||
context: subContext,
|
||||
recentSteps: mockSteps.filter((s) => s.isSubagent),
|
||||
};
|
||||
|
||||
const aggregated = {
|
||||
...mainAgent,
|
||||
stepCount: 24,
|
||||
speedSampleCount: 23,
|
||||
avgTokPerSec: 59.6,
|
||||
avgTtftSec: 1.38,
|
||||
sessionCostUsd: 1.28,
|
||||
sessionCacheHitPct: 88.9,
|
||||
inputTokens: 186400,
|
||||
cacheReadTokens: 1540000,
|
||||
outputTokens: 28400,
|
||||
totalTokens: 1754800,
|
||||
activeAgentBadge: '主',
|
||||
recentSteps: mockSteps,
|
||||
};
|
||||
|
||||
return {
|
||||
settings: mergedSettings,
|
||||
account: {
|
||||
planName: 'Google AI Pro',
|
||||
aiCredits: 1200,
|
||||
},
|
||||
quotas: {
|
||||
activePool: {
|
||||
family: 'Gemini',
|
||||
poolKey: 'Gemini',
|
||||
poolLabel: 'Gemini',
|
||||
usedPct: 36,
|
||||
remainingPct: 64,
|
||||
resetTime: reset5hIso,
|
||||
weeklyUsedPct: 48,
|
||||
weeklyRemainingPct: 52,
|
||||
weeklyResetTime: resetWkIso,
|
||||
},
|
||||
pools: [
|
||||
{
|
||||
poolKey: 'Gemini',
|
||||
poolLabel: 'Gemini',
|
||||
family: 'Gemini',
|
||||
usedPct: 36,
|
||||
remainingPct: 64,
|
||||
resetTime: reset5hIso,
|
||||
weeklyUsedPct: 48,
|
||||
weeklyRemainingPct: 52,
|
||||
weeklyResetTime: resetWkIso,
|
||||
cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 },
|
||||
cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 },
|
||||
},
|
||||
{
|
||||
poolKey: 'Claude & GPT',
|
||||
poolLabel: 'Claude & GPT',
|
||||
family: 'Claude & GPT',
|
||||
usedPct: 68,
|
||||
remainingPct: 32,
|
||||
resetTime: resetClaude5hIso,
|
||||
weeklyUsedPct: 41,
|
||||
weeklyRemainingPct: 59,
|
||||
weeklyResetTime: resetWkIso,
|
||||
cycle5h: { tokens: 620000, costUsd: 2.15, calls: 11 },
|
||||
cycleWeekly: { tokens: 5800000, costUsd: 18.6, calls: 92 },
|
||||
},
|
||||
],
|
||||
weekly: {
|
||||
isOfficial: true,
|
||||
usedPct: 48,
|
||||
remainingPct: 52,
|
||||
resetTime: resetWkIso,
|
||||
tokens: 20000000,
|
||||
costUsd: 30.0,
|
||||
calls: 278,
|
||||
},
|
||||
},
|
||||
runningConversations: [
|
||||
{
|
||||
cascadeId: 'mock-preview-conv',
|
||||
title: sessionTitle,
|
||||
isCurrentSelected: true,
|
||||
isMainRunning: true,
|
||||
isRunning: true,
|
||||
subagentCount: 1,
|
||||
runningSubagentCount: 0,
|
||||
latestTokPerSec: 68.4,
|
||||
contextUsedPct: 55.8,
|
||||
mainActivity: {
|
||||
phase: 'generating',
|
||||
label: t('live.generating'),
|
||||
stepProgress: '#24',
|
||||
detail: 'src/auth/tokenRefresh.ts',
|
||||
startedAtMs: Date.now() - 8000,
|
||||
signature: 'mock-preview:24',
|
||||
},
|
||||
subagents: [
|
||||
{
|
||||
cascadeId: 'mock-sub-1',
|
||||
index: 1,
|
||||
badgeText: '子1',
|
||||
shortLabel: `${t('fmt.subAgent')} #1`,
|
||||
role: subRole,
|
||||
isRunning: false,
|
||||
stepCount: 8,
|
||||
lastModifiedMs: anchorMinMs - 42_000,
|
||||
liveActivity: {
|
||||
phase: 'done',
|
||||
label: t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: anchorMinMs - 42_000,
|
||||
signature: 'mock-sub-1:8',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeConversation: {
|
||||
...mainAgent,
|
||||
cascadeId: 'mock-preview-conv',
|
||||
title: sessionTitle,
|
||||
hasSubagents: true,
|
||||
agents: [mainAgent, subAgent1],
|
||||
aggregated,
|
||||
recentSteps: mockSteps,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -77,6 +77,7 @@ export const CustomNumberInput = defineComponent({
|
||||
commitManualInput();
|
||||
}
|
||||
},
|
||||
onChange: () => commitManualInput(),
|
||||
onBlur: () => commitManualInput(),
|
||||
});
|
||||
|
||||
@@ -102,12 +103,13 @@ export const CustomNumberInput = defineComponent({
|
||||
}
|
||||
|
||||
function syncFieldDisplay(val = getProps().modelValue) {
|
||||
const { min, max } = getProps();
|
||||
const { min, max, ariaLabel } = getProps();
|
||||
const normalized = clampValue(val);
|
||||
if (textField.value !== String(normalized)) {
|
||||
textField.value = String(normalized);
|
||||
}
|
||||
patchAttr(textField, 'aria-valuenow', normalized);
|
||||
if (ariaLabel) patchAttr(textField, 'aria-label', ariaLabel);
|
||||
if (Number.isFinite(min)) patchAttr(textField, 'aria-valuemin', min);
|
||||
if (Number.isFinite(max)) patchAttr(textField, 'aria-valuemax', max);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* @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';
|
||||
@@ -12,8 +13,43 @@ import {
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { isEnglishLocale, t } from '../../i18n/index.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({
|
||||
name: 'CustomSelect',
|
||||
setup({ getProps, setProps, emit, onCleanup }) {
|
||||
@@ -49,33 +85,84 @@ export const CustomSelect = defineComponent({
|
||||
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]);
|
||||
|
||||
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) {
|
||||
isOpen = Boolean(nextOpen);
|
||||
if (isOpen) {
|
||||
const opts = getProps().options || [];
|
||||
const selSet = getSelectedSet();
|
||||
focusedIndex = Math.max(
|
||||
0,
|
||||
opts.findIndex((o) => selSet.has(o.value))
|
||||
);
|
||||
renderMenuOptions();
|
||||
}
|
||||
patchClasses(rootEl, { 'is-open': isOpen });
|
||||
patchAttr(triggerBtn, 'aria-expanded', isOpen ? 'true' : 'false');
|
||||
patchAttr(menuEl, 'hidden', !isOpen);
|
||||
patchSvgIcon(chevronIcon, isOpen ? 'chevron-up' : 'chevron-down');
|
||||
if (isOpen) {
|
||||
const opts = getProps().options || [];
|
||||
const currentVal = getProps().modelValue;
|
||||
focusedIndex = Math.max(
|
||||
0,
|
||||
opts.findIndex((o) => o.value === currentVal)
|
||||
);
|
||||
renderMenuOptions();
|
||||
}
|
||||
}
|
||||
|
||||
function chooseOption(option) {
|
||||
if (!option) return;
|
||||
const prevVal = getProps().modelValue;
|
||||
toggleOpen(false);
|
||||
if (option.value !== prevVal) {
|
||||
setProps({ modelValue: option.value });
|
||||
emit('update:modelValue', option.value);
|
||||
if (option.disabled && !getSelectedSet().has(option.value)) return;
|
||||
const { multiple, options = [], allValue = '', collapseAll = false } = getProps();
|
||||
if (!multiple) {
|
||||
const prevVal = getProps().modelValue;
|
||||
toggleOpen(false);
|
||||
if (option.value !== prevVal) {
|
||||
setProps({ 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +188,7 @@ export const CustomSelect = defineComponent({
|
||||
renderMenuOptions();
|
||||
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();
|
||||
const target = opts[focusedIndex];
|
||||
if (target) chooseOption(target);
|
||||
@@ -112,14 +199,20 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
|
||||
function renderMenuOptions() {
|
||||
const { options = [], modelValue } = getProps();
|
||||
const { options = [], multiple = false } = getProps();
|
||||
const selSet = getSelectedSet();
|
||||
patchAttr(menuEl, 'aria-multiselectable', multiple ? 'true' : null);
|
||||
patchKeyedList(menuEl, options, {
|
||||
keyFn: (opt) => opt.value,
|
||||
sigFn: (opt, idx) =>
|
||||
`${opt.value}::${opt.label}::${opt.meta || ''}::${opt.value === modelValue}::${idx === focusedIndex}`,
|
||||
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${Boolean(opt.disabled)}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
|
||||
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 metaSpan = h('span', { className: 'text-muted' });
|
||||
const metaSpan = h('span', { className: 'text-muted select-option-meta' });
|
||||
const checkIcon = createSvgIcon('check', { size: 12 });
|
||||
const btn = h(
|
||||
'button',
|
||||
@@ -129,25 +222,34 @@ export const CustomSelect = defineComponent({
|
||||
className: 'select-option',
|
||||
onClick: (e) => {
|
||||
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);
|
||||
},
|
||||
},
|
||||
[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) => {
|
||||
const selected = opt.value === modelValue;
|
||||
const isMulti = Boolean(getProps().multiple);
|
||||
const selected = selSet.has(opt.value);
|
||||
const focused = idx === focusedIndex;
|
||||
const isDisabled = Boolean(opt.disabled && !selected);
|
||||
patchAttr(refs.checkboxBox, 'hidden', !isMulti);
|
||||
patchClasses(refs.checkboxBox, { 'is-checked': selected });
|
||||
patchAttr(refs.checkboxIcon, 'hidden', !selected);
|
||||
patchText(refs.textSpan, opt.label);
|
||||
patchText(refs.metaSpan, opt.meta || '');
|
||||
patchAttr(refs.metaSpan, 'hidden', !opt.meta);
|
||||
patchAttr(refs.checkIcon, 'hidden', !selected);
|
||||
patchAttr(refs.checkIcon, 'hidden', isMulti || !selected);
|
||||
patchClasses(el, {
|
||||
'is-selected': selected,
|
||||
'is-focused': focused,
|
||||
'is-disabled': isDisabled,
|
||||
});
|
||||
patchAttr(el, 'disabled', isDisabled);
|
||||
patchAttr(el, 'aria-disabled', isDisabled ? 'true' : null);
|
||||
patchAttr(el, 'aria-selected', selected ? 'true' : 'false');
|
||||
patchAttr(el, 'data-value', opt.value);
|
||||
},
|
||||
@@ -155,17 +257,54 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
|
||||
function syncTriggerAndMenu() {
|
||||
const { options = [], modelValue, placeholder = '请选择', icon } = getProps();
|
||||
const {
|
||||
options = [],
|
||||
modelValue,
|
||||
placeholder = t('fmt.selectPlaceholder'),
|
||||
icon,
|
||||
multiple = false,
|
||||
allValue = '',
|
||||
multiUnit = isEnglishLocale() ? 'items' : '项',
|
||||
} = getProps();
|
||||
patchClasses(rootEl, { 'is-multi': Boolean(multiple) });
|
||||
patchAttr(leadIcon, 'hidden', !icon);
|
||||
if (icon) {
|
||||
patchSvgIcon(leadIcon, icon);
|
||||
}
|
||||
const matchedOpt = options.find((o) => o.value === modelValue);
|
||||
const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined);
|
||||
const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder;
|
||||
const labelText = selectedOpt ? selectedOpt.label : fallbackText;
|
||||
|
||||
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 = t('fmt.selectedCount', { count: vals.length, unit: multiUnit });
|
||||
titleText = t('fmt.selectedListTitle', {
|
||||
count: vals.length,
|
||||
names: names.join(isEnglishLocale() ? ', ' : '、'),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const matchedOpt = options.find((o) => o.value === modelValue);
|
||||
const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined);
|
||||
const fallbackText = modelValue
|
||||
? `${placeholder} (${String(modelValue).slice(0, 8)})`
|
||||
: placeholder;
|
||||
labelText = selectedOpt ? selectedOpt.label : fallbackText;
|
||||
titleText = labelText;
|
||||
}
|
||||
|
||||
patchText(triggerLabel, labelText);
|
||||
patchAttr(triggerBtn, 'title', labelText);
|
||||
patchAttr(triggerBtn, 'title', titleText);
|
||||
if (isOpen) {
|
||||
renderMenuOptions();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
/**
|
||||
* @fileoverview Shared Decoupled Capsule Bar Primitives & Widget (`CapsuleBarWidget.js`).
|
||||
* Powers both the live host window capsule (`WindowOverlayShell.js`) and the
|
||||
* real-UI structure preview (`SettingsStructureTab.js`), ensuring 100% DOM/CSS parity.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, SVG_NS } from '../../icons/SvgIcon.js';
|
||||
import { resolveCapsuleMetricPresentation } from '../../registries/metricRegistry.js';
|
||||
import {
|
||||
normalizeClientTopbarSlots,
|
||||
normalizeClientWindowMountMode,
|
||||
resolveScopedConversation,
|
||||
} from '../../store/telemetryStore.js';
|
||||
|
||||
export const RING_RADIUS = 5.2;
|
||||
export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
|
||||
|
||||
/**
|
||||
* Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring.
|
||||
*/
|
||||
export function createCapsuleSlotNode(slotIndex, initialMetric) {
|
||||
const ringSvg = document.createElementNS(SVG_NS, 'svg');
|
||||
ringSvg.setAttribute('viewBox', '0 0 14 14');
|
||||
ringSvg.setAttribute('class', 'wm-ring-svg');
|
||||
ringSvg.setAttribute('aria-hidden', 'true');
|
||||
|
||||
const ringTrack = document.createElementNS(SVG_NS, 'circle');
|
||||
ringTrack.setAttribute('cx', '7');
|
||||
ringTrack.setAttribute('cy', '7');
|
||||
ringTrack.setAttribute('r', String(RING_RADIUS));
|
||||
ringTrack.setAttribute('class', 'wm-ring-track');
|
||||
|
||||
const ringFill = document.createElementNS(SVG_NS, 'circle');
|
||||
ringFill.setAttribute('cx', '7');
|
||||
ringFill.setAttribute('cy', '7');
|
||||
ringFill.setAttribute('r', String(RING_RADIUS));
|
||||
ringFill.setAttribute('class', 'wm-ring-fill');
|
||||
ringFill.setAttribute('stroke-dasharray', String(RING_CIRCUMFERENCE));
|
||||
ringFill.setAttribute('stroke-dashoffset', String(RING_CIRCUMFERENCE));
|
||||
|
||||
ringSvg.appendChild(ringTrack);
|
||||
ringSvg.appendChild(ringFill);
|
||||
|
||||
const isNone = initialMetric === 'none';
|
||||
const isCtx = initialMetric === 'context';
|
||||
const textSpan = h('span', {
|
||||
className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text',
|
||||
text: isNone
|
||||
? ''
|
||||
: isCtx
|
||||
? '--%'
|
||||
: initialMetric === 'tps'
|
||||
? '-- t/s'
|
||||
: initialMetric === 'ttft'
|
||||
? '--s'
|
||||
: t('capsule.quotaUnknown'),
|
||||
});
|
||||
const el = h(
|
||||
'span',
|
||||
{
|
||||
className: isNone
|
||||
? 'wm-cap-slot'
|
||||
: isCtx
|
||||
? 'wm-cap-slot wm-ctx-seg'
|
||||
: initialMetric === 'tps'
|
||||
? 'wm-cap-slot wm-seg-speed'
|
||||
: initialMetric === 'ttft'
|
||||
? 'wm-cap-slot wm-seg-metric'
|
||||
: 'wm-cap-slot wm-seg-quota',
|
||||
hidden: isNone,
|
||||
'data-slot-idx': String(slotIndex),
|
||||
'data-metric': initialMetric,
|
||||
'data-vis-rank': isNone ? '' : String(slotIndex + 1),
|
||||
},
|
||||
isCtx ? [ringSvg, textSpan] : [textSpan]
|
||||
);
|
||||
|
||||
return {
|
||||
el,
|
||||
ringSvg,
|
||||
ringFill,
|
||||
textSpan,
|
||||
ringMounted: isCtx,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch 5 pre-allocated capsule slots and 4 separators in-place via `metricRegistry`.
|
||||
*/
|
||||
export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx) {
|
||||
let visRank = 0;
|
||||
const visRanks = [0, 0, 0, 0, 0];
|
||||
for (let i = 0; i < capsuleSlots.length; i += 1) {
|
||||
const slot = capsuleSlots[i];
|
||||
const metricKey = i < slotKeys.length ? slotKeys[i] : 'none';
|
||||
const pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE);
|
||||
if (pres.hidden) {
|
||||
patchAttr(slot.el, 'hidden', true);
|
||||
patchAttr(slot.el, 'data-metric', 'none');
|
||||
patchAttr(slot.el, 'data-vis-rank', '');
|
||||
continue;
|
||||
}
|
||||
visRank += 1;
|
||||
visRanks[i] = visRank;
|
||||
patchAttr(slot.el, 'hidden', false);
|
||||
patchAttr(slot.el, 'data-metric', pres.metric);
|
||||
patchAttr(slot.el, 'data-vis-rank', String(visRank));
|
||||
|
||||
if (pres.showRing && !slot.ringMounted) {
|
||||
slot.el.insertBefore(slot.ringSvg, slot.textSpan);
|
||||
slot.ringMounted = true;
|
||||
} else if (!pres.showRing && slot.ringMounted) {
|
||||
slot.ringSvg.remove();
|
||||
slot.ringMounted = false;
|
||||
}
|
||||
|
||||
const toneCls =
|
||||
pres.toneClass || (pres.danger ? 'tone-danger' : pres.warn ? 'tone-warn' : '');
|
||||
const fullSegClass = `${pres.segClass}${pres.running ? ' state-running' : ''}${toneCls ? ` ${toneCls}` : ''}`;
|
||||
patchAttr(slot.el, 'class', fullSegClass);
|
||||
const fullTextClass = `${pres.textClass}${toneCls ? ` ${toneCls}` : ''}`;
|
||||
patchAttr(slot.textSpan, 'class', fullTextClass);
|
||||
patchText(slot.textSpan, pres.text);
|
||||
|
||||
if (pres.showRing) {
|
||||
slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset));
|
||||
patchClasses(slot.ringFill, { 'tone-warn': pres.warn, 'tone-danger': pres.danger });
|
||||
}
|
||||
}
|
||||
|
||||
for (let s = 0; s < capsuleSeps.length; s += 1) {
|
||||
const sepEl = capsuleSeps[s];
|
||||
const nextRank = visRanks[s + 1] || 0;
|
||||
const showSep = nextRank >= 2;
|
||||
patchAttr(sepEl, 'hidden', !showSep);
|
||||
patchAttr(sepEl, 'data-sep-for-rank', showSep ? String(nextRank) : '');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Standalone Capsule Bar Preview Widget mounting the real `.wm-multi-btn` and `.wm-capsule-btn`
|
||||
* inside a contextual host bar (`dual` titlebar, `composer` toolbar, or `sidebar` disabled state).
|
||||
*/
|
||||
export const CapsuleBarWidget = defineComponent({
|
||||
name: 'CapsuleBarWidget',
|
||||
setup() {
|
||||
const multiDot = h('span', { className: 'wm-multi-dot' });
|
||||
const multiLabel = h('span', {
|
||||
className: 'wm-multi-label',
|
||||
text: t('capsule.multiZero'),
|
||||
});
|
||||
const multiBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'wm-multi-btn',
|
||||
tabindex: '-1',
|
||||
'aria-hidden': 'true',
|
||||
},
|
||||
[multiDot, multiLabel]
|
||||
);
|
||||
|
||||
const capsuleSlots = [
|
||||
createCapsuleSlotNode(0, 'tps'),
|
||||
createCapsuleSlotNode(1, 'ttft'),
|
||||
createCapsuleSlotNode(2, 'context'),
|
||||
createCapsuleSlotNode(3, 'none'),
|
||||
createCapsuleSlotNode(4, 'none'),
|
||||
];
|
||||
const capsuleSeps = [
|
||||
h('span', { className: 'wm-sep wm-sep-speed', 'data-sep-for-rank': '2' }),
|
||||
h('span', { className: 'wm-sep wm-sep-quota', 'data-sep-for-rank': '3' }),
|
||||
h('span', { className: 'wm-sep', 'data-sep-for-rank': '', hidden: true }),
|
||||
h('span', { className: 'wm-sep', 'data-sep-for-rank': '', hidden: true }),
|
||||
];
|
||||
|
||||
const capsuleBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'wm-capsule-btn',
|
||||
tabindex: '-1',
|
||||
'aria-hidden': 'true',
|
||||
},
|
||||
[
|
||||
capsuleSlots[0].el,
|
||||
capsuleSeps[0],
|
||||
capsuleSlots[1].el,
|
||||
capsuleSeps[1],
|
||||
capsuleSlots[2].el,
|
||||
capsuleSeps[2],
|
||||
capsuleSlots[3].el,
|
||||
capsuleSeps[3],
|
||||
capsuleSlots[4].el,
|
||||
]
|
||||
);
|
||||
|
||||
const capsuleCluster = h('div', { className: 'preview-capsule-cluster' }, [
|
||||
multiBtn,
|
||||
capsuleBtn,
|
||||
]);
|
||||
|
||||
// Contextual host chrome affordances for Titlebar vs Composer vs Sidebar-only
|
||||
const titlebarLeftMock = h('div', { className: 'preview-host-left is-titlebar' }, [
|
||||
h('span', { className: 'preview-win-title', text: 'Antigravity' }),
|
||||
]);
|
||||
const composerLeftMock = h(
|
||||
'div',
|
||||
{ className: 'preview-host-left is-composer', hidden: true },
|
||||
[
|
||||
h('span', { className: 'preview-composer-chip' }, [
|
||||
h('span', { text: 'Auto' }),
|
||||
createSvgIcon('chevron-down', { size: 10 }),
|
||||
]),
|
||||
h('span', { className: 'preview-composer-chip' }, [
|
||||
h('span', { text: 'Carbon (High)' }),
|
||||
createSvgIcon('chevron-down', { size: 10 }),
|
||||
]),
|
||||
]
|
||||
);
|
||||
|
||||
const titlebarRightMock = h('div', { className: 'preview-win-controls', 'aria-hidden': 'true' }, [
|
||||
h('span', { className: 'preview-win-dot' }),
|
||||
h('span', { className: 'preview-win-dot' }),
|
||||
h('span', { className: 'preview-win-dot' }),
|
||||
]);
|
||||
const composerSendMock = h(
|
||||
'span',
|
||||
{ className: 'preview-composer-send', 'aria-hidden': 'true', hidden: true },
|
||||
[createSvgIcon('arrow-up', { size: 11 })]
|
||||
);
|
||||
|
||||
const hostBarEl = h(
|
||||
'div',
|
||||
{ className: 'preview-capsule-bar', 'data-mount-mode': 'dual' },
|
||||
[titlebarLeftMock, composerLeftMock, capsuleCluster, titlebarRightMock, composerSendMock]
|
||||
);
|
||||
|
||||
const sidebarHintEl = h('div', {
|
||||
className: 'preview-sidebar-note',
|
||||
hidden: true,
|
||||
text: t('settings.str.previewMountSidebarHint'),
|
||||
});
|
||||
|
||||
const rootEl = h('div', { className: 'capsule-preview-widget' }, [hostBarEl, sidebarHintEl]);
|
||||
|
||||
function update({ data } = {}) {
|
||||
const settings = data?.settings || {};
|
||||
const mountMode = normalizeClientWindowMountMode(
|
||||
settings.windowMountMode,
|
||||
settings.enableWindowOverlay
|
||||
);
|
||||
const showMulti = settings.showTopbarMultiSession !== false;
|
||||
const slotKeys = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
|
||||
const isComposer = mountMode === 'composer';
|
||||
const isSidebar = mountMode === 'sidebar';
|
||||
patchAttr(hostBarEl, 'data-mount-mode', mountMode);
|
||||
patchClasses(hostBarEl, {
|
||||
'is-composer': isComposer,
|
||||
'is-sidebar-only': isSidebar,
|
||||
});
|
||||
|
||||
patchAttr(titlebarLeftMock, 'hidden', isComposer);
|
||||
patchAttr(titlebarRightMock, 'hidden', isComposer);
|
||||
patchAttr(composerLeftMock, 'hidden', !isComposer);
|
||||
patchAttr(composerSendMock, 'hidden', !isComposer);
|
||||
patchAttr(sidebarHintEl, 'hidden', !isSidebar);
|
||||
patchText(sidebarHintEl, t('settings.str.previewMountSidebarHint'));
|
||||
|
||||
patchAttr(multiBtn, 'hidden', !showMulti);
|
||||
|
||||
if (!data) {
|
||||
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
|
||||
patchText(multiLabel, t('capsule.multiZero'));
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { hasTelemetry: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation(
|
||||
data,
|
||||
'all',
|
||||
'auto'
|
||||
);
|
||||
const activeConv = data.activeConversation || {};
|
||||
const capActive = scopedConv || aggregated || activeConv;
|
||||
const ctx = ctxAgent?.context || capActive.context || activeConv.context || {};
|
||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTokens = Number(ctx.totalTokens || 0);
|
||||
const usedPct =
|
||||
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||
const dashOffset = +(
|
||||
RING_CIRCUMFERENCE *
|
||||
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
|
||||
).toFixed(2);
|
||||
|
||||
const rawRunningList = Array.isArray(data.runningConversations)
|
||||
? data.runningConversations
|
||||
: [];
|
||||
const runningCount = rawRunningList.length;
|
||||
const runningSubCount = rawRunningList.reduce(
|
||||
(acc, item) => acc + Number(item.runningSubagentCount || 0),
|
||||
0
|
||||
);
|
||||
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
|
||||
|
||||
patchClasses(multiBtn, {
|
||||
'is-running': runningCount > 0 && !hasWaiting,
|
||||
'is-waiting': runningCount > 0 && hasWaiting,
|
||||
});
|
||||
const multiBtnText =
|
||||
runningCount > 0
|
||||
? runningSubCount > 0
|
||||
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
|
||||
: t('capsule.multiRunning', { count: runningCount })
|
||||
: t('capsule.multiZero');
|
||||
patchText(multiLabel, multiBtnText);
|
||||
|
||||
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
|
||||
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
|
||||
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
|
||||
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
|
||||
const sessionTokens =
|
||||
Number(capActive.stepCount || 0) > 0 ||
|
||||
capActive.totalTokens != null ||
|
||||
capInTok + capCacheTok + capOutTok > 0
|
||||
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
|
||||
: null;
|
||||
|
||||
patchClasses(capsuleBtn, { 'is-running': isRunning });
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, {
|
||||
hasTelemetry: true,
|
||||
usedPct,
|
||||
dashOffset,
|
||||
isRunning,
|
||||
tps: capActive.latestTokPerSec ?? null,
|
||||
avgTps: capActive.avgTokPerSec ?? null,
|
||||
ttft: capActive.latestTtftSec ?? null,
|
||||
stepCost: capActive.latestStepCostUsd ?? null,
|
||||
sessionCost: capActive.sessionCostUsd ?? null,
|
||||
cacheHitPct:
|
||||
Number(capActive.stepCount || 0) > 0
|
||||
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
|
||||
: null,
|
||||
latestPromptTokens: capActive.latestPromptTokens ?? null,
|
||||
sessionTokens,
|
||||
quotas: data.quotas,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
update,
|
||||
multiBtn,
|
||||
capsuleBtn,
|
||||
capsuleSlots,
|
||||
capsuleSeps,
|
||||
hostBarEl,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,507 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Context Window Widget (`ContextWindowWidget.js`).
|
||||
* Supports both interactive multi-agent inspector mode (`LiveOverviewView`)
|
||||
* and pointer-events-none in-place pre-allocated mode (`WindowOverlayShell` hover popup).
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatTokens, resolveModelDisplayInfo } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
resolveScopedConversation,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
import { ContextSegmentMeter } from '../ui/ContextSegmentMeter.js';
|
||||
|
||||
const CTX_PILL_BASE_PAD_PX = 14;
|
||||
const CTX_CJK_CHAR_PX = 11;
|
||||
const CTX_ASCII_CHAR_PX = 6.1;
|
||||
const CTX_PILL_GAP_PX = 4;
|
||||
const CTX_DEFAULT_BAR_WIDTH_PX = 310;
|
||||
|
||||
function estimateCtxPillWidth(text) {
|
||||
let w = CTX_PILL_BASE_PAD_PX;
|
||||
for (const ch of String(text || '')) {
|
||||
w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX;
|
||||
}
|
||||
return Math.ceil(w);
|
||||
}
|
||||
|
||||
/**
|
||||
* 10 通道上下文窗口构成定义(通过动态 getter 自动跟随当前激活语言)。
|
||||
*/
|
||||
export const CTX_CHANNEL_DEFS = [
|
||||
{
|
||||
key: 'assistant',
|
||||
labelKey: 'ctx.ch.assistant',
|
||||
titleKey: 'ctx.ch.assistantTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-assistant',
|
||||
getValue: (c) => Number(c.assistantTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'toolResults',
|
||||
labelKey: 'ctx.ch.toolResults',
|
||||
titleKey: 'ctx.ch.toolResultsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-tool-results',
|
||||
getValue: (c) => Number(c.toolResultsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userInput',
|
||||
labelKey: 'ctx.ch.userInput',
|
||||
titleKey: 'ctx.ch.userInputTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-user-input',
|
||||
getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
|
||||
},
|
||||
{
|
||||
key: 'subagent',
|
||||
labelKey: 'ctx.ch.subagent',
|
||||
titleKey: 'ctx.ch.subagentTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-subagent-msg',
|
||||
getValue: (c) => Number(c.subagentTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'checkpoint',
|
||||
labelKey: 'ctx.ch.checkpoint',
|
||||
titleKey: 'ctx.ch.checkpointTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-checkpoint',
|
||||
getValue: (c) => Number(c.checkpointTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemPrompt',
|
||||
labelKey: 'ctx.ch.systemPrompt',
|
||||
titleKey: 'ctx.ch.systemPromptTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-system-prompt',
|
||||
getValue: (c) => Number(c.systemPromptTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemTools',
|
||||
labelKey: 'ctx.ch.systemTools',
|
||||
titleKey: 'ctx.ch.systemToolsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-system-tools',
|
||||
getValue: (c) => Number(c.systemToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'mcpTools',
|
||||
labelKey: 'ctx.ch.mcpTools',
|
||||
titleKey: 'ctx.ch.mcpToolsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-mcp-tools',
|
||||
getValue: (c) => Number(c.mcpToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'skills',
|
||||
labelKey: 'ctx.ch.skills',
|
||||
titleKey: 'ctx.ch.skillsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-skills',
|
||||
getValue: (c) => Number(c.skillsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userRules',
|
||||
labelKey: 'ctx.ch.userRules',
|
||||
titleKey: 'ctx.ch.userRulesTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-user-rules',
|
||||
getValue: (c) => Number(c.userRulesTokens || 0),
|
||||
},
|
||||
];
|
||||
|
||||
export const ContextWindowWidget = defineComponent({
|
||||
name: 'ContextWindowWidget',
|
||||
setup({ props, onCleanup }) {
|
||||
const interactiveInspector = props.interactiveInspector !== false;
|
||||
const getCtxAgentId =
|
||||
typeof props.getCtxAgentId === 'function'
|
||||
? props.getCtxAgentId
|
||||
: () => uiStore.getState().ctxInspectorAgentId;
|
||||
const setCtxAgentId =
|
||||
typeof props.setCtxAgentId === 'function'
|
||||
? props.setCtxAgentId
|
||||
: (nextId) => uiStore.setState({ ctxInspectorAgentId: nextId });
|
||||
const isVisibleFn =
|
||||
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
|
||||
|
||||
const titleTextEl = h('span', { text: t('module.context') });
|
||||
const ctxAgentBadge = h('span', {
|
||||
className: 'agent-badge badge-main',
|
||||
hidden: true,
|
||||
text: t('fmt.mainAgent'),
|
||||
});
|
||||
const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' });
|
||||
const ctxSegmentBar = ContextSegmentMeter({ context: {} });
|
||||
|
||||
const ctxPillGroup = h('div', { className: 'ctx-pill-group' });
|
||||
const ctxInspectorBar = h(
|
||||
'div',
|
||||
{ className: 'ctx-inspector-bar', hidden: true },
|
||||
[ctxPillGroup]
|
||||
);
|
||||
|
||||
const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => {
|
||||
const swatchEl = h('span', { className: `swatch ${ch.segClass}` });
|
||||
const labelEl = h('span', { text: ch.label });
|
||||
const valEl = h('strong', { className: 'text-mono', text: '0' });
|
||||
const itemEl = h(
|
||||
'div',
|
||||
{ className: 'legend-item', ...(interactiveInspector ? { title: ch.title } : {}) },
|
||||
[h('span', { className: 'legend-left' }, [swatchEl, labelEl]), valEl]
|
||||
);
|
||||
return { ch, defaultOrder: idx, swatchEl, labelEl, valEl, itemEl };
|
||||
});
|
||||
|
||||
const ctxLegendGrid = h(
|
||||
'div',
|
||||
{ className: 'ctx-legend-grid' },
|
||||
ctxChannels.map((entry) => entry.itemEl)
|
||||
);
|
||||
let lastLegendOrderSig = ctxChannels.map((entry) => entry.ch.key).join(',');
|
||||
let lastLocale = getEffectiveLocale();
|
||||
|
||||
const children = [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('layers', { size: 13 }),
|
||||
titleTextEl,
|
||||
ctxAgentBadge,
|
||||
]),
|
||||
h('span', { className: 'panel-meta' }, [ctxSummaryText]),
|
||||
]),
|
||||
];
|
||||
if (interactiveInspector) {
|
||||
children.push(ctxInspectorBar);
|
||||
}
|
||||
children.push(ctxSegmentBar.el, ctxLegendGrid);
|
||||
|
||||
const ctxPanel = h('section', { className: 'panel' }, children);
|
||||
|
||||
let latestData = null;
|
||||
let ctxPillsExpanded = false;
|
||||
let lastCascadeId = '';
|
||||
let cachedBarWidth = 0;
|
||||
|
||||
function update({ data } = {}) {
|
||||
latestData = data || null;
|
||||
const curLocale = getEffectiveLocale();
|
||||
patchText(titleTextEl, t('module.context'));
|
||||
|
||||
if (!data) {
|
||||
if (curLocale !== lastLocale) {
|
||||
lastLocale = curLocale;
|
||||
for (const entry of ctxChannels) {
|
||||
patchText(entry.labelEl, entry.ch.label);
|
||||
if (interactiveInspector) {
|
||||
patchAttr(entry.itemEl, 'title', entry.ch.title);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let availRowWidth = CTX_DEFAULT_BAR_WIDTH_PX;
|
||||
if (interactiveInspector) {
|
||||
const measuredWidth =
|
||||
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
|
||||
if (measuredWidth > 160) {
|
||||
cachedBarWidth = measuredWidth;
|
||||
}
|
||||
availRowWidth = cachedBarWidth > 160 ? cachedBarWidth : CTX_DEFAULT_BAR_WIDTH_PX;
|
||||
|
||||
const currentCascadeId = data.activeConversation?.cascadeId || '';
|
||||
if (currentCascadeId && currentCascadeId !== lastCascadeId) {
|
||||
if (lastCascadeId) {
|
||||
ctxPillsExpanded = false;
|
||||
}
|
||||
lastCascadeId = currentCascadeId;
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
hasSubagents,
|
||||
effectiveCtxScope,
|
||||
agents,
|
||||
aggregated,
|
||||
scopedConv,
|
||||
ctxAgent,
|
||||
} = resolveScopedConversation(data, 'all', getCtxAgentId());
|
||||
|
||||
const active = scopedConv || data.activeConversation || {};
|
||||
const ctx = ctxAgent?.context || active.context || {};
|
||||
|
||||
patchAttr(ctxAgentBadge, 'hidden', !(hasSubagents && ctxAgent));
|
||||
if (hasSubagents && ctxAgent) {
|
||||
const badgeCls = getAgentBadgeClass(ctxAgent.index || 0, Boolean(ctxAgent.isMain));
|
||||
patchAttr(ctxAgentBadge, 'class', `agent-badge ${badgeCls}`);
|
||||
const badgeFullText = formatAgentLabel(ctxAgent);
|
||||
patchText(ctxAgentBadge, badgeFullText);
|
||||
if (interactiveInspector) {
|
||||
patchAttr(ctxAgentBadge, 'title', badgeFullText);
|
||||
}
|
||||
}
|
||||
|
||||
if (interactiveInspector) {
|
||||
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
|
||||
if (hasSubagents && ctxAgent) {
|
||||
const rawActiveBadge = aggregated?.activeAgentBadge || '主';
|
||||
const activeBadgeText = isEnglishLocale()
|
||||
? rawActiveBadge === '主'
|
||||
? t('fmt.mainBadge')
|
||||
: rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n }))
|
||||
: rawActiveBadge;
|
||||
|
||||
const pillItems = [
|
||||
{
|
||||
key: 'auto',
|
||||
label: t('ctx.followActive', { badge: activeBadgeText }),
|
||||
title: t('ctx.followActiveTitle'),
|
||||
isActive: effectiveCtxScope === 'auto',
|
||||
mode: 'ctx-only',
|
||||
},
|
||||
];
|
||||
|
||||
const allAgentPills = agents.map((ag) => {
|
||||
const agPct = ag.context?.usedPct ?? 0;
|
||||
const agModelDisplay = resolveModelDisplayInfo(ag, data.settings, {
|
||||
fallback: t('fmt.unknownModel'),
|
||||
}).text;
|
||||
const badgeLabel = formatAgentBadgeText(ag);
|
||||
return {
|
||||
key: ag.agentId,
|
||||
label: `${badgeLabel} ${agPct}%`,
|
||||
title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${t('header.convMetaSteps', { count: ag.stepCount || 0 })})`,
|
||||
isActive: effectiveCtxScope === ag.agentId,
|
||||
mode: 'ctx-only',
|
||||
};
|
||||
});
|
||||
|
||||
const firstPillWidth =
|
||||
pillItems.length > 0 ? estimateCtxPillWidth(pillItems[0].label) : 0;
|
||||
const totalAllWidth = allAgentPills.reduce(
|
||||
(sum, p) => sum + CTX_PILL_GAP_PX + estimateCtxPillWidth(p.label),
|
||||
firstPillWidth
|
||||
);
|
||||
const needsCollapse = totalAllWidth > availRowWidth && allAgentPills.length > 2;
|
||||
|
||||
if (needsCollapse && !ctxPillsExpanded) {
|
||||
const toggleSample = t('ctx.expandMore', { count: allAgentPills.length });
|
||||
const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample);
|
||||
let usedW = firstPillWidth;
|
||||
let fitCount = 0;
|
||||
for (let i = 0; i < allAgentPills.length; i += 1) {
|
||||
const pw = CTX_PILL_GAP_PX + estimateCtxPillWidth(allAgentPills[i].label);
|
||||
if (fitCount >= 1 && usedW + pw + toggleReservePx > availRowWidth) {
|
||||
break;
|
||||
}
|
||||
usedW += pw;
|
||||
fitCount += 1;
|
||||
}
|
||||
const maxKeep = Math.max(1, allAgentPills.length - 2);
|
||||
const maxCollapsedCount = Math.max(1, Math.min(maxKeep, fitCount));
|
||||
const visibleAgentPills = allAgentPills.slice(0, maxCollapsedCount);
|
||||
const activeHiddenPill = allAgentPills
|
||||
.slice(maxCollapsedCount)
|
||||
.find((p) => p.isActive);
|
||||
if (activeHiddenPill) {
|
||||
if (visibleAgentPills.length >= 2) {
|
||||
visibleAgentPills[visibleAgentPills.length - 1] = activeHiddenPill;
|
||||
} else {
|
||||
visibleAgentPills.push(activeHiddenPill);
|
||||
}
|
||||
}
|
||||
const hiddenCount = allAgentPills.length - visibleAgentPills.length;
|
||||
pillItems.push(...visibleAgentPills, {
|
||||
key: '__toggle_more__',
|
||||
label: t('ctx.expandMore', { count: hiddenCount }),
|
||||
title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }),
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
} else {
|
||||
pillItems.push(...allAgentPills);
|
||||
if (needsCollapse) {
|
||||
pillItems.push({
|
||||
key: '__toggle_more__',
|
||||
label: t('ctx.collapse'),
|
||||
title: t('ctx.collapseTitle'),
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
patchKeyedList(ctxPillGroup, pillItems, {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: (item) =>
|
||||
`${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`,
|
||||
createRow: () => {
|
||||
const btn = h('button', { type: 'button', className: 'ctx-agent-pill' });
|
||||
return { el: btn, refs: { btn } };
|
||||
},
|
||||
updateRow: (refs, item) => {
|
||||
patchText(refs.btn, item.label);
|
||||
patchAttr(refs.btn, 'title', item.title);
|
||||
patchClasses(refs.btn, {
|
||||
'is-active': item.isActive,
|
||||
'is-more-toggle': Boolean(item.isMoreToggle),
|
||||
});
|
||||
refs.btn.onclick = () => {
|
||||
if (item.mode === 'toggle-expand') {
|
||||
ctxPillsExpanded = !ctxPillsExpanded;
|
||||
if (latestData) update({ data: latestData });
|
||||
} else {
|
||||
setCtxAgentId(item.key);
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTokens = Number(ctx.totalTokens || 0);
|
||||
const usedPct =
|
||||
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||
const ctxToneCls =
|
||||
usedPct >= 88 ? 'tone-danger' : usedPct >= 70 ? 'tone-warn' : '';
|
||||
patchAttr(ctxSummaryText, 'class', ctxToneCls ? `text-mono ${ctxToneCls}` : 'text-mono');
|
||||
patchText(
|
||||
ctxSummaryText,
|
||||
`${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)`
|
||||
);
|
||||
ctxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } });
|
||||
|
||||
if (interactiveInspector) {
|
||||
const localeChanged = curLocale !== lastLocale;
|
||||
lastLocale = curLocale;
|
||||
const scored = ctxChannels.map((entry) => {
|
||||
const val = entry.ch.getValue(ctx);
|
||||
if (localeChanged) {
|
||||
patchText(entry.labelEl, entry.ch.label);
|
||||
patchAttr(entry.itemEl, 'title', entry.ch.title);
|
||||
}
|
||||
patchText(entry.valEl, formatTokens(val));
|
||||
return { entry, val };
|
||||
});
|
||||
scored.sort((a, b) => b.val - a.val || a.entry.defaultOrder - b.entry.defaultOrder);
|
||||
const nextLegendOrderSig = scored.map((x) => x.entry.ch.key).join(',');
|
||||
if (nextLegendOrderSig !== lastLegendOrderSig) {
|
||||
lastLegendOrderSig = nextLegendOrderSig;
|
||||
for (const { entry } of scored) {
|
||||
ctxLegendGrid.appendChild(entry.itemEl);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lastLocale = curLocale;
|
||||
const scoredChannels = CTX_CHANNEL_DEFS.map((ch, defaultOrder) => ({
|
||||
ch,
|
||||
defaultOrder,
|
||||
val: ch.getValue(ctx),
|
||||
}));
|
||||
scoredChannels.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder);
|
||||
for (let i = 0; i < ctxChannels.length; i += 1) {
|
||||
const slot = ctxChannels[i];
|
||||
const item = scoredChannels[i];
|
||||
if (!slot || !item) continue;
|
||||
patchAttr(slot.swatchEl, 'class', `swatch ${item.ch.segClass}`);
|
||||
patchText(slot.labelEl, item.ch.label);
|
||||
patchText(slot.valEl, formatTokens(item.val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let ro = null;
|
||||
if (interactiveInspector && typeof ResizeObserver !== 'undefined') {
|
||||
ro = new ResizeObserver(() => {
|
||||
if (!isVisibleFn()) return;
|
||||
const nextW =
|
||||
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
|
||||
if (nextW > 160 && Math.abs(nextW - cachedBarWidth) >= 6) {
|
||||
cachedBarWidth = nextW;
|
||||
if (latestData?.activeConversation?.hasSubagents) {
|
||||
update({ data: latestData });
|
||||
}
|
||||
}
|
||||
});
|
||||
ro.observe(ctxPanel);
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (ro) ro.disconnect();
|
||||
ctxSegmentBar.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: ctxPanel,
|
||||
refs: { update, ctxSegmentBar },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,482 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`).
|
||||
* Displays active multi-session running conversations & collapsible subagent activity
|
||||
* with an isolated 1s elapsed timer lifecycle.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatElapsedSec } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
formatAgentBadgeText,
|
||||
getAgentBadgeClass,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
|
||||
export const LiveActivityWidget = defineComponent({
|
||||
name: 'LiveActivityWidget',
|
||||
setup({ props, onCleanup }) {
|
||||
const interactive = props.interactive !== false;
|
||||
const preview = Boolean(props.preview);
|
||||
const getCtxAgentId =
|
||||
typeof props.getCtxAgentId === 'function'
|
||||
? props.getCtxAgentId
|
||||
: () => uiStore.getState().ctxInspectorAgentId;
|
||||
const isVisibleFn =
|
||||
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
|
||||
|
||||
const liveActivityBar = h('div', {
|
||||
className: 'live-activity-list',
|
||||
hidden: true,
|
||||
'aria-live': 'polite',
|
||||
});
|
||||
|
||||
const expandedTaskConvIds = new Set();
|
||||
const activityTimersMap = new Map();
|
||||
let liveTickTimer = null;
|
||||
let latestData = null;
|
||||
|
||||
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
||||
const now = Date.now();
|
||||
const prev = activityTimersMap.get(timerKey);
|
||||
let startMs = prev?.startMs || 0;
|
||||
if (!prev || prev.sig !== sig) {
|
||||
const validRaw = Number(rawStartMs || 0);
|
||||
startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now;
|
||||
} else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) {
|
||||
startMs = Number(rawStartMs);
|
||||
}
|
||||
activityTimersMap.set(timerKey, { sig, startMs, el: targetEl });
|
||||
const elapsedSec = Math.max(0, (now - startMs) / 1000);
|
||||
patchText(targetEl, formatElapsedSec(elapsedSec));
|
||||
}
|
||||
|
||||
function updateLiveElapsedDisplay() {
|
||||
const now = Date.now();
|
||||
for (const entry of activityTimersMap.values()) {
|
||||
if (!entry?.el) continue;
|
||||
const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0;
|
||||
patchText(entry.el, formatElapsedSec(elapsedSec));
|
||||
}
|
||||
}
|
||||
|
||||
function pauseTicker() {
|
||||
if (liveTickTimer) {
|
||||
clearInterval(liveTickTimer);
|
||||
liveTickTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function stopLiveTicker() {
|
||||
pauseTicker();
|
||||
activityTimersMap.clear();
|
||||
}
|
||||
|
||||
function ensureLiveTicker() {
|
||||
if (!isVisibleFn() || activityTimersMap.size === 0) {
|
||||
pauseTicker();
|
||||
return;
|
||||
}
|
||||
if (!liveTickTimer) {
|
||||
liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
function resumeTicker() {
|
||||
if (activityTimersMap.size > 0) {
|
||||
updateLiveElapsedDisplay();
|
||||
ensureLiveTicker();
|
||||
}
|
||||
}
|
||||
|
||||
function createLiveTaskCard() {
|
||||
const dotIcon = createSvgIcon('dot', { size: 11 });
|
||||
patchClasses(dotIcon, { 'is-pulsing': true });
|
||||
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
|
||||
const titleEl = h('strong', {
|
||||
className: 'live-task-title',
|
||||
text: t('live.currentSession'),
|
||||
});
|
||||
const subToggleBtn = h('button', {
|
||||
type: 'button',
|
||||
className: 'live-sub-toggle',
|
||||
hidden: true,
|
||||
text: t('live.subToggleIdle', { total: 0, arrow: '▸' }),
|
||||
});
|
||||
const elapsedEl = h('span', {
|
||||
className: 'live-activity-elapsed text-mono',
|
||||
text: '0s',
|
||||
});
|
||||
|
||||
const headerEl = h('div', { className: 'live-task-header' }, [
|
||||
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]),
|
||||
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]),
|
||||
]);
|
||||
|
||||
const mainBadge = h('span', {
|
||||
className: 'agent-badge badge-main',
|
||||
hidden: true,
|
||||
text: t('fmt.mainBadge'),
|
||||
});
|
||||
const mainPhase = h('strong', {
|
||||
className: 'live-activity-phase',
|
||||
text: t('live.thinking'),
|
||||
});
|
||||
const mainProgress = h('span', {
|
||||
className: 'live-activity-progress text-mono',
|
||||
hidden: true,
|
||||
text: '',
|
||||
});
|
||||
const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' });
|
||||
const mainDetail = h('span', {
|
||||
className: 'live-activity-detail',
|
||||
hidden: true,
|
||||
text: '',
|
||||
});
|
||||
|
||||
const mainRowEl = h('div', { className: 'live-task-main-row' }, [
|
||||
mainBadge,
|
||||
mainPhase,
|
||||
mainProgress,
|
||||
mainSep,
|
||||
mainDetail,
|
||||
]);
|
||||
|
||||
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
|
||||
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
|
||||
|
||||
return {
|
||||
el: cardEl,
|
||||
refs: {
|
||||
cardEl,
|
||||
dotIcon,
|
||||
titleEl,
|
||||
subToggleBtn,
|
||||
elapsedEl,
|
||||
mainBadge,
|
||||
mainPhase,
|
||||
mainProgress,
|
||||
mainSep,
|
||||
mainDetail,
|
||||
subListEl,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createLiveSubRow() {
|
||||
const subBadge = h('span', {
|
||||
className: 'agent-badge badge-sub-1',
|
||||
text: t('fmt.subBadge', { index: 1 }),
|
||||
});
|
||||
const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') });
|
||||
const subSummary = h('span', { className: 'live-sub-summary', text: '' });
|
||||
const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' });
|
||||
|
||||
const rowEl = h('div', { className: 'live-sub-row' }, [
|
||||
h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]),
|
||||
subElapsed,
|
||||
]);
|
||||
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: {
|
||||
rowEl,
|
||||
subBadge,
|
||||
subRole,
|
||||
subSummary,
|
||||
subElapsed,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function update({ data } = {}) {
|
||||
latestData = data || null;
|
||||
if (!data) {
|
||||
patchAttr(liveActivityBar, 'hidden', true);
|
||||
stopLiveTicker();
|
||||
return;
|
||||
}
|
||||
|
||||
const { agents, aggregated } = resolveScopedConversation(
|
||||
data,
|
||||
'all',
|
||||
getCtxAgentId()
|
||||
);
|
||||
|
||||
const rawRunningList =
|
||||
Array.isArray(data.runningConversations) && data.runningConversations.length > 0
|
||||
? data.runningConversations
|
||||
: data.activeConversation?.isRunning || aggregated?.isRunning
|
||||
? [
|
||||
{
|
||||
cascadeId: data.activeConversation?.cascadeId || 'current',
|
||||
title: data.activeConversation?.title || t('live.currentSession'),
|
||||
isCurrentSelected: true,
|
||||
isMainRunning: Boolean(data.activeConversation?.isRunning),
|
||||
isRunning: true,
|
||||
mainActivity:
|
||||
data.activeConversation?.liveActivity || aggregated?.liveActivity || null,
|
||||
subagentCount: Math.max(0, agents.length - 1),
|
||||
runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length,
|
||||
subagents: agents
|
||||
.filter((a) => !a.isMain)
|
||||
.map((s, idx) => ({
|
||||
cascadeId: s.cascadeId || s.agentId,
|
||||
index: s.index || idx + 1,
|
||||
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
|
||||
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
isRunning: Boolean(s.isRunning),
|
||||
stepCount: Number(s.stepCount || 0),
|
||||
lastModifiedMs: s.lastModifiedMs || 0,
|
||||
liveActivity: s.liveActivity || {
|
||||
phase: s.isRunning ? 'thinking' : 'done',
|
||||
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: s.lastModifiedMs || 0,
|
||||
signature: `${s.agentId}:${s.stepCount || 0}`,
|
||||
},
|
||||
})),
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
const hasRunningTasks = rawRunningList.length > 0;
|
||||
patchAttr(liveActivityBar, 'hidden', !hasRunningTasks);
|
||||
if (!hasRunningTasks) {
|
||||
stopLiveTicker();
|
||||
expandedTaskConvIds.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeTimerKeys = new Set();
|
||||
for (const item of rawRunningList) {
|
||||
activeTimerKeys.add(`main:${item.cascadeId}`);
|
||||
for (const sub of item.subagents || []) {
|
||||
if (sub?.isRunning) {
|
||||
activeTimerKeys.add(`sub:${sub.cascadeId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId));
|
||||
for (const id of [...expandedTaskConvIds]) {
|
||||
if (!runningIdsSet.has(id)) {
|
||||
expandedTaskConvIds.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
const locale = getEffectiveLocale();
|
||||
patchKeyedList(liveActivityBar, rawRunningList, {
|
||||
keyFn: (item) => item.cascadeId,
|
||||
sigFn: (item) => {
|
||||
const isExp = interactive
|
||||
? expandedTaskConvIds.has(item.cascadeId)
|
||||
: Number(item.runningSubagentCount || 0) > 0;
|
||||
const subSig = (item.subagents || [])
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
)
|
||||
.join('|');
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
},
|
||||
createRow: createLiveTaskCard,
|
||||
updateRow: (refs, item) => {
|
||||
const act = item.mainActivity || {
|
||||
phase: 'thinking',
|
||||
label: t('live.thinking'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: item.lastModifiedMs || 0,
|
||||
signature: `fallback:${item.lastModifiedMs || 0}`,
|
||||
};
|
||||
|
||||
const isWaiting = act.phase === 'waiting';
|
||||
const isCompacting = act.phase === 'compacting';
|
||||
patchClasses(refs.cardEl, {
|
||||
'is-waiting': isWaiting,
|
||||
'is-compacting': isCompacting,
|
||||
});
|
||||
patchClasses(refs.dotIcon, { 'is-pulsing': true });
|
||||
|
||||
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
|
||||
patchText(refs.titleEl, convTitle);
|
||||
if (interactive && !preview) {
|
||||
patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle }));
|
||||
refs.titleEl.onclick = () => {
|
||||
if (item.cascadeId && item.cascadeId !== 'current') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
||||
fetchTelemetry({ force: false });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||
const isExpanded = interactive
|
||||
? expandedTaskConvIds.has(item.cascadeId)
|
||||
: runSubCount > 0;
|
||||
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
||||
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
||||
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
||||
if (subCount > 0) {
|
||||
const arrow = isExpanded ? '▾' : '▸';
|
||||
const toggleText =
|
||||
runSubCount > 0
|
||||
? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow })
|
||||
: t('live.subToggleIdle', { total: subCount, arrow });
|
||||
patchText(refs.subToggleBtn, toggleText);
|
||||
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
|
||||
if (interactive) {
|
||||
patchAttr(
|
||||
refs.subToggleBtn,
|
||||
'title',
|
||||
isExpanded ? t('live.subCollapseTitle') : t('live.subExpandTitle')
|
||||
);
|
||||
refs.subToggleBtn.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
if (expandedTaskConvIds.has(item.cascadeId)) {
|
||||
expandedTaskConvIds.delete(item.cascadeId);
|
||||
} else {
|
||||
expandedTaskConvIds.add(item.cascadeId);
|
||||
}
|
||||
if (latestData) update({ data: latestData });
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const mainTimerKey = `main:${item.cascadeId}`;
|
||||
activeTimerKeys.add(mainTimerKey);
|
||||
bindLiveElapsedTimer(
|
||||
mainTimerKey,
|
||||
`${item.cascadeId}:${act.signature || act.label}`,
|
||||
act.startedAtMs,
|
||||
refs.elapsedEl
|
||||
);
|
||||
|
||||
patchText(refs.mainPhase, act.label || t('live.thinking'));
|
||||
const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
|
||||
patchAttr(refs.mainProgress, 'hidden', !progText);
|
||||
if (progText) {
|
||||
patchText(refs.mainProgress, progText);
|
||||
}
|
||||
|
||||
const detailStr = act.detail || '';
|
||||
patchAttr(refs.mainSep, 'hidden', !detailStr);
|
||||
patchAttr(refs.mainDetail, 'hidden', !detailStr);
|
||||
patchText(refs.mainDetail, detailStr);
|
||||
|
||||
if (interactive) {
|
||||
const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`;
|
||||
patchAttr(refs.cardEl, 'title', fullTooltip);
|
||||
}
|
||||
|
||||
const showSubs = subCount > 0 && isExpanded;
|
||||
patchAttr(refs.subListEl, 'hidden', !showSubs);
|
||||
if (showSubs) {
|
||||
const subItems = item.subagents || [];
|
||||
patchKeyedList(refs.subListEl, subItems, {
|
||||
keyFn: (sub) => sub.cascadeId,
|
||||
sigFn: (sub) =>
|
||||
`${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
createRow: createLiveSubRow,
|
||||
updateRow: (subRefs, sub) => {
|
||||
const subAct = sub.liveActivity || {
|
||||
phase: sub.isRunning ? 'thinking' : 'done',
|
||||
label: sub.isRunning ? t('live.thinking') : t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: sub.lastModifiedMs || 0,
|
||||
};
|
||||
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
|
||||
|
||||
const badgeCls = getAgentBadgeClass(sub.index || 1, false);
|
||||
const subBadgeText = formatAgentBadgeText({
|
||||
...sub,
|
||||
isMain: false,
|
||||
index: sub.index || 1,
|
||||
});
|
||||
patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`);
|
||||
patchText(subRefs.subBadge, subBadgeText);
|
||||
|
||||
const roleText = sub.role || sub.shortLabel || t('fmt.subAgent');
|
||||
patchText(subRefs.subRole, roleText);
|
||||
|
||||
const rawSubLabel = sub.isRunning
|
||||
? subAct.label || ''
|
||||
: subAct.label || t('live.done');
|
||||
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
||||
const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || '']
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
|
||||
patchText(subRefs.subSummary, summaryStr);
|
||||
|
||||
if (interactive) {
|
||||
patchAttr(
|
||||
subRefs.rowEl,
|
||||
'title',
|
||||
`[${subBadgeText}] ${roleText}${summaryStr ? ` ${summaryStr}` : ''}`
|
||||
);
|
||||
}
|
||||
|
||||
if (sub.isRunning) {
|
||||
const subTimerKey = `sub:${sub.cascadeId}`;
|
||||
activeTimerKeys.add(subTimerKey);
|
||||
bindLiveElapsedTimer(
|
||||
subTimerKey,
|
||||
`${sub.cascadeId}:${subAct.signature || subAct.label}`,
|
||||
subAct.startedAtMs,
|
||||
subRefs.subElapsed
|
||||
);
|
||||
} else {
|
||||
activityTimersMap.delete(`sub:${sub.cascadeId}`);
|
||||
patchText(
|
||||
subRefs.subElapsed,
|
||||
t('header.convMetaSteps', { count: sub.stepCount || 0 })
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
for (const key of [...activityTimersMap.keys()]) {
|
||||
if (!activeTimerKeys.has(key)) {
|
||||
activityTimersMap.delete(key);
|
||||
}
|
||||
}
|
||||
updateLiveElapsedDisplay();
|
||||
ensureLiveTicker();
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
stopLiveTicker();
|
||||
});
|
||||
|
||||
return {
|
||||
el: liveActivityBar,
|
||||
refs: {
|
||||
update,
|
||||
pauseTicker,
|
||||
resumeTicker,
|
||||
stopLiveTicker,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Metric Matrix Widget (`MetricMatrixWidget.js`).
|
||||
* Renders 1..4 user-selected telemetry cells dynamically via `metricRegistry.js`.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { resolveOverviewMetricCell } from '../../registries/metricRegistry.js';
|
||||
import {
|
||||
normalizeClientOverviewMetrics,
|
||||
resolveScopedConversation,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
|
||||
export const MetricMatrixWidget = defineComponent({
|
||||
name: 'MetricMatrixWidget',
|
||||
setup({ props }) {
|
||||
const getCtxAgentId =
|
||||
typeof props?.getCtxAgentId === 'function'
|
||||
? props.getCtxAgentId
|
||||
: () => uiStore.getState().ctxInspectorAgentId;
|
||||
const matrixEl = h('section', {
|
||||
className: 'telemetry-matrix',
|
||||
'aria-label': t('module.metrics'),
|
||||
'data-cols': '4',
|
||||
});
|
||||
patchStyleVar(matrixEl, '--matrix-cols', '4');
|
||||
|
||||
function createMetricCellNode() {
|
||||
const labelSpan = h('span', { text: '—' });
|
||||
const iconSvg = createSvgIcon('pulse', { size: 11 });
|
||||
const valueEl = h('strong', { className: 'cell-value', text: '—' });
|
||||
const subEl = h('span', { className: 'cell-sub', text: '—' });
|
||||
const el = h('div', { className: 'matrix-cell' }, [
|
||||
h('div', { className: 'cell-label' }, [labelSpan, iconSvg]),
|
||||
valueEl,
|
||||
subEl,
|
||||
]);
|
||||
return {
|
||||
el,
|
||||
refs: { labelSpan, iconSvg, valueEl, subEl },
|
||||
};
|
||||
}
|
||||
|
||||
function update({ data } = {}) {
|
||||
patchAttr(matrixEl, 'aria-label', t('module.metrics'));
|
||||
const metricKeys = normalizeClientOverviewMetrics(data?.settings?.overviewMetrics);
|
||||
const colCount = Math.max(1, Math.min(4, metricKeys.length));
|
||||
patchAttr(matrixEl, 'data-cols', String(colCount));
|
||||
patchStyleVar(matrixEl, '--matrix-cols', String(colCount));
|
||||
|
||||
const { hasSubagents, scopedConv, ctxAgent } = resolveScopedConversation(
|
||||
data,
|
||||
'all',
|
||||
getCtxAgentId()
|
||||
);
|
||||
const active = scopedConv || data?.activeConversation || {};
|
||||
const ctx = ctxAgent?.context || active.context || {};
|
||||
const quotas = data?.quotas || {};
|
||||
const settings = data?.settings || {};
|
||||
const locale = getEffectiveLocale();
|
||||
|
||||
const cells = metricKeys.map((key) =>
|
||||
resolveOverviewMetricCell(key, {
|
||||
active,
|
||||
ctx,
|
||||
quotas,
|
||||
settings,
|
||||
hasSubagents,
|
||||
})
|
||||
);
|
||||
|
||||
patchKeyedList(matrixEl, cells, {
|
||||
keyFn: (cell) => cell.key,
|
||||
sigFn: (cell) =>
|
||||
`${locale}:${cell.key}:${cell.label}:${cell.icon}:${cell.isPulsing}:${cell.valueClass}:${cell.valueText}:${cell.subClass}:${cell.subText}`,
|
||||
createRow: createMetricCellNode,
|
||||
updateRow: (refs, cell) => {
|
||||
patchText(refs.labelSpan, cell.label);
|
||||
patchSvgIcon(refs.iconSvg, cell.icon);
|
||||
refs.iconSvg.setAttribute('width', String(cell.iconSize));
|
||||
refs.iconSvg.setAttribute('height', String(cell.iconSize));
|
||||
patchClasses(refs.iconSvg, { 'is-pulsing': Boolean(cell.isPulsing) });
|
||||
patchAttr(refs.valueEl, 'class', cell.valueClass);
|
||||
patchText(refs.valueEl, cell.valueText);
|
||||
patchAttr(refs.subEl, 'class', cell.subClass);
|
||||
patchText(refs.subEl, cell.subText);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize default 4-cell skeleton so hover/overview has zero initial height jump
|
||||
update({ data: null });
|
||||
|
||||
return {
|
||||
el: matrixEl,
|
||||
refs: { update },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,359 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`).
|
||||
* Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT)
|
||||
* and weekly summary footer for both `LiveOverviewView` and `WindowOverlayShell`.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatCountdown, formatTokens, formatUsd } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
* 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。
|
||||
*
|
||||
* @param {object|null|undefined} quotas
|
||||
* @param {number} minuteTick
|
||||
* @param {{ isPending?: boolean }} [options]
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) {
|
||||
const safeQuotas = quotas || {};
|
||||
const activePool = safeQuotas.activePool || {};
|
||||
const rawPools =
|
||||
Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0
|
||||
? safeQuotas.pools
|
||||
: [
|
||||
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
|
||||
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
|
||||
];
|
||||
const weekly = safeQuotas.weekly || {};
|
||||
const poolItems = rawPools.map((p) => {
|
||||
const key = p.poolKey || p.family || p.poolLabel || 'Other';
|
||||
const poolLabel = p.poolLabel || p.family || key;
|
||||
const isActivePool =
|
||||
Boolean(activePool.family) &&
|
||||
(activePool.poolKey === key ||
|
||||
activePool.family === p.family ||
|
||||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
|
||||
return {
|
||||
key,
|
||||
poolLabel,
|
||||
poolData: p,
|
||||
fallbackWeekly: weekly,
|
||||
isActivePool,
|
||||
minuteTick,
|
||||
isPending,
|
||||
};
|
||||
});
|
||||
if (
|
||||
weekly?.isOfficial === false &&
|
||||
poolItems.length > 0 &&
|
||||
!poolItems.some((item) => item.isActivePool)
|
||||
) {
|
||||
poolItems[0].isActivePool = true;
|
||||
}
|
||||
return poolItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
|
||||
*/
|
||||
export function createPoolQuotaRow() {
|
||||
const title5h = h('span', { className: 'quota-win-title', text: '5h' });
|
||||
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 row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header quota-win-head' }, [left5h, meta5h]),
|
||||
h('div', { className: 'progress-track' }, [fill5h]),
|
||||
]);
|
||||
|
||||
const titleWk = h('span', { className: 'quota-win-title', text: t('quota.weeklyShort') });
|
||||
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 rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header quota-win-head' }, [leftWk, metaWk]),
|
||||
h('div', { className: 'progress-track' }, [fillWk]),
|
||||
]);
|
||||
|
||||
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
|
||||
row5h,
|
||||
rowWk,
|
||||
]);
|
||||
|
||||
return {
|
||||
el,
|
||||
refs: {
|
||||
row5h,
|
||||
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 tokStr = formatTokens(weekly.tokens || 0);
|
||||
const costStr = formatUsd(weekly.costUsd || 0);
|
||||
const leftText = isCustomLocal
|
||||
? t('quota.footTokensCustom', { tok: tokStr, cost: costStr })
|
||||
: t('quota.footTokensCycle', { tok: tokStr, cost: costStr });
|
||||
const rightText =
|
||||
Number(account?.aiCredits) > 0
|
||||
? t('quota.footCredits', { credits: account.aiCredits })
|
||||
: isCustomLocal
|
||||
? t('quota.footCallsCustom', { calls: weekly.calls || 0 })
|
||||
: t('quota.footCallsCycle', { calls: weekly.calls || 0 });
|
||||
const tooltip = isCustomLocal ? t('quota.footTipCustom') : t('quota.footTipCycle');
|
||||
return { leftText, rightText, tooltip };
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步单个配额池行的 5h 与每周窗口状态。
|
||||
*/
|
||||
export function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
||||
const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item;
|
||||
patchAttr(
|
||||
rowEl,
|
||||
'style',
|
||||
idx === 0
|
||||
? 'display: flex; flex-direction: column; gap: 8px;'
|
||||
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
|
||||
);
|
||||
|
||||
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
|
||||
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
|
||||
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
|
||||
|
||||
const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false);
|
||||
const wkUsedRaw = useCustomWeekly
|
||||
? fallbackWeekly?.usedPct
|
||||
: poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
|
||||
const wkRemRaw = useCustomWeekly
|
||||
? fallbackWeekly?.remainingPct
|
||||
: poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
|
||||
const wkResetRaw = useCustomWeekly
|
||||
? fallbackWeekly?.resetTime || poolData?.weeklyResetTime
|
||||
: poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
|
||||
const hasWk = wkUsedRaw != null && wkRemRaw != null;
|
||||
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
|
||||
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
|
||||
|
||||
const hide5h = !has5h && hasWk;
|
||||
const hideWk = !hasWk && has5h;
|
||||
refs.row5h.hidden = hide5h;
|
||||
refs.row5h.style.display = hide5h ? 'none' : 'flex';
|
||||
refs.rowWk.hidden = hideWk;
|
||||
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
|
||||
|
||||
const fallbackMetaText = isPending ? t('quota.loading') : t('quota.failed');
|
||||
|
||||
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',
|
||||
t('quota.cycle5hTitle', {
|
||||
pool: poolLabel,
|
||||
tok: tok5h,
|
||||
cost: cost5h,
|
||||
calls: calls5h,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
refs.usage5h.hidden = true;
|
||||
patchText(refs.usage5h, '');
|
||||
patchAttr(refs.left5h, 'title', null);
|
||||
}
|
||||
patchText(
|
||||
refs.meta5h,
|
||||
has5h
|
||||
? t('quota.usedAndLeft', {
|
||||
reset: formatCountdown(poolData.resetTime),
|
||||
used: used5hVal.toFixed(1),
|
||||
rem: rem5hVal.toFixed(1),
|
||||
})
|
||||
: fallbackMetaText
|
||||
);
|
||||
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
|
||||
patchClasses(refs.fill5h, {
|
||||
'tone-warn': used5hVal >= 70 && used5hVal < 85,
|
||||
'tone-danger': used5hVal >= 85,
|
||||
});
|
||||
|
||||
const customTitle =
|
||||
useCustomWeekly && fallbackWeekly?.title
|
||||
? fallbackWeekly.title
|
||||
: t('quota.weeklyPool', { pool: poolLabel });
|
||||
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
|
||||
? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk })
|
||||
: t('quota.cycleWkPoolTitle', {
|
||||
pool: poolLabel,
|
||||
tok: tokWk,
|
||||
cost: costWk,
|
||||
calls: callsWk,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
refs.usageWk.hidden = true;
|
||||
patchText(refs.usageWk, '');
|
||||
patchAttr(refs.leftWk, 'title', null);
|
||||
}
|
||||
patchText(
|
||||
refs.metaWk,
|
||||
hasWk
|
||||
? t('quota.usedAndLeft', {
|
||||
reset: formatCountdown(wkResetRaw),
|
||||
used: usedWkVal.toFixed(1),
|
||||
rem: remWkVal.toFixed(1),
|
||||
})
|
||||
: fallbackMetaText
|
||||
);
|
||||
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
|
||||
patchClasses(refs.fillWk, {
|
||||
'tone-warn': usedWkVal >= 70 && usedWkVal < 85,
|
||||
'tone-danger': usedWkVal >= 85,
|
||||
});
|
||||
}
|
||||
|
||||
export function quotaPoolRowSig(item, idx) {
|
||||
const c5h = item.poolData?.cycle5h;
|
||||
const cWk = item.poolData?.cycleWeekly;
|
||||
const fw = item.fallbackWeekly;
|
||||
return `${getEffectiveLocale()}:${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 QuotaPoolsWidget = defineComponent({
|
||||
name: 'QuotaPoolsWidget',
|
||||
setup({ props }) {
|
||||
const compactHover = Boolean(props.compactHover);
|
||||
const titleTextEl = h('span', { text: t('module.quotas') });
|
||||
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
||||
const poolsListEl = h(
|
||||
'div',
|
||||
compactHover
|
||||
? { className: 'wm-hover-quota-pools' }
|
||||
: { style: 'display: flex; flex-direction: column; gap: 0;' }
|
||||
);
|
||||
|
||||
if (compactHover) {
|
||||
patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: quotaPoolRowSig,
|
||||
createRow: createPoolQuotaRow,
|
||||
updateRow: syncPoolQuotaRow,
|
||||
});
|
||||
}
|
||||
|
||||
const initFoot = formatQuotaSummaryFooter(null, null);
|
||||
const wkFootLeft = h('span', { className: 'text-muted', text: initFoot.leftText });
|
||||
const wkFootRight = h('span', {
|
||||
className: 'text-muted',
|
||||
text: compactHover ? initFoot.rightText : '',
|
||||
});
|
||||
|
||||
const quotaPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('pulse', { size: 13 }),
|
||||
titleTextEl,
|
||||
]),
|
||||
tierBadge,
|
||||
]),
|
||||
poolsListEl,
|
||||
h(
|
||||
'div',
|
||||
compactHover
|
||||
? { className: 'panel-header wm-hover-quota-foot' }
|
||||
: { className: 'panel-header', style: 'font-size: var(--fs-md); padding-top: 2px;' },
|
||||
[wkFootLeft, wkFootRight]
|
||||
),
|
||||
]);
|
||||
|
||||
function update({ data, minuteTick } = {}) {
|
||||
patchText(titleTextEl, t('module.quotas'));
|
||||
if (!data) {
|
||||
if (compactHover) {
|
||||
patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: quotaPoolRowSig,
|
||||
createRow: createPoolQuotaRow,
|
||||
updateRow: syncPoolQuotaRow,
|
||||
});
|
||||
const pendingFoot = formatQuotaSummaryFooter(null, null);
|
||||
patchText(wkFootLeft, pendingFoot.leftText);
|
||||
patchText(wkFootRight, pendingFoot.rightText);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const quotas = data.quotas || {};
|
||||
const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000);
|
||||
patchText(
|
||||
tierBadge,
|
||||
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
|
||||
);
|
||||
patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick), {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: quotaPoolRowSig,
|
||||
createRow: createPoolQuotaRow,
|
||||
updateRow: syncPoolQuotaRow,
|
||||
});
|
||||
|
||||
const footSummary = formatQuotaSummaryFooter(quotas, data.account);
|
||||
patchText(wkFootLeft, footSummary.leftText);
|
||||
patchText(wkFootRight, footSummary.rightText);
|
||||
patchAttr(wkFootLeft, 'title', footSummary.tooltip);
|
||||
patchAttr(wkFootRight, 'title', footSummary.tooltip);
|
||||
}
|
||||
|
||||
return {
|
||||
el: quotaPanel,
|
||||
refs: { update, poolsListEl },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* @fileoverview Reusable Decoupled Step Table Widget (`StepTableWidget.js`).
|
||||
* Powers both `StepsDetailView` ("按步查看") and `SettingsStructureTab` live preview,
|
||||
* dynamically rendering 2..12 columns via `stepColumnRegistry.js`, turn rail + prompt
|
||||
* preview tooltips, and independent Main/Sub agent badges.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
DEFAULT_STEP_COLUMN_KEYS,
|
||||
STEP_COLUMN_REGISTRY,
|
||||
} from '../../registries/stepColumnRegistry.js';
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
normalizeClientStepTokenComboFormat,
|
||||
} from '../../store/telemetryStore.js';
|
||||
|
||||
export function formatTurnPromptText(rawPrompt) {
|
||||
const text = String(rawPrompt || '').trim();
|
||||
if (!text || !isEnglishLocale()) return text;
|
||||
if (text === '[图片/附件提问]') return t('steps.turnMediaOnly');
|
||||
if (text.endsWith(' [附图]')) {
|
||||
return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export const StepTableWidget = defineComponent({
|
||||
name: 'StepTableWidget',
|
||||
setup({ props, onCleanup }) {
|
||||
const standalone = Boolean(props.standalone);
|
||||
const interactiveBadges = props.interactiveBadges !== false;
|
||||
const onSelectAgentScopes =
|
||||
typeof props.onSelectAgentScopes === 'function' ? props.onSelectAgentScopes : null;
|
||||
|
||||
const stepsTheadRow = h('tr');
|
||||
const stepsTbody = h('tbody');
|
||||
|
||||
function syncTableHeaderColumns(colKeys, headerCtx = {}) {
|
||||
const locale = getEffectiveLocale();
|
||||
const fmtKey = normalizeClientStepTokenComboFormat(headerCtx?.stepTokenComboFormat);
|
||||
const ctx = { stepTokenComboFormat: fmtKey };
|
||||
patchKeyedList(stepsTheadRow, colKeys, {
|
||||
keyFn: (colKey) => colKey,
|
||||
sigFn: (colKey) => `${locale}:${colKey}:${fmtKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel(ctx)}`,
|
||||
createRow: (colKey) => {
|
||||
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel(ctx) });
|
||||
return { el: th, refs: { th } };
|
||||
},
|
||||
updateRow: (refs, colKey) => {
|
||||
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel(ctx));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS);
|
||||
|
||||
const stepsTableEl = h('table', { className: 'data-table steps-data-table' }, [
|
||||
h('thead', {}, [stepsTheadRow]),
|
||||
stepsTbody,
|
||||
]);
|
||||
const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [stepsTableEl]);
|
||||
|
||||
const turnTipEl = h('div', {
|
||||
className: 'turn-prompt-tip',
|
||||
role: 'tooltip',
|
||||
hidden: true,
|
||||
});
|
||||
const hideTurnTip = () => patchAttr(turnTipEl, 'hidden', true);
|
||||
|
||||
const standaloneHostEl = standalone
|
||||
? h('div', { className: 'step-table-preview-host' }, [stepsTablePane, turnTipEl])
|
||||
: null;
|
||||
|
||||
let boundsContainerGetter =
|
||||
typeof props.getBoundsEl === 'function'
|
||||
? props.getBoundsEl
|
||||
: () => standaloneHostEl || stepsTablePane;
|
||||
|
||||
function setBoundsElGetter(fn) {
|
||||
if (typeof fn === 'function') {
|
||||
boundsContainerGetter = fn;
|
||||
}
|
||||
}
|
||||
|
||||
function showTurnTip(anchorCell, promptText) {
|
||||
const text = String(promptText || '').trim();
|
||||
const boundsEl = boundsContainerGetter?.();
|
||||
if (!anchorCell || !text) {
|
||||
hideTurnTip();
|
||||
return;
|
||||
}
|
||||
patchText(turnTipEl, text);
|
||||
patchAttr(turnTipEl, 'hidden', false);
|
||||
if (
|
||||
boundsEl &&
|
||||
typeof boundsEl.getBoundingClientRect === 'function' &&
|
||||
typeof anchorCell.getBoundingClientRect === 'function'
|
||||
) {
|
||||
const panelRect = boundsEl.getBoundingClientRect();
|
||||
const cellRect = anchorCell.getBoundingClientRect();
|
||||
if (panelRect.width > 0 && panelRect.height > 0) {
|
||||
const tipH = turnTipEl.offsetHeight || 36;
|
||||
const tipW = turnTipEl.offsetWidth || 180;
|
||||
const placeAbove =
|
||||
panelRect.bottom - cellRect.bottom < tipH + 10 &&
|
||||
cellRect.top - panelRect.top > tipH + 6;
|
||||
const topPx = placeAbove
|
||||
? Math.max(4, Math.round(cellRect.top - panelRect.top - tipH - 4))
|
||||
: Math.round(cellRect.bottom - panelRect.top + 4);
|
||||
const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8));
|
||||
const leftPx = Math.min(
|
||||
maxLeft,
|
||||
Math.max(6, Math.round(cellRect.left - panelRect.left + 4))
|
||||
);
|
||||
turnTipEl.style.top = `${topPx}px`;
|
||||
turnTipEl.style.left = `${leftPx}px`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stepsTablePane.addEventListener('scroll', hideTurnTip);
|
||||
stepsTbody.addEventListener('mouseleave', hideTurnTip);
|
||||
const hoverRows = new WeakMap();
|
||||
let lastRenderedRows = null;
|
||||
let lastRenderOptions = '';
|
||||
|
||||
function enterStepCell(event) {
|
||||
const { badge, prompt } = hoverRows.get(this);
|
||||
if (event?.target === badge) hideTurnTip();
|
||||
else showTurnTip(this, prompt);
|
||||
}
|
||||
|
||||
function moveInStepCell(event) {
|
||||
if (event?.target === hoverRows.get(this).badge) hideTurnTip();
|
||||
}
|
||||
|
||||
function moveAlongTurnRail(event) {
|
||||
const { badge, prompt } = hoverRows.get(this);
|
||||
const rect = this.getBoundingClientRect?.();
|
||||
const relX = rect ? (event?.clientX ?? 0) - rect.left : 0;
|
||||
if (event?.target !== badge && relX <= 18) showTurnTip(this, prompt);
|
||||
else hideTurnTip();
|
||||
}
|
||||
|
||||
function clearCellHover(cell) {
|
||||
if (!cell || !hoverRows.delete(cell)) return;
|
||||
cell.onmouseenter = null;
|
||||
cell.onmousemove = null;
|
||||
cell.onmouseleave = null;
|
||||
}
|
||||
|
||||
function renderStepTable(
|
||||
tableSteps,
|
||||
cascadeId,
|
||||
colKeys,
|
||||
locale,
|
||||
{
|
||||
effectiveScopes = ['all'],
|
||||
hasSubagents = false,
|
||||
isMergedMultiAgents = false,
|
||||
showStepTurnRail = false,
|
||||
showStepAgentBadge = true,
|
||||
showStepSpeedColor = false,
|
||||
stepTokenComboFormat = undefined,
|
||||
displaySettings = {},
|
||||
} = {}
|
||||
) {
|
||||
const colOrderSig = colKeys.join(',');
|
||||
const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat);
|
||||
const renderOptions = JSON.stringify([
|
||||
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
|
||||
showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt,
|
||||
displaySettings.modelDisplayMode, displaySettings.showUpstreamModel,
|
||||
displaySettings.orchestratorIdMode,
|
||||
]);
|
||||
if (lastRenderOptions === renderOptions && lastRenderedRows &&
|
||||
(lastRenderedRows === tableSteps || (lastRenderedRows.length === tableSteps.length &&
|
||||
tableSteps.every((step, i) => step === lastRenderedRows[i])))) {
|
||||
return;
|
||||
}
|
||||
const wantedSet = new Set(colKeys);
|
||||
syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt });
|
||||
|
||||
const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge);
|
||||
const cellCtx = {
|
||||
hasSubagents,
|
||||
showAgentBadge,
|
||||
showStepSpeedColor,
|
||||
stepTokenComboFormat: normTokenFmt,
|
||||
effectiveScopes,
|
||||
scopeSigKey: effectiveScopes.join(','),
|
||||
displaySettings,
|
||||
onSelectAgentScopes,
|
||||
};
|
||||
|
||||
const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents);
|
||||
const getStepTurnIdx = (st) =>
|
||||
useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex;
|
||||
const getStepIsStart = (st) =>
|
||||
Boolean(useRootTurn ? (st?.isRootTurnStart ?? st?.isTurnStart) : st?.isTurnStart);
|
||||
const getStepIsLatest = (st) =>
|
||||
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
|
||||
const getStepPrompt = (st) =>
|
||||
(useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || '';
|
||||
const turnKeys = showStepTurnRail ? tableSteps.map((st) => {
|
||||
const tIdx = getStepTurnIdx(st);
|
||||
if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
|
||||
return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`;
|
||||
}) : [];
|
||||
const formattedPrompts = new Map();
|
||||
function formattedTurnPrompt(st) {
|
||||
const raw = getStepPrompt(st);
|
||||
if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw));
|
||||
return formattedPrompts.get(raw);
|
||||
}
|
||||
|
||||
const decoratedSteps = tableSteps.map((st, idx) => {
|
||||
const tKey = turnKeys[idx];
|
||||
const hasTurn = Boolean(tKey);
|
||||
const hasUp = hasTurn && turnKeys[idx - 1] === tKey;
|
||||
const hasDown = hasTurn && turnKeys[idx + 1] === tKey;
|
||||
return {
|
||||
st,
|
||||
rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
|
||||
hasTurn,
|
||||
hasUp,
|
||||
hasDown,
|
||||
isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)),
|
||||
isLatest: hasTurn && getStepIsLatest(st),
|
||||
prompt: hasTurn ? formattedTurnPrompt(st) : '',
|
||||
};
|
||||
});
|
||||
|
||||
const railActive = Boolean(showStepTurnRail && decoratedSteps.some((d) => d.hasTurn));
|
||||
if (!railActive) {
|
||||
hideTurnTip();
|
||||
}
|
||||
patchClasses(stepsTableEl, { 'has-turn-rail': railActive });
|
||||
|
||||
patchKeyedList(stepsTbody, decoratedSteps, {
|
||||
keyFn: (item) => item.rowKey,
|
||||
sigFn: (item) => {
|
||||
const { st } = item;
|
||||
const parts = colKeys
|
||||
.map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx))
|
||||
.join('|');
|
||||
const badgeSig = showAgentBadge
|
||||
? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`
|
||||
: '';
|
||||
return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
|
||||
},
|
||||
createRow: () => {
|
||||
const tr = h('tr');
|
||||
return {
|
||||
el: tr,
|
||||
refs: {
|
||||
cellMap: new Map(),
|
||||
colOrderSig: '',
|
||||
railEl: null,
|
||||
agentBadgeEl: null,
|
||||
hoverTd: null,
|
||||
},
|
||||
};
|
||||
},
|
||||
updateRow: (refs, item, _idx, tr) => {
|
||||
const { st, hasTurn, hasUp, hasDown, isStart, isLatest, prompt } = item;
|
||||
|
||||
if (refs.colOrderSig !== colOrderSig) {
|
||||
if (refs.hoverTd) {
|
||||
clearCellHover(refs.hoverTd);
|
||||
refs.hoverTd = null;
|
||||
}
|
||||
for (const [oldColKey, entry] of refs.cellMap) {
|
||||
if (!wantedSet.has(oldColKey)) {
|
||||
if (refs.railEl?.parentNode === entry.td) {
|
||||
entry.td.removeChild(refs.railEl);
|
||||
}
|
||||
if (refs.agentBadgeEl?.parentNode === entry.td) {
|
||||
entry.td.removeChild(refs.agentBadgeEl);
|
||||
}
|
||||
tr.removeChild(entry.td);
|
||||
refs.cellMap.delete(oldColKey);
|
||||
}
|
||||
}
|
||||
|
||||
const isNewRow = refs.colOrderSig === '';
|
||||
for (let i = 0; i < colKeys.length; i++) {
|
||||
const colKey = colKeys[i];
|
||||
let cell = refs.cellMap.get(colKey);
|
||||
if (!cell) {
|
||||
cell = STEP_COLUMN_REGISTRY[colKey].createCell();
|
||||
refs.cellMap.set(colKey, cell);
|
||||
}
|
||||
if (isNewRow) {
|
||||
tr.appendChild(cell.td);
|
||||
} else {
|
||||
const currentTd = tr.children[i] || null;
|
||||
if (currentTd !== cell.td) tr.insertBefore(cell.td, currentTd);
|
||||
}
|
||||
}
|
||||
refs.colOrderSig = colOrderSig;
|
||||
}
|
||||
|
||||
for (const colKey of colKeys) {
|
||||
const cellEntry = refs.cellMap.get(colKey);
|
||||
STEP_COLUMN_REGISTRY[colKey].updateCell(cellEntry.refs, st, cellCtx);
|
||||
}
|
||||
|
||||
const firstColKey = colKeys[0];
|
||||
const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null;
|
||||
const showRowRail = Boolean(hasTurn && firstTd);
|
||||
if (showRowRail && !refs.railEl) {
|
||||
refs.railEl = h('span', { className: 'turn-rail', 'aria-hidden': 'true' });
|
||||
}
|
||||
if (showAgentBadge && firstTd && !refs.agentBadgeEl) {
|
||||
refs.agentBadgeEl = h('span', { className: 'agent-badge', style: 'margin-right: 4px;' });
|
||||
}
|
||||
if (firstTd) {
|
||||
if (refs.railEl && (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl)) {
|
||||
firstTd.insertBefore(refs.railEl, firstTd.firstChild);
|
||||
}
|
||||
const afterRail = refs.railEl
|
||||
? refs.railEl.nextSibling ?? firstTd.children[1] ?? null
|
||||
: firstTd.firstChild;
|
||||
if (refs.agentBadgeEl &&
|
||||
(refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl)) {
|
||||
firstTd.insertBefore(refs.agentBadgeEl, afterRail);
|
||||
}
|
||||
}
|
||||
|
||||
patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge || !firstTd);
|
||||
if (showAgentBadge && firstTd) {
|
||||
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
|
||||
const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : '';
|
||||
patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`);
|
||||
const badgeText = isEnglishLocale()
|
||||
? formatAgentBadgeText({
|
||||
isMain: !st.isSubagent,
|
||||
index: st.agentIndex || 0,
|
||||
badgeText: st.agentBadge,
|
||||
})
|
||||
: st.agentBadge || (st.isSubagent ? '子' : '主');
|
||||
patchText(refs.agentBadgeEl, badgeText);
|
||||
|
||||
if (interactiveBadges && onSelectAgentScopes) {
|
||||
const targetScope = st.agentId || 'main';
|
||||
const isSoleTarget =
|
||||
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
|
||||
const agentName = isEnglishLocale()
|
||||
? formatAgentLabel({
|
||||
isMain: !st.isSubagent,
|
||||
index: st.agentIndex || 0,
|
||||
role: st.agentRole || '',
|
||||
})
|
||||
: st.agentLabel || t('steps.unitAgent');
|
||||
patchAttr(
|
||||
refs.agentBadgeEl,
|
||||
'title',
|
||||
isSoleTarget
|
||||
? t('steps.badgeBackAll')
|
||||
: t('steps.badgeFilterAgent', { agent: agentName })
|
||||
);
|
||||
refs.agentBadgeEl.onclick = (e) => {
|
||||
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') {
|
||||
const next = effectiveScopes.includes(targetScope)
|
||||
? effectiveScopes.filter((id) => id !== targetScope)
|
||||
: [...effectiveScopes, targetScope];
|
||||
onSelectAgentScopes(next.length > 0 ? next : ['all']);
|
||||
} else {
|
||||
onSelectAgentScopes(isSoleTarget ? ['all'] : [targetScope]);
|
||||
}
|
||||
};
|
||||
} else {
|
||||
patchAttr(refs.agentBadgeEl, 'title', null);
|
||||
refs.agentBadgeEl.onclick = null;
|
||||
}
|
||||
} else if (refs.agentBadgeEl) {
|
||||
refs.agentBadgeEl.onclick = null;
|
||||
}
|
||||
|
||||
patchAttr(refs.railEl, 'hidden', !showRowRail);
|
||||
if (showRowRail) {
|
||||
const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : '';
|
||||
patchAttr(refs.railEl, 'class', `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}`);
|
||||
}
|
||||
|
||||
const hoverTd = showRowRail && prompt ? firstTd : null;
|
||||
if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd);
|
||||
refs.hoverTd = hoverTd;
|
||||
if (hoverTd) {
|
||||
hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt });
|
||||
hoverTd.onmouseenter = firstColKey === 'step' ? enterStepCell : null;
|
||||
hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail;
|
||||
hoverTd.onmouseleave = hideTurnTip;
|
||||
}
|
||||
},
|
||||
});
|
||||
lastRenderOptions = renderOptions;
|
||||
lastRenderedRows = tableSteps;
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
stepsTablePane.removeEventListener('scroll', hideTurnTip);
|
||||
stepsTbody.removeEventListener('mouseleave', hideTurnTip);
|
||||
});
|
||||
|
||||
return {
|
||||
el: standaloneHostEl || stepsTablePane,
|
||||
refs: {
|
||||
stepsTablePane,
|
||||
stepsTableEl,
|
||||
stepsTheadRow,
|
||||
stepsTbody,
|
||||
turnTipEl,
|
||||
syncTableHeaderColumns,
|
||||
renderStepTable,
|
||||
hideTurnTip,
|
||||
setBoundsElGetter,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* @fileoverview Theme accent palette & panel font-scale appearance engine.
|
||||
* Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts,
|
||||
* while strictly isolating `#ag-usage-monitor-capsule` from font scaling.
|
||||
*/
|
||||
|
||||
export const THEME_ACCENT_PRESETS = Object.freeze([
|
||||
{ key: 'host', labelKey: 'settings.gen.accentHost', cssColor: '' },
|
||||
{ key: 'blue', labelKey: 'settings.gen.accentBlue', cssColor: 'hsl(217 84% 53%)' },
|
||||
{ key: 'emerald', labelKey: 'settings.gen.accentEmerald', cssColor: 'hsl(152 66% 39%)' },
|
||||
{ key: 'amber', labelKey: 'settings.gen.accentAmber', cssColor: 'hsl(34 88% 46%)' },
|
||||
{ key: 'violet', labelKey: 'settings.gen.accentViolet', cssColor: 'hsl(262 76% 58%)' },
|
||||
{ key: 'cyan', labelKey: 'settings.gen.accentCyan', cssColor: 'hsl(191 82% 41%)' },
|
||||
{ key: 'rose', labelKey: 'settings.gen.accentRose', cssColor: 'hsl(346 78% 54%)' },
|
||||
]);
|
||||
|
||||
export const FONT_SCALE_FACTORS = Object.freeze({
|
||||
sm: 0.92,
|
||||
md: 1,
|
||||
lg: 1.08,
|
||||
xl: 1.15,
|
||||
});
|
||||
|
||||
export function normalizeClientThemeAccent(raw) {
|
||||
const val = String(raw ?? '').trim().toLowerCase();
|
||||
return THEME_ACCENT_PRESETS.some((p) => p.key === val) ? val : 'host';
|
||||
}
|
||||
|
||||
export function normalizeClientFontScale(raw) {
|
||||
const val = String(raw ?? '').trim().toLowerCase();
|
||||
return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md';
|
||||
}
|
||||
|
||||
function setOrClearStyleVar(el, propName, value) {
|
||||
if (!el || !el.style) return;
|
||||
if (value) {
|
||||
if (typeof el.style.setProperty === 'function') {
|
||||
el.style.setProperty(propName, value);
|
||||
} else {
|
||||
el.style[propName] = value;
|
||||
}
|
||||
} else if (typeof el.style.removeProperty === 'function') {
|
||||
el.style.removeProperty(propName);
|
||||
} else if (typeof el.style.setProperty === 'function') {
|
||||
el.style.setProperty(propName, '');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronize theme accent and (optionally) font scale tokens onto a root/host element.
|
||||
*
|
||||
* @param {HTMLElement | null | undefined} targetEl
|
||||
* @param {object | null | undefined} settings
|
||||
* @param {{ includeFontScale?: boolean }} [options]
|
||||
*/
|
||||
export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = {}) {
|
||||
if (!targetEl || !targetEl.style) return;
|
||||
const accentKey = normalizeClientThemeAccent(settings?.themeAccent);
|
||||
const preset = THEME_ACCENT_PRESETS.find((p) => p.key === accentKey) || THEME_ACCENT_PRESETS[0];
|
||||
|
||||
if (preset.key !== 'host' && preset.cssColor) {
|
||||
setOrClearStyleVar(targetEl, '--user-accent-primary', preset.cssColor);
|
||||
setOrClearStyleVar(targetEl, '--user-accent-contrast', '#ffffff');
|
||||
} else {
|
||||
setOrClearStyleVar(targetEl, '--user-accent-primary', '');
|
||||
setOrClearStyleVar(targetEl, '--user-accent-contrast', '');
|
||||
}
|
||||
targetEl.setAttribute?.('data-accent', preset.key);
|
||||
|
||||
if (includeFontScale) {
|
||||
const scaleKey = normalizeClientFontScale(settings?.fontScale);
|
||||
const factor = FONT_SCALE_FACTORS[scaleKey] ?? 1;
|
||||
setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor));
|
||||
targetEl.setAttribute?.('data-font-scale', scaleKey);
|
||||
} else {
|
||||
setOrClearStyleVar(targetEl, '--ui-font-scale', '');
|
||||
if (typeof targetEl.removeAttribute === 'function') {
|
||||
targetEl.removeAttribute('data-font-scale');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
export function defineComponent({ name, setup }) {
|
||||
return function createInstance(initialProps = {}) {
|
||||
let props = { ...initialProps };
|
||||
const props = { ...initialProps };
|
||||
const cleanups = [];
|
||||
|
||||
function emit(event, payload) {
|
||||
@@ -30,7 +30,7 @@ export function defineComponent({ name, setup }) {
|
||||
let setupResult = null;
|
||||
|
||||
function setProps(nextProps = {}) {
|
||||
props = { ...props, ...nextProps };
|
||||
Object.assign(props, nextProps);
|
||||
if (setupResult && typeof setupResult.onPropsChange === 'function') {
|
||||
setupResult.onPropsChange(props);
|
||||
}
|
||||
@@ -41,6 +41,7 @@ export function defineComponent({ name, setup }) {
|
||||
}
|
||||
|
||||
setupResult = setup({
|
||||
props,
|
||||
getProps: () => props,
|
||||
setProps,
|
||||
emit,
|
||||
|
||||
@@ -179,6 +179,15 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda
|
||||
}
|
||||
}
|
||||
|
||||
if (!container.firstChild && orderedNodes.length > 1 && typeof document.createDocumentFragment === 'function') {
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const node of orderedNodes) {
|
||||
fragment.appendChild(node);
|
||||
}
|
||||
container.appendChild(fragment);
|
||||
return;
|
||||
}
|
||||
|
||||
// Reorder or insert nodes with minimal DOM moves
|
||||
for (let i = 0; i < orderedNodes.length; i++) {
|
||||
const targetNode = orderedNodes[i];
|
||||
|
||||
@@ -3,10 +3,64 @@
|
||||
* USD estimates, countdown timers, and custom datetime displays.
|
||||
*/
|
||||
|
||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||
|
||||
const EN_MONTH_SHORT = Object.freeze([
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
|
||||
]);
|
||||
|
||||
export function formatMetric(value, unit = '') {
|
||||
return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
|
||||
}
|
||||
|
||||
export function formatCachePct(value) {
|
||||
if (value == null || !Number.isFinite(Number(value))) return '—';
|
||||
const num = Math.max(0, Math.min(100, +Number(value).toFixed(1)));
|
||||
return `${num}%`;
|
||||
}
|
||||
|
||||
export function getSpeedToneClass(tokPerSec) {
|
||||
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
||||
return 'tone-muted';
|
||||
}
|
||||
const v = Number(tokPerSec);
|
||||
if (v >= 60) return 'tone-good';
|
||||
if (v >= 35) return 'tone-info';
|
||||
if (v >= 20) return 'tone-warn';
|
||||
return 'tone-danger';
|
||||
}
|
||||
|
||||
export function getCacheToneClass(cacheHitPct, promptTokens = null) {
|
||||
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) {
|
||||
return 'tone-muted';
|
||||
}
|
||||
const v = Number(cacheHitPct);
|
||||
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) {
|
||||
return 'tone-muted';
|
||||
}
|
||||
if (v >= 85) return 'tone-good';
|
||||
if (v >= 65) return 'tone-info';
|
||||
if (v >= 30) return 'tone-warn';
|
||||
return 'tone-danger';
|
||||
}
|
||||
|
||||
export function getStepCostToneClass(costUsd) {
|
||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '';
|
||||
const v = Number(costUsd);
|
||||
if (v >= 0.3) return 'tone-danger';
|
||||
if (v >= 0.15) return 'tone-warn';
|
||||
return '';
|
||||
}
|
||||
|
||||
export function getTtftToneClass(ttftSec) {
|
||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '';
|
||||
const v = Number(ttftSec);
|
||||
if (v >= 30) return 'tone-danger';
|
||||
if (v >= 18) return 'tone-warn';
|
||||
return '';
|
||||
}
|
||||
|
||||
export function formatTokens(num) {
|
||||
const n = Number(num || 0);
|
||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
||||
@@ -34,11 +88,22 @@ export function formatCnyApprox(usdAmount, rate = 7.2) {
|
||||
export function formatDateSpanBadge(startMs, endMs) {
|
||||
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
|
||||
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date();
|
||||
if (isEnglishLocale()) {
|
||||
const sMon = EN_MONTH_SHORT[s.getMonth()] || '';
|
||||
const eMon = EN_MONTH_SHORT[e.getMonth()] || '';
|
||||
if (s.getFullYear() !== e.getFullYear()) {
|
||||
return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`;
|
||||
}
|
||||
return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`;
|
||||
}
|
||||
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()}日`;
|
||||
}
|
||||
|
||||
export function formatUsd(amount, { precise = false } = {}) {
|
||||
if (amount == null || !Number.isFinite(Number(amount))) return '待定';
|
||||
if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending');
|
||||
const val = Number(amount || 0);
|
||||
if (precise) {
|
||||
if (val > 0 && val < 0.001) return '<$0.001';
|
||||
@@ -47,42 +112,48 @@ export function formatUsd(amount, { precise = false } = {}) {
|
||||
return `$${val.toFixed(2)}`;
|
||||
}
|
||||
|
||||
const SPEED_REASON_LABELS = {
|
||||
__proto__: null,
|
||||
incomplete_or_invalid_timing: 'fmt.speedIncomplete',
|
||||
canceled: 'fmt.speedCanceled',
|
||||
compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable',
|
||||
invalid_output_tokens: 'fmt.speedInvalidOutput',
|
||||
inconsistent_timing: 'fmt.speedInconsistent',
|
||||
short_timing: 'fmt.speedShort',
|
||||
legacy_cache: 'fmt.speedLegacy',
|
||||
};
|
||||
|
||||
export function speedReasonText(reason) {
|
||||
return ({
|
||||
incomplete_or_invalid_timing: '生成未完成',
|
||||
invalid_output_tokens: '无有效输出',
|
||||
inconsistent_timing: '耗时数据异常',
|
||||
short_timing: '耗时过短 (<0.5s)',
|
||||
legacy_cache: '旧版缓存记录',
|
||||
})[reason] || '';
|
||||
const label = SPEED_REASON_LABELS[reason];
|
||||
return label ? t(label) : '';
|
||||
}
|
||||
|
||||
export function sampleSummary(summary) {
|
||||
const valid = summary?.sampleCount || 0;
|
||||
const excluded = summary?.excludedCount || 0;
|
||||
return `${valid}/${valid + excluded} 步`;
|
||||
return t('fmt.sampleSteps', { valid, total: valid + excluded });
|
||||
}
|
||||
|
||||
export function formatCountdown(isoTime, nowMs = Date.now()) {
|
||||
if (!isoTime) return '未知重置时间';
|
||||
if (!isoTime) return t('fmt.resetUnknown');
|
||||
const targetMs = Date.parse(isoTime);
|
||||
if (!Number.isFinite(targetMs) || targetMs <= 0) return '未知重置时间';
|
||||
if (!Number.isFinite(targetMs) || targetMs <= 0) return t('fmt.resetUnknown');
|
||||
const diffMs = targetMs - nowMs;
|
||||
if (diffMs <= 0) return '即将重置';
|
||||
if (diffMs < 60_000) return '<1分钟后重置';
|
||||
if (diffMs <= 0) return t('fmt.resetSoon');
|
||||
if (diffMs < 60_000) return t('fmt.resetUnder1m');
|
||||
|
||||
const totalMinutes = Math.floor(diffMs / 60000);
|
||||
const days = Math.floor(totalMinutes / (60 * 24));
|
||||
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
|
||||
if (days > 0) return `${days}天 ${hours}小时后重置`;
|
||||
if (hours > 0) return `${hours}小时 ${minutes}分后重置`;
|
||||
return `${minutes}分钟后重置`;
|
||||
if (days > 0) return t('fmt.resetDaysHours', { d: days, h: hours });
|
||||
if (hours > 0) return t('fmt.resetHoursMins', { h: hours, m: minutes });
|
||||
return t('fmt.resetMins', { m: minutes });
|
||||
}
|
||||
|
||||
export function formatCompactDateTime(ms) {
|
||||
if (!ms || !Number.isFinite(ms)) return '选择时间';
|
||||
if (!ms || !Number.isFinite(ms)) return t('fmt.selectTime');
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
@@ -101,6 +172,42 @@ export function formatElapsedSec(seconds) {
|
||||
return `${h}h ${remM}m`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化普通模型显示模式(`'short'` 精简代号 | `'upstream_compact'` 去厂商前缀原始 ID | `'upstream'` 完整原始 ID)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyShowUpstream]
|
||||
* @returns {'short'|'upstream_compact'|'upstream'}
|
||||
*/
|
||||
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||
return 'upstream_compact';
|
||||
}
|
||||
if (m === 'short') return 'short';
|
||||
if (legacyShowUpstream === true) return 'upstream';
|
||||
return 'short';
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。
|
||||
*
|
||||
* @param {string} rawText
|
||||
* @returns {string}
|
||||
*/
|
||||
export function stripVendorModelPrefix(rawText) {
|
||||
return String(rawText || '')
|
||||
.trim()
|
||||
.replace(/^(?:gemini|claude|gpt)-(?=.+)/i, '');
|
||||
}
|
||||
|
||||
function stripCompactionMarker(rawText) {
|
||||
return String(rawText || '')
|
||||
.replace(/(?:·(?:压缩|compact)|\[自动压缩\]|\[auto[- ]?compact\])\s*$/iu, '')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。
|
||||
*
|
||||
@@ -117,25 +224,38 @@ export function normalizeOrchestratorIdDisplayMode(mode) {
|
||||
* 规则:
|
||||
* - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`gemini-flash-worker-agy` / `M669`)
|
||||
* 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `worker-agy-hydrogen`;
|
||||
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型“精简代号 / 原始模型 ID”切换影响;
|
||||
* - 其余普通模型继续按 `showUpstreamModel` 与视图选项切换。
|
||||
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响;
|
||||
* - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`);
|
||||
* - 独立拆分 `baseText` 与 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。
|
||||
*
|
||||
* @param {object|null|undefined} target
|
||||
* @param {{ showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings]
|
||||
* @param {{ modelDisplayMode?: string, showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings]
|
||||
* @param {{ preferLabelInShort?: boolean, fallback?: string }} [options]
|
||||
* @returns {{ text: string, title: string, isOrchestratorSeries: boolean }}
|
||||
* @returns {{ text: string, baseText: string, compactionSuffix: string, isCompaction: boolean, title: string, isOrchestratorSeries: boolean }}
|
||||
*/
|
||||
export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
const showUpstream =
|
||||
typeof settings === 'boolean' ? settings : Boolean(settings?.showUpstreamModel);
|
||||
const modelDisplayMode =
|
||||
typeof settings === 'boolean'
|
||||
? settings
|
||||
? 'upstream'
|
||||
: 'short'
|
||||
: normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel);
|
||||
const showUpstream = modelDisplayMode !== 'short';
|
||||
const orchestratorMode = normalizeOrchestratorIdDisplayMode(
|
||||
typeof settings === 'object' && settings ? settings.orchestratorIdMode : 'compact'
|
||||
);
|
||||
const preferLabelInShort = Boolean(options?.preferLabelInShort);
|
||||
const fallback = options?.fallback ?? '模型未知';
|
||||
const fallback = options?.fallback ?? t('fmt.unknownModel');
|
||||
|
||||
if (!target || typeof target !== 'object') {
|
||||
return { text: fallback, title: fallback, isOrchestratorSeries: false };
|
||||
return {
|
||||
text: fallback,
|
||||
baseText: fallback,
|
||||
compactionSuffix: '',
|
||||
isCompaction: false,
|
||||
title: fallback,
|
||||
isOrchestratorSeries: false,
|
||||
};
|
||||
}
|
||||
|
||||
const shortText = String(
|
||||
@@ -152,9 +272,12 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
|
||||
const isCompaction =
|
||||
Boolean(target.isCompactionStep) ||
|
||||
/·压缩\s*$/.test(shortText) ||
|
||||
/·压缩\s*$/.test(upstreamText) ||
|
||||
/·压缩\s*$/.test(labelText);
|
||||
/·(?:压缩|compact)\s*$/iu.test(shortText) ||
|
||||
/·(?:压缩|compact)\s*$/iu.test(upstreamText) ||
|
||||
/·(?:压缩|compact)\s*$/iu.test(labelText) ||
|
||||
/\[自动压缩\]\s*$/u.test(labelText);
|
||||
|
||||
const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : '';
|
||||
|
||||
const combined = `${modelKeyText} ${shortText} ${labelText} ${upstreamText} ${responseText}`;
|
||||
const isOrchWorker =
|
||||
@@ -177,25 +300,215 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
compactId = 'orchestrator-argon';
|
||||
fullId = 'gemini-pro-orchestrator-argon (argon-4)';
|
||||
}
|
||||
const suffix = isCompaction ? '·压缩' : '';
|
||||
const text = `${orchestratorMode === 'full' ? fullId : compactId}${suffix}`;
|
||||
const baseText = orchestratorMode === 'full' ? fullId : compactId;
|
||||
const text = `${baseText}${compactionSuffix}`;
|
||||
const multiUpstream =
|
||||
Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
|
||||
? target.upstreamModels.join(' / ')
|
||||
: '';
|
||||
const title = multiUpstream || `${fullId}${suffix}`;
|
||||
return { text, title, isOrchestratorSeries: true };
|
||||
const title = multiUpstream || `${fullId}${compactionSuffix}`;
|
||||
return {
|
||||
text,
|
||||
baseText,
|
||||
compactionSuffix,
|
||||
isCompaction,
|
||||
title,
|
||||
isOrchestratorSeries: true,
|
||||
};
|
||||
}
|
||||
|
||||
const standardText =
|
||||
const rawSelected =
|
||||
(showUpstream
|
||||
? upstreamText || responseText || shortText || labelText
|
||||
: preferLabelInShort
|
||||
? labelText || shortText
|
||||
: shortText || labelText) || fallback;
|
||||
const cleanRawBase = stripCompactionMarker(rawSelected) || fallback;
|
||||
const baseText =
|
||||
modelDisplayMode === 'upstream_compact'
|
||||
? stripVendorModelPrefix(cleanRawBase) || cleanRawBase
|
||||
: cleanRawBase;
|
||||
const text = `${baseText}${compactionSuffix}`;
|
||||
const fullUpstreamWithSuffix = `${cleanRawBase}${compactionSuffix}`;
|
||||
const standardTitle =
|
||||
showUpstream && Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
|
||||
? target.upstreamModels.join(' / ')
|
||||
: standardText;
|
||||
return { text: standardText, title: standardTitle, isOrchestratorSeries: false };
|
||||
: showUpstream
|
||||
? fullUpstreamWithSuffix
|
||||
: text;
|
||||
return {
|
||||
text,
|
||||
baseText,
|
||||
compactionSuffix,
|
||||
isCompaction,
|
||||
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
|
||||
: normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel) !== 'short';
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ export function deliverCdpBridgeResponses(responses) {
|
||||
return delivered;
|
||||
}
|
||||
|
||||
function callViaCdpBridge(bridge, path, { method, body, signal }) {
|
||||
function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) {
|
||||
const abortErr = new Error('Request aborted');
|
||||
@@ -79,7 +79,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
|
||||
bridge.rpcPending.delete(reqId);
|
||||
cleanupQueueItem();
|
||||
reject(new Error('CDP bridge timeout'));
|
||||
}, 8000);
|
||||
}, cdpTimeoutMs);
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timeoutId);
|
||||
@@ -118,7 +118,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) {
|
||||
const upperMethod = method.toUpperCase();
|
||||
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
||||
|
||||
@@ -138,43 +138,27 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
signal = requestController.signal;
|
||||
}
|
||||
|
||||
const runRequest = async () => {
|
||||
const execHttpOnce = async (activeBridge) => {
|
||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
|
||||
const fetchFn = sidecar?.fetch
|
||||
? sidecar.fetch.bind(sidecar)
|
||||
: typeof window !== 'undefined' && typeof window.fetch === 'function'
|
||||
? window.fetch.bind(window)
|
||||
: globalThis.fetch.bind(globalThis);
|
||||
|
||||
const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path;
|
||||
const requestUrl = activeBridge ? `http://127.0.0.1:${activeBridge.port}${path}` : path;
|
||||
const headers = {};
|
||||
if (body !== undefined || !bridge) {
|
||||
if (body !== undefined || !activeBridge) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
if (bridge) {
|
||||
headers['X-Usage-Monitor-Token'] = bridge.token;
|
||||
if (bridge.transportMode === 'cdp') {
|
||||
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
|
||||
}
|
||||
}
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetchFn(requestUrl, {
|
||||
method: upperMethod,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
} catch (fetchErr) {
|
||||
if (!bridge || signal?.aborted || fetchErr?.name === 'AbortError') {
|
||||
throw fetchErr;
|
||||
}
|
||||
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
|
||||
bridge.transportMode = 'cdp';
|
||||
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
|
||||
if (activeBridge) {
|
||||
headers['X-Usage-Monitor-Token'] = activeBridge.token;
|
||||
}
|
||||
const res = await fetchFn(requestUrl, {
|
||||
method: upperMethod,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
if (signal?.aborted) {
|
||||
const abortErr = new Error('Request aborted');
|
||||
abortErr.name = 'AbortError';
|
||||
@@ -189,9 +173,60 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || `HTTP ${res.status}`);
|
||||
}
|
||||
if (activeBridge) {
|
||||
activeBridge.transportMode = 'http';
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
const fallbackViaCdpWithRecovery = async (initialBridge) => {
|
||||
initialBridge.transportMode = 'cdp';
|
||||
try {
|
||||
return await callViaCdpBridge(initialBridge, path, {
|
||||
method: upperMethod,
|
||||
body,
|
||||
signal,
|
||||
cdpTimeoutMs,
|
||||
});
|
||||
} catch (cdpErr) {
|
||||
if (signal?.aborted || cdpErr?.name === 'AbortError') {
|
||||
throw cdpErr;
|
||||
}
|
||||
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次
|
||||
const latestBridge = getWindowBridgeConfig() || initialBridge;
|
||||
latestBridge.transportMode = 'http';
|
||||
return execHttpOnce(latestBridge);
|
||||
}
|
||||
};
|
||||
|
||||
const runRequest = async () => {
|
||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
|
||||
if (bridge && bridge.transportMode === 'cdp') {
|
||||
return fallbackViaCdpWithRecovery(bridge);
|
||||
}
|
||||
|
||||
try {
|
||||
return await execHttpOnce(bridge);
|
||||
} catch (fetchErr) {
|
||||
if (signal?.aborted || fetchErr?.name === 'AbortError') {
|
||||
throw fetchErr;
|
||||
}
|
||||
if (!bridge) {
|
||||
// 辅助栏 Webview 在 Worker 热替换瞬间若有极短暂波动,延迟 180ms 自动无感重试一次
|
||||
if (upperMethod === 'GET') {
|
||||
await new Promise((r) => setTimeout(r, 180));
|
||||
if (!signal?.aborted) {
|
||||
return execHttpOnce(null);
|
||||
}
|
||||
}
|
||||
throw fetchErr;
|
||||
}
|
||||
// 当宿主环境的 CSP connect-src、混合内容策略或瞬态端口切换阻断直连时,切至带 HTTP 自愈恢复的 CDP 通道
|
||||
return fallbackViaCdpWithRecovery(bridge);
|
||||
}
|
||||
};
|
||||
|
||||
const promise = runRequest().finally(() => {
|
||||
if (dedupKey) {
|
||||
inFlightGets.delete(dedupKey);
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
/**
|
||||
* @fileoverview English (en-US) dictionary for Antigravity Usage & Speed Monitor.
|
||||
* Zero emoji characters.
|
||||
*/
|
||||
|
||||
export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
// Top Navigation
|
||||
'nav.overview': 'Live',
|
||||
'nav.consumption': 'Usage',
|
||||
'nav.steps': 'Steps',
|
||||
'nav.settings': 'Settings',
|
||||
|
||||
// Top Session Header
|
||||
'header.followLatest': 'Follow Latest Session',
|
||||
'header.currentWindowNamed': 'Current ({title})',
|
||||
'header.latestNamed': 'Latest ({title})',
|
||||
'header.lockedSession': 'Pinned Session ({id})',
|
||||
'header.lockedMeta': 'Pinned',
|
||||
'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)',
|
||||
'header.convMetaSteps': '{count} steps',
|
||||
'header.hasUpdate': 'Update',
|
||||
'header.upgradeToVer': 'Update v{ver}',
|
||||
'header.upgrading': 'Updating…',
|
||||
'header.ariaUpdate': 'New version available, click to update',
|
||||
'header.ariaRefresh': 'Refresh telemetry',
|
||||
'header.statusSyncing': 'Syncing',
|
||||
'header.statusSynced': 'Synced',
|
||||
'header.statusRetrying': 'Retrying',
|
||||
'header.statusGenerating': 'Running{suffix}',
|
||||
'header.statusQuotaCached': 'Quota Cached',
|
||||
'header.statusQuotaOffline': 'Quota Offline',
|
||||
'header.statusLive': 'Live 2s',
|
||||
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': 'N/A',
|
||||
'fmt.speedIncomplete': 'Incomplete timing',
|
||||
'fmt.speedCanceled': 'Canceled',
|
||||
'fmt.speedCompactionTimingUnavailable': 'Untimed compaction',
|
||||
'fmt.speedInvalidOutput': 'No valid output',
|
||||
'fmt.speedInconsistent': 'Invalid timing',
|
||||
'fmt.speedShort': 'Too brief (<0.5s)',
|
||||
'fmt.speedLegacy': 'Legacy cached',
|
||||
'fmt.sampleSteps': '{valid}/{total} steps',
|
||||
'fmt.resetUnknown': 'Unknown reset',
|
||||
'fmt.resetSoon': 'Resetting soon',
|
||||
'fmt.resetUnder1m': 'Resets in <1m',
|
||||
'fmt.resetDaysHours': 'Resets in {d}d {h}h',
|
||||
'fmt.resetHoursMins': 'Resets in {h}h {m}m',
|
||||
'fmt.resetMins': 'Resets in {m}m',
|
||||
'fmt.selectTime': 'Select time',
|
||||
'fmt.unknownModel': 'Unknown model',
|
||||
'fmt.compactionSuffix': '·compact',
|
||||
'fmt.mainAgent': 'Main Agent',
|
||||
'fmt.mainBadge': 'Main',
|
||||
'fmt.subAgent': 'Subagent',
|
||||
'fmt.subBadge': 'S{index}',
|
||||
'fmt.subBadgeShort': 'Sub',
|
||||
'fmt.selectedCount': '{count} {unit} selected',
|
||||
'fmt.selectedListTitle': 'Selected ({count}): {names}',
|
||||
'fmt.selectPlaceholder': 'Select',
|
||||
|
||||
// Capsule & Multi-Session Overlay
|
||||
'capsule.ariaMonitor': 'Usage & Speed Monitor',
|
||||
'capsule.ariaMulti': 'Active Sessions Overview',
|
||||
'capsule.multiZero': '0 active',
|
||||
'capsule.multiRunning': '{count} active',
|
||||
'capsule.multiRunningWithSubs': '{count} active · {subs} sub',
|
||||
'capsule.tpsRunning': 'Running',
|
||||
'capsule.tpsIdle': 'Idle',
|
||||
'capsule.quotaLeft': '{pct}% left',
|
||||
'capsule.quotaUnknown': '--% left',
|
||||
'capsule.newVersion': 'Update',
|
||||
'capsule.updating': 'Updating…',
|
||||
'capsule.ariaUpdateTitle': 'New version available, click to update',
|
||||
'capsule.hoverNewVer': 'Update v{ver} available',
|
||||
'capsule.hoverNewVerGeneric': 'New version available',
|
||||
'capsule.hoverUpdateHintTopbar': 'Click v{ver} in titlebar to update',
|
||||
'capsule.hoverUpdateHintComposer': 'Click v{ver} badge to update',
|
||||
'capsule.hoverUpdateHintTopbarGeneric': 'Click update badge in titlebar',
|
||||
'capsule.hoverUpdateHintComposerGeneric': 'Click update badge to install',
|
||||
'multi.title': 'Active Sessions',
|
||||
'multi.ariaDialog': 'Active Sessions Panel',
|
||||
'multi.pinned': 'Pinned',
|
||||
'multi.loading': 'Loading...',
|
||||
'multi.empty': 'No active running sessions',
|
||||
'multi.allIdle': 'All idle',
|
||||
'multi.metaWithSubs': '{main} main · {subs} subagents active',
|
||||
'multi.metaMainOnly': '{main} sessions active',
|
||||
'multi.hereTag': 'Here',
|
||||
'multi.inspectSessionTitle': 'Inspect session in monitor: {title}',
|
||||
|
||||
// Live Overview & Widgets
|
||||
'module.metrics': 'Live Metrics',
|
||||
'module.context': 'Context Window',
|
||||
'module.quotas': 'Available Quotas',
|
||||
'module.live_tasks': 'Live Running Tasks',
|
||||
|
||||
// Capsule Slot Metric Options
|
||||
'capMetric.context': 'Context Usage (%)',
|
||||
'capMetric.tps': 'Output Speed (TPS)',
|
||||
'capMetric.ttft': 'First Token Latency (TTFT)',
|
||||
'capMetric.avg_tps': 'Avg Speed (Avg TPS)',
|
||||
'capMetric.cost': 'Step Cost ($)',
|
||||
'capMetric.session_cost': 'Session Cost ($)',
|
||||
'capMetric.cache_hit': 'Cache Hit Rate (%)',
|
||||
'capMetric.session_tokens': 'Session Tokens',
|
||||
'capMetric.quota_auto': 'Auto Tightest Quota',
|
||||
'capMetric.gemini_5h': 'Gemini 5h Quota',
|
||||
'capMetric.gemini_weekly': 'Gemini Weekly Quota',
|
||||
'capMetric.claude_5h': 'Claude 5h Quota',
|
||||
'capMetric.claude_weekly': 'Claude Weekly Quota',
|
||||
|
||||
// Overview Matrix Metric Options & Cells
|
||||
'ovMetric.tps': 'Output Speed',
|
||||
'ovMetric.ttft': 'First Token',
|
||||
'ovMetric.avg_tps': 'Avg Speed',
|
||||
'ovMetric.step_cost': 'Step Cost',
|
||||
'ovMetric.session_cost': 'Session Cost',
|
||||
'ovMetric.cache_hit': 'Cache Hit',
|
||||
'ovMetric.session_tokens': 'Session Tokens',
|
||||
'ovMetric.context_usage': 'Context Usage',
|
||||
'ovMetric.quota_tightest': 'Tightest Quota',
|
||||
'ovMetric.subAvgTtft': 'Avg {val}',
|
||||
'ovMetric.subAvgCache': 'Avg {val}',
|
||||
'ovMetric.subValidSamples': 'Valid {samples}',
|
||||
'ovMetric.subTotalCost': 'Total {cost}',
|
||||
'ovMetric.subStepCost': 'Step {cost}',
|
||||
'ovMetric.subInOutTokens': 'In {inTok} · Out {outTok}',
|
||||
'ovMetric.subCtxRatio': '{used} / {limit}',
|
||||
'ovMetric.subQuotaPool': '{label}',
|
||||
'ovMetric.subQuotaPending': 'Waiting for quota sync',
|
||||
|
||||
// Context Window Widget
|
||||
'ctx.followActive': 'Follow Active ({badge})',
|
||||
'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window',
|
||||
'ctx.expandMore': '+{count} More ▾',
|
||||
'ctx.expandMoreTitle': 'Expand all {count} subagent context pills',
|
||||
'ctx.collapse': 'Less ▴',
|
||||
'ctx.collapseTitle': 'Collapse extra subagent pills',
|
||||
'ctx.ch.assistant': 'Assistant',
|
||||
'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments',
|
||||
'ctx.ch.toolResults': 'Tool Results',
|
||||
'ctx.ch.toolResultsTitle': 'File reads, terminal outputs, and tool execution results',
|
||||
'ctx.ch.userInput': 'User Input',
|
||||
'ctx.ch.userInputTitle': 'User messages and uploaded attachments',
|
||||
'ctx.ch.subagent': 'Subagent',
|
||||
'ctx.ch.subagentTitle': 'Subagent reports and background task notifications',
|
||||
'ctx.ch.checkpoint': 'Checkpoint',
|
||||
'ctx.ch.checkpointTitle': 'Compacted conversation checkpoint summaries',
|
||||
'ctx.ch.systemPrompt': 'System Prompt',
|
||||
'ctx.ch.systemPromptTitle': 'Core identity, sandbox, artifact, and environment prompts',
|
||||
'ctx.ch.systemTools': 'System Tools',
|
||||
'ctx.ch.systemToolsTitle': 'Built-in tool schema declarations',
|
||||
'ctx.ch.mcpTools': 'MCP Tools',
|
||||
'ctx.ch.mcpToolsTitle': 'MCP external server tool and resource schemas',
|
||||
'ctx.ch.skills': 'Skills',
|
||||
'ctx.ch.skillsTitle': 'Installed Skills index and instructions',
|
||||
'ctx.ch.userRules': 'User Rules',
|
||||
'ctx.ch.userRulesTitle': 'Global and workspace custom user_rules',
|
||||
|
||||
// Quota Pools Widget
|
||||
'quota.weeklyShort': 'Weekly',
|
||||
'quota.weeklyPool': 'Weekly ({pool})',
|
||||
'quota.loading': 'Loading...',
|
||||
'quota.failed': 'Unavailable (--%)',
|
||||
'quota.usedAndLeft': '{reset} · Used {used}% ({rem}% left)',
|
||||
'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls',
|
||||
'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls',
|
||||
'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls',
|
||||
'quota.footTokensCustom': 'Week Total: {tok} ({cost})',
|
||||
'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})',
|
||||
'quota.footCredits': 'AI Credits: {credits}',
|
||||
'quota.footCallsCustom': 'Week Calls: {calls}',
|
||||
'quota.footCallsCycle': 'Cycle Calls: {calls}',
|
||||
'quota.footTipCustom': 'Counted since Monday 00:00 local time',
|
||||
'quota.footTipCycle': 'Summed across each quota pool weekly reset window',
|
||||
|
||||
// Live Activity Widget
|
||||
'live.currentSession': 'Current Session',
|
||||
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
||||
'live.thinking': 'Thinking',
|
||||
'live.running': 'Running',
|
||||
'live.done': 'Done',
|
||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||
'live.subToggleRunning': 'Subagents {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': 'Subagents ({total}) {arrow}',
|
||||
'live.subCollapseTitle': 'Collapse subagent list',
|
||||
'live.subExpandTitle': 'Expand subagent activity list',
|
||||
|
||||
// Consumption View
|
||||
'cons.rangeToday': 'Today',
|
||||
'cons.range24h': '24h',
|
||||
'cons.range7d': '7d',
|
||||
'cons.range14d': '14d',
|
||||
'cons.range30d': '30d',
|
||||
'cons.rangeAll': 'All',
|
||||
'cons.rangeCustom': 'Custom',
|
||||
'cons.rangeAria': 'Usage statistics time range',
|
||||
'cons.applyFilter': 'Apply',
|
||||
'cons.rangeTo': 'to',
|
||||
'cons.overviewTitle': 'Usage Overview',
|
||||
'cons.totalTokens': 'Total Tokens',
|
||||
'cons.estCost': 'Est. Cost',
|
||||
'cons.cacheHitRate': 'Cache Hit Rate',
|
||||
'cons.callsCount': '{calls} calls',
|
||||
'cons.cacheHitTokens': 'Hit {tokens}',
|
||||
'cons.newInput': 'New Input',
|
||||
'cons.uncachedInput': 'Uncached input',
|
||||
'cons.cacheRead': 'Cache Read',
|
||||
'cons.savedCost': 'Saved {cost}',
|
||||
'cons.outputUsage': 'Output',
|
||||
'cons.replyAndThink': 'Reply {resp} · Think {think}',
|
||||
'cons.trendTitle': 'Usage Trend',
|
||||
'cons.allTime': 'All Time',
|
||||
'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details',
|
||||
'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details',
|
||||
'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details',
|
||||
'cons.topModels': 'Top Models',
|
||||
'cons.clientSources': 'Client Sources',
|
||||
'cons.monthlyTitle': 'Monthly Breakdown',
|
||||
'cons.monthLabel': 'M{m}',
|
||||
'cons.legInput': 'Input',
|
||||
'cons.legCache': 'Cache',
|
||||
'cons.legOutput': 'Output',
|
||||
'cons.legThinking': 'Think',
|
||||
'cons.footInput': 'In ',
|
||||
'cons.footCache': 'Cache ',
|
||||
'cons.footOutput': 'Out ',
|
||||
'cons.footThinking': 'Think ',
|
||||
'cons.footCalls': 'Calls ',
|
||||
|
||||
// Steps Detail View & Step Column Registry
|
||||
'steps.title': 'Step Records',
|
||||
'steps.tabSteps': 'Steps ({count})',
|
||||
'steps.tabStepsFiltered': 'Steps ({filtered}/{total})',
|
||||
'steps.tabModels': 'Analytics',
|
||||
'steps.allAgents': 'All Agents',
|
||||
'steps.allModels': 'All Models',
|
||||
'steps.selectModel': 'Select Model',
|
||||
'steps.unitAgent': 'agents',
|
||||
'steps.unitModel': 'models',
|
||||
'steps.lineTitle': 'Session Timeline',
|
||||
'steps.fitTitle': 'Trend Fit',
|
||||
'steps.modelsTitle': 'Model Summary',
|
||||
'steps.modelsEmpty': 'No model calls in current scope',
|
||||
'steps.metricTotalTokens': 'Tokens',
|
||||
'steps.metricContext': 'Context',
|
||||
'steps.metricTps': 'TPS',
|
||||
'steps.metricTtft': 'TTFT',
|
||||
'steps.metricCache': 'Cache',
|
||||
'steps.metricCost': 'Cost',
|
||||
'steps.badgeBackAll': 'Click to return to All Agents',
|
||||
'steps.badgeFilterAgent': 'Click to filter {agent} (Ctrl/Shift-click to multi-select)',
|
||||
'steps.ctxTitle': 'Context {ctx} · Thinking {think} · Reply {resp}',
|
||||
'steps.ioCacheTitle': 'New In {inPart} · Out {outPart} · Cache Read {cachePart}',
|
||||
'steps.tokSeg.context.th': 'Ctx',
|
||||
'steps.tokSeg.context.tip': 'Context',
|
||||
'steps.tokSeg.in.th': 'In',
|
||||
'steps.tokSeg.in.tip': 'New In',
|
||||
'steps.tokSeg.out.th': 'Out',
|
||||
'steps.tokSeg.out.tip': 'Output',
|
||||
'steps.tokSeg.cache.th': 'Cache',
|
||||
'steps.tokSeg.cache.tip': 'Cache Read',
|
||||
'steps.tokSeg.think.th': 'Think',
|
||||
'steps.tokSeg.think.tip': 'Thinking',
|
||||
'steps.tokSeg.reply.th': 'Reply',
|
||||
'steps.tokSeg.reply.tip': 'Reply',
|
||||
'steps.tokSeg.total.th': 'Total',
|
||||
'steps.tokSeg.total.tip': 'Total',
|
||||
'steps.modelCallsShare': '{calls} calls · {pct}%',
|
||||
'steps.modelCallsOnly': '{calls} calls',
|
||||
'steps.modelsSummaryPrefix': '{count} models · ',
|
||||
'steps.modelPerfFoot': 'Avg {tps} · TTFT {ttft} · Cache {cache}%',
|
||||
'steps.modelSplitFoot': 'In {inTok} · Cache {cacheTok} · Think {thinkTok} · Out {respTok}',
|
||||
'steps.fitActiveCardTitle': '{title} (Active in Trend Fit; Ctrl/Shift-click to compare)',
|
||||
'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)',
|
||||
'steps.turnMediaOnly': '[Media Attachment]',
|
||||
'steps.turnMediaSuffix': '[Media]',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': 'Step',
|
||||
'stepCol.step.opt': 'Step Number (#)',
|
||||
'stepCol.time.th': 'Time',
|
||||
'stepCol.time.opt': 'Timestamp (HH:mm:ss)',
|
||||
'stepCol.model.th': 'Model',
|
||||
'stepCol.model.opt': 'Model',
|
||||
'stepCol.tps.th': 'Speed',
|
||||
'stepCol.tps.opt': 'Output Speed (TPS)',
|
||||
'stepCol.ttft.th': 'TTFT',
|
||||
'stepCol.ttft.opt': 'First Token (TTFT)',
|
||||
'stepCol.duration.th': 'Time(s)',
|
||||
'stepCol.duration.opt': 'Total Duration (s)',
|
||||
'stepCol.tokens_combo.th': 'Ctx / Think / Reply',
|
||||
'stepCol.tokens_combo.opt': 'Ctx / Think / Reply (Combo)',
|
||||
'stepCol.tokens_io_cache.th': 'In / Out / Cache',
|
||||
'stepCol.tokens_io_cache.opt': 'In / Out / Cache (Combo)',
|
||||
'stepCol.tokens_custom.opt': 'Custom Combo ({fmt})',
|
||||
'stepCol.input_tokens.th': 'Input',
|
||||
'stepCol.input_tokens.opt': 'New Input Tokens',
|
||||
'stepCol.cache_tokens.th': 'CacheTok',
|
||||
'stepCol.cache_tokens.opt': 'Cache Read Tokens',
|
||||
'stepCol.output_tokens.th': 'Output',
|
||||
'stepCol.output_tokens.opt': 'Total Output Tokens',
|
||||
'stepCol.cache.th': 'Cache',
|
||||
'stepCol.cache.opt': 'Cache Hit Rate (%)',
|
||||
'stepCol.cost.th': 'Cost',
|
||||
'stepCol.cost.opt': 'Step Cost ($)',
|
||||
|
||||
// Preferences (3-Tab Modular Settings)
|
||||
'settings.subTab.general': 'General',
|
||||
'settings.subTab.structure': 'Structure',
|
||||
'settings.subTab.account': 'Account',
|
||||
'settings.subTab.other': 'Other',
|
||||
'settings.account.current': 'Current account',
|
||||
'settings.account.signedOut': 'Signed out',
|
||||
'settings.account.unknown': 'Account status unavailable',
|
||||
'settings.account.email': 'Account email',
|
||||
'settings.account.credential': 'OAuth credential',
|
||||
'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.',
|
||||
'settings.account.save': 'Import credential',
|
||||
'settings.account.capture': 'Save current credential',
|
||||
'settings.account.reload': 'Refresh list',
|
||||
'settings.account.switch': 'Switch',
|
||||
'settings.account.remove': 'Remove',
|
||||
'settings.account.active': 'In use',
|
||||
'settings.account.written': 'Credential written',
|
||||
'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.',
|
||||
'settings.account.savedCredentials': 'Saved credentials',
|
||||
'settings.account.empty': 'No saved credentials.',
|
||||
'settings.account.loading': 'Loading saved credentials…',
|
||||
'settings.account.saved': 'Credential saved.',
|
||||
'settings.account.removed': 'Saved credential removed.',
|
||||
'settings.account.switched': 'Account switched. Refreshing the current quota.',
|
||||
'settings.account.switching': 'Replacing the credential and confirming the active account…',
|
||||
'settings.account.verifying': 'Verifying the credential owner…',
|
||||
'settings.account.loadQuota': 'Check quota',
|
||||
'settings.account.loadingQuota': 'Checking quota for this credential…',
|
||||
'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.',
|
||||
'settings.account.quota': 'Quota remaining by pool',
|
||||
'settings.account.quota5h': '5 hours {percent}%',
|
||||
'settings.account.quotaWeekly': 'Weekly {percent}%',
|
||||
'settings.account.noQuota': 'Quota pools are unavailable for the current account.',
|
||||
'settings.account.quotaStale': 'Quota refresh failed. Showing the last data for the current account.',
|
||||
'settings.account.unsupported': 'Credential switching currently supports Antigravity shared sign-in on Windows.',
|
||||
'settings.account.invalidEmail': 'Select a saved account first.',
|
||||
'settings.account.invalidCredential': 'Enter a valid Antigravity OAuth credential for a personal account.',
|
||||
'settings.account.credentialTooLarge': 'The credential exceeds the Windows Credential Manager limit of 2560 bytes.',
|
||||
'settings.account.notFound': 'This credential was removed. Refresh the list.',
|
||||
'settings.account.noCurrentCredential': 'The shared credential for the current account is unavailable.',
|
||||
'settings.account.busy': 'Another window is updating credentials. Try again shortly.',
|
||||
'settings.account.storeFailed': 'The credential operation failed. Try again.',
|
||||
'settings.account.rollbackFailed': 'Writing and restoring the credential both failed. Check the active account in Antigravity before continuing.',
|
||||
'settings.account.credentialAccessDenied': 'Windows denied access to Credential Manager. Open Antigravity in your Windows user session and try again.',
|
||||
'settings.account.credentialChanged': 'This credential was updated in another window. Refresh the list and try again.',
|
||||
'settings.account.credentialRejected': 'Google rejected this credential. Check that the Antigravity refresh token is still valid.',
|
||||
'settings.account.identityMismatch': 'The credential belongs to a different account. Import the credential again.',
|
||||
'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.',
|
||||
'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.',
|
||||
'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.',
|
||||
'settings.subTab.aria': 'Preferences category tabs',
|
||||
'settings.saving': 'Saving…',
|
||||
'settings.saved': 'Saved',
|
||||
'settings.saveFailed': 'Save failed',
|
||||
'settings.resetDone': 'Reset to default',
|
||||
'settings.resetBtn': 'Reset',
|
||||
|
||||
// Preferences -> General Tab
|
||||
'settings.gen.appearanceTitle': 'Interface & Appearance',
|
||||
'settings.gen.language': 'Language',
|
||||
'settings.gen.langZh': '简体中文',
|
||||
'settings.gen.langEn': 'English',
|
||||
'settings.gen.langAuto': 'Follow System',
|
||||
'settings.gen.themeAccent': 'Accent Color',
|
||||
'settings.gen.accentHost': 'Host',
|
||||
'settings.gen.accentBlue': 'Blue',
|
||||
'settings.gen.accentEmerald': 'Emerald',
|
||||
'settings.gen.accentAmber': 'Amber',
|
||||
'settings.gen.accentViolet': 'Violet',
|
||||
'settings.gen.accentCyan': 'Cyan',
|
||||
'settings.gen.accentRose': 'Rose',
|
||||
'settings.gen.fontScale': 'Font Size',
|
||||
'settings.gen.fontSm': 'Small',
|
||||
'settings.gen.fontMd': 'Default',
|
||||
'settings.gen.fontLg': 'Large',
|
||||
'settings.gen.fontXl': 'XL',
|
||||
'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact',
|
||||
'settings.gen.updateTitle': 'Updates & Pricing',
|
||||
'settings.gen.updateMode': 'Update Policy',
|
||||
'settings.gen.updateManual': 'Notify only, update manually',
|
||||
'settings.gen.updateAuto': 'Auto update',
|
||||
'settings.gen.updateOff': 'Disable updates',
|
||||
'settings.gen.pricingLabel': 'Pricing Catalog',
|
||||
'settings.gen.versionLabel': 'Current Version',
|
||||
'settings.gen.modelCount': '{count} models',
|
||||
'settings.gen.srcRemote': 'Cloud synced',
|
||||
'settings.gen.srcLocal': 'Local file',
|
||||
'settings.gen.srcDefault': 'Built-in',
|
||||
'settings.gen.syncAt': 'Synced {time}',
|
||||
'settings.gen.pubAt': 'Published {date}',
|
||||
'settings.gen.defaultPricing': 'Default catalog',
|
||||
'settings.gen.syncBtn': 'Sync Pricing',
|
||||
'settings.gen.syncingBtn': 'Syncing…',
|
||||
'settings.gen.syncingMsg': 'Syncing pricing catalog…',
|
||||
'settings.gen.syncedMsg': 'Pricing updated ({count} models)',
|
||||
'settings.gen.syncFallbackMsg': 'Timed out, using local catalog',
|
||||
'settings.gen.checkUpdateBtn': 'Check Updates',
|
||||
'settings.gen.checkingBtn': 'Checking…',
|
||||
'settings.gen.checkingMsg': 'Checking for updates…',
|
||||
'settings.gen.checkFailedMsg': 'Check failed: {err}',
|
||||
'settings.gen.upToDateMsg': 'Already up to date (v{ver})',
|
||||
'settings.gen.downloadingMsg': 'Downloading update…',
|
||||
'settings.gen.updatedRestartMsg': 'Update complete, restarting panel…',
|
||||
'settings.gen.updateSkippedMsg': 'Update not applied',
|
||||
'settings.gen.updateFailedMsg': 'Update failed',
|
||||
'settings.gen.canUpgradeSub': 'v{ver} available ({mode})',
|
||||
'settings.gen.upgradeToBtn': 'Upgrade to v{ver}',
|
||||
'settings.gen.manualUpgradeBtn': 'Upgrade v{ver}',
|
||||
'settings.gen.updateOffSub': 'Notifications off ({mode})',
|
||||
'settings.gen.latestSub': 'Up to date ({mode})',
|
||||
|
||||
// Preferences -> Structure Tab
|
||||
'settings.str.thirdTabAria': 'Structure section tabs',
|
||||
'settings.str.tabMount': 'Mount & Bar',
|
||||
'settings.str.tabHover': 'Hover View',
|
||||
'settings.str.tabOverview': 'Overview',
|
||||
'settings.str.tabSteps': 'Step Table',
|
||||
'settings.str.previewMountSidebarHint': 'Window capsule is disabled in Sidebar Only mode; switching back to Titlebar or Composer applies the capsule above',
|
||||
'settings.str.mountSection': 'Mount & Capsule Bar',
|
||||
'settings.str.mountBadge': '{count}/5 slots',
|
||||
'settings.str.mountMode': 'Panel Mount Mode',
|
||||
'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)',
|
||||
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
|
||||
'settings.str.mountSidebar': 'Sidebar Only',
|
||||
'settings.str.popoverWidthLabel': 'Popover Width',
|
||||
'settings.str.popoverWidthAuto': 'Auto Fit',
|
||||
'settings.str.popoverWidthCustom': 'Custom',
|
||||
'settings.str.popoverWidthHint': 'Auto Fit widens wide tables like Step Records to avoid horizontal scroll; Custom accepts 440–1080 px',
|
||||
'settings.str.multiToggle': 'Active Sessions Pill',
|
||||
'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule',
|
||||
'settings.str.show': 'Show',
|
||||
'settings.str.hide': 'Hide',
|
||||
'settings.str.on': 'On',
|
||||
'settings.str.off': 'Off',
|
||||
'settings.str.capsuleSlotsLabel': 'Capsule Metrics & Order (Left → Right, 1–5, draggable)',
|
||||
'settings.str.addCapsuleSlot': 'Add Slot ({count}/{max})',
|
||||
'settings.str.hoverSection': 'Hover Quick-View',
|
||||
'settings.str.hoverBadgeOff': 'Off',
|
||||
'settings.str.hoverBadgeCount': '{count} modules',
|
||||
'settings.str.hoverModulesLabel': 'Hover Popup Modules (Top → Bottom, 0–4, draggable)',
|
||||
'settings.str.hoverEmptyHint': 'Hover quick-view disabled (click capsule to open full panel)',
|
||||
'settings.str.addHoverModule': 'Add Module ({count}/{max})',
|
||||
'settings.str.overviewSection': 'Live Overview Layout',
|
||||
'settings.str.overviewBadge': '{modCount} mod · {metCount} cells',
|
||||
'settings.str.overviewModulesLabel': 'Overview Modules & Order (Top → Bottom, min 1, draggable)',
|
||||
'settings.str.addOverviewModule': 'Add Module ({count}/{max})',
|
||||
'settings.str.overviewMetricsLabel': 'First-Row Metrics (Left → Right, 1–4, draggable)',
|
||||
'settings.str.overviewMetricsInactiveHint': '"Live Metrics" is hidden here; these cells still apply to Hover Quick-View or when re-added',
|
||||
'settings.str.addOverviewMetric': 'Add Metric ({count}/{max})',
|
||||
'settings.str.stepsSection': 'Step Table Columns',
|
||||
'settings.str.stepsBadge': '{count} cols',
|
||||
'settings.str.stepTurnRailToggle': 'Turn Rail & Preview',
|
||||
'settings.str.stepAgentBadgeToggle': 'Main/Sub Agent Badge',
|
||||
'settings.str.stepSpeedColorToggle': 'Speed Multi-Color',
|
||||
'settings.str.stepTokenComboLabel': 'Custom Token Combo Format',
|
||||
'settings.str.stepTokenComboPlaceholder': 'e.g. context:new:cache or in:out:cache',
|
||||
'settings.str.stepTokenComboHint': 'Tokens: context, in/new, out, cache, think, reply, total — separated by : or / (1–4 items)',
|
||||
'settings.str.stepsColsLabel': '"Steps" Visible Columns (Left → Right, min 2, draggable)',
|
||||
'settings.str.addStepCol': 'Add Column ({count}/{max})',
|
||||
'settings.slot.dragHint': 'Drag up or down to reorder',
|
||||
'settings.slot.moveUp': 'Move earlier',
|
||||
'settings.slot.moveDown': 'Move later',
|
||||
'settings.slot.remove': 'Remove item',
|
||||
'settings.slot.minReached': 'Keep at least {min}',
|
||||
'settings.slot.alreadyAdded': 'Added',
|
||||
'settings.mock.sessionTitle': 'Refactor Auth Middleware & Session Cache',
|
||||
'settings.mock.subRole': 'API Audit',
|
||||
'settings.mock.turnPromptLatest': 'Fix token refresh race condition under concurrent requests and add tests',
|
||||
'settings.mock.turnPromptPrev': 'Audit route guards and expired session cleanup logic',
|
||||
|
||||
// Preferences -> Other Tab
|
||||
'settings.oth.modelTitle': 'Model Identity Display',
|
||||
'settings.oth.modelFormat': 'Model Name Format',
|
||||
'settings.oth.modelShort': 'Short Alias (e.g. argon-4-high)',
|
||||
'settings.oth.modelUpstream': 'Raw Upstream ID (e.g. gemini-3.8-flash-n)',
|
||||
'settings.oth.modelUpstreamCompact': 'Trimmed Raw ID (hide gemini- / claude- / gpt-)',
|
||||
'settings.oth.orchFormat': 'Orchestrator Series ID',
|
||||
'settings.oth.orchCompact': 'Compact Alias (e.g. orchestrator-argon)',
|
||||
'settings.oth.orchFull': 'Full Upstream ID (e.g. gemini-pro-orchestrator)',
|
||||
'settings.oth.baselineTitle': 'Model Context Settings',
|
||||
'settings.oth.ctxRiskTitle': 'Unofficial Override Risk Warning',
|
||||
'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!',
|
||||
'settings.oth.ctxRiskAcceptBtn': 'I Understand the Risk, Unlock',
|
||||
'settings.oth.ctxModel': 'Model',
|
||||
'settings.oth.ctxBaselineLabel': 'Context Window Limit',
|
||||
'settings.oth.ctxChooseModel': 'Choose a model',
|
||||
'settings.oth.ctxDefault': 'Follow host settings',
|
||||
'settings.oth.ctxExpensive': '{name} (uses more quota)',
|
||||
'settings.oth.ctxTokens': '{count} tokens',
|
||||
'settings.oth.ctxUnavailable': '{name} (currently unavailable)',
|
||||
'settings.oth.ctxConfigured': '{name} · Set',
|
||||
'settings.oth.ctxConfiguredReported': '{name} · Set / Last seen {reported}',
|
||||
'settings.oth.ctxDefaultReported': 'Default · Last seen {name}',
|
||||
'settings.oth.ctxReported': 'The host reported {name} on the latest request.',
|
||||
'settings.oth.ctxMixed': 'Different limits by thinking level',
|
||||
'settings.oth.ctxMixedHint': 'Thinking levels for this model have different saved limits. Choose a limit to apply it to all levels.',
|
||||
'settings.oth.ctxBaselineHint': 'Thinking levels for the same model share a limit. Saved limits are reapplied at plugin startup and used for future messages.',
|
||||
'settings.oth.ctxNoModels': 'The host has not returned any available models.',
|
||||
'settings.oth.ctxNoOptions': 'The host has not provided context options or a capacity for this model. Follow host settings is the only available option.',
|
||||
'settings.oth.maintTitle': 'Cache & Reset',
|
||||
'settings.oth.cacheLabel': 'Local Trajectory Cache',
|
||||
'settings.oth.cacheDesc': 'Clear cached step records and rescan all conversation transcripts immediately',
|
||||
'settings.oth.rebuildBtn': 'Rebuild Trajectory Cache',
|
||||
'settings.oth.rebuildingBtn': 'Rebuilding…',
|
||||
'settings.oth.rebuildDone': 'Trajectory cache rebuilt',
|
||||
'settings.oth.rebuildFailed': 'Failed to rebuild cache',
|
||||
'settings.oth.resetLabel': 'Factory Defaults',
|
||||
'settings.oth.resetDesc': 'Restore all preferences across General, Structure, and Other tabs to default values',
|
||||
'settings.oth.resetAllBtn': 'Reset All Defaults',
|
||||
'settings.oth.resetConfirmBtn': 'Click Again to Confirm',
|
||||
'settings.oth.resettingBtn': 'Resetting…',
|
||||
'settings.oth.resetAllDone': 'All preferences restored to defaults',
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* @fileoverview Reactive lightweight i18n engine (`zh-CN` / `en-US` / `auto`).
|
||||
* Default language is `'zh-CN'` so out-of-the-box UI matches existing behavior 100%.
|
||||
*/
|
||||
|
||||
import { createReactiveStore } from '../core/reactive.js';
|
||||
import { I18N_MESSAGES_ZH_CN } from './zh-CN.js';
|
||||
import { I18N_MESSAGES_EN_US } from './en-US.js';
|
||||
|
||||
export const I18N_DICTIONARIES = Object.freeze({
|
||||
'zh-CN': I18N_MESSAGES_ZH_CN,
|
||||
'en-US': I18N_MESSAGES_EN_US,
|
||||
});
|
||||
|
||||
export function normalizeI18nLanguage(raw) {
|
||||
const val = String(raw ?? '').trim();
|
||||
if (val === 'auto') return 'auto';
|
||||
if (/^en(?:-|$)/i.test(val)) return 'en-US';
|
||||
if (/^zh(?:-|$)/i.test(val)) return 'zh-CN';
|
||||
return 'zh-CN';
|
||||
}
|
||||
|
||||
export function detectHostSystemLocale() {
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && navigator.language) {
|
||||
return String(navigator.language).toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US';
|
||||
}
|
||||
} catch {
|
||||
// Ignore environment navigator read errors
|
||||
}
|
||||
return 'zh-CN';
|
||||
}
|
||||
|
||||
export const i18nStore = createReactiveStore({
|
||||
language: 'zh-CN',
|
||||
locale: 'zh-CN',
|
||||
});
|
||||
|
||||
export function setI18nLanguage(rawLang) {
|
||||
const language = normalizeI18nLanguage(rawLang);
|
||||
const locale = language === 'auto' ? detectHostSystemLocale() : language;
|
||||
const cur = i18nStore.getState();
|
||||
if (cur.language !== language || cur.locale !== locale) {
|
||||
i18nStore.setState({ language, locale });
|
||||
}
|
||||
return locale;
|
||||
}
|
||||
|
||||
export function getEffectiveLocale() {
|
||||
return i18nStore.getState().locale || 'zh-CN';
|
||||
}
|
||||
|
||||
export function isEnglishLocale() {
|
||||
return getEffectiveLocale() === 'en-US';
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a message key with optional `{name}` variable interpolation.
|
||||
*
|
||||
* @param {string} key
|
||||
* @param {Record<string, string | number>} [vars]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function t(key, vars = undefined) {
|
||||
const locale = getEffectiveLocale();
|
||||
const dict = I18N_DICTIONARIES[locale] || I18N_MESSAGES_ZH_CN;
|
||||
const template = dict[key] ?? I18N_MESSAGES_ZH_CN[key] ?? key;
|
||||
if (!vars || typeof template !== 'string') return template;
|
||||
return template.replace(/\{(\w+)\}/g, (_, k) =>
|
||||
vars[k] !== undefined && vars[k] !== null ? String(vars[k]) : ''
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/**
|
||||
* @fileoverview Simplified Chinese (zh-CN) dictionary for Antigravity Usage & Speed Monitor.
|
||||
* Matches 100% of the existing out-of-the-box UI copy. Zero emoji characters.
|
||||
*/
|
||||
|
||||
export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
// Top Navigation
|
||||
'nav.overview': '实时监控',
|
||||
'nav.consumption': '用量统计',
|
||||
'nav.steps': '调用明细',
|
||||
'nav.settings': '偏好设置',
|
||||
|
||||
// Top Session Header
|
||||
'header.followLatest': '跟随最新会话',
|
||||
'header.currentWindowNamed': '当前窗口 ({title})',
|
||||
'header.latestNamed': '最新 ({title})',
|
||||
'header.lockedSession': '已锁定会话 ({id})',
|
||||
'header.lockedMeta': '已锁定',
|
||||
'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)',
|
||||
'header.convMetaSteps': '{count}步',
|
||||
'header.hasUpdate': '有新版本',
|
||||
'header.upgradeToVer': '升级 v{ver}',
|
||||
'header.upgrading': '升级中…',
|
||||
'header.ariaUpdate': '发现新版本,点击升级',
|
||||
'header.ariaRefresh': '刷新数据',
|
||||
'header.statusSyncing': '同步中',
|
||||
'header.statusSynced': '已刷新',
|
||||
'header.statusRetrying': '重试中',
|
||||
'header.statusGenerating': '生成中{suffix}',
|
||||
'header.statusQuotaCached': '额度缓存',
|
||||
'header.statusQuotaOffline': '额度离线',
|
||||
'header.statusLive': '实时 2s',
|
||||
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': '待定',
|
||||
'fmt.speedIncomplete': '计时不完整',
|
||||
'fmt.speedCanceled': '已取消',
|
||||
'fmt.speedCompactionTimingUnavailable': '压缩无计时',
|
||||
'fmt.speedInvalidOutput': '无有效输出',
|
||||
'fmt.speedInconsistent': '耗时数据异常',
|
||||
'fmt.speedShort': '耗时过短 (<0.5s)',
|
||||
'fmt.speedLegacy': '旧版缓存记录',
|
||||
'fmt.sampleSteps': '{valid}/{total} 步',
|
||||
'fmt.resetUnknown': '未知重置时间',
|
||||
'fmt.resetSoon': '即将重置',
|
||||
'fmt.resetUnder1m': '<1分钟后重置',
|
||||
'fmt.resetDaysHours': '{d}天 {h}小时后重置',
|
||||
'fmt.resetHoursMins': '{h}小时 {m}分后重置',
|
||||
'fmt.resetMins': '{m}分钟后重置',
|
||||
'fmt.selectTime': '选择时间',
|
||||
'fmt.unknownModel': '模型未知',
|
||||
'fmt.compactionSuffix': '·压缩',
|
||||
'fmt.mainAgent': '主代理',
|
||||
'fmt.mainBadge': '主',
|
||||
'fmt.subAgent': '子代理',
|
||||
'fmt.subBadge': '子{index}',
|
||||
'fmt.subBadgeShort': '子',
|
||||
'fmt.selectedCount': '已选 {count} {unit}',
|
||||
'fmt.selectedListTitle': '已选 ({count}):{names}',
|
||||
'fmt.selectPlaceholder': '请选择',
|
||||
|
||||
// Capsule & Multi-Session Overlay
|
||||
'capsule.ariaMonitor': '用量与速度监控',
|
||||
'capsule.ariaMulti': '多会话实时信息',
|
||||
'capsule.multiZero': '0 运行中',
|
||||
'capsule.multiRunning': '{count} 运行中',
|
||||
'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子',
|
||||
'capsule.tpsRunning': '生成中',
|
||||
'capsule.tpsIdle': '待命',
|
||||
'capsule.quotaLeft': '余 {pct}%',
|
||||
'capsule.quotaUnknown': '余 --%',
|
||||
'capsule.newVersion': '新版本',
|
||||
'capsule.updating': '更新中…',
|
||||
'capsule.ariaUpdateTitle': '发现新版本,点击立即更新',
|
||||
'capsule.hoverNewVer': '发现新版本 v{ver}',
|
||||
'capsule.hoverNewVerGeneric': '发现新版本可用',
|
||||
'capsule.hoverUpdateHintTopbar': '点击顶栏 v{ver} 即可更新',
|
||||
'capsule.hoverUpdateHintComposer': '点击版本胶囊 v{ver} 即可更新',
|
||||
'capsule.hoverUpdateHintTopbarGeneric': '点击顶栏版本胶囊即可更新',
|
||||
'capsule.hoverUpdateHintComposerGeneric': '点击版本胶囊即可更新',
|
||||
'multi.title': '实时运行会话',
|
||||
'multi.ariaDialog': '多会话实时信息面板',
|
||||
'multi.pinned': '已固定',
|
||||
'multi.loading': '读取中...',
|
||||
'multi.empty': '当前暂无在线运行的会话',
|
||||
'multi.allIdle': '全部待命',
|
||||
'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中',
|
||||
'multi.metaMainOnly': '{main} 个会话运行中',
|
||||
'multi.hereTag': '本窗',
|
||||
'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}',
|
||||
|
||||
// Live Overview & Widgets
|
||||
'module.metrics': '实时指标',
|
||||
'module.context': '上下文窗口',
|
||||
'module.quotas': '可用额度',
|
||||
'module.live_tasks': '实时运行任务',
|
||||
|
||||
// Capsule Slot Metric Options
|
||||
'capMetric.context': '上下文占用 (%)',
|
||||
'capMetric.tps': '输出速度 (TPS)',
|
||||
'capMetric.ttft': '首字延迟 (TTFT)',
|
||||
'capMetric.avg_tps': '会话均速 (Avg TPS)',
|
||||
'capMetric.cost': '本次费用 ($)',
|
||||
'capMetric.session_cost': '会话累计费用 ($)',
|
||||
'capMetric.cache_hit': '缓存命中率 (%)',
|
||||
'capMetric.session_tokens': '会话总 Token',
|
||||
'capMetric.quota_auto': '自动紧俏额度',
|
||||
'capMetric.gemini_5h': 'Gemini 5h 额度',
|
||||
'capMetric.gemini_weekly': 'Gemini 周额度',
|
||||
'capMetric.claude_5h': 'Claude 5h 额度',
|
||||
'capMetric.claude_weekly': 'Claude 周额度',
|
||||
|
||||
// Overview Matrix Metric Options & Cells
|
||||
'ovMetric.tps': '输出速度',
|
||||
'ovMetric.ttft': '首字延迟',
|
||||
'ovMetric.avg_tps': '平均速度',
|
||||
'ovMetric.step_cost': '本次费用',
|
||||
'ovMetric.session_cost': '累计费用',
|
||||
'ovMetric.cache_hit': '缓存命中率',
|
||||
'ovMetric.session_tokens': '会话 Token',
|
||||
'ovMetric.context_usage': '上下文占用',
|
||||
'ovMetric.quota_tightest': '紧俏额度',
|
||||
'ovMetric.subAvgTtft': '均值 {val}',
|
||||
'ovMetric.subAvgCache': '均值 {val}',
|
||||
'ovMetric.subValidSamples': '有效 {samples}',
|
||||
'ovMetric.subTotalCost': '累计 {cost}',
|
||||
'ovMetric.subStepCost': '本次 {cost}',
|
||||
'ovMetric.subInOutTokens': '入 {inTok} · 出 {outTok}',
|
||||
'ovMetric.subCtxRatio': '{used} / {limit}',
|
||||
'ovMetric.subQuotaPool': '{label}',
|
||||
'ovMetric.subQuotaPending': '等待配额同步',
|
||||
|
||||
// Context Window Widget
|
||||
'ctx.followActive': '跟随活跃 ({badge})',
|
||||
'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口',
|
||||
'ctx.expandMore': '+{count} 展开 ▾',
|
||||
'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊',
|
||||
'ctx.collapse': '收起 ▴',
|
||||
'ctx.collapseTitle': '折叠多余子代理胶囊',
|
||||
'ctx.ch.assistant': '模型回复',
|
||||
'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参',
|
||||
'ctx.ch.toolResults': '工具结果',
|
||||
'ctx.ch.toolResultsTitle': '文件读取、终端输出与工具执行返回内容',
|
||||
'ctx.ch.userInput': '用户消息',
|
||||
'ctx.ch.userInputTitle': '用户提问文本与上传附件',
|
||||
'ctx.ch.subagent': '子代理通知',
|
||||
'ctx.ch.subagentTitle': '子代理完成汇报与后台任务系统通知',
|
||||
'ctx.ch.checkpoint': '压缩摘要',
|
||||
'ctx.ch.checkpointTitle': '自动上下文压缩生成的历史摘要检查点',
|
||||
'ctx.ch.systemPrompt': '系统提示词',
|
||||
'ctx.ch.systemPromptTitle': '核心身份、终端沙箱、制品与环境提示词',
|
||||
'ctx.ch.systemTools': '系统工具',
|
||||
'ctx.ch.systemToolsTitle': '内置系统工具 Schema 定义',
|
||||
'ctx.ch.mcpTools': 'MCP 工具',
|
||||
'ctx.ch.mcpToolsTitle': 'MCP 外部服务工具与资源定义',
|
||||
'ctx.ch.skills': 'Skill',
|
||||
'ctx.ch.skillsTitle': '已挂载的 Skills 技能索引与说明',
|
||||
'ctx.ch.userRules': '用户规则',
|
||||
'ctx.ch.userRulesTitle': '全局与工作区自定义规则 (user_rules)',
|
||||
|
||||
// Quota Pools Widget
|
||||
'quota.weeklyShort': '周限',
|
||||
'quota.weeklyPool': '周限 ({pool})',
|
||||
'quota.loading': '读取中...',
|
||||
'quota.failed': '获取失败 (--%)',
|
||||
'quota.usedAndLeft': '{reset} · 已用 {used}% (余 {rem}%)',
|
||||
'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用',
|
||||
'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用',
|
||||
'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用',
|
||||
'quota.footTokensCustom': '本周累计: {tok} ({cost})',
|
||||
'quota.footTokensCycle': '周期累计: {tok} ({cost})',
|
||||
'quota.footCredits': 'AI 积分: {credits}',
|
||||
'quota.footCallsCustom': '本周调用: {calls} 次',
|
||||
'quota.footCallsCycle': '周期调用: {calls} 次',
|
||||
'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计',
|
||||
'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总',
|
||||
|
||||
// Live Activity Widget
|
||||
'live.currentSession': '当前会话',
|
||||
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
||||
'live.thinking': '推理中',
|
||||
'live.running': '运行中',
|
||||
'live.done': '已完成',
|
||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||
'live.subToggleRunning': '子代理 {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': '子代理 ({total}) {arrow}',
|
||||
'live.subCollapseTitle': '点击收起子代理列表',
|
||||
'live.subExpandTitle': '点击展开查看子代理缩略状态',
|
||||
|
||||
// Consumption View
|
||||
'cons.rangeToday': '今天',
|
||||
'cons.range24h': '1天',
|
||||
'cons.range7d': '7天',
|
||||
'cons.range14d': '14天',
|
||||
'cons.range30d': '30天',
|
||||
'cons.rangeAll': '全部',
|
||||
'cons.rangeCustom': '自定义',
|
||||
'cons.rangeAria': '消耗统计时间范围',
|
||||
'cons.applyFilter': '筛选',
|
||||
'cons.rangeTo': '至',
|
||||
'cons.overviewTitle': '用量总览',
|
||||
'cons.totalTokens': '总 Token',
|
||||
'cons.estCost': '预估费用',
|
||||
'cons.cacheHitRate': '缓存命中率',
|
||||
'cons.callsCount': '{calls} 次',
|
||||
'cons.cacheHitTokens': '命中 {tokens}',
|
||||
'cons.newInput': '新输入',
|
||||
'cons.uncachedInput': '未命中缓存输入',
|
||||
'cons.cacheRead': '缓存读取',
|
||||
'cons.savedCost': '节省 {cost}',
|
||||
'cons.outputUsage': '输出用量',
|
||||
'cons.replyAndThink': '回复 {resp} · 思考 {think}',
|
||||
'cons.trendTitle': '用量趋势',
|
||||
'cons.allTime': '全部时间',
|
||||
'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看',
|
||||
'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看',
|
||||
'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看',
|
||||
'cons.topModels': '模型排行',
|
||||
'cons.clientSources': '客户端来源',
|
||||
'cons.monthlyTitle': '月度统计',
|
||||
'cons.monthLabel': '{m}月',
|
||||
'cons.legInput': '输入',
|
||||
'cons.legCache': '缓存',
|
||||
'cons.legOutput': '输出',
|
||||
'cons.legThinking': '思考',
|
||||
'cons.footInput': '输入 ',
|
||||
'cons.footCache': '缓存 ',
|
||||
'cons.footOutput': '输出 ',
|
||||
'cons.footThinking': '思考 ',
|
||||
'cons.footCalls': '调用 ',
|
||||
|
||||
// Steps Detail View & Step Column Registry
|
||||
'steps.title': '调用记录',
|
||||
'steps.tabSteps': '按步查看 ({count})',
|
||||
'steps.tabStepsFiltered': '按步查看 ({filtered}/{total})',
|
||||
'steps.tabModels': '总汇总',
|
||||
'steps.allAgents': '全部汇总',
|
||||
'steps.allModels': '全部模型',
|
||||
'steps.selectModel': '选择模型',
|
||||
'steps.unitAgent': '代理',
|
||||
'steps.unitModel': '模型',
|
||||
'steps.lineTitle': '会话走势',
|
||||
'steps.fitTitle': '趋势拟合',
|
||||
'steps.modelsTitle': '模型总览',
|
||||
'steps.modelsEmpty': '当前范围暂无模型调用记录',
|
||||
'steps.metricTotalTokens': '总Token',
|
||||
'steps.metricContext': '上下文',
|
||||
'steps.metricTps': 'TPS',
|
||||
'steps.metricTtft': '首字',
|
||||
'steps.metricCache': '缓存',
|
||||
'steps.metricCost': '费用',
|
||||
'steps.badgeBackAll': '点击切回全部汇总',
|
||||
'steps.badgeFilterAgent': '点击仅过滤查看 {agent}(按住 Ctrl/Shift 可加减多选)',
|
||||
'steps.ctxTitle': '上下文 {ctx} · 思考 {think} · 正文 {resp}',
|
||||
'steps.ioCacheTitle': '新输入 {inPart} · 输出 {outPart} · 缓存读 {cachePart}',
|
||||
'steps.tokSeg.context.th': '上下文',
|
||||
'steps.tokSeg.context.tip': '上下文',
|
||||
'steps.tokSeg.in.th': '输入',
|
||||
'steps.tokSeg.in.tip': '新输入',
|
||||
'steps.tokSeg.out.th': '输出',
|
||||
'steps.tokSeg.out.tip': '输出',
|
||||
'steps.tokSeg.cache.th': '缓存',
|
||||
'steps.tokSeg.cache.tip': '缓存读',
|
||||
'steps.tokSeg.think.th': '思考',
|
||||
'steps.tokSeg.think.tip': '思考',
|
||||
'steps.tokSeg.reply.th': '正文',
|
||||
'steps.tokSeg.reply.tip': '正文',
|
||||
'steps.tokSeg.total.th': '总计',
|
||||
'steps.tokSeg.total.tip': '总计',
|
||||
'steps.modelCallsShare': '{calls}次 · {pct}%',
|
||||
'steps.modelCallsOnly': '{calls}次',
|
||||
'steps.modelsSummaryPrefix': '{count} 模型 · ',
|
||||
'steps.modelPerfFoot': '均速 {tps} · 首字 {ttft} · 缓存 {cache}%',
|
||||
'steps.modelSplitFoot': '入 {inTok} · 缓 {cacheTok} · 思 {thinkTok} · 正 {respTok}',
|
||||
'steps.fitActiveCardTitle': '{title}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)',
|
||||
'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)',
|
||||
'steps.turnMediaOnly': '[图片/附件提问]',
|
||||
'steps.turnMediaSuffix': '[附图]',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': '步序',
|
||||
'stepCol.step.opt': '调用步序 (#)',
|
||||
'stepCol.time.th': '时间',
|
||||
'stepCol.time.opt': '调用时间 (HH:mm:ss)',
|
||||
'stepCol.model.th': '模型',
|
||||
'stepCol.model.opt': '调用模型',
|
||||
'stepCol.tps.th': '速度',
|
||||
'stepCol.tps.opt': '输出速度 (TPS)',
|
||||
'stepCol.ttft.th': '首字',
|
||||
'stepCol.ttft.opt': '首字延迟 (TTFT)',
|
||||
'stepCol.duration.th': '耗时',
|
||||
'stepCol.duration.opt': '端到端耗时 (s)',
|
||||
'stepCol.tokens_combo.th': '上下文 / 思考 / 正文',
|
||||
'stepCol.tokens_combo.opt': '上下文 / 思考 / 正文 (组合)',
|
||||
'stepCol.tokens_io_cache.th': '输入 / 输出 / 缓存',
|
||||
'stepCol.tokens_io_cache.opt': '输入 / 输出 / 缓存 (组合)',
|
||||
'stepCol.tokens_custom.opt': '自定义组合 ({fmt})',
|
||||
'stepCol.input_tokens.th': '新输入',
|
||||
'stepCol.input_tokens.opt': '新输入 Token',
|
||||
'stepCol.cache_tokens.th': '缓存读',
|
||||
'stepCol.cache_tokens.opt': '缓存读取 Token',
|
||||
'stepCol.output_tokens.th': '总输出',
|
||||
'stepCol.output_tokens.opt': '总输出 Token',
|
||||
'stepCol.cache.th': '缓存',
|
||||
'stepCol.cache.opt': '缓存命中率 (%)',
|
||||
'stepCol.cost.th': '费用',
|
||||
'stepCol.cost.opt': '单步费用 ($)',
|
||||
|
||||
// Preferences (3-Tab Modular Settings)
|
||||
'settings.subTab.general': '常规',
|
||||
'settings.subTab.structure': '结构',
|
||||
'settings.subTab.account': '账号',
|
||||
'settings.subTab.other': '其他',
|
||||
'settings.subTab.aria': '偏好设置分类切换',
|
||||
'settings.account.current': '当前账号',
|
||||
'settings.account.signedOut': '未登录',
|
||||
'settings.account.unknown': '暂未获取账号状态',
|
||||
'settings.account.email': '账号邮箱',
|
||||
'settings.account.credential': 'OAuth 凭证',
|
||||
'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。',
|
||||
'settings.account.save': '导入凭证',
|
||||
'settings.account.capture': '保存当前凭证',
|
||||
'settings.account.reload': '刷新列表',
|
||||
'settings.account.switch': '切换',
|
||||
'settings.account.remove': '移除',
|
||||
'settings.account.active': '当前使用',
|
||||
'settings.account.written': '凭证已写入',
|
||||
'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。',
|
||||
'settings.account.savedCredentials': '已保存的凭证',
|
||||
'settings.account.empty': '暂无已保存的凭证。',
|
||||
'settings.account.loading': '正在读取已保存的凭证…',
|
||||
'settings.account.saved': '凭证已保存。',
|
||||
'settings.account.removed': '已移除保存的凭证。',
|
||||
'settings.account.switched': '已切换账号,正在刷新当前额度。',
|
||||
'settings.account.switching': '正在替换凭证并确认宿主账号…',
|
||||
'settings.account.verifying': '正在验证凭证所属账号…',
|
||||
'settings.account.loadQuota': '查额度',
|
||||
'settings.account.loadingQuota': '正在查询此凭证的额度…',
|
||||
'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。',
|
||||
'settings.account.quota': '额度池剩余',
|
||||
'settings.account.quota5h': '5 小时 {percent}%',
|
||||
'settings.account.quotaWeekly': '每周 {percent}%',
|
||||
'settings.account.noQuota': '暂未获取当前账号的额度池。',
|
||||
'settings.account.quotaStale': '额度刷新失败,显示的是当前账号上次获取的数据。',
|
||||
'settings.account.unsupported': '凭证切换目前支持 Windows 上的 Antigravity 共享登录。',
|
||||
'settings.account.invalidEmail': '请先选择一个已保存的账号。',
|
||||
'settings.account.invalidCredential': '请输入有效的 Antigravity 个人账号 OAuth 凭证。',
|
||||
'settings.account.credentialTooLarge': '凭证超过 Windows 凭据管理器的 2560 字节上限。',
|
||||
'settings.account.notFound': '该凭证已移除,请刷新列表。',
|
||||
'settings.account.noCurrentCredential': '暂时无法读取当前账号的共享凭证。',
|
||||
'settings.account.busy': '另一个窗口正在操作凭证,请稍后重试。',
|
||||
'settings.account.storeFailed': '凭证操作失败,请重试。',
|
||||
'settings.account.rollbackFailed': '凭证写入和回滚均失败。请在 Antigravity 中确认当前账号后再继续。',
|
||||
'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。',
|
||||
'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。',
|
||||
'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。',
|
||||
'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。',
|
||||
'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。',
|
||||
'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。',
|
||||
'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。',
|
||||
'settings.saving': '保存中…',
|
||||
'settings.saved': '已保存',
|
||||
'settings.saveFailed': '保存失败',
|
||||
'settings.resetDone': '已恢复默认',
|
||||
'settings.resetBtn': '恢复默认',
|
||||
|
||||
// Preferences -> General Tab
|
||||
'settings.gen.appearanceTitle': '界面与外观',
|
||||
'settings.gen.language': '界面语言',
|
||||
'settings.gen.langZh': '简体中文',
|
||||
'settings.gen.langEn': 'English',
|
||||
'settings.gen.langAuto': '跟随系统',
|
||||
'settings.gen.themeAccent': '主题色',
|
||||
'settings.gen.accentHost': '跟随宿主',
|
||||
'settings.gen.accentBlue': '经典蓝',
|
||||
'settings.gen.accentEmerald': '翡翠绿',
|
||||
'settings.gen.accentAmber': '琥珀橙',
|
||||
'settings.gen.accentViolet': '鸢尾紫',
|
||||
'settings.gen.accentCyan': '青碧色',
|
||||
'settings.gen.accentRose': '玫瑰红',
|
||||
'settings.gen.fontScale': '字体大小',
|
||||
'settings.gen.fontSm': '小',
|
||||
'settings.gen.fontMd': '标准',
|
||||
'settings.gen.fontLg': '大',
|
||||
'settings.gen.fontXl': '特大',
|
||||
'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高',
|
||||
'settings.gen.updateTitle': '版本更新',
|
||||
'settings.gen.updateMode': '更新方式',
|
||||
'settings.gen.updateManual': '仅提示新版本,手动更新',
|
||||
'settings.gen.updateAuto': '自动更新',
|
||||
'settings.gen.updateOff': '关闭更新',
|
||||
'settings.gen.pricingLabel': '价格表',
|
||||
'settings.gen.versionLabel': '当前版本',
|
||||
'settings.gen.modelCount': '{count} 个模型',
|
||||
'settings.gen.srcRemote': '云端同步',
|
||||
'settings.gen.srcLocal': '本地文件',
|
||||
'settings.gen.srcDefault': '内置默认',
|
||||
'settings.gen.syncAt': '更新于 {time}',
|
||||
'settings.gen.pubAt': '发布于 {date}',
|
||||
'settings.gen.defaultPricing': '默认价格',
|
||||
'settings.gen.syncBtn': '更新价格表',
|
||||
'settings.gen.syncingBtn': '更新中…',
|
||||
'settings.gen.syncingMsg': '正在同步价格表…',
|
||||
'settings.gen.syncedMsg': '价格表已更新 ({count} 个模型)',
|
||||
'settings.gen.syncFallbackMsg': '连接超时,使用本地价格表',
|
||||
'settings.gen.checkUpdateBtn': '检查更新',
|
||||
'settings.gen.checkingBtn': '检查中…',
|
||||
'settings.gen.checkingMsg': '正在检查新版本…',
|
||||
'settings.gen.checkFailedMsg': '检查失败:{err}',
|
||||
'settings.gen.upToDateMsg': '当前已是最新版本 (v{ver})',
|
||||
'settings.gen.downloadingMsg': '正在下载更新…',
|
||||
'settings.gen.updatedRestartMsg': '更新完成,正在重启面板…',
|
||||
'settings.gen.updateSkippedMsg': '未执行更新',
|
||||
'settings.gen.updateFailedMsg': '更新失败',
|
||||
'settings.gen.canUpgradeSub': '可升级至 v{ver} ({mode})',
|
||||
'settings.gen.upgradeToBtn': '升级至 v{ver}',
|
||||
'settings.gen.manualUpgradeBtn': '手动升级 v{ver}',
|
||||
'settings.gen.updateOffSub': '已关闭更新提醒 ({mode})',
|
||||
'settings.gen.latestSub': '已是最新 ({mode})',
|
||||
|
||||
// Preferences -> Structure Tab
|
||||
'settings.str.thirdTabAria': '结构子菜单切换',
|
||||
'settings.str.tabMount': '挂载胶囊',
|
||||
'settings.str.tabHover': '鼠标悬浮窗',
|
||||
'settings.str.tabOverview': '实时监控布局',
|
||||
'settings.str.tabSteps': '调用明细字段',
|
||||
'settings.str.previewMountSidebarHint': '当前为仅侧边栏模式,主窗口不挂载胶囊;切回顶部栏或输入框挂载后将按上方样式呈现',
|
||||
'settings.str.mountSection': '挂载胶囊',
|
||||
'settings.str.mountBadge': '{count}/5 项',
|
||||
'settings.str.mountMode': '面板挂载方式',
|
||||
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
|
||||
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
|
||||
'settings.str.mountSidebar': '仅侧边栏',
|
||||
'settings.str.popoverWidthLabel': '悬浮面板宽度',
|
||||
'settings.str.popoverWidthAuto': '自适应',
|
||||
'settings.str.popoverWidthCustom': '指定宽度',
|
||||
'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px',
|
||||
'settings.str.multiToggle': '实时运行会话入口',
|
||||
'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊',
|
||||
'settings.str.show': '显示',
|
||||
'settings.str.hide': '隐藏',
|
||||
'settings.str.on': '开启',
|
||||
'settings.str.off': '关闭',
|
||||
'settings.str.capsuleSlotsLabel': '胶囊数值与顺序 (左 → 右,1~5 项,可拖拽)',
|
||||
'settings.str.addCapsuleSlot': '添加槽位 ({count}/{max})',
|
||||
'settings.str.hoverSection': '鼠标悬浮窗',
|
||||
'settings.str.hoverBadgeOff': '已关闭',
|
||||
'settings.str.hoverBadgeCount': '{count} 模块',
|
||||
'settings.str.hoverModulesLabel': '悬浮窗展示模块 (上 → 下,0~4 项,可拖拽)',
|
||||
'settings.str.hoverEmptyHint': '已关闭悬浮速览窗(点击胶囊仍可展开完整面板)',
|
||||
'settings.str.addHoverModule': '添加模块 ({count}/{max})',
|
||||
'settings.str.overviewSection': '实时监控布局',
|
||||
'settings.str.overviewBadge': '{modCount} 模块 · {metCount} 指标',
|
||||
'settings.str.overviewModulesLabel': '监控模块与顺序 (上 → 下,至少 1 项,可拖拽)',
|
||||
'settings.str.addOverviewModule': '添加模块 ({count}/{max})',
|
||||
'settings.str.overviewMetricsLabel': '第一行实时指标 (左 → 右,1~4 项,可拖拽)',
|
||||
'settings.str.overviewMetricsInactiveHint': '当前已移出「实时指标」模块,此配置将在悬浮窗启用或重新添加模块时生效',
|
||||
'settings.str.addOverviewMetric': '添加指标 ({count}/{max})',
|
||||
'settings.str.stepsSection': '调用明细字段',
|
||||
'settings.str.stepsBadge': '{count} 列',
|
||||
'settings.str.stepTurnRailToggle': '对话轮次导轨',
|
||||
'settings.str.stepAgentBadgeToggle': '主/子代理标识',
|
||||
'settings.str.stepSpeedColorToggle': '输出速度多色分级',
|
||||
'settings.str.stepTokenComboLabel': '自定义 Token 组合格式',
|
||||
'settings.str.stepTokenComboPlaceholder': '例如 context:new:cache 或 in:out:cache',
|
||||
'settings.str.stepTokenComboHint': '可用字段:context(上下文)、in/new(新输入)、out(输出)、cache(缓存)、think(思考)、reply(正文)、total(总计),以 : 或 / 分隔(1~4 项)',
|
||||
'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列,可拖拽)',
|
||||
'settings.str.addStepCol': '添加字段 ({count}/{max})',
|
||||
'settings.slot.dragHint': '按住上下拖动调整顺序',
|
||||
'settings.slot.moveUp': '前移',
|
||||
'settings.slot.moveDown': '后移',
|
||||
'settings.slot.remove': '移除此项',
|
||||
'settings.slot.minReached': '至少保留 {min} 项',
|
||||
'settings.slot.alreadyAdded': '已添加',
|
||||
'settings.mock.sessionTitle': '重构鉴权中间件与会话缓存',
|
||||
'settings.mock.subRole': '接口审计',
|
||||
'settings.mock.turnPromptLatest': '排查并发刷新令牌时的竞态问题,补齐单元测试',
|
||||
'settings.mock.turnPromptPrev': '梳理路由守卫与过期会话清理逻辑',
|
||||
|
||||
// Preferences -> Other Tab
|
||||
'settings.oth.modelTitle': '模型标识显示',
|
||||
'settings.oth.modelFormat': '模型名称格式',
|
||||
'settings.oth.modelShort': '精简代号 (如 argon-4-high)',
|
||||
'settings.oth.modelUpstream': '原始模型 ID (如 gemini-3.8-flash-n)',
|
||||
'settings.oth.modelUpstreamCompact': '去前缀原始 ID (如 3.8-flash-n / sonnet-4-6 / 5.4-mini)',
|
||||
'settings.oth.orchFormat': 'Orchestrator 系列 ID',
|
||||
'settings.oth.orchCompact': '精简代号 (如 orchestrator-argon)',
|
||||
'settings.oth.orchFull': '原始完整 ID (如 gemini-pro-orchestrator)',
|
||||
'settings.oth.baselineTitle': '模型上下文设置',
|
||||
'settings.oth.ctxRiskTitle': '非官方能力风险提示',
|
||||
'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!',
|
||||
'settings.oth.ctxRiskAcceptBtn': '我已知晓风险,继续使用',
|
||||
'settings.oth.ctxModel': '模型',
|
||||
'settings.oth.ctxBaselineLabel': '上下文窗口上限',
|
||||
'settings.oth.ctxChooseModel': '选择模型',
|
||||
'settings.oth.ctxDefault': '跟随宿主设置',
|
||||
'settings.oth.ctxExpensive': '{name}(消耗更多配额)',
|
||||
'settings.oth.ctxTokens': '{count} token',
|
||||
'settings.oth.ctxUnavailable': '{name}(当前不可用)',
|
||||
'settings.oth.ctxConfigured': '{name} · 已设置',
|
||||
'settings.oth.ctxConfiguredReported': '{name} · 已设置 / 最近 {reported}',
|
||||
'settings.oth.ctxDefaultReported': '默认 · 最近 {name}',
|
||||
'settings.oth.ctxReported': '最近一次请求由宿主报告为 {name}。',
|
||||
'settings.oth.ctxMixed': '各推理档设置不同',
|
||||
'settings.oth.ctxMixedHint': '该模型的推理档保留了不同的旧设置。选择一个上限即可统一。',
|
||||
'settings.oth.ctxBaselineHint': '同一模型的推理档共享上限。插件会在启动后重新应用已保存的设置,用于之后发送的消息。',
|
||||
'settings.oth.ctxNoModels': '宿主暂未返回可用模型。',
|
||||
'settings.oth.ctxNoOptions': '宿主未提供此模型的上下文档位或容量,当前只能跟随宿主设置。',
|
||||
'settings.oth.maintTitle': '缓存与重置',
|
||||
'settings.oth.cacheLabel': '本地轨迹缓存',
|
||||
'settings.oth.cacheDesc': '清空内存与磁盘步骤解析缓存并立即重扫全部会话',
|
||||
'settings.oth.rebuildBtn': '重建本地轨迹缓存',
|
||||
'settings.oth.rebuildingBtn': '重建中…',
|
||||
'settings.oth.rebuildDone': '本地轨迹缓存已重建',
|
||||
'settings.oth.rebuildFailed': '缓存重建失败',
|
||||
'settings.oth.resetLabel': '恢复出厂偏好',
|
||||
'settings.oth.resetDesc': '将常规、结构与其他分页中的所有偏好设置还原为初始默认状态',
|
||||
'settings.oth.resetAllBtn': '恢复全部默认设置',
|
||||
'settings.oth.resetConfirmBtn': '再次点击确认重置',
|
||||
'settings.oth.resettingBtn': '重置中…',
|
||||
'settings.oth.resetAllDone': '已恢复全部默认设置',
|
||||
});
|
||||
@@ -89,4 +89,12 @@ export const SVG_ICON_DEFS = Object.freeze({
|
||||
close: [
|
||||
{ tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } },
|
||||
],
|
||||
grip: [
|
||||
{ tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
{ tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
{ tag: 'circle', attrs: { cx: '6', cy: '8', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
{ tag: 'circle', attrs: { cx: '10', cy: '8', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
{ tag: 'circle', attrs: { cx: '6', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
{ tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -6,17 +6,33 @@
|
||||
|
||||
import { App } from './App.js';
|
||||
import { mountWindowOverlay } from './components/layout/WindowOverlayShell.js';
|
||||
import { applyAppearanceToRoot } from './core/appearance.js';
|
||||
import { isWindowOverlayMode } from './core/httpClient.js';
|
||||
import { startAsyncTelemetryLoop } from './store/telemetryStore.js';
|
||||
import { setI18nLanguage } from './i18n/index.js';
|
||||
import { startAsyncTelemetryLoop, telemetryStore } from './store/telemetryStore.js';
|
||||
|
||||
async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
||||
if (!mountTarget) return null;
|
||||
const appInstance = App();
|
||||
mountTarget.appendChild(appInstance.el);
|
||||
|
||||
const unsubAppearance = telemetryStore.subscribe(
|
||||
(st) => st.telemetry?.settings,
|
||||
(settings) => {
|
||||
setI18nLanguage(settings?.language);
|
||||
if (typeof document !== 'undefined' && document.documentElement) {
|
||||
applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const stopPolling = startAsyncTelemetryLoop(2000);
|
||||
return {
|
||||
appInstance,
|
||||
stopPolling,
|
||||
stopPolling: () => {
|
||||
unsubAppearance();
|
||||
stopPolling();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -25,6 +41,14 @@ function startEntry() {
|
||||
mountWindowOverlay();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof window !== 'undefined' &&
|
||||
!window.sidecar?.fetch &&
|
||||
typeof document !== 'undefined' &&
|
||||
document.documentElement
|
||||
) {
|
||||
document.documentElement.setAttribute('data-standalone', 'true');
|
||||
}
|
||||
bootstrapApp();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,672 @@
|
||||
/**
|
||||
* @fileoverview Decoupled Metric Registry (`metricRegistry.js`).
|
||||
* Centralizes presentation & option metadata for:
|
||||
* 1. Topbar / Composer Capsule Slots (1..5 items out of 13 metrics)
|
||||
* 2. Live Overview / Hover First-Row Metric Matrix (1..4 items out of 9 metrics)
|
||||
*/
|
||||
|
||||
import {
|
||||
formatCachePct,
|
||||
formatMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
getCacheToneClass,
|
||||
getSpeedToneClass,
|
||||
getStepCostToneClass,
|
||||
getTtftToneClass,
|
||||
resolveModelDisplayInfo,
|
||||
sampleSummary,
|
||||
speedReasonText,
|
||||
} from '../core/formatters.js';
|
||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||
|
||||
export const CAPSULE_METRIC_KEYS = Object.freeze([
|
||||
'context',
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'cost',
|
||||
'session_cost',
|
||||
'cache_hit',
|
||||
'session_tokens',
|
||||
'quota_auto',
|
||||
'gemini_5h',
|
||||
'gemini_weekly',
|
||||
'claude_5h',
|
||||
'claude_weekly',
|
||||
]);
|
||||
|
||||
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'step_cost',
|
||||
'session_cost',
|
||||
'cache_hit',
|
||||
'session_tokens',
|
||||
'context_usage',
|
||||
'quota_tightest',
|
||||
]);
|
||||
|
||||
const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
||||
|
||||
export function getCapsuleMetricOptions() {
|
||||
return CAPSULE_METRIC_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: t(`capMetric.${key}`),
|
||||
}));
|
||||
}
|
||||
|
||||
export function getOverviewMetricOptions() {
|
||||
return OVERVIEW_METRIC_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: t(`ovMetric.${key}`),
|
||||
}));
|
||||
}
|
||||
|
||||
export function resolveQuotaCapsuleSummary(quotas) {
|
||||
if (!quotas) return null;
|
||||
const activePool = quotas.activePool;
|
||||
const weekly = quotas.weekly;
|
||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
||||
const candidates = [];
|
||||
const defaultPoolName = isEnglishLocale() ? 'Active Pool' : '当前池';
|
||||
const wkTag = isEnglishLocale() ? 'Wk' : '周';
|
||||
|
||||
if (activePool && Number.isFinite(Number(activePool.remainingPct))) {
|
||||
candidates.push({
|
||||
pct: Number(activePool.remainingPct),
|
||||
label: activePool.poolLabel || activePool.family || defaultPoolName,
|
||||
windowTag: '5h',
|
||||
});
|
||||
}
|
||||
if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) {
|
||||
candidates.push({
|
||||
pct: Number(activePool.weeklyRemainingPct),
|
||||
label: activePool.poolLabel || activePool.family || defaultPoolName,
|
||||
windowTag: wkTag,
|
||||
});
|
||||
}
|
||||
if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) {
|
||||
candidates.push({
|
||||
pct: Number(weekly.remainingPct),
|
||||
label: weekly.poolFamily || (isEnglishLocale() ? 'Weekly' : '周限额'),
|
||||
windowTag: wkTag,
|
||||
});
|
||||
}
|
||||
if (!candidates.length && pools.length > 0) {
|
||||
for (const p of pools) {
|
||||
const pLabel = p?.poolLabel || p?.family || defaultPoolName;
|
||||
if (p && Number.isFinite(Number(p.remainingPct))) {
|
||||
candidates.push({ pct: Number(p.remainingPct), label: pLabel, windowTag: '5h' });
|
||||
}
|
||||
if (p && Number.isFinite(Number(p.weeklyRemainingPct))) {
|
||||
candidates.push({ pct: Number(p.weeklyRemainingPct), label: pLabel, windowTag: wkTag });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!candidates.length) return null;
|
||||
candidates.sort((a, b) => a.pct - b.pct);
|
||||
const tightest = candidates[0];
|
||||
const runnerUp = candidates.length > 1 ? candidates[1] : null;
|
||||
const rounded = Math.max(0, Math.min(100, Math.round(tightest.pct)));
|
||||
const runnerPct = runnerUp ? Math.max(0, Math.min(100, Math.round(runnerUp.pct))) : null;
|
||||
const subLabelText = runnerUp
|
||||
? runnerUp.label === tightest.label
|
||||
? `${tightest.label} ${tightest.windowTag} · ${runnerUp.windowTag} ${runnerPct}%`
|
||||
: `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%`
|
||||
: `${tightest.label} · ${tightest.windowTag}`;
|
||||
return {
|
||||
roundedPct: rounded,
|
||||
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
||||
subLabelText,
|
||||
detailText: candidates
|
||||
.map((c) => {
|
||||
const cPct = Math.max(0, Math.min(100, Math.round(c.pct)));
|
||||
return `${c.label} ${c.windowTag} ${t('capsule.quotaLeft', { pct: cPct })}`;
|
||||
})
|
||||
.join(' · '),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。
|
||||
*
|
||||
* @param {object|null|undefined} quotas
|
||||
* @param {'gemini_5h'|'gemini_weekly'|'claude_5h'|'claude_weekly'} slotKey
|
||||
* @returns {{ roundedPct: number, shortText: string } | null}
|
||||
*/
|
||||
export function resolveSpecificQuotaSlotSummary(quotas, slotKey) {
|
||||
if (!quotas) return null;
|
||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
||||
const activePool = quotas.activePool || null;
|
||||
const isClaude = slotKey.startsWith('claude_');
|
||||
const isWeekly = slotKey.endsWith('_weekly');
|
||||
let rawPct = null;
|
||||
|
||||
if (isClaude) {
|
||||
const claudePool =
|
||||
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
|
||||
pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || '')));
|
||||
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
||||
if (cand != null && Number.isFinite(Number(cand))) {
|
||||
rawPct = Number(cand);
|
||||
} else if (
|
||||
activePool &&
|
||||
THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) {
|
||||
rawPct = Number(fb);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const stdGemini =
|
||||
pools.find((p) => p?.poolKey === 'Gemini') ||
|
||||
pools.find(
|
||||
(p) =>
|
||||
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
|
||||
!/carbon|argon/i.test(String(p?.poolKey || ''))
|
||||
);
|
||||
const geminiFamilyPools = pools.filter((p) =>
|
||||
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
|
||||
);
|
||||
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
|
||||
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
|
||||
rawPct = Number(primaryCand);
|
||||
} else {
|
||||
const familyVals = geminiFamilyPools
|
||||
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
|
||||
.filter((v) => v != null && Number.isFinite(Number(v)))
|
||||
.map(Number);
|
||||
if (familyVals.length > 0) {
|
||||
rawPct = Math.min(...familyVals);
|
||||
} else if (
|
||||
activePool &&
|
||||
!THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) {
|
||||
rawPct = Number(fb);
|
||||
}
|
||||
}
|
||||
if (
|
||||
rawPct == null &&
|
||||
isWeekly &&
|
||||
quotas.weekly &&
|
||||
!THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) &&
|
||||
quotas.weekly.remainingPct != null &&
|
||||
Number.isFinite(Number(quotas.weekly.remainingPct))
|
||||
) {
|
||||
rawPct = Number(quotas.weekly.remainingPct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
||||
const rounded = Math.max(0, Math.min(100, Math.round(rawPct)));
|
||||
return {
|
||||
roundedPct: rounded,
|
||||
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatCompactCapsuleCost(costUsd) {
|
||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
||||
const val = Math.max(0, Number(costUsd));
|
||||
if (val === 0) return '$0.00';
|
||||
if (val < 0.001) return '<$0.001';
|
||||
if (val < 1) return `$${val.toFixed(3)}`;
|
||||
if (val < 100) return `$${val.toFixed(2)}`;
|
||||
return `$${Math.round(val)}`;
|
||||
}
|
||||
|
||||
export function formatCompactCapsuleTtft(ttftSec) {
|
||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
|
||||
const val = Number(ttftSec);
|
||||
if (val < 1) return `${val.toFixed(2)}s`;
|
||||
if (val < 100) return `${val.toFixed(1)}s`;
|
||||
return `${Math.round(val)}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析顶栏/输入框精简胶囊单槽位展示结构。
|
||||
*
|
||||
* @param {string} metricKey
|
||||
* @param {object} slotCtx
|
||||
* @param {number} ringCircumference
|
||||
*/
|
||||
export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) {
|
||||
if (!metricKey || metricKey === 'none') {
|
||||
return {
|
||||
hidden: true,
|
||||
metric: 'none',
|
||||
segClass: 'wm-cap-slot',
|
||||
textClass: 'wm-slot-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: '',
|
||||
toneClass: '',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'context') {
|
||||
if (!slotCtx.hasTelemetry) {
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'context',
|
||||
segClass: 'wm-cap-slot wm-ctx-seg',
|
||||
textClass: 'wm-slot-text wm-ctx-pct',
|
||||
showRing: true,
|
||||
dashOffset: ringCircumference,
|
||||
text: '--%',
|
||||
toneClass: '',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
const isDanger = slotCtx.usedPct >= 88;
|
||||
const isWarn = !isDanger && slotCtx.usedPct >= 70;
|
||||
const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : '';
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'context',
|
||||
segClass: 'wm-cap-slot wm-ctx-seg',
|
||||
textClass: 'wm-slot-text wm-ctx-pct',
|
||||
showRing: true,
|
||||
dashOffset: slotCtx.dashOffset,
|
||||
text: `${Math.round(slotCtx.usedPct)}%`,
|
||||
toneClass,
|
||||
running: false,
|
||||
warn: isWarn,
|
||||
danger: isDanger,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'tps') {
|
||||
if (!slotCtx.hasTelemetry) {
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'tps',
|
||||
segClass: 'wm-cap-slot wm-seg-speed',
|
||||
textClass: 'wm-slot-text wm-speed-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: '-- t/s',
|
||||
toneClass: '',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0;
|
||||
const toneClass = hasValidTps ? getSpeedToneClass(slotCtx.tps) : '';
|
||||
const tpsText = hasValidTps
|
||||
? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s`
|
||||
: slotCtx.isRunning
|
||||
? t('capsule.tpsRunning')
|
||||
: t('capsule.tpsIdle');
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'tps',
|
||||
segClass: 'wm-cap-slot wm-seg-speed',
|
||||
textClass: 'wm-slot-text wm-speed-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: tpsText,
|
||||
toneClass,
|
||||
running: Boolean(slotCtx.isRunning),
|
||||
warn: toneClass === 'tone-warn',
|
||||
danger: toneClass === 'tone-danger',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'avg_tps') {
|
||||
const avgVal = slotCtx.hasTelemetry ? slotCtx.avgTps : null;
|
||||
const valid = Number.isFinite(avgVal) && avgVal > 0;
|
||||
const toneClass = valid ? getSpeedToneClass(avgVal) : '';
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'avg_tps',
|
||||
segClass: 'wm-cap-slot wm-seg-speed',
|
||||
textClass: 'wm-slot-text wm-speed-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? `${avgVal >= 100 ? Math.round(avgVal) : avgVal.toFixed(1)} t/s` : '-- t/s',
|
||||
toneClass,
|
||||
running: false,
|
||||
warn: toneClass === 'tone-warn',
|
||||
danger: toneClass === 'tone-danger',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'ttft') {
|
||||
const val = slotCtx.hasTelemetry ? slotCtx.ttft : null;
|
||||
const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0;
|
||||
const numVal = valid ? Number(val) : 0;
|
||||
const toneClass = valid ? getTtftToneClass(numVal) : '';
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'ttft',
|
||||
segClass: 'wm-cap-slot wm-seg-ttft',
|
||||
textClass: 'wm-slot-text wm-ttft-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? formatCompactCapsuleTtft(numVal) : '--s',
|
||||
toneClass,
|
||||
running: false,
|
||||
warn: toneClass === 'tone-warn',
|
||||
danger: toneClass === 'tone-danger',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'cost' || metricKey === 'session_cost') {
|
||||
const costVal = !slotCtx.hasTelemetry
|
||||
? null
|
||||
: metricKey === 'session_cost'
|
||||
? slotCtx.sessionCost
|
||||
: slotCtx.stepCost;
|
||||
const toneClass =
|
||||
metricKey === 'cost' && slotCtx.hasTelemetry && costVal != null
|
||||
? getStepCostToneClass(costVal)
|
||||
: '';
|
||||
return {
|
||||
hidden: false,
|
||||
metric: metricKey,
|
||||
segClass: 'wm-cap-slot wm-seg-cost',
|
||||
textClass: 'wm-slot-text wm-cost-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--',
|
||||
toneClass,
|
||||
running: false,
|
||||
warn: toneClass === 'tone-warn',
|
||||
danger: toneClass === 'tone-danger',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'cache_hit') {
|
||||
const cachePct = slotCtx.hasTelemetry ? slotCtx.cacheHitPct : null;
|
||||
const valid = cachePct != null && Number.isFinite(Number(cachePct));
|
||||
const numVal = valid ? Number(cachePct) : 0;
|
||||
const toneClass = valid ? getCacheToneClass(numVal, slotCtx.latestPromptTokens) : '';
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'cache_hit',
|
||||
segClass: 'wm-cap-slot wm-seg-cache',
|
||||
textClass: 'wm-slot-text wm-cache-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? `${Math.round(numVal)}%` : '--%',
|
||||
toneClass,
|
||||
running: false,
|
||||
warn: toneClass === 'tone-warn',
|
||||
danger: toneClass === 'tone-danger',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'session_tokens') {
|
||||
const tokVal = slotCtx.hasTelemetry ? slotCtx.sessionTokens : null;
|
||||
const valid = tokVal != null && Number.isFinite(Number(tokVal)) && Number(tokVal) >= 0;
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'session_tokens',
|
||||
segClass: 'wm-cap-slot wm-seg-tokens',
|
||||
textClass: 'wm-slot-text wm-tokens-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? formatTokens(Number(tokVal)) : '--',
|
||||
toneClass: '',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
const quotaSum = !slotCtx.hasTelemetry
|
||||
? null
|
||||
: metricKey === 'quota_auto'
|
||||
? resolveQuotaCapsuleSummary(slotCtx.quotas)
|
||||
: resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey);
|
||||
const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15);
|
||||
const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30);
|
||||
const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : '';
|
||||
return {
|
||||
hidden: false,
|
||||
metric: metricKey,
|
||||
segClass: 'wm-cap-slot wm-seg-quota',
|
||||
textClass: 'wm-slot-text wm-quota-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: quotaSum ? quotaSum.shortText : t('capsule.quotaUnknown'),
|
||||
toneClass,
|
||||
running: false,
|
||||
warn: isWarn,
|
||||
danger: isDanger,
|
||||
};
|
||||
}
|
||||
|
||||
function translateRawAgentBadge(rawBadge) {
|
||||
if (!rawBadge) return '';
|
||||
if (!isEnglishLocale()) return String(rawBadge);
|
||||
const str = String(rawBadge).trim();
|
||||
if (str === '主') return t('fmt.mainBadge');
|
||||
const m = str.match(/^子(\d+)$/);
|
||||
if (m) return t('fmt.subBadge', { index: m[1] });
|
||||
if (str === '子') return t('fmt.subBadgeShort');
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析实时监控第一行矩阵单个单元格的展示数据。
|
||||
*
|
||||
* @param {string} metricKey
|
||||
* @param {{ active?: object, ctx?: object, quotas?: object, settings?: object, hasSubagents?: boolean }} cellCtx
|
||||
*/
|
||||
export function resolveOverviewMetricCell(metricKey, cellCtx = {}) {
|
||||
const active = cellCtx.active || {};
|
||||
const ctx = cellCtx.ctx || active.context || {};
|
||||
const quotas = cellCtx.quotas || {};
|
||||
const settings = cellCtx.settings || {};
|
||||
const hasSubagents = Boolean(cellCtx.hasSubagents);
|
||||
const hasAnySteps = Number(active.stepCount || 0) > 0;
|
||||
|
||||
if (metricKey === 'tps') {
|
||||
const activeModelDisplay = resolveModelDisplayInfo(active, settings, {
|
||||
fallback: t('fmt.unknownModel'),
|
||||
}).text;
|
||||
const reason = speedReasonText(active.latestSpeedReason);
|
||||
const badgeStr = translateRawAgentBadge(active.activeAgentBadge);
|
||||
const modelAndAgent =
|
||||
hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay;
|
||||
const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0;
|
||||
const speedTone = hasAnySteps && hasSpeed ? getSpeedToneClass(active.latestTokPerSec) : '';
|
||||
return {
|
||||
key: 'tps',
|
||||
label: t('ovMetric.tps'),
|
||||
icon: 'dot',
|
||||
iconSize: 10,
|
||||
isPulsing: Boolean(active.isRunning),
|
||||
valueText: formatMetric(active.latestTokPerSec, ' tok/s'),
|
||||
valueClass: speedTone ? `cell-value ${speedTone}` : 'cell-value',
|
||||
subText: reason
|
||||
? !hasSpeed
|
||||
? `${reason} · ${modelAndAgent}`
|
||||
: `${modelAndAgent} · ${reason}`
|
||||
: modelAndAgent,
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'ttft') {
|
||||
const ttftTone = hasAnySteps ? getTtftToneClass(active.latestTtftSec) : '';
|
||||
return {
|
||||
key: 'ttft',
|
||||
label: t('ovMetric.ttft'),
|
||||
icon: 'clock',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: formatMetric(active.latestTtftSec, 's'),
|
||||
valueClass: ttftTone ? `cell-value ${ttftTone}` : 'cell-value',
|
||||
subText: t('ovMetric.subAvgTtft', {
|
||||
val: formatMetric(active.ttftSummary?.avgSec, 's'),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'avg_tps') {
|
||||
const hasAvgSpeed = Number.isFinite(active.avgTokPerSec) && Number(active.avgTokPerSec) > 0;
|
||||
const avgSpeedTone = hasAnySteps && hasAvgSpeed ? getSpeedToneClass(active.avgTokPerSec) : '';
|
||||
return {
|
||||
key: 'avg_tps',
|
||||
label: t('ovMetric.avg_tps'),
|
||||
icon: 'pulse',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: formatMetric(active.avgTokPerSec, ' tok/s'),
|
||||
valueClass: avgSpeedTone ? `cell-value ${avgSpeedTone}` : 'cell-value',
|
||||
subText: t('ovMetric.subValidSamples', {
|
||||
samples: sampleSummary(active.speedSummary),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'step_cost' || metricKey === 'session_cost') {
|
||||
const stepCost = active.latestStepCostUsd;
|
||||
const sessCost = Number(active.sessionCostUsd || 0);
|
||||
const stepCnt = Number(active.stepCount || 0);
|
||||
const isAllUnpriced =
|
||||
stepCnt > 0 && Number(active.sessionUnpricedCalls || 0) >= stepCnt && !(sessCost > 0);
|
||||
const stepCostText =
|
||||
!hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true });
|
||||
const totalCostText =
|
||||
!hasAnySteps && active.sessionCostUsd == null
|
||||
? '—'
|
||||
: formatUsd(isAllUnpriced ? null : sessCost, {
|
||||
precise: sessCost > 0 && sessCost < 0.1,
|
||||
});
|
||||
|
||||
if (metricKey === 'step_cost') {
|
||||
const costTone = hasAnySteps ? getStepCostToneClass(stepCost) : '';
|
||||
return {
|
||||
key: 'step_cost',
|
||||
label: t('ovMetric.step_cost'),
|
||||
icon: 'bolt',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: stepCostText,
|
||||
valueClass: costTone ? `cell-value ${costTone}` : 'cell-value',
|
||||
subText: t('ovMetric.subTotalCost', { cost: totalCostText }),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
key: 'session_cost',
|
||||
label: t('ovMetric.session_cost'),
|
||||
icon: 'bolt',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: totalCostText,
|
||||
valueClass: 'cell-value',
|
||||
subText: t('ovMetric.subStepCost', { cost: stepCostText }),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'cache_hit') {
|
||||
const latestCache = active.latestCacheHitPct;
|
||||
const avgCache = active.sessionCacheHitPct ?? active.latestCacheHitPct;
|
||||
const hasLatest = hasAnySteps && latestCache != null && Number.isFinite(Number(latestCache));
|
||||
const hasAvg = hasAnySteps && avgCache != null && Number.isFinite(Number(avgCache));
|
||||
const cacheTone = hasLatest ? getCacheToneClass(latestCache, active.latestPromptTokens) : '';
|
||||
return {
|
||||
key: 'cache_hit',
|
||||
label: t('ovMetric.cache_hit'),
|
||||
icon: 'layers',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: hasLatest ? formatCachePct(latestCache) : '—',
|
||||
valueClass: cacheTone ? `cell-value ${cacheTone}` : 'cell-value',
|
||||
subText: t('ovMetric.subAvgCache', {
|
||||
val: hasAvg ? formatCachePct(avgCache) : '—',
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'session_tokens') {
|
||||
const inTok = Math.max(0, Number(active.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(active.cacheReadTokens || 0));
|
||||
const outTok = Math.max(0, Number(active.outputTokens || 0));
|
||||
const totalTok = Math.max(0, Number(active.totalTokens ?? inTok + cacheTok + outTok));
|
||||
return {
|
||||
key: 'session_tokens',
|
||||
label: t('ovMetric.session_tokens'),
|
||||
icon: 'chart-bar',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: !hasAnySteps && !totalTok ? '—' : formatTokens(totalTok),
|
||||
valueClass: 'cell-value',
|
||||
subText: t('ovMetric.subInOutTokens', {
|
||||
inTok: formatTokens(inTok + cacheTok),
|
||||
outTok: formatTokens(outTok),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'context_usage') {
|
||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTokens = Number(ctx.totalTokens || 0);
|
||||
const usedPct =
|
||||
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||
const toneCls =
|
||||
usedPct >= 88
|
||||
? 'cell-value tone-danger'
|
||||
: usedPct >= 70
|
||||
? 'cell-value tone-warn'
|
||||
: 'cell-value';
|
||||
return {
|
||||
key: 'context_usage',
|
||||
label: t('ovMetric.context_usage'),
|
||||
icon: 'layers',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: `${usedPct}%`,
|
||||
valueClass: toneCls,
|
||||
subText: t('ovMetric.subCtxRatio', {
|
||||
used: formatTokens(totalTokens),
|
||||
limit: formatTokens(limitTokens),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
const quotaSum = resolveQuotaCapsuleSummary(quotas);
|
||||
const quotaToneCls =
|
||||
quotaSum && quotaSum.roundedPct <= 15
|
||||
? 'cell-value tone-danger'
|
||||
: quotaSum && quotaSum.roundedPct <= 30
|
||||
? 'cell-value tone-warn'
|
||||
: 'cell-value';
|
||||
return {
|
||||
key: 'quota_tightest',
|
||||
label: t('ovMetric.quota_tightest'),
|
||||
icon: 'pulse',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: quotaSum ? quotaSum.shortText : '—',
|
||||
valueClass: quotaToneCls,
|
||||
subText: quotaSum
|
||||
? t('ovMetric.subQuotaPool', { label: quotaSum.subLabelText })
|
||||
: t('ovMetric.subQuotaPending'),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
/**
|
||||
* @fileoverview Decoupled Step Table Column Registry (`stepColumnRegistry.js`).
|
||||
* Defines all 12 customizable columns for `StepsDetailView` ("按步查看"),
|
||||
* preserving 100% of the 7 out-of-the-box default columns, clickable agent filter badges,
|
||||
* speed reason sub-lines, token combo tooltips, and high-cost highlights.
|
||||
*/
|
||||
|
||||
import { h, patchAttr, patchText } from '../core/domPatch.js';
|
||||
import {
|
||||
formatCachePct,
|
||||
formatMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
getCacheToneClass,
|
||||
getSpeedToneClass,
|
||||
getStepCostToneClass,
|
||||
getTtftToneClass,
|
||||
resolveModelDisplayInfo,
|
||||
speedReasonText,
|
||||
} from '../core/formatters.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT,
|
||||
normalizeClientStepTokenComboFormat,
|
||||
parseClientStepTokenComboSegments,
|
||||
} from '../store/telemetryStore.js';
|
||||
|
||||
export const STEP_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
'time',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'tokens_io_cache',
|
||||
'tokens_custom',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'tokens_combo',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
function resolveStepTokenParts(st) {
|
||||
const inTok = Math.max(0, Number(st?.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(st?.cacheReadTokens || 0));
|
||||
const outTok = Math.max(0, Number(st?.outputTokens || 0));
|
||||
const thinkTok = Math.max(0, Number(st?.thinkingTokens || 0));
|
||||
const respTok =
|
||||
st?.responseTokens != null
|
||||
? Math.max(0, Number(st.responseTokens))
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
const totalTok = inTok + cacheTok + outTok;
|
||||
const ctxTok = Math.max(0, Number(st?.contextTokens ?? totalTok));
|
||||
return { inTok, cacheTok, outTok, thinkTok, respTok, totalTok, ctxTok };
|
||||
}
|
||||
|
||||
function formatPartWithOptionalCost(tokCount, costVal) {
|
||||
const countStr = Math.round(Number(tokCount || 0)).toLocaleString();
|
||||
if (costVal != null && Number.isFinite(Number(costVal))) {
|
||||
return `${countStr} (${formatUsd(Number(costVal), { precise: true })})`;
|
||||
}
|
||||
return countStr;
|
||||
}
|
||||
|
||||
export function formatCustomTokenComboHeader(rawFormat) {
|
||||
const segs = parseClientStepTokenComboSegments(rawFormat);
|
||||
return segs.map((seg) => t(`steps.tokSeg.${seg}.th`)).join(' / ');
|
||||
}
|
||||
|
||||
function resolveSegmentDisplay(seg, parts, st) {
|
||||
switch (seg) {
|
||||
case 'context':
|
||||
return {
|
||||
short: formatTokens(parts.ctxTok),
|
||||
tip: `${t('steps.tokSeg.context.tip')} ${Math.round(parts.ctxTok).toLocaleString()}`,
|
||||
};
|
||||
case 'in':
|
||||
return {
|
||||
short: formatTokens(parts.inTok),
|
||||
tip: `${t('steps.tokSeg.in.tip')} ${formatPartWithOptionalCost(parts.inTok, st?.inCostUsd)}`,
|
||||
};
|
||||
case 'out':
|
||||
return {
|
||||
short: formatTokens(parts.outTok),
|
||||
tip: `${t('steps.tokSeg.out.tip')} ${formatPartWithOptionalCost(parts.outTok, st?.outCostUsd)}`,
|
||||
};
|
||||
case 'cache':
|
||||
return {
|
||||
short: formatTokens(parts.cacheTok),
|
||||
tip: `${t('steps.tokSeg.cache.tip')} ${formatPartWithOptionalCost(parts.cacheTok, st?.cacheCostUsd)}`,
|
||||
};
|
||||
case 'think':
|
||||
return {
|
||||
short: formatTokens(parts.thinkTok),
|
||||
tip: `${t('steps.tokSeg.think.tip')} ${Math.round(parts.thinkTok).toLocaleString()}`,
|
||||
};
|
||||
case 'reply':
|
||||
return {
|
||||
short: formatTokens(parts.respTok),
|
||||
tip: `${t('steps.tokSeg.reply.tip')} ${Math.round(parts.respTok).toLocaleString()}`,
|
||||
};
|
||||
case 'total':
|
||||
default:
|
||||
return {
|
||||
short: formatTokens(parts.totalTok),
|
||||
tip: `${t('steps.tokSeg.total.tip')} ${formatPartWithOptionalCost(parts.totalTok, st?.costUsd)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function formatStepClockTime(createdAtMs) {
|
||||
const ms = Number(createdAtMs || 0);
|
||||
if (!(ms > 0) || !Number.isFinite(ms)) {
|
||||
return { text: '—', title: '' };
|
||||
}
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
const hhmmss = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
const full = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hhmmss}`;
|
||||
return { text: hhmmss, title: full };
|
||||
}
|
||||
|
||||
export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
step: {
|
||||
key: 'step',
|
||||
thLabel: () => t('stepCol.step.th'),
|
||||
optLabel: () => t('stepCol.step.opt'),
|
||||
sigPart: (st) => `${st.stepIndex}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.valEl, `#${Number(st.stepIndex)}`);
|
||||
},
|
||||
},
|
||||
|
||||
time: {
|
||||
key: 'time',
|
||||
thLabel: () => t('stepCol.time.th'),
|
||||
optLabel: () => t('stepCol.time.opt'),
|
||||
sigPart: (st) => `${st.createdAtMs || 0}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', { className: 'text-muted' }, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const { text, title } = formatStepClockTime(st.createdAtMs);
|
||||
patchText(refs.valEl, text);
|
||||
patchAttr(refs.td, 'title', title || null);
|
||||
},
|
||||
},
|
||||
|
||||
model: {
|
||||
key: 'model',
|
||||
thLabel: () => t('stepCol.model.th'),
|
||||
optLabel: () => t('stepCol.model.opt'),
|
||||
sigPart: (st, ctx) => {
|
||||
const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
|
||||
return `${disp.baseText}:${disp.compactionSuffix}:${disp.title}`;
|
||||
},
|
||||
createCell: () => {
|
||||
const nameEl = h('span', { className: 'step-model-name' });
|
||||
const compactEl = h('span', { className: 'step-model-compact', hidden: true });
|
||||
const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl, compactEl]);
|
||||
const td = h('td', {}, [wrapEl]);
|
||||
return { td, refs: { td, wrapEl, nameEl, compactEl } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
|
||||
patchText(refs.nameEl, modelDisplay.baseText);
|
||||
const suffix = modelDisplay.compactionSuffix || '';
|
||||
patchText(refs.compactEl, suffix);
|
||||
patchAttr(refs.compactEl, 'hidden', !suffix);
|
||||
patchAttr(refs.td, 'title', modelDisplay.title);
|
||||
},
|
||||
},
|
||||
|
||||
tps: {
|
||||
key: 'tps',
|
||||
thLabel: () => t('stepCol.tps.th'),
|
||||
optLabel: () => t('stepCol.tps.opt'),
|
||||
sigPart: (st, ctx) =>
|
||||
`${st.tokPerSec}:${st.selectedSpeedReason || ''}:${ctx?.showStepSpeedColor === true ? 1 : 0}`,
|
||||
createCell: () => {
|
||||
const speedMain = h('strong', {
|
||||
className: 'cell-value tone-muted',
|
||||
style: 'font-size: var(--fs-base-sm);',
|
||||
});
|
||||
const wrapEl = h(
|
||||
'span',
|
||||
{ style: 'display: inline-block; vertical-align: middle;' },
|
||||
[speedMain]
|
||||
);
|
||||
const td = h('td', {}, [wrapEl]);
|
||||
return { td, refs: { wrapEl, speedMain, speedReason: null } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
const hasValidSpeed =
|
||||
st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0;
|
||||
const toneCls =
|
||||
ctx?.showStepSpeedColor === true
|
||||
? getSpeedToneClass(st.tokPerSec)
|
||||
: hasValidSpeed
|
||||
? ''
|
||||
: 'tone-muted';
|
||||
patchAttr(refs.speedMain, 'class', toneCls ? `cell-value ${toneCls}` : 'cell-value');
|
||||
const reason = speedReasonText(st.selectedSpeedReason);
|
||||
if (reason && !refs.speedReason) {
|
||||
refs.speedReason = h('div', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-2xs);',
|
||||
});
|
||||
refs.wrapEl.appendChild(refs.speedReason);
|
||||
}
|
||||
if (refs.speedReason) {
|
||||
patchText(refs.speedReason, reason);
|
||||
patchAttr(refs.speedReason, 'hidden', !reason);
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
ttft: {
|
||||
key: 'ttft',
|
||||
thLabel: () => t('stepCol.ttft.th'),
|
||||
optLabel: () => t('stepCol.ttft.opt'),
|
||||
sigPart: (st) => `${st.ttftSec}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.valEl, formatMetric(st.ttftSec, 's'));
|
||||
const tone = getTtftToneClass(st.ttftSec);
|
||||
patchAttr(refs.valEl, 'class', tone || null);
|
||||
},
|
||||
},
|
||||
|
||||
duration: {
|
||||
key: 'duration',
|
||||
thLabel: () => t('stepCol.duration.th'),
|
||||
optLabel: () => t('stepCol.duration.opt'),
|
||||
sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const dur = st.totalDurationSec ?? st.streamDurationSec ?? null;
|
||||
patchText(refs.valEl, formatMetric(dur, 's'));
|
||||
},
|
||||
},
|
||||
|
||||
tokens_combo: {
|
||||
key: 'tokens_combo',
|
||||
thLabel: () => t('stepCol.tokens_combo.th'),
|
||||
optLabel: () => t('stepCol.tokens_combo.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.contextTokens}:${st.outputTokens}:${st.thinkingTokens}:${st.responseTokens}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const parts = resolveStepTokenParts(st);
|
||||
patchText(
|
||||
refs.valEl,
|
||||
`${formatTokens(parts.ctxTok)} / ${formatTokens(parts.thinkTok)} / ${formatTokens(parts.respTok)}`
|
||||
);
|
||||
patchAttr(
|
||||
refs.td,
|
||||
'title',
|
||||
t('steps.ctxTitle', {
|
||||
ctx: Math.round(parts.ctxTok),
|
||||
think: Math.round(parts.thinkTok),
|
||||
resp: Math.round(parts.respTok),
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
tokens_io_cache: {
|
||||
key: 'tokens_io_cache',
|
||||
thLabel: () => t('stepCol.tokens_io_cache.th'),
|
||||
optLabel: () => t('stepCol.tokens_io_cache.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.inputTokens || 0}:${st.outputTokens || 0}:${st.cacheReadTokens || 0}:${st.inCostUsd ?? ''}:${st.outCostUsd ?? ''}:${st.cacheCostUsd ?? ''}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const parts = resolveStepTokenParts(st);
|
||||
patchText(
|
||||
refs.valEl,
|
||||
`${formatTokens(parts.inTok)} / ${formatTokens(parts.outTok)} / ${formatTokens(parts.cacheTok)}`
|
||||
);
|
||||
patchAttr(
|
||||
refs.td,
|
||||
'title',
|
||||
t('steps.ioCacheTitle', {
|
||||
inPart: formatPartWithOptionalCost(parts.inTok, st?.inCostUsd),
|
||||
outPart: formatPartWithOptionalCost(parts.outTok, st?.outCostUsd),
|
||||
cachePart: formatPartWithOptionalCost(parts.cacheTok, st?.cacheCostUsd),
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
tokens_custom: {
|
||||
key: 'tokens_custom',
|
||||
thLabel: (ctx) => formatCustomTokenComboHeader(ctx?.stepTokenComboFormat),
|
||||
optLabel: (ctx) =>
|
||||
t('stepCol.tokens_custom.opt', {
|
||||
fmt: formatCustomTokenComboHeader(ctx?.stepTokenComboFormat),
|
||||
}),
|
||||
sigPart: (st, ctx) =>
|
||||
`${normalizeClientStepTokenComboFormat(ctx?.stepTokenComboFormat)}:${st.contextTokens || 0}:${st.inputTokens || 0}:${st.cacheReadTokens || 0}:${st.outputTokens || 0}:${st.thinkingTokens || 0}:${st.responseTokens ?? ''}:${st.costUsd ?? ''}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
const segs = parseClientStepTokenComboSegments(ctx?.stepTokenComboFormat);
|
||||
const parts = resolveStepTokenParts(st);
|
||||
const rendered = segs.map((seg) => resolveSegmentDisplay(seg, parts, st));
|
||||
patchText(
|
||||
refs.valEl,
|
||||
rendered.map((r) => r.short).join(' / ')
|
||||
);
|
||||
patchAttr(
|
||||
refs.td,
|
||||
'title',
|
||||
rendered.map((r) => r.tip).join(' · ')
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
input_tokens: {
|
||||
key: 'input_tokens',
|
||||
thLabel: () => t('stepCol.input_tokens.th'),
|
||||
optLabel: () => t('stepCol.input_tokens.opt'),
|
||||
sigPart: (st) => `${st.inputTokens || 0}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.valEl, formatTokens(st.inputTokens || 0));
|
||||
},
|
||||
},
|
||||
|
||||
cache_tokens: {
|
||||
key: 'cache_tokens',
|
||||
thLabel: () => t('stepCol.cache_tokens.th'),
|
||||
optLabel: () => t('stepCol.cache_tokens.opt'),
|
||||
sigPart: (st) => `${st.cacheReadTokens || 0}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.valEl, formatTokens(st.cacheReadTokens || 0));
|
||||
},
|
||||
},
|
||||
|
||||
output_tokens: {
|
||||
key: 'output_tokens',
|
||||
thLabel: () => t('stepCol.output_tokens.th'),
|
||||
optLabel: () => t('stepCol.output_tokens.opt'),
|
||||
sigPart: (st) => `${st.outputTokens || 0}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.valEl, formatTokens(st.outputTokens || 0));
|
||||
},
|
||||
},
|
||||
|
||||
cache: {
|
||||
key: 'cache',
|
||||
thLabel: () => t('stepCol.cache.th'),
|
||||
optLabel: () => t('stepCol.cache.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.cacheHitPct ?? 0}:${(st.inputTokens || 0) + (st.cacheReadTokens || 0) > 0 ? 1 : 0}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span', {
|
||||
className: 'cell-value tone-muted',
|
||||
style: 'font-size: var(--fs-base-sm);',
|
||||
});
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const promptTokens = Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0);
|
||||
patchText(refs.valEl, formatCachePct(st.cacheHitPct ?? 0));
|
||||
patchAttr(
|
||||
refs.valEl,
|
||||
'class',
|
||||
`cell-value ${getCacheToneClass(st.cacheHitPct ?? 0, promptTokens)}`
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
cost: {
|
||||
key: 'cost',
|
||||
thLabel: () => t('stepCol.cost.th'),
|
||||
optLabel: () => t('stepCol.cost.opt'),
|
||||
sigPart: (st) => `${st.costUsd}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span', { style: 'font-weight: 600;' });
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const costVal = st.costUsd;
|
||||
patchText(refs.valEl, formatUsd(costVal, { precise: true }));
|
||||
const tone = getStepCostToneClass(costVal);
|
||||
patchAttr(refs.valEl, 'class', tone || null);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export function getStepColumnOptions(
|
||||
stepTokenComboFormat = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT
|
||||
) {
|
||||
const ctx = { stepTokenComboFormat };
|
||||
return STEP_COLUMN_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: STEP_COLUMN_REGISTRY[key].optLabel(ctx),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* @fileoverview Decoupled Overview & Hover Widget Registry (`widgetRegistry.js`).
|
||||
* Maps module keys (`metrics`, `context`, `quotas`, `live_tasks`) to standalone
|
||||
* widget components and provides `createDynamicWidgetHost` for zero-hardcode mounting,
|
||||
* live reordering, and clean instance disposal.
|
||||
*/
|
||||
|
||||
import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js';
|
||||
import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js';
|
||||
import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js';
|
||||
import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
export const OVERVIEW_WIDGET_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
|
||||
metrics: {
|
||||
key: 'metrics',
|
||||
labelKey: 'module.metrics',
|
||||
create: ({ mode, isVisibleFn, preview, getCtxAgentId }) =>
|
||||
MetricMatrixWidget({ mode, isVisibleFn, preview, getCtxAgentId }),
|
||||
},
|
||||
context: {
|
||||
key: 'context',
|
||||
labelKey: 'module.context',
|
||||
create: ({ mode, isVisibleFn, preview, getCtxAgentId, setCtxAgentId }) =>
|
||||
ContextWindowWidget({
|
||||
interactiveInspector: mode !== 'hover',
|
||||
isVisibleFn,
|
||||
preview,
|
||||
getCtxAgentId,
|
||||
setCtxAgentId,
|
||||
}),
|
||||
},
|
||||
quotas: {
|
||||
key: 'quotas',
|
||||
labelKey: 'module.quotas',
|
||||
create: ({ mode }) =>
|
||||
QuotaPoolsWidget({
|
||||
compactHover: mode === 'hover',
|
||||
}),
|
||||
},
|
||||
live_tasks: {
|
||||
key: 'live_tasks',
|
||||
labelKey: 'module.live_tasks',
|
||||
create: ({ mode, isVisibleFn, preview, getCtxAgentId }) =>
|
||||
LiveActivityWidget({
|
||||
interactive: mode !== 'hover',
|
||||
isVisibleFn,
|
||||
preview,
|
||||
getCtxAgentId,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
export function getOverviewModuleOptions() {
|
||||
return OVERVIEW_WIDGET_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: t(`module.${key}`),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a dynamic container host that mounts, reorders, updates, and disposes
|
||||
* standalone telemetry widgets based on user-configured module keys.
|
||||
*
|
||||
* @param {{
|
||||
* containerEl: HTMLElement,
|
||||
* mode?: 'overview' | 'hover',
|
||||
* isVisibleFn?: () => boolean,
|
||||
* initialModuleKeys?: string[]
|
||||
* }} options
|
||||
*/
|
||||
export function createDynamicWidgetHost({
|
||||
containerEl,
|
||||
mode = 'overview',
|
||||
preview = false,
|
||||
isVisibleFn = () => true,
|
||||
initialModuleKeys = [],
|
||||
}) {
|
||||
const instances = new Map();
|
||||
let currentKeys = [];
|
||||
let previewCtxAgentId = 'auto';
|
||||
let latestUpdatePayload = null;
|
||||
|
||||
const getCtxAgentId = preview ? () => previewCtxAgentId : undefined;
|
||||
const setCtxAgentId = preview
|
||||
? (nextId) => {
|
||||
previewCtxAgentId = String(nextId || 'auto');
|
||||
if (latestUpdatePayload) {
|
||||
for (const key of currentKeys) {
|
||||
instances.get(key)?.refs?.update?.(latestUpdatePayload);
|
||||
}
|
||||
}
|
||||
}
|
||||
: undefined;
|
||||
|
||||
function syncModules(nextKeys) {
|
||||
const validKeys = [];
|
||||
const seen = new Set();
|
||||
for (const rawKey of Array.isArray(nextKeys) ? nextKeys : []) {
|
||||
const k = String(rawKey || '').trim();
|
||||
if (!k || seen.has(k) || !OVERVIEW_WIDGET_REGISTRY[k]) continue;
|
||||
seen.add(k);
|
||||
validKeys.push(k);
|
||||
}
|
||||
|
||||
// Remove and destroy widgets no longer present
|
||||
for (const [existingKey, inst] of [...instances.entries()]) {
|
||||
if (!seen.has(existingKey)) {
|
||||
try {
|
||||
inst.el?.remove?.();
|
||||
} catch {}
|
||||
try {
|
||||
inst.destroy?.();
|
||||
} catch {}
|
||||
instances.delete(existingKey);
|
||||
}
|
||||
}
|
||||
|
||||
// Instantiate newly added widgets
|
||||
for (const key of validKeys) {
|
||||
if (!instances.has(key)) {
|
||||
const inst = OVERVIEW_WIDGET_REGISTRY[key].create({
|
||||
mode,
|
||||
preview,
|
||||
isVisibleFn,
|
||||
getCtxAgentId,
|
||||
setCtxAgentId,
|
||||
});
|
||||
instances.set(key, inst);
|
||||
}
|
||||
}
|
||||
|
||||
// Reorder DOM nodes in containerEl only where needed
|
||||
const orderChanged =
|
||||
validKeys.length !== currentKeys.length ||
|
||||
validKeys.some((k, idx) => currentKeys[idx] !== k) ||
|
||||
(containerEl.children && containerEl.children.length !== validKeys.length);
|
||||
|
||||
if (orderChanged) {
|
||||
for (let i = 0; i < validKeys.length; i += 1) {
|
||||
const targetEl = instances.get(validKeys[i]).el;
|
||||
const curChild = containerEl.children ? containerEl.children[i] : null;
|
||||
if (curChild !== targetEl) {
|
||||
if (curChild && typeof containerEl.insertBefore === 'function') {
|
||||
containerEl.insertBefore(targetEl, curChild);
|
||||
} else {
|
||||
containerEl.appendChild(targetEl);
|
||||
}
|
||||
}
|
||||
}
|
||||
currentKeys = [...validKeys];
|
||||
}
|
||||
|
||||
return validKeys;
|
||||
}
|
||||
|
||||
function update({ moduleKeys = [], data = null, minuteTick = undefined } = {}) {
|
||||
latestUpdatePayload = { data, minuteTick };
|
||||
const validKeys = syncModules(moduleKeys);
|
||||
for (const key of validKeys) {
|
||||
const inst = instances.get(key);
|
||||
inst?.refs?.update?.({ data, minuteTick });
|
||||
}
|
||||
}
|
||||
|
||||
function pauseTickers() {
|
||||
for (const inst of instances.values()) {
|
||||
inst?.refs?.pauseTicker?.();
|
||||
}
|
||||
}
|
||||
|
||||
function resumeTickers() {
|
||||
for (const inst of instances.values()) {
|
||||
inst?.refs?.resumeTicker?.();
|
||||
}
|
||||
}
|
||||
|
||||
function getInstance(key) {
|
||||
return instances.get(key) || null;
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
for (const inst of instances.values()) {
|
||||
try {
|
||||
inst.el?.remove?.();
|
||||
} catch {}
|
||||
try {
|
||||
inst.destroy?.();
|
||||
} catch {}
|
||||
}
|
||||
instances.clear();
|
||||
currentKeys = [];
|
||||
}
|
||||
|
||||
if (Array.isArray(initialModuleKeys) && initialModuleKeys.length > 0) {
|
||||
syncModules(initialModuleKeys);
|
||||
}
|
||||
|
||||
return {
|
||||
update,
|
||||
pauseTickers,
|
||||
resumeTickers,
|
||||
getInstance,
|
||||
getActiveKeys: () => [...currentKeys],
|
||||
destroy,
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
|
||||
import { createReactiveStore } from '../core/reactive.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
export const VIEW_TABS = Object.freeze([
|
||||
{ value: 'overview', label: '实时监控', icon: 'pulse' },
|
||||
@@ -11,9 +12,25 @@ export const VIEW_TABS = Object.freeze([
|
||||
{ value: 'settings', label: '偏好设置', icon: 'sliders' },
|
||||
]);
|
||||
|
||||
export function getViewTabs() {
|
||||
return [
|
||||
{ value: 'overview', label: t('nav.overview'), icon: 'pulse' },
|
||||
{ value: 'consumption', label: t('nav.consumption'), icon: 'chart-bar' },
|
||||
{ value: 'steps', label: t('nav.steps'), icon: 'table' },
|
||||
{ value: 'settings', label: t('nav.settings'), icon: 'sliders' },
|
||||
];
|
||||
}
|
||||
|
||||
export const uiStore = createReactiveStore({
|
||||
activeView: 'overview',
|
||||
monitorVisible: true,
|
||||
stepsSubTab: 'steps', // 'steps' | 'models'
|
||||
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
|
||||
settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps'
|
||||
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
|
||||
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
|
||||
});
|
||||
|
||||
export function getVisibleMonitorView(state = uiStore.getState()) {
|
||||
return state.monitorVisible ? state.activeView : null;
|
||||
}
|
||||
|
||||
@@ -35,11 +35,9 @@
|
||||
@keyframes anim-popover-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate3d(0, -3px, 0) scale(0.985);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate3d(0, 0, 0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ body {
|
||||
background: var(--surface-bg);
|
||||
color: var(--text-primary);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
||||
font-size: 12.5px;
|
||||
font-size: var(--fs-body);
|
||||
line-height: 1.4;
|
||||
font-variant-numeric: tabular-nums;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
@@ -48,20 +48,44 @@ input {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
max-width: none;
|
||||
height: 100dvh;
|
||||
max-height: 100dvh;
|
||||
margin: 0 auto;
|
||||
margin: 0;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
gap: var(--space-3);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
html[data-standalone="true"] .app-shell {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
@media (min-width: 980px) {
|
||||
html[data-standalone="true"] .app-shell {
|
||||
padding: var(--space-4) var(--space-5);
|
||||
border-left: 1px solid var(--border-hairline);
|
||||
border-right: 1px solid var(--border-hairline);
|
||||
}
|
||||
}
|
||||
|
||||
.top-deck {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -29,7 +29,8 @@
|
||||
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;
|
||||
right: 0;
|
||||
min-width: 220px;
|
||||
@@ -56,7 +57,7 @@
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 6px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 600;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-ok) 32%, var(--border-hairline));
|
||||
@@ -153,7 +154,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
border-radius: var(--radius-pill);
|
||||
@@ -180,7 +181,7 @@
|
||||
|
||||
.pill-tab-badge {
|
||||
margin-left: -2px;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
@@ -212,6 +213,10 @@
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.custom-select[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -224,7 +229,7 @@
|
||||
color: var(--text-primary);
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
@@ -258,7 +263,7 @@
|
||||
box-shadow: var(--shadow-popover);
|
||||
padding: 4px;
|
||||
z-index: 60;
|
||||
animation: anim-popover-in var(--dur-fast) var(--ease-fast);
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-option {
|
||||
@@ -271,7 +276,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
text-align: left;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
@@ -288,6 +293,15 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.select-option.is-disabled {
|
||||
opacity: 0.42;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.select-option.is-disabled:hover {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.select-option-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
@@ -296,6 +310,42 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.select-option-meta {
|
||||
font-size: var(--fs-md);
|
||||
flex-shrink: 0;
|
||||
font-family: var(--font-mono);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.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">) --- */
|
||||
.number-input {
|
||||
display: inline-flex;
|
||||
@@ -366,7 +416,7 @@
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@@ -396,7 +446,7 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
}
|
||||
|
||||
.dt-weekdays,
|
||||
@@ -408,7 +458,7 @@
|
||||
}
|
||||
|
||||
.dt-weekday {
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
padding: 2px 0;
|
||||
}
|
||||
@@ -418,7 +468,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -444,7 +494,7 @@
|
||||
gap: var(--space-2);
|
||||
padding-top: var(--space-2);
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
}
|
||||
|
||||
.dt-time-controls {
|
||||
@@ -495,7 +545,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
@@ -520,7 +570,6 @@
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
gap: 5px;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -529,6 +578,7 @@
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
padding-right: 6px;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: none;
|
||||
@@ -542,10 +592,11 @@
|
||||
}
|
||||
|
||||
.scrollbar-rail {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 5px;
|
||||
margin: 2px 0;
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 0;
|
||||
bottom: 2px;
|
||||
width: 4px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--border-hairline) 35%, transparent);
|
||||
z-index: 15;
|
||||
@@ -561,7 +612,7 @@
|
||||
}
|
||||
|
||||
.scrollbar-rail.is-inactive {
|
||||
display: none !important;
|
||||
visibility: hidden;
|
||||
opacity: 0 !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -589,7 +640,7 @@
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
@@ -606,7 +657,7 @@
|
||||
border: 1px solid var(--accent-primary);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
cursor: pointer;
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
@@ -631,7 +682,7 @@
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast), border-color var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
@@ -665,7 +716,7 @@
|
||||
gap: 4px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 600;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
@@ -705,7 +756,7 @@
|
||||
justify-content: center;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
background: transparent;
|
||||
@@ -764,7 +815,7 @@
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--text-secondary);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */
|
||||
:host(.wm-capsule-host) {
|
||||
--ui-font-scale: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
@@ -32,6 +33,44 @@
|
||||
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"]) {
|
||||
position: fixed;
|
||||
top: 6px;
|
||||
@@ -251,8 +290,8 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wm-seg-speed.state-running {
|
||||
color: var(--metric-speed);
|
||||
.wm-seg-speed.state-running:not([class*="tone-"]) {
|
||||
color: var(--accent-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@@ -288,6 +327,38 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 缓存命中率槽位(固定预占宽度 44px 居中对齐) */
|
||||
.wm-seg-cache {
|
||||
width: 44px;
|
||||
}
|
||||
|
||||
.wm-cache-text {
|
||||
width: 44px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 会话总 Token 槽位(固定预占宽度 52px 居中对齐) */
|
||||
.wm-seg-tokens {
|
||||
width: 52px;
|
||||
}
|
||||
|
||||
.wm-tokens-text {
|
||||
width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wm-cap-slot.tone-good,
|
||||
.wm-cap-slot.tone-good .wm-slot-text {
|
||||
color: var(--metric-ok);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.wm-cap-slot.tone-info,
|
||||
.wm-cap-slot.tone-info .wm-slot-text {
|
||||
color: var(--metric-info);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.wm-cap-slot.tone-warn,
|
||||
.wm-cap-slot.tone-warn .wm-slot-text {
|
||||
color: var(--metric-warn);
|
||||
@@ -300,6 +371,11 @@
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.wm-cap-slot.tone-muted,
|
||||
.wm-cap-slot.tone-muted .wm-slot-text {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* 仅在超窄 ring-only 折叠态下使用右上角 5px 提示圆点;常规态由柔和微胶囊 .wm-update-btn 承载 */
|
||||
.wm-update-dot {
|
||||
position: absolute;
|
||||
@@ -385,16 +461,24 @@
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 与分隔线次序 data-sep-for-rank 动态折叠) */
|
||||
/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 1..5 与分隔线次序 data-sep-for-rank 动态折叠) */
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"] {
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="5"] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-label {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -406,8 +490,12 @@
|
||||
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct,
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label {
|
||||
display: none !important;
|
||||
@@ -431,7 +519,7 @@
|
||||
pointer-events: none;
|
||||
z-index: 2147483000;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
||||
font-size: 12.5px;
|
||||
font-size: var(--fs-body);
|
||||
line-height: 1.4;
|
||||
font-variant-numeric: tabular-nums;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
@@ -449,11 +537,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes wm-popover-in-up {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(3px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.wm-popover-panel {
|
||||
--step-model-max-w: 240px;
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(492px, calc(100vw - 24px));
|
||||
width: min(var(--wm-popover-w, 540px), calc(100vw - 24px));
|
||||
height: min(588px, calc(100vh - 54px));
|
||||
max-height: calc(100vh - 54px);
|
||||
display: flex;
|
||||
@@ -481,7 +581,7 @@
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(492px, calc(100vw - 24px));
|
||||
width: min(522px, calc(100vw - 24px));
|
||||
max-height: calc(100vh - 54px);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
display: flex;
|
||||
@@ -505,7 +605,7 @@
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(484px, calc(100vw - 24px));
|
||||
width: min(464px, calc(100vw - 24px));
|
||||
max-height: calc(100vh - 54px);
|
||||
padding: 14px 16px;
|
||||
display: flex;
|
||||
@@ -526,6 +626,21 @@
|
||||
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-hover-tip.is-instant,
|
||||
.wm-multi-panel.is-instant {
|
||||
@@ -545,6 +660,13 @@
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.wm-hover-widgets {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wm-hover-update-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -554,7 +676,7 @@
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--accent-primary-soft);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
@@ -569,7 +691,7 @@
|
||||
|
||||
.wm-hover-update-hint {
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -582,7 +704,7 @@
|
||||
}
|
||||
|
||||
.wm-hover-quota-foot {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
@@ -591,7 +713,7 @@
|
||||
align-items: center;
|
||||
height: 16px;
|
||||
padding: 0 5px;
|
||||
font-size: 10px;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
@@ -604,7 +726,7 @@
|
||||
align-items: center;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
font-size: 10px;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||
@@ -619,7 +741,7 @@
|
||||
}
|
||||
|
||||
.wm-task-metrics {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
@@ -656,7 +778,7 @@
|
||||
}
|
||||
|
||||
.wm-multi-panel .live-task-title {
|
||||
font-size: 12.5px;
|
||||
font-size: var(--fs-body);
|
||||
}
|
||||
|
||||
.wm-multi-empty {
|
||||
@@ -666,7 +788,7 @@
|
||||
gap: var(--space-3);
|
||||
min-height: 36px;
|
||||
padding: 12px 2px 4px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,39 +11,79 @@
|
||||
--radius-sm: 4px;
|
||||
--radius-xs: 2px;
|
||||
|
||||
/* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode & safe dark fallback) */
|
||||
--surface-bg: var(--background, hsl(0 0% 100%));
|
||||
--surface-panel: var(--card, var(--background, hsl(0 0% 100%)));
|
||||
/* Host-Bridged Surfaces (Antigravity 2.0 + Antigravity IDE --vscode-* + safe fallback) */
|
||||
--surface-bg: var(--background, var(--vscode-sideBar-background, var(--vscode-editor-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-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-active: color-mix(in srgb, var(--accent-primary) 12%, var(--surface-panel));
|
||||
|
||||
/* 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%);
|
||||
|
||||
/* Typography Hierarchy */
|
||||
--text-primary: var(--foreground, hsl(215 22% 15%));
|
||||
--text-secondary: var(--muted-foreground, hsl(215 12% 44%));
|
||||
/* Typography Hierarchy & Scalable Font Tokens */
|
||||
--ui-font-scale: 1;
|
||||
--fs-2xs: calc(9.5px * var(--ui-font-scale, 1));
|
||||
--fs-xs: calc(10px * var(--ui-font-scale, 1));
|
||||
--fs-sm: calc(10.5px * var(--ui-font-scale, 1));
|
||||
--fs-md: calc(11px * var(--ui-font-scale, 1));
|
||||
--fs-base-sm: calc(11.5px * var(--ui-font-scale, 1));
|
||||
--fs-base: calc(12px * var(--ui-font-scale, 1));
|
||||
--fs-body: calc(12.5px * var(--ui-font-scale, 1));
|
||||
--fs-lg: calc(14.5px * var(--ui-font-scale, 1));
|
||||
--fs-hero: calc(17px * var(--ui-font-scale, 1));
|
||||
|
||||
--text-primary: var(--foreground, var(--vscode-foreground, var(--vscode-editor-foreground, hsl(215 22% 15%))));
|
||||
--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-inverse: var(--surface-panel);
|
||||
--text-inverse: var(--user-accent-contrast, var(--surface-panel));
|
||||
|
||||
/* Semantic Telemetry Accents */
|
||||
--accent-primary: var(--primary, hsl(217 82% 51%));
|
||||
--accent-primary: var(
|
||||
--user-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-border: color-mix(in srgb, var(--accent-primary) 38%, var(--border-hairline));
|
||||
|
||||
--metric-speed: hsl(14 76% 52%);
|
||||
--metric-speed-soft: color-mix(in srgb, var(--metric-speed) 14%, transparent);
|
||||
|
||||
--metric-ok: hsl(145 64% 38%);
|
||||
--metric-ok: hsl(145 64% 41%);
|
||||
--metric-ok-soft: color-mix(in srgb, var(--metric-ok) 14%, transparent);
|
||||
|
||||
--metric-warn: hsl(34 86% 44%);
|
||||
--metric-info: hsl(197 82% 46%);
|
||||
--metric-info-soft: color-mix(in srgb, var(--metric-info) 14%, transparent);
|
||||
|
||||
--metric-warn: hsl(35 88% 47%);
|
||||
--metric-warn-soft: color-mix(in srgb, var(--metric-warn) 15%, transparent);
|
||||
|
||||
--metric-danger: var(--destructive, hsl(0 74% 50%));
|
||||
--metric-danger: hsl(4 78% 55%);
|
||||
--metric-danger-soft: color-mix(in srgb, var(--metric-danger) 14%, transparent);
|
||||
|
||||
/* Context Window 10-Channel Palette */
|
||||
--ctx-assistant: hsl(217 82% 54%);
|
||||
@@ -79,3 +119,15 @@
|
||||
--space-4: 10px;
|
||||
--space-5: 12px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html[data-standalone="true"] {
|
||||
color-scheme: dark;
|
||||
--background: hsl(222 18% 10%);
|
||||
--card: hsl(222 16% 13%);
|
||||
--border: hsl(220 14% 21%);
|
||||
--foreground: hsl(214 24% 92%);
|
||||
--muted-foreground: hsl(215 14% 63%);
|
||||
--primary: hsl(217 86% 61%);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
}
|
||||
|
||||
.cons-badge {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
@@ -98,21 +98,21 @@
|
||||
}
|
||||
|
||||
.cons-hero-num {
|
||||
font-size: 17px;
|
||||
font-size: var(--fs-hero);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-hero-cost {
|
||||
font-size: 17px;
|
||||
font-size: var(--fs-hero);
|
||||
font-weight: 700;
|
||||
color: var(--accent-primary);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-hero-cache {
|
||||
font-size: 17px;
|
||||
font-size: var(--fs-hero);
|
||||
font-weight: 700;
|
||||
color: var(--ctx-cached);
|
||||
letter-spacing: -0.02em;
|
||||
@@ -132,7 +132,7 @@
|
||||
}
|
||||
|
||||
.cons-sub-label {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -140,7 +140,7 @@
|
||||
}
|
||||
|
||||
.cons-mid-num {
|
||||
font-size: 14.5px;
|
||||
font-size: var(--fs-lg);
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
color: var(--text-primary);
|
||||
@@ -168,7 +168,7 @@
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 20px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
@@ -187,7 +187,7 @@
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
padding: 0 6px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--metric-ok);
|
||||
background: color-mix(in srgb, var(--metric-ok) 11%, transparent);
|
||||
@@ -201,7 +201,7 @@
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
@@ -211,7 +211,7 @@
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
@@ -238,7 +238,7 @@
|
||||
|
||||
.trend-svg {
|
||||
width: 100%;
|
||||
height: 118px;
|
||||
height: 120px;
|
||||
display: block;
|
||||
overflow: visible;
|
||||
}
|
||||
@@ -304,9 +304,10 @@
|
||||
top: 0;
|
||||
left: var(--tip-x, 50%);
|
||||
transform: translateX(var(--tip-shift, -50%));
|
||||
min-width: 148px;
|
||||
max-width: 240px;
|
||||
padding: 5px 8px;
|
||||
width: max-content;
|
||||
min-width: 152px;
|
||||
max-width: min(300px, calc(100% - 8px));
|
||||
padding: 5px 9px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
@@ -322,7 +323,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
gap: 10px;
|
||||
font-size: 10.5px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
@@ -331,42 +332,62 @@
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.trend-tip-calls {
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
max-width: 190px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.trend-tip-main {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.trend-tip-tokens {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--accent-primary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.trend-tip-cost {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.trend-tip-sub {
|
||||
font-size: 10px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
padding-top: 2px;
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.trend-tooltip.is-hm-top {
|
||||
top: 0;
|
||||
bottom: auto;
|
||||
}
|
||||
|
||||
.trend-tooltip.is-hm-bottom {
|
||||
top: auto;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.trend-x-axis {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
@@ -401,6 +422,177 @@
|
||||
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) --- */
|
||||
.cons-item-list {
|
||||
display: flex;
|
||||
@@ -419,10 +611,14 @@
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 10px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cons-item-foot > .legend-left:last-child {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cons-item-foot strong {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
@@ -516,6 +712,6 @@
|
||||
justify-content: center;
|
||||
gap: var(--space-4);
|
||||
padding-top: var(--space-2);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
flex: 1;
|
||||
@@ -47,12 +47,52 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
color: var(--text-secondary);
|
||||
flex-shrink: 0;
|
||||
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: var(--fs-base-sm);
|
||||
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: var(--fs-sm);
|
||||
font-weight: 400;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.quota-win-meta {
|
||||
font-size: var(--fs-md);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */
|
||||
.live-activity-list {
|
||||
display: flex;
|
||||
@@ -90,7 +130,7 @@
|
||||
}
|
||||
|
||||
.live-task-title {
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
color: var(--text-primary);
|
||||
@@ -118,7 +158,7 @@
|
||||
gap: 3px;
|
||||
height: 18px;
|
||||
padding: 0 6px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-panel);
|
||||
@@ -168,7 +208,7 @@
|
||||
}
|
||||
|
||||
.live-activity-phase {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -176,7 +216,7 @@
|
||||
}
|
||||
|
||||
.live-activity-progress {
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
@@ -187,13 +227,13 @@
|
||||
}
|
||||
|
||||
.live-activity-sep {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.live-activity-detail {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -203,7 +243,7 @@
|
||||
}
|
||||
|
||||
.live-activity-elapsed {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
@@ -230,7 +270,7 @@
|
||||
gap: 10px;
|
||||
min-height: 22px;
|
||||
min-width: 0;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
@@ -266,7 +306,7 @@
|
||||
}
|
||||
|
||||
.live-sub-elapsed {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
min-width: 28px;
|
||||
@@ -276,7 +316,7 @@
|
||||
|
||||
.telemetry-matrix {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: repeat(var(--matrix-cols, 4), minmax(0, 1fr));
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
@@ -298,12 +338,12 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cell-value {
|
||||
font-size: 14.5px;
|
||||
font-size: var(--fs-lg);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -311,16 +351,41 @@
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cell-value.accent-speed {
|
||||
.cell-value.accent-speed,
|
||||
.accent-speed {
|
||||
color: var(--metric-speed);
|
||||
}
|
||||
|
||||
.cell-value.accent-ok {
|
||||
.cell-value.accent-ok,
|
||||
.accent-ok,
|
||||
.cell-value.tone-good,
|
||||
.tone-good {
|
||||
color: var(--metric-ok);
|
||||
}
|
||||
|
||||
.cell-value.tone-info,
|
||||
.tone-info {
|
||||
color: var(--metric-info);
|
||||
}
|
||||
|
||||
.cell-value.tone-warn,
|
||||
.tone-warn {
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.cell-value.tone-danger,
|
||||
.tone-danger {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.cell-value.tone-muted,
|
||||
.tone-muted {
|
||||
color: var(--text-muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.cell-sub {
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -417,7 +482,7 @@
|
||||
padding: 2px 0 0 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
@@ -487,7 +552,7 @@
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
@@ -533,7 +598,7 @@
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 1px 5px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
border-radius: var(--radius-xs);
|
||||
@@ -576,8 +641,8 @@
|
||||
}
|
||||
|
||||
@media (max-width: 390px) {
|
||||
.telemetry-matrix {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
.telemetry-matrix:not([data-cols="1"]):not([data-cols="2"]) {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.dual-grid {
|
||||
grid-template-columns: 1fr;
|
||||
|
||||
@@ -0,0 +1,837 @@
|
||||
/*
|
||||
* 模块化偏好设置样式表 (views-settings.css).
|
||||
* 包含:
|
||||
* 1. 顶部偏好设置切换导航条 (.settings-view-root, .settings-subnav-bar)
|
||||
* 2. 主题强调色色卡选择器 (.theme-color-picker, .theme-host-chip, .theme-swatch-btn)
|
||||
* 3. 结构页手风琴折叠面板 (.collapsible-section, .collapsible-trigger, .collapsible-body)
|
||||
* 4. 通用 + / - / ↑ / ↓ 自添加排序列表 (.editable-slot-list, .editable-slot-row, .slot-add-btn)
|
||||
* 5. 其他页维护操作行与二次确认危险态按钮 (.settings-action-row, .btn-danger-confirm)
|
||||
*/
|
||||
|
||||
.settings-view-root {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.settings-subnav-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 3px 4px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.settings-subnav-bar .segmented {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(0, 1fr);
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.settings-subnav-bar .seg-btn {
|
||||
height: 24px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* --- 结构页三级子导航菜单 (.settings-thirdnav-bar) --- */
|
||||
.settings-thirdnav-bar {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.structure-thirdnav-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
height: 25px;
|
||||
min-width: 0;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--surface-subtle);
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.structure-thirdnav-btn:hover {
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-strong);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.structure-thirdnav-btn.is-active {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.structure-thirdnav-label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.settings-tab-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding-bottom: 2px;
|
||||
}
|
||||
|
||||
.settings-hint-text {
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.4;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* --- 主题色色卡选择器 (ThemeColorPicker) --- */
|
||||
.theme-color-picker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.theme-host-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
height: 24px;
|
||||
padding: 0 9px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-pill);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.theme-host-chip:hover {
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.theme-host-chip.is-active {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.theme-swatch-group {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.theme-swatch-btn {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border-radius: var(--radius-pill);
|
||||
border: 1.5px solid color-mix(in srgb, var(--text-primary) 18%, transparent);
|
||||
background: var(--swatch-color, var(--accent-primary));
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.theme-swatch-btn:hover {
|
||||
transform: scale(1.08);
|
||||
}
|
||||
|
||||
.theme-swatch-btn.is-active {
|
||||
border-color: var(--text-primary);
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--swatch-color, var(--accent-primary)) 32%, transparent);
|
||||
}
|
||||
|
||||
.theme-swatch-btn .svg-icon {
|
||||
stroke-width: 2.5;
|
||||
}
|
||||
|
||||
/* --- 手风琴折叠面板 (CollapsibleSection) --- */
|
||||
.collapsible-section {
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.collapsible-header-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
.collapsible-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.collapsible-trigger:hover {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.collapsible-title-static {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
color: var(--text-primary);
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- 结构页真实 UI 实时预览画布(无套娃外框,直接呈现真实组件) --- */
|
||||
.structure-preview-canvas {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.structure-preview-canvas.is-scaled {
|
||||
zoom: 0.86;
|
||||
}
|
||||
|
||||
.wm-hover-tip.is-preview {
|
||||
position: relative;
|
||||
top: auto;
|
||||
left: auto;
|
||||
width: 100%;
|
||||
max-height: none;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
z-index: 1;
|
||||
pointer-events: auto;
|
||||
box-shadow: none;
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.overview-modules-host.is-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.structure-preview-empty,
|
||||
.preview-sidebar-note {
|
||||
padding: 7px 10px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.4;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-panel);
|
||||
border: 1px dashed var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.capsule-preview-widget {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.preview-capsule-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-height: 36px;
|
||||
padding: 4px 8px;
|
||||
background: var(--surface-bg);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
overflow-x: auto;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.preview-capsule-bar.is-composer {
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--surface-panel);
|
||||
}
|
||||
|
||||
.preview-capsule-bar.is-composer .wm-multi-btn,
|
||||
.preview-capsule-bar.is-composer .wm-capsule-btn {
|
||||
height: 26px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.preview-capsule-bar.is-composer .wm-multi-btn {
|
||||
padding: 0 7px;
|
||||
}
|
||||
|
||||
.preview-capsule-bar.is-composer .wm-capsule-btn {
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
.preview-capsule-bar.is-sidebar-only {
|
||||
opacity: 0.42;
|
||||
filter: grayscale(0.35);
|
||||
}
|
||||
|
||||
.preview-capsule-cluster {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.preview-host-left {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: var(--fs-sm);
|
||||
flex-shrink: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.preview-win-title {
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.preview-composer-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--fs-xs);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.preview-win-controls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding-left: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.preview-win-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 26%, transparent);
|
||||
}
|
||||
|
||||
.preview-composer-send {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.step-table-preview-host {
|
||||
position: relative;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--surface-panel);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.step-table-preview-host .data-table tbody tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.collapsible-chevron {
|
||||
color: var(--text-secondary);
|
||||
transition: transform var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.collapsible-section.is-expanded .collapsible-chevron {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.collapsible-title-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.collapsible-right {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.collapsible-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 18px;
|
||||
padding: 0 6px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.collapsible-status {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.collapsible-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4) var(--space-4);
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-divider {
|
||||
height: 1px;
|
||||
width: 100%;
|
||||
background: var(--border-hairline);
|
||||
margin: 2px 0;
|
||||
}
|
||||
|
||||
/* --- 通用可增删排序槽位列表 (EditableSlotList) --- */
|
||||
.editable-slot-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.editable-slot-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.editable-slot-empty {
|
||||
padding: 8px 10px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px dashed var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.editable-slot-row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 2px 4px 2px 6px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--surface-panel);
|
||||
transition: border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.editable-slot-row:focus-within,
|
||||
.editable-slot-row:has(.is-open) {
|
||||
z-index: 35;
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.editable-slot-row .select-menu {
|
||||
max-height: 216px;
|
||||
}
|
||||
|
||||
.slot-drag-handle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 22px;
|
||||
margin-left: -2px;
|
||||
color: var(--text-muted);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: grab;
|
||||
flex-shrink: 0;
|
||||
touch-action: none;
|
||||
transition:
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
background-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.editable-slot-row:hover .slot-drag-handle:not(.is-disabled) {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.slot-drag-handle:hover:not(.is-disabled) {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.slot-drag-handle.is-disabled {
|
||||
opacity: 0.25;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.editable-slot-list.is-dragging-list,
|
||||
.editable-slot-list.is-dragging-list * {
|
||||
cursor: grabbing !important;
|
||||
user-select: none !important;
|
||||
}
|
||||
|
||||
.editable-slot-row.is-dragging {
|
||||
z-index: 40;
|
||||
border-color: var(--accent-primary);
|
||||
background: color-mix(in srgb, var(--accent-primary) 9%, var(--surface-panel));
|
||||
box-shadow: var(--shadow-popover);
|
||||
}
|
||||
|
||||
.editable-slot-row.is-dragging .slot-drag-handle {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.slot-remove-btn {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.slot-remove-btn:hover:not(:disabled) {
|
||||
color: var(--metric-danger);
|
||||
background: color-mix(in srgb, var(--metric-danger) 10%, transparent);
|
||||
}
|
||||
|
||||
.editable-slot-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
padding-top: 1px;
|
||||
}
|
||||
|
||||
.slot-add-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
height: 24px;
|
||||
padding: 0 9px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border: 1px dashed var(--accent-primary-border);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
opacity var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.slot-add-btn:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--accent-primary) 18%, transparent);
|
||||
}
|
||||
|
||||
.slot-add-btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* --- 其他页:维护操作行 --- */
|
||||
.settings-action-block {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.settings-action-block + .settings-action-block {
|
||||
padding-top: var(--space-3);
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-action-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.settings-action-title {
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.settings-action-desc {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.settings-account-identity {
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.settings-account-list,
|
||||
.settings-account-form,
|
||||
.settings-account-form label {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-list:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.settings-account-entry {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) 0;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-account-form label {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.settings-account-form input {
|
||||
min-width: 0;
|
||||
padding: var(--space-2);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
font: inherit;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.settings-account-form button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.settings-account-buttons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.settings-account-quota {
|
||||
text-align: right;
|
||||
color: var(--text-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.settings-context-model .select-option-meta {
|
||||
max-width: 62%;
|
||||
text-align: right;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.btn-danger-confirm {
|
||||
color: var(--metric-danger) !important;
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 55%, var(--border-hairline)) !important;
|
||||
background: color-mix(in srgb, var(--metric-danger) 11%, var(--surface-panel)) !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.settings-inline-controls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.settings-text-input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-primary);
|
||||
outline: none;
|
||||
transition: border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.settings-text-input:focus {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.settings-number-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.settings-number-wrap[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.settings-number-wrap .number-input {
|
||||
height: 24px;
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
.settings-number-wrap .num-step-btn {
|
||||
width: 22px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.settings-number-wrap .num-field {
|
||||
width: 48px;
|
||||
min-width: 48px;
|
||||
padding: 0 4px;
|
||||
text-align: center;
|
||||
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
|
||||
.settings-number-unit {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* --- 其他页:模型上下文设置风险警告遮罩 --- */
|
||||
.ctx-risk-stage {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ctx-controls-body {
|
||||
grid-area: 1 / 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
transition:
|
||||
filter var(--dur-fast) var(--ease-fast),
|
||||
opacity var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.ctx-controls-body.is-locked {
|
||||
filter: blur(4px);
|
||||
opacity: 0.24;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ctx-risk-mask {
|
||||
grid-area: 1 / 1;
|
||||
z-index: 5;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline));
|
||||
background: color-mix(in srgb, var(--surface-panel) 88%, var(--metric-warn) 7%);
|
||||
}
|
||||
|
||||
.ctx-risk-mask[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.ctx-risk-head {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.ctx-risk-icon {
|
||||
color: var(--metric-warn);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.ctx-risk-title {
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.ctx-risk-desc {
|
||||
margin: 0;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.5;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.ctx-risk-accept-btn {
|
||||
margin-top: 2px;
|
||||
height: 26px;
|
||||
padding: 0 var(--space-3);
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
@@ -27,11 +27,15 @@
|
||||
background: var(--surface-panel);
|
||||
}
|
||||
|
||||
.table-viewport.is-step-table {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* --- 2. 粘性表头数据表 (Sticky-Header Data Table) --- */
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
|
||||
.data-table th,
|
||||
@@ -42,15 +46,20 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-table th.is-right,
|
||||
.data-table td.is-right {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.data-table th:first-child,
|
||||
.data-table td:first-child {
|
||||
padding-left: 7px;
|
||||
padding-left: 2px;
|
||||
}
|
||||
|
||||
.data-table th:last-child,
|
||||
.data-table td:last-child {
|
||||
text-align: right;
|
||||
padding-right: 10px;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
@@ -66,6 +75,33 @@
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.step-model-cell {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
max-width: var(--step-model-max-w, 176px);
|
||||
min-width: 0;
|
||||
vertical-align: bottom;
|
||||
}
|
||||
|
||||
.step-model-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.step-model-compact {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--metric-info, var(--accent-primary));
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.step-model-compact[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-panel-header {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 6px;
|
||||
@@ -88,19 +124,606 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.steps-inline-scope-select {
|
||||
flex: 0 1 180px;
|
||||
.steps-inline-scope-select,
|
||||
.steps-inline-model-select {
|
||||
flex: 0 1 165px;
|
||||
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;
|
||||
padding: 0 6px;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
/* --- 2.5 极简对话轮次导轨与起点圆点 (Minimalist Turn Rail & Prompt Preview) --- */
|
||||
.steps-data-table.has-turn-rail th:first-child,
|
||||
.steps-data-table.has-turn-rail td:first-child {
|
||||
padding-left: 17px;
|
||||
}
|
||||
|
||||
.steps-data-table td:first-child {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.turn-rail {
|
||||
--rail-line: color-mix(in srgb, var(--text-secondary) 28%, var(--border-hairline));
|
||||
--rail-dot: color-mix(in srgb, var(--accent-primary) 52%, var(--text-secondary));
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: -1px;
|
||||
left: 5px;
|
||||
width: 8px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.turn-rail.is-latest {
|
||||
--rail-line: color-mix(in srgb, var(--accent-primary) 62%, var(--surface-panel));
|
||||
--rail-dot: var(--accent-primary);
|
||||
}
|
||||
|
||||
.steps-data-table tbody tr:hover .turn-rail {
|
||||
--rail-line: color-mix(in srgb, var(--accent-primary) 78%, var(--surface-panel));
|
||||
--rail-dot: var(--accent-primary);
|
||||
}
|
||||
|
||||
.turn-rail::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 3.25px;
|
||||
width: 1.5px;
|
||||
background: var(--rail-line);
|
||||
}
|
||||
|
||||
.turn-rail:not(.has-up):not(.has-down)::before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.turn-rail.has-up.has-down::before {
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.turn-rail.has-up:not(.has-down)::before {
|
||||
top: 0;
|
||||
bottom: 50%;
|
||||
}
|
||||
|
||||
.turn-rail.has-down:not(.has-up)::before {
|
||||
top: 50%;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.turn-rail.is-cap::after,
|
||||
.turn-rail.is-origin::after {
|
||||
content: '';
|
||||
box-sizing: border-box;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 4px;
|
||||
transform: translate(-50%, -50%);
|
||||
border-radius: var(--radius-pill);
|
||||
}
|
||||
|
||||
.turn-rail.is-cap::after {
|
||||
width: 3.5px;
|
||||
height: 3.5px;
|
||||
background: var(--rail-line);
|
||||
}
|
||||
|
||||
.turn-rail.is-origin::after {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
background: var(--surface-panel);
|
||||
border: 1.5px solid var(--rail-dot);
|
||||
box-shadow: 0 0 0 1px var(--surface-panel);
|
||||
}
|
||||
|
||||
.turn-rail.is-latest.is-origin::after {
|
||||
background: var(--rail-dot);
|
||||
}
|
||||
|
||||
.turn-rail[hidden],
|
||||
.turn-prompt-tip[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* 极简紧凑提问文本悬停预览气泡 */
|
||||
.turn-prompt-tip {
|
||||
position: absolute;
|
||||
z-index: 45;
|
||||
max-width: min(286px, calc(100% - 16px));
|
||||
padding: 5px 8px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.42;
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-xs);
|
||||
box-shadow: var(--shadow-popover);
|
||||
white-space: pre-line;
|
||||
word-break: break-word;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 3;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
/* --- 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: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sstep-card .seg-btn {
|
||||
padding: 2px 6px;
|
||||
font-size: var(--fs-sm);
|
||||
}
|
||||
|
||||
.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: var(--fs-sm);
|
||||
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: var(--fs-md);
|
||||
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: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.smodel-calls-pill {
|
||||
flex-shrink: 0;
|
||||
font-size: var(--fs-xs);
|
||||
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: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.smodel-cost {
|
||||
font-size: var(--fs-base);
|
||||
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: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.smodel-perf {
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.smodel-split {
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -23,28 +23,35 @@ import {
|
||||
formatDateSpanBadge,
|
||||
formatTokensPrecise,
|
||||
formatUsd,
|
||||
mergeModelsByDisplayName,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdDisplayMode,
|
||||
resolveModelDisplayInfo,
|
||||
} from '../core/formatters.js';
|
||||
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { createTrendAreaChart } from '../components/charts/TrendAreaChart.js';
|
||||
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
||||
import {
|
||||
createTrendAreaChart,
|
||||
HEATMAP_DAYS_THRESHOLD,
|
||||
} from '../components/charts/TrendAreaChart.js';
|
||||
import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
|
||||
/** 消耗统计顶栏支持的时间范围预设项 */
|
||||
const TIME_RANGE_OPTIONS = [
|
||||
{ value: 'today', label: '今天' },
|
||||
{ value: '24h', label: '1天' },
|
||||
{ value: '7d', label: '7天' },
|
||||
{ value: '14d', label: '14天' },
|
||||
{ value: '30d', label: '30天' },
|
||||
{ value: 'all', label: '全部' },
|
||||
{ value: 'custom', label: '自定义' },
|
||||
];
|
||||
function getConsumptionTimeRangeOptions() {
|
||||
return [
|
||||
{ value: 'today', label: t('cons.rangeToday') },
|
||||
{ value: '24h', label: t('cons.range24h') },
|
||||
{ value: '7d', label: t('cons.range7d') },
|
||||
{ value: '14d', label: t('cons.range14d') },
|
||||
{ value: '30d', label: t('cons.range30d') },
|
||||
{ value: 'all', label: t('cons.rangeAll') },
|
||||
{ value: 'custom', label: t('cons.rangeCustom') },
|
||||
];
|
||||
}
|
||||
|
||||
export const ConsumptionView = defineComponent({
|
||||
name: 'ConsumptionView',
|
||||
@@ -55,9 +62,9 @@ export const ConsumptionView = defineComponent({
|
||||
let hasUncommittedCustomDraft = false;
|
||||
|
||||
const timeFilterSwitch = SegmentedControl({
|
||||
ariaLabel: '消耗统计时间范围',
|
||||
ariaLabel: t('cons.rangeAria'),
|
||||
modelValue: telemetryStore.getState().selectedTimeRange,
|
||||
options: TIME_RANGE_OPTIONS,
|
||||
options: getConsumptionTimeRangeOptions(),
|
||||
onUpdateModelValue: (nextRange) => {
|
||||
if (nextRange === 'custom') {
|
||||
const st = telemetryStore.getState();
|
||||
@@ -92,6 +99,7 @@ export const ConsumptionView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const applyCustomBtnLabel = h('span', { text: t('cons.applyFilter') });
|
||||
const applyCustomBtn = h(
|
||||
'button',
|
||||
{
|
||||
@@ -116,9 +124,10 @@ export const ConsumptionView = defineComponent({
|
||||
fetchTelemetry({ force: true });
|
||||
},
|
||||
},
|
||||
[createSvgIcon('check', { size: 12 }), h('span', { text: '筛选' })]
|
||||
[createSvgIcon('check', { size: 12 }), applyCustomBtnLabel]
|
||||
);
|
||||
|
||||
const rangeToSpan = h('span', { className: 'text-muted', text: t('cons.rangeTo') });
|
||||
const customRangeBar = h(
|
||||
'div',
|
||||
{
|
||||
@@ -128,7 +137,7 @@ export const ConsumptionView = defineComponent({
|
||||
},
|
||||
[
|
||||
startPicker.el,
|
||||
h('span', { className: 'text-muted', text: '至' }),
|
||||
rangeToSpan,
|
||||
endPicker.el,
|
||||
applyCustomBtn,
|
||||
]
|
||||
@@ -137,31 +146,38 @@ export const ConsumptionView = defineComponent({
|
||||
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) ---
|
||||
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' });
|
||||
const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' });
|
||||
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' });
|
||||
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) });
|
||||
const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' });
|
||||
const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '≈ ¥0' });
|
||||
const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: '≈ ¥0' });
|
||||
|
||||
const cacheHitPctEl = h('strong', { className: 'cons-hero-cache text-mono', text: '0%' });
|
||||
const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '命中 0' });
|
||||
const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.cacheHitTokens', { tokens: 0 }) });
|
||||
|
||||
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
|
||||
const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '未命中缓存输入' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.uncachedInput') });
|
||||
|
||||
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
|
||||
const cacheMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '节省 $0.00' });
|
||||
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.savedCost', { cost: '$0.00' }) });
|
||||
|
||||
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
|
||||
const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '回复 0 · 思考 0' });
|
||||
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.replyAndThink', { resp: 0, think: 0 }) });
|
||||
|
||||
const overviewSegBar = createFourSegmentBar();
|
||||
const overviewTitleSpan = h('span', { text: t('cons.overviewTitle') });
|
||||
const totalTokensLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.totalTokens') });
|
||||
const estCostLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.estCost') });
|
||||
const cacheHitRateLabel = h('span', { text: t('cons.cacheHitRate') });
|
||||
const newInputLabel = h('span', { text: t('cons.newInput') });
|
||||
const cacheReadLabel = h('span', { text: t('cons.cacheRead') });
|
||||
const outputUsageLabel = h('span', { text: t('cons.outputUsage') });
|
||||
|
||||
const overviewPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header cons-overview-head' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
h('span', { text: '用量总览' }),
|
||||
overviewTitleSpan,
|
||||
dateSpanBadge,
|
||||
]),
|
||||
timeFilterSwitch.el,
|
||||
@@ -170,17 +186,17 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-box cons-unified-matrix' }, [
|
||||
h('div', { className: 'cons-split-3' }, [
|
||||
h('div', { className: 'cons-col' }, [
|
||||
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token' }),
|
||||
totalTokensLabel,
|
||||
h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]),
|
||||
]),
|
||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '预估费用' }),
|
||||
estCostLabel,
|
||||
h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]),
|
||||
]),
|
||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||
h('span', { className: 'legend-left', style: 'font-size: 11px;' }, [
|
||||
h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存命中率' }),
|
||||
cacheHitRateLabel,
|
||||
]),
|
||||
h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]),
|
||||
]),
|
||||
@@ -190,7 +206,7 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
h('span', { text: '新输入' }),
|
||||
newInputLabel,
|
||||
]),
|
||||
inputSharePct,
|
||||
]),
|
||||
@@ -201,7 +217,7 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存读取' }),
|
||||
cacheReadLabel,
|
||||
]),
|
||||
cacheSharePct,
|
||||
]),
|
||||
@@ -212,7 +228,7 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
h('span', { text: '输出用量' }),
|
||||
outputUsageLabel,
|
||||
]),
|
||||
outputSharePct,
|
||||
]),
|
||||
@@ -225,18 +241,19 @@ export const ConsumptionView = defineComponent({
|
||||
]);
|
||||
|
||||
// --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 + 悬停精确日期/小时浮层 + 多刻度时间轴) ---
|
||||
const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' });
|
||||
const trendTitleSpan = h('span', { text: t('cons.trendTitle') });
|
||||
const trendRangeBadge = h('span', { className: 'cons-badge', text: t('cons.allTime') });
|
||||
const trendGranularityHint = h('span', {
|
||||
className: 'text-muted text-mono',
|
||||
style: 'font-size: 10.5px;',
|
||||
text: '按小时 · 悬停查看明细',
|
||||
style: 'font-size: var(--fs-sm);',
|
||||
text: t('cons.trendPointsHintHourly', { points: 0 }),
|
||||
});
|
||||
const trendChart = createTrendAreaChart();
|
||||
|
||||
const trendPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
h('span', { text: '用量趋势' }),
|
||||
trendTitleSpan,
|
||||
trendRangeBadge,
|
||||
]),
|
||||
trendGranularityHint,
|
||||
@@ -245,24 +262,27 @@ export const ConsumptionView = defineComponent({
|
||||
]);
|
||||
|
||||
// --- Section 3: 模型排行列表 ---
|
||||
const modelsTitleSpan = h('span', { className: 'panel-title', text: t('cons.topModels') });
|
||||
const modelsListEl = h('div', { className: 'cons-item-list' });
|
||||
const modelsPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '模型排行' }),
|
||||
modelsTitleSpan,
|
||||
]),
|
||||
modelsListEl,
|
||||
]);
|
||||
|
||||
// --- Section 4: 客户端来源列表 ---
|
||||
const sourcesTitleSpan = h('span', { className: 'panel-title', text: t('cons.clientSources') });
|
||||
const sourcesListEl = h('div', { className: 'cons-item-list' });
|
||||
const sourcesPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '客户端来源' }),
|
||||
sourcesTitleSpan,
|
||||
]),
|
||||
sourcesListEl,
|
||||
]);
|
||||
|
||||
// --- Section 5: 按月细分 (12 个月垂直 4 段堆叠柱状图) ---
|
||||
const monthlyTitleSpan = h('span', { className: 'panel-title', text: t('cons.monthlyTitle') });
|
||||
const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' });
|
||||
const monthlyCols = Array.from({ length: 12 }, (_, idx) => {
|
||||
const costText = h('span', { className: 'month-cost text-mono', text: '' });
|
||||
@@ -277,7 +297,7 @@ export const ConsumptionView = defineComponent({
|
||||
barIn,
|
||||
]);
|
||||
const zeroDot = h('span', { className: 'month-zero-dot' });
|
||||
const monthLabel = h('span', { className: 'month-label', text: `${idx + 1}月` });
|
||||
const monthLabel = h('span', { className: 'month-label', text: t('cons.monthLabel', { m: idx + 1 }) });
|
||||
const tokText = h('span', { className: 'month-tok text-mono', text: '' });
|
||||
|
||||
const colEl = h('div', { className: 'month-col' }, [
|
||||
@@ -300,9 +320,14 @@ export const ConsumptionView = defineComponent({
|
||||
};
|
||||
});
|
||||
|
||||
const legInputSpan = h('span', { text: t('cons.legInput') });
|
||||
const legCacheSpan = h('span', { text: t('cons.legCache') });
|
||||
const legOutputSpan = h('span', { text: t('cons.legOutput') });
|
||||
const legThinkingSpan = h('span', { text: t('cons.legThinking') });
|
||||
|
||||
const monthlyPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '月度统计' }),
|
||||
monthlyTitleSpan,
|
||||
monthlyYearBadge,
|
||||
]),
|
||||
h(
|
||||
@@ -313,19 +338,19 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'monthly-legend' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
h('span', { text: '输入' }),
|
||||
legInputSpan,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存' }),
|
||||
legCacheSpan,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
h('span', { text: '输出' }),
|
||||
legOutputSpan,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-thinking' }),
|
||||
h('span', { text: '思考' }),
|
||||
legThinkingSpan,
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
@@ -359,6 +384,12 @@ export const ConsumptionView = defineComponent({
|
||||
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||
const segBar = createFourSegmentBar();
|
||||
|
||||
const inLbl = h('span', { text: t('cons.footInput') });
|
||||
const cacheLbl = h('span', { text: t('cons.footCache') });
|
||||
const outLbl = h('span', { text: t('cons.footOutput') });
|
||||
const thinkLbl = h('span', { text: t('cons.footThinking') });
|
||||
const callsLbl = h('span', { text: t('cons.footCalls') });
|
||||
|
||||
const inVal = h('strong', { className: 'text-mono' });
|
||||
const cacheVal = h('strong', { className: 'text-mono' });
|
||||
const outVal = h('strong', { className: 'text-mono' });
|
||||
@@ -378,26 +409,26 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-item-foot' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
h('span', { text: '输入 ' }),
|
||||
inLbl,
|
||||
inVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存 ' }),
|
||||
cacheLbl,
|
||||
cacheVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
h('span', { text: '输出 ' }),
|
||||
outLbl,
|
||||
outVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-thinking' }),
|
||||
h('span', { text: '思考 ' }),
|
||||
thinkLbl,
|
||||
thinkVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { text: '调用 ' }),
|
||||
callsLbl,
|
||||
callsVal,
|
||||
]),
|
||||
]),
|
||||
@@ -405,7 +436,23 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: { nameEl, pctBadge, totalTokEl, costEl, segBar, inVal, cacheVal, outVal, thinkVal, callsVal },
|
||||
refs: {
|
||||
nameEl,
|
||||
pctBadge,
|
||||
totalTokEl,
|
||||
costEl,
|
||||
segBar,
|
||||
inLbl,
|
||||
cacheLbl,
|
||||
outLbl,
|
||||
thinkLbl,
|
||||
callsLbl,
|
||||
inVal,
|
||||
cacheVal,
|
||||
outVal,
|
||||
thinkVal,
|
||||
callsVal,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -413,6 +460,11 @@ export const ConsumptionView = defineComponent({
|
||||
* 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。
|
||||
*/
|
||||
function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) {
|
||||
patchText(refs.inLbl, t('cons.footInput'));
|
||||
patchText(refs.cacheLbl, t('cons.footCache'));
|
||||
patchText(refs.outLbl, t('cons.footOutput'));
|
||||
patchText(refs.thinkLbl, t('cons.footThinking'));
|
||||
patchText(refs.callsLbl, t('cons.footCalls'));
|
||||
const displayLabel = item.label || item.name || item.shortName || '—';
|
||||
patchText(refs.nameEl, displayLabel);
|
||||
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
|
||||
@@ -421,7 +473,16 @@ export const ConsumptionView = defineComponent({
|
||||
patchText(refs.pctBadge, `${share.toFixed(1)}%`);
|
||||
patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : '');
|
||||
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 =
|
||||
item.responseTokens != null
|
||||
@@ -446,11 +507,39 @@ export const ConsumptionView = defineComponent({
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
|
||||
let lastRenderedUsage = '';
|
||||
|
||||
/**
|
||||
* 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。
|
||||
*/
|
||||
function renderConsumptionData(slice) {
|
||||
if (!slice) return;
|
||||
const cons = slice.consumption || {};
|
||||
const preset =
|
||||
slice.range !== 'custom' && cons.presets?.[slice.range]
|
||||
? cons.presets[slice.range]
|
||||
: null;
|
||||
const acct = preset?.account || cons.account || {};
|
||||
const rangeInfo = cons.selectedRange || {};
|
||||
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs);
|
||||
const now = new Date();
|
||||
const currentMonthIdx = now.getMonth();
|
||||
const monthlyYear = cons.monthlyYear || now.getFullYear();
|
||||
const locale = i18nStore.getState().locale;
|
||||
// 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。
|
||||
const signature = JSON.stringify([
|
||||
locale, slice.range, slice.customStartMs, slice.customEndMs, slice.modelDisplayMode,
|
||||
slice.showUpstreamModel, slice.orchestratorIdMode, dateSpan,
|
||||
preset?.label || rangeInfo.label, acct,
|
||||
cons.trendSeries, slice.modelBreakdown, cons.sourcesBreakdown,
|
||||
monthlyYear, currentMonthIdx, cons.monthlySeries,
|
||||
]);
|
||||
if (signature === lastRenderedUsage) return;
|
||||
drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear });
|
||||
lastRenderedUsage = signature;
|
||||
}
|
||||
|
||||
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) {
|
||||
timeFilterSwitch.setValue(slice.range);
|
||||
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
|
||||
if (!hasUncommittedCustomDraft) {
|
||||
@@ -460,16 +549,8 @@ export const ConsumptionView = defineComponent({
|
||||
endPicker.setValue(draftEndMs);
|
||||
}
|
||||
|
||||
const cons = slice.consumption || {};
|
||||
const preset =
|
||||
slice.range !== 'custom' && cons.presets?.[slice.range]
|
||||
? cons.presets[slice.range]
|
||||
: null;
|
||||
const acct = preset?.account || cons.account || {};
|
||||
const rangeInfo = cons.selectedRange || {};
|
||||
|
||||
// 1. 同步用量概览矩阵与顶部 4 段比例条
|
||||
patchText(dateSpanBadge, formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs));
|
||||
patchText(dateSpanBadge, dateSpan);
|
||||
const totalTokens = Number(acct.totalTokens || 0);
|
||||
const inputTokens = Number(acct.inputTokens || 0);
|
||||
const cacheTokens = Number(acct.cacheReadTokens || 0);
|
||||
@@ -480,12 +561,12 @@ export const ConsumptionView = defineComponent({
|
||||
const savedCostUsd = Number(acct.savedCostUsd || 0);
|
||||
|
||||
patchText(heroTotalTokens, formatTokensPrecise(totalTokens));
|
||||
patchText(heroTotalCalls, `${acct.calls || 0} 次`);
|
||||
patchText(heroTotalCalls, t('cons.callsCount', { calls: acct.calls || 0 }));
|
||||
patchText(heroCostUsd, formatUsd(costUsd));
|
||||
patchText(heroCostCny, formatCnyApprox(costUsd));
|
||||
|
||||
patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`);
|
||||
patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`);
|
||||
patchText(cacheTokensEl, t('cons.cacheHitTokens', { tokens: formatTokensPrecise(cacheTokens) }));
|
||||
|
||||
let inPct = 0;
|
||||
let cachePct = 0;
|
||||
@@ -511,20 +592,25 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
patchText(inputSharePct, `${inPct}%`);
|
||||
patchText(inputMainTokens, formatTokensPrecise(inputTokens));
|
||||
patchText(inputSubText, '未命中缓存输入');
|
||||
patchText(inputSubText, t('cons.uncachedInput'));
|
||||
|
||||
patchText(cacheSharePct, `${cachePct}%`);
|
||||
patchText(cacheMainTokens, formatTokensPrecise(cacheTokens));
|
||||
patchText(
|
||||
cacheSubText,
|
||||
`节省 ${formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 })}`
|
||||
t('cons.savedCost', {
|
||||
cost: formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 }),
|
||||
})
|
||||
);
|
||||
|
||||
patchText(outputSharePct, `${outPct}%`);
|
||||
patchText(outputMainTokens, formatTokensPrecise(outputTokens));
|
||||
patchText(
|
||||
outputSubText,
|
||||
`回复 ${formatTokensPrecise(responseTokens)} · 思考 ${formatTokensPrecise(thinkingTokens)}`
|
||||
t('cons.replyAndThink', {
|
||||
resp: formatTokensPrecise(responseTokens),
|
||||
think: formatTokensPrecise(thinkingTokens),
|
||||
})
|
||||
);
|
||||
|
||||
overviewSegBar.update({
|
||||
@@ -534,44 +620,54 @@ export const ConsumptionView = defineComponent({
|
||||
thinkingTokens,
|
||||
});
|
||||
|
||||
// 2. 同步历史趋势交互式 SVG 面积图与粒度提示
|
||||
patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间');
|
||||
// 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与粒度提示
|
||||
const rangeBadgeText = isEnglishLocale()
|
||||
? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label ||
|
||||
t('cons.allTime')
|
||||
: preset?.label || rangeInfo.label || t('cons.allTime');
|
||||
patchText(trendRangeBadge, rangeBadgeText);
|
||||
const trendSeries = cons.trendSeries || [];
|
||||
const isHourlyTrend =
|
||||
trendSeries[0]?.granularity === 'hour' ||
|
||||
(trendSeries[0]?.label || '').includes(':');
|
||||
const isHeatmapTrend = !isHourlyTrend && trendSeries.length > HEATMAP_DAYS_THRESHOLD;
|
||||
patchText(
|
||||
trendGranularityHint,
|
||||
`${isHourlyTrend ? '按小时' : '按日'} (${trendSeries.length || 0}点) · 悬停查看`
|
||||
isHeatmapTrend
|
||||
? t('cons.trendHeatmapHint', { days: trendSeries.length })
|
||||
: isHourlyTrend
|
||||
? t('cons.trendPointsHintHourly', { points: trendSeries.length || 0 })
|
||||
: t('cons.trendPointsHintDaily', { points: trendSeries.length || 0 })
|
||||
);
|
||||
trendChart.update(trendSeries);
|
||||
|
||||
// 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账,遵循模型名称与 Orchestrator ID 格式设置)
|
||||
// 3. 同步热门模型列表(按最终展示名称去重归并后按总 Token 数降序排列并执行键值增量对账)
|
||||
const localeSig = i18nStore.getState().locale;
|
||||
const displaySettings = {
|
||||
modelDisplayMode: normalizeModelDisplayMode(
|
||||
slice.modelDisplayMode,
|
||||
slice.showUpstreamModel
|
||||
),
|
||||
showUpstreamModel: Boolean(slice.showUpstreamModel),
|
||||
orchestratorIdMode: slice.orchestratorIdMode,
|
||||
};
|
||||
const models = (slice.modelBreakdown || [])
|
||||
.slice()
|
||||
.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);
|
||||
|
||||
patchKeyedList(modelsListEl, models, {
|
||||
keyFn: (m) => m.label || m.shortName,
|
||||
sigFn: (m) => {
|
||||
const disp = resolveModelDisplayInfo(m, displaySettings, { preferLabelInShort: true });
|
||||
return `${disp.text}:${disp.title}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`;
|
||||
},
|
||||
keyFn: (m) => m.displayText || m.label || m.shortName,
|
||||
sigFn: (m) =>
|
||||
`${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
||||
createRow: createBreakdownItemRow,
|
||||
updateRow: (refs, m) => {
|
||||
const disp = resolveModelDisplayInfo(m, displaySettings, { preferLabelInShort: true });
|
||||
return updateBreakdownItemRow(
|
||||
updateRow: (refs, m) =>
|
||||
updateBreakdownItemRow(
|
||||
refs,
|
||||
{ ...m, label: disp.text, title: disp.title },
|
||||
{ ...m, label: m.displayText, title: m.displayTitle },
|
||||
modelsTotalTok,
|
||||
true
|
||||
);
|
||||
},
|
||||
),
|
||||
});
|
||||
|
||||
// 4. 同步数据来源列表
|
||||
@@ -579,14 +675,12 @@ export const ConsumptionView = defineComponent({
|
||||
const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0);
|
||||
patchKeyedList(sourcesListEl, sources, {
|
||||
keyFn: (s) => s.name,
|
||||
sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`,
|
||||
sigFn: (s) => `${localeSig}:${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`,
|
||||
createRow: createBreakdownItemRow,
|
||||
updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true),
|
||||
});
|
||||
|
||||
// 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度)
|
||||
const monthlyYear = cons.monthlyYear || new Date().getFullYear();
|
||||
const currentMonthIdx = new Date().getMonth();
|
||||
patchText(monthlyYearBadge, String(monthlyYear));
|
||||
const monthlySeries = cons.monthlySeries || [];
|
||||
const maxMonthTokens = Math.max(
|
||||
@@ -640,6 +734,10 @@ export const ConsumptionView = defineComponent({
|
||||
customEndMs: st.customEndMs,
|
||||
consumption: st.telemetry?.consumption,
|
||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||
modelDisplayMode: normalizeModelDisplayMode(
|
||||
st.telemetry?.settings?.modelDisplayMode,
|
||||
st.telemetry?.settings?.showUpstreamModel
|
||||
),
|
||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
|
||||
st.telemetry?.settings?.orchestratorIdMode
|
||||
@@ -647,7 +745,7 @@ export const ConsumptionView = defineComponent({
|
||||
}),
|
||||
(slice) => {
|
||||
latestSlice = slice;
|
||||
if (uiStore.getState().activeView !== 'consumption') {
|
||||
if (getVisibleMonitorView() !== 'consumption') {
|
||||
isDirty = true;
|
||||
return;
|
||||
}
|
||||
@@ -657,7 +755,7 @@ export const ConsumptionView = defineComponent({
|
||||
);
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
getVisibleMonitorView,
|
||||
(activeView) => {
|
||||
if (activeView === 'consumption' && isDirty) {
|
||||
isDirty = false;
|
||||
@@ -668,9 +766,51 @@ export const ConsumptionView = defineComponent({
|
||||
}
|
||||
);
|
||||
|
||||
function syncStaticLocaleLabels() {
|
||||
timeFilterSwitch.setProps({
|
||||
ariaLabel: t('cons.rangeAria'),
|
||||
options: getConsumptionTimeRangeOptions(),
|
||||
});
|
||||
patchText(applyCustomBtnLabel, t('cons.applyFilter'));
|
||||
patchText(rangeToSpan, t('cons.rangeTo'));
|
||||
patchText(overviewTitleSpan, t('cons.overviewTitle'));
|
||||
patchText(totalTokensLabel, t('cons.totalTokens'));
|
||||
patchText(estCostLabel, t('cons.estCost'));
|
||||
patchText(cacheHitRateLabel, t('cons.cacheHitRate'));
|
||||
patchText(newInputLabel, t('cons.newInput'));
|
||||
patchText(cacheReadLabel, t('cons.cacheRead'));
|
||||
patchText(outputUsageLabel, t('cons.outputUsage'));
|
||||
patchText(trendTitleSpan, t('cons.trendTitle'));
|
||||
patchText(modelsTitleSpan, t('cons.topModels'));
|
||||
patchText(sourcesTitleSpan, t('cons.clientSources'));
|
||||
patchText(monthlyTitleSpan, t('cons.monthlyTitle'));
|
||||
for (let i = 0; i < 12; i++) {
|
||||
patchText(monthlyCols[i].monthLabel, t('cons.monthLabel', { m: i + 1 }));
|
||||
}
|
||||
patchText(legInputSpan, t('cons.legInput'));
|
||||
patchText(legCacheSpan, t('cons.legCache'));
|
||||
patchText(legOutputSpan, t('cons.legOutput'));
|
||||
patchText(legThinkingSpan, t('cons.legThinking'));
|
||||
}
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
syncStaticLocaleLabels();
|
||||
if (getVisibleMonitorView() === 'consumption' && latestSlice) {
|
||||
isDirty = false;
|
||||
renderConsumptionData(latestSlice);
|
||||
} else {
|
||||
isDirty = true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsub();
|
||||
unsubView();
|
||||
unsubI18n();
|
||||
trendChart.destroy?.();
|
||||
timeFilterSwitch.destroy();
|
||||
startPicker.destroy();
|
||||
endPicker.destroy();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,685 +1,184 @@
|
||||
/**
|
||||
* @fileoverview View 4: SettingsView (系统设置视图).
|
||||
* 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板:
|
||||
* 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)、模型名称格式(精简代号 / 原始模型 ID)与 Orchestrator 系列 ID 格式;
|
||||
* 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序;
|
||||
* 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
||||
* @fileoverview View 4: Modular preferences ("常规" / "结构" / "账号" / "其他").
|
||||
* Orchestrates the four preference tabs
|
||||
* with top sub-navigation and a shared `CustomScrollbar` viewport.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import {
|
||||
DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||
normalizeClientOrchestratorIdMode,
|
||||
normalizeClientTopbarSlots,
|
||||
normalizeClientUpdateMode,
|
||||
saveSettingsPatch,
|
||||
telemetryStore,
|
||||
triggerCloudSync,
|
||||
triggerPluginUpdate,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { h, patchAttr } from '../core/domPatch.js';
|
||||
import { i18nStore, t } from '../i18n/index.js';
|
||||
import { telemetryStore } from '../store/telemetryStore.js';
|
||||
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
|
||||
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
|
||||
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
|
||||
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
|
||||
|
||||
/** 步骤明细表中的模型名称显示方式可选项 */
|
||||
const STEP_MODEL_DISPLAY_OPTIONS = [
|
||||
{ value: 'short', label: '精简代号 (如 argon-4-high)' },
|
||||
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
||||
];
|
||||
export const SHOW_ACCOUNT_TAB = false;
|
||||
|
||||
/** Orchestrator 系列模型 ID 显示方式可选项(独立于普通模型名称格式) */
|
||||
const ORCHESTRATOR_ID_DISPLAY_OPTIONS = [
|
||||
{ value: 'compact', label: '精简代号 (如 orchestrator-argon)' },
|
||||
{ value: 'full', label: '原始完整 ID (如 gemini-pro-orchestrator)' },
|
||||
];
|
||||
|
||||
/** 面板挂载模式可选项(顶部栏 + 侧边栏 vs 仅侧边栏) */
|
||||
const WINDOW_MOUNT_OPTIONS = [
|
||||
{ value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' },
|
||||
{ value: 'sidebar', label: '仅侧边栏' },
|
||||
];
|
||||
|
||||
/** 顶栏左侧实时运行会话入口显隐选项 */
|
||||
const TOPBAR_MULTI_TOGGLE_OPTIONS = [
|
||||
{ value: 'show', label: '显示' },
|
||||
{ value: 'hide', label: '隐藏' },
|
||||
];
|
||||
|
||||
/** 顶栏右侧精简胶囊三槽位可选指标项 */
|
||||
const TOPBAR_SLOT_OPTIONS = [
|
||||
{ value: 'context', label: '上下文占用 (%)' },
|
||||
{ value: 'tps', label: '输出速度 (TPS)' },
|
||||
{ value: 'ttft', label: '首字延迟 (TTFT)' },
|
||||
{ value: 'cost', label: '本次费用 ($)' },
|
||||
{ value: 'quota_auto', label: '自动紧俏额度' },
|
||||
{ value: 'gemini_5h', label: 'Gemini 5h 额度' },
|
||||
{ value: 'gemini_weekly', label: 'Gemini 周额度' },
|
||||
{ value: 'claude_5h', label: 'Claude 5h 额度' },
|
||||
{ value: 'claude_weekly', label: 'Claude 周额度' },
|
||||
{ value: 'none', label: '不显示' },
|
||||
];
|
||||
|
||||
/** 插件版本更新策略可选项(默认仅提示新版本、手动更新) */
|
||||
const AUTO_UPDATE_OPTIONS = [
|
||||
{ value: 'manual', label: '仅提示新版本,手动更新' },
|
||||
{ value: 'auto', label: '自动更新' },
|
||||
{ value: 'off', label: '关闭更新' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 格式化云端价格目录的最近同步时间或版本日期文本。
|
||||
*/
|
||||
function formatSyncTimeText(tsMs, updatedAt) {
|
||||
if (Number(tsMs) > 0) {
|
||||
const d = new Date(Number(tsMs));
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `更新于 ${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
if (updatedAt) {
|
||||
return `发布于 ${String(updatedAt).slice(0, 10)}`;
|
||||
}
|
||||
return '默认价格';
|
||||
function getSettingsSubTabOptions() {
|
||||
return [
|
||||
{ value: 'general', label: t('settings.subTab.general') },
|
||||
{ value: 'structure', label: t('settings.subTab.structure') },
|
||||
...(SHOW_ACCOUNT_TAB ? [{ value: 'account', label: t('settings.subTab.account') }] : []),
|
||||
{ value: 'other', label: t('settings.subTab.other') },
|
||||
];
|
||||
}
|
||||
|
||||
export const SettingsView = defineComponent({
|
||||
name: 'SettingsView',
|
||||
setup({ onCleanup }) {
|
||||
let draftShowUpstreamModel = false;
|
||||
let draftOrchestratorIdMode = 'compact';
|
||||
let draftPluginUpdateMode = 'manual';
|
||||
let draftEnableWindowOverlay = true;
|
||||
let draftShowTopbarMulti = true;
|
||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
let statusTimer = null;
|
||||
let topbarTimer = null;
|
||||
let cloudTimer = null;
|
||||
const initialSubTab = uiStore.getState().settingsSubTab || 'general';
|
||||
|
||||
const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
const topbarStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
|
||||
/** 在常规设置面板右上角展示短暂的保存状态提示 */
|
||||
function showSaveFeedback(text) {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
patchText(saveStatusText, text);
|
||||
if (text === '已保存' || text === '保存失败') {
|
||||
statusTimer = setTimeout(() => {
|
||||
statusTimer = null;
|
||||
patchText(saveStatusText, '');
|
||||
}, text === '保存失败' ? 2500 : 1500);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在顶部栏定制面板右上角展示短暂的状态提示 */
|
||||
function showTopbarFeedback(text, autoClearMs = 1500) {
|
||||
if (topbarTimer) {
|
||||
clearTimeout(topbarTimer);
|
||||
topbarTimer = null;
|
||||
}
|
||||
patchText(topbarStatusText, text);
|
||||
if (autoClearMs > 0) {
|
||||
topbarTimer = setTimeout(() => {
|
||||
topbarTimer = null;
|
||||
patchText(topbarStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在云端同步面板右上角展示同步或更新进度提示 */
|
||||
function showCloudFeedback(text, autoClearMs = 3500) {
|
||||
if (cloudTimer) {
|
||||
clearTimeout(cloudTimer);
|
||||
cloudTimer = null;
|
||||
}
|
||||
patchText(cloudStatusMsg, text);
|
||||
if (autoClearMs > 0) {
|
||||
cloudTimer = setTimeout(() => {
|
||||
cloudTimer = null;
|
||||
patchText(cloudStatusMsg, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 面板 1:常规设置 ---
|
||||
const windowMountSelect = CustomSelect({
|
||||
modelValue: 'dual',
|
||||
icon: 'dock',
|
||||
options: WINDOW_MOUNT_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextEnable = val !== 'sidebar';
|
||||
draftEnableWindowOverlay = nextEnable;
|
||||
windowMountSelect.setValue(nextEnable ? 'dual' : 'sidebar');
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
enableWindowOverlay: nextEnable,
|
||||
});
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
const subNavSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.subTab.aria'),
|
||||
modelValue: initialSubTab,
|
||||
options: getSettingsSubTabOptions(),
|
||||
onUpdateModelValue: (nextSubTab) => {
|
||||
uiStore.setState({ settingsSubTab: nextSubTab }, { sync: true });
|
||||
},
|
||||
});
|
||||
|
||||
const stepModelSelect = CustomSelect({
|
||||
modelValue: 'short',
|
||||
icon: 'table',
|
||||
options: STEP_MODEL_DISPLAY_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextUpstream = val === 'upstream';
|
||||
draftShowUpstreamModel = nextUpstream;
|
||||
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showUpstreamModel: nextUpstream,
|
||||
});
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
},
|
||||
});
|
||||
const subNavBar = h('div', { className: 'settings-subnav-bar' }, [subNavSwitch.el]);
|
||||
|
||||
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' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
h('span', { text: '常规设置' }),
|
||||
]),
|
||||
saveStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '面板挂载方式' }),
|
||||
windowMountSelect.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '模型名称格式' }),
|
||||
stepModelSelect.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: 'Orchestrator 系列 ID' }),
|
||||
orchestratorIdSelect.el,
|
||||
]),
|
||||
]);
|
||||
|
||||
// --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) ---
|
||||
const multiSessionToggle = SegmentedControl({
|
||||
ariaLabel: '实时运行会话开关',
|
||||
modelValue: 'show',
|
||||
options: TOPBAR_MULTI_TOGGLE_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextShow = val !== 'hide';
|
||||
draftShowTopbarMulti = nextShow;
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showTopbarMultiSession: nextShow,
|
||||
});
|
||||
showTopbarFeedback('已保存', 1500);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
async function persistTopbarSlots(nextRawSlots, noticeText = '') {
|
||||
const normalized = normalizeClientTopbarSlots(nextRawSlots);
|
||||
draftTopbarSlots = normalized;
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback(noticeText || '保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
topbarCapsuleSlots: normalized,
|
||||
});
|
||||
showTopbarFeedback(noticeText || '已保存', noticeText ? 2000 : 1500);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
let viewScrollbar = null;
|
||||
const refreshScroll = () => {
|
||||
if (viewScrollbar) {
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
};
|
||||
|
||||
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
|
||||
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
|
||||
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
|
||||
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
|
||||
|
||||
let showingAccount = false;
|
||||
function applyActiveSubTab(subTab, activeView) {
|
||||
const target =
|
||||
subTab === 'structure' ||
|
||||
subTab === 'other' ||
|
||||
(SHOW_ACCOUNT_TAB && subTab === 'account')
|
||||
? subTab
|
||||
: 'general';
|
||||
subNavSwitch.setValue(target);
|
||||
patchAttr(generalTab.el, 'hidden', target !== 'general');
|
||||
patchAttr(structureTab.el, 'hidden', target !== 'structure');
|
||||
patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure');
|
||||
patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
|
||||
patchAttr(otherTab.el, 'hidden', target !== 'other');
|
||||
const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
|
||||
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
|
||||
showingAccount = nextShowingAccount;
|
||||
refreshScroll();
|
||||
}
|
||||
|
||||
function handleSlotMetricChange(slotIndex, nextVal) {
|
||||
const candidate = [...draftTopbarSlots];
|
||||
candidate[slotIndex] = nextVal;
|
||||
const wouldAllBeHidden = candidate.every((item) => item === 'none');
|
||||
void persistTopbarSlots(
|
||||
candidate,
|
||||
wouldAllBeHidden ? '至少保留 1 项显示' : ''
|
||||
);
|
||||
}
|
||||
|
||||
function swapTopbarSlots(idxA, idxB) {
|
||||
if (idxA < 0 || idxA > 2 || idxB < 0 || idxB > 2 || idxA === idxB) return;
|
||||
const candidate = [...draftTopbarSlots];
|
||||
const temp = candidate[idxA];
|
||||
candidate[idxA] = candidate[idxB];
|
||||
candidate[idxB] = temp;
|
||||
void persistTopbarSlots(candidate);
|
||||
}
|
||||
|
||||
const slotSelects = [0, 1, 2].map((idx) =>
|
||||
CustomSelect({
|
||||
modelValue: draftTopbarSlots[idx],
|
||||
options: TOPBAR_SLOT_OPTIONS,
|
||||
onUpdateModelValue: (val) => handleSlotMetricChange(idx, val),
|
||||
})
|
||||
);
|
||||
|
||||
const slotRows = [0, 1, 2].map((idx) => {
|
||||
const upBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
disabled: idx === 0,
|
||||
'aria-label': `槽位 ${idx + 1} 左移`,
|
||||
title: idx === 0 ? '已在最左' : '上移 (在顶栏靠左)',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
swapTopbarSlots(idx, idx - 1);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-up', { size: 12 })]
|
||||
);
|
||||
|
||||
const downBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
disabled: idx === 2,
|
||||
'aria-label': `槽位 ${idx + 1} 右移`,
|
||||
title: idx === 2 ? '已在最右' : '下移 (在顶栏靠右)',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
swapTopbarSlots(idx, idx + 1);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-down', { size: 12 })]
|
||||
);
|
||||
|
||||
return h('div', { className: 'topbar-slot-row', 'data-slot-row': String(idx) }, [
|
||||
h('span', { className: 'slot-index-badge', text: String(idx + 1) }),
|
||||
slotSelects[idx].el,
|
||||
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn]),
|
||||
]);
|
||||
});
|
||||
|
||||
const resetTopbarBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm',
|
||||
disabled: true,
|
||||
onClick: async () => {
|
||||
draftShowTopbarMulti = true;
|
||||
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||
});
|
||||
showTopbarFeedback('已恢复默认', 1600);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
},
|
||||
[h('span', { text: '恢复默认' })]
|
||||
);
|
||||
|
||||
function syncTopbarControls() {
|
||||
multiSessionToggle.setValue(draftShowTopbarMulti ? 'show' : 'hide');
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
slotSelects[i].setValue(draftTopbarSlots[i]);
|
||||
}
|
||||
const isDefault =
|
||||
draftShowTopbarMulti === true &&
|
||||
draftTopbarSlots[0] === DEFAULT_CLIENT_TOPBAR_SLOTS[0] &&
|
||||
draftTopbarSlots[1] === DEFAULT_CLIENT_TOPBAR_SLOTS[1] &&
|
||||
draftTopbarSlots[2] === DEFAULT_CLIENT_TOPBAR_SLOTS[2];
|
||||
patchAttr(resetTopbarBtn, 'disabled', isDefault);
|
||||
}
|
||||
|
||||
const topbarPanel = h('section', { className: 'panel topbar-config-panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('dock', { size: 13 }),
|
||||
h('span', { text: '顶部栏定制' }),
|
||||
]),
|
||||
h('span', { className: 'topbar-header-right' }, [topbarStatusText, resetTopbarBtn]),
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
h('span', { className: 'form-label', text: '实时运行会话' }),
|
||||
multiSessionToggle.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '胶囊数值与顺序 (左 → 右)' }),
|
||||
h('div', { className: 'topbar-slot-list' }, slotRows),
|
||||
]),
|
||||
]);
|
||||
|
||||
// --- 面板 3:版本更新面板 ---
|
||||
const autoUpdateSelect = CustomSelect({
|
||||
modelValue: 'manual',
|
||||
icon: 'refresh',
|
||||
options: AUTO_UPDATE_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientUpdateMode(val);
|
||||
draftPluginUpdateMode = nextMode;
|
||||
autoUpdateSelect.setValue(nextMode);
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
showCloudFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
pluginUpdateMode: nextMode,
|
||||
autoUpdatePlugin: nextMode === 'auto',
|
||||
});
|
||||
showCloudFeedback('已保存', 1800);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
showCloudFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.4' });
|
||||
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
|
||||
|
||||
const syncPricingBtnText = h('span', { text: '更新价格表' });
|
||||
const syncPricingBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(syncPricingBtn, 'disabled', true);
|
||||
patchText(syncPricingBtnText, '更新中…');
|
||||
showCloudFeedback('正在同步价格表…', 0);
|
||||
try {
|
||||
const res = await triggerCloudSync();
|
||||
const cs = res?.cloudStatus;
|
||||
if (res?.ok && cs) {
|
||||
showCloudFeedback(`价格表已更新 (${cs.modelCount} 个模型)`, 3500);
|
||||
} else {
|
||||
showCloudFeedback(cs?.lastSyncError || '连接超时,使用本地价格表', 4500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || '同步失败,使用本地价格表', 4500);
|
||||
} finally {
|
||||
patchAttr(syncPricingBtn, 'disabled', false);
|
||||
patchText(syncPricingBtnText, '更新价格表');
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 12 }), syncPricingBtnText]
|
||||
);
|
||||
|
||||
const updatePluginBtnText = h('span', { text: '检查更新' });
|
||||
const updatePluginBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(updatePluginBtn, 'disabled', true);
|
||||
try {
|
||||
if (!latestCloudStatus?.updateAvailable) {
|
||||
patchText(updatePluginBtnText, '检查中…');
|
||||
showCloudFeedback('正在检查新版本…', 0);
|
||||
const syncRes = await triggerCloudSync();
|
||||
const cs = syncRes?.cloudStatus || latestCloudStatus;
|
||||
if (cs) {
|
||||
latestCloudStatus = cs;
|
||||
renderCloudStatus(cs);
|
||||
}
|
||||
if (!syncRes?.ok && cs?.lastSyncError) {
|
||||
showCloudFeedback(`检查失败:${cs.lastSyncError}`, 5000);
|
||||
return;
|
||||
}
|
||||
if (!cs?.updateAvailable) {
|
||||
const curVer = cs?.currentPluginVersion || '1.4.4';
|
||||
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
|
||||
return;
|
||||
}
|
||||
}
|
||||
patchText(updatePluginBtnText, '更新中…');
|
||||
showCloudFeedback('正在下载更新…', 0);
|
||||
const res = await triggerPluginUpdate();
|
||||
if (res?.cloudStatus) {
|
||||
latestCloudStatus = res.cloudStatus;
|
||||
}
|
||||
if (res?.ok) {
|
||||
showCloudFeedback(res.message || '更新完成,正在重启面板…', 5000);
|
||||
} else {
|
||||
showCloudFeedback(res?.message || '未执行更新', 5500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || '更新失败', 5000);
|
||||
} finally {
|
||||
patchAttr(updatePluginBtn, 'disabled', false);
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText]
|
||||
);
|
||||
|
||||
const cloudPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('bolt', { size: 13 }),
|
||||
h('span', { text: '版本更新' }),
|
||||
]),
|
||||
cloudStatusMsg,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '更新方式' }),
|
||||
autoUpdateSelect.el,
|
||||
]),
|
||||
h('div', { className: 'dual-grid' }, [
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('span', { className: 'cell-label', text: '价格表' }),
|
||||
pricingCountVal,
|
||||
pricingSyncSub,
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('span', { className: 'cell-label', text: '当前版本' }),
|
||||
versionVal,
|
||||
versionSub,
|
||||
]),
|
||||
]),
|
||||
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
||||
]);
|
||||
|
||||
const settingsInner = h(
|
||||
const contentContainer = h(
|
||||
'div',
|
||||
{
|
||||
style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;',
|
||||
},
|
||||
[generalPanel, topbarPanel, cloudPanel]
|
||||
{},
|
||||
SHOW_ACCOUNT_TAB
|
||||
? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
|
||||
: [generalTab.el, structureTab.el, otherTab.el]
|
||||
);
|
||||
const viewScrollbar = CustomScrollbar({
|
||||
contentEl: settingsInner,
|
||||
viewScrollbar = CustomScrollbar({
|
||||
contentEl: contentContainer,
|
||||
className: 'view-pane',
|
||||
});
|
||||
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
applyActiveSubTab(initialSubTab, uiStore.getState().activeView);
|
||||
|
||||
/** 将后端返回的最新设置同步至表单控件 */
|
||||
function renderSettings(settings) {
|
||||
if (!settings) return;
|
||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
|
||||
draftPluginUpdateMode = normalizeClientUpdateMode(
|
||||
settings.pluginUpdateMode,
|
||||
settings.autoUpdatePlugin
|
||||
);
|
||||
draftEnableWindowOverlay = settings.enableWindowOverlay !== false;
|
||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
const rootEl = h('div', { className: 'settings-view-root' }, [
|
||||
subNavBar,
|
||||
structureTab.refs.thirdNavBar,
|
||||
viewScrollbar.el,
|
||||
]);
|
||||
|
||||
windowMountSelect.setValue(draftEnableWindowOverlay ? 'dual' : 'sidebar');
|
||||
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
||||
orchestratorIdSelect.setValue(draftOrchestratorIdMode);
|
||||
autoUpdateSelect.setValue(draftPluginUpdateMode);
|
||||
syncTopbarControls();
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
|
||||
/** 将云端价格表统计与插件版本对比状态同步至云端面板 */
|
||||
function renderCloudStatus(cs) {
|
||||
if (!cs) return;
|
||||
const srcLabel =
|
||||
cs.source === 'remote'
|
||||
? '云端同步'
|
||||
: cs.source === 'local'
|
||||
? '本地文件'
|
||||
: '内置默认';
|
||||
patchText(pricingCountVal, `${cs.modelCount || 0} 个模型`);
|
||||
patchText(
|
||||
pricingSyncSub,
|
||||
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||
);
|
||||
|
||||
const curVer = cs.currentPluginVersion || '1.4.4';
|
||||
const latVer = cs.latestPluginVersion || curVer;
|
||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||
patchText(versionVal, `v${curVer}`);
|
||||
if (cs.updateAvailable && draftPluginUpdateMode !== 'off') {
|
||||
patchText(versionSub, `可升级至 v${latVer} (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': true });
|
||||
patchText(updatePluginBtnText, `升级至 v${latVer}`);
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false });
|
||||
} else if (draftPluginUpdateMode === 'off') {
|
||||
patchText(versionSub, `已关闭更新提醒 (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(updatePluginBtnText, cs.updateAvailable ? `手动升级 v${latVer}` : '检查更新');
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
function syncActiveTab() {
|
||||
const ui = uiStore.getState();
|
||||
const { settingsSubTab } = ui;
|
||||
if (getVisibleMonitorView(ui) !== 'settings') return;
|
||||
const telemetry = telemetryStore.getState().telemetry;
|
||||
const settings = telemetry?.settings;
|
||||
if (settingsSubTab === 'structure') {
|
||||
if (settings) structureTab.refs.renderSettings(settings);
|
||||
} else if (settingsSubTab === 'other') {
|
||||
if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []);
|
||||
} else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') {
|
||||
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
|
||||
} else {
|
||||
patchText(versionSub, `已是最新 (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(updatePluginBtnText, '检查更新');
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
if (settings) generalTab.refs.renderSettings(settings);
|
||||
if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus);
|
||||
}
|
||||
|
||||
if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) {
|
||||
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
||||
}
|
||||
viewScrollbar.refresh();
|
||||
refreshScroll();
|
||||
}
|
||||
|
||||
const unsub = telemetryStore.subscribe(
|
||||
const unsubTelemetry = telemetryStore.subscribe(
|
||||
(st) => ({
|
||||
settings: st.telemetry?.settings,
|
||||
cloudStatus: st.telemetry?.cloudStatus,
|
||||
contextWindowModels: st.telemetry?.contextWindowModels,
|
||||
account: st.telemetry?.account,
|
||||
quotas: st.telemetry?.quotas,
|
||||
}),
|
||||
syncActiveTab
|
||||
);
|
||||
|
||||
const unsubUi = uiStore.subscribe(
|
||||
(st) => ({
|
||||
activeView: getVisibleMonitorView(st),
|
||||
settingsSubTab: st.settingsSubTab,
|
||||
}),
|
||||
(slice) => {
|
||||
latestSettings = slice.settings;
|
||||
latestCloudStatus = slice.cloudStatus;
|
||||
renderSettings(slice.settings);
|
||||
if (uiStore.getState().activeView === 'settings') {
|
||||
renderCloudStatus(slice.cloudStatus);
|
||||
}
|
||||
applyActiveSubTab(slice.settingsSubTab, slice.activeView);
|
||||
syncActiveTab();
|
||||
}
|
||||
);
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
(activeView) => {
|
||||
if (activeView === 'settings') {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
subNavSwitch.setProps({
|
||||
modelValue: uiStore.getState().settingsSubTab || 'general',
|
||||
options: getSettingsSubTabOptions(),
|
||||
});
|
||||
generalTab.refs.refreshLabels();
|
||||
structureTab.refs.refreshLabels();
|
||||
accountTab.refs.refreshLabels();
|
||||
otherTab.refs.refreshLabels();
|
||||
refreshScroll();
|
||||
}
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
if (statusTimer) clearTimeout(statusTimer);
|
||||
if (topbarTimer) clearTimeout(topbarTimer);
|
||||
if (cloudTimer) clearTimeout(cloudTimer);
|
||||
unsub();
|
||||
unsubView();
|
||||
windowMountSelect.destroy();
|
||||
stepModelSelect.destroy();
|
||||
orchestratorIdSelect.destroy();
|
||||
multiSessionToggle.destroy();
|
||||
for (const sel of slotSelects) {
|
||||
sel.destroy();
|
||||
}
|
||||
autoUpdateSelect.destroy();
|
||||
unsubTelemetry();
|
||||
unsubUi();
|
||||
unsubI18n();
|
||||
subNavSwitch.destroy();
|
||||
generalTab.destroy();
|
||||
structureTab.destroy();
|
||||
accountTab.destroy();
|
||||
otherTab.destroy();
|
||||
viewScrollbar.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: viewScrollbar.el,
|
||||
el: rootEl,
|
||||
refs: {
|
||||
windowMountSelect,
|
||||
stepModelSelect,
|
||||
orchestratorIdSelect,
|
||||
multiSessionToggle,
|
||||
slotSelects,
|
||||
resetTopbarBtn,
|
||||
autoUpdateSelect,
|
||||
subNavSwitch,
|
||||
generalTab,
|
||||
structureTab,
|
||||
accountTab,
|
||||
otherTab,
|
||||
viewScrollbar,
|
||||
// Convenience aliases for external callers / tests
|
||||
windowMountSelect: structureTab.refs.windowMountSelect,
|
||||
multiSessionToggle: structureTab.refs.multiSessionToggle,
|
||||
topbarSlotsList: structureTab.refs.topbarSlotsList,
|
||||
stepModelSelect: otherTab.refs.stepModelSelect,
|
||||
orchestratorIdSelect: otherTab.refs.orchestratorIdSelect,
|
||||
autoUpdateSelect: generalTab.refs.autoUpdateSelect,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,235 @@
|
||||
/** @fileoverview Saved account credentials and the host's active account quota. */
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchKeyedList, patchText } from '../../core/domPatch.js';
|
||||
import { callSidecarApi } from '../../core/httpClient.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { fetchTelemetry } from '../../store/telemetryStore.js';
|
||||
|
||||
const key = (name) => `settings.account.${name}`;
|
||||
const errors = new Set([
|
||||
'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
|
||||
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
|
||||
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
|
||||
'oauthUnavailable', 'quotaUnavailable',
|
||||
]);
|
||||
|
||||
function renderQuotaRows(container, quotaPools) {
|
||||
const locale = getEffectiveLocale();
|
||||
const pools = quotaPools.filter((pool) => Number.isFinite(pool.remainingPct) || Number.isFinite(pool.weeklyRemainingPct));
|
||||
patchKeyedList(container, pools, {
|
||||
keyFn: (pool) => pool.poolKey || pool.poolLabel,
|
||||
sigFn: (pool) => JSON.stringify([locale, pool.poolLabel, pool.remainingPct, pool.weeklyRemainingPct]),
|
||||
createRow: () => {
|
||||
const label = h('span');
|
||||
const remaining = h('span', { className: 'settings-account-quota' });
|
||||
return { el: h('div', { className: 'settings-action-block' }, [label, remaining]), refs: { label, remaining } };
|
||||
},
|
||||
updateRow: ({ label, remaining }, pool) => {
|
||||
patchText(label, pool.poolLabel || pool.poolKey);
|
||||
const values = [];
|
||||
if (Number.isFinite(pool.remainingPct)) values.push(t(key('quota5h'), { percent: pool.remainingPct }));
|
||||
if (Number.isFinite(pool.weeklyRemainingPct)) values.push(t(key('quotaWeekly'), { percent: pool.weeklyRemainingPct }));
|
||||
patchText(remaining, values.join(' · '));
|
||||
},
|
||||
});
|
||||
return pools.length;
|
||||
}
|
||||
|
||||
export const SettingsAccountTab = defineComponent({
|
||||
name: 'SettingsAccountTab',
|
||||
setup({ props, onCleanup }) {
|
||||
let account = null;
|
||||
let quotas = null;
|
||||
let accounts = [];
|
||||
let selectedEmail = '';
|
||||
let supported = null;
|
||||
let operation = '';
|
||||
let status = '';
|
||||
let disposed = false;
|
||||
const savedQuotas = new Map();
|
||||
|
||||
const title = h('span', { className: 'panel-title' });
|
||||
const identityLabel = h('div', { className: 'settings-action-title' });
|
||||
const identity = h('div', { className: 'settings-action-desc settings-account-identity' });
|
||||
const plan = h('div', { className: 'settings-action-desc' });
|
||||
const quotaTitle = h('div', { className: 'settings-action-title' });
|
||||
const quotaRows = h('div', { className: 'settings-account-list' });
|
||||
const quotaMessage = h('div', { className: 'settings-action-desc' });
|
||||
const savedTitle = h('span', { className: 'panel-title' });
|
||||
const savedRows = h('div', { className: 'settings-account-list' });
|
||||
const savedMessage = h('div', { className: 'settings-action-desc' });
|
||||
const pending = h('div', { className: 'settings-action-desc', role: 'status' });
|
||||
const feedback = h('div', { className: 'settings-action-desc', role: 'status' });
|
||||
const capture = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('capture') });
|
||||
const reload = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('list') });
|
||||
const credentialLabel = h('span');
|
||||
const importHint = h('div', { className: 'settings-action-desc' });
|
||||
const credential = h('input', { type: 'password', required: true, autocomplete: 'off', spellcheck: 'false', maxlength: 16384 });
|
||||
const save = h('button', { type: 'submit', className: 'btn-secondary' });
|
||||
const form = h('form', { className: 'settings-account-form', autocomplete: 'off', onSubmit: importCredential }, [
|
||||
h('label', {}, [credentialLabel, credential]),
|
||||
importHint,
|
||||
save,
|
||||
]);
|
||||
|
||||
function render() {
|
||||
const signedIn = account?.status === 'signedIn';
|
||||
const activeEmail = signedIn ? account.email?.trim().toLowerCase() : '';
|
||||
const canWrite = supported === true && !operation;
|
||||
const locale = getEffectiveLocale();
|
||||
patchText(title, t(key('current')));
|
||||
patchText(identityLabel, t(key('email')));
|
||||
patchText(identity, signedIn ? account.email || account.name :
|
||||
t(key(account?.status === 'signedOut' ? 'signedOut' : 'unknown')));
|
||||
patchText(plan, signedIn ? account.tierName || account.planName || '' : '');
|
||||
patchAttr(plan, 'hidden', !plan.textContent);
|
||||
|
||||
patchText(quotaTitle, t(key('quota')));
|
||||
const poolCount = renderQuotaRows(quotaRows, signedIn ? quotas?.pools || [] : []);
|
||||
patchText(quotaMessage, t(key(poolCount ? 'quotaStale' : 'noQuota')));
|
||||
patchAttr(quotaMessage, 'hidden', poolCount > 0 && !quotas?.meta?.isStale);
|
||||
|
||||
patchText(savedTitle, t(key('savedCredentials')));
|
||||
patchText(capture, t(key('capture')));
|
||||
patchText(reload, t(key('reload')));
|
||||
patchText(save, t(key('save')));
|
||||
patchText(credentialLabel, t(key('credential')));
|
||||
patchText(importHint, t(key('importHint')));
|
||||
patchAttr(capture, 'disabled', !canWrite || !activeEmail);
|
||||
patchAttr(reload, 'disabled', Boolean(operation));
|
||||
patchAttr(form, 'hidden', supported === false);
|
||||
patchAttr(save, 'disabled', !canWrite);
|
||||
patchAttr(credential, 'disabled', !canWrite);
|
||||
patchText(savedMessage, t(key(supported === null ? 'loading' : 'empty')));
|
||||
patchAttr(savedMessage, 'hidden', accounts.length > 0 || supported === false || Boolean(status));
|
||||
const message = status || (operation === 'switch' ? 'switching' : operation === 'quota' ? 'loadingQuota' :
|
||||
operation === 'save' || operation === 'capture' ? 'verifying' : '');
|
||||
patchText(feedback, message ? t(key(message)) : '');
|
||||
patchAttr(feedback, 'hidden', !message);
|
||||
const waiting = selectedEmail && activeEmail !== selectedEmail;
|
||||
patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : '');
|
||||
patchAttr(pending, 'hidden', !waiting);
|
||||
|
||||
patchKeyedList(savedRows, accounts, {
|
||||
keyFn: (addr) => addr,
|
||||
sigFn: (addr) => JSON.stringify([locale, activeEmail, selectedEmail, canWrite, savedQuotas.get(addr)]),
|
||||
createRow: (addr) => {
|
||||
const state = h('div', { className: 'settings-action-desc' });
|
||||
const select = h('button', {
|
||||
type: 'button', className: 'btn-secondary settings-account-switch', onClick: () => request('switch', { email: addr }),
|
||||
});
|
||||
const remove = h('button', {
|
||||
type: 'button', className: 'btn-secondary', onClick: () => request('remove', { email: addr }),
|
||||
});
|
||||
const loadQuota = h('button', {
|
||||
type: 'button', className: 'btn-secondary settings-account-load-quota', onClick: () => request('quota', { email: addr }),
|
||||
});
|
||||
const rows = h('div', { className: 'settings-account-list' });
|
||||
const empty = h('div', { className: 'settings-action-desc' });
|
||||
return {
|
||||
el: h('div', { className: 'settings-account-entry' }, [
|
||||
h('div', { className: 'settings-action-block' }, [
|
||||
h('div', { className: 'settings-action-info' }, [h('div', { className: 'settings-account-identity', text: addr }), state]),
|
||||
h('div', { className: 'settings-account-buttons' }, [loadQuota, select, remove]),
|
||||
]), rows, empty,
|
||||
]),
|
||||
refs: { state, select, remove, loadQuota, rows, empty },
|
||||
};
|
||||
},
|
||||
updateRow: (row, addr) => {
|
||||
const active = addr === activeEmail;
|
||||
const written = addr === selectedEmail && !active;
|
||||
patchText(row.state, active ? t(key('active')) : written ? t(key('written')) : '');
|
||||
patchAttr(row.state, 'hidden', !active && !written);
|
||||
patchText(row.select, t(key('switch')));
|
||||
patchText(row.remove, t(key('remove')));
|
||||
patchText(row.loadQuota, t(key('loadQuota')));
|
||||
patchAttr(row.select, 'disabled', !canWrite);
|
||||
patchAttr(row.remove, 'disabled', !canWrite);
|
||||
patchAttr(row.loadQuota, 'disabled', !canWrite);
|
||||
const cached = savedQuotas.get(addr);
|
||||
const count = renderQuotaRows(row.rows, cached || []);
|
||||
patchText(row.empty, t(key('emptyCredentialQuota')));
|
||||
patchAttr(row.empty, 'hidden', !cached || count > 0);
|
||||
},
|
||||
});
|
||||
props.onLayoutChange?.();
|
||||
}
|
||||
|
||||
async function request(action, fields) {
|
||||
if (operation) return;
|
||||
operation = action;
|
||||
status = '';
|
||||
render();
|
||||
try {
|
||||
const result = action === 'list'
|
||||
? await callSidecarApi('/api/accounts')
|
||||
: await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields }, cdpTimeoutMs: 40000 });
|
||||
if (disposed) return;
|
||||
if (result?.error) {
|
||||
if (result.error === 'unsupported') supported = false;
|
||||
status = errors.has(result.error) ? result.error : 'storeFailed';
|
||||
return;
|
||||
}
|
||||
if (action === 'quota') {
|
||||
savedQuotas.set(result.email, result.pools);
|
||||
return;
|
||||
}
|
||||
supported = result?.supported === true;
|
||||
accounts = result?.accounts || [];
|
||||
selectedEmail = result?.selectedEmail || '';
|
||||
if (action === 'save' || action === 'capture') status = 'saved';
|
||||
if (action === 'remove') {
|
||||
savedQuotas.delete(fields.email);
|
||||
status = 'removed';
|
||||
}
|
||||
if (action === 'switch') {
|
||||
status = result.confirmed ? 'switched' : '';
|
||||
void fetchTelemetry({ force: true }).catch(() => {});
|
||||
}
|
||||
} catch {
|
||||
status = 'storeFailed';
|
||||
} finally {
|
||||
operation = '';
|
||||
if (!disposed) render();
|
||||
}
|
||||
}
|
||||
|
||||
function importCredential(event) {
|
||||
event.preventDefault();
|
||||
if (operation) return;
|
||||
const input = credential.value;
|
||||
credential.value = '';
|
||||
void request('save', { credential: input });
|
||||
}
|
||||
|
||||
function renderAccount(value, quotaData) {
|
||||
if (account === value && quotas === quotaData) return;
|
||||
account = value;
|
||||
quotas = quotaData;
|
||||
render();
|
||||
}
|
||||
|
||||
const root = h('div', { className: 'settings-tab-stack' }, [
|
||||
h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [title]),
|
||||
h('div', { className: 'settings-action-block' }, [
|
||||
h('div', { className: 'settings-action-info' }, [identityLabel, identity, plan]),
|
||||
]),
|
||||
quotaTitle, quotaRows, quotaMessage, pending,
|
||||
]),
|
||||
h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [savedTitle]),
|
||||
h('div', { className: 'settings-account-buttons' }, [capture, reload]),
|
||||
savedRows, savedMessage, form, feedback,
|
||||
]),
|
||||
]);
|
||||
render();
|
||||
onCleanup(() => {
|
||||
disposed = true;
|
||||
credential.value = '';
|
||||
});
|
||||
return { el: root, refs: { renderAccount, refreshLabels: render, load: () => request('list') } };
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,479 @@
|
||||
/**
|
||||
* @fileoverview Preferences Tab 1: `SettingsGeneralTab.js` ("常规").
|
||||
* Manages UI Language (`zh-CN` / `en-US` / `auto`), Theme Accent (`host` + 6 swatches),
|
||||
* Panel Font Scale (`sm` / `md` / `lg` / `xl`), Pricing Sync, and Plugin Updates.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
normalizeClientFontScale,
|
||||
normalizeClientThemeAccent,
|
||||
} from '../../core/appearance.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { normalizeI18nLanguage, setI18nLanguage, t } from '../../i18n/index.js';
|
||||
import {
|
||||
normalizeClientUpdateMode,
|
||||
saveSettingsPatch,
|
||||
triggerCloudSync,
|
||||
triggerPluginUpdate,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { ThemeColorPicker } from '../../components/settings/ThemeColorPicker.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||
|
||||
function getLanguageOptions() {
|
||||
return [
|
||||
{ value: 'zh-CN', label: t('settings.gen.langZh') },
|
||||
{ value: 'en-US', label: t('settings.gen.langEn') },
|
||||
{ value: 'auto', label: t('settings.gen.langAuto') },
|
||||
];
|
||||
}
|
||||
|
||||
function getFontScaleOptions() {
|
||||
return [
|
||||
{ value: 'sm', label: t('settings.gen.fontSm') },
|
||||
{ value: 'md', label: t('settings.gen.fontMd') },
|
||||
{ value: 'lg', label: t('settings.gen.fontLg') },
|
||||
{ value: 'xl', label: t('settings.gen.fontXl') },
|
||||
];
|
||||
}
|
||||
|
||||
function getUpdateModeOptions() {
|
||||
return [
|
||||
{ value: 'manual', label: t('settings.gen.updateManual') },
|
||||
{ value: 'auto', label: t('settings.gen.updateAuto') },
|
||||
{ value: 'off', label: t('settings.gen.updateOff') },
|
||||
];
|
||||
}
|
||||
|
||||
function formatCloudSyncTimeText(tsMs, updatedAt) {
|
||||
if (Number(tsMs) > 0) {
|
||||
const d = new Date(Number(tsMs));
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
const timeStr = `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
return t('settings.gen.syncAt', { time: timeStr });
|
||||
}
|
||||
if (updatedAt) {
|
||||
return t('settings.gen.pubAt', { date: String(updatedAt).slice(0, 10) });
|
||||
}
|
||||
return t('settings.gen.defaultPricing');
|
||||
}
|
||||
|
||||
export const SettingsGeneralTab = defineComponent({
|
||||
name: 'SettingsGeneralTab',
|
||||
setup({ props, onCleanup }) {
|
||||
let draftLanguage = 'zh-CN';
|
||||
let draftThemeAccent = 'host';
|
||||
let draftFontScale = 'md';
|
||||
let draftPluginUpdateMode = 'manual';
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
let appearanceTimer = null;
|
||||
let cloudTimer = null;
|
||||
|
||||
const appearanceStatusText = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
const cloudStatusMsg = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
|
||||
function showAppearanceFeedback(text, autoClearMs = 1500) {
|
||||
if (appearanceTimer) {
|
||||
clearTimeout(appearanceTimer);
|
||||
appearanceTimer = null;
|
||||
}
|
||||
patchText(appearanceStatusText, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
appearanceTimer = setTimeout(() => {
|
||||
appearanceTimer = null;
|
||||
patchText(appearanceStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
function showCloudFeedback(text, autoClearMs = 3500) {
|
||||
if (cloudTimer) {
|
||||
clearTimeout(cloudTimer);
|
||||
cloudTimer = null;
|
||||
}
|
||||
patchText(cloudStatusMsg, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
cloudTimer = setTimeout(() => {
|
||||
cloudTimer = null;
|
||||
patchText(cloudStatusMsg, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Card 1: 界面与外观 ---
|
||||
const appearanceTitleEl = h('span', { text: t('settings.gen.appearanceTitle') });
|
||||
const langLabelEl = h('span', { className: 'form-label', text: t('settings.gen.language') });
|
||||
const accentLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.gen.themeAccent'),
|
||||
});
|
||||
const fontLabelEl = h('span', { className: 'form-label', text: t('settings.gen.fontScale') });
|
||||
const fontHintEl = h('span', {
|
||||
className: 'settings-hint-text',
|
||||
text: t('settings.gen.fontHint'),
|
||||
});
|
||||
|
||||
const languageSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.gen.language'),
|
||||
modelValue: draftLanguage,
|
||||
options: getLanguageOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextLang = normalizeI18nLanguage(val);
|
||||
draftLanguage = nextLang;
|
||||
setI18nLanguage(nextLang);
|
||||
languageSwitch.setValue(nextLang);
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ language: nextLang });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const themeColorPicker = ThemeColorPicker({
|
||||
modelValue: draftThemeAccent,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextAccent = normalizeClientThemeAccent(val);
|
||||
draftThemeAccent = nextAccent;
|
||||
themeColorPicker.refs.setValue(nextAccent);
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ themeAccent: nextAccent });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const fontScaleSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.gen.fontScale'),
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextScale = normalizeClientFontScale(val);
|
||||
draftFontScale = nextScale;
|
||||
fontScaleSwitch.setValue(nextScale);
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ fontScale: nextScale });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
props.onLayoutChange?.();
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const appearancePanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
appearanceTitleEl,
|
||||
]),
|
||||
appearanceStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]),
|
||||
h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]),
|
||||
h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]),
|
||||
]);
|
||||
|
||||
// --- Card 2: 版本更新 ---
|
||||
const updateTitleEl = h('span', { text: t('settings.gen.updateTitle') });
|
||||
const updateModeLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.gen.updateMode'),
|
||||
});
|
||||
const pricingCellLabelEl = h('span', {
|
||||
className: 'cell-label',
|
||||
text: t('settings.gen.pricingLabel'),
|
||||
});
|
||||
const versionCellLabelEl = h('span', {
|
||||
className: 'cell-label',
|
||||
text: t('settings.gen.versionLabel'),
|
||||
});
|
||||
|
||||
const autoUpdateSelect = CustomSelect({
|
||||
modelValue: 'manual',
|
||||
icon: 'refresh',
|
||||
options: getUpdateModeOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientUpdateMode(val);
|
||||
draftPluginUpdateMode = nextMode;
|
||||
autoUpdateSelect.setValue(nextMode);
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
showCloudFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
pluginUpdateMode: nextMode,
|
||||
autoUpdatePlugin: nextMode === 'auto',
|
||||
});
|
||||
showCloudFeedback(t('settings.saved'), 1800);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
||||
showCloudFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: t('quota.loading') });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.4' });
|
||||
const versionSub = h('span', { className: 'cell-sub', text: t('settings.gen.checkingBtn') });
|
||||
|
||||
const syncPricingBtnText = h('span', { text: t('settings.gen.syncBtn') });
|
||||
const syncPricingBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(syncPricingBtn, 'disabled', true);
|
||||
patchText(syncPricingBtnText, t('settings.gen.syncingBtn'));
|
||||
showCloudFeedback(t('settings.gen.syncingMsg'), 0);
|
||||
try {
|
||||
const res = await triggerCloudSync();
|
||||
const cs = res?.cloudStatus;
|
||||
if (res?.ok && cs) {
|
||||
showCloudFeedback(t('settings.gen.syncedMsg', { count: cs.modelCount }), 3500);
|
||||
} else {
|
||||
showCloudFeedback(cs?.lastSyncError || t('settings.gen.syncFallbackMsg'), 4500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || t('settings.gen.syncFallbackMsg'), 4500);
|
||||
} finally {
|
||||
patchAttr(syncPricingBtn, 'disabled', false);
|
||||
patchText(syncPricingBtnText, t('settings.gen.syncBtn'));
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 12 }), syncPricingBtnText]
|
||||
);
|
||||
|
||||
const updatePluginBtnText = h('span', { text: t('settings.gen.checkUpdateBtn') });
|
||||
const updatePluginBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(updatePluginBtn, 'disabled', true);
|
||||
try {
|
||||
if (!latestCloudStatus?.updateAvailable) {
|
||||
patchText(updatePluginBtnText, t('settings.gen.checkingBtn'));
|
||||
showCloudFeedback(t('settings.gen.checkingMsg'), 0);
|
||||
const syncRes = await triggerCloudSync();
|
||||
const cs = syncRes?.cloudStatus || latestCloudStatus;
|
||||
if (cs) {
|
||||
latestCloudStatus = cs;
|
||||
renderCloudStatus(cs);
|
||||
}
|
||||
if (!syncRes?.ok && cs?.lastSyncError) {
|
||||
showCloudFeedback(
|
||||
t('settings.gen.checkFailedMsg', { err: cs.lastSyncError }),
|
||||
5000
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!cs?.updateAvailable) {
|
||||
const curVer = cs?.currentPluginVersion || '1.4.4';
|
||||
showCloudFeedback(t('settings.gen.upToDateMsg', { ver: curVer }), 4500);
|
||||
return;
|
||||
}
|
||||
}
|
||||
patchText(updatePluginBtnText, t('capsule.updating'));
|
||||
showCloudFeedback(t('settings.gen.downloadingMsg'), 0);
|
||||
const res = await triggerPluginUpdate();
|
||||
if (res?.cloudStatus) {
|
||||
latestCloudStatus = res.cloudStatus;
|
||||
}
|
||||
if (res?.ok) {
|
||||
showCloudFeedback(res.message || t('settings.gen.updatedRestartMsg'), 5000);
|
||||
} else {
|
||||
showCloudFeedback(res?.message || t('settings.gen.updateSkippedMsg'), 5500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || t('settings.gen.updateFailedMsg'), 5000);
|
||||
} finally {
|
||||
patchAttr(updatePluginBtn, 'disabled', false);
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText]
|
||||
);
|
||||
|
||||
const cloudPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('bolt', { size: 13 }),
|
||||
updateTitleEl,
|
||||
]),
|
||||
cloudStatusMsg,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [updateModeLabelEl, autoUpdateSelect.el]),
|
||||
h('div', { className: 'dual-grid' }, [
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
pricingCellLabelEl,
|
||||
pricingCountVal,
|
||||
pricingSyncSub,
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [versionCellLabelEl, versionVal, versionSub]),
|
||||
]),
|
||||
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'settings-tab-stack' }, [appearancePanel, cloudPanel]);
|
||||
|
||||
function renderSettings(settings) {
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
draftLanguage = normalizeI18nLanguage(settings.language);
|
||||
draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent);
|
||||
draftFontScale = normalizeClientFontScale(settings.fontScale);
|
||||
draftPluginUpdateMode = normalizeClientUpdateMode(
|
||||
settings.pluginUpdateMode,
|
||||
settings.autoUpdatePlugin
|
||||
);
|
||||
|
||||
languageSwitch.setProps({
|
||||
modelValue: draftLanguage,
|
||||
options: getLanguageOptions(),
|
||||
});
|
||||
themeColorPicker.refs.setValue(draftThemeAccent);
|
||||
fontScaleSwitch.setProps({
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
options: getUpdateModeOptions(),
|
||||
});
|
||||
}
|
||||
|
||||
function renderCloudStatus(cs) {
|
||||
if (!cs) return;
|
||||
latestCloudStatus = cs;
|
||||
const srcLabel =
|
||||
cs.source === 'remote'
|
||||
? t('settings.gen.srcRemote')
|
||||
: cs.source === 'local'
|
||||
? t('settings.gen.srcLocal')
|
||||
: t('settings.gen.srcDefault');
|
||||
patchText(pricingCountVal, t('settings.gen.modelCount', { count: cs.modelCount || 0 }));
|
||||
patchText(
|
||||
pricingSyncSub,
|
||||
`${srcLabel} · ${formatCloudSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||
);
|
||||
|
||||
const curVer = cs.currentPluginVersion || '1.4.4';
|
||||
const latVer = cs.latestPluginVersion || curVer;
|
||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||
patchText(versionVal, `v${curVer}`);
|
||||
if (cs.updateAvailable && draftPluginUpdateMode !== 'off') {
|
||||
patchText(versionSub, t('settings.gen.canUpgradeSub', { ver: latVer, mode: modeTag }));
|
||||
patchClasses(versionSub, { 'accent-ok': true });
|
||||
patchText(updatePluginBtnText, t('settings.gen.upgradeToBtn', { ver: latVer }));
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false });
|
||||
} else if (draftPluginUpdateMode === 'off') {
|
||||
patchText(versionSub, t('settings.gen.updateOffSub', { mode: modeTag }));
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(
|
||||
updatePluginBtnText,
|
||||
cs.updateAvailable
|
||||
? t('settings.gen.manualUpgradeBtn', { ver: latVer })
|
||||
: t('settings.gen.checkUpdateBtn')
|
||||
);
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
} else {
|
||||
patchText(versionSub, t('settings.gen.latestSub', { mode: modeTag }));
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(updatePluginBtnText, t('settings.gen.checkUpdateBtn'));
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
}
|
||||
|
||||
if (
|
||||
!cloudTimer &&
|
||||
(cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))
|
||||
) {
|
||||
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshLabels() {
|
||||
patchText(appearanceTitleEl, t('settings.gen.appearanceTitle'));
|
||||
patchText(langLabelEl, t('settings.gen.language'));
|
||||
patchText(accentLabelEl, t('settings.gen.themeAccent'));
|
||||
patchText(fontLabelEl, t('settings.gen.fontScale'));
|
||||
patchText(fontHintEl, t('settings.gen.fontHint'));
|
||||
patchText(updateTitleEl, t('settings.gen.updateTitle'));
|
||||
patchText(updateModeLabelEl, t('settings.gen.updateMode'));
|
||||
patchText(pricingCellLabelEl, t('settings.gen.pricingLabel'));
|
||||
patchText(versionCellLabelEl, t('settings.gen.versionLabel'));
|
||||
if (!syncPricingBtn.hasAttribute('disabled')) {
|
||||
patchText(syncPricingBtnText, t('settings.gen.syncBtn'));
|
||||
}
|
||||
languageSwitch.setProps({
|
||||
modelValue: draftLanguage,
|
||||
options: getLanguageOptions(),
|
||||
});
|
||||
themeColorPicker.refs.refreshLabels();
|
||||
fontScaleSwitch.setProps({
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
options: getUpdateModeOptions(),
|
||||
});
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
} else {
|
||||
patchText(pricingSyncSub, t('quota.loading'));
|
||||
}
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (appearanceTimer) clearTimeout(appearanceTimer);
|
||||
if (cloudTimer) clearTimeout(cloudTimer);
|
||||
languageSwitch.destroy();
|
||||
themeColorPicker.destroy();
|
||||
fontScaleSwitch.destroy();
|
||||
autoUpdateSelect.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
languageSwitch,
|
||||
themeColorPicker,
|
||||
fontScaleSwitch,
|
||||
autoUpdateSelect,
|
||||
syncPricingBtn,
|
||||
updatePluginBtn,
|
||||
renderSettings,
|
||||
renderCloudStatus,
|
||||
refreshLabels,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,565 @@
|
||||
/**
|
||||
* @fileoverview Preferences Tab 3: `SettingsOtherTab.js` ("其他").
|
||||
* Houses Model Identifier Formatting, Per-Model Context Windows,
|
||||
* Local Trajectory Cache Rebuild, and Two-Step Factory Preference Reset.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { setI18nLanguage, t } from '../../i18n/index.js';
|
||||
import {
|
||||
normalizeClientModelDisplayMode,
|
||||
normalizeClientOrchestratorIdMode,
|
||||
rebuildTrajectoryCache,
|
||||
resetAllSettings,
|
||||
saveModelContextWindow,
|
||||
saveSettingsPatch,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
|
||||
function getStepModelDisplayOptions() {
|
||||
return [
|
||||
{ value: 'short', label: t('settings.oth.modelShort') },
|
||||
{ value: 'upstream', label: t('settings.oth.modelUpstream') },
|
||||
{ value: 'upstream_compact', label: t('settings.oth.modelUpstreamCompact') },
|
||||
];
|
||||
}
|
||||
|
||||
function getOrchestratorIdDisplayOptions() {
|
||||
return [
|
||||
{ value: 'compact', label: t('settings.oth.orchCompact') },
|
||||
{ value: 'full', label: t('settings.oth.orchFull') },
|
||||
];
|
||||
}
|
||||
|
||||
export const SettingsOtherTab = defineComponent({
|
||||
name: 'SettingsOtherTab',
|
||||
setup({ onCleanup, getProps }) {
|
||||
let draftModelDisplayMode = 'short';
|
||||
let draftOrchestratorIdMode = 'compact';
|
||||
let draftContextRiskAccepted = false;
|
||||
let acceptingContextRisk = false;
|
||||
let latestSettings = null;
|
||||
let contextWindowModels = [];
|
||||
let contextModelId = '';
|
||||
let savingContextWindow = false;
|
||||
let contextFeedback = '';
|
||||
let modelTimer = null;
|
||||
let maintTimer = null;
|
||||
let resetConfirmTimer = null;
|
||||
let resetConfirmArmed = false;
|
||||
let isRebuilding = false;
|
||||
let isResetting = false;
|
||||
|
||||
const modelStatusText = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
const maintStatusText = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
|
||||
function showModelFeedback(text, autoClearMs = 1500) {
|
||||
if (modelTimer) {
|
||||
clearTimeout(modelTimer);
|
||||
modelTimer = null;
|
||||
}
|
||||
patchText(modelStatusText, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
modelTimer = setTimeout(() => {
|
||||
modelTimer = null;
|
||||
patchText(modelStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
function showMaintFeedback(text, autoClearMs = 2500) {
|
||||
if (maintTimer) {
|
||||
clearTimeout(maintTimer);
|
||||
maintTimer = null;
|
||||
}
|
||||
patchText(maintStatusText, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
maintTimer = setTimeout(() => {
|
||||
maintTimer = null;
|
||||
patchText(maintStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Card 1: 模型标识显示 ---
|
||||
const modelCardTitleEl = h('span', { text: t('settings.oth.modelTitle') });
|
||||
const modelFormatLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.modelFormat'),
|
||||
});
|
||||
const orchFormatLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.orchFormat'),
|
||||
});
|
||||
|
||||
const stepModelSelect = CustomSelect({
|
||||
modelValue: 'short',
|
||||
icon: 'table',
|
||||
options: getStepModelDisplayOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientModelDisplayMode(val);
|
||||
draftModelDisplayMode = nextMode;
|
||||
stepModelSelect.setValue(nextMode);
|
||||
showModelFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
modelDisplayMode: nextMode,
|
||||
showUpstreamModel: nextMode !== 'short',
|
||||
});
|
||||
showModelFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showModelFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const orchestratorIdSelect = CustomSelect({
|
||||
modelValue: 'compact',
|
||||
icon: 'layers',
|
||||
options: getOrchestratorIdDisplayOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientOrchestratorIdMode(val);
|
||||
draftOrchestratorIdMode = nextMode;
|
||||
orchestratorIdSelect.setValue(nextMode);
|
||||
showModelFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ orchestratorIdMode: nextMode });
|
||||
showModelFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showModelFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const modelPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
modelCardTitleEl,
|
||||
]),
|
||||
modelStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [modelFormatLabelEl, stepModelSelect.el]),
|
||||
h('div', { className: 'form-row' }, [orchFormatLabelEl, orchestratorIdSelect.el]),
|
||||
]);
|
||||
|
||||
// --- Card 2: 按模型设置上下文窗口 ---
|
||||
const baselineTitleEl = h('span', { text: t('settings.oth.baselineTitle') });
|
||||
const ctxModelLabel = h('span', { className: 'form-label' });
|
||||
const ctxWindowLabel = h('span', { className: 'form-label' });
|
||||
const ctxHint = h('span', { className: 'settings-hint-text' });
|
||||
const ctxStatus = h('span', { className: 'text-muted', role: 'status' });
|
||||
const ctxModelSelect = CustomSelect({
|
||||
className: 'settings-context-model',
|
||||
options: [],
|
||||
onUpdateModelValue: (id) => {
|
||||
if (!draftContextRiskAccepted || savingContextWindow) return;
|
||||
contextModelId = id;
|
||||
contextFeedback = '';
|
||||
renderContextWindows();
|
||||
},
|
||||
});
|
||||
const ctxWindowSelect = CustomSelect({
|
||||
options: [],
|
||||
onUpdateModelValue: async (value) => {
|
||||
if (!draftContextRiskAccepted || savingContextWindow || !contextModelId) return;
|
||||
savingContextWindow = true;
|
||||
contextFeedback = 'settings.saving';
|
||||
renderContextWindows();
|
||||
try {
|
||||
const modelContextWindows = await saveModelContextWindow(contextModelId, value || null);
|
||||
latestSettings = { ...latestSettings, modelContextWindows };
|
||||
contextFeedback = 'settings.saved';
|
||||
} catch {
|
||||
contextFeedback = 'settings.saveFailed';
|
||||
} finally {
|
||||
savingContextWindow = false;
|
||||
renderContextWindows();
|
||||
}
|
||||
},
|
||||
});
|
||||
const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]);
|
||||
const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]);
|
||||
const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [
|
||||
ctxModelRow,
|
||||
ctxWindowRow,
|
||||
h('div', { className: 'form-row' }, [ctxHint]),
|
||||
]);
|
||||
|
||||
const ctxRiskTitleEl = h('strong', {
|
||||
className: 'ctx-risk-title',
|
||||
text: t('settings.oth.ctxRiskTitle'),
|
||||
});
|
||||
const ctxRiskBodyEl = h('p', {
|
||||
className: 'ctx-risk-desc',
|
||||
text: t('settings.oth.ctxRiskBody'),
|
||||
});
|
||||
const ctxRiskAcceptBtnText = h('span', { text: t('settings.oth.ctxRiskAcceptBtn') });
|
||||
const ctxRiskAcceptBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary btn-danger-confirm ctx-risk-accept-btn',
|
||||
onClick: async () => {
|
||||
if (acceptingContextRisk || draftContextRiskAccepted) return;
|
||||
acceptingContextRisk = true;
|
||||
draftContextRiskAccepted = true;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowRiskAccepted: true };
|
||||
contextFeedback = 'settings.saving';
|
||||
renderContextWindows();
|
||||
try {
|
||||
await saveSettingsPatch({ contextWindowRiskAccepted: true });
|
||||
contextFeedback = 'settings.saved';
|
||||
} catch {
|
||||
draftContextRiskAccepted = false;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowRiskAccepted: false };
|
||||
contextFeedback = 'settings.saveFailed';
|
||||
} finally {
|
||||
acceptingContextRisk = false;
|
||||
renderContextWindows();
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('warning', { size: 12 }), ctxRiskAcceptBtnText]
|
||||
);
|
||||
const ctxRiskMask = h(
|
||||
'div',
|
||||
{
|
||||
className: 'ctx-risk-mask',
|
||||
role: 'region',
|
||||
'aria-label': t('settings.oth.ctxRiskTitle'),
|
||||
},
|
||||
[
|
||||
h('div', { className: 'ctx-risk-head' }, [
|
||||
createSvgIcon('warning', { size: 14, className: 'ctx-risk-icon' }),
|
||||
ctxRiskTitleEl,
|
||||
]),
|
||||
ctxRiskBodyEl,
|
||||
ctxRiskAcceptBtn,
|
||||
]
|
||||
);
|
||||
const ctxRiskStage = h('div', { className: 'ctx-risk-stage' }, [ctxControlsBody, ctxRiskMask]);
|
||||
|
||||
function renderContextWindows() {
|
||||
const unlocked = Boolean(draftContextRiskAccepted);
|
||||
if (!unlocked) {
|
||||
ctxModelSelect.close();
|
||||
ctxWindowSelect.close();
|
||||
}
|
||||
patchClasses(ctxControlsBody, { 'is-locked': !unlocked });
|
||||
patchAttr(ctxControlsBody, 'inert', !unlocked);
|
||||
patchAttr(ctxControlsBody, 'aria-hidden', unlocked ? null : 'true');
|
||||
patchAttr(ctxRiskMask, 'hidden', unlocked);
|
||||
patchAttr(ctxRiskMask, 'aria-label', t('settings.oth.ctxRiskTitle'));
|
||||
patchText(ctxRiskTitleEl, t('settings.oth.ctxRiskTitle'));
|
||||
patchText(ctxRiskBodyEl, t('settings.oth.ctxRiskBody'));
|
||||
patchText(ctxRiskAcceptBtnText, t('settings.oth.ctxRiskAcceptBtn'));
|
||||
patchAttr(ctxRiskAcceptBtn, 'disabled', acceptingContextRisk);
|
||||
|
||||
const saved = latestSettings?.modelContextWindows || {};
|
||||
const models = new Map(contextWindowModels.map((model) => [model.id, model]));
|
||||
const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members]));
|
||||
for (const id of Object.keys(saved)) {
|
||||
if (!knownIds.has(id)) models.set(id, { id, label: id.replace(/^model:/, ''), options: [] });
|
||||
}
|
||||
if (!models.has(contextModelId)) contextModelId = '';
|
||||
const mixed = '\u0000mixed';
|
||||
const getSelection = ({ id, members = [] }) => {
|
||||
const legacy = new Set(members.map((member) => saved[member]).filter(Boolean));
|
||||
return saved[id] || (legacy.size > 1 ? mixed : legacy.values().next().value) || '';
|
||||
};
|
||||
const formatLimit = (value) => /^\d+$/.test(value) ? t('settings.oth.ctxTokens', { count: Number(value).toLocaleString() }) : value;
|
||||
const isAvailable = (model, value) => model.options.some(({ name }) => name === value) ||
|
||||
(/^[1-9]\d*$/.test(value) && Number(value) <= model.capacity);
|
||||
const current = models.get(contextModelId);
|
||||
const options = current?.options || [];
|
||||
const selected = current ? getSelection(current) : '';
|
||||
const choices = [
|
||||
{ value: '', label: t('settings.oth.ctxDefault') },
|
||||
...options.map(({ name, expensive, tokens }) => ({
|
||||
value: name,
|
||||
label: tokens ? formatLimit(name) :
|
||||
(expensive ? t('settings.oth.ctxExpensive', { name }) : name),
|
||||
})),
|
||||
];
|
||||
if (selected && !choices.some((item) => item.value === selected)) {
|
||||
let label = t('settings.oth.ctxMixed');
|
||||
if (selected !== mixed) {
|
||||
const name = formatLimit(selected);
|
||||
label = isAvailable(current, selected) ? name : t('settings.oth.ctxUnavailable', { name });
|
||||
}
|
||||
choices.push({ value: selected, label, disabled: true });
|
||||
}
|
||||
ctxModelSelect.setProps({
|
||||
modelValue: contextModelId,
|
||||
options: [
|
||||
{ value: '', label: t('settings.oth.ctxChooseModel') },
|
||||
...[...models.values()].map((model) => {
|
||||
const value = getSelection(model);
|
||||
let meta = t('settings.oth.ctxDefault');
|
||||
if (value === mixed) meta = t('settings.oth.ctxMixed');
|
||||
else if (value) {
|
||||
const name = formatLimit(value);
|
||||
if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name });
|
||||
else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) {
|
||||
meta = t('settings.oth.ctxConfiguredReported', {
|
||||
name,
|
||||
reported: formatLimit(String(model.reportedLimitTokens)),
|
||||
});
|
||||
} else meta = t('settings.oth.ctxConfigured', { name });
|
||||
}
|
||||
else if (model.reportedLimitTokens) meta = t('settings.oth.ctxDefaultReported', { name: formatLimit(String(model.reportedLimitTokens)) });
|
||||
return { value: model.id, label: model.label, meta };
|
||||
}),
|
||||
],
|
||||
});
|
||||
ctxWindowSelect.setProps({ modelValue: selected, options: choices });
|
||||
patchAttr(ctxModelSelect.refs.triggerBtn, 'disabled', !unlocked || savingContextWindow);
|
||||
patchAttr(ctxWindowSelect.refs.triggerBtn, 'disabled', !unlocked || savingContextWindow || (!options.length && !selected));
|
||||
patchAttr(ctxModelSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxModel'));
|
||||
patchAttr(ctxWindowSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxBaselineLabel'));
|
||||
patchAttr(ctxModelRow, 'hidden', !models.size);
|
||||
patchAttr(ctxWindowRow, 'hidden', !contextModelId);
|
||||
patchText(ctxModelLabel, t('settings.oth.ctxModel'));
|
||||
patchText(ctxWindowLabel, t('settings.oth.ctxBaselineLabel'));
|
||||
const hint = !models.size ? 'ctxNoModels' : selected === mixed ? 'ctxMixedHint' :
|
||||
contextModelId && !options.length ? 'ctxNoOptions' : 'ctxBaselineHint';
|
||||
const reported = current?.reportedLimitTokens;
|
||||
patchText(ctxHint, [t(`settings.oth.${hint}`), reported &&
|
||||
t('settings.oth.ctxReported', { name: formatLimit(String(reported)) })].filter(Boolean).join(' '));
|
||||
patchText(ctxStatus, contextFeedback ? t(contextFeedback) : '');
|
||||
getProps().onLayoutChange?.();
|
||||
}
|
||||
|
||||
const baselinePanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('layers', { size: 13 }),
|
||||
baselineTitleEl,
|
||||
]),
|
||||
ctxStatus,
|
||||
]),
|
||||
ctxRiskStage,
|
||||
]);
|
||||
renderContextWindows();
|
||||
|
||||
// --- Card 3: 缓存与重置 ---
|
||||
const maintTitleEl = h('span', { text: t('settings.oth.maintTitle') });
|
||||
const cacheLabelEl = h('span', {
|
||||
className: 'settings-action-title',
|
||||
text: t('settings.oth.cacheLabel'),
|
||||
});
|
||||
const cacheDescEl = h('span', {
|
||||
className: 'settings-action-desc',
|
||||
text: t('settings.oth.cacheDesc'),
|
||||
});
|
||||
|
||||
const rebuildBtnText = h('span', { text: t('settings.oth.rebuildBtn') });
|
||||
const rebuildCacheBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
if (isRebuilding) return;
|
||||
isRebuilding = true;
|
||||
patchAttr(rebuildCacheBtn, 'disabled', true);
|
||||
patchText(rebuildBtnText, t('settings.oth.rebuildingBtn'));
|
||||
showMaintFeedback(t('settings.oth.rebuildingBtn'), 0);
|
||||
try {
|
||||
const res = await rebuildTrajectoryCache();
|
||||
if (res?.ok !== false) {
|
||||
showMaintFeedback(t('settings.oth.rebuildDone'), 2800);
|
||||
} else {
|
||||
showMaintFeedback(t('settings.oth.rebuildFailed'), 3000);
|
||||
}
|
||||
} catch {
|
||||
showMaintFeedback(t('settings.oth.rebuildFailed'), 3000);
|
||||
} finally {
|
||||
isRebuilding = false;
|
||||
patchAttr(rebuildCacheBtn, 'disabled', false);
|
||||
patchText(rebuildBtnText, t('settings.oth.rebuildBtn'));
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 12 }), rebuildBtnText]
|
||||
);
|
||||
|
||||
const resetLabelEl = h('span', {
|
||||
className: 'settings-action-title',
|
||||
text: t('settings.oth.resetLabel'),
|
||||
});
|
||||
const resetDescEl = h('span', {
|
||||
className: 'settings-action-desc',
|
||||
text: t('settings.oth.resetDesc'),
|
||||
});
|
||||
|
||||
const resetBtnText = h('span', { text: t('settings.oth.resetAllBtn') });
|
||||
|
||||
function disarmResetConfirm() {
|
||||
resetConfirmArmed = false;
|
||||
if (resetConfirmTimer) {
|
||||
clearTimeout(resetConfirmTimer);
|
||||
resetConfirmTimer = null;
|
||||
}
|
||||
patchClasses(resetAllBtn, { 'btn-danger-confirm': false });
|
||||
if (!isResetting) {
|
||||
patchText(resetBtnText, t('settings.oth.resetAllBtn'));
|
||||
}
|
||||
}
|
||||
|
||||
const resetAllBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
if (isResetting) return;
|
||||
if (!resetConfirmArmed) {
|
||||
resetConfirmArmed = true;
|
||||
patchClasses(resetAllBtn, { 'btn-danger-confirm': true });
|
||||
patchText(resetBtnText, t('settings.oth.resetConfirmBtn'));
|
||||
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
|
||||
resetConfirmTimer = setTimeout(() => {
|
||||
disarmResetConfirm();
|
||||
}, 3000);
|
||||
return;
|
||||
}
|
||||
|
||||
disarmResetConfirm();
|
||||
isResetting = true;
|
||||
patchAttr(resetAllBtn, 'disabled', true);
|
||||
patchText(resetBtnText, t('settings.oth.resettingBtn'));
|
||||
showMaintFeedback(t('settings.oth.resettingBtn'), 0);
|
||||
try {
|
||||
const res = await resetAllSettings();
|
||||
setI18nLanguage(res?.settings?.language || 'zh-CN');
|
||||
showMaintFeedback(t('settings.oth.resetAllDone'), 2800);
|
||||
} catch {
|
||||
showMaintFeedback(t('settings.saveFailed'), 2800);
|
||||
} finally {
|
||||
isResetting = false;
|
||||
patchAttr(resetAllBtn, 'disabled', false);
|
||||
patchText(resetBtnText, t('settings.oth.resetAllBtn'));
|
||||
}
|
||||
},
|
||||
},
|
||||
[resetBtnText]
|
||||
);
|
||||
|
||||
const maintPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('refresh', { size: 13 }),
|
||||
maintTitleEl,
|
||||
]),
|
||||
maintStatusText,
|
||||
]),
|
||||
h('div', { className: 'settings-action-block' }, [
|
||||
h('div', { className: 'settings-action-info' }, [cacheLabelEl, cacheDescEl]),
|
||||
rebuildCacheBtn,
|
||||
]),
|
||||
h('div', { className: 'settings-action-block' }, [
|
||||
h('div', { className: 'settings-action-info' }, [resetLabelEl, resetDescEl]),
|
||||
resetAllBtn,
|
||||
]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'settings-tab-stack' }, [
|
||||
modelPanel,
|
||||
baselinePanel,
|
||||
maintPanel,
|
||||
]);
|
||||
|
||||
function renderSettings(settings, models = contextWindowModels) {
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
contextWindowModels = models;
|
||||
draftModelDisplayMode = normalizeClientModelDisplayMode(
|
||||
settings.modelDisplayMode,
|
||||
settings.showUpstreamModel
|
||||
);
|
||||
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
|
||||
if (!acceptingContextRisk) {
|
||||
draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted);
|
||||
}
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftModelDisplayMode,
|
||||
options: getStepModelDisplayOptions(),
|
||||
});
|
||||
orchestratorIdSelect.setProps({
|
||||
modelValue: draftOrchestratorIdMode,
|
||||
options: getOrchestratorIdDisplayOptions(),
|
||||
});
|
||||
renderContextWindows();
|
||||
}
|
||||
|
||||
function refreshLabels() {
|
||||
patchText(modelCardTitleEl, t('settings.oth.modelTitle'));
|
||||
patchText(modelFormatLabelEl, t('settings.oth.modelFormat'));
|
||||
patchText(orchFormatLabelEl, t('settings.oth.orchFormat'));
|
||||
patchText(baselineTitleEl, t('settings.oth.baselineTitle'));
|
||||
renderContextWindows();
|
||||
patchText(maintTitleEl, t('settings.oth.maintTitle'));
|
||||
patchText(cacheLabelEl, t('settings.oth.cacheLabel'));
|
||||
patchText(cacheDescEl, t('settings.oth.cacheDesc'));
|
||||
patchText(resetLabelEl, t('settings.oth.resetLabel'));
|
||||
patchText(resetDescEl, t('settings.oth.resetDesc'));
|
||||
|
||||
if (!isRebuilding) {
|
||||
patchText(rebuildBtnText, t('settings.oth.rebuildBtn'));
|
||||
}
|
||||
if (!isResetting) {
|
||||
patchText(
|
||||
resetBtnText,
|
||||
resetConfirmArmed ? t('settings.oth.resetConfirmBtn') : t('settings.oth.resetAllBtn')
|
||||
);
|
||||
}
|
||||
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftModelDisplayMode,
|
||||
options: getStepModelDisplayOptions(),
|
||||
});
|
||||
orchestratorIdSelect.setProps({
|
||||
modelValue: draftOrchestratorIdMode,
|
||||
options: getOrchestratorIdDisplayOptions(),
|
||||
});
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (modelTimer) clearTimeout(modelTimer);
|
||||
if (maintTimer) clearTimeout(maintTimer);
|
||||
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
|
||||
stepModelSelect.destroy();
|
||||
orchestratorIdSelect.destroy();
|
||||
ctxModelSelect.destroy();
|
||||
ctxWindowSelect.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
stepModelSelect,
|
||||
orchestratorIdSelect,
|
||||
ctxModelSelect,
|
||||
ctxWindowSelect,
|
||||
rebuildCacheBtn,
|
||||
resetAllBtn,
|
||||
renderSettings,
|
||||
refreshLabels,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @fileoverview Antigravity Usage Monitor 独立 Web 监控 CLI 入口 (`standalone.mjs`)。
|
||||
*
|
||||
* 在无头服务器 (`agy` / `agy remote-control serve`) 或纯终端环境下,脱离 `sidecar_sdk`
|
||||
* 直接拉起完整的四分页监控面板与 API 服务:
|
||||
* - `node sidecars/panel/standalone.mjs --port 8787`(配合 `ssh -L 8787:127.0.0.1:8787` 零鉴权安全访问)
|
||||
* - `node sidecars/panel/standalone.mjs --host 0.0.0.0 --port 8787 --token <secret>`(带访问令牌保护)
|
||||
*/
|
||||
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
function applyPreImportEnvOverrides(argv) {
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const raw = String(argv[i] || '');
|
||||
if (!raw) continue;
|
||||
const eqIdx = raw.indexOf('=');
|
||||
const flag = eqIdx > 0 ? raw.slice(0, eqIdx) : raw;
|
||||
const readVal = () => {
|
||||
if (eqIdx > 0) return raw.slice(eqIdx + 1).trim();
|
||||
if (i + 1 < argv.length) {
|
||||
i += 1;
|
||||
return String(argv[i] || '').trim();
|
||||
}
|
||||
return '';
|
||||
};
|
||||
if (flag === '--data-dir') {
|
||||
const v = readVal();
|
||||
if (v) process.env.USAGE_MONITOR_DATA_DIR = v;
|
||||
} else if (flag === '--app-data-dir') {
|
||||
const v = readVal();
|
||||
if (v) process.env.USAGE_MONITOR_APP_DATA_DIR = v;
|
||||
} else if (flag === '--gemini-dir') {
|
||||
const v = readVal();
|
||||
if (v) process.env.ANTIGRAVITY_GEMINI_DIR = v;
|
||||
} else if (flag === '--ls-addr') {
|
||||
const v = readVal();
|
||||
if (v) process.env.ANTIGRAVITY_LS_ADDRESS = v;
|
||||
} else if (flag === '--csrf-token') {
|
||||
const v = readVal();
|
||||
if (v) process.env.ANTIGRAVITY_CSRF_TOKEN = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function runStandaloneCli(argv = process.argv.slice(2)) {
|
||||
applyPreImportEnvOverrides(argv);
|
||||
|
||||
const {
|
||||
createStandaloneWebServer,
|
||||
formatStandaloneHelpText,
|
||||
parseStandaloneCliArgs,
|
||||
} = await import('./backend/standalone-server.mjs');
|
||||
const { DATA_DIR, lsRuntimeEndpoint } = await import('./backend/config.mjs');
|
||||
const { ensureLsEndpointDiscovered } = await import('./backend/ls-discovery.mjs');
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseStandaloneCliArgs(argv, process.env, { defaultPort: 8787 });
|
||||
} catch (err) {
|
||||
console.error(`[usage-monitor] ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (parsed.help) {
|
||||
console.log(formatStandaloneHelpText());
|
||||
return null;
|
||||
}
|
||||
|
||||
let controller;
|
||||
try {
|
||||
controller = createStandaloneWebServer({
|
||||
host: parsed.host,
|
||||
port: parsed.port,
|
||||
token: parsed.token,
|
||||
lsAddr: parsed.lsAddr,
|
||||
csrfToken: parsed.csrfToken,
|
||||
});
|
||||
const status = await controller.start();
|
||||
await ensureLsEndpointDiscovered({ force: false }).catch(() => false);
|
||||
const lsDesc = lsRuntimeEndpoint.baseUrl
|
||||
? `connected (${lsRuntimeEndpoint.baseUrl})`
|
||||
: 'offline fallback (reading local transcripts/cache; will auto-connect when agy starts)';
|
||||
const authDesc = status.tokenProtected
|
||||
? 'token required (--token)'
|
||||
: 'loopback-only (use ssh -L for remote access)';
|
||||
console.log(`[usage-monitor] Standalone Web UI listening at ${status.url}`);
|
||||
console.log(`[usage-monitor] Security mode: ${authDesc}`);
|
||||
console.log(`[usage-monitor] Language Server: ${lsDesc}`);
|
||||
console.log(`[usage-monitor] Data directory: ${DATA_DIR}`);
|
||||
} catch (err) {
|
||||
console.error(`[usage-monitor] Failed to start standalone server: ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
return null;
|
||||
}
|
||||
|
||||
let closing = false;
|
||||
const gracefulShutdown = async () => {
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
try {
|
||||
await controller.stop();
|
||||
} finally {
|
||||
process.exit(0);
|
||||
}
|
||||
};
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
void gracefulShutdown();
|
||||
});
|
||||
process.on('SIGTERM', () => {
|
||||
void gracefulShutdown();
|
||||
});
|
||||
|
||||
return controller;
|
||||
}
|
||||
|
||||
const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
||||
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
||||
void runStandaloneCli();
|
||||
}
|
||||
+2076
-106
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,128 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, rmdir, unlink } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveGoogleCredential, retrieveCredentialQuota } from '../backend/account-oauth.mjs';
|
||||
import { handleAccountCredentialAction, normalizeAccountCredential, runWindowsCredentialStore } from '../backend/account-switch.mjs';
|
||||
|
||||
test('accepts a shared OAuth credential or refresh token, and rejects other credential types', () => {
|
||||
const refreshToken = '1//synthetic-refresh-token-for-test';
|
||||
assert.deepEqual(JSON.parse(normalizeAccountCredential(refreshToken)), {
|
||||
auth_method: 'consumer',
|
||||
token: { access_token: '', token_type: 'Bearer', refresh_token: refreshToken, expiry: '1970-01-01T00:00:00.000Z' },
|
||||
});
|
||||
const saved = JSON.parse(normalizeAccountCredential(JSON.stringify({
|
||||
token: { refresh_token: refreshToken, access_token: 'example-access', expiry_timestamp: 1800000000 },
|
||||
})));
|
||||
assert.equal(saved.token.access_token, 'example-access');
|
||||
assert.equal(saved.token.expiry, '2027-01-15T08:00:00.000Z');
|
||||
assert.equal(normalizeAccountCredential(JSON.stringify({ auth_method: 'enterprise', refresh_token: refreshToken })), null);
|
||||
assert.equal(normalizeAccountCredential('example-api-key'), null);
|
||||
});
|
||||
|
||||
test('import uses the verified email and switches only after checking the credential identity', async () => {
|
||||
const calls = [];
|
||||
const input = '1//synthetic-refresh-token-for-test';
|
||||
const credential = JSON.parse(normalizeAccountCredential(input));
|
||||
const saved = JSON.stringify(credential);
|
||||
let verifiedEmail = 'Next@example.com';
|
||||
const options = {
|
||||
platform: 'win32',
|
||||
resolveCredential: async (_credential, opts) => {
|
||||
calls.push(opts.refresh ? 'refresh-identity' : 'verify-identity');
|
||||
return { email: verifiedEmail, credential };
|
||||
},
|
||||
rpc: async (method) => {
|
||||
calls.push(method);
|
||||
return { userStatus: { email: 'Next@example.com' } };
|
||||
},
|
||||
store: async (request) => {
|
||||
calls.push(request.action);
|
||||
if (request.action === 'read') return { credential: saved };
|
||||
assert.equal(request.target, 'gemini:antigravity');
|
||||
assert.equal(request.email, 'next@example.com');
|
||||
if (request.action === 'switch') assert.equal(request.expectedCredential, saved);
|
||||
return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved };
|
||||
},
|
||||
};
|
||||
assert.deepEqual(await handleAccountCredentialAction({ action: 'save', email: 'ignored@example.com', credential: input }, options), {
|
||||
supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com',
|
||||
});
|
||||
assert.deepEqual(calls.splice(0), ['refresh-identity', 'save']);
|
||||
const result = await handleAccountCredentialAction({ action: 'switch', email: 'NEXT@example.com' }, options);
|
||||
assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', confirmed: true });
|
||||
assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'switch', 'GetAuthStatus', 'GetUserStatus']);
|
||||
verifiedEmail = 'different@example.com';
|
||||
assert.deepEqual(await handleAccountCredentialAction({ action: 'switch', email: 'next@example.com' }, options), { error: 'identityMismatch' });
|
||||
assert.deepEqual(calls, ['read', 'verify-identity']);
|
||||
});
|
||||
|
||||
test('a saved credential can query its quota without replacing the active login', async () => {
|
||||
const credential = normalizeAccountCredential(JSON.stringify({ refresh_token: 'test', access_token: 'saved-access' }));
|
||||
const pools = [{ poolKey: 'Gemini', remainingPct: 0, weeklyRemainingPct: 29 }];
|
||||
const result = await handleAccountCredentialAction({ action: 'quota', email: 'next@example.com' }, {
|
||||
platform: 'win32',
|
||||
store: async (request) => {
|
||||
assert.equal(request.action, 'read');
|
||||
return { credential };
|
||||
},
|
||||
resolveCredential: async (stored) => ({ email: 'next@example.com', credential: stored }),
|
||||
getQuota: async (token) => {
|
||||
assert.equal(token, 'saved-access');
|
||||
return pools;
|
||||
},
|
||||
});
|
||||
assert.deepEqual(result, { email: 'next@example.com', pools });
|
||||
});
|
||||
|
||||
test('Google OAuth confirms the email and the same account token retrieves quota pools', async () => {
|
||||
const endpoints = [];
|
||||
const refreshToken = 'first-refresh';
|
||||
const token = { access_token: 'new-access', refresh_token: 'latest-refresh', expires_in: 3600 };
|
||||
const fetchFn = async (url, request) => {
|
||||
endpoints.push(url);
|
||||
assert.equal(request.redirect, 'error');
|
||||
if (url.endsWith('/token')) {
|
||||
assert.equal(request.body.get('refresh_token'), refreshToken);
|
||||
return { ok: true, json: async () => token };
|
||||
}
|
||||
assert.equal(request.headers.Authorization, 'Bearer new-access');
|
||||
if (url.endsWith('/userinfo')) return { ok: true, json: async () => ({ email: 'owner@example.com', verified_email: true }) };
|
||||
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: { id: 'test-project' } }) };
|
||||
assert.equal(JSON.parse(request.body).project, 'test-project');
|
||||
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
|
||||
assert.match(url, /:retrieveUserQuotaSummary$/);
|
||||
return { ok: true, json: async () => ({ response: { quotaSummary: { groups: [
|
||||
{ name: 'Gemini Models', buckets: [{ window: '5h', remaining_fraction: 0 }, { window: 'weekly', remainingFraction: 0.29 }] },
|
||||
] } } }) };
|
||||
};
|
||||
const resolved = await resolveGoogleCredential({ token: { refresh_token: refreshToken } }, {
|
||||
fetchFn, getClients: async () => [{ id: 'desktop-client', secret: 'test-config' }],
|
||||
});
|
||||
assert.equal(resolved.email, 'owner@example.com');
|
||||
assert.equal(resolved.credential.token.refresh_token, token.refresh_token);
|
||||
const pools = await retrieveCredentialQuota(resolved.credential.token.access_token, fetchFn);
|
||||
assert.deepEqual(pools.map(({ poolKey, remainingPct, weeklyRemainingPct }) => [poolKey, remainingPct, weeklyRemainingPct]), [['Gemini', 0, 29]]);
|
||||
assert.equal(endpoints.length, 5);
|
||||
});
|
||||
|
||||
test('Windows vault atomically saves, reloads and removes encrypted entries', { skip: process.platform !== 'win32' }, async () => {
|
||||
const directory = await mkdtemp(fileURLToPath(new URL('../.account-test-', import.meta.url)));
|
||||
const vault = join(directory, 'test.dpapi');
|
||||
const run = (action, email, credential) => runWindowsCredentialStore({ action, email, credential, vault });
|
||||
try {
|
||||
const credential = normalizeAccountCredential('1//synthetic-refresh-token-for-test');
|
||||
assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '' });
|
||||
assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '' });
|
||||
assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
|
||||
assert.deepEqual(await run('read', 'next@example.com'), { credential });
|
||||
assert.deepEqual(await runWindowsCredentialStore({ action: 'save', email: 'next@example.com', credential, expectedCredential: 'stale', vault }), { error: 'credentialChanged' });
|
||||
assert.equal((await readFile(vault)).includes('synthetic-refresh-token-for-test'), false);
|
||||
assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
|
||||
assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '' });
|
||||
} finally {
|
||||
await unlink(vault).catch((err) => { if (err.code !== 'ENOENT') throw err; });
|
||||
await rmdir(directory);
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import vm from 'node:vm';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import * as metrics from '../speed-metrics.mjs';
|
||||
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||
|
||||
@@ -14,7 +17,14 @@ const DEFAULT_BUNDLED_CATALOG = {
|
||||
};
|
||||
|
||||
const BACKEND_MODULE_FILES = [
|
||||
'../backend/context-windows.mjs',
|
||||
'../backend/account-oauth.mjs',
|
||||
'../backend/account-switch.mjs',
|
||||
'../backend/settings-schema.mjs',
|
||||
'../backend/config.mjs',
|
||||
'../backend/cli-sqlite-reader.mjs',
|
||||
'../backend/cli-statusline-config.mjs',
|
||||
'../backend/ls-discovery.mjs',
|
||||
'../backend/pricing-catalog.mjs',
|
||||
'../backend/plugin-updater.mjs',
|
||||
'../backend/ls-rpc.mjs',
|
||||
@@ -24,6 +34,7 @@ const BACKEND_MODULE_FILES = [
|
||||
'../backend/usage-aggregator.mjs',
|
||||
'../backend/telemetry-builder.mjs',
|
||||
'../backend/window-bridge.mjs',
|
||||
'../backend/api-actions.mjs',
|
||||
'../main.mjs',
|
||||
];
|
||||
|
||||
@@ -41,10 +52,12 @@ export function backendHarness({
|
||||
cache={},
|
||||
deepStats=null,
|
||||
transcripts={},
|
||||
diskDirs={},
|
||||
settings={},
|
||||
trajectories={},
|
||||
summaries={},
|
||||
userStatus={},
|
||||
availableModels={},
|
||||
quotaSummary={groups:[]},
|
||||
localCatalog=DEFAULT_BUNDLED_CATALOG,
|
||||
remoteCatalog=null,
|
||||
@@ -54,18 +67,25 @@ export function backendHarness({
|
||||
remoteFetch=null,
|
||||
execFileImpl=null,
|
||||
sourceText=null,
|
||||
clock=null,
|
||||
metricsImplementation=metrics,
|
||||
}={}) {
|
||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
||||
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal, Buffer,
|
||||
...metricsImplementation, URL, AbortSignal, Buffer, isDeepStrictEqual, randomUUID,
|
||||
...(clock ? { Date: class extends Date {
|
||||
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
||||
static now() { return clock(); }
|
||||
} } : {}),
|
||||
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
console:{error:m=>state.errors.push(m)},
|
||||
cpSync:()=>{},
|
||||
rmSync:()=>{},
|
||||
renameSync:()=>{},
|
||||
unlinkSync:()=>{},
|
||||
execFile:execFileImpl || ((cmd,args,opts,cb)=>{
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
fn(new Error('execFile not mocked'));
|
||||
@@ -82,9 +102,15 @@ export function backendHarness({
|
||||
return Boolean(m && state.transcripts?.[m[1]]);
|
||||
}
|
||||
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir);
|
||||
if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true;
|
||||
return false;
|
||||
},
|
||||
mkdirSync:()=>{},readdirSync:()=>[],
|
||||
mkdirSync:()=>{},
|
||||
readdirSync:p=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
if (diskDirs && Array.isArray(diskDirs[norm])) return diskDirs[norm];
|
||||
return [];
|
||||
},
|
||||
statSync:p=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
if (norm.endsWith('/.system_generated/logs/transcript.jsonl')) {
|
||||
@@ -107,7 +133,7 @@ export function backendHarness({
|
||||
const lines = m && state.transcripts?.[m[1]];
|
||||
return Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines || '');
|
||||
}
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(settings);
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(state.settings);
|
||||
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return JSON.stringify(state.deepStats);
|
||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
||||
if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||
@@ -118,11 +144,17 @@ export function backendHarness({
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
const parsed = typeof s === 'string' ? JSON.parse(s) : s;
|
||||
state.saves.push({path:p,data:parsed});
|
||||
if (norm.endsWith('settings.json')) {
|
||||
state.settings = parsed;
|
||||
}
|
||||
if (norm.endsWith('remote_pricing_cache.json')) {
|
||||
state.remoteCatalog = parsed;
|
||||
}
|
||||
},
|
||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,fileURLToPath:()=>mainPath,
|
||||
writeTrajectoryCacheFile:(p,data)=>{
|
||||
state.saves.push({path:p,data:JSON.parse(JSON.stringify(data))});
|
||||
},
|
||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,delimiter:path.delimiter,pathToFileURL,fileURLToPath:()=>mainPath,
|
||||
Response:class {constructor(body,options){this.body=body;this.options=options;}},
|
||||
SidecarApp:class {page(){} api(){} run(){}},
|
||||
fetch:async(url,options={})=>{
|
||||
@@ -136,14 +168,14 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data||{}};
|
||||
}
|
||||
if(method==='RetrieveUserQuotaSummary') {
|
||||
const qs=state.quotaSummary;
|
||||
const qs=await state.quotaSummary;
|
||||
if(qs instanceof Error) throw qs;
|
||||
return {ok:true,json:async()=>({response:qs})};
|
||||
}
|
||||
const data={GetUserStatus:{userStatus:state.userStatus},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method];
|
||||
const data={GetUserStatus:{userStatus:state.userStatus},GetAvailableModels:{response:{models:availableModels}},GetAllCascadeTrajectories:{trajectorySummaries:state.summaries}}[method];
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
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,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -289,7 +289,7 @@ test('repository migration: scrubs legacy yuhuan2498281558 cache URLs/TTL and mi
|
||||
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',
|
||||
sourceUrl: 'https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json',
|
||||
fetchedAtMs: Date.now() - 60_000, // 1 min ago from old repo -> must NOT block non-forced sync to yuhuan-dev
|
||||
fetchedAtMs: Date.now() - 60_000,
|
||||
pricing: {
|
||||
'gemini-4-carbon-high': { input: 2.0, cache: 0.1, output: 10.0, short: 'carbon-4-high', family: 'Gemini' },
|
||||
},
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import vm from 'node:vm';
|
||||
import { createContextWindowSyncExpression } from '../backend/context-windows.mjs';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
|
||||
const argon = 'MODEL_PLACEHOLDER_M430';
|
||||
const flash = 'MODEL_PLACEHOLDER_M431';
|
||||
const other = 'MODEL_PLACEHOLDER_M432';
|
||||
const carbon = 'MODEL_PLACEHOLDER_M427';
|
||||
const carbonLow = 'MODEL_PLACEHOLDER_M438';
|
||||
const newCarbonLow = 'MODEL_PLACEHOLDER_M439';
|
||||
const carbonGroup = 'model:gemini-4-carbon';
|
||||
const availableModels = {
|
||||
'gemini-4-carbon-high': { model: carbon, maxTokens: 1048576, maxOutputTokens: 262144 },
|
||||
'gemini-4-carbon-low': { model: carbonLow, maxTokens: 700000, maxOutputTokens: 64000 },
|
||||
'gemini-other': { model: other, maxTokens: 250000, maxOutputTokens: 64000 },
|
||||
};
|
||||
const carbonModels = [
|
||||
{ label: 'Gemini 4 Carbon (High)', modelId: 'gemini-4-carbon-high', modelOrAlias: { model: carbon } },
|
||||
{ label: 'Gemini 4 Carbon (Low)', modelId: 'gemini-4-carbon-low', modelOrAlias: { model: carbonLow } },
|
||||
];
|
||||
|
||||
test('saves and restores one model at a time using host presets or verified model capacity', async () => {
|
||||
const h = backendHarness({
|
||||
settings: { contextLimitOverrideTokens: 900000 },
|
||||
availableModels,
|
||||
userStatus: {
|
||||
cascadeModelConfigData: {
|
||||
clientModelConfigs: [
|
||||
{ label: 'Argon', modelOrAlias: { model: argon },
|
||||
contextWindowOptions: [{ name: '512K' }, { name: '900K', expensive: true }] },
|
||||
{ label: 'Flash', modelOrAlias: { model: flash }, contextWindowOptions: [{ name: '256K' }] },
|
||||
{ label: 'Other', modelOrAlias: { model: other } },
|
||||
...carbonModels,
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const update = h.executeModelContextWindowAction;
|
||||
const { contextWindowModels } = await h.buildTelemetryPayloadInternal('');
|
||||
const [argonModel, flashModel, otherModel, carbonModel] = JSON.parse(JSON.stringify(contextWindowModels));
|
||||
assert.deepEqual(argonModel.options, [{ name: '512K', expensive: false }, { name: '900K', expensive: true }]);
|
||||
assert.deepEqual(flashModel.options, [{ name: '256K', expensive: false }]);
|
||||
assert.deepEqual(otherModel.options.map(({ tokens }) => tokens), [128000, 186000]);
|
||||
assert.equal(carbonModel.id, carbonGroup);
|
||||
assert.equal(carbonModel.label, 'Gemini 4 Carbon');
|
||||
assert.deepEqual(carbonModel.members, [carbon, carbonLow]);
|
||||
assert.equal(carbonModel.options.at(-1).tokens, 636000);
|
||||
assert.equal((await update({ modelId: carbonGroup, option: '768000' })).status, 400);
|
||||
h.state.settings.modelContextWindows = { [carbon]: '768000', [carbonLow]: '256000' };
|
||||
assert.equal((await update({ modelId: carbonGroup, option: '512000' })).status, 200);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [carbonGroup]: '512000' });
|
||||
assert.equal((await update({ modelId: carbonGroup, option: null })).status, 200);
|
||||
assert.equal((await update({ modelId: flash, option: '900K' })).status, 400);
|
||||
assert.equal((await update({ modelId: other, option: '900K' })).status, 400);
|
||||
assert.equal((await update({ modelId: '__proto__', option: null })).status, 400);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, {});
|
||||
|
||||
const [a, b] = await Promise.all([
|
||||
update({ modelId: argon, option: '900K' }),
|
||||
update({ modelId: flash, option: '256K' }),
|
||||
]);
|
||||
assert.equal(a.status, 200);
|
||||
assert.equal(b.status, 200);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [argon]: '900K', [flash]: '256K' });
|
||||
assert.equal((await update({ modelId: argon, option: null })).status, 200);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [flash]: '256K' });
|
||||
h.executeResetSettingsAction();
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, {});
|
||||
});
|
||||
|
||||
test('reports the latest observed threshold separately from the saved group preference', async () => {
|
||||
const h = backendHarness({
|
||||
availableModels,
|
||||
settings: { modelContextWindows: { [carbonGroup]: '512000' } },
|
||||
userStatus: { cascadeModelConfigData: { clientModelConfigs: carbonModels } },
|
||||
summaries: { active: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:01Z', status: 'IDLE' } },
|
||||
trajectories: {
|
||||
active: { trajectory: {
|
||||
steps: [{ metadata: {
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
finishedGeneratingAt: '2026-01-01T00:00:01Z',
|
||||
modelUsage: { model: carbonLow, inputTokens: 20, outputTokens: 20 },
|
||||
}, plannerResponse: { response: 'ok' } }],
|
||||
generatorMetadata: [{ stepIndices: [0], chatModel: {
|
||||
chatStartMetadata: { contextWindowMetadata: { maxContextTokens: 256000 } },
|
||||
} }],
|
||||
} },
|
||||
},
|
||||
});
|
||||
const result = await h.buildTelemetryPayloadInternal('active');
|
||||
assert.equal(result.contextWindowModels.find(({ id }) => id === carbonGroup).reportedLimitTokens, 256000);
|
||||
assert.equal(result.settings.modelContextWindows[carbonGroup], '512000');
|
||||
const previouslyCached = h.state.saves.find(({ data }) => data.active?.contextLimitTelemetry).data.active;
|
||||
const cached = structuredClone(previouslyCached);
|
||||
delete cached.contextLimitTelemetry;
|
||||
delete cached.steps[0].reportedContextLimitTokens;
|
||||
const upgraded = backendHarness({
|
||||
availableModels,
|
||||
userStatus: h.state.userStatus,
|
||||
cache: { active: cached },
|
||||
summaries: { active: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:01Z', status: 'IDLE' } },
|
||||
trajectories: h.state.trajectories,
|
||||
});
|
||||
const reloaded = await upgraded.buildTelemetryPayloadInternal('active');
|
||||
assert.equal(reloaded.contextWindowModels[0].reportedLimitTokens, 256000);
|
||||
});
|
||||
|
||||
test('host requests apply a rule only to the exact model across App and IDE transports', async () => {
|
||||
const sendPath = '/exa.language_server_pb.LanguageServerService/SendUserCascadeMessage';
|
||||
const statusPath = sendPath.replace('SendUserCascadeMessage', 'GetUserStatus');
|
||||
const host = 'https://127.0.0.1:25190';
|
||||
let catalog = availableModels;
|
||||
let variants = carbonModels;
|
||||
const nativeFetch = async (url, init) => {
|
||||
if (url === host + statusPath.replace('GetUserStatus', 'GetAvailableModels')) {
|
||||
return { ok: true, json: async () => ({ response: { models: catalog } }) };
|
||||
}
|
||||
if (url !== host + statusPath || init.body !== '{}') return init;
|
||||
assert.equal(init.headers['x-codeium-csrf-token'], 'local-test');
|
||||
return { ok: true, json: async () => ({ userStatus: { cascadeModelConfigData: { clientModelConfigs: [
|
||||
{ modelOrAlias: { model: argon }, contextWindowOptions: [{ name: '900K' }] },
|
||||
{ modelOrAlias: { model: flash }, contextWindowOptions: [{ name: '256K' }] },
|
||||
...variants,
|
||||
{ modelOrAlias: { model: other } },
|
||||
] } } }) };
|
||||
};
|
||||
class WebSocket {
|
||||
constructor(url) { this.url = url; }
|
||||
send(data) { return data; }
|
||||
}
|
||||
const nativeSend = WebSocket.prototype.send;
|
||||
const window = { location: new URL(host), fetch: nativeFetch, WebSocket, __APP_CONFIG__: { csrfToken: 'local-test' } };
|
||||
const context = vm.createContext({ window, URL, TextEncoder, TextDecoder, Headers, Uint8Array, AbortSignal, setTimeout, clearTimeout });
|
||||
const install = (rules, boot = 'first') => vm.runInContext(createContextWindowSyncExpression(rules, boot), context);
|
||||
const request = (model) => ({
|
||||
cascadeId: 'conversation-1',
|
||||
items: [{ text: 'Keep the request intact' }],
|
||||
cascadeConfig: {
|
||||
plannerConfig: { planModel: model },
|
||||
checkpointConfig: { maxTokenLimit: 128000, checkpointIntervalTokens: 20000 },
|
||||
},
|
||||
});
|
||||
const options = (body, type = 'application/json') => ({
|
||||
method: 'POST', headers: { 'Content-Type': type }, body,
|
||||
});
|
||||
const preferences = { [argon]: '900K', [flash]: '900K', [carbonGroup]: '512000', [other]: '512000' };
|
||||
await install(preferences);
|
||||
try {
|
||||
const payload = request(argon);
|
||||
const input = options(JSON.stringify(payload));
|
||||
const edited = JSON.parse((await window.fetch(host + sendPath, input)).body);
|
||||
assert.deepEqual(edited, {
|
||||
...payload,
|
||||
cascadeConfig: {
|
||||
...payload.cascadeConfig,
|
||||
checkpointConfig: { contextWindow: '900K', checkpointIntervalTokens: 20000 },
|
||||
},
|
||||
});
|
||||
const untouched = options(JSON.stringify(request(flash)));
|
||||
assert.equal(await window.fetch(host + sendPath, untouched), untouched);
|
||||
const lowCapacity = options(JSON.stringify(request(other)));
|
||||
assert.equal(await window.fetch(host + sendPath, lowCapacity), lowCapacity);
|
||||
const carbonPayload = request(carbon);
|
||||
carbonPayload.cascadeConfig.checkpointConfig.contextWindow = 'default';
|
||||
const carbonBody = (await window.fetch(host + sendPath, options(JSON.stringify(carbonPayload)))).body;
|
||||
assert.deepEqual(JSON.parse(carbonBody).cascadeConfig.checkpointConfig,
|
||||
{ maxTokenLimit: 512000, checkpointIntervalTokens: 20000 });
|
||||
const lowPayload = options(JSON.stringify(request(carbonLow)));
|
||||
assert.equal(JSON.parse((await window.fetch(host + sendPath, lowPayload)).body).cascadeConfig.checkpointConfig.maxTokenLimit, 512000);
|
||||
assert.equal(await window.fetch('https://127.0.0.1:25191' + sendPath, input), input);
|
||||
assert.equal(await window.fetch(host + statusPath, input), input);
|
||||
|
||||
const frame = Buffer.alloc(5 + Buffer.byteLength(input.body));
|
||||
frame.writeUInt32BE(frame.length - 5, 1);
|
||||
frame.write(input.body, 5);
|
||||
const framed = await window.fetch(host + sendPath, options(frame, 'application/grpc-web+json'));
|
||||
assert.equal(Buffer.from(framed.body).readUInt32BE(1), framed.body.length - 5);
|
||||
assert.deepEqual(JSON.parse(Buffer.from(framed.body.subarray(5)).toString()), edited);
|
||||
|
||||
const socket = new WebSocket('wss://127.0.0.1:25190/connect-websocket');
|
||||
const msg = { type: 'start', stream: false, procedure: sendPath, streamId: 'request-1', payload };
|
||||
assert.deepEqual(JSON.parse(socket.send(JSON.stringify(msg))), { ...msg, payload: edited });
|
||||
const unrelated = JSON.stringify({ ...msg, payload: request(flash) });
|
||||
assert.equal(socket.send(unrelated), unrelated);
|
||||
const external = new WebSocket('wss://127.0.0.1:25191/connect-websocket');
|
||||
assert.equal(external.send(JSON.stringify(msg)), JSON.stringify(msg));
|
||||
|
||||
const firstHook = window.fetch;
|
||||
variants = [carbonModels[0], { ...carbonModels[1], modelOrAlias: { model: newCarbonLow } }];
|
||||
catalog = { ...availableModels, 'gemini-4-carbon-low': { ...availableModels['gemini-4-carbon-low'], model: newCarbonLow } };
|
||||
await install(preferences, 'second');
|
||||
assert.notEqual(window.fetch, firstHook);
|
||||
assert.equal(await window.fetch(host + sendPath, lowPayload), lowPayload);
|
||||
window.fetch = nativeFetch;
|
||||
await install(preferences, 'second');
|
||||
const newLowPayload = options(JSON.stringify(request(newCarbonLow)));
|
||||
assert.equal(JSON.parse((await window.fetch(host + sendPath, newLowPayload)).body).cascadeConfig.checkpointConfig.maxTokenLimit, 512000);
|
||||
|
||||
catalog['gemini-4-carbon-low'] = { model: newCarbonLow, maxTokens: 300000, maxOutputTokens: 64000 };
|
||||
await install(preferences, 'third');
|
||||
assert.equal(await window.fetch(host + sendPath, newLowPayload), newLowPayload);
|
||||
assert.equal(await window.fetch(host + sendPath, options(JSON.stringify(carbonPayload))).then(({ body }) => body), JSON.stringify(carbonPayload));
|
||||
} finally {
|
||||
await install({});
|
||||
}
|
||||
assert.equal(window.fetch, nativeFetch);
|
||||
assert.equal(WebSocket.prototype.send, nativeSend);
|
||||
});
|
||||
@@ -3,7 +3,11 @@ import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs';
|
||||
import { formatUsd, resolveModelDisplayInfo } from '../src/core/formatters.js';
|
||||
import {
|
||||
formatUsd,
|
||||
mergeModelsByDisplayName,
|
||||
resolveModelDisplayInfo,
|
||||
} from '../src/core/formatters.js';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
|
||||
const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418';
|
||||
@@ -482,3 +486,213 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and
|
||||
'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].weeklyRemainingPct = 45;
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -396,6 +402,36 @@ test('switching accounts within 10s immediately invalidates quotaSummaryCache',
|
||||
assert.equal(second.quotas.pools[0].weeklyRemainingPct, 8.7);
|
||||
});
|
||||
|
||||
test('late quota results from another account cannot replace the current account cache', async () => {
|
||||
const quota = (remainingFraction) => ({ groups: [{
|
||||
displayName: 'Gemini Models',
|
||||
buckets: [{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction }],
|
||||
}] });
|
||||
const pro = { name: 'Same name', userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' } };
|
||||
let resolvePrevious;
|
||||
const h = backendHarness({
|
||||
userStatus: { ...pro, email: 'a@example.com' },
|
||||
quotaSummary: new Promise((resolve) => { resolvePrevious = resolve; }),
|
||||
});
|
||||
const previous = h.buildTelemetryPayloadInternal('none');
|
||||
while (!h.state.calls.some(({ method }) => method === 'RetrieveUserQuotaSummary')) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
h.state.userStatus = { ...pro, email: 'b@example.com' };
|
||||
h.state.quotaSummary = quota(0.24);
|
||||
const switched = await h.buildTelemetryPayloadInternal('none');
|
||||
assert.equal(switched.account.email, 'b@example.com');
|
||||
assert.equal(switched.quotas.pools.find(({ poolKey }) => poolKey === 'Gemini').weeklyRemainingPct, 24);
|
||||
|
||||
resolvePrevious(quota(0.75));
|
||||
const stale = await previous;
|
||||
assert.equal(stale.quotas.meta.hasOfficialData, false);
|
||||
const refreshed = await h.buildTelemetryPayloadInternal('none');
|
||||
assert.equal(refreshed.account.email, 'b@example.com');
|
||||
assert.equal(refreshed.quotas.pools.find(({ poolKey }) => poolKey === 'Gemini').weeklyRemainingPct, 24);
|
||||
});
|
||||
|
||||
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';
|
||||
@@ -483,3 +519,140 @@ test('Orchestrator quota pool binding follows active phase: Carbon/Argon while p
|
||||
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)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs';
|
||||
import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs';
|
||||
|
||||
function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,response=1000,
|
||||
thinkingDuration='4s',tools=false,text=true,status='CORTEX_STEP_STATUS_DONE'}={}) {
|
||||
@@ -72,6 +72,26 @@ test('unfinished, missing-completion and reversed-time requests cannot fabricate
|
||||
assert.equal(parse({total:0}).totalTokPerSec,null);
|
||||
assert.equal(parse({status:'CORTEX_STEP_STATUS_GENERATING'}).totalTokPerSec,null);
|
||||
});
|
||||
test('cleared steps with a recorded generation end retain their original request speed',()=>{
|
||||
const {s,gm}=sample({status:'CORTEX_STEP_STATUS_CLEARED'});
|
||||
s.metadata.completedAt='2026-01-01T00:04:00Z';
|
||||
const [cleared]=extractModelSteps([s],[gm]);
|
||||
assert.equal(cleared.totalDurationSec,12);
|
||||
assert.equal(cleared.totalTokPerSec,1100/12);
|
||||
assert.equal(cleared.isComplete,true);
|
||||
|
||||
for(const status of ['CORTEX_STEP_STATUS_CANCELED','CORTEX_STEP_STATUS_ERROR','CORTEX_STEP_STATUS_GENERATING']){
|
||||
assert.equal(extractModelSteps([{...s,status}],[gm])[0].totalTokPerSec,null);
|
||||
}
|
||||
const [canceled]=extractModelSteps([{...s,status:'CORTEX_STEP_STATUS_CANCELED'}],[gm]);
|
||||
assert.equal(speedMetric(canceled).reason,'canceled');
|
||||
delete s.metadata.finishedGeneratingAt;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
|
||||
const [checkpoint]=extractModelSteps([{...s,type:'CORTEX_STEP_TYPE_CHECKPOINT'}],[gm]);
|
||||
assert.equal(speedMetric(checkpoint).value,null);
|
||||
assert.equal(speedMetric(checkpoint).reason,'compaction_timing_unavailable');
|
||||
assert.equal(summarizeSpeed([checkpoint,canceled]).sampleCount,0);
|
||||
});
|
||||
test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{
|
||||
const zero=parse({output:0,response:0,thinking:0});
|
||||
assert.equal(zero.totalTokPerSec,0);assert.equal(zero.responseTokens,0);
|
||||
@@ -281,3 +301,108 @@ test('extractLiveActivity covers thinking, partial streaming tool args, multi-to
|
||||
assert.equal(actTranscript2.stepProgress, '2/2');
|
||||
assert.equal(actTranscript2.detail, '列出插件项目全部源文件 (Get-ChildItem -Path "f:\\ppt")');
|
||||
});
|
||||
|
||||
test('extractModelSteps tracks sequential user turns, merges consecutive prompts, marks media, and strips compaction context summaries', () => {
|
||||
const mkModelStep = (stepIndex) => ({
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
metadata: {
|
||||
sourceTrajectoryStepInfo: { stepIndex },
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
finishedGeneratingAt: '2026-01-01T00:00:02Z',
|
||||
modelUsage: { inputTokens: '100', cacheReadTokens: '200', outputTokens: '80' },
|
||||
},
|
||||
plannerResponse: { response: 'ok' },
|
||||
});
|
||||
|
||||
const steps = extractModelSteps([
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_USER_INPUT',
|
||||
userInput: { userResponse: '第一轮提问' },
|
||||
},
|
||||
mkModelStep(1),
|
||||
{ type: 'CORTEX_STEP_TYPE_VIEW_FILE' },
|
||||
mkModelStep(3),
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_USER_INPUT',
|
||||
userInput: { userResponse: '取消前一句' },
|
||||
},
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_USER_INPUT',
|
||||
userInput: { userResponse: '第二轮补充提问', media: [{}] },
|
||||
},
|
||||
mkModelStep(7),
|
||||
{
|
||||
type: 'USER_INPUT',
|
||||
content:
|
||||
'<CONTEXT_SUMMARY><USER_REQUEST>旧摘要文本</USER_REQUEST></CONTEXT_SUMMARY>\n<USER_REQUEST>\n 第三轮真实提问 \n</USER_REQUEST>\n<ADDITIONAL_METADATA>ignored</ADDITIONAL_METADATA>',
|
||||
},
|
||||
mkModelStep(9),
|
||||
]);
|
||||
|
||||
assert.equal(steps.length, 4);
|
||||
assert.equal(steps[0].turnIndex, 1);
|
||||
assert.equal(steps[0].isTurnStart, true);
|
||||
assert.equal(steps[0].turnPrompt, '第一轮提问');
|
||||
|
||||
assert.equal(steps[1].turnIndex, 1);
|
||||
assert.equal(steps[1].isTurnStart, false);
|
||||
assert.equal(steps[1].turnPrompt, undefined);
|
||||
|
||||
assert.equal(steps[2].turnIndex, 2);
|
||||
assert.equal(steps[2].isTurnStart, true);
|
||||
assert.equal(steps[2].turnPrompt, '取消前一句\n第二轮补充提问 [附图]');
|
||||
|
||||
assert.equal(steps[3].turnIndex, 3);
|
||||
assert.equal(steps[3].isTurnStart, true);
|
||||
assert.equal(steps[3].turnPrompt, '第三轮真实提问');
|
||||
});
|
||||
|
||||
test('extractContextBreakdown parses split top-level SKILLS, RULES, SUBAGENTS, and PLUGINS groups without dropping tokens', () => {
|
||||
const breakdown = extractContextBreakdown({
|
||||
chatStartMetadata: {
|
||||
contextWindowMetadata: {
|
||||
estimatedTokensUsed: 148852,
|
||||
maxContextTokens: 256000,
|
||||
tokenBreakdown: {
|
||||
totalTokens: 148852,
|
||||
groups: [
|
||||
{ type: 'TOKEN_TYPE_SYSTEM_PROMPT', name: 'System Prompt', numTokens: 5505 },
|
||||
{ type: 'TOKEN_TYPE_MCP_TOOLS', name: 'Mcp Tools', numTokens: 234 },
|
||||
{ type: 'TOKEN_TYPE_SUBAGENTS', name: 'Subagents', numTokens: 1741 },
|
||||
{ type: 'TOKEN_TYPE_SKILLS', name: 'Skills', numTokens: 2201 },
|
||||
{ type: 'TOKEN_TYPE_PLUGINS', name: 'Plugins', numTokens: 1601 },
|
||||
{ type: 'TOKEN_TYPE_RULES', name: 'Rules', numTokens: 2282 },
|
||||
{ type: 'TOKEN_TYPE_TOOLS', name: 'Tools', numTokens: 8857 },
|
||||
{
|
||||
type: 'TOKEN_TYPE_CHAT_MESSAGES',
|
||||
name: 'Chat Messages',
|
||||
numTokens: 126431,
|
||||
children: [
|
||||
{ name: '2449: CHECKPOINT', numTokens: 5087 },
|
||||
{ name: '2450: USER_INPUT', numTokens: 281 },
|
||||
{ name: '2455: SYSTEM_MESSAGE', numTokens: 179 },
|
||||
{ name: '2502: PLANNER_RESPONSE', numTokens: 15017 },
|
||||
{ name: '2503: GENERIC', numTokens: 105867 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.ok(breakdown);
|
||||
assert.equal(breakdown.skillsTokens, 2201);
|
||||
assert.equal(breakdown.userRulesTokens, 2282);
|
||||
assert.equal(breakdown.systemPromptTokens, 5505 + 1741 + 1601);
|
||||
assert.equal(breakdown.mcpToolsTokens, 234);
|
||||
assert.equal(breakdown.systemToolsTokens, 8857);
|
||||
assert.equal(breakdown.checkpointTokens, 5087);
|
||||
assert.equal(breakdown.userInputTokens, 281);
|
||||
assert.equal(breakdown.subagentTokens, 179);
|
||||
assert.equal(breakdown.assistantTokens, 15017);
|
||||
assert.equal(breakdown.toolResultsTokens, 105867);
|
||||
assert.equal(breakdown.messagesTokens, 126431);
|
||||
assert.equal(breakdown.totalTokens, 148852);
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user