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');