From 5aabbfb1febb86d746099ba840fb3a1f9e3c43bf Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 22 Nov 2026 11:41:34 +0900 Subject: [PATCH] feat(cli): add statusLine --style pill|bar|compact gauge modes and --json snapshot output --- .../panel/backend/cli-statusline-config.mjs | 150 ++++++++++++++++-- sidecars/panel/cli-statusline.mjs | 23 ++- sidecars/panel/test/backend.test.mjs | 112 +++++++++++++ 3 files changed, 269 insertions(+), 16 deletions(-) diff --git a/sidecars/panel/backend/cli-statusline-config.mjs b/sidecars/panel/backend/cli-statusline-config.mjs index 9752ebc..44f28c5 100644 --- a/sidecars/panel/backend/cli-statusline-config.mjs +++ b/sidecars/panel/backend/cli-statusline-config.mjs @@ -33,6 +33,21 @@ import { resolveCapsuleQuotaSlotPct, } from '../shared/telemetry-display-rules.mjs'; +export const CLI_STATUSLINE_GAUGE_STYLES = Object.freeze(['pill', 'bar', 'compact']); + +/** + * 归一化 CLI 进度指示器样式(`pill` 底色胶囊 / `bar` 透明盲文条 / `compact` 极简纯文本)。 + * + * @param {unknown} raw + * @returns {'pill'|'bar'|'compact'} + */ +export function normalizeCliStatusLineGaugeStyle(raw) { + const val = String(raw || '').trim().toLowerCase(); + if (val === 'bar' || val === 'braille') return 'bar'; + if (val === 'compact' || val === 'text' || val === 'plain') return 'compact'; + return 'pill'; +} + // 24-bit ANSI SGR 调色板(和桌面端语义色阶及 CLI 原生底栏对齐;上下文和配额槽位采用 24-bit 底色胶囊填充,零 OSC 序列) const SGR_RESET = '\x1b[0m'; const SGR_BOLD = '\x1b[1m'; @@ -771,6 +786,27 @@ function cliBuildPillGauge( return `${out}${SGR_RESET}`; } +const CLI_BAR_PARTIAL_GLYPHS = Object.freeze([' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█']); +const CLI_BAR_TRACK_GLYPH = '⢕'; + +/** + * 渲染零背景色的透明迷你进度条(如 `上下文 ██▌⢕⢕ 42%` / `G5h █████ 95%`),适配浅色/透明终端及老旧 SSH 复用器。 + */ +function cliBuildBarGauge(label, pct, { fillFg = SGR_FG_ACCENT, valFg = SGR_FG_BRIGHT } = {}) { + const clamped = Math.max(0, Math.min(100, Number(pct) || 0)); + const width = 5; + const exactEighths = Math.round((clamped / 100) * width * 8); + const fullCells = Math.floor(exactEighths / 8); + const remEighths = exactEighths % 8; + const filledPart = + '█'.repeat(Math.min(width, fullCells)) + + (fullCells < width && remEighths > 0 ? CLI_BAR_PARTIAL_GLYPHS[remEighths] : ''); + const emptyCount = Math.max(0, width - fullCells - (remEighths > 0 ? 1 : 0)); + const emptyPart = CLI_BAR_TRACK_GLYPH.repeat(emptyCount); + const valStr = `${Math.round(clamped)}%`.padStart(3, ' '); + return `${SGR_FG_MUTED}${label} ${fillFg}${filledPart}${emptyPart ? `${SGR_FG_DIM}${emptyPart}` : ''} ${valFg}${valStr}${SGR_RESET}`; +} + function cliResolveQuotaSlotPrefix(metricKey, isEn) { if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; @@ -785,9 +821,14 @@ function cliResolveQuotaSlotPrefix(metricKey, isEn) { function cliRenderSingleSlot( metricKey, slotCtx, - { isEn = false, useColor = true, slotSet, usePill = true } = {} + { isEn = false, useColor = true, slotSet, usePill = true, gaugeStyle = '' } = {} ) { const hasTelemetry = slotCtx.hasTelemetry !== false; + const resolvedStyle = gaugeStyle + ? normalizeCliStatusLineGaugeStyle(gaugeStyle) + : usePill + ? 'pill' + : 'compact'; if (metricKey === 'context') { const valid = hasTelemetry && slotCtx.usedPct != null && Number.isFinite(Number(slotCtx.usedPct)); @@ -799,7 +840,7 @@ function cliRenderSingleSlot( } const isDanger = pctNum != null && pctNum >= 88; const isWarn = !isDanger && pctNum != null && pctNum >= 70; - if (usePill && pctNum != null) { + if (resolvedStyle === 'pill' && pctNum != null) { const fillBg = isDanger ? SGR_BG_PILL_DANGER : isWarn @@ -819,6 +860,10 @@ function cliRenderSingleSlot( : pctNum != null ? `${SGR_BOLD}${SGR_FG_BRIGHT}` : SGR_FG_MUTED; + if (resolvedStyle === 'bar' && pctNum != null) { + const fillFg = isDanger ? SGR_FG_DANGER : isWarn ? SGR_FG_WARN : SGR_FG_ACCENT; + return cliBuildBarGauge(label, pctNum, { fillFg, valFg: valColor }); + } return `${SGR_FG_MUTED}${label} ${valColor}${textVal}${SGR_RESET}`; } @@ -931,7 +976,7 @@ function cliRenderSingleSlot( return `${prefix} ${quotaPct}%`; } - if (usePill) { + if (resolvedStyle === 'pill') { const fillBg = isDanger ? SGR_BG_PILL_DANGER : isWarn @@ -945,6 +990,11 @@ function cliRenderSingleSlot( return cliBuildPillGauge(prefix, quotaPct, { fillBg, fillLabelFg }); } + if (resolvedStyle === 'bar') { + const fillFg = isDanger ? SGR_FG_DANGER : isWarn ? SGR_FG_WARN : SGR_FG_GOOD; + return cliBuildBarGauge(prefix, quotaPct, { fillFg, valFg: pctSgr }); + } + return `${SGR_FG_MUTED}${prefix} ${pctSgr}${quotaPct}%${SGR_RESET}`; } @@ -1159,12 +1209,22 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { ? cliStatusFormatAnomalyTag(slotCtx.latestAnomaly, { isEn, useColor }) : ''; - const defaultUsePill = options.showProgressBars !== false; + const primaryGaugeStyle = + options.gaugeStyle != null && String(options.gaugeStyle).trim() + ? normalizeCliStatusLineGaugeStyle(options.gaugeStyle) + : options.showProgressBars === false + ? 'compact' + : 'pill'; + const defaultUseGauge = primaryGaugeStyle !== 'compact'; - const buildCapsulesForSlots = (slotList, includeAnomaly = true, usePill = defaultUsePill) => { + const buildCapsulesForSlots = ( + slotList, + includeAnomaly = true, + gaugeStyle = primaryGaugeStyle + ) => { const slotSet = new Set(slotList); const rendered = slotList.map((key) => - cliRenderSingleSlot(key, slotCtx, { isEn, useColor, slotSet, usePill }) + cliRenderSingleSlot(key, slotCtx, { isEn, useColor, slotSet, gaugeStyle }) ); if (includeAnomaly && anomalyBadge) { rendered.push(anomalyBadge); @@ -1177,7 +1237,7 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { }; }; - const baseCapsules = buildCapsulesForSlots(activeSlots, true, defaultUsePill); + const baseCapsules = buildCapsulesForSlots(activeSlots, true, primaryGaugeStyle); const rawWidth = Number(options.terminalWidth); if (!Number.isFinite(rawWidth) || rawWidth <= 0) { return baseCapsules.fullCapsule; @@ -1219,20 +1279,20 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { const primaryComposed = tryCompose(baseCapsules); if (primaryComposed) return primaryComposed; - if (defaultUsePill) { - const noPillCapsules = buildCapsulesForSlots(activeSlots, true, false); - const noPillComposed = tryCompose(noPillCapsules); - if (noPillComposed) return noPillComposed; + if (defaultUseGauge) { + const noGaugeCapsules = buildCapsulesForSlots(activeSlots, true, 'compact'); + const noGaugeComposed = tryCompose(noGaugeCapsules); + if (noGaugeComposed) return noGaugeComposed; } let reducedSlots = [...activeSlots]; while (reducedSlots.length > 1) { reducedSlots = cliStatusShedLowestPrioritySlot(reducedSlots); - const reducedCap = buildCapsulesForSlots(reducedSlots, true, defaultUsePill); + const reducedCap = buildCapsulesForSlots(reducedSlots, true, primaryGaugeStyle); const composed = tryCompose(reducedCap); if (composed) return composed; - if (defaultUsePill) { - const reducedPlain = buildCapsulesForSlots(reducedSlots, true, false); + if (defaultUseGauge) { + const reducedPlain = buildCapsulesForSlots(reducedSlots, true, 'compact'); const composedPlain = tryCompose(reducedPlain); if (composedPlain) return composedPlain; } @@ -1241,9 +1301,69 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { if (cliDisplayWidth(baseCapsules.fullCapsule) <= maxWidth) { return baseCapsules.fullCapsule; } - const minimalCap = buildCapsulesForSlots(reducedSlots, false, false); + const minimalCap = buildCapsulesForSlots(reducedSlots, false, 'compact'); if (cliDisplayWidth(minimalCap.fullCapsule) <= maxWidth) { return minimalCap.fullCapsule; } return minimalCap.slotsBody; } + +/** + * 构建供外部终端提示符(Starship / Oh-My-Posh / tmux / Waybar)或脚本消费的结构化单行 JSON 遥测快照, + * 内含压缩线对齐后的上下文占比及各配额池剩余额度状态。 + * + * @param {object} slotCtx + * @param {{ modelDisplayName?: string, modelEffort?: string, cycleMode?: string, nowMs?: number }} [meta] + * @returns {object} + */ +export function buildCliJsonStatusOutput( + slotCtx = {}, + { modelDisplayName = '', modelEffort = '', cycleMode = '', nowMs = Date.now() } = {} +) { + const parsedModel = parseCliModelAndEffort(modelDisplayName, modelEffort); + const pools = Array.isArray(slotCtx?.quotas?.pools) ? slotCtx.quotas.pools : []; + const quotaPools = pools.map((p) => ({ + poolKey: p?.poolKey || p?.family || '', + remaining5hPct: p?.remainingPct ?? null, + remainingWeeklyPct: p?.weeklyRemainingPct ?? null, + reset5h: p?.resetTime || null, + resetWeekly: p?.weeklyResetTime || null, + })); + + return { + timestamp: new Date(nowMs).toISOString(), + hasTelemetry: slotCtx.hasTelemetry !== false, + isRunning: Boolean(slotCtx.isRunning), + hasWaiting: Boolean(slotCtx.hasWaiting), + runningCount: Math.max(0, Math.floor(Number(slotCtx.runningCount) || 0)), + runningSubCount: Math.max(0, Math.floor(Number(slotCtx.runningSubCount) || 0)), + stepCount: slotCtx.stepCount ?? null, + model: { + displayName: parsedModel.modelName || '', + effort: parsedModel.effort || '', + cycleMode: String(cycleMode || '').trim(), + }, + speed: { + tps: slotCtx.tps ?? null, + avgTps: slotCtx.avgTps ?? null, + ttftSec: slotCtx.ttft ?? null, + }, + cost: { + stepUsd: slotCtx.stepCost ?? null, + sessionUsd: slotCtx.sessionCost ?? null, + }, + cache: { + hitPct: slotCtx.cacheHitPct ?? null, + latestPromptTokens: slotCtx.latestPromptTokens ?? null, + sessionTokens: slotCtx.sessionTokens ?? null, + }, + context: { + usedPct: slotCtx.usedPct ?? null, + }, + quotas: { + autoRemainingPct: resolveCapsuleQuotaSlotPct(slotCtx.quotas, 'quota_auto'), + pools: quotaPools, + }, + latestAnomaly: slotCtx.latestAnomaly || null, + }; +} diff --git a/sidecars/panel/cli-statusline.mjs b/sidecars/panel/cli-statusline.mjs index 21ce54a..befd572 100644 --- a/sidecars/panel/cli-statusline.mjs +++ b/sidecars/panel/cli-statusline.mjs @@ -36,8 +36,10 @@ import { } from './backend/cli-sqlite-reader.mjs'; import { withReadOnlySqliteDb } from './backend/sqlite-client.mjs'; import { + buildCliJsonStatusOutput, ensureCliStatusLineConfigured, formatCliStatusLineCapsule, + normalizeCliStatusLineGaugeStyle, } from './backend/cli-statusline-config.mjs'; import { CLI_STATUS_SNAPSHOT_FILE, @@ -585,6 +587,8 @@ export function parseCliStatusLineArgs(argv = []) { showAnomaly: null, language: '', noColor: false, + style: '', + json: false, }; for (let i = 0; i < argv.length; i += 1) { const raw = String(argv[i] || '').trim(); @@ -605,6 +609,8 @@ export function parseCliStatusLineArgs(argv = []) { 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 === '--style') out.style = normalizeCliStatusLineGaugeStyle(readVal()); + else if (flag === '--json') out.json = true; 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; @@ -615,7 +621,7 @@ export function parseCliStatusLineArgs(argv = []) { return out; } -function buildPersistableStatusLineFlags(parsed) { +export function buildPersistableStatusLineFlags(parsed) { const parts = []; if (parsed.slotsRaw && parsed.slotsRaw.toLowerCase() !== 'auto') { const norm = normalizeCliStatusLineSlots(parsed.slotsRaw); @@ -626,6 +632,7 @@ function buildPersistableStatusLineFlags(parsed) { ) { parts.push(`--preset ${parsed.preset}`); } + if (parsed.style) parts.push(`--style ${normalizeCliStatusLineGaugeStyle(parsed.style)}`); if (parsed.showMultiSession === false) parts.push('--no-multi'); else if (parsed.showMultiSession === true) parts.push('--multi'); if (parsed.showAnomaly === false) parts.push('--no-anomaly'); @@ -641,6 +648,8 @@ function formatCliStatusLineHelp() { ' --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)', + ' --style pill|bar|compact Gauge style (24-bit pill / transparent bar / plain text)', + ' --json Output single-line structured JSON snapshot for scripts/prompts', ' --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', @@ -893,8 +902,20 @@ export async function runCliStatusLineMain(argv = process.argv.slice(2)) { effectiveSlots = resolveEffectiveCliStatusLineSlots(settings); } + if (cliArgs.json) { + const jsonPayload = buildCliJsonStatusOutput(slotCtx, { + modelDisplayName, + modelEffort: typeof stdinData?.model?.effort === 'string' ? stdinData.model.effort : '', + cycleMode: typeof stdinData?.cycle_mode === 'string' ? stdinData.cycle_mode : '', + nowMs, + }); + process.stdout.write(`${JSON.stringify(jsonPayload)}\n`); + return; + } + const line = formatCliStatusLineCapsule(slotCtx, { slots: effectiveSlots, + gaugeStyle: cliArgs.style || undefined, showMultiSession: cliArgs.showMultiSession !== null ? cliArgs.showMultiSession diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index bc791a4..9b35bf5 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -3332,3 +3332,115 @@ test('scope=conversation switches sessions with zero LS RPCs, preserves usageRev await pendingSwitch; assert.equal(telemetryStore.getState().telemetry.activeConversation.recentSteps.length, 2); }); + +test('CLI statusLine supports --style pill|bar|compact switching, flag persistence, and --json snapshot output', async () => { + const { + buildCliJsonStatusOutput, + formatCliStatusLineCapsule, + normalizeCliStatusLineGaugeStyle, + } = await import('../backend/cli-statusline-config.mjs'); + const { + parseCliStatusLineArgs, + buildPersistableStatusLineFlags, + } = await import('../cli-statusline.mjs'); + + assert.equal(normalizeCliStatusLineGaugeStyle('bar'), 'bar'); + assert.equal(normalizeCliStatusLineGaugeStyle('compact'), 'compact'); + assert.equal(normalizeCliStatusLineGaugeStyle('unknown'), 'pill'); + + const parsedArgs = parseCliStatusLineArgs([ + '--slots', + 'tps,context,gemini_5h', + '--style', + 'bar', + '--json', + '--no-multi', + ]); + assert.equal(parsedArgs.style, 'bar'); + assert.equal(parsedArgs.json, true); + assert.equal(parsedArgs.showMultiSession, false); + assert.match(buildPersistableStatusLineFlags(parsedArgs), /--style bar/); + + const nowMs = Date.UTC(2026, 10, 22, 12, 0, 0); + const slotCtx = { + hasTelemetry: true, + isRunning: false, + hasWaiting: false, + runningCount: 1, + runningSubCount: 0, + stepCount: 5, + tps: 52.3, + avgTps: 48.0, + ttft: 2.1, + stepCost: 0.04, + sessionCost: 0.32, + cacheHitPct: 88.5, + latestPromptTokens: 80_000, + sessionTokens: 320_000, + usedPct: 42, + quotas: { + activePool: { poolKey: 'Gemini', remainingPct: 40, weeklyRemainingPct: 80 }, + pools: [ + { + poolKey: 'Gemini', + family: 'Gemini', + usedPct: 60, + remainingPct: 40, + resetTime: new Date(nowMs + 3 * 3_600_000).toISOString(), + weeklyUsedPct: 20, + weeklyRemainingPct: 80, + weeklyResetTime: new Date(nowMs + 3.5 * 24 * 3_600_000).toISOString(), + }, + ], + }, + }; + + // 1. Pill style emits 24-bit background fill (48;2;) + const pillOut = formatCliStatusLineCapsule(slotCtx, { + slots: ['tps', 'context', 'gemini_5h'], + gaugeStyle: 'pill', + language: 'zh-CN', + color: true, + }); + assert.match(pillOut, /\x1b\[48;2;/); + + // 2. Bar style emits transparent Braille/block bar without 48;2; background codes + const barOut = formatCliStatusLineCapsule(slotCtx, { + slots: ['tps', 'context', 'gemini_5h'], + gaugeStyle: 'bar', + language: 'zh-CN', + color: true, + }); + assert.doesNotMatch(barOut, /\x1b\[48;2;/); + assert.match(barOut, /[█▏▎▍▌▋▊▉]/); + assert.match(barOut, /⢕/); + + // 3. Compact style emits clean text-only gauges without 48;2; or bar glyphs + const compactOut = formatCliStatusLineCapsule(slotCtx, { + slots: ['tps', 'context', 'gemini_5h'], + gaugeStyle: 'compact', + language: 'zh-CN', + color: true, + }); + assert.doesNotMatch(compactOut, /\x1b\[48;2;/); + assert.doesNotMatch(compactOut, /[█⢕]/); + assert.match(compactOut, /上下文.*42%/); + assert.match(compactOut, /G5h.*40%/); + + // 4. Structured JSON output includes model, speed, context, and quota pool snapshots + const jsonSnap = buildCliJsonStatusOutput(slotCtx, { + modelDisplayName: 'Gemini 4 Neon', + modelEffort: 'xhigh', + cycleMode: 'auto', + nowMs, + }); + assert.equal(jsonSnap.model.displayName, 'Gemini 4 Neon'); + assert.equal(jsonSnap.model.effort, 'xhigh'); + assert.equal(jsonSnap.speed.tps, 52.3); + assert.equal(jsonSnap.context.usedPct, 42); + assert.equal(jsonSnap.quotas.autoRemainingPct, 40); + assert.equal(jsonSnap.quotas.pools.length, 1); + assert.equal(jsonSnap.quotas.pools[0].poolKey, 'Gemini'); + assert.equal(jsonSnap.quotas.pools[0].remaining5hPct, 40); + assert.equal(jsonSnap.quotas.pools[0].remainingWeeklyPct, 80); +});