From 3eb9e0e2a5556313b914d8073ea8779223a6d71f Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sat, 21 Nov 2026 21:03:01 +0900 Subject: [PATCH] feat(cli): upgrade statusLine with Braille progress bars, instant waiting sync, /statusline flags, and CLI-gated settings --- sidecars/panel/app.js | 456 ++++++++++++++++- sidecars/panel/backend/api-actions.mjs | 51 +- .../panel/backend/cli-statusline-config.mjs | 470 +++++++++++++++--- sidecars/panel/backend/config.mjs | 6 + sidecars/panel/backend/settings-schema.mjs | 14 + sidecars/panel/backend/telemetry-builder.mjs | 35 +- sidecars/panel/cli-statusline.mjs | 373 +++++++++++++- sidecars/panel/index.html | 4 +- .../panel/shared/settings-normalization.mjs | 78 +++ sidecars/panel/src/core/settingsBackup.js | 5 + sidecars/panel/src/i18n/en-US.js | 10 + sidecars/panel/src/i18n/zh-CN.js | 10 + sidecars/panel/src/store/telemetryStore.js | 40 ++ sidecars/panel/src/styles/views-settings.css | 177 +++++++ sidecars/panel/src/views/SettingsView.js | 4 +- .../views/settings/SettingsStructureTab.js | 309 +++++++++++- sidecars/panel/styles.css | 177 +++++++ sidecars/panel/test/backend-harness.mjs | 2 +- sidecars/panel/test/backend.test.mjs | 425 +++++++++++++++- sidecars/panel/test/window-bridge.test.mjs | 155 ++++++ 20 files changed, 2690 insertions(+), 111 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 9d1e6b6..b9f63a7 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2,7 +2,7 @@ 'use strict'; // --- shared/settings-normalization.mjs --- -const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi } = (() => { +const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -41,6 +41,21 @@ const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); const MIN_TOPBAR_SLOTS = 1; const MAX_TOPBAR_SLOTS = 5; +const DEFAULT_CLI_STATUSLINE_SLOTS = Object.freeze([ + 'tps', + 'ttft', + 'session_cost', + 'quota_auto', + 'context', +]); +const MIN_CLI_STATUSLINE_SLOTS = 1; +const MAX_CLI_STATUSLINE_SLOTS = 6; +const CLI_STATUSLINE_PRESETS = Object.freeze({ + compact: Object.freeze(['tps', 'ttft', 'context']), + balanced: DEFAULT_CLI_STATUSLINE_SLOTS, + full: Object.freeze(['tps', 'ttft', 'cache_hit', 'session_cost', 'quota_auto', 'context']), +}); + const OVERVIEW_MODULE_KEYS = Object.freeze([ 'metrics', 'context', @@ -341,6 +356,69 @@ function normalizeTopbarCapsuleSlots(raw) { return out; } +/** + * 归一化 CLI 底部状态栏独立槽位配置(`null` 表示自动跟随宽屏默认或自定义顶栏槽位; + * 支持预设名 `compact` / `balanced` / `full`、逗号分隔列表或数组,保留 1~6 个去重合法槽位)。 + * + * @param {unknown} raw + * @returns {string[]|null} + */ +function normalizeCliStatusLineSlots(raw) { + if (raw === undefined || raw === null) return null; + let items = null; + if (typeof raw === 'string') { + const clean = raw.trim(); + const lower = clean.toLowerCase(); + if (!clean || lower === 'auto' || lower === 'default') { + return null; + } + if (Object.prototype.hasOwnProperty.call(CLI_STATUSLINE_PRESETS, lower)) { + return [...CLI_STATUSLINE_PRESETS[lower]]; + } + items = clean.split(/[\s,|:]+/); + } else if (Array.isArray(raw)) { + items = raw; + } else { + return null; + } + const seen = new Set(); + const out = []; + for (const item of items) { + const val = String(item ?? '').trim(); + if (!val || val === 'none') continue; + const mapped = val === 'step_cost' ? 'cost' : val; + if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue; + seen.add(mapped); + out.push(mapped); + if (out.length >= MAX_CLI_STATUSLINE_SLOTS) break; + } + return out.length >= MIN_CLI_STATUSLINE_SLOTS ? out : null; +} + +/** + * 解析当前生效的 CLI 底栏槽位列表: + * 1. 若用户显式设置了 `cliStatusLineSlots`,优先使用; + * 2. 若用户自定义了非默认 `topbarCapsuleSlots`,沿用其自定义顺序保持兼容; + * 3. 否则采用面向宽终端的 5 槽默认组合(速度 / 首字 / 费用 / 配额 / 上下文)。 + * + * @param {object|null|undefined} settings + * @returns {string[]} + */ +function resolveEffectiveCliStatusLineSlots(settings) { + const customCli = normalizeCliStatusLineSlots(settings?.cliStatusLineSlots); + if (customCli && customCli.length > 0) { + return customCli; + } + const topbar = normalizeTopbarCapsuleSlots(settings?.topbarCapsuleSlots); + const isDefaultTopbar = + topbar.length === DEFAULT_TOPBAR_SLOTS.length && + topbar.every((k, i) => k === DEFAULT_TOPBAR_SLOTS[i]); + if (!isDefaultTopbar) { + return topbar; + } + return [...DEFAULT_CLI_STATUSLINE_SLOTS]; +} + /** * 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。 * @@ -482,7 +560,7 @@ function normalizeExperimentalModernUi(val) { } return Boolean(val); } -return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi }; +return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, DEFAULT_CLI_STATUSLINE_SLOTS, MIN_CLI_STATUSLINE_SLOTS, MAX_CLI_STATUSLINE_SLOTS, CLI_STATUSLINE_PRESETS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeCliStatusLineSlots, resolveEffectiveCliStatusLineSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort, normalizeModernUi, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- @@ -1631,6 +1709,16 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px', 'settings.str.multiToggle': '实时运行会话入口', 'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊', + 'settings.str.cliSlotsLabel': 'CLI 槽位顺序 (左 → 右,1~6 项,可拖拽)', + 'settings.str.addCliSlot': '添加 CLI 槽位 ({count}/{max})', + 'settings.str.cliCustomCmdHint': '检测到自定义 statusLine 命令,为避免误覆盖默认不会自动改写', + 'settings.str.cliPausedHint': 'CLI 端当前已暂停或未写入 statusLine 配置', + 'settings.str.cliFlagsOverrideHint': '检测到 CLI 启动参数包含显式槽位覆盖,命令行参数将优先于此处配置', + 'settings.str.cliRestoreBtn': '一键接管并恢复', + 'settings.str.cliEnableBtn': '重新写入并启用', + 'settings.str.cliClearFlagsBtn': '清除命令行覆盖', + 'settings.str.cliRestoringBtn': '正在写入...', + 'settings.str.cliPreviewRunning': '{count} 运行中', 'settings.str.show': '显示', 'settings.str.hide': '隐藏', 'settings.str.on': '开启', @@ -2383,6 +2471,16 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.str.popoverWidthHint': 'Auto Fit widens wide tables like Step Records to avoid horizontal scroll; Custom accepts 440–1080 px', 'settings.str.multiToggle': 'Active Sessions Pill', 'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule', + 'settings.str.cliSlotsLabel': 'CLI Slot Order (Left → Right, 1–6, draggable)', + 'settings.str.addCliSlot': 'Add CLI Slot ({count}/{max})', + 'settings.str.cliCustomCmdHint': 'Custom statusLine command detected; preserved automatically unless you take over', + 'settings.str.cliPausedHint': 'CLI statusLine is currently paused or not yet configured', + 'settings.str.cliFlagsOverrideHint': 'Explicit CLI launch flags (--slots / --preset) detected and take precedence over these slots', + 'settings.str.cliRestoreBtn': 'Take Over & Restore', + 'settings.str.cliEnableBtn': 'Re-enable in CLI', + 'settings.str.cliClearFlagsBtn': 'Clear Flag Override', + 'settings.str.cliRestoringBtn': 'Applying...', + 'settings.str.cliPreviewRunning': '{count} active', 'settings.str.show': 'Show', 'settings.str.hide': 'Hide', 'settings.str.on': 'On', @@ -4972,6 +5070,7 @@ function buildExportableSettingsJson(settings = {}) { popoverWidthMode: normalizePopoverWidthMode(src.popoverWidthMode), popoverWidth: normalizePopoverWidth(src.popoverWidth), enableCliStatusLine: src.enableCliStatusLine !== false, + cliStatusLineSlots: normalizeCliStatusLineSlots(src.cliStatusLineSlots), standalonePort: normalizeStandalonePort(src.standalonePort), showTopbarMultiSession: src.showTopbarMultiSession !== false, topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots), @@ -5063,6 +5162,9 @@ function parseImportedSettingsJson(rawText) { if (hasKey('enableCliStatusLine') && typeof src.enableCliStatusLine === 'boolean') { patch.enableCliStatusLine = src.enableCliStatusLine; } + if (hasKey('cliStatusLineSlots')) { + patch.cliStatusLineSlots = normalizeCliStatusLineSlots(src.cliStatusLineSlots); + } if (hasKey('standalonePort')) { patch.standalonePort = normalizeStandalonePort(src.standalonePort); } @@ -5425,7 +5527,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView }; })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -5809,6 +5911,8 @@ function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) { const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS; const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS; +const CLIENT_CLI_STATUSLINE_PRESETS = CLI_STATUSLINE_PRESETS; +const DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS = DEFAULT_CLI_STATUSLINE_SLOTS; const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS; const DEFAULT_CLIENT_OVERVIEW_MODULES = DEFAULT_OVERVIEW_MODULES; const DEFAULT_CLIENT_HOVER_MODULES = DEFAULT_HOVER_MODULES; @@ -5827,6 +5931,8 @@ const normalizeClientPopoverWidthMode = normalizePopoverWidthMode; const normalizeClientPopoverWidth = normalizePopoverWidth; const normalizeClientModelDisplayMode = normalizeModelDisplayMode; const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; +const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots; +const resolveEffectiveClientCliStatusLineSlots = resolveEffectiveCliStatusLineSlots; const normalizeClientHoverModules = normalizeHoverModules; const normalizeClientOverviewModules = normalizeOverviewModules; const normalizeClientOverviewMetrics = normalizeOverviewMetrics; @@ -5915,6 +6021,7 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.enableCliStatusLine !== false) !== (nSet?.enableCliStatusLine !== false)) { return false; } + if (!sameArr(pSet?.cliStatusLineSlots, nSet?.cliStatusLineSlots)) return false; if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) { return false; } @@ -5946,6 +6053,16 @@ function isEquivalentTelemetry(prev, next) { ) { return false; } + const pCli = prev.cliStatusLine; + const nCli = next.cliStatusLine; + if ( + Boolean(pCli?.installed) !== Boolean(nCli?.installed) || + Boolean(pCli?.configured) !== Boolean(nCli?.configured) || + Boolean(pCli?.preservedCustom) !== Boolean(nCli?.preservedCustom) || + String(pCli?.managedFlags || '') !== String(nCli?.managedFlags || '') + ) { + return false; + } const pCloud = prev.cloudStatus; const nCloud = next.cloudStatus; if ( @@ -7083,6 +7200,9 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'cliStatusLineSlots')) { + safePatch.cliStatusLineSlots = normalizeClientCliStatusLineSlots(safePatch.cliStatusLineSlots); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'hoverModules')) { safePatch.hoverModules = normalizeClientHoverModules(safePatch.hoverModules); } @@ -7328,6 +7448,24 @@ async function triggerBridgeHostRelaunch() { } } +async function triggerCliStatusLineAction(action) { + const res = await callSidecarApi('/api/settings', { + method: 'POST', + body: { __cliStatusLineAction: String(action || 'force_install') }, + }); + const cur = telemetryStore.getState().telemetry; + if (cur && res && typeof res === 'object') { + const nextTelemetry = { + ...cur, + ...(res.cliStatusLine ? { cliStatusLine: res.cliStatusLine } : {}), + ...(res.settings ? { settings: { ...cur.settings, ...res.settings } } : {}), + }; + telemetryStore.setState({ telemetry: nextTelemetry }); + } + void fetchTelemetry({ force: true }).catch(() => {}); + return res; +} + async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { @@ -7585,7 +7723,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -20825,6 +20963,91 @@ function isSameList(a, b) { return true; } +function buildCliPreviewMiniBar(pct, width = 8, emptyChar = '⢕') { + const clamped = Math.max(0, Math.min(100, Number(pct))); + let filled = Math.round((clamped / 100) * width); + if (clamped > 0 && filled === 0) filled = 1; + if (clamped < 95 && filled >= width) filled = Math.max(0, width - 1); + return { + barFilled: '█'.repeat(filled), + barEmpty: emptyChar.repeat(Math.max(0, width - filled)), + }; +} + +function formatCliPreviewSlot(slotKey, isEn) { + switch (slotKey) { + case 'tps': + return { prefix: '', barFilled: '', barEmpty: '', text: '68.4 t/s', tone: 'good' }; + case 'avg_tps': + return { + prefix: '', + barFilled: '', + barEmpty: '', + text: isEn ? 'avg 54.0' : '均 54.0', + tone: 'info', + }; + case 'ttft': + return { prefix: '', barFilled: '', barEmpty: '', text: '1.1s', tone: 'good' }; + case 'cost': + return { prefix: '', barFilled: '', barEmpty: '', text: '$0.040', tone: 'normal' }; + case 'session_cost': + return { prefix: '', barFilled: '', barEmpty: '', text: '$0.42', tone: 'normal' }; + case 'cache_hit': + return { + prefix: '', + barFilled: '', + barEmpty: '', + text: isEn ? 'cache 92%' : '缓 92%', + tone: 'good', + }; + case 'session_tokens': + return { prefix: '', barFilled: '', barEmpty: '', text: '142K tok', tone: 'muted' }; + case 'quota_auto': + return { + prefix: isEn ? '5h ' : '余 ', + ...buildCliPreviewMiniBar(64, 8, '⣿'), + text: ' 64%', + tone: 'good', + }; + case 'gemini_5h': + return { + prefix: 'G5h ', + ...buildCliPreviewMiniBar(64, 8, '⣿'), + text: ' 64%', + tone: 'good', + }; + case 'gemini_weekly': + return { + prefix: isEn ? 'Gw ' : 'G周 ', + ...buildCliPreviewMiniBar(88, 8, '⣿'), + text: ' 88%', + tone: 'good', + }; + case 'claude_5h': + return { + prefix: 'C5h ', + ...buildCliPreviewMiniBar(96, 8, '⣿'), + text: ' 96%', + tone: 'good', + }; + case 'claude_weekly': + return { + prefix: isEn ? 'Cw ' : 'C周 ', + ...buildCliPreviewMiniBar(99, 8, '⣿'), + text: ' 99%', + tone: 'good', + }; + case 'context': + default: + return { + prefix: isEn ? 'Ctx ' : '上下文 ', + ...buildCliPreviewMiniBar(56), + text: ' 56%', + tone: 'accent', + }; + } +} + const SettingsStructureTab = defineComponent({ name: 'SettingsStructureTab', setup({ props, onCleanup }) { @@ -20833,6 +21056,7 @@ const SettingsStructureTab = defineComponent({ let draftPopoverWidthMode = 'auto'; let draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH; let draftEnableCliStatusLine = true; + let draftCliStatusLineSlots = null; let draftShowTopbarMulti = true; let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES]; @@ -20846,8 +21070,16 @@ const SettingsStructureTab = defineComponent({ let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS]; let latestSettings = null; let latestWindowBridge = null; + let latestCliStatusLine = null; let latestHostPlatform = 'win32'; + function getEffectiveDraftCliSlots() { + return resolveEffectiveClientCliStatusLineSlots({ + cliStatusLineSlots: draftCliStatusLineSlots, + topbarCapsuleSlots: draftTopbarSlots, + }); + } + function isStructureVisible() { const st = uiStore.getState(); return getVisibleMonitorView(st) === 'settings' && st.settingsSubTab === 'structure'; @@ -20979,6 +21211,50 @@ const SettingsStructureTab = defineComponent({ className: 'form-label', text: t('settings.str.cliCapsuleToggle'), }); + const cliSlotsLabelEl = h('span', { + className: 'form-label', + text: t('settings.str.cliSlotsLabel'), + }); + const cliStatusHintEl = h('span', { + className: 'settings-hint-text cli-status-hint', + }); + let cliActionBusy = false; + let activeCliStatusAction = ''; + const cliStatusActionBtn = h('button', { + type: 'button', + className: 'cli-status-action-btn', + hidden: true, + text: t('settings.str.cliRestoreBtn'), + onClick: async () => { + if (cliActionBusy || !activeCliStatusAction) return; + cliActionBusy = true; + const actionToRun = activeCliStatusAction; + patchAttr(cliStatusActionBtn, 'disabled', true); + patchText(cliStatusActionBtn, t('settings.str.cliRestoringBtn')); + mountSection.refs.showStatus(t('settings.saving'), 0); + try { + const res = await triggerCliStatusLineAction(actionToRun); + if (res?.cliStatusLine) { + latestCliStatusLine = res.cliStatusLine; + } + if (res?.settings && typeof res.settings === 'object') { + latestSettings = { ...(latestSettings || {}), ...res.settings }; + draftEnableCliStatusLine = latestSettings.enableCliStatusLine !== false; + } + mountSection.refs.showStatus( + res?.ok === false ? t('settings.saveFailed') : t('settings.saved'), + 1800 + ); + } catch { + mountSection.refs.showStatus(t('settings.saveFailed'), 2500); + } finally { + cliActionBusy = false; + patchAttr(cliStatusActionBtn, 'disabled', false); + syncMountSectionMeta(); + props.onLayoutChange?.(); + } + }, + }); const capsuleSlotsLabelEl = h('span', { className: 'form-label', text: t('settings.str.capsuleSlotsLabel'), @@ -21059,12 +21335,85 @@ const SettingsStructureTab = defineComponent({ onUpdateModelValue: (val) => { draftEnableCliStatusLine = val !== 'off'; syncMountSectionMeta(); + props.onLayoutChange?.(); void persistStructurePatch(mountSection, { enableCliStatusLine: draftEnableCliStatusLine, }); }, }); + const cliPreviewMultiTextEl = h('span', { + text: t('settings.str.cliPreviewRunning', { count: 2 }), + }); + const cliPreviewMultiEl = h('span', { className: 'cli-preview-multi' }, [ + h('span', { className: 'cli-preview-dot', 'aria-hidden': 'true', text: '●' }), + cliPreviewMultiTextEl, + ]); + const cliPreviewSlotParts = []; + const cliPreviewSepEls = []; + const cliPreviewChildren = [cliPreviewMultiEl]; + for (let i = 0; i < 6; i += 1) { + if (i > 0) { + const sepEl = h('span', { + className: 'cli-preview-sep', + 'aria-hidden': 'true', + text: '|', + }); + cliPreviewSepEls.push(sepEl); + cliPreviewChildren.push(sepEl); + } + const prefixEl = h('span', { className: 'cli-preview-prefix' }); + const barFillEl = h('span', { className: 'cli-preview-bar-fill' }); + const barEmptyEl = h('span', { className: 'cli-preview-bar-empty' }); + const valueEl = h('span', { className: 'cli-preview-val' }); + const slotEl = h('span', { className: 'cli-preview-slot' }, [ + prefixEl, + barFillEl, + barEmptyEl, + valueEl, + ]); + cliPreviewSlotParts.push({ slotEl, prefixEl, barFillEl, barEmptyEl, valueEl }); + cliPreviewChildren.push(slotEl); + } + const cliPreviewEl = h('div', { className: 'cli-status-preview' }, cliPreviewChildren); + + const cliSlotsList = EditableSlotList({ + items: getEffectiveDraftCliSlots(), + options: getCapsuleMetricOptions(), + minItems: 1, + maxItems: 6, + addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), + onPreview: (previewItems) => { + draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(previewItems); + refreshCliPreview(); + }, + onChange: (nextItems) => { + draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(nextItems); + syncMountSectionMeta(); + props.onLayoutChange?.(); + void persistStructurePatch(mountSection, { + cliStatusLineSlots: draftCliStatusLineSlots, + }); + }, + }); + + const cliStatusFooterEl = h('div', { className: 'cli-status-footer', hidden: true }, [ + cliStatusHintEl, + cliStatusActionBtn, + ]); + + const cliStatusDetailEl = h('div', { className: 'cli-statusline-detail' }, [ + cliPreviewEl, + h('div', { className: 'form-row' }, [cliSlotsLabelEl, cliSlotsList.el]), + cliStatusFooterEl, + ]); + + const cliStatusGroupEl = h('div', { className: 'cli-statusline-group', hidden: true }, [ + h('div', { className: 'settings-divider' }), + h('div', { className: 'settings-inline-row' }, [cliCapsuleLabelEl, cliCapsuleToggle.el]), + cliStatusDetailEl, + ]); + const topbarSlotsList = EditableSlotList({ items: draftTopbarSlots, options: getCapsuleMetricOptions(), @@ -21098,6 +21447,7 @@ const SettingsStructureTab = defineComponent({ draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH; popoverWidthStepper.setProps({ modelValue: DEFAULT_CLIENT_POPOVER_WIDTH }); draftEnableCliStatusLine = true; + draftCliStatusLineSlots = null; draftShowTopbarMulti = true; draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; syncMountSectionMeta(); @@ -21110,6 +21460,7 @@ const SettingsStructureTab = defineComponent({ popoverWidthMode: 'auto', popoverWidth: DEFAULT_CLIENT_POPOVER_WIDTH, enableCliStatusLine: true, + cliStatusLineSlots: null, showTopbarMultiSession: true, topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS], }, @@ -21135,17 +21486,44 @@ const SettingsStructureTab = defineComponent({ multiToggleLabelEl, multiSessionToggle.el, ]), - h('div', { className: 'settings-inline-row' }, [ - cliCapsuleLabelEl, - cliCapsuleToggle.el, - ]), h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]), + cliStatusGroupEl, ], }); + function refreshCliPreview() { + const effectiveSlots = getEffectiveDraftCliSlots(); + const isEn = getEffectiveLocale() === 'en-US'; + patchAttr(cliPreviewMultiEl, 'hidden', !draftShowTopbarMulti); + patchText(cliPreviewMultiTextEl, t('settings.str.cliPreviewRunning', { count: 2 })); + for (let i = 0; i < cliPreviewSlotParts.length; i += 1) { + const parts = cliPreviewSlotParts[i]; + const sepEl = i > 0 ? cliPreviewSepEls[i - 1] : null; + const key = effectiveSlots[i]; + const visible = Boolean(key); + patchAttr(parts.slotEl, 'hidden', !visible); + if (sepEl) patchAttr(sepEl, 'hidden', !visible); + if (visible) { + const item = formatCliPreviewSlot(key, isEn); + patchAttr(parts.slotEl, 'data-metric', key); + patchText(parts.prefixEl, item.prefix || ''); + patchText(parts.barFillEl, item.barFilled || ''); + patchText(parts.barEmptyEl, item.barEmpty || ''); + patchText(parts.valueEl, item.text || ''); + patchClasses(parts.slotEl, { + 'tone-good': item.tone === 'good', + 'tone-info': item.tone === 'info', + 'tone-accent': item.tone === 'accent', + 'tone-muted': item.tone === 'muted', + }); + } + } + } + function refreshMountPreview() { if (!isStructureVisible() || activeThirdTab !== 'mount') return; capsulePreviewWidget.refs.update({ data: buildDraftTelemetry() }); + refreshCliPreview(); } function syncMountSectionMeta() { @@ -21173,10 +21551,53 @@ const SettingsStructureTab = defineComponent({ modelValue: draftShowTopbarMulti ? 'show' : 'hide', options: getMultiToggleOptions(), }); + const cliInstalled = Boolean(latestCliStatusLine?.installed); + patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled); cliCapsuleToggle.setProps({ modelValue: draftEnableCliStatusLine ? 'on' : 'off', options: getEnableToggleOptions(), }); + patchAttr(cliStatusDetailEl, 'hidden', !draftEnableCliStatusLine); + const effectiveCliSlots = getEffectiveDraftCliSlots(); + cliSlotsList.refs.setProps({ + items: effectiveCliSlots, + options: getCapsuleMetricOptions(), + addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), + }); + const preservedCustom = Boolean(latestCliStatusLine?.preservedCustom); + const isConfigured = Boolean(latestCliStatusLine?.configured); + const hasInlineSlotFlags = /(?:^|\s)--(?:slots|preset)(?:=|\s|$)/i.test( + String(latestCliStatusLine?.managedFlags || '') + ); + const isPausedInCli = cliInstalled && !preservedCustom && !isConfigured && draftEnableCliStatusLine; + const cliHintText = preservedCustom + ? t('settings.str.cliCustomCmdHint') + : isPausedInCli + ? t('settings.str.cliPausedHint') + : hasInlineSlotFlags + ? t('settings.str.cliFlagsOverrideHint') + : ''; + patchAttr(cliStatusFooterEl, 'hidden', !cliHintText); + patchClasses(cliStatusHintEl, { 'is-warn': preservedCustom || isPausedInCli }); + patchText(cliStatusHintEl, cliHintText); + activeCliStatusAction = preservedCustom || isPausedInCli + ? 'force_install' + : hasInlineSlotFlags + ? 'clear_flags' + : ''; + patchAttr(cliStatusActionBtn, 'hidden', !activeCliStatusAction); + patchClasses(cliStatusActionBtn, { 'is-warn': preservedCustom }); + if (!cliActionBusy && activeCliStatusAction) { + patchText( + cliStatusActionBtn, + preservedCustom + ? t('settings.str.cliRestoreBtn') + : isPausedInCli + ? t('settings.str.cliEnableBtn') + : t('settings.str.cliClearFlagsBtn') + ); + } + refreshCliPreview(); topbarSlotsList.refs.setProps({ items: draftTopbarSlots, options: getCapsuleMetricOptions(), @@ -21190,6 +21611,7 @@ const SettingsStructureTab = defineComponent({ draftPopoverWidthMode === 'auto' && draftPopoverWidth === DEFAULT_CLIENT_POPOVER_WIDTH && draftEnableCliStatusLine === true && + draftCliStatusLineSlots === null && draftShowTopbarMulti === true && isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS); mountSection.refs.setResetDisabled(isDefault); @@ -21755,12 +22177,14 @@ const SettingsStructureTab = defineComponent({ function renderSettings( settings, windowBridge = latestWindowBridge, - hostPlatform = latestHostPlatform + hostPlatform = latestHostPlatform, + cliStatusLine = latestCliStatusLine ) { if (!settings) return; latestSettings = settings; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; + if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay @@ -21768,6 +22192,7 @@ const SettingsStructureTab = defineComponent({ draftPopoverWidthMode = normalizeClientPopoverWidthMode(settings.popoverWidthMode); draftPopoverWidth = normalizeClientPopoverWidth(settings.popoverWidth); draftEnableCliStatusLine = settings.enableCliStatusLine !== false; + draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(settings.cliStatusLineSlots); draftShowTopbarMulti = settings.showTopbarMultiSession !== false; draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots); draftHoverModules = normalizeClientHoverModules(settings.hoverModules); @@ -21802,6 +22227,7 @@ const SettingsStructureTab = defineComponent({ popoverWidthStepper.setProps({ ariaLabel: t('settings.str.popoverWidthLabel') }); patchText(multiToggleLabelEl, t('settings.str.multiToggle')); patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle')); + patchText(cliSlotsLabelEl, t('settings.str.cliSlotsLabel')); patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel')); hoverSection.refs.setTitle(t('settings.str.hoverSection')); @@ -21872,6 +22298,7 @@ const SettingsStructureTab = defineComponent({ popoverWidthModeToggle.destroy(); multiSessionToggle.destroy(); cliCapsuleToggle.destroy(); + cliSlotsList.destroy(); topbarSlotsList.destroy(); hoverModulesList.destroy(); overviewModulesList.destroy(); @@ -21898,6 +22325,13 @@ const SettingsStructureTab = defineComponent({ windowMountSelect, multiSessionToggle, cliCapsuleToggle, + cliStatusGroupEl, + cliStatusDetailEl, + cliPreviewEl, + cliSlotsList, + cliStatusFooterEl, + cliStatusHintEl, + cliStatusActionBtn, topbarSlotsList, hoverModulesList, overviewModulesList, @@ -26870,7 +27304,8 @@ const SettingsView = defineComponent({ structureTab.refs.renderSettings( settings, telemetry?.windowBridge, - telemetry?.hostPlatform + telemetry?.hostPlatform, + telemetry?.cliStatusLine ); } } else if (settingsSubTab === 'other') { @@ -26895,6 +27330,7 @@ const SettingsView = defineComponent({ (st) => ({ settings: st.telemetry?.settings, windowBridge: st.telemetry?.windowBridge, + cliStatusLine: st.telemetry?.cliStatusLine, hostPlatform: st.telemetry?.hostPlatform, cloudStatus: st.telemetry?.cloudStatus, contextWindowModels: st.telemetry?.contextWindowModels, diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index bb233c0..68e4e62 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -63,7 +63,10 @@ import { resolveDevToolsPortCandidates, startDefaultWindowBridge, } from './window-bridge.mjs'; -import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs'; +import { + ensureCliStatusLineConfigured, + getCliStatusLineRuntimeStatus, +} from './cli-statusline-config.mjs'; export const bootBundleVersion = computeRuntimeCodeVersion(); @@ -632,6 +635,49 @@ export async function executeBridgeRelaunchAction() { }; } +export function executeCliStatusLineAction(rawAction) { + const action = String(rawAction || '').trim(); + if (action !== 'force_install' && action !== 'clear_flags') { + return { + status: 400, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ ok: false, error: 'Unsupported CLI statusLine action' }), + }; + } + + let current = loadSettings(); + if (action === 'force_install' && current.enableCliStatusLine === false) { + const nextSettings = normalizeFullSettings({ + ...current, + enableCliStatusLine: true, + }); + if (saveJson(SETTINGS_FILE, nextSettings)) { + current = nextSettings; + } + } + + const result = ensureCliStatusLineConfigured({ + enabled: true, + forceReplaceCustom: action === 'force_install', + preserveManagedFlags: false, + }); + const cliStatusLine = getCliStatusLineRuntimeStatus(); + const ok = Boolean(result?.updated || result?.alreadyConfigured || cliStatusLine.configured); + return { + status: ok ? 200 : 500, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ + ok, + action, + result, + cliStatusLine, + settings: current, + }), + }; +} + const BRIDGE_ROUTE_LOOKUP = new Map( BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action]) ); @@ -645,6 +691,9 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un if (isPlainObject(data) && data.__bridgeAction === 'relaunch') { return executeBridgeRelaunchAction(); } + if (isPlainObject(data) && typeof data.__cliStatusLineAction === 'string') { + return executeCliStatusLineAction(data.__cliStatusLineAction); + } return executeSettingsAction(data); case 'accounts_get': return executeAccountCredentialAction(undefined, opts); diff --git a/sidecars/panel/backend/cli-statusline-config.mjs b/sidecars/panel/backend/cli-statusline-config.mjs index d6fa436..c83c215 100644 --- a/sidecars/panel/backend/cli-statusline-config.mjs +++ b/sidecars/panel/backend/cli-statusline-config.mjs @@ -15,7 +15,13 @@ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 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'; +import { + HERE, + lsRuntimeEndpoint, + normalizeCliStatusLineSlots, + normalizeLanguageSetting, + normalizeTopbarCapsuleSlots, +} from './config.mjs'; import { classifyCacheTier, classifySpeedTier, @@ -35,9 +41,10 @@ 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_SEP = '\x1b[38;2;110;122;140m'; const SGR_FG_DOT_IDLE = '\x1b[38;2;100;116;139m'; const SGR_FG_ACCENT = '\x1b[38;2;96;165;250m'; +const SGR_FG_TEAL = '\x1b[38;2;45;212;191m'; 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'; @@ -149,24 +156,29 @@ export function buildCliStatusLineCommand( platform = process.platform, execPath = process.execPath, nodeOnPath = true, + extraFlags = '', } = {} ) { const normScript = String(scriptPath || '').trim().replace(/\\/g, '/'); + const cleanFlags = String(extraFlags || '').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}`; + return cleanFlags ? `${runner} ${normScript} ${cleanFlags}` : `${runner} ${normScript}`; } const fileUrl = toPercentEncodedFileUrl(normScript).replace(/'/g, '%27'); - return `${runner} --input-type=module -e import('${fileUrl}')`; + const base = `${runner} --input-type=module -e import('${fileUrl}')`; + return cleanFlags ? `${base} -- ${cleanFlags}` : base; } if (nodeOnPath) { - return `node "${normScript.replace(/"/g, '\\"')}"`; + const base = `node "${normScript.replace(/"/g, '\\"')}"`; + return cleanFlags ? `${base} ${cleanFlags}` : base; } const escapedExec = String(execPath || 'node').replace(/"/g, '\\"'); const escapedScript = normScript.replace(/"/g, '\\"'); - return `"${escapedExec}" "${escapedScript}"`; + const base = `"${escapedExec}" "${escapedScript}"`; + return cleanFlags ? `${base} ${cleanFlags}` : base; } /** @@ -183,21 +195,107 @@ export function isManagedCliStatusLineCommand(cmd) { } /** - * 在纯对象层面更新或移除本插件托管的 `statusLine` 配置,绝不覆盖用户自定义的第三方脚本。 + * 提取用户通过 `/statusline` 追加在托管命令末尾的参数(如 `--slots tps,cost,context --no-multi`)。 + * + * @param {unknown} cmd + * @returns {string} + */ +export function extractManagedCliStatusLineFlags(cmd) { + if (!isManagedCliStatusLineCommand(cmd)) return ''; + const trimmed = String(cmd || '').trim(); + const m = trimmed.match(/cli-statusline\.mjs(?:#autorun)?(?:["')]+)?\s+(--[\s\S]+)$/i); + if (!m) return ''; + return m[1].replace(/^--\s+/, '').trim(); +} + +/** + * 探测本机是否已安装并初始化 Antigravity CLI(`~/.gemini/antigravity-cli`), + * 及当前 CLI `settings.json` 中的 `statusLine` 托管状态(零子进程、纯本地文件探测)。 + * + * @param {{ env?: Record, homeDir?: string }} [options] + * @returns {{ installed: boolean, configured: boolean, preservedCustom: boolean, managedFlags: string }} + */ +export function getCliStatusLineRuntimeStatus({ + env = process.env, + homeDir = homedir(), +} = {}) { + const settingsPath = resolveCliSettingsPath(env, homeDir); + const cliDir = dirname(settingsPath); + let installed = false; + try { + installed = existsSync(cliDir); + } catch { + installed = false; + } + if (!installed) { + return { + installed: false, + configured: false, + preservedCustom: false, + managedFlags: '', + }; + } + + let configured = false; + let preservedCustom = false; + let managedFlags = ''; + try { + if (existsSync(settingsPath)) { + const raw = readFileSync(settingsPath, 'utf8').replace(/^\uFEFF/, '').trim(); + if (raw) { + const parsed = JSON.parse(raw); + const sl = parsed?.statusLine; + if (isCliStatusPlainObject(sl)) { + const cmd = typeof sl.command === 'string' ? sl.command.trim() : ''; + if (cmd) { + if (isManagedCliStatusLineCommand(cmd)) { + configured = sl.enabled !== false; + managedFlags = extractManagedCliStatusLineFlags(cmd); + } else { + preservedCustom = true; + } + } + } else if (sl !== undefined && sl !== null) { + preservedCustom = true; + } + } + } + } catch { + // 忽略损坏或无权限读取的 CLI settings.json + } + + return { + installed: true, + configured, + preservedCustom, + managedFlags, + }; +} + +/** + * 在纯对象层面更新或移除本插件托管的 `statusLine` 配置,绝不覆盖用户自定义的第三方脚本, + * 并在未显式覆盖参数时保留用户在 `/statusline` 命令末尾附加的定制参数。 * * @param {unknown} rawObj - * @param {{ enabled?: boolean, command?: string, stackWithDefault?: boolean }} [options] + * @param {{ enabled?: boolean, command?: string, stackWithDefault?: boolean, preserveManagedFlags?: boolean }} [options] */ export function applyCliStatusLineToSettingsObject( rawObj, - { enabled = true, command = '', stackWithDefault = false } = {} + { + enabled = true, + command = '', + stackWithDefault = false, + preserveManagedFlags = true, + forceReplaceCustom = false, + } = {} ) { const baseObj = isCliStatusPlainObject(rawObj) ? rawObj : {}; const existing = baseObj.statusLine; + let existingCmd = ''; if (isCliStatusPlainObject(existing)) { - const existingCmd = typeof existing.command === 'string' ? existing.command.trim() : ''; - if (existingCmd && !isManagedCliStatusLineCommand(existingCmd)) { + existingCmd = typeof existing.command === 'string' ? existing.command.trim() : ''; + if (existingCmd && !isManagedCliStatusLineCommand(existingCmd) && !forceReplaceCustom) { return { changed: false, preservedCustom: true, @@ -205,7 +303,7 @@ export function applyCliStatusLineToSettingsObject( object: baseObj, }; } - } else if (existing !== undefined && existing !== null) { + } else if (existing !== undefined && existing !== null && !forceReplaceCustom) { return { changed: false, preservedCustom: true, @@ -231,7 +329,7 @@ export function applyCliStatusLineToSettingsObject( }; } - const cleanCmd = String(command || '').trim(); + let cleanCmd = String(command || '').trim(); if (!cleanCmd) { return { changed: false, @@ -239,6 +337,13 @@ export function applyCliStatusLineToSettingsObject( object: baseObj, }; } + if (preserveManagedFlags && !extractManagedCliStatusLineFlags(cleanCmd)) { + const prevFlags = extractManagedCliStatusLineFlags(existingCmd); + if (prevFlags) { + const isAutorun = cleanCmd.includes('--input-type=module -e import('); + cleanCmd = isAutorun ? `${cleanCmd} -- ${prevFlags}` : `${cleanCmd} ${prevFlags}`; + } + } const prevBlock = isCliStatusPlainObject(existing) ? existing : {}; const desiredPadding = @@ -301,6 +406,9 @@ export function ensureCliStatusLineConfigured({ platform = process.platform, execPath = process.execPath, nodeOnPath, + extraFlags = '', + preserveManagedFlags = true, + forceReplaceCustom = false, } = {}) { if ( lsRuntimeEndpoint.addr === 'test.invalid' && @@ -346,9 +454,15 @@ export function ensureCliStatusLineConfigured({ platform, execPath, nodeOnPath: hasNodePath, + extraFlags, }); - const applied = applyCliStatusLineToSettingsObject(currentObj, { enabled, command }); + const applied = applyCliStatusLineToSettingsObject(currentObj, { + enabled, + command, + preserveManagedFlags: extraFlags ? false : preserveManagedFlags, + forceReplaceCustom, + }); if (!applied.changed) { return { checked: true, @@ -577,28 +691,68 @@ function cliComposeBalancedThreeColumn(leftStr, centerStr, rightStr, maxWidth) { return cw <= maxWidth ? centerStr : ''; } +function cliBuildMiniProgressBar( + pct, + { width = 8, fillSgr = SGR_FG_TEAL, emptyChar = '⢕', useColor = true } = {} +) { + if (!(width > 0)) return ''; + const clamped = Math.max(0, Math.min(100, Number(pct))); + let filled = Math.round((clamped / 100) * width); + if (clamped > 0 && filled === 0) filled = 1; + if (clamped < 95 && filled >= width) filled = Math.max(0, width - 1); + const empty = Math.max(0, width - filled); + const filledStr = '█'.repeat(filled); + const emptyStr = emptyChar.repeat(empty); + if (!useColor) { + return `${filledStr}${emptyStr}`; + } + const fillPart = filledStr ? `${fillSgr}${filledStr}` : ''; + const emptyPart = emptyStr ? `${SGR_FG_DIM}${emptyStr}` : ''; + return `${fillPart}${emptyPart}${SGR_RESET}`; +} + +function cliResolveQuotaSlotPrefix(metricKey, isEn) { + if (metricKey === 'gemini_5h') return 'G5h'; + if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; + if (metricKey === 'claude_5h') return 'C5h'; + if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; + return isEn ? '5h' : '余'; +} + /** - * 将单槽位指标格式化为纯文本与无背景前景语义 SGR 片段。 + * 将单槽位指标格式化为纯文本及无背景前景语义 SGR 片段。 */ -function cliRenderSingleSlot(metricKey, slotCtx, { isEn = false, useColor = true, slotSet } = {}) { +function cliRenderSingleSlot( + metricKey, + slotCtx, + { isEn = false, useColor = true, slotSet, barWidth = 8 } = {} +) { 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 label = isEn ? 'Ctx' : '上下文'; 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 + const isMid = !isDanger && !isWarn && pctNum != null && pctNum >= 50; + const barColor = isDanger ? SGR_FG_DANGER : isWarn ? SGR_FG_WARN - : pctNum != null + : isMid ? SGR_FG_ACCENT - : SGR_FG_MUTED; + : pctNum != null + ? SGR_FG_TEAL + : SGR_FG_MUTED; + const barSegment = + barWidth > 0 && pctNum != null + ? `${cliBuildMiniProgressBar(pctNum, { width: barWidth, fillSgr: barColor, emptyChar: '⢕', useColor })} ` + : ''; + if (!useColor) { + return `${label} ${barSegment}${textVal}`; + } const valColor = isDanger ? `${SGR_BOLD}${SGR_FG_DANGER}` : isWarn @@ -606,7 +760,7 @@ function cliRenderSingleSlot(metricKey, slotCtx, { isEn = false, useColor = true : pctNum != null ? `${SGR_BOLD}${SGR_FG_BRIGHT}` : SGR_FG_MUTED; - return `${ringColor}◎ ${valColor}${textVal}${SGR_RESET}`; + return `${SGR_FG_MUTED}${label} ${barSegment}${valColor}${textVal}${SGR_RESET}`; } if (metricKey === 'tps') { @@ -697,23 +851,52 @@ function cliRenderSingleSlot(metricKey, slotCtx, { isEn = false, useColor = true } const quotaPct = hasTelemetry ? cliResolveQuotaPct(slotCtx.quotas, metricKey) : null; - const textVal = - quotaPct != null - ? isEn - ? `${quotaPct}% left` - : `余 ${quotaPct}%` - : isEn - ? 'Quota --' - : '余 --%'; - if (!useColor) return textVal; + const prefix = cliResolveQuotaSlotPrefix(metricKey, isEn); const isDanger = quotaPct != null && quotaPct <= 15; const isWarn = !isDanger && quotaPct != null && quotaPct <= 30; - const color = isDanger + const isMid = !isDanger && !isWarn && quotaPct != null && quotaPct <= 60; + const fillSgr = isDanger + ? SGR_FG_DANGER + : isWarn + ? SGR_FG_WARN + : isMid + ? SGR_FG_INFO + : SGR_FG_GOOD; + const pctSgr = isDanger ? `${SGR_BOLD}${SGR_FG_DANGER}` : isWarn ? `${SGR_BOLD}${SGR_FG_WARN}` - : SGR_FG_MUTED; - return `${color}${textVal}${SGR_RESET}`; + : quotaPct != null + ? SGR_FG_NORMAL + : SGR_FG_MUTED; + + if (quotaPct == null) { + const emptyText = + metricKey === 'quota_auto' && isEn ? 'Quota --' : `${prefix} --%`; + return useColor ? `${SGR_FG_MUTED}${emptyText}${SGR_RESET}` : emptyText; + } + + if (barWidth > 0) { + const bar = cliBuildMiniProgressBar(quotaPct, { + width: barWidth, + fillSgr, + emptyChar: '⣿', + useColor, + }); + if (!useColor) { + return `${prefix} ${bar} ${quotaPct}%`; + } + return `${SGR_FG_MUTED}${prefix} ${bar} ${pctSgr}${quotaPct}%${SGR_RESET}`; + } + + const compactText = + metricKey === 'quota_auto' + ? isEn + ? `${quotaPct}% left` + : `余 ${quotaPct}%` + : `${prefix} ${quotaPct}%`; + if (!useColor) return compactText; + return `${pctSgr}${compactText}${SGR_RESET}`; } /** @@ -767,13 +950,128 @@ function detectCliHostLanguageIsEn() { return false; } +const CLI_STATUS_SLOT_KEEP_PRIORITY = Object.freeze({ + context: 100, + tps: 90, + quota_auto: 80, + gemini_5h: 78, + claude_5h: 76, + ttft: 70, + session_cost: 60, + cost: 58, + cache_hit: 50, + avg_tps: 45, + session_tokens: 40, + gemini_weekly: 35, + claude_weekly: 30, +}); + +function cliStatusHasRenderableValue(metricKey, slotCtx) { + if (slotCtx.hasTelemetry === false) return false; + if (metricKey === 'context') { + return slotCtx.usedPct != null && Number.isFinite(Number(slotCtx.usedPct)); + } + if (metricKey === 'tps') { + return Number.isFinite(Number(slotCtx.tps)) && Number(slotCtx.tps) > 0; + } + if (metricKey === 'avg_tps') { + return Number.isFinite(Number(slotCtx.avgTps)) && Number(slotCtx.avgTps) > 0; + } + if (metricKey === 'ttft') { + return ( + slotCtx.ttft != null && + Number.isFinite(Number(slotCtx.ttft)) && + Number(slotCtx.ttft) >= 0 + ); + } + if (metricKey === 'cost') { + return slotCtx.stepCost != null && Number.isFinite(Number(slotCtx.stepCost)); + } + if (metricKey === 'session_cost') { + return slotCtx.sessionCost != null && Number.isFinite(Number(slotCtx.sessionCost)); + } + if (metricKey === 'cache_hit') { + return slotCtx.cacheHitPct != null && Number.isFinite(Number(slotCtx.cacheHitPct)); + } + if (metricKey === 'session_tokens') { + return ( + slotCtx.sessionTokens != null && + Number.isFinite(Number(slotCtx.sessionTokens)) && + Number(slotCtx.sessionTokens) >= 0 + ); + } + return cliResolveQuotaPct(slotCtx.quotas, metricKey) != null; +} + +function cliStatusFormatAnomalyTag(anomaly, { isEn = false, useColor = true } = {}) { + if (!anomaly || !(Number(anomaly.count) > 0)) return ''; + const n = Math.max(1, Math.floor(Number(anomaly.count) || 1)); + const kind = String(anomaly.primaryKind || 'error'); + let label = ''; + if (isEn) { + if (kind === 'capacity') label = n === 1 ? '503' : `503x${n}`; + else if (kind === 'upstream') label = n === 1 ? '500' : `500x${n}`; + else if (kind === 'rate_limit') label = `429x${n}`; + else if (kind === 'timeout') label = `TO${n}`; + else if (kind === 'disconnect') label = `Drop${n}`; + else if (kind === 'model_output') label = `Fix${n}`; + else if (kind === 'safety') label = `Safe${n}`; + else if (kind === 'mixed') label = `Warn${n}`; + else label = `Err${n}`; + } else { + if (kind === 'capacity') label = n === 1 ? '503' : `503×${n}`; + else if (kind === 'upstream') label = n === 1 ? '500' : `500×${n}`; + else if (kind === 'rate_limit') label = `限流${n}`; + else if (kind === 'timeout') label = `超时${n}`; + else if (kind === 'disconnect') label = `断连${n}`; + else if (kind === 'model_output') label = `纠偏${n}`; + else if (kind === 'safety') label = `过滤${n}`; + else if (kind === 'auth_or_model') label = `受限${n}`; + else if (kind === 'mixed') label = `异常${n}`; + else label = `报错${n}`; + } + const plain = `! ${label}`; + if (!useColor) return plain; + const color = + anomaly.severity === 'danger' || kind === 'rate_limit' || kind === 'auth_or_model' + ? `${SGR_BOLD}${SGR_FG_DANGER}` + : `${SGR_BOLD}${SGR_FG_WARN}`; + return `${color}${plain}${SGR_RESET}`; +} + +function cliStatusShedLowestPrioritySlot(slotKeys) { + if (!Array.isArray(slotKeys) || slotKeys.length <= 1) return slotKeys; + let dropIdx = slotKeys.length - 1; + let lowestPrio = Infinity; + for (let i = 0; i < slotKeys.length; i += 1) { + const prio = CLI_STATUS_SLOT_KEEP_PRIORITY[slotKeys[i]] ?? 50; + if (prio <= lowestPrio) { + lowestPrio = prio; + dropIdx = i; + } + } + return slotKeys.filter((_, idx) => idx !== dropIdx); +} + export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { - const slots = normalizeTopbarCapsuleSlots(options.slots); + const normalizedCliSlots = normalizeCliStatusLineSlots(options.slots); + const rawSlots = normalizedCliSlots || normalizeTopbarCapsuleSlots(options.slots); const showMulti = options.showMultiSession !== false; + const showAnomaly = options.showAnomaly !== false; const normLang = normalizeLanguageSetting(options.language); const isEn = normLang === 'auto' ? detectCliHostLanguageIsEn() : normLang === 'en-US'; const useColor = options.color !== false; - const slotSet = new Set(slots); + + // 新会话尚无任何完成步骤(stepCount === 0)时,隐藏纯占位性的 "--s" / "--" 槽位,避免刚启动显得满屏缺数据 + let activeSlots = rawSlots; + if (slotCtx.stepCount === 0) { + const filtered = rawSlots.filter( + (key) => key === 'tps' || cliStatusHasRenderableValue(key, slotCtx) + ); + if (filtered.length > 0) { + activeSlots = filtered; + } + } const runningCount = Math.max(0, Math.floor(Number(slotCtx.runningCount) || 0)); const runningSubCount = Math.max(0, Math.floor(Number(slotCtx.runningSubCount) || 0)); @@ -807,21 +1105,37 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { } } - 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 anomalyBadge = showAnomaly + ? cliStatusFormatAnomalyTag(slotCtx.latestAnomaly, { isEn, useColor }) + : ''; + const defaultBarWidth = options.showProgressBars === false ? 0 : 8; + + const buildCapsulesForSlots = (slotList, includeAnomaly = true, barWidth = defaultBarWidth) => { + const slotSet = new Set(slotList); + const rendered = slotList.map((key) => + cliRenderSingleSlot(key, slotCtx, { isEn, useColor, slotSet, barWidth }) + ); + if (includeAnomaly && anomalyBadge) { + rendered.push(anomalyBadge); + } + const body = rendered.join(sep); + return { + slotsBody: body, + fullCapsule: multiCore ? `${multiCore} ${body}` : body, + compactCapsule: multiCore ? `${multiCore} ${body}` : body, + }; + }; + + const baseCapsules = buildCapsulesForSlots(activeSlots, true, defaultBarWidth); const rawWidth = Number(options.terminalWidth); if (!Number.isFinite(rawWidth) || rawWidth <= 0) { - return fullCapsule; + return baseCapsules.fullCapsule; } - // 预留右侧 1 列安全边距,与 `agy` 原生底栏右边缘对齐并避免 Windows `conhost`/`cmd.exe` 末列自动折行 + // 预留右侧 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({ @@ -839,20 +1153,60 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { useColor, }); - const tier1 = cliComposeBalancedThreeColumn(fullLeft, fullCapsule, fullRight, maxWidth); - if (tier1) return tier1; + const tryCompose = (cap) => + cliComposeBalancedThreeColumn(fullLeft, cap.fullCapsule, fullRight, maxWidth) || + cliComposeBalancedThreeColumn(shortLeft, cap.fullCapsule, fullRight, maxWidth) || + cliComposeBalancedThreeColumn(shortLeft, cap.compactCapsule, compactRight, maxWidth) || + cliComposeBalancedThreeColumn('', cap.compactCapsule, compactRight, maxWidth); - const tier2 = cliComposeBalancedThreeColumn(shortLeft, fullCapsule, fullRight, maxWidth); - if (tier2) return tier2; + const fullPrimary = cliComposeBalancedThreeColumn( + fullLeft, + baseCapsules.fullCapsule, + fullRight, + maxWidth + ); + if (fullPrimary) return fullPrimary; - 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; + // 中等终端优先把进度条从 8 格微缩至 5 格以保住左右完整原生提示,再逐级收缩左右栏和槽位 + if (defaultBarWidth > 5) { + const compactBarCapsules = buildCapsulesForSlots(activeSlots, true, 5); + const fullCompactBar = cliComposeBalancedThreeColumn( + fullLeft, + compactBarCapsules.fullCapsule, + fullRight, + maxWidth + ); + if (fullCompactBar) return fullCompactBar; } - return slotsBody; + + const primaryComposed = tryCompose(baseCapsules); + if (primaryComposed) return primaryComposed; + + if (defaultBarWidth > 5) { + const compactBarCapsules = buildCapsulesForSlots(activeSlots, true, 5); + const compactBarComposed = tryCompose(compactBarCapsules); + if (compactBarComposed) return compactBarComposed; + } + if (defaultBarWidth > 0) { + const noBarCapsules = buildCapsulesForSlots(activeSlots, true, 0); + const noBarComposed = tryCompose(noBarCapsules); + if (noBarComposed) return noBarComposed; + } + + let reducedSlots = [...activeSlots]; + while (reducedSlots.length > 1) { + reducedSlots = cliStatusShedLowestPrioritySlot(reducedSlots); + const reducedCap = buildCapsulesForSlots(reducedSlots, true, 0); + const composed = tryCompose(reducedCap); + if (composed) return composed; + } + + if (cliDisplayWidth(baseCapsules.fullCapsule) <= maxWidth) { + return baseCapsules.fullCapsule; + } + const minimalCap = buildCapsulesForSlots(reducedSlots, false, 0); + if (cliDisplayWidth(minimalCap.fullCapsule) <= maxWidth) { + return minimalCap.fullCapsule; + } + return minimalCap.slotsBody; } diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index f51465e..1696bf7 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -17,6 +17,8 @@ import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs'; import { normalizeFullSettings } from './settings-schema.mjs'; export { + CLI_STATUSLINE_PRESETS, + DEFAULT_CLI_STATUSLINE_SLOTS, DEFAULT_HOVER_MODULES, DEFAULT_OVERVIEW_METRICS, DEFAULT_OVERVIEW_MODULES, @@ -26,8 +28,10 @@ export { DEFAULT_STEP_TOKEN_COMBO_FORMAT, DEFAULT_TOPBAR_SLOTS, FONT_SCALE_KEYS, + MAX_CLI_STATUSLINE_SLOTS, MAX_POPOVER_WIDTH, MAX_TOPBAR_SLOTS, + MIN_CLI_STATUSLINE_SLOTS, MIN_POPOVER_WIDTH, MIN_TOPBAR_SLOTS, OVERVIEW_METRIC_KEYS, @@ -37,6 +41,7 @@ export { THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, createDefaultSettingsObject, + normalizeCliStatusLineSlots, normalizeFontScale, normalizeFullSettings, normalizeHoverModules, @@ -57,6 +62,7 @@ export { normalizeWeeklyLimitMode, normalizeWindowMountMode, parseStepTokenComboSegments, + resolveEffectiveCliStatusLineSlots, } from './settings-schema.mjs'; /** diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 3942b69..320b133 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -6,6 +6,8 @@ import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs'; import { + CLI_STATUSLINE_PRESETS, + DEFAULT_CLI_STATUSLINE_SLOTS, DEFAULT_HOVER_MODULES, DEFAULT_OVERVIEW_METRICS, DEFAULT_OVERVIEW_MODULES, @@ -14,8 +16,10 @@ import { DEFAULT_STEP_TOKEN_COMBO_FORMAT, DEFAULT_TOPBAR_SLOTS, FONT_SCALE_KEYS, + MAX_CLI_STATUSLINE_SLOTS, MAX_POPOVER_WIDTH, MAX_TOPBAR_SLOTS, + MIN_CLI_STATUSLINE_SLOTS, MIN_POPOVER_WIDTH, MIN_TOPBAR_SLOTS, OVERVIEW_METRIC_KEYS, @@ -26,6 +30,7 @@ import { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeCliStatusLineSlots, normalizeExperimentalModernUi, normalizeFontScale, normalizeHoverModules, @@ -46,9 +51,12 @@ import { normalizeWeeklyLimitMode, normalizeWindowMountMode, parseStepTokenComboSegments, + resolveEffectiveCliStatusLineSlots, } from '../shared/settings-normalization.mjs'; export { + CLI_STATUSLINE_PRESETS, + DEFAULT_CLI_STATUSLINE_SLOTS, DEFAULT_HOVER_MODULES, DEFAULT_OVERVIEW_METRICS, DEFAULT_OVERVIEW_MODULES, @@ -57,8 +65,10 @@ export { DEFAULT_STEP_TOKEN_COMBO_FORMAT, DEFAULT_TOPBAR_SLOTS, FONT_SCALE_KEYS, + MAX_CLI_STATUSLINE_SLOTS, MAX_POPOVER_WIDTH, MAX_TOPBAR_SLOTS, + MIN_CLI_STATUSLINE_SLOTS, MIN_POPOVER_WIDTH, MIN_TOPBAR_SLOTS, OVERVIEW_METRIC_KEYS, @@ -69,6 +79,7 @@ export { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeCliStatusLineSlots, normalizeExperimentalModernUi, normalizeFontScale, normalizeHoverModules, @@ -89,6 +100,7 @@ export { normalizeWeeklyLimitMode, normalizeWindowMountMode, parseStepTokenComboSegments, + resolveEffectiveCliStatusLineSlots, }; function isSchemaPlainObject(v) { @@ -127,6 +139,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ popoverWidthMode: 'auto', popoverWidth: DEFAULT_POPOVER_WIDTH, enableCliStatusLine: true, + cliStatusLineSlots: null, standalonePort: 0, showTopbarMultiSession: true, topbarCapsuleSlots: DEFAULT_TOPBAR_SLOTS, @@ -203,6 +216,7 @@ export function normalizeFullSettings(rawInput) { popoverWidthMode: normalizePopoverWidthMode(safeRaw.popoverWidthMode), popoverWidth: normalizePopoverWidth(safeRaw.popoverWidth), enableCliStatusLine: safeRaw.enableCliStatusLine !== false, + cliStatusLineSlots: normalizeCliStatusLineSlots(safeRaw.cliStatusLineSlots), standalonePort: normalizeStandalonePort(safeRaw.standalonePort), showTopbarMultiSession: safeRaw.showTopbarMultiSession !== false, topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots), diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index c8c781b..7d46564 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -31,6 +31,7 @@ import { } from './config.mjs'; import { getEndpointCacheStore } from './endpoint-registry.mjs'; import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs'; +import { getCliStatusLineRuntimeStatus } from './cli-statusline-config.mjs'; import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs'; import { enumerateAndSyncConversations } from './local-scanner.mjs'; import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; @@ -2073,6 +2074,7 @@ export async function buildTelemetryPayloadInternal( }, uiBundleVersion, windowBridge: getDefaultWindowBridgeStatus(), + cliStatusLine: getCliStatusLineRuntimeStatus(), settings: loadSettings(), contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => { const latest = group.members.reduce((previous, id) => { @@ -2477,6 +2479,34 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) { const runningList = Array.isArray(finalPayload?.runningConversations) ? finalPayload.runningConversations : []; + const activeSteps = Array.isArray(ac.recentSteps) ? ac.recentSteps : []; + let sessionAnomalyCount = 0; + let latestAnomaly = null; + for (let i = 0; i < activeSteps.length; i += 1) { + const a = activeSteps[i]?.anomaly; + if (a && Number(a.count) > 0) { + sessionAnomalyCount += Number(a.count); + } + } + const lastStepAnomaly = activeSteps.length > 0 ? activeSteps[activeSteps.length - 1]?.anomaly : null; + if (lastStepAnomaly && Number(lastStepAnomaly.count) > 0) { + latestAnomaly = { + primaryKind: String(lastStepAnomaly.primaryKind || 'error'), + count: Number(lastStepAnomaly.count), + severity: lastStepAnomaly.severity === 'danger' ? 'danger' : 'warn', + totalDelaySec: Number(lastStepAnomaly.totalDelaySec || 0), + }; + } + + const waitingCascadeIds = runningList + .filter( + (item) => + item?.mainActivity?.phase === 'waiting' || + (Array.isArray(item?.subagents) && + item.subagents.some((sub) => sub?.isRunning && sub?.liveActivity?.phase === 'waiting')) + ) + .map((item) => String(item?.cascadeId || '').toLowerCase()) + .filter(Boolean); return { updatedAtMs, @@ -2485,7 +2515,8 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) { (acc, item) => acc + Number(item?.runningSubagentCount || 0), 0 ), - hasWaiting: runningList.some((item) => item?.mainActivity?.phase === 'waiting'), + hasWaiting: waitingCascadeIds.length > 0, + waitingCascadeIds, quotas: finalPayload?.quotas || null, activeConversation: { cascadeId: ac.cascadeId || '', @@ -2500,6 +2531,8 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) { latestCacheHitPct: capSource.latestCacheHitPct ?? ac.latestCacheHitPct ?? null, latestPromptTokens: Number(capSource.latestPromptTokens ?? ac.latestPromptTokens ?? 0), totalTokens: Number(capSource.totalTokens ?? ac.totalTokens ?? 0), + ...(latestAnomaly ? { latestAnomaly } : {}), + ...(sessionAnomalyCount > 0 ? { sessionAnomalyCount } : {}), }, }; } diff --git a/sidecars/panel/cli-statusline.mjs b/sidecars/panel/cli-statusline.mjs index d2a8908..28da026 100644 --- a/sidecars/panel/cli-statusline.mjs +++ b/sidecars/panel/cli-statusline.mjs @@ -9,8 +9,13 @@ * 2. 联动用户偏好设置中的胶囊槽位顺序(`topbarCapsuleSlots`)与开关(`enableCliStatusLine`), * 向 `stdout` 输出单行 24-bit ANSI 状态胶囊。 * - * 同时支持手动管理命令: - * - `node sidecars/panel/cli-statusline.mjs --install` + * 同时支持直接在 `/statusline` 命令末尾传入定制参数,及手动管理命令: + * - `--slots tps,ttft,cache_hit,session_cost,quota_auto,context`(支持预设名 `compact` / `balanced` / `full` / `auto`) + * - `--preset compact|balanced|full` + * - `--multi` / `--no-multi`(开关多会话计数指示) + * - `--anomaly` / `--no-anomaly`(开关最近一步异常角标) + * - `--lang zh-CN|en-US|auto`、`--no-color` + * - `node sidecars/panel/cli-statusline.mjs --install [--preset full --no-multi ...]` * - `node sidecars/panel/cli-statusline.mjs --uninstall` */ @@ -19,6 +24,7 @@ import { homedir } from 'node:os'; import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { + extractLiveActivity, extractModelSteps, speedMetric, summarizeSpeed, @@ -35,8 +41,12 @@ import { } from './backend/cli-statusline-config.mjs'; import { CLI_STATUS_SNAPSHOT_FILE, + CLI_STATUSLINE_PRESETS, + TOPBAR_SLOT_KEYS, loadJson, loadSettings, + normalizeCliStatusLineSlots, + resolveEffectiveCliStatusLineSlots, } from './backend/config.mjs'; import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs'; import { isThirdPartyPoolText } from './shared/telemetry-display-rules.mjs'; @@ -192,14 +202,18 @@ export function resolveCliLocalSessionMetrics({ let runningRootCount = 0; let runningSubCount = 0; - for (const summary of summariesMap.values()) { + const freshRunningRootIds = []; + for (const [cidKey, summary] of summariesMap.entries()) { 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; + else { + runningRootCount += 1; + freshRunningRootIds.push(String(cidKey || '').toLowerCase()); + } } if (!existsSync(convDir)) { @@ -211,8 +225,13 @@ export function resolveCliLocalSessionMetrics({ } let targetCid = extractConversationIdFromStdin(stdinData); - if (!targetCid && stdinData?.cwd) { - const ftsCid = findConversationIdByWorkspaceFts(cliRoot, stdinData.cwd); + const effectiveCwd = + stdinData?.cwd || + stdinData?.workspace?.current_dir || + stdinData?.workspace?.project_dir || + ''; + if (!targetCid && effectiveCwd) { + const ftsCid = findConversationIdByWorkspaceFts(cliRoot, effectiveCwd); if (ftsCid && existsSync(join(convDir, `${ftsCid}.db`))) { targetCid = ftsCid; } @@ -268,27 +287,87 @@ export function resolveCliLocalSessionMetrics({ const rootTraj = readLocalSqliteTrajectory(rootDb); if (rootTraj) { targetCid = traj.rootConversationId || traj.parentConversationId; + dbPath = rootDb; traj = rootTraj; } } } + let dbMtimeMs = 0; + try { + dbMtimeMs = Math.max(dbMtimeMs, statSync(dbPath).mtimeMs || 0); + } catch { + // 忽略 stat 异常 + } + try { + const walPath = `${dbPath}-wal`; + if (existsSync(walPath)) { + dbMtimeMs = Math.max(dbMtimeMs, statSync(walPath).mtimeMs || 0); + } + } catch { + // 忽略 WAL stat 异常 + } + if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) { return { found: false, cascadeId: targetCid, + dbMtimeMs, runningRootCount, runningSubCount, + targetIsRunning: freshRunningRootIds.includes(String(targetCid || '').toLowerCase()), + targetIsWaiting: false, + targetWaitingApprovalFresh: false, + otherLocalWaiting: false, }; } + const targetLower = String(targetCid || '').toLowerCase(); + const targetIsRunning = freshRunningRootIds.includes(targetLower); + const targetLiveAct = extractLiveActivity(traj.steps, true); + const targetIsWaiting = Boolean( + targetLiveAct?.phase === 'waiting' || targetLiveAct?.waitingApproval + ); + const targetWaitingApprovalFresh = Boolean( + targetLiveAct?.waitingApproval && + dbMtimeMs > 0 && + nowMs - dbMtimeMs <= CLI_RUNNING_STALE_MS + ); + + let otherLocalWaiting = false; + let checkedOthers = 0; + for (const runCid of freshRunningRootIds) { + if (!runCid || runCid === targetLower) continue; + if (checkedOthers >= 3) break; + const otherDb = join(convDir, `${runCid}.db`); + if (!existsSync(otherDb)) continue; + checkedOthers += 1; + try { + const otherTraj = readLocalSqliteTrajectory(otherDb); + if (otherTraj && Array.isArray(otherTraj.steps) && otherTraj.steps.length > 0) { + const otherAct = extractLiveActivity(otherTraj.steps, true); + if (otherAct?.phase === 'waiting' || otherAct?.waitingApproval) { + otherLocalWaiting = true; + break; + } + } + } catch { + // 忽略单会话读取异常 + } + } + const steps = extractModelSteps(traj.steps, traj.generatorMetadata || []); if (steps.length === 0) { return { found: false, cascadeId: targetCid, + dbMtimeMs, runningRootCount, runningSubCount, + targetIsRunning, + targetIsWaiting, + targetWaitingApprovalFresh, + otherLocalWaiting, }; } @@ -305,6 +384,9 @@ export function resolveCliLocalSessionMetrics({ let latestLimitTokens = 0; let latestTps = null; let latestTtft = null; + let sessionAnomalyCount = 0; + let latestAnomaly = null; + let latestModelHint = ''; for (const step of steps) { const inTok = Math.max(0, Number(step.inputTokens || 0)); @@ -316,7 +398,16 @@ export function resolveCliLocalSessionMetrics({ totalCacheReadTokens += cacheTok; totalOutputTokens += outTok; + if (step.anomaly && Number(step.anomaly.count) > 0) { + sessionAnomalyCount += Number(step.anomaly.count); + } + const modelInfo = resolveStepModel(step); + if (modelInfo?.label || step.modelDisplayName || step.responseModel) { + latestModelHint = String( + modelInfo?.label || step.modelDisplayName || step.responseModel || '' + ).trim(); + } const stepUsd = computeStepCost(step, modelInfo?.pricing || null); if (stepUsd !== null && Number.isFinite(stepUsd)) { sessionCostUsd += stepUsd; @@ -349,6 +440,16 @@ export function resolveCliLocalSessionMetrics({ } } + const lastStep = steps[steps.length - 1]; + if (lastStep?.anomaly && Number(lastStep.anomaly.count) > 0) { + latestAnomaly = { + primaryKind: String(lastStep.anomaly.primaryKind || 'error'), + count: Number(lastStep.anomaly.count), + severity: lastStep.anomaly.severity === 'danger' ? 'danger' : 'warn', + totalDelaySec: Number(lastStep.anomaly.totalDelaySec || 0), + }; + } + const speedSum = summarizeSpeed(steps); const ttftSum = summarizeTtft(steps); const totalPromptAll = totalInputTokens + totalCacheReadTokens; @@ -358,9 +459,14 @@ export function resolveCliLocalSessionMetrics({ return { found: true, cascadeId: targetCid, + dbMtimeMs, stepCount: steps.length, runningRootCount, runningSubCount, + targetIsRunning, + targetIsWaiting, + targetWaitingApprovalFresh, + otherLocalWaiting, tps: latestTps, avgTps: speedSum?.avgTokPerSec != null ? +speedSum.avgTokPerSec.toFixed(1) : null, ttft: latestTtft ?? ttftSum?.avgSec ?? null, @@ -369,6 +475,9 @@ export function resolveCliLocalSessionMetrics({ cacheHitPct: latestCacheHitPct ?? sessionCacheHitPct, latestPromptTokens, sessionTokens: totalInputTokens + totalCacheReadTokens + totalOutputTokens, + latestAnomaly, + sessionAnomalyCount, + latestModelHint, usedPct: latestLimitTokens > 0 && latestContextTokens > 0 ? Math.min(100, +((latestContextTokens / latestLimitTokens) * 100).toFixed(1)) @@ -410,8 +519,130 @@ function buildStdinFallbackQuotas(stdinData) { }; } +function selectCliActiveQuotaPool(quotas, modelHint = '') { + if (!quotas || typeof quotas !== 'object') return quotas || null; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const hint = String(modelHint || '').trim(); + if (!hint || pools.length <= 1) return quotas; + + const hintLower = hint.toLowerCase(); + const baseHint = hintLower.replace(/\s*\([^)]*\)\s*$/, '').trim(); + + // 1. 优先按配额池内置模型清单精确/前缀匹配 + const exactPool = pools.find((p) => { + const models = Array.isArray(p?.models) ? p.models : []; + return models.some((m) => { + const ml = String(m || '').trim().toLowerCase(); + return ml === hintLower || (baseHint && ml.startsWith(baseHint)); + }); + }); + if (exactPool) { + return { ...quotas, activePool: exactPool }; + } + + // 2. 按模型家族匹配(Claude & GPT / Carbon / Argon / Gemini) + const wantThirdParty = isThirdPartyPoolText(hint); + const familyMatched = pools.filter((p) => { + const pk = String(p?.poolKey || p?.poolLabel || p?.family || '').toLowerCase(); + if (wantThirdParty) return isThirdPartyPoolText(pk); + if (/\bcarbon\b/i.test(hint) && pk.includes('carbon')) return true; + if (/\bargon\b/i.test(hint) && pk.includes('argon')) return true; + return !isThirdPartyPoolText(pk) && (pk.includes('gemini') || pk === 'default'); + }); + if (familyMatched.length > 0) { + const activePool = familyMatched.reduce((minP, cur) => + Number(cur?.remainingPct ?? 100) < Number(minP?.remainingPct ?? 100) ? cur : minP + ); + return { ...quotas, activePool }; + } + return quotas; +} + /** - * 融合 `stdin` (`StatusLineData`)、本地 CLI SQLite 步骤指标与后台守护配额快照,生成胶囊上下文。 + * 解析通过 `/statusline` 传入 `cli-statusline.mjs` 的命令行参数。 + * + * @param {string[]} [argv] + */ +export function parseCliStatusLineArgs(argv = []) { + const out = { + install: false, + uninstall: false, + help: false, + resetFlags: false, + slotsRaw: null, + preset: '', + showMultiSession: null, + showAnomaly: null, + language: '', + noColor: false, + }; + for (let i = 0; i < argv.length; i += 1) { + const raw = String(argv[i] || '').trim(); + if (!raw || raw === '--') continue; + const eqIdx = raw.indexOf('='); + const flag = eqIdx > 0 ? raw.slice(0, eqIdx) : raw; + const readVal = () => { + if (eqIdx > 0) return raw.slice(eqIdx + 1).trim(); + if (i + 1 < argv.length && !String(argv[i + 1]).startsWith('-')) { + i += 1; + return String(argv[i] || '').trim(); + } + return ''; + }; + if (flag === '--install') out.install = true; + else if (flag === '--uninstall') out.uninstall = true; + else if (flag === '--help' || flag === '-h') out.help = true; + else if (flag === '--reset-flags') out.resetFlags = true; + else if (flag === '--slots') out.slotsRaw = readVal(); + else if (flag === '--preset') out.preset = readVal().toLowerCase(); + else if (flag === '--multi' || flag === '--show-multi') out.showMultiSession = true; + else if (flag === '--no-multi' || flag === '--hide-multi') out.showMultiSession = false; + else if (flag === '--anomaly' || flag === '--show-anomaly') out.showAnomaly = true; + else if (flag === '--no-anomaly' || flag === '--hide-anomaly') out.showAnomaly = false; + else if (flag === '--lang') out.language = readVal(); + else if (flag === '--no-color') out.noColor = true; + } + return out; +} + +function buildPersistableStatusLineFlags(parsed) { + const parts = []; + if (parsed.slotsRaw && parsed.slotsRaw.toLowerCase() !== 'auto') { + const norm = normalizeCliStatusLineSlots(parsed.slotsRaw); + if (norm && norm.length > 0) parts.push(`--slots ${norm.join(',')}`); + } else if ( + parsed.preset && + Object.prototype.hasOwnProperty.call(CLI_STATUSLINE_PRESETS, parsed.preset) + ) { + parts.push(`--preset ${parsed.preset}`); + } + if (parsed.showMultiSession === false) parts.push('--no-multi'); + else if (parsed.showMultiSession === true) parts.push('--multi'); + if (parsed.showAnomaly === false) parts.push('--no-anomaly'); + else if (parsed.showAnomaly === true) parts.push('--anomaly'); + if (parsed.language) parts.push(`--lang ${parsed.language}`); + if (parsed.noColor) parts.push('--no-color'); + return parts.join(' '); +} + +function formatCliStatusLineHelp() { + return [ + 'Antigravity Usage Monitor - CLI statusLine options:', + ' --slots Custom 1-6 slots (e.g. tps,ttft,session_cost,quota_auto,context)', + ' --preset compact|balanced|full', + ' Built-in slot presets (3 / 5 / 6 slots)', + ' --multi / --no-multi Show or hide running sessions indicator', + ' --anomaly / --no-anomaly Show or hide latest-step anomaly badge (! 503 / ! 429)', + ' --lang zh-CN|en-US|auto Override display language', + ' --no-color Disable ANSI colors', + ' --install [flags...] Install into ~/.gemini/antigravity-cli/settings.json', + ' --uninstall Remove managed statusLine from CLI settings', + `Available slot keys: ${TOPBAR_SLOT_KEYS.join(', ')}`, + ].join('\n'); +} + +/** + * 融合 `stdin` (`StatusLineData`)、本地 CLI SQLite 步骤指标及后台守护配额快照,生成胶囊上下文。 */ export function buildMergedCliCapsuleContext({ stdinData = null, @@ -420,12 +651,30 @@ export function buildMergedCliCapsuleContext({ nowMs = Date.now(), } = {}) { const agentState = String(stdinData?.agent_state || '').trim().toLowerCase(); + const stdinIsWaiting = + agentState.includes('wait') || + agentState.includes('approv') || + agentState.includes('confirm') || + agentState.includes('permission') || + agentState.includes('consent') || + agentState.includes('review') || + agentState === 'ask' || + agentState === 'pending_user' || + Boolean( + stdinData?.waiting_for_approval || + stdinData?.awaiting_approval || + stdinData?.has_pending_approval + ); const stdinIsRunning = - agentState === 'running' || - agentState === 'streaming' || - agentState === 'executing' || - agentState === 'thinking'; - const stdinIsWaiting = agentState === 'waiting' || agentState === 'awaiting_approval'; + !stdinIsWaiting && + (agentState === 'running' || + agentState === 'streaming' || + agentState === 'executing' || + agentState === 'thinking' || + agentState === 'working' || + agentState === 'tool_use' || + agentState === 'tool_executing' || + agentState === 'generating'); const stdinSubagents = Array.isArray(stdinData?.subagents) ? stdinData.subagents.filter((s) => { @@ -444,14 +693,43 @@ export function buildMergedCliCapsuleContext({ 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 localActiveRunning = + stdinIsRunning || + stdinIsWaiting || + Boolean(localMetrics?.targetIsRunning) || + Boolean(localMetrics?.targetWaitingApprovalFresh); + const runningCount = localActiveRunning ? 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 localTargetWaiting = Boolean( + localMetrics?.targetWaitingApprovalFresh || + (localMetrics?.targetIsWaiting && localActiveRunning) + ); + const localOtherWaiting = Boolean(localMetrics?.otherLocalWaiting); + const localCidLower = String(localMetrics?.cascadeId || '').toLowerCase(); + const localDbNewerThanSnap = + Number(localMetrics?.dbMtimeMs || 0) > Number(snapshot?.updatedAtMs || 0); + let snapHasWaiting = false; + if (snapLiveFresh) { + if ( + Array.isArray(snapshot?.waitingCascadeIds) && + localCidLower && + localMetrics?.found && + localDbNewerThanSnap + ) { + // 本地 SQLite WAL 更新晚于桌面端快照时,当前 CLI 会话以本地 WAL 为准(恢复运行秒变绿),同时保留桌面端其他会话的等待态 + snapHasWaiting = snapshot.waitingCascadeIds.some( + (id) => String(id || '').toLowerCase() && String(id || '').toLowerCase() !== localCidLower + ); + } else { + snapHasWaiting = Boolean(snapshot?.hasWaiting); + } + } + const hasWaiting = stdinIsWaiting || localTargetWaiting || localOtherWaiting || snapHasWaiting; const stdinUsedPct = stdinData?.context_window?.used_percentage; const usedPct = @@ -481,15 +759,27 @@ export function buildMergedCliCapsuleContext({ ? snapshot.activeConversation : null; - const mergedQuotas = + const activeModelHint = String( + stdinData?.model?.display_name || stdinData?.model?.id || localMetrics?.latestModelHint || '' + ).trim(); + const rawQuotas = (snapQuotaFresh && snapshot?.quotas) || buildStdinFallbackQuotas(stdinData) || null; + const mergedQuotas = selectCliActiveQuotaPool(rawQuotas, activeModelHint); const hasTelemetry = Boolean( stdinData || localMetrics?.found || snapActive || mergedQuotas ); + const resolvedStepCount = localMetrics?.found + ? Number(localMetrics.stepCount || 0) + : snapActive?.stepCount != null + ? Number(snapActive.stepCount) + : stdinData + ? 0 + : undefined; return { hasTelemetry, + stepCount: resolvedStepCount, isRunning: stdinIsRunning || stdinIsWaiting, hasWaiting, runningCount, @@ -504,17 +794,30 @@ export function buildMergedCliCapsuleContext({ latestPromptTokens: localMetrics?.latestPromptTokens ?? snapActive?.latestPromptTokens ?? null, sessionTokens: localMetrics?.sessionTokens ?? stdinSessionTokens ?? snapActive?.totalTokens ?? null, + latestAnomaly: localMetrics?.latestAnomaly ?? snapActive?.latestAnomaly ?? null, + sessionAnomalyCount: + localMetrics?.sessionAnomalyCount ?? snapActive?.sessionAnomalyCount ?? 0, quotas: mergedQuotas, }; } export async function runCliStatusLineMain(argv = process.argv.slice(2)) { - if (argv.includes('--install')) { - const res = ensureCliStatusLineConfigured({ enabled: true }); + const cliArgs = parseCliStatusLineArgs(argv); + if (cliArgs.help) { + process.stdout.write(`${formatCliStatusLineHelp()}\n`); + return; + } + if (cliArgs.install) { + const extraFlags = buildPersistableStatusLineFlags(cliArgs); + const res = ensureCliStatusLineConfigured({ + enabled: true, + extraFlags, + preserveManagedFlags: !cliArgs.resetFlags && !extraFlags && cliArgs.slotsRaw !== 'auto', + }); process.stdout.write(`${JSON.stringify(res)}\n`); return; } - if (argv.includes('--uninstall')) { + if (cliArgs.uninstall) { const res = ensureCliStatusLineConfigured({ enabled: false }); process.stdout.write(`${JSON.stringify(res)}\n`); return; @@ -556,12 +859,34 @@ export async function runCliStatusLineMain(argv = process.argv.slice(2)) { } const useColor = - !Object.prototype.hasOwnProperty.call(process.env, 'NO_COLOR') || - String(process.env.NO_COLOR || '') === ''; + !cliArgs.noColor && + (!Object.prototype.hasOwnProperty.call(process.env, 'NO_COLOR') || + String(process.env.NO_COLOR || '') === ''); + + let effectiveSlots = null; + if (cliArgs.slotsRaw !== null) { + effectiveSlots = + cliArgs.slotsRaw.toLowerCase() === 'auto' + ? resolveEffectiveCliStatusLineSlots(settings) + : normalizeCliStatusLineSlots(cliArgs.slotsRaw) || + resolveEffectiveCliStatusLineSlots(settings); + } else if ( + cliArgs.preset && + Object.prototype.hasOwnProperty.call(CLI_STATUSLINE_PRESETS, cliArgs.preset) + ) { + effectiveSlots = [...CLI_STATUSLINE_PRESETS[cliArgs.preset]]; + } else { + effectiveSlots = resolveEffectiveCliStatusLineSlots(settings); + } + const line = formatCliStatusLineCapsule(slotCtx, { - slots: settings?.topbarCapsuleSlots, - showMultiSession: settings?.showTopbarMultiSession !== false, - language: settings?.language, + slots: effectiveSlots, + showMultiSession: + cliArgs.showMultiSession !== null + ? cliArgs.showMultiSession + : settings?.showTopbarMultiSession !== false, + showAnomaly: cliArgs.showAnomaly !== null ? cliArgs.showAnomaly : true, + language: cliArgs.language || settings?.language, color: useColor, terminalWidth: Number.isFinite(terminalWidth) && terminalWidth > 0 ? terminalWidth : 0, cycleMode: typeof stdinData?.cycle_mode === 'string' ? stdinData.cycle_mode : '', diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 37c16d4..a36f6d8 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs index 99d077f..a9dc8fe 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -36,6 +36,21 @@ export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); export const MIN_TOPBAR_SLOTS = 1; export const MAX_TOPBAR_SLOTS = 5; +export const DEFAULT_CLI_STATUSLINE_SLOTS = Object.freeze([ + 'tps', + 'ttft', + 'session_cost', + 'quota_auto', + 'context', +]); +export const MIN_CLI_STATUSLINE_SLOTS = 1; +export const MAX_CLI_STATUSLINE_SLOTS = 6; +export const CLI_STATUSLINE_PRESETS = Object.freeze({ + compact: Object.freeze(['tps', 'ttft', 'context']), + balanced: DEFAULT_CLI_STATUSLINE_SLOTS, + full: Object.freeze(['tps', 'ttft', 'cache_hit', 'session_cost', 'quota_auto', 'context']), +}); + export const OVERVIEW_MODULE_KEYS = Object.freeze([ 'metrics', 'context', @@ -336,6 +351,69 @@ export function normalizeTopbarCapsuleSlots(raw) { return out; } +/** + * 归一化 CLI 底部状态栏独立槽位配置(`null` 表示自动跟随宽屏默认或自定义顶栏槽位; + * 支持预设名 `compact` / `balanced` / `full`、逗号分隔列表或数组,保留 1~6 个去重合法槽位)。 + * + * @param {unknown} raw + * @returns {string[]|null} + */ +export function normalizeCliStatusLineSlots(raw) { + if (raw === undefined || raw === null) return null; + let items = null; + if (typeof raw === 'string') { + const clean = raw.trim(); + const lower = clean.toLowerCase(); + if (!clean || lower === 'auto' || lower === 'default') { + return null; + } + if (Object.prototype.hasOwnProperty.call(CLI_STATUSLINE_PRESETS, lower)) { + return [...CLI_STATUSLINE_PRESETS[lower]]; + } + items = clean.split(/[\s,|:]+/); + } else if (Array.isArray(raw)) { + items = raw; + } else { + return null; + } + const seen = new Set(); + const out = []; + for (const item of items) { + const val = String(item ?? '').trim(); + if (!val || val === 'none') continue; + const mapped = val === 'step_cost' ? 'cost' : val; + if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue; + seen.add(mapped); + out.push(mapped); + if (out.length >= MAX_CLI_STATUSLINE_SLOTS) break; + } + return out.length >= MIN_CLI_STATUSLINE_SLOTS ? out : null; +} + +/** + * 解析当前生效的 CLI 底栏槽位列表: + * 1. 若用户显式设置了 `cliStatusLineSlots`,优先使用; + * 2. 若用户自定义了非默认 `topbarCapsuleSlots`,沿用其自定义顺序保持兼容; + * 3. 否则采用面向宽终端的 5 槽默认组合(速度 / 首字 / 费用 / 配额 / 上下文)。 + * + * @param {object|null|undefined} settings + * @returns {string[]} + */ +export function resolveEffectiveCliStatusLineSlots(settings) { + const customCli = normalizeCliStatusLineSlots(settings?.cliStatusLineSlots); + if (customCli && customCli.length > 0) { + return customCli; + } + const topbar = normalizeTopbarCapsuleSlots(settings?.topbarCapsuleSlots); + const isDefaultTopbar = + topbar.length === DEFAULT_TOPBAR_SLOTS.length && + topbar.every((k, i) => k === DEFAULT_TOPBAR_SLOTS[i]); + if (!isDefaultTopbar) { + return topbar; + } + return [...DEFAULT_CLI_STATUSLINE_SLOTS]; +} + /** * 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。 * diff --git a/sidecars/panel/src/core/settingsBackup.js b/sidecars/panel/src/core/settingsBackup.js index 458f35d..90331c8 100644 --- a/sidecars/panel/src/core/settingsBackup.js +++ b/sidecars/panel/src/core/settingsBackup.js @@ -4,6 +4,7 @@ */ import { + normalizeCliStatusLineSlots, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -104,6 +105,7 @@ export function buildExportableSettingsJson(settings = {}) { popoverWidthMode: normalizePopoverWidthMode(src.popoverWidthMode), popoverWidth: normalizePopoverWidth(src.popoverWidth), enableCliStatusLine: src.enableCliStatusLine !== false, + cliStatusLineSlots: normalizeCliStatusLineSlots(src.cliStatusLineSlots), standalonePort: normalizeStandalonePort(src.standalonePort), showTopbarMultiSession: src.showTopbarMultiSession !== false, topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots), @@ -195,6 +197,9 @@ export function parseImportedSettingsJson(rawText) { if (hasKey('enableCliStatusLine') && typeof src.enableCliStatusLine === 'boolean') { patch.enableCliStatusLine = src.enableCliStatusLine; } + if (hasKey('cliStatusLineSlots')) { + patch.cliStatusLineSlots = normalizeCliStatusLineSlots(src.cliStatusLineSlots); + } if (hasKey('standalonePort')) { patch.standalonePort = normalizeStandalonePort(src.standalonePort); } diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 8f915a1..bede5ef 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -559,6 +559,16 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.str.popoverWidthHint': 'Auto Fit widens wide tables like Step Records to avoid horizontal scroll; Custom accepts 440–1080 px', 'settings.str.multiToggle': 'Active Sessions Pill', 'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule', + 'settings.str.cliSlotsLabel': 'CLI Slot Order (Left → Right, 1–6, draggable)', + 'settings.str.addCliSlot': 'Add CLI Slot ({count}/{max})', + 'settings.str.cliCustomCmdHint': 'Custom statusLine command detected; preserved automatically unless you take over', + 'settings.str.cliPausedHint': 'CLI statusLine is currently paused or not yet configured', + 'settings.str.cliFlagsOverrideHint': 'Explicit CLI launch flags (--slots / --preset) detected and take precedence over these slots', + 'settings.str.cliRestoreBtn': 'Take Over & Restore', + 'settings.str.cliEnableBtn': 'Re-enable in CLI', + 'settings.str.cliClearFlagsBtn': 'Clear Flag Override', + 'settings.str.cliRestoringBtn': 'Applying...', + 'settings.str.cliPreviewRunning': '{count} active', 'settings.str.show': 'Show', 'settings.str.hide': 'Hide', 'settings.str.on': 'On', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index c773bee..1282a5e 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -559,6 +559,16 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px', 'settings.str.multiToggle': '实时运行会话入口', 'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊', + 'settings.str.cliSlotsLabel': 'CLI 槽位顺序 (左 → 右,1~6 项,可拖拽)', + 'settings.str.addCliSlot': '添加 CLI 槽位 ({count}/{max})', + 'settings.str.cliCustomCmdHint': '检测到自定义 statusLine 命令,为避免误覆盖默认不会自动改写', + 'settings.str.cliPausedHint': 'CLI 端当前已暂停或未写入 statusLine 配置', + 'settings.str.cliFlagsOverrideHint': '检测到 CLI 启动参数包含显式槽位覆盖,命令行参数将优先于此处配置', + 'settings.str.cliRestoreBtn': '一键接管并恢复', + 'settings.str.cliEnableBtn': '重新写入并启用', + 'settings.str.cliClearFlagsBtn': '清除命令行覆盖', + 'settings.str.cliRestoringBtn': '正在写入...', + 'settings.str.cliPreviewRunning': '{count} 运行中', 'settings.str.show': '显示', 'settings.str.hide': '隐藏', 'settings.str.on': '开启', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 00907b6..c7d6e72 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -26,6 +26,8 @@ import { resolveSettingsModernUi, } from '../core/appearance.js'; import { + CLI_STATUSLINE_PRESETS, + DEFAULT_CLI_STATUSLINE_SLOTS, DEFAULT_HOVER_MODULES, DEFAULT_OVERVIEW_METRICS, DEFAULT_OVERVIEW_MODULES, @@ -39,6 +41,7 @@ import { OVERVIEW_MODULE_KEYS, STEP_TABLE_COLUMN_KEYS, TOPBAR_SLOT_KEYS, + normalizeCliStatusLineSlots, normalizeHoverModules, normalizeModelDisplayMode, normalizeOrchestratorIdMode, @@ -53,6 +56,7 @@ import { normalizeWeeklyLimitMode, normalizeWindowMountMode, parseStepTokenComboSegments, + resolveEffectiveCliStatusLineSlots, } from '../../shared/settings-normalization.mjs'; import { LOCAL_ENDPOINT_ID, @@ -438,6 +442,8 @@ function reconcileIncomingTelemetrySettings(payload, reqSettingsRev) { export const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS; export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS; +export const CLIENT_CLI_STATUSLINE_PRESETS = CLI_STATUSLINE_PRESETS; +export const DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS = DEFAULT_CLI_STATUSLINE_SLOTS; export const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS; export const DEFAULT_CLIENT_OVERVIEW_MODULES = DEFAULT_OVERVIEW_MODULES; export const DEFAULT_CLIENT_HOVER_MODULES = DEFAULT_HOVER_MODULES; @@ -456,6 +462,8 @@ export const normalizeClientPopoverWidthMode = normalizePopoverWidthMode; export const normalizeClientPopoverWidth = normalizePopoverWidth; export const normalizeClientModelDisplayMode = normalizeModelDisplayMode; export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; +export const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots; +export const resolveEffectiveClientCliStatusLineSlots = resolveEffectiveCliStatusLineSlots; export const normalizeClientHoverModules = normalizeHoverModules; export const normalizeClientOverviewModules = normalizeOverviewModules; export const normalizeClientOverviewMetrics = normalizeOverviewMetrics; @@ -544,6 +552,7 @@ export function isEquivalentTelemetry(prev, next) { if ((pSet?.enableCliStatusLine !== false) !== (nSet?.enableCliStatusLine !== false)) { return false; } + if (!sameArr(pSet?.cliStatusLineSlots, nSet?.cliStatusLineSlots)) return false; if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) { return false; } @@ -575,6 +584,16 @@ export function isEquivalentTelemetry(prev, next) { ) { return false; } + const pCli = prev.cliStatusLine; + const nCli = next.cliStatusLine; + if ( + Boolean(pCli?.installed) !== Boolean(nCli?.installed) || + Boolean(pCli?.configured) !== Boolean(nCli?.configured) || + Boolean(pCli?.preservedCustom) !== Boolean(nCli?.preservedCustom) || + String(pCli?.managedFlags || '') !== String(nCli?.managedFlags || '') + ) { + return false; + } const pCloud = prev.cloudStatus; const nCloud = next.cloudStatus; if ( @@ -1712,6 +1731,9 @@ export async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'cliStatusLineSlots')) { + safePatch.cliStatusLineSlots = normalizeClientCliStatusLineSlots(safePatch.cliStatusLineSlots); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'hoverModules')) { safePatch.hoverModules = normalizeClientHoverModules(safePatch.hoverModules); } @@ -1957,6 +1979,24 @@ export async function triggerBridgeHostRelaunch() { } } +export async function triggerCliStatusLineAction(action) { + const res = await callSidecarApi('/api/settings', { + method: 'POST', + body: { __cliStatusLineAction: String(action || 'force_install') }, + }); + const cur = telemetryStore.getState().telemetry; + if (cur && res && typeof res === 'object') { + const nextTelemetry = { + ...cur, + ...(res.cliStatusLine ? { cliStatusLine: res.cliStatusLine } : {}), + ...(res.settings ? { settings: { ...cur.settings, ...res.settings } } : {}), + }; + telemetryStore.setState({ telemetry: nextTelemetry }); + } + void fetchTelemetry({ force: true }).catch(() => {}); + return res; +} + export async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 511072f..7e8c73c 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -995,3 +995,180 @@ .settings-hidden-file-input { display: none !important; } + +/* --- Antigravity CLI 底部状态胶囊专属配置块(仅检测到 CLI 时展示) --- */ +.cli-statusline-group { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.cli-statusline-group[hidden], +.cli-statusline-detail[hidden] { + display: none !important; +} + +.cli-statusline-detail { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.cli-status-preview { + display: flex; + align-items: center; + flex-wrap: nowrap; + gap: 0; + min-height: 30px; + padding: 5px 10px; + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-bg); + font-family: var(--font-mono); + font-size: var(--fs-sm); + font-variant-numeric: tabular-nums; + line-height: 1.3; + white-space: nowrap; + overflow-x: auto; + user-select: none; +} + +.cli-preview-multi { + display: inline-flex; + align-items: center; + gap: 5px; + margin-right: 12px; + color: var(--text-secondary); +} + +.cli-preview-multi[hidden], +.cli-preview-slot[hidden], +.cli-preview-sep[hidden] { + display: none !important; +} + +.cli-preview-dot { + color: var(--metric-good); + font-size: var(--fs-xs); +} + +.cli-preview-sep { + margin: 0 7px; + color: var(--text-muted); + opacity: 0.72; +} + +.cli-preview-slot { + color: var(--text-primary); + font-weight: 500; +} + +.cli-preview-slot.tone-good { + color: var(--metric-good); +} + +.cli-preview-slot.tone-info { + color: var(--metric-info); +} + +.cli-preview-slot.tone-accent { + color: var(--accent-primary); +} + +.cli-preview-slot.tone-muted { + color: var(--text-secondary); +} + +.cli-preview-prefix { + color: var(--text-secondary); + font-weight: 400; +} + +.cli-preview-bar-fill { + letter-spacing: 0; +} + +.cli-preview-bar-empty { + color: var(--text-muted); + opacity: 0.65; + letter-spacing: 0; +} + +.cli-preview-val { + color: var(--text-primary); +} + +.cli-preview-slot.tone-good .cli-preview-val, +.cli-preview-slot.tone-good .cli-preview-bar-fill { + color: var(--metric-good); +} + +.cli-preview-slot.tone-info .cli-preview-val, +.cli-preview-slot.tone-info .cli-preview-bar-fill { + color: var(--metric-info); +} + +.cli-preview-slot.tone-accent .cli-preview-bar-fill { + color: var(--accent-primary); +} + +.cli-preview-slot.tone-muted .cli-preview-val { + color: var(--text-secondary); +} + +.cli-status-footer { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 6px; +} + +.cli-status-footer[hidden] { + display: none !important; +} + +.cli-status-hint.is-warn { + color: var(--metric-warn); +} + +.cli-status-action-btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 10px; + border-radius: var(--radius-xs); + border: 1px solid var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-size: var(--fs-sm); + font-weight: 600; + cursor: pointer; + white-space: nowrap; + transition: + background-color var(--dur-instant) var(--ease-fast), + opacity var(--dur-instant) var(--ease-fast); +} + +.cli-status-action-btn:hover:not(:disabled) { + background: color-mix(in srgb, var(--accent-primary) 20%, transparent); +} + +.cli-status-action-btn.is-warn { + border-color: color-mix(in srgb, var(--metric-warn) 48%, var(--border-hairline)); + background: color-mix(in srgb, var(--metric-warn) 14%, transparent); + color: var(--metric-warn); +} + +.cli-status-action-btn.is-warn:hover:not(:disabled) { + background: color-mix(in srgb, var(--metric-warn) 22%, transparent); +} + +.cli-status-action-btn:disabled { + opacity: 0.65; + cursor: wait; +} + +.cli-status-action-btn[hidden] { + display: none !important; +} diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index 76dace3..101752a 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -107,7 +107,8 @@ export const SettingsView = defineComponent({ structureTab.refs.renderSettings( settings, telemetry?.windowBridge, - telemetry?.hostPlatform + telemetry?.hostPlatform, + telemetry?.cliStatusLine ); } } else if (settingsSubTab === 'other') { @@ -132,6 +133,7 @@ export const SettingsView = defineComponent({ (st) => ({ settings: st.telemetry?.settings, windowBridge: st.telemetry?.windowBridge, + cliStatusLine: st.telemetry?.cliStatusLine, hostPlatform: st.telemetry?.hostPlatform, cloudStatus: st.telemetry?.cloudStatus, contextWindowModels: st.telemetry?.contextWindowModels, diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index 4aaa801..b9bb992 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -29,6 +29,7 @@ import { DEFAULT_CLIENT_TOPBAR_SLOTS, MAX_CLIENT_POPOVER_WIDTH, MIN_CLIENT_POPOVER_WIDTH, + normalizeClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewMetrics, normalizeClientOverviewModules, @@ -38,7 +39,9 @@ import { normalizeClientStepTokenComboFormat, normalizeClientTopbarSlots, normalizeClientWindowMountMode, + resolveEffectiveClientCliStatusLineSlots, saveSettingsPatch, + triggerCliStatusLineAction, } from '../../store/telemetryStore.js'; import { getVisibleMonitorView, uiStore } from '../../store/uiStore.js'; import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js'; @@ -100,6 +103,91 @@ function isSameList(a, b) { return true; } +function buildCliPreviewMiniBar(pct, width = 8, emptyChar = '⢕') { + const clamped = Math.max(0, Math.min(100, Number(pct))); + let filled = Math.round((clamped / 100) * width); + if (clamped > 0 && filled === 0) filled = 1; + if (clamped < 95 && filled >= width) filled = Math.max(0, width - 1); + return { + barFilled: '█'.repeat(filled), + barEmpty: emptyChar.repeat(Math.max(0, width - filled)), + }; +} + +function formatCliPreviewSlot(slotKey, isEn) { + switch (slotKey) { + case 'tps': + return { prefix: '', barFilled: '', barEmpty: '', text: '68.4 t/s', tone: 'good' }; + case 'avg_tps': + return { + prefix: '', + barFilled: '', + barEmpty: '', + text: isEn ? 'avg 54.0' : '均 54.0', + tone: 'info', + }; + case 'ttft': + return { prefix: '', barFilled: '', barEmpty: '', text: '1.1s', tone: 'good' }; + case 'cost': + return { prefix: '', barFilled: '', barEmpty: '', text: '$0.040', tone: 'normal' }; + case 'session_cost': + return { prefix: '', barFilled: '', barEmpty: '', text: '$0.42', tone: 'normal' }; + case 'cache_hit': + return { + prefix: '', + barFilled: '', + barEmpty: '', + text: isEn ? 'cache 92%' : '缓 92%', + tone: 'good', + }; + case 'session_tokens': + return { prefix: '', barFilled: '', barEmpty: '', text: '142K tok', tone: 'muted' }; + case 'quota_auto': + return { + prefix: isEn ? '5h ' : '余 ', + ...buildCliPreviewMiniBar(64, 8, '⣿'), + text: ' 64%', + tone: 'good', + }; + case 'gemini_5h': + return { + prefix: 'G5h ', + ...buildCliPreviewMiniBar(64, 8, '⣿'), + text: ' 64%', + tone: 'good', + }; + case 'gemini_weekly': + return { + prefix: isEn ? 'Gw ' : 'G周 ', + ...buildCliPreviewMiniBar(88, 8, '⣿'), + text: ' 88%', + tone: 'good', + }; + case 'claude_5h': + return { + prefix: 'C5h ', + ...buildCliPreviewMiniBar(96, 8, '⣿'), + text: ' 96%', + tone: 'good', + }; + case 'claude_weekly': + return { + prefix: isEn ? 'Cw ' : 'C周 ', + ...buildCliPreviewMiniBar(99, 8, '⣿'), + text: ' 99%', + tone: 'good', + }; + case 'context': + default: + return { + prefix: isEn ? 'Ctx ' : '上下文 ', + ...buildCliPreviewMiniBar(56), + text: ' 56%', + tone: 'accent', + }; + } +} + export const SettingsStructureTab = defineComponent({ name: 'SettingsStructureTab', setup({ props, onCleanup }) { @@ -108,6 +196,7 @@ export const SettingsStructureTab = defineComponent({ let draftPopoverWidthMode = 'auto'; let draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH; let draftEnableCliStatusLine = true; + let draftCliStatusLineSlots = null; let draftShowTopbarMulti = true; let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES]; @@ -121,8 +210,16 @@ export const SettingsStructureTab = defineComponent({ let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS]; let latestSettings = null; let latestWindowBridge = null; + let latestCliStatusLine = null; let latestHostPlatform = 'win32'; + function getEffectiveDraftCliSlots() { + return resolveEffectiveClientCliStatusLineSlots({ + cliStatusLineSlots: draftCliStatusLineSlots, + topbarCapsuleSlots: draftTopbarSlots, + }); + } + function isStructureVisible() { const st = uiStore.getState(); return getVisibleMonitorView(st) === 'settings' && st.settingsSubTab === 'structure'; @@ -254,6 +351,50 @@ export const SettingsStructureTab = defineComponent({ className: 'form-label', text: t('settings.str.cliCapsuleToggle'), }); + const cliSlotsLabelEl = h('span', { + className: 'form-label', + text: t('settings.str.cliSlotsLabel'), + }); + const cliStatusHintEl = h('span', { + className: 'settings-hint-text cli-status-hint', + }); + let cliActionBusy = false; + let activeCliStatusAction = ''; + const cliStatusActionBtn = h('button', { + type: 'button', + className: 'cli-status-action-btn', + hidden: true, + text: t('settings.str.cliRestoreBtn'), + onClick: async () => { + if (cliActionBusy || !activeCliStatusAction) return; + cliActionBusy = true; + const actionToRun = activeCliStatusAction; + patchAttr(cliStatusActionBtn, 'disabled', true); + patchText(cliStatusActionBtn, t('settings.str.cliRestoringBtn')); + mountSection.refs.showStatus(t('settings.saving'), 0); + try { + const res = await triggerCliStatusLineAction(actionToRun); + if (res?.cliStatusLine) { + latestCliStatusLine = res.cliStatusLine; + } + if (res?.settings && typeof res.settings === 'object') { + latestSettings = { ...(latestSettings || {}), ...res.settings }; + draftEnableCliStatusLine = latestSettings.enableCliStatusLine !== false; + } + mountSection.refs.showStatus( + res?.ok === false ? t('settings.saveFailed') : t('settings.saved'), + 1800 + ); + } catch { + mountSection.refs.showStatus(t('settings.saveFailed'), 2500); + } finally { + cliActionBusy = false; + patchAttr(cliStatusActionBtn, 'disabled', false); + syncMountSectionMeta(); + props.onLayoutChange?.(); + } + }, + }); const capsuleSlotsLabelEl = h('span', { className: 'form-label', text: t('settings.str.capsuleSlotsLabel'), @@ -334,12 +475,85 @@ export const SettingsStructureTab = defineComponent({ onUpdateModelValue: (val) => { draftEnableCliStatusLine = val !== 'off'; syncMountSectionMeta(); + props.onLayoutChange?.(); void persistStructurePatch(mountSection, { enableCliStatusLine: draftEnableCliStatusLine, }); }, }); + const cliPreviewMultiTextEl = h('span', { + text: t('settings.str.cliPreviewRunning', { count: 2 }), + }); + const cliPreviewMultiEl = h('span', { className: 'cli-preview-multi' }, [ + h('span', { className: 'cli-preview-dot', 'aria-hidden': 'true', text: '●' }), + cliPreviewMultiTextEl, + ]); + const cliPreviewSlotParts = []; + const cliPreviewSepEls = []; + const cliPreviewChildren = [cliPreviewMultiEl]; + for (let i = 0; i < 6; i += 1) { + if (i > 0) { + const sepEl = h('span', { + className: 'cli-preview-sep', + 'aria-hidden': 'true', + text: '|', + }); + cliPreviewSepEls.push(sepEl); + cliPreviewChildren.push(sepEl); + } + const prefixEl = h('span', { className: 'cli-preview-prefix' }); + const barFillEl = h('span', { className: 'cli-preview-bar-fill' }); + const barEmptyEl = h('span', { className: 'cli-preview-bar-empty' }); + const valueEl = h('span', { className: 'cli-preview-val' }); + const slotEl = h('span', { className: 'cli-preview-slot' }, [ + prefixEl, + barFillEl, + barEmptyEl, + valueEl, + ]); + cliPreviewSlotParts.push({ slotEl, prefixEl, barFillEl, barEmptyEl, valueEl }); + cliPreviewChildren.push(slotEl); + } + const cliPreviewEl = h('div', { className: 'cli-status-preview' }, cliPreviewChildren); + + const cliSlotsList = EditableSlotList({ + items: getEffectiveDraftCliSlots(), + options: getCapsuleMetricOptions(), + minItems: 1, + maxItems: 6, + addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), + onPreview: (previewItems) => { + draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(previewItems); + refreshCliPreview(); + }, + onChange: (nextItems) => { + draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(nextItems); + syncMountSectionMeta(); + props.onLayoutChange?.(); + void persistStructurePatch(mountSection, { + cliStatusLineSlots: draftCliStatusLineSlots, + }); + }, + }); + + const cliStatusFooterEl = h('div', { className: 'cli-status-footer', hidden: true }, [ + cliStatusHintEl, + cliStatusActionBtn, + ]); + + const cliStatusDetailEl = h('div', { className: 'cli-statusline-detail' }, [ + cliPreviewEl, + h('div', { className: 'form-row' }, [cliSlotsLabelEl, cliSlotsList.el]), + cliStatusFooterEl, + ]); + + const cliStatusGroupEl = h('div', { className: 'cli-statusline-group', hidden: true }, [ + h('div', { className: 'settings-divider' }), + h('div', { className: 'settings-inline-row' }, [cliCapsuleLabelEl, cliCapsuleToggle.el]), + cliStatusDetailEl, + ]); + const topbarSlotsList = EditableSlotList({ items: draftTopbarSlots, options: getCapsuleMetricOptions(), @@ -373,6 +587,7 @@ export const SettingsStructureTab = defineComponent({ draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH; popoverWidthStepper.setProps({ modelValue: DEFAULT_CLIENT_POPOVER_WIDTH }); draftEnableCliStatusLine = true; + draftCliStatusLineSlots = null; draftShowTopbarMulti = true; draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS]; syncMountSectionMeta(); @@ -385,6 +600,7 @@ export const SettingsStructureTab = defineComponent({ popoverWidthMode: 'auto', popoverWidth: DEFAULT_CLIENT_POPOVER_WIDTH, enableCliStatusLine: true, + cliStatusLineSlots: null, showTopbarMultiSession: true, topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS], }, @@ -410,17 +626,44 @@ export const SettingsStructureTab = defineComponent({ multiToggleLabelEl, multiSessionToggle.el, ]), - h('div', { className: 'settings-inline-row' }, [ - cliCapsuleLabelEl, - cliCapsuleToggle.el, - ]), h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]), + cliStatusGroupEl, ], }); + function refreshCliPreview() { + const effectiveSlots = getEffectiveDraftCliSlots(); + const isEn = getEffectiveLocale() === 'en-US'; + patchAttr(cliPreviewMultiEl, 'hidden', !draftShowTopbarMulti); + patchText(cliPreviewMultiTextEl, t('settings.str.cliPreviewRunning', { count: 2 })); + for (let i = 0; i < cliPreviewSlotParts.length; i += 1) { + const parts = cliPreviewSlotParts[i]; + const sepEl = i > 0 ? cliPreviewSepEls[i - 1] : null; + const key = effectiveSlots[i]; + const visible = Boolean(key); + patchAttr(parts.slotEl, 'hidden', !visible); + if (sepEl) patchAttr(sepEl, 'hidden', !visible); + if (visible) { + const item = formatCliPreviewSlot(key, isEn); + patchAttr(parts.slotEl, 'data-metric', key); + patchText(parts.prefixEl, item.prefix || ''); + patchText(parts.barFillEl, item.barFilled || ''); + patchText(parts.barEmptyEl, item.barEmpty || ''); + patchText(parts.valueEl, item.text || ''); + patchClasses(parts.slotEl, { + 'tone-good': item.tone === 'good', + 'tone-info': item.tone === 'info', + 'tone-accent': item.tone === 'accent', + 'tone-muted': item.tone === 'muted', + }); + } + } + } + function refreshMountPreview() { if (!isStructureVisible() || activeThirdTab !== 'mount') return; capsulePreviewWidget.refs.update({ data: buildDraftTelemetry() }); + refreshCliPreview(); } function syncMountSectionMeta() { @@ -448,10 +691,53 @@ export const SettingsStructureTab = defineComponent({ modelValue: draftShowTopbarMulti ? 'show' : 'hide', options: getMultiToggleOptions(), }); + const cliInstalled = Boolean(latestCliStatusLine?.installed); + patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled); cliCapsuleToggle.setProps({ modelValue: draftEnableCliStatusLine ? 'on' : 'off', options: getEnableToggleOptions(), }); + patchAttr(cliStatusDetailEl, 'hidden', !draftEnableCliStatusLine); + const effectiveCliSlots = getEffectiveDraftCliSlots(); + cliSlotsList.refs.setProps({ + items: effectiveCliSlots, + options: getCapsuleMetricOptions(), + addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), + }); + const preservedCustom = Boolean(latestCliStatusLine?.preservedCustom); + const isConfigured = Boolean(latestCliStatusLine?.configured); + const hasInlineSlotFlags = /(?:^|\s)--(?:slots|preset)(?:=|\s|$)/i.test( + String(latestCliStatusLine?.managedFlags || '') + ); + const isPausedInCli = cliInstalled && !preservedCustom && !isConfigured && draftEnableCliStatusLine; + const cliHintText = preservedCustom + ? t('settings.str.cliCustomCmdHint') + : isPausedInCli + ? t('settings.str.cliPausedHint') + : hasInlineSlotFlags + ? t('settings.str.cliFlagsOverrideHint') + : ''; + patchAttr(cliStatusFooterEl, 'hidden', !cliHintText); + patchClasses(cliStatusHintEl, { 'is-warn': preservedCustom || isPausedInCli }); + patchText(cliStatusHintEl, cliHintText); + activeCliStatusAction = preservedCustom || isPausedInCli + ? 'force_install' + : hasInlineSlotFlags + ? 'clear_flags' + : ''; + patchAttr(cliStatusActionBtn, 'hidden', !activeCliStatusAction); + patchClasses(cliStatusActionBtn, { 'is-warn': preservedCustom }); + if (!cliActionBusy && activeCliStatusAction) { + patchText( + cliStatusActionBtn, + preservedCustom + ? t('settings.str.cliRestoreBtn') + : isPausedInCli + ? t('settings.str.cliEnableBtn') + : t('settings.str.cliClearFlagsBtn') + ); + } + refreshCliPreview(); topbarSlotsList.refs.setProps({ items: draftTopbarSlots, options: getCapsuleMetricOptions(), @@ -465,6 +751,7 @@ export const SettingsStructureTab = defineComponent({ draftPopoverWidthMode === 'auto' && draftPopoverWidth === DEFAULT_CLIENT_POPOVER_WIDTH && draftEnableCliStatusLine === true && + draftCliStatusLineSlots === null && draftShowTopbarMulti === true && isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS); mountSection.refs.setResetDisabled(isDefault); @@ -1030,12 +1317,14 @@ export const SettingsStructureTab = defineComponent({ function renderSettings( settings, windowBridge = latestWindowBridge, - hostPlatform = latestHostPlatform + hostPlatform = latestHostPlatform, + cliStatusLine = latestCliStatusLine ) { if (!settings) return; latestSettings = settings; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; + if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay @@ -1043,6 +1332,7 @@ export const SettingsStructureTab = defineComponent({ draftPopoverWidthMode = normalizeClientPopoverWidthMode(settings.popoverWidthMode); draftPopoverWidth = normalizeClientPopoverWidth(settings.popoverWidth); draftEnableCliStatusLine = settings.enableCliStatusLine !== false; + draftCliStatusLineSlots = normalizeClientCliStatusLineSlots(settings.cliStatusLineSlots); draftShowTopbarMulti = settings.showTopbarMultiSession !== false; draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots); draftHoverModules = normalizeClientHoverModules(settings.hoverModules); @@ -1077,6 +1367,7 @@ export const SettingsStructureTab = defineComponent({ popoverWidthStepper.setProps({ ariaLabel: t('settings.str.popoverWidthLabel') }); patchText(multiToggleLabelEl, t('settings.str.multiToggle')); patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle')); + patchText(cliSlotsLabelEl, t('settings.str.cliSlotsLabel')); patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel')); hoverSection.refs.setTitle(t('settings.str.hoverSection')); @@ -1147,6 +1438,7 @@ export const SettingsStructureTab = defineComponent({ popoverWidthModeToggle.destroy(); multiSessionToggle.destroy(); cliCapsuleToggle.destroy(); + cliSlotsList.destroy(); topbarSlotsList.destroy(); hoverModulesList.destroy(); overviewModulesList.destroy(); @@ -1173,6 +1465,13 @@ export const SettingsStructureTab = defineComponent({ windowMountSelect, multiSessionToggle, cliCapsuleToggle, + cliStatusGroupEl, + cliStatusDetailEl, + cliPreviewEl, + cliSlotsList, + cliStatusFooterEl, + cliStatusHintEl, + cliStatusActionBtn, topbarSlotsList, hoverModulesList, overviewModulesList, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index c1ffac8..b96d084 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -5704,6 +5704,183 @@ html[data-standalone="true"] .app-shell { display: none !important; } +/* --- Antigravity CLI 底部状态胶囊专属配置块(仅检测到 CLI 时展示) --- */ +.cli-statusline-group { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.cli-statusline-group[hidden], +.cli-statusline-detail[hidden] { + display: none !important; +} + +.cli-statusline-detail { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.cli-status-preview { + display: flex; + align-items: center; + flex-wrap: nowrap; + gap: 0; + min-height: 30px; + padding: 5px 10px; + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-bg); + font-family: var(--font-mono); + font-size: var(--fs-sm); + font-variant-numeric: tabular-nums; + line-height: 1.3; + white-space: nowrap; + overflow-x: auto; + user-select: none; +} + +.cli-preview-multi { + display: inline-flex; + align-items: center; + gap: 5px; + margin-right: 12px; + color: var(--text-secondary); +} + +.cli-preview-multi[hidden], +.cli-preview-slot[hidden], +.cli-preview-sep[hidden] { + display: none !important; +} + +.cli-preview-dot { + color: var(--metric-good); + font-size: var(--fs-xs); +} + +.cli-preview-sep { + margin: 0 7px; + color: var(--text-muted); + opacity: 0.72; +} + +.cli-preview-slot { + color: var(--text-primary); + font-weight: 500; +} + +.cli-preview-slot.tone-good { + color: var(--metric-good); +} + +.cli-preview-slot.tone-info { + color: var(--metric-info); +} + +.cli-preview-slot.tone-accent { + color: var(--accent-primary); +} + +.cli-preview-slot.tone-muted { + color: var(--text-secondary); +} + +.cli-preview-prefix { + color: var(--text-secondary); + font-weight: 400; +} + +.cli-preview-bar-fill { + letter-spacing: 0; +} + +.cli-preview-bar-empty { + color: var(--text-muted); + opacity: 0.65; + letter-spacing: 0; +} + +.cli-preview-val { + color: var(--text-primary); +} + +.cli-preview-slot.tone-good .cli-preview-val, +.cli-preview-slot.tone-good .cli-preview-bar-fill { + color: var(--metric-good); +} + +.cli-preview-slot.tone-info .cli-preview-val, +.cli-preview-slot.tone-info .cli-preview-bar-fill { + color: var(--metric-info); +} + +.cli-preview-slot.tone-accent .cli-preview-bar-fill { + color: var(--accent-primary); +} + +.cli-preview-slot.tone-muted .cli-preview-val { + color: var(--text-secondary); +} + +.cli-status-footer { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 6px; +} + +.cli-status-footer[hidden] { + display: none !important; +} + +.cli-status-hint.is-warn { + color: var(--metric-warn); +} + +.cli-status-action-btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 10px; + border-radius: var(--radius-xs); + border: 1px solid var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-size: var(--fs-sm); + font-weight: 600; + cursor: pointer; + white-space: nowrap; + transition: + background-color var(--dur-instant) var(--ease-fast), + opacity var(--dur-instant) var(--ease-fast); +} + +.cli-status-action-btn:hover:not(:disabled) { + background: color-mix(in srgb, var(--accent-primary) 20%, transparent); +} + +.cli-status-action-btn.is-warn { + border-color: color-mix(in srgb, var(--metric-warn) 48%, var(--border-hairline)); + background: color-mix(in srgb, var(--metric-warn) 14%, transparent); + color: var(--metric-warn); +} + +.cli-status-action-btn.is-warn:hover:not(:disabled) { + background: color-mix(in srgb, var(--metric-warn) 22%, transparent); +} + +.cli-status-action-btn:disabled { + opacity: 0.65; + cursor: wait; +} + +.cli-status-action-btn[hidden] { + display: none !important; +} + /* --- src/styles/overlay.css --- */ /* * 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css). diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 85f2391..7967a2c 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -207,6 +207,6 @@ export function backendHarness({ return {ok:true,json:async()=>data}; }, }; - vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeCliStatusLineSlots,resolveEffectiveCliStatusLineSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,extractManagedCliStatusLineFlags,getCliStatusLineRuntimeStatus,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx); return {...ctx.api,state}; } diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index cfacc5f..269b3a2 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -1966,7 +1966,7 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from color: false, } ); - assert.equal(plainCapsule, '● 0 运行中 11.8s | 38.1 t/s | 余 57% | ◎ 17%'); + assert.equal(plainCapsule, '● 0 运行中 11.8s | 38.1 t/s | 余 █████⣿⣿⣿ 57% | 上下文 █⢕⢕⢕⢕⢕⢕⢕ 17%'); const ansiCapsule = h.formatCliStatusLineCapsule( { @@ -1989,7 +1989,7 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from 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%' + '● 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 @@ -2017,10 +2017,44 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from 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.includes('● 2 运行中 5.6s | 22.0 t/s | 余 ████⣿⣿⣿⣿ 54% | 上下文 █⢕⢕⢕⢕⢕⢕⢕ 2%'), + 'Keeps full 8-cell Braille bars and full chrome when 4 slots fit in 120 columns' + ); 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'); + // Mid-width 115-column terminal steps down 8-cell bars to 5-cell bars before trimming chrome + const inlineBar115 = 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: 115, + cycleMode: 'auto', + modelDisplayName: 'Gemini 4 Hydrogen (Medium)', + modelEffort: 'medium', + } + ); + const plainBar115 = inlineBar115.replace(/\x1b\[[0-9;]*m/g, ''); + assert.ok(plainBar115.startsWith('? for shortcuts '), 'Keeps ? for shortcuts when stepping down to 5-cell bars'); + assert.ok( + plainBar115.includes('● 2 运行中 5.6s | 22.0 t/s | 余 ███⣿⣿ 54% | 上下文 █⢕⢕⢕⢕ 2%'), + 'Gracefully steps down 8-cell bars to 5-cell bars on 115-col terminal while keeping full chrome' + ); + assert.ok(plainBar115.endsWith(' auto · Gemini 4 Hydrogen · medium'), 'Keeps full right chrome on 115-col terminal'); + assert.equal(h.cliDisplayWidth(inlineBar115), 114, '115-col bar fits cleanly within terminalWidth - 1'); + // Narrow 80-column terminal gracefully compacts without wrapping const inlineBar80 = h.formatCliStatusLineCapsule( { @@ -2044,7 +2078,7 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from } ); 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%')); + 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))); @@ -2193,7 +2227,7 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from input: stdinPayload, encoding: 'utf8', }).trim(); - assert.equal(capsuleOut, '● 0 运行中 1.8s | 38.1 t/s | 余 57% | ◎ 17%'); + 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'); @@ -2231,7 +2265,7 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from 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.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); @@ -2242,7 +2276,7 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from input: stdinPayload, encoding: 'utf8', }).trim(); - assert.equal(cmdCapsuleOut, '● 0 运行中 1.8s | 38.1 t/s | 余 57% | ◎ 17%'); + assert.equal(cmdCapsuleOut, '● 0 运行中 1.8s | 38.1 t/s | 余 █████⣿⣿⣿ 57% | 上下文 █⢕⢕⢕⢕⢕⢕⢕ 17%'); const spaceDir = join(tempRoot, 'Dir With Spaces'); mkdirSync(spaceDir, { recursive: true }); @@ -2258,7 +2292,7 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from input: stdinPayload, encoding: 'utf8', }).trim(); - assert.equal(autorunOut, '● 0 运行中 1.8s | 38.1 t/s | 余 57% | ◎ 17%'); + 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 @@ -2302,6 +2336,381 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from } }); +test('CLI statusLine v1.5.4 upgrades: /statusline inline flags, preserved managed flags, model-aware quota pool, empty-session cleanup, anomaly badge, and narrow-terminal shedding', async () => { + const h = backendHarness(); + const { + buildMergedCliCapsuleContext, + parseCliStatusLineArgs, + } = await import('../cli-statusline.mjs'); + + // 1. Slot presets, comma lists (1-6 slots), and backwards-compatible fallback + assert.deepEqual( + [...h.resolveEffectiveCliStatusLineSlots({ topbarCapsuleSlots: ['tps', 'ttft', 'context'], cliStatusLineSlots: null })], + ['tps', 'ttft', 'session_cost', 'quota_auto', 'context'] + ); + assert.deepEqual( + [...h.resolveEffectiveCliStatusLineSlots({ topbarCapsuleSlots: ['ttft', 'tps', 'quota_auto', 'context'], cliStatusLineSlots: null })], + ['ttft', 'tps', 'quota_auto', 'context'] + ); + assert.deepEqual([...h.normalizeCliStatusLineSlots('full')], [ + 'tps', 'ttft', 'cache_hit', 'session_cost', 'quota_auto', 'context', + ]); + assert.deepEqual([...h.normalizeCliStatusLineSlots('compact')], ['tps', 'ttft', 'context']); + assert.equal(h.normalizeCliStatusLineSlots('auto'), null); + + // 2. Managed flag extraction & preservation across daemon sync + assert.equal( + h.extractManagedCliStatusLineFlags('node C:/plugin/cli-statusline.mjs --slots tps,cache_hit,context --no-multi'), + '--slots tps,cache_hit,context --no-multi' + ); + assert.equal( + h.extractManagedCliStatusLineFlags("node --input-type=module -e import('file:///C:/dir%20a/cli-statusline.mjs#autorun') -- --preset full"), + '--preset full' + ); + const preservedFlags = h.applyCliStatusLineToSettingsObject( + { + statusLine: { + type: 'command', + command: 'node C:/plugin/cli-statusline.mjs --preset full --no-multi', + enabled: true, + padding: 0, + stack_with_default: true, + }, + }, + { enabled: true, command: 'node C:/plugin/cli-statusline.mjs' } + ); + assert.equal(preservedFlags.changed, true); + assert.equal( + preservedFlags.object.statusLine.command, + 'node C:/plugin/cli-statusline.mjs --preset full --no-multi', + 'User flags appended via /statusline must survive daemon statusLine reconciliation' + ); + + // 3. Inline flag parsing + const parsedFlags = parseCliStatusLineArgs([ + '--slots', 'tps,cache_hit,context', + '--no-multi', + '--no-anomaly', + '--lang=en-US', + '--no-color', + ]); + assert.equal(parsedFlags.slotsRaw, 'tps,cache_hit,context'); + assert.equal(parsedFlags.showMultiSession, false); + assert.equal(parsedFlags.showAnomaly, false); + assert.equal(parsedFlags.language, 'en-US'); + assert.equal(parsedFlags.noColor, true); + + // 4. Model-aware active quota pool & expanded agent_state detection (working / tool_use) + const mergedClaudeCtx = buildMergedCliCapsuleContext({ + stdinData: { + agent_state: 'tool_use', + model: { id: 'claude-opus-4-6-thinking', display_name: 'Claude Opus 4.6 (Thinking)' }, + context_window: { used_percentage: 22 }, + }, + snapshot: { + updatedAtMs: Date.now(), + runningCount: 0, + quotas: { + activePool: { poolKey: 'Gemini', poolLabel: 'Gemini', remainingPct: 25 }, + pools: [ + { poolKey: 'Gemini', poolLabel: 'Gemini', remainingPct: 25, models: ['Gemini 4 Neon (XHigh)'] }, + { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', remainingPct: 100, models: ['Claude Opus 4.6 (Thinking)'] }, + ], + }, + }, + }); + assert.equal(mergedClaudeCtx.isRunning, true); + assert.equal(mergedClaudeCtx.runningCount, 1); + assert.equal(mergedClaudeCtx.quotas.activePool.poolKey, 'Claude & GPT'); + assert.equal(mergedClaudeCtx.quotas.activePool.remainingPct, 100); + + // 5. Fresh session (stepCount: 0) hides empty --s / -- placeholders while keeping status, quota, and context + const freshBar = h.formatCliStatusLineCapsule( + { + hasTelemetry: true, + stepCount: 0, + isRunning: false, + runningCount: 0, + tps: null, + ttft: null, + sessionCost: null, + usedPct: 16, + quotas: { activePool: { remainingPct: 98 } }, + }, + { + slots: ['tps', 'ttft', 'session_cost', 'quota_auto', 'context'], + language: 'zh-CN', + color: false, + } + ); + assert.equal(freshBar, '● 0 运行中 空闲 | 余 ████████ 98% | 上下文 █⢕⢕⢕⢕⢕⢕⢕ 16%'); + + // 5b. Dedicated 5h / weekly / context 8-cell mini progress bars in zh-CN & en-US + const quotaBarCtx = { + hasTelemetry: true, + stepCount: 3, + usedPct: 56, + quotas: { + pools: [ + { poolKey: 'Gemini', family: 'Gemini', remainingPct: 64, weeklyRemainingPct: 88 }, + { poolKey: 'Claude & GPT', family: 'Claude & GPT', remainingPct: 96, weeklyRemainingPct: 14 }, + ], + }, + }; + assert.equal( + h.formatCliStatusLineCapsule(quotaBarCtx, { + slots: ['gemini_5h', 'gemini_weekly', 'claude_5h', 'claude_weekly', 'context'], + showMultiSession: false, + language: 'zh-CN', + color: false, + }), + 'G5h █████⣿⣿⣿ 64% | G周 ███████⣿ 88% | C5h ████████ 96% | C周 █⣿⣿⣿⣿⣿⣿⣿ 14% | 上下文 ████⢕⢕⢕⢕ 56%' + ); + assert.equal( + h.formatCliStatusLineCapsule(quotaBarCtx, { + slots: ['gemini_weekly', 'claude_weekly', 'context'], + showMultiSession: false, + language: 'en-US', + color: false, + }), + 'Gw ███████⣿ 88% | Cw █⣿⣿⣿⣿⣿⣿⣿ 14% | Ctx ████⢕⢕⢕⢕ 56%' + ); + + // 5c. Local SQLite WAITING step immediately turns CLI dot amber even while Desktop snapshot is still false + const waitingFromLocalDb = buildMergedCliCapsuleContext({ + stdinData: { agent_state: 'running' }, + localMetrics: { + found: true, + cascadeId: '11111111-1111-1111-1111-111111111111', + dbMtimeMs: Date.now(), + targetIsRunning: true, + targetIsWaiting: true, + targetWaitingApprovalFresh: true, + runningRootCount: 1, + stepCount: 5, + }, + snapshot: { + updatedAtMs: Date.now() - 1000, + runningCount: 1, + hasWaiting: false, + waitingCascadeIds: [], + }, + }); + assert.equal(waitingFromLocalDb.runningCount, 1); + assert.equal(waitingFromLocalDb.hasWaiting, true); + const amberDotLine = h.formatCliStatusLineCapsule(waitingFromLocalDb, { + slots: ['tps', 'context'], + language: 'zh-CN', + color: true, + }); + assert.ok(amberDotLine.includes('\x1b[38;2;251;191;36m● '), 'Waiting session dot must render amber SGR'); + + // Once local DB resumes (newer than stale Desktop snapshot), dot returns to green immediately + const resumedFromLocalDb = buildMergedCliCapsuleContext({ + stdinData: { agent_state: 'running' }, + localMetrics: { + found: true, + cascadeId: '11111111-1111-1111-1111-111111111111', + dbMtimeMs: Date.now(), + targetIsRunning: true, + targetIsWaiting: false, + targetWaitingApprovalFresh: false, + runningRootCount: 1, + stepCount: 6, + }, + snapshot: { + updatedAtMs: Date.now() - 1500, + runningCount: 1, + hasWaiting: true, + waitingCascadeIds: ['11111111-1111-1111-1111-111111111111'], + }, + }); + assert.equal(resumedFromLocalDb.hasWaiting, false); + + // 6. Anomaly badge (toggleable via showAnomaly) + zero background SGR / OSC + const withAnom = h.formatCliStatusLineCapsule( + { + hasTelemetry: true, + stepCount: 4, + runningCount: 1, + tps: 44.2, + ttft: 2.1, + usedPct: 35, + latestAnomaly: { primaryKind: 'capacity', count: 1, severity: 'warn' }, + }, + { + slots: ['tps', 'ttft', 'context'], + language: 'zh-CN', + color: true, + } + ); + assert.equal(/\x1b\[48;/.test(withAnom), false); + assert.equal(/\x1b\]/.test(withAnom), false); + assert.equal(withAnom.replace(/\x1b\[[0-9;]*m/g, ''), '● 1 运行中 44.2 t/s | 2.1s | 上下文 ███⢕⢕⢕⢕⢕ 35% | ! 503'); + + const withoutAnom = h.formatCliStatusLineCapsule( + { + hasTelemetry: true, + stepCount: 4, + runningCount: 1, + tps: 44.2, + ttft: 2.1, + usedPct: 35, + latestAnomaly: { primaryKind: 'capacity', count: 1, severity: 'warn' }, + }, + { + slots: ['tps', 'ttft', 'context'], + language: 'zh-CN', + showAnomaly: false, + color: false, + } + ); + assert.equal(withoutAnom, '● 1 运行中 44.2 t/s | 2.1s | 上下文 ███⢕⢕⢕⢕⢕ 35%'); + + // 7. Narrow 72-column terminal progressively sheds lower-priority slots without wrapping + const narrow72 = h.formatCliStatusLineCapsule( + { + hasTelemetry: true, + stepCount: 6, + runningCount: 1, + tps: 48.2, + ttft: 1.4, + cacheHitPct: 95, + sessionCost: 1.25, + usedPct: 34, + quotas: { activePool: { remainingPct: 88 } }, + }, + { + slots: ['tps', 'ttft', 'cache_hit', 'session_cost', 'quota_auto', 'context'], + language: 'zh-CN', + color: false, + terminalWidth: 72, + cycleMode: 'auto', + modelDisplayName: 'Gemini 4 Neon (XHigh)', + modelEffort: 'xhigh', + } + ); + assert.ok(h.cliDisplayWidth(narrow72) <= 71, `Expected <= 71 cols, got ${h.cliDisplayWidth(narrow72)}`); + assert.ok(narrow72.includes('上下文 34%')); + assert.ok(narrow72.includes('48.2 t/s')); + + // 8. Subprocess E2E: inline flags & --install preserving custom flags + const tempRoot = mkdtempSync(fileURLToPath(new URL('./.cli-sl-flags-', import.meta.url))); + try { + const cliDir = join(tempRoot, 'antigravity-cli'); + const dataDir = join(tempRoot, 'data'); + mkdirSync(cliDir, { recursive: true }); + mkdirSync(dataDir, { recursive: true }); + const statusLineScript = fileURLToPath(new URL('../cli-statusline.mjs', import.meta.url)); + const env = { + ...process.env, + ANTIGRAVITY_GEMINI_DIR: tempRoot, + USAGE_MONITOR_DATA_DIR: dataDir, + USAGE_MONITOR_ALLOW_TEST_CLI_SETTINGS: '1', + NO_COLOR: '1', + }; + + const installCustom = JSON.parse( + execFileSync(process.execPath, [statusLineScript, '--install', '--preset', 'full', '--no-multi'], { + env, + encoding: 'utf8', + }).trim() + ); + assert.equal(installCustom.updated, true); + assert.ok(installCustom.command.includes('--preset full --no-multi')); + + const reinstallBare = JSON.parse( + execFileSync(process.execPath, [statusLineScript, '--install'], { + env, + encoding: 'utf8', + }).trim() + ); + assert.equal(reinstallBare.updated, false); + const savedCliSettings = JSON.parse(readFileSync(join(cliDir, 'settings.json'), 'utf8')); + assert.ok(savedCliSettings.statusLine.command.includes('--preset full --no-multi')); + + const inlineOut = execFileSync( + process.execPath, + [statusLineScript, '--slots', 'tps,quota_auto,context', '--no-multi', '--lang', 'en-US'], + { + env, + input: JSON.stringify({ + agent_state: 'idle', + context_window: { used_percentage: 19 }, + quota: { Gemini: { remaining_fraction: 0.91 } }, + }), + encoding: 'utf8', + } + ).trim(); + assert.equal(inlineOut, 'Idle | 5h ███████⣿ 91% | Ctx ██⢕⢕⢕⢕⢕⢕ 19%'); + + // 9. Runtime CLI installation & status detection (strictly gated on antigravity-cli dir) + forceReplaceCustom recovery + const { ensureCliStatusLineConfigured, getCliStatusLineRuntimeStatus } = await import( + '../backend/cli-statusline-config.mjs' + ); + const missingStatus = getCliStatusLineRuntimeStatus({ + env: { ANTIGRAVITY_GEMINI_DIR: join(tempRoot, 'nonexistent-gemini') }, + }); + assert.deepEqual(missingStatus, { + installed: false, + configured: false, + preservedCustom: false, + managedFlags: '', + }); + + const managedStatus = getCliStatusLineRuntimeStatus({ + env: { ANTIGRAVITY_GEMINI_DIR: tempRoot }, + }); + assert.deepEqual(managedStatus, { + installed: true, + configured: true, + preservedCustom: false, + managedFlags: '--preset full --no-multi', + }); + + writeFileSync( + join(cliDir, 'settings.json'), + JSON.stringify({ statusLine: { type: 'command', command: 'custom-bar' } }), + 'utf8' + ); + const customStatus = getCliStatusLineRuntimeStatus({ + env: { ANTIGRAVITY_GEMINI_DIR: tempRoot }, + }); + assert.deepEqual(customStatus, { + installed: true, + configured: false, + preservedCustom: true, + managedFlags: '', + }); + + const forceRestored = ensureCliStatusLineConfigured({ + enabled: true, + env, + forceReplaceCustom: true, + preserveManagedFlags: false, + }); + assert.equal(forceRestored.updated, true); + assert.deepEqual( + getCliStatusLineRuntimeStatus({ env: { ANTIGRAVITY_GEMINI_DIR: tempRoot } }), + { + installed: true, + configured: true, + preservedCustom: false, + managedFlags: '', + } + ); + + const noCliPayload = await backendHarness().buildTelemetryPayloadInternal('', false, { range: 'today' }); + assert.equal(noCliPayload.cliStatusLine?.installed, false); + const withCliPayload = await backendHarness({ + diskDirs: { '/test-home/.gemini/antigravity-cli': [] }, + }).buildTelemetryPayloadInternal('', false, { range: 'today' }); + assert.equal(withCliPayload.cliStatusLine?.installed, true); + } finally { + rmSync(tempRoot, { recursive: true, force: true }); + } +}); + test('v1.5 feedback settings schema: custom token combo DSL, 3-way model display mode, popover width bounds, and Worker hot-reload IPC', async () => { const { Worker } = await import('node:worker_threads'); const h = backendHarness({ diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 2c08e5d..ff137f4 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -5841,3 +5841,158 @@ test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisi }); } }); + +test('SettingsStructureTab CLI statusLine controls stay hidden unless CLI is detected, render progress-bar previews without preset bloat, and support one-click restore', async () => { + const { SettingsStructureTab } = await import('../src/views/settings/SettingsStructureTab.js'); + const { setI18nLanguage } = await import('../src/i18n/index.js'); + + const prevDoc = globalThis.document; + const prevFetch = globalThis.fetch; + const savedPatches = []; + const { document: mockDoc } = createMockDom(); + globalThis.document = mockDoc; + globalThis.fetch = async (url, opts = {}) => { + if (String(url).endsWith('/api/settings') && opts.method === 'POST') { + const patch = JSON.parse(opts.body); + savedPatches.push(patch); + if (patch.__cliStatusLineAction === 'force_install') { + return { + ok: true, + status: 200, + json: async () => ({ + ok: true, + cliStatusLine: { + installed: true, + configured: true, + preservedCustom: false, + managedFlags: '', + }, + settings: { enableCliStatusLine: true }, + }), + }; + } + if (patch.__cliStatusLineAction === 'clear_flags') { + return { + ok: true, + status: 200, + json: async () => ({ + ok: true, + cliStatusLine: { + installed: true, + configured: true, + preservedCustom: false, + managedFlags: '', + }, + }), + }; + } + return { ok: true, status: 200, json: async () => patch }; + } + return { ok: true, status: 200, json: async () => ({}) }; + }; + + try { + setI18nLanguage('zh-CN'); + const strTab = SettingsStructureTab({ onLayoutChange: () => {} }); + const groupEl = strTab.refs.cliStatusGroupEl; + const detailEl = strTab.refs.cliStatusDetailEl; + const previewEl = strTab.refs.cliPreviewEl; + const hintEl = strTab.refs.cliStatusHintEl; + const actionBtn = strTab.refs.cliStatusActionBtn; + + // 1. Default / CLI not detected -> entire CLI group stays hidden, zero redundant preset buttons + assert.equal(groupEl.hasAttribute('hidden'), true, 'CLI controls hidden before detection'); + assert.equal(groupEl.querySelectorAll('.cli-preset-btn').length, 0, 'No redundant preset button row'); + strTab.refs.renderSettings( + { enableCliStatusLine: true, cliStatusLineSlots: null, topbarCapsuleSlots: ['tps', 'ttft', 'context'] }, + { state: 'active' }, + 'win32', + { installed: false, configured: false, preservedCustom: false, managedFlags: '' } + ); + assert.equal(groupEl.hasAttribute('hidden'), true, 'CLI controls stay hidden when CLI is not installed'); + + // 2. CLI detected -> group becomes visible with 5 default slots + mini progress bars on quota & context + strTab.refs.renderSettings( + { enableCliStatusLine: true, cliStatusLineSlots: null, topbarCapsuleSlots: ['tps', 'ttft', 'context'] }, + { state: 'active' }, + 'win32', + { installed: true, configured: true, preservedCustom: false, managedFlags: '' } + ); + assert.equal(groupEl.hasAttribute('hidden'), false, 'CLI controls appear once CLI is detected'); + assert.equal(detailEl.hasAttribute('hidden'), false, 'CLI detail shown when enabled'); + assert.equal(strTab.refs.cliStatusFooterEl.hasAttribute('hidden'), true, 'No idle sync hint footer when healthy'); + assert.equal(actionBtn.hasAttribute('hidden'), true, 'No recovery button when healthy'); + const visibleSlots = () => + previewEl + .querySelectorAll('.cli-preview-slot') + .filter((el) => !el.hasAttribute('hidden')) + .map((el) => el.textContent); + assert.deepEqual(visibleSlots(), ['68.4 t/s', '1.1s', '$0.42', '余 █████⣿⣿⣿ 64%', '上下文 ████⢕⢕⢕⢕ 56%']); + + // 3. Dedicated 5h / weekly / context slots render distinct mini progress bars in live preview + strTab.refs.renderSettings( + { + enableCliStatusLine: true, + cliStatusLineSlots: ['gemini_5h', 'gemini_weekly', 'claude_5h', 'claude_weekly', 'context'], + }, + { state: 'active' }, + 'win32', + { installed: true, configured: true, preservedCustom: false, managedFlags: '' } + ); + assert.deepEqual(visibleSlots(), [ + 'G5h █████⣿⣿⣿ 64%', + 'G周 ███████⣿ 88%', + 'C5h ████████ 96%', + 'C周 ████████ 99%', + '上下文 ████⢕⢕⢕⢕ 56%', + ]); + + // 4. Turning CLI statusLine off collapses detail panel + strTab.refs.renderSettings( + { enableCliStatusLine: false, cliStatusLineSlots: ['tps', 'ttft', 'context'] }, + { state: 'active' }, + 'win32', + { installed: true, configured: false, preservedCustom: false, managedFlags: '' } + ); + assert.equal(groupEl.hasAttribute('hidden'), false, 'Toggle itself remains reachable while CLI is installed'); + assert.equal(detailEl.hasAttribute('hidden'), true, 'Slot controls hide when CLI statusLine is turned off'); + + // 5. Custom/broken third-party command shows amber notice + one-click restore button + strTab.refs.renderSettings( + { enableCliStatusLine: true, cliStatusLineSlots: null }, + { state: 'active' }, + 'win32', + { installed: true, configured: false, preservedCustom: true, managedFlags: '' } + ); + assert.equal(hintEl.classList.contains('is-warn'), true); + assert.match(hintEl.textContent, /自定义 statusLine/); + assert.equal(actionBtn.hasAttribute('hidden'), false); + assert.equal(actionBtn.classList.contains('is-warn'), true); + assert.equal(actionBtn.textContent, '一键接管并恢复'); + + // Clicking one-click restore sends __cliStatusLineAction: 'force_install' and clears warning + actionBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 25)); + assert.equal(savedPatches[savedPatches.length - 1]?.__cliStatusLineAction, 'force_install'); + assert.equal(actionBtn.hasAttribute('hidden'), true, 'Recovery button hides once restored'); + assert.equal(hintEl.classList.contains('is-warn'), false); + + // 6. Inline CLI launch flags override notice + clear button + strTab.refs.renderSettings( + { enableCliStatusLine: true, cliStatusLineSlots: null }, + { state: 'active' }, + 'win32', + { installed: true, configured: true, preservedCustom: false, managedFlags: '--preset full' } + ); + assert.equal(hintEl.classList.contains('is-warn'), false); + assert.match(hintEl.textContent, /命令行参数将优先/); + assert.equal(actionBtn.hasAttribute('hidden'), false); + assert.equal(actionBtn.textContent, '清除命令行覆盖'); + + strTab.destroy(); + } finally { + setI18nLanguage('zh-CN'); + globalThis.document = prevDoc; + globalThis.fetch = prevFetch; + } +});