diff --git a/.gitignore b/.gitignore
index 8739bcb..524df6a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,8 @@
.data/
node_modules/
plan/
+dist/
+usage-monitor.zip
*.log
*.dpapi
.account-test-*
diff --git a/README.md b/README.md
index 0fd77ff..1a3af90 100644
--- a/README.md
+++ b/README.md
@@ -117,25 +117,7 @@ English · [简体中文](README.zh-CN.md)
Keep the folder name as `usage-monitor`. **No `npm install` is needed.**
-### Option 1: Git Clone
-
-```powershell
-# Windows (PowerShell)
-git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
-```
-
-```bash
-# macOS / Linux
-git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
-```
-
-Or ask Antigravity directly:
-
-```text
-Clone https://github.com/yuhuan-dev/antigravity-usage-monitor to ~/.gemini/config/plugins/usage-monitor and enable the plugin
-```
-
-### Option 2: Release ZIP
+### Option 1: Release ZIP
Download [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip) and extract it into `~/.gemini/config/plugins/` so the directory path is `~/.gemini/config/plugins/usage-monitor`.
@@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
+### Option 2: Git Clone
+
+```powershell
+# Windows (PowerShell)
+git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
+```
+
+```bash
+# macOS / Linux
+git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
+```
+
+Or ask Antigravity directly:
+
+```text
+Clone https://github.com/yuhuan-dev/antigravity-usage-monitor with --filter=blob:none --single-branch to ~/.gemini/config/plugins/usage-monitor and enable the plugin
+```
+
---
## Usage
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 0a27513..550ec68 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -117,30 +117,12 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、
插件目录名需保持为 `usage-monitor`,**无需运行 `npm install`**。
-### 方式一:Git 克隆
-
-```powershell
-# Windows PowerShell
-git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
-```
-
-```bash
-# macOS / Linux
-git clone https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
-```
-
-也可以直接在 Antigravity 对话中执行:
-
-```text
-把 https://github.com/yuhuan-dev/antigravity-usage-monitor 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件
-```
-
-### 方式二:下载 Release 压缩包
+### 方式一:下载 Release 压缩包
下载 [`usage-monitor.zip`](https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip),解压到 `~/.gemini/config/plugins/` 下并保持文件夹名为 `usage-monitor`。
-Windows PowerShell 下载与解压命令
+Windows PowerShell 下载及解压命令
```powershell
$pluginsDir = "$env:USERPROFILE\.gemini\config\plugins"
@@ -151,6 +133,24 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
+### 方式二:Git 克隆
+
+```powershell
+# Windows PowerShell
+git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git "$env:USERPROFILE\.gemini\config\plugins\usage-monitor"
+```
+
+```bash
+# macOS / Linux
+git clone --filter=blob:none --single-branch https://github.com/yuhuan-dev/antigravity-usage-monitor.git ~/.gemini/config/plugins/usage-monitor
+```
+
+也可以直接在 Antigravity 对话中执行:
+
+```text
+把 https://github.com/yuhuan-dev/antigravity-usage-monitor 用 --filter=blob:none --single-branch 克隆到 ~/.gemini/config/plugins/usage-monitor 并启用插件
+```
+
---
## 使用方式
diff --git a/plugin.json b/plugin.json
index 1342256..ca8c3bd 100644
--- a/plugin.json
+++ b/plugin.json
@@ -1,7 +1,7 @@
{
"name": "usage-monitor",
"displayName": "Usage & Speed Monitor",
- "version": "1.5.1",
+ "version": "1.5.2",
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
"logo": "assets/logo.svg",
"suggestedPrompts": [
diff --git a/pricing-catalog.json b/pricing-catalog.json
index 8df9fe4..d2d403a 100644
--- a/pricing-catalog.json
+++ b/pricing-catalog.json
@@ -1,8 +1,8 @@
{
"schemaVersion": 1,
- "catalogVersion": "2026.11.19.1",
- "updatedAt": "2026-11-19T09:20:00+09:00",
- "latestPluginVersion": "1.5.1",
+ "catalogVersion": "2026.11.19.2",
+ "updatedAt": "2026-11-19T09:35:00+09:00",
+ "latestPluginVersion": "1.5.2",
"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",
diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js
index 4d62a6d..a512d4d 100644
--- a/sidecars/panel/app.js
+++ b/sidecars/panel/app.js
@@ -2,7 +2,7 @@
'use strict';
// --- shared/settings-normalization.mjs ---
-const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort } = (() => {
+const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi } = (() => {
/**
* @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。
*/
@@ -451,7 +451,21 @@ function normalizeStandalonePort(port) {
if (num >= 1024 && num <= 65535) return num;
return 0;
}
-return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort };
+
+/**
+ * 归一化实验性现代化新 UI 开关(默认 `false`)。
+ *
+ * @param {unknown} val
+ * @returns {boolean}
+ */
+function normalizeExperimentalModernUi(val) {
+ if (typeof val === 'string') {
+ const lower = val.trim().toLowerCase();
+ return lower === 'true' || lower === '1' || lower === 'on';
+ }
+ return Boolean(val);
+}
+return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeExperimentalModernUi };
})();
// --- shared/telemetry-display-rules.mjs ---
@@ -1043,6 +1057,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'header.lockedSession': '已锁定会话 ({id})',
'header.lockedMeta': '已锁定',
'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)',
+ 'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)',
+ 'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)',
'header.convMetaSteps': '{count}步',
'header.hasUpdate': '有新版本',
'header.upgradeToVer': '升级 v{ver}',
@@ -1061,6 +1077,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'fmt.pending': '待定',
'fmt.speedIncomplete': '计时不完整',
'fmt.speedCanceled': '已取消',
+ 'fmt.speedError': '调用报错',
+ 'fmt.speedInterrupted': '连接中断',
'fmt.speedCompactionTimingUnavailable': '压缩无计时',
'fmt.speedInvalidOutput': '无有效输出',
'fmt.speedInconsistent': '耗时数据异常',
@@ -1081,6 +1099,11 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'fmt.subAgent': '子代理',
'fmt.subBadge': '子{index}',
'fmt.subBadgeShort': '子',
+ 'fmt.swarmAgent': '蜂群',
+ 'fmt.swarmBadge': '蜂{index}',
+ 'fmt.swarmBadgeShort': '蜂',
+ 'fmt.swarmMonitorHint': '巡检',
+ 'fmt.swarmNarratorHint': '旁白',
'fmt.sideQuestion': '旁路提问',
'fmt.sideBadge': '旁{index}',
'fmt.sideBadgeShort': '旁',
@@ -1094,6 +1117,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'capsule.multiZero': '0 运行中',
'capsule.multiRunning': '{count} 运行中',
'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子',
+ 'capsule.multiRunningWithSwarm': '{count} 运行 · {subs} 蜂',
'capsule.tpsRunning': '生成中',
'capsule.tpsIdle': '待命',
'capsule.quotaLeft': '余 {pct}%',
@@ -1114,6 +1138,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'multi.empty': '当前暂无在线运行的会话',
'multi.allIdle': '全部待命',
'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中',
+ 'multi.metaWithSwarm': '{main} 主会话 · {subs} 蜂群运行中',
'multi.metaMainOnly': '{main} 个会话运行中',
'multi.hereTag': '本窗',
'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}',
@@ -1162,9 +1187,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
// Context Window Widget
'ctx.followActive': '跟随活跃 ({badge})',
'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口',
- 'ctx.expandMore': '+{count} 展开 ▾',
+ 'ctx.expandMore': '+{count} 展开',
'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊',
- 'ctx.collapse': '收起 ▴',
+ 'ctx.collapse': '收起',
'ctx.collapseTitle': '折叠多余子代理胶囊',
'ctx.ch.assistant': '模型回复',
'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参',
@@ -1210,14 +1235,21 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'live.thinking': '推理中',
'live.generating': '生成中',
'live.running': '运行中',
+ 'live.waiting': '待命中',
+ 'live.killed': '已终止',
'live.done': '已完成',
'live.doneWithSteps': '已完成 ({steps} 步)',
- 'live.subToggleRunning': '子代理 {run}/{total} {arrow}',
- 'live.subToggleIdle': '子代理 ({total}) {arrow}',
+ 'live.waitingWithSteps': '待命中 ({steps} 步)',
+ 'live.killedWithSteps': '已终止 ({steps} 步)',
+ 'live.subToggleRunning': '子代理 {run}/{total}',
+ 'live.subToggleIdle': '子代理 ({total})',
+ 'live.swarmToggleRunning': '蜂群 {run}/{total}',
+ 'live.swarmToggleIdle': '蜂群 ({total})',
'live.subCollapseTitle': '点击收起子代理列表',
'live.subExpandTitle': '点击展开查看子代理缩略状态',
// Consumption View
+ 'cons.rangeCycle': '周期',
'cons.rangeToday': '今天',
'cons.range24h': '1天',
'cons.range7d': '7天',
@@ -1249,6 +1281,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.clientSources': '客户端来源',
'cons.monthlyTitle': '月度统计',
'cons.monthLabel': '{m}月',
+ 'cons.monthFullLabel': '{year}年 {m}月',
+ 'cons.hoverModelsHint': '悬停查看模型',
+ 'cons.otherModelsCount': '其他 ({count})',
'cons.legInput': '输入',
'cons.legCache': '缓存',
'cons.legOutput': '输出',
@@ -1306,6 +1341,38 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)',
'steps.turnMediaOnly': '[图片/附件提问]',
'steps.turnMediaSuffix': '[附图]',
+ 'steps.anomalyTag.timeout': '超时{n}',
+ 'steps.anomalyTag.rate_limit': '限流{n}',
+ 'steps.anomalyTag.capacity': '503×{n}',
+ 'steps.anomalyTag.capacitySingle': '503',
+ 'steps.anomalyTag.disconnect': '断连{n}',
+ 'steps.anomalyTag.upstream': '500×{n}',
+ 'steps.anomalyTag.upstreamSingle': '500',
+ 'steps.anomalyTag.model_output': '纠偏{n}',
+ 'steps.anomalyTag.safety': '过滤{n}',
+ 'steps.anomalyTag.auth_or_model': '受限{n}',
+ 'steps.anomalyTag.error': '报错{n}',
+ 'steps.anomalyTag.mixed': '异常{n}',
+ 'steps.anomalyKind.timeout': '流空闲 / 连接超时',
+ 'steps.anomalyKind.rate_limit': '429 限流 / 配额耗尽',
+ 'steps.anomalyKind.capacity': '503 上游算力不足',
+ 'steps.anomalyKind.disconnect': '连接中断 / 断流',
+ 'steps.anomalyKind.upstream': '上游 5xx 内部错误',
+ 'steps.anomalyKind.model_output': '模型输出 / 工具参数无效',
+ 'steps.anomalyKind.safety': '内容安全过滤',
+ 'steps.anomalyKind.auth_or_model': '请求受限 / 模型不可用',
+ 'steps.anomalyKind.error': '调用异常',
+ 'steps.anomalyKind.canceled': '用户取消',
+ 'steps.anomalyStepTitle': '#{step} · 异常 {count} 次',
+ 'steps.anomalyDelayPart': '退避 {sec}s',
+ 'steps.anomalyTerminalTag': '中止',
+ 'steps.anomalyModelTitle': '{model} · 异常 {count} 次',
+ 'steps.anomalyModelSub': '涉及 {steps} 步',
+ 'steps.anomalyModelKindRow': '{kind}:{count} 次',
+ 'steps.anomalyModelClickHint': '点击前往「按步查看」筛选异常步',
+ 'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)',
+ 'steps.anomalyFilterLabel': '仅看异常 ({count})',
+ 'steps.anomalyFilterAll': '返回全部步骤',
// Step Table Columns (Headers & Option Labels)
'stepCol.step.th': '步序',
@@ -1414,6 +1481,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.gen.fontLg': '大',
'settings.gen.fontXl': '特大',
'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高',
+ 'settings.gen.modernUi': '新 UI(实验性)',
+ 'settings.gen.modernUiOff': '关闭',
+ 'settings.gen.modernUiOn': '开启',
+ 'settings.gen.modernUiHint': '去除大部分线框,采用柔和分层底色与更流畅的现代过渡动画',
'settings.gen.updateTitle': '版本更新',
'settings.gen.updateMode': '更新方式',
'settings.gen.updateManual': '仅提示新版本,手动更新',
@@ -1463,14 +1534,20 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.str.mountSidebar': '仅侧边栏',
'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊',
'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写',
- 'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。',
+ 'settings.bridge.restartBody': '已自动为快捷方式、自启项及协议关联写入 --remote-debugging-port=0(后续通过常规快捷方式打开均自动生效)。点击下方按钮即可退出后台进程并立即生效。',
+ 'settings.bridge.readOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可生效',
+ 'settings.bridge.ctxReadOnlyTitle': '公共桌面快捷方式受权限保护,授权重启即可激活上下文覆写',
+ 'settings.bridge.readOnlyBody': '个人启动项已配好,但公共桌面或开始菜单快捷方式需管理员权限修改。点击下方按钮并在系统弹窗中确认授权,即可一次性修补公共图标并带参重开(后续日常打开均自动生效)。',
+ 'settings.bridge.macTitle': '当前会话未开启调试端口,一键重开即可启用挂载',
+ 'settings.bridge.ctxMacTitle': '当前会话未开启调试端口,一键重开即可激活上下文覆写',
'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效',
'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效',
'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入',
'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。',
- 'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。',
+ 'settings.bridge.guideMac': '受 macOS 应用签名限制,从 Dock 直接冷启动默认不带调试端口参数。点击下方按钮即可一键带参重开恢复(日常仅关窗不完全退出 Cmd+Q 则持续有效)。',
'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。',
'settings.bridge.relaunchBtn': '立即重启并启用挂载',
+ 'settings.bridge.relaunchAuthBtn': '授权修补并立即重启',
'settings.bridge.relaunchingBtn': '正在重启客户端...',
'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试',
'settings.bridge.dismissAria': '暂时关闭提示',
@@ -1578,6 +1655,15 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'live.act.invoke_subagent': '调用子代理',
'live.act.send_message': '通信子代理',
'live.act.manage_subagents': '管理子代理',
+ 'live.act.swarm_add': '派生工蜂',
+ 'live.act.swarm_title': '命名蜂群',
+ 'live.act.swarm_kill': '终止工蜂',
+ 'live.act.swarm_model': '切换工蜂模型',
+ 'live.act.swarm_channel': '蜂群频道',
+ 'live.act.swarm_status': '巡检蜂群',
+ 'live.act.post_message': '发布看板',
+ 'live.act.read_board': '读取看板',
+ 'live.act.swarm_wait': '看板待命',
'live.act.manage_task': '后台任务',
'live.act.schedule': '定时任务',
'live.act.ask_question': '等待用户选择',
@@ -1588,6 +1674,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'live.act.compacting': '上下文压缩',
'live.act.responding': '正在输出回复',
'live.act.waiting_subagent': '等待子代理',
+ 'live.act.waiting_swarm': '等待工蜂',
+ 'live.act.swarm_waiting': '待命中',
+ 'live.act.swarm_killed': '已终止',
'live.act.starting': '启动中',
'live.act.done': '已完成',
'live.act.awaitingApproval': '等待确认 · {label}',
@@ -1673,6 +1762,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'header.lockedSession': 'Pinned Session ({id})',
'header.lockedMeta': 'Pinned',
'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)',
+ 'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)',
+ 'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)',
'header.convMetaSteps': '{count} steps',
'header.hasUpdate': 'Update',
'header.upgradeToVer': 'Update v{ver}',
@@ -1691,6 +1782,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'fmt.pending': 'N/A',
'fmt.speedIncomplete': 'Incomplete timing',
'fmt.speedCanceled': 'Canceled',
+ 'fmt.speedError': 'Call error',
+ 'fmt.speedInterrupted': 'Interrupted',
'fmt.speedCompactionTimingUnavailable': 'Untimed compaction',
'fmt.speedInvalidOutput': 'No valid output',
'fmt.speedInconsistent': 'Invalid timing',
@@ -1711,6 +1804,11 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'fmt.subAgent': 'Subagent',
'fmt.subBadge': 'S{index}',
'fmt.subBadgeShort': 'Sub',
+ 'fmt.swarmAgent': 'Swarm',
+ 'fmt.swarmBadge': 'W{index}',
+ 'fmt.swarmBadgeShort': 'Swarm',
+ 'fmt.swarmMonitorHint': 'Monitor',
+ 'fmt.swarmNarratorHint': 'Narrator',
'fmt.sideQuestion': 'Side Question',
'fmt.sideBadge': 'Q{index}',
'fmt.sideBadgeShort': 'Q',
@@ -1724,6 +1822,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'capsule.multiZero': '0 active',
'capsule.multiRunning': '{count} active',
'capsule.multiRunningWithSubs': '{count} active · {subs} sub',
+ 'capsule.multiRunningWithSwarm': '{count} active · {subs} swarm',
'capsule.tpsRunning': 'Running',
'capsule.tpsIdle': 'Idle',
'capsule.quotaLeft': '{pct}% left',
@@ -1744,6 +1843,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'multi.empty': 'No active running sessions',
'multi.allIdle': 'All idle',
'multi.metaWithSubs': '{main} main · {subs} subagents active',
+ 'multi.metaWithSwarm': '{main} main · {subs} swarm active',
'multi.metaMainOnly': '{main} sessions active',
'multi.hereTag': 'Here',
'multi.inspectSessionTitle': 'Inspect session in monitor: {title}',
@@ -1792,9 +1892,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({
// Context Window Widget
'ctx.followActive': 'Follow Active ({badge})',
'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window',
- 'ctx.expandMore': '+{count} More ▾',
+ 'ctx.expandMore': '+{count} More',
'ctx.expandMoreTitle': 'Expand all {count} subagent context pills',
- 'ctx.collapse': 'Less ▴',
+ 'ctx.collapse': 'Less',
'ctx.collapseTitle': 'Collapse extra subagent pills',
'ctx.ch.assistant': 'Assistant',
'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments',
@@ -1840,14 +1940,21 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'live.thinking': 'Thinking',
'live.generating': 'Generating',
'live.running': 'Running',
+ 'live.waiting': 'Waiting',
+ 'live.killed': 'Killed',
'live.done': 'Done',
'live.doneWithSteps': 'Done ({steps} steps)',
- 'live.subToggleRunning': 'Subagents {run}/{total} {arrow}',
- 'live.subToggleIdle': 'Subagents ({total}) {arrow}',
+ 'live.waitingWithSteps': 'Waiting ({steps} steps)',
+ 'live.killedWithSteps': 'Killed ({steps} steps)',
+ 'live.subToggleRunning': 'Subagents {run}/{total}',
+ 'live.subToggleIdle': 'Subagents ({total})',
+ 'live.swarmToggleRunning': 'Swarm {run}/{total}',
+ 'live.swarmToggleIdle': 'Swarm ({total})',
'live.subCollapseTitle': 'Collapse subagent list',
'live.subExpandTitle': 'Expand subagent activity list',
// Consumption View
+ 'cons.rangeCycle': 'Cycle',
'cons.rangeToday': 'Today',
'cons.range24h': '24h',
'cons.range7d': '7d',
@@ -1879,6 +1986,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'cons.clientSources': 'Client Sources',
'cons.monthlyTitle': 'Monthly Breakdown',
'cons.monthLabel': 'M{m}',
+ 'cons.monthFullLabel': 'M{m}, {year}',
+ 'cons.hoverModelsHint': 'Hover for models',
+ 'cons.otherModelsCount': 'Others ({count})',
'cons.legInput': 'Input',
'cons.legCache': 'Cache',
'cons.legOutput': 'Output',
@@ -1936,6 +2046,38 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)',
'steps.turnMediaOnly': '[Media Attachment]',
'steps.turnMediaSuffix': '[Media]',
+ 'steps.anomalyTag.timeout': 'TO{n}',
+ 'steps.anomalyTag.rate_limit': '429×{n}',
+ 'steps.anomalyTag.capacity': '503×{n}',
+ 'steps.anomalyTag.capacitySingle': '503',
+ 'steps.anomalyTag.disconnect': 'Drop{n}',
+ 'steps.anomalyTag.upstream': '500×{n}',
+ 'steps.anomalyTag.upstreamSingle': '500',
+ 'steps.anomalyTag.model_output': 'Fix{n}',
+ 'steps.anomalyTag.safety': 'Safe{n}',
+ 'steps.anomalyTag.auth_or_model': 'Err{n}',
+ 'steps.anomalyTag.error': 'Err{n}',
+ 'steps.anomalyTag.mixed': 'Warn{n}',
+ 'steps.anomalyKind.timeout': 'Stream Idle / Connect Timeout',
+ 'steps.anomalyKind.rate_limit': '429 Rate Limit / Quota Reached',
+ 'steps.anomalyKind.capacity': '503 No Capacity Available',
+ 'steps.anomalyKind.disconnect': 'Connection Reset / Stream Interrupted',
+ 'steps.anomalyKind.upstream': 'Upstream 5xx Internal Error',
+ 'steps.anomalyKind.model_output': 'Invalid Model Output / Tool Call',
+ 'steps.anomalyKind.safety': 'Content Safety Filter',
+ 'steps.anomalyKind.auth_or_model': 'Request / Model Rejected',
+ 'steps.anomalyKind.error': 'Call Error',
+ 'steps.anomalyKind.canceled': 'Canceled by User',
+ 'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors',
+ 'steps.anomalyDelayPart': 'Backoff {sec}s',
+ 'steps.anomalyTerminalTag': 'Stopped',
+ 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors',
+ 'steps.anomalyModelSub': '{steps} steps affected',
+ 'steps.anomalyModelKindRow': '{kind}: {count}',
+ 'steps.anomalyModelClickHint': 'Click to filter anomalous steps',
+ 'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)',
+ 'steps.anomalyFilterLabel': 'Anomalies Only ({count})',
+ 'steps.anomalyFilterAll': 'Show All Steps',
// Step Table Columns (Headers & Option Labels)
'stepCol.step.th': 'Step',
@@ -2044,6 +2186,10 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'settings.gen.fontLg': 'Large',
'settings.gen.fontXl': 'XL',
'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact',
+ 'settings.gen.modernUi': 'Modern UI (Experimental)',
+ 'settings.gen.modernUiOff': 'Off',
+ 'settings.gen.modernUiOn': 'On',
+ 'settings.gen.modernUiHint': 'Removes most borders in favor of soft tonal surfaces and smoother animations',
'settings.gen.updateTitle': 'Updates & Pricing',
'settings.gen.updateMode': 'Update Policy',
'settings.gen.updateManual': 'Notify only, update manually',
@@ -2093,14 +2239,20 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'settings.str.mountSidebar': 'Sidebar Only',
'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate',
'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override',
- 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.',
+ 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts, startup entries, and protocol handlers (subsequent shortcut launches mount automatically). Click below to close background processes and relaunch now.',
+ 'settings.bridge.readOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch to Activate',
+ 'settings.bridge.ctxReadOnlyTitle': 'Public Shortcut Protected — Authorize & Relaunch for Context Override',
+ 'settings.bridge.readOnlyBody': 'Personal launch entries are configured, but public shortcuts require administrator permission. Click below and approve the system prompt to patch public shortcuts once and relaunch.',
+ 'settings.bridge.macTitle': 'Debug Port Inactive — One-Click Relaunch to Enable Mount',
+ 'settings.bridge.ctxMacTitle': 'Debug Port Inactive — One-Click Relaunch for Context Override',
'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive',
'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive',
'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending',
'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.',
- 'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.',
+ 'settings.bridge.guideMac': 'Due to macOS app code signing, cold launches from Dock omit the debug port flag. Click below to relaunch with the flag in one click (stays active until you fully Quit via Cmd+Q).',
'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.',
'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount',
+ 'settings.bridge.relaunchAuthBtn': 'Authorize & Relaunch',
'settings.bridge.relaunchingBtn': 'Relaunching Host...',
'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry',
'settings.bridge.dismissAria': 'Dismiss notice for now',
@@ -2208,6 +2360,15 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'live.act.invoke_subagent': 'Invoke Subagent',
'live.act.send_message': 'Message Subagent',
'live.act.manage_subagents': 'Manage Subagents',
+ 'live.act.swarm_add': 'Spawn Worker',
+ 'live.act.swarm_title': 'Name Swarm',
+ 'live.act.swarm_kill': 'Kill Worker',
+ 'live.act.swarm_model': 'Switch Worker Model',
+ 'live.act.swarm_channel': 'Swarm Channel',
+ 'live.act.swarm_status': 'Check Swarm',
+ 'live.act.post_message': 'Post to Board',
+ 'live.act.read_board': 'Read Board',
+ 'live.act.swarm_wait': 'Parked on Board',
'live.act.manage_task': 'Manage Task',
'live.act.schedule': 'Schedule Task',
'live.act.ask_question': 'Waiting for User Choice',
@@ -2218,6 +2379,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'live.act.compacting': 'Compacting Context',
'live.act.responding': 'Responding',
'live.act.waiting_subagent': 'Waiting for Subagent',
+ 'live.act.waiting_swarm': 'Waiting for Swarm',
+ 'live.act.swarm_waiting': 'Waiting',
+ 'live.act.swarm_killed': 'Killed',
'live.act.starting': 'Starting',
'live.act.done': 'Completed',
'live.act.awaitingApproval': 'Awaiting Approval · {label}',
@@ -2353,7 +2517,7 @@ return { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nS
})();
// --- src/core/appearance.js ---
-const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot } = (() => {
+const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot } = (() => {
/**
* @fileoverview Theme accent palette & panel font-scale appearance engine.
* Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts,
@@ -2394,23 +2558,342 @@ function normalizeClientFontScale(raw) {
return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md';
}
+function normalizeClientModernUi(raw) {
+ if (typeof raw === 'string') {
+ const lower = raw.trim().toLowerCase();
+ return lower === 'true' || lower === '1' || lower === 'on';
+ }
+ return Boolean(raw);
+}
+
+/**
+ * Check whether `el` (or its Shadow DOM host / document root) is currently under `[data-modern-ui="true"]`.
+ *
+ * @param {Node | null | undefined} el
+ * @returns {boolean}
+ */
+function isModernUiActiveForElement(el) {
+ let cur = el || null;
+ while (cur) {
+ if (typeof cur.getAttribute === 'function' && cur.getAttribute('data-modern-ui') === 'true') {
+ return true;
+ }
+ if (cur.parentNode) {
+ cur = cur.parentNode;
+ } else if (cur.host) {
+ cur = cur.host;
+ } else {
+ break;
+ }
+ }
+ if (typeof document !== 'undefined' && document.documentElement) {
+ return document.documentElement.getAttribute?.('data-modern-ui') === 'true';
+ }
+ return false;
+}
+
+const LIGHT_THEME_CLASSES = new Set([
+ 'light',
+ 'vs-light',
+ 'vscode-light',
+ 'hc-light',
+ 'vscode-high-contrast-light',
+]);
+
+const DARK_THEME_CLASSES = new Set([
+ 'dark',
+ 'vs-dark',
+ 'vscode-dark',
+ 'hc-black',
+ 'vscode-high-contrast',
+]);
+
+function hslToRgb(hDeg, sPct, lPct) {
+ const h = (((hDeg % 360) + 360) % 360) / 360;
+ const s = Math.max(0, Math.min(1, sPct / 100));
+ const l = Math.max(0, Math.min(1, lPct / 100));
+ if (s === 0) {
+ const v = l * 255;
+ return [v, v, v];
+ }
+ const hue2rgb = (p, q, t) => {
+ let tt = t;
+ if (tt < 0) tt += 1;
+ if (tt > 1) tt -= 1;
+ if (tt < 1 / 6) return p + (q - p) * 6 * tt;
+ if (tt < 1 / 2) return q;
+ if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
+ return p;
+ };
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ const p = 2 * l - q;
+ return [
+ hue2rgb(p, q, h + 1 / 3) * 255,
+ hue2rgb(p, q, h) * 255,
+ hue2rgb(p, q, h - 1 / 3) * 255,
+ ];
+}
+
+function parseAlphaToken(rawAlpha) {
+ if (rawAlpha == null || rawAlpha === '') return 1;
+ const str = String(rawAlpha).trim();
+ if (!str) return 1;
+ if (str.endsWith('%')) {
+ const pct = parseFloat(str);
+ return Number.isFinite(pct) ? pct / 100 : 1;
+ }
+ const num = parseFloat(str);
+ return Number.isFinite(num) ? num : 1;
+}
+
+/**
+ * Parse `#hex`, `rgb()/rgba()`, or `hsl()/hsla()` into perceptual luminance `[0, 1]`.
+ * Returns `null` when transparent (`alpha <= 0.15`) or unparseable.
+ *
+ * @param {string | null | undefined} rawColor
+ * @returns {number | null}
+ */
+function parseCssColorLuminance(rawColor) {
+ const str = String(rawColor ?? '').trim().toLowerCase();
+ if (!str || str === 'transparent' || str === 'none' || str === 'inherit' || str === 'initial') {
+ return null;
+ }
+
+ if (str.startsWith('#')) {
+ const hex = str.slice(1);
+ let r = 0;
+ let g = 0;
+ let b = 0;
+ let a = 1;
+ if (hex.length === 3 || hex.length === 4) {
+ r = parseInt(hex[0] + hex[0], 16);
+ g = parseInt(hex[1] + hex[1], 16);
+ b = parseInt(hex[2] + hex[2], 16);
+ if (hex.length === 4) a = parseInt(hex[3] + hex[3], 16) / 255;
+ } else if (hex.length === 6 || hex.length === 8) {
+ r = parseInt(hex.slice(0, 2), 16);
+ g = parseInt(hex.slice(2, 4), 16);
+ b = parseInt(hex.slice(4, 6), 16);
+ if (hex.length === 8) a = parseInt(hex.slice(6, 8), 16) / 255;
+ } else {
+ return null;
+ }
+ if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) {
+ return null;
+ }
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+ }
+
+ const rgbMatch = str.match(/^rgba?\(([^)]+)\)$/);
+ if (rgbMatch) {
+ const body = rgbMatch[1].trim();
+ const [channelsPart, slashAlpha] = body.split('/');
+ const parts = channelsPart
+ .trim()
+ .split(/[\s,]+/)
+ .filter(Boolean);
+ if (parts.length < 3) return null;
+ const parseChan = (tok) =>
+ tok.endsWith('%') ? (parseFloat(tok) / 100) * 255 : parseFloat(tok);
+ const r = parseChan(parts[0]);
+ const g = parseChan(parts[1]);
+ const b = parseChan(parts[2]);
+ const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]);
+ if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || a <= 0.15) {
+ return null;
+ }
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+ }
+
+ const hslMatch = str.match(/^hsla?\(([^)]+)\)$/);
+ if (hslMatch) {
+ const body = hslMatch[1].trim();
+ const [channelsPart, slashAlpha] = body.split('/');
+ const parts = channelsPart
+ .trim()
+ .split(/[\s,]+/)
+ .filter(Boolean);
+ if (parts.length < 3) return null;
+ const h = parseFloat(parts[0]);
+ const s = parseFloat(parts[1]);
+ const l = parseFloat(parts[2]);
+ const a = slashAlpha !== undefined ? parseAlphaToken(slashAlpha) : parseAlphaToken(parts[3]);
+ if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l) || a <= 0.15) {
+ return null;
+ }
+ const [r, g, b] = hslToRgb(h, s, l);
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+ }
+
+ return null;
+}
+
+function readStyleProp(el, cs, prop) {
+ if (prop.startsWith('--')) {
+ const inlineVal =
+ typeof el?.style?.getPropertyValue === 'function'
+ ? el.style.getPropertyValue(prop)
+ : el?.style?.[prop];
+ if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim();
+ const compVal = cs?.getPropertyValue?.(prop);
+ return compVal ? String(compVal).trim() : '';
+ }
+ const inlineVal = el?.style?.[prop];
+ if (inlineVal && String(inlineVal).trim()) return String(inlineVal).trim();
+ const compVal = cs?.[prop];
+ return compVal ? String(compVal).trim() : '';
+}
+
+/**
+ * Detect whether the active host surface is `'light'` or `'dark'`.
+ * Inspects explicit Antigravity / VS Code theme classes & attributes first,
+ * then actual computed surface/text luminance, then `prefers-color-scheme`.
+ *
+ * @param {HTMLElement | null | undefined} [targetEl]
+ * @returns {'light' | 'dark'}
+ */
+function detectHostColorScheme(targetEl = null) {
+ const doc = typeof document !== 'undefined' ? document : null;
+ const win = typeof window !== 'undefined' ? window : null;
+ let workbenchEl = null;
+ try {
+ workbenchEl =
+ typeof doc?.querySelector === 'function' ? doc.querySelector('.monaco-workbench') : null;
+ } catch {
+ workbenchEl = null;
+ }
+
+ const candidates = [];
+ for (const el of [doc?.body, doc?.documentElement, workbenchEl, targetEl]) {
+ if (el && !candidates.includes(el)) {
+ candidates.push(el);
+ }
+ }
+
+ // 1. Explicit host theme attributes & class tokens (never read our own data-color-scheme)
+ for (const el of candidates) {
+ const vscodeKind = String(el.getAttribute?.('data-vscode-theme-kind') || '')
+ .trim()
+ .toLowerCase();
+ if (vscodeKind) {
+ if (vscodeKind.includes('light')) return 'light';
+ if (vscodeKind.includes('dark') || vscodeKind.includes('high-contrast')) return 'dark';
+ }
+ const dataTheme = String(
+ el.getAttribute?.('data-theme') || el.getAttribute?.('data-color-mode') || ''
+ )
+ .trim()
+ .toLowerCase();
+ if (dataTheme === 'light' || dataTheme.endsWith('-light')) return 'light';
+ if (dataTheme === 'dark' || dataTheme.endsWith('-dark')) return 'dark';
+
+ const rawCls = typeof el.className === 'string' ? el.className : '';
+ if (rawCls) {
+ const tokens = rawCls.trim().toLowerCase().split(/\s+/);
+ for (const tok of tokens) {
+ if (LIGHT_THEME_CLASSES.has(tok)) return 'light';
+ if (DARK_THEME_CLASSES.has(tok)) return 'dark';
+ }
+ }
+ }
+
+ // 2. Computed / inline surface background luminance
+ const bgTargets = [];
+ for (const el of [targetEl, doc?.body, doc?.documentElement, workbenchEl]) {
+ if (el && !bgTargets.includes(el)) {
+ bgTargets.push(el);
+ }
+ }
+ const bgProps = [
+ '--background',
+ '--card',
+ '--vscode-sideBar-background',
+ '--vscode-editor-background',
+ 'backgroundColor',
+ ];
+ for (const el of bgTargets) {
+ let cs = null;
+ try {
+ cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null;
+ } catch {
+ cs = null;
+ }
+ for (const prop of bgProps) {
+ const lum = parseCssColorLuminance(readStyleProp(el, cs, prop));
+ if (lum !== null) {
+ return lum > 0.52 ? 'light' : 'dark';
+ }
+ }
+ }
+
+ // 3. Computed / inline foreground text luminance
+ const fgProps = ['--foreground', '--vscode-foreground', '--vscode-editor-foreground', 'color'];
+ for (const el of bgTargets) {
+ let cs = null;
+ try {
+ cs = typeof win?.getComputedStyle === 'function' ? win.getComputedStyle(el) : null;
+ } catch {
+ cs = null;
+ }
+ for (const prop of fgProps) {
+ const lum = parseCssColorLuminance(readStyleProp(el, cs, prop));
+ if (lum !== null) {
+ return lum < 0.48 ? 'light' : 'dark';
+ }
+ }
+ }
+
+ // 4. OS media query fallback
+ try {
+ if (win?.matchMedia?.('(prefers-color-scheme: dark)')?.matches) {
+ return 'dark';
+ }
+ } catch {
+ // ignore matchMedia errors
+ }
+
+ return 'light';
+}
+
+function setAttrIfChanged(el, name, value) {
+ if (!el || typeof el.setAttribute !== 'function') return;
+ if (typeof el.getAttribute === 'function' && el.getAttribute(name) === value) return;
+ el.setAttribute(name, value);
+}
+
+function removeAttrIfPresent(el, name) {
+ if (!el || typeof el.removeAttribute !== 'function') return;
+ if (typeof el.hasAttribute === 'function' && !el.hasAttribute(name)) return;
+ el.removeAttribute(name);
+}
+
function setOrClearStyleVar(el, propName, value) {
if (!el || !el.style) return;
+ const cur =
+ typeof el.style.getPropertyValue === 'function'
+ ? el.style.getPropertyValue(propName)
+ : el.style[propName] || '';
if (value) {
+ if (cur === value) return;
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, '');
+ } else if (cur) {
+ if (typeof el.style.removeProperty === 'function') {
+ el.style.removeProperty(propName);
+ } else if (typeof el.style.setProperty === 'function') {
+ el.style.setProperty(propName, '');
+ } else {
+ el.style[propName] = '';
+ }
}
}
/**
- * Synchronize theme accent and (optionally) font scale tokens onto a root/host element.
+ * Synchronize theme accent, host color scheme polarity, and (optionally) font scale tokens
+ * onto a root/host element.
*
* @param {HTMLElement | null | undefined} targetEl
* @param {object | null | undefined} settings
@@ -2428,7 +2911,17 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } =
setOrClearStyleVar(targetEl, '--user-accent-primary', '');
setOrClearStyleVar(targetEl, '--user-accent-contrast', '');
}
- targetEl.setAttribute?.('data-accent', preset.key);
+ setAttrIfChanged(targetEl, 'data-accent', preset.key);
+
+ const colorScheme = detectHostColorScheme(targetEl);
+ setAttrIfChanged(targetEl, 'data-color-scheme', colorScheme);
+
+ const isModernUi = normalizeClientModernUi(settings?.experimentalModernUi);
+ if (isModernUi) {
+ setAttrIfChanged(targetEl, 'data-modern-ui', 'true');
+ } else {
+ removeAttrIfPresent(targetEl, 'data-modern-ui');
+ }
if (includeFontScale) {
const scaleKey = normalizeClientFontScale(settings?.fontScale);
@@ -2436,20 +2929,18 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } =
const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1;
setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor));
setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor));
- targetEl.setAttribute?.('data-font-scale', scaleKey);
+ setAttrIfChanged(targetEl, 'data-font-scale', scaleKey);
} else {
setOrClearStyleVar(targetEl, '--ui-font-scale', '');
setOrClearStyleVar(targetEl, '--ui-panel-scale', '');
- if (typeof targetEl.removeAttribute === 'function') {
- targetEl.removeAttribute('data-font-scale');
- }
+ removeAttrIfPresent(targetEl, 'data-font-scale');
}
}
-return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot };
+return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, normalizeClientModernUi, isModernUiActiveForElement, parseCssColorLuminance, detectHostColorScheme, applyAppearanceToRoot };
})();
// --- src/core/domPatch.js ---
-const { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList } = (() => {
+const { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList, positionAnchoredPopup } = (() => {
/**
* @fileoverview Incremental DOM patching utilities and keyed list reconciler.
* Prevents full innerHTML replacements and preserves active DOM element state.
@@ -2583,7 +3074,11 @@ const keyedListState = new WeakMap();
* Keyed incremental list reconciler.
* Reuses existing DOM nodes by key and patches only changed items in-place.
*/
-function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) {
+function patchKeyedList(
+ container,
+ items,
+ { keyFn = (_, i) => i, sigFn, createRow, updateRow, destroyRow } = {}
+) {
if (!container) return;
let map = keyedListState.get(container);
if (!map) {
@@ -2627,6 +3122,7 @@ function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }
if (record.el.parentNode === container) {
container.removeChild(record.el);
}
+ destroyRow?.(record.refs, record.el);
map.delete(oldKey);
}
}
@@ -2649,7 +3145,198 @@ function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }
}
}
}
-return { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList };
+
+const CLIPPING_OVERFLOW_RE = /(?:hidden|clip|auto|scroll)/i;
+
+/**
+ * 解析浮层所在的可视裁剪边界(兼容 Shadow DOM 悬浮窗 `.wm-popover-panel`、
+ * 侧栏 `.app-shell`、自定义滚动容器 `.custom-scroll-content` 与窗口视口)。
+ *
+ * @param {HTMLElement} anchorRootEl
+ * @returns {{ left: number, top: number, right: number, bottom: number, width: number, height: number } | null}
+ */
+function resolvePopupBoundaryRect(anchorRootEl) {
+ if (!anchorRootEl) return null;
+ const winW = typeof window !== 'undefined' ? Number(window.innerWidth || 0) : 0;
+ const winH = typeof window !== 'undefined' ? Number(window.innerHeight || 0) : 0;
+ let boundLeft = 0;
+ let boundTop = 0;
+ let boundRight = winW > 0 ? winW : Infinity;
+ let boundBottom = winH > 0 ? winH : Infinity;
+ let hasBoundary = winW > 0 && winH > 0;
+
+ const getStyle =
+ typeof window !== 'undefined' && typeof window.getComputedStyle === 'function'
+ ? window.getComputedStyle
+ : null;
+
+ let cur = anchorRootEl.parentNode || null;
+ while (cur) {
+ if (cur.nodeType === 1 || typeof cur.getBoundingClientRect === 'function') {
+ const cls = cur.classList;
+ const isShell = Boolean(
+ cls?.contains?.('wm-popover-panel') ||
+ cls?.contains?.('wm-multi-panel') ||
+ cls?.contains?.('app-shell') ||
+ cls?.contains?.('custom-scroll-host') ||
+ cls?.contains?.('custom-scroll-content')
+ );
+ let clipsX = isShell;
+ let clipsY = isShell;
+ if (!isShell && getStyle) {
+ try {
+ const cs = getStyle(cur);
+ if (cs) {
+ clipsX = CLIPPING_OVERFLOW_RE.test(cs.overflowX || cs.overflow || '');
+ clipsY = CLIPPING_OVERFLOW_RE.test(cs.overflowY || cs.overflow || '');
+ }
+ } catch {
+ // 忽略 Mock DOM 样式查询异常
+ }
+ }
+ if (clipsX || clipsY) {
+ const r = cur.getBoundingClientRect?.();
+ if (r && r.width > 0 && r.height > 0) {
+ hasBoundary = true;
+ if (clipsX) {
+ boundLeft = Math.max(boundLeft, r.left);
+ boundRight = Math.min(boundRight, r.right);
+ }
+ if (clipsY) {
+ boundTop = Math.max(boundTop, r.top);
+ boundBottom = Math.min(boundBottom, r.bottom);
+ }
+ }
+ }
+ }
+ // 到达 ShadowRoot 或文档顶层后停止,避免误受宿主页面外层容器干扰
+ if (!cur.parentNode) break;
+ cur = cur.parentNode;
+ }
+
+ if (!hasBoundary || !Number.isFinite(boundRight) || !Number.isFinite(boundBottom)) {
+ return null;
+ }
+ const width = Math.max(0, boundRight - boundLeft);
+ const height = Math.max(0, boundBottom - boundTop);
+ if (width <= 0 || height <= 0) return null;
+ return { left: boundLeft, top: boundTop, right: boundRight, bottom: boundBottom, width, height };
+}
+
+/**
+ * 为锚定在触发器上的绝对定位下拉浮层执行水平/垂直碰撞检测与边界夹紧:
+ * - 水平方向优先左对齐,右侧溢出时切右对齐,仍越界则直接夹紧在容器可视安全区内;
+ * - 垂直方向底部空间不足且上方更宽裕时自动向上翻转(追加 `.is-above`),并按可用空间收紧 `max-height`。
+ *
+ * @param {HTMLElement} rootEl 定位基准容器 (`position: relative`)
+ * @param {HTMLElement} triggerEl 触发按钮
+ * @param {HTMLElement} popupEl 下拉浮层 (`position: absolute`)
+ * @param {{ margin?: number, gap?: number, maxHeight?: number, minFlipSpace?: number }} [opts]
+ */
+function positionAnchoredPopup(
+ rootEl,
+ triggerEl,
+ popupEl,
+ { margin = 6, gap = 4, maxHeight = 220, minFlipSpace = 140 } = {}
+) {
+ if (!rootEl || !triggerEl || !popupEl || !popupEl.style) return;
+ if (popupEl.hasAttribute?.('hidden')) return;
+
+ const rootRect = rootEl.getBoundingClientRect?.();
+ const triggerRect = triggerEl.getBoundingClientRect?.();
+ if (
+ !rootRect ||
+ !triggerRect ||
+ !(triggerRect.width > 0 && triggerRect.height > 0)
+ ) {
+ return;
+ }
+
+ const bound = resolvePopupBoundaryRect(rootEl);
+ if (!bound) return;
+
+ // 清除旧的动态夹紧值以便读取自然布局宽度
+ popupEl.style.left = '';
+ popupEl.style.right = '';
+ popupEl.style.top = '';
+ popupEl.style.bottom = '';
+ popupEl.style.minWidth = '';
+ popupEl.style.maxWidth = '';
+ popupEl.style.maxHeight = '';
+
+ const availWidth = Math.max(120, Math.floor(bound.width - margin * 2));
+ popupEl.style.maxWidth = `${availWidth}px`;
+
+ const rawRect = popupEl.getBoundingClientRect?.();
+ // 优先读取 offsetWidth,避免入场动画 scale(0.975) 导致测宽偏小
+ const naturalW = Math.max(
+ Number(popupEl.offsetWidth || 0),
+ Math.ceil(Number(rawRect?.width || 0))
+ );
+ if (naturalW > availWidth) {
+ popupEl.style.minWidth = '0px';
+ }
+ const popupW = Math.min(availWidth, naturalW > 0 ? naturalW : Math.max(triggerRect.width, 210));
+
+ const safeLeft = bound.left + margin;
+ const safeRight = bound.right - margin;
+ const rawLeft = Number(rawRect?.left);
+ const rawRight = Number(rawRect?.right);
+ const hasRawBox = Number.isFinite(rawLeft) && Number.isFinite(rawRight) && rawRight > rawLeft;
+ // 若入场缩放动画(如 scale(0.975))正在首帧生效,按对称补偿还原终态边界再判断是否越界
+ const scalePadX = hasRawBox ? Math.max(0, (popupW - (rawRight - rawLeft)) / 2) : 0;
+ const naturalLeft = hasRawBox ? rawLeft - scalePadX : triggerRect.left;
+ const naturalRight = hasRawBox
+ ? Math.max(rawRight + scalePadX, naturalLeft + popupW)
+ : naturalLeft + popupW;
+ const fitsAsDefault = hasRawBox && naturalLeft >= safeLeft && naturalRight <= safeRight;
+
+ if (!fitsAsDefault) {
+ let targetLeft = triggerRect.left;
+ if (targetLeft + popupW > safeRight) {
+ const rightAlignedLeft = triggerRect.right - popupW;
+ if (rightAlignedLeft >= safeLeft) {
+ targetLeft = rightAlignedLeft;
+ } else {
+ targetLeft = Math.max(safeLeft, safeRight - popupW);
+ }
+ }
+ if (targetLeft < safeLeft) {
+ targetLeft = safeLeft;
+ }
+
+ const offsetLeft = Math.round(targetLeft - rootRect.left);
+ popupEl.style.left = `${offsetLeft}px`;
+ popupEl.style.right = 'auto';
+ }
+
+ const spaceBelow = Math.max(0, bound.bottom - triggerRect.bottom - gap - margin);
+ const spaceAbove = Math.max(0, triggerRect.top - bound.top - gap - margin);
+ const naturalH = Math.max(
+ Number(popupEl.scrollHeight || 0),
+ Number(popupEl.offsetHeight || 0),
+ Math.ceil(Number(rawRect?.height || 0))
+ );
+ const desiredH = maxHeight > 0 ? Math.min(maxHeight, naturalH || maxHeight) : naturalH || 240;
+ const shouldOpenAbove =
+ spaceBelow < Math.min(desiredH, minFlipSpace) && spaceAbove > spaceBelow;
+
+ patchClasses(popupEl, { 'is-above': shouldOpenAbove });
+ if (shouldOpenAbove) {
+ popupEl.style.top = 'auto';
+ popupEl.style.bottom = `calc(100% + ${gap}px)`;
+ if (maxHeight > 0) {
+ popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceAbove)))}px`;
+ }
+ } else {
+ popupEl.style.top = `calc(100% + ${gap}px)`;
+ popupEl.style.bottom = 'auto';
+ if (maxHeight > 0) {
+ popupEl.style.maxHeight = `${Math.max(88, Math.floor(Math.min(maxHeight, spaceBelow)))}px`;
+ }
+ }
+}
+return { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList, positionAnchoredPopup };
})();
// --- src/core/component.js ---
@@ -2732,7 +3419,7 @@ return { defineComponent };
})();
// --- src/core/formatters.js ---
-const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail } = (() => {
+const { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => {
/**
* @fileoverview Pure formatting utilities for speed metrics, token counts,
* USD estimates, countdown timers, and custom datetime displays.
@@ -2745,7 +3432,13 @@ const EN_MONTH_SHORT = Object.freeze([
]);
function formatMetric(value, unit = '') {
- return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
+ if (!Number.isFinite(value)) return '—';
+ const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1);
+ return `${numStr}${unit}`;
+}
+
+function formatSpeedMetric(value, unit = ' tok/s') {
+ return formatMetric(value, unit);
}
function formatCachePct(value) {
@@ -2821,6 +3514,8 @@ const SPEED_REASON_LABELS = {
__proto__: null,
incomplete_or_invalid_timing: 'fmt.speedIncomplete',
canceled: 'fmt.speedCanceled',
+ error: 'fmt.speedError',
+ interrupted: 'fmt.speedInterrupted',
compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable',
invalid_output_tokens: 'fmt.speedInvalidOutput',
inconsistent_timing: 'fmt.speedInconsistent',
@@ -2833,6 +3528,135 @@ function speedReasonText(reason) {
return label ? t(label) : '';
}
+const ANOMALY_KIND_ORDER = Object.freeze([
+ 'rate_limit',
+ 'timeout',
+ 'capacity',
+ 'disconnect',
+ 'upstream',
+ 'model_output',
+ 'safety',
+ 'auth_or_model',
+ 'error',
+]);
+
+function formatAnomalyKindLabel(kind) {
+ const k = String(kind || 'error');
+ const key = `steps.anomalyKind.${k}`;
+ const text = t(key);
+ return text === key ? t('steps.anomalyKind.error') : text;
+}
+
+function formatAnomalyTagText(primaryKind, count = 1) {
+ const n = Math.max(1, Math.floor(Number(count) || 1));
+ const k = String(primaryKind || 'error');
+ if (k === 'capacity' && n === 1) return t('steps.anomalyTag.capacitySingle');
+ if (k === 'upstream' && n === 1) return t('steps.anomalyTag.upstreamSingle');
+ const key = `steps.anomalyTag.${k}`;
+ const formatted = t(key, { n });
+ return formatted === key ? t('steps.anomalyTag.error', { n }) : formatted;
+}
+
+function resolveModelAnomalySummary(m) {
+ const count = Math.max(0, Number(m?.anomalyCount || 0));
+ const steps = Math.max(0, Number(m?.anomalySteps || 0));
+ if (count <= 0 && steps <= 0) return null;
+ const byKind = m?.anomalyByKind && typeof m.anomalyByKind === 'object' ? m.anomalyByKind : {};
+ const entries = Object.entries(byKind)
+ .map(([k, v]) => [k, Math.max(0, Number(v || 0))])
+ .filter(([, v]) => v > 0)
+ .sort((a, b) => {
+ if (b[1] !== a[1]) return b[1] - a[1];
+ const pa = ANOMALY_KIND_ORDER.indexOf(a[0]);
+ const pb = ANOMALY_KIND_ORDER.indexOf(b[0]);
+ return (pa < 0 ? 99 : pa) - (pb < 0 ? 99 : pb);
+ });
+ const totalCount = count || entries.reduce((sum, [, v]) => sum + v, 0) || steps;
+ const primaryKind = entries.length === 1 ? entries[0][0] : entries.length > 1 ? 'mixed' : 'error';
+ const severity =
+ Number(m?.anomalyDangerCount || 0) > 0 ||
+ entries.some(([k]) => k === 'rate_limit' || k === 'auth_or_model')
+ ? 'danger'
+ : 'warn';
+ return {
+ count: totalCount,
+ steps: steps || totalCount,
+ totalDelaySec: Math.max(0, Number(m?.anomalyTotalDelaySec || 0)),
+ primaryKind,
+ severity,
+ entries,
+ tagText: formatAnomalyTagText(primaryKind, totalCount),
+ };
+}
+
+function formatStepAnomalyInlineSummary(anomaly) {
+ if (!anomaly || !(Number(anomaly.count) > 0)) return '';
+ const tag = formatAnomalyTagText(anomaly.primaryKind, anomaly.count);
+ const label = formatAnomalyKindLabel(anomaly.primaryKind);
+ const delaySec = Number(anomaly.totalDelaySec || 0);
+ const delayPart = delaySec > 0 ? ` · ${t('steps.anomalyDelayPart', { sec: delaySec })}` : '';
+ return `${tag} · ${label}${delayPart}`;
+}
+
+function buildStepAnomalyDiagnostic(st) {
+ const a = st?.anomaly;
+ if (!a || !(Number(a.count) > 0)) return null;
+ const title = t('steps.anomalyStepTitle', {
+ step: Number(st.stepIndex ?? 0),
+ count: Number(a.count),
+ });
+ const delaySec = Number(a.totalDelaySec || 0);
+ const sub = delaySec > 0 ? t('steps.anomalyDelayPart', { sec: delaySec }) : '';
+ const events = Array.isArray(a.events) ? a.events : [];
+ const rows = events.map((ev, idx) => {
+ const label = formatAnomalyKindLabel(ev.kind);
+ const parts = [`#${ev.attempt || idx + 1} ${label}`];
+ if (Number(ev.delaySec) > 0) {
+ parts.push(t('steps.anomalyDelayPart', { sec: ev.delaySec }));
+ }
+ if (ev.terminal) {
+ parts.push(t('steps.anomalyTerminalTag'));
+ }
+ return {
+ text: parts.join(' · '),
+ detail: ev.message || '',
+ danger: Boolean(ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model'),
+ };
+ });
+ return {
+ title,
+ sub,
+ rows,
+ hint: '',
+ severity: a.severity === 'danger' ? 'danger' : 'warn',
+ };
+}
+
+function buildModelAnomalyDiagnostic(m) {
+ const sum = resolveModelAnomalySummary(m);
+ if (!sum) return null;
+ const title = t('steps.anomalyModelTitle', {
+ model: m?.displayText || m?.shortName || m?.label || '—',
+ count: sum.count,
+ });
+ const subParts = [t('steps.anomalyModelSub', { steps: sum.steps })];
+ if (sum.totalDelaySec > 0) {
+ subParts.push(t('steps.anomalyDelayPart', { sec: sum.totalDelaySec }));
+ }
+ const rows = sum.entries.map(([k, v]) => ({
+ text: t('steps.anomalyModelKindRow', { kind: formatAnomalyKindLabel(k), count: v }),
+ detail: '',
+ danger: k === 'rate_limit' || k === 'auth_or_model',
+ }));
+ return {
+ title,
+ sub: subParts.join(' · '),
+ rows,
+ hint: t('steps.anomalyModelClickHint'),
+ severity: sum.severity,
+ };
+}
+
function sampleSummary(summary) {
const valid = summary?.sampleCount || 0;
const excluded = summary?.excludedCount || 0;
@@ -3111,6 +3935,12 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) {
ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0,
ttftWeight: hasTtft ? ttftWeight : 0,
ttftSampleCount,
+ anomalySteps: Math.max(0, Number(m.anomalySteps || 0)),
+ anomalyCount: Math.max(0, Number(m.anomalyCount || 0)),
+ anomalyDangerCount: Math.max(0, Number(m.anomalyDangerCount || 0)),
+ anomalyTotalDelaySec: Math.max(0, Number(m.anomalyTotalDelaySec || 0)),
+ anomalyByKind:
+ m.anomalyByKind && typeof m.anomalyByKind === 'object' ? { ...m.anomalyByKind } : {},
};
if (m.upstreamName) acc.upstreamSet.add(m.upstreamName);
byDisplay.set(key, acc);
@@ -3139,6 +3969,17 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) {
acc.costUsd += costUsd;
acc.unpricedCalls += unpricedCalls;
+ acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0));
+ acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0));
+ acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0));
+ acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0));
+ if (m.anomalyByKind && typeof m.anomalyByKind === 'object') {
+ for (const [ak, av] of Object.entries(m.anomalyByKind)) {
+ const cnt = Math.max(0, Number(av || 0));
+ if (cnt > 0) acc.anomalyByKind[ak] = (acc.anomalyByKind[ak] || 0) + cnt;
+ }
+ }
+
if (hasSpeed) {
acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight;
acc.speedWeight += speedWeight;
@@ -3189,6 +4030,15 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) {
avgTokPerSec,
avgTtftSec,
ttftSampleCount: acc.ttftSampleCount,
+ ...(acc.anomalyCount > 0
+ ? {
+ anomalySteps: acc.anomalySteps,
+ anomalyCount: acc.anomalyCount,
+ anomalyDangerCount: acc.anomalyDangerCount,
+ anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1),
+ anomalyByKind: acc.anomalyByKind,
+ }
+ : {}),
speedSummary: acc.baseItem.speedSummary
? {
...acc.baseItem.speedSummary,
@@ -3218,21 +4068,48 @@ function getAgentBadgeClass(index = 0, isMain = false) {
return `badge-sub-${slot}`;
}
+function resolveStructuredAgentKind(agent) {
+ if (!agent) return 'main';
+ if (agent.agentKind) return agent.agentKind;
+ if (agent.isMain) return 'main';
+ if (agent.isSideQuestion || agent.typeName === 'side_question') return 'side_question';
+ if (
+ agent.typeName === 'worker' ||
+ agent.typeName === 'swarm_worker' ||
+ /^Swarm\s+Worker\s*\(/i.test(String(agent.role || ''))
+ ) {
+ return 'swarm_worker';
+ }
+ return 'subagent';
+}
+
+function normalizeSwarmMemberHandle(rawText) {
+ const trimmed = String(rawText || '').trim();
+ if (!trimmed) return '';
+ const wrapper = trimmed.match(/^Swarm\s+Worker\s*\(([^)]+)\)\s*$/i);
+ const inner = (wrapper ? wrapper[1] : trimmed).replace(/^@+/, '').trim();
+ if (
+ !inner ||
+ inner === '蜂群' ||
+ inner === '工蜂' ||
+ inner.toLowerCase() === 'swarm' ||
+ inner.toLowerCase() === 'worker' ||
+ inner.toLowerCase() === 'swarm worker'
+ ) {
+ return '';
+ }
+ return `@${inner}`;
+}
+
/**
- * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。
+ * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理、蜂群节点或旁路提问的紧凑徽章文本(零正则反拆中文)。
*
* @param {object|null|undefined} agent
* @returns {string}
*/
function formatAgentBadgeText(agent) {
if (!agent) return t('fmt.mainBadge');
- const kind =
- agent.agentKind ||
- (agent.isMain
- ? 'main'
- : agent.isSideQuestion || agent.typeName === 'side_question'
- ? 'side_question'
- : 'subagent');
+ const kind = resolveStructuredAgentKind(agent);
if (kind === 'all') return t('header.scopeAllShort');
if (kind === 'main') return t('fmt.mainBadge');
if (kind === 'side_question') {
@@ -3241,6 +4118,12 @@ function formatAgentBadgeText(agent) {
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
return t('fmt.sideBadgeShort');
}
+ if (kind === 'swarm_worker') {
+ const ord = Number(agent.agentOrdinal || agent.index || 0);
+ if (ord > 0) return t('fmt.swarmBadge', { index: ord });
+ if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
+ return t('fmt.swarmBadgeShort');
+ }
const ord = Number(agent.agentOrdinal || agent.index || 0);
if (ord > 0) return t('fmt.subBadge', { index: ord });
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
@@ -3255,13 +4138,7 @@ function formatAgentBadgeText(agent) {
*/
function formatAgentLabel(agent) {
if (!agent) return t('fmt.mainAgent');
- const kind =
- agent.agentKind ||
- (agent.isMain
- ? 'main'
- : agent.isSideQuestion || agent.typeName === 'side_question'
- ? 'side_question'
- : 'subagent');
+ const kind = resolveStructuredAgentKind(agent);
if (kind === 'all') return t('header.scopeAll');
if (kind === 'main') return t('fmt.mainAgent');
@@ -3282,6 +4159,20 @@ function formatAgentLabel(agent) {
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
}
+ if (kind === 'swarm_worker') {
+ const ord = Number(agent.agentOrdinal || agent.index || 0);
+ const baseLabel = ord > 0 ? `${t('fmt.swarmAgent')} #${ord}` : t('fmt.swarmAgent');
+ const handle = normalizeSwarmMemberHandle(rawCustom || agent.role || '');
+ if (!handle) return baseLabel;
+ let auxSuffix = '';
+ if (/^@monitor(?:-\d+)?$/i.test(handle)) {
+ auxSuffix = ` (${t('fmt.swarmMonitorHint')})`;
+ } else if (/^@narrator(?:-\d+)?$/i.test(handle)) {
+ auxSuffix = ` (${t('fmt.swarmNarratorHint')})`;
+ }
+ return `${baseLabel} · ${handle}${auxSuffix}`;
+ }
+
const ord = Number(agent.agentOrdinal || agent.index || 0);
const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent');
const isGeneric =
@@ -3293,6 +4184,31 @@ function formatAgentLabel(agent) {
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
}
+/**
+ * 格式化会话选项右侧元信息(自适应区分纯蜂群、蜂群+子代理混合、常规子代理与单会话步数)。
+ *
+ * @param {object|null|undefined} conv
+ * @returns {string}
+ */
+function formatConversationMeta(conv) {
+ if (!conv) return '';
+ const main = Number(conv.stepCount || 0);
+ const totalSubs = Number(conv.subagentCount || 0);
+ const swarm = Number(conv.swarmCount || 0);
+ const otherSubs = Math.max(0, totalSubs - swarm);
+ const total = Number(conv.totalStepCount ?? conv.totalStepsAllAgents ?? main);
+ if (swarm > 0 && otherSubs > 0) {
+ return t('header.convMetaWithSwarmAndSubs', { main, swarm, subs: otherSubs, total });
+ }
+ if (swarm > 0) {
+ return t('header.convMetaWithSwarm', { main, swarm, total });
+ }
+ if (totalSubs > 0) {
+ return t('header.convMetaWithSubs', { main, subs: totalSubs, total });
+ }
+ return t('header.convMetaSteps', { count: main });
+}
+
/**
* 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。
*
@@ -3332,11 +4248,170 @@ function formatLiveActivityDetail(act) {
}
return String(act.detail || '');
}
-return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail };
+
+/**
+ * 20 色感知均匀色环(无特定模型绑定,兼顾亮/暗背景可读性,彻底消除标准 HSL 绿色/暗红区过度聚集撞色)。
+ * 每项为 `[hue, saturationPct, lightnessPct]`。
+ */
+const PERCEPTUAL_MODEL_COLOR_RING = [
+ [217, 82, 53], // Royal Blue
+ [14, 80, 52], // Coral / Vermilion
+ [162, 74, 41], // Teal / Jade
+ [272, 74, 58], // Vivid Violet
+ [36, 88, 47], // Rich Amber
+ [336, 78, 53], // Rose / Raspberry
+ [193, 84, 43], // Cerulean / Cyan
+ [138, 66, 41], // Emerald Green
+ [246, 74, 60], // Indigo
+ [25, 86, 50], // Tangerine Orange
+ [306, 70, 52], // Magenta / Orchid
+ [177, 76, 39], // Deep Seafoam
+ [355, 76, 54], // Crimson Red
+ [205, 80, 48], // Ocean Blue
+ [45, 88, 44], // Warm Gold
+ [288, 68, 55], // Amethyst Purple
+ [102, 60, 42], // Leaf Green
+ [230, 76, 57], // Cobalt Blue
+ [322, 74, 51], // Berry Pink
+ [185, 72, 46], // Turquoise
+];
+
+/**
+ * 提取跨平台、跨语言、同屏三栏(模型排行 / 客户端来源 / 月度统计)严格一致的模型颜色种子字符串。
+ *
+ * 优先取单模型稳定 `sourceLabels[0]`;若多个外层槽位已在当前显示策略下合并(如 `4-argon`),
+ * 则以规范化 `displayText` 为种子,确保跨客户端与跨月份聚合子集不同时依然映射至完全相同的颜色。
+ *
+ * @param {object|string|null|undefined} model
+ * @returns {string}
+ */
+function getCanonicalModelColorSeed(model) {
+ if (typeof model === 'string') {
+ return model.trim().toLowerCase().replace(/\s+/g, ' ');
+ }
+ if (!model || typeof model !== 'object') return '';
+ if (
+ Number(model.mergedCount || 0) <= 1 &&
+ Array.isArray(model.sourceLabels) &&
+ model.sourceLabels.length === 1 &&
+ model.sourceLabels[0]
+ ) {
+ return String(model.sourceLabels[0]).trim().toLowerCase().replace(/\s+/g, ' ');
+ }
+ const raw =
+ model.displayText ||
+ model.label ||
+ model.modelId ||
+ model.baseItem?.modelId ||
+ model.shortName ||
+ model.name ||
+ '';
+ return String(raw).trim().toLowerCase().replace(/\s+/g, ' ');
+}
+
+function hashModelSeed32(str) {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
+ }
+ h ^= h >>> 16;
+ h = Math.imul(h, 0x85ebca6b);
+ h ^= h >>> 13;
+ h = Math.imul(h, 0xc2b2ae35);
+ h ^= h >>> 16;
+ return h >>> 0;
+}
+
+function formatRingSlotHsl(slotIdx, shiftLight = 0) {
+ const [hue, sat, light] = PERCEPTUAL_MODEL_COLOR_RING[slotIdx % PERCEPTUAL_MODEL_COLOR_RING.length];
+ const clampedLight = Math.min(66, Math.max(34, light + shiftLight));
+ return `hsl(${hue} ${sat}% ${clampedLight}%)`;
+}
+
+/**
+ * 基于模型标识通过 32 位雪崩哈希映射至 20 色感知均匀色环,确保跨电脑同模型同色且无需硬编码颜色表。
+ *
+ * @param {object|string|null|undefined} seedOrModel
+ * @returns {string}
+ */
+function resolveDeterministicModelColor(seedOrModel) {
+ const seed = getCanonicalModelColorSeed(seedOrModel);
+ if (!seed) return 'var(--accent-primary)';
+ const h = hashModelSeed32(seed);
+ return formatRingSlotHsl(h % PERCEPTUAL_MODEL_COLOR_RING.length);
+}
+
+/**
+ * 为一组模型构建确定性颜色映射表(双遍固有槽位保护):
+ * 1. 所有无槽位冲突的模型 100% 保持其纯哈希固有色,不受长尾模型增减影响;
+ * 2. 仅当同屏两个模型恰好落入同一色环槽位时,按严格字典序以互质步长 `+7` 优先探查未被任何模型占用的空闲槽位。
+ *
+ * @param {Array