From 328e8cd74e024dad1a8f207f005c6461cc45df69 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sat, 21 Nov 2026 13:45:29 +0900 Subject: [PATCH 01/31] feat(panel): upgrade consumption rankings, pointer-following breakdown popovers, full session search, sortable steps, and settings backup --- sidecars/panel/app.js | 2517 ++++++++++++++--- sidecars/panel/backend/local-scanner.mjs | 161 +- sidecars/panel/backend/telemetry-builder.mjs | 82 +- sidecars/panel/backend/usage-aggregator.mjs | 137 + sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 2 + sidecars/panel/src/App.js | 61 +- .../src/components/charts/TrendAreaChart.js | 356 ++- .../src/components/layout/TopSessionHeader.js | 4 + .../ui/ConsumptionTooltipContent.js | 256 ++ .../panel/src/components/ui/CustomSelect.js | 181 +- .../src/components/widgets/StepTableWidget.js | 87 +- sidecars/panel/src/core/settingsBackup.js | 237 ++ sidecars/panel/src/i18n/en-US.js | 32 + sidecars/panel/src/i18n/zh-CN.js | 32 + sidecars/panel/src/icons/svgRegistry.js | 12 + .../src/registries/stepColumnRegistry.js | 82 +- sidecars/panel/src/store/telemetryStore.js | 32 + sidecars/panel/src/styles/base.css | 4 + sidecars/panel/src/styles/controls.css | 94 + sidecars/panel/src/styles/modern-ui.css | 19 +- .../panel/src/styles/views-consumption.css | 302 +- sidecars/panel/src/styles/views-settings.css | 12 + sidecars/panel/src/styles/views-tables.css | 63 +- sidecars/panel/src/views/ConsumptionView.js | 974 ++++++- sidecars/panel/src/views/StepsDetailView.js | 85 +- .../src/views/settings/SettingsOtherTab.js | 115 + sidecars/panel/styles.css | 494 +++- sidecars/panel/test/backend.test.mjs | 9 + sidecars/panel/test/consumption-bars.test.mjs | 57 +- sidecars/panel/test/modern-ui.test.mjs | 27 +- .../test/practical-enhancements.test.mjs | 969 +++++++ sidecars/panel/test/window-bridge.test.mjs | 2 +- 33 files changed, 6765 insertions(+), 736 deletions(-) create mode 100644 sidecars/panel/src/components/ui/ConsumptionTooltipContent.js create mode 100644 sidecars/panel/src/core/settingsBackup.js create mode 100644 sidecars/panel/test/practical-enhancements.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 3beaf73..ffd78c1 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -872,6 +872,18 @@ const SVG_ICON_DEFS = Object.freeze({ { tag: 'rect', attrs: { x: '5.2', y: '5.2', width: '8.3', height: '8.3', rx: '1.3' } }, { tag: 'path', attrs: { d: 'M3.5 10.8H2.8a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.8 2h6.2a1.3 1.3 0 0 1 1.3 1.3v.7' } }, ], + search: [ + { tag: 'circle', attrs: { cx: '7.2', cy: '7.2', r: '4.5' } }, + { tag: 'path', attrs: { d: 'M10.6 10.6L14 14' } }, + ], + download: [ + { tag: 'path', attrs: { d: 'M8 2.4v7.6M5 7.2L8 10.2l3-3' } }, + { tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } }, + ], + upload: [ + { tag: 'path', attrs: { d: 'M8 10.2V2.6M5 5.4L8 2.4l3 3' } }, + { tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } }, + ], grip: [ { tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, @@ -1092,6 +1104,10 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', 'header.statusLive': '监控中', + 'header.searchSessionPlaceholder': '搜索会话标题或 ID…', + 'select.searchPlaceholder': '输入关键词筛选…', + 'select.noMatches': '没有匹配的选项', + 'select.clearSearch': '清空搜索', // Formatters & Common Labels 'fmt.pending': '待定', @@ -1313,6 +1329,26 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.footOutput': '输出 ', 'cons.footThinking': '思考 ', 'cons.footCalls': '调用 ', + 'cons.rankTabAria': '排行视图切换', + 'cons.rankTabModelsCount': '模型排行 ({count})', + 'cons.rankTabSessions': '会话排行', + 'cons.rankTabSessionsCount': '会话排行 ({count})', + 'cons.topConvsEmpty': '当前时间范围暂无会话消耗记录', + 'cons.topConvsSortAria': '会话排行排序方式', + 'cons.topConvsSortCost': '费用', + 'cons.topConvsSortTokens': 'Token', + 'cons.topConvCacheMeta': '缓存 {pct}%', + 'cons.topConvJumpTip': '点击跳转到该会话调用记录', + 'cons.modelsSortAria': '模型排行排序方式', + 'cons.modelsSortTokens': 'Token', + 'cons.modelsSortCost': '费用', + 'cons.modelsSortSpeed': '均速', + 'cons.modelsSortCalls': '调用', + 'cons.modelUnitCost': '均价 {cost}/1M', + 'cons.speedRelTip': '相对本时段最快模型的均速比例', + 'cons.focusTtft': '首字 {ttft}', + 'cons.focusSpeedMeta': '首字 {ttft} · 缓存 {cache}% · 输出 {out}', + 'cons.focusCallsMeta': '单次均耗 {avgTok} · 费用 {cost}', // Steps Detail View & Step Column Registry 'steps.title': '调用记录', @@ -1397,6 +1433,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)', 'steps.anomalyFilterLabel': '仅看异常 ({count})', 'steps.anomalyFilterAll': '返回全部步骤', + 'steps.sortClickTip': '点击按「{col}」排序', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': '步序', @@ -1666,6 +1703,13 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', + 'settings.oth.backupLabel': '配置备份及恢复', + 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON(不含账号凭证)', + 'settings.oth.exportJsonBtn': '导出 JSON', + 'settings.oth.importJsonBtn': '导入 JSON', + 'settings.oth.exportDone': '配置 JSON 已导出', + 'settings.oth.importDone': '已恢复 {count} 项偏好设置', + 'settings.oth.importInvalid': '导入失败:JSON 无效或未包含可识别的偏好项', // Structured Live Activity Actions 'live.act.run_command': '执行命令', @@ -1801,6 +1845,10 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', 'header.statusLive': 'Monitoring', + 'header.searchSessionPlaceholder': 'Search sessions by title or ID…', + 'select.searchPlaceholder': 'Filter options…', + 'select.noMatches': 'No matching items', + 'select.clearSearch': 'Clear search', // Formatters & Common Labels 'fmt.pending': 'N/A', @@ -2022,6 +2070,26 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.footOutput': 'Out ', 'cons.footThinking': 'Think ', 'cons.footCalls': 'Calls ', + 'cons.rankTabAria': 'Switch ranking view', + 'cons.rankTabModelsCount': 'Models ({count})', + 'cons.rankTabSessions': 'Sessions', + 'cons.rankTabSessionsCount': 'Sessions ({count})', + 'cons.topConvsEmpty': 'No session usage in this range', + 'cons.topConvsSortAria': 'Sort sessions ranking', + 'cons.topConvsSortCost': 'Cost', + 'cons.topConvsSortTokens': 'Tokens', + 'cons.topConvCacheMeta': 'Cache {pct}%', + 'cons.topConvJumpTip': 'Click to inspect this session in Steps', + 'cons.modelsSortAria': 'Sort models ranking', + 'cons.modelsSortTokens': 'Tokens', + 'cons.modelsSortCost': 'Cost', + 'cons.modelsSortSpeed': 'Speed', + 'cons.modelsSortCalls': 'Calls', + 'cons.modelUnitCost': 'Eff. {cost}/1M', + 'cons.speedRelTip': 'Speed relative to fastest model in this range', + 'cons.focusTtft': 'TTFT {ttft}', + 'cons.focusSpeedMeta': 'TTFT {ttft} · Cache {cache}% · Out {out}', + 'cons.focusCallsMeta': 'Avg {avgTok}/call · Cost {cost}', // Steps Detail View & Step Column Registry 'steps.title': 'Step Records', @@ -2106,6 +2174,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)', 'steps.anomalyFilterLabel': 'Anomalies Only ({count})', 'steps.anomalyFilterAll': 'Show All Steps', + 'steps.sortClickTip': 'Click to sort by {col}', // Step Table Columns (Headers & Option Labels) 'stepCol.step.th': 'Step', @@ -2375,6 +2444,13 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resetConfirmBtn': 'Click Again to Confirm', 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', + 'settings.oth.backupLabel': 'Preferences Backup & Restore', + 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON (excludes credentials)', + 'settings.oth.exportJsonBtn': 'Export JSON', + 'settings.oth.importJsonBtn': 'Import JSON', + 'settings.oth.exportDone': 'Preferences JSON exported', + 'settings.oth.importDone': 'Restored {count} preference settings', + 'settings.oth.importInvalid': 'Import failed: invalid JSON or no recognized settings', // Structured Live Activity Actions 'live.act.run_command': 'Run Command', @@ -4540,6 +4616,228 @@ function buildDeterministicModelColorMap(models = []) { return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); +// --- src/core/settingsBackup.js --- +const { triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson } = (() => { +/** + * @fileoverview 偏好设置便携 JSON 备份及恢复工具 (`settingsBackup.js`). + * 仅处理经过白名单归一化的用户界面偏好项,不包含账号凭证及高风险上下文窗口覆盖。 + */ + + +const SETTINGS_BACKUP_SCHEMA = 'antigravity-usage-monitor.settings'; +const MAX_SETTINGS_IMPORT_BYTES = 128 * 1024; + +function sanitizePositiveBudgetNum(val) { + const num = Number(val); + return Number.isFinite(num) && num > 0 ? num : null; +} + +/** + * 在浏览器端通过内存 Blob 触发文件下载(零本地磁盘外部写入)。 + * + * @param {string} filename + * @param {string} content + * @param {string} [mimeType] + * @returns {boolean} + */ +function triggerTextFileDownload( + filename, + content, + mimeType = 'application/json;charset=utf-8' +) { + try { + if ( + typeof Blob === 'undefined' || + typeof URL === 'undefined' || + typeof URL.createObjectURL !== 'function' || + typeof document === 'undefined' + ) { + return false; + } + const blob = new Blob([String(content ?? '')], { type: mimeType }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.setAttribute('href', url); + a.setAttribute('download', String(filename || 'export.json')); + a.style.display = 'none'; + document.body?.appendChild?.(a); + a.click?.(); + a.remove?.(); + setTimeout(() => { + try { + URL.revokeObjectURL(url); + } catch {} + }, 1000); + return true; + } catch { + return false; + } +} + +/** + * 将当前用户偏好设置序列化为跨设备可迁移的安全 JSON 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。 + * + * @param {object} [settings={}] + * @returns {string} + */ +function buildExportableSettingsJson(settings = {}) { + const src = settings && typeof settings === 'object' ? settings : {}; + const modelDisplayMode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); + const modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true; + const payload = { + schema: SETTINGS_BACKUP_SCHEMA, + version: 1, + exportedAt: new Date().toISOString(), + settings: { + language: normalizeLanguageSetting(src.language), + themeAccent: normalizeThemeAccent(src.themeAccent), + fontScale: normalizeFontScale(src.fontScale), + modernUi, + weeklyLimitMode: normalizeWeeklyLimitMode(src.weeklyLimitMode), + weeklyTokenBudget: sanitizePositiveBudgetNum(src.weeklyTokenBudget) ?? 150000000, + weeklyCostBudget: sanitizePositiveBudgetNum(src.weeklyCostBudget) ?? 100, + modelDisplayMode, + showUpstreamModel: modelDisplayMode !== 'short', + orchestratorIdMode: normalizeOrchestratorIdMode(src.orchestratorIdMode), + pluginUpdateMode: normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin), + windowMountMode: normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay), + popoverWidthMode: normalizePopoverWidthMode(src.popoverWidthMode), + popoverWidth: normalizePopoverWidth(src.popoverWidth), + enableCliStatusLine: src.enableCliStatusLine !== false, + standalonePort: normalizeStandalonePort(src.standalonePort), + showTopbarMultiSession: src.showTopbarMultiSession !== false, + topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots), + hoverModules: normalizeHoverModules(src.hoverModules), + overviewModules: normalizeOverviewModules(src.overviewModules), + overviewMetrics: normalizeOverviewMetrics(src.overviewMetrics), + showStepTurnRail: src.showStepTurnRail === true, + showStepAgentBadge: src.showStepAgentBadge !== false, + showStepSpeedColor: src.showStepSpeedColor === true, + stepTokenComboFormat: normalizeStepTokenComboFormat(src.stepTokenComboFormat), + stepTableColumns: normalizeStepTableColumns(src.stepTableColumns), + }, + }; + return `${JSON.stringify(payload, null, 2)}\n`; +} + +/** + * 校验并解析导入的偏好设置 JSON,仅提取并归一化白名单内的便携配置项。 + * + * @param {string} rawText + * @returns {{ ok: true, patch: object, appliedCount: number } | { ok: false, errorCode: string }} + */ +function parseImportedSettingsJson(rawText) { + if (typeof rawText !== 'string' || !rawText.trim() || rawText.length > MAX_SETTINGS_IMPORT_BYTES) { + return { ok: false, errorCode: 'invalid_json' }; + } + let parsed; + try { + parsed = JSON.parse(rawText); + } catch { + return { ok: false, errorCode: 'invalid_json' }; + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { ok: false, errorCode: 'invalid_json' }; + } + + const hasWrappedSettings = + parsed.settings && typeof parsed.settings === 'object' && !Array.isArray(parsed.settings); + if (parsed.schema !== undefined && parsed.schema !== SETTINGS_BACKUP_SCHEMA) { + return { ok: false, errorCode: 'invalid_schema' }; + } + const src = hasWrappedSettings ? parsed.settings : parsed; + const hasKey = (k) => Object.prototype.hasOwnProperty.call(src, k); + const patch = {}; + + if (hasKey('language')) patch.language = normalizeLanguageSetting(src.language); + if (hasKey('themeAccent')) patch.themeAccent = normalizeThemeAccent(src.themeAccent); + if (hasKey('fontScale')) patch.fontScale = normalizeFontScale(src.fontScale); + if (hasKey('modernUi')) { + const val = normalizeModernUi(src.modernUi); + patch.modernUi = val; + patch.experimentalModernUi = val; + } + if (hasKey('weeklyLimitMode')) { + patch.weeklyLimitMode = normalizeWeeklyLimitMode(src.weeklyLimitMode); + } + if (hasKey('weeklyTokenBudget')) { + const num = sanitizePositiveBudgetNum(src.weeklyTokenBudget); + if (num !== null) patch.weeklyTokenBudget = num; + } + if (hasKey('weeklyCostBudget')) { + const num = sanitizePositiveBudgetNum(src.weeklyCostBudget); + if (num !== null) patch.weeklyCostBudget = num; + } + if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) { + const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); + patch.modelDisplayMode = mode; + patch.showUpstreamModel = mode !== 'short'; + } + if (hasKey('orchestratorIdMode')) { + patch.orchestratorIdMode = normalizeOrchestratorIdMode(src.orchestratorIdMode); + } + if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) { + const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin); + patch.pluginUpdateMode = mode; + patch.autoUpdatePlugin = mode === 'auto'; + } + if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) { + const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay); + patch.windowMountMode = mode; + patch.enableWindowOverlay = mode !== 'sidebar'; + } + if (hasKey('popoverWidthMode')) { + patch.popoverWidthMode = normalizePopoverWidthMode(src.popoverWidthMode); + } + if (hasKey('popoverWidth')) { + patch.popoverWidth = normalizePopoverWidth(src.popoverWidth); + } + if (hasKey('enableCliStatusLine') && typeof src.enableCliStatusLine === 'boolean') { + patch.enableCliStatusLine = src.enableCliStatusLine; + } + if (hasKey('standalonePort')) { + patch.standalonePort = normalizeStandalonePort(src.standalonePort); + } + if (hasKey('showTopbarMultiSession') && typeof src.showTopbarMultiSession === 'boolean') { + patch.showTopbarMultiSession = src.showTopbarMultiSession; + } + if (hasKey('topbarCapsuleSlots') && Array.isArray(src.topbarCapsuleSlots)) { + patch.topbarCapsuleSlots = normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots); + } + if (hasKey('hoverModules') && Array.isArray(src.hoverModules)) { + patch.hoverModules = normalizeHoverModules(src.hoverModules); + } + if (hasKey('overviewModules') && Array.isArray(src.overviewModules)) { + patch.overviewModules = normalizeOverviewModules(src.overviewModules); + } + if (hasKey('overviewMetrics') && Array.isArray(src.overviewMetrics)) { + patch.overviewMetrics = normalizeOverviewMetrics(src.overviewMetrics); + } + if (hasKey('showStepTurnRail') && typeof src.showStepTurnRail === 'boolean') { + patch.showStepTurnRail = src.showStepTurnRail; + } + if (hasKey('showStepAgentBadge') && typeof src.showStepAgentBadge === 'boolean') { + patch.showStepAgentBadge = src.showStepAgentBadge; + } + if (hasKey('showStepSpeedColor') && typeof src.showStepSpeedColor === 'boolean') { + patch.showStepSpeedColor = src.showStepSpeedColor; + } + if (hasKey('stepTokenComboFormat')) { + patch.stepTokenComboFormat = normalizeStepTokenComboFormat(src.stepTokenComboFormat); + } + if (hasKey('stepTableColumns') && Array.isArray(src.stepTableColumns)) { + patch.stepTableColumns = normalizeStepTableColumns(src.stepTableColumns); + } + + const appliedCount = Object.keys(patch).length; + if (appliedCount === 0) { + return { ok: false, errorCode: 'empty_patch' }; + } + return { ok: true, patch, appliedCount }; +} +return { triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson }; +})(); + // --- src/core/httpClient.js --- const { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => { /** @@ -5159,6 +5457,7 @@ function recordConsumptionSliceToCache( account: cons.account, trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [], sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [], + topConversations: Array.isArray(cons.topConversations) ? cons.topConversations : [], modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [], }); } @@ -5176,6 +5475,9 @@ function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision account: cachedEntry.account ?? prevCons.account, trendSeries: cachedEntry.trendSeries, sourcesBreakdown: cachedEntry.sourcesBreakdown, + topConversations: Array.isArray(cachedEntry.topConversations) + ? cachedEntry.topConversations + : [], }, modelBreakdown: cachedEntry.modelBreakdown, }; @@ -5652,7 +5954,14 @@ function isEquivalentTelemetry(prev, next) { a[k]?.costUsd !== b[k]?.costUsd || a[k]?.unpricedCalls !== b[k]?.unpricedCalls || a[k]?.totalTokens !== b[k]?.totalTokens || + a[k]?.inputTokens !== b[k]?.inputTokens || + a[k]?.cacheReadTokens !== b[k]?.cacheReadTokens || + a[k]?.thinkingTokens !== b[k]?.thinkingTokens || + a[k]?.responseTokens !== b[k]?.responseTokens || a[k]?.calls !== b[k]?.calls || + (a[k]?.avgTokPerSec ?? null) !== (b[k]?.avgTokPerSec ?? null) || + (a[k]?.avgTtftSec ?? null) !== (b[k]?.avgTtftSec ?? null) || + (a[k]?.cacheHitPct ?? null) !== (b[k]?.cacheHitPct ?? null) || Number(a[k]?.anomalyCount || 0) !== Number(b[k]?.anomalyCount || 0) || Number(a[k]?.anomalySteps || 0) !== Number(b[k]?.anomalySteps || 0) ) { @@ -5668,6 +5977,10 @@ function isEquivalentTelemetry(prev, next) { for (let i = 0; i < pTrend.length; i++) { if ( pTrend[i]?.tokens !== nTrend[i]?.tokens || + pTrend[i]?.inputTokens !== nTrend[i]?.inputTokens || + pTrend[i]?.cacheReadTokens !== nTrend[i]?.cacheReadTokens || + pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens || + pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens || pTrend[i]?.calls !== nTrend[i]?.calls || pTrend[i]?.label !== nTrend[i]?.label || pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || @@ -5716,6 +6029,22 @@ function isEquivalentTelemetry(prev, next) { } } + const pTopConvs = prev.consumption?.topConversations || []; + const nTopConvs = next.consumption?.topConversations || []; + if (pTopConvs.length !== nTopConvs.length) return false; + for (let i = 0; i < pTopConvs.length; i++) { + if ( + pTopConvs[i]?.cascadeId !== nTopConvs[i]?.cascadeId || + pTopConvs[i]?.title !== nTopConvs[i]?.title || + pTopConvs[i]?.totalTokens !== nTopConvs[i]?.totalTokens || + pTopConvs[i]?.costUsd !== nTopConvs[i]?.costUsd || + pTopConvs[i]?.calls !== nTopConvs[i]?.calls || + !areModelSlicesEqual(pTopConvs[i]?.models, nTopConvs[i]?.models) + ) { + return false; + } + } + // 8. 比对账号订阅档位与动态多配额池 if ( prev.account?.email !== next.account?.email || @@ -6028,6 +6357,7 @@ async function requestTelemetry(params, force) { account: latestSt.telemetry.consumption.account, trendSeries: latestSt.telemetry.consumption.trendSeries, sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown, + topConversations: latestSt.telemetry.consumption.topConversations, }, modelBreakdown: latestSt.telemetry.modelBreakdown, }; @@ -7107,7 +7437,7 @@ return { TopLongPillNav }; })(); // --- src/components/ui/CustomSelect.js --- -const { CustomSelect } = (() => { +const { filterSelectOptionsByQuery, CustomSelect } = (() => { /** * @fileoverview Bespoke CustomSelect dropdown component replacing native '); @@ -1659,9 +1660,16 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro topbarSegBtns[5].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); - assert.equal(mockSettings.enableCliStatusLine, false, 'CLI bottom capsule toggle turns off enableCliStatusLine'); + assert.equal(mockSettings.contextAgentMode, 'auto', 'Capsule/Hover context mode switches to follow active (auto)'); topbarSegBtns[4].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.contextAgentMode, 'main', 'Capsule/Hover context mode switches back to lock main agent'); + + topbarSegBtns[7].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + assert.equal(mockSettings.enableCliStatusLine, false, 'CLI bottom capsule toggle turns off enableCliStatusLine'); + topbarSegBtns[6].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.enableCliStatusLine, true, 'CLI bottom capsule toggle restores enableCliStatusLine'); // Dynamic 1..5 capsule slots via EditableSlotList (+ / - / ↑ / ↓ & mouse drag-and-drop) @@ -6015,3 +6023,285 @@ test('SettingsStructureTab CLI statusLine controls stay hidden unless CLI is det globalThis.fetch = prevFetch; } }); + +test('Issue #35: topbar capsule and hover HUD lock to main agent by default, toggle cleanly to follow-active, and preserve manual main selection', async () => { + const { + buildExportableSettingsJson, + parseImportedSettingsJson, + } = await import('../src/core/settingsBackup.js'); + + // 1. Settings backup exports and re-imports contextAgentMode cleanly + const exported = buildExportableSettingsJson({ contextAgentMode: 'auto' }); + const parsedBackup = parseImportedSettingsJson(exported); + assert.equal(parsedBackup.ok, true); + assert.equal(parsedBackup.patch.contextAgentMode, 'auto'); + + // 2. Compiled app.js E2E with Main Agent (44.3%) vs active running Subagent (63.7%) + const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); + const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); + const rootUuid = '11111111-2222-3333-4444-555555555555'; + const subUuid = 'sub-worker-5'; + + const { document: mockDocument, body, makeElement } = createMockDom({ + defaultRect: { left: 900, right: 1080, top: 6, bottom: 32, width: 180, height: 26 }, + }); + const titlebar = makeElement('div'); + titlebar.className = 'flex items-center @container/titlebar'; + const titleRight = makeElement('div'); + titleRight.className = 'flex items-center gap-1'; + titlebar.appendChild(titleRight); + body.appendChild(titlebar); + + const mockSettings = { + language: 'zh-CN', + themeAccent: 'host', + fontScale: 'md', + modernUi: true, + windowMountMode: 'dual', + enableWindowOverlay: true, + showTopbarMultiSession: true, + contextAgentMode: 'main', + topbarCapsuleSlots: ['tps', 'ttft', 'context'], + hoverModules: ['metrics', 'context'], + overviewModules: ['metrics', 'context'], + overviewMetrics: ['tps', 'ttft', 'avg_tps', 'step_cost'], + stepTableColumns: ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost'], + }; + + const mainContext = { + totalTokens: 113408, + limitTokens: 256000, + compactionLimitTokens: 256000, + usedPct: 44.3, + messagesTokens: 90000, + toolResultsTokens: 54000, + assistantTokens: 22000, + userInputTokens: 14000, + systemPromptTokens: 10000, + systemToolsTokens: 13408, + }; + const subContext = { + totalTokens: 163072, + limitTokens: 256000, + compactionLimitTokens: 256000, + usedPct: 63.7, + messagesTokens: 138000, + toolResultsTokens: 96000, + assistantTokens: 30000, + userInputTokens: 12000, + systemPromptTokens: 11000, + systemToolsTokens: 14072, + }; + + const buildPayload = () => ({ + bundleVersion: 'ver-issue35', + settings: { ...mockSettings }, + quotas: { pools: [] }, + conversations: [ + { + cascadeId: rootUuid, + title: 'Main Task With Active Subagent', + isRunning: true, + stepCount: 12, + subagentCount: 1, + contextUsedPct: 44.3, + }, + ], + runningConversations: [], + activeConversation: { + cascadeId: rootUuid, + title: 'Main Task With Active Subagent', + isRunning: true, + hasSubagents: true, + subagentCount: 1, + stepCount: 12, + latestTokPerSec: 65, + avgTokPerSec: 60, + latestTtftSec: 1.1, + context: mainContext, + agents: [ + { + agentId: 'main', + cascadeId: rootUuid, + isMain: true, + agentKind: 'main', + index: 0, + badgeText: '主', + role: '主代理', + isRunning: false, + stepCount: 8, + latestTokPerSec: 65, + avgTokPerSec: 60, + latestTtftSec: 1.1, + context: mainContext, + recentSteps: [], + }, + { + agentId: subUuid, + cascadeId: subUuid, + isMain: false, + agentKind: 'subagent', + agentOrdinal: 1, + index: 1, + badgeText: '子1', + shortLabel: '子代理 #1', + role: 'Subagent Worker', + isRunning: true, + stepCount: 4, + latestTokPerSec: 88, + avgTokPerSec: 80, + latestTtftSec: 0.7, + context: subContext, + recentSteps: [], + }, + ], + aggregated: { + agentId: 'all', + isRunning: true, + stepCount: 12, + activeAgentId: subUuid, + activeAgentKind: 'subagent', + activeAgentOrdinal: 1, + activeAgentBadge: '子1', + latestTokPerSec: 88, + avgTokPerSec: 70, + latestTtftSec: 0.7, + context: subContext, + }, + }, + consumption: { range: '7d', summary: {}, trendSeries: [], topModels: [], topConversations: [] }, + }); + + const mockLocation = { pathname: `/c/${rootUuid}`, href: `http://localhost/c/${rootUuid}` }; + const mockWindow = { + innerWidth: 1280, + innerHeight: 800, + location: mockLocation, + document: mockDocument, + __AGUsageMonitorBridge: { port: 49235, token: 'tok-35', version: 'ver-issue35', platform: 'win32' }, + addEventListener() {}, + removeEventListener() {}, + getComputedStyle: () => ({ display: 'flex', flexDirection: 'row', visibility: 'visible' }), + requestAnimationFrame: (cb) => setTimeout(cb, 0), + cancelAnimationFrame: (id) => clearTimeout(id), + fetch: async (url, opts = {}) => { + const urlStr = String(url); + if (urlStr.includes('/styles.css')) { + return { ok: true, status: 200, text: async () => stylesCss }; + } + if (urlStr.includes('/api/settings') && String(opts.method || '').toUpperCase() === 'POST') { + Object.assign(mockSettings, JSON.parse(opts.body || '{}')); + return { ok: true, status: 200, json: async () => ({ ok: true, settings: { ...mockSettings } }) }; + } + return { ok: true, status: 200, json: async () => buildPayload() }; + }, + }; + mockWindow.window = mockWindow; + mockWindow.globalThis = mockWindow; + + const sandbox = vm.createContext({ + window: mockWindow, + globalThis: mockWindow, + document: mockDocument, + location: mockLocation, + navigator: {}, + URLSearchParams, + AbortController, + setTimeout, + clearTimeout, + setInterval, + clearInterval, + queueMicrotask, + fetch: mockWindow.fetch, + console, + }); + + const readVal = (el) => el?.getAttribute?.('data-od-value') || el?.textContent || ''; + + vm.runInContext(appJs, sandbox); + await new Promise((r) => setTimeout(r, 50)); + + const ov = mockWindow.__AGUsageMonitorOverlay; + try { + assert.ok(ov, 'Overlay initialized'); + const capsuleHost = mockDocument.getElementById('ag-usage-monitor-capsule'); + const portalHost = mockDocument.getElementById('ag-usage-monitor-portal'); + const capsuleBtn = capsuleHost.shadowRoot.querySelector('.wm-capsule-btn'); + const ctxPctEl = capsuleHost.shadowRoot.querySelector('.wm-ctx-pct'); + const hoverTipEl = portalHost.shadowRoot.querySelector('.wm-hover-tip'); + + // A. Default contextAgentMode === 'main': topbar capsule & hover HUD lock to Main (44% / 44.3%) + assert.equal(readVal(ctxPctEl), '44%', 'Topbar capsule locks to Main Agent (44%) despite active subagent (64%)'); + capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 }); + await new Promise((r) => setTimeout(r, 20)); + const hoverCtxPanel = hoverTipEl.querySelector('.ctx-legend-grid')?.parentNode; + assert.ok(hoverCtxPanel, 'Hover HUD context panel rendered'); + assert.match(hoverCtxPanel.textContent, /44\.3%/, 'Hover HUD locks to Main Agent 44.3%'); + assert.match(hoverCtxPanel.textContent, /主代理/, 'Hover HUD shows Main Agent badge'); + + // B. Full panel defaults to Main, and clicking subagent pill inside panel does NOT hijack capsule/hover + ov.open(); + await new Promise((r) => setTimeout(r, 25)); + const popoverEl = portalHost.shadowRoot.querySelector('.wm-popover-panel'); + const overviewCtxPanel = popoverEl.querySelector('.overview-modules-host .ctx-legend-grid')?.parentNode; + assert.ok(overviewCtxPanel, 'Overview context panel rendered'); + const subPill = overviewCtxPanel.querySelector(`.ctx-agent-pill[data-pill-key="${subUuid}"]`); + const mainPill = overviewCtxPanel.querySelector('.ctx-agent-pill[data-pill-key="main"]'); + assert.equal(mainPill.classList.contains('is-active'), true, 'Full panel defaults to Main Agent pill'); + assert.match(overviewCtxPanel.textContent, /44\.3%/); + + subPill.onclick({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 25)); + assert.equal(subPill.classList.contains('is-active'), true, 'Full panel can still inspect subagent on demand'); + assert.match(overviewCtxPanel.textContent, /63\.7%/, 'Full panel shows inspected subagent 63.7%'); + assert.equal(readVal(ctxPctEl), '44%', 'Topbar capsule stays locked to Main Agent (44%) while panel inspects subagent'); + ov.close(); + capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 }); + await new Promise((r) => setTimeout(r, 20)); + assert.match(hoverCtxPanel.textContent, /44\.3%/, 'Hover HUD stays locked to Main Agent (44.3%)'); + + // C. Switching toggle to 'auto' (跟随活跃) makes capsule & hover follow active subagent (64% / 63.7%) + ov.open(); + await new Promise((r) => setTimeout(r, 20)); + const navTabs = popoverEl.querySelectorAll('.pill-tab'); + navTabs[navTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} }); // Settings + await new Promise((r) => setTimeout(r, 20)); + const settingsRoot = popoverEl.querySelector('.settings-view-root'); + const subTabs = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn'); + subTabs[1].dispatchEvent({ type: 'click', stopPropagation() {} }); // Structure + await new Promise((r) => setTimeout(r, 25)); + const [, structurePane] = settingsRoot.querySelectorAll('.settings-tab-stack'); + const autoBtn = Array.from(structurePane.querySelectorAll('.seg-btn')).find( + (b) => b.textContent.trim() === '跟随活跃' + ); + assert.ok(autoBtn, 'Context agent mode toggle renders 跟随活跃 option'); + autoBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 35)); + assert.equal(mockSettings.contextAgentMode, 'auto'); + assert.equal(readVal(ctxPctEl), '64%', 'Topbar capsule follows active subagent (64%) when switched to auto'); + ov.close(); + capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 }); + await new Promise((r) => setTimeout(r, 20)); + assert.match(hoverCtxPanel.textContent, /63\.7%/, 'Hover HUD follows active subagent (63.7%) when switched to auto'); + + // D. Manual '主' lock in auto mode survives same-session syncHostRoute() without resetting to 'auto' + ov.open(); + await new Promise((r) => setTimeout(r, 20)); + navTabs[0].dispatchEvent({ type: 'click', stopPropagation() {} }); // Overview + await new Promise((r) => setTimeout(r, 20)); + const mainPillAfterAuto = overviewCtxPanel.querySelector('.ctx-agent-pill[data-pill-key="main"]'); + mainPillAfterAuto.onclick({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 20)); + assert.equal(readVal(ctxPctEl), '44%', 'Manual main pill updates topbar capsule to 44% in auto mode'); + + // Simulate host route refresh on the same root conversation (e.g. focus/subagent jitter) + mockLocation.pathname = '/'; + ov.syncHostRoute(); + mockLocation.pathname = `/c/${rootUuid}`; + ov.syncHostRoute(); + await new Promise((r) => setTimeout(r, 35)); + assert.equal(readVal(ctxPctEl), '44%', 'Same-session route refresh preserves manual main lock instead of resetting to auto'); + } finally { + ov?.dispose?.(); + } +}); From 95a3c0c3550b98172e541e1105866cb0ca32fd8c Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 22 Nov 2026 17:39:00 +0900 Subject: [PATCH 19/31] feat(panel): upgrade topbar quota ring indicators, unify structure previews, and polish quota panel --- sidecars/panel/app.js | 297 +++++++++++------- sidecars/panel/index.html | 4 +- .../settings/structurePreviewMock.js | 34 +- .../components/widgets/CapsuleBarWidget.js | 26 +- .../components/widgets/QuotaPoolsWidget.js | 33 +- sidecars/panel/src/core/formatters.js | 1 + sidecars/panel/src/i18n/en-US.js | 1 - sidecars/panel/src/i18n/zh-CN.js | 1 - .../panel/src/registries/metricRegistry.js | 41 ++- sidecars/panel/src/styles/modern-ui.css | 7 + sidecars/panel/src/styles/overlay.css | 44 ++- sidecars/panel/src/styles/views-overview.css | 19 ++ sidecars/panel/src/styles/views-settings.css | 9 +- .../views/settings/SettingsStructureTab.js | 168 ++++++---- sidecars/panel/styles.css | 79 ++++- sidecars/panel/test/window-bridge.test.mjs | 36 ++- 16 files changed, 533 insertions(+), 267 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index e943bd0..842870e 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1807,7 +1807,6 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px', 'settings.str.multiToggle': '实时运行会话入口', 'settings.str.contextAgentModeLabel': '胶囊及悬浮上下文', - 'settings.str.contextAgentModeHint': '锁定主代理时,顶栏百分比及悬停速览始终展示主代理;完整面板内仍可随时点选子代理明细', 'settings.str.contextAgentMain': '锁定主代理', 'settings.str.contextAgentAuto': '跟随活跃', 'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊', @@ -2668,7 +2667,6 @@ 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.contextAgentModeLabel': 'Capsule & Hover Context', - 'settings.str.contextAgentModeHint': 'Lock to Main Agent keeps the topbar percentage and hover HUD on Main Agent; you can still inspect subagents inside the full panel', 'settings.str.contextAgentMain': 'Lock Main Agent', 'settings.str.contextAgentAuto': 'Follow Active', 'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule', @@ -4518,6 +4516,7 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { target.baseModelUpstream ?? target.activeModelUpstream ?? target.modelUpstream ?? + target.upstreamModel ?? target.upstreamName ?? '' ).trim(); @@ -16786,9 +16785,22 @@ function resolveQuotaCapsuleSummary(quotas) { ? `${tightest.label} ${tightest.windowTag} · ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} · ${tightest.windowTag}`; + const tightestIsClaude = /claude|gpt|fable|oss|third/i.test(String(tightest.label || '')); + const tightestIsGemini = !tightestIsClaude && /gemini|argon|carbon|neon|flash|pro/i.test(String(tightest.label || '')); + const tightestWinShort = tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'w' : '周'; + const poolPrefix = tightestIsClaude + ? `C${tightestWinShort}` + : tightestIsGemini + ? `G${tightestWinShort}` + : tightest.windowTag === '5h' + ? '5h' + : isEnglishLocale() + ? 'Wk' + : '周'; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), + poolPrefix, subLabelText, detailText: candidates .map((c) => { @@ -16799,6 +16811,16 @@ function resolveQuotaCapsuleSummary(quotas) { }; } +function resolveQuotaCapsulePrefix(metricKey, quotaSum) { + const isEn = isEnglishLocale(); + 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周'; + if (quotaSum?.poolPrefix) return quotaSum.poolPrefix; + return isEn ? 'Q' : '余'; +} + /** * 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。 * @@ -17018,17 +17040,25 @@ function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) : metricKey === 'quota_auto' ? resolveQuotaCapsuleSummary(slotCtx.quotas) : resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey); - const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15); - const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30); + const hasQuotaPct = Boolean(quotaSum && Number.isFinite(quotaSum.roundedPct)); + const clampedPct = hasQuotaPct ? Math.max(0, Math.min(100, quotaSum.roundedPct)) : 0; + const quotaDashOffset = hasQuotaPct + ? +(ringCircumference * (1 - clampedPct / 100)).toFixed(2) + : ringCircumference; + const isDanger = Boolean(hasQuotaPct && clampedPct <= 15); + const isWarn = Boolean(hasQuotaPct && !isDanger && clampedPct <= 30); const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : ''; return { hidden: false, metric: metricKey, segClass: 'wm-cap-slot wm-seg-quota', textClass: 'wm-slot-text wm-quota-text', - showRing: false, - dashOffset: ringCircumference, - text: quotaSum ? quotaSum.shortText : t('capsule.quotaUnknown'), + showRing: true, + ringKind: 'quota', + ringEmpty: !hasQuotaPct, + dashOffset: quotaDashOffset, + prefix: resolveQuotaCapsulePrefix(metricKey, quotaSum), + text: hasQuotaPct ? `${clampedPct}%` : '--%', toneClass, running: false, warn: isWarn, @@ -18057,7 +18087,7 @@ function createPoolQuotaRow() { h('div', { className: 'progress-track' }, [fillWk]), ]); - const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ + const el = h('div', { className: 'quota-pool-row' }, [ row5h, rowWk, ]); @@ -18107,13 +18137,7 @@ function formatQuotaSummaryFooter(quotas, account) { */ function syncPoolQuotaRow(refs, item, idx, rowEl) { const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item; - patchAttr( - rowEl, - 'style', - idx === 0 - ? 'display: flex; flex-direction: column; gap: 8px;' - : 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' - ); + patchClasses(rowEl, { 'quota-pool-row': true, 'has-divider': idx > 0 }); const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; const used5hVal = has5h ? Number(poolData.usedPct) : 0; @@ -18258,13 +18282,6 @@ const QuotaPoolsWidget = defineComponent({ }); } - const initFoot = formatQuotaSummaryFooter(null, null); - const wkFootLeft = h('span', { className: 'text-muted', text: initFoot.leftText }); - const wkFootRight = h('span', { - className: 'text-muted', - text: compactHover ? initFoot.rightText : '', - }); - const quotaPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -18274,13 +18291,6 @@ const QuotaPoolsWidget = defineComponent({ tierBadge, ]), poolsListEl, - h( - 'div', - compactHover - ? { className: 'panel-header wm-hover-quota-foot' } - : { className: 'panel-header', style: 'font-size: var(--fs-md); padding-top: 2px;' }, - [wkFootLeft, wkFootRight] - ), ]); function update({ data, minuteTick } = {}) { @@ -18293,9 +18303,6 @@ const QuotaPoolsWidget = defineComponent({ createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); - const pendingFoot = formatQuotaSummaryFooter(null, null); - patchText(wkFootLeft, pendingFoot.leftText); - patchText(wkFootRight, pendingFoot.rightText); } return; } @@ -18312,12 +18319,6 @@ const QuotaPoolsWidget = defineComponent({ createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); - - const footSummary = formatQuotaSummaryFooter(quotas, data.account); - patchText(wkFootLeft, footSummary.leftText); - patchText(wkFootRight, footSummary.rightText); - patchAttr(wkFootLeft, 'title', footSummary.tooltip); - patchAttr(wkFootRight, 'title', footSummary.tooltip); } return { @@ -20186,6 +20187,7 @@ function createCapsuleSlotNode(slotIndex, initialMetric) { const isNone = initialMetric === 'none'; const isCtx = initialMetric === 'context'; + const prefixSpan = h('span', { className: 'wm-slot-prefix' }); const textSpan = h('span', { className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text', text: isNone @@ -20196,7 +20198,7 @@ function createCapsuleSlotNode(slotIndex, initialMetric) { ? '-- t/s' : initialMetric === 'ttft' ? '--s' - : t('capsule.quotaUnknown'), + : '--%', }); const el = h( 'span', @@ -20222,8 +20224,10 @@ function createCapsuleSlotNode(slotIndex, initialMetric) { el, ringSvg, ringFill, + prefixSpan, textSpan, ringMounted: isCtx, + prefixMounted: false, }; } @@ -20250,13 +20254,25 @@ function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx) { patchAttr(slot.el, 'data-vis-rank', String(visRank)); if (pres.showRing && !slot.ringMounted) { - slot.el.insertBefore(slot.ringSvg, slot.textSpan); + slot.el.insertBefore(slot.ringSvg, slot.el.firstChild || slot.textSpan); slot.ringMounted = true; } else if (!pres.showRing && slot.ringMounted) { slot.ringSvg.remove(); slot.ringMounted = false; } + const prefixText = String(pres.prefix || ''); + if (prefixText) { + patchText(slot.prefixSpan, prefixText); + if (!slot.prefixMounted) { + slot.el.insertBefore(slot.prefixSpan, slot.textSpan); + slot.prefixMounted = true; + } + } else if (slot.prefixMounted) { + slot.prefixSpan.remove(); + slot.prefixMounted = false; + } + const toneCls = pres.toneClass || (pres.danger ? 'tone-danger' : pres.warn ? 'tone-warn' : ''); const fullSegClass = `${pres.segClass}${pres.running ? ' state-running' : ''}${toneCls ? ` ${toneCls}` : ''}`; @@ -20267,7 +20283,12 @@ function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx) { if (pres.showRing) { slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset)); - patchClasses(slot.ringFill, { 'tone-warn': pres.warn, 'tone-danger': pres.danger }); + patchClasses(slot.ringFill, { + 'is-quota': pres.ringKind === 'quota', + 'is-empty': pres.ringEmpty === true, + 'tone-warn': pres.warn, + 'tone-danger': pres.danger, + }); } } @@ -22417,10 +22438,12 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) isSubagent: false, agentBadge: '主', agentLabel: t('fmt.mainAgent'), - modelLabel: 'Gemini 4 Carbon (High)', - modelShort: 'gemini-4-carbon', - rawModel: 'MODEL_PLACEHOLDER_M37', - upstreamModel: 'gemini-4-carbon-high', + modelKey: 'MODEL_PLACEHOLDER_M667', + modelLabel: 'Gemini Pro Orchestrator (Carbon)', + modelShort: 'orchestrator-carbon', + rawModel: 'MODEL_PLACEHOLDER_M667', + modelUpstream: 'gemini-pro-orchestrator', + upstreamModel: 'gemini-pro-orchestrator', tokPerSec: 17.8, ttftSec: 19.4, totalDurationSec: 31.2, @@ -22474,18 +22497,19 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) outputTokens: 22100, totalTokens: 1434500, latestModelLabel: 'Gemini 4 Carbon (High)', - latestModelShort: 'gemini-4-carbon', + latestModelShort: 'carbon-4-high', latestRawModel: 'MODEL_PLACEHOLDER_M37', latestUpstreamModel: 'gemini-4-carbon-high', activeModelLabel: 'Gemini 4 Carbon (High)', - activeModelShort: 'gemini-4-carbon', + activeModelShort: 'carbon-4-high', activeModelUpstream: 'gemini-4-carbon-high', sessionUnpricedCalls: 0, modelBreakdown: [ { modelKey: 'MODEL_PLACEHOLDER_M37', - modelShort: 'gemini-4-carbon', + modelShort: 'carbon-4-high', modelLabel: 'Gemini 4 Carbon (High)', + modelUpstream: 'gemini-4-carbon-high', upstreamModel: 'gemini-4-carbon-high', calls: 16, inputTokens: 152400, @@ -22505,6 +22529,8 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) agentId: 'sub-1', cascadeId: 'mock-sub-1', isMain: false, + agentKind: 'subagent', + agentOrdinal: 1, index: 1, badgeText: '子1', shortLabel: `${t('fmt.subAgent')} #1`, @@ -22528,18 +22554,19 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) outputTokens: 6300, totalTokens: 320300, latestModelLabel: 'Gemini 3.8 Flash', - latestModelShort: 'gemini-3.8-flash', + latestModelShort: 'flash-3.8', latestRawModel: 'MODEL_PLACEHOLDER_M42', latestUpstreamModel: 'gemini-3.8-flash-n', activeModelLabel: 'Gemini 3.8 Flash', - activeModelShort: 'gemini-3.8-flash', + activeModelShort: 'flash-3.8', activeModelUpstream: 'gemini-3.8-flash-n', sessionUnpricedCalls: 0, modelBreakdown: [ { modelKey: 'MODEL_PLACEHOLDER_M42', - modelShort: 'gemini-3.8-flash', + modelShort: 'flash-3.8', modelLabel: 'Gemini 3.8 Flash', + modelUpstream: 'gemini-3.8-flash-n', upstreamModel: 'gemini-3.8-flash-n', calls: 8, inputTokens: 34000, @@ -22562,9 +22589,9 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) agentKind: 'all', agentOrdinal: 0, badgeText: t('header.scopeAllShort'), - activeAgentId: 'main', - activeAgentKind: 'main', - activeAgentOrdinal: 0, + activeAgentId: 'sub-1', + activeAgentKind: 'subagent', + activeAgentOrdinal: 1, stepCount: 24, speedSampleCount: 23, speedSummary: { sampleCount: 23, excludedCount: 1 }, @@ -22578,7 +22605,7 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) cacheReadTokens: 1540000, outputTokens: 28400, totalTokens: 1754800, - activeAgentBadge: t('fmt.mainBadge'), + activeAgentBadge: '子1', modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], recentSteps: mockSteps, }; @@ -25137,75 +25164,113 @@ function isSameList(a, b) { return true; } -function formatCliPreviewSlot(slotKey, isEn) { +function formatCliPreviewSlot(slotKey, slotCtx, isEn) { + const safeCtx = slotCtx || {}; + const quotas = safeCtx.quotas || {}; + const quotaPct = (key, fallback) => { + const summary = resolveSpecificQuotaSlotSummary(quotas, key); + return summary && Number.isFinite(summary.roundedPct) ? summary.roundedPct : fallback; + }; switch (slotKey) { - case 'tps': - return { prefix: '', text: '68.4 t/s', tone: 'good', pillPct: null }; - case 'avg_tps': + case 'tps': { + const val = Number.isFinite(Number(safeCtx.tps)) ? Number(safeCtx.tps).toFixed(1) : '68.4'; + return { prefix: '', text: `${val} t/s`, tone: 'good', pillPct: null }; + } + case 'avg_tps': { + const val = Number.isFinite(Number(safeCtx.avgTps)) ? Number(safeCtx.avgTps).toFixed(1) : '59.6'; return { prefix: '', - text: isEn ? 'avg 54.0' : '均 54.0', + text: isEn ? `avg ${val}` : `均 ${val}`, tone: 'info', pillPct: null, }; - case 'ttft': - return { prefix: '', text: '1.1s', tone: 'good', pillPct: null }; - case 'cost': - return { prefix: '', text: '$0.040', tone: 'normal', pillPct: null }; - case 'session_cost': - return { prefix: '', text: '$0.42', tone: 'normal', pillPct: null }; - case 'cache_hit': + } + case 'ttft': { + const val = Number.isFinite(Number(safeCtx.ttft)) ? formatMetric(Number(safeCtx.ttft), 's') : '1.1s'; + return { prefix: '', text: val, tone: 'good', pillPct: null }; + } + case 'cost': { + const num = Number.isFinite(Number(safeCtx.stepCost)) ? Number(safeCtx.stepCost) : 0.042; + return { prefix: '', text: `$${num.toFixed(3)}`, tone: 'normal', pillPct: null }; + } + case 'session_cost': { + const num = Number.isFinite(Number(safeCtx.sessionCost)) ? Number(safeCtx.sessionCost) : 1.28; + return { prefix: '', text: formatUsd(num), tone: 'normal', pillPct: null }; + } + case 'cache_hit': { + const pct = Number.isFinite(Number(safeCtx.cacheHitPct)) + ? Math.round(Number(safeCtx.cacheHitPct)) + : 95; return { prefix: '', - text: isEn ? 'cache 92%' : '缓 92%', + text: isEn ? `cache ${pct}%` : `缓 ${pct}%`, tone: 'good', pillPct: null, }; - case 'session_tokens': - return { prefix: '', text: '142K tok', tone: 'muted', pillPct: null }; - case 'quota_auto': + } + case 'session_tokens': { + const tokStr = Number.isFinite(Number(safeCtx.sessionTokens)) + ? formatTokens(Number(safeCtx.sessionTokens)) + : '1.8M'; + return { prefix: '', text: `${tokStr} tok`, tone: 'muted', pillPct: null }; + } + case 'quota_auto': { + const pct = quotaPct('quota_auto', 64); return { prefix: isEn ? '5h ' : '余 ', - text: '64%', + text: `${pct}%`, tone: 'good', - pillPct: 64, + pillPct: pct, }; - case 'gemini_5h': + } + case 'gemini_5h': { + const pct = quotaPct('gemini_5h', 64); return { prefix: 'G5h ', - text: '64%', + text: `${pct}%`, tone: 'good', - pillPct: 64, + pillPct: pct, }; - case 'gemini_weekly': + } + case 'gemini_weekly': { + const pct = quotaPct('gemini_weekly', 52); return { prefix: isEn ? 'Gw ' : 'G周 ', - text: '88%', + text: `${pct}%`, tone: 'good', - pillPct: 88, + pillPct: pct, }; - case 'claude_5h': + } + case 'claude_5h': { + const pct = quotaPct('claude_5h', 32); return { prefix: 'C5h ', - text: '96%', + text: `${pct}%`, tone: 'good', - pillPct: 96, + pillPct: pct, }; - case 'claude_weekly': + } + case 'claude_weekly': { + const pct = quotaPct('claude_weekly', 59); return { prefix: isEn ? 'Cw ' : 'C周 ', - text: '99%', + text: `${pct}%`, tone: 'good', - pillPct: 99, + pillPct: pct, }; + } case 'context': - default: + default: { + const pct = Number.isFinite(Number(safeCtx.usedPct)) + ? Math.round(Number(safeCtx.usedPct)) + : 56; return { prefix: isEn ? 'Ctx ' : '上下文 ', - text: '56%', + text: `${pct}%`, tone: 'accent', - pillPct: 56, + pillPct: pct, }; + } } } @@ -25364,10 +25429,6 @@ const SettingsStructureTab = defineComponent({ className: 'form-label', text: t('settings.str.popoverWidthLabel'), }); - const popoverWidthHintEl = h('span', { - className: 'settings-hint-text', - text: t('settings.str.popoverWidthHint'), - }); const multiToggleLabelEl = h('span', { className: 'form-label', text: t('settings.str.multiToggle'), @@ -25376,10 +25437,6 @@ const SettingsStructureTab = defineComponent({ className: 'form-label', text: t('settings.str.contextAgentModeLabel'), }); - const contextAgentModeHintEl = h('span', { - className: 'settings-hint-text', - text: t('settings.str.contextAgentModeHint'), - }); const cliCapsuleLabelEl = h('span', { className: 'form-label', text: t('settings.str.cliCapsuleToggle'), @@ -25532,7 +25589,7 @@ const SettingsStructureTab = defineComponent({ }); const cliPreviewMultiTextEl = h('span', { - text: t('settings.str.cliPreviewRunning', { count: 2 }), + text: t('settings.str.cliPreviewRunning', { count: 1 }), }); const cliPreviewMultiEl = h('span', { className: 'cli-preview-multi' }, [ h('span', { className: 'cli-preview-dot', 'aria-hidden': 'true', text: '●' }), @@ -25660,37 +25717,42 @@ const SettingsStructureTab = defineComponent({ h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]), mountBridgeNotice.el, - h('div', { className: 'form-row' }, [ - h('div', { className: 'settings-inline-row' }, [ - popoverWidthLabelEl, - h('div', { className: 'settings-inline-controls' }, [ - popoverWidthModeToggle.el, - popoverWidthNumWrap, - ]), + h('div', { className: 'settings-inline-row' }, [ + popoverWidthLabelEl, + h('div', { className: 'settings-inline-controls' }, [ + popoverWidthModeToggle.el, + popoverWidthNumWrap, ]), - popoverWidthHintEl, ]), h('div', { className: 'settings-inline-row' }, [ multiToggleLabelEl, multiSessionToggle.el, ]), - h('div', { className: 'form-row' }, [ - h('div', { className: 'settings-inline-row' }, [ - contextAgentModeLabelEl, - contextAgentModeToggle.el, - ]), - contextAgentModeHintEl, + h('div', { className: 'settings-inline-row' }, [ + contextAgentModeLabelEl, + contextAgentModeToggle.el, ]), h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]), cliStatusGroupEl, ], }); - function refreshCliPreview() { + function refreshCliPreview(previewData = null) { const effectiveSlots = getEffectiveDraftCliSlots(); const isEn = getEffectiveLocale() === 'en-US'; + const mockData = previewData || buildDraftTelemetry(); + const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( + mockData, + 'all', + resolveOverlayCtxInspectorAgentId(mockData, 'auto') + ); + const slotCtx = buildCapsuleSlotContext(mockData, { scopedConv, ctxAgent, aggregated }); + const runningCount = Math.max( + 1, + Array.isArray(mockData?.runningConversations) ? mockData.runningConversations.length : 1 + ); patchAttr(cliPreviewMultiEl, 'hidden', !draftShowTopbarMulti); - patchText(cliPreviewMultiTextEl, t('settings.str.cliPreviewRunning', { count: 2 })); + patchText(cliPreviewMultiTextEl, t('settings.str.cliPreviewRunning', { count: runningCount })); for (let i = 0; i < cliPreviewSlotParts.length; i += 1) { const parts = cliPreviewSlotParts[i]; const sepEl = i > 0 ? cliPreviewSepEls[i - 1] : null; @@ -25699,7 +25761,7 @@ const SettingsStructureTab = defineComponent({ patchAttr(parts.slotEl, 'hidden', !visible); if (sepEl) patchAttr(sepEl, 'hidden', !visible); if (visible) { - const item = formatCliPreviewSlot(key, isEn); + const item = formatCliPreviewSlot(key, slotCtx, isEn); const isPill = Number.isFinite(item.pillPct); patchAttr(parts.slotEl, 'data-metric', key); patchText(parts.prefixEl, item.prefix || ''); @@ -25718,8 +25780,9 @@ const SettingsStructureTab = defineComponent({ function refreshMountPreview() { if (!isStructureVisible() || activeThirdTab !== 'mount') return; - capsulePreviewWidget.refs.update({ data: buildDraftTelemetry() }); - refreshCliPreview(); + const mockData = buildDraftTelemetry(); + capsulePreviewWidget.refs.update({ data: mockData }); + refreshCliPreview(mockData); } function syncMountSectionMeta() { @@ -26460,11 +26523,9 @@ const SettingsStructureTab = defineComponent({ mountSection.refs.setResetLabel(t('settings.resetBtn')); patchText(mountModeLabelEl, t('settings.str.mountMode')); patchText(popoverWidthLabelEl, t('settings.str.popoverWidthLabel')); - patchText(popoverWidthHintEl, t('settings.str.popoverWidthHint')); popoverWidthStepper.setProps({ ariaLabel: t('settings.str.popoverWidthLabel') }); patchText(multiToggleLabelEl, t('settings.str.multiToggle')); patchText(contextAgentModeLabelEl, t('settings.str.contextAgentModeLabel')); - patchText(contextAgentModeHintEl, t('settings.str.contextAgentModeHint')); patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle')); patchText(cliSlotsLabelEl, t('settings.str.cliSlotsLabel')); patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel')); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index cdee470..39692f1 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/settings/structurePreviewMock.js b/sidecars/panel/src/components/settings/structurePreviewMock.js index 9cc2e4a..147cb08 100644 --- a/sidecars/panel/src/components/settings/structurePreviewMock.js +++ b/sidecars/panel/src/components/settings/structurePreviewMock.js @@ -186,10 +186,12 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides isSubagent: false, agentBadge: '主', agentLabel: t('fmt.mainAgent'), - modelLabel: 'Gemini 4 Carbon (High)', - modelShort: 'gemini-4-carbon', - rawModel: 'MODEL_PLACEHOLDER_M37', - upstreamModel: 'gemini-4-carbon-high', + modelKey: 'MODEL_PLACEHOLDER_M667', + modelLabel: 'Gemini Pro Orchestrator (Carbon)', + modelShort: 'orchestrator-carbon', + rawModel: 'MODEL_PLACEHOLDER_M667', + modelUpstream: 'gemini-pro-orchestrator', + upstreamModel: 'gemini-pro-orchestrator', tokPerSec: 17.8, ttftSec: 19.4, totalDurationSec: 31.2, @@ -243,18 +245,19 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides outputTokens: 22100, totalTokens: 1434500, latestModelLabel: 'Gemini 4 Carbon (High)', - latestModelShort: 'gemini-4-carbon', + latestModelShort: 'carbon-4-high', latestRawModel: 'MODEL_PLACEHOLDER_M37', latestUpstreamModel: 'gemini-4-carbon-high', activeModelLabel: 'Gemini 4 Carbon (High)', - activeModelShort: 'gemini-4-carbon', + activeModelShort: 'carbon-4-high', activeModelUpstream: 'gemini-4-carbon-high', sessionUnpricedCalls: 0, modelBreakdown: [ { modelKey: 'MODEL_PLACEHOLDER_M37', - modelShort: 'gemini-4-carbon', + modelShort: 'carbon-4-high', modelLabel: 'Gemini 4 Carbon (High)', + modelUpstream: 'gemini-4-carbon-high', upstreamModel: 'gemini-4-carbon-high', calls: 16, inputTokens: 152400, @@ -274,6 +277,8 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides agentId: 'sub-1', cascadeId: 'mock-sub-1', isMain: false, + agentKind: 'subagent', + agentOrdinal: 1, index: 1, badgeText: '子1', shortLabel: `${t('fmt.subAgent')} #1`, @@ -297,18 +302,19 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides outputTokens: 6300, totalTokens: 320300, latestModelLabel: 'Gemini 3.8 Flash', - latestModelShort: 'gemini-3.8-flash', + latestModelShort: 'flash-3.8', latestRawModel: 'MODEL_PLACEHOLDER_M42', latestUpstreamModel: 'gemini-3.8-flash-n', activeModelLabel: 'Gemini 3.8 Flash', - activeModelShort: 'gemini-3.8-flash', + activeModelShort: 'flash-3.8', activeModelUpstream: 'gemini-3.8-flash-n', sessionUnpricedCalls: 0, modelBreakdown: [ { modelKey: 'MODEL_PLACEHOLDER_M42', - modelShort: 'gemini-3.8-flash', + modelShort: 'flash-3.8', modelLabel: 'Gemini 3.8 Flash', + modelUpstream: 'gemini-3.8-flash-n', upstreamModel: 'gemini-3.8-flash-n', calls: 8, inputTokens: 34000, @@ -331,9 +337,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides agentKind: 'all', agentOrdinal: 0, badgeText: t('header.scopeAllShort'), - activeAgentId: 'main', - activeAgentKind: 'main', - activeAgentOrdinal: 0, + activeAgentId: 'sub-1', + activeAgentKind: 'subagent', + activeAgentOrdinal: 1, stepCount: 24, speedSampleCount: 23, speedSummary: { sampleCount: 23, excludedCount: 1 }, @@ -347,7 +353,7 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides cacheReadTokens: 1540000, outputTokens: 28400, totalTokens: 1754800, - activeAgentBadge: t('fmt.mainBadge'), + activeAgentBadge: '子1', modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], recentSteps: mockSteps, }; diff --git a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index e08d016..359786d 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -310,6 +310,7 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) { const isNone = initialMetric === 'none'; const isCtx = initialMetric === 'context'; + const prefixSpan = h('span', { className: 'wm-slot-prefix' }); const textSpan = h('span', { className: isCtx ? 'wm-slot-text wm-ctx-pct' : 'wm-slot-text', text: isNone @@ -320,7 +321,7 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) { ? '-- t/s' : initialMetric === 'ttft' ? '--s' - : t('capsule.quotaUnknown'), + : '--%', }); const el = h( 'span', @@ -346,8 +347,10 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) { el, ringSvg, ringFill, + prefixSpan, textSpan, ringMounted: isCtx, + prefixMounted: false, }; } @@ -374,13 +377,25 @@ export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCt patchAttr(slot.el, 'data-vis-rank', String(visRank)); if (pres.showRing && !slot.ringMounted) { - slot.el.insertBefore(slot.ringSvg, slot.textSpan); + slot.el.insertBefore(slot.ringSvg, slot.el.firstChild || slot.textSpan); slot.ringMounted = true; } else if (!pres.showRing && slot.ringMounted) { slot.ringSvg.remove(); slot.ringMounted = false; } + const prefixText = String(pres.prefix || ''); + if (prefixText) { + patchText(slot.prefixSpan, prefixText); + if (!slot.prefixMounted) { + slot.el.insertBefore(slot.prefixSpan, slot.textSpan); + slot.prefixMounted = true; + } + } else if (slot.prefixMounted) { + slot.prefixSpan.remove(); + slot.prefixMounted = false; + } + const toneCls = pres.toneClass || (pres.danger ? 'tone-danger' : pres.warn ? 'tone-warn' : ''); const fullSegClass = `${pres.segClass}${pres.running ? ' state-running' : ''}${toneCls ? ` ${toneCls}` : ''}`; @@ -391,7 +406,12 @@ export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCt if (pres.showRing) { slot.ringFill.setAttribute('stroke-dashoffset', String(pres.dashOffset)); - patchClasses(slot.ringFill, { 'tone-warn': pres.warn, 'tone-danger': pres.danger }); + patchClasses(slot.ringFill, { + 'is-quota': pres.ringKind === 'quota', + 'is-empty': pres.ringEmpty === true, + 'tone-warn': pres.warn, + 'tone-danger': pres.danger, + }); } } diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index 224adf4..5d3f503 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -88,7 +88,7 @@ export function createPoolQuotaRow() { h('div', { className: 'progress-track' }, [fillWk]), ]); - const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [ + const el = h('div', { className: 'quota-pool-row' }, [ row5h, rowWk, ]); @@ -138,13 +138,7 @@ export function formatQuotaSummaryFooter(quotas, account) { */ export function syncPoolQuotaRow(refs, item, idx, rowEl) { const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item; - patchAttr( - rowEl, - 'style', - idx === 0 - ? 'display: flex; flex-direction: column; gap: 8px;' - : 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);' - ); + patchClasses(rowEl, { 'quota-pool-row': true, 'has-divider': idx > 0 }); const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; const used5hVal = has5h ? Number(poolData.usedPct) : 0; @@ -289,13 +283,6 @@ export const QuotaPoolsWidget = defineComponent({ }); } - const initFoot = formatQuotaSummaryFooter(null, null); - const wkFootLeft = h('span', { className: 'text-muted', text: initFoot.leftText }); - const wkFootRight = h('span', { - className: 'text-muted', - text: compactHover ? initFoot.rightText : '', - }); - const quotaPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -305,13 +292,6 @@ export const QuotaPoolsWidget = defineComponent({ tierBadge, ]), poolsListEl, - h( - 'div', - compactHover - ? { className: 'panel-header wm-hover-quota-foot' } - : { className: 'panel-header', style: 'font-size: var(--fs-md); padding-top: 2px;' }, - [wkFootLeft, wkFootRight] - ), ]); function update({ data, minuteTick } = {}) { @@ -324,9 +304,6 @@ export const QuotaPoolsWidget = defineComponent({ createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); - const pendingFoot = formatQuotaSummaryFooter(null, null); - patchText(wkFootLeft, pendingFoot.leftText); - patchText(wkFootRight, pendingFoot.rightText); } return; } @@ -343,12 +320,6 @@ export const QuotaPoolsWidget = defineComponent({ createRow: createPoolQuotaRow, updateRow: syncPoolQuotaRow, }); - - const footSummary = formatQuotaSummaryFooter(quotas, data.account); - patchText(wkFootLeft, footSummary.leftText); - patchText(wkFootRight, footSummary.rightText); - patchAttr(wkFootLeft, 'title', footSummary.tooltip); - patchAttr(wkFootRight, 'title', footSummary.tooltip); } return { diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index fff94cc..7c520b9 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -616,6 +616,7 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) { target.baseModelUpstream ?? target.activeModelUpstream ?? target.modelUpstream ?? + target.upstreamModel ?? target.upstreamName ?? '' ).trim(); diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index d7018e7..a9cd875 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -618,7 +618,6 @@ 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.contextAgentModeLabel': 'Capsule & Hover Context', - 'settings.str.contextAgentModeHint': 'Lock to Main Agent keeps the topbar percentage and hover HUD on Main Agent; you can still inspect subagents inside the full panel', 'settings.str.contextAgentMain': 'Lock Main Agent', 'settings.str.contextAgentAuto': 'Follow Active', 'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 2ff7561..cc5bbc1 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -618,7 +618,6 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px', 'settings.str.multiToggle': '实时运行会话入口', 'settings.str.contextAgentModeLabel': '胶囊及悬浮上下文', - 'settings.str.contextAgentModeHint': '锁定主代理时,顶栏百分比及悬停速览始终展示主代理;完整面板内仍可随时点选子代理明细', 'settings.str.contextAgentMain': '锁定主代理', 'settings.str.contextAgentAuto': '跟随活跃', 'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊', diff --git a/sidecars/panel/src/registries/metricRegistry.js b/sidecars/panel/src/registries/metricRegistry.js index 9e70df0..10a7f4c 100644 --- a/sidecars/panel/src/registries/metricRegistry.js +++ b/sidecars/panel/src/registries/metricRegistry.js @@ -96,9 +96,22 @@ export function resolveQuotaCapsuleSummary(quotas) { ? `${tightest.label} ${tightest.windowTag} · ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} · ${tightest.windowTag}`; + const tightestIsClaude = /claude|gpt|fable|oss|third/i.test(String(tightest.label || '')); + const tightestIsGemini = !tightestIsClaude && /gemini|argon|carbon|neon|flash|pro/i.test(String(tightest.label || '')); + const tightestWinShort = tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'w' : '周'; + const poolPrefix = tightestIsClaude + ? `C${tightestWinShort}` + : tightestIsGemini + ? `G${tightestWinShort}` + : tightest.windowTag === '5h' + ? '5h' + : isEnglishLocale() + ? 'Wk' + : '周'; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), + poolPrefix, subLabelText, detailText: candidates .map((c) => { @@ -109,6 +122,16 @@ export function resolveQuotaCapsuleSummary(quotas) { }; } +function resolveQuotaCapsulePrefix(metricKey, quotaSum) { + const isEn = isEnglishLocale(); + 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周'; + if (quotaSum?.poolPrefix) return quotaSum.poolPrefix; + return isEn ? 'Q' : '余'; +} + /** * 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。 * @@ -328,17 +351,25 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf : metricKey === 'quota_auto' ? resolveQuotaCapsuleSummary(slotCtx.quotas) : resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey); - const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15); - const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30); + const hasQuotaPct = Boolean(quotaSum && Number.isFinite(quotaSum.roundedPct)); + const clampedPct = hasQuotaPct ? Math.max(0, Math.min(100, quotaSum.roundedPct)) : 0; + const quotaDashOffset = hasQuotaPct + ? +(ringCircumference * (1 - clampedPct / 100)).toFixed(2) + : ringCircumference; + const isDanger = Boolean(hasQuotaPct && clampedPct <= 15); + const isWarn = Boolean(hasQuotaPct && !isDanger && clampedPct <= 30); const toneClass = isDanger ? 'tone-danger' : isWarn ? 'tone-warn' : ''; return { hidden: false, metric: metricKey, segClass: 'wm-cap-slot wm-seg-quota', textClass: 'wm-slot-text wm-quota-text', - showRing: false, - dashOffset: ringCircumference, - text: quotaSum ? quotaSum.shortText : t('capsule.quotaUnknown'), + showRing: true, + ringKind: 'quota', + ringEmpty: !hasQuotaPct, + dashOffset: quotaDashOffset, + prefix: resolveQuotaCapsulePrefix(metricKey, quotaSum), + text: hasQuotaPct ? `${clampedPct}%` : '--%', toneClass, running: false, warn: isWarn, diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 10bb1e9..20fbb75 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -650,6 +650,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .structure-preview-empty, [data-modern-ui="true"] .preview-sidebar-note, [data-modern-ui="true"] .preview-capsule-bar, +[data-modern-ui="true"] .cli-status-preview, [data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-multi-btn, [data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-capsule-btn, [data-modern-ui="true"] .preview-composer-chip { @@ -657,6 +658,10 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-surface-subtle); } +[data-modern-ui="true"][data-color-scheme="light"] .quota-pool-row.has-divider { + border-top-color: hsl(216 24% 92%); +} + [data-modern-ui="true"] .slot-add-btn, [data-modern-ui="true"] .settings-bridge-relaunch-btn { border: none; @@ -940,8 +945,10 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } :host([data-modern-ui="true"]) .wm-slot-text.wm-ctx-pct[data-od-active="1"], +:host([data-modern-ui="true"]) .wm-slot-text.wm-quota-text[data-od-active="1"], :host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"], [data-modern-ui="true"] .wm-slot-text.wm-ctx-pct[data-od-active="1"], +[data-modern-ui="true"] .wm-slot-text.wm-quota-text[data-od-active="1"], [data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { justify-content: flex-start; } diff --git a/sidecars/panel/src/styles/overlay.css b/sidecars/panel/src/styles/overlay.css index b77c47c..145967e 100644 --- a/sidecars/panel/src/styles/overlay.css +++ b/sidecars/panel/src/styles/overlay.css @@ -262,6 +262,14 @@ stroke var(--dur-fast) var(--ease-fast); } +.wm-ring-fill.is-quota { + stroke: var(--metric-ok); +} + +.wm-ring-fill.is-empty { + stroke: transparent; +} + .wm-ring-fill.tone-warn { stroke: var(--metric-warn); } @@ -324,14 +332,35 @@ font-weight: 500; } -/* 配额槽位(固定预占宽度 52px 居中对齐,完整容纳 余 100% / 余 --% 且在任意槽位对称) */ +/* 配额槽位(环形剩余进度圈 + 池/窗口短标 + 清晰百分比,零嵌套边框) */ .wm-seg-quota { - width: 52px; + justify-content: center; + gap: 4px; + width: auto; + min-width: 68px; + padding: 0 2px; +} + +.wm-slot-prefix { + display: inline-block; + font-size: inherit; + font-weight: 500; + color: var(--text-secondary); + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; } .wm-quota-text { - width: 52px; - text-align: center; + min-width: 28px; + max-width: none; + overflow: visible; + text-overflow: clip; + text-align: left; + font-weight: 500; + color: var(--text-primary); } /* 缓存命中率槽位(固定预占宽度 44px 居中对齐) */ @@ -504,6 +533,8 @@ :host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="4"], :host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="5"], :host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-slot-prefix, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-quota-text, :host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label { display: none !important; } @@ -512,8 +543,11 @@ padding: 0 6px; } -:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg { +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-seg-quota { width: 14px; + min-width: 14px; + padding: 0; } /* --- 2. 顶层浮层传送门宿主 (Body Portal Host: Multi-Session HUD, Tooltip & Full 4-Tab Popover) --- */ diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 3b20082..640d357 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -53,6 +53,25 @@ white-space: nowrap; } +/* 配额池分组行及池间分隔线(暗黑模式保留原分割色,浅色模式使用柔和细线) */ +.quota-pool-row { + display: flex; + flex-direction: column; + gap: 8px; +} + +.quota-pool-row.has-divider { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid var(--border-hairline); +} + +:root[data-color-scheme="light"] .quota-pool-row.has-divider, +:host([data-color-scheme="light"]) .quota-pool-row.has-divider, +[data-color-scheme="light"] .quota-pool-row.has-divider { + border-top-color: color-mix(in srgb, var(--text-primary) 7%, transparent); +} + /* 配额池窗口行头:标题 + 周期用量内联(窄栏自适应截断,零额外纵向行高) */ .quota-win-head { gap: 8px; diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index de6aefe..bfe476e 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -1453,6 +1453,7 @@ .cli-preview-prefix { color: var(--text-secondary); font-weight: 400; + white-space: pre; } .cli-preview-val { @@ -1472,8 +1473,8 @@ } .cli-preview-slot.is-pill { - --cli-pill-track: color-mix(in srgb, var(--text-primary) 10%, var(--surface-panel)); - --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 34%, var(--surface-panel)); + --cli-pill-track: color-mix(in srgb, var(--text-primary) 7%, transparent); + --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 24%, transparent); padding: 1px 6px; border-radius: 3px; background: linear-gradient( @@ -1486,11 +1487,11 @@ } .cli-preview-slot.is-pill.tone-good { - --cli-pill-fill: color-mix(in srgb, var(--metric-ok) 32%, var(--surface-panel)); + --cli-pill-fill: color-mix(in srgb, var(--metric-ok) 22%, transparent); } .cli-preview-slot.is-pill.tone-accent { - --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 34%, var(--surface-panel)); + --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 24%, transparent); } .cli-preview-slot.is-pill .cli-preview-prefix { diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index 514d67f..f1b3311 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -8,11 +8,13 @@ import { defineComponent } from '../../core/component.js'; import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; +import { formatMetric, formatTokens, formatUsd } from '../../core/formatters.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; import { getCapsuleMetricOptions, getOverviewMetricOptions, + resolveSpecificQuotaSlotSummary, } from '../../registries/metricRegistry.js'; import { getStepColumnOptions } from '../../registries/stepColumnRegistry.js'; import { @@ -43,6 +45,7 @@ import { normalizeClientWindowMountMode, resolveEffectiveClientCliStatusLineSlots, resolveOverlayCtxInspectorAgentId, + resolveScopedConversation, saveSettingsPatch, triggerCliStatusLineAction, } from '../../store/telemetryStore.js'; @@ -54,7 +57,10 @@ import { buildStructurePreviewTelemetry } from '../../components/settings/struct import { CustomNumberInput } from '../../components/ui/CustomNumberInput.js'; import { CustomSelect } from '../../components/ui/CustomSelect.js'; import { SegmentedControl } from '../../components/ui/SegmentedControl.js'; -import { CapsuleBarWidget } from '../../components/widgets/CapsuleBarWidget.js'; +import { + CapsuleBarWidget, + buildCapsuleSlotContext, +} from '../../components/widgets/CapsuleBarWidget.js'; import { StepTableWidget } from '../../components/widgets/StepTableWidget.js'; const STRUCTURE_THIRD_TABS = Object.freeze([ @@ -113,75 +119,113 @@ function isSameList(a, b) { return true; } -function formatCliPreviewSlot(slotKey, isEn) { +function formatCliPreviewSlot(slotKey, slotCtx, isEn) { + const safeCtx = slotCtx || {}; + const quotas = safeCtx.quotas || {}; + const quotaPct = (key, fallback) => { + const summary = resolveSpecificQuotaSlotSummary(quotas, key); + return summary && Number.isFinite(summary.roundedPct) ? summary.roundedPct : fallback; + }; switch (slotKey) { - case 'tps': - return { prefix: '', text: '68.4 t/s', tone: 'good', pillPct: null }; - case 'avg_tps': + case 'tps': { + const val = Number.isFinite(Number(safeCtx.tps)) ? Number(safeCtx.tps).toFixed(1) : '68.4'; + return { prefix: '', text: `${val} t/s`, tone: 'good', pillPct: null }; + } + case 'avg_tps': { + const val = Number.isFinite(Number(safeCtx.avgTps)) ? Number(safeCtx.avgTps).toFixed(1) : '59.6'; return { prefix: '', - text: isEn ? 'avg 54.0' : '均 54.0', + text: isEn ? `avg ${val}` : `均 ${val}`, tone: 'info', pillPct: null, }; - case 'ttft': - return { prefix: '', text: '1.1s', tone: 'good', pillPct: null }; - case 'cost': - return { prefix: '', text: '$0.040', tone: 'normal', pillPct: null }; - case 'session_cost': - return { prefix: '', text: '$0.42', tone: 'normal', pillPct: null }; - case 'cache_hit': + } + case 'ttft': { + const val = Number.isFinite(Number(safeCtx.ttft)) ? formatMetric(Number(safeCtx.ttft), 's') : '1.1s'; + return { prefix: '', text: val, tone: 'good', pillPct: null }; + } + case 'cost': { + const num = Number.isFinite(Number(safeCtx.stepCost)) ? Number(safeCtx.stepCost) : 0.042; + return { prefix: '', text: `$${num.toFixed(3)}`, tone: 'normal', pillPct: null }; + } + case 'session_cost': { + const num = Number.isFinite(Number(safeCtx.sessionCost)) ? Number(safeCtx.sessionCost) : 1.28; + return { prefix: '', text: formatUsd(num), tone: 'normal', pillPct: null }; + } + case 'cache_hit': { + const pct = Number.isFinite(Number(safeCtx.cacheHitPct)) + ? Math.round(Number(safeCtx.cacheHitPct)) + : 95; return { prefix: '', - text: isEn ? 'cache 92%' : '缓 92%', + text: isEn ? `cache ${pct}%` : `缓 ${pct}%`, tone: 'good', pillPct: null, }; - case 'session_tokens': - return { prefix: '', text: '142K tok', tone: 'muted', pillPct: null }; - case 'quota_auto': + } + case 'session_tokens': { + const tokStr = Number.isFinite(Number(safeCtx.sessionTokens)) + ? formatTokens(Number(safeCtx.sessionTokens)) + : '1.8M'; + return { prefix: '', text: `${tokStr} tok`, tone: 'muted', pillPct: null }; + } + case 'quota_auto': { + const pct = quotaPct('quota_auto', 64); return { prefix: isEn ? '5h ' : '余 ', - text: '64%', + text: `${pct}%`, tone: 'good', - pillPct: 64, + pillPct: pct, }; - case 'gemini_5h': + } + case 'gemini_5h': { + const pct = quotaPct('gemini_5h', 64); return { prefix: 'G5h ', - text: '64%', + text: `${pct}%`, tone: 'good', - pillPct: 64, + pillPct: pct, }; - case 'gemini_weekly': + } + case 'gemini_weekly': { + const pct = quotaPct('gemini_weekly', 52); return { prefix: isEn ? 'Gw ' : 'G周 ', - text: '88%', + text: `${pct}%`, tone: 'good', - pillPct: 88, + pillPct: pct, }; - case 'claude_5h': + } + case 'claude_5h': { + const pct = quotaPct('claude_5h', 32); return { prefix: 'C5h ', - text: '96%', + text: `${pct}%`, tone: 'good', - pillPct: 96, + pillPct: pct, }; - case 'claude_weekly': + } + case 'claude_weekly': { + const pct = quotaPct('claude_weekly', 59); return { prefix: isEn ? 'Cw ' : 'C周 ', - text: '99%', + text: `${pct}%`, tone: 'good', - pillPct: 99, + pillPct: pct, }; + } case 'context': - default: + default: { + const pct = Number.isFinite(Number(safeCtx.usedPct)) + ? Math.round(Number(safeCtx.usedPct)) + : 56; return { prefix: isEn ? 'Ctx ' : '上下文 ', - text: '56%', + text: `${pct}%`, tone: 'accent', - pillPct: 56, + pillPct: pct, }; + } } } @@ -340,10 +384,6 @@ export const SettingsStructureTab = defineComponent({ className: 'form-label', text: t('settings.str.popoverWidthLabel'), }); - const popoverWidthHintEl = h('span', { - className: 'settings-hint-text', - text: t('settings.str.popoverWidthHint'), - }); const multiToggleLabelEl = h('span', { className: 'form-label', text: t('settings.str.multiToggle'), @@ -352,10 +392,6 @@ export const SettingsStructureTab = defineComponent({ className: 'form-label', text: t('settings.str.contextAgentModeLabel'), }); - const contextAgentModeHintEl = h('span', { - className: 'settings-hint-text', - text: t('settings.str.contextAgentModeHint'), - }); const cliCapsuleLabelEl = h('span', { className: 'form-label', text: t('settings.str.cliCapsuleToggle'), @@ -508,7 +544,7 @@ export const SettingsStructureTab = defineComponent({ }); const cliPreviewMultiTextEl = h('span', { - text: t('settings.str.cliPreviewRunning', { count: 2 }), + text: t('settings.str.cliPreviewRunning', { count: 1 }), }); const cliPreviewMultiEl = h('span', { className: 'cli-preview-multi' }, [ h('span', { className: 'cli-preview-dot', 'aria-hidden': 'true', text: '●' }), @@ -636,37 +672,42 @@ export const SettingsStructureTab = defineComponent({ h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]), mountBridgeNotice.el, - h('div', { className: 'form-row' }, [ - h('div', { className: 'settings-inline-row' }, [ - popoverWidthLabelEl, - h('div', { className: 'settings-inline-controls' }, [ - popoverWidthModeToggle.el, - popoverWidthNumWrap, - ]), + h('div', { className: 'settings-inline-row' }, [ + popoverWidthLabelEl, + h('div', { className: 'settings-inline-controls' }, [ + popoverWidthModeToggle.el, + popoverWidthNumWrap, ]), - popoverWidthHintEl, ]), h('div', { className: 'settings-inline-row' }, [ multiToggleLabelEl, multiSessionToggle.el, ]), - h('div', { className: 'form-row' }, [ - h('div', { className: 'settings-inline-row' }, [ - contextAgentModeLabelEl, - contextAgentModeToggle.el, - ]), - contextAgentModeHintEl, + h('div', { className: 'settings-inline-row' }, [ + contextAgentModeLabelEl, + contextAgentModeToggle.el, ]), h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]), cliStatusGroupEl, ], }); - function refreshCliPreview() { + function refreshCliPreview(previewData = null) { const effectiveSlots = getEffectiveDraftCliSlots(); const isEn = getEffectiveLocale() === 'en-US'; + const mockData = previewData || buildDraftTelemetry(); + const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( + mockData, + 'all', + resolveOverlayCtxInspectorAgentId(mockData, 'auto') + ); + const slotCtx = buildCapsuleSlotContext(mockData, { scopedConv, ctxAgent, aggregated }); + const runningCount = Math.max( + 1, + Array.isArray(mockData?.runningConversations) ? mockData.runningConversations.length : 1 + ); patchAttr(cliPreviewMultiEl, 'hidden', !draftShowTopbarMulti); - patchText(cliPreviewMultiTextEl, t('settings.str.cliPreviewRunning', { count: 2 })); + patchText(cliPreviewMultiTextEl, t('settings.str.cliPreviewRunning', { count: runningCount })); for (let i = 0; i < cliPreviewSlotParts.length; i += 1) { const parts = cliPreviewSlotParts[i]; const sepEl = i > 0 ? cliPreviewSepEls[i - 1] : null; @@ -675,7 +716,7 @@ export const SettingsStructureTab = defineComponent({ patchAttr(parts.slotEl, 'hidden', !visible); if (sepEl) patchAttr(sepEl, 'hidden', !visible); if (visible) { - const item = formatCliPreviewSlot(key, isEn); + const item = formatCliPreviewSlot(key, slotCtx, isEn); const isPill = Number.isFinite(item.pillPct); patchAttr(parts.slotEl, 'data-metric', key); patchText(parts.prefixEl, item.prefix || ''); @@ -694,8 +735,9 @@ export const SettingsStructureTab = defineComponent({ function refreshMountPreview() { if (!isStructureVisible() || activeThirdTab !== 'mount') return; - capsulePreviewWidget.refs.update({ data: buildDraftTelemetry() }); - refreshCliPreview(); + const mockData = buildDraftTelemetry(); + capsulePreviewWidget.refs.update({ data: mockData }); + refreshCliPreview(mockData); } function syncMountSectionMeta() { @@ -1436,11 +1478,9 @@ export const SettingsStructureTab = defineComponent({ mountSection.refs.setResetLabel(t('settings.resetBtn')); patchText(mountModeLabelEl, t('settings.str.mountMode')); patchText(popoverWidthLabelEl, t('settings.str.popoverWidthLabel')); - patchText(popoverWidthHintEl, t('settings.str.popoverWidthHint')); popoverWidthStepper.setProps({ ariaLabel: t('settings.str.popoverWidthLabel') }); patchText(multiToggleLabelEl, t('settings.str.multiToggle')); patchText(contextAgentModeLabelEl, t('settings.str.contextAgentModeLabel')); - patchText(contextAgentModeHintEl, t('settings.str.contextAgentModeHint')); patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle')); patchText(cliSlotsLabelEl, t('settings.str.cliSlotsLabel')); patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel')); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 804f1cf..e9c8e0e 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -1731,6 +1731,25 @@ html[data-standalone="true"] .app-shell { white-space: nowrap; } +/* 配额池分组行及池间分隔线(暗黑模式保留原分割色,浅色模式使用柔和细线) */ +.quota-pool-row { + display: flex; + flex-direction: column; + gap: 8px; +} + +.quota-pool-row.has-divider { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid var(--border-hairline); +} + +:root[data-color-scheme="light"] .quota-pool-row.has-divider, +:host([data-color-scheme="light"]) .quota-pool-row.has-divider, +[data-color-scheme="light"] .quota-pool-row.has-divider { + border-top-color: color-mix(in srgb, var(--text-primary) 7%, transparent); +} + /* 配额池窗口行头:标题 + 周期用量内联(窄栏自适应截断,零额外纵向行高) */ .quota-win-head { gap: 8px; @@ -6833,6 +6852,7 @@ html[data-standalone="true"] .app-shell { .cli-preview-prefix { color: var(--text-secondary); font-weight: 400; + white-space: pre; } .cli-preview-val { @@ -6852,8 +6872,8 @@ html[data-standalone="true"] .app-shell { } .cli-preview-slot.is-pill { - --cli-pill-track: color-mix(in srgb, var(--text-primary) 10%, var(--surface-panel)); - --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 34%, var(--surface-panel)); + --cli-pill-track: color-mix(in srgb, var(--text-primary) 7%, transparent); + --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 24%, transparent); padding: 1px 6px; border-radius: 3px; background: linear-gradient( @@ -6866,11 +6886,11 @@ html[data-standalone="true"] .app-shell { } .cli-preview-slot.is-pill.tone-good { - --cli-pill-fill: color-mix(in srgb, var(--metric-ok) 32%, var(--surface-panel)); + --cli-pill-fill: color-mix(in srgb, var(--metric-ok) 22%, transparent); } .cli-preview-slot.is-pill.tone-accent { - --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 34%, var(--surface-panel)); + --cli-pill-fill: color-mix(in srgb, var(--accent-primary) 24%, transparent); } .cli-preview-slot.is-pill .cli-preview-prefix { @@ -7204,6 +7224,14 @@ html[data-standalone="true"] .app-shell { stroke var(--dur-fast) var(--ease-fast); } +.wm-ring-fill.is-quota { + stroke: var(--metric-ok); +} + +.wm-ring-fill.is-empty { + stroke: transparent; +} + .wm-ring-fill.tone-warn { stroke: var(--metric-warn); } @@ -7266,14 +7294,35 @@ html[data-standalone="true"] .app-shell { font-weight: 500; } -/* 配额槽位(固定预占宽度 52px 居中对齐,完整容纳 余 100% / 余 --% 且在任意槽位对称) */ +/* 配额槽位(环形剩余进度圈 + 池/窗口短标 + 清晰百分比,零嵌套边框) */ .wm-seg-quota { - width: 52px; + justify-content: center; + gap: 4px; + width: auto; + min-width: 68px; + padding: 0 2px; +} + +.wm-slot-prefix { + display: inline-block; + font-size: inherit; + font-weight: 500; + color: var(--text-secondary); + line-height: 18px; + letter-spacing: 0.015em; + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; } .wm-quota-text { - width: 52px; - text-align: center; + min-width: 28px; + max-width: none; + overflow: visible; + text-overflow: clip; + text-align: left; + font-weight: 500; + color: var(--text-primary); } /* 缓存命中率槽位(固定预占宽度 44px 居中对齐) */ @@ -7446,6 +7495,8 @@ html[data-standalone="true"] .app-shell { :host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="4"], :host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="5"], :host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-slot-prefix, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-quota-text, :host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label { display: none !important; } @@ -7454,8 +7505,11 @@ html[data-standalone="true"] .app-shell { padding: 0 6px; } -:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg { +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg, +:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-seg-quota { width: 14px; + min-width: 14px; + padding: 0; } /* --- 2. 顶层浮层传送门宿主 (Body Portal Host: Multi-Session HUD, Tooltip & Full 4-Tab Popover) --- */ @@ -8410,6 +8464,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .structure-preview-empty, [data-modern-ui="true"] .preview-sidebar-note, [data-modern-ui="true"] .preview-capsule-bar, +[data-modern-ui="true"] .cli-status-preview, [data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-multi-btn, [data-modern-ui="true"] .preview-capsule-bar.is-composer .wm-capsule-btn, [data-modern-ui="true"] .preview-composer-chip { @@ -8417,6 +8472,10 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { background: var(--modern-surface-subtle); } +[data-modern-ui="true"][data-color-scheme="light"] .quota-pool-row.has-divider { + border-top-color: hsl(216 24% 92%); +} + [data-modern-ui="true"] .slot-add-btn, [data-modern-ui="true"] .settings-bridge-relaunch-btn { border: none; @@ -8700,8 +8759,10 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } :host([data-modern-ui="true"]) .wm-slot-text.wm-ctx-pct[data-od-active="1"], +:host([data-modern-ui="true"]) .wm-slot-text.wm-quota-text[data-od-active="1"], :host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"], [data-modern-ui="true"] .wm-slot-text.wm-ctx-pct[data-od-active="1"], +[data-modern-ui="true"] .wm-slot-text.wm-quota-text[data-od-active="1"], [data-modern-ui="true"] .wm-multi-label[data-od-active="1"] { justify-content: flex-start; } diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 8f82283..65cb9be 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -1345,9 +1345,16 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const claudeHoverUsages = hoverQuotaPools.children[1].querySelectorAll('.quota-win-usage'); assert.equal(claudeHoverUsages[0].textContent, '· 0 ($0.00)'); assert.equal(claudeHoverUsages[1].textContent, '· 7.3M ($3.82)'); - const hoverFootSpans = hoverTipEl.querySelector('.wm-hover-quota-foot').children; - assert.equal(hoverFootSpans[0].textContent, '周期累计: 25.5M ($9.22)'); - assert.equal(hoverFootSpans[1].textContent, '周期调用: 160 次'); + assert.equal( + hoverTipEl.querySelector('.wm-hover-quota-foot'), + null, + 'Redundant quota cycle summary footer removed now that each pool displays inline cycle usage' + ); + assert.equal( + hoverQuotaPools.children[1].classList.contains('has-divider'), + true, + 'Secondary quota pool uses CSS class divider for light/dark polarity control' + ); // Verify clicking multi-session button pins open multi-session panel, and clicking capsule switches to 4-tab panel multiBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); @@ -1689,9 +1696,12 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro capRowSelects[0].querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h'); - assert.equal(readCapVal(capSlots[0].children[0]), '余 44%'); + assert.equal(capSlots[0].querySelector('.wm-slot-prefix')?.textContent, 'G5h'); + assert.equal(readCapVal(capSlots[0].querySelector('.wm-quota-text')), '44%'); + assert.equal(capSlots[0].querySelector('.wm-ring-fill')?.classList.contains('is-quota'), true); assert.equal(previewCapsuleSlots[0].getAttribute('data-metric'), 'gemini_5h', 'Preview slot 0 mirrors gemini_5h'); - assert.equal(readCapVal(previewCapsuleSlots[0].children[0]), '余 64%', 'Preview slot 0 renders simulated gemini_5h'); + assert.equal(previewCapsuleSlots[0].querySelector('.wm-slot-prefix')?.textContent, 'G5h'); + assert.equal(readCapVal(previewCapsuleSlots[0].querySelector('.wm-quota-text')), '64%', 'Preview slot 0 renders simulated gemini_5h'); assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft'); assert.equal(readCapVal(capSlots[1].children[0]), '0.85s'); @@ -1708,7 +1718,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro await new Promise((r) => setTimeout(r, 30)); assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']); assert.equal(readCapVal(capSlots[0].children[0]), '0.85s'); - assert.equal(readCapVal(capSlots[1].children[0]), '余 44%'); + assert.equal(capSlots[1].querySelector('.wm-slot-prefix')?.textContent, 'G5h'); + assert.equal(readCapVal(capSlots[1].querySelector('.wm-quota-text')), '44%'); // Mouse drag-and-drop reorder: drag Row 0 ('ttft') down below Row 2 ('cost') -> ['gemini_5h', 'cost', 'ttft'] const capSlotListEl = capSlotWrap.querySelector('.editable-slot-list'); @@ -5946,7 +5957,12 @@ test('SettingsStructureTab CLI statusLine controls stay hidden unless CLI is det .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%']); + assert.deepEqual(visibleSlots(), ['68.4 t/s', '1.1s', '$1.28', '余 52%', '上下文 56%']); + assert.equal( + previewEl.querySelector('.cli-preview-multi')?.textContent, + '●1 运行中', + 'CLI preview shares the exact same running count (1) as the top Antigravity preview bar' + ); const pillSlots1 = previewEl .querySelectorAll('.cli-preview-slot.is-pill') .filter((el) => !el.hasAttribute('hidden')); @@ -5964,9 +5980,9 @@ test('SettingsStructureTab CLI statusLine controls stay hidden unless CLI is det ); assert.deepEqual(visibleSlots(), [ 'G5h 64%', - 'G周 88%', - 'C5h 96%', - 'C周 99%', + 'G周 52%', + 'C5h 32%', + 'C周 59%', '上下文 56%', ]); const pillSlots2 = previewEl From 4d6d676e56b2c7003dc039d63767ebfc06c37276 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 22 Nov 2026 18:34:58 +0900 Subject: [PATCH 20/31] feat(panel): add experimental quota reservation estimator, violet bar indicator, and clipboard log export --- sidecars/panel/app.js | 457 ++++++++++++-- sidecars/panel/backend/api-actions.mjs | 16 + sidecars/panel/backend/config.mjs | 1 + sidecars/panel/backend/quota-pools.mjs | 2 + sidecars/panel/backend/quota-reservation.mjs | 563 +++++++++++++++++ sidecars/panel/backend/settings-schema.mjs | 6 + sidecars/panel/backend/telemetry-builder.mjs | 10 + sidecars/panel/backend/usage-aggregator.mjs | 27 + sidecars/panel/index.html | 4 +- .../panel/shared/settings-normalization.mjs | 14 + .../panel/shared/window-bridge-protocol.mjs | 5 + .../settings/structurePreviewMock.js | 4 + .../components/widgets/QuotaPoolsWidget.js | 186 ++++-- sidecars/panel/src/core/settingsBackup.js | 9 + sidecars/panel/src/i18n/en-US.js | 15 + sidecars/panel/src/i18n/zh-CN.js | 15 + sidecars/panel/src/store/telemetryStore.js | 28 + sidecars/panel/src/styles/tokens.css | 5 + sidecars/panel/src/styles/views-overview.css | 17 + sidecars/panel/src/styles/views-settings.css | 22 + .../src/views/settings/SettingsOtherTab.js | 183 +++++- sidecars/panel/styles.css | 44 ++ sidecars/panel/test/backend-harness.mjs | 1 + .../test/cross-module-regressions.test.mjs | 3 +- .../panel/test/quota-reservation.test.mjs | 571 ++++++++++++++++++ sidecars/panel/test/window-bridge.test.mjs | 6 +- 26 files changed, 2128 insertions(+), 86 deletions(-) create mode 100644 sidecars/panel/backend/quota-reservation.mjs create mode 100644 sidecars/panel/test/quota-reservation.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 842870e..2f7bb22 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, 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, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, normalizeContextAgentMode, 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, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -561,6 +561,20 @@ function normalizeContextAgentMode(raw) { return val === 'auto' ? 'auto' : 'main'; } +/** + * 归一化实验性配额预占估算开关(默认 `false`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +function normalizeExperimentalQuotaReservation(val) { + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(val); +} + /** * 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。 * @@ -574,7 +588,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, 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, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, normalizeContextAgentMode, 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, CONTEXT_AGENT_MODES, DEFAULT_CONTEXT_AGENT_MODE, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- @@ -869,6 +883,11 @@ const BRIDGE_API_ROUTE_DEFS = Object.freeze([ }), Object.freeze({ path: '/api/export-file', method: 'POST', action: 'export_file' }), Object.freeze({ path: '/api/reveal-file', method: 'POST', action: 'reveal_file' }), + Object.freeze({ + path: '/api/quota-reservation/log', + method: 'GET', + action: 'quota_reservation_log', + }), ]); const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); @@ -1371,6 +1390,11 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.loading': '读取中...', 'quota.failed': '获取失败 (--%)', 'quota.usedAndLeft': '{reset} · 已用 {used}% (余 {rem}%)', + 'quota.usedBeforeReserved': '{reset} · 已用 {used}% (', + 'quota.reservedTag': '预占 {rsv}%', + 'quota.usedAfterReserved': ' · 余 {rem}%)', + 'quota.reservedTip': '预占估算(试验性):约 {rsv}%(实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', + 'quota.reservedTipMulti': '预占估算(试验性):约 {rsv}%(检测到 {leases} 笔叠加租约,实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', @@ -1870,6 +1894,16 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.orchFormat': 'Orchestrator 系列 ID', 'settings.oth.orchCompact': '精简代号 (如 orchestrator-argon)', 'settings.oth.orchFull': '原始完整 ID (如 gemini-pro-orchestrator)', + 'settings.oth.expTitle': '试验性功能', + 'settings.oth.expBadge': '试验性', + 'settings.oth.quotaReserveLabel': '配额预占估算', + 'settings.oth.quotaReserveDesc': '在可用额度中估算 5h / 周限的 0.5% / 1% 租约预占,并用紫色标注占比及进度条段', + 'settings.oth.quotaReserveLogLabel': '预占观测日志', + 'settings.oth.quotaReserveLogDesc': '将内存中的配额跳变及退还记录复制到剪贴板,便于分析触发阈值', + 'settings.oth.exportReserveLogBtn': '导出预占日志', + 'settings.oth.exportReserveLogCopied': '已复制 {count} 条观测日志到剪贴板', + 'settings.oth.exportReserveLogEmpty': '暂无跳变记录,已复制当前摘要到剪贴板', + 'settings.oth.exportReserveLogFailed': '获取或复制预占日志失败', 'settings.oth.baselineTitle': '模型上下文设置', 'settings.oth.ctxRiskTitle': '非官方能力风险提示', 'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', @@ -2231,6 +2265,11 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.loading': 'Loading...', 'quota.failed': 'Unavailable (--%)', 'quota.usedAndLeft': '{reset} · Used {used}% ({rem}% left)', + 'quota.usedBeforeReserved': '{reset} · Used {used}% (', + 'quota.reservedTag': '{rsv}% rsv', + 'quota.usedAfterReserved': ' · {rem}% left)', + 'quota.reservedTip': 'Estimated lease reservation (Experimental): ~{rsv}% (~{actual}% actual used); unused share refunds after ~10 min idle', + 'quota.reservedTipMulti': 'Estimated lease reservation (Experimental): ~{rsv}% ({leases} stacked leases, ~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', @@ -2730,6 +2769,16 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.orchFormat': 'Orchestrator Series ID', 'settings.oth.orchCompact': 'Compact Alias (e.g. orchestrator-argon)', 'settings.oth.orchFull': 'Full Upstream ID (e.g. gemini-pro-orchestrator)', + 'settings.oth.expTitle': 'Experimental', + 'settings.oth.expBadge': 'Experimental', + 'settings.oth.quotaReserveLabel': 'Quota Reservation Estimate', + 'settings.oth.quotaReserveDesc': 'Estimate 0.5% / 1% 5h & weekly lease holds in Available Quotas and highlight the reserved share in violet', + 'settings.oth.quotaReserveLogLabel': 'Reservation Observation Log', + 'settings.oth.quotaReserveLogDesc': 'Copy in-memory quota jump & refund events to clipboard for threshold tuning', + 'settings.oth.exportReserveLogBtn': 'Export Reserve Log', + 'settings.oth.exportReserveLogCopied': 'Copied {count} log entries to clipboard', + 'settings.oth.exportReserveLogEmpty': 'No events yet; copied current summary to clipboard', + 'settings.oth.exportReserveLogFailed': 'Failed to copy reservation log', 'settings.oth.baselineTitle': 'Model Context Settings', 'settings.oth.ctxRiskTitle': 'Unofficial Override Risk Warning', 'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', @@ -5649,6 +5698,9 @@ function buildExportableSettingsJson(settings = {}) { showStepFilterToolbar: src.showStepFilterToolbar === true, stepTokenComboFormat: normalizeStepTokenComboFormat(src.stepTokenComboFormat), stepTableColumns: normalizeStepTableColumns(src.stepTableColumns), + experimentalQuotaReservation: normalizeExperimentalQuotaReservation( + src.experimentalQuotaReservation + ), }, }; return `${JSON.stringify(payload, null, 2)}\n`; @@ -5771,6 +5823,11 @@ function parseImportedSettingsJson(rawText) { if (hasKey('stepTableColumns') && Array.isArray(src.stepTableColumns)) { patch.stepTableColumns = normalizeStepTableColumns(src.stepTableColumns); } + if (hasKey('experimentalQuotaReservation')) { + patch.experimentalQuotaReservation = normalizeExperimentalQuotaReservation( + src.experimentalQuotaReservation + ); + } const appliedCount = Object.keys(patch).length; if (appliedCount === 0) { @@ -8626,7 +8683,7 @@ return { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFee })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, 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, normalizeClientContextAgentMode, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, 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, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -9034,6 +9091,7 @@ const normalizeClientPopoverWidth = normalizePopoverWidth; const normalizeClientModelDisplayMode = normalizeModelDisplayMode; const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; const normalizeClientContextAgentMode = normalizeContextAgentMode; +const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation; const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots; /** @@ -9172,6 +9230,12 @@ function isEquivalentTelemetry(prev, next) { if (Boolean(pSet?.showStepFilterToolbar) !== Boolean(nSet?.showStepFilterToolbar)) { return false; } + if ( + normalizeClientExperimentalQuotaReservation(pSet?.experimentalQuotaReservation) !== + normalizeClientExperimentalQuotaReservation(nSet?.experimentalQuotaReservation) + ) { + return false; + } if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false; if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false; if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false; @@ -9634,9 +9698,13 @@ function isEquivalentTelemetry(prev, next) { pPools[i]?.poolLabel !== nPools[i]?.poolLabel || pPools[i]?.usedPct !== nPools[i]?.usedPct || pPools[i]?.remainingPct !== nPools[i]?.remainingPct || + pPools[i]?.reservedPct !== nPools[i]?.reservedPct || + pPools[i]?.reservedLeaseCount !== nPools[i]?.reservedLeaseCount || pPools[i]?.resetTime !== nPools[i]?.resetTime || pPools[i]?.weeklyUsedPct !== nPools[i]?.weeklyUsedPct || pPools[i]?.weeklyRemainingPct !== nPools[i]?.weeklyRemainingPct || + pPools[i]?.weeklyReservedPct !== nPools[i]?.weeklyReservedPct || + pPools[i]?.weeklyReservedLeaseCount !== nPools[i]?.weeklyReservedLeaseCount || pPools[i]?.weeklyResetTime !== nPools[i]?.weeklyResetTime || pPools[i]?.cycle5h?.tokens !== nPools[i]?.cycle5h?.tokens || pPools[i]?.cycle5h?.costUsd !== nPools[i]?.cycle5h?.costUsd || @@ -10360,6 +10428,11 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepFilterToolbar')) { safePatch.showStepFilterToolbar = Boolean(safePatch.showStepFilterToolbar); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalQuotaReservation')) { + safePatch.experimentalQuotaReservation = normalizeClientExperimentalQuotaReservation( + safePatch.experimentalQuotaReservation + ); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } @@ -10640,6 +10713,17 @@ async function fetchSessionMigrationCatalog() { } } +async function fetchQuotaReservationLog() { + try { + return await callSidecarApi('/api/quota-reservation/log', { method: 'GET' }); + } catch { + return callSidecarApi('/api/settings', { + method: 'POST', + body: { __quotaReservationAction: 'log' }, + }); + } +} + async function executeSessionMigration(payload) { let res; try { @@ -10916,7 +11000,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, 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, normalizeClientContextAgentMode, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, 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, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -18024,7 +18108,11 @@ const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncP * @param {{ isPending?: boolean }} [options] * @returns {Array} */ -function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) { +function buildQuotaPoolItems( + quotas, + minuteTick = 0, + { isPending = false, showReserved = false } = {} +) { const safeQuotas = quotas || {}; const activePool = safeQuotas.activePool || {}; const rawPools = @@ -18051,6 +18139,7 @@ function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) isActivePool, minuteTick, isPending, + showReserved: Boolean(showReserved), }; }); if ( @@ -18064,27 +18153,45 @@ function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) } /** - * 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。 + * 创建单个配额池的 DOM 行结构,内含 5h 限额及每周限额两个可独立显隐的子窗口进度条。 */ function createPoolQuotaRow() { const title5h = h('span', { className: 'quota-win-title', text: '5h' }); const usage5h = h('span', { className: 'quota-win-usage', hidden: true, text: '' }); const left5h = h('span', { className: 'quota-win-left' }, [title5h, usage5h]); - const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' }); + const meta5hBefore = h('span', { text: '--' }); + const meta5hReserved = h('span', { className: 'quota-reserved-pct', hidden: true, text: '' }); + const meta5hAfter = h('span', { hidden: true, text: '' }); + const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono' }, [ + meta5hBefore, + meta5hReserved, + meta5hAfter, + ]); const fill5h = h('div', { className: 'progress-fill' }); + const fillReserved5h = h('div', { className: 'progress-fill-reserved' }); + const track5h = h('div', { className: 'progress-track' }, [fill5h, fillReserved5h]); const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ h('div', { className: 'panel-header quota-win-head' }, [left5h, meta5h]), - h('div', { className: 'progress-track' }, [fill5h]), + track5h, ]); const titleWk = h('span', { className: 'quota-win-title', text: t('quota.weeklyShort') }); const usageWk = h('span', { className: 'quota-win-usage', hidden: true, text: '' }); const leftWk = h('span', { className: 'quota-win-left' }, [titleWk, usageWk]); - const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' }); + const metaWkBefore = h('span', { text: '--' }); + const metaWkReserved = h('span', { className: 'quota-reserved-pct', hidden: true, text: '' }); + const metaWkAfter = h('span', { hidden: true, text: '' }); + const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono' }, [ + metaWkBefore, + metaWkReserved, + metaWkAfter, + ]); const fillWk = h('div', { className: 'progress-fill' }); + const fillReservedWk = h('div', { className: 'progress-fill-reserved' }); + const trackWk = h('div', { className: 'progress-track' }, [fillWk, fillReservedWk]); const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ h('div', { className: 'panel-header quota-win-head' }, [leftWk, metaWk]), - h('div', { className: 'progress-track' }, [fillWk]), + trackWk, ]); const el = h('div', { className: 'quota-pool-row' }, [ @@ -18100,13 +18207,23 @@ function createPoolQuotaRow() { title5h, usage5h, meta5h, + meta5hBefore, + meta5hReserved, + meta5hAfter, + track5h, fill5h, + fillReserved5h, rowWk, leftWk, titleWk, usageWk, metaWk, + metaWkBefore, + metaWkReserved, + metaWkAfter, + trackWk, fillWk, + fillReservedWk, }, }; } @@ -18132,11 +18249,84 @@ function formatQuotaSummaryFooter(quotas, account) { return { leftText, rightText, tooltip }; } +function syncQuotaWindowMeter({ + hasData, + usedVal, + remVal, + resetTime, + fallbackMetaText, + showReserved, + rawReservedPct, + leaseCount, + metaBeforeEl, + metaReservedEl, + metaAfterEl, + trackEl, + fillEl, + fillReservedEl, +}) { + const numReserved = showReserved && hasData ? Number(rawReservedPct || 0) : 0; + const rsvVal = + Number.isFinite(numReserved) && numReserved >= 0.05 ? Math.min(usedVal, numReserved) : 0; + const actualVal = Math.max(0, usedVal - rsvVal); + const resetStr = hasData ? formatCountdown(resetTime) : ''; + + if (hasData && rsvVal > 0) { + const rsvStr = rsvVal.toFixed(1); + const actualStr = actualVal.toFixed(1); + const leases = Math.max(1, Number(leaseCount) || 1); + const tipText = + leases >= 2 + ? t('quota.reservedTipMulti', { rsv: rsvStr, leases, actual: actualStr }) + : t('quota.reservedTip', { rsv: rsvStr, actual: actualStr }); + patchText( + metaBeforeEl, + t('quota.usedBeforeReserved', { reset: resetStr, used: usedVal.toFixed(1) }) + ); + metaReservedEl.hidden = false; + patchText(metaReservedEl, t('quota.reservedTag', { rsv: rsvStr })); + patchAttr(metaReservedEl, 'title', tipText); + metaAfterEl.hidden = false; + patchText(metaAfterEl, t('quota.usedAfterReserved', { rem: remVal.toFixed(1) })); + patchAttr(trackEl, 'title', tipText); + const actualWidth = +Math.min(100, actualVal).toFixed(2); + const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); + patchStyleVar(fillEl, '--fill-w', `${actualWidth}%`); + patchStyleVar(fillReservedEl, '--reserved-w', `${rsvWidth}%`); + patchClasses(fillReservedEl, { 'is-active': true }); + } else { + patchText( + metaBeforeEl, + hasData + ? t('quota.usedAndLeft', { + reset: resetStr, + used: usedVal.toFixed(1), + rem: remVal.toFixed(1), + }) + : fallbackMetaText + ); + metaReservedEl.hidden = true; + patchText(metaReservedEl, ''); + patchAttr(metaReservedEl, 'title', null); + metaAfterEl.hidden = true; + patchText(metaAfterEl, ''); + patchAttr(trackEl, 'title', null); + patchStyleVar(fillEl, '--fill-w', `${Math.min(100, usedVal)}%`); + patchStyleVar(fillReservedEl, '--reserved-w', '0%'); + patchClasses(fillReservedEl, { 'is-active': false }); + } + + patchClasses(fillEl, { + 'tone-warn': usedVal >= 70 && usedVal < 85, + 'tone-danger': usedVal >= 85, + }); +} + /** - * 同步单个配额池行的 5h 与每周窗口状态。 + * 同步单个配额池行的 5h 及每周窗口状态。 */ function syncPoolQuotaRow(refs, item, idx, rowEl) { - const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item; + const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending, showReserved } = item; patchClasses(rowEl, { 'quota-pool-row': true, 'has-divider': idx > 0 }); const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; @@ -18165,6 +18355,7 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { refs.rowWk.style.display = hideWk ? 'none' : 'flex'; const fallbackMetaText = isPending ? t('quota.loading') : t('quota.failed'); + const allowReserved = Boolean(showReserved && !isPending); patchText(refs.title5h, `5h (${poolLabel})`); const c5h = poolData?.cycle5h; @@ -18189,20 +18380,21 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.usage5h, ''); patchAttr(refs.left5h, 'title', null); } - patchText( - refs.meta5h, - has5h - ? t('quota.usedAndLeft', { - reset: formatCountdown(poolData.resetTime), - used: used5hVal.toFixed(1), - rem: rem5hVal.toFixed(1), - }) - : fallbackMetaText - ); - patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); - patchClasses(refs.fill5h, { - 'tone-warn': used5hVal >= 70 && used5hVal < 85, - 'tone-danger': used5hVal >= 85, + syncQuotaWindowMeter({ + hasData: has5h, + usedVal: used5hVal, + remVal: rem5hVal, + resetTime: poolData?.resetTime, + fallbackMetaText, + showReserved: allowReserved, + rawReservedPct: poolData?.reservedPct, + leaseCount: poolData?.reservedLeaseCount, + metaBeforeEl: refs.meta5hBefore, + metaReservedEl: refs.meta5hReserved, + metaAfterEl: refs.meta5hAfter, + trackEl: refs.track5h, + fillEl: refs.fill5h, + fillReservedEl: refs.fillReserved5h, }); const customTitle = @@ -18236,20 +18428,21 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.usageWk, ''); patchAttr(refs.leftWk, 'title', null); } - patchText( - refs.metaWk, - hasWk - ? t('quota.usedAndLeft', { - reset: formatCountdown(wkResetRaw), - used: usedWkVal.toFixed(1), - rem: remWkVal.toFixed(1), - }) - : fallbackMetaText - ); - patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); - patchClasses(refs.fillWk, { - 'tone-warn': usedWkVal >= 70 && usedWkVal < 85, - 'tone-danger': usedWkVal >= 85, + syncQuotaWindowMeter({ + hasData: hasWk, + usedVal: usedWkVal, + remVal: remWkVal, + resetTime: wkResetRaw, + fallbackMetaText, + showReserved: allowReserved && !useCustomWeekly, + rawReservedPct: poolData?.weeklyReservedPct, + leaseCount: poolData?.weeklyReservedLeaseCount, + metaBeforeEl: refs.metaWkBefore, + metaReservedEl: refs.metaWkReserved, + metaAfterEl: refs.metaWkAfter, + trackEl: refs.trackWk, + fillEl: refs.fillWk, + fillReservedEl: refs.fillReservedWk, }); } @@ -18257,7 +18450,7 @@ function quotaPoolRowSig(item, idx) { const c5h = item.poolData?.cycle5h; const cWk = item.poolData?.cycleWeekly; const fw = item.fallbackWeekly; - return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; + return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } const QuotaPoolsWidget = defineComponent({ @@ -18308,12 +18501,13 @@ const QuotaPoolsWidget = defineComponent({ } const quotas = data.quotas || {}; + const showReserved = data.settings?.experimentalQuotaReservation === true; const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000); patchText( tierBadge, `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` ); - patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick), { + patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick, { showReserved }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, createRow: createPoolQuotaRow, @@ -22641,9 +22835,13 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) family: 'Gemini', usedPct: 36, remainingPct: 64, + reservedPct: 1.0, + reservedLeaseCount: 1, resetTime: reset5hIso, weeklyUsedPct: 48, weeklyRemainingPct: 52, + weeklyReservedPct: 0.5, + weeklyReservedLeaseCount: 1, weeklyResetTime: resetWkIso, cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 }, cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 }, @@ -26668,6 +26866,29 @@ const { SettingsOtherTab } = (() => { */ +function getEnableToggleOptions() { + return [ + { value: 'on', label: t('settings.str.on') }, + { value: 'off', label: t('settings.str.off') }, + ]; +} + +function formatQuotaReservationLogForClipboard(snapshot) { + const safe = snapshot && typeof snapshot === 'object' ? snapshot : {}; + const buckets = Array.isArray(safe.buckets) ? safe.buckets : []; + const events = Array.isArray(safe.events) ? safe.events : []; + const bucketLines = buckets.map((b) => ` ${JSON.stringify(b)}`).join(',\n'); + const eventLines = events.map((e) => ` ${JSON.stringify(e)}`).join(',\n'); + return [ + '{', + ` "generatedAt": ${JSON.stringify(safe.generatedAt || new Date().toISOString())},`, + ` "count": ${events.length},`, + ` "buckets": [${bucketLines ? `\n${bucketLines}\n ` : ''}],`, + ` "events": [${eventLines ? `\n${eventLines}\n ` : ''}]`, + '}', + ].join('\n'); +} + function getStepModelDisplayOptions() { return [ { value: 'short', label: t('settings.oth.modelShort') }, @@ -26688,6 +26909,7 @@ const SettingsOtherTab = defineComponent({ setup({ onCleanup, getProps }) { let draftModelDisplayMode = 'short'; let draftOrchestratorIdMode = 'compact'; + let draftExperimentalQuotaReservation = false; let draftContextRiskAccepted = false; let acceptingContextRisk = false; let latestSettings = null; @@ -26698,6 +26920,7 @@ const SettingsOtherTab = defineComponent({ let savingContextWindow = false; let contextFeedback = ''; let modelTimer = null; + let expTimer = null; let maintTimer = null; let resetConfirmTimer = null; let resetConfirmArmed = false; @@ -26709,12 +26932,31 @@ const SettingsOtherTab = defineComponent({ style: 'font-size: var(--fs-md);', text: '', }); + const expStatusText = h('span', { + className: 'text-muted', + style: 'font-size: var(--fs-md);', + text: '', + }); const maintStatusText = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: '', }); + function showExpFeedback(text, autoClearMs = 1500) { + if (expTimer) { + clearTimeout(expTimer); + expTimer = null; + } + patchText(expStatusText, text); + if (text && autoClearMs > 0) { + expTimer = setTimeout(() => { + expTimer = null; + patchText(expStatusText, ''); + }, autoClearMs); + } + } + function showModelFeedback(text, autoClearMs = 1500) { if (modelTimer) { clearTimeout(modelTimer); @@ -26807,6 +27049,112 @@ const SettingsOtherTab = defineComponent({ h('div', { className: 'form-row' }, [orchFormatLabelEl, orchestratorIdSelect.el]), ]); + // --- Card 2: 试验性功能 --- + const expTitleEl = h('span', { text: t('settings.oth.expTitle') }); + const quotaReserveLabelEl = h('span', { + className: 'settings-action-title', + text: t('settings.oth.quotaReserveLabel'), + }); + const quotaReserveBadgeEl = h('span', { + className: 'settings-experimental-badge', + text: t('settings.oth.expBadge'), + }); + const quotaReserveDescEl = h('span', { + className: 'settings-action-desc', + text: t('settings.oth.quotaReserveDesc'), + }); + const quotaReserveLogLabelEl = h('span', { + className: 'settings-action-title', + text: t('settings.oth.quotaReserveLogLabel'), + }); + const quotaReserveLogDescEl = h('span', { + className: 'settings-action-desc', + text: t('settings.oth.quotaReserveLogDesc'), + }); + const exportReserveLogBtnText = h('span', { + text: t('settings.oth.exportReserveLogBtn'), + }); + let isExportingReserveLog = false; + + const exportReserveLogBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary', + onClick: async () => { + if (isExportingReserveLog) return; + isExportingReserveLog = true; + patchAttr(exportReserveLogBtn, 'disabled', true); + try { + const snapshot = await fetchQuotaReservationLog(); + const text = formatQuotaReservationLogForClipboard(snapshot); + const count = Array.isArray(snapshot?.events) ? snapshot.events.length : 0; + const successMsg = + count > 0 + ? t('settings.oth.exportReserveLogCopied', { count }) + : t('settings.oth.exportReserveLogEmpty'); + const ok = await copyTextWithFeedback(text, successMsg); + showExpFeedback(ok ? successMsg : t('settings.oth.exportReserveLogFailed'), 2800); + } catch { + showExpFeedback(t('settings.oth.exportReserveLogFailed'), 2800); + } finally { + isExportingReserveLog = false; + patchAttr(exportReserveLogBtn, 'disabled', false); + } + }, + }, + [createSvgIcon('copy', { size: 12 }), exportReserveLogBtnText] + ); + + const quotaReserveToggle = SegmentedControl({ + modelValue: 'off', + ariaLabel: t('settings.oth.quotaReserveLabel'), + options: getEnableToggleOptions(), + onUpdateModelValue: async (val) => { + const nextEnabled = val === 'on'; + draftExperimentalQuotaReservation = nextEnabled; + quotaReserveToggle.setProps({ + modelValue: nextEnabled ? 'on' : 'off', + options: getEnableToggleOptions(), + }); + showExpFeedback(t('settings.saving'), 0); + try { + await saveSettingsPatch({ experimentalQuotaReservation: nextEnabled }); + showExpFeedback(t('settings.saved'), 1500); + } catch { + if (latestSettings) renderSettings(latestSettings); + showExpFeedback(t('settings.saveFailed'), 2500); + } + }, + }); + + const experimentalPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + expTitleEl, + ]), + expStatusText, + ]), + h('div', { className: 'settings-action-block' }, [ + h('div', { className: 'settings-action-info' }, [ + h('div', { className: 'settings-experimental-label-group' }, [ + quotaReserveLabelEl, + quotaReserveBadgeEl, + ]), + quotaReserveDescEl, + ]), + quotaReserveToggle.el, + ]), + h('div', { className: 'settings-action-block' }, [ + h('div', { className: 'settings-action-info' }, [ + quotaReserveLogLabelEl, + quotaReserveLogDescEl, + ]), + exportReserveLogBtn, + ]), + ]); + // --- Card 2: 按模型设置上下文窗口 --- const baselineTitleEl = h('span', { text: t('settings.oth.baselineTitle') }); const ctxModelLabel = h('span', { className: 'form-label' }); @@ -27254,6 +27602,7 @@ const SettingsOtherTab = defineComponent({ const rootEl = h('div', { className: 'settings-tab-stack' }, [ modelPanel, + experimentalPanel, baselinePanel, maintPanel, sessionMigrationCard.el, @@ -27275,6 +27624,9 @@ const SettingsOtherTab = defineComponent({ settings.showUpstreamModel ); draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode); + draftExperimentalQuotaReservation = normalizeClientExperimentalQuotaReservation( + settings.experimentalQuotaReservation + ); if (!acceptingContextRisk) { draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted); } @@ -27286,6 +27638,11 @@ const SettingsOtherTab = defineComponent({ modelValue: draftOrchestratorIdMode, options: getOrchestratorIdDisplayOptions(), }); + quotaReserveToggle.setProps({ + modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.quotaReserveLabel'), + }); renderContextWindows(); void sessionMigrationCard.refs.ensureLoaded(); } @@ -27294,6 +27651,18 @@ const SettingsOtherTab = defineComponent({ patchText(modelCardTitleEl, t('settings.oth.modelTitle')); patchText(modelFormatLabelEl, t('settings.oth.modelFormat')); patchText(orchFormatLabelEl, t('settings.oth.orchFormat')); + patchText(expTitleEl, t('settings.oth.expTitle')); + patchText(quotaReserveLabelEl, t('settings.oth.quotaReserveLabel')); + patchText(quotaReserveBadgeEl, t('settings.oth.expBadge')); + patchText(quotaReserveDescEl, t('settings.oth.quotaReserveDesc')); + patchText(quotaReserveLogLabelEl, t('settings.oth.quotaReserveLogLabel')); + patchText(quotaReserveLogDescEl, t('settings.oth.quotaReserveLogDesc')); + patchText(exportReserveLogBtnText, t('settings.oth.exportReserveLogBtn')); + quotaReserveToggle.setProps({ + modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.quotaReserveLabel'), + }); patchText(baselineTitleEl, t('settings.oth.baselineTitle')); renderContextWindows(); patchText(maintTitleEl, t('settings.oth.maintTitle')); @@ -27329,10 +27698,12 @@ const SettingsOtherTab = defineComponent({ onCleanup(() => { if (modelTimer) clearTimeout(modelTimer); + if (expTimer) clearTimeout(expTimer); if (maintTimer) clearTimeout(maintTimer); if (resetConfirmTimer) clearTimeout(resetConfirmTimer); stepModelSelect.destroy(); orchestratorIdSelect.destroy(); + quotaReserveToggle.destroy(); ctxBridgeNotice.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); @@ -27344,6 +27715,8 @@ const SettingsOtherTab = defineComponent({ refs: { stepModelSelect, orchestratorIdSelect, + quotaReserveToggle, + exportReserveLogBtn, ctxBridgeNotice, ctxModelSelect, ctxWindowSelect, diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index d092ba7..7a40c97 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -64,6 +64,7 @@ import { resolveDevToolsPortCandidates, startDefaultWindowBridge, } from './window-bridge.mjs'; +import { getQuotaReservationLogSnapshot } from './quota-reservation.mjs'; import { getSessionMigrationCatalog, migrateSessions } from './session-migrator.mjs'; import { ensureCliStatusLineConfigured, @@ -750,6 +751,16 @@ export function executeExportFileAction(data, opts = {}) { }; } +export function executeQuotaReservationLogAction() { + const snapshot = getQuotaReservationLogSnapshot(); + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ ok: true, ...snapshot }), + }; +} + export function executeRevealFileAction(data, opts = {}) { const result = revealLocalExportFile(data?.filePath, { ...(opts?.platform ? { platform: opts.platform } : {}), @@ -791,6 +802,9 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un if (isPlainObject(data) && data.__exportFileAction === 'reveal') { return executeRevealFileAction(data.payload || data, opts); } + if (isPlainObject(data) && data.__quotaReservationAction === 'log') { + return executeQuotaReservationLogAction(); + } return executeSettingsAction(data); case 'accounts_get': return executeAccountCredentialAction(undefined, opts); @@ -816,6 +830,8 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un return executeExportFileAction(data, opts); case 'reveal_file': return executeRevealFileAction(data, opts); + case 'quota_reservation_log': + return executeQuotaReservationLogAction(); default: return { status: 404, diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 23776dd..281f44b 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -45,6 +45,7 @@ export { createDefaultSettingsObject, normalizeCliStatusLineSlots, normalizeContextAgentMode, + normalizeExperimentalQuotaReservation, normalizeFontScale, normalizeFullSettings, normalizeHoverModules, diff --git a/sidecars/panel/backend/quota-pools.mjs b/sidecars/panel/backend/quota-pools.mjs index 47d6729..c8dd7fe 100644 --- a/sidecars/panel/backend/quota-pools.mjs +++ b/sidecars/panel/backend/quota-pools.mjs @@ -418,10 +418,12 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { isAvailable: Boolean(b5h || bWk), has5h: Boolean(b5h), hasWeekly: Boolean(bWk), + remainingFraction: b5h?.remainingFraction ?? null, remainingPct: b5h?.remainingPct ?? null, remainingIntPct: b5h?.remainingIntPct ?? null, usedPct: b5h?.usedPct ?? null, resetTime: b5h?.resetTime || null, + weeklyRemainingFraction: bWk?.remainingFraction ?? null, weeklyRemainingPct: bWk?.remainingPct ?? null, weeklyRemainingIntPct: bWk?.remainingIntPct ?? null, weeklyUsedPct: bWk?.usedPct ?? null, diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs new file mode 100644 index 0000000..b06a654 --- /dev/null +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -0,0 +1,563 @@ +/** + * @fileoverview 实验性配额预占估算器(`quota-reservation.mjs`)。 + * + * 基于分布式配额租约(Per-Bucket / Per-Session Quota Lease)的行为特征: + * 1. 5h 桶及周限桶各自独立追踪(支持错档触发); + * 2. 多高消耗会话并发时支持多笔租约线性叠加(如 0.5% / 1.0% / 2.0%+); + * 3. 在租约期内继续产生真实消耗时按单桶换算率扣减可退差额; + * 4. 上游退还租约(同周期内 officialUsedPct 下降)时按 FIFO 精准核销并反向校准单桶费率; + * 5. 纯内存 O(1) 状态机,零额外 RPC、零额外磁盘写入。 + */ + +import { parseIsoMs } from '../trajectory-metrics.mjs'; + +export const QR_LEASE_TTL_MS = 10 * 60 * 1000; +export const QR_LEASE_GRACE_MS = 90 * 1000; +export const QR_LEASE_IDLE_EXPIRY_MS = QR_LEASE_TTL_MS + QR_LEASE_GRACE_MS; +export const QR_LEASE_MAX_AGE_MS = 22 * 60 * 1000; +export const QR_PENDING_COST_TTL_MS = 60 * 1000; +export const QR_CYCLE_RESET_SHIFT_MS = 30 * 60 * 1000; +export const QR_MIN_JUMP_EXCESS_PCT = 0.35; +export const QR_COLD_START_JUMP_PCT = 0.45; +export const QR_COLD_START_MAX_COST_USD = 0.25; +export const QR_REFUND_EPSILON_PCT = 0.04; +export const QR_MIN_DISPLAY_RESERVED_PCT = 0.05; +const QR_MAX_TRACKED_BUCKETS = 128; +const QR_MAX_ACTIVE_LEASES = 16; +const QR_MAX_EVENT_LOG = 500; + +function qrClamp(val, min, max) { + return Math.max(min, Math.min(max, val)); +} + +function qrRound1(val) { + return Math.round(val * 10) / 10; +} + +function qrClampRate(rate) { + if (!Number.isFinite(rate) || rate <= 0) return null; + return qrClamp(rate, 0.005, 50); +} + +function qrResolveExactUsedPct(poolObj, win) { + const rawFrac = + win === 'weekly' ? poolObj?.weeklyRemainingFraction : poolObj?.remainingFraction; + if (rawFrac !== undefined && rawFrac !== null && Number.isFinite(Number(rawFrac))) { + return qrClamp((1 - qrClamp(Number(rawFrac), 0, 1)) * 100, 0, 100); + } + const rawUsed = win === 'weekly' ? poolObj?.weeklyUsedPct : poolObj?.usedPct; + if (rawUsed !== undefined && rawUsed !== null && Number.isFinite(Number(rawUsed))) { + return qrClamp(Number(rawUsed), 0, 100); + } + return null; +} + +function qrSumLeases(leases) { + let sum = 0; + for (let i = 0; i < leases.length; i += 1) { + sum += Math.max(0, Number(leases[i]?.remainingPct) || 0); + } + return sum; +} + +function qrConsumeLeasesFifo(leases, amountPct) { + let left = Math.max(0, Number(amountPct) || 0); + if (left <= 0 || leases.length === 0) return 0; + let consumed = 0; + for (let i = 0; i < leases.length && left > 1e-6; i += 1) { + const cur = Math.max(0, Number(leases[i].remainingPct) || 0); + const take = Math.min(cur, left); + leases[i].remainingPct = cur - take; + left -= take; + consumed += take; + } + for (let i = leases.length - 1; i >= 0; i -= 1) { + if (leases[i].remainingPct <= 1e-4) { + leases.splice(i, 1); + } + } + return consumed; +} + +function qrUpdateRateEma(state, sampleRate) { + const clamped = qrClampRate(sampleRate); + if (clamped === null) return; + if (state.ratePctPerUsd !== null && state.rateSamples >= 3) { + const bounded = qrClamp(clamped, state.ratePctPerUsd * 0.25, state.ratePctPerUsd * 4); + state.ratePctPerUsd = state.ratePctPerUsd * 0.8 + bounded * 0.2; + } else if (state.ratePctPerUsd !== null) { + state.ratePctPerUsd = state.ratePctPerUsd * 0.55 + clamped * 0.45; + } else { + state.ratePctPerUsd = clamped; + } + state.rateSamples += 1; +} + +function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { + if (state.ratePctPerUsd !== null && Number.isFinite(state.ratePctPerUsd)) { + return state.ratePctPerUsd; + } + if (cycleCostUsd >= 0.5 && officialUsedPct >= 0.3) { + return qrClampRate(officialUsedPct / cycleCostUsd); + } + return null; +} + +function qrCalibrateFromSettled(state, officialUsedPct, cycleCostUsd, nowMs) { + if ( + state.lastSettledUsedPct !== null && + state.lastSettledCostUsd !== null && + cycleCostUsd > state.lastSettledCostUsd + 0.25 && + officialUsedPct > state.lastSettledUsedPct + 0.05 + ) { + const dUsed = officialUsedPct - state.lastSettledUsedPct; + const dCost = cycleCostUsd - state.lastSettledCostUsd; + qrUpdateRateEma(state, dUsed / dCost); + } + state.lastSettledUsedPct = officialUsedPct; + state.lastSettledCostUsd = cycleCostUsd; + state.lastSettledAtMs = nowMs; +} + +function qrPruneExpiredLeases(state, poolLastActivityMs, officialUsedPct, cycleCostUsd, nowMs) { + if (state.activeLeases.length === 0) return; + const beforeLen = state.activeLeases.length; + for (let i = state.activeLeases.length - 1; i >= 0; i -= 1) { + const lease = state.activeLeases[i]; + const lastActiveMs = Math.max(lease.lastTouchedMs || 0, poolLastActivityMs || 0); + const idleExpired = lastActiveMs > 0 && nowMs - lastActiveMs >= QR_LEASE_IDLE_EXPIRY_MS; + const maxAgeExpired = nowMs - (lease.createdAtMs || 0) >= QR_LEASE_MAX_AGE_MS; + if (idleExpired || maxAgeExpired) { + state.activeLeases.splice(i, 1); + } + } + if (beforeLen > 0 && state.activeLeases.length === 0) { + qrCalibrateFromSettled(state, officialUsedPct, cycleCostUsd, nowMs); + } +} + +function qrFormatOutput(state, officialUsedPct) { + const rawReserved = qrClamp(qrSumLeases(state.activeLeases), 0, officialUsedPct); + if (rawReserved < QR_MIN_DISPLAY_RESERVED_PCT) { + return { + reservedPct: 0, + reservedLeaseCount: 0, + reservedExpiresAtMs: null, + }; + } + const rounded = qrClamp(qrRound1(rawReserved), 0, qrRound1(officialUsedPct)); + let earliestExpiresAtMs = null; + for (let i = 0; i < state.activeLeases.length; i += 1) { + const exp = (state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) + QR_LEASE_TTL_MS; + if (exp > 0 && (earliestExpiresAtMs === null || exp < earliestExpiresAtMs)) { + earliestExpiresAtMs = exp; + } + } + return { + reservedPct: rounded, + reservedLeaseCount: state.activeLeases.length, + reservedExpiresAtMs: earliestExpiresAtMs, + }; +} + +/** + * 创建独立的配额预占状态追踪器(支持单元测试隔离,同时后端提供全局默认实例)。 + */ +export function createQuotaReservationTracker() { + const buckets = new Map(); + const eventLog = []; + + function appendEventLog(entry) { + eventLog.push(entry); + if (eventLog.length > QR_MAX_EVENT_LOG) { + eventLog.splice(0, eventLog.length - QR_MAX_EVENT_LOG); + } + } + + function getOrCreateBucket(bucketKey) { + let st = buckets.get(bucketKey); + if (st) { + buckets.delete(bucketKey); + buckets.set(bucketKey, st); + return st; + } + if (buckets.size >= QR_MAX_TRACKED_BUCKETS) { + const oldestKey = buckets.keys().next().value; + if (oldestKey !== undefined) buckets.delete(oldestKey); + } + st = { + resetTimeMs: 0, + lastQuotaTs: 0, + lastOfficialUsedPct: null, + lastCycleCostUsd: 0, + lastUnpricedCalls: 0, + pendingCostUsd: 0, + pendingCostAtMs: 0, + ratePctPerUsd: null, + rateSamples: 0, + lastSettledUsedPct: null, + lastSettledCostUsd: null, + lastSettledAtMs: 0, + activeLeases: [], + lastRefundAtMs: 0, + lastRefundPct: 0, + }; + buckets.set(bucketKey, st); + return st; + } + + function observeBucket({ + bucketKey, + poolKey = '', + win = '', + officialUsedPct, + resetTimeMs = 0, + quotaFetchedAtMs = 0, + cycleCostUsd = 0, + unpricedCalls = 0, + poolLastActivityMs = 0, + activeSessionCount10m = 0, + recent10mCostUsd = 0, + nowMs = Date.now(), + }) { + if (officialUsedPct === null || !Number.isFinite(officialUsedPct)) { + return { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; + } + const safeUsed = qrClamp(Number(officialUsedPct), 0, 100); + const safeCost = Math.max(0, Number(cycleCostUsd) || 0); + const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0); + const safeResetMs = Number(resetTimeMs) > 0 ? Number(resetTimeMs) : 0; + const safeFetchTs = Number(quotaFetchedAtMs) > 0 ? Number(quotaFetchedAtMs) : nowMs; + const safeSess10m = Math.max(0, Number(activeSessionCount10m) || 0); + const safeCost10m = Math.max(0, Number(recent10mCostUsd) || 0); + const parsedParts = String(bucketKey || '').split('::'); + const logPool = poolKey || parsedParts[2] || ''; + const logWin = win || parsedParts[3] || ''; + const st = getOrCreateBucket(bucketKey); + + const recordLog = (event, fields = {}) => { + appendEventLog({ + ts: new Date(nowMs).toISOString(), + pool: logPool, + win: logWin, + event, + usedPct: +safeUsed.toFixed(3), + dUsed: +(Number(fields.deltaOfficial) || 0).toFixed(3), + costUsd: +safeCost.toFixed(4), + dCost: +(Number(fields.rawDeltaCost) || 0).toFixed(4), + expPct: +(Number(fields.expectedDeltaPct) || 0).toFixed(3), + excessPct: +(Number(fields.excessPct) || 0).toFixed(3), + rate: st.ratePctPerUsd !== null ? +st.ratePctPerUsd.toFixed(4) : null, + rsvPct: Number(fields.reservedPct) || 0, + leases: Number(fields.reservedLeaseCount) || 0, + sess10m: safeSess10m, + cost10m: +safeCost10m.toFixed(4), + }); + }; + + // 1. 周期重置检测:清空旧租约及待配对成本,保留已校准的单桶费率 + const resetShifted = + safeResetMs > 0 && + st.resetTimeMs > 0 && + Math.abs(safeResetMs - st.resetTimeMs) > QR_CYCLE_RESET_SHIFT_MS; + const rolloverDrop = + st.lastOfficialUsedPct !== null && st.lastOfficialUsedPct >= 5 && safeUsed < 1; + if (resetShifted || rolloverDrop) { + const prevUsed = st.lastOfficialUsedPct ?? 0; + st.resetTimeMs = safeResetMs; + st.lastQuotaTs = safeFetchTs; + st.lastOfficialUsedPct = safeUsed; + st.lastCycleCostUsd = safeCost; + st.lastUnpricedCalls = safeUnpriced; + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + st.activeLeases = []; + st.lastSettledUsedPct = safeUsed; + st.lastSettledCostUsd = safeCost; + st.lastSettledAtMs = nowMs; + const out = qrFormatOutput(st, safeUsed); + recordLog('reset', { deltaOfficial: safeUsed - prevUsed, ...out }); + return out; + } + + // 2. 首次观测:建立基线并按当前周期已有消耗做低权重冷启动费率估计 + if (st.lastOfficialUsedPct === null) { + st.resetTimeMs = safeResetMs; + st.lastQuotaTs = safeFetchTs; + st.lastOfficialUsedPct = safeUsed; + st.lastCycleCostUsd = safeCost; + st.lastUnpricedCalls = safeUnpriced; + if (safeCost >= 0.5 && safeUsed >= 0.3) { + st.ratePctPerUsd = qrClampRate(safeUsed / safeCost); + st.rateSamples = 1; + } + st.lastSettledUsedPct = safeUsed; + st.lastSettledCostUsd = safeCost; + st.lastSettledAtMs = nowMs; + const out = qrFormatOutput(st, safeUsed); + recordLog('baseline', out); + return out; + } + + if (safeResetMs > 0 && st.resetTimeMs === 0) { + st.resetTimeMs = safeResetMs; + } + + // 3. 同一份缓存配额响应:跳过重复差分,仅检查租约超时清理 + const isFreshSample = + safeFetchTs !== st.lastQuotaTs || Math.abs(safeUsed - st.lastOfficialUsedPct) > 1e-4; + if (!isFreshSample) { + const beforeCachePrune = st.activeLeases.length; + qrPruneExpiredLeases(st, poolLastActivityMs, safeUsed, safeCost, nowMs); + const out = qrFormatOutput(st, safeUsed); + if (beforeCachePrune > st.activeLeases.length) { + recordLog('expire', out); + } + return out; + } + + const deltaOfficial = safeUsed - st.lastOfficialUsedPct; + const rawDeltaCost = Math.max(0, safeCost - st.lastCycleCostUsd); + const deltaUnpriced = Math.max(0, safeUnpriced - st.lastUnpricedCalls); + const pendingValid = + st.pendingCostUsd > 0 && nowMs - st.pendingCostAtMs <= QR_PENDING_COST_TTL_MS; + const effectiveDeltaCost = rawDeltaCost + (pendingValid ? st.pendingCostUsd : 0); + const rate = qrResolveEffectiveRate(st, safeUsed, safeCost); + const expectedDeltaPct = rate !== null ? effectiveDeltaCost * rate : 0; + const excessPct = deltaOfficial - expectedDeltaPct; + let eventKind = 'idle'; + + if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) { + // 4A. 同周期余额回升:上游租约到期退还差额(FIFO 核销 + 结算校准) + const refundedPct = -deltaOfficial; + qrConsumeLeasesFifo(st.activeLeases, refundedPct); + st.lastRefundAtMs = nowMs; + st.lastRefundPct = refundedPct; + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + if (qrSumLeases(st.activeLeases) < QR_MIN_DISPLAY_RESERVED_PCT) { + st.activeLeases = []; + qrCalibrateFromSettled(st, safeUsed, safeCost, nowMs); + } + eventKind = 'refund'; + } else if (deltaOfficial > 1e-3) { + // 4B. 官方已用比例上升:区分租约跳变及常规消耗 + const detectedWithRate = rate !== null && excessPct >= QR_MIN_JUMP_EXCESS_PCT; + const detectedColdStart = + rate === null && + deltaOfficial >= QR_COLD_START_JUMP_PCT && + effectiveDeltaCost <= QR_COLD_START_MAX_COST_USD; + + if (detectedWithRate || detectedColdStart) { + const leaseRemaining = detectedWithRate ? excessPct : deltaOfficial; + st.activeLeases.push({ + amountPct: leaseRemaining, + remainingPct: leaseRemaining, + createdAtMs: nowMs, + lastTouchedMs: nowMs, + sessionCount: Math.max(1, safeSess10m || 1), + }); + if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) { + st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); + } + eventKind = 'lease'; + } else if (st.activeLeases.length > 0 && expectedDeltaPct > deltaOfficial) { + // 租约期内同时出现官方微增及本地消耗:超出官方增量的消耗计入当前租约内消费 + const shortfall = expectedDeltaPct - deltaOfficial; + qrConsumeLeasesFifo(st.activeLeases, shortfall); + for (let i = 0; i < st.activeLeases.length; i += 1) { + st.activeLeases[i].lastTouchedMs = nowMs; + } + eventKind = 'consume'; + } else { + if ( + st.activeLeases.length === 0 && + effectiveDeltaCost >= 0.05 && + deltaUnpriced === 0 && + deltaOfficial < QR_COLD_START_JUMP_PCT + ) { + // 纯净未租约消耗:平稳校准该桶 $/1% 换算率 + qrUpdateRateEma(st, deltaOfficial / effectiveDeltaCost); + st.lastSettledUsedPct = safeUsed; + st.lastSettledCostUsd = safeCost; + st.lastSettledAtMs = nowMs; + } + eventKind = 'normal'; + } + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + } else if (rawDeltaCost > 0) { + // 4C. 官方已用比例持平但本地产生真实消耗 + if (st.activeLeases.length > 0) { + // 正在原地消耗已预借租约:按换算率缩减可退差额并刷新租约活跃时刻 + const consumedPct = rate !== null ? rawDeltaCost * rate : 0; + if (consumedPct > 0) { + qrConsumeLeasesFifo(st.activeLeases, consumedPct); + } + for (let i = 0; i < st.activeLeases.length; i += 1) { + st.activeLeases[i].lastTouchedMs = nowMs; + } + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + eventKind = 'consume'; + } else { + // 尚未租约:暂存短时待配对成本,吸收 10~30s 记账延迟或小额步长累积 + st.pendingCostUsd = effectiveDeltaCost; + st.pendingCostAtMs = nowMs; + eventKind = 'lag_pending'; + } + } + + st.lastQuotaTs = safeFetchTs; + st.lastOfficialUsedPct = safeUsed; + st.lastCycleCostUsd = safeCost; + st.lastUnpricedCalls = safeUnpriced; + + // 5. 租约 TTL 超时兜底(静默超过 11.5 分钟仍未退还,说明租约已在窗内耗尽) + const beforePrune = st.activeLeases.length; + qrPruneExpiredLeases(st, poolLastActivityMs, safeUsed, safeCost, nowMs); + if (beforePrune > st.activeLeases.length && eventKind === 'idle') { + eventKind = 'expire'; + } + + const out = qrFormatOutput(st, safeUsed); + if (eventKind !== 'idle') { + recordLog(eventKind, { + deltaOfficial, + rawDeltaCost, + expectedDeltaPct, + excessPct, + ...out, + }); + } + return out; + } + + function updatePools({ + endpointId = 'local', + accountScope = '', + quotaPoolsMap = null, + poolCycleStats = null, + quotaFetchedAtMs = 0, + nowMs = Date.now(), + } = {}) { + if (!(quotaPoolsMap instanceof Map) || quotaPoolsMap.size === 0) return; + const scopePrefix = `${String(endpointId || 'local')}::${String(accountScope || '')}`; + + for (const [poolKey, poolObj] of quotaPoolsMap.entries()) { + if (!poolObj || typeof poolObj !== 'object') continue; + const pStats = poolCycleStats instanceof Map ? poolCycleStats.get(poolKey) : null; + const recent10m = pStats?.recent10m || null; + const poolLastActivityMs = Number(recent10m?.lastActivityMs) || 0; + const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0; + const recent10mCostUsd = Number(recent10m?.costUsd) || 0; + + const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null; + const res5h = + used5hExact !== null + ? observeBucket({ + bucketKey: `${scopePrefix}::${poolKey}::5h`, + poolKey, + win: '5h', + officialUsedPct: used5hExact, + resetTimeMs: parseIsoMs(poolObj.resetTime), + quotaFetchedAtMs, + cycleCostUsd: pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0, + unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0, + poolLastActivityMs, + activeSessionCount10m, + recent10mCostUsd, + nowMs, + }) + : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; + + const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; + const resWk = + usedWkExact !== null + ? observeBucket({ + bucketKey: `${scopePrefix}::${poolKey}::weekly`, + poolKey, + win: 'weekly', + officialUsedPct: usedWkExact, + resetTimeMs: parseIsoMs(poolObj.weeklyResetTime), + quotaFetchedAtMs, + cycleCostUsd: pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0, + unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0, + poolLastActivityMs, + activeSessionCount10m, + recent10mCostUsd, + nowMs, + }) + : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; + + poolObj.reservedPct = res5h.reservedPct; + poolObj.reservedLeaseCount = res5h.reservedLeaseCount; + poolObj.reservedExpiresAtMs = res5h.reservedExpiresAtMs; + poolObj.weeklyReservedPct = resWk.reservedPct; + poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount; + poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs; + } + } + + function getLogSnapshot() { + const bucketSummaries = []; + for (const [key, st] of buckets.entries()) { + const parts = key.split('::'); + const usedPct = st.lastOfficialUsedPct ?? 0; + const out = qrFormatOutput(st, usedPct); + bucketSummaries.push({ + pool: parts[2] || key, + win: parts[3] || '', + usedPct: +usedPct.toFixed(3), + cycleCostUsd: +Number(st.lastCycleCostUsd || 0).toFixed(4), + ratePctPerUsd: st.ratePctPerUsd !== null ? +st.ratePctPerUsd.toFixed(4) : null, + rateSamples: st.rateSamples, + reservedPct: out.reservedPct, + leases: out.reservedLeaseCount, + }); + } + return { + generatedAt: new Date().toISOString(), + count: eventLog.length, + maxEntries: QR_MAX_EVENT_LOG, + buckets: bucketSummaries, + events: eventLog.slice(), + }; + } + + function reset() { + buckets.clear(); + eventLog.length = 0; + } + + return { + observeBucket, + updatePools, + getLogSnapshot, + reset, + _buckets: buckets, + }; +} + +const defaultQuotaReservationTracker = createQuotaReservationTracker(); + +/** + * 使用全局默认追踪器为 `quotaPoolsMap` 中的所有配额池刷新 5h 及周限的实验性预占估算字段。 + */ +export function updatePoolQuotaReservationEstimates(params) { + return defaultQuotaReservationTracker.updatePools(params); +} + +/** + * 获取当前内存中的配额预占观测日志快照(供「其他 → 试验性功能」复制到剪贴板)。 + */ +export function getQuotaReservationLogSnapshot() { + return defaultQuotaReservationTracker.getLogSnapshot(); +} + +/** + * 清空全局默认配额预占状态(供测试隔离使用)。 + */ +export function resetQuotaReservationState() { + defaultQuotaReservationTracker.reset(); +} diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index e50b2ca..1963974 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -35,6 +35,7 @@ import { normalizeCliStatusLineSlots, normalizeContextAgentMode, normalizeExperimentalModernUi, + normalizeExperimentalQuotaReservation, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -87,6 +88,7 @@ export { normalizeCliStatusLineSlots, normalizeContextAgentMode, normalizeExperimentalModernUi, + normalizeExperimentalQuotaReservation, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -159,6 +161,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ showStepFilterToolbar: false, stepTokenComboFormat: DEFAULT_STEP_TOKEN_COMBO_FORMAT, stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS, + experimentalQuotaReservation: false, contextWindowRiskAccepted: false, modelContextWindows: Object.freeze({}), }); @@ -238,6 +241,9 @@ export function normalizeFullSettings(rawInput) { showStepFilterToolbar: safeRaw.showStepFilterToolbar === true, stepTokenComboFormat: normalizeStepTokenComboFormat(safeRaw.stepTokenComboFormat), stepTableColumns: normalizeStepTableColumns(safeRaw.stepTableColumns), + experimentalQuotaReservation: normalizeExperimentalQuotaReservation( + safeRaw.experimentalQuotaReservation + ), contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true, modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows), }; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 73da8e6..6a4309c 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -45,6 +45,7 @@ import { } from './model-pricing.mjs'; import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './pricing-catalog.mjs'; import { buildOfficialQuotaPools } from './quota-pools.mjs'; +import { updatePoolQuotaReservationEstimates } from './quota-reservation.mjs'; import { getDefaultWindowBridgeStatus } from './window-bridge.mjs'; import { aggregateConsumptionPresetBundle, @@ -1684,6 +1685,15 @@ export async function buildTelemetryPayloadInternal( poolObj.cycleWeekly = pStats?.cycleWeekly || createEmptyCycleSummary(); } + updatePoolQuotaReservationEstimates({ + endpointId, + accountScope: accountScope || '', + quotaPoolsMap, + poolCycleStats, + quotaFetchedAtMs: officialQuotaInfo?.fetchedAtMs || 0, + nowMs: Date.now(), + }); + // 6. 组装当前活跃配额池与每周限额视图数据 const { activePoolQuota, weeklyQuota } = buildActivePoolAndWeeklyQuotas({ activePoolKey, diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 3e0c79b..055a115 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -800,6 +800,8 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { startWkMs, b5h: createUsageBucket(), bWk: createUsageBucket(), + lastActivityMs: 0, + recent10mSessions: new Map(), }); } } @@ -1567,6 +1569,20 @@ export function aggregateMultiWindowUsage({ ); if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) { + if (qMs > poolBucketEntry.lastActivityMs) { + poolBucketEntry.lastActivityMs = qMs; + } + if (qMs >= nowMs - 10 * 60 * 1000) { + const sessKey = String(cascadeId || ''); + let sessStat = poolBucketEntry.recent10mSessions.get(sessKey); + if (!sessStat) { + sessStat = { costUsd: 0, calls: 0, lastActivityMs: 0 }; + poolBucketEntry.recent10mSessions.set(sessKey, sessStat); + } + sessStat.costUsd += stepUsage.resolvedCost; + sessStat.calls += 1; + if (qMs > sessStat.lastActivityMs) sessStat.lastActivityMs = qMs; + } if (qMs >= poolBucketEntry.start5hMs) { accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); } @@ -1774,9 +1790,20 @@ export function aggregateMultiWindowUsage({ let rawPoolsWeeklyCostUsd = 0; let rawPoolsWeeklyUnpricedCalls = 0; for (const [poolKey, entry] of poolCycleBuckets.entries()) { + let recent10mCostUsd = 0; + for (const sStat of entry.recent10mSessions.values()) { + recent10mCostUsd += sStat.costUsd; + } poolCycleStats.set(poolKey, { cycle5h: formatCycleSummary(entry.b5h), cycleWeekly: formatCycleSummary(entry.bWk), + exactCost5hUsd: +entry.b5h.costUsd.toFixed(6), + exactCostWeeklyUsd: +entry.bWk.costUsd.toFixed(6), + recent10m: { + lastActivityMs: entry.lastActivityMs, + activeSessionCount: entry.recent10mSessions.size, + costUsd: +recent10mCostUsd.toFixed(4), + }, }); rawPoolsWeeklyCalls += entry.bWk.calls; rawPoolsWeeklyTokens += entry.bWk.totalTokens; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 39692f1..098b898 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 05e1c28..a8d8a18 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -556,6 +556,20 @@ export function normalizeContextAgentMode(raw) { return val === 'auto' ? 'auto' : 'main'; } +/** + * 归一化实验性配额预占估算开关(默认 `false`)。 + * + * @param {unknown} val + * @returns {boolean} + */ +export function normalizeExperimentalQuotaReservation(val) { + if (typeof val === 'string') { + const lower = val.trim().toLowerCase(); + return lower === 'true' || lower === '1' || lower === 'on'; + } + return Boolean(val); +} + /** * 归一化旧版实验性新 UI 字段(保留兼容,缺省返回 `false`)。 * diff --git a/sidecars/panel/shared/window-bridge-protocol.mjs b/sidecars/panel/shared/window-bridge-protocol.mjs index 98d4fce..c58fa86 100644 --- a/sidecars/panel/shared/window-bridge-protocol.mjs +++ b/sidecars/panel/shared/window-bridge-protocol.mjs @@ -40,6 +40,11 @@ export const BRIDGE_API_ROUTE_DEFS = Object.freeze([ }), Object.freeze({ path: '/api/export-file', method: 'POST', action: 'export_file' }), Object.freeze({ path: '/api/reveal-file', method: 'POST', action: 'reveal_file' }), + Object.freeze({ + path: '/api/quota-reservation/log', + method: 'GET', + action: 'quota_reservation_log', + }), ]); export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); diff --git a/sidecars/panel/src/components/settings/structurePreviewMock.js b/sidecars/panel/src/components/settings/structurePreviewMock.js index 147cb08..103f63d 100644 --- a/sidecars/panel/src/components/settings/structurePreviewMock.js +++ b/sidecars/panel/src/components/settings/structurePreviewMock.js @@ -389,9 +389,13 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides family: 'Gemini', usedPct: 36, remainingPct: 64, + reservedPct: 1.0, + reservedLeaseCount: 1, resetTime: reset5hIso, weeklyUsedPct: 48, weeklyRemainingPct: 52, + weeklyReservedPct: 0.5, + weeklyReservedLeaseCount: 1, weeklyResetTime: resetWkIso, cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 }, cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 }, diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index 5d3f503..e40bee3 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -25,7 +25,11 @@ import { getEffectiveLocale, t } from '../../i18n/index.js'; * @param {{ isPending?: boolean }} [options] * @returns {Array} */ -export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) { +export function buildQuotaPoolItems( + quotas, + minuteTick = 0, + { isPending = false, showReserved = false } = {} +) { const safeQuotas = quotas || {}; const activePool = safeQuotas.activePool || {}; const rawPools = @@ -52,6 +56,7 @@ export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false isActivePool, minuteTick, isPending, + showReserved: Boolean(showReserved), }; }); if ( @@ -65,27 +70,45 @@ export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } /** - * 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。 + * 创建单个配额池的 DOM 行结构,内含 5h 限额及每周限额两个可独立显隐的子窗口进度条。 */ export function createPoolQuotaRow() { const title5h = h('span', { className: 'quota-win-title', text: '5h' }); const usage5h = h('span', { className: 'quota-win-usage', hidden: true, text: '' }); const left5h = h('span', { className: 'quota-win-left' }, [title5h, usage5h]); - const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' }); + const meta5hBefore = h('span', { text: '--' }); + const meta5hReserved = h('span', { className: 'quota-reserved-pct', hidden: true, text: '' }); + const meta5hAfter = h('span', { hidden: true, text: '' }); + const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono' }, [ + meta5hBefore, + meta5hReserved, + meta5hAfter, + ]); const fill5h = h('div', { className: 'progress-fill' }); + const fillReserved5h = h('div', { className: 'progress-fill-reserved' }); + const track5h = h('div', { className: 'progress-track' }, [fill5h, fillReserved5h]); const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ h('div', { className: 'panel-header quota-win-head' }, [left5h, meta5h]), - h('div', { className: 'progress-track' }, [fill5h]), + track5h, ]); const titleWk = h('span', { className: 'quota-win-title', text: t('quota.weeklyShort') }); const usageWk = h('span', { className: 'quota-win-usage', hidden: true, text: '' }); const leftWk = h('span', { className: 'quota-win-left' }, [titleWk, usageWk]); - const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' }); + const metaWkBefore = h('span', { text: '--' }); + const metaWkReserved = h('span', { className: 'quota-reserved-pct', hidden: true, text: '' }); + const metaWkAfter = h('span', { hidden: true, text: '' }); + const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono' }, [ + metaWkBefore, + metaWkReserved, + metaWkAfter, + ]); const fillWk = h('div', { className: 'progress-fill' }); + const fillReservedWk = h('div', { className: 'progress-fill-reserved' }); + const trackWk = h('div', { className: 'progress-track' }, [fillWk, fillReservedWk]); const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [ h('div', { className: 'panel-header quota-win-head' }, [leftWk, metaWk]), - h('div', { className: 'progress-track' }, [fillWk]), + trackWk, ]); const el = h('div', { className: 'quota-pool-row' }, [ @@ -101,13 +124,23 @@ export function createPoolQuotaRow() { title5h, usage5h, meta5h, + meta5hBefore, + meta5hReserved, + meta5hAfter, + track5h, fill5h, + fillReserved5h, rowWk, leftWk, titleWk, usageWk, metaWk, + metaWkBefore, + metaWkReserved, + metaWkAfter, + trackWk, fillWk, + fillReservedWk, }, }; } @@ -133,11 +166,84 @@ export function formatQuotaSummaryFooter(quotas, account) { return { leftText, rightText, tooltip }; } +function syncQuotaWindowMeter({ + hasData, + usedVal, + remVal, + resetTime, + fallbackMetaText, + showReserved, + rawReservedPct, + leaseCount, + metaBeforeEl, + metaReservedEl, + metaAfterEl, + trackEl, + fillEl, + fillReservedEl, +}) { + const numReserved = showReserved && hasData ? Number(rawReservedPct || 0) : 0; + const rsvVal = + Number.isFinite(numReserved) && numReserved >= 0.05 ? Math.min(usedVal, numReserved) : 0; + const actualVal = Math.max(0, usedVal - rsvVal); + const resetStr = hasData ? formatCountdown(resetTime) : ''; + + if (hasData && rsvVal > 0) { + const rsvStr = rsvVal.toFixed(1); + const actualStr = actualVal.toFixed(1); + const leases = Math.max(1, Number(leaseCount) || 1); + const tipText = + leases >= 2 + ? t('quota.reservedTipMulti', { rsv: rsvStr, leases, actual: actualStr }) + : t('quota.reservedTip', { rsv: rsvStr, actual: actualStr }); + patchText( + metaBeforeEl, + t('quota.usedBeforeReserved', { reset: resetStr, used: usedVal.toFixed(1) }) + ); + metaReservedEl.hidden = false; + patchText(metaReservedEl, t('quota.reservedTag', { rsv: rsvStr })); + patchAttr(metaReservedEl, 'title', tipText); + metaAfterEl.hidden = false; + patchText(metaAfterEl, t('quota.usedAfterReserved', { rem: remVal.toFixed(1) })); + patchAttr(trackEl, 'title', tipText); + const actualWidth = +Math.min(100, actualVal).toFixed(2); + const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); + patchStyleVar(fillEl, '--fill-w', `${actualWidth}%`); + patchStyleVar(fillReservedEl, '--reserved-w', `${rsvWidth}%`); + patchClasses(fillReservedEl, { 'is-active': true }); + } else { + patchText( + metaBeforeEl, + hasData + ? t('quota.usedAndLeft', { + reset: resetStr, + used: usedVal.toFixed(1), + rem: remVal.toFixed(1), + }) + : fallbackMetaText + ); + metaReservedEl.hidden = true; + patchText(metaReservedEl, ''); + patchAttr(metaReservedEl, 'title', null); + metaAfterEl.hidden = true; + patchText(metaAfterEl, ''); + patchAttr(trackEl, 'title', null); + patchStyleVar(fillEl, '--fill-w', `${Math.min(100, usedVal)}%`); + patchStyleVar(fillReservedEl, '--reserved-w', '0%'); + patchClasses(fillReservedEl, { 'is-active': false }); + } + + patchClasses(fillEl, { + 'tone-warn': usedVal >= 70 && usedVal < 85, + 'tone-danger': usedVal >= 85, + }); +} + /** - * 同步单个配额池行的 5h 与每周窗口状态。 + * 同步单个配额池行的 5h 及每周窗口状态。 */ export function syncPoolQuotaRow(refs, item, idx, rowEl) { - const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item; + const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending, showReserved } = item; patchClasses(rowEl, { 'quota-pool-row': true, 'has-divider': idx > 0 }); const has5h = poolData?.usedPct != null && poolData?.remainingPct != null; @@ -166,6 +272,7 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { refs.rowWk.style.display = hideWk ? 'none' : 'flex'; const fallbackMetaText = isPending ? t('quota.loading') : t('quota.failed'); + const allowReserved = Boolean(showReserved && !isPending); patchText(refs.title5h, `5h (${poolLabel})`); const c5h = poolData?.cycle5h; @@ -190,20 +297,21 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.usage5h, ''); patchAttr(refs.left5h, 'title', null); } - patchText( - refs.meta5h, - has5h - ? t('quota.usedAndLeft', { - reset: formatCountdown(poolData.resetTime), - used: used5hVal.toFixed(1), - rem: rem5hVal.toFixed(1), - }) - : fallbackMetaText - ); - patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`); - patchClasses(refs.fill5h, { - 'tone-warn': used5hVal >= 70 && used5hVal < 85, - 'tone-danger': used5hVal >= 85, + syncQuotaWindowMeter({ + hasData: has5h, + usedVal: used5hVal, + remVal: rem5hVal, + resetTime: poolData?.resetTime, + fallbackMetaText, + showReserved: allowReserved, + rawReservedPct: poolData?.reservedPct, + leaseCount: poolData?.reservedLeaseCount, + metaBeforeEl: refs.meta5hBefore, + metaReservedEl: refs.meta5hReserved, + metaAfterEl: refs.meta5hAfter, + trackEl: refs.track5h, + fillEl: refs.fill5h, + fillReservedEl: refs.fillReserved5h, }); const customTitle = @@ -237,20 +345,21 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.usageWk, ''); patchAttr(refs.leftWk, 'title', null); } - patchText( - refs.metaWk, - hasWk - ? t('quota.usedAndLeft', { - reset: formatCountdown(wkResetRaw), - used: usedWkVal.toFixed(1), - rem: remWkVal.toFixed(1), - }) - : fallbackMetaText - ); - patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`); - patchClasses(refs.fillWk, { - 'tone-warn': usedWkVal >= 70 && usedWkVal < 85, - 'tone-danger': usedWkVal >= 85, + syncQuotaWindowMeter({ + hasData: hasWk, + usedVal: usedWkVal, + remVal: remWkVal, + resetTime: wkResetRaw, + fallbackMetaText, + showReserved: allowReserved && !useCustomWeekly, + rawReservedPct: poolData?.weeklyReservedPct, + leaseCount: poolData?.weeklyReservedLeaseCount, + metaBeforeEl: refs.metaWkBefore, + metaReservedEl: refs.metaWkReserved, + metaAfterEl: refs.metaWkAfter, + trackEl: refs.trackWk, + fillEl: refs.fillWk, + fillReservedEl: refs.fillReservedWk, }); } @@ -258,7 +367,7 @@ export function quotaPoolRowSig(item, idx) { const c5h = item.poolData?.cycle5h; const cWk = item.poolData?.cycleWeekly; const fw = item.fallbackWeekly; - return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; + return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } export const QuotaPoolsWidget = defineComponent({ @@ -309,12 +418,13 @@ export const QuotaPoolsWidget = defineComponent({ } const quotas = data.quotas || {}; + const showReserved = data.settings?.experimentalQuotaReservation === true; const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000); patchText( tierBadge, `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` ); - patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick), { + patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick, { showReserved }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, createRow: createPoolQuotaRow, diff --git a/sidecars/panel/src/core/settingsBackup.js b/sidecars/panel/src/core/settingsBackup.js index 41f007f..481d975 100644 --- a/sidecars/panel/src/core/settingsBackup.js +++ b/sidecars/panel/src/core/settingsBackup.js @@ -6,6 +6,7 @@ import { normalizeCliStatusLineSlots, normalizeContextAgentMode, + normalizeExperimentalQuotaReservation, normalizeFontScale, normalizeHoverModules, normalizeLanguageSetting, @@ -120,6 +121,9 @@ export function buildExportableSettingsJson(settings = {}) { showStepFilterToolbar: src.showStepFilterToolbar === true, stepTokenComboFormat: normalizeStepTokenComboFormat(src.stepTokenComboFormat), stepTableColumns: normalizeStepTableColumns(src.stepTableColumns), + experimentalQuotaReservation: normalizeExperimentalQuotaReservation( + src.experimentalQuotaReservation + ), }, }; return `${JSON.stringify(payload, null, 2)}\n`; @@ -242,6 +246,11 @@ export function parseImportedSettingsJson(rawText) { if (hasKey('stepTableColumns') && Array.isArray(src.stepTableColumns)) { patch.stepTableColumns = normalizeStepTableColumns(src.stepTableColumns); } + if (hasKey('experimentalQuotaReservation')) { + patch.experimentalQuotaReservation = normalizeExperimentalQuotaReservation( + src.experimentalQuotaReservation + ); + } const appliedCount = Object.keys(patch).length; if (appliedCount === 0) { diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index a9cd875..e82e194 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -182,6 +182,11 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.loading': 'Loading...', 'quota.failed': 'Unavailable (--%)', 'quota.usedAndLeft': '{reset} · Used {used}% ({rem}% left)', + 'quota.usedBeforeReserved': '{reset} · Used {used}% (', + 'quota.reservedTag': '{rsv}% rsv', + 'quota.usedAfterReserved': ' · {rem}% left)', + 'quota.reservedTip': 'Estimated lease reservation (Experimental): ~{rsv}% (~{actual}% actual used); unused share refunds after ~10 min idle', + 'quota.reservedTipMulti': 'Estimated lease reservation (Experimental): ~{rsv}% ({leases} stacked leases, ~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', @@ -681,6 +686,16 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.orchFormat': 'Orchestrator Series ID', 'settings.oth.orchCompact': 'Compact Alias (e.g. orchestrator-argon)', 'settings.oth.orchFull': 'Full Upstream ID (e.g. gemini-pro-orchestrator)', + 'settings.oth.expTitle': 'Experimental', + 'settings.oth.expBadge': 'Experimental', + 'settings.oth.quotaReserveLabel': 'Quota Reservation Estimate', + 'settings.oth.quotaReserveDesc': 'Estimate 0.5% / 1% 5h & weekly lease holds in Available Quotas and highlight the reserved share in violet', + 'settings.oth.quotaReserveLogLabel': 'Reservation Observation Log', + 'settings.oth.quotaReserveLogDesc': 'Copy in-memory quota jump & refund events to clipboard for threshold tuning', + 'settings.oth.exportReserveLogBtn': 'Export Reserve Log', + 'settings.oth.exportReserveLogCopied': 'Copied {count} log entries to clipboard', + 'settings.oth.exportReserveLogEmpty': 'No events yet; copied current summary to clipboard', + 'settings.oth.exportReserveLogFailed': 'Failed to copy reservation log', 'settings.oth.baselineTitle': 'Model Context Settings', 'settings.oth.ctxRiskTitle': 'Unofficial Override Risk Warning', 'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index cc5bbc1..5dd98c3 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -182,6 +182,11 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.loading': '读取中...', 'quota.failed': '获取失败 (--%)', 'quota.usedAndLeft': '{reset} · 已用 {used}% (余 {rem}%)', + 'quota.usedBeforeReserved': '{reset} · 已用 {used}% (', + 'quota.reservedTag': '预占 {rsv}%', + 'quota.usedAfterReserved': ' · 余 {rem}%)', + 'quota.reservedTip': '预占估算(试验性):约 {rsv}%(实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', + 'quota.reservedTipMulti': '预占估算(试验性):约 {rsv}%(检测到 {leases} 笔叠加租约,实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', @@ -681,6 +686,16 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.orchFormat': 'Orchestrator 系列 ID', 'settings.oth.orchCompact': '精简代号 (如 orchestrator-argon)', 'settings.oth.orchFull': '原始完整 ID (如 gemini-pro-orchestrator)', + 'settings.oth.expTitle': '试验性功能', + 'settings.oth.expBadge': '试验性', + 'settings.oth.quotaReserveLabel': '配额预占估算', + 'settings.oth.quotaReserveDesc': '在可用额度中估算 5h / 周限的 0.5% / 1% 租约预占,并用紫色标注占比及进度条段', + 'settings.oth.quotaReserveLogLabel': '预占观测日志', + 'settings.oth.quotaReserveLogDesc': '将内存中的配额跳变及退还记录复制到剪贴板,便于分析触发阈值', + 'settings.oth.exportReserveLogBtn': '导出预占日志', + 'settings.oth.exportReserveLogCopied': '已复制 {count} 条观测日志到剪贴板', + 'settings.oth.exportReserveLogEmpty': '暂无跳变记录,已复制当前摘要到剪贴板', + 'settings.oth.exportReserveLogFailed': '获取或复制预占日志失败', 'settings.oth.baselineTitle': '模型上下文设置', 'settings.oth.ctxRiskTitle': '非官方能力风险提示', 'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 032c8e8..2eb3b01 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -44,6 +44,7 @@ import { TOPBAR_SLOT_KEYS, normalizeCliStatusLineSlots, normalizeContextAgentMode, + normalizeExperimentalQuotaReservation, normalizeHoverModules, normalizeModelDisplayMode, normalizeOrchestratorIdMode, @@ -468,6 +469,7 @@ export const normalizeClientPopoverWidth = normalizePopoverWidth; export const normalizeClientModelDisplayMode = normalizeModelDisplayMode; export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; export const normalizeClientContextAgentMode = normalizeContextAgentMode; +export const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation; export const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots; /** @@ -606,6 +608,12 @@ export function isEquivalentTelemetry(prev, next) { if (Boolean(pSet?.showStepFilterToolbar) !== Boolean(nSet?.showStepFilterToolbar)) { return false; } + if ( + normalizeClientExperimentalQuotaReservation(pSet?.experimentalQuotaReservation) !== + normalizeClientExperimentalQuotaReservation(nSet?.experimentalQuotaReservation) + ) { + return false; + } if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false; if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false; if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false; @@ -1068,9 +1076,13 @@ export function isEquivalentTelemetry(prev, next) { pPools[i]?.poolLabel !== nPools[i]?.poolLabel || pPools[i]?.usedPct !== nPools[i]?.usedPct || pPools[i]?.remainingPct !== nPools[i]?.remainingPct || + pPools[i]?.reservedPct !== nPools[i]?.reservedPct || + pPools[i]?.reservedLeaseCount !== nPools[i]?.reservedLeaseCount || pPools[i]?.resetTime !== nPools[i]?.resetTime || pPools[i]?.weeklyUsedPct !== nPools[i]?.weeklyUsedPct || pPools[i]?.weeklyRemainingPct !== nPools[i]?.weeklyRemainingPct || + pPools[i]?.weeklyReservedPct !== nPools[i]?.weeklyReservedPct || + pPools[i]?.weeklyReservedLeaseCount !== nPools[i]?.weeklyReservedLeaseCount || pPools[i]?.weeklyResetTime !== nPools[i]?.weeklyResetTime || pPools[i]?.cycle5h?.tokens !== nPools[i]?.cycle5h?.tokens || pPools[i]?.cycle5h?.costUsd !== nPools[i]?.cycle5h?.costUsd || @@ -1794,6 +1806,11 @@ export async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'showStepFilterToolbar')) { safePatch.showStepFilterToolbar = Boolean(safePatch.showStepFilterToolbar); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'experimentalQuotaReservation')) { + safePatch.experimentalQuotaReservation = normalizeClientExperimentalQuotaReservation( + safePatch.experimentalQuotaReservation + ); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } @@ -2074,6 +2091,17 @@ export async function fetchSessionMigrationCatalog() { } } +export async function fetchQuotaReservationLog() { + try { + return await callSidecarApi('/api/quota-reservation/log', { method: 'GET' }); + } catch { + return callSidecarApi('/api/settings', { + method: 'POST', + body: { __quotaReservationAction: 'log' }, + }); + } +} + export async function executeSessionMigration(payload) { let res; try { diff --git a/sidecars/panel/src/styles/tokens.css b/sidecars/panel/src/styles/tokens.css index caf9a1f..568d164 100644 --- a/sidecars/panel/src/styles/tokens.css +++ b/sidecars/panel/src/styles/tokens.css @@ -88,6 +88,10 @@ --metric-danger: hsl(4 78% 55%); --metric-danger-soft: color-mix(in srgb, var(--metric-danger) 14%, transparent); + --quota-reserved: hsl(262 76% 58%); + --quota-reserved-soft: color-mix(in srgb, var(--quota-reserved) 13%, transparent); + --quota-reserved-border: color-mix(in srgb, var(--quota-reserved) 34%, transparent); + /* Context Window 10-Channel Palette */ --ctx-assistant: hsl(215 62% 52%); --ctx-tool-results: hsl(172 68% 40%); @@ -126,6 +130,7 @@ :root[data-color-scheme="dark"], :host([data-color-scheme="dark"]), [data-color-scheme="dark"] { + --quota-reserved: hsl(264 86% 72%); --ctx-assistant: hsl(216 30% 58%); --ctx-tool-results: hsl(168 72% 54%); --ctx-user-input: hsl(258 86% 73%); diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 640d357..6ab2c6e 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -577,6 +577,23 @@ background: var(--metric-danger); } +.progress-fill-reserved { + height: 100%; + width: var(--reserved-w, 0%); + background: var(--quota-reserved); + transition: width var(--dur-normal) var(--ease-fast); + flex-shrink: 0; +} + +.progress-fill-reserved.is-active { + min-width: 3px; +} + +.quota-reserved-pct { + color: var(--quota-reserved); + font-weight: 500; +} + /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index bfe476e..1b1c131 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -1559,3 +1559,25 @@ .cli-status-action-btn[hidden] { display: none !important; } + +.settings-experimental-label-group { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.settings-experimental-badge { + display: inline-flex; + align-items: center; + padding: 1px 6px; + border-radius: var(--radius-pill); + background: var(--quota-reserved-soft); + border: 1px solid var(--quota-reserved-border); + color: var(--quota-reserved); + font-size: var(--fs-2xs); + font-weight: 600; + line-height: 1.35; + white-space: nowrap; + flex-shrink: 0; +} diff --git a/sidecars/panel/src/views/settings/SettingsOtherTab.js b/sidecars/panel/src/views/settings/SettingsOtherTab.js index 0da4277..79d74ab 100644 --- a/sidecars/panel/src/views/settings/SettingsOtherTab.js +++ b/sidecars/panel/src/views/settings/SettingsOtherTab.js @@ -12,8 +12,13 @@ import { buildExportableSettingsJson, parseImportedSettingsJson, } from '../../core/settingsBackup.js'; -import { exportTextFileWithFeedback } from '../../core/fileExportClient.js'; import { + copyTextWithFeedback, + exportTextFileWithFeedback, +} from '../../core/fileExportClient.js'; +import { + fetchQuotaReservationLog, + normalizeClientExperimentalQuotaReservation, normalizeClientModelDisplayMode, normalizeClientOrchestratorIdMode, rebuildTrajectoryCache, @@ -22,9 +27,33 @@ import { saveSettingsPatch, } from '../../store/telemetryStore.js'; import { CustomSelect } from '../../components/ui/CustomSelect.js'; +import { SegmentedControl } from '../../components/ui/SegmentedControl.js'; import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js'; import { SessionMigrationCard } from '../../components/settings/SessionMigrationCard.js'; +function getEnableToggleOptions() { + return [ + { value: 'on', label: t('settings.str.on') }, + { value: 'off', label: t('settings.str.off') }, + ]; +} + +function formatQuotaReservationLogForClipboard(snapshot) { + const safe = snapshot && typeof snapshot === 'object' ? snapshot : {}; + const buckets = Array.isArray(safe.buckets) ? safe.buckets : []; + const events = Array.isArray(safe.events) ? safe.events : []; + const bucketLines = buckets.map((b) => ` ${JSON.stringify(b)}`).join(',\n'); + const eventLines = events.map((e) => ` ${JSON.stringify(e)}`).join(',\n'); + return [ + '{', + ` "generatedAt": ${JSON.stringify(safe.generatedAt || new Date().toISOString())},`, + ` "count": ${events.length},`, + ` "buckets": [${bucketLines ? `\n${bucketLines}\n ` : ''}],`, + ` "events": [${eventLines ? `\n${eventLines}\n ` : ''}]`, + '}', + ].join('\n'); +} + function getStepModelDisplayOptions() { return [ { value: 'short', label: t('settings.oth.modelShort') }, @@ -45,6 +74,7 @@ export const SettingsOtherTab = defineComponent({ setup({ onCleanup, getProps }) { let draftModelDisplayMode = 'short'; let draftOrchestratorIdMode = 'compact'; + let draftExperimentalQuotaReservation = false; let draftContextRiskAccepted = false; let acceptingContextRisk = false; let latestSettings = null; @@ -55,6 +85,7 @@ export const SettingsOtherTab = defineComponent({ let savingContextWindow = false; let contextFeedback = ''; let modelTimer = null; + let expTimer = null; let maintTimer = null; let resetConfirmTimer = null; let resetConfirmArmed = false; @@ -66,12 +97,31 @@ export const SettingsOtherTab = defineComponent({ style: 'font-size: var(--fs-md);', text: '', }); + const expStatusText = h('span', { + className: 'text-muted', + style: 'font-size: var(--fs-md);', + text: '', + }); const maintStatusText = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: '', }); + function showExpFeedback(text, autoClearMs = 1500) { + if (expTimer) { + clearTimeout(expTimer); + expTimer = null; + } + patchText(expStatusText, text); + if (text && autoClearMs > 0) { + expTimer = setTimeout(() => { + expTimer = null; + patchText(expStatusText, ''); + }, autoClearMs); + } + } + function showModelFeedback(text, autoClearMs = 1500) { if (modelTimer) { clearTimeout(modelTimer); @@ -164,6 +214,112 @@ export const SettingsOtherTab = defineComponent({ h('div', { className: 'form-row' }, [orchFormatLabelEl, orchestratorIdSelect.el]), ]); + // --- Card 2: 试验性功能 --- + const expTitleEl = h('span', { text: t('settings.oth.expTitle') }); + const quotaReserveLabelEl = h('span', { + className: 'settings-action-title', + text: t('settings.oth.quotaReserveLabel'), + }); + const quotaReserveBadgeEl = h('span', { + className: 'settings-experimental-badge', + text: t('settings.oth.expBadge'), + }); + const quotaReserveDescEl = h('span', { + className: 'settings-action-desc', + text: t('settings.oth.quotaReserveDesc'), + }); + const quotaReserveLogLabelEl = h('span', { + className: 'settings-action-title', + text: t('settings.oth.quotaReserveLogLabel'), + }); + const quotaReserveLogDescEl = h('span', { + className: 'settings-action-desc', + text: t('settings.oth.quotaReserveLogDesc'), + }); + const exportReserveLogBtnText = h('span', { + text: t('settings.oth.exportReserveLogBtn'), + }); + let isExportingReserveLog = false; + + const exportReserveLogBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary', + onClick: async () => { + if (isExportingReserveLog) return; + isExportingReserveLog = true; + patchAttr(exportReserveLogBtn, 'disabled', true); + try { + const snapshot = await fetchQuotaReservationLog(); + const text = formatQuotaReservationLogForClipboard(snapshot); + const count = Array.isArray(snapshot?.events) ? snapshot.events.length : 0; + const successMsg = + count > 0 + ? t('settings.oth.exportReserveLogCopied', { count }) + : t('settings.oth.exportReserveLogEmpty'); + const ok = await copyTextWithFeedback(text, successMsg); + showExpFeedback(ok ? successMsg : t('settings.oth.exportReserveLogFailed'), 2800); + } catch { + showExpFeedback(t('settings.oth.exportReserveLogFailed'), 2800); + } finally { + isExportingReserveLog = false; + patchAttr(exportReserveLogBtn, 'disabled', false); + } + }, + }, + [createSvgIcon('copy', { size: 12 }), exportReserveLogBtnText] + ); + + const quotaReserveToggle = SegmentedControl({ + modelValue: 'off', + ariaLabel: t('settings.oth.quotaReserveLabel'), + options: getEnableToggleOptions(), + onUpdateModelValue: async (val) => { + const nextEnabled = val === 'on'; + draftExperimentalQuotaReservation = nextEnabled; + quotaReserveToggle.setProps({ + modelValue: nextEnabled ? 'on' : 'off', + options: getEnableToggleOptions(), + }); + showExpFeedback(t('settings.saving'), 0); + try { + await saveSettingsPatch({ experimentalQuotaReservation: nextEnabled }); + showExpFeedback(t('settings.saved'), 1500); + } catch { + if (latestSettings) renderSettings(latestSettings); + showExpFeedback(t('settings.saveFailed'), 2500); + } + }, + }); + + const experimentalPanel = h('section', { className: 'panel' }, [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('pulse', { size: 13 }), + expTitleEl, + ]), + expStatusText, + ]), + h('div', { className: 'settings-action-block' }, [ + h('div', { className: 'settings-action-info' }, [ + h('div', { className: 'settings-experimental-label-group' }, [ + quotaReserveLabelEl, + quotaReserveBadgeEl, + ]), + quotaReserveDescEl, + ]), + quotaReserveToggle.el, + ]), + h('div', { className: 'settings-action-block' }, [ + h('div', { className: 'settings-action-info' }, [ + quotaReserveLogLabelEl, + quotaReserveLogDescEl, + ]), + exportReserveLogBtn, + ]), + ]); + // --- Card 2: 按模型设置上下文窗口 --- const baselineTitleEl = h('span', { text: t('settings.oth.baselineTitle') }); const ctxModelLabel = h('span', { className: 'form-label' }); @@ -611,6 +767,7 @@ export const SettingsOtherTab = defineComponent({ const rootEl = h('div', { className: 'settings-tab-stack' }, [ modelPanel, + experimentalPanel, baselinePanel, maintPanel, sessionMigrationCard.el, @@ -632,6 +789,9 @@ export const SettingsOtherTab = defineComponent({ settings.showUpstreamModel ); draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode); + draftExperimentalQuotaReservation = normalizeClientExperimentalQuotaReservation( + settings.experimentalQuotaReservation + ); if (!acceptingContextRisk) { draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted); } @@ -643,6 +803,11 @@ export const SettingsOtherTab = defineComponent({ modelValue: draftOrchestratorIdMode, options: getOrchestratorIdDisplayOptions(), }); + quotaReserveToggle.setProps({ + modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.quotaReserveLabel'), + }); renderContextWindows(); void sessionMigrationCard.refs.ensureLoaded(); } @@ -651,6 +816,18 @@ export const SettingsOtherTab = defineComponent({ patchText(modelCardTitleEl, t('settings.oth.modelTitle')); patchText(modelFormatLabelEl, t('settings.oth.modelFormat')); patchText(orchFormatLabelEl, t('settings.oth.orchFormat')); + patchText(expTitleEl, t('settings.oth.expTitle')); + patchText(quotaReserveLabelEl, t('settings.oth.quotaReserveLabel')); + patchText(quotaReserveBadgeEl, t('settings.oth.expBadge')); + patchText(quotaReserveDescEl, t('settings.oth.quotaReserveDesc')); + patchText(quotaReserveLogLabelEl, t('settings.oth.quotaReserveLogLabel')); + patchText(quotaReserveLogDescEl, t('settings.oth.quotaReserveLogDesc')); + patchText(exportReserveLogBtnText, t('settings.oth.exportReserveLogBtn')); + quotaReserveToggle.setProps({ + modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.quotaReserveLabel'), + }); patchText(baselineTitleEl, t('settings.oth.baselineTitle')); renderContextWindows(); patchText(maintTitleEl, t('settings.oth.maintTitle')); @@ -686,10 +863,12 @@ export const SettingsOtherTab = defineComponent({ onCleanup(() => { if (modelTimer) clearTimeout(modelTimer); + if (expTimer) clearTimeout(expTimer); if (maintTimer) clearTimeout(maintTimer); if (resetConfirmTimer) clearTimeout(resetConfirmTimer); stepModelSelect.destroy(); orchestratorIdSelect.destroy(); + quotaReserveToggle.destroy(); ctxBridgeNotice.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); @@ -701,6 +880,8 @@ export const SettingsOtherTab = defineComponent({ refs: { stepModelSelect, orchestratorIdSelect, + quotaReserveToggle, + exportReserveLogBtn, ctxBridgeNotice, ctxModelSelect, ctxWindowSelect, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index e9c8e0e..d00858f 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -89,6 +89,10 @@ --metric-danger: hsl(4 78% 55%); --metric-danger-soft: color-mix(in srgb, var(--metric-danger) 14%, transparent); + --quota-reserved: hsl(262 76% 58%); + --quota-reserved-soft: color-mix(in srgb, var(--quota-reserved) 13%, transparent); + --quota-reserved-border: color-mix(in srgb, var(--quota-reserved) 34%, transparent); + /* Context Window 10-Channel Palette */ --ctx-assistant: hsl(215 62% 52%); --ctx-tool-results: hsl(172 68% 40%); @@ -127,6 +131,7 @@ :root[data-color-scheme="dark"], :host([data-color-scheme="dark"]), [data-color-scheme="dark"] { + --quota-reserved: hsl(264 86% 72%); --ctx-assistant: hsl(216 30% 58%); --ctx-tool-results: hsl(168 72% 54%); --ctx-user-input: hsl(258 86% 73%); @@ -2255,6 +2260,23 @@ html[data-standalone="true"] .app-shell { background: var(--metric-danger); } +.progress-fill-reserved { + height: 100%; + width: var(--reserved-w, 0%); + background: var(--quota-reserved); + transition: width var(--dur-normal) var(--ease-fast); + flex-shrink: 0; +} + +.progress-fill-reserved.is-active { + min-width: 3px; +} + +.quota-reserved-pct { + color: var(--quota-reserved); + font-weight: 500; +} + /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; @@ -6959,6 +6981,28 @@ html[data-standalone="true"] .app-shell { display: none !important; } +.settings-experimental-label-group { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.settings-experimental-badge { + display: inline-flex; + align-items: center; + padding: 1px 6px; + border-radius: var(--radius-pill); + background: var(--quota-reserved-soft); + border: 1px solid var(--quota-reserved-border); + color: var(--quota-reserved); + font-size: var(--fs-2xs); + font-weight: 600; + line-height: 1.35; + white-space: nowrap; + flex-shrink: 0; +} + /* --- src/styles/overlay.css --- */ /* * 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css). diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 82a04af..47e91c5 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -38,6 +38,7 @@ const BACKEND_MODULE_FILES = [ '../backend/ls-rpc.mjs', '../backend/model-pricing.mjs', '../backend/quota-pools.mjs', + '../backend/quota-reservation.mjs', '../backend/local-scanner.mjs', '../backend/usage-aggregator.mjs', '../backend/telemetry-builder.mjs', diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index ceb5fa1..c3a0cc7 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1126,12 +1126,13 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen assert.equal(normalizeI18nLanguage('system'), 'auto'); assert.equal(typeof isEquivalentTelemetry, 'function'); - assert.equal(BRIDGE_API_ROUTE_DEFS.length, 14); + assert.equal(BRIDGE_API_ROUTE_DEFS.length, 15); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/bridge/relaunch')); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/catalog')); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/migrate')); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/export-file')); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/reveal-file')); + assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/quota-reservation/log')); // 1. Third-party pool parity across backend, CLI statusline, and frontend metricRegistry const h = backendHarness(); diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs new file mode 100644 index 0000000..81bbc7f --- /dev/null +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -0,0 +1,571 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + QR_LEASE_IDLE_EXPIRY_MS, + createQuotaReservationTracker, +} from '../backend/quota-reservation.mjs'; +import { normalizeFullSettings } from '../backend/settings-schema.mjs'; +import { + buildExportableSettingsJson, + parseImportedSettingsJson, +} from '../src/core/settingsBackup.js'; +import { backendHarness } from './backend-harness.mjs'; +import { createMockDom } from './mock-dom.mjs'; + +const T0 = Date.parse('2026-11-22T09:00:00Z'); +const RESET_5H = Date.parse('2026-11-22T14:00:00Z'); +const RESET_WK = Date.parse('2026-11-28T09:00:00Z'); + +test('quota-reservation: 5h & weekly independently track staggered leases (错档触发)', () => { + const tracker = createQuotaReservationTracker(); + + // Bootstrap settled baseline: 5h ≈ 0.75 %/$, weekly ≈ 0.22 %/$ + const pool0 = new Map([ + [ + 'Gemini', + { + poolKey: 'Gemini', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - 0.03, + usedPct: 3.0, + resetTime: new Date(RESET_5H).toISOString(), + weeklyRemainingFraction: 1 - 0.11, + weeklyUsedPct: 11.0, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + const stats0 = new Map([ + [ + 'Gemini', + { + cycle5h: { costUsd: 4.0, unpricedCalls: 0 }, + cycleWeekly: { costUsd: 50.0, unpricedCalls: 0 }, + exactCost5hUsd: 4.0, + exactCostWeeklyUsd: 50.0, + recent10m: { lastActivityMs: T0, activeSessionCount: 1, costUsd: 0.1 }, + }, + ], + ]); + + tracker.updatePools({ + endpointId: 'local', + accountScope: 'u@example.com', + quotaPoolsMap: pool0, + poolCycleStats: stats0, + quotaFetchedAtMs: T0, + nowMs: T0, + }); + assert.equal(pool0.get('Gemini').reservedPct, 0); + assert.equal(pool0.get('Gemini').weeklyReservedPct, 0); + + // Heavy turn ($0.10): 5h jumps +1.0% (lease 1%), weekly jumps +0.5% (lease 0.5%) + const t1 = T0 + 20_000; + const pool1 = new Map([ + [ + 'Gemini', + { + ...pool0.get('Gemini'), + remainingFraction: 1 - 0.04, + usedPct: 4.0, + weeklyRemainingFraction: 1 - 0.115, + weeklyUsedPct: 11.5, + }, + ], + ]); + const stats1 = new Map([ + [ + 'Gemini', + { + cycle5h: { costUsd: 4.1, unpricedCalls: 0 }, + cycleWeekly: { costUsd: 50.1, unpricedCalls: 0 }, + exactCost5hUsd: 4.1, + exactCostWeeklyUsd: 50.1, + recent10m: { lastActivityMs: t1, activeSessionCount: 1, costUsd: 0.2 }, + }, + ], + ]); + + tracker.updatePools({ + endpointId: 'local', + accountScope: 'u@example.com', + quotaPoolsMap: pool1, + poolCycleStats: stats1, + quotaFetchedAtMs: t1, + nowMs: t1, + }); + + // 5h excess = 1.0 - 0.075 = 0.925 -> 0.9%; weekly excess = 0.5 - 0.022 = 0.478 -> 0.5% + assert.equal(pool1.get('Gemini').reservedPct, 0.9); + assert.equal(pool1.get('Gemini').reservedLeaseCount, 1); + assert.equal(pool1.get('Gemini').weeklyReservedPct, 0.5); + assert.equal(pool1.get('Gemini').weeklyReservedLeaseCount, 1); +}); + +test('quota-reservation: consumes inside active lease and snaps to 0 on partial refund (退还差额)', () => { + const tracker = createQuotaReservationTracker(); + const key = 'local::u@example.com::Gemini::5h'; + + // Seed calibrated baseline: 1% per $1.00 (4.0% / $4.00) + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 4.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: T0, + cycleCostUsd: 4.0, + poolLastActivityMs: T0, + nowMs: T0, + }); + + // Trigger 1.0% lease on $0.05 step -> excess = 0.95% -> 1.0% + const t1 = T0 + 15_000; + const r1 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 5.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t1, + cycleCostUsd: 4.05, + poolLastActivityMs: t1, + nowMs: t1, + }); + assert.equal(r1.reservedPct, 1.0); + + // Follow-up turns spend $0.35 inside the lease while official stays flat at 5.0% + const t2 = t1 + 30_000; + const r2 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 5.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t2, + cycleCostUsd: 4.4, + poolLastActivityMs: t2, + nowMs: t2, + }); + assert.equal(r2.reservedPct, 0.6); + + // 10 minutes idle: server refunds remaining 0.6% (official drops 5.0% -> 4.4%) + const t3 = t2 + 10 * 60 * 1000; + const r3 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 4.4, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t3, + cycleCostUsd: 4.4, + poolLastActivityMs: t2, + nowMs: t3, + }); + assert.equal(r3.reservedPct, 0); + assert.equal(r3.reservedLeaseCount, 0); +}); + +test('quota-reservation: stacks multiple concurrent session leases (2%+) and settles FIFO', () => { + const tracker = createQuotaReservationTracker(); + const key = 'local::u@example.com::Gemini::weekly'; + + // Seed weekly baseline: 0.2 %/$ (10% / $50) + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 10.0, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: T0, + cycleCostUsd: 50.0, + poolLastActivityMs: T0, + nowMs: T0, + }); + + // Session A triggers +1.0% weekly lease + const t1 = T0 + 15_000; + const r1 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 11.0, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: t1, + cycleCostUsd: 50.1, + poolLastActivityMs: t1, + activeSessionCount10m: 1, + nowMs: t1, + }); + assert.equal(r1.reservedPct, 1.0); + assert.equal(r1.reservedLeaseCount, 1); + + // Session B opens concurrently and triggers a second +1.0% weekly lease -> total ~2.0% + const t2 = t1 + 25_000; + const r2 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 12.0, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: t2, + cycleCostUsd: 50.2, + poolLastActivityMs: t2, + activeSessionCount10m: 2, + nowMs: t2, + }); + assert.equal(r2.reservedPct, 2.0); + assert.equal(r2.reservedLeaseCount, 2); + + // Session A's lease expires first (-0.98% refund) -> Session B's ~1.0% lease remains + const t3 = t1 + 10 * 60 * 1000; + const r3 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 11.02, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: t3, + cycleCostUsd: 50.2, + poolLastActivityMs: t2, + activeSessionCount10m: 1, + nowMs: t3, + }); + assert.equal(r3.reservedPct, 1.0); + assert.equal(r3.reservedLeaseCount, 1); + + // Session B's lease expires (-0.98% refund) -> back to 0% + const t4 = t2 + 10 * 60 * 1000; + const r4 = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 10.04, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: t4, + cycleCostUsd: 50.2, + poolLastActivityMs: t2, + activeSessionCount10m: 0, + nowMs: t4, + }); + assert.equal(r4.reservedPct, 0); + assert.equal(r4.reservedLeaseCount, 0); +}); + +test('quota-reservation: avoids false positives on genuinely large steps, handles TTL expiry & cycle reset', () => { + const tracker = createQuotaReservationTracker(); + const key = 'local::u@example.com::Gemini::5h'; + + // Baseline 0.75 %/$ + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 3.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: T0, + cycleCostUsd: 4.0, + poolLastActivityMs: T0, + nowMs: T0, + }); + + // Legitimate large $2.00 step -> expected +1.5%, official +1.5% -> NOT a reservation + const t1 = T0 + 20_000; + const rLarge = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 4.5, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t1, + cycleCostUsd: 6.0, + poolLastActivityMs: t1, + nowMs: t1, + }); + assert.equal(rLarge.reservedPct, 0); + + // Lease triggers (+0.5% on tiny $0.02 step), then idle past TTL+grace with no refund -> auto expires + const t2 = t1 + 20_000; + const rJump = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 5.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t2, + cycleCostUsd: 6.02, + poolLastActivityMs: t2, + nowMs: t2, + }); + assert.equal(rJump.reservedPct, 0.5); + + const tExpired = t2 + QR_LEASE_IDLE_EXPIRY_MS + 1_000; + const rExpired = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 5.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: tExpired, + cycleCostUsd: 6.02, + poolLastActivityMs: t2, + nowMs: tExpired, + }); + assert.equal(rExpired.reservedPct, 0); + + // Trigger another lease then simulate 5h cycle rollover -> clears immediately while keeping rate + const t3 = tExpired + 20_000; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 6.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t3, + cycleCostUsd: 6.05, + poolLastActivityMs: t3, + nowMs: t3, + }); + const tReset = t3 + 60_000; + const rReset = tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 0.0, + resetTimeMs: RESET_5H + 5 * 3600 * 1000, + quotaFetchedAtMs: tReset, + cycleCostUsd: 0, + poolLastActivityMs: t3, + nowMs: tReset, + }); + assert.equal(rReset.reservedPct, 0); + assert.ok(tracker._buckets.get(key).ratePctPerUsd > 0, 'calibrated rate preserved across reset'); +}); + +test('experimentalQuotaReservation setting defaults false and round-trips through schema & backup', () => { + const def = normalizeFullSettings({}); + assert.equal(def.experimentalQuotaReservation, false); + + const enabled = normalizeFullSettings({ experimentalQuotaReservation: true }); + assert.equal(enabled.experimentalQuotaReservation, true); + + const json = buildExportableSettingsJson(enabled); + const parsed = parseImportedSettingsJson(json); + assert.equal(parsed.ok, true); + assert.equal(parsed.patch.experimentalQuotaReservation, true); +}); + +test('backendHarness buildTelemetry populates reservedPct on pools across official quota jumps', async () => { + let now = T0; + const h = backendHarness({ + clock: () => now, + userStatus: { email: 'tester@example.com', userTier: { name: 'Google AI Ultra' } }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { + bucketId: 'gemini-5h', + window: '5h', + remainingFraction: 0.96, + resetTime: new Date(RESET_5H).toISOString(), + }, + { + bucketId: 'gemini-weekly', + window: 'weekly', + remainingFraction: 0.85, + resetTime: new Date(RESET_WK).toISOString(), + }, + ], + }, + ], + }, + }); + + const p1 = await h.buildTelemetryPayloadInternal(null, true); + const g1 = p1.quotas.pools.find((p) => p.poolKey === 'Gemini'); + assert.equal(p1.settings.experimentalQuotaReservation, false); + assert.equal(g1.reservedPct, 0); + assert.equal(g1.weeklyReservedPct, 0); + + // Advance clock beyond quota cache TTL and simulate a +1.0% 5h lease jump with no local cost change + now += 20_000; + h.state.quotaSummary = { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { + bucketId: 'gemini-5h', + window: '5h', + remainingFraction: 0.95, + resetTime: new Date(RESET_5H).toISOString(), + }, + { + bucketId: 'gemini-weekly', + window: 'weekly', + remainingFraction: 0.845, + resetTime: new Date(RESET_WK).toISOString(), + }, + ], + }, + ], + }; + + const p2 = await h.buildTelemetryPayloadInternal(null, true); + const g2 = p2.quotas.pools.find((p) => p.poolKey === 'Gemini'); + assert.equal(g2.reservedPct, 1.0); + assert.equal(g2.weeklyReservedPct, 0.5); + + const logRes = await h.dispatchBridgeApiRequest('/api/quota-reservation/log', 'GET'); + assert.equal(logRes.status, 200); + const logJson = JSON.parse(logRes.body); + assert.equal(logJson.ok, true); + assert.ok(logJson.count >= 4, 'baseline + lease events recorded in ring buffer'); + assert.ok( + logJson.events.some((e) => e.pool === 'Gemini' && e.win === '5h' && e.event === 'lease'), + '5h lease jump logged' + ); + assert.ok( + logJson.events.some((e) => e.pool === 'Gemini' && e.win === 'weekly' && e.event === 'lease'), + 'weekly lease jump logged' + ); +}); + +test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/text and toggle', async () => { + const { document } = createMockDom(); + const origDocument = globalThis.document; + const origWindow = globalThis.window; + const origFetch = globalThis.fetch; + const origNavigator = globalThis.navigator; + let copiedClipboardText = ''; + Object.defineProperty(globalThis, 'navigator', { + configurable: true, + value: { + clipboard: { + async writeText(text) { + copiedClipboardText = String(text); + }, + }, + }, + }); + globalThis.document = document; + globalThis.window = { + innerWidth: 960, + innerHeight: 720, + addEventListener() {}, + removeEventListener() {}, + location: { origin: 'http://127.0.0.1:0', href: 'http://127.0.0.1:0/' }, + }; + const savedPatches = []; + globalThis.fetch = async (url, opts = {}) => { + if (String(url).includes('/api/quota-reservation/log')) { + return { + ok: true, + status: 200, + json: async () => ({ + ok: true, + generatedAt: '2026-11-22T09:20:00.000Z', + count: 1, + buckets: [{ pool: 'Gemini', win: '5h', usedPct: 4.1, reservedPct: 1, leases: 1 }], + events: [ + { + ts: '2026-11-22T09:19:50.000Z', + pool: 'Gemini', + win: '5h', + event: 'lease', + usedPct: 4.1, + dUsed: 1, + rsvPct: 1, + leases: 1, + }, + ], + }), + }; + } + if (String(url).includes('/api/settings') && opts.method === 'POST') { + const patch = JSON.parse(opts.body); + savedPatches.push(patch); + return { + ok: true, + status: 200, + json: async () => ({ ok: true, settings: patch }), + }; + } + return { ok: true, status: 200, json: async () => ({ ok: true }) }; + }; + + try { + const [{ setI18nLanguage }, { QuotaPoolsWidget }, { SettingsOtherTab }] = await Promise.all([ + import('../src/i18n/index.js'), + import('../src/components/widgets/QuotaPoolsWidget.js'), + import('../src/views/settings/SettingsOtherTab.js'), + ]); + setI18nLanguage('zh-CN'); + + const widget = QuotaPoolsWidget(); + const baseData = { + settings: { experimentalQuotaReservation: false }, + account: { tierName: 'Google AI Ultra', planName: 'Pro' }, + quotas: { + pools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + usedPct: 4.1, + remainingPct: 95.9, + reservedPct: 1.0, + reservedLeaseCount: 1, + resetTime: new Date(Date.now() + 3 * 3600 * 1000).toISOString(), + weeklyUsedPct: 16.2, + weeklyRemainingPct: 83.8, + weeklyReservedPct: 0.5, + weeklyReservedLeaseCount: 1, + weeklyResetTime: new Date(Date.now() + 5 * 24 * 3600 * 1000).toISOString(), + }, + ], + weekly: { isOfficial: true }, + }, + }; + + // Toggle OFF: no reserved highlight + widget.refs.update({ data: baseData, minuteTick: 1 }); + const rsvTagsOff = widget.el.querySelectorAll('.quota-reserved-pct'); + assert.equal(rsvTagsOff.length, 2); + assert.equal(rsvTagsOff[0].hidden, true); + assert.equal(rsvTagsOff[1].hidden, true); + const fillBarsOff = widget.el.querySelectorAll('.progress-fill'); + assert.equal(fillBarsOff[0].style.getPropertyValue('--fill-w'), '4.1%'); + + // Toggle ON: violet reserved bar segment + colored percentage tag + widget.refs.update({ + data: { ...baseData, settings: { experimentalQuotaReservation: true } }, + minuteTick: 1, + }); + const rsvTagsOn = widget.el.querySelectorAll('.quota-reserved-pct'); + assert.equal(rsvTagsOn[0].hidden, false); + assert.equal(rsvTagsOn[0].textContent, '预占 1.0%'); + assert.equal(rsvTagsOn[1].hidden, false); + assert.equal(rsvTagsOn[1].textContent, '预占 0.5%'); + + const fillBarsOn = widget.el.querySelectorAll('.progress-fill'); + const rsvBarsOn = widget.el.querySelectorAll('.progress-fill-reserved'); + assert.equal(fillBarsOn[0].style.getPropertyValue('--fill-w'), '3.1%'); + assert.equal(rsvBarsOn[0].style.getPropertyValue('--reserved-w'), '1%'); + assert.equal(rsvBarsOn[0].classList.contains('is-active'), true); + assert.equal(fillBarsOn[1].style.getPropertyValue('--fill-w'), '15.7%'); + assert.equal(rsvBarsOn[1].style.getPropertyValue('--reserved-w'), '0.5%'); + + // SettingsOtherTab renders experimental badge and persists toggle click + const othTab = SettingsOtherTab({ onLayoutChange: () => {} }); + othTab.refs.renderSettings({ experimentalQuotaReservation: false }, []); + const badge = othTab.el.querySelector('.settings-experimental-badge'); + assert.ok(badge, 'experimental badge rendered'); + assert.equal(badge.textContent, '试验性'); + + const toggleBtns = othTab.refs.quotaReserveToggle.el.querySelectorAll('.seg-btn'); + assert.equal(toggleBtns.length, 2); + toggleBtns[0].dispatchEvent({ + type: 'click', + stopPropagation() {}, + preventDefault() {}, + }); + await new Promise((r) => setTimeout(r, 15)); + assert.equal( + savedPatches.some((p) => p.experimentalQuotaReservation === true), + true, + 'clicking 开启 saves experimentalQuotaReservation: true' + ); + + othTab.refs.exportReserveLogBtn.dispatchEvent({ type: 'click' }); + await new Promise((r) => setTimeout(r, 25)); + const copiedObj = JSON.parse(copiedClipboardText); + assert.equal(copiedObj.count, 1); + assert.equal(copiedObj.events[0].event, 'lease'); + assert.equal(copiedObj.events[0].pool, 'Gemini'); + + othTab.destroy(); + widget.destroy(); + } finally { + globalThis.fetch = origFetch; + globalThis.document = origDocument; + globalThis.window = origWindow; + Object.defineProperty(globalThis, 'navigator', { + configurable: true, + value: origNavigator, + }); + } +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 65cb9be..4d42fea 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -2082,8 +2082,10 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const maintBtns = otherPane .querySelectorAll('.btn-secondary') .filter((btn) => !btn.classList.contains('ctx-risk-accept-btn')); - const rebuildBtn = maintBtns[0]; - const resetAllBtn = maintBtns[1]; + const exportReserveLogBtn = maintBtns.find((b) => /导出预占日志/.test(b.textContent)); + assert.ok(exportReserveLogBtn, 'Experimental quota reservation log export button rendered'); + const rebuildBtn = maintBtns.find((b) => /重建本地轨迹缓存/.test(b.textContent)); + const resetAllBtn = maintBtns.find((b) => /恢复全部默认设置/.test(b.textContent)); rebuildBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(cacheRebuildCalls, 1, 'POST /api/cache/rebuild invoked cleanly'); From 6da6c75390fa5e651b1cc1a0848a705b23c28c41 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 22 Nov 2026 20:59:02 +0900 Subject: [PATCH 21/31] feat(panel): refine quota reservation estimator, tier 5x/20x badge, conditional argon_weekly slot, and chart markers --- sidecars/panel/app.js | 416 +++++++++----- .../panel/backend/cli-statusline-config.mjs | 11 +- sidecars/panel/backend/config.mjs | 1 + sidecars/panel/backend/quota-reservation.mjs | 533 +++++++++++++++--- sidecars/panel/backend/telemetry-builder.mjs | 40 +- sidecars/panel/index.html | 4 +- .../panel/shared/settings-normalization.mjs | 1 + .../panel/shared/telemetry-display-rules.mjs | 64 ++- .../components/charts/SessionStepCharts.js | 75 ++- .../src/components/charts/TrendAreaChart.js | 27 +- .../settings/structurePreviewMock.js | 25 +- .../components/widgets/QuotaPoolsWidget.js | 70 ++- sidecars/panel/src/i18n/en-US.js | 9 +- sidecars/panel/src/i18n/zh-CN.js | 9 +- .../panel/src/registries/metricRegistry.js | 60 +- sidecars/panel/src/store/telemetryStore.js | 2 + sidecars/panel/src/styles/modern-ui.css | 5 - sidecars/panel/src/styles/views-overview.css | 57 +- sidecars/panel/src/styles/views-tables.css | 25 +- sidecars/panel/src/views/SettingsView.js | 3 +- .../views/settings/SettingsStructureTab.js | 72 ++- sidecars/panel/styles.css | 87 ++- sidecars/panel/test/quota-pools.test.mjs | 138 +++++ .../panel/test/quota-reservation.test.mjs | 320 ++++++++++- sidecars/panel/test/step-anomalies.test.mjs | 7 +- sidecars/panel/test/window-bridge.test.mjs | 4 +- 26 files changed, 1673 insertions(+), 392 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 2f7bb22..53f2bda 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -33,6 +33,7 @@ const TOPBAR_SLOT_KEYS = Object.freeze([ 'quota_auto', 'gemini_5h', 'gemini_weekly', + 'argon_weekly', 'claude_5h', 'claude_weekly', ]); @@ -592,7 +593,7 @@ return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KE })(); // --- shared/telemetry-display-rules.mjs --- -const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { +const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { /** * @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。 */ @@ -691,8 +692,40 @@ function formatCompactCapsuleTtft(ttftSec) { return `${Math.round(val)}s`; } +function readPoolWeeklyRemainingPct(pool) { + if (!pool || typeof pool !== 'object') return null; + const raw = pool.weeklyRemainingPct ?? pool.remainingWeeklyPct; + return raw != null && Number.isFinite(Number(raw)) ? Number(raw) : null; +} + +function isArgonPoolObject(pool) { + if (!pool || typeof pool !== 'object') return false; + if (pool.poolKey === 'Argon' || pool.family === 'Argon') return true; + return /\bargon\b/i.test(String(pool.poolKey || pool.poolLabel || pool.family || '')); +} + /** - * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 + * 判断当前配额摘要中是否存在独立的 Argon 周限配额池(如 Google AI Pro 账号)。 + * + * @param {object|null|undefined} quotas + * @returns {boolean} + */ +function hasArgonWeeklyQuotaPool(quotas) { + if (!quotas || typeof quotas !== 'object') return false; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const argonPool = pools.find(isArgonPoolObject); + if (argonPool && readPoolWeeklyRemainingPct(argonPool) != null) { + return true; + } + const activePool = quotas.activePool; + if (activePool && isArgonPoolObject(activePool) && readPoolWeeklyRemainingPct(activePool) != null) { + return true; + } + return false; +} + +/** + * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `argon_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 * * @param {object|null|undefined} quotas * @param {string} slotKey @@ -709,8 +742,9 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (activePool && Number.isFinite(Number(activePool.remainingPct))) { candidates.push(Number(activePool.remainingPct)); } - if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { - candidates.push(Number(activePool.weeklyRemainingPct)); + const activeWk = readPoolWeeklyRemainingPct(activePool); + if (activeWk != null) { + candidates.push(activeWk); } if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { candidates.push(Number(weekly.remainingPct)); @@ -718,15 +752,24 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (!candidates.length && pools.length > 0) { for (const p of pools) { if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); - if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { - candidates.push(Number(p.weeklyRemainingPct)); - } + const pWk = readPoolWeeklyRemainingPct(p); + if (pWk != null) candidates.push(pWk); } } if (!candidates.length) return null; return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); } + if (slotKey === 'argon_weekly') { + const argonPool = pools.find(isArgonPoolObject); + let argonPct = readPoolWeeklyRemainingPct(argonPool); + if (argonPct == null && isArgonPoolObject(activePool)) { + argonPct = readPoolWeeklyRemainingPct(activePool); + } + if (argonPct == null || !Number.isFinite(argonPct)) return null; + return Math.max(0, Math.min(100, Math.round(argonPct))); + } + const isClaude = slotKey.startsWith('claude_'); const isWeekly = slotKey.endsWith('_weekly'); let rawPct = null; @@ -735,11 +778,11 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const claudePool = pools.find((p) => p?.poolKey === 'Claude & GPT') || pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + const cand = isWeekly ? readPoolWeeklyRemainingPct(claudePool) : claudePool?.remainingPct; if (cand != null && Number.isFinite(Number(cand))) { rawPct = Number(cand); } else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } } else { @@ -753,12 +796,12 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const geminiFamilyPools = pools.filter((p) => /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + const primaryCand = isWeekly ? readPoolWeeklyRemainingPct(stdGemini) : stdGemini?.remainingPct; if (primaryCand != null && Number.isFinite(Number(primaryCand))) { rawPct = Number(primaryCand); } else { const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .map((p) => (isWeekly ? readPoolWeeklyRemainingPct(p) : p?.remainingPct)) .filter((v) => v != null && Number.isFinite(Number(v))) .map(Number); if (familyVals.length > 0) { @@ -767,7 +810,7 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { activePool && !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } if ( @@ -836,7 +879,7 @@ function scaleBucketsExact(buckets, keys, targetTotal) { } return out; } -return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; +return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; })(); // --- shared/window-bridge-protocol.mjs --- @@ -1333,6 +1376,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'capMetric.quota_auto': '自动紧俏额度', 'capMetric.gemini_5h': 'Gemini 5h 额度', 'capMetric.gemini_weekly': 'Gemini 周额度', + 'capMetric.argon_weekly': 'Argon 周额度', 'capMetric.claude_5h': 'Claude 5h 额度', 'capMetric.claude_weekly': 'Claude 周额度', @@ -1395,6 +1439,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.usedAfterReserved': ' · 余 {rem}%)', 'quota.reservedTip': '预占估算(试验性):约 {rsv}%(实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.reservedTipMulti': '预占估算(试验性):约 {rsv}%(检测到 {leases} 笔叠加租约,实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', + 'quota.legendActual': '实占', + 'quota.legendReserved': '预占', 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', @@ -1899,7 +1945,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.quotaReserveLabel': '配额预占估算', 'settings.oth.quotaReserveDesc': '在可用额度中估算 5h / 周限的 0.5% / 1% 租约预占,并用紫色标注占比及进度条段', 'settings.oth.quotaReserveLogLabel': '预占观测日志', - 'settings.oth.quotaReserveLogDesc': '将内存中的配额跳变及退还记录复制到剪贴板,便于分析触发阈值', + 'settings.oth.quotaReserveLogDesc': '将配额跳变及退还观测记录复制到剪贴板,重启后自动保留,便于分析触发阈值', 'settings.oth.exportReserveLogBtn': '导出预占日志', 'settings.oth.exportReserveLogCopied': '已复制 {count} 条观测日志到剪贴板', 'settings.oth.exportReserveLogEmpty': '暂无跳变记录,已复制当前摘要到剪贴板', @@ -1939,7 +1985,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', 'settings.oth.backupLabel': '配置备份及恢复', - 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON(不含账号凭证)', + 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON', 'settings.oth.exportJsonBtn': '导出 JSON', 'settings.oth.importJsonBtn': '导入 JSON', 'settings.oth.exportDone': '配置 JSON 已导出', @@ -1953,7 +1999,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.migModeLabel': '迁移方式', 'settings.oth.migModeMove': '完整迁移(推荐)', 'settings.oth.migModeClone': '克隆副本', - 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端(零重复计费;迁移前建议先关闭源端该会话)', + 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端', 'settings.oth.migModeCloneHint': '保留源会话并生成新 ID,新副本仅统计迁入后的新步骤', 'settings.oth.migProjectLabel': '绑定目标项目', 'settings.oth.migProjectOutside': '独立会话(无所属项目)', @@ -2208,6 +2254,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'capMetric.quota_auto': 'Auto Tightest Quota', 'capMetric.gemini_5h': 'Gemini 5h Quota', 'capMetric.gemini_weekly': 'Gemini Weekly Quota', + 'capMetric.argon_weekly': 'Argon Weekly Quota', 'capMetric.claude_5h': 'Claude 5h Quota', 'capMetric.claude_weekly': 'Claude Weekly Quota', @@ -2270,6 +2317,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.usedAfterReserved': ' · {rem}% left)', 'quota.reservedTip': 'Estimated lease reservation (Experimental): ~{rsv}% (~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.reservedTipMulti': 'Estimated lease reservation (Experimental): ~{rsv}% ({leases} stacked leases, ~{actual}% actual used); unused share refunds after ~10 min idle', + 'quota.legendActual': 'Actual', + 'quota.legendReserved': 'Reserved', 'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', @@ -2774,7 +2823,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.quotaReserveLabel': 'Quota Reservation Estimate', 'settings.oth.quotaReserveDesc': 'Estimate 0.5% / 1% 5h & weekly lease holds in Available Quotas and highlight the reserved share in violet', 'settings.oth.quotaReserveLogLabel': 'Reservation Observation Log', - 'settings.oth.quotaReserveLogDesc': 'Copy in-memory quota jump & refund events to clipboard for threshold tuning', + 'settings.oth.quotaReserveLogDesc': 'Copy persisted quota jump & refund observations to clipboard (retained across restarts)', 'settings.oth.exportReserveLogBtn': 'Export Reserve Log', 'settings.oth.exportReserveLogCopied': 'Copied {count} log entries to clipboard', 'settings.oth.exportReserveLogEmpty': 'No events yet; copied current summary to clipboard', @@ -2814,7 +2863,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', 'settings.oth.backupLabel': 'Preferences Backup & Restore', - 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON (excludes credentials)', + 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON', 'settings.oth.exportJsonBtn': 'Export JSON', 'settings.oth.importJsonBtn': 'Import JSON', 'settings.oth.exportDone': 'Preferences JSON exported', @@ -2828,7 +2877,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.migModeLabel': 'Migration Mode', 'settings.oth.migModeMove': 'Full Move (Recommended)', 'settings.oth.migModeClone': 'Clone Copy', - 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving (close source session first)', + 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving', 'settings.oth.migModeCloneHint': 'Keeps source intact with a fresh UUID; only counts new steps generated after cloning', 'settings.oth.migProjectLabel': 'Target Project', 'settings.oth.migProjectOutside': 'Standalone (No Project)', @@ -9660,7 +9709,9 @@ function isEquivalentTelemetry(prev, next) { prev.account?.email !== next.account?.email || prev.account?.name !== next.account?.name || prev.account?.status !== next.account?.status || + prev.account?.tierId !== next.account?.tierId || prev.account?.tierName !== next.account?.tierName || + prev.account?.tierMultiplier !== next.account?.tierMultiplier || prev.account?.planName !== next.account?.planName || prev.account?.aiCredits !== next.account?.aiCredits ) { @@ -13349,16 +13400,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); - const dotsGroup = document.createElementNS(SVG_NS, 'g'); - dotsGroup.setAttribute('class', 'trend-dots-group'); - svg.appendChild(dotsGroup); - - const peakDot = document.createElementNS(SVG_NS, 'circle'); - peakDot.setAttribute('r', '3'); - peakDot.setAttribute('class', 'trend-peak-dot'); - svg.appendChild(peakDot); - - // 悬停十字准星与焦点圆点 + // 悬停十字准星及焦点圆点 const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '12'); @@ -14197,25 +14239,9 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } - - // 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期) - while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); - if (pts.length <= 36) { - for (let i = 0; i < pts.length; i++) { - if (pts[i].tokens <= 0) continue; - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pts[i].x.toFixed(1)); - dot.setAttribute('cy', pts[i].y.toFixed(1)); - dot.setAttribute('r', '2'); - dot.setAttribute('class', 'trend-node-dot'); - dotsGroup.appendChild(dot); - } - } } const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; - patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); - patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); const peakSlot = slots[peakIdx]; const peakText = @@ -15542,16 +15568,15 @@ function createSessionLineChart() { patchStyleVar(mLine, '--sstep-fit-accent', seriesColor); multiLineGroup.appendChild(mLine); - if (seriesPts.length <= 36) { - for (const pt of seriesPts) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - dot.setAttribute('r', seriesPts.length > 20 ? '1.7' : '2.1'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar(dot, '--dot-stroke', seriesColor); - dotsGroup.appendChild(dot); - } + if (seriesPts.length === 1) { + const pt = seriesPts[0]; + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', pt.x.toFixed(1)); + dot.setAttribute('cy', pt.y.toFixed(1)); + dot.setAttribute('r', '2.1'); + dot.setAttribute('class', 'sstep-node-dot'); + patchStyleVar(dot, '--dot-stroke', seriesColor); + dotsGroup.appendChild(dot); } } } @@ -15575,40 +15600,30 @@ function createSessionLineChart() { patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`); } - - if (points.length <= 64) { - for (const pt of points) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - if (pt.valid) { - dot.setAttribute('r', points.length > 36 ? '1.8' : '2.3'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar( - dot, - '--dot-stroke', - modelColorMap.size > 1 ? pt.dotColor : accentColor - ); - } else { - dot.setAttribute('r', '1.6'); - dot.setAttribute('class', 'sstep-node-dot is-skipped'); - } - dotsGroup.appendChild(dot); - } - } } + const anomalyTicks = []; for (const pt of points) { if (!pt.valid || !pt.anomalySummary) continue; - const aDot = document.createElementNS(SVG_NS, 'circle'); - aDot.setAttribute('cx', pt.x.toFixed(1)); - aDot.setAttribute('cy', pt.y.toFixed(1)); - aDot.setAttribute('r', '2.9'); - aDot.setAttribute( + anomalyTicks.push(pt); + } + anomalyTicks.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); + const tickTopY = (BOTTOM_Y - 5).toFixed(1); + const tickBotY = BOTTOM_Y.toFixed(1); + for (const pt of anomalyTicks) { + const xStr = pt.x.toFixed(1); + const aTick = document.createElementNS(SVG_NS, 'line'); + aTick.setAttribute('x1', xStr); + aTick.setAttribute('x2', xStr); + aTick.setAttribute('y1', tickTopY); + aTick.setAttribute('y2', tickBotY); + aTick.setAttribute( 'class', - `sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` + `sstep-anomaly-dot sstep-anomaly-tick${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` ); - anomalyDotsGroup.appendChild(aDot); + anomalyDotsGroup.appendChild(aTick); } const tickIndices = computeStepTickIndices(points.length); @@ -16519,11 +16534,14 @@ function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + anomalyOverlayDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const sp of anomalyOverlayDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', sp.x.toFixed(1)); aDot.setAttribute('cy', sp.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}` @@ -16693,11 +16711,14 @@ function createModelFitChart() { dot.setAttribute('class', 'sstep-scatter-dot'); scatterTarget.appendChild(dot); } + singleAnomalyDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const s of singleAnomalyDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', s.x.toFixed(1)); aDot.setAttribute('cy', s.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}` @@ -16803,11 +16824,16 @@ const { CAPSULE_METRIC_KEYS, getCapsuleMetricOptions, getOverviewMetricOptions, const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS; -function getCapsuleMetricOptions() { - return CAPSULE_METRIC_KEYS.map((key) => ({ - value: key, - label: t(`capMetric.${key}`), - })); +function getCapsuleMetricOptions({ quotas = null, selectedSlots = [] } = {}) { + const showArgonWeekly = + hasArgonWeeklyQuotaPool(quotas) || + (Array.isArray(selectedSlots) && selectedSlots.includes('argon_weekly')); + return CAPSULE_METRIC_KEYS.filter((key) => key !== 'argon_weekly' || showArgonWeekly).map( + (key) => ({ + value: key, + label: t(`capMetric.${key}`), + }) + ); } function getOverviewMetricOptions() { @@ -16870,17 +16896,21 @@ function resolveQuotaCapsuleSummary(quotas) { : `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} · ${tightest.windowTag}`; const tightestIsClaude = /claude|gpt|fable|oss|third/i.test(String(tightest.label || '')); - const tightestIsGemini = !tightestIsClaude && /gemini|argon|carbon|neon|flash|pro/i.test(String(tightest.label || '')); + const tightestIsArgon = !tightestIsClaude && /\bargon\b/i.test(String(tightest.label || '')); + const tightestIsGemini = + !tightestIsClaude && !tightestIsArgon && /gemini|carbon|neon|flash|pro/i.test(String(tightest.label || '')); const tightestWinShort = tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'w' : '周'; const poolPrefix = tightestIsClaude ? `C${tightestWinShort}` - : tightestIsGemini - ? `G${tightestWinShort}` - : tightest.windowTag === '5h' - ? '5h' - : isEnglishLocale() - ? 'Wk' - : '周'; + : tightestIsArgon + ? `A${tightestWinShort}` + : tightestIsGemini + ? `G${tightestWinShort}` + : tightest.windowTag === '5h' + ? '5h' + : isEnglishLocale() + ? 'Wk' + : '周'; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), @@ -16899,6 +16929,7 @@ function resolveQuotaCapsulePrefix(metricKey, quotaSum) { const isEn = isEnglishLocale(); if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; + if (metricKey === 'argon_weekly') return isEn ? 'Aw' : 'A周'; if (metricKey === 'claude_5h') return 'C5h'; if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; if (quotaSum?.poolPrefix) return quotaSum.poolPrefix; @@ -17119,6 +17150,22 @@ function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) }; } + if (metricKey === 'argon_weekly' && slotCtx.hasTelemetry && !hasArgonWeeklyQuotaPool(slotCtx.quotas)) { + return { + hidden: true, + metric: 'none', + segClass: 'wm-cap-slot', + textClass: 'wm-slot-text', + showRing: false, + dashOffset: ringCircumference, + text: '', + toneClass: '', + running: false, + warn: false, + danger: false, + }; + } + const quotaSum = !slotCtx.hasTelemetry ? null : metricKey === 'quota_auto' @@ -18092,7 +18139,7 @@ return { CTX_CHANNEL_DEFS, ContextWindowWidget }; })(); // --- src/components/widgets/QuotaPoolsWidget.js --- -const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, QuotaPoolsWidget } = (() => { +const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget } = (() => { /** * @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`). * Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT) @@ -18293,7 +18340,7 @@ function syncQuotaWindowMeter({ const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); patchStyleVar(fillEl, '--fill-w', `${actualWidth}%`); patchStyleVar(fillReservedEl, '--reserved-w', `${rsvWidth}%`); - patchClasses(fillReservedEl, { 'is-active': true }); + patchClasses(fillReservedEl, { 'is-active': true, 'has-sep': actualWidth > 0 }); } else { patchText( metaBeforeEl, @@ -18313,7 +18360,7 @@ function syncQuotaWindowMeter({ patchAttr(trackEl, 'title', null); patchStyleVar(fillEl, '--fill-w', `${Math.min(100, usedVal)}%`); patchStyleVar(fillReservedEl, '--reserved-w', '0%'); - patchClasses(fillReservedEl, { 'is-active': false }); + patchClasses(fillReservedEl, { 'is-active': false, 'has-sep': false }); } patchClasses(fillEl, { @@ -18453,6 +18500,45 @@ function quotaPoolRowSig(item, idx) { return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } +/** + * 格式化可用额度面板右上角的账号订阅徽章(区分 Ultra 5x / 20x,并对 Pro / Free 去重)。 + * + * @param {object|null|undefined} account + * @returns {string} + */ +function formatAccountTierBadge(account) { + const tierName = String(account?.tierName || '').trim() || 'Google AI'; + const tierId = String(account?.tierId || '').trim().toLowerCase(); + const explicitMult = String(account?.tierMultiplier || '').trim(); + const inferredMult = + explicitMult || + (/(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(`${tierId} ${tierName}`) + ? '5x' + : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(`${tierId} ${tierName}`) || tierId === 'g1-ultra-tier' + ? '20x' + : ''); + const rawPlan = String(account?.planName || '').trim(); + const isUltra = /\bultra\b/i.test(tierName) || /ultra/i.test(tierId); + + if (isUltra) { + if (inferredMult) { + const hasMultInTier = new RegExp(`(?:^|\\s|·)${inferredMult}(?:$|\\s)`, 'i').test(tierName); + return hasMultInTier ? tierName : `${tierName} · ${inferredMult}`; + } + if (rawPlan && !/^(?:pro|ultra)$/i.test(rawPlan)) { + return `${tierName} · ${rawPlan}`; + } + return tierName; + } + + if (!rawPlan) return tierName; + const escapedPlan = rawPlan.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + if (new RegExp(`(?:^|\\s|·)${escapedPlan}(?:$|\\s)`, 'i').test(tierName)) { + return tierName; + } + return `${tierName} · ${rawPlan}`; +} + const QuotaPoolsWidget = defineComponent({ name: 'QuotaPoolsWidget', setup({ props }) { @@ -18475,6 +18561,23 @@ const QuotaPoolsWidget = defineComponent({ }); } + const legendActualTextEl = h('span', { text: t('quota.legendActual') }); + const legendReservedTextEl = h('span', { text: t('quota.legendReserved') }); + const reserveLegendEl = h( + 'div', + { className: 'quota-reserve-legend', hidden: true }, + [ + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-actual', 'aria-hidden': 'true' }), + legendActualTextEl, + ]), + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-reserved', 'aria-hidden': 'true' }), + legendReservedTextEl, + ]), + ] + ); + const quotaPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -18484,11 +18587,15 @@ const QuotaPoolsWidget = defineComponent({ tierBadge, ]), poolsListEl, + reserveLegendEl, ]); function update({ data, minuteTick } = {}) { patchText(titleTextEl, t('module.quotas')); + patchText(legendActualTextEl, t('quota.legendActual')); + patchText(legendReservedTextEl, t('quota.legendReserved')); if (!data) { + reserveLegendEl.hidden = true; if (compactHover) { patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), { keyFn: (item) => item.key, @@ -18502,11 +18609,9 @@ const QuotaPoolsWidget = defineComponent({ const quotas = data.quotas || {}; const showReserved = data.settings?.experimentalQuotaReservation === true; + reserveLegendEl.hidden = !showReserved; const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000); - patchText( - tierBadge, - `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` - ); + patchText(tierBadge, formatAccountTierBadge(data.account)); patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick, { showReserved }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, @@ -18521,7 +18626,7 @@ const QuotaPoolsWidget = defineComponent({ }; }, }); -return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, QuotaPoolsWidget }; +return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget }; })(); // --- src/components/widgets/LiveActivityWidget.js --- @@ -22453,7 +22558,11 @@ const { buildStructurePreviewTelemetry } = (() => { */ -function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) { +function buildStructurePreviewTelemetry( + baseSettings = {}, + draftOverrides = {}, + { includeArgonPool = false } = {} +) { const anchorMinMs = Math.floor(Date.now() / 60000) * 60000; const reset5hIso = new Date(anchorMinMs + (2 * 60 + 42) * 60000).toISOString(); const resetWkIso = new Date(anchorMinMs + (4 * 24 * 60 + 180) * 60000).toISOString(); @@ -22807,8 +22916,10 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) return { settings: mergedSettings, account: { + tierId: 'g1-ultra-lite-tier', tierName: 'Google AI Ultra', - planName: 'Pro', + tierMultiplier: '5x', + planName: '5x', aiCredits: 0, }, quotas: { @@ -22846,6 +22957,21 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 }, cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 }, }, + ...(includeArgonPool + ? [ + { + poolKey: 'Argon', + poolLabel: 'Gemini 4 Argon', + family: 'Argon', + has5h: false, + hasWeekly: true, + weeklyUsedPct: 58, + weeklyRemainingPct: 42, + weeklyResetTime: resetWkIso, + cycleWeekly: { tokens: 4200000, costUsd: 6.4, calls: 48 }, + }, + ] + : []), { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', @@ -25439,6 +25565,15 @@ function formatCliPreviewSlot(slotKey, slotCtx, isEn) { pillPct: pct, }; } + case 'argon_weekly': { + const pct = quotaPct('argon_weekly', 42); + return { + prefix: isEn ? 'Aw ' : 'A周 ', + text: `${pct}%`, + tone: 'good', + pillPct: pct, + }; + } case 'claude_5h': { const pct = quotaPct('claude_5h', 32); return { @@ -25498,6 +25633,7 @@ const SettingsStructureTab = defineComponent({ let latestWindowBridge = null; let latestCliStatusLine = null; let latestHostPlatform = 'win32'; + let latestQuotas = null; function getEffectiveDraftCliSlots() { return resolveEffectiveClientCliStatusLineSlots({ @@ -25512,25 +25648,34 @@ const SettingsStructureTab = defineComponent({ } function buildDraftTelemetry() { - return buildStructurePreviewTelemetry(latestSettings, { - windowMountMode: draftWindowMountMode, - enableWindowOverlay: draftWindowMountMode !== 'sidebar', - popoverWidthMode: draftPopoverWidthMode, - popoverWidth: draftPopoverWidth, - enableCliStatusLine: draftEnableCliStatusLine, - showTopbarMultiSession: draftShowTopbarMulti, - contextAgentMode: draftContextAgentMode, - topbarCapsuleSlots: draftTopbarSlots, - hoverModules: draftHoverModules, - overviewModules: draftOverviewModules, - overviewMetrics: draftOverviewMetrics, - showStepTurnRail: draftShowStepTurnRail, - showStepAgentBadge: draftShowStepAgentBadge, - showStepSpeedColor: draftShowStepSpeedColor, - showStepFilterToolbar: draftShowStepFilterToolbar, - stepTokenComboFormat: draftStepTokenComboFormat, - stepTableColumns: draftStepColumns, - }); + const effectiveCliSlots = getEffectiveDraftCliSlots(); + const includeArgonPool = + hasArgonWeeklyQuotaPool(latestQuotas) || + draftTopbarSlots.includes('argon_weekly') || + effectiveCliSlots.includes('argon_weekly'); + return buildStructurePreviewTelemetry( + latestSettings, + { + windowMountMode: draftWindowMountMode, + enableWindowOverlay: draftWindowMountMode !== 'sidebar', + popoverWidthMode: draftPopoverWidthMode, + popoverWidth: draftPopoverWidth, + enableCliStatusLine: draftEnableCliStatusLine, + showTopbarMultiSession: draftShowTopbarMulti, + contextAgentMode: draftContextAgentMode, + topbarCapsuleSlots: draftTopbarSlots, + hoverModules: draftHoverModules, + overviewModules: draftOverviewModules, + overviewMetrics: draftOverviewMetrics, + showStepTurnRail: draftShowStepTurnRail, + showStepAgentBadge: draftShowStepAgentBadge, + showStepSpeedColor: draftShowStepSpeedColor, + showStepFilterToolbar: draftShowStepFilterToolbar, + stepTokenComboFormat: draftStepTokenComboFormat, + stepTableColumns: draftStepColumns, + }, + { includeArgonPool } + ); } async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') { @@ -26023,7 +26168,10 @@ const SettingsStructureTab = defineComponent({ const effectiveCliSlots = getEffectiveDraftCliSlots(); cliSlotsList.refs.setProps({ items: effectiveCliSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: effectiveCliSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), }); const preservedCustom = Boolean(latestCliStatusLine?.preservedCustom); @@ -26062,7 +26210,10 @@ const SettingsStructureTab = defineComponent({ refreshCliPreview(); topbarSlotsList.refs.setProps({ items: draftTopbarSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: draftTopbarSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }), }); mountSection.refs.setBadge( @@ -26674,13 +26825,15 @@ const SettingsStructureTab = defineComponent({ settings, windowBridge = latestWindowBridge, hostPlatform = latestHostPlatform, - cliStatusLine = latestCliStatusLine + cliStatusLine = latestCliStatusLine, + quotas = latestQuotas ) { if (!settings) return; latestSettings = settings; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine; + if (quotas !== undefined) latestQuotas = quotas; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay @@ -32736,7 +32889,8 @@ const SettingsView = defineComponent({ settings, telemetry?.windowBridge, telemetry?.hostPlatform, - telemetry?.cliStatusLine + telemetry?.cliStatusLine, + telemetry?.quotas ); } } else if (settingsSubTab === 'other') { diff --git a/sidecars/panel/backend/cli-statusline-config.mjs b/sidecars/panel/backend/cli-statusline-config.mjs index 44f28c5..ebcc362 100644 --- a/sidecars/panel/backend/cli-statusline-config.mjs +++ b/sidecars/panel/backend/cli-statusline-config.mjs @@ -30,6 +30,7 @@ import { formatCompactCapsuleCost, formatCompactCapsuleTtft, formatCompactTokens, + hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, } from '../shared/telemetry-display-rules.mjs'; @@ -810,6 +811,7 @@ function cliBuildBarGauge(label, pct, { fillFg = SGR_FG_ACCENT, valFg = SGR_FG_B function cliResolveQuotaSlotPrefix(metricKey, isEn) { if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; + if (metricKey === 'argon_weekly') return isEn ? 'Aw' : 'A周'; if (metricKey === 'claude_5h') return 'C5h'; if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; return isEn ? '5h' : '余'; @@ -1062,6 +1064,7 @@ const CLI_STATUS_SLOT_KEEP_PRIORITY = Object.freeze({ avg_tps: 45, session_tokens: 40, gemini_weekly: 35, + argon_weekly: 33, claude_weekly: 30, }); @@ -1163,8 +1166,14 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { // 新会话尚无任何完成步骤(stepCount === 0)时,隐藏纯占位性的 "--s" / "--" 槽位,避免刚启动显得满屏缺数据 let activeSlots = rawSlots; + if (slotCtx.hasTelemetry !== false && activeSlots.includes('argon_weekly') && !hasArgonWeeklyQuotaPool(slotCtx.quotas)) { + const withoutArgon = activeSlots.filter((key) => key !== 'argon_weekly'); + if (withoutArgon.length > 0) { + activeSlots = withoutArgon; + } + } if (slotCtx.stepCount === 0) { - const filtered = rawSlots.filter( + const filtered = activeSlots.filter( (key) => key === 'tps' || cliStatusHasRenderableValue(key, slotCtx) ); if (filtered.length > 0) { diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 281f44b..d34275a 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -160,6 +160,7 @@ export const SETTINGS_FILE = join(DATA_DIR, 'settings.json'); export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json'); export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json'); export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json'); +export const QUOTA_RESERVATION_STATE_FILE = join(DATA_DIR, 'quota_reservation_state.json'); /** * 本地对话记录目录、脑图日志目录、守护发现目录与跨端深层统计缓存路径候选列表(联合覆盖 Desktop / CLI / IDE)。 diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs index b06a654..ff2a8c3 100644 --- a/sidecars/panel/backend/quota-reservation.mjs +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -6,10 +6,16 @@ * 2. 多高消耗会话并发时支持多笔租约线性叠加(如 0.5% / 1.0% / 2.0%+); * 3. 在租约期内继续产生真实消耗时按单桶换算率扣减可退差额; * 4. 上游退还租约(同周期内 officialUsedPct 下降)时按 FIFO 精准核销并反向校准单桶费率; - * 5. 纯内存 O(1) 状态机,零额外 RPC、零额外磁盘写入。 + * 5. 轻量 O(1) 状态机 + DATA_DIR 节流持久化(保留最近 500 条事件,重启及热更新后自动恢复)。 */ import { parseIsoMs } from '../trajectory-metrics.mjs'; +import { + QUOTA_RESERVATION_STATE_FILE, + loadJson, + lsRuntimeEndpoint, + saveJson, +} from './config.mjs'; export const QR_LEASE_TTL_MS = 10 * 60 * 1000; export const QR_LEASE_GRACE_MS = 90 * 1000; @@ -22,9 +28,21 @@ export const QR_COLD_START_JUMP_PCT = 0.45; export const QR_COLD_START_MAX_COST_USD = 0.25; export const QR_REFUND_EPSILON_PCT = 0.04; export const QR_MIN_DISPLAY_RESERVED_PCT = 0.05; +export const QR_IDLE_CONFIRM_REFUND_MS = 5 * 60 * 1000; +export const QR_REFUND_CONFIRM_WINDOW_MS = 90 * 1000; +export const QR_REFUND_CONFIRM_MIN_SAMPLES = 3; +export const QR_RATE_BOUNCE_COOLDOWN_MS = 60 * 1000; +export const QR_RATE_WINDOW_SIZE = 20; +export const QR_RATE_OUTLIER_MIN_RATIO = 0.45; +export const QR_RATE_OUTLIER_MAX_RATIO = 2.0; +export const QR_RATE_DRIFT_STREAK = 5; +export const QR_CONSUME_MIN_SHORTFALL_PCT = 0.03; +export const QR_CONSUME_SHORTFALL_RATIO = 0.35; const QR_MAX_TRACKED_BUCKETS = 128; const QR_MAX_ACTIVE_LEASES = 16; const QR_MAX_EVENT_LOG = 500; +const QR_PERSIST_MIN_INTERVAL_MS = 5000; +const QR_STATE_SCHEMA_VERSION = 2; function qrClamp(val, min, max) { return Math.max(min, Math.min(max, val)); @@ -79,18 +97,52 @@ function qrConsumeLeasesFifo(leases, amountPct) { return consumed; } -function qrUpdateRateEma(state, sampleRate) { +function qrComputeMedian(values) { + if (!Array.isArray(values) || values.length === 0) return null; + const sorted = values.slice().sort((a, b) => a - b); + const mid = sorted.length >> 1; + return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +} + +function qrRecordRateSample(state, sampleRate) { const clamped = qrClampRate(sampleRate); - if (clamped === null) return; - if (state.ratePctPerUsd !== null && state.rateSamples >= 3) { - const bounded = qrClamp(clamped, state.ratePctPerUsd * 0.25, state.ratePctPerUsd * 4); - state.ratePctPerUsd = state.ratePctPerUsd * 0.8 + bounded * 0.2; - } else if (state.ratePctPerUsd !== null) { - state.ratePctPerUsd = state.ratePctPerUsd * 0.55 + clamped * 0.45; - } else { - state.ratePctPerUsd = clamped; + if (clamped === null) return false; + const win = Array.isArray(state.rateWindow) ? state.rateWindow : (state.rateWindow = []); + + if (win.length >= 4) { + const med = qrComputeMedian(win); + const lowBound = med * QR_RATE_OUTLIER_MIN_RATIO; + const highBound = med * QR_RATE_OUTLIER_MAX_RATIO; + if (clamped < lowBound || clamped > highBound) { + const side = clamped > highBound ? 1 : -1; + if (state.rateOutlierSide !== side) { + state.rateOutlierSide = side; + state.rateOutlierBuf = [clamped]; + } else { + state.rateOutlierBuf.push(clamped); + } + if (state.rateOutlierBuf.length >= QR_RATE_DRIFT_STREAK) { + // 连续多次干净同向偏移(如账号套餐倍率变化),重置中位数窗口 + state.rateWindow = state.rateOutlierBuf.slice(-QR_RATE_WINDOW_SIZE); + state.rateOutlierSide = 0; + state.rateOutlierBuf = []; + state.ratePctPerUsd = qrClampRate(qrComputeMedian(state.rateWindow)); + state.rateSamples += 1; + return true; + } + return false; + } } + + state.rateOutlierSide = 0; + state.rateOutlierBuf = []; + win.push(clamped); + if (win.length > QR_RATE_WINDOW_SIZE) { + win.splice(0, win.length - QR_RATE_WINDOW_SIZE); + } + state.ratePctPerUsd = qrClampRate(qrComputeMedian(win)); state.rateSamples += 1; + return true; } function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { @@ -103,41 +155,35 @@ function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { return null; } -function qrCalibrateFromSettled(state, officialUsedPct, cycleCostUsd, nowMs) { - if ( - state.lastSettledUsedPct !== null && - state.lastSettledCostUsd !== null && - cycleCostUsd > state.lastSettledCostUsd + 0.25 && - officialUsedPct > state.lastSettledUsedPct + 0.05 - ) { - const dUsed = officialUsedPct - state.lastSettledUsedPct; - const dCost = cycleCostUsd - state.lastSettledCostUsd; - qrUpdateRateEma(state, dUsed / dCost); - } - state.lastSettledUsedPct = officialUsedPct; - state.lastSettledCostUsd = cycleCostUsd; - state.lastSettledAtMs = nowMs; -} - -function qrPruneExpiredLeases(state, poolLastActivityMs, officialUsedPct, cycleCostUsd, nowMs) { +function qrPruneExpiredLeases(state, nowMs) { if (state.activeLeases.length === 0) return; - const beforeLen = state.activeLeases.length; for (let i = state.activeLeases.length - 1; i >= 0; i -= 1) { const lease = state.activeLeases[i]; - const lastActiveMs = Math.max(lease.lastTouchedMs || 0, poolLastActivityMs || 0); + const lastActiveMs = lease.lastTouchedMs || lease.createdAtMs || 0; const idleExpired = lastActiveMs > 0 && nowMs - lastActiveMs >= QR_LEASE_IDLE_EXPIRY_MS; const maxAgeExpired = nowMs - (lease.createdAtMs || 0) >= QR_LEASE_MAX_AGE_MS; if (idleExpired || maxAgeExpired) { state.activeLeases.splice(i, 1); } } - if (beforeLen > 0 && state.activeLeases.length === 0) { - qrCalibrateFromSettled(state, officialUsedPct, cycleCostUsd, nowMs); - } } function qrFormatOutput(state, officialUsedPct) { - const rawReserved = qrClamp(qrSumLeases(state.activeLeases), 0, officialUsedPct); + const rawSum = qrSumLeases(state.activeLeases); + let dropOffset = 0; + if (state.pendingDrop && Number.isFinite(state.pendingDrop.preDropUsedPct)) { + const costSinceDrop = Math.max( + 0, + Number(state.lastCycleCostUsd || 0) - Number(state.pendingDrop.preDropCostUsd || 0) + ); + const expectedSinceDrop = + state.ratePctPerUsd !== null && Number.isFinite(state.ratePctPerUsd) + ? costSinceDrop * state.ratePctPerUsd + : 0; + dropOffset = Math.max(0, state.pendingDrop.preDropUsedPct + expectedSinceDrop - officialUsedPct); + } + const visibleRaw = Math.max(0, rawSum - dropOffset); + const rawReserved = qrClamp(visibleRaw, 0, officialUsedPct); if (rawReserved < QR_MIN_DISPLAY_RESERVED_PCT) { return { reservedPct: 0, @@ -148,7 +194,9 @@ function qrFormatOutput(state, officialUsedPct) { const rounded = qrClamp(qrRound1(rawReserved), 0, qrRound1(officialUsedPct)); let earliestExpiresAtMs = null; for (let i = 0; i < state.activeLeases.length; i += 1) { - const exp = (state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) + QR_LEASE_TTL_MS; + const exp = + (state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) + + QR_LEASE_TTL_MS; if (exp > 0 && (earliestExpiresAtMs === null || exp < earliestExpiresAtMs)) { earliestExpiresAtMs = exp; } @@ -160,18 +208,189 @@ function qrFormatOutput(state, officialUsedPct) { }; } +function qrSanitizePersistedLeases(rawLeases) { + if (!Array.isArray(rawLeases)) return []; + const out = []; + for (let i = 0; i < rawLeases.length && out.length < QR_MAX_ACTIVE_LEASES; i += 1) { + const item = rawLeases[i]; + if (!item || typeof item !== 'object') continue; + const rem = Number(item.remainingPct); + const amt = Number(item.amountPct); + const createdAtMs = Number(item.createdAtMs) || 0; + const lastTouchedMs = Number(item.lastTouchedMs) || createdAtMs; + if (!Number.isFinite(rem) || rem <= 1e-4) continue; + out.push({ + amountPct: Number.isFinite(amt) && amt > 0 ? amt : rem, + remainingPct: rem, + createdAtMs, + lastTouchedMs, + sessionCount: Math.max(1, Number(item.sessionCount) || 1), + }); + } + return out; +} + +function qrSanitizePersistedPendingDrop(raw) { + if (!raw || typeof raw !== 'object') return null; + const preDropUsedPct = Number(raw.preDropUsedPct); + const lowestUsedPct = Number(raw.lowestUsedPct); + const dropPct = Number(raw.dropPct); + const droppedAtMs = Number(raw.droppedAtMs) || 0; + if (!Number.isFinite(preDropUsedPct) || !Number.isFinite(lowestUsedPct) || !Number.isFinite(dropPct) || dropPct <= 0 || droppedAtMs <= 0) { + return null; + } + return { + preDropUsedPct: qrClamp(preDropUsedPct, 0, 100), + preDropCostUsd: Math.max(0, Number(raw.preDropCostUsd) || 0), + dropPct: qrClamp(dropPct, 0, 100), + droppedAtMs, + lowSamples: Math.max(1, Math.floor(Number(raw.lowSamples) || 1)), + lowestUsedPct: qrClamp(lowestUsedPct, 0, 100), + }; +} + +function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { + if (!raw || typeof raw !== 'object') return null; + const lastOfficial = + raw.lastOfficialUsedPct !== undefined && + raw.lastOfficialUsedPct !== null && + Number.isFinite(Number(raw.lastOfficialUsedPct)) + ? qrClamp(Number(raw.lastOfficialUsedPct), 0, 100) + : null; + const rateWindow = + preserveRate && Array.isArray(raw.rateWindow) + ? raw.rateWindow + .map((v) => qrClampRate(Number(v))) + .filter((v) => v !== null) + .slice(-QR_RATE_WINDOW_SIZE) + : []; + const rate = preserveRate + ? rateWindow.length > 0 + ? qrClampRate(qrComputeMedian(rateWindow)) + : raw.ratePctPerUsd !== undefined && raw.ratePctPerUsd !== null + ? qrClampRate(Number(raw.ratePctPerUsd)) + : null + : null; + return { + resetTimeMs: Math.max(0, Number(raw.resetTimeMs) || 0), + lastQuotaTs: Math.max(0, Number(raw.lastQuotaTs) || 0), + lastOfficialUsedPct: lastOfficial, + lastCycleCostUsd: Math.max(0, Number(raw.lastCycleCostUsd) || 0), + lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0), + pendingCostUsd: 0, + pendingCostAtMs: 0, + ratePctPerUsd: rate, + rateSamples: preserveRate ? Math.max(rateWindow.length, Math.floor(Number(raw.rateSamples) || 0)) : 0, + rateWindow, + rateOutlierSide: 0, + rateOutlierBuf: [], + activeLeases: qrSanitizePersistedLeases(raw.activeLeases), + pendingDrop: preserveRate ? qrSanitizePersistedPendingDrop(raw.pendingDrop) : null, + lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0), + lastRefundAtMs: Math.max(0, Number(raw.lastRefundAtMs) || 0), + lastRefundPct: Math.max(0, Number(raw.lastRefundPct) || 0), + }; +} + /** - * 创建独立的配额预占状态追踪器(支持单元测试隔离,同时后端提供全局默认实例)。 + * 创建独立的配额预占状态追踪器(支持可选持久化钩子及单元测试隔离)。 + * + * @param {{ loadState?: () => object|null, saveState?: (payload: object) => void }} [options] */ -export function createQuotaReservationTracker() { +export function createQuotaReservationTracker({ loadState = null, saveState = null } = {}) { const buckets = new Map(); const eventLog = []; + let hydrated = typeof loadState !== 'function'; + let lastPersistMs = 0; - function appendEventLog(entry) { + function ensureHydrated() { + if (hydrated) return; + hydrated = true; + try { + const persisted = loadState?.(); + if (!persisted || typeof persisted !== 'object') return; + const isCurrentSchema = Number(persisted.version) === QR_STATE_SCHEMA_VERSION; + if (persisted.buckets && typeof persisted.buckets === 'object') { + const entries = Object.entries(persisted.buckets).slice(-QR_MAX_TRACKED_BUCKETS); + for (const [k, rawSt] of entries) { + // 从 v1 升级到 v2 时丢弃旧版可能被双副本抖动污染的 EMA 费率,保留历史事件日志 + const clean = qrSanitizePersistedBucket(rawSt, { preserveRate: isCurrentSchema }); + if (k && clean) { + buckets.set(k, clean); + } + } + } + if (Array.isArray(persisted.events)) { + const recent = persisted.events + .filter((e) => e && typeof e === 'object' && typeof e.ts === 'string') + .slice(-QR_MAX_EVENT_LOG); + eventLog.push(...recent); + } + } catch { + // 忽略损坏的持久化状态,自动从空白基线重建 + } + } + + function serializeState(nowMs = Date.now()) { + const serializedBuckets = {}; + for (const [k, st] of buckets.entries()) { + serializedBuckets[k] = { + resetTimeMs: st.resetTimeMs, + lastQuotaTs: st.lastQuotaTs, + lastOfficialUsedPct: st.lastOfficialUsedPct, + lastCycleCostUsd: st.lastCycleCostUsd, + lastUnpricedCalls: st.lastUnpricedCalls, + ratePctPerUsd: st.ratePctPerUsd, + rateSamples: st.rateSamples, + rateWindow: st.rateWindow, + activeLeases: st.activeLeases, + pendingDrop: st.pendingDrop, + lastBounceAtMs: st.lastBounceAtMs, + lastRefundAtMs: st.lastRefundAtMs, + lastRefundPct: st.lastRefundPct, + }; + } + return { + version: QR_STATE_SCHEMA_VERSION, + savedAt: new Date(nowMs).toISOString(), + buckets: serializedBuckets, + events: eventLog.slice(-QR_MAX_EVENT_LOG), + }; + } + + function persistIfNeeded(eventKind, nowMs) { + if (typeof saveState !== 'function') return; + if ( + !eventKind || + eventKind === 'idle' || + eventKind === 'lag_pending' || + eventKind === 'drop_pending' || + eventKind === 'replica_flip' + ) { + return; + } + const isUrgent = + eventKind === 'lease' || + eventKind === 'refund' || + eventKind === 'reset' || + eventKind === 'expire'; + if (!isUrgent && lastPersistMs > 0 && nowMs - lastPersistMs < QR_PERSIST_MIN_INTERVAL_MS) { + return; + } + lastPersistMs = nowMs; + try { + saveState(serializeState(nowMs)); + } catch { + // 持久化失败不影响内存态主流程 + } + } + + function appendEventLog(entry, nowMs) { eventLog.push(entry); if (eventLog.length > QR_MAX_EVENT_LOG) { eventLog.splice(0, eventLog.length - QR_MAX_EVENT_LOG); } + persistIfNeeded(entry.event, nowMs); } function getOrCreateBucket(bucketKey) { @@ -195,10 +414,12 @@ export function createQuotaReservationTracker() { pendingCostAtMs: 0, ratePctPerUsd: null, rateSamples: 0, - lastSettledUsedPct: null, - lastSettledCostUsd: null, - lastSettledAtMs: 0, + rateWindow: [], + rateOutlierSide: 0, + rateOutlierBuf: [], activeLeases: [], + pendingDrop: null, + lastBounceAtMs: 0, lastRefundAtMs: 0, lastRefundPct: 0, }; @@ -223,6 +444,7 @@ export function createQuotaReservationTracker() { if (officialUsedPct === null || !Number.isFinite(officialUsedPct)) { return { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; } + ensureHydrated(); const safeUsed = qrClamp(Number(officialUsedPct), 0, 100); const safeCost = Math.max(0, Number(cycleCostUsd) || 0); const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0); @@ -236,26 +458,29 @@ export function createQuotaReservationTracker() { const st = getOrCreateBucket(bucketKey); const recordLog = (event, fields = {}) => { - appendEventLog({ - ts: new Date(nowMs).toISOString(), - pool: logPool, - win: logWin, - event, - usedPct: +safeUsed.toFixed(3), - dUsed: +(Number(fields.deltaOfficial) || 0).toFixed(3), - costUsd: +safeCost.toFixed(4), - dCost: +(Number(fields.rawDeltaCost) || 0).toFixed(4), - expPct: +(Number(fields.expectedDeltaPct) || 0).toFixed(3), - excessPct: +(Number(fields.excessPct) || 0).toFixed(3), - rate: st.ratePctPerUsd !== null ? +st.ratePctPerUsd.toFixed(4) : null, - rsvPct: Number(fields.reservedPct) || 0, - leases: Number(fields.reservedLeaseCount) || 0, - sess10m: safeSess10m, - cost10m: +safeCost10m.toFixed(4), - }); + appendEventLog( + { + ts: new Date(nowMs).toISOString(), + pool: logPool, + win: logWin, + event, + usedPct: +safeUsed.toFixed(3), + dUsed: +(Number(fields.deltaOfficial) || 0).toFixed(3), + costUsd: +safeCost.toFixed(4), + dCost: +(Number(fields.rawDeltaCost) || 0).toFixed(4), + expPct: +(Number(fields.expectedDeltaPct) || 0).toFixed(3), + excessPct: +(Number(fields.excessPct) || 0).toFixed(3), + rate: st.ratePctPerUsd !== null ? +st.ratePctPerUsd.toFixed(4) : null, + rsvPct: Number(fields.reservedPct) || 0, + leases: Number(fields.reservedLeaseCount) || 0, + sess10m: safeSess10m, + cost10m: +safeCost10m.toFixed(4), + }, + nowMs + ); }; - // 1. 周期重置检测:清空旧租约及待配对成本,保留已校准的单桶费率 + // 1. 周期重置检测:静默忽略 0% 空闲池的滑动重置时间漂移;真正跨周期时清空租约但保留单桶费率 const resetShifted = safeResetMs > 0 && st.resetTimeMs > 0 && @@ -264,23 +489,30 @@ export function createQuotaReservationTracker() { st.lastOfficialUsedPct !== null && st.lastOfficialUsedPct >= 5 && safeUsed < 1; if (resetShifted || rolloverDrop) { const prevUsed = st.lastOfficialUsedPct ?? 0; + const isIdleZeroDrift = + !rolloverDrop && + prevUsed < 0.05 && + safeUsed < 0.05 && + st.activeLeases.length === 0 && + st.pendingDrop === null; st.resetTimeMs = safeResetMs; st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; st.lastUnpricedCalls = safeUnpriced; + if (isIdleZeroDrift) { + return qrFormatOutput(st, safeUsed); + } st.pendingCostUsd = 0; st.pendingCostAtMs = 0; st.activeLeases = []; - st.lastSettledUsedPct = safeUsed; - st.lastSettledCostUsd = safeCost; - st.lastSettledAtMs = nowMs; + st.pendingDrop = null; const out = qrFormatOutput(st, safeUsed); recordLog('reset', { deltaOfficial: safeUsed - prevUsed, ...out }); return out; } - // 2. 首次观测:建立基线并按当前周期已有消耗做低权重冷启动费率估计 + // 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(不入中位数样本池) if (st.lastOfficialUsedPct === null) { st.resetTimeMs = safeResetMs; st.lastQuotaTs = safeFetchTs; @@ -291,9 +523,6 @@ export function createQuotaReservationTracker() { st.ratePctPerUsd = qrClampRate(safeUsed / safeCost); st.rateSamples = 1; } - st.lastSettledUsedPct = safeUsed; - st.lastSettledCostUsd = safeCost; - st.lastSettledAtMs = nowMs; const out = qrFormatOutput(st, safeUsed); recordLog('baseline', out); return out; @@ -308,7 +537,7 @@ export function createQuotaReservationTracker() { safeFetchTs !== st.lastQuotaTs || Math.abs(safeUsed - st.lastOfficialUsedPct) > 1e-4; if (!isFreshSample) { const beforeCachePrune = st.activeLeases.length; - qrPruneExpiredLeases(st, poolLastActivityMs, safeUsed, safeCost, nowMs); + qrPruneExpiredLeases(st, nowMs); const out = qrFormatOutput(st, safeUsed); if (beforeCachePrune > st.activeLeases.length) { recordLog('expire', out); @@ -325,28 +554,136 @@ export function createQuotaReservationTracker() { const rate = qrResolveEffectiveRate(st, safeUsed, safeCost); const expectedDeltaPct = rate !== null ? effectiveDeltaCost * rate : 0; const excessPct = deltaOfficial - expectedDeltaPct; + const isIdleRefundReady = + poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS; let eventKind = 'idle'; - if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) { - // 4A. 同周期余额回升:上游租约到期退还差额(FIFO 核销 + 结算校准) - const refundedPct = -deltaOfficial; - qrConsumeLeasesFifo(st.activeLeases, refundedPct); + const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => { + const amt = Math.max(0, Number(refundedPct) || 0); + if (amt > 0) { + qrConsumeLeasesFifo(st.activeLeases, amt); + } st.lastRefundAtMs = nowMs; - st.lastRefundPct = refundedPct; - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; + st.lastRefundPct = amt; + st.lastBounceAtMs = nowMs; + st.pendingDrop = null; + if (!keepPendingCost) { + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + } if (qrSumLeases(st.activeLeases) < QR_MIN_DISPLAY_RESERVED_PCT) { st.activeLeases = []; - qrCalibrateFromSettled(st, safeUsed, safeCost, nowMs); } eventKind = 'refund'; + }; + + if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) { + // 4A. 同周期余额回升:区分「静默到期真退还」及「活跃期双副本回落待确认」 + const prevHigh = st.pendingDrop + ? Math.max(st.pendingDrop.preDropUsedPct, st.lastOfficialUsedPct) + : st.lastOfficialUsedPct; + const totalDrop = Math.max(0, prevHigh - safeUsed); + st.lastBounceAtMs = nowMs; + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + + if (isIdleRefundReady && st.activeLeases.length > 0) { + confirmRefund(totalDrop); + } else if (st.pendingDrop) { + st.pendingDrop.preDropUsedPct = prevHigh; + st.pendingDrop.lowestUsedPct = Math.min(st.pendingDrop.lowestUsedPct, safeUsed); + st.pendingDrop.dropPct = Math.max(0, prevHigh - st.pendingDrop.lowestUsedPct); + st.pendingDrop.lowSamples += 1; + if ( + st.pendingDrop.lowSamples >= QR_REFUND_CONFIRM_MIN_SAMPLES && + nowMs - st.pendingDrop.droppedAtMs >= QR_REFUND_CONFIRM_WINDOW_MS + ) { + confirmRefund(st.pendingDrop.dropPct); + } else { + eventKind = 'drop_pending'; + } + } else { + st.pendingDrop = { + preDropUsedPct: st.lastOfficialUsedPct, + preDropCostUsd: st.lastCycleCostUsd, + dropPct: -deltaOfficial, + droppedAtMs: nowMs, + lowSamples: 1, + lowestUsedPct: safeUsed, + }; + eventKind = 'drop_pending'; + } + } else if (st.pendingDrop) { + // 4B-Pending. 当前处于回落观察窗内:判断是「弹回高副本」还是「持续低位确认退还」 + const pd = st.pendingDrop; + const costSinceDrop = Math.max(0, safeCost - pd.preDropCostUsd); + const expectedSinceDrop = rate !== null ? costSinceDrop * rate : 0; + const expectedOnTick = rate !== null ? rawDeltaCost * rate : 0; + const jumpAboveTickSpend = deltaOfficial - expectedOnTick; + const reboundFloor = pd.preDropUsedPct - Math.min(0.15, pd.dropPct * 0.35); + const isReplicaRebound = + deltaOfficial > 1e-3 && + jumpAboveTickSpend >= Math.max(QR_REFUND_EPSILON_PCT, pd.dropPct * 0.45) && + safeUsed >= reboundFloor; + + if (isReplicaRebound) { + const excessAboveHighWater = safeUsed - (pd.preDropUsedPct + expectedSinceDrop); + st.pendingDrop = null; + st.lastBounceAtMs = nowMs; + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + if (rate !== null && excessAboveHighWater >= QR_MIN_JUMP_EXCESS_PCT) { + st.activeLeases.push({ + amountPct: excessAboveHighWater, + remainingPct: excessAboveHighWater, + createdAtMs: nowMs, + lastTouchedMs: nowMs, + sessionCount: Math.max(1, safeSess10m || 1), + }); + if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) { + st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); + } + eventKind = 'lease'; + } else { + eventKind = 'replica_flip'; + } + } else { + pd.lowSamples += 1; + const sustainedLow = + isIdleRefundReady || + (pd.lowSamples >= QR_REFUND_CONFIRM_MIN_SAMPLES && + nowMs - pd.droppedAtMs >= QR_REFUND_CONFIRM_WINDOW_MS); + if (sustainedLow) { + if (rawDeltaCost > 0 && deltaOfficial <= 1e-3) { + st.pendingCostUsd = effectiveDeltaCost; + st.pendingCostAtMs = nowMs; + } + const effectiveDrop = Math.max(0, pd.preDropUsedPct + expectedSinceDrop - safeUsed); + confirmRefund(effectiveDrop > 0 ? Math.min(pd.dropPct, effectiveDrop) : pd.dropPct, { + keepPendingCost: deltaOfficial <= 1e-3 && st.pendingCostUsd > 0, + }); + } else if (deltaOfficial > 1e-3) { + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + eventKind = 'drop_pending'; + } else if (rawDeltaCost > 0) { + st.pendingCostUsd = effectiveDeltaCost; + st.pendingCostAtMs = nowMs; + eventKind = 'lag_pending'; + } + } } else if (deltaOfficial > 1e-3) { - // 4B. 官方已用比例上升:区分租约跳变及常规消耗 + // 4B. 官方已用比例上升:区分租约跳变、真实租约内消费及常规消耗 const detectedWithRate = rate !== null && excessPct >= QR_MIN_JUMP_EXCESS_PCT; const detectedColdStart = rate === null && deltaOfficial >= QR_COLD_START_JUMP_PCT && effectiveDeltaCost <= QR_COLD_START_MAX_COST_USD; + const shortfall = expectedDeltaPct - deltaOfficial; + const isSignificantShortfall = + st.activeLeases.length > 0 && + expectedDeltaPct > 0 && + shortfall >= Math.max(QR_CONSUME_MIN_SHORTFALL_PCT, expectedDeltaPct * QR_CONSUME_SHORTFALL_RATIO); if (detectedWithRate || detectedColdStart) { const leaseRemaining = detectedWithRate ? excessPct : deltaOfficial; @@ -361,26 +698,27 @@ export function createQuotaReservationTracker() { st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); } eventKind = 'lease'; - } else if (st.activeLeases.length > 0 && expectedDeltaPct > deltaOfficial) { - // 租约期内同时出现官方微增及本地消耗:超出官方增量的消耗计入当前租约内消费 - const shortfall = expectedDeltaPct - deltaOfficial; + } else if (isSignificantShortfall) { + // 租约期内出现明显低于预期的官方增量:仅把显著缺口计入当前租约内消费 qrConsumeLeasesFifo(st.activeLeases, shortfall); for (let i = 0; i < st.activeLeases.length; i += 1) { st.activeLeases[i].lastTouchedMs = nowMs; } eventKind = 'consume'; } else { + const outsideBounceCooldown = + st.lastBounceAtMs === 0 || nowMs - st.lastBounceAtMs >= QR_RATE_BOUNCE_COOLDOWN_MS; if ( st.activeLeases.length === 0 && - effectiveDeltaCost >= 0.05 && + outsideBounceCooldown && + !pendingValid && + rawDeltaCost >= 0.04 && deltaUnpriced === 0 && - deltaOfficial < QR_COLD_START_JUMP_PCT + deltaOfficial > 0.005 && + deltaOfficial < QR_MIN_JUMP_EXCESS_PCT ) { - // 纯净未租约消耗:平稳校准该桶 $/1% 换算率 - qrUpdateRateEma(st, deltaOfficial / effectiveDeltaCost); - st.lastSettledUsedPct = safeUsed; - st.lastSettledCostUsd = safeCost; - st.lastSettledAtMs = nowMs; + // 纯净未租约且无近期副本抖动的单步消耗:进入滚动中位数费率校准池 + qrRecordRateSample(st, deltaOfficial / rawDeltaCost); } eventKind = 'normal'; } @@ -413,9 +751,9 @@ export function createQuotaReservationTracker() { st.lastCycleCostUsd = safeCost; st.lastUnpricedCalls = safeUnpriced; - // 5. 租约 TTL 超时兜底(静默超过 11.5 分钟仍未退还,说明租约已在窗内耗尽) + // 5. 租约 TTL 超时兜底(租约本身超过 11.5 分钟无实质扣减或满 22 分钟自动清理) const beforePrune = st.activeLeases.length; - qrPruneExpiredLeases(st, poolLastActivityMs, safeUsed, safeCost, nowMs); + qrPruneExpiredLeases(st, nowMs); if (beforePrune > st.activeLeases.length && eventKind === 'idle') { eventKind = 'expire'; } @@ -500,6 +838,7 @@ export function createQuotaReservationTracker() { } function getLogSnapshot() { + ensureHydrated(); const bucketSummaries = []; for (const [key, st] of buckets.entries()) { const parts = key.split('::'); @@ -528,6 +867,8 @@ export function createQuotaReservationTracker() { function reset() { buckets.clear(); eventLog.length = 0; + lastPersistMs = 0; + hydrated = true; } return { @@ -539,7 +880,23 @@ export function createQuotaReservationTracker() { }; } -const defaultQuotaReservationTracker = createQuotaReservationTracker(); +function qrIsTestRuntime() { + return ( + lsRuntimeEndpoint?.addr === 'test.invalid' || + String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid' + ); +} + +const defaultQuotaReservationTracker = createQuotaReservationTracker({ + loadState: () => { + if (qrIsTestRuntime()) return null; + return loadJson(QUOTA_RESERVATION_STATE_FILE, null); + }, + saveState: (payload) => { + if (qrIsTestRuntime()) return; + saveJson(QUOTA_RESERVATION_STATE_FILE, payload); + }, +}); /** * 使用全局默认追踪器为 `quotaPoolsMap` 中的所有配额池刷新 5h 及周限的实验性预占估算字段。 diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 6a4309c..b1ab10d 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -1713,13 +1713,39 @@ export async function buildTelemetryPayloadInternal( const realAiCredits = Number(g1CreditEntry?.creditAmount || 0); const uiBundleVersion = computeRuntimeCodeVersion(); - const rawTierName = userStatus?.userTier?.name || ''; - const inferredPlanFallback = /\bfree\b/i.test(rawTierName) + const rawTierId = String(userStatus?.userTier?.id || '').trim(); + const rawTierName = String(userStatus?.userTier?.name || '').trim(); + const rawTierDesc = String(userStatus?.userTier?.description || '').trim(); + const rawPlanName = String(userStatus?.planStatus?.planInfo?.planName || '').trim(); + const tierIdLower = rawTierId.toLowerCase(); + const tierText = `${rawTierId} ${rawTierName} ${rawTierDesc}`; + const resolvedTierMultiplier = /(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(tierText) + ? '5x' + : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(tierText) || + tierIdLower === 'g1-ultra-tier' || + (/^g1-ultra(?:-[a-z0-9]+)?-tier$/i.test(tierIdLower) && !/lite|5x/i.test(tierIdLower)) + ? '20x' + : ''; + const resolvedTierName = + rawTierName || + (/ultra/i.test(tierIdLower) + ? 'Google AI Ultra' + : /pro/i.test(tierIdLower) + ? 'Google AI Pro' + : /free|standard/i.test(tierIdLower) + ? 'Google AI Free' + : 'Google AI'); + const isUltraTier = /\bultra\b/i.test(resolvedTierName) || /ultra/i.test(tierIdLower); + const inferredPlanFallback = /\bfree\b/i.test(resolvedTierName) ? 'Free' - : /\bultra\b/i.test(rawTierName) - ? 'Ultra' + : isUltraTier + ? resolvedTierMultiplier || 'Ultra' : 'Pro'; - const resolvedPlanName = userStatus?.planStatus?.planInfo?.planName || inferredPlanFallback; + // Google 上游对 Ultra 订阅的 planStatus.planInfo.planName 仍会返回 "Pro",按 userTier.id 还原 5x / 20x + const resolvedPlanName = isUltraTier + ? resolvedTierMultiplier || + (rawPlanName && !/^pro$/i.test(rawPlanName) ? rawPlanName : 'Ultra') + : rawPlanName || inferredPlanFallback; // 预计算近期会话与运行中会话的轻量缓存速览指标(零额外 RPC 开销) const quickStatsMemo = new Map(); @@ -2100,7 +2126,9 @@ export async function buildTelemetryPayloadInternal( status: accountStatus, email: userStatus?.email || '', name: userStatus?.name || '', - tierName: rawTierName || 'Google AI', + tierId: rawTierId, + tierName: resolvedTierName, + tierMultiplier: resolvedTierMultiplier, planName: resolvedPlanName, aiCredits: realAiCredits > 0 ? realAiCredits : null, totalConversations: conversations.length, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 098b898..124feb7 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 a8d8a18..889a52e 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -28,6 +28,7 @@ export const TOPBAR_SLOT_KEYS = Object.freeze([ 'quota_auto', 'gemini_5h', 'gemini_weekly', + 'argon_weekly', 'claude_5h', 'claude_weekly', ]); diff --git a/sidecars/panel/shared/telemetry-display-rules.mjs b/sidecars/panel/shared/telemetry-display-rules.mjs index cf6aa7d..75e3892 100644 --- a/sidecars/panel/shared/telemetry-display-rules.mjs +++ b/sidecars/panel/shared/telemetry-display-rules.mjs @@ -96,8 +96,40 @@ export function formatCompactCapsuleTtft(ttftSec) { return `${Math.round(val)}s`; } +function readPoolWeeklyRemainingPct(pool) { + if (!pool || typeof pool !== 'object') return null; + const raw = pool.weeklyRemainingPct ?? pool.remainingWeeklyPct; + return raw != null && Number.isFinite(Number(raw)) ? Number(raw) : null; +} + +function isArgonPoolObject(pool) { + if (!pool || typeof pool !== 'object') return false; + if (pool.poolKey === 'Argon' || pool.family === 'Argon') return true; + return /\bargon\b/i.test(String(pool.poolKey || pool.poolLabel || pool.family || '')); +} + /** - * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 + * 判断当前配额摘要中是否存在独立的 Argon 周限配额池(如 Google AI Pro 账号)。 + * + * @param {object|null|undefined} quotas + * @returns {boolean} + */ +export function hasArgonWeeklyQuotaPool(quotas) { + if (!quotas || typeof quotas !== 'object') return false; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const argonPool = pools.find(isArgonPoolObject); + if (argonPool && readPoolWeeklyRemainingPct(argonPool) != null) { + return true; + } + const activePool = quotas.activePool; + if (activePool && isArgonPoolObject(activePool) && readPoolWeeklyRemainingPct(activePool) != null) { + return true; + } + return false; +} + +/** + * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `argon_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 * * @param {object|null|undefined} quotas * @param {string} slotKey @@ -114,8 +146,9 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (activePool && Number.isFinite(Number(activePool.remainingPct))) { candidates.push(Number(activePool.remainingPct)); } - if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { - candidates.push(Number(activePool.weeklyRemainingPct)); + const activeWk = readPoolWeeklyRemainingPct(activePool); + if (activeWk != null) { + candidates.push(activeWk); } if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { candidates.push(Number(weekly.remainingPct)); @@ -123,15 +156,24 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (!candidates.length && pools.length > 0) { for (const p of pools) { if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); - if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { - candidates.push(Number(p.weeklyRemainingPct)); - } + const pWk = readPoolWeeklyRemainingPct(p); + if (pWk != null) candidates.push(pWk); } } if (!candidates.length) return null; return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); } + if (slotKey === 'argon_weekly') { + const argonPool = pools.find(isArgonPoolObject); + let argonPct = readPoolWeeklyRemainingPct(argonPool); + if (argonPct == null && isArgonPoolObject(activePool)) { + argonPct = readPoolWeeklyRemainingPct(activePool); + } + if (argonPct == null || !Number.isFinite(argonPct)) return null; + return Math.max(0, Math.min(100, Math.round(argonPct))); + } + const isClaude = slotKey.startsWith('claude_'); const isWeekly = slotKey.endsWith('_weekly'); let rawPct = null; @@ -140,11 +182,11 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const claudePool = pools.find((p) => p?.poolKey === 'Claude & GPT') || pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + const cand = isWeekly ? readPoolWeeklyRemainingPct(claudePool) : claudePool?.remainingPct; if (cand != null && Number.isFinite(Number(cand))) { rawPct = Number(cand); } else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } } else { @@ -158,12 +200,12 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const geminiFamilyPools = pools.filter((p) => /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + const primaryCand = isWeekly ? readPoolWeeklyRemainingPct(stdGemini) : stdGemini?.remainingPct; if (primaryCand != null && Number.isFinite(Number(primaryCand))) { rawPct = Number(primaryCand); } else { const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .map((p) => (isWeekly ? readPoolWeeklyRemainingPct(p) : p?.remainingPct)) .filter((v) => v != null && Number.isFinite(Number(v))) .map(Number); if (familyVals.length > 0) { @@ -172,7 +214,7 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { activePool && !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } if ( diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 232ec07..1af6fa6 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -1311,16 +1311,15 @@ export function createSessionLineChart() { patchStyleVar(mLine, '--sstep-fit-accent', seriesColor); multiLineGroup.appendChild(mLine); - if (seriesPts.length <= 36) { - for (const pt of seriesPts) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - dot.setAttribute('r', seriesPts.length > 20 ? '1.7' : '2.1'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar(dot, '--dot-stroke', seriesColor); - dotsGroup.appendChild(dot); - } + if (seriesPts.length === 1) { + const pt = seriesPts[0]; + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', pt.x.toFixed(1)); + dot.setAttribute('cy', pt.y.toFixed(1)); + dot.setAttribute('r', '2.1'); + dot.setAttribute('class', 'sstep-node-dot'); + patchStyleVar(dot, '--dot-stroke', seriesColor); + dotsGroup.appendChild(dot); } } } @@ -1344,40 +1343,30 @@ export function createSessionLineChart() { patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`); } - - if (points.length <= 64) { - for (const pt of points) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - if (pt.valid) { - dot.setAttribute('r', points.length > 36 ? '1.8' : '2.3'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar( - dot, - '--dot-stroke', - modelColorMap.size > 1 ? pt.dotColor : accentColor - ); - } else { - dot.setAttribute('r', '1.6'); - dot.setAttribute('class', 'sstep-node-dot is-skipped'); - } - dotsGroup.appendChild(dot); - } - } } + const anomalyTicks = []; for (const pt of points) { if (!pt.valid || !pt.anomalySummary) continue; - const aDot = document.createElementNS(SVG_NS, 'circle'); - aDot.setAttribute('cx', pt.x.toFixed(1)); - aDot.setAttribute('cy', pt.y.toFixed(1)); - aDot.setAttribute('r', '2.9'); - aDot.setAttribute( + anomalyTicks.push(pt); + } + anomalyTicks.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); + const tickTopY = (BOTTOM_Y - 5).toFixed(1); + const tickBotY = BOTTOM_Y.toFixed(1); + for (const pt of anomalyTicks) { + const xStr = pt.x.toFixed(1); + const aTick = document.createElementNS(SVG_NS, 'line'); + aTick.setAttribute('x1', xStr); + aTick.setAttribute('x2', xStr); + aTick.setAttribute('y1', tickTopY); + aTick.setAttribute('y2', tickBotY); + aTick.setAttribute( 'class', - `sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` + `sstep-anomaly-dot sstep-anomaly-tick${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` ); - anomalyDotsGroup.appendChild(aDot); + anomalyDotsGroup.appendChild(aTick); } const tickIndices = computeStepTickIndices(points.length); @@ -2288,11 +2277,14 @@ export function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + anomalyOverlayDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const sp of anomalyOverlayDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', sp.x.toFixed(1)); aDot.setAttribute('cy', sp.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}` @@ -2462,11 +2454,14 @@ export function createModelFitChart() { dot.setAttribute('class', 'sstep-scatter-dot'); scatterTarget.appendChild(dot); } + singleAnomalyDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const s of singleAnomalyDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', s.x.toFixed(1)); aDot.setAttribute('cy', s.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}` diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 8c4f461..321d99b 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -281,16 +281,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); - const dotsGroup = document.createElementNS(SVG_NS, 'g'); - dotsGroup.setAttribute('class', 'trend-dots-group'); - svg.appendChild(dotsGroup); - - const peakDot = document.createElementNS(SVG_NS, 'circle'); - peakDot.setAttribute('r', '3'); - peakDot.setAttribute('class', 'trend-peak-dot'); - svg.appendChild(peakDot); - - // 悬停十字准星与焦点圆点 + // 悬停十字准星及焦点圆点 const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '12'); @@ -1129,25 +1120,9 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } - - // 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期) - while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); - if (pts.length <= 36) { - for (let i = 0; i < pts.length; i++) { - if (pts[i].tokens <= 0) continue; - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pts[i].x.toFixed(1)); - dot.setAttribute('cy', pts[i].y.toFixed(1)); - dot.setAttribute('r', '2'); - dot.setAttribute('class', 'trend-node-dot'); - dotsGroup.appendChild(dot); - } - } } const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; - patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); - patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); const peakSlot = slots[peakIdx]; const peakText = diff --git a/sidecars/panel/src/components/settings/structurePreviewMock.js b/sidecars/panel/src/components/settings/structurePreviewMock.js index 103f63d..e3b6708 100644 --- a/sidecars/panel/src/components/settings/structurePreviewMock.js +++ b/sidecars/panel/src/components/settings/structurePreviewMock.js @@ -7,7 +7,11 @@ import { t } from '../../i18n/index.js'; -export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) { +export function buildStructurePreviewTelemetry( + baseSettings = {}, + draftOverrides = {}, + { includeArgonPool = false } = {} +) { const anchorMinMs = Math.floor(Date.now() / 60000) * 60000; const reset5hIso = new Date(anchorMinMs + (2 * 60 + 42) * 60000).toISOString(); const resetWkIso = new Date(anchorMinMs + (4 * 24 * 60 + 180) * 60000).toISOString(); @@ -361,8 +365,10 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides return { settings: mergedSettings, account: { + tierId: 'g1-ultra-lite-tier', tierName: 'Google AI Ultra', - planName: 'Pro', + tierMultiplier: '5x', + planName: '5x', aiCredits: 0, }, quotas: { @@ -400,6 +406,21 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 }, cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 }, }, + ...(includeArgonPool + ? [ + { + poolKey: 'Argon', + poolLabel: 'Gemini 4 Argon', + family: 'Argon', + has5h: false, + hasWeekly: true, + weeklyUsedPct: 58, + weeklyRemainingPct: 42, + weeklyResetTime: resetWkIso, + cycleWeekly: { tokens: 4200000, costUsd: 6.4, calls: 48 }, + }, + ] + : []), { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index e40bee3..d9312e3 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -210,7 +210,7 @@ function syncQuotaWindowMeter({ const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); patchStyleVar(fillEl, '--fill-w', `${actualWidth}%`); patchStyleVar(fillReservedEl, '--reserved-w', `${rsvWidth}%`); - patchClasses(fillReservedEl, { 'is-active': true }); + patchClasses(fillReservedEl, { 'is-active': true, 'has-sep': actualWidth > 0 }); } else { patchText( metaBeforeEl, @@ -230,7 +230,7 @@ function syncQuotaWindowMeter({ patchAttr(trackEl, 'title', null); patchStyleVar(fillEl, '--fill-w', `${Math.min(100, usedVal)}%`); patchStyleVar(fillReservedEl, '--reserved-w', '0%'); - patchClasses(fillReservedEl, { 'is-active': false }); + patchClasses(fillReservedEl, { 'is-active': false, 'has-sep': false }); } patchClasses(fillEl, { @@ -370,6 +370,45 @@ export function quotaPoolRowSig(item, idx) { return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } +/** + * 格式化可用额度面板右上角的账号订阅徽章(区分 Ultra 5x / 20x,并对 Pro / Free 去重)。 + * + * @param {object|null|undefined} account + * @returns {string} + */ +export function formatAccountTierBadge(account) { + const tierName = String(account?.tierName || '').trim() || 'Google AI'; + const tierId = String(account?.tierId || '').trim().toLowerCase(); + const explicitMult = String(account?.tierMultiplier || '').trim(); + const inferredMult = + explicitMult || + (/(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(`${tierId} ${tierName}`) + ? '5x' + : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(`${tierId} ${tierName}`) || tierId === 'g1-ultra-tier' + ? '20x' + : ''); + const rawPlan = String(account?.planName || '').trim(); + const isUltra = /\bultra\b/i.test(tierName) || /ultra/i.test(tierId); + + if (isUltra) { + if (inferredMult) { + const hasMultInTier = new RegExp(`(?:^|\\s|·)${inferredMult}(?:$|\\s)`, 'i').test(tierName); + return hasMultInTier ? tierName : `${tierName} · ${inferredMult}`; + } + if (rawPlan && !/^(?:pro|ultra)$/i.test(rawPlan)) { + return `${tierName} · ${rawPlan}`; + } + return tierName; + } + + if (!rawPlan) return tierName; + const escapedPlan = rawPlan.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + if (new RegExp(`(?:^|\\s|·)${escapedPlan}(?:$|\\s)`, 'i').test(tierName)) { + return tierName; + } + return `${tierName} · ${rawPlan}`; +} + export const QuotaPoolsWidget = defineComponent({ name: 'QuotaPoolsWidget', setup({ props }) { @@ -392,6 +431,23 @@ export const QuotaPoolsWidget = defineComponent({ }); } + const legendActualTextEl = h('span', { text: t('quota.legendActual') }); + const legendReservedTextEl = h('span', { text: t('quota.legendReserved') }); + const reserveLegendEl = h( + 'div', + { className: 'quota-reserve-legend', hidden: true }, + [ + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-actual', 'aria-hidden': 'true' }), + legendActualTextEl, + ]), + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-reserved', 'aria-hidden': 'true' }), + legendReservedTextEl, + ]), + ] + ); + const quotaPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -401,11 +457,15 @@ export const QuotaPoolsWidget = defineComponent({ tierBadge, ]), poolsListEl, + reserveLegendEl, ]); function update({ data, minuteTick } = {}) { patchText(titleTextEl, t('module.quotas')); + patchText(legendActualTextEl, t('quota.legendActual')); + patchText(legendReservedTextEl, t('quota.legendReserved')); if (!data) { + reserveLegendEl.hidden = true; if (compactHover) { patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), { keyFn: (item) => item.key, @@ -419,11 +479,9 @@ export const QuotaPoolsWidget = defineComponent({ const quotas = data.quotas || {}; const showReserved = data.settings?.experimentalQuotaReservation === true; + reserveLegendEl.hidden = !showReserved; const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000); - patchText( - tierBadge, - `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` - ); + patchText(tierBadge, formatAccountTierBadge(data.account)); patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick, { showReserved }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index e82e194..2cbf819 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -125,6 +125,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'capMetric.quota_auto': 'Auto Tightest Quota', 'capMetric.gemini_5h': 'Gemini 5h Quota', 'capMetric.gemini_weekly': 'Gemini Weekly Quota', + 'capMetric.argon_weekly': 'Argon Weekly Quota', 'capMetric.claude_5h': 'Claude 5h Quota', 'capMetric.claude_weekly': 'Claude Weekly Quota', @@ -187,6 +188,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.usedAfterReserved': ' · {rem}% left)', 'quota.reservedTip': 'Estimated lease reservation (Experimental): ~{rsv}% (~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.reservedTipMulti': 'Estimated lease reservation (Experimental): ~{rsv}% ({leases} stacked leases, ~{actual}% actual used); unused share refunds after ~10 min idle', + 'quota.legendActual': 'Actual', + 'quota.legendReserved': 'Reserved', 'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', @@ -691,7 +694,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.quotaReserveLabel': 'Quota Reservation Estimate', 'settings.oth.quotaReserveDesc': 'Estimate 0.5% / 1% 5h & weekly lease holds in Available Quotas and highlight the reserved share in violet', 'settings.oth.quotaReserveLogLabel': 'Reservation Observation Log', - 'settings.oth.quotaReserveLogDesc': 'Copy in-memory quota jump & refund events to clipboard for threshold tuning', + 'settings.oth.quotaReserveLogDesc': 'Copy persisted quota jump & refund observations to clipboard (retained across restarts)', 'settings.oth.exportReserveLogBtn': 'Export Reserve Log', 'settings.oth.exportReserveLogCopied': 'Copied {count} log entries to clipboard', 'settings.oth.exportReserveLogEmpty': 'No events yet; copied current summary to clipboard', @@ -731,7 +734,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', 'settings.oth.backupLabel': 'Preferences Backup & Restore', - 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON (excludes credentials)', + 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON', 'settings.oth.exportJsonBtn': 'Export JSON', 'settings.oth.importJsonBtn': 'Import JSON', 'settings.oth.exportDone': 'Preferences JSON exported', @@ -745,7 +748,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.migModeLabel': 'Migration Mode', 'settings.oth.migModeMove': 'Full Move (Recommended)', 'settings.oth.migModeClone': 'Clone Copy', - 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving (close source session first)', + 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving', 'settings.oth.migModeCloneHint': 'Keeps source intact with a fresh UUID; only counts new steps generated after cloning', 'settings.oth.migProjectLabel': 'Target Project', 'settings.oth.migProjectOutside': 'Standalone (No Project)', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 5dd98c3..eb000cd 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -125,6 +125,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'capMetric.quota_auto': '自动紧俏额度', 'capMetric.gemini_5h': 'Gemini 5h 额度', 'capMetric.gemini_weekly': 'Gemini 周额度', + 'capMetric.argon_weekly': 'Argon 周额度', 'capMetric.claude_5h': 'Claude 5h 额度', 'capMetric.claude_weekly': 'Claude 周额度', @@ -187,6 +188,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.usedAfterReserved': ' · 余 {rem}%)', 'quota.reservedTip': '预占估算(试验性):约 {rsv}%(实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.reservedTipMulti': '预占估算(试验性):约 {rsv}%(检测到 {leases} 笔叠加租约,实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', + 'quota.legendActual': '实占', + 'quota.legendReserved': '预占', 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', @@ -691,7 +694,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.quotaReserveLabel': '配额预占估算', 'settings.oth.quotaReserveDesc': '在可用额度中估算 5h / 周限的 0.5% / 1% 租约预占,并用紫色标注占比及进度条段', 'settings.oth.quotaReserveLogLabel': '预占观测日志', - 'settings.oth.quotaReserveLogDesc': '将内存中的配额跳变及退还记录复制到剪贴板,便于分析触发阈值', + 'settings.oth.quotaReserveLogDesc': '将配额跳变及退还观测记录复制到剪贴板,重启后自动保留,便于分析触发阈值', 'settings.oth.exportReserveLogBtn': '导出预占日志', 'settings.oth.exportReserveLogCopied': '已复制 {count} 条观测日志到剪贴板', 'settings.oth.exportReserveLogEmpty': '暂无跳变记录,已复制当前摘要到剪贴板', @@ -731,7 +734,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', 'settings.oth.backupLabel': '配置备份及恢复', - 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON(不含账号凭证)', + 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON', 'settings.oth.exportJsonBtn': '导出 JSON', 'settings.oth.importJsonBtn': '导入 JSON', 'settings.oth.exportDone': '配置 JSON 已导出', @@ -745,7 +748,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.migModeLabel': '迁移方式', 'settings.oth.migModeMove': '完整迁移(推荐)', 'settings.oth.migModeClone': '克隆副本', - 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端(零重复计费;迁移前建议先关闭源端该会话)', + 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端', 'settings.oth.migModeCloneHint': '保留源会话并生成新 ID,新副本仅统计迁入后的新步骤', 'settings.oth.migProjectLabel': '绑定目标项目', 'settings.oth.migProjectOutside': '独立会话(无所属项目)', diff --git a/sidecars/panel/src/registries/metricRegistry.js b/sidecars/panel/src/registries/metricRegistry.js index 10a7f4c..26e44fc 100644 --- a/sidecars/panel/src/registries/metricRegistry.js +++ b/sidecars/panel/src/registries/metricRegistry.js @@ -24,17 +24,28 @@ import { OVERVIEW_METRIC_KEYS, TOPBAR_SLOT_KEYS } from '../../shared/settings-no import { formatCompactCapsuleCost, formatCompactCapsuleTtft, + hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, } from '../../shared/telemetry-display-rules.mjs'; -export { OVERVIEW_METRIC_KEYS, formatCompactCapsuleCost, formatCompactCapsuleTtft }; +export { + OVERVIEW_METRIC_KEYS, + formatCompactCapsuleCost, + formatCompactCapsuleTtft, + hasArgonWeeklyQuotaPool, +}; export const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS; -export function getCapsuleMetricOptions() { - return CAPSULE_METRIC_KEYS.map((key) => ({ - value: key, - label: t(`capMetric.${key}`), - })); +export function getCapsuleMetricOptions({ quotas = null, selectedSlots = [] } = {}) { + const showArgonWeekly = + hasArgonWeeklyQuotaPool(quotas) || + (Array.isArray(selectedSlots) && selectedSlots.includes('argon_weekly')); + return CAPSULE_METRIC_KEYS.filter((key) => key !== 'argon_weekly' || showArgonWeekly).map( + (key) => ({ + value: key, + label: t(`capMetric.${key}`), + }) + ); } export function getOverviewMetricOptions() { @@ -97,17 +108,21 @@ export function resolveQuotaCapsuleSummary(quotas) { : `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} · ${tightest.windowTag}`; const tightestIsClaude = /claude|gpt|fable|oss|third/i.test(String(tightest.label || '')); - const tightestIsGemini = !tightestIsClaude && /gemini|argon|carbon|neon|flash|pro/i.test(String(tightest.label || '')); + const tightestIsArgon = !tightestIsClaude && /\bargon\b/i.test(String(tightest.label || '')); + const tightestIsGemini = + !tightestIsClaude && !tightestIsArgon && /gemini|carbon|neon|flash|pro/i.test(String(tightest.label || '')); const tightestWinShort = tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'w' : '周'; const poolPrefix = tightestIsClaude ? `C${tightestWinShort}` - : tightestIsGemini - ? `G${tightestWinShort}` - : tightest.windowTag === '5h' - ? '5h' - : isEnglishLocale() - ? 'Wk' - : '周'; + : tightestIsArgon + ? `A${tightestWinShort}` + : tightestIsGemini + ? `G${tightestWinShort}` + : tightest.windowTag === '5h' + ? '5h' + : isEnglishLocale() + ? 'Wk' + : '周'; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), @@ -126,6 +141,7 @@ function resolveQuotaCapsulePrefix(metricKey, quotaSum) { const isEn = isEnglishLocale(); if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; + if (metricKey === 'argon_weekly') return isEn ? 'Aw' : 'A周'; if (metricKey === 'claude_5h') return 'C5h'; if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; if (quotaSum?.poolPrefix) return quotaSum.poolPrefix; @@ -346,6 +362,22 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf }; } + if (metricKey === 'argon_weekly' && slotCtx.hasTelemetry && !hasArgonWeeklyQuotaPool(slotCtx.quotas)) { + return { + hidden: true, + metric: 'none', + segClass: 'wm-cap-slot', + textClass: 'wm-slot-text', + showRing: false, + dashOffset: ringCircumference, + text: '', + toneClass: '', + running: false, + warn: false, + danger: false, + }; + } + const quotaSum = !slotCtx.hasTelemetry ? null : metricKey === 'quota_auto' diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 2eb3b01..1ff307d 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1038,7 +1038,9 @@ export function isEquivalentTelemetry(prev, next) { prev.account?.email !== next.account?.email || prev.account?.name !== next.account?.name || prev.account?.status !== next.account?.status || + prev.account?.tierId !== next.account?.tierId || prev.account?.tierName !== next.account?.tierName || + prev.account?.tierMultiplier !== next.account?.tierMultiplier || prev.account?.planName !== next.account?.planName || prev.account?.aiCredits !== next.account?.aiCredits ) { diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 20fbb75..db52cad 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -628,11 +628,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { margin: 4px 2px 2px; } -[data-modern-ui="true"] .sstep-anomaly-dot, -[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly { - fill: var(--modern-surface-card); -} - /* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ [data-modern-ui="true"] .collapsible-body, [data-modern-ui="true"] .settings-action-block + .settings-action-block, diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 6ab2c6e..1de48f3 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -580,13 +580,23 @@ .progress-fill-reserved { height: 100%; width: var(--reserved-w, 0%); - background: var(--quota-reserved); - transition: width var(--dur-normal) var(--ease-fast); + background: repeating-linear-gradient( + -45deg, + color-mix(in srgb, var(--quota-reserved) 72%, transparent) 0 2px, + color-mix(in srgb, var(--quota-reserved) 26%, transparent) 2px 5px + ); + transition: + width var(--dur-normal) var(--ease-fast), + margin-left var(--dur-fast) var(--ease-fast); flex-shrink: 0; } .progress-fill-reserved.is-active { - min-width: 3px; + min-width: 5px; +} + +.progress-fill-reserved.is-active.has-sep { + margin-left: 1px; } .quota-reserved-pct { @@ -594,6 +604,47 @@ font-weight: 500; } +.quota-reserve-legend { + display: flex; + align-items: center; + gap: 12px; + margin-top: 2px; + padding-top: 2px; + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.quota-reserve-legend[hidden] { + display: none; +} + +.quota-legend-item { + display: inline-flex; + align-items: center; + gap: 5px; + white-space: nowrap; +} + +.quota-legend-line { + display: inline-block; + width: 14px; + height: 2px; + border-radius: 1px; + flex-shrink: 0; +} + +.quota-legend-line.is-actual { + background: var(--accent-primary); +} + +.quota-legend-line.is-reserved { + background: repeating-linear-gradient( + 90deg, + var(--quota-reserved) 0 4px, + transparent 4px 6.5px + ); +} + /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 4c90ee6..54bf4ef 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -896,18 +896,29 @@ stroke: var(--metric-danger); } -.sstep-anomaly-dot, -.sstep-scatter-dot.is-anomaly { - fill: var(--surface-panel); - fill-opacity: 1; +.sstep-anomaly-dot { stroke: var(--metric-warn); - stroke-width: 1.6; + stroke-width: 1.5; + stroke-opacity: 0.82; + stroke-linecap: round; pointer-events: none; } -.sstep-anomaly-dot.is-danger, -.sstep-scatter-dot.is-anomaly.is-danger { +.sstep-anomaly-dot.is-danger { stroke: var(--metric-danger); + stroke-opacity: 0.92; +} + +.sstep-scatter-dot.is-anomaly { + fill: var(--metric-warn); + fill-opacity: 0.88; + stroke: none; + pointer-events: none; +} + +.sstep-scatter-dot.is-anomaly.is-danger { + fill: var(--metric-danger); + fill-opacity: 0.92; } .trend-tip-anomaly { diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index 101752a..52bcba5 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -108,7 +108,8 @@ export const SettingsView = defineComponent({ settings, telemetry?.windowBridge, telemetry?.hostPlatform, - telemetry?.cliStatusLine + telemetry?.cliStatusLine, + telemetry?.quotas ); } } else if (settingsSubTab === 'other') { diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index f1b3311..4e681c7 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -14,6 +14,7 @@ import { createSvgIcon } from '../../icons/SvgIcon.js'; import { getCapsuleMetricOptions, getOverviewMetricOptions, + hasArgonWeeklyQuotaPool, resolveSpecificQuotaSlotSummary, } from '../../registries/metricRegistry.js'; import { getStepColumnOptions } from '../../registries/stepColumnRegistry.js'; @@ -196,6 +197,15 @@ function formatCliPreviewSlot(slotKey, slotCtx, isEn) { pillPct: pct, }; } + case 'argon_weekly': { + const pct = quotaPct('argon_weekly', 42); + return { + prefix: isEn ? 'Aw ' : 'A周 ', + text: `${pct}%`, + tone: 'good', + pillPct: pct, + }; + } case 'claude_5h': { const pct = quotaPct('claude_5h', 32); return { @@ -255,6 +265,7 @@ export const SettingsStructureTab = defineComponent({ let latestWindowBridge = null; let latestCliStatusLine = null; let latestHostPlatform = 'win32'; + let latestQuotas = null; function getEffectiveDraftCliSlots() { return resolveEffectiveClientCliStatusLineSlots({ @@ -269,25 +280,34 @@ export const SettingsStructureTab = defineComponent({ } function buildDraftTelemetry() { - return buildStructurePreviewTelemetry(latestSettings, { - windowMountMode: draftWindowMountMode, - enableWindowOverlay: draftWindowMountMode !== 'sidebar', - popoverWidthMode: draftPopoverWidthMode, - popoverWidth: draftPopoverWidth, - enableCliStatusLine: draftEnableCliStatusLine, - showTopbarMultiSession: draftShowTopbarMulti, - contextAgentMode: draftContextAgentMode, - topbarCapsuleSlots: draftTopbarSlots, - hoverModules: draftHoverModules, - overviewModules: draftOverviewModules, - overviewMetrics: draftOverviewMetrics, - showStepTurnRail: draftShowStepTurnRail, - showStepAgentBadge: draftShowStepAgentBadge, - showStepSpeedColor: draftShowStepSpeedColor, - showStepFilterToolbar: draftShowStepFilterToolbar, - stepTokenComboFormat: draftStepTokenComboFormat, - stepTableColumns: draftStepColumns, - }); + const effectiveCliSlots = getEffectiveDraftCliSlots(); + const includeArgonPool = + hasArgonWeeklyQuotaPool(latestQuotas) || + draftTopbarSlots.includes('argon_weekly') || + effectiveCliSlots.includes('argon_weekly'); + return buildStructurePreviewTelemetry( + latestSettings, + { + windowMountMode: draftWindowMountMode, + enableWindowOverlay: draftWindowMountMode !== 'sidebar', + popoverWidthMode: draftPopoverWidthMode, + popoverWidth: draftPopoverWidth, + enableCliStatusLine: draftEnableCliStatusLine, + showTopbarMultiSession: draftShowTopbarMulti, + contextAgentMode: draftContextAgentMode, + topbarCapsuleSlots: draftTopbarSlots, + hoverModules: draftHoverModules, + overviewModules: draftOverviewModules, + overviewMetrics: draftOverviewMetrics, + showStepTurnRail: draftShowStepTurnRail, + showStepAgentBadge: draftShowStepAgentBadge, + showStepSpeedColor: draftShowStepSpeedColor, + showStepFilterToolbar: draftShowStepFilterToolbar, + stepTokenComboFormat: draftStepTokenComboFormat, + stepTableColumns: draftStepColumns, + }, + { includeArgonPool } + ); } async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') { @@ -780,7 +800,10 @@ export const SettingsStructureTab = defineComponent({ const effectiveCliSlots = getEffectiveDraftCliSlots(); cliSlotsList.refs.setProps({ items: effectiveCliSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: effectiveCliSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), }); const preservedCustom = Boolean(latestCliStatusLine?.preservedCustom); @@ -819,7 +842,10 @@ export const SettingsStructureTab = defineComponent({ refreshCliPreview(); topbarSlotsList.refs.setProps({ items: draftTopbarSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: draftTopbarSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }), }); mountSection.refs.setBadge( @@ -1431,13 +1457,15 @@ export const SettingsStructureTab = defineComponent({ settings, windowBridge = latestWindowBridge, hostPlatform = latestHostPlatform, - cliStatusLine = latestCliStatusLine + cliStatusLine = latestCliStatusLine, + quotas = latestQuotas ) { if (!settings) return; latestSettings = settings; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine; + if (quotas !== undefined) latestQuotas = quotas; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index d00858f..43513c3 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2263,13 +2263,23 @@ html[data-standalone="true"] .app-shell { .progress-fill-reserved { height: 100%; width: var(--reserved-w, 0%); - background: var(--quota-reserved); - transition: width var(--dur-normal) var(--ease-fast); + background: repeating-linear-gradient( + -45deg, + color-mix(in srgb, var(--quota-reserved) 72%, transparent) 0 2px, + color-mix(in srgb, var(--quota-reserved) 26%, transparent) 2px 5px + ); + transition: + width var(--dur-normal) var(--ease-fast), + margin-left var(--dur-fast) var(--ease-fast); flex-shrink: 0; } .progress-fill-reserved.is-active { - min-width: 3px; + min-width: 5px; +} + +.progress-fill-reserved.is-active.has-sep { + margin-left: 1px; } .quota-reserved-pct { @@ -2277,6 +2287,47 @@ html[data-standalone="true"] .app-shell { font-weight: 500; } +.quota-reserve-legend { + display: flex; + align-items: center; + gap: 12px; + margin-top: 2px; + padding-top: 2px; + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.quota-reserve-legend[hidden] { + display: none; +} + +.quota-legend-item { + display: inline-flex; + align-items: center; + gap: 5px; + white-space: nowrap; +} + +.quota-legend-line { + display: inline-block; + width: 14px; + height: 2px; + border-radius: 1px; + flex-shrink: 0; +} + +.quota-legend-line.is-actual { + background: var(--accent-primary); +} + +.quota-legend-line.is-reserved { + background: repeating-linear-gradient( + 90deg, + var(--quota-reserved) 0 4px, + transparent 4px 6.5px + ); +} + /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; @@ -4683,18 +4734,29 @@ html[data-standalone="true"] .app-shell { stroke: var(--metric-danger); } -.sstep-anomaly-dot, -.sstep-scatter-dot.is-anomaly { - fill: var(--surface-panel); - fill-opacity: 1; +.sstep-anomaly-dot { stroke: var(--metric-warn); - stroke-width: 1.6; + stroke-width: 1.5; + stroke-opacity: 0.82; + stroke-linecap: round; pointer-events: none; } -.sstep-anomaly-dot.is-danger, -.sstep-scatter-dot.is-anomaly.is-danger { +.sstep-anomaly-dot.is-danger { stroke: var(--metric-danger); + stroke-opacity: 0.92; +} + +.sstep-scatter-dot.is-anomaly { + fill: var(--metric-warn); + fill-opacity: 0.88; + stroke: none; + pointer-events: none; +} + +.sstep-scatter-dot.is-anomaly.is-danger { + fill: var(--metric-danger); + fill-opacity: 0.92; } .trend-tip-anomaly { @@ -8486,11 +8548,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { margin: 4px 2px 2px; } -[data-modern-ui="true"] .sstep-anomaly-dot, -[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly { - fill: var(--modern-surface-card); -} - /* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ [data-modern-ui="true"] .collapsible-body, [data-modern-ui="true"] .settings-action-block + .settings-action-block, diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index ea372dc..10383ca 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -78,6 +78,10 @@ test('Ultra user: Argon and Flash sharing Gemini Models remain a single Gemini p Array.from(p.quotas.pools, (pool) => pool.poolKey), ['Gemini', 'Claude & GPT'] ); + assert.equal(p.account.tierId, 'g1-ultra-lite-tier'); + assert.equal(p.account.tierName, 'Google AI Ultra'); + assert.equal(p.account.tierMultiplier, '5x'); + assert.equal(p.account.planName, '5x'); assert.equal(p.quotas.activePool.family, 'Gemini'); assert.equal(p.quotas.activePool.weeklyRemainingPct, 8.7); assert.equal(p.quotas.weekly.poolFamily, 'Gemini'); @@ -663,3 +667,137 @@ test('per-pool cycle5h and cycleWeekly isolate each pool by its own reset window const cycleSourcesTok = pCycle.consumption.sourcesBreakdown.reduce((sum, s) => sum + s.totalTokens, 0); assert.equal(cycleSourcesTok, 155_000); }); + +test('account tier badge distinguishes Ultra 5x (g1-ultra-lite-tier) vs Ultra 20x (g1-ultra-tier) and deduplicates Pro/Free', async () => { + const { formatAccountTierBadge } = await import('../src/components/widgets/QuotaPoolsWidget.js'); + + const hUltra20 = backendHarness({ + userStatus: { + userTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const p20 = await hUltra20.buildTelemetryPayloadInternal(null); + assert.equal(p20.account.tierMultiplier, '20x'); + assert.equal(p20.account.planName, '20x'); + assert.equal(formatAccountTierBadge(p20.account), 'Google AI Ultra · 20x'); + + const hUltra5 = backendHarness({ + userStatus: { + userTier: { id: 'g1-ultra-lite-tier', name: 'Google AI Ultra' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const p5 = await hUltra5.buildTelemetryPayloadInternal(null); + assert.equal(p5.account.tierMultiplier, '5x'); + assert.equal(p5.account.planName, '5x'); + assert.equal(formatAccountTierBadge(p5.account), 'Google AI Ultra · 5x'); + + const hUltraNoId = backendHarness({ + userStatus: { + userTier: { name: 'Google AI Ultra' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const pNoId = await hUltraNoId.buildTelemetryPayloadInternal(null); + assert.equal(pNoId.account.tierMultiplier, ''); + assert.equal(formatAccountTierBadge(pNoId.account), 'Google AI Ultra'); + + const hPro = backendHarness({ + userStatus: { + userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const pPro = await hPro.buildTelemetryPayloadInternal(null); + assert.equal(formatAccountTierBadge(pPro.account), 'Google AI Pro'); + + assert.equal( + formatAccountTierBadge({ tierName: 'Google AI Free', planName: 'Free' }), + 'Google AI Free' + ); + assert.equal( + formatAccountTierBadge({ tierName: 'Google AI', planName: 'Enterprise' }), + 'Google AI · Enterprise' + ); +}); + +test('argon_weekly capsule & CLI slot enables only when user has an Argon weekly pool and auto-hides otherwise', async () => { + const [ + { normalizeTopbarCapsuleSlots }, + { hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct }, + { formatCliStatusLineCapsule }, + { getCapsuleMetricOptions, resolveCapsuleMetricPresentation }, + { setI18nLanguage }, + ] = await Promise.all([ + import('../shared/settings-normalization.mjs'), + import('../shared/telemetry-display-rules.mjs'), + import('../backend/cli-statusline-config.mjs'), + import('../src/registries/metricRegistry.js'), + import('../src/i18n/index.js'), + ]); + setI18nLanguage('zh-CN'); + + const slots = normalizeTopbarCapsuleSlots(['tps', 'argon_weekly', 'context']); + assert.deepEqual(slots, ['tps', 'argon_weekly', 'context']); + + const proQuotas = { + pools: [ + { poolKey: 'Gemini', remainingPct: 90, weeklyRemainingPct: 80 }, + { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', weeklyRemainingPct: 42 }, + { poolKey: 'Claude & GPT', remainingPct: 100, weeklyRemainingPct: 100 }, + ], + }; + const ultraQuotas = { + pools: [ + { poolKey: 'Gemini', remainingPct: 90, weeklyRemainingPct: 80 }, + { poolKey: 'Claude & GPT', remainingPct: 100, weeklyRemainingPct: 100 }, + ], + }; + + assert.equal(hasArgonWeeklyQuotaPool(proQuotas), true); + assert.equal(hasArgonWeeklyQuotaPool(ultraQuotas), false); + assert.equal(resolveCapsuleQuotaSlotPct(proQuotas, 'argon_weekly'), 42); + assert.equal(resolveCapsuleQuotaSlotPct(ultraQuotas, 'argon_weekly'), null); + + // Picker options show argon_weekly only for Argon pool users (or if already selected) + const optsPro = getCapsuleMetricOptions({ quotas: proQuotas }); + const optsUltra = getCapsuleMetricOptions({ quotas: ultraQuotas }); + const optsUltraSelected = getCapsuleMetricOptions({ + quotas: ultraQuotas, + selectedSlots: ['argon_weekly'], + }); + assert.equal(optsPro.some((o) => o.value === 'argon_weekly'), true); + assert.equal(optsUltra.some((o) => o.value === 'argon_weekly'), false); + assert.equal(optsUltraSelected.some((o) => o.value === 'argon_weekly'), true); + + // Topbar capsule presentation renders A周 42% for Pro and hides cleanly for Ultra + const presPro = resolveCapsuleMetricPresentation( + 'argon_weekly', + { hasTelemetry: true, quotas: proQuotas }, + 34.56 + ); + assert.equal(presPro.hidden, false); + assert.equal(presPro.prefix, 'A周'); + assert.equal(presPro.text, '42%'); + + const presUltra = resolveCapsuleMetricPresentation( + 'argon_weekly', + { hasTelemetry: true, quotas: ultraQuotas }, + 34.56 + ); + assert.equal(presUltra.hidden, true); + + // CLI status line renders A周 42% for Pro and omits argon_weekly cleanly for Ultra + const cliPro = formatCliStatusLineCapsule( + { hasTelemetry: true, stepCount: 3, tps: 50, usedPct: 30, quotas: proQuotas }, + { slots: ['tps', 'argon_weekly', 'context'], language: 'zh-CN', color: false } + ); + assert.match(cliPro, /A周 42%/); + + const cliUltra = formatCliStatusLineCapsule( + { hasTelemetry: true, stepCount: 3, tps: 50, usedPct: 30, quotas: ultraQuotas }, + { slots: ['tps', 'argon_weekly', 'context'], language: 'zh-CN', color: false } + ); + assert.doesNotMatch(cliUltra, /A周/); +}); diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs index 81bbc7f..8c70bb5 100644 --- a/sidecars/panel/test/quota-reservation.test.mjs +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -2,6 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { QR_LEASE_IDLE_EXPIRY_MS, + QR_REFUND_CONFIRM_WINDOW_MS, createQuotaReservationTracker, } from '../backend/quota-reservation.mjs'; import { normalizeFullSettings } from '../backend/settings-schema.mjs'; @@ -313,6 +314,311 @@ test('quota-reservation: avoids false positives on genuinely large steps, handle assert.ok(tracker._buckets.get(key).ratePctPerUsd > 0, 'calibrated rate preserved across reset'); }); +test('quota-reservation: persists log, calibrated rate, and active leases across plugin restarts', () => { + let storedPayload = null; + const trackerA = createQuotaReservationTracker({ + loadState: () => storedPayload, + saveState: (payload) => { + storedPayload = JSON.parse(JSON.stringify(payload)); + }, + }); + const key = 'local::u@example.com::Gemini::5h'; + + trackerA.observeBucket({ + bucketKey: key, + officialUsedPct: 4.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: T0, + cycleCostUsd: 4.0, + poolLastActivityMs: T0, + nowMs: T0, + }); + + const t1 = T0 + 20_000; + trackerA.observeBucket({ + bucketKey: key, + officialUsedPct: 5.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t1, + cycleCostUsd: 4.05, + poolLastActivityMs: t1, + nowMs: t1, + }); + assert.ok(storedPayload && storedPayload.events.length === 2, 'baseline + lease persisted to disk'); + + // Simulate full plugin restart with a brand new tracker instance reading storedPayload + const trackerB = createQuotaReservationTracker({ + loadState: () => storedPayload, + saveState: (payload) => { + storedPayload = JSON.parse(JSON.stringify(payload)); + }, + }); + const snapBeforeAnyPoll = trackerB.getLogSnapshot(); + assert.equal(snapBeforeAnyPoll.count, 2, 'historical events immediately available after restart'); + assert.equal(snapBeforeAnyPoll.buckets[0].reservedPct, 1.0, 'active lease survives restart'); + assert.equal(snapBeforeAnyPoll.buckets[0].ratePctPerUsd, 1.0, 'calibrated rate survives restart'); + + // Refund arriving after restart cleanly reconciles against the hydrated lease + const t2 = t1 + 10 * 60 * 1000; + const rAfterRestart = trackerB.observeBucket({ + bucketKey: key, + officialUsedPct: 4.05, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t2, + cycleCostUsd: 4.05, + poolLastActivityMs: t1, + nowMs: t2, + }); + assert.equal(rAfterRestart.reservedPct, 0); + assert.equal(trackerB.getLogSnapshot().count, 3); +}); + +test('quota-reservation: suppresses replica ping-pong, keeps rolling median rate clean, and ignores 0% idle reset drift', () => { + const tracker = createQuotaReservationTracker(); + const key5h = 'local::u@example.com::Gemini::5h'; + const keyWk = 'local::u@example.com::Gemini::weekly'; + const keyIdle = 'local::u@example.com::Claude & GPT::5h'; + + let ts = T0; + let u5 = 13.0; + let uw = 18.0; + let c5 = 18.0; + let cw = 86.0; + + // Baseline + 8 clean steps at exact 0.6667 %/$ (5h) and 0.1667 %/$ (weekly) + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: uw, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + tracker.observeBucket({ + bucketKey: keyIdle, + officialUsedPct: 0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: 0, + poolLastActivityMs: 0, + nowMs: ts, + }); + + for (let i = 0; i < 8; i += 1) { + ts += 15_000; + const dc = 0.09; + c5 += dc; + cw += dc; + u5 += dc * (2 / 3); + uw += dc * (1 / 6); + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: uw, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + } + + // Idle 0% pool resetTime drifts by 35 min -> silently absorbed (no spurious reset event) + tracker.observeBucket({ + bucketKey: keyIdle, + officialUsedPct: 0, + resetTimeMs: RESET_5H + 35 * 60 * 1000, + quotaFetchedAtMs: ts + 35 * 60 * 1000, + cycleCostUsd: 0, + poolLastActivityMs: 0, + nowMs: ts, + }); + assert.equal( + tracker.getLogSnapshot().events.some((e) => e.pool === 'Claude & GPT' && e.event === 'reset'), + false, + 'idle 0% pool drift must not emit reset' + ); + + // Weekly triggers a +0.9% lease on Cell B, then bounces Cell A <-> Cell B 5 times while 5h bounces +/-0.2% + ts += 10_000; + const wkBase = uw; + const wkHigh = uw + 0.9; + const rLease = tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkHigh, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rLease.reservedPct, 0.9); + assert.equal(rLease.reservedLeaseCount, 1); + + for (let i = 0; i < 5; i += 1) { + // Drop to Cell A (low replica) + ts += 10_000; + c5 += 0.06; + cw += 0.06; + const rLowWk = tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkBase + (i + 1) * 0.01, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rLowWk.reservedPct, 0, 'low replica hides lease portion so actual stays stable'); + + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5 - 0.2 + i * 0.04, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + + // Bounce back to Cell B (high replica) + ts += 10_000; + c5 += 0.06; + cw += 0.06; + const rHighWk = tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkHigh + (i + 1) * 0.02, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rHighWk.reservedPct, 0.9, 'rebound restores same lease without duplicating'); + assert.equal(rHighWk.reservedLeaseCount, 1); + + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5 + 0.08 + i * 0.08, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + } + + // Both rolling-median rates remain unpolluted near 0.6667 and 0.1667 + const snapMid = tracker.getLogSnapshot(); + const b5h = snapMid.buckets.find((b) => b.pool === 'Gemini' && b.win === '5h'); + const bWk = snapMid.buckets.find((b) => b.pool === 'Gemini' && b.win === 'weekly'); + assert.ok(Math.abs(b5h.ratePctPerUsd - 0.6667) < 0.02, `5h rate stays clean: ${b5h.ratePctPerUsd}`); + assert.ok(Math.abs(bWk.ratePctPerUsd - 0.1667) < 0.01, `weekly rate stays clean: ${bWk.ratePctPerUsd}`); + + // Sustained drop on weekly (stays low across >= 3 samples and >= 90s while active) confirms genuine refund + for (let i = 0; i < 4; i += 1) { + ts += Math.ceil(QR_REFUND_CONFIRM_WINDOW_MS / 3); + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkBase + 0.1, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + } + const bWkAfter = tracker.getLogSnapshot().buckets.find((b) => b.pool === 'Gemini' && b.win === 'weekly'); + assert.equal(bWkAfter.reservedPct, 0); + assert.equal(bWkAfter.leases, 0); +}); + +test('quota-reservation: ignores sub-epsilon shortfall noise and drops polluted v1 EMA rate on schema upgrade', () => { + // 1. Sub-epsilon rounding mismatch during normal spending must not keep stale leases alive + const tracker = createQuotaReservationTracker(); + const key = 'local::u@example.com::Gemini::5h'; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 10.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: T0, + cycleCostUsd: 15.0, + poolLastActivityMs: T0, + nowMs: T0, + }); + // Trigger +1.0% lease at t1 + const t1 = T0 + 15_000; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 11.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t1, + cycleCostUsd: 15.0, + poolLastActivityMs: t1, + nowMs: t1, + }); + // Normal steps at ~0.666 %/$ (0.001% below cold-start 0.667) across 12 minutes -> lease expires normally + let u = 11.0; + let c = 15.0; + let now = t1; + for (let i = 0; i < 12; i += 1) { + now += 60_000; + c += 0.09; + u += 0.059; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: u, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: now, + cycleCostUsd: c, + poolLastActivityMs: now, + nowMs: now, + }); + } + const snap = tracker.getLogSnapshot(); + assert.equal(snap.buckets[0].reservedPct, 0, 'normal billing does not infinitely renew stale lease'); + + // 2. Loading v1 persisted payload resets polluted EMA rate while preserving event log + const v1Payload = { + version: 1, + savedAt: new Date(T0).toISOString(), + buckets: { + [key]: { + resetTimeMs: RESET_5H, + lastQuotaTs: T0, + lastOfficialUsedPct: 30.0, + lastCycleCostUsd: 38.0, + ratePctPerUsd: 2.005, + rateSamples: 41, + activeLeases: [], + }, + }, + events: [{ ts: new Date(T0).toISOString(), pool: 'Gemini', win: '5h', event: 'normal' }], + }; + const migrated = createQuotaReservationTracker({ loadState: () => v1Payload }); + const migSnap = migrated.getLogSnapshot(); + assert.equal(migSnap.count, 1, 'v1 events preserved on upgrade'); + assert.equal(migSnap.buckets[0].ratePctPerUsd, null, 'polluted v1 rate cleared for clean recalibration'); +}); + test('experimentalQuotaReservation setting defaults false and round-trips through schema & backup', () => { const def = normalizeFullSettings({}); assert.equal(def.experimentalQuotaReservation, false); @@ -501,8 +807,11 @@ test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/te }, }; - // Toggle OFF: no reserved highlight + // Toggle OFF: no reserved highlight and legend hidden widget.refs.update({ data: baseData, minuteTick: 1 }); + const legendEl = widget.el.querySelector('.quota-reserve-legend'); + assert.ok(legendEl, 'quota reservation legend mounted'); + assert.equal(legendEl.hidden, true); const rsvTagsOff = widget.el.querySelectorAll('.quota-reserved-pct'); assert.equal(rsvTagsOff.length, 2); assert.equal(rsvTagsOff[0].hidden, true); @@ -510,11 +819,16 @@ test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/te const fillBarsOff = widget.el.querySelectorAll('.progress-fill'); assert.equal(fillBarsOff[0].style.getPropertyValue('--fill-w'), '4.1%'); - // Toggle ON: violet reserved bar segment + colored percentage tag + // Toggle ON: violet reserved bar segment + colored percentage tag + bottom solid/dashed legend widget.refs.update({ data: { ...baseData, settings: { experimentalQuotaReservation: true } }, minuteTick: 1, }); + assert.equal(legendEl.hidden, false); + assert.ok(legendEl.querySelector('.quota-legend-line.is-actual')); + assert.ok(legendEl.querySelector('.quota-legend-line.is-reserved')); + assert.match(legendEl.textContent, /实占/); + assert.match(legendEl.textContent, /预占/); const rsvTagsOn = widget.el.querySelectorAll('.quota-reserved-pct'); assert.equal(rsvTagsOn[0].hidden, false); assert.equal(rsvTagsOn[0].textContent, '预占 1.0%'); @@ -526,8 +840,10 @@ test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/te assert.equal(fillBarsOn[0].style.getPropertyValue('--fill-w'), '3.1%'); assert.equal(rsvBarsOn[0].style.getPropertyValue('--reserved-w'), '1%'); assert.equal(rsvBarsOn[0].classList.contains('is-active'), true); + assert.equal(rsvBarsOn[0].classList.contains('has-sep'), true); assert.equal(fillBarsOn[1].style.getPropertyValue('--fill-w'), '15.7%'); assert.equal(rsvBarsOn[1].style.getPropertyValue('--reserved-w'), '0.5%'); + assert.equal(rsvBarsOn[1].classList.contains('has-sep'), true); // SettingsOtherTab renders experimental badge and persists toggle click const othTab = SettingsOtherTab({ onLayoutChange: () => {} }); diff --git a/sidecars/panel/test/step-anomalies.test.mjs b/sidecars/panel/test/step-anomalies.test.mjs index 8c94862..e2411da 100644 --- a/sidecars/panel/test/step-anomalies.test.mjs +++ b/sidecars/panel/test/step-anomalies.test.mjs @@ -857,7 +857,9 @@ test('StepsDetailView total summary cards, session anomaly strip, click-to-filte metric: 'tps', }); const lineAnomalyDots = lineChart.el.querySelectorAll('.sstep-anomaly-dot'); - assert.equal(lineAnomalyDots.length, 1, 'Line chart renders anomaly ring marker even when steps > 64'); + assert.equal(lineAnomalyDots.length, 1, 'Line chart renders bottom rug tick marker even when steps > 64'); + assert.equal(lineAnomalyDots[0].tagName.toLowerCase(), 'line'); + assert.equal(lineAnomalyDots[0].classList.contains('sstep-anomaly-tick'), true); assert.equal(lineAnomalyDots[0].classList.contains('is-danger'), true); fitChart = createModelFitChart(); @@ -868,7 +870,8 @@ test('StepsDetailView total summary cards, session anomaly strip, click-to-filte metric: 'tps', }); const fitAnomalyDots = fitChart.el.querySelectorAll('.sstep-scatter-dot.is-anomaly'); - assert.equal(fitAnomalyDots.length, 1, 'Fit scatter chart renders anomaly ring overlay without overdraw drop'); + assert.equal(fitAnomalyDots.length, 1, 'Fit scatter chart renders solid matching-size anomaly dot without overdraw drop'); + assert.equal(fitAnomalyDots[0].getAttribute('r'), '2.1'); assert.equal(fitAnomalyDots[0].classList.contains('is-danger'), true); assert.ok(fitChart.el.querySelector('.trend-tip-anomaly'), 'Fit chart tooltip mounts linked anomaly diagnostic row'); } finally { diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 4d42fea..ee78cb0 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -1854,8 +1854,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.ok(previewCellSubs.includes('有效 23/24 步'), 'Preview Avg TPS card shows populated valid sample ratio'); assert.equal( overviewPreviewHostEl.children[2].querySelector('.panel-meta').textContent, - 'Google AI Ultra · Pro', - 'Preview quota badge matches real tier · plan format' + 'Google AI Ultra · 5x', + 'Preview quota badge displays Ultra 5x multiplier instead of legacy Pro' ); const [ovModWrap, ovMetricWrap] = sec2.querySelectorAll('.editable-slot-wrap'); From 743bdfa24d72a62055b388dbcfc168e88f124a60 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 22 Nov 2026 21:03:11 +0900 Subject: [PATCH 22/31] feat(panel): add local CloudCode proxy sync and independent Main/Subagent-Swarm context window toggles (#36) --- sidecars/panel/app.js | 148 +++- sidecars/panel/backend/api-actions.mjs | 14 +- sidecars/panel/backend/cloudcode-proxy.mjs | 827 ++++++++++++++++++ sidecars/panel/backend/context-windows.mjs | 31 +- sidecars/panel/backend/settings-schema.mjs | 4 + sidecars/panel/backend/telemetry-builder.mjs | 2 + sidecars/panel/backend/window-bridge.mjs | 259 ++++-- sidecars/panel/index.html | 4 +- sidecars/panel/main.mjs | 23 + sidecars/panel/src/i18n/en-US.js | 3 + sidecars/panel/src/i18n/zh-CN.js | 3 + sidecars/panel/src/store/telemetryStore.js | 20 + sidecars/panel/src/styles/views-settings.css | 8 + sidecars/panel/src/views/SettingsView.js | 4 +- .../src/views/settings/SettingsOtherTab.js | 118 ++- sidecars/panel/styles.css | 8 + sidecars/panel/test/backend-harness.mjs | 3 +- sidecars/panel/test/context-windows.test.mjs | 480 ++++++++++ 18 files changed, 1862 insertions(+), 97 deletions(-) create mode 100644 sidecars/panel/backend/cloudcode-proxy.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 53f2bda..1b1b294 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1955,6 +1955,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', 'settings.oth.ctxRiskAcceptBtn': '我已知晓风险,继续使用', 'settings.oth.ctxModel': '模型', + 'settings.oth.ctxMainLabel': '主代理', + 'settings.oth.ctxSwarmLabel': '子代理与蜂群', + 'settings.oth.ctxSwarmError': '本地同步异常:{error}', 'settings.oth.ctxBaselineLabel': '上下文窗口上限', 'settings.oth.ctxChooseModel': '选择模型', 'settings.oth.ctxDefault': '跟随宿主设置', @@ -2833,6 +2836,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', 'settings.oth.ctxRiskAcceptBtn': 'I Understand the Risk, Unlock', 'settings.oth.ctxModel': 'Model', + 'settings.oth.ctxMainLabel': 'Main Agent', + 'settings.oth.ctxSwarmLabel': 'Subagents & Swarm', + 'settings.oth.ctxSwarmError': 'Local sync failed: {error}', 'settings.oth.ctxBaselineLabel': 'Context Window Limit', 'settings.oth.ctxChooseModel': 'Choose a model', 'settings.oth.ctxDefault': 'Follow host settings', @@ -9211,6 +9217,20 @@ function isEquivalentTelemetry(prev, next) { if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; } + if ( + (pSet?.contextWindowMainEnabled !== false) !== (nSet?.contextWindowMainEnabled !== false) || + Boolean(pSet?.contextWindowSwarmEnabled) !== Boolean(nSet?.contextWindowSwarmEnabled) + ) { + return false; + } + if ( + (prev.cloudCodeProxy?.state || 'disabled') !== (next.cloudCodeProxy?.state || 'disabled') || + Number(prev.cloudCodeProxy?.ruleCount || 0) !== Number(next.cloudCodeProxy?.ruleCount || 0) || + String(prev.cloudCodeProxy?.error || '') !== String(next.cloudCodeProxy?.error || '') || + Number(prev.cloudCodeProxy?.syncedAtMs || 0) !== Number(next.cloudCodeProxy?.syncedAtMs || 0) + ) { + return false; + } if ( JSON.stringify(pSet?.modelContextWindows) !== JSON.stringify(nSet?.modelContextWindows) || JSON.stringify(prev.contextWindowModels) !== JSON.stringify(next.contextWindowModels) @@ -10527,6 +10547,12 @@ async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowRiskAccepted')) { safePatch.contextWindowRiskAccepted = Boolean(safePatch.contextWindowRiskAccepted); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowMainEnabled')) { + safePatch.contextWindowMainEnabled = Boolean(safePatch.contextWindowMainEnabled); + } + if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowSwarmEnabled')) { + safePatch.contextWindowSwarmEnabled = Boolean(safePatch.contextWindowSwarmEnabled); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) { safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode); } @@ -27065,8 +27091,12 @@ const SettingsOtherTab = defineComponent({ let draftExperimentalQuotaReservation = false; let draftContextRiskAccepted = false; let acceptingContextRisk = false; + let draftContextMainEnabled = true; + let draftContextSwarmEnabled = false; + let savingContextScope = false; let latestSettings = null; let latestWindowBridge = null; + let latestCloudCodeProxy = null; let latestHostPlatform = 'win32'; let contextWindowModels = []; let contextModelId = ''; @@ -27346,10 +27376,79 @@ const SettingsOtherTab = defineComponent({ }, }); const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true }); + const ctxMainLabelEl = h('span', { + className: 'form-label', + text: t('settings.oth.ctxMainLabel'), + }); + const ctxMainToggle = SegmentedControl({ + modelValue: 'on', + ariaLabel: t('settings.oth.ctxMainLabel'), + options: getEnableToggleOptions(), + onUpdateModelValue: async (val) => { + if (!draftContextRiskAccepted || savingContextScope) return; + const nextEnabled = val === 'on'; + const prevEnabled = draftContextMainEnabled; + savingContextScope = true; + draftContextMainEnabled = nextEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: nextEnabled }; + contextFeedback = 'settings.saving'; + renderContextWindows(); + try { + await saveSettingsPatch({ contextWindowMainEnabled: nextEnabled }); + contextFeedback = 'settings.saved'; + } catch { + draftContextMainEnabled = prevEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: prevEnabled }; + contextFeedback = 'settings.saveFailed'; + } finally { + savingContextScope = false; + renderContextWindows(); + } + }, + }); + const ctxSwarmLabelEl = h('span', { + className: 'form-label', + text: t('settings.oth.ctxSwarmLabel'), + }); + const ctxSwarmToggle = SegmentedControl({ + modelValue: 'off', + ariaLabel: t('settings.oth.ctxSwarmLabel'), + options: getEnableToggleOptions(), + onUpdateModelValue: async (val) => { + if (!draftContextRiskAccepted || savingContextScope) return; + const nextEnabled = val === 'on'; + const prevEnabled = draftContextSwarmEnabled; + savingContextScope = true; + draftContextSwarmEnabled = nextEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: nextEnabled }; + contextFeedback = 'settings.saving'; + renderContextWindows(); + try { + await saveSettingsPatch({ contextWindowSwarmEnabled: nextEnabled }); + contextFeedback = 'settings.saved'; + } catch { + draftContextSwarmEnabled = prevEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: prevEnabled }; + contextFeedback = 'settings.saveFailed'; + } finally { + savingContextScope = false; + renderContextWindows(); + } + }, + }); + const ctxMainRow = h('div', { className: 'form-row' }, [ctxMainLabelEl, ctxMainToggle.el]); + const ctxSwarmRow = h('div', { className: 'form-row' }, [ctxSwarmLabelEl, ctxSwarmToggle.el]); + const ctxSyncStatusEl = h('span', { + className: 'settings-hint-text ctx-sync-status is-error', + hidden: true, + }); const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]); const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]); const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ ctxBridgeNotice.el, + ctxMainRow, + ctxSwarmRow, + ctxSyncStatusEl, ctxModelRow, ctxWindowRow, h('div', { className: 'form-row' }, [ctxHint]), @@ -27428,8 +27527,31 @@ const SettingsOtherTab = defineComponent({ const saved = latestSettings?.modelContextWindows || {}; const wbState = String(latestWindowBridge?.state || '').trim(); const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable'; + const proxyState = String(latestCloudCodeProxy?.state || 'disabled'); + const isProxyActive = Boolean(latestCloudCodeProxy?.active && proxyState === 'active'); + + patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel')); + ctxMainToggle.setProps({ + modelValue: draftContextMainEnabled ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.ctxMainLabel'), + }); + patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel')); + ctxSwarmToggle.setProps({ + modelValue: draftContextSwarmEnabled ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.ctxSwarmLabel'), + }); + + const syncErrorText = + draftContextSwarmEnabled && proxyState === 'error' && latestCloudCodeProxy?.error + ? t('settings.oth.ctxSwarmError', { error: latestCloudCodeProxy.error }) + : ''; + patchAttr(ctxSyncStatusEl, 'hidden', !syncErrorText); + patchText(ctxSyncStatusEl, syncErrorText); + ctxBridgeNotice.refs.update({ - visible: unlocked, + visible: unlocked && draftContextMainEnabled, windowBridge: latestWindowBridge, hostPlatform: latestHostPlatform, }); @@ -27477,7 +27599,13 @@ const SettingsOtherTab = defineComponent({ else if (value) { const name = formatLimit(value); if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name }); - else if (isBridgeMissing) meta = t('settings.oth.ctxPendingBridge', { name }); + else if ( + isBridgeMissing && + draftContextMainEnabled && + !(draftContextSwarmEnabled && isProxyActive) + ) { + meta = t('settings.oth.ctxPendingBridge', { name }); + } else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) { meta = t('settings.oth.ctxConfiguredReported', { name, @@ -27765,13 +27893,15 @@ const SettingsOtherTab = defineComponent({ settings, models = contextWindowModels, windowBridge = latestWindowBridge, - hostPlatform = latestHostPlatform + hostPlatform = latestHostPlatform, + cloudCodeProxy = latestCloudCodeProxy ) { if (!settings) return; latestSettings = settings; contextWindowModels = models; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; + if (cloudCodeProxy !== undefined) latestCloudCodeProxy = cloudCodeProxy; draftModelDisplayMode = normalizeClientModelDisplayMode( settings.modelDisplayMode, settings.showUpstreamModel @@ -27783,6 +27913,10 @@ const SettingsOtherTab = defineComponent({ if (!acceptingContextRisk) { draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted); } + if (!savingContextScope) { + draftContextMainEnabled = settings.contextWindowMainEnabled !== false; + draftContextSwarmEnabled = settings.contextWindowSwarmEnabled === true; + } stepModelSelect.setProps({ modelValue: draftModelDisplayMode, options: getStepModelDisplayOptions(), @@ -27858,6 +27992,8 @@ const SettingsOtherTab = defineComponent({ orchestratorIdSelect.destroy(); quotaReserveToggle.destroy(); ctxBridgeNotice.destroy(); + ctxMainToggle.destroy(); + ctxSwarmToggle.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); sessionMigrationCard.destroy(); @@ -27871,6 +28007,8 @@ const SettingsOtherTab = defineComponent({ quotaReserveToggle, exportReserveLogBtn, ctxBridgeNotice, + ctxMainToggle, + ctxSwarmToggle, ctxModelSelect, ctxWindowSelect, sessionMigrationCard, @@ -32899,7 +33037,8 @@ const SettingsView = defineComponent({ settings, telemetry.contextWindowModels || [], telemetry?.windowBridge, - telemetry?.hostPlatform + telemetry?.hostPlatform, + telemetry?.cloudCodeProxy ); } } else if (accountTab && settingsSubTab === 'account') { @@ -32915,6 +33054,7 @@ const SettingsView = defineComponent({ (st) => ({ settings: st.telemetry?.settings, windowBridge: st.telemetry?.windowBridge, + cloudCodeProxy: st.telemetry?.cloudCodeProxy, cliStatusLine: st.telemetry?.cliStatusLine, hostPlatform: st.telemetry?.hostPlatform, cloudStatus: st.telemetry?.cloudStatus, diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 7a40c97..95de098 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -376,12 +376,16 @@ export function executeSettingsAction(data) { current.windowMountMode, current.enableWindowOverlay ); + const contextWindowScopeChanged = + (updated.contextWindowMainEnabled !== false) !== (current.contextWindowMainEnabled !== false) || + (updated.contextWindowSwarmEnabled === true) !== (current.contextWindowSwarmEnabled === true); const affectsBackendTelemetry = updated.weeklyLimitMode !== current.weeklyLimitMode || updated.weeklyTokenBudget !== current.weeklyTokenBudget || updated.weeklyCostBudget !== current.weeklyCostBudget || updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) || - updated.windowMountMode !== prevMountMode; + updated.windowMountMode !== prevMountMode || + contextWindowScopeChanged; inFlightRequests.clear(); if (affectsBackendTelemetry) { clearTelemetryBuilderMemo(); @@ -391,6 +395,8 @@ export function executeSettingsAction(data) { updated.windowMountMode !== prevMountMode ) { void notifyWindowOverlaySetting(updated.enableWindowOverlay); + } else if (contextWindowScopeChanged) { + void notifyModelContextWindowsChanged(); } if ((updated.enableCliStatusLine !== false) !== (current.enableCliStatusLine !== false)) { ensureCliStatusLineConfigured({ enabled: updated.enableCliStatusLine !== false }); @@ -514,7 +520,11 @@ export function executeResetSettingsAction() { updated.windowMountMode !== prevMountMode ) { void notifyWindowOverlaySetting(updated.enableWindowOverlay); - } else if (Object.keys(current.modelContextWindows).length) { + } else if ( + Object.keys(current.modelContextWindows).length || + current.contextWindowMainEnabled === false || + current.contextWindowSwarmEnabled === true + ) { void notifyModelContextWindowsChanged(); } if ((updated.enableCliStatusLine !== false) !== (current.enableCliStatusLine !== false)) { diff --git a/sidecars/panel/backend/cloudcode-proxy.mjs b/sidecars/panel/backend/cloudcode-proxy.mjs new file mode 100644 index 0000000..f64db52 --- /dev/null +++ b/sidecars/panel/backend/cloudcode-proxy.mjs @@ -0,0 +1,827 @@ +/** + * @fileoverview 本地透明 CloudCode 反代与 `SetCloudCodeURL` 调度器 (`cloudcode-proxy.mjs`)。 + * + * 用于在不修改宿主二进制、无需 `--dev_mode` 或自签证书的前提下,通过 Language Server 原生 + * `SetCloudCodeURL` RPC 将 `/v1internal:fetchAvailableModels` 流量经由 `127.0.0.1` 随机端口 + * 透明转发至官方 CloudCode 上游,并在响应中按模型改写 `CASCADE_USE_EXPERIMENT_CHECKPOINTER` + * 实验配置(覆盖非 `self` 子代理与蜂群 worker),其余请求零缓冲流式透传。 + */ + +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { lsRuntimeEndpoint } from './config.mjs'; +import { callLsRpc } from './ls-rpc.mjs'; + +export const DEFAULT_UPSTREAM_CLOUDCODE_URL = 'https://daily-cloudcode-pa.googleapis.com'; + +const CC_PROXY_UPSTREAM_URL_RE = /https:\/\/[a-z0-9.-]*cloudcode-pa\.googleapis\.com/gi; +const CC_PROXY_CHECKPOINTER_KEY = 'CASCADE_USE_EXPERIMENT_CHECKPOINTER'; +const CC_PROXY_CHECKPOINTER_PREFIX = `${CC_PROXY_CHECKPOINTER_KEY}/`; +const CC_PROXY_MAX_LOG_READ_BYTES = 512 * 1024; +const CC_PROXY_RETRY_COOLDOWN_MS = 15_000; +const CC_PROXY_SYS_PROXY_CACHE_MS = 15_000; + +let ccProxyNodeModulesPromise = null; + +async function loadCcProxyNodeModules() { + if (!ccProxyNodeModulesPromise) { + ccProxyNodeModulesPromise = Promise.all([ + import('node:http'), + import('node:https'), + import('node:tls'), + import('node:zlib'), + import('node:child_process'), + import('node:fs'), + ]).then(([httpMod, httpsMod, tlsMod, zlibMod, cpMod, fsMod]) => ({ + http: httpMod.default || httpMod, + https: httpsMod.default || httpsMod, + tls: tlsMod.default || tlsMod, + zlib: zlibMod.default || zlibMod, + execFileSync: cpMod.execFileSync, + openSync: fsMod.openSync, + readSync: fsMod.readSync, + closeSync: fsMod.closeSync, + })); + } + return ccProxyNodeModulesPromise; +} + +function isCcProxyLoopbackHost(hostname) { + const host = String(hostname || '').trim().toLowerCase().replace(/^\[|\]$/g, ''); + return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '0.0.0.0'; +} + +export function isValidUpstreamCloudCodeUrl(rawUrl, { allowHttp = false } = {}) { + try { + const parsed = new URL(String(rawUrl || '').trim()); + if (parsed.protocol !== 'https:' && !(allowHttp && parsed.protocol === 'http:')) { + return false; + } + if (!allowHttp && isCcProxyLoopbackHost(parsed.hostname)) { + return false; + } + return Boolean(parsed.hostname); + } catch { + return false; + } +} + +function readLogFileTailUtf8(filePath, sizeBytes, fsTailOps = null) { + if (!Number.isFinite(sizeBytes) || sizeBytes <= CC_PROXY_MAX_LOG_READ_BYTES || !fsTailOps) { + return readFileSync(filePath, 'utf8'); + } + const { openSync, readSync, closeSync } = fsTailOps; + const start = Math.max(0, sizeBytes - CC_PROXY_MAX_LOG_READ_BYTES); + const length = sizeBytes - start; + const fd = openSync(filePath, 'r'); + try { + const buf = Buffer.allocUnsafe(length); + const bytesRead = readSync(fd, buf, 0, length, start); + return buf.subarray(0, bytesRead).toString('utf8'); + } finally { + closeSync(fd); + } +} + +function getCcProxyLogCandidateDirs(env, platform, homeDir) { + const safeEnv = env || {}; + const home = String(homeDir || '').trim(); + if (platform === 'win32') { + return [ + safeEnv.APPDATA ? join(safeEnv.APPDATA, 'Antigravity', 'logs') : '', + safeEnv.LOCALAPPDATA ? join(safeEnv.LOCALAPPDATA, 'Antigravity', 'logs') : '', + home ? join(home, '.gemini', 'antigravity', 'logs') : '', + ].filter(Boolean); + } + if (platform === 'darwin') { + return [ + home ? join(home, 'Library', 'Application Support', 'Antigravity', 'logs') : '', + home ? join(home, '.gemini', 'antigravity', 'logs') : '', + ].filter(Boolean); + } + return [ + home ? join(home, '.config', 'Antigravity', 'logs') : '', + home ? join(home, '.gemini', 'antigravity', 'logs') : '', + ].filter(Boolean); +} + +/** + * 探测宿主真实上游 CloudCode URL(严格排除本地回环地址,防止自环)。 + * + * @param {object} [opts] + * @returns {string} + */ +export function detectUpstreamCloudCodeUrl({ + env = process.env, + platform = process.platform, + homeDir = homedir(), + fsTailOps = null, +} = {}) { + const envUrl = String(env?.ANTIGRAVITY_CLOUDCODE_URL || env?.CLOUDCODE_URL || '').trim(); + if (isValidUpstreamCloudCodeUrl(envUrl)) { + return envUrl.replace(/\/+$/, ''); + } + + for (const dir of getCcProxyLogCandidateDirs(env, platform, homeDir)) { + if (!existsSync(dir)) continue; + try { + const entries = readdirSync(dir) + .filter((name) => /\.log$/i.test(String(name || ''))) + .map((name) => { + const fullPath = join(dir, String(name)); + const st = statSync(fullPath); + return { fullPath, mtimeMs: Number(st?.mtimeMs || 0), size: Number(st?.size || 0) }; + }) + .sort((a, b) => b.mtimeMs - a.mtimeMs); + for (const item of entries.slice(0, 5)) { + const text = readLogFileTailUtf8(item.fullPath, item.size, fsTailOps); + const matches = text.match(CC_PROXY_UPSTREAM_URL_RE); + if (matches && matches.length > 0) { + for (let i = matches.length - 1; i >= 0; i -= 1) { + const candidate = matches[i].replace(/\/+$/, ''); + if (isValidUpstreamCloudCodeUrl(candidate)) { + return candidate; + } + } + } + } + } catch { + // 忽略单个日志目录读取异常 + } + } + + return DEFAULT_UPSTREAM_CLOUDCODE_URL; +} + +function shouldCcProxyBypassHost(hostname, noProxyRaw) { + const target = String(hostname || '').trim().toLowerCase(); + const list = String(noProxyRaw || '').trim(); + if (!target || !list) return false; + for (const part of list.split(/[;,]/)) { + const raw = part.trim().toLowerCase(); + if (!raw) continue; + if (raw === '*') return true; + const rule = raw.replace(/^\*\./, '.').replace(/:\d+$/, ''); + if (!rule) continue; + if (rule.startsWith('.')) { + if (target.endsWith(rule) || target === rule.slice(1)) return true; + } else if (target === rule || target.endsWith(`.${rule}`)) { + return true; + } + } + return false; +} + +function parseWindowsProxyServerValue(rawVal) { + let srv = String(rawVal || '').trim(); + if (!srv) return ''; + if (srv.includes('=')) { + const parts = srv.split(';').map((p) => p.trim()).filter(Boolean); + const httpsPart = parts.find((p) => p.toLowerCase().startsWith('https=')); + const httpPart = parts.find((p) => p.toLowerCase().startsWith('http=')); + const chosen = httpsPart || httpPart || ''; + srv = chosen.slice(chosen.indexOf('=') + 1).trim(); + } + if (!srv) return ''; + return /^https?:\/\//i.test(srv) ? srv : `http://${srv}`; +} + +export async function detectSystemHttpsProxy(targetHostname = '', { env = process.env, platform = process.platform } = {}) { + const noProxy = env?.NO_PROXY || env?.no_proxy || ''; + if (shouldCcProxyBypassHost(targetHostname, noProxy)) return ''; + const envProxy = String( + env?.HTTPS_PROXY || env?.https_proxy || env?.ALL_PROXY || env?.all_proxy || '' + ).trim(); + if (envProxy) return /^https?:\/\//i.test(envProxy) ? envProxy : `http://${envProxy}`; + if (platform !== 'win32') return ''; + try { + const { execFileSync } = await loadCcProxyNodeModules(); + const out = execFileSync( + 'reg', + ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'], + { encoding: 'utf8', timeout: 2500, windowsHide: true } + ); + if (!/ProxyEnable\s+REG_DWORD\s+0x1\b/i.test(out)) return ''; + const overrideMatch = out.match(/ProxyOverride\s+REG_SZ\s+([^\r\n]+)/i); + if (overrideMatch && shouldCcProxyBypassHost(targetHostname, overrideMatch[1])) { + return ''; + } + const serverMatch = out.match(/ProxyServer\s+REG_SZ\s+([^\r\n]+)/i); + return serverMatch ? parseWindowsProxyServerValue(serverMatch[1]) : ''; + } catch { + return ''; + } +} + +function parseCcProxyPositiveLimit(rawValue) { + const num = Number(rawValue); + return Number.isSafeInteger(num) && num > 0 ? num : null; +} + +/** + * 从模型目录(`GetAvailableModels` 或 `/v1internal:fetchAvailableModels` 的 `models` 映射)中 + * 提取各模型上游原始的 `CASCADE_USE_EXPERIMENT_CHECKPOINTER.max_token_limit`。 + * + * @param {Record|null|undefined} modelsMap + * @returns {Record} + */ +export function extractUpstreamCheckpointDefaults(modelsMap) { + const defaultsByModelId = {}; + if (!modelsMap || typeof modelsMap !== 'object' || Array.isArray(modelsMap)) { + return defaultsByModelId; + } + for (const entry of Object.values(modelsMap)) { + const modelId = typeof entry?.model === 'string' ? entry.model.trim() : ''; + if (!modelId) continue; + const rawStr = entry?.modelExperiments?.experiments?.[CC_PROXY_CHECKPOINTER_KEY]?.stringValue; + if (typeof rawStr !== 'string' || !rawStr.trim()) continue; + try { + const parsed = JSON.parse(rawStr); + const lim = parseCcProxyPositiveLimit(parsed?.max_token_limit ?? parsed?.maxTokenLimit); + if (lim !== null) { + defaultsByModelId[modelId] = lim; + } + } catch { + // 忽略非法 JSON + } + } + return defaultsByModelId; +} + +/** + * 按解析后的 `rulesByModelId`(键为 `MODEL_*` 枚举 ID,值为数值 token 上限或命名档位) + * 原地改写 `/v1internal:fetchAvailableModels` 响应体中的 `CASCADE_USE_EXPERIMENT_CHECKPOINTER`。 + * + * @param {any} fetchResp + * @param {Record} rulesByModelId + * @returns {{ modified: boolean, applied: Array<{ modelKey: string, modelId: string, prevLimit: number|null, nextRule: number|string }>, defaultsByModelId: Record }} + */ +export function rewriteFetchAvailableModelsPayload(fetchResp, rulesByModelId) { + const models = fetchResp?.models; + const defaultsByModelId = extractUpstreamCheckpointDefaults(models); + if ( + !models || + typeof models !== 'object' || + Array.isArray(models) || + !rulesByModelId || + typeof rulesByModelId !== 'object' + ) { + return { modified: false, applied: [], defaultsByModelId }; + } + + const applied = []; + for (const [modelKey, entry] of Object.entries(models)) { + if (!entry || typeof entry !== 'object') continue; + const modelId = typeof entry.model === 'string' ? entry.model.trim() : ''; + if (!modelId || !Object.prototype.hasOwnProperty.call(rulesByModelId, modelId)) continue; + const rule = rulesByModelId[modelId]; + const isNumericRule = typeof rule === 'number' && Number.isSafeInteger(rule) && rule > 0; + const isNamedRule = typeof rule === 'string' && rule.trim().length > 0; + if (!isNumericRule && !isNamedRule) continue; + + if (!entry.modelExperiments || typeof entry.modelExperiments !== 'object') { + entry.modelExperiments = {}; + } + if (!entry.modelExperiments.experiments || typeof entry.modelExperiments.experiments !== 'object') { + entry.modelExperiments.experiments = {}; + } + const expMap = entry.modelExperiments.experiments; + const ckKeys = Object.keys(expMap).filter( + (k) => k === CC_PROXY_CHECKPOINTER_KEY || k.startsWith(CC_PROXY_CHECKPOINTER_PREFIX) + ); + if (!ckKeys.includes(CC_PROXY_CHECKPOINTER_KEY)) { + ckKeys.unshift(CC_PROXY_CHECKPOINTER_KEY); + } + + const prevLimit = defaultsByModelId[modelId] ?? null; + if (isNumericRule) { + for (const ckKey of ckKeys) { + const prevRaw = expMap[ckKey]?.stringValue; + let ckObj = {}; + if (typeof prevRaw === 'string' && prevRaw.trim()) { + try { + const parsed = JSON.parse(prevRaw); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + ckObj = parsed; + } + } catch { + ckObj = {}; + } + } + ckObj.max_token_limit = String(rule); + delete ckObj.maxTokenLimit; + expMap[ckKey] = { + ...(expMap[ckKey] && typeof expMap[ckKey] === 'object' ? expMap[ckKey] : {}), + stringValue: JSON.stringify(ckObj), + }; + } + } else { + const variantKey = `${CC_PROXY_CHECKPOINTER_PREFIX}context-window_${rule.trim()}`; + const variantRaw = expMap[variantKey]?.stringValue; + if (typeof variantRaw !== 'string' || !variantRaw.trim()) { + continue; + } + for (const ckKey of ckKeys) { + expMap[ckKey] = { + ...(expMap[ckKey] && typeof expMap[ckKey] === 'object' ? expMap[ckKey] : {}), + stringValue: variantRaw, + }; + } + } + + if (Array.isArray(entry.ignoreExperiments)) { + entry.ignoreExperiments = entry.ignoreExperiments.filter( + (x) => + x !== CC_PROXY_CHECKPOINTER_KEY && + !String(x || '').startsWith(CC_PROXY_CHECKPOINTER_PREFIX) && + x !== 'checkpoint-variant' + ); + } + + applied.push({ modelKey, modelId, prevLimit, nextRule: rule }); + } + + return { modified: applied.length > 0, applied, defaultsByModelId }; +} + +function sanitizeCcProxyRules(rulesByModelId) { + const out = {}; + if (!rulesByModelId || typeof rulesByModelId !== 'object' || Array.isArray(rulesByModelId)) { + return out; + } + for (const [modelId, value] of Object.entries(rulesByModelId)) { + if (!modelId) continue; + if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) { + out[modelId] = value; + } else if (typeof value === 'string' && value.trim().length > 0) { + out[modelId] = value.trim(); + } + } + return out; +} + +function canonicalizeCcProxyRules(rules) { + const keys = Object.keys(rules).sort(); + return JSON.stringify(keys.map((k) => [k, rules[k]])); +} + +function decompressCcProxyBody(zlib, buf, encoding) { + const enc = String(encoding || '').toLowerCase(); + if (enc.includes('gzip')) return zlib.gunzipSync(buf); + if (enc.includes('deflate')) return zlib.inflateSync(buf); + if (enc.includes('br')) return zlib.brotliDecompressSync(buf); + return buf; +} + +function openCcProxyTunnelSocket(http, tls, targetHost, targetPort, proxyUrl) { + if (!proxyUrl) return Promise.resolve(null); + const parsedProxy = new URL(proxyUrl); + return new Promise((resolve, reject) => { + const connectReq = http.request({ + host: parsedProxy.hostname, + port: Number(parsedProxy.port || (parsedProxy.protocol === 'https:' ? 443 : 80)), + method: 'CONNECT', + path: `${targetHost}:${targetPort}`, + headers: { Host: `${targetHost}:${targetPort}` }, + }); + connectReq.on('connect', (res, socket) => { + if (res.statusCode !== 200) { + socket.destroy(); + reject(new Error(`Proxy CONNECT failed (${res.statusCode})`)); + return; + } + const tlsSocket = tls.connect({ socket, servername: targetHost }); + tlsSocket.once('secureConnect', () => resolve(tlsSocket)); + tlsSocket.once('error', reject); + }); + connectReq.on('error', reject); + connectReq.end(); + }); +} + +/** + * 创建本地 CloudCode 反代生命周期控制器。 + * + * @param {object} [options] + */ +export function createCloudCodeProxyController({ + callRpcFn = callLsRpc, + getEndpointFn = () => lsRuntimeEndpoint, + detectUpstreamFn = null, + detectProxyFn = null, + allowHttpUpstream = false, + allowTestEndpoint = false, + retryCooldownMs = CC_PROXY_RETRY_COOLDOWN_MS, +} = {}) { + let server = null; + let localUrl = ''; + let upstreamUrl = ''; + let lsSwitched = false; + let activeRules = {}; + let upstreamDefaults = {}; + let appliedSig = ''; + let lastFailedSig = ''; + let lastErrorAtMs = 0; + let cachedSysProxy = { url: '', checkedAtMs: 0, host: '' }; + let syncChain = Promise.resolve(); + + let status = { + state: 'disabled', // 'disabled' | 'active' | 'error' + active: false, + ruleCount: 0, + appliedModels: [], + upstreamUrl: '', + localUrl: '', + syncedAtMs: 0, + error: '', + }; + + function getStatus() { + return { + ...status, + appliedModels: [...status.appliedModels], + }; + } + + function getUpstreamDefaults() { + return { ...upstreamDefaults }; + } + + function seedUpstreamDefaultsFromCatalog(catalogModels) { + if (lsSwitched) return; + const extracted = extractUpstreamCheckpointDefaults(catalogModels); + if (Object.keys(extracted).length > 0) { + upstreamDefaults = { ...upstreamDefaults, ...extracted }; + } + } + + async function resolveUpstreamUrl() { + if (upstreamUrl && isValidUpstreamCloudCodeUrl(upstreamUrl, { allowHttp: allowHttpUpstream })) { + return upstreamUrl; + } + let detected = ''; + if (typeof detectUpstreamFn === 'function') { + detected = String((await detectUpstreamFn()) || '').trim(); + } else { + const mods = await loadCcProxyNodeModules().catch(() => null); + detected = detectUpstreamCloudCodeUrl({ + fsTailOps: mods + ? { openSync: mods.openSync, readSync: mods.readSync, closeSync: mods.closeSync } + : null, + }); + } + upstreamUrl = isValidUpstreamCloudCodeUrl(detected, { allowHttp: allowHttpUpstream }) + ? detected.replace(/\/+$/, '') + : DEFAULT_UPSTREAM_CLOUDCODE_URL; + return upstreamUrl; + } + + async function resolveSystemProxyForHost(targetHostname) { + const now = Date.now(); + if ( + cachedSysProxy.host === targetHostname && + now - cachedSysProxy.checkedAtMs < CC_PROXY_SYS_PROXY_CACHE_MS + ) { + return cachedSysProxy.url; + } + let proxyUrl = ''; + if (typeof detectProxyFn === 'function') { + proxyUrl = String((await detectProxyFn(targetHostname)) || '').trim(); + } else { + proxyUrl = await detectSystemHttpsProxy(targetHostname); + } + cachedSysProxy = { host: targetHostname, url: proxyUrl, checkedAtMs: now }; + return proxyUrl; + } + + async function closeProxyServer() { + const srv = server; + server = null; + localUrl = ''; + if (!srv) return; + try { + srv.closeAllConnections?.(); + } catch { + // Node <18.2 fallback + } + await new Promise((resolve) => { + try { + srv.close(() => resolve()); + } catch { + resolve(); + } + }); + } + + async function ensureProxyServerStarted() { + if (server && localUrl) return localUrl; + const { http, https, tls, zlib } = await loadCcProxyNodeModules(); + const targetBase = await resolveUpstreamUrl(); + const upstreamParsed = new URL(targetBase); + const isUpstreamHttps = upstreamParsed.protocol === 'https:'; + const upstreamPort = Number(upstreamParsed.port || (isUpstreamHttps ? 443 : 80)); + + const srv = http.createServer(async (req, res) => { + const reqUrl = req.url || '/'; + const isFetchModels = reqUrl.includes('fetchAvailableModels'); + try { + const fwdHeaders = { ...req.headers, host: upstreamParsed.host }; + if (isFetchModels) { + delete fwdHeaders['accept-encoding']; + } + let customSocket = null; + if (isUpstreamHttps) { + const proxyUrl = await resolveSystemProxyForHost(upstreamParsed.hostname); + if (proxyUrl) { + customSocket = await openCcProxyTunnelSocket( + http, + tls, + upstreamParsed.hostname, + upstreamPort, + proxyUrl + ); + } + } + const upOpts = { + hostname: upstreamParsed.hostname, + port: upstreamPort, + path: reqUrl, + method: req.method, + headers: fwdHeaders, + ...(customSocket ? { agent: false, createConnection: () => customSocket } : {}), + }; + + req.setTimeout?.(0); + const transport = isUpstreamHttps ? https : http; + const upReq = transport.request(upOpts, (upRes) => { + if (!isFetchModels || Number(upRes.statusCode || 0) !== 200) { + res.writeHead(upRes.statusCode || 502, upRes.headers); + res.flushHeaders?.(); + upRes.pipe(res); + return; + } + const chunks = []; + upRes.on('data', (chunk) => chunks.push(chunk)); + upRes.on('end', () => { + const rawBuf = Buffer.concat(chunks); + let outBuf = rawBuf; + const outHeaders = { ...upRes.headers }; + try { + const plain = decompressCcProxyBody(zlib, rawBuf, upRes.headers['content-encoding']); + const parsed = JSON.parse(plain.toString('utf8')); + const rewriteRes = rewriteFetchAvailableModelsPayload(parsed, activeRules); + if (Object.keys(rewriteRes.defaultsByModelId).length > 0) { + upstreamDefaults = { ...upstreamDefaults, ...rewriteRes.defaultsByModelId }; + } + if (rewriteRes.modified) { + const rewritten = Buffer.from(JSON.stringify(parsed), 'utf8'); + delete outHeaders['content-encoding']; + delete outHeaders['transfer-encoding']; + outHeaders['content-length'] = String(rewritten.length); + outBuf = rewritten; + status = { + ...status, + syncedAtMs: Date.now(), + }; + } + } catch { + // 解析失败时原样回传上游响应 + } + res.writeHead(upRes.statusCode || 200, outHeaders); + res.end(outBuf); + }); + upRes.on('error', (err) => { + if (!res.headersSent) res.writeHead(502); + res.end(`Upstream stream error: ${err.message}`); + }); + }); + + upReq.setTimeout?.(0); + upReq.on('error', (err) => { + if (!res.headersSent) res.writeHead(502); + res.end(`Proxy upstream error: ${err.message}`); + }); + req.pipe(upReq); + } catch (err) { + if (!res.headersSent) res.writeHead(502); + res.end(`Proxy setup error: ${err.message}`); + } + }); + + await new Promise((resolve, reject) => { + srv.once('error', reject); + srv.listen(0, '127.0.0.1', () => { + srv.off('error', reject); + resolve(); + }); + }); + srv.unref?.(); + const addrInfo = srv.address(); + const port = typeof addrInfo === 'object' && addrInfo ? Number(addrInfo.port || 0) : 0; + server = srv; + localUrl = `http://127.0.0.1:${port}`; + return localUrl; + } + + async function restoreLsCloudCodeUrl() { + if (!lsSwitched) return; + lsSwitched = false; + appliedSig = ''; + const targetRestore = upstreamUrl || DEFAULT_UPSTREAM_CLOUDCODE_URL; + try { + await callRpcFn('SetCloudCodeURL', { url: targetRestore }, 4000); + } catch { + // 忽略 LS 已退出或暂不可达时的还原异常 + } + } + + async function reconcileInternal({ enabled = false, rulesByModelId = {}, initialCatalogModels = null } = {}) { + if (initialCatalogModels) { + seedUpstreamDefaultsFromCatalog(initialCatalogModels); + } + const cleanRules = sanitizeCcProxyRules(rulesByModelId); + const ruleKeys = Object.keys(cleanRules); + const shouldEnable = Boolean(enabled && ruleKeys.length > 0); + const ep = getEndpointFn() || {}; + const hasUsableLs = + Boolean(ep.baseUrl) && (allowTestEndpoint || String(ep.addr || '') !== 'test.invalid'); + + if (!shouldEnable) { + activeRules = {}; + lastFailedSig = ''; + lastErrorAtMs = 0; + if (lsSwitched && hasUsableLs) { + await restoreLsCloudCodeUrl(); + } else { + lsSwitched = false; + appliedSig = ''; + } + await closeProxyServer(); + status = { + state: 'disabled', + active: false, + ruleCount: 0, + appliedModels: [], + upstreamUrl: upstreamUrl || '', + localUrl: '', + syncedAtMs: 0, + error: '', + }; + return getStatus(); + } + + if (!hasUsableLs) { + activeRules = cleanRules; + status = { + state: 'disabled', + active: false, + ruleCount: ruleKeys.length, + appliedModels: ruleKeys, + upstreamUrl: upstreamUrl || '', + localUrl: '', + syncedAtMs: 0, + error: '', + }; + return getStatus(); + } + + activeRules = cleanRules; + const epKey = `${String(ep.addr || ep.baseUrl)}|${String(ep.csrfToken || '')}`; + const rulesCanon = canonicalizeCcProxyRules(cleanRules); + const desiredSig = `${epKey}|${rulesCanon}`; + + if (lsSwitched && server && localUrl && appliedSig === desiredSig && status.state === 'active') { + return getStatus(); + } + + if ( + lastFailedSig === desiredSig && + lastErrorAtMs > 0 && + Date.now() - lastErrorAtMs < retryCooldownMs + ) { + return getStatus(); + } + + try { + const targetUpstream = await resolveUpstreamUrl(); + const listenUrl = await ensureProxyServerStarted(); + await callRpcFn('SetCloudCodeURL', { url: listenUrl }, 5000); + lsSwitched = true; + appliedSig = desiredSig; + lastFailedSig = ''; + lastErrorAtMs = 0; + status = { + state: 'active', + active: true, + ruleCount: ruleKeys.length, + appliedModels: ruleKeys, + upstreamUrl: targetUpstream, + localUrl: listenUrl, + syncedAtMs: Date.now(), + error: '', + }; + } catch (err) { + lastFailedSig = desiredSig; + lastErrorAtMs = Date.now(); + if (!lsSwitched) { + await closeProxyServer(); + } + status = { + state: 'error', + active: false, + ruleCount: ruleKeys.length, + appliedModels: ruleKeys, + upstreamUrl: upstreamUrl || '', + localUrl: lsSwitched ? localUrl : '', + syncedAtMs: status.syncedAtMs || 0, + error: String(err?.message || 'SetCloudCodeURL failed'), + }; + } + return getStatus(); + } + + function reconcile(opts) { + syncChain = syncChain.then(() => reconcileInternal(opts)).catch(() => getStatus()); + return syncChain; + } + + function stop() { + syncChain = syncChain + .then(async () => { + activeRules = {}; + lastFailedSig = ''; + lastErrorAtMs = 0; + const ep = getEndpointFn() || {}; + const hasUsableLs = + Boolean(ep.baseUrl) && (allowTestEndpoint || String(ep.addr || '') !== 'test.invalid'); + if (lsSwitched && hasUsableLs) { + await restoreLsCloudCodeUrl(); + } else { + lsSwitched = false; + appliedSig = ''; + } + await closeProxyServer(); + status = { + state: 'disabled', + active: false, + ruleCount: 0, + appliedModels: [], + upstreamUrl: upstreamUrl || '', + localUrl: '', + syncedAtMs: 0, + error: '', + }; + return getStatus(); + }) + .catch(() => getStatus()); + return syncChain; + } + + return { + reconcile, + stop, + getStatus, + getUpstreamDefaults, + seedUpstreamDefaultsFromCatalog, + }; +} + +let defaultCloudCodeProxyController = null; + +export function getDefaultCloudCodeProxy() { + if (!defaultCloudCodeProxyController) { + defaultCloudCodeProxyController = createCloudCodeProxyController(); + } + return defaultCloudCodeProxyController; +} + +export function getDefaultCloudCodeProxyStatus() { + if (!defaultCloudCodeProxyController) { + return { + state: 'disabled', + active: false, + ruleCount: 0, + appliedModels: [], + upstreamUrl: '', + localUrl: '', + syncedAtMs: 0, + error: '', + }; + } + return defaultCloudCodeProxyController.getStatus(); +} + +export function getDefaultCloudCodeUpstreamDefaults() { + if (!defaultCloudCodeProxyController) return {}; + return defaultCloudCodeProxyController.getUpstreamDefaults(); +} + +export function reconcileDefaultCloudCodeProxy(opts) { + return getDefaultCloudCodeProxy().reconcile(opts); +} + +export function stopDefaultCloudCodeProxy() { + if (!defaultCloudCodeProxyController) return Promise.resolve(); + return defaultCloudCodeProxyController.stop(); +} diff --git a/sidecars/panel/backend/context-windows.mjs b/sidecars/panel/backend/context-windows.mjs index eb806f9..14e5c15 100644 --- a/sidecars/panel/backend/context-windows.mjs +++ b/sidecars/panel/backend/context-windows.mjs @@ -122,18 +122,29 @@ export async function syncHostContextWindows( bootId, key = '__AGUsageMonitorContextWindows', fallbackRules = {}, - allowRemoteHost = false + allowRemoteHost = false, + overrideRules = null ) { let state = window[key]; const appConfig = window.__APP_CONFIG__; const csrfToken = appConfig?.csrfToken || state?.observedCsrfToken || ''; - const hasPrefs = Boolean(rules && Object.keys(rules).length > 0); + const hasOverrideMode = Boolean( + overrideRules && typeof overrideRules === 'object' && !Array.isArray(overrideRules) + ); + const safeOverride = hasOverrideMode ? overrideRules : null; + const hasPrefs = hasOverrideMode + ? Object.keys(safeOverride).length > 0 + : Boolean(rules && Object.keys(rules).length > 0); const safeFallback = fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules) ? fallbackRules : {}; const hasFallback = Object.keys(safeFallback).length > 0; - if (!hasPrefs || (!allowRemoteHost && appConfig?.isRemoteControl) || (!csrfToken && !hasFallback)) { + if ( + !hasPrefs || + (!allowRemoteHost && appConfig?.isRemoteControl) || + (!hasOverrideMode && !csrfToken && !hasFallback) + ) { state?.dispose(); return { attached: false, ruleCount: 0 }; } @@ -274,6 +285,11 @@ export async function syncHostContextWindows( clearTimeout(state.timer); state.timer = setTimeout(() => state.dispose(), 15000); + if (hasOverrideMode) { + state.rules = { ...safeOverride }; + return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length }; + } + if (!csrfToken) { state.rules = { ...safeFallback }; return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length }; @@ -324,8 +340,13 @@ export function createContextWindowSyncExpression( preferences, bootId, fallbackRules = {}, - allowRemoteHost = false + allowRemoteHost = false, + overrideRules = null ) { + const safeOverride = + overrideRules && typeof overrideRules === 'object' && !Array.isArray(overrideRules) + ? overrideRules + : null; return `(() => { ${isContextWindowModelId.toString()} ${isContextWindowSettingId.toString()} @@ -334,6 +355,6 @@ export function createContextWindowSyncExpression( ${getContextWindowGroups.toString()} ${resolveContextWindowOption.toString()} ${resolveContextWindowRules.toString()} - return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}, ${JSON.stringify(Boolean(allowRemoteHost))}); + return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}, ${JSON.stringify(Boolean(allowRemoteHost))}, ${JSON.stringify(safeOverride)}); })()`; } diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 1963974..d7e4d76 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -163,6 +163,8 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS, experimentalQuotaReservation: false, contextWindowRiskAccepted: false, + contextWindowMainEnabled: true, + contextWindowSwarmEnabled: false, modelContextWindows: Object.freeze({}), }); @@ -245,6 +247,8 @@ export function normalizeFullSettings(rawInput) { safeRaw.experimentalQuotaReservation ), contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true, + contextWindowMainEnabled: safeRaw.contextWindowMainEnabled !== false, + contextWindowSwarmEnabled: safeRaw.contextWindowSwarmEnabled === true, modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows), }; } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index b1ab10d..014ca31 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -46,6 +46,7 @@ import { import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './pricing-catalog.mjs'; import { buildOfficialQuotaPools } from './quota-pools.mjs'; import { updatePoolQuotaReservationEstimates } from './quota-reservation.mjs'; +import { getDefaultCloudCodeProxyStatus } from './cloudcode-proxy.mjs'; import { getDefaultWindowBridgeStatus } from './window-bridge.mjs'; import { aggregateConsumptionPresetBundle, @@ -2112,6 +2113,7 @@ export async function buildTelemetryPayloadInternal( }, uiBundleVersion, windowBridge: getDefaultWindowBridgeStatus(), + cloudCodeProxy: getDefaultCloudCodeProxyStatus(), cliStatusLine: getCliStatusLineRuntimeStatus(), settings: loadSettings(), contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => { diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index e85b579..e93e166 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -60,6 +60,7 @@ import { } from './endpoint-registry.mjs'; import { getLocalHubPorts } from './ls-discovery.mjs'; import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs'; +import { getDefaultCloudCodeProxy } from './cloudcode-proxy.mjs'; const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`; const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`; @@ -1092,8 +1093,14 @@ export function createWindowBridgeController(options) { WebSocketImpl = globalThis.WebSocket, bindRemoteRpcInvoker = false, getLocalHubPortsFn = getLocalHubPorts, + cloudCodeProxy = null, + manageCloudCodeProxy = false, + resolveLocalContextRulesFn = null, } = options || {}; + const activeCloudCodeProxy = + cloudCodeProxy || (manageCloudCodeProxy ? getDefaultCloudCodeProxy() : null); + function isPidAlive(pid) { if (!Number.isInteger(pid) || pid <= 0) return false; if (pid === process.pid) return true; @@ -1678,6 +1685,74 @@ export function createWindowBridgeController(options) { return hostLauncherPromise; } + async function resolveFallbackRulesForEndpoint(endpointId, contextWindows) { + if (!contextWindows || !Object.keys(contextWindows).length) { + return { verified: false, rules: {}, catalog: null }; + } + const epObj = + endpointId && endpointId !== LOCAL_ENDPOINT_ID + ? getRegisteredRemoteEndpoint(endpointId) + : null; + if (!epObj && typeof resolveLocalContextRulesFn === 'function') { + try { + const custom = await resolveLocalContextRulesFn(contextWindows); + if (custom && typeof custom === 'object') { + return { + verified: custom.verified !== false, + rules: custom.rules && typeof custom.rules === 'object' ? custom.rules : {}, + catalog: custom.catalog || null, + }; + } + } catch { + return { verified: false, rules: {}, catalog: null }; + } + } + if (!epObj && (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.addr === 'test.invalid')) { + return { verified: false, rules: {}, catalog: null }; + } + const cacheKey = epObj ? epObj.id : LOCAL_ENDPOINT_ID; + let cached = cachedBackendCtxModelsByEndpoint.get(cacheKey) || { + expiresAt: 0, + verified: false, + models: [], + catalog: null, + }; + if (Date.now() >= cached.expiresAt) { + try { + const [stRes, cat] = await Promise.all([ + callLsRpc('GetUserStatus', {}, 2000, epObj), + getContextModelCatalog(epObj), + ]); + const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs; + if (Array.isArray(cfgs)) { + cached = { + expiresAt: Date.now() + 10_000, + verified: true, + models: getContextWindowModels(cfgs, cat), + catalog: cat || null, + }; + cachedBackendCtxModelsByEndpoint.delete(cacheKey); + if (cachedBackendCtxModelsByEndpoint.size >= 16) { + const oldestKey = cachedBackendCtxModelsByEndpoint.keys().next().value; + if (oldestKey !== undefined) cachedBackendCtxModelsByEndpoint.delete(oldestKey); + } + cachedBackendCtxModelsByEndpoint.set(cacheKey, cached); + } + } catch { + // 忽略瞬态 LS 查询失败,保留上次缓存或交由调用方回退 + } + } + if (cached.verified) { + return { + verified: true, + rules: + cached.models.length > 0 ? resolveContextWindowRules(cached.models, contextWindows) : {}, + catalog: cached.catalog || null, + }; + } + return { verified: false, rules: {}, catalog: null }; + } + async function runSyncInternal({ forceReinject = false } = {}) { if (stopped) return { ok: false, reason: 'stopped' }; const bundleVersion = String(getBundleVersionFn() || ''); @@ -1694,10 +1769,15 @@ export function createWindowBridgeController(options) { const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar'); const contextWindows = curSettings.modelContextWindows || {}; const hasContextWindows = Object.keys(contextWindows).length > 0; + const ctxMainEnabled = curSettings.contextWindowMainEnabled !== false; + const ctxSwarmEnabled = curSettings.contextWindowSwarmEnabled === true; + const needsMainCdpContext = hasContextWindows && ctxMainEnabled; + const needsCloudCodeProxy = hasContextWindows && ctxSwarmEnabled; + const needsAnyCdpContext = hasContextWindows && (ctxMainEnabled || ctxSwarmEnabled); let leasedBySelf = false; let currentLease = null; - if ((enabled || hasContextWindows) && leaseFilePath && !forceReinject) { + if ((enabled || needsAnyCdpContext || needsCloudCodeProxy) && leaseFilePath && !forceReinject) { const lease = loadJson(leaseFilePath, null); currentLease = lease; const leasePid = Number(lease?.pid || 0); @@ -1747,8 +1827,25 @@ export function createWindowBridgeController(options) { }); } + let preResolvedLocalCtx = null; + if (activeCloudCodeProxy) { + if (needsCloudCodeProxy) { + preResolvedLocalCtx = await resolveFallbackRulesForEndpoint( + LOCAL_ENDPOINT_ID, + contextWindows + ); + await activeCloudCodeProxy.reconcile({ + enabled: true, + rulesByModelId: preResolvedLocalCtx.rules, + initialCatalogModels: preResolvedLocalCtx.catalog, + }); + } else { + await activeCloudCodeProxy.reconcile({ enabled: false, rulesByModelId: {} }); + } + } + const shouldCheckLaunchers = - (enabled || hasContextWindows) && + (enabled || needsMainCdpContext) && autoConfigureIdeArgv && (lastLauncherProvisionAtMs === 0 || Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs); @@ -1763,7 +1860,7 @@ export function createWindowBridgeController(options) { if (provPending) { await provPending.catch(() => {}); } - updateBridgeStatus(enabled || hasContextWindows ? 'no_devtools_port' : 'disabled', { + updateBridgeStatus(enabled || needsMainCdpContext ? 'no_devtools_port' : 'disabled', { enabled, leasedBySelf, bundleVersion, @@ -1781,7 +1878,7 @@ export function createWindowBridgeController(options) { if (provPending) { await provPending.catch(() => {}); } - updateBridgeStatus(enabled || hasContextWindows ? 'cdp_unreachable' : 'disabled', { + updateBridgeStatus(enabled || needsMainCdpContext ? 'cdp_unreachable' : 'disabled', { enabled, leasedBySelf, bundleVersion, @@ -1807,7 +1904,7 @@ export function createWindowBridgeController(options) { if ( !enabled && - !hasContextWindows && + !needsAnyCdpContext && !hadContextWindows && !hadInjectedTargets && !hadInjectedChatFrames && @@ -1947,58 +2044,24 @@ export function createWindowBridgeController(options) { } } - if (hasContextWindows || hadContextWindows) { - async function resolveFallbackRulesForEndpoint(endpointId) { - if (!hasContextWindows) return { verified: false, rules: {} }; - const epObj = endpointId && endpointId !== LOCAL_ENDPOINT_ID - ? getRegisteredRemoteEndpoint(endpointId) - : null; - if (!epObj && (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.addr === 'test.invalid')) { - return { verified: false, rules: {} }; - } - const cacheKey = epObj ? epObj.id : LOCAL_ENDPOINT_ID; - let cached = cachedBackendCtxModelsByEndpoint.get(cacheKey) || { - expiresAt: 0, - verified: false, - models: [], - }; - if (Date.now() >= cached.expiresAt) { - try { - const [stRes, cat] = await Promise.all([ - callLsRpc('GetUserStatus', {}, 2000, epObj), - getContextModelCatalog(epObj), - ]); - const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs; - if (Array.isArray(cfgs)) { - cached = { - expiresAt: Date.now() + 10_000, - verified: true, - models: getContextWindowModels(cfgs, cat), - }; - cachedBackendCtxModelsByEndpoint.delete(cacheKey); - if (cachedBackendCtxModelsByEndpoint.size >= 16) { - const oldestKey = cachedBackendCtxModelsByEndpoint.keys().next().value; - if (oldestKey !== undefined) cachedBackendCtxModelsByEndpoint.delete(oldestKey); - } - cachedBackendCtxModelsByEndpoint.set(cacheKey, cached); - } - } catch { - // 忽略瞬态 LS 查询失败,保留上次缓存或交由调用方回退 + if (needsAnyCdpContext || hadContextWindows) { + const localFallbackRes = needsAnyCdpContext + ? preResolvedLocalCtx || + (await resolveFallbackRulesForEndpoint(LOCAL_ENDPOINT_ID, contextWindows)) + : { verified: false, rules: {}, catalog: null }; + const localFallbackRules = localFallbackRes.rules; + const pinMainBackToDefaults = needsCloudCodeProxy && !ctxMainEnabled; + const pinBackRules = {}; + if (pinMainBackToDefaults) { + const upstreamDefaults = activeCloudCodeProxy?.getUpstreamDefaults?.() || {}; + for (const modelId of Object.keys(localFallbackRules)) { + const defaultLimit = Number(upstreamDefaults[modelId]); + if (Number.isSafeInteger(defaultLimit) && defaultLimit > 0) { + pinBackRules[modelId] = defaultLimit; } } - if (cached.verified) { - return { - verified: true, - rules: cached.models.length > 0 - ? resolveContextWindowRules(cached.models, contextWindows) - : {}, - }; - } - return { verified: false, rules: {} }; } - const localFallbackRes = await resolveFallbackRulesForEndpoint(LOCAL_ENDPOINT_ID); - const localFallbackRules = localFallbackRes.rules; const remoteFallbackRulesById = new Map(); const uniqueRemoteIds = new Set( targets @@ -2010,13 +2073,15 @@ export function createWindowBridgeController(options) { cachedBackendCtxModelsByEndpoint.delete(cachedKey); } } - await Promise.allSettled( - Array.from(uniqueRemoteIds).map(async (epId) => { - const res = await resolveFallbackRulesForEndpoint(epId); - // 仅在远端未能验证模型目录时安全回退本机规则;远端已验证但返回空规则时绝不套用本机高配规则 - remoteFallbackRulesById.set(epId, res.verified ? res.rules : localFallbackRules); - }) - ); + if (needsMainCdpContext) { + await Promise.allSettled( + Array.from(uniqueRemoteIds).map(async (epId) => { + const res = await resolveFallbackRulesForEndpoint(epId, contextWindows); + // 仅在远端未能验证模型目录时安全回退本机规则;远端已验证但返回空规则时绝不套用本机高配规则 + remoteFallbackRulesById.set(epId, res.verified ? res.rules : localFallbackRules); + }) + ); + } const ctxEvalTasks = []; const seenCtxUrls = new Set(); @@ -2025,31 +2090,59 @@ export function createWindowBridgeController(options) { const wsUrl = String(target.webSocketDebuggerUrl || '').trim(); if (!wsUrl || seenCtxUrls.has(wsUrl)) continue; seenCtxUrls.add(wsUrl); - const epFallback = - target.isRemoteEndpoint && target.endpointId - ? remoteFallbackRulesById.get(target.endpointId) || localFallbackRules - : localFallbackRules; - const expr = createContextWindowSyncExpression( - contextWindows, - contextWindowBootId, - epFallback, - true - ); + let expr; + if (!needsAnyCdpContext) { + expr = createContextWindowSyncExpression({}, contextWindowBootId, {}, true, null); + } else if (pinMainBackToDefaults) { + // 仅启用子代理与蜂群时:本地主窗口显式回填上游默认上限把主代理钉回默认;远端主窗口不注入覆盖 + expr = target.isRemoteEndpoint + ? createContextWindowSyncExpression({}, contextWindowBootId, {}, true, null) + : createContextWindowSyncExpression( + contextWindows, + contextWindowBootId, + pinBackRules, + true, + pinBackRules + ); + } else { + const epFallback = + target.isRemoteEndpoint && target.endpointId + ? remoteFallbackRulesById.get(target.endpointId) || localFallbackRules + : localFallbackRules; + expr = createContextWindowSyncExpression( + contextWindows, + contextWindowBootId, + epFallback, + true, + null + ); + } ctxEvalTasks.push(evaluateOnTarget(wsUrl, expr)); } - const ideChatExpr = createContextWindowSyncExpression( - contextWindows, - contextWindowBootId, - localFallbackRules, - false - ); + const ideChatExpr = !needsAnyCdpContext + ? createContextWindowSyncExpression({}, contextWindowBootId, {}, false, null) + : pinMainBackToDefaults + ? createContextWindowSyncExpression( + contextWindows, + contextWindowBootId, + pinBackRules, + false, + pinBackRules + ) + : createContextWindowSyncExpression( + contextWindows, + contextWindowBootId, + localFallbackRules, + false, + null + ); for (const chatUrl of collectAllChatDebuggerUrls(targets)) { if (!chatUrl || seenCtxUrls.has(chatUrl)) continue; seenCtxUrls.add(chatUrl); ctxEvalTasks.push(evaluateOnTarget(chatUrl, ideChatExpr)); } await Promise.allSettled(ctxEvalTasks); - hadContextWindows = hasContextWindows; + hadContextWindows = needsAnyCdpContext; } const disposeExpr = `(() => { @@ -2532,6 +2625,9 @@ export function createWindowBridgeController(options) { hadInjectedTargets = false; hadInjectedChatFrames = false; hadContextWindows = false; + if (activeCloudCodeProxy) { + await activeCloudCodeProxy.stop().catch(() => {}); + } if (bindRemoteRpcInvoker) { setRemoteWindowRpcInvoker(null); } @@ -2548,7 +2644,9 @@ export function createWindowBridgeController(options) { hadInjectedTargets = true; hadInjectedChatFrames = true; const cur = getSettingsFn() || {}; - const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; + const hasCtx = + Object.keys(cur.modelContextWindows || {}).length > 0 && + cur.contextWindowMainEnabled !== false; if (!hasCtx && autoConfigureIdeArgv) { launcherConfigured = false; hasReadOnlyShortcuts = false; @@ -2574,7 +2672,9 @@ export function createWindowBridgeController(options) { const cur = getSettingsFn() || {}; const mountMode = normalizeWindowMountMode(cur.windowMountMode, cur.enableWindowOverlay); const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar'); - const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; + const hasCtx = + Object.keys(cur.modelContextWindows || {}).length > 0 && + cur.contextWindowMainEnabled !== false; if (hasCtx) { lastLauncherProvisionAtMs = 0; } else if (!overlayOn && autoConfigureIdeArgv) { @@ -2640,6 +2740,7 @@ export function startDefaultWindowBridge(options) { defaultBridgeController = createWindowBridgeController({ leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'), bindRemoteRpcInvoker: true, + manageCloudCodeProxy: true, ...options, }); defaultBridgeController.start(); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 124feb7..cea9490 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index 107d2f8..82e83e5 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -242,5 +242,28 @@ if (isTestHarnessEnv) { ); } } else { + let processStopping = false; + async function handleProcessExitSignal(exitCode = 0) { + if (processStopping) return; + processStopping = true; + const forceTimer = setTimeout(() => process.exit(exitCode), 1800); + forceTimer.unref?.(); + try { + if (activeWorker) { + const w = activeWorker; + activeWorker = null; + await stopWorkerGracefully(w); + } + } finally { + clearTimeout(forceTimer); + process.exit(exitCode); + } + } + process.once('SIGTERM', () => { + void handleProcessExitSignal(0); + }); + process.once('SIGINT', () => { + void handleProcessExitSignal(0); + }); void ensureActiveWorker(); } diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 2cbf819..3aa9ebe 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -704,6 +704,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', 'settings.oth.ctxRiskAcceptBtn': 'I Understand the Risk, Unlock', 'settings.oth.ctxModel': 'Model', + 'settings.oth.ctxMainLabel': 'Main Agent', + 'settings.oth.ctxSwarmLabel': 'Subagents & Swarm', + 'settings.oth.ctxSwarmError': 'Local sync failed: {error}', 'settings.oth.ctxBaselineLabel': 'Context Window Limit', 'settings.oth.ctxChooseModel': 'Choose a model', 'settings.oth.ctxDefault': 'Follow host settings', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index eb000cd..5297365 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -704,6 +704,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', 'settings.oth.ctxRiskAcceptBtn': '我已知晓风险,继续使用', 'settings.oth.ctxModel': '模型', + 'settings.oth.ctxMainLabel': '主代理', + 'settings.oth.ctxSwarmLabel': '子代理与蜂群', + 'settings.oth.ctxSwarmError': '本地同步异常:{error}', 'settings.oth.ctxBaselineLabel': '上下文窗口上限', 'settings.oth.ctxChooseModel': '选择模型', 'settings.oth.ctxDefault': '跟随宿主设置', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 1ff307d..4920a91 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -540,6 +540,20 @@ export function isEquivalentTelemetry(prev, next) { if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; } + if ( + (pSet?.contextWindowMainEnabled !== false) !== (nSet?.contextWindowMainEnabled !== false) || + Boolean(pSet?.contextWindowSwarmEnabled) !== Boolean(nSet?.contextWindowSwarmEnabled) + ) { + return false; + } + if ( + (prev.cloudCodeProxy?.state || 'disabled') !== (next.cloudCodeProxy?.state || 'disabled') || + Number(prev.cloudCodeProxy?.ruleCount || 0) !== Number(next.cloudCodeProxy?.ruleCount || 0) || + String(prev.cloudCodeProxy?.error || '') !== String(next.cloudCodeProxy?.error || '') || + Number(prev.cloudCodeProxy?.syncedAtMs || 0) !== Number(next.cloudCodeProxy?.syncedAtMs || 0) + ) { + return false; + } if ( JSON.stringify(pSet?.modelContextWindows) !== JSON.stringify(nSet?.modelContextWindows) || JSON.stringify(prev.contextWindowModels) !== JSON.stringify(next.contextWindowModels) @@ -1856,6 +1870,12 @@ export async function saveSettingsPatch(patch) { if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowRiskAccepted')) { safePatch.contextWindowRiskAccepted = Boolean(safePatch.contextWindowRiskAccepted); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowMainEnabled')) { + safePatch.contextWindowMainEnabled = Boolean(safePatch.contextWindowMainEnabled); + } + if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowSwarmEnabled')) { + safePatch.contextWindowSwarmEnabled = Boolean(safePatch.contextWindowSwarmEnabled); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) { safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode); } diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 1b1c131..732b84e 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -793,6 +793,14 @@ user-select: none; } +.ctx-sync-status { + margin: -4px 0 2px; +} + +.ctx-sync-status.is-error { + color: var(--metric-warn); +} + .ctx-risk-mask { grid-area: 1 / 1; z-index: 5; diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index 52bcba5..dc27d12 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -118,7 +118,8 @@ export const SettingsView = defineComponent({ settings, telemetry.contextWindowModels || [], telemetry?.windowBridge, - telemetry?.hostPlatform + telemetry?.hostPlatform, + telemetry?.cloudCodeProxy ); } } else if (accountTab && settingsSubTab === 'account') { @@ -134,6 +135,7 @@ export const SettingsView = defineComponent({ (st) => ({ settings: st.telemetry?.settings, windowBridge: st.telemetry?.windowBridge, + cloudCodeProxy: st.telemetry?.cloudCodeProxy, cliStatusLine: st.telemetry?.cliStatusLine, hostPlatform: st.telemetry?.hostPlatform, cloudStatus: st.telemetry?.cloudStatus, diff --git a/sidecars/panel/src/views/settings/SettingsOtherTab.js b/sidecars/panel/src/views/settings/SettingsOtherTab.js index 79d74ab..3097c2c 100644 --- a/sidecars/panel/src/views/settings/SettingsOtherTab.js +++ b/sidecars/panel/src/views/settings/SettingsOtherTab.js @@ -77,8 +77,12 @@ export const SettingsOtherTab = defineComponent({ let draftExperimentalQuotaReservation = false; let draftContextRiskAccepted = false; let acceptingContextRisk = false; + let draftContextMainEnabled = true; + let draftContextSwarmEnabled = false; + let savingContextScope = false; let latestSettings = null; let latestWindowBridge = null; + let latestCloudCodeProxy = null; let latestHostPlatform = 'win32'; let contextWindowModels = []; let contextModelId = ''; @@ -358,10 +362,79 @@ export const SettingsOtherTab = defineComponent({ }, }); const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true }); + const ctxMainLabelEl = h('span', { + className: 'form-label', + text: t('settings.oth.ctxMainLabel'), + }); + const ctxMainToggle = SegmentedControl({ + modelValue: 'on', + ariaLabel: t('settings.oth.ctxMainLabel'), + options: getEnableToggleOptions(), + onUpdateModelValue: async (val) => { + if (!draftContextRiskAccepted || savingContextScope) return; + const nextEnabled = val === 'on'; + const prevEnabled = draftContextMainEnabled; + savingContextScope = true; + draftContextMainEnabled = nextEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: nextEnabled }; + contextFeedback = 'settings.saving'; + renderContextWindows(); + try { + await saveSettingsPatch({ contextWindowMainEnabled: nextEnabled }); + contextFeedback = 'settings.saved'; + } catch { + draftContextMainEnabled = prevEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: prevEnabled }; + contextFeedback = 'settings.saveFailed'; + } finally { + savingContextScope = false; + renderContextWindows(); + } + }, + }); + const ctxSwarmLabelEl = h('span', { + className: 'form-label', + text: t('settings.oth.ctxSwarmLabel'), + }); + const ctxSwarmToggle = SegmentedControl({ + modelValue: 'off', + ariaLabel: t('settings.oth.ctxSwarmLabel'), + options: getEnableToggleOptions(), + onUpdateModelValue: async (val) => { + if (!draftContextRiskAccepted || savingContextScope) return; + const nextEnabled = val === 'on'; + const prevEnabled = draftContextSwarmEnabled; + savingContextScope = true; + draftContextSwarmEnabled = nextEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: nextEnabled }; + contextFeedback = 'settings.saving'; + renderContextWindows(); + try { + await saveSettingsPatch({ contextWindowSwarmEnabled: nextEnabled }); + contextFeedback = 'settings.saved'; + } catch { + draftContextSwarmEnabled = prevEnabled; + latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: prevEnabled }; + contextFeedback = 'settings.saveFailed'; + } finally { + savingContextScope = false; + renderContextWindows(); + } + }, + }); + const ctxMainRow = h('div', { className: 'form-row' }, [ctxMainLabelEl, ctxMainToggle.el]); + const ctxSwarmRow = h('div', { className: 'form-row' }, [ctxSwarmLabelEl, ctxSwarmToggle.el]); + const ctxSyncStatusEl = h('span', { + className: 'settings-hint-text ctx-sync-status is-error', + hidden: true, + }); const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]); const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]); const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ ctxBridgeNotice.el, + ctxMainRow, + ctxSwarmRow, + ctxSyncStatusEl, ctxModelRow, ctxWindowRow, h('div', { className: 'form-row' }, [ctxHint]), @@ -440,8 +513,31 @@ export const SettingsOtherTab = defineComponent({ const saved = latestSettings?.modelContextWindows || {}; const wbState = String(latestWindowBridge?.state || '').trim(); const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable'; + const proxyState = String(latestCloudCodeProxy?.state || 'disabled'); + const isProxyActive = Boolean(latestCloudCodeProxy?.active && proxyState === 'active'); + + patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel')); + ctxMainToggle.setProps({ + modelValue: draftContextMainEnabled ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.ctxMainLabel'), + }); + patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel')); + ctxSwarmToggle.setProps({ + modelValue: draftContextSwarmEnabled ? 'on' : 'off', + options: getEnableToggleOptions(), + ariaLabel: t('settings.oth.ctxSwarmLabel'), + }); + + const syncErrorText = + draftContextSwarmEnabled && proxyState === 'error' && latestCloudCodeProxy?.error + ? t('settings.oth.ctxSwarmError', { error: latestCloudCodeProxy.error }) + : ''; + patchAttr(ctxSyncStatusEl, 'hidden', !syncErrorText); + patchText(ctxSyncStatusEl, syncErrorText); + ctxBridgeNotice.refs.update({ - visible: unlocked, + visible: unlocked && draftContextMainEnabled, windowBridge: latestWindowBridge, hostPlatform: latestHostPlatform, }); @@ -489,7 +585,13 @@ export const SettingsOtherTab = defineComponent({ else if (value) { const name = formatLimit(value); if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name }); - else if (isBridgeMissing) meta = t('settings.oth.ctxPendingBridge', { name }); + else if ( + isBridgeMissing && + draftContextMainEnabled && + !(draftContextSwarmEnabled && isProxyActive) + ) { + meta = t('settings.oth.ctxPendingBridge', { name }); + } else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) { meta = t('settings.oth.ctxConfiguredReported', { name, @@ -777,13 +879,15 @@ export const SettingsOtherTab = defineComponent({ settings, models = contextWindowModels, windowBridge = latestWindowBridge, - hostPlatform = latestHostPlatform + hostPlatform = latestHostPlatform, + cloudCodeProxy = latestCloudCodeProxy ) { if (!settings) return; latestSettings = settings; contextWindowModels = models; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; + if (cloudCodeProxy !== undefined) latestCloudCodeProxy = cloudCodeProxy; draftModelDisplayMode = normalizeClientModelDisplayMode( settings.modelDisplayMode, settings.showUpstreamModel @@ -795,6 +899,10 @@ export const SettingsOtherTab = defineComponent({ if (!acceptingContextRisk) { draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted); } + if (!savingContextScope) { + draftContextMainEnabled = settings.contextWindowMainEnabled !== false; + draftContextSwarmEnabled = settings.contextWindowSwarmEnabled === true; + } stepModelSelect.setProps({ modelValue: draftModelDisplayMode, options: getStepModelDisplayOptions(), @@ -870,6 +978,8 @@ export const SettingsOtherTab = defineComponent({ orchestratorIdSelect.destroy(); quotaReserveToggle.destroy(); ctxBridgeNotice.destroy(); + ctxMainToggle.destroy(); + ctxSwarmToggle.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); sessionMigrationCard.destroy(); @@ -883,6 +993,8 @@ export const SettingsOtherTab = defineComponent({ quotaReserveToggle, exportReserveLogBtn, ctxBridgeNotice, + ctxMainToggle, + ctxSwarmToggle, ctxModelSelect, ctxWindowSelect, sessionMigrationCard, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 43513c3..e86ae69 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -6276,6 +6276,14 @@ html[data-standalone="true"] .app-shell { user-select: none; } +.ctx-sync-status { + margin: -4px 0 2px; +} + +.ctx-sync-status.is-error { + color: var(--metric-warn); +} + .ctx-risk-mask { grid-area: 1 / 1; z-index: 5; diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 47e91c5..d2587d8 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -36,6 +36,7 @@ const BACKEND_MODULE_FILES = [ '../backend/pricing-catalog.mjs', '../backend/plugin-updater.mjs', '../backend/ls-rpc.mjs', + '../backend/cloudcode-proxy.mjs', '../backend/model-pricing.mjs', '../backend/quota-pools.mjs', '../backend/quota-reservation.mjs', @@ -209,6 +210,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,normalizeContextAgentMode,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); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,getDefaultCloudCodeProxyStatus,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,normalizeContextAgentMode,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/context-windows.test.mjs b/sidecars/panel/test/context-windows.test.mjs index 01320cc..297a2f4 100644 --- a/sidecars/panel/test/context-windows.test.mjs +++ b/sidecars/panel/test/context-windows.test.mjs @@ -1,8 +1,17 @@ import assert from 'node:assert/strict'; +import http from 'node:http'; import test from 'node:test'; import vm from 'node:vm'; import { createContextWindowSyncExpression } from '../backend/context-windows.mjs'; +import { + createCloudCodeProxyController, + extractUpstreamCheckpointDefaults, + isValidUpstreamCloudCodeUrl, + rewriteFetchAvailableModelsPayload, +} from '../backend/cloudcode-proxy.mjs'; +import { createWindowBridgeController } from '../backend/window-bridge.mjs'; import { backendHarness } from './backend-harness.mjs'; +import { createMockDom } from './mock-dom.mjs'; const argon = 'MODEL_PLACEHOLDER_M430'; const flash = 'MODEL_PLACEHOLDER_M431'; @@ -304,3 +313,474 @@ test('Issue #27: syncHostContextWindows falls back to backend pre-resolved rules } assert.equal(window.fetch, nativeFetch); }); + +test('cloudcode-proxy validates upstream URLs and rewrites checkpointer experiments cleanly', () => { + assert.equal(isValidUpstreamCloudCodeUrl('https://daily-cloudcode-pa.googleapis.com'), true); + assert.equal(isValidUpstreamCloudCodeUrl('https://cloudcode-pa.googleapis.com'), true); + assert.equal(isValidUpstreamCloudCodeUrl('http://127.0.0.1:18148'), false); + assert.equal(isValidUpstreamCloudCodeUrl('https://127.0.0.1:18148'), false); + assert.equal(isValidUpstreamCloudCodeUrl('https://localhost:443'), false); + assert.equal(isValidUpstreamCloudCodeUrl('http://daily-cloudcode-pa.googleapis.com'), false); + + const payload = { + models: { + 'gemini-4-carbon-high': { + model: carbon, + maxTokens: 1048576, + maxOutputTokens: 32768, + ignoreExperiments: ['CASCADE_USE_EXPERIMENT_CHECKPOINTER', 'checkpoint-variant', 'unrelated-flag'], + modelExperiments: { + experiments: { + CASCADE_USE_EXPERIMENT_CHECKPOINTER: { + stringValue: JSON.stringify({ + strategy: 'CHECKPOINT_STRATEGY_SAME_MODEL', + max_token_limit: '512000', + max_output_tokens: '32768', + }), + }, + 'CASCADE_USE_EXPERIMENT_CHECKPOINTER/claude-1m_840k': { + stringValue: JSON.stringify({ max_token_limit: '840000' }), + }, + }, + }, + }, + 'argon-named': { + model: argon, + maxTokens: 1048576, + maxOutputTokens: 32768, + modelExperiments: { + experiments: { + CASCADE_USE_EXPERIMENT_CHECKPOINTER: { + stringValue: JSON.stringify({ max_token_limit: '256000' }), + }, + 'CASCADE_USE_EXPERIMENT_CHECKPOINTER/context-window_900K': { + stringValue: JSON.stringify({ max_token_limit: '900000', enabled: true }), + }, + }, + }, + }, + 'untouched-flash': { + model: flash, + maxTokens: 1048576, + modelExperiments: { + experiments: { + CASCADE_USE_EXPERIMENT_CHECKPOINTER: { + stringValue: JSON.stringify({ max_token_limit: '128000' }), + }, + }, + }, + }, + }, + }; + + const beforeDefaults = extractUpstreamCheckpointDefaults(payload.models); + assert.deepEqual(beforeDefaults, { [carbon]: 512000, [argon]: 256000, [flash]: 128000 }); + + const res = rewriteFetchAvailableModelsPayload(payload, { [carbon]: 300000, [argon]: '900K' }); + assert.equal(res.modified, true); + assert.equal(res.applied.length, 2); + assert.deepEqual(res.defaultsByModelId, { [carbon]: 512000, [argon]: 256000, [flash]: 128000 }); + + const carbonMain = JSON.parse( + payload.models['gemini-4-carbon-high'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER + .stringValue + ); + const carbonVariant = JSON.parse( + payload.models['gemini-4-carbon-high'].modelExperiments.experiments[ + 'CASCADE_USE_EXPERIMENT_CHECKPOINTER/claude-1m_840k' + ].stringValue + ); + assert.equal(carbonMain.max_token_limit, '300000'); + assert.equal(carbonMain.strategy, 'CHECKPOINT_STRATEGY_SAME_MODEL'); + assert.equal(carbonVariant.max_token_limit, '300000'); + assert.equal(payload.models['gemini-4-carbon-high'].maxTokens, 1048576); + assert.deepEqual(payload.models['gemini-4-carbon-high'].ignoreExperiments, ['unrelated-flag']); + + const argonMain = JSON.parse( + payload.models['argon-named'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER.stringValue + ); + assert.equal(argonMain.max_token_limit, '900000'); + assert.equal(argonMain.enabled, true); + + const flashMain = JSON.parse( + payload.models['untouched-flash'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER.stringValue + ); + assert.equal(flashMain.max_token_limit, '128000'); +}); + +test('createCloudCodeProxyController proxies fetchAvailableModels, streams passthrough, and restores SetCloudCodeURL cleanly', async () => { + const upstreamHits = []; + const upstreamServer = http.createServer((req, res) => { + upstreamHits.push(req.url); + if (req.url?.includes('fetchAvailableModels')) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + models: { + 'gemini-4-carbon-high': { + model: carbon, + maxTokens: 1048576, + modelExperiments: { + experiments: { + CASCADE_USE_EXPERIMENT_CHECKPOINTER: { + stringValue: JSON.stringify({ max_token_limit: '512000' }), + }, + }, + }, + }, + }, + }) + ); + return; + } + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.write('chunk-1:'); + res.end('chunk-2'); + }); + await new Promise((resolve) => upstreamServer.listen(0, '127.0.0.1', resolve)); + const upstreamPort = upstreamServer.address().port; + const upstreamUrl = `http://127.0.0.1:${upstreamPort}`; + + const rpcCalls = []; + let failSetUrl = false; + const proxy = createCloudCodeProxyController({ + allowHttpUpstream: true, + allowTestEndpoint: true, + retryCooldownMs: 5000, + detectUpstreamFn: () => upstreamUrl, + detectProxyFn: async () => '', + getEndpointFn: () => ({ addr: '127.0.0.1:44444', baseUrl: 'http://127.0.0.1:44444', csrfToken: 'tok-1' }), + callRpcFn: async (method, body) => { + rpcCalls.push({ method, body }); + if (failSetUrl && method === 'SetCloudCodeURL') { + throw new Error('enterprise gateway pinned'); + } + return {}; + }, + }); + + try { + // 1. Enable with rule -> starts proxy & calls SetCloudCodeURL + const st1 = await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } }); + assert.equal(st1.state, 'active'); + assert.equal(st1.active, true); + assert.equal(st1.ruleCount, 1); + assert.equal(rpcCalls.length, 1); + assert.equal(rpcCalls[0].method, 'SetCloudCodeURL'); + assert.equal(rpcCalls[0].body.url, st1.localUrl); + + // 2. Fetch through proxy: /v1internal:fetchAvailableModels rewritten + upstream default captured + const modelsRes = await fetch(`${st1.localUrl}/v1internal:fetchAvailableModels`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: '{}', + }); + assert.equal(modelsRes.status, 200); + const modelsJson = await modelsRes.json(); + const rewrittenLimit = JSON.parse( + modelsJson.models['gemini-4-carbon-high'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER + .stringValue + ).max_token_limit; + assert.equal(rewrittenLimit, '300000'); + assert.deepEqual(proxy.getUpstreamDefaults(), { [carbon]: 512000 }); + + // 3. Non-intercepted path passes through verbatim + const streamRes = await fetch(`${st1.localUrl}/v1internal:streamGenerateContent`, { + method: 'POST', + body: '{}', + }); + assert.equal(await streamRes.text(), 'chunk-1:chunk-2'); + + // 4. Same reconcile is idempotent (no redundant SetCloudCodeURL) + await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } }); + assert.equal(rpcCalls.length, 1); + + // 5. Rule change re-triggers SetCloudCodeURL to flush LS cache + await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 256000 } }); + assert.equal(rpcCalls.length, 2); + assert.equal(rpcCalls[1].body.url, st1.localUrl); + + // 6. Disabling restores upstream URL and closes proxy + const stOff = await proxy.reconcile({ enabled: false, rulesByModelId: { [carbon]: 256000 } }); + assert.equal(stOff.state, 'disabled'); + assert.equal(stOff.active, false); + assert.equal(rpcCalls.length, 3); + assert.equal(rpcCalls[2].body.url, upstreamUrl); + + // 7. Error handling & cooldown + failSetUrl = true; + const stErr = await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 256000 } }); + assert.equal(stErr.state, 'error'); + assert.match(stErr.error, /enterprise gateway pinned/); + assert.equal(rpcCalls.length, 4); + await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 256000 } }); + assert.equal(rpcCalls.length, 4, 'cooldown skips immediate retry'); + } finally { + failSetUrl = false; + await proxy.stop(); + await new Promise((resolve) => upstreamServer.close(() => resolve())); + } + assert.ok(upstreamHits.some((u) => u.includes('fetchAvailableModels'))); + assert.ok(upstreamHits.some((u) => u.includes('streamGenerateContent'))); +}); + +test('independent Main Agent & Subagents/Swarm switches persist, pin back main defaults, and reconcile across all 4 combos', async () => { + // 1. Settings defaults, persistence, telemetry exposure, and factory reset + const h = backendHarness({ + availableModels, + userStatus: { cascadeModelConfigData: { clientModelConfigs: carbonModels } }, + }); + const initSettings = h.loadSettings(); + assert.equal(initSettings.contextWindowMainEnabled, true); + assert.equal(initSettings.contextWindowSwarmEnabled, false); + + const patchRes = h.executeSettingsAction({ + contextWindowMainEnabled: false, + contextWindowSwarmEnabled: true, + }); + assert.equal(patchRes.status, 200); + assert.equal(h.loadSettings().contextWindowMainEnabled, false); + assert.equal(h.loadSettings().contextWindowSwarmEnabled, true); + + const tele = await h.buildTelemetryPayloadInternal(''); + assert.equal(tele.settings.contextWindowMainEnabled, false); + assert.equal(tele.settings.contextWindowSwarmEnabled, true); + assert.equal(tele.cloudCodeProxy.state, 'disabled'); + + h.executeResetSettingsAction(); + assert.equal(h.loadSettings().contextWindowMainEnabled, true); + assert.equal(h.loadSettings().contextWindowSwarmEnabled, false); + + // 2. syncHostContextWindows pin-back mode overrides preferences with upstream default even when csrfToken exists + const sendPath = '/exa.language_server_pb.LanguageServerService/SendUserCascadeMessage'; + const host = 'https://127.0.0.1:26195'; + const nativeFetch = async (_url, init) => init; + class WebSocket { + constructor(url) { + this.url = url; + } + send(data) { + return data; + } + } + const win = { + location: new URL(host), + fetch: nativeFetch, + WebSocket, + __APP_CONFIG__: { csrfToken: 'pin-test-token' }, + }; + const ctx = vm.createContext({ + window: win, + URL, + TextEncoder, + TextDecoder, + Headers, + Uint8Array, + AbortSignal, + setTimeout, + clearTimeout, + }); + try { + const syncOut = await vm.runInContext( + createContextWindowSyncExpression( + { [carbonGroup]: '300000' }, + 'pin-boot', + { [carbon]: 512000 }, + true, + { [carbon]: 512000 } + ), + ctx + ); + assert.deepEqual({ ...syncOut }, { attached: true, ruleCount: 1 }); + const reqPayload = { + cascadeConfig: { + plannerConfig: { planModel: carbon }, + checkpointConfig: {}, + }, + }; + const out = await win.fetch(host + sendPath, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(reqPayload), + }); + assert.equal( + JSON.parse(out.body).cascadeConfig.checkpointConfig.maxTokenLimit, + 512000, + 'pin-back mode forces main agent back to upstream default limit' + ); + } finally { + await vm.runInContext(createContextWindowSyncExpression({}, 'pin-boot', {}, true, null), ctx); + } + assert.equal(win.fetch, nativeFetch); + + // 3. Window bridge reconciles CloudCode proxy even without CDP ports when Swarm toggle is enabled + const proxyLog = []; + let proxyStopped = false; + let currentSettings = { + enableWindowOverlay: false, + windowMountMode: 'sidebar', + modelContextWindows: { [carbonGroup]: '300000' }, + contextWindowMainEnabled: false, + contextWindowSwarmEnabled: true, + }; + const mockCloudCodeProxy = { + async reconcile(opts) { + proxyLog.push(opts); + return { state: opts.enabled ? 'active' : 'disabled', active: Boolean(opts.enabled) }; + }, + getUpstreamDefaults: () => ({ [carbon]: 512000 }), + async stop() { + proxyStopped = true; + }, + }; + const bridgeCtrl = createWindowBridgeController({ + handleApiRequest: async () => ({ status: 200, body: '{}' }), + readAssetFn: async () => '', + getSettingsFn: () => currentSettings, + env: {}, + homeDir: '/nonexistent-home-for-test', + autoConfigureIdeArgv: false, + cloudCodeProxy: mockCloudCodeProxy, + resolveLocalContextRulesFn: async () => ({ + verified: true, + rules: { [carbon]: 300000 }, + catalog: availableModels, + }), + }); + await bridgeCtrl.syncAllWindows(); + assert.equal(proxyLog.length, 1); + assert.equal(proxyLog[0].enabled, true); + assert.deepEqual(proxyLog[0].rulesByModelId, { [carbon]: 300000 }); + + // Turning off Swarm switch disables CloudCode proxy + currentSettings = { ...currentSettings, contextWindowSwarmEnabled: false }; + await bridgeCtrl.syncAllWindows(); + assert.equal(proxyLog.length, 2); + assert.equal(proxyLog[1].enabled, false); + + await bridgeCtrl.stop(); + assert.equal(proxyStopped, true); +}); + +test('SettingsOtherTab renders independent Main Agent and Subagents/Swarm switches with live sync feedback', async () => { + const { document } = createMockDom(); + const origDocument = globalThis.document; + const origWindow = globalThis.window; + const origFetch = globalThis.fetch; + const savedPatches = []; + + globalThis.document = document; + globalThis.window = { + location: { origin: 'http://127.0.0.1:41234', href: 'http://127.0.0.1:41234/' }, + addEventListener() {}, + removeEventListener() {}, + }; + globalThis.fetch = async (url, init = {}) => { + if (String(url).includes('/api/settings') && init.method === 'POST') { + const patch = JSON.parse(init.body || '{}'); + savedPatches.push(patch); + return { ok: true, json: async () => ({ ...patch }) }; + } + return { ok: true, json: async () => ({}) }; + }; + + try { + const [{ setI18nLanguage }, { SettingsOtherTab }] = await Promise.all([ + import('../src/i18n/index.js'), + import('../src/views/settings/SettingsOtherTab.js'), + ]); + setI18nLanguage('zh-CN'); + const tab = SettingsOtherTab({ onLayoutChange: () => {} }); + const mockModels = [ + { + id: carbonGroup, + label: 'Gemini 4 Carbon', + members: [carbon], + capacity: 786432, + options: [{ name: '300000', tokens: 300000 }], + }, + ]; + tab.refs.renderSettings( + { + contextWindowRiskAccepted: true, + contextWindowMainEnabled: true, + contextWindowSwarmEnabled: true, + modelContextWindows: { [carbonGroup]: '300000' }, + }, + mockModels, + { state: 'active' }, + 'win32', + { state: 'active', active: true, ruleCount: 1, error: '' } + ); + + const statusEl = tab.el.querySelector('.ctx-sync-status'); + assert.ok(statusEl); + assert.equal(statusEl.hasAttribute('hidden'), true, 'no extra status clutter when active'); + + // Toggle Main Agent off -> persists patch + const mainOffBtn = tab.refs.ctxMainToggle.el.querySelectorAll('button')[1]; + mainOffBtn.dispatchEvent({ + type: 'click', + target: mainOffBtn, + currentTarget: mainOffBtn, + stopPropagation() {}, + preventDefault() {}, + }); + await new Promise((r) => setTimeout(r, 15)); + assert.deepEqual(savedPatches[0], { contextWindowMainEnabled: false }); + + // Toggle Subagents & Swarm off -> persists patch + const swarmOffBtn = tab.refs.ctxSwarmToggle.el.querySelectorAll('button')[1]; + swarmOffBtn.dispatchEvent({ + type: 'click', + target: swarmOffBtn, + currentTarget: swarmOffBtn, + stopPropagation() {}, + preventDefault() {}, + }); + await new Promise((r) => setTimeout(r, 15)); + assert.deepEqual(savedPatches[1], { contextWindowSwarmEnabled: false }); + + // Error state surfaces cleanly + tab.refs.renderSettings( + { + contextWindowRiskAccepted: true, + contextWindowMainEnabled: false, + contextWindowSwarmEnabled: true, + modelContextWindows: { [carbonGroup]: '300000' }, + }, + mockModels, + { state: 'no_devtools_port' }, + 'win32', + { state: 'error', active: false, ruleCount: 1, error: 'gateway pinned' } + ); + assert.equal(statusEl.hasAttribute('hidden'), false); + assert.match(statusEl.textContent, /gateway pinned/); + + // English labels refresh cleanly + setI18nLanguage('en-US'); + tab.refs.refreshLabels(); + assert.match(statusEl.textContent, /Local sync failed: gateway pinned/); + + // Both off -> stays clean without extra small-text clutter + tab.refs.renderSettings( + { + contextWindowRiskAccepted: true, + contextWindowMainEnabled: false, + contextWindowSwarmEnabled: false, + modelContextWindows: { [carbonGroup]: '300000' }, + }, + mockModels, + { state: 'active' }, + 'win32', + { state: 'disabled', active: false, ruleCount: 0, error: '' } + ); + assert.equal(statusEl.hasAttribute('hidden'), true); + + tab.destroy(); + } finally { + globalThis.document = origDocument; + globalThis.window = origWindow; + globalThis.fetch = origFetch; + } +}); From 8b9fe3d92f7e3bd452ecbe050cb06ab62c358ced Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 22 Nov 2026 21:51:55 +0900 Subject: [PATCH 23/31] fix(panel): format boundary 0.0% and 100.0% percentages as 0% and 100% --- sidecars/panel/app.js | 104 +++++++++++------- sidecars/panel/index.html | 4 +- .../components/charts/SessionStepCharts.js | 7 +- .../src/components/ui/ContextSegmentMeter.js | 4 +- .../components/widgets/QuotaPoolsWidget.js | 19 ++-- sidecars/panel/src/core/formatters.js | 20 ++++ sidecars/panel/src/core/reportExporter.js | 31 +++--- sidecars/panel/src/core/stepInspector.js | 9 +- sidecars/panel/src/views/ConsumptionView.js | 21 ++-- sidecars/panel/src/views/StepsDetailView.js | 3 +- sidecars/panel/test/quota-pools.test.mjs | 15 +++ 11 files changed, 155 insertions(+), 82 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 1b1b294..b632dd6 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -4014,7 +4014,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { +const { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -4042,6 +4042,26 @@ function formatCachePct(value) { return `${num}%`; } +/** + * 格式化百分比数值文本:常规值保留 1 位小数,将边界值 `0.0` / `100.0` 收口为整数 `0` / `100`。 + * + * @param {number|string|null|undefined} value + * @param {{ withSymbol?: boolean }} [options] + * @returns {string} + */ +function formatPctNumber(value, { withSymbol = false } = {}) { + const num = Number(value); + if (!Number.isFinite(num)) return withSymbol ? '0%' : '0'; + const rounded = Math.round(num * 10) / 10; + const str = + Math.abs(rounded) < 1e-9 + ? '0' + : Math.abs(rounded - 100) < 1e-9 + ? '100' + : rounded.toFixed(1); + return withSymbol ? `${str}%` : str; +} + function getSpeedToneClass(tokPerSec) { return `tone-${classifySpeedTier(tokPerSec)}`; } @@ -5319,7 +5339,7 @@ function buildDeterministicModelColorMap(models = []) { return colorMap; } -return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; +return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); // --- src/core/stepInspector.js --- @@ -5581,10 +5601,12 @@ function buildStepDiagnosticMarkdown( const promptTok = Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0); const cachePct = st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct)) - ? `${Number(st.cacheHitPct).toFixed(1)}%` + ? formatPctNumber(st.cacheHitPct, { withSymbol: true }) : promptTok > 0 - ? `${((Number(st.cacheReadTokens || 0) / promptTok) * 100).toFixed(1)}%` - : '0.0%'; + ? formatPctNumber((Number(st.cacheReadTokens || 0) / promptTok) * 100, { + withSymbol: true, + }) + : '0%'; const ctxTok = Number(st.contextTokens || promptTok + Number(st.outputTokens || 0)); const ctxDelta = prevContextTokens != null && ctxTok > 0 @@ -6962,10 +6984,10 @@ function buildStepsCsv(steps, { displaySettings = {}, includeBom = true } = {}) const promptTok = inTok + cacheTok; const cachePct = st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct)) - ? Number(st.cacheHitPct).toFixed(1) + ? formatPctNumber(st.cacheHitPct) : promptTok > 0 - ? ((cacheTok / promptTok) * 100).toFixed(1) - : '0.0'; + ? formatPctNumber((cacheTok / promptTok) * 100) + : '0'; const ctxTok = Number(st.contextTokens || promptTok + outTok); const anomCount = Number(st.anomaly?.count || 0); const anomDesc = @@ -7226,7 +7248,7 @@ function buildStepsMarkdownReport( const agg = summarizeStepsForExport(list, displaySettings); const totalTok = agg.sumIn + agg.sumCache + agg.sumOut; - const cacheHitPct = (computeCacheHitRatio(agg.sumIn, agg.sumCache) * 100).toFixed(1); + const cacheHitPct = formatPctNumber(computeCacheHitRatio(agg.sumIn, agg.sumCache) * 100); const avgTps = agg.tpsCnt > 0 ? formatSpeedMetric(agg.tpsSum / agg.tpsCnt, ' tok/s') : '—'; const avgTtft = agg.ttftCnt > 0 ? formatMetric(agg.ttftSum / agg.ttftCnt, 's') : '—'; const heading = title @@ -7267,7 +7289,9 @@ function buildStepsMarkdownReport( ); for (const m of agg.sortedModels) { const mTotal = m.inTok + m.cacheTok + m.outTok; - const mCache = `${(computeCacheHitRatio(m.inTok, m.cacheTok) * 100).toFixed(1)}%`; + const mCache = formatPctNumber(computeCacheHitRatio(m.inTok, m.cacheTok) * 100, { + withSymbol: true, + }); const mTps = m.tpsCnt > 0 ? formatSpeedMetric(m.tpsSum / m.tpsCnt, ' tok/s') : '—'; lines.push( `| ${escapeMdCell(m.label)} | ${m.calls} | ${formatTokensPrecise(mTotal)} | ${mCache} | ${mTps} | ${formatUsd(m.cost, { precise: m.cost > 0 && m.cost < 0.1 })} |` @@ -7368,7 +7392,7 @@ function buildConsumptionCsv( Number(acc.cacheReadTokens || 0), Number(acc.outputTokens || 0), Number(acc.totalTokens || 0), - Number(acc.cacheHitPct || 0).toFixed(1), + formatPctNumber(acc.cacheHitPct || 0), Number(acc.costUsd || 0).toFixed(4), `saved_usd=${Number(acc.savedCostUsd || 0).toFixed(4)}`, ]), @@ -7384,7 +7408,7 @@ function buildConsumptionCsv( Number(m.cacheReadTokens || 0), Number(m.outputTokens || 0), Number(m.totalTokens || 0), - Number(m.cacheHitPct || 0).toFixed(1), + formatPctNumber(m.cacheHitPct || 0), Number(m.costUsd || 0).toFixed(4), m.avgTokPerSec != null ? `avg_tps=${Number(m.avgTokPerSec).toFixed(1)}` : '', ]) @@ -7401,7 +7425,7 @@ function buildConsumptionCsv( Number(w.cacheReadTokens || 0), Number(w.responseTokens || 0) + Number(w.thinkingTokens || 0), Number(w.totalTokens || 0), - Number(w.cacheHitPct || 0).toFixed(1), + formatPctNumber(w.cacheHitPct || 0), Number(w.costUsd || 0).toFixed(4), `sessions=${Number(w.sessionCount || 0)}`, ]) @@ -7418,7 +7442,7 @@ function buildConsumptionCsv( Number(c.cacheReadTokens || 0), Number(c.responseTokens || 0) + Number(c.thinkingTokens || 0), Number(c.totalTokens || 0), - Number(c.cacheHitPct || 0).toFixed(1), + formatPctNumber(c.cacheHitPct || 0), Number(c.costUsd || 0).toFixed(4), c.sourceName || c.appSource || '', ]) @@ -7966,14 +7990,14 @@ function buildConsumptionMarkdownReport( '', `- **Total Tokens**: ${formatTokensPrecise(acc.totalTokens || 0)} (${Number(acc.calls || 0)} calls)`, `- **Est. Cost**: ${formatUsd(acc.costUsd || 0)} (Cache Saved ${formatUsd(acc.savedCostUsd || 0)})`, - `- **Cache Hit Rate**: ${Number(acc.cacheHitPct || 0).toFixed(1)}% (Input ${formatTokensPrecise(acc.inputTokens || 0)} / Cache ${formatTokensPrecise(acc.cacheReadTokens || 0)} / Output ${formatTokensPrecise(acc.outputTokens || 0)})`, + `- **Cache Hit Rate**: ${formatPctNumber(acc.cacheHitPct || 0, { withSymbol: true })} (Input ${formatTokensPrecise(acc.inputTokens || 0)} / Cache ${formatTokensPrecise(acc.cacheReadTokens || 0)} / Output ${formatTokensPrecise(acc.outputTokens || 0)})`, ] : [ `# 用量统计报告 · ${rangeLabel}`, '', `- **总 Token**: ${formatTokensPrecise(acc.totalTokens || 0)}(共 ${Number(acc.calls || 0)} 次调用)`, `- **预估费用**: ${formatUsd(acc.costUsd || 0)}(缓存节省 ${formatUsd(acc.savedCostUsd || 0)})`, - `- **缓存命中率**: ${Number(acc.cacheHitPct || 0).toFixed(1)}%(新输入 ${formatTokensPrecise(acc.inputTokens || 0)} / 缓存读取 ${formatTokensPrecise(acc.cacheReadTokens || 0)} / 输出 ${formatTokensPrecise(acc.outputTokens || 0)})`, + `- **缓存命中率**: ${formatPctNumber(acc.cacheHitPct || 0, { withSymbol: true })}(新输入 ${formatTokensPrecise(acc.inputTokens || 0)} / 缓存读取 ${formatTokensPrecise(acc.cacheReadTokens || 0)} / 输出 ${formatTokensPrecise(acc.outputTokens || 0)})`, ]; if (models.length > 0) { @@ -7988,7 +8012,7 @@ function buildConsumptionMarkdownReport( ); for (const m of models) { lines.push( - `| ${escapeMdCell(m.displayText || m.label || m.shortName)} | ${Number(m.calls || 0)} | ${formatTokensPrecise(m.totalTokens || 0)} | ${Number(m.cacheHitPct || 0).toFixed(1)}% | ${m.avgTokPerSec != null ? formatSpeedMetric(m.avgTokPerSec, ' tok/s') : '—'} | ${formatUsd(m.costUsd || 0)} |` + `| ${escapeMdCell(m.displayText || m.label || m.shortName)} | ${Number(m.calls || 0)} | ${formatTokensPrecise(m.totalTokens || 0)} | ${formatPctNumber(m.cacheHitPct || 0, { withSymbol: true })} | ${m.avgTokPerSec != null ? formatSpeedMetric(m.avgTokPerSec, ' tok/s') : '—'} | ${formatUsd(m.costUsd || 0)} |` ); } } @@ -8005,7 +8029,7 @@ function buildConsumptionMarkdownReport( ); for (const w of workspaces) { lines.push( - `| ${escapeMdCell(w.label || w.workspacePath || (en ? 'Unbound' : '未绑定工作区'))} | ${Number(w.sessionCount || 0)} | ${Number(w.calls || 0)} | ${formatTokensPrecise(w.totalTokens || 0)} | ${Number(w.cacheHitPct || 0).toFixed(1)}% | ${formatUsd(w.costUsd || 0)} |` + `| ${escapeMdCell(w.label || w.workspacePath || (en ? 'Unbound' : '未绑定工作区'))} | ${Number(w.sessionCount || 0)} | ${Number(w.calls || 0)} | ${formatTokensPrecise(w.totalTokens || 0)} | ${formatPctNumber(w.cacheHitPct || 0, { withSymbol: true })} | ${formatUsd(w.costUsd || 0)} |` ); } } @@ -8022,7 +8046,7 @@ function buildConsumptionMarkdownReport( ); for (const c of sessions.slice(0, 8)) { lines.push( - `| ${escapeMdCell(c.title || c.cascadeId)} | ${Number(c.calls || 0)} | ${formatTokensPrecise(c.totalTokens || 0)} | ${Number(c.cacheHitPct || 0).toFixed(1)}% | ${formatUsd(c.costUsd || 0)} |` + `| ${escapeMdCell(c.title || c.cascadeId)} | ${Number(c.calls || 0)} | ${formatTokensPrecise(c.totalTokens || 0)} | ${formatPctNumber(c.cacheHitPct || 0, { withSymbol: true })} | ${formatUsd(c.costUsd || 0)} |` ); } } @@ -12815,7 +12839,7 @@ const ContextSegmentMeter = defineComponent({ slotEl, 'title', isActive - ? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${item.pct.toFixed(1)}%)` + ? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${formatPctNumber(item.pct, { withSymbol: true })})` : null ); } @@ -14856,7 +14880,7 @@ function formatYAxisTick(metric, val, step) { return step >= 1 ? `${Math.round(val)}s` : `${val.toFixed(1)}s`; } if (metric === 'cache') { - return step >= 1 ? `${Math.round(val)}%` : `${val.toFixed(1)}%`; + return step >= 1 ? `${Math.round(val)}%` : formatPctNumber(val, { withSymbol: true }); } if (metric === 'cost') { if (step >= 1) return `$${Math.round(val)}`; @@ -14931,7 +14955,7 @@ function formatChartMetricValue(metric, val) { case 'ttft': return formatMetric(val, 's'); case 'cache': - return `${val.toFixed(1)}%`; + return formatPctNumber(val, { withSymbol: true }); case 'cost': return formatUsd(val, { precise: true }); default: @@ -14950,7 +14974,7 @@ function formatChartMetricCompact(metric, val) { case 'ttft': return formatMetric(val, 's'); case 'cache': - return `${val.toFixed(1)}%`; + return formatPctNumber(val, { withSymbol: true }); case 'cost': return formatUsd(val, { precise: true }); default: @@ -18345,8 +18369,8 @@ function syncQuotaWindowMeter({ const resetStr = hasData ? formatCountdown(resetTime) : ''; if (hasData && rsvVal > 0) { - const rsvStr = rsvVal.toFixed(1); - const actualStr = actualVal.toFixed(1); + const rsvStr = formatPctNumber(rsvVal); + const actualStr = formatPctNumber(actualVal); const leases = Math.max(1, Number(leaseCount) || 1); const tipText = leases >= 2 @@ -18354,13 +18378,13 @@ function syncQuotaWindowMeter({ : t('quota.reservedTip', { rsv: rsvStr, actual: actualStr }); patchText( metaBeforeEl, - t('quota.usedBeforeReserved', { reset: resetStr, used: usedVal.toFixed(1) }) + t('quota.usedBeforeReserved', { reset: resetStr, used: formatPctNumber(usedVal) }) ); metaReservedEl.hidden = false; patchText(metaReservedEl, t('quota.reservedTag', { rsv: rsvStr })); patchAttr(metaReservedEl, 'title', tipText); metaAfterEl.hidden = false; - patchText(metaAfterEl, t('quota.usedAfterReserved', { rem: remVal.toFixed(1) })); + patchText(metaAfterEl, t('quota.usedAfterReserved', { rem: formatPctNumber(remVal) })); patchAttr(trackEl, 'title', tipText); const actualWidth = +Math.min(100, actualVal).toFixed(2); const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); @@ -18373,8 +18397,8 @@ function syncQuotaWindowMeter({ hasData ? t('quota.usedAndLeft', { reset: resetStr, - used: usedVal.toFixed(1), - rem: remVal.toFixed(1), + used: formatPctNumber(usedVal), + rem: formatPctNumber(remVal), }) : fallbackMetaText ); @@ -29340,7 +29364,7 @@ const ConsumptionView = defineComponent({ responseTokens, outputTokens: responseTokens + thinkingTokens, tokText: formatTokensPrecise(tok), - pctText: `${pct.toFixed(1)}%`, + pctText: formatPctNumber(pct, { withSymbol: true }), color, isOther: false, }; @@ -29377,7 +29401,7 @@ const ConsumptionView = defineComponent({ responseTokens: otherResp, outputTokens: otherResp + otherThink, tokText: formatTokensPrecise(otherTok), - pctText: `${otherPct.toFixed(1)}%`, + pctText: formatPctNumber(otherPct, { withSymbol: true }), color: 'var(--cons-other-seg)', isOther: true, }); @@ -29541,7 +29565,7 @@ const ConsumptionView = defineComponent({ : promptTok > 0 && Number(item.cacheReadTokens || 0) > 0 ? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1) : 0; - const cachePctStr = cachePctVal.toFixed(1); + const cachePctStr = formatPctNumber(cachePctVal); const effCostPer1M = !isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null; const outTok = Number( @@ -29555,7 +29579,7 @@ const ConsumptionView = defineComponent({ const barPct = costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, `${costShare.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true })); patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal)); patchText(refs.costEl, costText); @@ -29630,7 +29654,7 @@ const ConsumptionView = defineComponent({ callsBase > 0 && callsCount > 0 ? Math.min(100, Math.max(1, (callsCount / callsBase) * 100)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, `${callsShare.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); patchText(refs.costEl, t('cons.callsCount', { calls: callsCount })); @@ -29670,7 +29694,7 @@ const ConsumptionView = defineComponent({ grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); patchText(refs.costEl, costText); @@ -29844,7 +29868,7 @@ const ConsumptionView = defineComponent({ const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; const scaleRatio = grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; - patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); const costVal = Number(item.costUsd || 0); @@ -30095,7 +30119,7 @@ const ConsumptionView = defineComponent({ ? Math.min(1, Math.max(0.01, total / tokBase)) : 0; - patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); if (sortMode === 'tokens') { patchText(refs.totalTokEl, costText); patchText(refs.costEl, formatTokensPrecise(total)); @@ -30165,7 +30189,7 @@ const ConsumptionView = defineComponent({ if (showFallbackMeta) { const srcLabel = item.sourceName || item.appSource || ''; const cacheLabel = t('cons.topConvCacheMeta', { - pct: Number(item.cacheHitPct ?? 0).toFixed(1), + pct: formatPctNumber(item.cacheHitPct ?? 0), }); patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel); } @@ -30282,7 +30306,7 @@ const ConsumptionView = defineComponent({ patchText(heroCostUsd, formatUsd(costUsd)); patchText(heroCostCny, formatCnyApprox(costUsd)); - patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`); + patchText(cacheHitPctEl, formatPctNumber(acct.cacheHitPct ?? 0, { withSymbol: true })); patchText(cacheTokensEl, t('cons.cacheHitTokens', { tokens: formatTokensPrecise(cacheTokens) })); let inPct = 0; @@ -31533,7 +31557,7 @@ const StepsDetailView = defineComponent({ patchText(inspKpiCache.lbl, t('steps.inspCacheLabel')); patchText(inspKpiCache.val, formatTokensPrecise(cacheTok)); - patchText(inspKpiCache.sub, `${cachePct.toFixed(1)}%`); + patchText(inspKpiCache.sub, formatPctNumber(cachePct, { withSymbol: true })); patchText(inspKpiOutput.lbl, t('steps.inspOutputLabel')); patchText(inspKpiOutput.val, formatTokensPrecise(outTok)); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index cea9490..1c3b438 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 1af6fa6..b754b92 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -12,6 +12,7 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core import { formatAgentBadgeText, formatMetric, + formatPctNumber, formatSpeedMetric, formatStepAnomalyInlineSummary, formatTokens, @@ -573,7 +574,7 @@ function formatYAxisTick(metric, val, step) { return step >= 1 ? `${Math.round(val)}s` : `${val.toFixed(1)}s`; } if (metric === 'cache') { - return step >= 1 ? `${Math.round(val)}%` : `${val.toFixed(1)}%`; + return step >= 1 ? `${Math.round(val)}%` : formatPctNumber(val, { withSymbol: true }); } if (metric === 'cost') { if (step >= 1) return `$${Math.round(val)}`; @@ -648,7 +649,7 @@ function formatChartMetricValue(metric, val) { case 'ttft': return formatMetric(val, 's'); case 'cache': - return `${val.toFixed(1)}%`; + return formatPctNumber(val, { withSymbol: true }); case 'cost': return formatUsd(val, { precise: true }); default: @@ -667,7 +668,7 @@ function formatChartMetricCompact(metric, val) { case 'ttft': return formatMetric(val, 's'); case 'cache': - return `${val.toFixed(1)}%`; + return formatPctNumber(val, { withSymbol: true }); case 'cost': return formatUsd(val, { precise: true }); default: diff --git a/sidecars/panel/src/components/ui/ContextSegmentMeter.js b/sidecars/panel/src/components/ui/ContextSegmentMeter.js index b342f43..1d002e5 100644 --- a/sidecars/panel/src/components/ui/ContextSegmentMeter.js +++ b/sidecars/panel/src/components/ui/ContextSegmentMeter.js @@ -6,7 +6,7 @@ import { defineComponent } from '../../core/component.js'; import { h, patchAttr, patchClasses, patchStyleVar } from '../../core/domPatch.js'; -import { formatTokens } from '../../core/formatters.js'; +import { formatPctNumber, formatTokens } from '../../core/formatters.js'; import { t } from '../../i18n/index.js'; const SEGMENT_DEFS = [ @@ -84,7 +84,7 @@ export const ContextSegmentMeter = defineComponent({ slotEl, 'title', isActive - ? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${item.pct.toFixed(1)}%)` + ? `${t(item.def.labelKey)} · ${formatTokens(item.val)} (${formatPctNumber(item.pct, { withSymbol: true })})` : null ); } diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index d9312e3..b3f2532 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -13,7 +13,12 @@ import { patchStyleVar, patchText, } from '../../core/domPatch.js'; -import { formatCountdown, formatTokens, formatUsd } from '../../core/formatters.js'; +import { + formatCountdown, + formatPctNumber, + formatTokens, + formatUsd, +} from '../../core/formatters.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; @@ -189,8 +194,8 @@ function syncQuotaWindowMeter({ const resetStr = hasData ? formatCountdown(resetTime) : ''; if (hasData && rsvVal > 0) { - const rsvStr = rsvVal.toFixed(1); - const actualStr = actualVal.toFixed(1); + const rsvStr = formatPctNumber(rsvVal); + const actualStr = formatPctNumber(actualVal); const leases = Math.max(1, Number(leaseCount) || 1); const tipText = leases >= 2 @@ -198,13 +203,13 @@ function syncQuotaWindowMeter({ : t('quota.reservedTip', { rsv: rsvStr, actual: actualStr }); patchText( metaBeforeEl, - t('quota.usedBeforeReserved', { reset: resetStr, used: usedVal.toFixed(1) }) + t('quota.usedBeforeReserved', { reset: resetStr, used: formatPctNumber(usedVal) }) ); metaReservedEl.hidden = false; patchText(metaReservedEl, t('quota.reservedTag', { rsv: rsvStr })); patchAttr(metaReservedEl, 'title', tipText); metaAfterEl.hidden = false; - patchText(metaAfterEl, t('quota.usedAfterReserved', { rem: remVal.toFixed(1) })); + patchText(metaAfterEl, t('quota.usedAfterReserved', { rem: formatPctNumber(remVal) })); patchAttr(trackEl, 'title', tipText); const actualWidth = +Math.min(100, actualVal).toFixed(2); const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); @@ -217,8 +222,8 @@ function syncQuotaWindowMeter({ hasData ? t('quota.usedAndLeft', { reset: resetStr, - used: usedVal.toFixed(1), - rem: remVal.toFixed(1), + used: formatPctNumber(usedVal), + rem: formatPctNumber(remVal), }) : fallbackMetaText ); diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 7c520b9..413a55b 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -37,6 +37,26 @@ export function formatCachePct(value) { return `${num}%`; } +/** + * 格式化百分比数值文本:常规值保留 1 位小数,将边界值 `0.0` / `100.0` 收口为整数 `0` / `100`。 + * + * @param {number|string|null|undefined} value + * @param {{ withSymbol?: boolean }} [options] + * @returns {string} + */ +export function formatPctNumber(value, { withSymbol = false } = {}) { + const num = Number(value); + if (!Number.isFinite(num)) return withSymbol ? '0%' : '0'; + const rounded = Math.round(num * 10) / 10; + const str = + Math.abs(rounded) < 1e-9 + ? '0' + : Math.abs(rounded - 100) < 1e-9 + ? '100' + : rounded.toFixed(1); + return withSymbol ? `${str}%` : str; +} + export function getSpeedToneClass(tokPerSec) { return `tone-${classifySpeedTier(tokPerSec)}`; } diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index 9b4057d..1f4c3c2 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -8,6 +8,7 @@ import { formatAnomalyKindLabel, formatCompactDateTime, formatMetric, + formatPctNumber, formatSpeedMetric, formatTokensPrecise, formatUsd, @@ -429,10 +430,10 @@ export function buildStepsCsv(steps, { displaySettings = {}, includeBom = true } const promptTok = inTok + cacheTok; const cachePct = st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct)) - ? Number(st.cacheHitPct).toFixed(1) + ? formatPctNumber(st.cacheHitPct) : promptTok > 0 - ? ((cacheTok / promptTok) * 100).toFixed(1) - : '0.0'; + ? formatPctNumber((cacheTok / promptTok) * 100) + : '0'; const ctxTok = Number(st.contextTokens || promptTok + outTok); const anomCount = Number(st.anomaly?.count || 0); const anomDesc = @@ -693,7 +694,7 @@ export function buildStepsMarkdownReport( const agg = summarizeStepsForExport(list, displaySettings); const totalTok = agg.sumIn + agg.sumCache + agg.sumOut; - const cacheHitPct = (computeCacheHitRatio(agg.sumIn, agg.sumCache) * 100).toFixed(1); + const cacheHitPct = formatPctNumber(computeCacheHitRatio(agg.sumIn, agg.sumCache) * 100); const avgTps = agg.tpsCnt > 0 ? formatSpeedMetric(agg.tpsSum / agg.tpsCnt, ' tok/s') : '—'; const avgTtft = agg.ttftCnt > 0 ? formatMetric(agg.ttftSum / agg.ttftCnt, 's') : '—'; const heading = title @@ -734,7 +735,9 @@ export function buildStepsMarkdownReport( ); for (const m of agg.sortedModels) { const mTotal = m.inTok + m.cacheTok + m.outTok; - const mCache = `${(computeCacheHitRatio(m.inTok, m.cacheTok) * 100).toFixed(1)}%`; + const mCache = formatPctNumber(computeCacheHitRatio(m.inTok, m.cacheTok) * 100, { + withSymbol: true, + }); const mTps = m.tpsCnt > 0 ? formatSpeedMetric(m.tpsSum / m.tpsCnt, ' tok/s') : '—'; lines.push( `| ${escapeMdCell(m.label)} | ${m.calls} | ${formatTokensPrecise(mTotal)} | ${mCache} | ${mTps} | ${formatUsd(m.cost, { precise: m.cost > 0 && m.cost < 0.1 })} |` @@ -835,7 +838,7 @@ export function buildConsumptionCsv( Number(acc.cacheReadTokens || 0), Number(acc.outputTokens || 0), Number(acc.totalTokens || 0), - Number(acc.cacheHitPct || 0).toFixed(1), + formatPctNumber(acc.cacheHitPct || 0), Number(acc.costUsd || 0).toFixed(4), `saved_usd=${Number(acc.savedCostUsd || 0).toFixed(4)}`, ]), @@ -851,7 +854,7 @@ export function buildConsumptionCsv( Number(m.cacheReadTokens || 0), Number(m.outputTokens || 0), Number(m.totalTokens || 0), - Number(m.cacheHitPct || 0).toFixed(1), + formatPctNumber(m.cacheHitPct || 0), Number(m.costUsd || 0).toFixed(4), m.avgTokPerSec != null ? `avg_tps=${Number(m.avgTokPerSec).toFixed(1)}` : '', ]) @@ -868,7 +871,7 @@ export function buildConsumptionCsv( Number(w.cacheReadTokens || 0), Number(w.responseTokens || 0) + Number(w.thinkingTokens || 0), Number(w.totalTokens || 0), - Number(w.cacheHitPct || 0).toFixed(1), + formatPctNumber(w.cacheHitPct || 0), Number(w.costUsd || 0).toFixed(4), `sessions=${Number(w.sessionCount || 0)}`, ]) @@ -885,7 +888,7 @@ export function buildConsumptionCsv( Number(c.cacheReadTokens || 0), Number(c.responseTokens || 0) + Number(c.thinkingTokens || 0), Number(c.totalTokens || 0), - Number(c.cacheHitPct || 0).toFixed(1), + formatPctNumber(c.cacheHitPct || 0), Number(c.costUsd || 0).toFixed(4), c.sourceName || c.appSource || '', ]) @@ -1433,14 +1436,14 @@ export function buildConsumptionMarkdownReport( '', `- **Total Tokens**: ${formatTokensPrecise(acc.totalTokens || 0)} (${Number(acc.calls || 0)} calls)`, `- **Est. Cost**: ${formatUsd(acc.costUsd || 0)} (Cache Saved ${formatUsd(acc.savedCostUsd || 0)})`, - `- **Cache Hit Rate**: ${Number(acc.cacheHitPct || 0).toFixed(1)}% (Input ${formatTokensPrecise(acc.inputTokens || 0)} / Cache ${formatTokensPrecise(acc.cacheReadTokens || 0)} / Output ${formatTokensPrecise(acc.outputTokens || 0)})`, + `- **Cache Hit Rate**: ${formatPctNumber(acc.cacheHitPct || 0, { withSymbol: true })} (Input ${formatTokensPrecise(acc.inputTokens || 0)} / Cache ${formatTokensPrecise(acc.cacheReadTokens || 0)} / Output ${formatTokensPrecise(acc.outputTokens || 0)})`, ] : [ `# 用量统计报告 · ${rangeLabel}`, '', `- **总 Token**: ${formatTokensPrecise(acc.totalTokens || 0)}(共 ${Number(acc.calls || 0)} 次调用)`, `- **预估费用**: ${formatUsd(acc.costUsd || 0)}(缓存节省 ${formatUsd(acc.savedCostUsd || 0)})`, - `- **缓存命中率**: ${Number(acc.cacheHitPct || 0).toFixed(1)}%(新输入 ${formatTokensPrecise(acc.inputTokens || 0)} / 缓存读取 ${formatTokensPrecise(acc.cacheReadTokens || 0)} / 输出 ${formatTokensPrecise(acc.outputTokens || 0)})`, + `- **缓存命中率**: ${formatPctNumber(acc.cacheHitPct || 0, { withSymbol: true })}(新输入 ${formatTokensPrecise(acc.inputTokens || 0)} / 缓存读取 ${formatTokensPrecise(acc.cacheReadTokens || 0)} / 输出 ${formatTokensPrecise(acc.outputTokens || 0)})`, ]; if (models.length > 0) { @@ -1455,7 +1458,7 @@ export function buildConsumptionMarkdownReport( ); for (const m of models) { lines.push( - `| ${escapeMdCell(m.displayText || m.label || m.shortName)} | ${Number(m.calls || 0)} | ${formatTokensPrecise(m.totalTokens || 0)} | ${Number(m.cacheHitPct || 0).toFixed(1)}% | ${m.avgTokPerSec != null ? formatSpeedMetric(m.avgTokPerSec, ' tok/s') : '—'} | ${formatUsd(m.costUsd || 0)} |` + `| ${escapeMdCell(m.displayText || m.label || m.shortName)} | ${Number(m.calls || 0)} | ${formatTokensPrecise(m.totalTokens || 0)} | ${formatPctNumber(m.cacheHitPct || 0, { withSymbol: true })} | ${m.avgTokPerSec != null ? formatSpeedMetric(m.avgTokPerSec, ' tok/s') : '—'} | ${formatUsd(m.costUsd || 0)} |` ); } } @@ -1472,7 +1475,7 @@ export function buildConsumptionMarkdownReport( ); for (const w of workspaces) { lines.push( - `| ${escapeMdCell(w.label || w.workspacePath || (en ? 'Unbound' : '未绑定工作区'))} | ${Number(w.sessionCount || 0)} | ${Number(w.calls || 0)} | ${formatTokensPrecise(w.totalTokens || 0)} | ${Number(w.cacheHitPct || 0).toFixed(1)}% | ${formatUsd(w.costUsd || 0)} |` + `| ${escapeMdCell(w.label || w.workspacePath || (en ? 'Unbound' : '未绑定工作区'))} | ${Number(w.sessionCount || 0)} | ${Number(w.calls || 0)} | ${formatTokensPrecise(w.totalTokens || 0)} | ${formatPctNumber(w.cacheHitPct || 0, { withSymbol: true })} | ${formatUsd(w.costUsd || 0)} |` ); } } @@ -1489,7 +1492,7 @@ export function buildConsumptionMarkdownReport( ); for (const c of sessions.slice(0, 8)) { lines.push( - `| ${escapeMdCell(c.title || c.cascadeId)} | ${Number(c.calls || 0)} | ${formatTokensPrecise(c.totalTokens || 0)} | ${Number(c.cacheHitPct || 0).toFixed(1)}% | ${formatUsd(c.costUsd || 0)} |` + `| ${escapeMdCell(c.title || c.cascadeId)} | ${Number(c.calls || 0)} | ${formatTokensPrecise(c.totalTokens || 0)} | ${formatPctNumber(c.cacheHitPct || 0, { withSymbol: true })} | ${formatUsd(c.costUsd || 0)} |` ); } } diff --git a/sidecars/panel/src/core/stepInspector.js b/sidecars/panel/src/core/stepInspector.js index ed6ff3b..af59555 100644 --- a/sidecars/panel/src/core/stepInspector.js +++ b/sidecars/panel/src/core/stepInspector.js @@ -8,6 +8,7 @@ import { formatAnomalyKindLabel, formatCompactDateTime, formatMetric, + formatPctNumber, formatSpeedMetric, formatTimingDetailSec, formatTokensPrecise, @@ -267,10 +268,12 @@ export function buildStepDiagnosticMarkdown( const promptTok = Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0); const cachePct = st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct)) - ? `${Number(st.cacheHitPct).toFixed(1)}%` + ? formatPctNumber(st.cacheHitPct, { withSymbol: true }) : promptTok > 0 - ? `${((Number(st.cacheReadTokens || 0) / promptTok) * 100).toFixed(1)}%` - : '0.0%'; + ? formatPctNumber((Number(st.cacheReadTokens || 0) / promptTok) * 100, { + withSymbol: true, + }) + : '0%'; const ctxTok = Number(st.contextTokens || promptTok + Number(st.outputTokens || 0)); const ctxDelta = prevContextTokens != null && ctxTok > 0 diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index fa4563f..deeeb4e 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -23,6 +23,7 @@ import { formatCnyApprox, formatDateSpanBadge, formatMetric, + formatPctNumber, formatSpeedMetric, formatTokensPrecise, formatUsd, @@ -813,7 +814,7 @@ export const ConsumptionView = defineComponent({ responseTokens, outputTokens: responseTokens + thinkingTokens, tokText: formatTokensPrecise(tok), - pctText: `${pct.toFixed(1)}%`, + pctText: formatPctNumber(pct, { withSymbol: true }), color, isOther: false, }; @@ -850,7 +851,7 @@ export const ConsumptionView = defineComponent({ responseTokens: otherResp, outputTokens: otherResp + otherThink, tokText: formatTokensPrecise(otherTok), - pctText: `${otherPct.toFixed(1)}%`, + pctText: formatPctNumber(otherPct, { withSymbol: true }), color: 'var(--cons-other-seg)', isOther: true, }); @@ -1014,7 +1015,7 @@ export const ConsumptionView = defineComponent({ : promptTok > 0 && Number(item.cacheReadTokens || 0) > 0 ? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1) : 0; - const cachePctStr = cachePctVal.toFixed(1); + const cachePctStr = formatPctNumber(cachePctVal); const effCostPer1M = !isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null; const outTok = Number( @@ -1028,7 +1029,7 @@ export const ConsumptionView = defineComponent({ const barPct = costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, `${costShare.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true })); patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal)); patchText(refs.costEl, costText); @@ -1103,7 +1104,7 @@ export const ConsumptionView = defineComponent({ callsBase > 0 && callsCount > 0 ? Math.min(100, Math.max(1, (callsCount / callsBase) * 100)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, `${callsShare.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); patchText(refs.costEl, t('cons.callsCount', { calls: callsCount })); @@ -1143,7 +1144,7 @@ export const ConsumptionView = defineComponent({ grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; patchAttr(refs.pctBadge, 'hidden', false); patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); patchText(refs.costEl, costText); @@ -1317,7 +1318,7 @@ export const ConsumptionView = defineComponent({ const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; const scaleRatio = grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; - patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); patchText(refs.totalTokEl, formatTokensPrecise(total)); const costVal = Number(item.costUsd || 0); @@ -1568,7 +1569,7 @@ export const ConsumptionView = defineComponent({ ? Math.min(1, Math.max(0.01, total / tokBase)) : 0; - patchText(refs.pctBadge, `${share.toFixed(1)}%`); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); if (sortMode === 'tokens') { patchText(refs.totalTokEl, costText); patchText(refs.costEl, formatTokensPrecise(total)); @@ -1638,7 +1639,7 @@ export const ConsumptionView = defineComponent({ if (showFallbackMeta) { const srcLabel = item.sourceName || item.appSource || ''; const cacheLabel = t('cons.topConvCacheMeta', { - pct: Number(item.cacheHitPct ?? 0).toFixed(1), + pct: formatPctNumber(item.cacheHitPct ?? 0), }); patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel); } @@ -1755,7 +1756,7 @@ export const ConsumptionView = defineComponent({ patchText(heroCostUsd, formatUsd(costUsd)); patchText(heroCostCny, formatCnyApprox(costUsd)); - patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`); + patchText(cacheHitPctEl, formatPctNumber(acct.cacheHitPct ?? 0, { withSymbol: true })); patchText(cacheTokensEl, t('cons.cacheHitTokens', { tokens: formatTokensPrecise(cacheTokens) })); let inPct = 0; diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index b40a5da..00bd223 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -20,6 +20,7 @@ import { formatAnomalyTagText, formatCompactDateTime, formatMetric, + formatPctNumber, formatSpeedMetric, formatTimingDetailSec, formatTokens, @@ -755,7 +756,7 @@ export const StepsDetailView = defineComponent({ patchText(inspKpiCache.lbl, t('steps.inspCacheLabel')); patchText(inspKpiCache.val, formatTokensPrecise(cacheTok)); - patchText(inspKpiCache.sub, `${cachePct.toFixed(1)}%`); + patchText(inspKpiCache.sub, formatPctNumber(cachePct, { withSymbol: true })); patchText(inspKpiOutput.lbl, t('steps.inspOutputLabel')); patchText(inspKpiOutput.val, formatTokensPrecise(outTok)); diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index 10383ca..7c8aa32 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -801,3 +801,18 @@ test('argon_weekly capsule & CLI slot enables only when user has an Argon weekly ); assert.doesNotMatch(cliUltra, /A周/); }); + +test('formatPctNumber collapses boundary 0.0 -> 0 and 100.0 -> 100 while preserving intermediate decimals', async () => { + const { formatPctNumber } = await import('../src/core/formatters.js'); + assert.equal(formatPctNumber(0), '0'); + assert.equal(formatPctNumber(0, { withSymbol: true }), '0%'); + assert.equal(formatPctNumber(0.04, { withSymbol: true }), '0%'); + assert.equal(formatPctNumber(-0.01, { withSymbol: true }), '0%'); + assert.equal(formatPctNumber(100), '100'); + assert.equal(formatPctNumber(100, { withSymbol: true }), '100%'); + assert.equal(formatPctNumber(99.96, { withSymbol: true }), '100%'); + assert.equal(formatPctNumber(0.5, { withSymbol: true }), '0.5%'); + assert.equal(formatPctNumber(1.0, { withSymbol: true }), '1.0%'); + assert.equal(formatPctNumber(50.0, { withSymbol: true }), '50.0%'); + assert.equal(formatPctNumber(99.9, { withSymbol: true }), '99.9%'); +}); From 615a387de8d9fc6e64fc7fb622b560574ce3f362 Mon Sep 17 00:00:00 2001 From: ss Date: Sun, 22 Nov 2026 22:24:01 +0800 Subject: [PATCH 24/31] fix(panel): ignore empty .db-wal mtime churn and throttle remote SSH trajectory rescan --- sidecars/panel/backend/local-scanner.mjs | 63 +++++++- sidecars/panel/backend/sqlite-client.mjs | 3 +- .../sqlite-hybrid-and-side-question.test.mjs | 44 ++++- .../panel/test/ssh-remote-endpoints.test.mjs | 152 ++++++++++++++++++ 4 files changed, 252 insertions(+), 10 deletions(-) diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 0ada7fa..7afb436 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -122,7 +122,9 @@ function readConversationMtime(files = []) { const fullPath = /[\\/]|^[a-zA-Z]:/.test(nameOrPath) ? nameOrPath : join(CONVERSATIONS_DIR, nameOrPath); - mtimeMs = Math.max(mtimeMs, Number(statSync(fullPath)?.mtimeMs || 0)); + const st = statSync(fullPath); + if (/\.db-wal$/i.test(fullPath) && Number(st?.size || 0) <= 0) continue; + mtimeMs = Math.max(mtimeMs, Number(st?.mtimeMs || 0)); } catch { // 轨迹文件可能在目录枚举后被宿主删除。 } @@ -352,6 +354,12 @@ function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountNa const MAX_SUBAGENT_RECONCILE_DEPTH = 4; const FAILED_RPC_COOLDOWN_MS = 60_000; const ACTIVE_FAILED_RPC_COOLDOWN_MS = 15_000; +const REMOTE_FAILED_RPC_COOLDOWN_MS = 15 * 60_000; +const REMOTE_ACTIVE_FAILED_RPC_COOLDOWN_MS = 30_000; +const NOT_FOUND_RPC_COOLDOWN_MS = 30 * 60_000; +const REMOTE_TRAJECTORY_RPC_TIMEOUT_MS = 25_000; +const REMOTE_BACKGROUND_FETCH_LIMIT = 2; +const REMOTE_CONSECUTIVE_TIMEOUT_BREAKER = 2; const TRANSCRIPT_TAIL_MAX_BYTES = 96 * 1024; const MAX_TRANSCRIPT_MEMO_ENTRIES = 64; const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -1407,7 +1415,8 @@ export async function enumerateAndSyncConversations({ const persistCacheIfNeeded = cacheStore.persistTrajectoryCacheIfNeeded; const activeCooldownMap = isRemote ? endpoint.failedFetchCooldownMap : failedFetchCooldownMap; const activeLiveActivityMemo = isRemote ? endpoint.liveActivityMemo : liveActivityMemo; - const maxConcurrentRpc = isRemote ? 2 : MAX_CONCURRENT_RPC; + const maxConcurrentRpc = isRemote ? 1 : MAX_CONCURRENT_RPC; + let remoteConsecutiveTimeouts = 0; const nowSweepMs = Date.now(); if (forceRefresh) { @@ -1791,6 +1800,9 @@ export async function enumerateAndSyncConversations({ attemptedFetchIds.add(c.cascadeId.toLowerCase()); } for (let i = 0; i < targetConvs.length; i += maxConcurrentRpc) { + if (isRemote && remoteConsecutiveTimeouts >= REMOTE_CONSECUTIVE_TIMEOUT_BREAKER) { + break; + } const batch = targetConvs.slice(i, i + maxConcurrentRpc); await Promise.all( batch.map(async (conv) => { @@ -1825,10 +1837,13 @@ export async function enumerateAndSyncConversations({ trajRes = await callLsRpc( 'GetCascadeTrajectory', { cascadeId: conv.cascadeId }, - 5000, + isRemote ? REMOTE_TRAJECTORY_RPC_TIMEOUT_MS : 5000, endpoint ); } + if (isRemote) { + remoteConsecutiveTimeouts = 0; + } if (!Array.isArray(trajRes?.trajectory?.steps)) { throw new Error('Trajectory steps unavailable'); } @@ -2144,10 +2159,23 @@ export async function enumerateAndSyncConversations({ ) { console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`); } + const errText = String(err?.message || ''); + const isNotFoundErr = /(?:\(404\)|\bnot_found\b)/i.test(errText); + const isTimeoutErr = /(?:timed out|timeout|aborted)/i.test(errText); + if (isRemote && isTimeoutErr) { + remoteConsecutiveTimeouts += 1; + } if (!(isRunning && (hasTailStepInfo || offlineRecovered))) { - const cooldownMs = - isRunning || isReq ? ACTIVE_FAILED_RPC_COOLDOWN_MS : FAILED_RPC_COOLDOWN_MS; - activeCooldownMap.set(cooldownKey, { failedAt: nowPollMs, cooldownMs }); + const cooldownMs = isNotFoundErr + ? NOT_FOUND_RPC_COOLDOWN_MS + : isRemote + ? isRunning || isReq + ? REMOTE_ACTIVE_FAILED_RPC_COOLDOWN_MS + : REMOTE_FAILED_RPC_COOLDOWN_MS + : isRunning || isReq + ? ACTIVE_FAILED_RPC_COOLDOWN_MS + : FAILED_RPC_COOLDOWN_MS; + activeCooldownMap.set(cooldownKey, { failedAt: Date.now(), cooldownMs }); } const tailStepsOnErr = partialTailSteps.length > 0 @@ -2320,7 +2348,28 @@ export async function enumerateAndSyncConversations({ return false; }); - await fetchTrajectoryBatch(toFetch); + let fetchQueue = toFetch; + if (isRemote && toFetch.length > REMOTE_BACKGROUND_FETCH_LIMIT) { + const priorityConvs = []; + const backgroundConvs = []; + for (const conv of toFetch) { + const lowerCid = conv.cascadeId.toLowerCase(); + const isPriority = + conv.status === 'CASCADE_RUN_STATUS_RUNNING' || + lowerCid === reqLower || + lowerCid === contextTelemetryCascadeId || + lowerCid === selectedRootId || + Boolean(conv.rootConversationId && conv.rootConversationId.toLowerCase() === selectedRootId); + if (isPriority) { + priorityConvs.push(conv); + } else if (backgroundConvs.length < REMOTE_BACKGROUND_FETCH_LIMIT) { + backgroundConvs.push(conv); + } + } + fetchQueue = [...priorityConvs, ...backgroundConvs]; + } + + await fetchTrajectoryBatch(fetchQueue); /** * 阶段 2:根据父会话的 `subagentRefs` 将子代理归属关系、角色名称与启动顺序回填至子代理会话, diff --git a/sidecars/panel/backend/sqlite-client.mjs b/sidecars/panel/backend/sqlite-client.mjs index 03da145..76b290d 100644 --- a/sidecars/panel/backend/sqlite-client.mjs +++ b/sidecars/panel/backend/sqlite-client.mjs @@ -88,8 +88,9 @@ export function computeSqliteWalSig(dbPath) { } const dbMtimeMs = Number(dbStat.mtimeMs || 0); const dbSize = Number(dbStat.size || 0); - const walMtimeMs = Number(walStat?.mtimeMs || 0); const walSize = Number(walStat?.size || 0); + // 0 字节的空 .db-wal 不含未 checkpoint 事务帧,忽略其 mtime 避免只读打开或宿主 LRU 驱逐触发死循环重扫 + const walMtimeMs = walSize > 0 ? Number(walStat?.mtimeMs || 0) : 0; return { exists: true, mtimeMs: Math.max(dbMtimeMs, walMtimeMs), diff --git a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs index 3ffe156..8f0c762 100644 --- a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs +++ b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs @@ -3,10 +3,10 @@ import assert from 'node:assert/strict'; import http from 'node:http'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; -import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'; +import { mkdtempSync, mkdirSync, rmSync, truncateSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs'; +import { computeSqliteWalSig, readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs'; import { backendHarness } from './backend-harness.mjs'; import { i18nStore } from '../src/i18n/index.js'; import { @@ -786,3 +786,43 @@ test('SQLite trajectory reader scans backwards past trailing plannerConfig-only 'must decode tokenBreakdown on gen_metadata[0] even with 3 trailing plannerConfig-only records' ); }); + +test('computeSqliteWalSig ignores zero-byte .db-wal mtime churn while detecting non-empty WAL writes', (t) => { + const tempRoot = mkdtempSync(join(tmpdir(), 'agy-sqlite-empty-wal-')); + t.after(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })); + + const dbPath = join(tempRoot, 'aaaaaaaa-bbbb-4ccc-8ddd-111111111111.db'); + const walPath = `${dbPath}-wal`; + writeFileSync(dbPath, Buffer.from('sqlite-main-placeholder')); + const baseSec = 1_795_000_000; + utimesSync(dbPath, baseSec, baseSec); + + const sigNoWal = computeSqliteWalSig(dbPath); + assert.equal(sigNoWal.exists, true); + assert.ok(sigNoWal.sig.endsWith('|0:0'), `expected |0:0 suffix, got ${sigNoWal.sig}`); + + // Creating and touching a 0-byte .db-wal (e.g. SQLite WAL open/close or host LRU eviction) + // must NOT change sig or mtimeMs. + writeFileSync(walPath, Buffer.alloc(0)); + utimesSync(walPath, baseSec + 120, baseSec + 120); + const sigEmptyWal1 = computeSqliteWalSig(dbPath); + assert.deepEqual(sigEmptyWal1, sigNoWal); + + utimesSync(walPath, baseSec + 360, baseSec + 360); + const sigEmptyWal2 = computeSqliteWalSig(dbPath); + assert.deepEqual(sigEmptyWal2, sigNoWal); + + // Real uncheckpointed WAL write (size > 0) MUST change sig and advance mtimeMs. + writeFileSync(walPath, Buffer.alloc(4096, 1)); + utimesSync(walPath, baseSec + 500, baseSec + 500); + const sigNonEmptyWal = computeSqliteWalSig(dbPath); + assert.notEqual(sigNonEmptyWal.sig, sigNoWal.sig); + assert.ok(sigNonEmptyWal.mtimeMs > sigNoWal.mtimeMs); + assert.ok(sigNonEmptyWal.sig.endsWith(':4096')); + + // Truncating the WAL back to 0 bytes converges back to the canonical |0:0 signature. + truncateSync(walPath, 0); + utimesSync(walPath, baseSec + 900, baseSec + 900); + const sigTruncatedWal = computeSqliteWalSig(dbPath); + assert.deepEqual(sigTruncatedWal, sigNoWal); +}); diff --git a/sidecars/panel/test/ssh-remote-endpoints.test.mjs b/sidecars/panel/test/ssh-remote-endpoints.test.mjs index eb15561..5410dbd 100644 --- a/sidecars/panel/test/ssh-remote-endpoints.test.mjs +++ b/sidecars/panel/test/ssh-remote-endpoints.test.mjs @@ -2265,4 +2265,156 @@ test('Local Swarm ground truth (members.json killed=false & live transcript.json assert.equal(byCid2.get(wakingCid)?.swarmState, 'working'); }); +test('remote endpoint caps background history fetches per poll, prioritizes active/selected sessions, records completion-time cooldowns, and trips timeout breaker', async () => { + let now = Date.UTC(2026, 10, 22, 12, 0, 0); + const h = backendHarness({ clock: () => now }); + const ep = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:41999', + hostLabel: 'slow-ssh-host', + stableHostKey: 'slow-ssh-host', + }); + + const isoAt = (sec) => new Date(Date.UTC(2026, 10, 22, 11, 0, sec)).toISOString(); + const makeStep = (sec) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: isoAt(sec), + completedAt: isoAt(sec + 2), + generatorModel: 'gemini-4-carbon-high', + modelUsage: { + model: 'gemini-4-carbon-high', + inputTokens: '100', + outputTokens: '50', + }, + }, + }); + + const selectedCid = '11111111-1111-4111-8111-000000000001'; + const runningCid = '11111111-1111-4111-8111-000000000002'; + const hist1 = '11111111-1111-4111-8111-000000000003'; + const hist2 = '11111111-1111-4111-8111-000000000004'; + const hist3 = '11111111-1111-4111-8111-000000000005'; + const hist4 = '11111111-1111-4111-8111-000000000006'; + + const fetchedPerPoll = []; + let currentPollFetches = []; + h.setRemoteWindowRpcInvoker(async (_ep, method, body) => { + if (method === 'GetUserStatus') return { userStatus: { email: 'remote@example.com' } }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + [selectedCid]: { stepCount: 1, createdTime: isoAt(10), lastModifiedTime: isoAt(10), status: 'CASCADE_RUN_STATUS_IDLE' }, + [runningCid]: { stepCount: 1, createdTime: isoAt(20), lastModifiedTime: isoAt(20), status: 'CASCADE_RUN_STATUS_RUNNING' }, + [hist1]: { stepCount: 1, createdTime: isoAt(60), lastModifiedTime: isoAt(60), status: 'CASCADE_RUN_STATUS_IDLE' }, + [hist2]: { stepCount: 1, createdTime: isoAt(50), lastModifiedTime: isoAt(50), status: 'CASCADE_RUN_STATUS_IDLE' }, + [hist3]: { stepCount: 1, createdTime: isoAt(40), lastModifiedTime: isoAt(40), status: 'CASCADE_RUN_STATUS_IDLE' }, + [hist4]: { stepCount: 1, createdTime: isoAt(30), lastModifiedTime: isoAt(30), status: 'CASCADE_RUN_STATUS_IDLE' }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + currentPollFetches.push(body?.cascadeId); + return { trajectory: { steps: [makeStep(1)] } }; + } + return {}; + }); + + // Poll 1: Must fetch selectedCid + runningCid + at most 2 background history items (hist1, hist2) + currentPollFetches = []; + await h.executeTelemetryAction({ conversationId: selectedCid, range: 'today' }, { endpointId: ep.id }); + fetchedPerPoll.push([...currentPollFetches]); + assert.ok(fetchedPerPoll[0].includes(selectedCid)); + assert.ok(fetchedPerPoll[0].includes(runningCid)); + assert.ok(fetchedPerPoll[0].includes(hist1)); + assert.ok(fetchedPerPoll[0].includes(hist2)); + assert.equal(fetchedPerPoll[0].includes(hist3), false, 'hist3 must be deferred to a later poll'); + assert.equal(fetchedPerPoll[0].includes(hist4), false, 'hist4 must be deferred to a later poll'); + + // Poll 2: Backfills remaining hist3, hist4 (plus runningCid because it is RUNNING) + currentPollFetches = []; + now += 5_000; + await h.executeTelemetryAction({ conversationId: selectedCid, range: 'today' }, { endpointId: ep.id }); + assert.ok(currentPollFetches.includes(hist3)); + assert.ok(currentPollFetches.includes(hist4)); + assert.equal(currentPollFetches.includes(hist1), false, 'cached hist1 must not be re-fetched'); + + // Part 2: Consecutive timeout breaker + completion-time cooldown + 404 long cooldown + const ep2 = h.registerRemoteEndpoint({ + origin: 'https://127.0.0.1:42000', + hostLabel: 'timeout-ssh-host', + stableHostKey: 'timeout-ssh-host', + }); + const t1 = '22222222-2222-4222-8222-000000000001'; + const t2 = '22222222-2222-4222-8222-000000000002'; + const t3 = '22222222-2222-4222-8222-000000000003'; + const missingCid = '22222222-2222-4222-8222-000000000004'; + const calls2 = []; + + h.setRemoteWindowRpcInvoker(async (_ep, method, body) => { + if (method === 'GetUserStatus') return { userStatus: { email: 'remote@example.com' } }; + if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } }; + if (method === 'GetAllCascadeTrajectories') { + return { + trajectorySummaries: { + [t1]: { stepCount: 1, createdTime: isoAt(90), lastModifiedTime: isoAt(90), status: 'CASCADE_RUN_STATUS_IDLE' }, + [t2]: { stepCount: 1, createdTime: isoAt(80), lastModifiedTime: isoAt(80), status: 'CASCADE_RUN_STATUS_IDLE' }, + [t3]: { stepCount: 1, createdTime: isoAt(70), lastModifiedTime: isoAt(70), status: 'CASCADE_RUN_STATUS_IDLE' }, + [missingCid]: { stepCount: 1, createdTime: isoAt(60), lastModifiedTime: isoAt(60), status: 'CASCADE_RUN_STATUS_IDLE' }, + }, + }; + } + if (method === 'GetCascadeTrajectory') { + const cid = body?.cascadeId; + calls2.push(cid); + if (cid === missingCid) { + throw new Error('RPC GetCascadeTrajectory failed (404): not_found'); + } + // Simulate slow remote RPC advancing the clock by 70s (> old 60s cooldown) before timing out + now += 70_000; + throw new Error('signal timed out'); + } + return {}; + }); + + // Poll A: t1 (selected, isReq=true -> 30s cooldown) and t2 (background -> 15m cooldown) both time out + // after advancing clock by 70s each -> trips 2-consecutive-timeout breaker, so t3 is NOT attempted. + await h.executeTelemetryAction({ conversationId: t1, range: 'today' }, { endpointId: ep2.id }); + assert.deepEqual(calls2, [t1, t2]); + + // Poll B (+15s after Poll A finished): if failedAt had wrongly used nowPollMs (140s earlier), + // BOTH t1 and t2 would already be expired; with completion-time Date.now(), t2 stays in 15m cooldown + // (and t1 is still within 30s of its completion if only 15s elapsed since t2 finished? t1 finished 85s ago -> expired, + // while t2 finished 15s ago -> still in 15m cooldown). Verify t2 stays suppressed and t3 + missingCid run. + calls2.length = 0; + now += 15_000; + await h.executeTelemetryAction({ conversationId: t3, range: 'today' }, { endpointId: ep2.id }); + assert.equal(calls2.includes(t2), false, 't2 must stay in 15m remote timeout cooldown'); + assert.ok(calls2.includes(t3), 'selected t3 must be attempted'); + assert.ok(calls2.includes(missingCid) || calls2.includes(t1), 'remaining non-cooled entries proceed until breaker'); + + // Ensure missingCid hits 404 once if deferred by breaker above + if (!calls2.includes(missingCid)) { + calls2.length = 0; + now += 5_000; + await h.executeTelemetryAction({ conversationId: missingCid, range: 'today' }, { endpointId: ep2.id }); + assert.ok(calls2.includes(missingCid)); + } + + // Poll C (+10 min later): t2 STILL in 15m timeout cooldown, missingCid STILL in 30m 404 cooldown + calls2.length = 0; + now += 10 * 60_000; + await h.executeTelemetryAction({ conversationId: missingCid, range: 'today' }, { endpointId: ep2.id }); + assert.equal(calls2.includes(t2), false, 't2 must remain in 15m remote timeout cooldown'); + assert.equal(calls2.includes(missingCid), false, '404 missingCid must remain in 30m cooldown'); + + // Poll D (+10 more min -> 20m since 404): missingCid STILL in 30m 404 cooldown + calls2.length = 0; + now += 10 * 60_000; + await h.executeTelemetryAction({ conversationId: missingCid, range: 'today' }, { endpointId: ep2.id }); + assert.equal(calls2.includes(missingCid), false, '404 missingCid must stay in 30m cooldown after 20m'); +}); + + From 3a40bacc9d70b239eca0752d619a0cad81af61a9 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Mon, 23 Nov 2026 09:45:54 +0900 Subject: [PATCH 25/31] fix(panel): resolve P0 step inspector, V4 timing projection, harmonic speed merge, and UI cleanup bugs --- sidecars/panel/app.js | 338 ++++++++++++--- sidecars/panel/backend/account-switch.mjs | 2 +- sidecars/panel/backend/api-actions.mjs | 5 +- sidecars/panel/index.html | 4 +- .../components/layout/WindowOverlayShell.js | 3 + .../settings/SessionMigrationCard.js | 2 +- .../src/components/ui/CustomDateTimePicker.js | 44 +- .../src/components/ui/CustomNumberInput.js | 16 +- .../src/components/ui/SegmentedControl.js | 11 +- .../src/components/widgets/StepTableWidget.js | 9 +- sidecars/panel/src/core/formatters.js | 55 ++- sidecars/panel/src/core/reportExporter.js | 79 ++-- sidecars/panel/src/core/stepInspector.js | 29 +- sidecars/panel/src/i18n/en-US.js | 15 + sidecars/panel/src/i18n/zh-CN.js | 15 + sidecars/panel/src/views/StepsDetailView.js | 62 ++- .../test/practical-enhancements.test.mjs | 409 ++++++++++++++++++ 17 files changed, 958 insertions(+), 140 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index b632dd6..47ebe86 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2124,6 +2124,21 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', 'chart.trend.hmActiveZero': '活跃 0/{total} 天', 'chart.trend.peakPill': '峰值 {label} · {tokens}', + + // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) + 'ui.dt.wdayMon': '一', + 'ui.dt.wdayTue': '二', + 'ui.dt.wdayWed': '三', + 'ui.dt.wdayThu': '四', + 'ui.dt.wdayFri': '五', + 'ui.dt.wdaySat': '六', + 'ui.dt.wdaySun': '日', + 'ui.dt.prevMonth': '上个月', + 'ui.dt.nextMonth': '下个月', + 'ui.dt.hourMinute': '时 / 分', + 'ui.num.decrease': '减少数值', + 'ui.num.increase': '增加数值', + 'ui.seg.defaultAria': '分段切换器', }); return { I18N_MESSAGES_ZH_CN }; })(); @@ -3005,6 +3020,21 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', 'chart.trend.hmActiveZero': 'Active 0/{total}d', 'chart.trend.peakPill': 'Peak {label} · {tokens}', + + // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) + 'ui.dt.wdayMon': 'Mo', + 'ui.dt.wdayTue': 'Tu', + 'ui.dt.wdayWed': 'We', + 'ui.dt.wdayThu': 'Th', + 'ui.dt.wdayFri': 'Fr', + 'ui.dt.wdaySat': 'Sa', + 'ui.dt.wdaySun': 'Su', + 'ui.dt.prevMonth': 'Previous month', + 'ui.dt.nextMonth': 'Next month', + 'ui.dt.hourMinute': 'Hr / Min', + 'ui.num.decrease': 'Decrease value', + 'ui.num.increase': 'Increase value', + 'ui.seg.defaultAria': 'Segmented switcher', }); return { I18N_MESSAGES_EN_US }; })(); @@ -4833,14 +4863,30 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { const speedSampleCount = Math.max(0, Number(m.speedSummary?.sampleCount || 0)); const speedExcludedCount = Math.max(0, Number(m.speedSummary?.excludedCount || 0)); const speedWeight = speedSampleCount > 0 ? speedSampleCount : Math.max(1, outTok || calls || 1); - const hasSpeed = m.avgTokPerSec != null && Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0; + const hasSpeed = + m.avgTokPerSec != null && Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0; + const rawSpeedTokens = Number(m.speedSummary?.tokens); + const rawSpeedSeconds = Number(m.speedSummary?.seconds); + const hasExactSpeedSummary = + Number.isFinite(rawSpeedTokens) && + Number.isFinite(rawSpeedSeconds) && + rawSpeedSeconds > 0 && + rawSpeedTokens >= 0; const ttftSampleCount = Math.max(0, Number(m.ttftSampleCount || 0)); const ttftWeight = ttftSampleCount > 0 ? ttftSampleCount : Math.max(1, calls || 1); - const hasTtft = m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0; + const hasTtft = + m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0; let acc = byDisplay.get(key); if (!acc) { + const initExcludedReasons = {}; + if (m.speedSummary?.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { + for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { + const cnt = Math.max(0, Number(rv || 0)); + if (cnt > 0) initExcludedReasons[rk] = cnt; + } + } acc = { baseItem: m, mergedCount: 1, @@ -4860,10 +4906,15 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { totalTokens: totTok, costUsd, unpricedCalls, + hasAnySpeedSummary: Boolean(m.speedSummary), + allSpeedExact: !hasSpeed || hasExactSpeedSummary, + speedTokens: hasExactSpeedSummary ? rawSpeedTokens : 0, + speedSeconds: hasExactSpeedSummary ? rawSpeedSeconds : 0, speedWeightedSum: hasSpeed ? Number(m.avgTokPerSec) * speedWeight : 0, speedWeight: hasSpeed ? speedWeight : 0, speedSampleCount, speedExcludedCount, + speedExcludedReasons: initExcludedReasons, ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0, ttftWeight: hasTtft ? ttftWeight : 0, ttftSampleCount, @@ -4912,12 +4963,24 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { } } + if (m.speedSummary) acc.hasAnySpeedSummary = true; + if (hasSpeed && !hasExactSpeedSummary) acc.allSpeedExact = false; + if (hasExactSpeedSummary) { + acc.speedTokens += rawSpeedTokens; + acc.speedSeconds += rawSpeedSeconds; + } if (hasSpeed) { acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight; acc.speedWeight += speedWeight; } acc.speedSampleCount += speedSampleCount; acc.speedExcludedCount += speedExcludedCount; + if (m.speedSummary?.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { + for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { + const cnt = Math.max(0, Number(rv || 0)); + if (cnt > 0) acc.speedExcludedReasons[rk] = (acc.speedExcludedReasons[rk] || 0) + cnt; + } + } if (hasTtft) { acc.ttftWeightedSum += Number(m.avgTtftSec) * ttftWeight; @@ -4937,8 +5000,13 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { } const promptTok = acc.inputTokens + acc.cacheReadTokens; const cacheHitPct = promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0; - const avgTokPerSec = - acc.speedWeight > 0 ? +(acc.speedWeightedSum / acc.speedWeight).toFixed(1) : null; + const rawAvgTps = + acc.allSpeedExact && acc.speedSeconds > 0 + ? acc.speedTokens / acc.speedSeconds + : acc.speedWeight > 0 + ? acc.speedWeightedSum / acc.speedWeight + : null; + const avgTokPerSec = rawAvgTps !== null ? +rawAvgTps.toFixed(1) : null; const avgTtftSec = acc.ttftWeight > 0 ? +(acc.ttftWeightedSum / acc.ttftWeight).toFixed(1) : null; const upstreamModels = Array.from(acc.upstreamSet); @@ -4971,12 +5039,15 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { anomalyByKind: acc.anomalyByKind, } : {}), - speedSummary: acc.baseItem.speedSummary + speedSummary: acc.hasAnySpeedSummary ? { - ...acc.baseItem.speedSummary, + ...(acc.baseItem.speedSummary || {}), + tokens: acc.speedTokens, + seconds: +acc.speedSeconds.toFixed(6), sampleCount: acc.speedSampleCount, excludedCount: acc.speedExcludedCount, - avgTokPerSec, + excludedReasons: acc.speedExcludedReasons, + avgTokPerSec: rawAvgTps, } : undefined, upstreamModels, @@ -5363,7 +5434,8 @@ const STEP_SLOW_TTFT_MIN_SEC = 30; */ function getStepSelectionKey(st, fallbackCascadeId = '') { if (!st || typeof st !== 'object') return ''; - const agentKey = st.agentId || st.cascadeId || fallbackCascadeId || 'main'; + const agentKey = + st.agentCascadeId || st.agentId || st.cascadeId || fallbackCascadeId || 'conv'; return `${agentKey}-${st.stepIndex}`; } @@ -5458,6 +5530,11 @@ function filterStepsBySearchAndChip( if (rawTerms.length > 0) { const modelInfo = resolveModelDisplayInfo(st, displaySettings); const anomalyKinds = st.anomaly?.kinds ? Object.keys(st.anomaly.kinds).join(' ') : ''; + const anomalyEventsText = Array.isArray(st.anomaly?.events) + ? st.anomaly.events + .map((ev) => `${ev?.kind || ''} ${ev?.attempt ?? ''} ${ev?.message || ''}`) + .join(' ') + : ''; const anomalyItemsText = Array.isArray(st.anomaly?.items) ? st.anomaly.items .map((it) => `${it?.kind || ''} ${it?.httpStatus || ''} ${it?.detail || ''}`) @@ -5470,6 +5547,9 @@ function filterStepsBySearchAndChip( modelInfo.title, st.modelLabel || '', st.modelShort || '', + st.modelKey || '', + st.modelUpstream || '', + st.responseModel || '', st.rawModelId || '', st.upstreamName || '', st.turnPrompt || '', @@ -5479,6 +5559,7 @@ function filterStepsBySearchAndChip( st.agentBadge || '', st.isCompactionStep ? 'compaction 压缩' : '', anomalyKinds, + anomalyEventsText, anomalyItemsText, ] .join(' ') @@ -5543,15 +5624,15 @@ function findPrevAgentContextTokens(allSteps, targetStep) { */ function computeStepTimingWaterfall(st) { if (!st || typeof st !== 'object') return null; + const rawTtft = st.ttftSec ?? st.nativeTtftSec; const ttft = - st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0 - ? Number(st.ttftSec) + rawTtft != null && Number.isFinite(Number(rawTtft)) && Number(rawTtft) >= 0 + ? Number(rawTtft) : 0; + const rawStream = st.nativeStreamSec ?? st.streamDurationSec; const stream = - st.streamDurationSec != null && - Number.isFinite(Number(st.streamDurationSec)) && - Number(st.streamDurationSec) >= 0 - ? Number(st.streamDurationSec) + rawStream != null && Number.isFinite(Number(rawStream)) && Number(rawStream) >= 0 + ? Number(rawStream) : 0; const thinking = st.thinkingDurationSec != null && @@ -5559,9 +5640,10 @@ function computeStepTimingWaterfall(st) { Number(st.thinkingDurationSec) >= 0 ? Number(st.thinkingDurationSec) : 0; + const rawDur = st.totalDurationSec ?? st.durationSec; const rawTotal = - st.durationSec != null && Number.isFinite(Number(st.durationSec)) && Number(st.durationSec) > 0 - ? Number(st.durationSec) + rawDur != null && Number.isFinite(Number(rawDur)) && Number(rawDur) > 0 + ? Number(rawDur) : ttft + stream; const totalSec = Math.max(rawTotal, ttft + stream); if (!(totalSec > 0)) return null; @@ -6726,7 +6808,8 @@ function summarizeStepsForExport(list, displaySettings) { let sumCost = 0; let sumDuration = 0; let maxContext = 0; - let tpsSum = 0; + let tpsTokSum = 0; + let tpsSecSum = 0; let tpsCnt = 0; let ttftSum = 0; let ttftCnt = 0; @@ -6748,7 +6831,8 @@ function summarizeStepsForExport(list, displaySettings) { : Math.max(0, outTok - thinkTok); const ctxTok = Math.max(0, Number(st.contextTokens || inTok + cacheTok + outTok)); const cost = Number(st.costUsd || 0); - const dur = Number(st.durationSec || 0); + const rawDur = st.totalDurationSec ?? st.durationSec; + const dur = rawDur != null && Number.isFinite(Number(rawDur)) ? Number(rawDur) : 0; sumIn += inTok; sumCache += cacheTok; @@ -6760,11 +6844,21 @@ function summarizeStepsForExport(list, displaySettings) { if (Number.isFinite(dur) && dur > 0) sumDuration += dur; const validTps = - !st.isCompactionStep && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0; + !st.isCompactionStep && + outTok >= 50 && + !st.selectedSpeedReason && + Number.isFinite(Number(st.tokPerSec)) && + Number(st.tokPerSec) > 0; + const stepSpeedSec = validTps + ? st.totalDurationSec != null && Number(st.totalDurationSec) >= 0.5 + ? Number(st.totalDurationSec) + : outTok / Number(st.tokPerSec) + : 0; const validTtft = !st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0; - if (validTps) { - tpsSum += Number(st.tokPerSec); + if (validTps && stepSpeedSec > 0) { + tpsTokSum += outTok; + tpsSecSum += stepSpeedSec; tpsCnt += 1; } if (validTtft) { @@ -6789,7 +6883,8 @@ function summarizeStepsForExport(list, displaySettings) { cacheTok: 0, outTok: 0, cost: 0, - tpsSum: 0, + tpsTokSum: 0, + tpsSecSum: 0, tpsCnt: 0, ttftSum: 0, ttftCnt: 0, @@ -6801,8 +6896,9 @@ function summarizeStepsForExport(list, displaySettings) { mAcc.cacheTok += cacheTok; mAcc.outTok += outTok; if (Number.isFinite(cost) && cost > 0) mAcc.cost += cost; - if (validTps) { - mAcc.tpsSum += Number(st.tokPerSec); + if (validTps && stepSpeedSec > 0) { + mAcc.tpsTokSum += outTok; + mAcc.tpsSecSum += stepSpeedSec; mAcc.tpsCnt += 1; } if (validTtft) { @@ -6826,7 +6922,8 @@ function summarizeStepsForExport(list, displaySettings) { sumCost, sumDuration, maxContext, - tpsSum, + tpsTokSum, + tpsSecSum, tpsCnt, ttftSum, ttftCnt, @@ -7009,8 +7106,9 @@ function buildStepsCsv(steps, { displaySettings = {}, includeBom = true } = {}) st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) ? Number(st.ttftSec).toFixed(3) : '', - st.durationSec != null && Number.isFinite(Number(st.durationSec)) - ? Number(st.durationSec).toFixed(3) + (st.totalDurationSec ?? st.durationSec) != null && + Number.isFinite(Number(st.totalDurationSec ?? st.durationSec)) + ? Number(st.totalDurationSec ?? st.durationSec).toFixed(3) : '', inTok, cacheTok, @@ -7077,9 +7175,10 @@ function buildStepsXlsx( !st.isCompactionStep && st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) ? Number(st.ttftSec) : null; + const rawDurVal = st.totalDurationSec ?? st.durationSec; const durVal = - st.durationSec != null && Number.isFinite(Number(st.durationSec)) - ? Number(st.durationSec) + rawDurVal != null && Number.isFinite(Number(rawDurVal)) + ? Number(rawDurVal) : null; const costVal = st.costUsd != null && Number.isFinite(Number(st.costUsd)) ? Number(st.costUsd) : null; @@ -7131,7 +7230,7 @@ function buildStepsXlsx( ? `${agg.compactionCount} compact` : `含 ${agg.compactionCount} 次压缩` : '', - agg.tpsCnt > 0 ? +(agg.tpsSum / agg.tpsCnt).toFixed(1) : null, + agg.tpsSecSum > 0 ? +(agg.tpsTokSum / agg.tpsSecSum).toFixed(1) : null, agg.ttftCnt > 0 ? +(agg.ttftSum / agg.ttftCnt).toFixed(2) : null, agg.sumDuration > 0 ? +agg.sumDuration.toFixed(2) : null, agg.sumIn, @@ -7190,7 +7289,7 @@ function buildStepsXlsx( m.outTok, mTotal, computeCacheHitRatio(m.inTok, m.cacheTok), - m.tpsCnt > 0 ? +(m.tpsSum / m.tpsCnt).toFixed(1) : null, + m.tpsSecSum > 0 ? +(m.tpsTokSum / m.tpsSecSum).toFixed(1) : null, m.ttftCnt > 0 ? +(m.ttftSum / m.ttftCnt).toFixed(2) : null, m.cost, ]; @@ -7205,7 +7304,7 @@ function buildStepsXlsx( agg.sumOut, agg.sumIn + agg.sumCache + agg.sumOut, computeCacheHitRatio(agg.sumIn, agg.sumCache), - agg.tpsCnt > 0 ? +(agg.tpsSum / agg.tpsCnt).toFixed(1) : null, + agg.tpsSecSum > 0 ? +(agg.tpsTokSum / agg.tpsSecSum).toFixed(1) : null, agg.ttftCnt > 0 ? +(agg.ttftSum / agg.ttftCnt).toFixed(2) : null, agg.sumCost, ], @@ -7249,7 +7348,8 @@ function buildStepsMarkdownReport( const totalTok = agg.sumIn + agg.sumCache + agg.sumOut; const cacheHitPct = formatPctNumber(computeCacheHitRatio(agg.sumIn, agg.sumCache) * 100); - const avgTps = agg.tpsCnt > 0 ? formatSpeedMetric(agg.tpsSum / agg.tpsCnt, ' tok/s') : '—'; + const avgTps = + agg.tpsSecSum > 0 ? formatSpeedMetric(agg.tpsTokSum / agg.tpsSecSum, ' tok/s') : '—'; const avgTtft = agg.ttftCnt > 0 ? formatMetric(agg.ttftSum / agg.ttftCnt, 's') : '—'; const heading = title ? `# ${title}` @@ -7292,7 +7392,8 @@ function buildStepsMarkdownReport( const mCache = formatPctNumber(computeCacheHitRatio(m.inTok, m.cacheTok) * 100, { withSymbol: true, }); - const mTps = m.tpsCnt > 0 ? formatSpeedMetric(m.tpsSum / m.tpsCnt, ' tok/s') : '—'; + const mTps = + m.tpsSecSum > 0 ? formatSpeedMetric(m.tpsTokSum / m.tpsSecSum, ' tok/s') : '—'; lines.push( `| ${escapeMdCell(m.label)} | ${m.calls} | ${formatTokensPrecise(mTotal)} | ${mCache} | ${mTps} | ${formatUsd(m.cost, { precise: m.cost > 0 && m.cost < 0.1 })} |` ); @@ -7607,8 +7708,8 @@ function buildConsumptionXlsx( let mOut = 0; let mTot = 0; let mCost = 0; - let tpsWeighted = 0; - let tpsWeight = 0; + let tpsTokSum = 0; + let tpsSecSum = 0; const modelRows = models.map((m, idx) => { const calls = Math.max(0, Number(m.calls || 0)); const inTok = Math.max(0, Number(m.inputTokens || 0)); @@ -7626,10 +7727,20 @@ function buildConsumptionXlsx( mOut += outTok; mTot += totTok; mCost += cost; - if (tps != null) { - const w = Math.max(1, outTok || calls); - tpsWeighted += tps * w; - tpsWeight += w; + const rawSpeedTok = Number(m.speedSummary?.tokens); + const rawSpeedSec = Number(m.speedSummary?.seconds); + if ( + Number.isFinite(rawSpeedTok) && + Number.isFinite(rawSpeedSec) && + rawSpeedSec > 0 && + rawSpeedTok >= 0 + ) { + tpsTokSum += rawSpeedTok; + tpsSecSum += rawSpeedSec; + } else if (tps != null) { + const fallbackTok = outTok > 0 ? outTok : Math.max(1, calls); + tpsTokSum += fallbackTok; + tpsSecSum += fallbackTok / tps; } return [ idx + 1, @@ -7655,7 +7766,7 @@ function buildConsumptionXlsx( mOut, mTot, computeCacheHitRatio(mIn, mCache), - tpsWeight > 0 ? +(tpsWeighted / tpsWeight).toFixed(1) : null, + tpsSecSum > 0 ? +(tpsTokSum / tpsSecSum).toFixed(1) : null, mCost, ], }); @@ -11925,7 +12036,7 @@ const { CustomNumberInput } = (() => { const CustomNumberInput = defineComponent({ name: 'CustomNumberInput', - setup({ getProps, setProps, emit }) { + setup({ getProps, setProps, emit, onCleanup }) { function clampValue(raw) { const { min = -Infinity, max = Infinity, precision = 0 } = getProps(); const num = Number(raw); @@ -11952,7 +12063,7 @@ const CustomNumberInput = defineComponent({ { type: 'button', className: 'num-step-btn', - 'aria-label': '减少数值', + 'aria-label': t('ui.num.decrease'), onClick: (e) => { e.preventDefault(); applyStep(-1, e.shiftKey ? 10 : 1); @@ -11966,7 +12077,7 @@ const CustomNumberInput = defineComponent({ { type: 'button', className: 'num-step-btn', - 'aria-label': '增加数值', + 'aria-label': t('ui.num.increase'), onClick: (e) => { e.preventDefault(); applyStep(1, e.shiftKey ? 10 : 1); @@ -12030,6 +12141,15 @@ const CustomNumberInput = defineComponent({ } const rootEl = h('div', { className: 'number-input' }, [decBtn, textField, incBtn]); + const unsubI18n = i18nStore.subscribe( + (st) => st.locale, + () => { + patchAttr(decBtn, 'aria-label', t('ui.num.decrease')); + patchAttr(incBtn, 'aria-label', t('ui.num.increase')); + }, + { immediate: false } + ); + onCleanup(unsubI18n); syncFieldDisplay(); return { @@ -12053,7 +12173,15 @@ const { CustomDateTimePicker } = (() => { */ -const WEEKDAYS = ['一', '二', '三', '四', '五', '六', '日']; +const WEEKDAY_KEYS = [ + 'ui.dt.wdayMon', + 'ui.dt.wdayTue', + 'ui.dt.wdayWed', + 'ui.dt.wdayThu', + 'ui.dt.wdayFri', + 'ui.dt.wdaySat', + 'ui.dt.wdaySun', +]; function buildCalendarDays(viewYear, viewMonth, selectedDate) { const firstDay = new Date(viewYear, viewMonth, 1); @@ -12114,7 +12242,7 @@ const CustomDateTimePicker = defineComponent({ { type: 'button', className: 'icon-btn', - 'aria-label': '上个月', + 'aria-label': t('ui.dt.prevMonth'), onClick: (e) => { e.stopPropagation(); viewMonth -= 1; @@ -12133,7 +12261,7 @@ const CustomDateTimePicker = defineComponent({ { type: 'button', className: 'icon-btn', - 'aria-label': '下个月', + 'aria-label': t('ui.dt.nextMonth'), onClick: (e) => { e.stopPropagation(); viewMonth += 1; @@ -12149,11 +12277,10 @@ const CustomDateTimePicker = defineComponent({ const navBar = h('div', { className: 'dt-nav' }, [prevMonthBtn, monthTitle, nextMonthBtn]); - const weekdayRow = h( - 'div', - { className: 'dt-weekdays' }, - WEEKDAYS.map((w) => h('span', { className: 'dt-weekday', text: w })) + const weekdaySpans = WEEKDAY_KEYS.map((key) => + h('span', { className: 'dt-weekday', text: t(key) }) ); + const weekdayRow = h('div', { className: 'dt-weekdays' }, weekdaySpans); const daysGrid = h('div', { className: 'dt-days' }); @@ -12173,8 +12300,9 @@ const CustomDateTimePicker = defineComponent({ emit('update:modelValue', nextMs); } + const hourMinLabelEl = h('span', { className: 'text-muted', text: t('ui.dt.hourMinute') }); const timeRow = h('div', { className: 'dt-time-row' }, [ - h('span', { className: 'text-muted', text: '时 / 分' }), + hourMinLabelEl, h('div', { className: 'dt-time-controls' }, [ h('div', { className: 'dt-mini-step' }, [ h('button', { @@ -12343,6 +12471,25 @@ const CustomDateTimePicker = defineComponent({ onCleanup(() => setRepositionListeners(false)); } + function syncI18nLabels() { + patchAttr(prevMonthBtn, 'aria-label', t('ui.dt.prevMonth')); + patchAttr(nextMonthBtn, 'aria-label', t('ui.dt.nextMonth')); + patchText(hourMinLabelEl, t('ui.dt.hourMinute')); + for (let i = 0; i < WEEKDAY_KEYS.length; i += 1) { + patchText(weekdaySpans[i], t(WEEKDAY_KEYS[i])); + } + } + + const unsubI18n = i18nStore.subscribe( + (st) => st.locale, + () => { + syncI18nLabels(); + syncDisplay(); + }, + { immediate: false } + ); + onCleanup(unsubI18n); + syncDisplay(); return { @@ -12554,10 +12701,18 @@ const SegmentedControl = defineComponent({ { className: 'segmented', role: 'group', - 'aria-label': getProps().ariaLabel || '分段切换器', + 'aria-label': getProps().ariaLabel || t('ui.seg.defaultAria'), }, [gliderEl] ); + const unsubI18n = i18nStore.subscribe( + (st) => st.locale, + () => { + patchAttr(rootEl, 'aria-label', getProps().ariaLabel || t('ui.seg.defaultAria')); + }, + { immediate: false } + ); + onCleanup(unsubI18n); const btnMap = new Map(); let orderedBtns = []; @@ -21514,9 +21669,11 @@ const StepTableWidget = defineComponent({ } function getStepRowIdentity(st, fallbackCascadeId) { - const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); + const agentKey = String( + st?.agentCascadeId || st?.agentId || st?.cascadeId || fallbackCascadeId || 'conv' + ); const stepNum = Number(st?.stepIndex); - const rowKey = `${agentKey}-${st?.stepIndex}`; + const rowKey = getStepSelectionKey(st, fallbackCascadeId); return { agentKey, stepNum, rowKey }; } @@ -21892,7 +22049,7 @@ const StepTableWidget = defineComponent({ logicalIdx: idx, isStripeEven: (idx & 1) === 1, hasReason: Boolean(hasReasonFlags && hasReasonFlags[idx]), - rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`, + rowKey: getStepSelectionKey(st, cascadeId), hasTurn, hasUp, hasDown, @@ -24705,7 +24862,7 @@ const SessionMigrationCard = defineComponent({ } } - listScrollbar?.methods?.refresh?.(); + listScrollbar?.refresh?.(); patchAttr(migrateBtn, 'disabled', isMigrating || selectedIds.size === 0 || !targetClient); patchText( @@ -30870,7 +31027,7 @@ return { ConsumptionView }; })(); // --- src/views/StepsDetailView.js --- -const { StepsDetailView } = (() => { +const { mergeSelectedAgentUnits, StepsDetailView } = (() => { /** * @fileoverview View 3: StepsDetailView (步骤明细与总汇总分析视图). * 提供“按步查看”与“总汇总”双子视图切换: @@ -30916,10 +31073,15 @@ function mergeSelectedAgentUnits(units) { anomalyDangerCount: 0, anomalyTotalDelaySec: 0, anomalyByKind: {}, - _speedWeightedSum: 0, - _speedWeight: 0, + _hasAnySpeedSummary: false, + _speedTokens: 0, + _speedSeconds: 0, + _speedSampleCount: 0, + _speedExcludedCount: 0, + _speedExcludedReasons: {}, _ttftWeightedSum: 0, _ttftWeight: 0, + _ttftSampleCount: 0, }; if (acc.upstreamName) acc.upstreamSet.add(acc.upstreamName); modelMap.set(gk, acc); @@ -30966,19 +31128,43 @@ function mergeSelectedAgentUnits(units) { } } - if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) { - const w = Math.max(1, outTok || calls || 1); - acc._speedWeightedSum += Number(m.avgTokPerSec) * w; - acc._speedWeight += w; + const rawSpeedTok = Number(m.speedSummary?.tokens); + const rawSpeedSec = Number(m.speedSummary?.seconds); + if ( + Number.isFinite(rawSpeedTok) && + Number.isFinite(rawSpeedSec) && + rawSpeedSec > 0 && + rawSpeedTok >= 0 + ) { + acc._hasAnySpeedSummary = true; + acc._speedTokens += rawSpeedTok; + acc._speedSeconds += rawSpeedSec; + } else if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) { + const fallbackTok = outTok > 0 ? outTok : Math.max(1, calls || 1); + acc._speedTokens += fallbackTok; + acc._speedSeconds += fallbackTok / Number(m.avgTokPerSec); + } + if (m.speedSummary) { + acc._hasAnySpeedSummary = true; + acc._speedSampleCount += Math.max(0, Number(m.speedSummary.sampleCount || 0)); + acc._speedExcludedCount += Math.max(0, Number(m.speedSummary.excludedCount || 0)); + if (m.speedSummary.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { + for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { + const cnt = Math.max(0, Number(rv || 0)); + if (cnt > 0) acc._speedExcludedReasons[rk] = (acc._speedExcludedReasons[rk] || 0) + cnt; + } + } } if ( m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0 ) { - const w = Math.max(1, calls || 1); + const ttftSamples = Math.max(0, Number(m.ttftSampleCount || 0)); + const w = ttftSamples > 0 ? ttftSamples : Math.max(1, calls || 1); acc._ttftWeightedSum += Number(m.avgTtftSec) * w; acc._ttftWeight += w; + acc._ttftSampleCount += ttftSamples; } } } @@ -30993,6 +31179,7 @@ function mergeSelectedAgentUnits(units) { const mergedModels = Array.from(modelMap.values()) .map((acc) => { const promptTok = acc.inputTokens + acc.cacheReadTokens; + const rawAvgTps = acc._speedSeconds > 0 ? acc._speedTokens / acc._speedSeconds : null; return { label: acc.label, shortName: acc.shortName, @@ -31008,10 +31195,22 @@ function mergeSelectedAgentUnits(units) { totalTokens: acc.totalTokens, costUsd: +acc.costUsd.toFixed(6), unpricedCalls: acc.unpricedCalls, - avgTokPerSec: - acc._speedWeight > 0 ? +(acc._speedWeightedSum / acc._speedWeight).toFixed(1) : null, + avgTokPerSec: rawAvgTps !== null ? +rawAvgTps.toFixed(1) : null, avgTtftSec: acc._ttftWeight > 0 ? +(acc._ttftWeightedSum / acc._ttftWeight).toFixed(1) : null, + ttftSampleCount: acc._ttftSampleCount, + ...(acc._hasAnySpeedSummary + ? { + speedSummary: { + tokens: acc._speedTokens, + seconds: +acc._speedSeconds.toFixed(6), + sampleCount: acc._speedSampleCount, + excludedCount: acc._speedExcludedCount, + excludedReasons: acc._speedExcludedReasons, + avgTokPerSec: rawAvgTps, + }, + } + : {}), cacheHitPct: promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0, ...(acc.anomalyCount > 0 ? { @@ -32946,7 +33145,7 @@ const StepsDetailView = defineComponent({ }; }, }); -return { StepsDetailView }; +return { mergeSelectedAgentUnits, StepsDetailView }; })(); // --- src/views/SettingsView.js --- @@ -36390,6 +36589,9 @@ function mountWindowOverlay() { window.removeEventListener?.('popstate', onPopState); navigator?.windowControlsOverlay?.removeEventListener?.('geometrychange', onWindowResize); restorePatchedActionToolbar(); + try { + multiRunningWidget.destroy(); + } catch {} try { hoverWidgetHost.destroy(); } catch {} diff --git a/sidecars/panel/backend/account-switch.mjs b/sidecars/panel/backend/account-switch.mjs index 3597e95..1f426b6 100644 --- a/sidecars/panel/backend/account-switch.mjs +++ b/sidecars/panel/backend/account-switch.mjs @@ -103,7 +103,7 @@ export async function handleAccountCredentialAction(data, { if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' }; const email = normalizeAccountEmail(data?.email); if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' }; - const gemini = join(homedir(), '.gemini'); + const gemini = String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homedir(), '.gemini'); const config = { target: 'gemini:antigravity', vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'), diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 95de098..54c93e1 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -92,7 +92,8 @@ function projectDisplayStep(st) { const { stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, - streamDurationSec, selectedSpeedReason, anomaly, anomalySig, contextTokens, inputTokens, cacheReadTokens, + nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, anomaly, anomalySig, + contextTokens, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd, cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal, agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent, @@ -104,7 +105,7 @@ function projectDisplayStep(st) { return { stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, - streamDurationSec, selectedSpeedReason, + nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, ...(anomaly ? { anomaly, anomalySig } : {}), contextTokens, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 1c3b438..088a19e 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index f3e356f..60e391d 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -2921,6 +2921,9 @@ export function mountWindowOverlay() { window.removeEventListener?.('popstate', onPopState); navigator?.windowControlsOverlay?.removeEventListener?.('geometrychange', onWindowResize); restorePatchedActionToolbar(); + try { + multiRunningWidget.destroy(); + } catch {} try { hoverWidgetHost.destroy(); } catch {} diff --git a/sidecars/panel/src/components/settings/SessionMigrationCard.js b/sidecars/panel/src/components/settings/SessionMigrationCard.js index fec8d8e..05ff2bb 100644 --- a/sidecars/panel/src/components/settings/SessionMigrationCard.js +++ b/sidecars/panel/src/components/settings/SessionMigrationCard.js @@ -577,7 +577,7 @@ export const SessionMigrationCard = defineComponent({ } } - listScrollbar?.methods?.refresh?.(); + listScrollbar?.refresh?.(); patchAttr(migrateBtn, 'disabled', isMigrating || selectedIds.size === 0 || !targetClient); patchText( diff --git a/sidecars/panel/src/components/ui/CustomDateTimePicker.js b/sidecars/panel/src/components/ui/CustomDateTimePicker.js index e0d9681..d72c731 100644 --- a/sidecars/panel/src/components/ui/CustomDateTimePicker.js +++ b/sidecars/panel/src/components/ui/CustomDateTimePicker.js @@ -14,9 +14,18 @@ import { positionAnchoredPopup, } from '../../core/domPatch.js'; import { formatCompactDateTime } from '../../core/formatters.js'; +import { i18nStore, t } from '../../i18n/index.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; -const WEEKDAYS = ['一', '二', '三', '四', '五', '六', '日']; +const WEEKDAY_KEYS = [ + 'ui.dt.wdayMon', + 'ui.dt.wdayTue', + 'ui.dt.wdayWed', + 'ui.dt.wdayThu', + 'ui.dt.wdayFri', + 'ui.dt.wdaySat', + 'ui.dt.wdaySun', +]; function buildCalendarDays(viewYear, viewMonth, selectedDate) { const firstDay = new Date(viewYear, viewMonth, 1); @@ -77,7 +86,7 @@ export const CustomDateTimePicker = defineComponent({ { type: 'button', className: 'icon-btn', - 'aria-label': '上个月', + 'aria-label': t('ui.dt.prevMonth'), onClick: (e) => { e.stopPropagation(); viewMonth -= 1; @@ -96,7 +105,7 @@ export const CustomDateTimePicker = defineComponent({ { type: 'button', className: 'icon-btn', - 'aria-label': '下个月', + 'aria-label': t('ui.dt.nextMonth'), onClick: (e) => { e.stopPropagation(); viewMonth += 1; @@ -112,11 +121,10 @@ export const CustomDateTimePicker = defineComponent({ const navBar = h('div', { className: 'dt-nav' }, [prevMonthBtn, monthTitle, nextMonthBtn]); - const weekdayRow = h( - 'div', - { className: 'dt-weekdays' }, - WEEKDAYS.map((w) => h('span', { className: 'dt-weekday', text: w })) + const weekdaySpans = WEEKDAY_KEYS.map((key) => + h('span', { className: 'dt-weekday', text: t(key) }) ); + const weekdayRow = h('div', { className: 'dt-weekdays' }, weekdaySpans); const daysGrid = h('div', { className: 'dt-days' }); @@ -136,8 +144,9 @@ export const CustomDateTimePicker = defineComponent({ emit('update:modelValue', nextMs); } + const hourMinLabelEl = h('span', { className: 'text-muted', text: t('ui.dt.hourMinute') }); const timeRow = h('div', { className: 'dt-time-row' }, [ - h('span', { className: 'text-muted', text: '时 / 分' }), + hourMinLabelEl, h('div', { className: 'dt-time-controls' }, [ h('div', { className: 'dt-mini-step' }, [ h('button', { @@ -306,6 +315,25 @@ export const CustomDateTimePicker = defineComponent({ onCleanup(() => setRepositionListeners(false)); } + function syncI18nLabels() { + patchAttr(prevMonthBtn, 'aria-label', t('ui.dt.prevMonth')); + patchAttr(nextMonthBtn, 'aria-label', t('ui.dt.nextMonth')); + patchText(hourMinLabelEl, t('ui.dt.hourMinute')); + for (let i = 0; i < WEEKDAY_KEYS.length; i += 1) { + patchText(weekdaySpans[i], t(WEEKDAY_KEYS[i])); + } + } + + const unsubI18n = i18nStore.subscribe( + (st) => st.locale, + () => { + syncI18nLabels(); + syncDisplay(); + }, + { immediate: false } + ); + onCleanup(unsubI18n); + syncDisplay(); return { diff --git a/sidecars/panel/src/components/ui/CustomNumberInput.js b/sidecars/panel/src/components/ui/CustomNumberInput.js index fedd488..b6413c2 100644 --- a/sidecars/panel/src/components/ui/CustomNumberInput.js +++ b/sidecars/panel/src/components/ui/CustomNumberInput.js @@ -6,11 +6,12 @@ import { defineComponent } from '../../core/component.js'; import { h, patchAttr } from '../../core/domPatch.js'; +import { i18nStore, t } from '../../i18n/index.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; export const CustomNumberInput = defineComponent({ name: 'CustomNumberInput', - setup({ getProps, setProps, emit }) { + setup({ getProps, setProps, emit, onCleanup }) { function clampValue(raw) { const { min = -Infinity, max = Infinity, precision = 0 } = getProps(); const num = Number(raw); @@ -37,7 +38,7 @@ export const CustomNumberInput = defineComponent({ { type: 'button', className: 'num-step-btn', - 'aria-label': '减少数值', + 'aria-label': t('ui.num.decrease'), onClick: (e) => { e.preventDefault(); applyStep(-1, e.shiftKey ? 10 : 1); @@ -51,7 +52,7 @@ export const CustomNumberInput = defineComponent({ { type: 'button', className: 'num-step-btn', - 'aria-label': '增加数值', + 'aria-label': t('ui.num.increase'), onClick: (e) => { e.preventDefault(); applyStep(1, e.shiftKey ? 10 : 1); @@ -115,6 +116,15 @@ export const CustomNumberInput = defineComponent({ } const rootEl = h('div', { className: 'number-input' }, [decBtn, textField, incBtn]); + const unsubI18n = i18nStore.subscribe( + (st) => st.locale, + () => { + patchAttr(decBtn, 'aria-label', t('ui.num.decrease')); + patchAttr(incBtn, 'aria-label', t('ui.num.increase')); + }, + { immediate: false } + ); + onCleanup(unsubI18n); syncFieldDisplay(); return { diff --git a/sidecars/panel/src/components/ui/SegmentedControl.js b/sidecars/panel/src/components/ui/SegmentedControl.js index 834c53f..c5c50d6 100644 --- a/sidecars/panel/src/components/ui/SegmentedControl.js +++ b/sidecars/panel/src/components/ui/SegmentedControl.js @@ -7,6 +7,7 @@ import { defineComponent } from '../../core/component.js'; import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; +import { i18nStore, t } from '../../i18n/index.js'; export const SegmentedControl = defineComponent({ name: 'SegmentedControl', @@ -17,10 +18,18 @@ export const SegmentedControl = defineComponent({ { className: 'segmented', role: 'group', - 'aria-label': getProps().ariaLabel || '分段切换器', + 'aria-label': getProps().ariaLabel || t('ui.seg.defaultAria'), }, [gliderEl] ); + const unsubI18n = i18nStore.subscribe( + (st) => st.locale, + () => { + patchAttr(rootEl, 'aria-label', getProps().ariaLabel || t('ui.seg.defaultAria')); + }, + { immediate: false } + ); + onCleanup(unsubI18n); const btnMap = new Map(); let orderedBtns = []; diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index eb4a3b8..ff00382 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -21,6 +21,7 @@ import { resolveModelDisplayInfo, speedReasonText, } from '../../core/formatters.js'; +import { getStepSelectionKey } from '../../core/stepInspector.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { @@ -722,9 +723,11 @@ export const StepTableWidget = defineComponent({ } function getStepRowIdentity(st, fallbackCascadeId) { - const agentKey = String(st?.agentCascadeId || fallbackCascadeId || 'conv'); + const agentKey = String( + st?.agentCascadeId || st?.agentId || st?.cascadeId || fallbackCascadeId || 'conv' + ); const stepNum = Number(st?.stepIndex); - const rowKey = `${agentKey}-${st?.stepIndex}`; + const rowKey = getStepSelectionKey(st, fallbackCascadeId); return { agentKey, stepNum, rowKey }; } @@ -1100,7 +1103,7 @@ export const StepTableWidget = defineComponent({ logicalIdx: idx, isStripeEven: (idx & 1) === 1, hasReason: Boolean(hasReasonFlags && hasReasonFlags[idx]), - rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`, + rowKey: getStepSelectionKey(st, cascadeId), hasTurn, hasUp, hasDown, diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 413a55b..e09a243 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -829,14 +829,30 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { const speedSampleCount = Math.max(0, Number(m.speedSummary?.sampleCount || 0)); const speedExcludedCount = Math.max(0, Number(m.speedSummary?.excludedCount || 0)); const speedWeight = speedSampleCount > 0 ? speedSampleCount : Math.max(1, outTok || calls || 1); - const hasSpeed = m.avgTokPerSec != null && Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0; + const hasSpeed = + m.avgTokPerSec != null && Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0; + const rawSpeedTokens = Number(m.speedSummary?.tokens); + const rawSpeedSeconds = Number(m.speedSummary?.seconds); + const hasExactSpeedSummary = + Number.isFinite(rawSpeedTokens) && + Number.isFinite(rawSpeedSeconds) && + rawSpeedSeconds > 0 && + rawSpeedTokens >= 0; const ttftSampleCount = Math.max(0, Number(m.ttftSampleCount || 0)); const ttftWeight = ttftSampleCount > 0 ? ttftSampleCount : Math.max(1, calls || 1); - const hasTtft = m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0; + const hasTtft = + m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0; let acc = byDisplay.get(key); if (!acc) { + const initExcludedReasons = {}; + if (m.speedSummary?.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { + for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { + const cnt = Math.max(0, Number(rv || 0)); + if (cnt > 0) initExcludedReasons[rk] = cnt; + } + } acc = { baseItem: m, mergedCount: 1, @@ -856,10 +872,15 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { totalTokens: totTok, costUsd, unpricedCalls, + hasAnySpeedSummary: Boolean(m.speedSummary), + allSpeedExact: !hasSpeed || hasExactSpeedSummary, + speedTokens: hasExactSpeedSummary ? rawSpeedTokens : 0, + speedSeconds: hasExactSpeedSummary ? rawSpeedSeconds : 0, speedWeightedSum: hasSpeed ? Number(m.avgTokPerSec) * speedWeight : 0, speedWeight: hasSpeed ? speedWeight : 0, speedSampleCount, speedExcludedCount, + speedExcludedReasons: initExcludedReasons, ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0, ttftWeight: hasTtft ? ttftWeight : 0, ttftSampleCount, @@ -908,12 +929,24 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { } } + if (m.speedSummary) acc.hasAnySpeedSummary = true; + if (hasSpeed && !hasExactSpeedSummary) acc.allSpeedExact = false; + if (hasExactSpeedSummary) { + acc.speedTokens += rawSpeedTokens; + acc.speedSeconds += rawSpeedSeconds; + } if (hasSpeed) { acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight; acc.speedWeight += speedWeight; } acc.speedSampleCount += speedSampleCount; acc.speedExcludedCount += speedExcludedCount; + if (m.speedSummary?.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { + for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { + const cnt = Math.max(0, Number(rv || 0)); + if (cnt > 0) acc.speedExcludedReasons[rk] = (acc.speedExcludedReasons[rk] || 0) + cnt; + } + } if (hasTtft) { acc.ttftWeightedSum += Number(m.avgTtftSec) * ttftWeight; @@ -933,8 +966,13 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { } const promptTok = acc.inputTokens + acc.cacheReadTokens; const cacheHitPct = promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0; - const avgTokPerSec = - acc.speedWeight > 0 ? +(acc.speedWeightedSum / acc.speedWeight).toFixed(1) : null; + const rawAvgTps = + acc.allSpeedExact && acc.speedSeconds > 0 + ? acc.speedTokens / acc.speedSeconds + : acc.speedWeight > 0 + ? acc.speedWeightedSum / acc.speedWeight + : null; + const avgTokPerSec = rawAvgTps !== null ? +rawAvgTps.toFixed(1) : null; const avgTtftSec = acc.ttftWeight > 0 ? +(acc.ttftWeightedSum / acc.ttftWeight).toFixed(1) : null; const upstreamModels = Array.from(acc.upstreamSet); @@ -967,12 +1005,15 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { anomalyByKind: acc.anomalyByKind, } : {}), - speedSummary: acc.baseItem.speedSummary + speedSummary: acc.hasAnySpeedSummary ? { - ...acc.baseItem.speedSummary, + ...(acc.baseItem.speedSummary || {}), + tokens: acc.speedTokens, + seconds: +acc.speedSeconds.toFixed(6), sampleCount: acc.speedSampleCount, excludedCount: acc.speedExcludedCount, - avgTokPerSec, + excludedReasons: acc.speedExcludedReasons, + avgTokPerSec: rawAvgTps, } : undefined, upstreamModels, diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index 1f4c3c2..9fba24f 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -172,7 +172,8 @@ function summarizeStepsForExport(list, displaySettings) { let sumCost = 0; let sumDuration = 0; let maxContext = 0; - let tpsSum = 0; + let tpsTokSum = 0; + let tpsSecSum = 0; let tpsCnt = 0; let ttftSum = 0; let ttftCnt = 0; @@ -194,7 +195,8 @@ function summarizeStepsForExport(list, displaySettings) { : Math.max(0, outTok - thinkTok); const ctxTok = Math.max(0, Number(st.contextTokens || inTok + cacheTok + outTok)); const cost = Number(st.costUsd || 0); - const dur = Number(st.durationSec || 0); + const rawDur = st.totalDurationSec ?? st.durationSec; + const dur = rawDur != null && Number.isFinite(Number(rawDur)) ? Number(rawDur) : 0; sumIn += inTok; sumCache += cacheTok; @@ -206,11 +208,21 @@ function summarizeStepsForExport(list, displaySettings) { if (Number.isFinite(dur) && dur > 0) sumDuration += dur; const validTps = - !st.isCompactionStep && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0; + !st.isCompactionStep && + outTok >= 50 && + !st.selectedSpeedReason && + Number.isFinite(Number(st.tokPerSec)) && + Number(st.tokPerSec) > 0; + const stepSpeedSec = validTps + ? st.totalDurationSec != null && Number(st.totalDurationSec) >= 0.5 + ? Number(st.totalDurationSec) + : outTok / Number(st.tokPerSec) + : 0; const validTtft = !st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0; - if (validTps) { - tpsSum += Number(st.tokPerSec); + if (validTps && stepSpeedSec > 0) { + tpsTokSum += outTok; + tpsSecSum += stepSpeedSec; tpsCnt += 1; } if (validTtft) { @@ -235,7 +247,8 @@ function summarizeStepsForExport(list, displaySettings) { cacheTok: 0, outTok: 0, cost: 0, - tpsSum: 0, + tpsTokSum: 0, + tpsSecSum: 0, tpsCnt: 0, ttftSum: 0, ttftCnt: 0, @@ -247,8 +260,9 @@ function summarizeStepsForExport(list, displaySettings) { mAcc.cacheTok += cacheTok; mAcc.outTok += outTok; if (Number.isFinite(cost) && cost > 0) mAcc.cost += cost; - if (validTps) { - mAcc.tpsSum += Number(st.tokPerSec); + if (validTps && stepSpeedSec > 0) { + mAcc.tpsTokSum += outTok; + mAcc.tpsSecSum += stepSpeedSec; mAcc.tpsCnt += 1; } if (validTtft) { @@ -272,7 +286,8 @@ function summarizeStepsForExport(list, displaySettings) { sumCost, sumDuration, maxContext, - tpsSum, + tpsTokSum, + tpsSecSum, tpsCnt, ttftSum, ttftCnt, @@ -455,8 +470,9 @@ export function buildStepsCsv(steps, { displaySettings = {}, includeBom = true } st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) ? Number(st.ttftSec).toFixed(3) : '', - st.durationSec != null && Number.isFinite(Number(st.durationSec)) - ? Number(st.durationSec).toFixed(3) + (st.totalDurationSec ?? st.durationSec) != null && + Number.isFinite(Number(st.totalDurationSec ?? st.durationSec)) + ? Number(st.totalDurationSec ?? st.durationSec).toFixed(3) : '', inTok, cacheTok, @@ -523,9 +539,10 @@ export function buildStepsXlsx( !st.isCompactionStep && st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) ? Number(st.ttftSec) : null; + const rawDurVal = st.totalDurationSec ?? st.durationSec; const durVal = - st.durationSec != null && Number.isFinite(Number(st.durationSec)) - ? Number(st.durationSec) + rawDurVal != null && Number.isFinite(Number(rawDurVal)) + ? Number(rawDurVal) : null; const costVal = st.costUsd != null && Number.isFinite(Number(st.costUsd)) ? Number(st.costUsd) : null; @@ -577,7 +594,7 @@ export function buildStepsXlsx( ? `${agg.compactionCount} compact` : `含 ${agg.compactionCount} 次压缩` : '', - agg.tpsCnt > 0 ? +(agg.tpsSum / agg.tpsCnt).toFixed(1) : null, + agg.tpsSecSum > 0 ? +(agg.tpsTokSum / agg.tpsSecSum).toFixed(1) : null, agg.ttftCnt > 0 ? +(agg.ttftSum / agg.ttftCnt).toFixed(2) : null, agg.sumDuration > 0 ? +agg.sumDuration.toFixed(2) : null, agg.sumIn, @@ -636,7 +653,7 @@ export function buildStepsXlsx( m.outTok, mTotal, computeCacheHitRatio(m.inTok, m.cacheTok), - m.tpsCnt > 0 ? +(m.tpsSum / m.tpsCnt).toFixed(1) : null, + m.tpsSecSum > 0 ? +(m.tpsTokSum / m.tpsSecSum).toFixed(1) : null, m.ttftCnt > 0 ? +(m.ttftSum / m.ttftCnt).toFixed(2) : null, m.cost, ]; @@ -651,7 +668,7 @@ export function buildStepsXlsx( agg.sumOut, agg.sumIn + agg.sumCache + agg.sumOut, computeCacheHitRatio(agg.sumIn, agg.sumCache), - agg.tpsCnt > 0 ? +(agg.tpsSum / agg.tpsCnt).toFixed(1) : null, + agg.tpsSecSum > 0 ? +(agg.tpsTokSum / agg.tpsSecSum).toFixed(1) : null, agg.ttftCnt > 0 ? +(agg.ttftSum / agg.ttftCnt).toFixed(2) : null, agg.sumCost, ], @@ -695,7 +712,8 @@ export function buildStepsMarkdownReport( const totalTok = agg.sumIn + agg.sumCache + agg.sumOut; const cacheHitPct = formatPctNumber(computeCacheHitRatio(agg.sumIn, agg.sumCache) * 100); - const avgTps = agg.tpsCnt > 0 ? formatSpeedMetric(agg.tpsSum / agg.tpsCnt, ' tok/s') : '—'; + const avgTps = + agg.tpsSecSum > 0 ? formatSpeedMetric(agg.tpsTokSum / agg.tpsSecSum, ' tok/s') : '—'; const avgTtft = agg.ttftCnt > 0 ? formatMetric(agg.ttftSum / agg.ttftCnt, 's') : '—'; const heading = title ? `# ${title}` @@ -738,7 +756,8 @@ export function buildStepsMarkdownReport( const mCache = formatPctNumber(computeCacheHitRatio(m.inTok, m.cacheTok) * 100, { withSymbol: true, }); - const mTps = m.tpsCnt > 0 ? formatSpeedMetric(m.tpsSum / m.tpsCnt, ' tok/s') : '—'; + const mTps = + m.tpsSecSum > 0 ? formatSpeedMetric(m.tpsTokSum / m.tpsSecSum, ' tok/s') : '—'; lines.push( `| ${escapeMdCell(m.label)} | ${m.calls} | ${formatTokensPrecise(mTotal)} | ${mCache} | ${mTps} | ${formatUsd(m.cost, { precise: m.cost > 0 && m.cost < 0.1 })} |` ); @@ -1053,8 +1072,8 @@ export function buildConsumptionXlsx( let mOut = 0; let mTot = 0; let mCost = 0; - let tpsWeighted = 0; - let tpsWeight = 0; + let tpsTokSum = 0; + let tpsSecSum = 0; const modelRows = models.map((m, idx) => { const calls = Math.max(0, Number(m.calls || 0)); const inTok = Math.max(0, Number(m.inputTokens || 0)); @@ -1072,10 +1091,20 @@ export function buildConsumptionXlsx( mOut += outTok; mTot += totTok; mCost += cost; - if (tps != null) { - const w = Math.max(1, outTok || calls); - tpsWeighted += tps * w; - tpsWeight += w; + const rawSpeedTok = Number(m.speedSummary?.tokens); + const rawSpeedSec = Number(m.speedSummary?.seconds); + if ( + Number.isFinite(rawSpeedTok) && + Number.isFinite(rawSpeedSec) && + rawSpeedSec > 0 && + rawSpeedTok >= 0 + ) { + tpsTokSum += rawSpeedTok; + tpsSecSum += rawSpeedSec; + } else if (tps != null) { + const fallbackTok = outTok > 0 ? outTok : Math.max(1, calls); + tpsTokSum += fallbackTok; + tpsSecSum += fallbackTok / tps; } return [ idx + 1, @@ -1101,7 +1130,7 @@ export function buildConsumptionXlsx( mOut, mTot, computeCacheHitRatio(mIn, mCache), - tpsWeight > 0 ? +(tpsWeighted / tpsWeight).toFixed(1) : null, + tpsSecSum > 0 ? +(tpsTokSum / tpsSecSum).toFixed(1) : null, mCost, ], }); diff --git a/sidecars/panel/src/core/stepInspector.js b/sidecars/panel/src/core/stepInspector.js index af59555..c51cd33 100644 --- a/sidecars/panel/src/core/stepInspector.js +++ b/sidecars/panel/src/core/stepInspector.js @@ -30,7 +30,8 @@ export const STEP_SLOW_TTFT_MIN_SEC = 30; */ export function getStepSelectionKey(st, fallbackCascadeId = '') { if (!st || typeof st !== 'object') return ''; - const agentKey = st.agentId || st.cascadeId || fallbackCascadeId || 'main'; + const agentKey = + st.agentCascadeId || st.agentId || st.cascadeId || fallbackCascadeId || 'conv'; return `${agentKey}-${st.stepIndex}`; } @@ -125,6 +126,11 @@ export function filterStepsBySearchAndChip( if (rawTerms.length > 0) { const modelInfo = resolveModelDisplayInfo(st, displaySettings); const anomalyKinds = st.anomaly?.kinds ? Object.keys(st.anomaly.kinds).join(' ') : ''; + const anomalyEventsText = Array.isArray(st.anomaly?.events) + ? st.anomaly.events + .map((ev) => `${ev?.kind || ''} ${ev?.attempt ?? ''} ${ev?.message || ''}`) + .join(' ') + : ''; const anomalyItemsText = Array.isArray(st.anomaly?.items) ? st.anomaly.items .map((it) => `${it?.kind || ''} ${it?.httpStatus || ''} ${it?.detail || ''}`) @@ -137,6 +143,9 @@ export function filterStepsBySearchAndChip( modelInfo.title, st.modelLabel || '', st.modelShort || '', + st.modelKey || '', + st.modelUpstream || '', + st.responseModel || '', st.rawModelId || '', st.upstreamName || '', st.turnPrompt || '', @@ -146,6 +155,7 @@ export function filterStepsBySearchAndChip( st.agentBadge || '', st.isCompactionStep ? 'compaction 压缩' : '', anomalyKinds, + anomalyEventsText, anomalyItemsText, ] .join(' ') @@ -210,15 +220,15 @@ export function findPrevAgentContextTokens(allSteps, targetStep) { */ export function computeStepTimingWaterfall(st) { if (!st || typeof st !== 'object') return null; + const rawTtft = st.ttftSec ?? st.nativeTtftSec; const ttft = - st.ttftSec != null && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0 - ? Number(st.ttftSec) + rawTtft != null && Number.isFinite(Number(rawTtft)) && Number(rawTtft) >= 0 + ? Number(rawTtft) : 0; + const rawStream = st.nativeStreamSec ?? st.streamDurationSec; const stream = - st.streamDurationSec != null && - Number.isFinite(Number(st.streamDurationSec)) && - Number(st.streamDurationSec) >= 0 - ? Number(st.streamDurationSec) + rawStream != null && Number.isFinite(Number(rawStream)) && Number(rawStream) >= 0 + ? Number(rawStream) : 0; const thinking = st.thinkingDurationSec != null && @@ -226,9 +236,10 @@ export function computeStepTimingWaterfall(st) { Number(st.thinkingDurationSec) >= 0 ? Number(st.thinkingDurationSec) : 0; + const rawDur = st.totalDurationSec ?? st.durationSec; const rawTotal = - st.durationSec != null && Number.isFinite(Number(st.durationSec)) && Number(st.durationSec) > 0 - ? Number(st.durationSec) + rawDur != null && Number.isFinite(Number(rawDur)) && Number(rawDur) > 0 + ? Number(rawDur) : ttft + stream; const totalSec = Math.max(rawTotal, ttft + stream); if (!(totalSec > 0)) return null; diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 3aa9ebe..81c4176 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -873,4 +873,19 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', 'chart.trend.hmActiveZero': 'Active 0/{total}d', 'chart.trend.peakPill': 'Peak {label} · {tokens}', + + // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) + 'ui.dt.wdayMon': 'Mo', + 'ui.dt.wdayTue': 'Tu', + 'ui.dt.wdayWed': 'We', + 'ui.dt.wdayThu': 'Th', + 'ui.dt.wdayFri': 'Fr', + 'ui.dt.wdaySat': 'Sa', + 'ui.dt.wdaySun': 'Su', + 'ui.dt.prevMonth': 'Previous month', + 'ui.dt.nextMonth': 'Next month', + 'ui.dt.hourMinute': 'Hr / Min', + 'ui.num.decrease': 'Decrease value', + 'ui.num.increase': 'Increase value', + 'ui.seg.defaultAria': 'Segmented switcher', }); diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 5297365..0e0602b 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -873,4 +873,19 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', 'chart.trend.hmActiveZero': '活跃 0/{total} 天', 'chart.trend.peakPill': '峰值 {label} · {tokens}', + + // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) + 'ui.dt.wdayMon': '一', + 'ui.dt.wdayTue': '二', + 'ui.dt.wdayWed': '三', + 'ui.dt.wdayThu': '四', + 'ui.dt.wdayFri': '五', + 'ui.dt.wdaySat': '六', + 'ui.dt.wdaySun': '日', + 'ui.dt.prevMonth': '上个月', + 'ui.dt.nextMonth': '下个月', + 'ui.dt.hourMinute': '时 / 分', + 'ui.num.decrease': '减少数值', + 'ui.num.increase': '增加数值', + 'ui.seg.defaultAria': '分段切换器', }); diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index 00bd223..01c7705 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -78,7 +78,7 @@ import { SegmentedControl } from '../components/ui/SegmentedControl.js'; import { StepTableWidget } from '../components/widgets/StepTableWidget.js'; import { sortStepsByColumn } from '../registries/stepColumnRegistry.js'; -function mergeSelectedAgentUnits(units) { +export function mergeSelectedAgentUnits(units) { const combinedSteps = []; const modelMap = new Map(); @@ -115,10 +115,15 @@ function mergeSelectedAgentUnits(units) { anomalyDangerCount: 0, anomalyTotalDelaySec: 0, anomalyByKind: {}, - _speedWeightedSum: 0, - _speedWeight: 0, + _hasAnySpeedSummary: false, + _speedTokens: 0, + _speedSeconds: 0, + _speedSampleCount: 0, + _speedExcludedCount: 0, + _speedExcludedReasons: {}, _ttftWeightedSum: 0, _ttftWeight: 0, + _ttftSampleCount: 0, }; if (acc.upstreamName) acc.upstreamSet.add(acc.upstreamName); modelMap.set(gk, acc); @@ -165,19 +170,43 @@ function mergeSelectedAgentUnits(units) { } } - if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) { - const w = Math.max(1, outTok || calls || 1); - acc._speedWeightedSum += Number(m.avgTokPerSec) * w; - acc._speedWeight += w; + const rawSpeedTok = Number(m.speedSummary?.tokens); + const rawSpeedSec = Number(m.speedSummary?.seconds); + if ( + Number.isFinite(rawSpeedTok) && + Number.isFinite(rawSpeedSec) && + rawSpeedSec > 0 && + rawSpeedTok >= 0 + ) { + acc._hasAnySpeedSummary = true; + acc._speedTokens += rawSpeedTok; + acc._speedSeconds += rawSpeedSec; + } else if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) { + const fallbackTok = outTok > 0 ? outTok : Math.max(1, calls || 1); + acc._speedTokens += fallbackTok; + acc._speedSeconds += fallbackTok / Number(m.avgTokPerSec); + } + if (m.speedSummary) { + acc._hasAnySpeedSummary = true; + acc._speedSampleCount += Math.max(0, Number(m.speedSummary.sampleCount || 0)); + acc._speedExcludedCount += Math.max(0, Number(m.speedSummary.excludedCount || 0)); + if (m.speedSummary.excludedReasons && typeof m.speedSummary.excludedReasons === 'object') { + for (const [rk, rv] of Object.entries(m.speedSummary.excludedReasons)) { + const cnt = Math.max(0, Number(rv || 0)); + if (cnt > 0) acc._speedExcludedReasons[rk] = (acc._speedExcludedReasons[rk] || 0) + cnt; + } + } } if ( m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0 ) { - const w = Math.max(1, calls || 1); + const ttftSamples = Math.max(0, Number(m.ttftSampleCount || 0)); + const w = ttftSamples > 0 ? ttftSamples : Math.max(1, calls || 1); acc._ttftWeightedSum += Number(m.avgTtftSec) * w; acc._ttftWeight += w; + acc._ttftSampleCount += ttftSamples; } } } @@ -192,6 +221,7 @@ function mergeSelectedAgentUnits(units) { const mergedModels = Array.from(modelMap.values()) .map((acc) => { const promptTok = acc.inputTokens + acc.cacheReadTokens; + const rawAvgTps = acc._speedSeconds > 0 ? acc._speedTokens / acc._speedSeconds : null; return { label: acc.label, shortName: acc.shortName, @@ -207,10 +237,22 @@ function mergeSelectedAgentUnits(units) { totalTokens: acc.totalTokens, costUsd: +acc.costUsd.toFixed(6), unpricedCalls: acc.unpricedCalls, - avgTokPerSec: - acc._speedWeight > 0 ? +(acc._speedWeightedSum / acc._speedWeight).toFixed(1) : null, + avgTokPerSec: rawAvgTps !== null ? +rawAvgTps.toFixed(1) : null, avgTtftSec: acc._ttftWeight > 0 ? +(acc._ttftWeightedSum / acc._ttftWeight).toFixed(1) : null, + ttftSampleCount: acc._ttftSampleCount, + ...(acc._hasAnySpeedSummary + ? { + speedSummary: { + tokens: acc._speedTokens, + seconds: +acc._speedSeconds.toFixed(6), + sampleCount: acc._speedSampleCount, + excludedCount: acc._speedExcludedCount, + excludedReasons: acc._speedExcludedReasons, + avgTokPerSec: rawAvgTps, + }, + } + : {}), cacheHitPct: promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0, ...(acc.anomalyCount > 0 ? { diff --git a/sidecars/panel/test/practical-enhancements.test.mjs b/sidecars/panel/test/practical-enhancements.test.mjs index e10dae6..c9eb538 100644 --- a/sidecars/panel/test/practical-enhancements.test.mjs +++ b/sidecars/panel/test/practical-enhancements.test.mjs @@ -2107,3 +2107,412 @@ test('Feature 14: compact vertical ActionMenu replaces export bars, backend expo assert.equal(failedRes.mode, 'failed'); assert.equal(uiStore.getState().toast?.tone, 'warn'); }); + +test('P0 regression: V4 display-projected steps open inspector, preserve waterfall/diagnostics/XLSX duration, match anomaly events, compute harmonic speed, and clean up UI observers/i18n', async (t) => { + const { extractModelSteps, summarizeSpeed } = await import('../trajectory-metrics.mjs'); + const { handleAccountCredentialAction } = await import('../backend/account-switch.mjs'); + const { + getStepSelectionKey, + computeStepTimingWaterfall, + filterStepsBySearchAndChip, + } = await import('../src/core/stepInspector.js'); + const { + buildStepTimingDiagnostic, + mergeModelsByDisplayName, + } = await import('../src/core/formatters.js'); + const { + buildStepsXlsx, + buildStepsCsv, + buildStepsMarkdownReport, + buildConsumptionXlsx, + } = await import('../src/core/reportExporter.js'); + const { StepsDetailView, mergeSelectedAgentUnits } = await import('../src/views/StepsDetailView.js'); + const { CustomDateTimePicker } = await import('../src/components/ui/CustomDateTimePicker.js'); + const { CustomNumberInput } = await import('../src/components/ui/CustomNumberInput.js'); + const { SegmentedControl } = await import('../src/components/ui/SegmentedControl.js'); + const { mountWindowOverlay } = await import('../src/components/layout/WindowOverlayShell.js'); + const { WINDOW_OVERLAY_KEY } = await import('../shared/window-bridge-protocol.mjs'); + const { uiStore } = await import('../src/store/uiStore.js'); + const { telemetryStore } = await import('../src/store/telemetryStore.js'); + const { i18nStore, setI18nLanguage } = await import('../src/i18n/index.js'); + + function parseZipEntries(bytes) { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const entries = new Map(); + let pos = 0; + while (pos + 30 <= bytes.length && view.getUint32(pos, true) === 0x04034b50) { + const compSize = view.getUint32(pos + 18, true); + const nameLen = view.getUint16(pos + 26, true); + const extraLen = view.getUint16(pos + 28, true); + const nameStart = pos + 30; + const dataStart = nameStart + nameLen + extraLen; + const name = Buffer.from(bytes.subarray(nameStart, nameStart + nameLen)).toString('utf8'); + const text = Buffer.from(bytes.subarray(dataStart, dataStart + compSize)).toString('utf8'); + entries.set(name, text); + pos = dataStart + compSize; + } + return entries; + } + + // Extract genuine V4 step with nativeTtftSec, nativeStreamSec, thinkingDurationSec, toolCalls, and retryInfos + const rawSteps = [ + { + type: 'CORTEX_STEP_TYPE_USER_INPUT', + metadata: { createdAt: '2026-11-22T10:00:00Z' }, + userInput: { items: [{ text: 'Inspect V4 projected telemetry step' }] }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-22T10:00:01Z', + completedAt: '2026-11-22T10:00:11.050Z', + generatorModel: 'MODEL_PLACEHOLDER_M37', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: '4000', + outputTokens: '200', + thinkingTokens: '120', + cacheReadInputTokens: '16000', + }, + retryInfos: [ + { + attempt: 1, + error: 'HTTP 429 Resource Exhausted UniqueQuotaToken777', + retryDelay: '2.5s', + }, + ], + }, + plannerResponse: { + response: 'Completed', + thinkingDuration: '8.64s', + toolCalls: [{ id: 'tc-1', name: 'read_file' }], + }, + }, + ]; + const generatorMetadata = [ + { + stepIndices: [1], + chatModel: { + usage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: '4000', + outputTokens: '200', + thinkingOutputTokens: '120', + cacheReadTokens: '16000', + }, + timeToFirstToken: '8.32s', + streamingDuration: '1.73s', + }, + }, + ]; + const [extracted] = extractModelSteps(rawSteps, generatorMetadata); + const cascadeUuid = '28a876b9-8b93-4dbd-8c0b-3b6101fc481d'; + const projectedLikeStep = { + stepIndex: extracted.stepIndex, + createdAtMs: extracted.createdAtMs, + isCompactionStep: extracted.isCompactionStep, + modelKey: extracted.modelKey, + modelShort: '3.1-pro-h', + modelLabel: 'Gemini 3.1 Pro (High)', + modelUpstream: 'gemini-3.1-pro-high-upstream-id', + responseModel: '', + modelSource: extracted.modelSource, + tokPerSec: +(extracted.outputTokens / extracted.totalDurationSec).toFixed(1), + ttftSec: extracted.nativeTtftSec, + totalDurationSec: extracted.totalDurationSec, + nativeStreamSec: extracted.nativeStreamSec, + thinkingDurationSec: extracted.thinkingDurationSec, + hasToolCalls: extracted.hasToolCalls, + selectedSpeedReason: extracted.speedReason, + anomaly: extracted.anomaly, + anomalySig: extracted.anomalySig, + contextTokens: 20200, + inputTokens: extracted.inputTokens, + cacheReadTokens: extracted.cacheReadTokens, + outputTokens: extracted.outputTokens, + thinkingTokens: extracted.thinkingTokens, + responseTokens: extracted.responseTokens, + cacheHitPct: 80, + costUsd: 0.042, + agentId: 'main', + agentCascadeId: cascadeUuid, + agentLabel: 'Main', + agentBadge: 'MAIN', + agentIndex: 0, + isSubagent: false, + turnIndex: extracted.turnIndex, + isTurnStart: extracted.isTurnStart, + isLatestTurn: true, + turnPrompt: extracted.turnPrompt, + }; + + // B-04: Anomaly event message, modelKey, and modelUpstream search + assert.equal( + filterStepsBySearchAndChip([projectedLikeStep], { query: 'UniqueQuotaToken777' }).length, + 1 + ); + assert.equal( + filterStepsBySearchAndChip([projectedLikeStep], { query: 'MODEL_PLACEHOLDER_M37' }).length, + 1 + ); + assert.equal( + filterStepsBySearchAndChip([projectedLikeStep], { + query: 'gemini-3.1-pro-high-upstream-id', + }).length, + 1 + ); + + // B-02 & B-03: Waterfall, XLSX H2 duration cell, CSV duration, and timing diagnostic parity + const wf = computeStepTimingWaterfall(projectedLikeStep); + assert.equal(wf.totalSec, 10.05); + assert.equal(wf.ttftSec, 8.32); + assert.equal(wf.streamSec, 1.73); + assert.equal(wf.thinkingSec, 8.64); + + const xlsxXml = parseZipEntries(buildStepsXlsx([projectedLikeStep], { locale: 'en-US' })).get( + 'xl/worksheets/sheet1.xml' + ); + assert.match(xlsxXml, /]*>10\.05<\/v><\/c>/); + assert.match(buildStepsCsv([projectedLikeStep], { includeBom: false }), /,10\.050,/); + + setI18nLanguage('zh-CN'); + const diag = buildStepTimingDiagnostic(projectedLikeStep); + assert.equal(diag.rows.length, 3); + assert.match(diag.rows[1].text, /流式返回/); + assert.match(diag.rows[2].text, /原生思考计时/); + assert.match(diag.hint, /重叠/); + + // B-05: Speed aggregation matches official summarizeSpeed (18.2 tok/s, not 55.0 tok/s) and skips <50 tok short samples + const stepSlow = { + measurementVersion: 4, + isComplete: true, + isCompactionStep: false, + speedSampleEligible: true, + speedReason: null, + selectedSpeedReason: null, + stepIndex: 1, + modelShort: '4-neon', + modelLabel: 'Gemini 4 Neon', + outputTokens: 100, + totalDurationSec: 10, + totalTokPerSec: 10, + tokPerSec: 10, + }; + const stepFast = { + ...stepSlow, + stepIndex: 2, + totalDurationSec: 1, + totalTokPerSec: 100, + tokPerSec: 100, + }; + const stepShort = { + ...stepSlow, + stepIndex: 3, + speedSampleEligible: false, + speedReason: 'short_sample', + selectedSpeedReason: 'short_sample', + outputTokens: 10, + totalDurationSec: 0.5, + totalTokPerSec: 20, + tokPerSec: 20, + }; + const mSlow = { + label: 'Gemini 4 Neon', + shortName: '4-neon', + rawModel: 'MODEL_A', + calls: 1, + outputTokens: 100, + totalTokens: 100, + avgTokPerSec: 10, + speedSummary: summarizeSpeed([stepSlow]), + }; + const mFast = { + label: 'Gemini 4 Neon', + shortName: '4-neon', + rawModel: 'MODEL_A', + calls: 1, + outputTokens: 100, + totalTokens: 100, + avgTokPerSec: 100, + speedSummary: summarizeSpeed([stepFast]), + }; + const mergedDisplay = mergeModelsByDisplayName( + [mSlow, { ...mFast, rawModel: 'MODEL_B' }], + { modelDisplayMode: 'short' } + ); + assert.equal(mergedDisplay[0].avgTokPerSec, 18.2); + assert.equal(mergedDisplay[0].speedSummary.tokens, 200); + assert.equal(mergedDisplay[0].speedSummary.seconds, 11); + + const mergedUnits = mergeSelectedAgentUnits([ + { recentSteps: [stepSlow], modelBreakdown: [mSlow] }, + { recentSteps: [stepFast], modelBreakdown: [mFast] }, + ]); + assert.equal(mergedUnits.models[0].avgTokPerSec, 18.2); + + const consXlsxXml = parseZipEntries( + buildConsumptionXlsx( + { selectedRange: { key: '7d', label: '7d' }, account: { calls: 2, outputTokens: 200 } }, + [ + { ...mSlow, label: 'Slow', shortName: 'slow' }, + { ...mFast, label: 'Fast', shortName: 'fast' }, + ], + { locale: 'en-US' } + ) + ).get('xl/worksheets/sheet2.xml'); + assert.match(consXlsxXml, /]*>18\.2<\/v><\/c>/); + assert.match( + buildStepsMarkdownReport([stepSlow, stepFast, stepShort], { locale: 'en-US' }), + /\*\*Avg Speed\*\*: 18\.2 tok\/s/ + ); + + // B-01 & B-07 DOM checks: click real projected step opens drawer + i18n controls + WindowOverlayShell ResizeObserver cleanup + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevRo = globalThis.ResizeObserver; + const prevMo = globalThis.MutationObserver; + const prevUi = uiStore.getState(); + const prevTel = telemetryStore.getState(); + const prevLocale = i18nStore.getState().language; + + const { document } = createMockDom(); + globalThis.document = document; + let activeResizeObservers = 0; + globalThis.ResizeObserver = class { + constructor() { + this.connected = false; + } + observe() { + if (!this.connected) { + this.connected = true; + activeResizeObservers += 1; + } + } + unobserve() {} + disconnect() { + if (this.connected) { + this.connected = false; + activeResizeObservers -= 1; + } + } + }; + globalThis.MutationObserver = class { + observe() {} + disconnect() {} + }; + globalThis.window = { + innerWidth: 1280, + innerHeight: 800, + addEventListener() {}, + removeEventListener() {}, + requestAnimationFrame: (fn) => setTimeout(fn, 0), + cancelAnimationFrame: (id) => clearTimeout(id), + }; + + let stepsView = null; + let overlay = null; + t.after(() => { + stepsView?.destroy?.(); + overlay?.dispose?.(); + uiStore.setState(prevUi, { sync: true }); + telemetryStore.setState(prevTel, { sync: true }); + setI18nLanguage(prevLocale); + globalThis.document = prevDoc; + globalThis.window = prevWin; + globalThis.ResizeObserver = prevRo; + globalThis.MutationObserver = prevMo; + }); + + uiStore.setState({ activeView: 'steps', stepsSubTab: 'steps', monitorVisible: true }, { sync: true }); + telemetryStore.setState( + { + telemetry: { + settings: { stepTableColumns: ['step', 'model', 'tps', 'duration', 'cost'] }, + activeConversation: { + cascadeId: cascadeUuid, + stepCount: 1, + recentSteps: [projectedLikeStep], + modelBreakdown: [], + }, + }, + }, + { sync: true } + ); + stepsView = StepsDetailView(); + document.body.appendChild(stepsView.el); + assert.equal( + getStepSelectionKey(projectedLikeStep, cascadeUuid), + `${cascadeUuid}-${projectedLikeStep.stepIndex}` + ); + const tr = stepsView.el.querySelectorAll('tbody tr')[0]; + tr.onclick({}); + assert.equal(stepsView.refs.stepInspectorDrawerEl.hasAttribute('hidden'), false); + stepsView.destroy(); + stepsView = null; + + // B-07 i18n reactive switching + setI18nLanguage('en-US'); + const dt = CustomDateTimePicker({ modelValue: Date.UTC(2026, 10, 22, 12, 30) }); + const num = CustomNumberInput({ modelValue: 5 }); + const seg = SegmentedControl({ options: [{ label: 'A', value: 'a' }], modelValue: 'a' }); + assert.equal(dt.el.querySelector('.dt-weekdays').textContent, 'MoTuWeThFrSaSu'); + assert.equal(dt.el.querySelector('.dt-time-row .text-muted').textContent, 'Hr / Min'); + assert.equal(num.el.querySelectorAll('.num-step-btn')[0].getAttribute('aria-label'), 'Decrease value'); + assert.equal(seg.el.getAttribute('aria-label'), 'Segmented switcher'); + setI18nLanguage('zh-CN'); + await Promise.resolve(); + assert.equal(dt.el.querySelector('.dt-weekdays').textContent, '一二三四五六日'); + assert.equal(dt.el.querySelector('.dt-time-row .text-muted').textContent, '时 / 分'); + dt.destroy(); + num.destroy(); + seg.destroy(); + + // B-07 WindowOverlayShell dispose cleans up multiRunningWidget subScroll ResizeObserver + const roBaseline = activeResizeObservers; + globalThis.window[WINDOW_OVERLAY_KEY] = { isMultiPinnedOpen: () => true, dispose() {} }; + overlay = mountWindowOverlay(); + telemetryStore.setState( + { + telemetry: { + settings: {}, + runningConversations: [ + { + cascadeId: 'run-ro-1', + title: 'Swarm Run', + isMainRunning: true, + subagentCount: 1, + runningSubagentCount: 1, + subagents: [{ cascadeId: 'sub-ro-1', isRunning: true, stepCount: 2 }], + }, + ], + activeConversation: { cascadeId: 'run-ro-1', recentSteps: [], modelBreakdown: [] }, + }, + }, + { sync: true } + ); + overlay.dispose(); + overlay = null; + assert.equal(activeResizeObservers, roBaseline); + + // B-07 account-switch honors ANTIGRAVITY_GEMINI_DIR + const prevGemEnv = process.env.ANTIGRAVITY_GEMINI_DIR; + process.env.ANTIGRAVITY_GEMINI_DIR = 'D:\\CustomGeminiVerify'; + try { + let seenFallbacks = []; + await handleAccountCredentialAction( + { action: 'list' }, + { + platform: 'win32', + store: async (cfg) => { + seenFallbacks = cfg.fallbacks || []; + return { accounts: [], selectedEmail: '' }; + }, + } + ); + assert.equal(seenFallbacks.every((p) => p.startsWith('D:\\CustomGeminiVerify')), true); + } finally { + if (prevGemEnv === undefined) delete process.env.ANTIGRAVITY_GEMINI_DIR; + else process.env.ANTIGRAVITY_GEMINI_DIR = prevGemEnv; + } +}); From 424ac7348999054db7a2034ffe5a03816e192012 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Mon, 23 Nov 2026 11:30:07 +0900 Subject: [PATCH 26/31] perf(panel): optimize P1 hot paths and consolidate P2 shared primitives --- sidecars/panel/app.js | 1430 ++++++++++------- sidecars/panel/backend/cli-sqlite-reader.mjs | 215 ++- .../panel/backend/cli-statusline-config.mjs | 16 +- sidecars/panel/backend/cloudcode-proxy.mjs | 52 +- sidecars/panel/backend/config.mjs | 201 +-- .../panel/backend/desktop-launcher-config.mjs | 517 ++---- sidecars/panel/backend/endpoint-registry.mjs | 148 +- sidecars/panel/backend/fs-atomic.mjs | 70 + sidecars/panel/backend/http-helpers.mjs | 10 + sidecars/panel/backend/local-scanner.mjs | 114 +- sidecars/panel/backend/session-migrator.mjs | 108 +- sidecars/panel/backend/sqlite-client.mjs | 11 +- sidecars/panel/backend/telemetry-builder.mjs | 304 ++-- .../panel/backend/trajectory-cache-file.mjs | 6 +- .../panel/backend/trajectory-cache-store.mjs | 250 +++ sidecars/panel/backend/usage-aggregator.mjs | 79 +- sidecars/panel/backend/window-bridge.mjs | 41 +- .../backend/windows-shortcut-provision.ps1 | 284 ++++ sidecars/panel/cli-statusline.mjs | 252 ++- sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 145 +- sidecars/panel/shared/prompt-clean.mjs | 49 + sidecars/panel/shared/workspace-uri.mjs | 150 ++ .../components/charts/SessionStepCharts.js | 65 +- .../src/components/charts/TrendAreaChart.js | 59 +- .../components/layout/WindowOverlayShell.js | 126 +- .../components/settings/BridgeStatusNotice.js | 60 +- .../settings/SessionMigrationCard.js | 79 +- .../panel/src/components/ui/CustomSelect.js | 50 +- .../panel/src/components/ui/SearchInput.js | 118 ++ .../panel/src/components/ui/ToggleSwitch.js | 129 ++ sidecars/panel/src/core/fileExportClient.js | 182 +-- sidecars/panel/src/core/settingsBackup.js | 288 ++-- sidecars/panel/src/core/stepInspector.js | 66 +- sidecars/panel/src/styles/controls.css | 63 +- sidecars/panel/src/styles/modern-ui.css | 8 +- sidecars/panel/src/styles/views-settings.css | 114 -- sidecars/panel/src/styles/views-tables.css | 61 - sidecars/panel/src/views/ConsumptionView.js | 48 +- sidecars/panel/src/views/StepsDetailView.js | 51 +- .../src/views/settings/SettingsGeneralTab.js | 17 +- .../src/views/settings/SettingsOtherTab.js | 36 +- .../views/settings/SettingsStructureTab.js | 57 +- sidecars/panel/styles.css | 246 +-- sidecars/panel/test/backend-harness.mjs | 49 +- .../test/cross-module-regressions.test.mjs | 12 +- .../test/practical-enhancements.test.mjs | 334 ++++ sidecars/panel/trajectory-metrics.mjs | 11 +- 48 files changed, 4040 insertions(+), 2745 deletions(-) create mode 100644 sidecars/panel/backend/fs-atomic.mjs create mode 100644 sidecars/panel/backend/trajectory-cache-store.mjs create mode 100644 sidecars/panel/backend/windows-shortcut-provision.ps1 create mode 100644 sidecars/panel/shared/prompt-clean.mjs create mode 100644 sidecars/panel/shared/workspace-uri.mjs create mode 100644 sidecars/panel/src/components/ui/SearchInput.js create mode 100644 sidecars/panel/src/components/ui/ToggleSwitch.js diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 47ebe86..140d209 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -5414,7 +5414,7 @@ return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSp })(); // --- src/core/stepInspector.js --- -const { STEP_LOW_CACHE_MIN_PROMPT_TOKENS, STEP_LOW_CACHE_MAX_PCT, STEP_SLOW_TTFT_MIN_SEC, getStepSelectionKey, isLowCacheStep, isSlowTtftStep, computeStepQuickChipCounts, filterStepsBySearchAndChip, findPrevAgentContextTokens, computeStepTimingWaterfall, buildStepDiagnosticMarkdown, copyPlainTextToClipboard } = (() => { +const { STEP_LOW_CACHE_MIN_PROMPT_TOKENS, STEP_LOW_CACHE_MAX_PCT, STEP_SLOW_TTFT_MIN_SEC, getStepSelectionKey, isLowCacheStep, isSlowTtftStep, computeStepQuickChipCounts, filterStepsBySearchAndChip, findPrevAgentContextTokens, computeStepTimingWaterfall, buildStepDiagnosticMarkdown, copyPlainTextToClipboard, createCopiedFeedbackController } = (() => { /** * @fileoverview 步骤搜索筛选、快捷诊断统计、耗时瀑布计算及单步诊断 Markdown 导出纯函数模块 (`stepInspector.js`)。 * 保持零 DOM 耦合和单遍 O(N) 高性能,供 `StepsDetailView` 及单元测试直接复用。 @@ -5744,7 +5744,11 @@ async function copyPlainTextToClipboard(text) { document.body.appendChild(ta); ta.select?.(); const ok = document.execCommand('copy'); - ta.remove?.(); + if (typeof ta.remove === 'function') { + ta.remove(); + } else { + document.body.removeChild?.(ta); + } return Boolean(ok); } } catch { @@ -5752,14 +5756,74 @@ async function copyPlainTextToClipboard(text) { } return false; } -return { STEP_LOW_CACHE_MIN_PROMPT_TOKENS, STEP_LOW_CACHE_MAX_PCT, STEP_SLOW_TTFT_MIN_SEC, getStepSelectionKey, isLowCacheStep, isSlowTtftStep, computeStepQuickChipCounts, filterStepsBySearchAndChip, findPrevAgentContextTokens, computeStepTimingWaterfall, buildStepDiagnosticMarkdown, copyPlainTextToClipboard }; + +/** + * 统一的「已复制」临时反馈计时器控制器(自动重置定时器并在组件销毁时清理)。 + * + * @param {{ + * durationMs?: number, + * onChange?: (copiedKey: any) => void, + * onCleanup?: (cleanupFn: () => void) => void, + * }} [options={}] + */ +function createCopiedFeedbackController({ + durationMs = 1800, + onChange = null, + onCleanup = null, +} = {}) { + let activeKey = null; + let timer = null; + let disposed = false; + + function clear() { + if (timer) { + clearTimeout(timer); + timer = null; + } + if (activeKey !== null) { + activeKey = null; + if (!disposed) onChange?.(null); + } + } + + function trigger(key = true) { + if (disposed) return; + if (timer) clearTimeout(timer); + activeKey = key; + onChange?.(activeKey); + timer = setTimeout(() => { + timer = null; + if (disposed) return; + activeKey = null; + onChange?.(null); + }, durationMs); + timer?.unref?.(); + } + + onCleanup?.(() => { + disposed = true; + if (timer) { + clearTimeout(timer); + timer = null; + } + activeKey = null; + }); + + return { + isCopied: (key = true) => activeKey === key, + getActiveKey: () => activeKey, + trigger, + clear, + }; +} +return { STEP_LOW_CACHE_MIN_PROMPT_TOKENS, STEP_LOW_CACHE_MAX_PCT, STEP_SLOW_TTFT_MIN_SEC, getStepSelectionKey, isLowCacheStep, isSlowTtftStep, computeStepQuickChipCounts, filterStepsBySearchAndChip, findPrevAgentContextTokens, computeStepTimingWaterfall, buildStepDiagnosticMarkdown, copyPlainTextToClipboard, createCopiedFeedbackController }; })(); // --- src/core/settingsBackup.js --- -const { triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson } = (() => { +const { triggerBlobDownload, triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson } = (() => { /** * @fileoverview 偏好设置便携 JSON 备份及恢复工具 (`settingsBackup.js`). - * 仅处理经过白名单归一化的用户界面偏好项,不包含账号凭证及高风险上下文窗口覆盖。 + * 通过单一声明式字段描述符表同时驱动导出与导入归一化,消除双遍手写 30 个键的漏同步风险。 */ @@ -5772,17 +5836,17 @@ function sanitizePositiveBudgetNum(val) { } /** - * 在浏览器端通过内存 Blob 触发文件下载(零本地磁盘外部写入)。 + * 在浏览器端通过内存 Blob 触发文件下载(统一承载文本与二进制载荷)。 * * @param {string} filename - * @param {string} content + * @param {BlobPart} blobPart * @param {string} [mimeType] * @returns {boolean} */ -function triggerTextFileDownload( +function triggerBlobDownload( filename, - content, - mimeType = 'application/json;charset=utf-8' + blobPart, + mimeType = 'application/octet-stream' ) { try { if ( @@ -5793,11 +5857,11 @@ function triggerTextFileDownload( ) { return false; } - const blob = new Blob([String(content ?? '')], { type: mimeType }); + const blob = new Blob([blobPart], { type: mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.setAttribute('href', url); - a.setAttribute('download', String(filename || 'export.json')); + a.setAttribute('download', String(filename || 'export.dat')); a.style.display = 'none'; document.body?.appendChild?.(a); a.click?.(); @@ -5813,6 +5877,143 @@ function triggerTextFileDownload( } } +/** + * 在浏览器端通过内存 Blob 触发文本文件下载。 + * + * @param {string} filename + * @param {string} content + * @param {string} [mimeType] + * @returns {boolean} + */ +function triggerTextFileDownload( + filename, + content, + mimeType = 'application/json;charset=utf-8' +) { + return triggerBlobDownload( + String(filename || 'export.json'), + String(content ?? ''), + mimeType + ); +} + +const normField = (key, normalizeFn) => ({ + exportTo: (src, out) => { + out[key] = normalizeFn(src[key]); + }, + importTo: (src, hasKey, patch) => { + if (hasKey(key)) patch[key] = normalizeFn(src[key]); + }, +}); + +const boolField = (key, defaultVal) => ({ + exportTo: (src, out) => { + out[key] = defaultVal ? src[key] !== false : src[key] === true; + }, + importTo: (src, hasKey, patch) => { + if (hasKey(key) && typeof src[key] === 'boolean') patch[key] = src[key]; + }, +}); + +const arrayField = (key, normalizeFn) => ({ + exportTo: (src, out) => { + out[key] = normalizeFn(src[key]); + }, + importTo: (src, hasKey, patch) => { + if (hasKey(key) && Array.isArray(src[key])) patch[key] = normalizeFn(src[key]); + }, +}); + +const positiveBudgetField = (key, fallbackVal) => ({ + exportTo: (src, out) => { + out[key] = sanitizePositiveBudgetNum(src[key]) ?? fallbackVal; + }, + importTo: (src, hasKey, patch) => { + if (hasKey(key)) { + const num = sanitizePositiveBudgetNum(src[key]); + if (num !== null) patch[key] = num; + } + }, +}); + +const PORTABLE_SETTING_DESCRIPTORS = Object.freeze([ + normField('language', normalizeLanguageSetting), + normField('themeAccent', normalizeThemeAccent), + normField('fontScale', normalizeFontScale), + { + exportTo: (src, out) => { + out.modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true; + }, + importTo: (src, hasKey, patch) => { + if (hasKey('modernUi')) { + const val = normalizeModernUi(src.modernUi); + patch.modernUi = val; + patch.experimentalModernUi = val; + } + }, + }, + normField('weeklyLimitMode', normalizeWeeklyLimitMode), + positiveBudgetField('weeklyTokenBudget', 150000000), + positiveBudgetField('weeklyCostBudget', 100), + { + exportTo: (src, out) => { + const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); + out.modelDisplayMode = mode; + out.showUpstreamModel = mode !== 'short'; + }, + importTo: (src, hasKey, patch) => { + if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) { + const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); + patch.modelDisplayMode = mode; + patch.showUpstreamModel = mode !== 'short'; + } + }, + }, + normField('orchestratorIdMode', normalizeOrchestratorIdMode), + { + exportTo: (src, out) => { + out.pluginUpdateMode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin); + }, + importTo: (src, hasKey, patch) => { + if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) { + const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin); + patch.pluginUpdateMode = mode; + patch.autoUpdatePlugin = mode === 'auto'; + } + }, + }, + { + exportTo: (src, out) => { + out.windowMountMode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay); + }, + importTo: (src, hasKey, patch) => { + if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) { + const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay); + patch.windowMountMode = mode; + patch.enableWindowOverlay = mode !== 'sidebar'; + } + }, + }, + normField('popoverWidthMode', normalizePopoverWidthMode), + normField('popoverWidth', normalizePopoverWidth), + boolField('enableCliStatusLine', true), + normField('cliStatusLineSlots', normalizeCliStatusLineSlots), + normField('standalonePort', normalizeStandalonePort), + boolField('showTopbarMultiSession', true), + normField('contextAgentMode', normalizeContextAgentMode), + arrayField('topbarCapsuleSlots', normalizeTopbarCapsuleSlots), + arrayField('hoverModules', normalizeHoverModules), + arrayField('overviewModules', normalizeOverviewModules), + arrayField('overviewMetrics', normalizeOverviewMetrics), + boolField('showStepTurnRail', false), + boolField('showStepAgentBadge', true), + boolField('showStepSpeedColor', false), + boolField('showStepFilterToolbar', false), + normField('stepTokenComboFormat', normalizeStepTokenComboFormat), + arrayField('stepTableColumns', normalizeStepTableColumns), + normField('experimentalQuotaReservation', normalizeExperimentalQuotaReservation), +]); + /** * 将当前用户偏好设置序列化为跨设备可迁移的安全 JSON 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。 * @@ -5821,46 +6022,15 @@ function triggerTextFileDownload( */ function buildExportableSettingsJson(settings = {}) { const src = settings && typeof settings === 'object' ? settings : {}; - const modelDisplayMode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); - const modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true; + const outSettings = {}; + for (const desc of PORTABLE_SETTING_DESCRIPTORS) { + desc.exportTo(src, outSettings); + } const payload = { schema: SETTINGS_BACKUP_SCHEMA, version: 1, exportedAt: new Date().toISOString(), - settings: { - language: normalizeLanguageSetting(src.language), - themeAccent: normalizeThemeAccent(src.themeAccent), - fontScale: normalizeFontScale(src.fontScale), - modernUi, - weeklyLimitMode: normalizeWeeklyLimitMode(src.weeklyLimitMode), - weeklyTokenBudget: sanitizePositiveBudgetNum(src.weeklyTokenBudget) ?? 150000000, - weeklyCostBudget: sanitizePositiveBudgetNum(src.weeklyCostBudget) ?? 100, - modelDisplayMode, - showUpstreamModel: modelDisplayMode !== 'short', - orchestratorIdMode: normalizeOrchestratorIdMode(src.orchestratorIdMode), - pluginUpdateMode: normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin), - windowMountMode: normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay), - popoverWidthMode: normalizePopoverWidthMode(src.popoverWidthMode), - popoverWidth: normalizePopoverWidth(src.popoverWidth), - enableCliStatusLine: src.enableCliStatusLine !== false, - cliStatusLineSlots: normalizeCliStatusLineSlots(src.cliStatusLineSlots), - standalonePort: normalizeStandalonePort(src.standalonePort), - showTopbarMultiSession: src.showTopbarMultiSession !== false, - contextAgentMode: normalizeContextAgentMode(src.contextAgentMode), - topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots), - hoverModules: normalizeHoverModules(src.hoverModules), - overviewModules: normalizeOverviewModules(src.overviewModules), - overviewMetrics: normalizeOverviewMetrics(src.overviewMetrics), - showStepTurnRail: src.showStepTurnRail === true, - showStepAgentBadge: src.showStepAgentBadge !== false, - showStepSpeedColor: src.showStepSpeedColor === true, - showStepFilterToolbar: src.showStepFilterToolbar === true, - stepTokenComboFormat: normalizeStepTokenComboFormat(src.stepTokenComboFormat), - stepTableColumns: normalizeStepTableColumns(src.stepTableColumns), - experimentalQuotaReservation: normalizeExperimentalQuotaReservation( - src.experimentalQuotaReservation - ), - }, + settings: outSettings, }; return `${JSON.stringify(payload, null, 2)}\n`; } @@ -5894,98 +6064,8 @@ function parseImportedSettingsJson(rawText) { const hasKey = (k) => Object.prototype.hasOwnProperty.call(src, k); const patch = {}; - if (hasKey('language')) patch.language = normalizeLanguageSetting(src.language); - if (hasKey('themeAccent')) patch.themeAccent = normalizeThemeAccent(src.themeAccent); - if (hasKey('fontScale')) patch.fontScale = normalizeFontScale(src.fontScale); - if (hasKey('modernUi')) { - const val = normalizeModernUi(src.modernUi); - patch.modernUi = val; - patch.experimentalModernUi = val; - } - if (hasKey('weeklyLimitMode')) { - patch.weeklyLimitMode = normalizeWeeklyLimitMode(src.weeklyLimitMode); - } - if (hasKey('weeklyTokenBudget')) { - const num = sanitizePositiveBudgetNum(src.weeklyTokenBudget); - if (num !== null) patch.weeklyTokenBudget = num; - } - if (hasKey('weeklyCostBudget')) { - const num = sanitizePositiveBudgetNum(src.weeklyCostBudget); - if (num !== null) patch.weeklyCostBudget = num; - } - if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) { - const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel); - patch.modelDisplayMode = mode; - patch.showUpstreamModel = mode !== 'short'; - } - if (hasKey('orchestratorIdMode')) { - patch.orchestratorIdMode = normalizeOrchestratorIdMode(src.orchestratorIdMode); - } - if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) { - const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin); - patch.pluginUpdateMode = mode; - patch.autoUpdatePlugin = mode === 'auto'; - } - if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) { - const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay); - patch.windowMountMode = mode; - patch.enableWindowOverlay = mode !== 'sidebar'; - } - if (hasKey('popoverWidthMode')) { - patch.popoverWidthMode = normalizePopoverWidthMode(src.popoverWidthMode); - } - if (hasKey('popoverWidth')) { - patch.popoverWidth = normalizePopoverWidth(src.popoverWidth); - } - 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); - } - if (hasKey('showTopbarMultiSession') && typeof src.showTopbarMultiSession === 'boolean') { - patch.showTopbarMultiSession = src.showTopbarMultiSession; - } - if (hasKey('contextAgentMode')) { - patch.contextAgentMode = normalizeContextAgentMode(src.contextAgentMode); - } - if (hasKey('topbarCapsuleSlots') && Array.isArray(src.topbarCapsuleSlots)) { - patch.topbarCapsuleSlots = normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots); - } - if (hasKey('hoverModules') && Array.isArray(src.hoverModules)) { - patch.hoverModules = normalizeHoverModules(src.hoverModules); - } - if (hasKey('overviewModules') && Array.isArray(src.overviewModules)) { - patch.overviewModules = normalizeOverviewModules(src.overviewModules); - } - if (hasKey('overviewMetrics') && Array.isArray(src.overviewMetrics)) { - patch.overviewMetrics = normalizeOverviewMetrics(src.overviewMetrics); - } - if (hasKey('showStepTurnRail') && typeof src.showStepTurnRail === 'boolean') { - patch.showStepTurnRail = src.showStepTurnRail; - } - if (hasKey('showStepAgentBadge') && typeof src.showStepAgentBadge === 'boolean') { - patch.showStepAgentBadge = src.showStepAgentBadge; - } - if (hasKey('showStepSpeedColor') && typeof src.showStepSpeedColor === 'boolean') { - patch.showStepSpeedColor = src.showStepSpeedColor; - } - if (hasKey('showStepFilterToolbar') && typeof src.showStepFilterToolbar === 'boolean') { - patch.showStepFilterToolbar = src.showStepFilterToolbar; - } - if (hasKey('stepTokenComboFormat')) { - patch.stepTokenComboFormat = normalizeStepTokenComboFormat(src.stepTokenComboFormat); - } - if (hasKey('stepTableColumns') && Array.isArray(src.stepTableColumns)) { - patch.stepTableColumns = normalizeStepTableColumns(src.stepTableColumns); - } - if (hasKey('experimentalQuotaReservation')) { - patch.experimentalQuotaReservation = normalizeExperimentalQuotaReservation( - src.experimentalQuotaReservation - ); + for (const desc of PORTABLE_SETTING_DESCRIPTORS) { + desc.importTo(src, hasKey, patch); } const appliedCount = Object.keys(patch).length; @@ -5994,7 +6074,7 @@ function parseImportedSettingsJson(rawText) { } return { ok: true, patch, appliedCount }; } -return { triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson }; +return { triggerBlobDownload, triggerTextFileDownload, buildExportableSettingsJson, parseImportedSettingsJson }; })(); // --- src/core/xlsxBuilder.js --- @@ -8521,7 +8601,7 @@ return { getViewTabs, uiStore, showUiToast, dismissUiToast, getVisibleMonitorVie // --- src/core/fileExportClient.js --- const { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFeedback, copyTextWithFeedback } = (() => { /** - * @fileoverview 统一文本文件导出及剪贴板复制客户端 (`fileExportClient.js`)。 + * @fileoverview 统一文本/二进制文件导出及剪贴板复制客户端 (`fileExportClient.js`)。 * 优先调用本机后端 `/api/export-file` 落盘到用户 Downloads(或插件 `.data/exports`)并返回真实绝对路径, * 同时通过全局 Toast 清晰展示保存位置并提供「打开位置」快捷按钮; * 当后端不可达或处于远程浏览器访问时,自动平滑降级到 `showSaveFilePicker` 或浏览器 Blob 下载并给出明确提示。 @@ -8533,36 +8613,6 @@ function isHostEmbeddedWebview() { return Boolean(window.sidecar?.fetch) || isWindowOverlayMode(); } -function triggerBinaryFileDownload(filename, bytes, mimeType) { - try { - if ( - typeof Blob === 'undefined' || - typeof URL === 'undefined' || - typeof URL.createObjectURL !== 'function' || - typeof document === 'undefined' - ) { - return false; - } - const blob = new Blob([bytes], { type: mimeType }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.setAttribute('href', url); - a.setAttribute('download', String(filename || 'export.xlsx')); - a.style.display = 'none'; - document.body?.appendChild?.(a); - a.click?.(); - a.remove?.(); - setTimeout(() => { - try { - URL.revokeObjectURL(url); - } catch {} - }, 1000); - return true; - } catch { - return false; - } -} - function getPickerTypesForFilename(filename, mimeType) { const lower = String(filename || '').toLowerCase(); if (lower.endsWith('.xlsx') || String(mimeType || '').includes('spreadsheetml')) { @@ -8656,28 +8706,15 @@ async function requestLocalBackendExport(payload) { } /** - * 统一文本导出入口:优先本机后端落盘(返回精确路径 + 支持一键打开所在目录), - * 仅在真正独立浏览器上下文(非 Sidecar / 非 Electron 宿主)下降级为浏览器保存,避免宿主静默吞掉 Blob 下载后误报成功。 - * - * @param {string} filename - * @param {string} content - * @param {string} [mimeType='text/plain;charset=utf-8'] - * @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>} + * 共享多阶段导出与 Toast 反馈骨架(本机落盘 -> 宿主拦截保护 -> File System Access Picker -> Blob 下载)。 */ -async function exportTextFileWithFeedback( - filename, - content, - mimeType = 'application/json;charset=utf-8' -) { - const safeName = String(filename || 'export.txt'); - const text = String(content ?? ''); - - // 1. 优先通过本机后端落盘到 Downloads(含 /api/settings 穿透兼容旧常驻 main.mjs) - const { res: localRes } = await requestLocalBackendExport({ - filename: safeName, - content: text, - mimeType, - }); +async function runExportPipelineWithFeedback({ + safeName, + mimeType, + backendPayload, + writablePayload, +}) { + const { res: localRes } = await requestLocalBackendExport(backendPayload); if (localRes && localRes.ok && localRes.filePath) { const savedPath = String(localRes.filePath); const savedName = String(localRes.fileName || safeName); @@ -8694,7 +8731,7 @@ async function exportTextFileWithFeedback( return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName }; } - // 2. 在 Antigravity Sidecar / 双栖 Electron 宿主内, 会被静默吞掉,绝不误报“已下载到浏览器” + // 在 Antigravity Sidecar / 双栖 Electron 宿主内, 会被静默吞掉,绝不误报“已下载到浏览器” if (isHostEmbeddedWebview()) { showUiToast({ message: t('export.failed'), @@ -8705,7 +8742,6 @@ async function exportTextFileWithFeedback( return { ok: false, mode: 'failed' }; } - // 3. 普通独立浏览器原生「另存为」对话框 if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') { try { const handle = await window.showSaveFilePicker({ @@ -8713,7 +8749,7 @@ async function exportTextFileWithFeedback( types: getPickerTypesForFilename(safeName, mimeType), }); const writable = await handle.createWritable(); - await writable.write(text); + await writable.write(writablePayload); await writable.close(); const pickedName = handle.name || safeName; showUiToast({ @@ -8726,12 +8762,10 @@ async function exportTextFileWithFeedback( if (err && err.name === 'AbortError') { return { ok: false, mode: 'cancelled' }; } - // 沙箱/iframe 抛出 SecurityError 等时继续降级到 Blob 下载 } } - // 4. 独立浏览器标准 Blob 兜底下载 - const ok = triggerTextFileDownload(safeName, text, mimeType); + const ok = triggerBlobDownload(safeName, writablePayload, mimeType); if (ok) { showUiToast({ message: t('export.savedBrowser', { file: safeName }), @@ -8750,9 +8784,36 @@ async function exportTextFileWithFeedback( return { ok: false, mode: 'failed' }; } +/** + * 统一文本导出入口:优先本机后端落盘(返回精确路径 + 支持一键打开所在目录), + * 仅在真正独立浏览器上下文下降级为浏览器保存。 + * + * @param {string} filename + * @param {string} content + * @param {string} [mimeType='application/json;charset=utf-8'] + * @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>} + */ +async function exportTextFileWithFeedback( + filename, + content, + mimeType = 'application/json;charset=utf-8' +) { + const safeName = String(filename || 'export.txt'); + const text = String(content ?? ''); + return runExportPipelineWithFeedback({ + safeName, + mimeType, + backendPayload: { + filename: safeName, + content: text, + mimeType, + }, + writablePayload: text, + }); +} + /** * 统一二进制文件导出入口(用于原生 `.xlsx` Excel 工作簿)。 - * 优先转 Base64 经本机后端落盘到 Downloads 并展示完整路径 + 「打开位置」直达按钮。 * * @param {string} filename * @param {Uint8Array} bytes @@ -8769,80 +8830,17 @@ async function exportBinaryFileWithFeedback( showUiToast({ message: t('export.failed'), tone: 'warn', durationMs: 3600 }); return { ok: false, mode: 'failed' }; } - - const base64Content = uint8ArrayToBase64(bytes); - const { res: localRes } = await requestLocalBackendExport({ - filename: safeName, - content: base64Content, - encoding: 'base64', + return runExportPipelineWithFeedback({ + safeName, mimeType, + backendPayload: { + filename: safeName, + content: uint8ArrayToBase64(bytes), + encoding: 'base64', + mimeType, + }, + writablePayload: bytes, }); - if (localRes && localRes.ok && localRes.filePath) { - const savedPath = String(localRes.filePath); - const savedName = String(localRes.fileName || safeName); - showUiToast({ - message: t('export.savedLocal', { file: savedName }), - detail: savedPath, - actionLabel: t('export.openFolder'), - onAction: () => { - void revealExportedFile(savedPath); - }, - tone: 'ok', - durationMs: 7000, - }); - return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName }; - } - - if (isHostEmbeddedWebview()) { - showUiToast({ - message: t('export.failed'), - detail: t('export.hostUnavailable'), - tone: 'warn', - durationMs: 5200, - }); - return { ok: false, mode: 'failed' }; - } - - if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') { - try { - const handle = await window.showSaveFilePicker({ - suggestedName: safeName, - types: getPickerTypesForFilename(safeName, mimeType), - }); - const writable = await handle.createWritable(); - await writable.write(bytes); - await writable.close(); - const pickedName = handle.name || safeName; - showUiToast({ - message: t('export.savedPicked', { file: pickedName }), - tone: 'ok', - durationMs: 4200, - }); - return { ok: true, mode: 'picker', fileName: pickedName }; - } catch (err) { - if (err && err.name === 'AbortError') { - return { ok: false, mode: 'cancelled' }; - } - } - } - - const ok = triggerBinaryFileDownload(safeName, bytes, mimeType); - if (ok) { - showUiToast({ - message: t('export.savedBrowser', { file: safeName }), - detail: t('export.savedBrowserHint'), - tone: 'info', - durationMs: 5000, - }); - return { ok: true, mode: 'browser', fileName: safeName }; - } - - showUiToast({ - message: t('export.failed'), - tone: 'warn', - durationMs: 3600, - }); - return { ok: false, mode: 'failed' }; } /** @@ -11337,6 +11335,127 @@ const TopLongPillNav = defineComponent({ return { TopLongPillNav }; })(); +// --- src/components/ui/SearchInput.js --- +const { createSearchInput } = (() => { +/** + * @fileoverview Shared compact search input bar (`SearchInput.js`) with leading search icon + * and conditional clear button, reused across `CustomSelect`, `StepsDetailView`, and `SessionMigrationCard`. + */ + + +/** + * Creates a unified search input box while preserving caller-specific modifier classes. + * + * @param {{ + * wrapClassName?: string, + * iconClassName?: string, + * inputClassName?: string, + * clearClassName?: string, + * placeholder?: string, + * ariaLabel?: string, + * clearAriaLabel?: string, + * hidden?: boolean, + * stopClickPropagation?: boolean, + * closeIconSize?: number, + * onInput?: (value: string, event: any) => void, + * onClear?: (event: any) => void, + * onKeydown?: (event: any) => void, + * }} [options={}] + */ +function createSearchInput({ + wrapClassName = '', + iconClassName = '', + inputClassName = '', + clearClassName = '', + placeholder = '', + ariaLabel = '', + clearAriaLabel = '', + hidden = false, + stopClickPropagation = false, + closeIconSize = 10, + onInput = null, + onClear = null, + onKeydown = null, +} = {}) { + const iconEl = createSvgIcon('search', { + size: 12, + className: ['ui-search-icon', iconClassName].filter(Boolean).join(' '), + }); + + const inputEl = h('input', { + type: 'text', + className: ['ui-search-input', inputClassName].filter(Boolean).join(' '), + autocomplete: 'off', + spellcheck: 'false', + placeholder, + ...(ariaLabel ? { 'aria-label': ariaLabel } : {}), + ...(stopClickPropagation ? { onClick: (e) => e.stopPropagation?.() } : {}), + onInput: (e) => { + const val = String(e?.target?.value ?? inputEl.value ?? ''); + patchAttr(clearBtnEl, 'hidden', !val.trim()); + onInput?.(val, e); + }, + ...(onKeydown ? { onKeydown } : {}), + }); + + const clearBtnEl = h( + 'button', + { + type: 'button', + className: ['ui-search-clear', clearClassName].filter(Boolean).join(' '), + hidden: true, + ...(clearAriaLabel ? { 'aria-label': clearAriaLabel } : {}), + onClick: (e) => { + if (stopClickPropagation) e?.stopPropagation?.(); + inputEl.value = ''; + patchAttr(clearBtnEl, 'hidden', true); + if (onClear) { + onClear(e); + } else { + onInput?.('', e); + inputEl.focus?.(); + } + }, + }, + [createSvgIcon('close', { size: closeIconSize })] + ); + + const wrapEl = h( + 'div', + { + className: ['ui-search-wrap', wrapClassName].filter(Boolean).join(' '), + ...(hidden ? { hidden: true } : {}), + ...(stopClickPropagation ? { onClick: (e) => e.stopPropagation?.() } : {}), + }, + [iconEl, inputEl, clearBtnEl] + ); + + return { + el: wrapEl, + iconEl, + inputEl, + clearBtnEl, + getValue() { + return String(inputEl.value || ''); + }, + setValue(nextVal) { + const str = String(nextVal ?? ''); + inputEl.value = str; + patchAttr(clearBtnEl, 'hidden', !str.trim()); + }, + syncLabels({ placeholder: nextPlaceholder, ariaLabel: nextAria, clearAriaLabel: nextClearAria } = {}) { + if (nextPlaceholder !== undefined) patchAttr(inputEl, 'placeholder', nextPlaceholder); + if (nextAria !== undefined) patchAttr(inputEl, 'aria-label', nextAria); + if (nextClearAria !== undefined) patchAttr(clearBtnEl, 'aria-label', nextClearAria); + }, + focus() { + inputEl.focus?.(); + }, + }; +} +return { createSearchInput }; +})(); + // --- src/components/ui/CustomSelect.js --- const { filterSelectOptionsByQuery, CustomSelect } = (() => { /** @@ -11434,44 +11553,29 @@ const CustomSelect = defineComponent({ [leadIcon, triggerLabel, chevronIcon] ); - const searchIcon = createSvgIcon('search', { size: 12, className: 'select-search-icon' }); - const searchInput = h('input', { - type: 'text', - className: 'select-search-input', - autocomplete: 'off', - spellcheck: 'false', + const searchBox = createSearchInput({ + wrapClassName: 'select-search-wrap', + iconClassName: 'select-search-icon', + inputClassName: 'select-search-input', + clearClassName: 'select-search-clear', placeholder: getProps().searchPlaceholder || t('select.searchPlaceholder'), - onClick: (e) => e.stopPropagation(), - onInput: (e) => { - searchQuery = String(e?.target?.value ?? searchInput.value ?? ''); + clearAriaLabel: t('select.clearSearch'), + hidden: true, + stopClickPropagation: true, + closeIconSize: 10, + onInput: (val) => { + searchQuery = val; focusedIndex = 0; renderMenuOptions(); }, + onClear: () => { + clearSearchQuery(true); + }, onKeydown: handleKeydown, }); - const searchClearBtn = h( - 'button', - { - type: 'button', - className: 'select-search-clear', - hidden: true, - 'aria-label': t('select.clearSearch'), - onClick: (e) => { - e.stopPropagation(); - clearSearchQuery(true); - }, - }, - [createSvgIcon('close', { size: 10 })] - ); - const searchWrap = h( - 'div', - { - className: 'select-search-wrap', - hidden: true, - onClick: (e) => e.stopPropagation(), - }, - [searchIcon, searchInput, searchClearBtn] - ); + const searchWrap = searchBox.el; + const searchInput = searchBox.inputEl; + const searchClearBtn = searchBox.clearBtnEl; const optionsListEl = h('div', { className: 'select-options-list' }); const emptyHintEl = h('div', { @@ -12910,6 +13014,137 @@ const SegmentedControl = defineComponent({ return { SegmentedControl }; })(); +// --- src/components/ui/ToggleSwitch.js --- +const { ToggleSwitch } = (() => { +/** + * @fileoverview Zero-ResizeObserver binary toggle switch (`ToggleSwitch.js`). + * Uses a pure-CSS 2-column grid glider (`--seg-active-idx`) so Settings tabs do not + * instantiate 10+ ResizeObservers or force synchronous layout measurements for simple + * on/off or show/hide switches, while preserving `.segmented` / `.seg-btn` semantics. + */ + + +const TOGGLE_PRESET_DEFS = Object.freeze({ + enable: Object.freeze([ + { value: 'on', labelKey: 'settings.str.on' }, + { value: 'off', labelKey: 'settings.str.off' }, + ]), + visibility: Object.freeze([ + { value: 'show', labelKey: 'settings.str.show' }, + { value: 'hide', labelKey: 'settings.str.hide' }, + ]), + modernUi: Object.freeze([ + { value: 'on', labelKey: 'settings.gen.modernUiOn' }, + { value: 'off', labelKey: 'settings.gen.modernUiOff' }, + ]), +}); + +function resolveToggleOptions(props) { + if (Array.isArray(props.options) && props.options.length === 2) { + return props.options; + } + const defs = TOGGLE_PRESET_DEFS[props.preset] || TOGGLE_PRESET_DEFS.enable; + return [ + { value: defs[0].value, label: t(defs[0].labelKey) }, + { value: defs[1].value, label: t(defs[1].labelKey) }, + ]; +} + +const ToggleSwitch = defineComponent({ + name: 'ToggleSwitch', + setup({ getProps, setProps, emit, onCleanup }) { + const gliderEl = h('div', { className: 'seg-glider is-ready', 'aria-hidden': 'true' }); + const btns = [0, 1].map((slotIdx) => + h('button', { + type: 'button', + className: 'seg-btn', + onClick: (e) => { + e.stopPropagation(); + const opts = resolveToggleOptions(getProps()); + const opt = opts[slotIdx]; + if (opt) selectValue(opt.value); + }, + onKeydown: (e) => { + if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { + e.preventDefault(); + const opts = resolveToggleOptions(getProps()); + const nextIdx = slotIdx === 0 ? 1 : 0; + const targetOpt = opts[nextIdx]; + if (targetOpt) { + selectValue(targetOpt.value); + btns[nextIdx]?.focus?.(); + } + } + }, + }) + ); + + const rootEl = h( + 'div', + { + className: 'segmented segmented--binary has-glider toggle-switch', + role: 'group', + 'aria-label': getProps().ariaLabel || t('ui.seg.defaultAria'), + }, + [gliderEl, btns[0], btns[1]] + ); + + function selectValue(nextVal) { + if (getProps().modelValue !== nextVal) { + setProps({ modelValue: nextVal }); + emit('update:modelValue', nextVal); + } + } + + function syncToggle() { + const props = getProps(); + const opts = resolveToggleOptions(props); + const aria = props.ariaLabelKey ? t(props.ariaLabelKey) : props.ariaLabel || t('ui.seg.defaultAria'); + patchAttr(rootEl, 'aria-label', aria); + + let activeIdx = 0; + for (let i = 0; i < 2; i += 1) { + const opt = opts[i]; + const btn = btns[i]; + const active = opt.value === props.modelValue; + if (active) activeIdx = i; + patchText(btn, opt.label); + patchClasses(btn, { 'is-active': active }); + patchAttr(btn, 'aria-pressed', active ? 'true' : 'false'); + patchAttr(btn, 'data-seg-value', opt.value); + } + patchStyleVar(rootEl, '--seg-active-idx', String(activeIdx)); + } + + const unsubI18n = i18nStore.subscribe( + (st) => st.locale, + () => { + syncToggle(); + }, + { immediate: false } + ); + onCleanup(unsubI18n); + + syncToggle(); + + return { + el: rootEl, + onPropsChange: syncToggle, + methods: { + setValue(val) { + setProps({ modelValue: val }); + }, + setOptions(options) { + setProps({ options }); + }, + refreshGeometry() {}, + }, + }; + }, +}); +return { ToggleSwitch }; +})(); + // --- src/components/ui/ContextSegmentMeter.js --- const { ContextSegmentMeter } = (() => { /** @@ -13751,8 +13986,27 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { }); } + let cachedWrapRect = null; + let cachedSvgRect = null; + let cachedHmGridRect = null; + let cachedClipRect = undefined; + + function invalidateHoverRects() { + cachedWrapRect = null; + cachedSvgRect = null; + cachedHmGridRect = null; + cachedClipRect = undefined; + } + + function getCachedWrapRect() { + if (!cachedWrapRect) { + cachedWrapRect = chartWrap.getBoundingClientRect?.() || null; + } + return cachedWrapRect; + } + function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) { - const wrapRect = chartWrap.getBoundingClientRect?.() || null; + const wrapRect = getCachedWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width @@ -13762,13 +14016,8 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { ? wrapRect.height : Number(chartWrap.offsetHeight || VIEW_H); - const tipRect = tooltipEl.getBoundingClientRect?.() || null; - const tipW = - Number(tooltipEl.offsetWidth || 0) || - (tipRect && tipRect.width > 0 ? tipRect.width : 216); - const tipH = - Number(tooltipEl.offsetHeight || 0) || - (tipRect && tipRect.height > 0 ? tipRect.height : 104); + const tipW = Number(tooltipEl.offsetWidth || 0) || 216; + const tipH = Number(tooltipEl.offsetHeight || 0) || 104; const hasPointer = pointer && @@ -13781,8 +14030,11 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX; const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY; - const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null; - const clipRect = clipEl?.getBoundingClientRect?.() || null; + if (cachedClipRect === undefined) { + const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null; + cachedClipRect = clipEl?.getBoundingClientRect?.() || null; + } + const clipRect = cachedClipRect; const hasClip = Boolean( clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0 ); @@ -13848,7 +14100,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } } - const wrapRect = chartWrap.getBoundingClientRect?.() || null; + const wrapRect = getCachedWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width @@ -13895,7 +14147,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { populateTooltipContent(slot); } - const wrapRect = chartWrap.getBoundingClientRect?.() || null; + const wrapRect = getCachedWrapRect(); const cellRect = targetCell.getBoundingClientRect?.() || null; const wrapW = wrapRect && wrapRect.width > 0 @@ -13920,6 +14172,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } function clearHover() { + invalidateHoverRects(); cancelTipTrackRaf(); hoveredIdx = -1; lastPointer = null; @@ -13966,8 +14219,14 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { function handlePointerMove(e) { if (currentIsHeatmap || !currentSlots.length) return; - const rect = svg.getBoundingClientRect(); - if (!rect || rect.width <= 0) return; + if (!cachedSvgRect) { + cachedSvgRect = svg.getBoundingClientRect(); + } + const rect = cachedSvgRect; + if (!rect || rect.width <= 0) { + cachedSvgRect = null; + return; + } const relX = ((e.clientX - rect.left) / rect.width) * viewW; const { leftX, spanX } = resolvePlotBounds(viewW); const ratio = (relX - leftX) / Math.max(1, spanX); @@ -14010,8 +14269,12 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { return null; } - const rect = hmGridEl.getBoundingClientRect?.(); + if (!cachedHmGridRect) { + cachedHmGridRect = hmGridEl.getBoundingClientRect?.() || null; + } + const rect = cachedHmGridRect; if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) { + cachedHmGridRect = null; if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; } @@ -14166,6 +14429,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let onWinResize = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { + invalidateHoverRects(); if (!currentIsHeatmap && syncViewWidth() && currentSlots.length > 0) { lastRenderSig = ''; update(currentSlots); @@ -15284,7 +15548,14 @@ function createSessionLineChart() { let hoveredIdx = -1; let tickElsByIdx = new Map(); let lastSig = ''; + let lastPreSig = ''; + let lastSummaryBadge = ''; let lastUpdateParams = null; + let cachedPlotSvgRect = null; + + function invalidatePlotSvgRect() { + cachedPlotSvgRect = null; + } function syncViewWidth() { const measured = Math.round( @@ -15397,8 +15668,14 @@ function createSessionLineChart() { plotStage.addEventListener('mousemove', (e) => { if (!currentPoints.length) return; - const rect = svg.getBoundingClientRect(); - if (!rect || rect.width <= 0) return; + if (!cachedPlotSvgRect) { + cachedPlotSvgRect = svg.getBoundingClientRect(); + } + const rect = cachedPlotSvgRect; + if (!rect || rect.width <= 0) { + cachedPlotSvgRect = null; + return; + } const relX = ((e.clientX - rect.left) / rect.width) * viewW; const { leftX, spanX } = resolvePlotBounds(viewW); const ratio = (relX - leftX) / Math.max(1, spanX); @@ -15408,14 +15685,19 @@ function createSessionLineChart() { ); showHoverAt(idx); }); - plotStage.addEventListener('mouseleave', clearHover); + plotStage.addEventListener('mouseleave', () => { + invalidatePlotSvgRect(); + clearHover(); + }); let resizeObs = null; let onWinResize = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { + invalidatePlotSvgRect(); if (syncViewWidth() && lastUpdateParams) { lastSig = ''; + lastPreSig = ''; update(lastUpdateParams); } }); @@ -15496,6 +15778,9 @@ function createSessionLineChart() { if (!matchedSteps.length) { currentPoints = []; lastSig = 'empty'; + lastPreSig = ''; + lastSummaryBadge = t('chart.step.zeroSteps'); + invalidatePlotSvgRect(); patchAttr(areaPath, 'd', ''); patchAttr(linePath, 'd', ''); while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); @@ -15507,7 +15792,23 @@ function createSessionLineChart() { patchAttr(peakPill, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); clearHover(); - return { summaryBadge: t('chart.step.zeroSteps') }; + return { summaryBadge: lastSummaryBadge }; + } + + const locale = getEffectiveLocale(); + const extColorSig = modelColorByGroup + ? Array.from(modelColorByGroup.entries()) + .map(([k, v]) => `${k}=${v}`) + .join(',') + : ''; + let preStepParts = `${matchedSteps.length}:`; + for (let i = 0; i < matchedSteps.length; i += 1) { + const s = matchedSteps[i]; + preStepParts += `${s.stepIndex ?? i},${s.agentIndex ?? 0},${s.modelKey || s.modelShort || ''},${s.inputTokens || 0},${s.cacheReadTokens || 0},${s.outputTokens || 0},${s.contextTokens || 0},${s.tokPerSec ?? ''},${s.ttftSec ?? ''},${s.costUsd ?? ''},${s.anomalySig || ''};`; + } + const preSig = `${locale}|${viewW}|${metric}|${showAgentPrefix}|${displaySettings?.modelDisplayMode || ''}|${Boolean(displaySettings?.showUpstreamModel)}|${displaySettings?.orchestratorIdMode || ''}|${targetKeys.join(',')}|${extColorSig}|${preStepParts}`; + if (preSig === lastPreSig && lastSummaryBadge) { + return { summaryBadge: lastSummaryBadge }; } const modelColorMap = new Map(); @@ -15715,7 +16016,6 @@ function createSessionLineChart() { const validPoints = points.filter((p) => p.valid); patchAttr(emptyHintEl, 'hidden', validPoints.length > 0); - const locale = getEffectiveLocale(); const colorSig = Array.from(modelColorMap.entries()) .map(([k, v]) => `${k}=${v}`) .join(','); @@ -15961,6 +16261,8 @@ function createSessionLineChart() { }); } + lastPreSig = preSig; + lastSummaryBadge = summaryBadge; return { summaryBadge }; } @@ -16225,10 +16527,17 @@ function createModelFitChart() { patchClasses(tooltipEl, { 'is-tracking': false }); } + let cachedFitSvgRect = null; plotStage.addEventListener('mousemove', (e) => { if (!currentSamples.length) return; - const rect = svg.getBoundingClientRect(); - if (!rect || rect.width <= 0) return; + if (!cachedFitSvgRect) { + cachedFitSvgRect = svg.getBoundingClientRect(); + } + const rect = cachedFitSvgRect; + if (!rect || rect.width <= 0) { + cachedFitSvgRect = null; + return; + } const relX = ((e.clientX - rect.left) / rect.width) * viewW; let lo = 0; let hi = currentSamples.length - 1; @@ -16246,12 +16555,16 @@ function createModelFitChart() { } showHoverAt(bestIdx); }); - plotStage.addEventListener('mouseleave', clearHover); + plotStage.addEventListener('mouseleave', () => { + cachedFitSvgRect = null; + clearHover(); + }); let resizeObs = null; let onWinResize = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { + cachedFitSvgRect = null; if (syncViewWidth() && lastUpdateParams) { lastSig = ''; update(lastUpdateParams); @@ -23993,31 +24306,6 @@ const { BridgeStatusNotice } = (() => { const LAUNCH_FLAG_TEXT = '--remote-debugging-port=0'; -async function copyTextToClipboard(text) { - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(text); - return true; - } - } catch { - // Fallback to temporary textarea inside restricted webview contexts - } - try { - if (typeof document === 'undefined' || !document.body) return false; - const area = document.createElement('textarea'); - area.value = text; - area.setAttribute('readonly', 'true'); - area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;'; - document.body.appendChild(area); - area.select?.(); - const ok = Boolean(document.execCommand?.('copy')); - document.body.removeChild(area); - return ok; - } catch { - return false; - } -} - const BridgeStatusNotice = defineComponent({ name: 'BridgeStatusNotice', setup({ props, onCleanup }) { @@ -24029,11 +24317,16 @@ const BridgeStatusNotice = defineComponent({ hostPlatform: 'win32', }; let dismissed = false; - let copied = false; - let copiedTimer = null; let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed' let relaunchResetTimer = null; let destroyed = false; + const copyFeedback = createCopiedFeedbackController({ + durationMs: 1800, + onCleanup, + onChange: () => { + if (!destroyed) syncActionButtons(); + }, + }); const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' }); const titleEl = h('strong', { className: 'settings-bridge-title', text: '' }); @@ -24126,18 +24419,9 @@ const BridgeStatusNotice = defineComponent({ type: 'button', className: 'btn-ghost-sm settings-bridge-copy-btn', onClick: async () => { - await copyTextToClipboard(LAUNCH_FLAG_TEXT); + await copyPlainTextToClipboard(LAUNCH_FLAG_TEXT); if (destroyed) return; - copied = true; - if (copiedTimer) clearTimeout(copiedTimer); - syncActionButtons(); - copiedTimer = setTimeout(() => { - copiedTimer = null; - if (destroyed) return; - copied = false; - syncActionButtons(); - }, 1800); - copiedTimer?.unref?.(); + copyFeedback.trigger(true); }, }, [copyBtnIconEl, copyBtnTextEl] @@ -24180,10 +24464,11 @@ const BridgeStatusNotice = defineComponent({ : t('settings.bridge.relaunchBtn') ); - patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy'); + const isCopied = copyFeedback.isCopied(true); + patchSvgIcon(copyBtnIconEl, isCopied ? 'check' : 'copy'); patchText( copyBtnTextEl, - copied + isCopied ? t('settings.bridge.copiedBtn') : t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }) ); @@ -24268,10 +24553,6 @@ const BridgeStatusNotice = defineComponent({ onCleanup(() => { destroyed = true; - if (copiedTimer) { - clearTimeout(copiedTimer); - copiedTimer = null; - } if (relaunchResetTimer) { clearTimeout(relaunchResetTimer); relaunchResetTimer = null; @@ -24303,31 +24584,6 @@ const { SessionMigrationCard } = (() => { const SMIG_OUTSIDE_PROJECT_ID = 'outside-of-project'; -async function smigCopyText(text) { - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(text); - return true; - } - } catch { - // 退回受限 Webview 的隐藏文本域复制 - } - try { - if (typeof document === 'undefined' || !document.body) return false; - const area = document.createElement('textarea'); - area.value = text; - area.setAttribute('readonly', 'true'); - area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;'; - document.body.appendChild(area); - area.select?.(); - const ok = Boolean(document.execCommand?.('copy')); - document.body.removeChild(area); - return ok; - } catch { - return false; - } -} - function smigGetClientLabel(clientId) { if (clientId === 'cli') return t('settings.oth.migClientCli'); if (clientId === 'ide_legacy') return t('settings.oth.migClientIdeLegacy'); @@ -24487,41 +24743,27 @@ const SessionMigrationCard = defineComponent({ projectSelect.el, ]); - searchInput = h('input', { - type: 'text', - className: 'smig-search-input', - autocomplete: 'off', - spellcheck: 'false', + const searchBox = createSearchInput({ + wrapClassName: 'smig-search-wrap', + iconClassName: 'smig-search-icon', + inputClassName: 'smig-search-input', + clearClassName: 'smig-search-clear', placeholder: t('settings.oth.migSearchPlaceholder'), - value: '', - }); - searchClearBtn = h( - 'button', - { - type: 'button', - className: 'smig-search-clear', - hidden: true, - 'aria-label': t('select.clearSearch'), - onClick: () => { - searchQuery = ''; - searchInput.value = ''; - patchAttr(searchClearBtn, 'hidden', true); - renderSessionList(); - searchInput.focus?.(); - }, + clearAriaLabel: t('select.clearSearch'), + closeIconSize: 10, + onInput: (val) => { + searchQuery = String(val || '').trim(); + renderSessionList(); + }, + onClear: () => { + searchQuery = ''; + renderSessionList(); + searchInput.focus?.(); }, - [createSvgIcon('close', { size: 10 })] - ); - searchInput.addEventListener?.('input', () => { - searchQuery = String(searchInput.value || '').trim(); - patchAttr(searchClearBtn, 'hidden', !searchQuery); - renderSessionList(); }); - const searchWrap = h('div', { className: 'smig-search-wrap' }, [ - createSvgIcon('search', { size: 12, className: 'smig-search-icon' }), - searchInput, - searchClearBtn, - ]); + searchInput = searchBox.inputEl; + searchClearBtn = searchBox.clearBtnEl; + const searchWrap = searchBox.el; toggleAllBtn = h('button', { type: 'button', @@ -24947,7 +25189,7 @@ const SessionMigrationCard = defineComponent({ className: 'btn-ghost-sm smig-cmd-copy', text: isCopied ? t('settings.oth.migCopied') : t('settings.oth.migCopyCmd'), onClick: async () => { - const ok = await smigCopyText(item.resumeCommand); + const ok = await copyPlainTextToClipboard(item.resumeCommand); if (!ok || destroyed) return; copiedCmdId = item.newCascadeId; renderResultBox(); @@ -25102,13 +25344,6 @@ function getFontScaleOptions() { ]; } -function getModernUiOptions() { - return [ - { value: 'on', label: t('settings.gen.modernUiOn') }, - { value: 'off', label: t('settings.gen.modernUiOff') }, - ]; -} - function getUpdateModeOptions() { return [ { value: 'manual', label: t('settings.gen.updateManual') }, @@ -25276,10 +25511,10 @@ const SettingsGeneralTab = defineComponent({ }, }); - const modernUiSwitch = SegmentedControl({ - ariaLabel: t('settings.gen.modernUi'), + const modernUiSwitch = ToggleSwitch({ + ariaLabelKey: 'settings.gen.modernUi', + preset: 'modernUi', modelValue: 'on', - options: getModernUiOptions(), onUpdateModelValue: async (val) => { const nextModernUi = val !== 'off'; draftModernUi = nextModernUi; @@ -25501,7 +25736,6 @@ const SettingsGeneralTab = defineComponent({ }); modernUiSwitch.setProps({ modelValue: draftModernUi ? 'on' : 'off', - options: getModernUiOptions(), }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, @@ -25583,9 +25817,7 @@ const SettingsGeneralTab = defineComponent({ options: getFontScaleOptions(), }); modernUiSwitch.setProps({ - ariaLabel: t('settings.gen.modernUi'), modelValue: draftModernUi ? 'on' : 'off', - options: getModernUiOptions(), }); autoUpdateSelect.setProps({ modelValue: draftPluginUpdateMode, @@ -25659,20 +25891,6 @@ function getMountModeOptions() { ]; } -function getMultiToggleOptions() { - return [ - { value: 'show', label: t('settings.str.show') }, - { value: 'hide', label: t('settings.str.hide') }, - ]; -} - -function getEnableToggleOptions() { - return [ - { value: 'on', label: t('settings.str.on') }, - { value: 'off', label: t('settings.str.off') }, - ]; -} - function getPopoverWidthModeOptions() { return [ { value: 'auto', label: t('settings.str.popoverWidthAuto') }, @@ -26095,10 +26313,10 @@ const SettingsStructureTab = defineComponent({ }, }); - const multiSessionToggle = SegmentedControl({ - ariaLabel: t('settings.str.multiToggle'), + const multiSessionToggle = ToggleSwitch({ + ariaLabelKey: 'settings.str.multiToggle', + preset: 'visibility', modelValue: 'show', - options: getMultiToggleOptions(), onUpdateModelValue: (val) => { draftShowTopbarMulti = val !== 'hide'; syncMountSectionMeta(); @@ -26124,10 +26342,10 @@ const SettingsStructureTab = defineComponent({ }, }); - const cliCapsuleToggle = SegmentedControl({ - ariaLabel: t('settings.str.cliCapsuleToggle'), + const cliCapsuleToggle = ToggleSwitch({ + ariaLabelKey: 'settings.str.cliCapsuleToggle', + preset: 'enable', modelValue: 'on', - options: getEnableToggleOptions(), onUpdateModelValue: (val) => { draftEnableCliStatusLine = val !== 'off'; syncMountSectionMeta(); @@ -26358,7 +26576,6 @@ const SettingsStructureTab = defineComponent({ } multiSessionToggle.setProps({ modelValue: draftShowTopbarMulti ? 'show' : 'hide', - options: getMultiToggleOptions(), }); contextAgentModeToggle.setProps({ modelValue: draftContextAgentMode, @@ -26369,7 +26586,6 @@ const SettingsStructureTab = defineComponent({ patchAttr(cliStatusGroupEl, 'hidden', !cliInstalled); cliCapsuleToggle.setProps({ modelValue: draftEnableCliStatusLine ? 'on' : 'off', - options: getEnableToggleOptions(), }); patchAttr(cliStatusDetailEl, 'hidden', !draftEnableCliStatusLine); const effectiveCliSlots = getEffectiveDraftCliSlots(); @@ -26719,10 +26935,10 @@ const SettingsStructureTab = defineComponent({ text: t('settings.str.stepsColsLabel'), }); - const stepTurnRailToggle = SegmentedControl({ - ariaLabel: t('settings.str.stepTurnRailToggle'), + const stepTurnRailToggle = ToggleSwitch({ + ariaLabelKey: 'settings.str.stepTurnRailToggle', + preset: 'visibility', modelValue: 'hide', - options: getMultiToggleOptions(), onUpdateModelValue: (val) => { draftShowStepTurnRail = val !== 'hide'; syncStepsSectionMeta(); @@ -26732,10 +26948,10 @@ const SettingsStructureTab = defineComponent({ }, }); - const stepAgentBadgeToggle = SegmentedControl({ - ariaLabel: t('settings.str.stepAgentBadgeToggle'), + const stepAgentBadgeToggle = ToggleSwitch({ + ariaLabelKey: 'settings.str.stepAgentBadgeToggle', + preset: 'visibility', modelValue: 'show', - options: getMultiToggleOptions(), onUpdateModelValue: (val) => { draftShowStepAgentBadge = val !== 'hide'; syncStepsSectionMeta(); @@ -26745,10 +26961,10 @@ const SettingsStructureTab = defineComponent({ }, }); - const stepSpeedColorToggle = SegmentedControl({ - ariaLabel: t('settings.str.stepSpeedColorToggle'), + const stepSpeedColorToggle = ToggleSwitch({ + ariaLabelKey: 'settings.str.stepSpeedColorToggle', + preset: 'enable', modelValue: 'off', - options: getEnableToggleOptions(), onUpdateModelValue: (val) => { draftShowStepSpeedColor = val !== 'off'; syncStepsSectionMeta(); @@ -26758,10 +26974,10 @@ const SettingsStructureTab = defineComponent({ }, }); - const stepFilterToolbarToggle = SegmentedControl({ - ariaLabel: t('settings.str.stepFilterToolbarToggle'), + const stepFilterToolbarToggle = ToggleSwitch({ + ariaLabelKey: 'settings.str.stepFilterToolbarToggle', + preset: 'enable', modelValue: 'off', - options: getEnableToggleOptions(), onUpdateModelValue: (val) => { draftShowStepFilterToolbar = val !== 'off'; syncStepsSectionMeta(); @@ -26940,19 +27156,15 @@ const SettingsStructureTab = defineComponent({ function syncStepsSectionMeta() { stepTurnRailToggle.setProps({ modelValue: draftShowStepTurnRail ? 'show' : 'hide', - options: getMultiToggleOptions(), }); stepAgentBadgeToggle.setProps({ modelValue: draftShowStepAgentBadge ? 'show' : 'hide', - options: getMultiToggleOptions(), }); stepSpeedColorToggle.setProps({ modelValue: draftShowStepSpeedColor ? 'on' : 'off', - options: getEnableToggleOptions(), }); stepFilterToolbarToggle.setProps({ modelValue: draftShowStepFilterToolbar ? 'on' : 'off', - options: getEnableToggleOptions(), }); if (document?.activeElement !== stepTokenComboInput) { stepTokenComboInput.value = rawStepTokenComboText; @@ -27226,13 +27438,6 @@ const { SettingsOtherTab } = (() => { */ -function getEnableToggleOptions() { - return [ - { value: 'on', label: t('settings.str.on') }, - { value: 'off', label: t('settings.str.off') }, - ]; -} - function formatQuotaReservationLogForClipboard(snapshot) { const safe = snapshot && typeof snapshot === 'object' ? snapshot : {}; const buckets = Array.isArray(safe.buckets) ? safe.buckets : []; @@ -27470,16 +27675,15 @@ const SettingsOtherTab = defineComponent({ [createSvgIcon('copy', { size: 12 }), exportReserveLogBtnText] ); - const quotaReserveToggle = SegmentedControl({ + const quotaReserveToggle = ToggleSwitch({ modelValue: 'off', - ariaLabel: t('settings.oth.quotaReserveLabel'), - options: getEnableToggleOptions(), + ariaLabelKey: 'settings.oth.quotaReserveLabel', + preset: 'enable', onUpdateModelValue: async (val) => { const nextEnabled = val === 'on'; draftExperimentalQuotaReservation = nextEnabled; quotaReserveToggle.setProps({ modelValue: nextEnabled ? 'on' : 'off', - options: getEnableToggleOptions(), }); showExpFeedback(t('settings.saving'), 0); try { @@ -27561,10 +27765,10 @@ const SettingsOtherTab = defineComponent({ className: 'form-label', text: t('settings.oth.ctxMainLabel'), }); - const ctxMainToggle = SegmentedControl({ + const ctxMainToggle = ToggleSwitch({ modelValue: 'on', - ariaLabel: t('settings.oth.ctxMainLabel'), - options: getEnableToggleOptions(), + ariaLabelKey: 'settings.oth.ctxMainLabel', + preset: 'enable', onUpdateModelValue: async (val) => { if (!draftContextRiskAccepted || savingContextScope) return; const nextEnabled = val === 'on'; @@ -27591,10 +27795,10 @@ const SettingsOtherTab = defineComponent({ className: 'form-label', text: t('settings.oth.ctxSwarmLabel'), }); - const ctxSwarmToggle = SegmentedControl({ + const ctxSwarmToggle = ToggleSwitch({ modelValue: 'off', - ariaLabel: t('settings.oth.ctxSwarmLabel'), - options: getEnableToggleOptions(), + ariaLabelKey: 'settings.oth.ctxSwarmLabel', + preset: 'enable', onUpdateModelValue: async (val) => { if (!draftContextRiskAccepted || savingContextScope) return; const nextEnabled = val === 'on'; @@ -27714,14 +27918,10 @@ const SettingsOtherTab = defineComponent({ patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel')); ctxMainToggle.setProps({ modelValue: draftContextMainEnabled ? 'on' : 'off', - options: getEnableToggleOptions(), - ariaLabel: t('settings.oth.ctxMainLabel'), }); patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel')); ctxSwarmToggle.setProps({ modelValue: draftContextSwarmEnabled ? 'on' : 'off', - options: getEnableToggleOptions(), - ariaLabel: t('settings.oth.ctxSwarmLabel'), }); const syncErrorText = @@ -28108,8 +28308,6 @@ const SettingsOtherTab = defineComponent({ }); quotaReserveToggle.setProps({ modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', - options: getEnableToggleOptions(), - ariaLabel: t('settings.oth.quotaReserveLabel'), }); renderContextWindows(); void sessionMigrationCard.refs.ensureLoaded(); @@ -28128,8 +28326,6 @@ const SettingsOtherTab = defineComponent({ patchText(exportReserveLogBtnText, t('settings.oth.exportReserveLogBtn')); quotaReserveToggle.setProps({ modelValue: draftExperimentalQuotaReservation ? 'on' : 'off', - options: getEnableToggleOptions(), - ariaLabel: t('settings.oth.quotaReserveLabel'), }); patchText(baselineTitleEl, t('settings.oth.baselineTitle')); renderContextWindows(); @@ -29245,6 +29441,8 @@ const ConsumptionView = defineComponent({ }); let activeHoverTargetEl = null; + let cachedBreakdownRootRect = null; + let cachedBreakdownAnchorRect = null; const popoverContent = createConsumptionBreakdownContent({ showModelDot: true, @@ -29257,6 +29455,8 @@ const ConsumptionView = defineComponent({ ); function hideBreakdownPopover() { + cachedBreakdownRootRect = null; + cachedBreakdownAnchorRect = null; if (activeHoverTargetEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); activeHoverTargetEl = null; @@ -29266,27 +29466,29 @@ const ConsumptionView = defineComponent({ } function positionBreakdownPopover(anchorEl, pointerClientX = null, pointerClientY = null) { - const rootRect = rootEl.getBoundingClientRect?.() || { - left: 0, - top: 0, - width: 360, - height: 600, - }; - const anchorRect = anchorEl?.getBoundingClientRect?.() || { - left: 0, - top: 0, - bottom: 0, - width: 0, - height: 0, - }; - const tipRect = breakdownPopoverEl.getBoundingClientRect?.() || { - width: 216, - height: 108, - }; + if (!cachedBreakdownRootRect) { + cachedBreakdownRootRect = rootEl.getBoundingClientRect?.() || { + left: 0, + top: 0, + width: 360, + height: 600, + }; + } + const rootRect = cachedBreakdownRootRect; + if (!cachedBreakdownAnchorRect) { + cachedBreakdownAnchorRect = anchorEl?.getBoundingClientRect?.() || { + left: 0, + top: 0, + bottom: 0, + width: 0, + height: 0, + }; + } + const anchorRect = cachedBreakdownAnchorRect; + const tipW = Number(breakdownPopoverEl.offsetWidth || 0) || 216; + const tipH = Number(breakdownPopoverEl.offsetHeight || 0) || 108; const rootW = rootRect.width > 0 ? rootRect.width : 360; const rootH = rootRect.height > 0 ? rootRect.height : 600; - const tipW = tipRect.width > 0 ? tipRect.width : 216; - const tipH = tipRect.height > 0 ? tipRect.height : 108; const hasPointerX = Number.isFinite(pointerClientX) && pointerClientX > 0 && rootRect.width > 0; const hasPointerY = Number.isFinite(pointerClientY) && pointerClientY > 0 && rootRect.height > 0; @@ -29332,6 +29534,10 @@ const ConsumptionView = defineComponent({ } if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); + cachedBreakdownAnchorRect = null; + } else if (!activeHoverTargetEl) { + cachedBreakdownRootRect = null; + cachedBreakdownAnchorRect = null; } activeHoverTargetEl = anchorEl; patchClasses(anchorEl, { 'is-hovered': true }); @@ -31392,40 +31598,30 @@ const StepsDetailView = defineComponent({ ); // --- 步骤搜索栏及快捷诊断芯片 --- - const stepSearchClearBtn = h( - 'button', - { - type: 'button', - className: 'steps-search-clear', - hidden: true, - 'aria-label': t('steps.searchClearAria'), - onclick: () => { - stepSearchQuery = ''; - stepSearchInput.value = ''; - patchAttr(stepSearchClearBtn, 'hidden', true); - if (latestSlice) renderStepsData(latestSlice); - stepSearchInput.focus?.(); - }, - }, - [createSvgIcon('close', { size: 11 })] - ); - const stepSearchInput = h('input', { - type: 'text', - className: 'steps-search-input', + const stepSearchBox = createSearchInput({ + wrapClassName: 'steps-search-wrap', + iconClassName: 'steps-search-icon', + inputClassName: 'steps-search-input', + clearClassName: 'steps-search-clear', placeholder: t('steps.searchPlaceholder'), - 'aria-label': t('steps.searchPlaceholder'), - onInput: (e) => { - stepSearchQuery = String(e?.target?.value ?? ''); - patchAttr(stepSearchClearBtn, 'hidden', !stepSearchQuery.trim()); + ariaLabel: t('steps.searchPlaceholder'), + clearAriaLabel: t('steps.searchClearAria'), + closeIconSize: 11, + onInput: (val) => { + stepSearchQuery = String(val ?? ''); if (latestSlice) renderStepsData(latestSlice); }, + onClear: () => { + stepSearchQuery = ''; + if (latestSlice) renderStepsData(latestSlice); + stepSearchInput.focus?.(); + }, onKeydown: (e) => { if (e?.key === 'Escape') { e.stopPropagation?.(); if (stepSearchQuery) { stepSearchQuery = ''; - stepSearchInput.value = ''; - patchAttr(stepSearchClearBtn, 'hidden', true); + stepSearchBox.setValue(''); if (latestSlice) renderStepsData(latestSlice); } else { stepSearchInput.blur?.(); @@ -31433,11 +31629,9 @@ const StepsDetailView = defineComponent({ } }, }); - const stepSearchWrapEl = h('div', { className: 'steps-search-wrap' }, [ - createSvgIcon('search', { size: 12, className: 'steps-search-icon' }), - stepSearchInput, - stepSearchClearBtn, - ]); + const stepSearchWrapEl = stepSearchBox.el; + const stepSearchInput = stepSearchBox.inputEl; + const stepSearchClearBtn = stepSearchBox.clearBtnEl; const QUICK_CHIP_DEFS = [ { key: 'anomaly', i18nKey: 'steps.chipAnomaly', tone: 'is-warn' }, @@ -34600,6 +34794,51 @@ function getLeftSidebarRightEdge(vw) { /** * 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 */ +const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([ + 'src/styles/views-overview.css', + 'src/styles/views-consumption.css', + 'src/styles/views-tables.css', + 'src/styles/views-settings.css', + 'src/styles/controls.css', +]); + +let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null }; + +function buildSlimCapsuleCss(fullCss) { + if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss; + return fullCss + .split(/(?=\/\* --- src\/styles\/)/) + .filter((block) => { + const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//); + return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]); + }) + .join(''); +} + +function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) { + if (!shadowRoot) return; + if ( + fullCss && + typeof CSSStyleSheet === 'function' && + Array.isArray(shadowRoot.adoptedStyleSheets) + ) { + try { + if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) { + const sheet = new CSSStyleSheet(); + sheet.replaceSync(fullCss); + sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet }; + } + shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet]; + return; + } catch { + // 降级到传统