mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): add inline CLI statusLine capsule, step speed color toggle, and refined defaults
- Auto-provision native Antigravity CLI `statusLine` (`stack_with_default: false`) in `~/.gemini/antigravity-cli/settings.json` while strictly preserving custom third-party `statusLine.command` scripts, using zero-double-quote Windows commands compatible with Go `syscall.EscapeArg` under `cmd /c` - Add `cli-statusline.mjs` and `cli-statusline-config.mjs` to render a single-line transparent 24-bit ANSI footer (`? for shortcuts` left, live multi-session & 1..5 capsule metrics centered, deduplicated `mode · model · effort` right) with responsive narrow-terminal fallbacks and `stdin` quota fallback - Persist `cli-status-snapshot.json` during telemetry builds and self-heal sidecar restarts inside `executeTelemetryAction` error paths when `computeRuntimeCodeVersion()` advances - Add `enableCliStatusLine` and `showStepSpeedColor` preferences in Settings -> Structure, rename the mount sub-tab/section label in `zh-CN` to `挂载胶囊`, set default `topbarCapsuleSlots` to `['tps', 'ttft', 'context']`, and default `showStepTurnRail` and `showStepSpeedColor` to `false` - Add unit and end-to-end tests across `backend.test.mjs` and `window-bridge.test.mjs`, and update `README.md` / `README.zh-CN.md`
This commit is contained in:
@@ -50,7 +50,8 @@ The dashboard is organized into four tabs, with a top header to switch conversat
|
||||
- **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.
|
||||
- **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 Display**: Under **Layout -> Step Table**, independently toggle main/subagent badges, the turn rail (off by default), and **Speed Multi-Color** grading (off by default so step speeds render in clean monochrome when generation speed fluctuates).
|
||||
- **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).
|
||||
- **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*.
|
||||
@@ -103,8 +104,9 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
||||
- **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. **Headless CLI / `agy remote-control serve` Standalone Web Mode**:
|
||||
- On terminal-only machines or remote Linux servers, the backend automatically discovers `~/.gemini/antigravity-cli` (`daemon/hub_*.json`, conversations, and `transcript.jsonl`). When `agy` is offline, historical sessions and token accounting still load from local transcripts/cache and automatically upgrade to full live RPC telemetry once `agy` starts.
|
||||
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)
|
||||
|
||||
+5
-3
@@ -50,7 +50,8 @@
|
||||
- 按模型汇总:按当前所选会话(及所选主/子代理范围)统计各模型的调用次数、均速、总 Token 与费用。
|
||||
- **偏好设置**
|
||||
- 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。
|
||||
- 顶部栏定制:独立开关实时运行会话入口,并自由定义右侧三个指标槽位的显示内容与排列顺序。
|
||||
- 顶部栏与 CLI 胶囊定制:独立开关实时运行会话入口与 Antigravity CLI 底部状态胶囊(自动写入 `~/.gemini/antigravity-cli/settings.json` 的 `statusLine`),并自由定义 1 至 5 个指标槽位的显示内容与排列顺序(默认为输出速度、首字延迟、上下文占用)。
|
||||
- 调用明细显示:在「界面编排 -> 调用明细字段」可独立开关主/子代理标识、对话轮次导轨(默认关闭)与输出速度多色分级(默认关闭,以清爽单色显示输出速度,避免速度波动时色彩繁杂)。
|
||||
- 选择模型名称格式:精简代号或原始模型 ID,并可独立设置 Orchestrator 系列显示精简代号(如 `orchestrator-argon`、`worker-agy-hydrogen`)或原始完整 ID。
|
||||
- 按模型设置上下文:在「其他 → 模型上下文设置」为同一模型的各推理档统一设置上限,或切回「跟随宿主设置」。列表右侧显示已设置的上限和宿主最近报告的数值。App / IDE 窗口桥接在插件启动时重新读取宿主模型目录并应用已保存的设置,适用于之后发送的消息。CLI 使用 `AGY_CLI_AUTO_COMPACT_OVERRIDE`。
|
||||
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并提供「仅提示新版本,手动更新」(默认)、「自动更新」与「关闭更新」三档更新方式。
|
||||
@@ -103,8 +104,9 @@ Expand-Archive -Path "$env:TEMP\usage-monitor.zip" -DestinationPath $pluginsDir
|
||||
- **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. **无头 CLI / `agy remote-control serve` 独立 Web 模式**:
|
||||
- 在纯终端或远程 Linux 服务器上,插件会自动扫描 `~/.gemini/antigravity-cli`(含 `daemon/hub_*.json`、对话轨迹与 `transcript.jsonl`);即使 `agy` 暂未运行,也会基于本地日志离线展示历史会话与 Token 消耗,并在 `agy` 启动后自动重连升级为完整遥测。
|
||||
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)
|
||||
|
||||
+138
-25
@@ -673,20 +673,23 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
|
||||
// Preferences -> Structure Tab
|
||||
'settings.str.thirdTabAria': '结构子菜单切换',
|
||||
'settings.str.tabMount': '挂载与胶囊',
|
||||
'settings.str.tabMount': '挂载胶囊',
|
||||
'settings.str.tabHover': '鼠标悬浮窗',
|
||||
'settings.str.tabOverview': '实时监控布局',
|
||||
'settings.str.tabSteps': '调用明细字段',
|
||||
'settings.str.previewMountSidebarHint': '当前为仅侧边栏模式,主窗口不挂载胶囊;切回顶部栏或输入框挂载后将按上方样式呈现',
|
||||
'settings.str.mountSection': '挂载与胶囊栏',
|
||||
'settings.str.mountSection': '挂载胶囊',
|
||||
'settings.str.mountBadge': '{count}/5 项',
|
||||
'settings.str.mountMode': '面板挂载方式',
|
||||
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
|
||||
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
|
||||
'settings.str.mountSidebar': '仅侧边栏',
|
||||
'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': '鼠标悬浮窗',
|
||||
@@ -706,6 +709,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.str.stepsBadge': '{count} 列',
|
||||
'settings.str.stepTurnRailToggle': '对话轮次导轨',
|
||||
'settings.str.stepAgentBadgeToggle': '主/子代理标识',
|
||||
'settings.str.stepSpeedColorToggle': '输出速度多色分级',
|
||||
'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列,可拖拽)',
|
||||
'settings.str.addStepCol': '添加字段 ({count}/{max})',
|
||||
'settings.slot.dragHint': '按住上下拖动调整顺序',
|
||||
@@ -1175,8 +1179,11 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
|
||||
'settings.str.mountSidebar': 'Sidebar Only',
|
||||
'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',
|
||||
@@ -1196,6 +1203,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'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.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',
|
||||
@@ -2485,7 +2493,7 @@ const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([
|
||||
'claude_weekly',
|
||||
]);
|
||||
|
||||
const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||
const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
||||
|
||||
const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
@@ -2743,15 +2751,21 @@ function isEquivalentTelemetry(prev, next) {
|
||||
return false;
|
||||
}
|
||||
if (pSet?.enableWindowOverlay !== nSet?.enableWindowOverlay) return false;
|
||||
if ((pSet?.enableCliStatusLine !== false) !== (nSet?.enableCliStatusLine !== false)) {
|
||||
return false;
|
||||
}
|
||||
if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) {
|
||||
return false;
|
||||
}
|
||||
if ((pSet?.showStepTurnRail !== false) !== (nSet?.showStepTurnRail !== false)) {
|
||||
if (Boolean(pSet?.showStepTurnRail) !== Boolean(nSet?.showStepTurnRail)) {
|
||||
return false;
|
||||
}
|
||||
if ((pSet?.showStepAgentBadge !== false) !== (nSet?.showStepAgentBadge !== false)) {
|
||||
return false;
|
||||
}
|
||||
if (Boolean(pSet?.showStepSpeedColor) !== Boolean(nSet?.showStepSpeedColor)) {
|
||||
return false;
|
||||
}
|
||||
if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false;
|
||||
if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false;
|
||||
if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false;
|
||||
@@ -3365,6 +3379,9 @@ async function saveSettingsPatch(patch) {
|
||||
safePatch.weeklyLimitMode =
|
||||
mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official';
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) {
|
||||
safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) {
|
||||
safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession);
|
||||
}
|
||||
@@ -3374,6 +3391,9 @@ async function saveSettingsPatch(patch) {
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepAgentBadge')) {
|
||||
safePatch.showStepAgentBadge = Boolean(safePatch.showStepAgentBadge);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepSpeedColor')) {
|
||||
safePatch.showStepSpeedColor = Boolean(safePatch.showStepSpeedColor);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
|
||||
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
|
||||
}
|
||||
@@ -10331,7 +10351,8 @@ const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
key: 'tps',
|
||||
thLabel: () => t('stepCol.tps.th'),
|
||||
optLabel: () => t('stepCol.tps.opt'),
|
||||
sigPart: (st) => `${st.tokPerSec}:${st.selectedSpeedReason || ''}`,
|
||||
sigPart: (st, ctx) =>
|
||||
`${st.tokPerSec}:${st.selectedSpeedReason || ''}:${ctx?.showStepSpeedColor === true ? 1 : 0}`,
|
||||
createCell: () => {
|
||||
const speedMain = h('strong', {
|
||||
className: 'cell-value tone-muted',
|
||||
@@ -10345,9 +10366,17 @@ const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
const td = h('td', {}, [wrapEl]);
|
||||
return { td, refs: { wrapEl, speedMain, speedReason: null } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
updateCell: (refs, st, ctx) => {
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
patchAttr(refs.speedMain, 'class', `cell-value ${getSpeedToneClass(st.tokPerSec)}`);
|
||||
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', {
|
||||
@@ -10573,7 +10602,9 @@ function createCapsuleSlotNode(slotIndex, initialMetric) {
|
||||
? '--%'
|
||||
: initialMetric === 'tps'
|
||||
? '-- t/s'
|
||||
: t('capsule.quotaUnknown'),
|
||||
: initialMetric === 'ttft'
|
||||
? '--s'
|
||||
: t('capsule.quotaUnknown'),
|
||||
});
|
||||
const el = h(
|
||||
'span',
|
||||
@@ -10584,7 +10615,9 @@ function createCapsuleSlotNode(slotIndex, initialMetric) {
|
||||
? 'wm-cap-slot wm-ctx-seg'
|
||||
: initialMetric === 'tps'
|
||||
? 'wm-cap-slot wm-seg-speed'
|
||||
: 'wm-cap-slot wm-seg-quota',
|
||||
: initialMetric === 'ttft'
|
||||
? 'wm-cap-slot wm-seg-metric'
|
||||
: 'wm-cap-slot wm-seg-quota',
|
||||
hidden: isNone,
|
||||
'data-slot-idx': String(slotIndex),
|
||||
'data-metric': initialMetric,
|
||||
@@ -10679,9 +10712,9 @@ const CapsuleBarWidget = defineComponent({
|
||||
);
|
||||
|
||||
const capsuleSlots = [
|
||||
createCapsuleSlotNode(0, 'context'),
|
||||
createCapsuleSlotNode(1, 'tps'),
|
||||
createCapsuleSlotNode(2, 'quota_auto'),
|
||||
createCapsuleSlotNode(0, 'tps'),
|
||||
createCapsuleSlotNode(1, 'ttft'),
|
||||
createCapsuleSlotNode(2, 'context'),
|
||||
createCapsuleSlotNode(3, 'none'),
|
||||
createCapsuleSlotNode(4, 'none'),
|
||||
];
|
||||
@@ -11031,15 +11064,16 @@ const StepTableWidget = defineComponent({
|
||||
effectiveScopes = ['all'],
|
||||
hasSubagents = false,
|
||||
isMergedMultiAgents = false,
|
||||
showStepTurnRail = true,
|
||||
showStepTurnRail = false,
|
||||
showStepAgentBadge = true,
|
||||
showStepSpeedColor = false,
|
||||
displaySettings = {},
|
||||
} = {}
|
||||
) {
|
||||
const colOrderSig = colKeys.join(',');
|
||||
const renderOptions = JSON.stringify([
|
||||
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
|
||||
showStepTurnRail, showStepAgentBadge, displaySettings.showUpstreamModel,
|
||||
showStepTurnRail, showStepAgentBadge, showStepSpeedColor, displaySettings.showUpstreamModel,
|
||||
displaySettings.orchestratorIdMode,
|
||||
]);
|
||||
if (lastRenderOptions === renderOptions && lastRenderedRows &&
|
||||
@@ -11054,6 +11088,7 @@ const StepTableWidget = defineComponent({
|
||||
const cellCtx = {
|
||||
hasSubagents,
|
||||
showAgentBadge,
|
||||
showStepSpeedColor,
|
||||
effectiveScopes,
|
||||
scopeSigKey: effectiveScopes.join(','),
|
||||
displaySettings,
|
||||
@@ -12895,6 +12930,13 @@ function getMultiToggleOptions() {
|
||||
];
|
||||
}
|
||||
|
||||
function getEnableToggleOptions() {
|
||||
return [
|
||||
{ value: 'on', label: t('settings.str.on') },
|
||||
{ value: 'off', label: t('settings.str.off') },
|
||||
];
|
||||
}
|
||||
|
||||
function isSameList(a, b) {
|
||||
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
@@ -12908,13 +12950,15 @@ const SettingsStructureTab = defineComponent({
|
||||
setup({ props, onCleanup }) {
|
||||
let activeThirdTab = normalizeStructureTabKey(uiStore.getState().settingsStructureTab);
|
||||
let draftWindowMountMode = 'dual';
|
||||
let draftEnableCliStatusLine = true;
|
||||
let draftShowTopbarMulti = true;
|
||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
|
||||
let draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
|
||||
let draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS];
|
||||
let draftShowStepTurnRail = true;
|
||||
let draftShowStepTurnRail = false;
|
||||
let draftShowStepAgentBadge = true;
|
||||
let draftShowStepSpeedColor = false;
|
||||
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
let latestSettings = null;
|
||||
|
||||
@@ -12927,6 +12971,7 @@ const SettingsStructureTab = defineComponent({
|
||||
return buildStructurePreviewTelemetry(latestSettings, {
|
||||
windowMountMode: draftWindowMountMode,
|
||||
enableWindowOverlay: draftWindowMountMode !== 'sidebar',
|
||||
enableCliStatusLine: draftEnableCliStatusLine,
|
||||
showTopbarMultiSession: draftShowTopbarMulti,
|
||||
topbarCapsuleSlots: draftTopbarSlots,
|
||||
hoverModules: draftHoverModules,
|
||||
@@ -12934,6 +12979,7 @@ const SettingsStructureTab = defineComponent({
|
||||
overviewMetrics: draftOverviewMetrics,
|
||||
showStepTurnRail: draftShowStepTurnRail,
|
||||
showStepAgentBadge: draftShowStepAgentBadge,
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
stepTableColumns: draftStepColumns,
|
||||
});
|
||||
}
|
||||
@@ -13004,6 +13050,10 @@ const SettingsStructureTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.str.multiToggle'),
|
||||
});
|
||||
const cliCapsuleLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.cliCapsuleToggle'),
|
||||
});
|
||||
const capsuleSlotsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.capsuleSlotsLabel'),
|
||||
@@ -13038,6 +13088,19 @@ const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const cliCapsuleToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.cliCapsuleToggle'),
|
||||
modelValue: 'on',
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftEnableCliStatusLine = val !== 'off';
|
||||
syncMountSectionMeta();
|
||||
void persistStructurePatch(mountSection, {
|
||||
enableCliStatusLine: draftEnableCliStatusLine,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const topbarSlotsList = EditableSlotList({
|
||||
items: draftTopbarSlots,
|
||||
options: getCapsuleMetricOptions(),
|
||||
@@ -13065,6 +13128,7 @@ const SettingsStructureTab = defineComponent({
|
||||
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
|
||||
onReset: () => {
|
||||
draftWindowMountMode = 'dual';
|
||||
draftEnableCliStatusLine = true;
|
||||
draftShowTopbarMulti = true;
|
||||
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
syncMountSectionMeta();
|
||||
@@ -13074,6 +13138,7 @@ const SettingsStructureTab = defineComponent({
|
||||
{
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
enableCliStatusLine: true,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||
},
|
||||
@@ -13088,6 +13153,10 @@ const SettingsStructureTab = defineComponent({
|
||||
multiToggleLabelEl,
|
||||
multiSessionToggle.el,
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
cliCapsuleLabelEl,
|
||||
cliCapsuleToggle.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]),
|
||||
],
|
||||
});
|
||||
@@ -13106,6 +13175,10 @@ const SettingsStructureTab = defineComponent({
|
||||
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
cliCapsuleToggle.setProps({
|
||||
modelValue: draftEnableCliStatusLine ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
topbarSlotsList.refs.setProps({
|
||||
items: draftTopbarSlots,
|
||||
options: getCapsuleMetricOptions(),
|
||||
@@ -13116,6 +13189,7 @@ const SettingsStructureTab = defineComponent({
|
||||
);
|
||||
const isDefault =
|
||||
draftWindowMountMode === 'dual' &&
|
||||
draftEnableCliStatusLine === true &&
|
||||
draftShowTopbarMulti === true &&
|
||||
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
|
||||
mountSection.refs.setResetDisabled(isDefault);
|
||||
@@ -13376,6 +13450,10 @@ const SettingsStructureTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepAgentBadgeToggle'),
|
||||
});
|
||||
const stepSpeedColorLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepSpeedColorToggle'),
|
||||
});
|
||||
const stepColsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepsColsLabel'),
|
||||
@@ -13383,7 +13461,7 @@ const SettingsStructureTab = defineComponent({
|
||||
|
||||
const stepTurnRailToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepTurnRailToggle'),
|
||||
modelValue: 'show',
|
||||
modelValue: 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepTurnRail = val !== 'hide';
|
||||
@@ -13407,6 +13485,19 @@ const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const stepSpeedColorToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepSpeedColorToggle'),
|
||||
modelValue: 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepSpeedColor = val !== 'off';
|
||||
syncStepsSectionMeta();
|
||||
void persistStructurePatch(stepsSection, {
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const stepColumnsList = EditableSlotList({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
@@ -13433,16 +13524,18 @@ const SettingsStructureTab = defineComponent({
|
||||
title: t('settings.str.stepsSection'),
|
||||
badgeText: t('settings.str.stepsBadge', { count: draftStepColumns.length }),
|
||||
onReset: () => {
|
||||
draftShowStepTurnRail = true;
|
||||
draftShowStepTurnRail = false;
|
||||
draftShowStepAgentBadge = true;
|
||||
draftShowStepSpeedColor = false;
|
||||
draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
syncStepsSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(
|
||||
stepsSection,
|
||||
{
|
||||
showStepTurnRail: true,
|
||||
showStepTurnRail: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepSpeedColor: false,
|
||||
stepTableColumns: [...DEFAULT_CLIENT_STEP_COLUMNS],
|
||||
},
|
||||
'settings.resetDone'
|
||||
@@ -13459,6 +13552,10 @@ const SettingsStructureTab = defineComponent({
|
||||
stepAgentBadgeLabelEl,
|
||||
stepAgentBadgeToggle.el,
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
stepSpeedColorLabelEl,
|
||||
stepSpeedColorToggle.el,
|
||||
]),
|
||||
h('div', { className: 'settings-divider' }),
|
||||
h('div', { className: 'form-row' }, [stepColsLabelEl, stepColumnsList.el]),
|
||||
],
|
||||
@@ -13479,6 +13576,7 @@ const SettingsStructureTab = defineComponent({
|
||||
isMergedMultiAgents: true,
|
||||
showStepTurnRail: draftShowStepTurnRail,
|
||||
showStepAgentBadge: draftShowStepAgentBadge,
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
displaySettings: mockData.settings,
|
||||
}
|
||||
);
|
||||
@@ -13493,6 +13591,10 @@ const SettingsStructureTab = defineComponent({
|
||||
modelValue: draftShowStepAgentBadge ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
stepSpeedColorToggle.setProps({
|
||||
modelValue: draftShowStepSpeedColor ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
stepColumnsList.refs.setProps({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
@@ -13500,8 +13602,9 @@ const SettingsStructureTab = defineComponent({
|
||||
});
|
||||
stepsSection.refs.setBadge(t('settings.str.stepsBadge', { count: draftStepColumns.length }));
|
||||
const isDefault =
|
||||
draftShowStepTurnRail === true &&
|
||||
draftShowStepTurnRail === false &&
|
||||
draftShowStepAgentBadge === true &&
|
||||
draftShowStepSpeedColor === false &&
|
||||
isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS);
|
||||
stepsSection.refs.setResetDisabled(isDefault);
|
||||
refreshStepsPreview();
|
||||
@@ -13563,13 +13666,15 @@ const SettingsStructureTab = defineComponent({
|
||||
settings.windowMountMode,
|
||||
settings.enableWindowOverlay
|
||||
);
|
||||
draftEnableCliStatusLine = settings.enableCliStatusLine !== false;
|
||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
draftHoverModules = normalizeClientHoverModules(settings.hoverModules);
|
||||
draftOverviewModules = normalizeClientOverviewModules(settings.overviewModules);
|
||||
draftOverviewMetrics = normalizeClientOverviewMetrics(settings.overviewMetrics);
|
||||
draftShowStepTurnRail = settings.showStepTurnRail !== false;
|
||||
draftShowStepTurnRail = settings.showStepTurnRail === true;
|
||||
draftShowStepAgentBadge = settings.showStepAgentBadge !== false;
|
||||
draftShowStepSpeedColor = settings.showStepSpeedColor === true;
|
||||
draftStepColumns = normalizeClientStepColumns(settings.stepTableColumns);
|
||||
|
||||
syncMountSectionMeta();
|
||||
@@ -13588,6 +13693,7 @@ const SettingsStructureTab = defineComponent({
|
||||
mountSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(mountModeLabelEl, t('settings.str.mountMode'));
|
||||
patchText(multiToggleLabelEl, t('settings.str.multiToggle'));
|
||||
patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle'));
|
||||
patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel'));
|
||||
|
||||
hoverSection.refs.setTitle(t('settings.str.hoverSection'));
|
||||
@@ -13604,6 +13710,7 @@ const SettingsStructureTab = defineComponent({
|
||||
stepsSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(stepTurnRailLabelEl, t('settings.str.stepTurnRailToggle'));
|
||||
patchText(stepAgentBadgeLabelEl, t('settings.str.stepAgentBadgeToggle'));
|
||||
patchText(stepSpeedColorLabelEl, t('settings.str.stepSpeedColorToggle'));
|
||||
patchText(stepColsLabelEl, t('settings.str.stepsColsLabel'));
|
||||
|
||||
syncMountSectionMeta();
|
||||
@@ -13649,12 +13756,14 @@ const SettingsStructureTab = defineComponent({
|
||||
stepTablePreview.destroy();
|
||||
windowMountSelect.destroy();
|
||||
multiSessionToggle.destroy();
|
||||
cliCapsuleToggle.destroy();
|
||||
topbarSlotsList.destroy();
|
||||
hoverModulesList.destroy();
|
||||
overviewModulesList.destroy();
|
||||
overviewMetricsList.destroy();
|
||||
stepTurnRailToggle.destroy();
|
||||
stepAgentBadgeToggle.destroy();
|
||||
stepSpeedColorToggle.destroy();
|
||||
stepColumnsList.destroy();
|
||||
mountSection.destroy();
|
||||
hoverSection.destroy();
|
||||
@@ -13672,12 +13781,14 @@ const SettingsStructureTab = defineComponent({
|
||||
stepTablePreview,
|
||||
windowMountSelect,
|
||||
multiSessionToggle,
|
||||
cliCapsuleToggle,
|
||||
topbarSlotsList,
|
||||
hoverModulesList,
|
||||
overviewModulesList,
|
||||
overviewMetricsList,
|
||||
stepTurnRailToggle,
|
||||
stepAgentBadgeToggle,
|
||||
stepSpeedColorToggle,
|
||||
stepColumnsList,
|
||||
mountSection,
|
||||
hoverSection,
|
||||
@@ -16327,8 +16438,9 @@ const StepsDetailView = defineComponent({
|
||||
effectiveScopes,
|
||||
hasSubagents,
|
||||
isMergedMultiAgents,
|
||||
showStepTurnRail: slice.showStepTurnRail !== false,
|
||||
showStepTurnRail: slice.showStepTurnRail === true,
|
||||
showStepAgentBadge: slice.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: slice.showStepSpeedColor === true,
|
||||
displaySettings,
|
||||
});
|
||||
stepsScroll.refresh();
|
||||
@@ -16649,8 +16761,9 @@ const StepsDetailView = defineComponent({
|
||||
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
|
||||
st.telemetry?.settings?.orchestratorIdMode
|
||||
),
|
||||
showStepTurnRail: st.telemetry?.settings?.showStepTurnRail !== false,
|
||||
showStepTurnRail: st.telemetry?.settings?.showStepTurnRail === true,
|
||||
showStepAgentBadge: st.telemetry?.settings?.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: st.telemetry?.settings?.showStepSpeedColor === true,
|
||||
stepTableColumns: st.telemetry?.settings?.stepTableColumns,
|
||||
}),
|
||||
(slice) => {
|
||||
@@ -18212,9 +18325,9 @@ function mountWindowOverlay() {
|
||||
|
||||
// 构建可复用的预占胶囊槽位节点(由 CapsuleBarWidget 共享创建,支持 1..5 项动态槽位)
|
||||
const capsuleSlots = [
|
||||
createCapsuleSlotNode(0, 'context'),
|
||||
createCapsuleSlotNode(1, 'tps'),
|
||||
createCapsuleSlotNode(2, 'quota_auto'),
|
||||
createCapsuleSlotNode(0, 'tps'),
|
||||
createCapsuleSlotNode(1, 'ttft'),
|
||||
createCapsuleSlotNode(2, 'context'),
|
||||
createCapsuleSlotNode(3, 'none'),
|
||||
createCapsuleSlotNode(4, 'none'),
|
||||
];
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
notifyWindowOverlaySetting,
|
||||
startDefaultWindowBridge,
|
||||
} from './window-bridge.mjs';
|
||||
import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
|
||||
|
||||
export const bootBundleVersion = computeRuntimeCodeVersion();
|
||||
|
||||
@@ -222,7 +223,23 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
||||
};
|
||||
const payload = await buildTelemetryPayload(convId, force, filterOpts);
|
||||
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 &&
|
||||
@@ -305,6 +322,9 @@ export function executeSettingsAction(data) {
|
||||
) {
|
||||
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)
|
||||
@@ -387,6 +407,9 @@ export function executeResetSettingsAction() {
|
||||
} 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)
|
||||
@@ -501,6 +524,8 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu
|
||||
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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -176,6 +176,7 @@ 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)。
|
||||
@@ -335,6 +336,7 @@ export function computeRuntimeCodeVersion() {
|
||||
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,
|
||||
];
|
||||
|
||||
@@ -37,7 +37,7 @@ export const TOPBAR_SLOT_KEYS = Object.freeze([
|
||||
'claude_weekly',
|
||||
]);
|
||||
|
||||
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
||||
export const MIN_TOPBAR_SLOTS = 1;
|
||||
export const MAX_TOPBAR_SLOTS = 5;
|
||||
|
||||
@@ -368,14 +368,16 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
autoUpdatePlugin: false,
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
enableCliStatusLine: true,
|
||||
standalonePort: 0,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: DEFAULT_TOPBAR_SLOTS,
|
||||
hoverModules: DEFAULT_HOVER_MODULES,
|
||||
overviewModules: DEFAULT_OVERVIEW_MODULES,
|
||||
overviewMetrics: DEFAULT_OVERVIEW_METRICS,
|
||||
showStepTurnRail: true,
|
||||
showStepTurnRail: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepSpeedColor: false,
|
||||
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
|
||||
modelContextWindows: Object.freeze({}),
|
||||
});
|
||||
@@ -397,6 +399,7 @@ export function createDefaultSettingsObject() {
|
||||
autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin,
|
||||
windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode,
|
||||
enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay,
|
||||
enableCliStatusLine: DEFAULT_SETTINGS_SCHEMA.enableCliStatusLine,
|
||||
standalonePort: DEFAULT_SETTINGS_SCHEMA.standalonePort,
|
||||
showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession,
|
||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
||||
@@ -405,6 +408,7 @@ export function createDefaultSettingsObject() {
|
||||
overviewMetrics: [...DEFAULT_OVERVIEW_METRICS],
|
||||
showStepTurnRail: DEFAULT_SETTINGS_SCHEMA.showStepTurnRail,
|
||||
showStepAgentBadge: DEFAULT_SETTINGS_SCHEMA.showStepAgentBadge,
|
||||
showStepSpeedColor: DEFAULT_SETTINGS_SCHEMA.showStepSpeedColor,
|
||||
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
||||
modelContextWindows: {},
|
||||
};
|
||||
@@ -444,14 +448,16 @@ export function normalizeFullSettings(rawInput) {
|
||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||
windowMountMode,
|
||||
enableWindowOverlay: windowMountMode !== 'sidebar',
|
||||
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 !== false,
|
||||
showStepTurnRail: safeRaw.showStepTurnRail === true,
|
||||
showStepAgentBadge: safeRaw.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: safeRaw.showStepSpeedColor === true,
|
||||
stepTableColumns: normalizeStepTableColumns(safeRaw.stepTableColumns),
|
||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||
};
|
||||
|
||||
@@ -15,8 +15,9 @@ import {
|
||||
isLocalHostRequest,
|
||||
readLocalAsync,
|
||||
} from './api-actions.mjs';
|
||||
import { lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.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;
|
||||
@@ -574,6 +575,7 @@ export function createStandaloneWebServer(options = {}) {
|
||||
return getStatus();
|
||||
}
|
||||
if (!options.skipStartupDiscovery && lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
ensureCliStatusLineConfigured({ enabled: loadSettings().enableCliStatusLine !== false });
|
||||
if (lsRuntimeEndpoint.baseUrl) {
|
||||
syncCloudCatalog({ force: false }).catch(() => {});
|
||||
} else {
|
||||
|
||||
@@ -18,11 +18,13 @@ import {
|
||||
summarizeTtft,
|
||||
} from '../speed-metrics.mjs';
|
||||
import {
|
||||
CLI_STATUS_SNAPSHOT_FILE,
|
||||
computeRuntimeCodeVersion,
|
||||
inFlightRequests,
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
roundMetric,
|
||||
saveJson,
|
||||
trajectoryCache,
|
||||
} from './config.mjs';
|
||||
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
|
||||
@@ -1383,7 +1385,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
const finalPayload = {
|
||||
timestamp: new Date().toISOString(),
|
||||
uiBundleVersion,
|
||||
settings,
|
||||
@@ -1528,6 +1530,55 @@ export async function buildTelemetryPayloadInternal(
|
||||
},
|
||||
modelBreakdown,
|
||||
};
|
||||
|
||||
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
try {
|
||||
saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now()));
|
||||
} catch {
|
||||
// 快照落盘属于旁路辅助能力,任何异常绝不阻断主遥测响应
|
||||
}
|
||||
}
|
||||
|
||||
return finalPayload;
|
||||
}
|
||||
|
||||
export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) {
|
||||
const ac = finalPayload?.activeConversation || {};
|
||||
const capSource = ac.aggregated || ac;
|
||||
const ctx = ac.context || {};
|
||||
const limitTok = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTok = Number(ctx.totalTokens || 0);
|
||||
const usedPctVal =
|
||||
limitTok > 0 ? Math.min(100, +((totalTok / limitTok) * 100).toFixed(1)) : 0;
|
||||
|
||||
const runningList = Array.isArray(finalPayload?.runningConversations)
|
||||
? finalPayload.runningConversations
|
||||
: [];
|
||||
|
||||
return {
|
||||
updatedAtMs,
|
||||
runningCount: runningList.length,
|
||||
runningSubCount: runningList.reduce(
|
||||
(acc, item) => acc + Number(item?.runningSubagentCount || 0),
|
||||
0
|
||||
),
|
||||
hasWaiting: runningList.some((item) => item?.mainActivity?.phase === 'waiting'),
|
||||
quotas: finalPayload?.quotas || null,
|
||||
activeConversation: {
|
||||
cascadeId: ac.cascadeId || '',
|
||||
isRunning: Boolean(capSource.isRunning || ac.isRunning),
|
||||
stepCount: Number(capSource.stepCount ?? ac.stepCount ?? 0),
|
||||
usedPct: usedPctVal,
|
||||
latestTokPerSec: capSource.latestTokPerSec ?? ac.latestTokPerSec ?? null,
|
||||
avgTokPerSec: capSource.avgTokPerSec ?? ac.avgTokPerSec ?? null,
|
||||
latestTtftSec: capSource.latestTtftSec ?? ac.latestTtftSec ?? null,
|
||||
latestStepCostUsd: capSource.latestStepCostUsd ?? ac.latestStepCostUsd ?? null,
|
||||
sessionCostUsd: capSource.sessionCostUsd ?? ac.sessionCostUsd ?? null,
|
||||
latestCacheHitPct: capSource.latestCacheHitPct ?? ac.latestCacheHitPct ?? null,
|
||||
latestPromptTokens: Number(capSource.latestPromptTokens ?? ac.latestPromptTokens ?? 0),
|
||||
totalTokens: Number(capSource.totalTokens ?? ac.totalTokens ?? 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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=1794762860231">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794804132149">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794762860231"></script>
|
||||
<script src="/app.js?v=1794804132149"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1191,9 +1191,9 @@ export function mountWindowOverlay() {
|
||||
|
||||
// 构建可复用的预占胶囊槽位节点(由 CapsuleBarWidget 共享创建,支持 1..5 项动态槽位)
|
||||
const capsuleSlots = [
|
||||
createCapsuleSlotNode(0, 'context'),
|
||||
createCapsuleSlotNode(1, 'tps'),
|
||||
createCapsuleSlotNode(2, 'quota_auto'),
|
||||
createCapsuleSlotNode(0, 'tps'),
|
||||
createCapsuleSlotNode(1, 'ttft'),
|
||||
createCapsuleSlotNode(2, 'context'),
|
||||
createCapsuleSlotNode(3, 'none'),
|
||||
createCapsuleSlotNode(4, 'none'),
|
||||
];
|
||||
|
||||
@@ -54,7 +54,9 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) {
|
||||
? '--%'
|
||||
: initialMetric === 'tps'
|
||||
? '-- t/s'
|
||||
: t('capsule.quotaUnknown'),
|
||||
: initialMetric === 'ttft'
|
||||
? '--s'
|
||||
: t('capsule.quotaUnknown'),
|
||||
});
|
||||
const el = h(
|
||||
'span',
|
||||
@@ -65,7 +67,9 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) {
|
||||
? 'wm-cap-slot wm-ctx-seg'
|
||||
: initialMetric === 'tps'
|
||||
? 'wm-cap-slot wm-seg-speed'
|
||||
: 'wm-cap-slot wm-seg-quota',
|
||||
: initialMetric === 'ttft'
|
||||
? 'wm-cap-slot wm-seg-metric'
|
||||
: 'wm-cap-slot wm-seg-quota',
|
||||
hidden: isNone,
|
||||
'data-slot-idx': String(slotIndex),
|
||||
'data-metric': initialMetric,
|
||||
@@ -160,9 +164,9 @@ export const CapsuleBarWidget = defineComponent({
|
||||
);
|
||||
|
||||
const capsuleSlots = [
|
||||
createCapsuleSlotNode(0, 'context'),
|
||||
createCapsuleSlotNode(1, 'tps'),
|
||||
createCapsuleSlotNode(2, 'quota_auto'),
|
||||
createCapsuleSlotNode(0, 'tps'),
|
||||
createCapsuleSlotNode(1, 'ttft'),
|
||||
createCapsuleSlotNode(2, 'context'),
|
||||
createCapsuleSlotNode(3, 'none'),
|
||||
createCapsuleSlotNode(4, 'none'),
|
||||
];
|
||||
|
||||
@@ -166,15 +166,16 @@ export const StepTableWidget = defineComponent({
|
||||
effectiveScopes = ['all'],
|
||||
hasSubagents = false,
|
||||
isMergedMultiAgents = false,
|
||||
showStepTurnRail = true,
|
||||
showStepTurnRail = false,
|
||||
showStepAgentBadge = true,
|
||||
showStepSpeedColor = false,
|
||||
displaySettings = {},
|
||||
} = {}
|
||||
) {
|
||||
const colOrderSig = colKeys.join(',');
|
||||
const renderOptions = JSON.stringify([
|
||||
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
|
||||
showStepTurnRail, showStepAgentBadge, displaySettings.showUpstreamModel,
|
||||
showStepTurnRail, showStepAgentBadge, showStepSpeedColor, displaySettings.showUpstreamModel,
|
||||
displaySettings.orchestratorIdMode,
|
||||
]);
|
||||
if (lastRenderOptions === renderOptions && lastRenderedRows &&
|
||||
@@ -189,6 +190,7 @@ export const StepTableWidget = defineComponent({
|
||||
const cellCtx = {
|
||||
hasSubagents,
|
||||
showAgentBadge,
|
||||
showStepSpeedColor,
|
||||
effectiveScopes,
|
||||
scopeSigKey: effectiveScopes.join(','),
|
||||
displaySettings,
|
||||
|
||||
@@ -413,8 +413,11 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
|
||||
'settings.str.mountSidebar': 'Sidebar Only',
|
||||
'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',
|
||||
@@ -434,6 +437,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'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.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',
|
||||
|
||||
@@ -401,20 +401,23 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
|
||||
// Preferences -> Structure Tab
|
||||
'settings.str.thirdTabAria': '结构子菜单切换',
|
||||
'settings.str.tabMount': '挂载与胶囊',
|
||||
'settings.str.tabMount': '挂载胶囊',
|
||||
'settings.str.tabHover': '鼠标悬浮窗',
|
||||
'settings.str.tabOverview': '实时监控布局',
|
||||
'settings.str.tabSteps': '调用明细字段',
|
||||
'settings.str.previewMountSidebarHint': '当前为仅侧边栏模式,主窗口不挂载胶囊;切回顶部栏或输入框挂载后将按上方样式呈现',
|
||||
'settings.str.mountSection': '挂载与胶囊栏',
|
||||
'settings.str.mountSection': '挂载胶囊',
|
||||
'settings.str.mountBadge': '{count}/5 项',
|
||||
'settings.str.mountMode': '面板挂载方式',
|
||||
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
|
||||
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
|
||||
'settings.str.mountSidebar': '仅侧边栏',
|
||||
'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': '鼠标悬浮窗',
|
||||
@@ -434,6 +437,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.str.stepsBadge': '{count} 列',
|
||||
'settings.str.stepTurnRailToggle': '对话轮次导轨',
|
||||
'settings.str.stepAgentBadgeToggle': '主/子代理标识',
|
||||
'settings.str.stepSpeedColorToggle': '输出速度多色分级',
|
||||
'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列,可拖拽)',
|
||||
'settings.str.addStepCol': '添加字段 ({count}/{max})',
|
||||
'settings.slot.dragHint': '按住上下拖动调整顺序',
|
||||
|
||||
@@ -117,7 +117,8 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
key: 'tps',
|
||||
thLabel: () => t('stepCol.tps.th'),
|
||||
optLabel: () => t('stepCol.tps.opt'),
|
||||
sigPart: (st) => `${st.tokPerSec}:${st.selectedSpeedReason || ''}`,
|
||||
sigPart: (st, ctx) =>
|
||||
`${st.tokPerSec}:${st.selectedSpeedReason || ''}:${ctx?.showStepSpeedColor === true ? 1 : 0}`,
|
||||
createCell: () => {
|
||||
const speedMain = h('strong', {
|
||||
className: 'cell-value tone-muted',
|
||||
@@ -131,9 +132,17 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
const td = h('td', {}, [wrapEl]);
|
||||
return { td, refs: { wrapEl, speedMain, speedReason: null } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
updateCell: (refs, st, ctx) => {
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
patchAttr(refs.speedMain, 'class', `cell-value ${getSpeedToneClass(st.tokPerSec)}`);
|
||||
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', {
|
||||
|
||||
@@ -122,7 +122,7 @@ export const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([
|
||||
'claude_weekly',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||
export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
||||
|
||||
export const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
@@ -380,15 +380,21 @@ function isEquivalentTelemetry(prev, next) {
|
||||
return false;
|
||||
}
|
||||
if (pSet?.enableWindowOverlay !== nSet?.enableWindowOverlay) return false;
|
||||
if ((pSet?.enableCliStatusLine !== false) !== (nSet?.enableCliStatusLine !== false)) {
|
||||
return false;
|
||||
}
|
||||
if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) {
|
||||
return false;
|
||||
}
|
||||
if ((pSet?.showStepTurnRail !== false) !== (nSet?.showStepTurnRail !== false)) {
|
||||
if (Boolean(pSet?.showStepTurnRail) !== Boolean(nSet?.showStepTurnRail)) {
|
||||
return false;
|
||||
}
|
||||
if ((pSet?.showStepAgentBadge !== false) !== (nSet?.showStepAgentBadge !== false)) {
|
||||
return false;
|
||||
}
|
||||
if (Boolean(pSet?.showStepSpeedColor) !== Boolean(nSet?.showStepSpeedColor)) {
|
||||
return false;
|
||||
}
|
||||
if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false;
|
||||
if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false;
|
||||
if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false;
|
||||
@@ -1002,6 +1008,9 @@ export async function saveSettingsPatch(patch) {
|
||||
safePatch.weeklyLimitMode =
|
||||
mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official';
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) {
|
||||
safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) {
|
||||
safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession);
|
||||
}
|
||||
@@ -1011,6 +1020,9 @@ export async function saveSettingsPatch(patch) {
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepAgentBadge')) {
|
||||
safePatch.showStepAgentBadge = Boolean(safePatch.showStepAgentBadge);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepSpeedColor')) {
|
||||
safePatch.showStepSpeedColor = Boolean(safePatch.showStepSpeedColor);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
|
||||
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
|
||||
}
|
||||
|
||||
@@ -726,8 +726,9 @@ export const StepsDetailView = defineComponent({
|
||||
effectiveScopes,
|
||||
hasSubagents,
|
||||
isMergedMultiAgents,
|
||||
showStepTurnRail: slice.showStepTurnRail !== false,
|
||||
showStepTurnRail: slice.showStepTurnRail === true,
|
||||
showStepAgentBadge: slice.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: slice.showStepSpeedColor === true,
|
||||
displaySettings,
|
||||
});
|
||||
stepsScroll.refresh();
|
||||
@@ -1048,8 +1049,9 @@ export const StepsDetailView = defineComponent({
|
||||
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
|
||||
st.telemetry?.settings?.orchestratorIdMode
|
||||
),
|
||||
showStepTurnRail: st.telemetry?.settings?.showStepTurnRail !== false,
|
||||
showStepTurnRail: st.telemetry?.settings?.showStepTurnRail === true,
|
||||
showStepAgentBadge: st.telemetry?.settings?.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: st.telemetry?.settings?.showStepSpeedColor === true,
|
||||
stepTableColumns: st.telemetry?.settings?.stepTableColumns,
|
||||
}),
|
||||
(slice) => {
|
||||
|
||||
@@ -69,6 +69,13 @@ function getMultiToggleOptions() {
|
||||
];
|
||||
}
|
||||
|
||||
function getEnableToggleOptions() {
|
||||
return [
|
||||
{ value: 'on', label: t('settings.str.on') },
|
||||
{ value: 'off', label: t('settings.str.off') },
|
||||
];
|
||||
}
|
||||
|
||||
function isSameList(a, b) {
|
||||
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
@@ -82,13 +89,15 @@ export const SettingsStructureTab = defineComponent({
|
||||
setup({ props, onCleanup }) {
|
||||
let activeThirdTab = normalizeStructureTabKey(uiStore.getState().settingsStructureTab);
|
||||
let draftWindowMountMode = 'dual';
|
||||
let draftEnableCliStatusLine = true;
|
||||
let draftShowTopbarMulti = true;
|
||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
|
||||
let draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
|
||||
let draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS];
|
||||
let draftShowStepTurnRail = true;
|
||||
let draftShowStepTurnRail = false;
|
||||
let draftShowStepAgentBadge = true;
|
||||
let draftShowStepSpeedColor = false;
|
||||
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
let latestSettings = null;
|
||||
|
||||
@@ -101,6 +110,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
return buildStructurePreviewTelemetry(latestSettings, {
|
||||
windowMountMode: draftWindowMountMode,
|
||||
enableWindowOverlay: draftWindowMountMode !== 'sidebar',
|
||||
enableCliStatusLine: draftEnableCliStatusLine,
|
||||
showTopbarMultiSession: draftShowTopbarMulti,
|
||||
topbarCapsuleSlots: draftTopbarSlots,
|
||||
hoverModules: draftHoverModules,
|
||||
@@ -108,6 +118,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
overviewMetrics: draftOverviewMetrics,
|
||||
showStepTurnRail: draftShowStepTurnRail,
|
||||
showStepAgentBadge: draftShowStepAgentBadge,
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
stepTableColumns: draftStepColumns,
|
||||
});
|
||||
}
|
||||
@@ -178,6 +189,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.str.multiToggle'),
|
||||
});
|
||||
const cliCapsuleLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.cliCapsuleToggle'),
|
||||
});
|
||||
const capsuleSlotsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.capsuleSlotsLabel'),
|
||||
@@ -212,6 +227,19 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const cliCapsuleToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.cliCapsuleToggle'),
|
||||
modelValue: 'on',
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftEnableCliStatusLine = val !== 'off';
|
||||
syncMountSectionMeta();
|
||||
void persistStructurePatch(mountSection, {
|
||||
enableCliStatusLine: draftEnableCliStatusLine,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const topbarSlotsList = EditableSlotList({
|
||||
items: draftTopbarSlots,
|
||||
options: getCapsuleMetricOptions(),
|
||||
@@ -239,6 +267,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
|
||||
onReset: () => {
|
||||
draftWindowMountMode = 'dual';
|
||||
draftEnableCliStatusLine = true;
|
||||
draftShowTopbarMulti = true;
|
||||
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
syncMountSectionMeta();
|
||||
@@ -248,6 +277,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
{
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
enableCliStatusLine: true,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||
},
|
||||
@@ -262,6 +292,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
multiToggleLabelEl,
|
||||
multiSessionToggle.el,
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
cliCapsuleLabelEl,
|
||||
cliCapsuleToggle.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]),
|
||||
],
|
||||
});
|
||||
@@ -280,6 +314,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
cliCapsuleToggle.setProps({
|
||||
modelValue: draftEnableCliStatusLine ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
topbarSlotsList.refs.setProps({
|
||||
items: draftTopbarSlots,
|
||||
options: getCapsuleMetricOptions(),
|
||||
@@ -290,6 +328,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
);
|
||||
const isDefault =
|
||||
draftWindowMountMode === 'dual' &&
|
||||
draftEnableCliStatusLine === true &&
|
||||
draftShowTopbarMulti === true &&
|
||||
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
|
||||
mountSection.refs.setResetDisabled(isDefault);
|
||||
@@ -550,6 +589,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepAgentBadgeToggle'),
|
||||
});
|
||||
const stepSpeedColorLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepSpeedColorToggle'),
|
||||
});
|
||||
const stepColsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepsColsLabel'),
|
||||
@@ -557,7 +600,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
|
||||
const stepTurnRailToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepTurnRailToggle'),
|
||||
modelValue: 'show',
|
||||
modelValue: 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepTurnRail = val !== 'hide';
|
||||
@@ -581,6 +624,19 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const stepSpeedColorToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.stepSpeedColorToggle'),
|
||||
modelValue: 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowStepSpeedColor = val !== 'off';
|
||||
syncStepsSectionMeta();
|
||||
void persistStructurePatch(stepsSection, {
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const stepColumnsList = EditableSlotList({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
@@ -607,16 +663,18 @@ export const SettingsStructureTab = defineComponent({
|
||||
title: t('settings.str.stepsSection'),
|
||||
badgeText: t('settings.str.stepsBadge', { count: draftStepColumns.length }),
|
||||
onReset: () => {
|
||||
draftShowStepTurnRail = true;
|
||||
draftShowStepTurnRail = false;
|
||||
draftShowStepAgentBadge = true;
|
||||
draftShowStepSpeedColor = false;
|
||||
draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
syncStepsSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(
|
||||
stepsSection,
|
||||
{
|
||||
showStepTurnRail: true,
|
||||
showStepTurnRail: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepSpeedColor: false,
|
||||
stepTableColumns: [...DEFAULT_CLIENT_STEP_COLUMNS],
|
||||
},
|
||||
'settings.resetDone'
|
||||
@@ -633,6 +691,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
stepAgentBadgeLabelEl,
|
||||
stepAgentBadgeToggle.el,
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
stepSpeedColorLabelEl,
|
||||
stepSpeedColorToggle.el,
|
||||
]),
|
||||
h('div', { className: 'settings-divider' }),
|
||||
h('div', { className: 'form-row' }, [stepColsLabelEl, stepColumnsList.el]),
|
||||
],
|
||||
@@ -653,6 +715,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
isMergedMultiAgents: true,
|
||||
showStepTurnRail: draftShowStepTurnRail,
|
||||
showStepAgentBadge: draftShowStepAgentBadge,
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
displaySettings: mockData.settings,
|
||||
}
|
||||
);
|
||||
@@ -667,6 +730,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
modelValue: draftShowStepAgentBadge ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
stepSpeedColorToggle.setProps({
|
||||
modelValue: draftShowStepSpeedColor ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
stepColumnsList.refs.setProps({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
@@ -674,8 +741,9 @@ export const SettingsStructureTab = defineComponent({
|
||||
});
|
||||
stepsSection.refs.setBadge(t('settings.str.stepsBadge', { count: draftStepColumns.length }));
|
||||
const isDefault =
|
||||
draftShowStepTurnRail === true &&
|
||||
draftShowStepTurnRail === false &&
|
||||
draftShowStepAgentBadge === true &&
|
||||
draftShowStepSpeedColor === false &&
|
||||
isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS);
|
||||
stepsSection.refs.setResetDisabled(isDefault);
|
||||
refreshStepsPreview();
|
||||
@@ -737,13 +805,15 @@ export const SettingsStructureTab = defineComponent({
|
||||
settings.windowMountMode,
|
||||
settings.enableWindowOverlay
|
||||
);
|
||||
draftEnableCliStatusLine = settings.enableCliStatusLine !== false;
|
||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
draftHoverModules = normalizeClientHoverModules(settings.hoverModules);
|
||||
draftOverviewModules = normalizeClientOverviewModules(settings.overviewModules);
|
||||
draftOverviewMetrics = normalizeClientOverviewMetrics(settings.overviewMetrics);
|
||||
draftShowStepTurnRail = settings.showStepTurnRail !== false;
|
||||
draftShowStepTurnRail = settings.showStepTurnRail === true;
|
||||
draftShowStepAgentBadge = settings.showStepAgentBadge !== false;
|
||||
draftShowStepSpeedColor = settings.showStepSpeedColor === true;
|
||||
draftStepColumns = normalizeClientStepColumns(settings.stepTableColumns);
|
||||
|
||||
syncMountSectionMeta();
|
||||
@@ -762,6 +832,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
mountSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(mountModeLabelEl, t('settings.str.mountMode'));
|
||||
patchText(multiToggleLabelEl, t('settings.str.multiToggle'));
|
||||
patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle'));
|
||||
patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel'));
|
||||
|
||||
hoverSection.refs.setTitle(t('settings.str.hoverSection'));
|
||||
@@ -778,6 +849,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
stepsSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(stepTurnRailLabelEl, t('settings.str.stepTurnRailToggle'));
|
||||
patchText(stepAgentBadgeLabelEl, t('settings.str.stepAgentBadgeToggle'));
|
||||
patchText(stepSpeedColorLabelEl, t('settings.str.stepSpeedColorToggle'));
|
||||
patchText(stepColsLabelEl, t('settings.str.stepsColsLabel'));
|
||||
|
||||
syncMountSectionMeta();
|
||||
@@ -823,12 +895,14 @@ export const SettingsStructureTab = defineComponent({
|
||||
stepTablePreview.destroy();
|
||||
windowMountSelect.destroy();
|
||||
multiSessionToggle.destroy();
|
||||
cliCapsuleToggle.destroy();
|
||||
topbarSlotsList.destroy();
|
||||
hoverModulesList.destroy();
|
||||
overviewModulesList.destroy();
|
||||
overviewMetricsList.destroy();
|
||||
stepTurnRailToggle.destroy();
|
||||
stepAgentBadgeToggle.destroy();
|
||||
stepSpeedColorToggle.destroy();
|
||||
stepColumnsList.destroy();
|
||||
mountSection.destroy();
|
||||
hoverSection.destroy();
|
||||
@@ -846,12 +920,14 @@ export const SettingsStructureTab = defineComponent({
|
||||
stepTablePreview,
|
||||
windowMountSelect,
|
||||
multiSessionToggle,
|
||||
cliCapsuleToggle,
|
||||
topbarSlotsList,
|
||||
hoverModulesList,
|
||||
overviewModulesList,
|
||||
overviewMetricsList,
|
||||
stepTurnRailToggle,
|
||||
stepAgentBadgeToggle,
|
||||
stepSpeedColorToggle,
|
||||
stepColumnsList,
|
||||
mountSection,
|
||||
hoverSection,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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';
|
||||
@@ -22,6 +23,7 @@ const BACKEND_MODULE_FILES = [
|
||||
'../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',
|
||||
@@ -82,6 +84,8 @@ export function backendHarness({
|
||||
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'));
|
||||
@@ -150,7 +154,7 @@ export function backendHarness({
|
||||
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,fileURLToPath:()=>mainPath,
|
||||
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={})=>{
|
||||
@@ -172,6 +176,6 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
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,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle};',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,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -967,12 +967,14 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
|
||||
assert.equal(def.windowMountMode, 'dual');
|
||||
assert.equal(def.enableWindowOverlay, true);
|
||||
assert.equal(def.showTopbarMultiSession, true);
|
||||
assert.deepEqual([...def.topbarCapsuleSlots], ['context', 'tps', 'quota_auto']);
|
||||
assert.equal(def.enableCliStatusLine, true);
|
||||
assert.deepEqual([...def.topbarCapsuleSlots], ['tps', 'ttft', 'context']);
|
||||
assert.deepEqual([...def.hoverModules], ['metrics', 'context', 'quotas']);
|
||||
assert.deepEqual([...def.overviewModules], ['metrics', 'context', 'quotas', 'live_tasks']);
|
||||
assert.deepEqual([...def.overviewMetrics], ['tps', 'ttft', 'avg_tps', 'step_cost']);
|
||||
assert.equal(def.showStepTurnRail, true);
|
||||
assert.equal(def.showStepTurnRail, false);
|
||||
assert.equal(def.showStepAgentBadge, true);
|
||||
assert.equal(def.showStepSpeedColor, false);
|
||||
assert.deepEqual([...def.stepTableColumns], ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost']);
|
||||
assert.deepEqual({ ...def.modelContextWindows }, {});
|
||||
|
||||
@@ -1003,8 +1005,10 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
|
||||
hoverModules: ['metrics', 'context'],
|
||||
overviewModules: ['quotas', 'metrics'],
|
||||
overviewMetrics: ['avg_tps', 'cache_hit'],
|
||||
showStepTurnRail: false,
|
||||
enableCliStatusLine: false,
|
||||
showStepTurnRail: true,
|
||||
showStepAgentBadge: false,
|
||||
showStepSpeedColor: true,
|
||||
stepTableColumns: ['step', 'time', 'model', 'duration', 'input_tokens', 'output_tokens', 'cost'],
|
||||
contextLimitOverrideTokens: 128000,
|
||||
modelContextWindows: { MODEL_PLACEHOLDER_M418: '900K' },
|
||||
@@ -1017,8 +1021,10 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
|
||||
assert.deepEqual([...saveRes.updated.hoverModules], ['metrics', 'context']);
|
||||
assert.deepEqual([...saveRes.updated.overviewModules], ['quotas', 'metrics']);
|
||||
assert.deepEqual([...saveRes.updated.overviewMetrics], ['avg_tps', 'cache_hit']);
|
||||
assert.equal(saveRes.updated.showStepTurnRail, false);
|
||||
assert.equal(saveRes.updated.enableCliStatusLine, false);
|
||||
assert.equal(saveRes.updated.showStepTurnRail, true);
|
||||
assert.equal(saveRes.updated.showStepAgentBadge, false);
|
||||
assert.equal(saveRes.updated.showStepSpeedColor, true);
|
||||
assert.equal(saveRes.updated.contextLimitOverrideTokens, undefined);
|
||||
assert.deepEqual({ ...saveRes.updated.modelContextWindows }, {});
|
||||
|
||||
@@ -1046,9 +1052,11 @@ test('preferences schema defaults match pre-refactor UI, migrate legacy none slo
|
||||
assert.equal(resetRes.ok, true);
|
||||
assert.equal(resetRes.updated.language, 'zh-CN');
|
||||
assert.equal(resetRes.updated.themeAccent, 'host');
|
||||
assert.equal(resetRes.updated.showStepTurnRail, true);
|
||||
assert.equal(resetRes.updated.enableCliStatusLine, true);
|
||||
assert.equal(resetRes.updated.showStepTurnRail, false);
|
||||
assert.equal(resetRes.updated.showStepAgentBadge, true);
|
||||
assert.deepEqual([...resetRes.updated.topbarCapsuleSlots], ['context', 'tps', 'quota_auto']);
|
||||
assert.equal(resetRes.updated.showStepSpeedColor, false);
|
||||
assert.deepEqual([...resetRes.updated.topbarCapsuleSlots], ['tps', 'ttft', 'context']);
|
||||
});
|
||||
|
||||
test('assigns unified rootTurnIndex across interleaved main and subagent steps so multi-agent turn rail never fragments', async () => {
|
||||
@@ -1760,3 +1768,420 @@ test('Antigravity CLI annotations.pbtxt + SQLite trajectory reader recovers titl
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('provisions Antigravity CLI statusLine safely and renders live capsule from stdin + SQLite + quota snapshot', async (t) => {
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) {
|
||||
t.skip('node:sqlite is unavailable in this Node runtime');
|
||||
return;
|
||||
}
|
||||
|
||||
const h = backendHarness();
|
||||
assert.equal(
|
||||
h.buildCliStatusLineCommand('C:\\Users\\Administrator\\.gemini\\config\\plugins\\usage-monitor\\sidecars\\panel\\cli-statusline.mjs', {
|
||||
platform: 'win32',
|
||||
nodeOnPath: true,
|
||||
}),
|
||||
'node C:/Users/Administrator/.gemini/config/plugins/usage-monitor/sidecars/panel/cli-statusline.mjs'
|
||||
);
|
||||
const winSpaceCmd = h.buildCliStatusLineCommand(
|
||||
'C:\\Users\\Alice Smith\\.gemini\\config\\plugins\\usage-monitor\\sidecars\\panel\\cli-statusline.mjs',
|
||||
{
|
||||
platform: 'win32',
|
||||
execPath: 'C:\\Program Files\\nodejs\\node.exe',
|
||||
nodeOnPath: false,
|
||||
}
|
||||
);
|
||||
assert.equal(
|
||||
winSpaceCmd,
|
||||
"node --input-type=module -e import('file:///C:/Users/Alice%20Smith/.gemini/config/plugins/usage-monitor/sidecars/panel/cli-statusline.mjs#autorun')"
|
||||
);
|
||||
assert.equal(winSpaceCmd.includes('"'), false, 'Windows command must contain zero double quotes so Go syscall.EscapeArg never injects \\"');
|
||||
assert.equal(h.isManagedCliStatusLineCommand('node C:/path/to/cli-statusline.mjs'), true);
|
||||
assert.equal(h.isManagedCliStatusLineCommand(winSpaceCmd), true);
|
||||
assert.equal(h.isManagedCliStatusLineCommand('node "C:/legacy/path/cli-statusline.mjs"'), true);
|
||||
assert.equal(h.isManagedCliStatusLineCommand('python C:/custom/my-status.py'), false);
|
||||
|
||||
// Never overwrites user's third-party statusLine command
|
||||
const customPreserved = h.applyCliStatusLineToSettingsObject(
|
||||
{ theme: 'dark', statusLine: { type: 'command', command: 'python ~/my-status.py', enabled: true } },
|
||||
{ enabled: true, command: 'node "/plugin/cli-statusline.mjs"' }
|
||||
);
|
||||
assert.equal(customPreserved.changed, false);
|
||||
assert.equal(customPreserved.preservedCustom, true);
|
||||
|
||||
// Migrates legacy managed stack_with_default: true to single-line inline stack_with_default: false
|
||||
const migratedStack = h.applyCliStatusLineToSettingsObject(
|
||||
{
|
||||
statusLine: {
|
||||
type: 'command',
|
||||
command: 'node C:/plugin/cli-statusline.mjs',
|
||||
enabled: true,
|
||||
padding: 0,
|
||||
stack_with_default: true,
|
||||
},
|
||||
},
|
||||
{ enabled: true, command: 'node C:/plugin/cli-statusline.mjs' }
|
||||
);
|
||||
assert.equal(migratedStack.changed, true);
|
||||
assert.equal(migratedStack.object.statusLine.stack_with_default, false);
|
||||
|
||||
assert.deepEqual({ ...h.parseCliModelAndEffort('Gemini 4 Hydrogen (Medium)', 'medium') }, {
|
||||
modelName: 'Gemini 4 Hydrogen',
|
||||
effort: 'medium',
|
||||
});
|
||||
assert.deepEqual({ ...h.parseCliModelAndEffort('Gemini 4 Hydrogen (High)', '') }, {
|
||||
modelName: 'Gemini 4 Hydrogen',
|
||||
effort: 'high',
|
||||
});
|
||||
|
||||
// Capsule formatting in NO_COLOR and 24-bit ANSI modes uses transparent background (zero 48;...m SGR)
|
||||
const plainCapsule = h.formatCliStatusLineCapsule(
|
||||
{
|
||||
hasTelemetry: true,
|
||||
runningCount: 0,
|
||||
runningSubCount: 0,
|
||||
ttft: 11.8,
|
||||
tps: 38.1,
|
||||
usedPct: 17,
|
||||
quotas: { activePool: { remainingPct: 57 } },
|
||||
},
|
||||
{
|
||||
slots: ['ttft', 'tps', 'quota_auto', 'context'],
|
||||
showMultiSession: true,
|
||||
language: 'zh-CN',
|
||||
color: false,
|
||||
}
|
||||
);
|
||||
assert.equal(plainCapsule, '● 0 运行中 11.8s | 38.1 t/s | 余 57% | ◎ 17%');
|
||||
|
||||
const ansiCapsule = h.formatCliStatusLineCapsule(
|
||||
{
|
||||
hasTelemetry: true,
|
||||
runningCount: 2,
|
||||
runningSubCount: 1,
|
||||
ttft: 1.25,
|
||||
tps: 68.4,
|
||||
usedPct: 75,
|
||||
quotas: { activePool: { remainingPct: 22 } },
|
||||
},
|
||||
{
|
||||
slots: ['ttft', 'tps', 'quota_auto', 'context'],
|
||||
showMultiSession: true,
|
||||
language: 'zh-CN',
|
||||
color: true,
|
||||
}
|
||||
);
|
||||
assert.equal(/\x1b\[48;/.test(ansiCapsule), false, 'Emits zero background SGR codes');
|
||||
assert.equal(/\x1b\]/.test(ansiCapsule), false, 'Contains zero OSC sequences so Bubble Tea width never breaks');
|
||||
assert.equal(
|
||||
ansiCapsule.replace(/\x1b\[[0-9;]*m/g, ''),
|
||||
'● 2 运行中 · 1 子 1.3s | 68.4 t/s | 余 22% | ◎ 75%'
|
||||
);
|
||||
|
||||
// Full 3-column single-line bar with left shortcuts, centered metrics, and right mode/model/effort
|
||||
const inlineBar120 = h.formatCliStatusLineCapsule(
|
||||
{
|
||||
hasTelemetry: true,
|
||||
runningCount: 2,
|
||||
runningSubCount: 0,
|
||||
ttft: 5.6,
|
||||
tps: 22.0,
|
||||
usedPct: 2,
|
||||
quotas: { activePool: { remainingPct: 54 } },
|
||||
},
|
||||
{
|
||||
slots: ['ttft', 'tps', 'quota_auto', 'context'],
|
||||
showMultiSession: true,
|
||||
language: 'zh-CN',
|
||||
color: true,
|
||||
terminalWidth: 120,
|
||||
cycleMode: 'auto',
|
||||
modelDisplayName: 'Gemini 4 Hydrogen (Medium)',
|
||||
modelEffort: 'medium',
|
||||
}
|
||||
);
|
||||
assert.equal(/\x1b\[48;/.test(inlineBar120), false, 'Inline 3-column bar has zero background SGR');
|
||||
const plainBar120 = inlineBar120.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
assert.ok(plainBar120.startsWith('? for shortcuts '), 'Keeps ? for shortcuts on the left');
|
||||
assert.ok(plainBar120.includes('● 2 运行中 5.6s | 22.0 t/s | 余 54% | ◎ 2%'), 'Centers capsule metrics inline');
|
||||
assert.ok(plainBar120.endsWith(' auto · Gemini 4 Hydrogen · medium'), 'Renders deduplicated mode · model · effort on the right');
|
||||
assert.equal(h.cliDisplayWidth(inlineBar120), 119, 'Fits cleanly within terminalWidth - 1 without wrapping');
|
||||
|
||||
// Narrow 80-column terminal gracefully compacts without wrapping
|
||||
const inlineBar80 = h.formatCliStatusLineCapsule(
|
||||
{
|
||||
hasTelemetry: true,
|
||||
runningCount: 2,
|
||||
runningSubCount: 0,
|
||||
ttft: 5.6,
|
||||
tps: 22.0,
|
||||
usedPct: 2,
|
||||
quotas: { activePool: { remainingPct: 54 } },
|
||||
},
|
||||
{
|
||||
slots: ['ttft', 'tps', 'quota_auto', 'context'],
|
||||
showMultiSession: true,
|
||||
language: 'zh-CN',
|
||||
color: false,
|
||||
terminalWidth: 80,
|
||||
cycleMode: 'auto',
|
||||
modelDisplayName: 'Gemini 4 Hydrogen (Medium)',
|
||||
modelEffort: 'medium',
|
||||
}
|
||||
);
|
||||
assert.ok(h.cliDisplayWidth(inlineBar80) <= 79, 'Narrow 80-col bar never overflows terminalWidth - 1');
|
||||
assert.ok(inlineBar80.includes('5.6s | 22.0 t/s | 余 54% | ◎ 2%'));
|
||||
|
||||
// End-to-end filesystem + subprocess verification
|
||||
const tempRoot = mkdtempSync(fileURLToPath(new URL('./.cli-statusline-', import.meta.url)));
|
||||
try {
|
||||
const cliDir = join(tempRoot, 'antigravity-cli');
|
||||
const convDir = join(cliDir, 'conversations');
|
||||
const dataDir = join(tempRoot, 'data');
|
||||
mkdirSync(convDir, { recursive: true });
|
||||
mkdirSync(dataDir, { recursive: true });
|
||||
|
||||
const cliSettingsFile = join(cliDir, 'settings.json');
|
||||
writeFileSync(
|
||||
cliSettingsFile,
|
||||
JSON.stringify({ selectedAuthType: 'oauth', model: 'gemini-3.1-pro-high' }, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const statusLineScript = fileURLToPath(new URL('../cli-statusline.mjs', import.meta.url));
|
||||
const installEnv = {
|
||||
...process.env,
|
||||
ANTIGRAVITY_GEMINI_DIR: tempRoot,
|
||||
USAGE_MONITOR_DATA_DIR: dataDir,
|
||||
USAGE_MONITOR_ALLOW_TEST_CLI_SETTINGS: '1',
|
||||
};
|
||||
|
||||
const installOut = JSON.parse(
|
||||
execFileSync(process.execPath, [statusLineScript, '--install'], {
|
||||
env: installEnv,
|
||||
encoding: 'utf8',
|
||||
}).trim()
|
||||
);
|
||||
assert.equal(installOut.updated, true);
|
||||
const writtenSettings = JSON.parse(readFileSync(cliSettingsFile, 'utf8'));
|
||||
assert.equal(writtenSettings.selectedAuthType, 'oauth', 'Existing CLI settings preserved');
|
||||
assert.equal(writtenSettings.statusLine.type, 'command');
|
||||
assert.equal(writtenSettings.statusLine.enabled, true);
|
||||
assert.equal(writtenSettings.statusLine.stack_with_default, false);
|
||||
assert.ok(writtenSettings.statusLine.command.includes('cli-statusline.mjs'));
|
||||
|
||||
// Prepare real SQLite conversation + summaries + quota snapshot + custom user slot order
|
||||
const cid = '22222222-3333-4444-5555-666666666666';
|
||||
const sumDb = new DatabaseSync(join(cliDir, 'conversation_summaries.db'));
|
||||
sumDb.exec(`
|
||||
CREATE TABLE conversation_summaries (
|
||||
conversation_id TEXT NOT NULL,
|
||||
title TEXT,
|
||||
status TEXT,
|
||||
parent_conversation_id TEXT,
|
||||
agent_name TEXT,
|
||||
not_fully_idle INTEGER,
|
||||
killed INTEGER,
|
||||
step_count INTEGER,
|
||||
last_modified_time TEXT,
|
||||
app_data_dir TEXT
|
||||
);
|
||||
CREATE TABLE conversations_fts (conversation_id TEXT, title TEXT, workspace TEXT, last_modified_time INTEGER, chunk_index INTEGER);
|
||||
`);
|
||||
sumDb
|
||||
.prepare(
|
||||
`INSERT INTO conversation_summaries
|
||||
(conversation_id, title, status, parent_conversation_id, agent_name, not_fully_idle, killed, step_count, last_modified_time, app_data_dir)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.run(cid, 'CLI Capsule E2E', 'CASCADE_RUN_STATUS_IDLE', '', '', 0, 0, 2, '2026-11-15 17:00:15+00:00', 'antigravity-cli');
|
||||
sumDb
|
||||
.prepare('INSERT INTO conversations_fts (conversation_id, title, workspace, last_modified_time, chunk_index) VALUES (?, ?, ?, ?, ?)')
|
||||
.run(cid, 'CLI Capsule E2E', 'C:/Work/MyProject', 1794762015, -1);
|
||||
sumDb.close();
|
||||
|
||||
// 10.0s request (1794762001.0s -> 1794762011.0s), 381 outputTokens => 38.1 tok/s, TTFT = 1.8s
|
||||
const modelUsageBuf = Buffer.concat([
|
||||
encodeProtoFieldVarint(1, 1425), // MODEL_PLACEHOLDER_M425
|
||||
encodeProtoFieldVarint(2, 1200), // inputTokens
|
||||
encodeProtoFieldVarint(3, 381), // outputTokens
|
||||
encodeProtoFieldVarint(5, 13800), // cacheReadTokens
|
||||
encodeProtoFieldVarint(6, 24), // API_PROVIDER_GOOGLE_GEMINI
|
||||
]);
|
||||
const stepMetaBuf = Buffer.concat([
|
||||
encodeProtoFieldBytes(1, encodeProtoFieldVarint(1, 1794762001)), // createdAt
|
||||
encodeProtoFieldBytes(6, encodeProtoFieldVarint(1, 1794762011)), // finishedGeneratingAt (+10.0s)
|
||||
encodeProtoFieldBytes(7, encodeProtoFieldVarint(1, 1794762011)), // completedAt
|
||||
encodeProtoFieldBytes(9, modelUsageBuf),
|
||||
encodeProtoFieldBytes(20, encodeProtoFieldVarint(2, 1)), // stepIndex = 1
|
||||
]);
|
||||
const chatModelBuf = Buffer.concat([
|
||||
encodeProtoFieldVarint(3, 1425),
|
||||
encodeProtoFieldBytes(4, modelUsageBuf),
|
||||
encodeProtoFieldBytes(
|
||||
11,
|
||||
Buffer.concat([encodeProtoFieldVarint(1, 1), encodeProtoFieldVarint(2, 800000000)]) // TTFT = 1.8s
|
||||
),
|
||||
encodeProtoFieldBytes(12, encodeProtoFieldVarint(1, 10)), // streamingDuration = 10s
|
||||
]);
|
||||
const genMetaBuf = Buffer.concat([
|
||||
encodeProtoFieldBytes(2, Buffer.from([1])),
|
||||
encodeProtoFieldBytes(1, chatModelBuf),
|
||||
]);
|
||||
|
||||
const convDb = new DatabaseSync(join(convDir, `${cid}.db`));
|
||||
convDb.exec(`
|
||||
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||
`);
|
||||
convDb.prepare('INSERT INTO steps (idx, step_type, status, metadata) VALUES (?, ?, ?, ?)').run(0, 14, 3, null);
|
||||
convDb.prepare('INSERT INTO steps (idx, step_type, status, metadata) VALUES (?, ?, ?, ?)').run(1, 15, 3, stepMetaBuf);
|
||||
convDb.prepare('INSERT INTO gen_metadata (idx, data) VALUES (?, ?)').run(0, genMetaBuf);
|
||||
convDb.close();
|
||||
|
||||
writeFileSync(
|
||||
join(dataDir, 'settings.json'),
|
||||
JSON.stringify({
|
||||
language: 'zh-CN',
|
||||
showTopbarMultiSession: true,
|
||||
enableCliStatusLine: true,
|
||||
topbarCapsuleSlots: ['ttft', 'tps', 'quota_auto', 'context'],
|
||||
}),
|
||||
'utf8'
|
||||
);
|
||||
writeFileSync(
|
||||
join(dataDir, 'cli-status-snapshot.json'),
|
||||
JSON.stringify({
|
||||
updatedAtMs: Date.now(),
|
||||
runningCount: 0,
|
||||
runningSubCount: 0,
|
||||
hasWaiting: false,
|
||||
quotas: {
|
||||
activePool: { poolLabel: 'Gemini', remainingPct: 57 },
|
||||
pools: [{ poolKey: 'Gemini', poolLabel: 'Gemini', remainingPct: 57 }],
|
||||
},
|
||||
}),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const stdinPayload = JSON.stringify({
|
||||
agent_state: 'idle',
|
||||
cwd: 'C:\\Work\\MyProject',
|
||||
context_window: { used_percentage: 17, total_input_tokens: 15000, total_output_tokens: 381 },
|
||||
cost: { total_usd: 0.012 },
|
||||
});
|
||||
|
||||
const capsuleOut = execFileSync(process.execPath, [statusLineScript], {
|
||||
env: { ...installEnv, NO_COLOR: '1' },
|
||||
input: stdinPayload,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
assert.equal(capsuleOut, '● 0 运行中 1.8s | 38.1 t/s | 余 57% | ◎ 17%');
|
||||
|
||||
// Full 3-column single-line E2E with terminal_width + cycle_mode + model + native stdin quota fallback
|
||||
const emptySnapDir = join(tempRoot, 'empty-data');
|
||||
mkdirSync(emptySnapDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(emptySnapDir, 'settings.json'),
|
||||
JSON.stringify({
|
||||
language: 'zh-CN',
|
||||
showTopbarMultiSession: true,
|
||||
enableCliStatusLine: true,
|
||||
topbarCapsuleSlots: ['ttft', 'tps', 'quota_auto', 'context'],
|
||||
}),
|
||||
'utf8'
|
||||
);
|
||||
const fullLineStdin = JSON.stringify({
|
||||
agent_state: 'running',
|
||||
cwd: 'C:\\Work\\MyProject',
|
||||
terminal_width: 130,
|
||||
cycle_mode: 'auto',
|
||||
model: {
|
||||
id: 'gemini-4-hydrogen-medium',
|
||||
display_name: 'Gemini 4 Hydrogen (Medium)',
|
||||
effort: 'medium',
|
||||
},
|
||||
quota: {
|
||||
Gemini: { remaining_fraction: 0.54 },
|
||||
},
|
||||
context_window: { used_percentage: 2, total_input_tokens: 15000, total_output_tokens: 381 },
|
||||
});
|
||||
const fullLineOut = execFileSync(process.execPath, [statusLineScript], {
|
||||
env: { ...installEnv, USAGE_MONITOR_DATA_DIR: emptySnapDir },
|
||||
input: fullLineStdin,
|
||||
encoding: 'utf8',
|
||||
}).replace(/\r?\n$/, '');
|
||||
assert.equal(/\x1b\[48;/.test(fullLineOut), false, 'E2E ANSI output has zero background fill');
|
||||
const plainFullLine = fullLineOut.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
assert.ok(plainFullLine.startsWith('? for shortcuts '));
|
||||
assert.ok(plainFullLine.includes('● 1 运行中 1.8s | 38.1 t/s | 余 54% | ◎ 2%'));
|
||||
assert.ok(plainFullLine.endsWith(' auto · Gemini 4 Hydrogen · medium'));
|
||||
assert.equal(h.cliDisplayWidth(fullLineOut), 129);
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
assert.equal(writtenSettings.statusLine.command.includes('"'), false);
|
||||
const cmdCapsuleOut = execFileSync('cmd.exe', ['/c', writtenSettings.statusLine.command], {
|
||||
env: { ...installEnv, NO_COLOR: '1' },
|
||||
input: stdinPayload,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
assert.equal(cmdCapsuleOut, '● 0 运行中 1.8s | 38.1 t/s | 余 57% | ◎ 17%');
|
||||
|
||||
const spaceDir = join(tempRoot, 'Dir With Spaces');
|
||||
mkdirSync(spaceDir, { recursive: true });
|
||||
const spaceCmd = h.buildCliStatusLineCommand(statusLineScript, {
|
||||
platform: 'win32',
|
||||
nodeOnPath: true,
|
||||
});
|
||||
assert.ok(spaceCmd);
|
||||
const encodedAutorunCmd = `node --input-type=module -e import('${new URL('../cli-statusline.mjs', import.meta.url).href}#autorun')`;
|
||||
const autorunOut = execFileSync('cmd.exe', ['/c', encodedAutorunCmd], {
|
||||
cwd: spaceDir,
|
||||
env: { ...installEnv, NO_COLOR: '1' },
|
||||
input: stdinPayload,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
assert.equal(autorunOut, '● 0 运行中 1.8s | 38.1 t/s | 余 57% | ◎ 17%');
|
||||
}
|
||||
|
||||
// Verify real non-test.invalid buildTelemetryPayload writes cli-status-snapshot.json cleanly without throwing
|
||||
const builderUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href;
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
'--input-type=module',
|
||||
'-e',
|
||||
`const { buildTelemetryPayload } = await import(${JSON.stringify(builderUrl)});
|
||||
const p = await buildTelemetryPayload(${JSON.stringify(cid)}, false, { range: 'all' });
|
||||
if (!p || !p.activeConversation) process.exit(2);`,
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...installEnv,
|
||||
ANTIGRAVITY_LS_ADDRESS: '127.0.0.1:1',
|
||||
ANTIGRAVITY_CSRF_TOKEN: 'live-check',
|
||||
},
|
||||
encoding: 'utf8',
|
||||
}
|
||||
);
|
||||
const liveWrittenSnap = JSON.parse(readFileSync(join(dataDir, 'cli-status-snapshot.json'), 'utf8'));
|
||||
assert.equal(liveWrittenSnap.activeConversation.cascadeId, cid);
|
||||
assert.equal(liveWrittenSnap.activeConversation.latestTokPerSec, 38.1);
|
||||
assert.ok(Number.isFinite(liveWrittenSnap.updatedAtMs) && liveWrittenSnap.updatedAtMs > 0);
|
||||
|
||||
// Verify uninstall removes managed statusLine while keeping other settings intact
|
||||
const uninstallOut = JSON.parse(
|
||||
execFileSync(process.execPath, [statusLineScript, '--uninstall'], {
|
||||
env: installEnv,
|
||||
encoding: 'utf8',
|
||||
}).trim()
|
||||
);
|
||||
assert.equal(uninstallOut.updated, true);
|
||||
const afterUninstall = JSON.parse(readFileSync(cliSettingsFile, 'utf8'));
|
||||
assert.equal(afterUninstall.selectedAuthType, 'oauth');
|
||||
assert.equal(afterUninstall.statusLine, undefined);
|
||||
} finally {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -475,9 +475,9 @@ test('Capsule 4-stage responsive hysteresis and backend settings default/overrid
|
||||
assert.equal(defaultPayload.settings.enableWindowOverlay, true);
|
||||
assert.equal(defaultPayload.settings.showTopbarMultiSession, true);
|
||||
assert.deepEqual(Array.from(defaultPayload.settings.topbarCapsuleSlots), [
|
||||
'context',
|
||||
'tps',
|
||||
'quota_auto',
|
||||
'ttft',
|
||||
'context',
|
||||
]);
|
||||
|
||||
const disabledEnv = backendHarness({
|
||||
@@ -784,13 +784,15 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: ['context', 'tps', 'quota_auto'],
|
||||
enableCliStatusLine: true,
|
||||
topbarCapsuleSlots: ['tps', 'ttft', 'context'],
|
||||
hoverModules: ['metrics', 'context', 'quotas'],
|
||||
overviewModules: ['metrics', 'context', 'quotas', 'live_tasks'],
|
||||
overviewMetrics: ['tps', 'ttft', 'avg_tps', 'step_cost'],
|
||||
stepTableColumns: ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost'],
|
||||
showStepTurnRail: true,
|
||||
showStepTurnRail: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepSpeedColor: false,
|
||||
showUpstreamModel: false,
|
||||
orchestratorIdMode: 'compact',
|
||||
weeklyLimitMode: 'official',
|
||||
@@ -1369,15 +1371,18 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const multiLabelEl = multiBtn.querySelector('.wm-multi-label');
|
||||
assert.equal(multiLabelEl.textContent, '2 运行 · 1 子');
|
||||
|
||||
// Verify capsule reactive text (50% context, 92.4 t/s without bolt SVG, 余 68%)
|
||||
// Verify capsule reactive text (default order: 92.4 t/s without bolt SVG, 0.85s TTFT, 50% context)
|
||||
const defaultCapSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot');
|
||||
const ctxPctEl = capsuleHost.shadowRoot.querySelector('.wm-ctx-pct');
|
||||
const speedSegEl = capsuleHost.shadowRoot.querySelector('.wm-seg-speed');
|
||||
const quotaSegEl = capsuleHost.shadowRoot.querySelector('.wm-seg-quota');
|
||||
assert.equal(ctxPctEl.textContent, '50%');
|
||||
assert.equal(defaultCapSlots[0].getAttribute('data-metric'), 'tps');
|
||||
assert.equal(defaultCapSlots[1].getAttribute('data-metric'), 'ttft');
|
||||
assert.equal(defaultCapSlots[2].getAttribute('data-metric'), 'context');
|
||||
assert.equal(speedSegEl.children.length, 1, 'Speed segment has no lightning bolt SVG');
|
||||
assert.equal(speedSegEl.querySelector('.svg-icon'), null);
|
||||
assert.ok(speedSegEl.children[0].textContent.includes('92.4 t/s'));
|
||||
assert.equal(quotaSegEl.children[0].textContent, '余 68%');
|
||||
assert.equal(defaultCapSlots[1].children[0].textContent, '0.85s');
|
||||
assert.equal(ctxPctEl.textContent, '50%');
|
||||
|
||||
// Verify hovering left multi-session button opens .wm-multi-panel with live tasks, subagents, and recent sessions
|
||||
const multiPanelEl = portalHost.shadowRoot.querySelector('.wm-multi-panel');
|
||||
@@ -1648,7 +1653,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const thirdNavBtns = thirdNavBar.querySelectorAll('.structure-thirdnav-btn');
|
||||
assert.deepEqual(
|
||||
thirdNavBtns.map((btn) => btn.querySelector('.structure-thirdnav-label').textContent),
|
||||
['挂载与胶囊', '鼠标悬浮窗', '实时监控布局', '调用明细字段'],
|
||||
['挂载胶囊', '鼠标悬浮窗', '实时监控布局', '调用明细字段'],
|
||||
'3rd-level menu renders 4 structure sub-tabs'
|
||||
);
|
||||
assert.equal(thirdNavBtns[0].classList.contains('is-active'), true, 'First 3rd-level tab active by default');
|
||||
@@ -1668,10 +1673,10 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const previewMultiBtn = sec0.querySelector('.wm-multi-btn');
|
||||
assert.ok(previewCapsuleBar, 'Pane 0 mounts real CapsuleBarWidget preview');
|
||||
assert.equal(previewCapsuleSlots.length, 5, 'Preview CapsuleBarWidget mounts real 5 capsule slots');
|
||||
assert.equal(previewCapsuleSlots[0].querySelector('.wm-ctx-pct').textContent, '56%', 'Preview renders simulated context %');
|
||||
assert.equal(previewCapsuleSlots[1].children[0].textContent, '68.4 t/s', 'Preview renders simulated speed');
|
||||
assert.equal(previewCapsuleSlots[1].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards');
|
||||
assert.equal(previewCapsuleSlots[2].children[0].textContent, '余 52%', 'Preview renders simulated quota_auto (min of 5h 64% and weekly 52%)');
|
||||
assert.equal(previewCapsuleSlots[0].children[0].textContent, '68.4 t/s', 'Preview slot 0 renders simulated speed');
|
||||
assert.equal(previewCapsuleSlots[0].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards');
|
||||
assert.equal(previewCapsuleSlots[1].children[0].textContent, '1.1s', 'Preview slot 1 renders simulated TTFT');
|
||||
assert.equal(previewCapsuleSlots[2].querySelector('.wm-ctx-pct').textContent, '56%', 'Preview slot 2 renders simulated context %');
|
||||
const mountSelectEl = sec0.querySelectorAll('.custom-select')[0];
|
||||
|
||||
// Toggle windowMountSelect: dual -> composer -> sidebar -> dual (updating both live host & preview bar)
|
||||
@@ -1703,9 +1708,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true');
|
||||
assert.equal(previewCapsuleBar.getAttribute('data-mount-mode'), 'dual');
|
||||
|
||||
// Toggle topbar multi-session switch: show -> hide -> show
|
||||
// Toggle topbar multi-session switch (show -> hide -> show) and CLI bottom capsule switch (on -> off -> on)
|
||||
const topbarSegBtns = sec0.querySelectorAll('.seg-btn');
|
||||
assert.equal(topbarSegBtns.length, 2, 'Topbar multi-session toggle has 显示 / 隐藏 buttons');
|
||||
assert.equal(topbarSegBtns.length, 4, 'Topbar multi-session + CLI bottom capsule toggles render 4 buttons');
|
||||
topbarSegBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showTopbarMultiSession, false);
|
||||
@@ -1718,6 +1723,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(multiBtn.hasAttribute('hidden'), false, 'Topbar multi-session button restored immediately');
|
||||
assert.equal(previewMultiBtn.hasAttribute('hidden'), false, 'Preview multi-session button restored immediately');
|
||||
|
||||
topbarSegBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.enableCliStatusLine, false, 'CLI bottom capsule toggle turns off enableCliStatusLine');
|
||||
topbarSegBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.enableCliStatusLine, true, 'CLI bottom capsule toggle restores enableCliStatusLine');
|
||||
|
||||
// Dynamic 1..5 capsule slots via EditableSlotList (+ / - / ↑ / ↓ & mouse drag-and-drop)
|
||||
const capSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot');
|
||||
const capSeps = capsuleHost.shadowRoot.querySelectorAll('.wm-sep');
|
||||
@@ -1730,19 +1742,14 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
let capRowSelects = capSlotWrap.querySelectorAll('.custom-select');
|
||||
assert.equal(capRowSelects.length, 3, 'Default 3 capsule slot rows in EditableSlotList');
|
||||
|
||||
// Slot 0 -> Gemini 5h (index 9), Slot 1 -> TTFT (index 2), Slot 2 -> Cost (index 4)
|
||||
// Slot 0 ('tps') -> Gemini 5h (index 9), Slot 1 stays TTFT, Slot 2 ('context') -> Cost (index 4)
|
||||
capRowSelects[0].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
capRowSelects[0].querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h');
|
||||
assert.equal(capSlots[0].children.length, 1, 'Ring SVG detached cleanly when slot leaves context');
|
||||
assert.equal(capSlots[0].children[0].textContent, '余 44%');
|
||||
assert.equal(previewCapsuleSlots[0].getAttribute('data-metric'), 'gemini_5h', 'Preview slot 0 mirrors gemini_5h');
|
||||
assert.equal(previewCapsuleSlots[0].children[0].textContent, '余 64%', 'Preview slot 0 renders simulated gemini_5h');
|
||||
|
||||
capRowSelects[1].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
capRowSelects[1].querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft');
|
||||
assert.equal(capSlots[1].children[0].textContent, '0.85s');
|
||||
|
||||
@@ -1750,6 +1757,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
capRowSelects[2].querySelectorAll('.select-option')[4].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[2].getAttribute('data-metric'), 'cost');
|
||||
assert.equal(capSlots[2].children.length, 1, 'Ring SVG detached cleanly when slot leaves context');
|
||||
assert.equal(capSlots[2].children[0].textContent, '$0.040');
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']);
|
||||
|
||||
@@ -1822,13 +1830,15 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(capSlotWrap.querySelector('.slot-remove-btn').hasAttribute('disabled'), true, '- button disabled at min 1 slot');
|
||||
assert.equal(capSeps[0].hasAttribute('hidden'), true, 'All separators hidden when 1 slot');
|
||||
|
||||
// Reset Section 0 restores default 3 slots ['context', 'tps', 'quota_auto']
|
||||
// Reset Section 0 restores default 3 slots ['tps', 'ttft', 'context']
|
||||
sec0.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['context', 'tps', 'quota_auto']);
|
||||
assert.equal(capSlots[0].getAttribute('data-metric'), 'context');
|
||||
assert.equal(capSlots[0].children.length, 2, 'Ring SVG re-attached on Slot 0');
|
||||
assert.equal(capSlots[0].querySelector('.wm-ctx-pct').textContent, '50%');
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['tps', 'ttft', 'context']);
|
||||
assert.equal(capSlots[0].getAttribute('data-metric'), 'tps');
|
||||
assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft');
|
||||
assert.equal(capSlots[2].getAttribute('data-metric'), 'context');
|
||||
assert.equal(capSlots[2].children.length, 2, 'Ring SVG re-attached on Slot 2');
|
||||
assert.equal(capSlots[2].querySelector('.wm-ctx-pct').textContent, '50%');
|
||||
|
||||
// Pane 1 (3rd-level tab 'hover'): Hover Popup Modules (0..4) + real hover UI preview
|
||||
const sec1 = accordionSections[1];
|
||||
@@ -1920,9 +1930,30 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(sec3.hasAttribute('hidden'), false);
|
||||
const previewStepTable = sec3.querySelector('.steps-data-table');
|
||||
assert.ok(previewStepTable, 'Real StepTableWidget mounted in Steps structure preview');
|
||||
assert.equal(previewStepTable.classList.contains('has-turn-rail'), true, 'Preview step table shows turn rail by default');
|
||||
assert.equal(previewStepTable.classList.contains('has-turn-rail'), false, 'Preview step table hides turn rail by default');
|
||||
assert.equal(previewStepTable.children[0].children[0].children.length, 7, 'Preview step table renders 7 default columns');
|
||||
assert.equal(previewStepTable.children[1].children.length, 4, 'Preview step table renders 4 simulated steps');
|
||||
|
||||
const sec3SettingLabels = sec3.querySelectorAll('.form-label').map((el) => el.textContent);
|
||||
assert.ok(sec3SettingLabels.includes('对话轮次导轨'), 'Turn rail switch rendered in 调用明细字段');
|
||||
assert.ok(sec3SettingLabels.includes('主/子代理标识'), 'Main/Sub agent badge switch rendered in 调用明细字段');
|
||||
assert.ok(sec3SettingLabels.includes('输出速度多色分级'), 'Speed multi-color switch rendered in 调用明细字段');
|
||||
const sec3SegControls = sec3.querySelectorAll('.segmented');
|
||||
assert.equal(sec3SegControls.length, 3, 'Three independent switches rendered in 调用明细字段');
|
||||
const getRowSpeedClasses = (tableEl) =>
|
||||
Array.from(tableEl.children[1].children).map(
|
||||
(tr) => tr.children[2].querySelector('.cell-value')?.getAttribute('class') || ''
|
||||
);
|
||||
assert.equal(
|
||||
getRowSpeedClasses(previewStepTable).every((cls) => cls === 'cell-value'),
|
||||
true,
|
||||
'Preview step table renders monochrome speed cells by default'
|
||||
);
|
||||
// Toggle ON 对话轮次导轨 & 输出速度多色分级, and toggle OFF 主/子代理标识
|
||||
sec3SegControls[0].querySelectorAll('.seg-btn')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.equal(mockSettings.showStepTurnRail, true, 'Turn rail switch updates showStepTurnRail to true');
|
||||
assert.equal(previewStepTable.classList.contains('has-turn-rail'), true, 'Preview step table activates turn rail immediately');
|
||||
const previewFirstTd = previewStepTable.children[1].children[0].children[0];
|
||||
previewFirstTd.onmouseenter?.({ target: previewFirstTd });
|
||||
const previewTurnTip = sec3.querySelector('.turn-prompt-tip');
|
||||
@@ -1930,16 +1961,6 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.ok(previewTurnTip.textContent.includes('并发刷新令牌'), 'Preview turn tooltip displays realistic engineering prompt');
|
||||
previewFirstTd.onmouseleave?.();
|
||||
|
||||
const sec3SettingLabels = sec3.querySelectorAll('.form-label').map((el) => el.textContent);
|
||||
assert.ok(sec3SettingLabels.includes('对话轮次导轨'), 'Turn rail switch rendered in 调用明细字段');
|
||||
assert.ok(sec3SettingLabels.includes('主/子代理标识'), 'Main/Sub agent badge switch rendered in 调用明细字段');
|
||||
const sec3SegControls = sec3.querySelectorAll('.segmented');
|
||||
assert.equal(sec3SegControls.length, 2, 'Two independent switches rendered in 调用明细字段');
|
||||
// Toggle off 对话轮次导轨 and 主/子代理标识
|
||||
sec3SegControls[0].querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.equal(mockSettings.showStepTurnRail, false, 'Turn rail switch updates showStepTurnRail to false');
|
||||
assert.equal(previewStepTable.classList.contains('has-turn-rail'), false, 'Preview step table removes turn rail immediately');
|
||||
sec3SegControls[1].querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.equal(mockSettings.showStepAgentBadge, false, 'Agent badge switch updates showStepAgentBadge to false');
|
||||
@@ -1948,6 +1969,14 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
true,
|
||||
'Preview step table hides Main/Sub agent badge immediately'
|
||||
);
|
||||
sec3SegControls[2].querySelectorAll('.seg-btn')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.equal(mockSettings.showStepSpeedColor, true, 'Speed multi-color switch updates showStepSpeedColor to true');
|
||||
assert.equal(
|
||||
getRowSpeedClasses(previewStepTable).some((cls) => /tone-(good|info|warn|danger)/.test(cls)),
|
||||
true,
|
||||
'Preview step table enables multi-color speed tones immediately when showStepSpeedColor is true'
|
||||
);
|
||||
|
||||
const stepColWrap = sec3.querySelector('.editable-slot-wrap');
|
||||
stepColWrap.querySelector('.slot-add-btn').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
@@ -1958,27 +1987,37 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(previewStepTable.children[0].children[0].children.length, 9, 'Preview step table expands to 9 columns live');
|
||||
pillTabs[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
const stepTableWhileRailOff = allPanes[2].querySelector('.data-table');
|
||||
const stepTableWhileCustomOn = allPanes[2].querySelector('.data-table');
|
||||
assert.equal(
|
||||
stepTableWhileRailOff.classList.contains('has-turn-rail'),
|
||||
false,
|
||||
'has-turn-rail class removed when showStepTurnRail is false'
|
||||
);
|
||||
assert.equal(
|
||||
Array.from(stepTableWhileRailOff.querySelectorAll('.turn-rail'))
|
||||
.every((rail) => rail.hasAttribute('hidden')),
|
||||
stepTableWhileCustomOn.classList.contains('has-turn-rail'),
|
||||
true,
|
||||
'No visible turn rail when showStepTurnRail is false'
|
||||
'has-turn-rail class applied when showStepTurnRail is true'
|
||||
);
|
||||
const stepHeaderThs = stepTableWhileRailOff.children[0].children[0].children;
|
||||
assert.equal(
|
||||
Array.from(stepTableWhileCustomOn.children[1].children).some((tr) =>
|
||||
/tone-(good|info|warn|danger)/.test(
|
||||
tr.children[2].querySelector('.cell-value')?.getAttribute('class') || ''
|
||||
)
|
||||
),
|
||||
true,
|
||||
'StepsDetailView applies multi-color speed classes when showStepSpeedColor is true'
|
||||
);
|
||||
const stepHeaderThs = stepTableWhileCustomOn.children[0].children[0].children;
|
||||
assert.equal(stepHeaderThs.length, 9, 'StepsDetailView thead dynamically renders 9 columns');
|
||||
pillTabs[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
sec3.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
assert.equal(mockSettings.stepTableColumns.length, 7);
|
||||
assert.equal(mockSettings.showStepTurnRail, true, 'Section reset restores showStepTurnRail to true');
|
||||
assert.equal(mockSettings.showStepTurnRail, false, 'Section reset restores showStepTurnRail to false');
|
||||
assert.equal(mockSettings.showStepAgentBadge, true, 'Section reset restores showStepAgentBadge to true');
|
||||
assert.equal(mockSettings.showStepSpeedColor, false, 'Section reset restores showStepSpeedColor to false');
|
||||
assert.equal(previewStepTable.classList.contains('has-turn-rail'), false, 'Section reset hides turn rail in preview step table');
|
||||
assert.equal(
|
||||
getRowSpeedClasses(previewStepTable).every((cls) => cls === 'cell-value'),
|
||||
true,
|
||||
'Section reset restores monochrome speed classes in preview step table'
|
||||
);
|
||||
|
||||
// --- 其他 (model format, context limits, cache rebuild, reset) ---
|
||||
subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
@@ -2145,8 +2184,24 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(stepRows[0].children[4].getAttribute('title'), '上下文 37800 · 思考 420 · 正文 265');
|
||||
assert.equal(stepRows[1].children[4].children[0].textContent, '117.7k / 14.5k / 57');
|
||||
|
||||
// Verify minimalist Turn Rail (.has-turn-rail, cap & origin dots) and hover prompt preview tooltip
|
||||
// Verify minimalist Turn Rail (.has-turn-rail, cap & origin dots) is off by default and activates cleanly when enabled
|
||||
const stepsDataTable = stepsPane.querySelectorAll('.data-table')[0];
|
||||
assert.equal(stepsDataTable.classList.contains('has-turn-rail'), false, 'Turn rail off by default after full reset');
|
||||
assert.equal(
|
||||
Array.from(stepRows).every(
|
||||
(tr) => tr.children[2].querySelector('.cell-value')?.getAttribute('class') === 'cell-value'
|
||||
),
|
||||
true,
|
||||
'Speed column monochrome by default after full reset'
|
||||
);
|
||||
pillTabs[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
subNavBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
thirdNavBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
sec3SegControls[0].querySelectorAll('.seg-btn')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
pillTabs[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
assert.equal(stepsDataTable.classList.contains('has-turn-rail'), true, 'Turn rail active when showStepTurnRail=true');
|
||||
const row0Rail = stepRows[0].children[0].querySelector('.turn-rail');
|
||||
const row1Rail = stepRows[1].children[0].querySelector('.turn-rail');
|
||||
@@ -2583,10 +2638,14 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
]);
|
||||
assert.equal(delivered, 1);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
assert.equal(ctxPctEl.textContent, '25%', 'CDP relay delivered live telemetry without HTTP');
|
||||
assert.equal(speedSegEl.children[0].textContent, '121 t/s');
|
||||
assert.equal(quotaSegEl.hasAttribute('hidden'), false, 'Quota slot stays pre-reserved even when quotas=null');
|
||||
assert.equal(quotaSegEl.children[0].textContent, '余 --%');
|
||||
assert.equal(
|
||||
defaultCapSlots[2].querySelector('.wm-ctx-pct').textContent,
|
||||
'25%',
|
||||
'CDP relay delivered live telemetry without HTTP'
|
||||
);
|
||||
assert.equal(defaultCapSlots[0].children[0].textContent, '121 t/s');
|
||||
assert.equal(defaultCapSlots[1].hasAttribute('hidden'), false, 'TTFT slot stays pre-reserved even when latestTtftSec is absent');
|
||||
assert.equal(defaultCapSlots[1].children[0].textContent, '--s');
|
||||
assert.equal(
|
||||
hoverLegendGrid.children[0],
|
||||
firstLegendSlotBefore,
|
||||
|
||||
Reference in New Issue
Block a user