From b57c5d5987a7cb398c7c3088f78c4cfc0b32d62f Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 01:34:39 +0900 Subject: [PATCH 01/30] feat(panel): filter family-group and external usage from quota reservation --- sidecars/panel/app.js | 91 +++- sidecars/panel/backend/quota-reservation.mjs | 381 ++++++++++++-- sidecars/panel/backend/telemetry-builder.mjs | 46 ++ sidecars/panel/index.html | 4 +- .../components/widgets/QuotaPoolsWidget.js | 79 ++- sidecars/panel/src/i18n/en-US.js | 6 + sidecars/panel/src/i18n/zh-CN.js | 6 + sidecars/panel/src/styles/views-overview.css | 39 ++ sidecars/panel/styles.css | 39 ++ .../panel/test/quota-reservation.test.mjs | 496 +++++++++++++++++- 10 files changed, 1110 insertions(+), 77 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 650dd4d..ab09113 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1467,6 +1467,12 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopSamples': '{n} 样本', 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', + 'quota.ratePopSharedBadge': '共享活跃', + 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', + 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', + 'quota.ratePopExternalBaseline': '检测到本周期存在家庭组 / 其他设备消耗,预占和费率仅按本机实测校准', + 'quota.ratePopExt5h': '5h {pct}%', + 'quota.ratePopExtWk': '周限 {pct}%', // Live Activity Widget 'live.currentSession': '当前会话', @@ -2355,6 +2361,12 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopSamples': '{n} samples', 'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.', 'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.', + 'quota.ratePopSharedBadge': 'Shared active', + 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', + 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', + 'quota.ratePopExternalBaseline': 'Family group / other-device usage detected this cycle; reservations & rates calibrate on local steps only', + 'quota.ratePopExt5h': '5h {pct}%', + 'quota.ratePopExtWk': 'Weekly {pct}%', // Live Activity Widget 'live.currentSession': 'Current Session', @@ -19285,7 +19297,8 @@ const QuotaPoolsWidget = defineComponent({ const hasPoolFallback = models.length === 0 && (Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd)); - if (models.length === 0 && !hasPoolFallback) continue; + const ext = est.externalUsage && est.externalUsage.detected ? est.externalUsage : null; + if (models.length === 0 && !hasPoolFallback && !ext) continue; const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; const rows = @@ -19301,25 +19314,65 @@ const QuotaPoolsWidget = defineComponent({ samples: item.samples, }) ) - : [ - createRateModelCard({ - name: t('quota.ratePopPoolFallback'), - isMutedName: true, - isFallback: true, - rate5hPctPerUsd: est.rate5hPctPerUsd, - rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, - eqFull5hUsd: est.eqFull5hUsd, - eqFullWeeklyUsd: est.eqFullWeeklyUsd, - samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), - }), - ]; + : hasPoolFallback + ? [ + createRateModelCard({ + name: t('quota.ratePopPoolFallback'), + isMutedName: true, + isFallback: true, + rate5hPctPerUsd: est.rate5hPctPerUsd, + rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, + eqFull5hUsd: est.eqFull5hUsd, + eqFullWeeklyUsd: est.eqFullWeeklyUsd, + samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), + }), + ] + : []; - populatedGroups.push( - h('div', { className: 'quota-rate-pool-group' }, [ - h('div', { className: 'quota-rate-pool-label', text: poolLabel }), - h('div', { className: 'quota-rate-model-list' }, rows), - ]) - ); + const headChildren = [h('div', { className: 'quota-rate-pool-label', text: poolLabel })]; + if (ext?.activeRecently) { + headChildren.push( + h('span', { + className: 'quota-rate-shared-badge', + text: t('quota.ratePopSharedBadge'), + title: t('quota.ratePopSharedBadgeTip'), + }) + ); + } + + const groupChildren = [h('div', { className: 'quota-rate-pool-head' }, headChildren)]; + if (rows.length > 0) { + groupChildren.push(h('div', { className: 'quota-rate-model-list' }, rows)); + } else { + groupChildren.push( + h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') }) + ); + } + if (ext) { + const extParts = []; + if (Number(ext.used5hPct) >= 0.1) { + extParts.push( + t('quota.ratePopExt5h', { pct: formatPctNumber(Number(ext.used5hPct)) }) + ); + } + if (Number(ext.usedWeeklyPct) >= 0.1) { + extParts.push( + t('quota.ratePopExtWk', { pct: formatPctNumber(Number(ext.usedWeeklyPct)) }) + ); + } + const extText = + extParts.length > 0 + ? t('quota.ratePopExternalDetail', { detail: extParts.join(' · ') }) + : t('quota.ratePopExternalBaseline'); + groupChildren.push( + h('div', { + className: `quota-rate-ext-banner${ext.activeRecently ? ' is-active' : ''}`, + text: extText, + }) + ); + } + + populatedGroups.push(h('div', { className: 'quota-rate-pool-group' }, groupChildren)); } if (populatedGroups.length === 0) { diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs index 44f3ea2..127b26f 100644 --- a/sidecars/panel/backend/quota-reservation.mjs +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -41,6 +41,22 @@ export const QR_CONSUME_MIN_SHORTFALL_PCT = 0.03; export const QR_CONSUME_SHORTFALL_RATIO = 0.35; export const QR_MODEL_RATE_MIN_UI_SAMPLES = 3; export const QR_MODEL_SINGLE_DOMINANCE_RATIO = 0.95; +export const QR_LOCAL_ACTIVITY_GRACE_MS = 2 * 60 * 1000; +export const QR_EXTERNAL_ACTIVE_WINDOW_MS = 15 * 60 * 1000; +export const QR_EXTERNAL_MIN_IDLE_DELTA_PCT = 0.05; +export const QR_EXTERNAL_BASELINE_USED_PCT = 0.5; +export const QR_EXTERNAL_BASELINE_MAX_LOCAL_COST_USD = 0.05; +export const QR_CO_MOVE_MIN_5H_EXCESS_PCT = 0.35; +export const QR_CO_MOVE_MIN_WK_EXCESS_PCT = 0.1; +export const QR_CO_MOVE_MIN_RATE_RATIO = 1.8; +export const QR_CO_MOVE_MIN_USD_RATIO = 0.65; +export const QR_CO_MOVE_MAX_USD_RATIO = 1.55; +export const QR_UNCONFIRMED_NORMAL_STEPS_EVICT = 3; +export const QR_UNCONFIRMED_NORMAL_PCT_EVICT = 0.25; +export const QR_UNCONFIRMED_RATIO_FLOOR = 0.72; +export const QR_TENTATIVE_NORMAL_STEPS_EVICT = 2; +export const QR_TENTATIVE_NORMAL_PCT_EVICT = 0.12; +export const QR_TENTATIVE_LEASE_TTL_MS = 3 * 60 * 1000; const QR_MAX_MODELS_PER_BUCKET = 16; const QR_MAX_TRACKED_BUCKETS = 128; const QR_MAX_ACTIVE_LEASES = 16; @@ -74,14 +90,29 @@ function qrResolveExactUsedPct(poolObj, win) { return null; } -function qrSumLeases(leases) { +function qrSumLeases(leases, { includeTentative = true } = {}) { let sum = 0; for (let i = 0; i < leases.length; i += 1) { + if (!includeTentative && leases[i]?.tentative) continue; sum += Math.max(0, Number(leases[i]?.remainingPct) || 0); } return sum; } +function qrConfirmAllLeases(leases) { + let promoted = false; + for (let i = 0; i < leases.length; i += 1) { + if (leases[i].tentative) { + leases[i].tentative = false; + promoted = true; + } + leases[i].confirmed = true; + leases[i].unabsorbedNormalSteps = 0; + leases[i].unabsorbedExpectedPct = 0; + } + return promoted; +} + function qrConsumeLeasesFifo(leases, amountPct) { let left = Math.max(0, Number(amountPct) || 0); if (left <= 0 || leases.length === 0) return 0; @@ -153,7 +184,8 @@ function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { if (state.ratePctPerUsd !== null && Number.isFinite(state.ratePctPerUsd)) { return state.ratePctPerUsd; } - if (cycleCostUsd >= 0.5 && officialUsedPct >= 0.3) { + // 一旦检测到同池存在家庭组 / 其他设备外部消耗,禁止用累计总占比 / 本机花费做冷启动反推 + if (!state.hasExternalUsage && cycleCostUsd >= 0.5 && officialUsedPct >= 0.3) { return qrClampRate(officialUsedPct / cycleCostUsd); } return null; @@ -164,16 +196,20 @@ function qrPruneExpiredLeases(state, nowMs) { for (let i = state.activeLeases.length - 1; i >= 0; i -= 1) { const lease = state.activeLeases[i]; const lastActiveMs = lease.lastTouchedMs || lease.createdAtMs || 0; + const tentativeExpired = + Boolean(lease.tentative) && + (lease.createdAtMs || 0) > 0 && + nowMs - (lease.createdAtMs || 0) >= QR_TENTATIVE_LEASE_TTL_MS; 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) { + if (tentativeExpired || idleExpired || maxAgeExpired) { state.activeLeases.splice(i, 1); } } } function qrFormatOutput(state, officialUsedPct) { - const rawSum = qrSumLeases(state.activeLeases); + const rawSum = qrSumLeases(state.activeLeases, { includeTentative: false }); let dropOffset = 0; if (state.pendingDrop && Number.isFinite(state.pendingDrop.preDropUsedPct)) { const costSinceDrop = Math.max( @@ -197,7 +233,10 @@ function qrFormatOutput(state, officialUsedPct) { } const rounded = qrClamp(qrRound1(rawReserved), 0, qrRound1(officialUsedPct)); let earliestExpiresAtMs = null; + let visibleCount = 0; for (let i = 0; i < state.activeLeases.length; i += 1) { + if (state.activeLeases[i]?.tentative) continue; + visibleCount += 1; const exp = (state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) + QR_LEASE_TTL_MS; @@ -207,7 +246,7 @@ function qrFormatOutput(state, officialUsedPct) { } return { reservedPct: rounded, - reservedLeaseCount: state.activeLeases.length, + reservedLeaseCount: visibleCount, reservedExpiresAtMs: earliestExpiresAtMs, }; } @@ -229,6 +268,10 @@ function qrSanitizePersistedLeases(rawLeases) { createdAtMs, lastTouchedMs, sessionCount: Math.max(1, Number(item.sessionCount) || 1), + confirmed: item.confirmed !== false, + tentative: item.tentative === true, + unabsorbedNormalSteps: Math.max(0, Math.floor(Number(item.unabsorbedNormalSteps) || 0)), + unabsorbedExpectedPct: Math.max(0, Number(item.unabsorbedExpectedPct) || 0), }); } return out; @@ -353,7 +396,7 @@ function qrEstimateModelWeightedPct(st, deltaModelCosts, totalDeltaCostUsd, fall return weightedPct + unattributedCost * fallbackRate; } -function qrBuildPoolRateEstimate(st5h, stWk) { +function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) { const raw5hPool = st5h && st5h.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st5h.ratePctPerUsd) ? st5h.ratePctPerUsd @@ -425,7 +468,28 @@ function qrBuildPoolRateEstimate(st5h, stWk) { delete m._rawRw; } - if (models.length === 0 && rate5hPool === null && rateWkPool === null) { + const extDetected = Boolean(st5h?.hasExternalUsage || stWk?.hasExternalUsage); + const lastExtAtMs = Math.max( + Number(st5h?.lastExternalUsageAtMs) || 0, + Number(stWk?.lastExternalUsageAtMs) || 0 + ); + const extActiveRecently = + lastExtAtMs > 0 && nowMs >= lastExtAtMs && nowMs - lastExtAtMs <= QR_EXTERNAL_ACTIVE_WINDOW_MS; + const ext5hPct = +(Number(st5h?.externalUsedPct) || 0).toFixed(1); + const extWkPct = +(Number(stWk?.externalUsedPct) || 0).toFixed(1); + const extEvents = (Number(st5h?.externalEvents) || 0) + (Number(stWk?.externalEvents) || 0); + const externalUsage = extDetected + ? { + detected: true, + activeRecently: extActiveRecently, + used5hPct: ext5hPct, + usedWeeklyPct: extWkPct, + events: extEvents, + lastSeenAtMs: lastExtAtMs || null, + } + : null; + + if (models.length === 0 && rate5hPool === null && rateWkPool === null && !externalUsage) { return null; } @@ -437,9 +501,83 @@ function qrBuildPoolRateEstimate(st5h, stWk) { samples5h: st5h?.rateSamples || 0, samplesWeekly: stWk?.rateSamples || 0, models, + ...(externalUsage ? { externalUsage } : {}), }; } +function qrComputeBucketDeltaPreview(st, { officialUsedPct, resetTimeMs, quotaFetchedAtMs, cycleCostUsd, modelCostsUsd, nowMs }) { + if (!st || st.lastOfficialUsedPct === null || st.pendingDrop) return null; + if (officialUsedPct === null || !Number.isFinite(officialUsedPct)) return null; + const safeUsed = qrClamp(Number(officialUsedPct), 0, 100); + const safeCost = Math.max(0, Number(cycleCostUsd) || 0); + const safeResetMs = Number(resetTimeMs) > 0 ? Number(resetTimeMs) : 0; + const safeFetchTs = Number(quotaFetchedAtMs) > 0 ? Number(quotaFetchedAtMs) : nowMs; + const resetShifted = + safeResetMs > 0 && + st.resetTimeMs > 0 && + Math.abs(safeResetMs - st.resetTimeMs) > QR_CYCLE_RESET_SHIFT_MS; + const rolloverDrop = st.lastOfficialUsedPct >= 5 && safeUsed < 1; + if (resetShifted || rolloverDrop) return null; + const isFreshSample = + safeFetchTs !== st.lastQuotaTs || Math.abs(safeUsed - st.lastOfficialUsedPct) > 1e-4; + if (!isFreshSample) return null; + + const rate = st.ratePctPerUsd; + if (rate === null || !Number.isFinite(rate) || rate <= 0 || (st.rateSamples || 0) < 2) { + return null; + } + const deltaOfficial = safeUsed - st.lastOfficialUsedPct; + if (deltaOfficial <= 1e-3) return null; + + const rawDeltaCost = Math.max(0, safeCost - st.lastCycleCostUsd); + const safeModelCosts = qrSanitizeModelCosts(modelCostsUsd); + const prevModelCosts = st.lastModelCostsUsd && typeof st.lastModelCostsUsd === 'object' ? st.lastModelCostsUsd : {}; + const hasValidPrevModelBaseline = + st.lastCycleCostUsd <= 1e-6 || Object.keys(prevModelCosts).length > 0; + const rawDeltaModelCosts = {}; + if (hasValidPrevModelBaseline) { + for (const [mKey, curModelCost] of Object.entries(safeModelCosts)) { + const dModel = curModelCost - (Number(prevModelCosts[mKey]) || 0); + if (dModel > 1e-6) rawDeltaModelCosts[mKey] = dModel; + } + } + const pendingValid = + st.pendingCostUsd > 0 && nowMs - st.pendingCostAtMs <= QR_PENDING_COST_TTL_MS; + const effectiveDeltaCost = rawDeltaCost + (pendingValid ? st.pendingCostUsd : 0); + const effectiveDeltaModelCosts = { ...rawDeltaModelCosts }; + if (pendingValid && st.pendingModelCostsUsd && typeof st.pendingModelCostsUsd === 'object') { + for (const [mKey, pCost] of Object.entries(st.pendingModelCostsUsd)) { + if (Number.isFinite(pCost) && pCost > 0) { + effectiveDeltaModelCosts[mKey] = (effectiveDeltaModelCosts[mKey] || 0) + pCost; + } + } + } + const expectedDeltaPct = qrEstimateModelWeightedPct( + st, + effectiveDeltaModelCosts, + effectiveDeltaCost, + rate + ); + const excessPct = deltaOfficial - expectedDeltaPct; + return { rate, deltaOfficial, expectedDeltaPct, excessPct }; +} + +function qrDetectProportionalExternalJump(st5h, stWk, params5h, paramsWk) { + const p5 = qrComputeBucketDeltaPreview(st5h, params5h); + const pw = qrComputeBucketDeltaPreview(stWk, paramsWk); + if (!p5 || !pw) return false; + if (p5.rate / pw.rate < QR_CO_MOVE_MIN_RATE_RATIO) return false; + if (p5.excessPct < QR_CO_MOVE_MIN_5H_EXCESS_PCT) return false; + if (pw.excessPct < QR_CO_MOVE_MIN_WK_EXCESS_PCT) return false; + const impliedUsd5h = p5.excessPct / p5.rate; + const impliedUsdWk = pw.excessPct / pw.rate; + if (!Number.isFinite(impliedUsd5h) || !Number.isFinite(impliedUsdWk) || impliedUsdWk <= 1e-6) { + return false; + } + const usdRatio = impliedUsd5h / impliedUsdWk; + return usdRatio >= QR_CO_MOVE_MIN_USD_RATIO && usdRatio <= QR_CO_MOVE_MAX_USD_RATIO; +} + function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { if (!raw || typeof raw !== 'object') return null; const lastOfficial = @@ -484,6 +622,10 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0), lastRefundAtMs: Math.max(0, Number(raw.lastRefundAtMs) || 0), lastRefundPct: Math.max(0, Number(raw.lastRefundPct) || 0), + hasExternalUsage: raw.hasExternalUsage === true, + lastExternalUsageAtMs: Math.max(0, Number(raw.lastExternalUsageAtMs) || 0), + externalUsedPct: Math.max(0, Number(raw.externalUsedPct) || 0), + externalEvents: Math.max(0, Math.floor(Number(raw.externalEvents) || 0)), }; } @@ -555,6 +697,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastBounceAtMs: st.lastBounceAtMs, lastRefundAtMs: st.lastRefundAtMs, lastRefundPct: st.lastRefundPct, + hasExternalUsage: Boolean(st.hasExternalUsage), + lastExternalUsageAtMs: st.lastExternalUsageAtMs || 0, + externalUsedPct: +(Number(st.externalUsedPct) || 0).toFixed(3), + externalEvents: Math.max(0, Math.floor(Number(st.externalEvents) || 0)), }; } return { @@ -572,12 +718,15 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu eventKind === 'idle' || eventKind === 'lag_pending' || eventKind === 'drop_pending' || - eventKind === 'replica_flip' + eventKind === 'replica_flip' || + eventKind === 'lease_tentative' ) { return; } const isUrgent = eventKind === 'lease' || + eventKind === 'lease_rejected' || + eventKind === 'external_usage' || eventKind === 'refund' || eventKind === 'reset' || eventKind === 'expire'; @@ -633,6 +782,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastBounceAtMs: 0, lastRefundAtMs: 0, lastRefundPct: 0, + hasExternalUsage: false, + lastExternalUsageAtMs: 0, + externalUsedPct: 0, + externalEvents: 0, }; buckets.set(bucketKey, st); return st; @@ -651,6 +804,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu poolLastActivityMs = 0, activeSessionCount10m = 0, recent10mCostUsd = 0, + hasRunningLocalSession = false, + forceExternalJump = false, + peerLastExternalUsageAtMs = 0, nowMs = Date.now(), }) { if (officialUsedPct === null || !Number.isFinite(officialUsedPct)) { @@ -723,12 +879,17 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingModelCostsUsd = {}; st.activeLeases = []; st.pendingDrop = null; + st.hasExternalUsage = + safeUsed >= QR_EXTERNAL_BASELINE_USED_PCT && + safeCost < QR_EXTERNAL_BASELINE_MAX_LOCAL_COST_USD; + st.externalUsedPct = 0; + st.externalEvents = 0; const out = qrFormatOutput(st, safeUsed); recordLog('reset', { deltaOfficial: safeUsed - prevUsed, ...out }); return out; } - // 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(不入中位数样本池) + // 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(检测到外部消耗时跳过累计比值反推) if (st.lastOfficialUsedPct === null) { st.resetTimeMs = safeResetMs; st.lastQuotaTs = safeFetchTs; @@ -736,7 +897,12 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastCycleCostUsd = safeCost; st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; - if (safeCost >= 0.5 && safeUsed >= 0.3) { + if ( + safeUsed >= QR_EXTERNAL_BASELINE_USED_PCT && + safeCost < QR_EXTERNAL_BASELINE_MAX_LOCAL_COST_USD + ) { + st.hasExternalUsage = true; + } else if (!st.hasExternalUsage && safeCost >= 0.5 && safeUsed >= 0.3) { st.ratePctPerUsd = qrClampRate(safeUsed / safeCost); st.rateSamples = 1; } @@ -822,8 +988,29 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu let excessPct = deltaOfficial - expectedDeltaPct; const isIdleRefundReady = poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS; + const hasRecentLocalActivity = + poolLastActivityMs > 0 && nowMs - poolLastActivityMs <= QR_LOCAL_ACTIVITY_GRACE_MS; + const hasLocalPoolActivity = Boolean( + effectiveDeltaCost > 0 || hasRunningLocalSession || hasRecentLocalActivity + ); + const peerExternalTs = Number(peerLastExternalUsageAtMs) || 0; + const latestExternalTs = Math.max(Number(st.lastExternalUsageAtMs) || 0, peerExternalTs); + const externalActiveRecently = + latestExternalTs > 0 && + nowMs >= latestExternalTs && + nowMs - latestExternalTs <= QR_EXTERNAL_ACTIVE_WINDOW_MS; let eventKind = 'idle'; + const recordExternalDelta = (pct) => { + st.hasExternalUsage = true; + st.lastExternalUsageAtMs = nowMs; + st.externalUsedPct = Math.min( + 100, + (Number(st.externalUsedPct) || 0) + Math.max(0, Number(pct) || 0) + ); + st.externalEvents = (Number(st.externalEvents) || 0) + 1; + }; + const clearPendingCost = () => { st.pendingCostUsd = 0; st.pendingCostAtMs = 0; @@ -851,6 +1038,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) { // 4A. 同周期余额回升:区分「静默到期真退还」及「活跃期双副本回落待确认」 + if (st.activeLeases.length > 0) { + qrConfirmAllLeases(st.activeLeases); + } const prevHigh = st.pendingDrop ? Math.max(st.pendingDrop.preDropUsedPct, st.lastOfficialUsedPct) : st.lastOfficialUsedPct; @@ -898,22 +1088,35 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu safeUsed >= reboundFloor; if (isReplicaRebound) { + if (st.activeLeases.length > 0) { + qrConfirmAllLeases(st.activeLeases); + } const excessAboveHighWater = safeUsed - (pd.preDropUsedPct + expectedSinceDrop); st.pendingDrop = null; st.lastBounceAtMs = nowMs; clearPendingCost(); if (rate !== null && excessAboveHighWater >= QR_MIN_JUMP_EXCESS_PCT) { - st.activeLeases.push({ - amountPct: excessAboveHighWater, - remainingPct: excessAboveHighWater, - createdAtMs: nowMs, - lastTouchedMs: nowMs, - sessionCount: Math.max(1, safeSess10m || 1), - }); - if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) { - st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); + if (!hasLocalPoolActivity || forceExternalJump) { + recordExternalDelta(excessAboveHighWater); + eventKind = 'external_usage'; + } else { + const isTentative = externalActiveRecently; + st.activeLeases.push({ + amountPct: excessAboveHighWater, + remainingPct: excessAboveHighWater, + createdAtMs: nowMs, + lastTouchedMs: nowMs, + sessionCount: Math.max(1, safeSess10m || 1), + confirmed: false, + tentative: isTentative, + unabsorbedNormalSteps: 0, + unabsorbedExpectedPct: 0, + }); + if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) { + st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); + } + eventKind = isTentative ? 'lease_tentative' : 'lease'; } - eventKind = 'lease'; } else { eventKind = 'replica_flip'; } @@ -951,7 +1154,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu } } } else if (deltaOfficial > 1e-3) { - // 4B. 官方已用比例上升:区分租约跳变、真实租约内消费及常规消耗 + // 4B. 官方已用比例上升:先筛除外部/家庭组消耗,再区分租约跳变、真实租约内消费及常规消耗 + const isIdleExternalUsage = + !hasLocalPoolActivity && deltaOfficial >= QR_EXTERNAL_MIN_IDLE_DELTA_PCT; const detectedWithRate = rate !== null && excessPct >= QR_MIN_JUMP_EXCESS_PCT; const detectedColdStart = rate === null && @@ -963,30 +1168,70 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu expectedDeltaPct > 0 && shortfall >= Math.max(QR_CONSUME_MIN_SHORTFALL_PCT, expectedDeltaPct * QR_CONSUME_SHORTFALL_RATIO); - if (detectedWithRate || detectedColdStart) { + if (forceExternalJump || isIdleExternalUsage) { + const extAmt = + forceExternalJump && excessPct > 0 ? excessPct : deltaOfficial; + recordExternalDelta(extAmt); + eventKind = 'external_usage'; + } else if (detectedWithRate || detectedColdStart) { const leaseRemaining = detectedWithRate ? excessPct : deltaOfficial; + const isTentative = externalActiveRecently; st.activeLeases.push({ amountPct: leaseRemaining, remainingPct: leaseRemaining, createdAtMs: nowMs, lastTouchedMs: nowMs, sessionCount: Math.max(1, safeSess10m || 1), + confirmed: false, + tentative: isTentative, + unabsorbedNormalSteps: 0, + unabsorbedExpectedPct: 0, }); if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) { st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); } - eventKind = 'lease'; + eventKind = isTentative ? 'lease_tentative' : 'lease'; } else if (isSignificantShortfall) { - // 租约期内出现明显低于预期的官方增量:仅把显著缺口计入当前租约内消费 + // 租约期内出现明显低于预期的官方增量:佐证租约存在并把显著缺口计入当前租约内消费 + qrConfirmAllLeases(st.activeLeases); qrConsumeLeasesFifo(st.activeLeases, shortfall); for (let i = 0; i < st.activeLeases.length; i += 1) { st.activeLeases[i].lastTouchedMs = nowMs; } eventKind = 'consume'; } else { + // 检查未经佐证的疑似租约:若本机单会话持续按 1:1 实扣且无吸收/无回落,说明更可能是外部消耗,快速核销 + let rejectedLease = false; + if ( + st.activeLeases.length > 0 && + effectiveDeltaCost >= 0.02 && + expectedDeltaPct >= 0.02 && + deltaOfficial >= expectedDeltaPct * QR_UNCONFIRMED_RATIO_FLOOR + ) { + for (let i = st.activeLeases.length - 1; i >= 0; i -= 1) { + const lease = st.activeLeases[i]; + if (lease.confirmed) continue; + if (!lease.tentative && safeSess10m > 1) continue; + lease.unabsorbedNormalSteps = (lease.unabsorbedNormalSteps || 0) + 1; + lease.unabsorbedExpectedPct = (lease.unabsorbedExpectedPct || 0) + expectedDeltaPct; + const hitEvict = lease.tentative + ? lease.unabsorbedNormalSteps >= QR_TENTATIVE_NORMAL_STEPS_EVICT && + lease.unabsorbedExpectedPct >= QR_TENTATIVE_NORMAL_PCT_EVICT + : lease.unabsorbedNormalSteps >= QR_UNCONFIRMED_NORMAL_STEPS_EVICT && + lease.unabsorbedExpectedPct >= QR_UNCONFIRMED_NORMAL_PCT_EVICT; + if (hitEvict) { + const droppedPct = Math.max(0, Number(lease.remainingPct) || 0); + st.activeLeases.splice(i, 1); + recordExternalDelta(droppedPct); + rejectedLease = true; + } + } + } + const outsideBounceCooldown = st.lastBounceAtMs === 0 || nowMs - st.lastBounceAtMs >= QR_RATE_BOUNCE_COOLDOWN_MS; if ( + !rejectedLease && st.activeLeases.length === 0 && outsideBounceCooldown && !pendingValid && @@ -1003,7 +1248,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu mr.lastSeenMs = nowMs; } } - eventKind = 'normal'; + eventKind = rejectedLease ? 'lease_rejected' : 'normal'; } clearPendingCost(); } else if (rawDeltaCost > 0) { @@ -1021,6 +1266,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu } const sinceMs = hasBufferedLeaseCost ? st.pendingCostSinceMs : nowMs; if (nowMs - sinceMs >= QR_CONSUME_LAG_GRACE_MS) { + qrConfirmAllLeases(st.activeLeases); const consumedPct = qrEstimateModelWeightedPct(st, accModelCosts, accCost, rate); expectedDeltaPct = consumedPct; excessPct = deltaOfficial - expectedDeltaPct; @@ -1055,6 +1301,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu nowMs - st.pendingCostSinceMs >= QR_CONSUME_LAG_GRACE_MS ) { // 4C-2. 无新增花费但已跨过 25s 延迟观察窗且官方仍原地踏步:确认此前缓冲成本已在租约内消化 + qrConfirmAllLeases(st.activeLeases); const consumedPct = qrEstimateModelWeightedPct( st, st.pendingModelCostsUsd, @@ -1104,10 +1351,13 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu accountScope = '', quotaPoolsMap = null, poolCycleStats = null, + runningPoolKeys = null, + hasUnknownRunningPool = false, quotaFetchedAtMs = 0, nowMs = Date.now(), } = {}) { if (!(quotaPoolsMap instanceof Map) || quotaPoolsMap.size === 0) return; + ensureHydrated(); const normalizedAccountScope = String(accountScope || '').trim().toLowerCase(); const scopePrefix = `${String(endpointId || 'local')}::${normalizedAccountScope}`; @@ -1118,9 +1368,52 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const poolLastActivityMs = Number(recent10m?.lastActivityMs) || 0; const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0; const recent10mCostUsd = Number(recent10m?.costUsd) || 0; + const hasRunningLocalSession = Boolean( + hasUnknownRunningPool || + (runningPoolKeys instanceof Set && runningPoolKeys.has(poolKey)) + ); const key5h = `${scopePrefix}::${poolKey}::5h`; + const keyWk = `${scopePrefix}::${poolKey}::weekly`; const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null; + const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; + const reset5hMs = parseIsoMs(poolObj.resetTime); + const resetWkMs = parseIsoMs(poolObj.weeklyResetTime); + const cost5hUsd = pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0; + const costWkUsd = pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0; + const modelCosts5h = pStats?.modelCosts5h || null; + const modelCostsWk = pStats?.modelCostsWeekly || null; + + const prev5hSt = buckets.get(key5h) || null; + const prevWkSt = buckets.get(keyWk) || null; + const peerExtTs5h = Number(prevWkSt?.lastExternalUsageAtMs) || 0; + const peerExtTsWk = Number(prev5hSt?.lastExternalUsageAtMs) || 0; + + // 第 2 层:同一快照下 5h / 周限按已校准费率等比同涨 -> 判定为同一笔家庭组/外部真实消耗而非租约 + const isProportionalExternal = + used5hExact !== null && usedWkExact !== null + ? qrDetectProportionalExternalJump( + prev5hSt, + prevWkSt, + { + officialUsedPct: used5hExact, + resetTimeMs: reset5hMs, + quotaFetchedAtMs, + cycleCostUsd: cost5hUsd, + modelCostsUsd: modelCosts5h, + nowMs, + }, + { + officialUsedPct: usedWkExact, + resetTimeMs: resetWkMs, + quotaFetchedAtMs, + cycleCostUsd: costWkUsd, + modelCostsUsd: modelCostsWk, + nowMs, + } + ) + : false; + const res5h = used5hExact !== null ? observeBucket({ @@ -1128,20 +1421,26 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu poolKey, win: '5h', officialUsedPct: used5hExact, - resetTimeMs: parseIsoMs(poolObj.resetTime), + resetTimeMs: reset5hMs, quotaFetchedAtMs, - cycleCostUsd: pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0, - modelCostsUsd: pStats?.modelCosts5h || null, + cycleCostUsd: cost5hUsd, + modelCostsUsd: modelCosts5h, unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0, poolLastActivityMs, activeSessionCount10m, recent10mCostUsd, + hasRunningLocalSession, + forceExternalJump: isProportionalExternal, + peerLastExternalUsageAtMs: peerExtTs5h, nowMs, }) : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; - const keyWk = `${scopePrefix}::${poolKey}::weekly`; - const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; + const updated5hExtTs = Math.max( + peerExtTsWk, + Number(buckets.get(key5h)?.lastExternalUsageAtMs) || 0 + ); + const resWk = usedWkExact !== null ? observeBucket({ @@ -1149,14 +1448,17 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu poolKey, win: 'weekly', officialUsedPct: usedWkExact, - resetTimeMs: parseIsoMs(poolObj.weeklyResetTime), + resetTimeMs: resetWkMs, quotaFetchedAtMs, - cycleCostUsd: pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0, - modelCostsUsd: pStats?.modelCostsWeekly || null, + cycleCostUsd: costWkUsd, + modelCostsUsd: modelCostsWk, unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0, poolLastActivityMs, activeSessionCount10m, recent10mCostUsd, + hasRunningLocalSession, + forceExternalJump: isProportionalExternal, + peerLastExternalUsageAtMs: updated5hExtTs, nowMs, }) : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; @@ -1167,7 +1469,11 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu poolObj.weeklyReservedPct = resWk.reservedPct; poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount; poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs; - poolObj.rateEstimate = qrBuildPoolRateEstimate(buckets.get(key5h) || null, buckets.get(keyWk) || null); + poolObj.rateEstimate = qrBuildPoolRateEstimate( + buckets.get(key5h) || null, + buckets.get(keyWk) || null, + nowMs + ); } } @@ -1196,6 +1502,13 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu rateSamples: st.rateSamples, reservedPct: out.reservedPct, leases: out.reservedLeaseCount, + ...(st.hasExternalUsage + ? { + hasExternalUsage: true, + externalUsedPct: +(Number(st.externalUsedPct) || 0).toFixed(1), + externalEvents: Number(st.externalEvents) || 0, + } + : {}), ...(Object.keys(byModel).length > 0 ? { byModel } : {}), }); } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index c22f5e0..c9f78f2 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -1729,11 +1729,57 @@ export async function buildTelemetryPayloadInternal( poolObj.cycleWeekly = pStats?.cycleWeekly || createEmptyCycleSummary(); } + const runningPoolKeys = new Set(); + let hasUnknownRunningPool = false; + for (const rootConv of conversations) { + const isMainRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING'; + const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : []; + const runningSubs = rawSubs.filter((s) => s?.status === 'CASCADE_RUN_STATUS_RUNNING'); + if (!isMainRunning && runningSubs.length === 0) continue; + + const recordRunningPool = (cid) => { + const entry = findTrajectoryCacheEntry(cid, cacheStore); + const steps = Array.isArray(entry?.steps) ? entry.steps : []; + const lastStep = steps.length > 0 ? steps[steps.length - 1] : null; + if (!lastStep) { + if (activePoolKey && activePoolKey !== 'Unknown') { + runningPoolKeys.add(activePoolKey); + } else { + hasUnknownRunningPool = true; + } + return; + } + const mInfo = resolveStepModel(lastStep); + const { activePoolKey: pKey } = resolveActivePoolKeyFromStep( + { + modelKey: lastStep.modelKey || mInfo.modelId || 'unknown', + family: mInfo.family, + modelLabel: mInfo.label, + modelShort: mInfo.shortName, + modelUpstream: mInfo.modelId, + }, + quotaPoolsMap + ); + if (pKey && pKey !== 'Unknown') { + runningPoolKeys.add(pKey); + } else { + hasUnknownRunningPool = true; + } + }; + + if (isMainRunning) recordRunningPool(rootConv.cascadeId); + for (const sub of runningSubs) { + recordRunningPool(sub.cascadeId); + } + } + updatePoolQuotaReservationEstimates({ endpointId, accountScope: accountScope || '', quotaPoolsMap, poolCycleStats, + runningPoolKeys, + hasUnknownRunningPool, quotaFetchedAtMs: officialQuotaInfo?.fetchedAtMs || 0, nowMs: Date.now(), }); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 4329142..f2fc1b9 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index b4750c8..2fcbd3a 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -648,7 +648,8 @@ export const QuotaPoolsWidget = defineComponent({ const hasPoolFallback = models.length === 0 && (Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd)); - if (models.length === 0 && !hasPoolFallback) continue; + const ext = est.externalUsage && est.externalUsage.detected ? est.externalUsage : null; + if (models.length === 0 && !hasPoolFallback && !ext) continue; const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; const rows = @@ -664,25 +665,65 @@ export const QuotaPoolsWidget = defineComponent({ samples: item.samples, }) ) - : [ - createRateModelCard({ - name: t('quota.ratePopPoolFallback'), - isMutedName: true, - isFallback: true, - rate5hPctPerUsd: est.rate5hPctPerUsd, - rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, - eqFull5hUsd: est.eqFull5hUsd, - eqFullWeeklyUsd: est.eqFullWeeklyUsd, - samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), - }), - ]; + : hasPoolFallback + ? [ + createRateModelCard({ + name: t('quota.ratePopPoolFallback'), + isMutedName: true, + isFallback: true, + rate5hPctPerUsd: est.rate5hPctPerUsd, + rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, + eqFull5hUsd: est.eqFull5hUsd, + eqFullWeeklyUsd: est.eqFullWeeklyUsd, + samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), + }), + ] + : []; - populatedGroups.push( - h('div', { className: 'quota-rate-pool-group' }, [ - h('div', { className: 'quota-rate-pool-label', text: poolLabel }), - h('div', { className: 'quota-rate-model-list' }, rows), - ]) - ); + const headChildren = [h('div', { className: 'quota-rate-pool-label', text: poolLabel })]; + if (ext?.activeRecently) { + headChildren.push( + h('span', { + className: 'quota-rate-shared-badge', + text: t('quota.ratePopSharedBadge'), + title: t('quota.ratePopSharedBadgeTip'), + }) + ); + } + + const groupChildren = [h('div', { className: 'quota-rate-pool-head' }, headChildren)]; + if (rows.length > 0) { + groupChildren.push(h('div', { className: 'quota-rate-model-list' }, rows)); + } else { + groupChildren.push( + h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') }) + ); + } + if (ext) { + const extParts = []; + if (Number(ext.used5hPct) >= 0.1) { + extParts.push( + t('quota.ratePopExt5h', { pct: formatPctNumber(Number(ext.used5hPct)) }) + ); + } + if (Number(ext.usedWeeklyPct) >= 0.1) { + extParts.push( + t('quota.ratePopExtWk', { pct: formatPctNumber(Number(ext.usedWeeklyPct)) }) + ); + } + const extText = + extParts.length > 0 + ? t('quota.ratePopExternalDetail', { detail: extParts.join(' · ') }) + : t('quota.ratePopExternalBaseline'); + groupChildren.push( + h('div', { + className: `quota-rate-ext-banner${ext.activeRecently ? ' is-active' : ''}`, + text: extText, + }) + ); + } + + populatedGroups.push(h('div', { className: 'quota-rate-pool-group' }, groupChildren)); } if (populatedGroups.length === 0) { diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 88b637b..8612394 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -208,6 +208,12 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopSamples': '{n} samples', 'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.', 'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.', + 'quota.ratePopSharedBadge': 'Shared active', + 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', + 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', + 'quota.ratePopExternalBaseline': 'Family group / other-device usage detected this cycle; reservations & rates calibrate on local steps only', + 'quota.ratePopExt5h': '5h {pct}%', + 'quota.ratePopExtWk': 'Weekly {pct}%', // Live Activity Widget 'live.currentSession': 'Current Session', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 71f79b1..e2481ae 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -208,6 +208,12 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopSamples': '{n} 样本', 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', + 'quota.ratePopSharedBadge': '共享活跃', + 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', + 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', + 'quota.ratePopExternalBaseline': '检测到本周期存在家庭组 / 其他设备消耗,预占和费率仅按本机实测校准', + 'quota.ratePopExt5h': '5h {pct}%', + 'quota.ratePopExtWk': '周限 {pct}%', // Live Activity Widget 'live.currentSession': '当前会话', diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index cb2e381..929c862 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -738,12 +738,51 @@ border-top: 1px solid var(--border-hairline); } +.quota-rate-pool-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + .quota-rate-pool-label { font-size: var(--fs-2xs); font-weight: 600; color: var(--text-muted); } +.quota-rate-shared-badge { + display: inline-flex; + align-items: center; + padding: 1px 6px; + border-radius: 999px; + font-size: var(--fs-2xs); + font-weight: 600; + line-height: 1.4; + color: var(--metric-warn); + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); + border: 1px solid color-mix(in srgb, var(--metric-warn) 28%, transparent); + white-space: nowrap; + flex-shrink: 0; +} + +.quota-rate-ext-banner { + margin-top: 2px; + padding: 5px 8px; + border-radius: 6px; + font-size: var(--fs-2xs); + line-height: 1.45; + color: var(--text-secondary); + background: color-mix(in srgb, var(--metric-warn) 8%, transparent); + border: 1px solid color-mix(in srgb, var(--metric-warn) 22%, var(--border-hairline)); +} + +.quota-rate-ext-banner.is-active { + color: var(--text-primary); + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); + border-color: color-mix(in srgb, var(--metric-warn) 34%, var(--border-hairline)); +} + .quota-rate-model-list { display: flex; flex-direction: column; diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 9a512fe..537a36d 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2456,12 +2456,51 @@ html[data-standalone="true"] .app-shell { border-top: 1px solid var(--border-hairline); } +.quota-rate-pool-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + .quota-rate-pool-label { font-size: var(--fs-2xs); font-weight: 600; color: var(--text-muted); } +.quota-rate-shared-badge { + display: inline-flex; + align-items: center; + padding: 1px 6px; + border-radius: 999px; + font-size: var(--fs-2xs); + font-weight: 600; + line-height: 1.4; + color: var(--metric-warn); + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); + border: 1px solid color-mix(in srgb, var(--metric-warn) 28%, transparent); + white-space: nowrap; + flex-shrink: 0; +} + +.quota-rate-ext-banner { + margin-top: 2px; + padding: 5px 8px; + border-radius: 6px; + font-size: var(--fs-2xs); + line-height: 1.45; + color: var(--text-secondary); + background: color-mix(in srgb, var(--metric-warn) 8%, transparent); + border: 1px solid color-mix(in srgb, var(--metric-warn) 22%, var(--border-hairline)); +} + +.quota-rate-ext-banner.is-active { + color: var(--text-primary); + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); + border-color: color-mix(in srgb, var(--metric-warn) 34%, var(--border-hairline)); +} + .quota-rate-model-list { display: flex; flex-direction: column; diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs index 5c122f3..7d5e099 100644 --- a/sidecars/panel/test/quota-reservation.test.mjs +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -783,11 +783,123 @@ test('experimentalQuotaReservation setting defaults true and round-trips through assert.equal(disabledParsed.patch.experimentalQuotaReservation, false); }); -test('backendHarness buildTelemetry populates reservedPct on pools across official quota jumps', async () => { +test('backendHarness buildTelemetry populates reservedPct when local session is running and flags external_usage when idle', async () => { + // 1. Idle machine (no local running conversation / no local cost): external jump must be classified as external_usage (0% reserved) + let nowIdle = T0; + const hIdle = backendHarness({ + clock: () => nowIdle, + userStatus: { email: 'family-idle@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 idleP1 = await hIdle.buildTelemetryPayloadInternal(null, true); + const idleG1 = idleP1.quotas.pools.find((p) => p.poolKey === 'Gemini'); + assert.equal(idleP1.settings.experimentalQuotaReservation, true); + assert.equal(idleG1.reservedPct, 0); + assert.equal(idleG1.weeklyReservedPct, 0); + + nowIdle += 20_000; + hIdle.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 idleP2 = await hIdle.buildTelemetryPayloadInternal(null, true); + const idleG2 = idleP2.quotas.pools.find((p) => p.poolKey === 'Gemini'); + assert.equal(idleG2.reservedPct, 0, 'idle external 5h jump must not create fake reservation'); + assert.equal(idleG2.weeklyReservedPct, 0, 'idle external weekly jump must not create fake reservation'); + assert.equal(idleG2.rateEstimate?.externalUsage?.detected, true); + assert.equal(idleG2.rateEstimate?.externalUsage?.activeRecently, true); + assert.equal(idleG2.rateEstimate?.externalUsage?.used5hPct, 1.0); + assert.equal(idleG2.rateEstimate?.externalUsage?.usedWeeklyPct, 0.5); + + const idleLogRes = await hIdle.dispatchBridgeApiRequest('/api/quota-reservation/log', 'GET'); + assert.equal(idleLogRes.status, 200); + const idleLogJson = JSON.parse(idleLogRes.body); + assert.ok( + idleLogJson.events.some((e) => e.pool === 'Gemini' && e.win === '5h' && e.event === 'external_usage'), + 'idle 5h jump logged as external_usage' + ); + + // 2. Active local running Gemini conversation: same quota jump cleanly triggers local reservation leases let now = T0; const h = backendHarness({ clock: () => now, userStatus: { email: 'tester@example.com', userTier: { name: 'Google AI Ultra' } }, + summaries: { + 'conv-local-gem': { + summary: 'Local Gemini Session', + status: 'CASCADE_RUN_STATUS_RUNNING', + stepCount: 1, + createdTime: new Date(T0 - 15_000).toISOString(), + lastModifiedTime: new Date(T0).toISOString(), + }, + }, + trajectories: { + 'conv-local-gem': { + trajectory: { + generatorMetadata: [ + { + stepIndices: [0], + chatModel: { + model: 'gemini-4-neon-xhigh', + usage: { + inputTokens: 10000, + cacheReadTokens: 0, + outputTokens: 500, + }, + }, + }, + ], + steps: [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + metadata: { + createdAt: new Date(T0).toISOString(), + generatorModel: 'gemini-4-neon-xhigh', + }, + }, + ], + }, + }, + }, quotaSummary: { groups: [ { @@ -813,11 +925,9 @@ test('backendHarness buildTelemetry populates reservedPct on pools across offici const p1 = await h.buildTelemetryPayloadInternal(null, true); const g1 = p1.quotas.pools.find((p) => p.poolKey === 'Gemini'); - assert.equal(p1.settings.experimentalQuotaReservation, true); 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: [ @@ -1490,3 +1600,383 @@ test('QuotaPoolsWidget renders circle-? hover popover for account-isolated model globalThis.window = origWindow; } }); + +test('quota-reservation: 3-layer family-group defense blocks idle/proportional jumps, promotes corroborated tentative leases, and evicts unbacked ghost leases', () => { + const tracker = createQuotaReservationTracker(); + + const makePools = (used5h, usedWk) => + new Map([ + [ + 'Gemini', + { + poolKey: 'Gemini', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - used5h / 100, + usedPct: used5h, + resetTime: new Date(RESET_5H).toISOString(), + weeklyRemainingFraction: 1 - usedWk / 100, + weeklyUsedPct: usedWk, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + + const makeStats = (cost5h, costWk, lastActivityMs, sess10m = 1) => + new Map([ + [ + 'Gemini', + { + cycle5h: { costUsd: cost5h, unpricedCalls: 0 }, + cycleWeekly: { costUsd: costWk, unpricedCalls: 0 }, + exactCost5hUsd: cost5h, + exactCostWeeklyUsd: costWk, + recent10m: { lastActivityMs, activeSessionCount: sess10m, costUsd: sess10m > 0 ? 0.2 : 0 }, + }, + ], + ]); + + // 1. Cold-start baseline where family already spent 18% (5h) & 30% (weekly) while local spent $0: + // must mark hasExternalUsage without poisoning ratePctPerUsd + let ts = T0; + let u5 = 18.0; + let uw = 30.0; + let c5 = 0; + let cw = 0; + const pBase = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'family@example.com', + quotaPoolsMap: pBase, + poolCycleStats: makeStats(c5, cw, 0, 0), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pBase.get('Gemini').reservedPct, 0); + assert.equal(pBase.get('Gemini').rateEstimate?.externalUsage?.detected, true); + assert.equal(pBase.get('Gemini').rateEstimate?.externalUsage?.activeRecently, false); + const st5h = tracker._buckets.get('local::family@example.com::Gemini::5h'); + assert.equal(st5h.ratePctPerUsd, null, 'family cold-start must not fabricate inflated safeUsed/safeCost rate'); + + // 2. Calibrate real local burn rates cleanly via 3 single-step turns: 5h = 2.0 %/$, weekly = 0.5 %/$ + for (let i = 0; i < 3; i += 1) { + ts += 20_000; + c5 = +(c5 + 0.1).toFixed(4); + cw = +(cw + 0.1).toFixed(4); + u5 = +(u5 + 0.2).toFixed(4); + uw = +(uw + 0.05).toFixed(4); + const pCal = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'family@example.com', + quotaPoolsMap: pCal, + poolCycleStats: makeStats(c5, cw, ts, 1), + runningPoolKeys: new Set(['Gemini']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pCal.get('Gemini').reservedPct, 0); + } + assert.ok(Math.abs(st5h.ratePctPerUsd - 2.0) < 0.05); + + // 3. Layer 1 (Local-Activity Gate): local goes idle for 5 min (or uses Claude only) while family burns +1.2% 5h & +0.3% weekly + const lastLocalAct = ts; + ts += 5 * 60 * 1000; + u5 = +(u5 + 1.2).toFixed(4); + uw = +(uw + 0.3).toFixed(4); + const pIdleExt = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'family@example.com', + quotaPoolsMap: pIdleExt, + poolCycleStats: makeStats(c5, cw, lastLocalAct, 0), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pIdleExt.get('Gemini').reservedPct, 0, 'idle Gemini jump while running Claude is external_usage'); + assert.equal(pIdleExt.get('Gemini').weeklyReservedPct, 0); + assert.equal(pIdleExt.get('Gemini').rateEstimate?.externalUsage?.activeRecently, true); + assert.equal(pIdleExt.get('Gemini').rateEstimate?.externalUsage?.used5hPct, 1.2); + assert.equal(pIdleExt.get('Gemini').rateEstimate?.externalUsage?.usedWeeklyPct, 0.3); + + // 4. Layer 2 (5h/weekly proportional co-movement): local IS active ($0.05 step -> exp 0.10% / 0.025%), + // AND family member simultaneously spends $0.60 (+1.20% 5h, +0.30% weekly) on the same snapshot + ts += 30_000; + c5 = +(c5 + 0.05).toFixed(4); + cw = +(cw + 0.05).toFixed(4); + u5 = +(u5 + 1.3).toFixed(4); + uw = +(uw + 0.325).toFixed(4); + const pCoMove = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'family@example.com', + quotaPoolsMap: pCoMove, + poolCycleStats: makeStats(c5, cw, ts, 1), + runningPoolKeys: new Set(['Gemini']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pCoMove.get('Gemini').reservedPct, 0, 'proportional 5h+weekly jump blocked as external_usage'); + assert.equal(pCoMove.get('Gemini').weeklyReservedPct, 0); + assert.equal(pCoMove.get('Gemini').rateEstimate?.externalUsage?.used5hPct, 2.4); + + // 5. Layer 3a (Shared-active tentative lease -> corroborated promotion on consume): + // External usage was seen 30s ago -> a genuine staggered 5h +1.0% lease stays hidden (tentative) first + ts += 20_000; + c5 = +(c5 + 0.05).toFixed(4); + cw = +(cw + 0.05).toFixed(4); + u5 = +(u5 + 1.1).toFixed(4); // excess 1.0% on 5h only + uw = +(uw + 0.025).toFixed(4); // normal 1:1 on weekly + const pTent = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'family@example.com', + quotaPoolsMap: pTent, + poolCycleStats: makeStats(c5, cw, ts, 1), + runningPoolKeys: new Set(['Gemini']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pTent.get('Gemini').reservedPct, 0, 'shared-active new lease stays tentative/hidden until corroborated'); + + // Next local spend ($0.15 -> exp 0.30%) is absorbed with flat official (consume past lag grace) -> promotes tentative lease! + ts += 15_000; + c5 = +(c5 + 0.15).toFixed(4); + cw = +(cw + 0.15).toFixed(4); + uw = +(uw + 0.075).toFixed(4); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'family@example.com', + quotaPoolsMap: makePools(u5, uw), + poolCycleStats: makeStats(c5, cw, ts, 1), + runningPoolKeys: new Set(['Gemini']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + ts += QR_CONSUME_LAG_GRACE_MS + 1_000; + const pPromoted = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'family@example.com', + quotaPoolsMap: pPromoted, + poolCycleStats: makeStats(c5, cw, ts, 1), + runningPoolKeys: new Set(['Gemini']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pPromoted.get('Gemini').reservedPct, 0.7, 'corroborated tentative lease promotes cleanly (1.0% - 0.3% = 0.7%)'); + + // 6. Layer 3b (Unbacked single-session ghost lease fast eviction on a fresh solo-looking account): + const soloTracker = createQuotaReservationTracker(); + const sKey = 'local::overlap@example.com::Gemini::5h'; + let stTs = T0; + let su = 10.0; + let sc = 5.0; // calibrated 2.0 %/$ + soloTracker.observeBucket({ + bucketKey: sKey, + officialUsedPct: su, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: stTs, + cycleCostUsd: sc, + poolLastActivityMs: stTs, + activeSessionCount10m: 1, + nowMs: stTs, + }); + // Unseen family burst overlaps single local turn -> creates unconfirmed +0.8% lease + stTs += 15_000; + sc = +(sc + 0.05).toFixed(4); + su = +(su + 0.9).toFixed(4); + const rGhost = soloTracker.observeBucket({ + bucketKey: sKey, + officialUsedPct: su, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: stTs, + cycleCostUsd: sc, + poolLastActivityMs: stTs, + activeSessionCount10m: 1, + nowMs: stTs, + }); + assert.equal(rGhost.reservedPct, 0.8); + + // 3 consecutive normal 1:1 local steps ($0.05 -> +0.10% each, total 0.30% >= 0.25%) with zero absorption -> evicts ghost lease! + let rFinal = null; + for (let i = 0; i < 3; i += 1) { + stTs += 20_000; + sc = +(sc + 0.05).toFixed(4); + su = +(su + 0.1).toFixed(4); + rFinal = soloTracker.observeBucket({ + bucketKey: sKey, + officialUsedPct: su, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: stTs, + cycleCostUsd: sc, + poolLastActivityMs: stTs, + activeSessionCount10m: 1, + nowMs: stTs, + }); + } + assert.equal(rFinal.reservedPct, 0, 'unbacked single-session ghost lease fast-evicted after 3 unabsorbed 1:1 steps'); + assert.equal(soloTracker._buckets.get(sKey).hasExternalUsage, true); + assert.ok( + soloTracker.getLogSnapshot().events.some((e) => e.event === 'lease_rejected'), + 'eviction recorded as lease_rejected' + ); +}); + +test('QuotaPoolsWidget ? popover renders family-group/external usage banner and shared-active badge cleanly', async () => { + const { document } = createMockDom(); + const origDocument = globalThis.document; + const origWindow = globalThis.window; + 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/' }, + }; + + try { + const [{ setI18nLanguage }, { QuotaPoolsWidget }] = await Promise.all([ + import('../src/i18n/index.js'), + import('../src/components/widgets/QuotaPoolsWidget.js'), + ]); + setI18nLanguage('zh-CN'); + + const widget = QuotaPoolsWidget(); + const popover = widget.refs.ratePopoverEl; + + // 1. Solo account without external usage: no shared badge or external banner + widget.refs.update({ + data: { + account: { email: 'solo@example.com', tierName: 'Google AI Ultra' }, + quotas: { + pools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + usedPct: 12, + remainingPct: 88, + rateEstimate: { + rate5hPctPerUsd: 2, + rateWeeklyPctPerUsd: 0.5, + eqFull5hUsd: 50, + eqFullWeeklyUsd: 200, + samples5h: 5, + samplesWeekly: 5, + models: [], + }, + }, + ], + weekly: { isOfficial: true }, + }, + }, + minuteTick: 1, + }); + assert.equal(popover.querySelector('.quota-rate-shared-badge'), null); + assert.equal(popover.querySelector('.quota-rate-ext-banner'), null); + + // 2. Family-group active external usage with concrete 5h + weekly excluded % + const familyData = { + account: { email: 'family@example.com', tierName: 'Google AI Ultra' }, + quotas: { + pools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + usedPct: 24, + remainingPct: 76, + weeklyUsedPct: 35, + weeklyRemainingPct: 65, + rateEstimate: { + rate5hPctPerUsd: 2, + rateWeeklyPctPerUsd: 0.5, + eqFull5hUsd: 50, + eqFullWeeklyUsd: 200, + samples5h: 6, + samplesWeekly: 6, + models: [], + externalUsage: { + detected: true, + activeRecently: true, + used5hPct: 2.4, + usedWeeklyPct: 0.6, + events: 3, + lastSeenAtMs: Date.now(), + }, + }, + }, + ], + weekly: { isOfficial: true }, + }, + }; + widget.refs.update({ data: familyData, minuteTick: 2 }); + const sharedBadge = popover.querySelector('.quota-rate-shared-badge'); + const extBanner = popover.querySelector('.quota-rate-ext-banner'); + assert.ok(sharedBadge, 'shared-active badge rendered'); + assert.equal(sharedBadge.textContent, '共享活跃'); + assert.ok(extBanner, 'external usage banner rendered'); + assert.equal(extBanner.classList.contains('is-active'), true); + assert.match(extBanner.textContent, /家庭组 \/ 其他设备消耗/); + assert.match(extBanner.textContent, /5h 2\.4% · 周限 0\.6%/); + assert.equal(extBanner.textContent.includes('与'), false); + + // 3. Baseline-only external detection before any model samples exist + widget.refs.update({ + data: { + account: { email: 'family@example.com', tierName: 'Google AI Ultra' }, + quotas: { + pools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + usedPct: 18, + remainingPct: 82, + rateEstimate: { + rate5hPctPerUsd: null, + rateWeeklyPctPerUsd: null, + eqFull5hUsd: null, + eqFullWeeklyUsd: null, + samples5h: 0, + samplesWeekly: 0, + models: [], + externalUsage: { + detected: true, + activeRecently: false, + used5hPct: 0, + usedWeeklyPct: 0, + events: 0, + lastSeenAtMs: null, + }, + }, + }, + ], + weekly: { isOfficial: true }, + }, + }, + minuteTick: 3, + }); + assert.equal(popover.querySelector('.quota-rate-shared-badge'), null); + const baseBanner = popover.querySelector('.quota-rate-ext-banner'); + assert.ok(baseBanner); + assert.match(baseBanner.textContent, /仅按本机实测校准/); + + // 4. English locale rendering + setI18nLanguage('en-US'); + widget.refs.update({ data: familyData, minuteTick: 4 }); + assert.equal(popover.querySelector('.quota-rate-shared-badge').textContent, 'Shared active'); + assert.match( + popover.querySelector('.quota-rate-ext-banner').textContent, + /Family group \/ other-device usage detected.*5h 2\.4% · Weekly 0\.6%/ + ); + + widget.destroy(); + } finally { + globalThis.document = origDocument; + globalThis.window = origWindow; + } +}); From f7ed2e0aa8e9f44233a84ca4e2baaea6dedb674f Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 01:52:35 +0900 Subject: [PATCH 02/30] fix(panel): refine context risk warning layout and prevent settings header status overlap - Collapse locked context controls out of flow so the initial risk notice fits cleanly without extra vertical void or blur bleed, and soften the Modern UI notice and danger-confirm button surfaces - Lock settings panel header titles to flex: 0 0 auto and single-line truncate long status feedback (such as exported JSON paths) with hover tooltips --- sidecars/panel/app.js | 14 +++-- sidecars/panel/index.html | 4 +- sidecars/panel/src/styles/modern-ui.css | 15 +++++ sidecars/panel/src/styles/views-settings.css | 40 ++++++++++---- .../src/views/settings/SettingsOtherTab.js | 14 +++-- sidecars/panel/styles.css | 55 +++++++++++++++---- 6 files changed, 108 insertions(+), 34 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index ab09113..832878d 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -27820,8 +27820,7 @@ const SettingsOtherTab = defineComponent({ text: '', }); const maintStatusText = h('span', { - className: 'text-muted', - style: 'font-size: var(--fs-md);', + className: 'text-muted settings-panel-status', text: '', }); @@ -27859,10 +27858,12 @@ const SettingsOtherTab = defineComponent({ maintTimer = null; } patchText(maintStatusText, text); + patchAttr(maintStatusText, 'title', text || null); if (text && autoClearMs > 0) { maintTimer = setTimeout(() => { maintTimer = null; patchText(maintStatusText, ''); + patchAttr(maintStatusText, 'title', null); }, autoClearMs); } } @@ -28041,7 +28042,10 @@ const SettingsOtherTab = defineComponent({ const ctxModelLabel = h('span', { className: 'form-label' }); const ctxWindowLabel = h('span', { className: 'form-label' }); const ctxHint = h('span', { className: 'settings-hint-text' }); - const ctxStatus = h('span', { className: 'text-muted', role: 'status' }); + const ctxStatus = h('span', { + className: 'text-muted settings-panel-status', + role: 'status', + }); const ctxModelSelect = CustomSelect({ className: 'settings-context-model', searchable: true, @@ -28331,7 +28335,7 @@ const SettingsOtherTab = defineComponent({ } const baselinePanel = h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [ + h('div', { className: 'panel-header settings-panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('layers', { size: 13 }), baselineTitleEl, @@ -28548,7 +28552,7 @@ const SettingsOtherTab = defineComponent({ ]); const maintPanel = h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [ + h('div', { className: 'panel-header settings-panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('refresh', { size: 13 }), maintTitleEl, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index f2fc1b9..d0604a3 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index d9ec68d..db02513 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -668,6 +668,21 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } +[data-modern-ui="true"] .ctx-risk-mask { + border-radius: var(--radius-sm); + background: color-mix(in srgb, var(--metric-warn) 8%, transparent); +} + +[data-modern-ui="true"] .btn-danger-confirm { + border: none !important; + background: color-mix(in srgb, var(--metric-danger) 14%, transparent) !important; +} + +[data-modern-ui="true"] .btn-danger-confirm:hover:not(:disabled) { + border: none !important; + background: color-mix(in srgb, var(--metric-danger) 22%, transparent) !important; +} + [data-modern-ui="true"] .number-input, [data-modern-ui="true"] .dt-trigger, [data-modern-ui="true"] .dt-mini-step, diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index ab969fd..251592f 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -733,8 +733,11 @@ } .ctx-controls-body.is-locked { - filter: blur(4px); - opacity: 0.24; + height: 0; + overflow: hidden; + opacity: 0; + visibility: hidden; + filter: none; pointer-events: none; user-select: none; } @@ -753,12 +756,12 @@ display: flex; flex-direction: column; align-items: flex-start; - justify-content: center; - gap: var(--space-2); + justify-content: flex-start; + gap: 8px; padding: var(--space-3) var(--space-4); - border-radius: var(--radius-xs); - border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); - background: color-mix(in srgb, var(--surface-panel) 88%, var(--metric-warn) 7%); + border-radius: var(--radius-sm); + border: 1px solid color-mix(in srgb, var(--metric-warn) 36%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 93%, var(--metric-warn) 7%); } .ctx-risk-mask[hidden] { @@ -786,14 +789,29 @@ .ctx-risk-desc { margin: 0; font-size: var(--fs-sm); - line-height: 1.5; - color: var(--text-primary); + line-height: 1.55; + color: var(--text-secondary); } .ctx-risk-accept-btn { margin-top: 2px; - min-height: calc(26px * var(--ui-font-scale, 1)); - padding: 2px var(--space-3); + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 4px var(--space-3); + font-size: var(--fs-md); +} + +/* 设置页卡片头部右侧状态提示(长路径自动单行省略,防止把左侧标题挤成 0px 造成文字重叠) */ +.settings-panel-header > .panel-title { + flex: 0 0 auto; +} + +.settings-panel-status { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + text-align: right; font-size: var(--fs-md); } diff --git a/sidecars/panel/src/views/settings/SettingsOtherTab.js b/sidecars/panel/src/views/settings/SettingsOtherTab.js index f2ca719..272293b 100644 --- a/sidecars/panel/src/views/settings/SettingsOtherTab.js +++ b/sidecars/panel/src/views/settings/SettingsOtherTab.js @@ -100,8 +100,7 @@ export const SettingsOtherTab = defineComponent({ text: '', }); const maintStatusText = h('span', { - className: 'text-muted', - style: 'font-size: var(--fs-md);', + className: 'text-muted settings-panel-status', text: '', }); @@ -139,10 +138,12 @@ export const SettingsOtherTab = defineComponent({ maintTimer = null; } patchText(maintStatusText, text); + patchAttr(maintStatusText, 'title', text || null); if (text && autoClearMs > 0) { maintTimer = setTimeout(() => { maintTimer = null; patchText(maintStatusText, ''); + patchAttr(maintStatusText, 'title', null); }, autoClearMs); } } @@ -321,7 +322,10 @@ export const SettingsOtherTab = defineComponent({ const ctxModelLabel = h('span', { className: 'form-label' }); const ctxWindowLabel = h('span', { className: 'form-label' }); const ctxHint = h('span', { className: 'settings-hint-text' }); - const ctxStatus = h('span', { className: 'text-muted', role: 'status' }); + const ctxStatus = h('span', { + className: 'text-muted settings-panel-status', + role: 'status', + }); const ctxModelSelect = CustomSelect({ className: 'settings-context-model', searchable: true, @@ -611,7 +615,7 @@ export const SettingsOtherTab = defineComponent({ } const baselinePanel = h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [ + h('div', { className: 'panel-header settings-panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('layers', { size: 13 }), baselineTitleEl, @@ -828,7 +832,7 @@ export const SettingsOtherTab = defineComponent({ ]); const maintPanel = h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [ + h('div', { className: 'panel-header settings-panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('refresh', { size: 13 }), maintTitleEl, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 537a36d..beb31e7 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -6191,8 +6191,11 @@ html[data-standalone="true"] .app-shell { } .ctx-controls-body.is-locked { - filter: blur(4px); - opacity: 0.24; + height: 0; + overflow: hidden; + opacity: 0; + visibility: hidden; + filter: none; pointer-events: none; user-select: none; } @@ -6211,12 +6214,12 @@ html[data-standalone="true"] .app-shell { display: flex; flex-direction: column; align-items: flex-start; - justify-content: center; - gap: var(--space-2); + justify-content: flex-start; + gap: 8px; padding: var(--space-3) var(--space-4); - border-radius: var(--radius-xs); - border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); - background: color-mix(in srgb, var(--surface-panel) 88%, var(--metric-warn) 7%); + border-radius: var(--radius-sm); + border: 1px solid color-mix(in srgb, var(--metric-warn) 36%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 93%, var(--metric-warn) 7%); } .ctx-risk-mask[hidden] { @@ -6244,14 +6247,29 @@ html[data-standalone="true"] .app-shell { .ctx-risk-desc { margin: 0; font-size: var(--fs-sm); - line-height: 1.5; - color: var(--text-primary); + line-height: 1.55; + color: var(--text-secondary); } .ctx-risk-accept-btn { margin-top: 2px; - min-height: calc(26px * var(--ui-font-scale, 1)); - padding: 2px var(--space-3); + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 4px var(--space-3); + font-size: var(--fs-md); +} + +/* 设置页卡片头部右侧状态提示(长路径自动单行省略,防止把左侧标题挤成 0px 造成文字重叠) */ +.settings-panel-header > .panel-title { + flex: 0 0 auto; +} + +.settings-panel-status { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + text-align: right; font-size: var(--fs-md); } @@ -8457,6 +8475,21 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } +[data-modern-ui="true"] .ctx-risk-mask { + border-radius: var(--radius-sm); + background: color-mix(in srgb, var(--metric-warn) 8%, transparent); +} + +[data-modern-ui="true"] .btn-danger-confirm { + border: none !important; + background: color-mix(in srgb, var(--metric-danger) 14%, transparent) !important; +} + +[data-modern-ui="true"] .btn-danger-confirm:hover:not(:disabled) { + border: none !important; + background: color-mix(in srgb, var(--metric-danger) 22%, transparent) !important; +} + [data-modern-ui="true"] .number-input, [data-modern-ui="true"] .dt-trigger, [data-modern-ui="true"] .dt-mini-step, From b76a5889cabca79fcd4a09f111fa981f2cab533a Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 02:12:28 +0900 Subject: [PATCH 03/30] fix(panel): eliminate virtual-scroll column jitter in step table - Lock measured thead column widths with table-layout: fixed once virtualized rows mount, preserving horizontal scroll min-width on narrow viewports and unlocking automatically on layout, sort, locale, font-scale, or sizer changes - Fix buildColumnSizerSpec tokPerSec scoring bug and improve proportional width estimation across badges, models, timing, pending pricing, and bold first-column rows - Enable tabular-nums on .data-table cells to prevent sub-pixel width drift between digits --- sidecars/panel/app.js | 183 +++++++++++++---- sidecars/panel/index.html | 4 +- .../src/components/widgets/StepTableWidget.js | 185 ++++++++++++++---- sidecars/panel/src/styles/views-tables.css | 17 ++ sidecars/panel/styles.css | 17 ++ 5 files changed, 336 insertions(+), 70 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 832878d..4fcac35 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -21642,24 +21642,48 @@ const SIZER_ROW_KEY = '__vsizer__'; const SPACER_TOP_KEY = '__vspacer_top__'; const SPACER_BOTTOM_KEY = '__vspacer_bottom__'; -function estTokenChars(val) { - const n = Math.max(0, Number(val || 0)); - if (n >= 1_000_000) return n >= 10_000_000 ? 6 : 5; - if (n >= 100_000) return 6; - if (n >= 10_000) return 5; - if (n >= 1_000) return 4; - if (n >= 100) return 3; - if (n >= 10) return 2; - return 1; +function estProportionalTextWidth(text) { + const s = String(text || ''); + let w = 0; + for (let i = 0; i < s.length; i++) { + const code = s.charCodeAt(i); + if (code > 0x2e7f) { + w += 1.8; + } else if ( + code === 105 || code === 108 || code === 73 || code === 116 || code === 102 || + code === 114 || code === 46 || code === 44 || code === 58 || code === 59 || + code === 45 || code === 47 || code === 32 + ) { + w += 0.55; + } else if ( + code === 109 || code === 119 || code === 77 || code === 87 || code === 71 || + code === 79 || code === 81 || code === 67 + ) { + w += 1.32; + } else { + w += 1.0; + } + } + return w; } -function estCostChars(val) { - const n = Number(val); - if (!Number.isFinite(n) || n <= 0) return 1; - if (n >= 100) return 7; - if (n >= 10) return 6; - if (n >= 0.01) return 5; - return 7; +function estTokenChars(val) { + const n = Math.max(0, Number(val || 0)); + if (n >= 1_000_000) return n >= 10_000_000 ? 6.4 : 5.6; + if (n >= 100_000) return 6.0; + if (n >= 10_000) return 5.0; + if (n >= 1_000) return 4.1; + if (n >= 100) return 3.0; + if (n >= 10) return 2.0; + return 1.0; +} + +function estCostWidth(st) { + const c = st?.costUsd; + if (c == null || !Number.isFinite(Number(c))) { + return st?.isPricingPending ? estProportionalTextWidth(t('fmt.pricingPending')) : 1; + } + return estProportionalTextWidth(formatUsd(Number(c))); } function estSegmentChars(seg, st) { @@ -21755,19 +21779,27 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { let bestCostObj = firstStep; let bestBadgeText = ''; + let bestBadgeWidth = -1; let bestBadgeClass = ''; + let hasBoldFirstCol = false; const badgeCandidates = cellCtx?.showAgentBadge ? new Set() : null; for (let i = 0; i < tableSteps.length; i++) { const st = tableSteps[i]; if (!st || typeof st !== 'object') continue; + if (!hasBoldFirstCol && (isCompactionStepItem(st) || Number(st?.anomaly?.count) > 0)) { + hasBoldFirstCol = true; + } + if (badgeCandidates) { const bKey = `${st.agentKind || ''}|${st.isSubagent ? 1 : 0}|${st.isSideQuestion ? 1 : 0}|${st.agentOrdinal || 0}|${st.sideIndex || 0}|${st.agentIndex || 0}|${st.agentBadge || ''}`; if (!badgeCandidates.has(bKey)) { badgeCandidates.add(bKey); const text = resolveBadgeTextForStep(st); - if (text.length > bestBadgeText.length) { + const bw = estProportionalTextWidth(text); + if (bw > bestBadgeWidth) { + bestBadgeWidth = bw; bestBadgeText = text; bestBadgeClass = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); } @@ -21811,17 +21843,23 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needTtft) { const v = Number(st.ttftSec); - if (Number.isFinite(v) && v > maxTtftVal) { - maxTtftVal = v; - bestTtftObj = st; + if (Number.isFinite(v) && v >= 0) { + const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v; + if (score > maxTtftVal) { + maxTtftVal = score; + bestTtftObj = st; + } } } if (needDuration) { const v = Number(st.totalDurationSec ?? st.streamDurationSec); - if (Number.isFinite(v) && v > maxDurVal) { - maxDurVal = v; - bestDurObj = st; + if (Number.isFinite(v) && v >= 0) { + const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v; + if (score > maxDurVal) { + maxDurVal = score; + bestDurObj = st; + } } } @@ -21907,7 +21945,7 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needCost) { const c = Number(st.costUsd); - const score = estCostChars(c) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0); + const score = estCostWidth(st) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0); if (score > bestCostScore) { bestCostScore = score; bestCostObj = st; @@ -21918,13 +21956,13 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needStep) colSteps.step = bestStepObj; if (needTime) colSteps.time = bestTimeObj || firstStep; if (needModel && modelCandidates) { - let bestModelLen = -1; + let bestModelWidth = -1; let bestModelObj = firstStep; for (const cand of modelCandidates.values()) { const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); - const len = disp.baseText?.length || 0; - if (len > bestModelLen) { - bestModelLen = len; + const w = estProportionalTextWidth(disp.baseText || ''); + if (w > bestModelWidth) { + bestModelWidth = w; bestModelObj = cand; } } @@ -21932,19 +21970,20 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { } if (needTps) { let longestReasonKey = null; - let longestReasonLen = 0; + let longestReasonWidth = 0; if (reasonCandidates) { for (const rk of reasonCandidates) { const txt = speedReasonText(rk); - if (txt && txt.length > longestReasonLen) { - longestReasonLen = txt.length; + const w = txt ? estProportionalTextWidth(txt) : 0; + if (w > longestReasonWidth) { + longestReasonWidth = w; longestReasonKey = rk; } } } colSteps.tps = { ...(maxTpsObj || firstStep), - tokPerSec: maxTpsVal > 0 ? maxTpsVal : firstStep.tokPerSec, + tokPerSec: maxTpsObj ? maxTpsObj.tokPerSec : firstStep.tokPerSec, selectedSpeedReason: longestReasonKey, }; } @@ -21967,7 +22006,8 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { colSteps, badgeText: bestBadgeText, badgeClass: bestBadgeClass, - sig: `sizer:${bestBadgeText}:${sigParts.join('|')}`, + hasBoldFirstCol, + sig: `sizer:${bestBadgeText}:${hasBoldFirstCol ? 1 : 0}:${sigParts.join('|')}`, }; } @@ -22235,8 +22275,66 @@ const StepTableWidget = defineComponent({ let lastFontScale = 1; let calibratedSingleRowH = 0; let calibratedReasonRowH = 0; + let lockedColKey = ''; + let lockedPaneWidth = 0; const rowPool = []; + function computeColLockKey(ds) { + if (!ds?.isVirtualized) return ''; + return `${ds.locale}:${ds.colOrderSig}:${lastFontScale}:${ds.showAgentBadge ? 1 : 0}:${ds.railActive ? 1 : 0}:${ds.sortKey || ''}:${ds.sortDir || ''}:${ds.sizerSpec?.sig || ''}`; + } + + function unlockColumnWidths() { + lockedColKey = ''; + lockedPaneWidth = 0; + patchClasses(stepsTableEl, { 'is-cols-locked': false }); + if (stepsTableEl.style) { + stepsTableEl.style.minWidth = ''; + } + const ths = stepsTheadRow.children || []; + for (let i = 0; i < ths.length; i++) { + if (ths[i]?.style) ths[i].style.width = ''; + } + } + + function lockColumnWidthsIfNeeded() { + if (!activeDataset?.isVirtualized) return; + const paneW = Number(stepsTablePane.clientWidth || 0); + if (paneW <= 0) return; + const nextKey = computeColLockKey(activeDataset); + if (lockedColKey === nextKey && Math.abs(paneW - lockedPaneWidth) < 1) return; + + const ths = stepsTheadRow.children || []; + const colCount = activeDataset.colKeys.length; + if (ths.length !== colCount) return; + + // Release fixed layout momentarily if stale so browser resolves natural widths from sizer + header + if (stepsTableEl.classList?.contains('is-cols-locked')) { + unlockColumnWidths(); + } + + const widths = []; + for (let i = 0; i < colCount; i++) { + const w = Number(ths[i]?.getBoundingClientRect?.()?.width || 0); + if (!Number.isFinite(w) || w <= 0) return; + widths.push(w); + } + const tableW = Number(stepsTableEl.getBoundingClientRect?.()?.width || 0); + if (!Number.isFinite(tableW) || tableW <= 0) return; + + for (let i = 0; i < colCount; i++) { + if (ths[i]?.style) { + ths[i].style.width = `${widths[i].toFixed(2)}px`; + } + } + if (stepsTableEl.style) { + stepsTableEl.style.minWidth = tableW > paneW + 0.5 ? `${tableW.toFixed(2)}px` : ''; + } + patchClasses(stepsTableEl, { 'is-cols-locked': true }); + lockedColKey = nextKey; + lockedPaneWidth = paneW; + } + function readUiFontScale() { try { if (typeof getComputedStyle === 'function') { @@ -22299,6 +22397,7 @@ const StepTableWidget = defineComponent({ lastFontScale = nextScale; calibratedSingleRowH = 0; calibratedReasonRowH = 0; + unlockColumnWidths(); if (activeDataset?.isVirtualized) { const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); activeDataset.rowTops = rebuilt.rowTops; @@ -22447,6 +22546,7 @@ const StepTableWidget = defineComponent({ calibrateRafId = 0; if (!activeDataset?.isVirtualized) return; if (Number(stepsTablePane.clientHeight || 0) <= 0) return; + lockColumnWidthsIfNeeded(); const needSingle = calibratedSingleRowH <= 0; const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; if (!needSingle && !needReason) return; @@ -22539,7 +22639,12 @@ const StepTableWidget = defineComponent({ if (!activeDataset?.isVirtualized) return; const needSingle = calibratedSingleRowH <= 0; const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; - if (!needSingle && !needReason) return; + const paneW = Number(stepsTablePane.clientWidth || 0); + const needColLock = + !lockedColKey || + lockedColKey !== computeColLockKey(activeDataset) || + (paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1); + if (!needSingle && !needReason && !needColLock) return; if (calibrateRafId) return; if (typeof requestAnimationFrame === 'function') { calibrateRafId = requestAnimationFrame(calibrateRowHeights); @@ -22772,6 +22877,7 @@ const StepTableWidget = defineComponent({ updateRow: (refs, item, _idx, tr) => { if (item.isSizer) { const spec = item.sizerSpec; + patchClasses(tr, { 'has-bold-first': Boolean(spec.hasBoldFirstCol) }); if (refs.colOrderSig !== colOrderSig) { for (const [oldColKey, entry] of refs.cellMap) { if (!wantedSet.has(oldColKey)) { @@ -23104,6 +23210,10 @@ const StepTableWidget = defineComponent({ function refreshViewport() { if (!activeDataset?.isVirtualized) return; const scaleChanged = syncFontScaleIfChanged(); + const paneW = Number(stepsTablePane.clientWidth || 0); + if (lockedColKey && paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1) { + unlockColumnWidths(); + } renderCurrentWindow({ force: scaleChanged, enteringRowKeys: null }); scheduleCalibrateRowHeights(); } @@ -23327,8 +23437,13 @@ const StepTableWidget = defineComponent({ totalBodyH, sizerSpec, effectiveScopes, + sortKey: normSortKey, + sortDir: normSortDir, formattedPrompts: new Map(), }; + if (!isVirtualized || computeColLockKey(activeDataset) !== lockedColKey) { + unlockColumnWidths(); + } renderedSliceStart = -1; renderedSliceEnd = -1; renderedTopSpacerH = -1; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index d0604a3..c660904 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index 2a5de1e..fa9c870 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -17,6 +17,8 @@ import { buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, buildStepTimingDiagnostic, + formatMetric, + formatUsd, hasStepTimingData, resolveModelDisplayInfo, speedReasonText, @@ -55,24 +57,48 @@ const SIZER_ROW_KEY = '__vsizer__'; const SPACER_TOP_KEY = '__vspacer_top__'; const SPACER_BOTTOM_KEY = '__vspacer_bottom__'; -function estTokenChars(val) { - const n = Math.max(0, Number(val || 0)); - if (n >= 1_000_000) return n >= 10_000_000 ? 6 : 5; - if (n >= 100_000) return 6; - if (n >= 10_000) return 5; - if (n >= 1_000) return 4; - if (n >= 100) return 3; - if (n >= 10) return 2; - return 1; +function estProportionalTextWidth(text) { + const s = String(text || ''); + let w = 0; + for (let i = 0; i < s.length; i++) { + const code = s.charCodeAt(i); + if (code > 0x2e7f) { + w += 1.8; + } else if ( + code === 105 || code === 108 || code === 73 || code === 116 || code === 102 || + code === 114 || code === 46 || code === 44 || code === 58 || code === 59 || + code === 45 || code === 47 || code === 32 + ) { + w += 0.55; + } else if ( + code === 109 || code === 119 || code === 77 || code === 87 || code === 71 || + code === 79 || code === 81 || code === 67 + ) { + w += 1.32; + } else { + w += 1.0; + } + } + return w; } -function estCostChars(val) { - const n = Number(val); - if (!Number.isFinite(n) || n <= 0) return 1; - if (n >= 100) return 7; - if (n >= 10) return 6; - if (n >= 0.01) return 5; - return 7; +function estTokenChars(val) { + const n = Math.max(0, Number(val || 0)); + if (n >= 1_000_000) return n >= 10_000_000 ? 6.4 : 5.6; + if (n >= 100_000) return 6.0; + if (n >= 10_000) return 5.0; + if (n >= 1_000) return 4.1; + if (n >= 100) return 3.0; + if (n >= 10) return 2.0; + return 1.0; +} + +function estCostWidth(st) { + const c = st?.costUsd; + if (c == null || !Number.isFinite(Number(c))) { + return st?.isPricingPending ? estProportionalTextWidth(t('fmt.pricingPending')) : 1; + } + return estProportionalTextWidth(formatUsd(Number(c))); } function estSegmentChars(seg, st) { @@ -168,19 +194,27 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { let bestCostObj = firstStep; let bestBadgeText = ''; + let bestBadgeWidth = -1; let bestBadgeClass = ''; + let hasBoldFirstCol = false; const badgeCandidates = cellCtx?.showAgentBadge ? new Set() : null; for (let i = 0; i < tableSteps.length; i++) { const st = tableSteps[i]; if (!st || typeof st !== 'object') continue; + if (!hasBoldFirstCol && (isCompactionStepItem(st) || Number(st?.anomaly?.count) > 0)) { + hasBoldFirstCol = true; + } + if (badgeCandidates) { const bKey = `${st.agentKind || ''}|${st.isSubagent ? 1 : 0}|${st.isSideQuestion ? 1 : 0}|${st.agentOrdinal || 0}|${st.sideIndex || 0}|${st.agentIndex || 0}|${st.agentBadge || ''}`; if (!badgeCandidates.has(bKey)) { badgeCandidates.add(bKey); const text = resolveBadgeTextForStep(st); - if (text.length > bestBadgeText.length) { + const bw = estProportionalTextWidth(text); + if (bw > bestBadgeWidth) { + bestBadgeWidth = bw; bestBadgeText = text; bestBadgeClass = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); } @@ -224,17 +258,23 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needTtft) { const v = Number(st.ttftSec); - if (Number.isFinite(v) && v > maxTtftVal) { - maxTtftVal = v; - bestTtftObj = st; + if (Number.isFinite(v) && v >= 0) { + const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v; + if (score > maxTtftVal) { + maxTtftVal = score; + bestTtftObj = st; + } } } if (needDuration) { const v = Number(st.totalDurationSec ?? st.streamDurationSec); - if (Number.isFinite(v) && v > maxDurVal) { - maxDurVal = v; - bestDurObj = st; + if (Number.isFinite(v) && v >= 0) { + const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v; + if (score > maxDurVal) { + maxDurVal = score; + bestDurObj = st; + } } } @@ -320,7 +360,7 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needCost) { const c = Number(st.costUsd); - const score = estCostChars(c) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0); + const score = estCostWidth(st) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0); if (score > bestCostScore) { bestCostScore = score; bestCostObj = st; @@ -331,13 +371,13 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { if (needStep) colSteps.step = bestStepObj; if (needTime) colSteps.time = bestTimeObj || firstStep; if (needModel && modelCandidates) { - let bestModelLen = -1; + let bestModelWidth = -1; let bestModelObj = firstStep; for (const cand of modelCandidates.values()) { const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' }); - const len = disp.baseText?.length || 0; - if (len > bestModelLen) { - bestModelLen = len; + const w = estProportionalTextWidth(disp.baseText || ''); + if (w > bestModelWidth) { + bestModelWidth = w; bestModelObj = cand; } } @@ -345,19 +385,20 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { } if (needTps) { let longestReasonKey = null; - let longestReasonLen = 0; + let longestReasonWidth = 0; if (reasonCandidates) { for (const rk of reasonCandidates) { const txt = speedReasonText(rk); - if (txt && txt.length > longestReasonLen) { - longestReasonLen = txt.length; + const w = txt ? estProportionalTextWidth(txt) : 0; + if (w > longestReasonWidth) { + longestReasonWidth = w; longestReasonKey = rk; } } } colSteps.tps = { ...(maxTpsObj || firstStep), - tokPerSec: maxTpsVal > 0 ? maxTpsVal : firstStep.tokPerSec, + tokPerSec: maxTpsObj ? maxTpsObj.tokPerSec : firstStep.tokPerSec, selectedSpeedReason: longestReasonKey, }; } @@ -380,7 +421,8 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) { colSteps, badgeText: bestBadgeText, badgeClass: bestBadgeClass, - sig: `sizer:${bestBadgeText}:${sigParts.join('|')}`, + hasBoldFirstCol, + sig: `sizer:${bestBadgeText}:${hasBoldFirstCol ? 1 : 0}:${sigParts.join('|')}`, }; } @@ -648,8 +690,66 @@ export const StepTableWidget = defineComponent({ let lastFontScale = 1; let calibratedSingleRowH = 0; let calibratedReasonRowH = 0; + let lockedColKey = ''; + let lockedPaneWidth = 0; const rowPool = []; + function computeColLockKey(ds) { + if (!ds?.isVirtualized) return ''; + return `${ds.locale}:${ds.colOrderSig}:${lastFontScale}:${ds.showAgentBadge ? 1 : 0}:${ds.railActive ? 1 : 0}:${ds.sortKey || ''}:${ds.sortDir || ''}:${ds.sizerSpec?.sig || ''}`; + } + + function unlockColumnWidths() { + lockedColKey = ''; + lockedPaneWidth = 0; + patchClasses(stepsTableEl, { 'is-cols-locked': false }); + if (stepsTableEl.style) { + stepsTableEl.style.minWidth = ''; + } + const ths = stepsTheadRow.children || []; + for (let i = 0; i < ths.length; i++) { + if (ths[i]?.style) ths[i].style.width = ''; + } + } + + function lockColumnWidthsIfNeeded() { + if (!activeDataset?.isVirtualized) return; + const paneW = Number(stepsTablePane.clientWidth || 0); + if (paneW <= 0) return; + const nextKey = computeColLockKey(activeDataset); + if (lockedColKey === nextKey && Math.abs(paneW - lockedPaneWidth) < 1) return; + + const ths = stepsTheadRow.children || []; + const colCount = activeDataset.colKeys.length; + if (ths.length !== colCount) return; + + // Release fixed layout momentarily if stale so browser resolves natural widths from sizer + header + if (stepsTableEl.classList?.contains('is-cols-locked')) { + unlockColumnWidths(); + } + + const widths = []; + for (let i = 0; i < colCount; i++) { + const w = Number(ths[i]?.getBoundingClientRect?.()?.width || 0); + if (!Number.isFinite(w) || w <= 0) return; + widths.push(w); + } + const tableW = Number(stepsTableEl.getBoundingClientRect?.()?.width || 0); + if (!Number.isFinite(tableW) || tableW <= 0) return; + + for (let i = 0; i < colCount; i++) { + if (ths[i]?.style) { + ths[i].style.width = `${widths[i].toFixed(2)}px`; + } + } + if (stepsTableEl.style) { + stepsTableEl.style.minWidth = tableW > paneW + 0.5 ? `${tableW.toFixed(2)}px` : ''; + } + patchClasses(stepsTableEl, { 'is-cols-locked': true }); + lockedColKey = nextKey; + lockedPaneWidth = paneW; + } + function readUiFontScale() { try { if (typeof getComputedStyle === 'function') { @@ -712,6 +812,7 @@ export const StepTableWidget = defineComponent({ lastFontScale = nextScale; calibratedSingleRowH = 0; calibratedReasonRowH = 0; + unlockColumnWidths(); if (activeDataset?.isVirtualized) { const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags); activeDataset.rowTops = rebuilt.rowTops; @@ -860,6 +961,7 @@ export const StepTableWidget = defineComponent({ calibrateRafId = 0; if (!activeDataset?.isVirtualized) return; if (Number(stepsTablePane.clientHeight || 0) <= 0) return; + lockColumnWidthsIfNeeded(); const needSingle = calibratedSingleRowH <= 0; const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; if (!needSingle && !needReason) return; @@ -952,7 +1054,12 @@ export const StepTableWidget = defineComponent({ if (!activeDataset?.isVirtualized) return; const needSingle = calibratedSingleRowH <= 0; const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason; - if (!needSingle && !needReason) return; + const paneW = Number(stepsTablePane.clientWidth || 0); + const needColLock = + !lockedColKey || + lockedColKey !== computeColLockKey(activeDataset) || + (paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1); + if (!needSingle && !needReason && !needColLock) return; if (calibrateRafId) return; if (typeof requestAnimationFrame === 'function') { calibrateRafId = requestAnimationFrame(calibrateRowHeights); @@ -1185,6 +1292,7 @@ export const StepTableWidget = defineComponent({ updateRow: (refs, item, _idx, tr) => { if (item.isSizer) { const spec = item.sizerSpec; + patchClasses(tr, { 'has-bold-first': Boolean(spec.hasBoldFirstCol) }); if (refs.colOrderSig !== colOrderSig) { for (const [oldColKey, entry] of refs.cellMap) { if (!wantedSet.has(oldColKey)) { @@ -1517,6 +1625,10 @@ export const StepTableWidget = defineComponent({ function refreshViewport() { if (!activeDataset?.isVirtualized) return; const scaleChanged = syncFontScaleIfChanged(); + const paneW = Number(stepsTablePane.clientWidth || 0); + if (lockedColKey && paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1) { + unlockColumnWidths(); + } renderCurrentWindow({ force: scaleChanged, enteringRowKeys: null }); scheduleCalibrateRowHeights(); } @@ -1740,8 +1852,13 @@ export const StepTableWidget = defineComponent({ totalBodyH, sizerSpec, effectiveScopes, + sortKey: normSortKey, + sortDir: normSortDir, formattedPrompts: new Map(), }; + if (!isVirtualized || computeColLockKey(activeDataset) !== lockedColKey) { + unlockColumnWidths(); + } renderedSliceStart = -1; renderedSliceEnd = -1; renderedTopSpacerH = -1; diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 6d2a3dd..933465a 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -56,6 +56,19 @@ white-space: nowrap; } +.data-table td { + font-variant-numeric: tabular-nums; +} + +.data-table.is-cols-locked { + table-layout: fixed; +} + +.data-table.is-cols-locked td:not(:first-child) { + overflow: hidden; + text-overflow: ellipsis; +} + .data-table th.is-right, .data-table td.is-right { text-align: right; @@ -140,6 +153,10 @@ height: 0; } +.data-table tbody tr.step-vsizer.has-bold-first td:first-child { + font-weight: 600; +} + .step-vsizer-inner { display: block; height: 0; diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index beb31e7..3419c81 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -4189,6 +4189,19 @@ html[data-standalone="true"] .app-shell { white-space: nowrap; } +.data-table td { + font-variant-numeric: tabular-nums; +} + +.data-table.is-cols-locked { + table-layout: fixed; +} + +.data-table.is-cols-locked td:not(:first-child) { + overflow: hidden; + text-overflow: ellipsis; +} + .data-table th.is-right, .data-table td.is-right { text-align: right; @@ -4273,6 +4286,10 @@ html[data-standalone="true"] .app-shell { height: 0; } +.data-table tbody tr.step-vsizer.has-bold-first td:first-child { + font-weight: 600; +} + .step-vsizer-inner { display: block; height: 0; From 2e1126a88f0ff90799696c896a47e400947962c5 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 02:45:31 +0900 Subject: [PATCH 04/30] fix(panel): preserve context window breakdown after conversation undo - Anchor unindexed (stepIndices: []) trailing generatorMetadata breakdowns to the prior generator watermark and backfill pre-compaction anchor steps without leaking onto compaction checkpoints - Preserve matching historical step contextBreakdown entries and a compact 5-channel static baseline across trajectory rescans so deleting the tail generatorMetadata on undo no longer zeroes out channels - Reconstruct missing context channels from step token deltas and the cached static baseline when no breakdown payload remains, with estimatedContextTokens fallback for zero-usage tail steps --- sidecars/panel/backend/cli-sqlite-reader.mjs | 12 +- sidecars/panel/backend/local-scanner.mjs | 168 +++++++++- sidecars/panel/backend/telemetry-builder.mjs | 131 +++++++- sidecars/panel/test/backend.test.mjs | 325 +++++++++++++++++++ sidecars/panel/trajectory-metrics.mjs | 81 +++-- 5 files changed, 680 insertions(+), 37 deletions(-) diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index 9d08e04..ef95418 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -1807,15 +1807,23 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if (ownGenRecords.length > 0) { // 从末尾向前定位最近一条包含完整上下文拆解(tokenBreakdown / promptSections / tools / messagePrompts)的记录, - // 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成。 + // 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成; + // 若末尾完整记录因回退/中断成为 `stepIndices: []`,继续跳过被宿主裁剪的轻量记录并尝试补解更早的完整带索引记录。 + let foundUnindexedBreakdown = false; for (let i = ownGenRecords.length - 1; i >= 0; i--) { const rec = ownGenRecords[i]; + if (foundUnindexedBreakdown && Number(rec?.rawData?.byteLength || 0) <= 2048) { + continue; + } try { const fullDecoded = decodeProtoGeneratorMeta(rec.rawData, true); if (fullDecoded) { rec.gm = fullDecoded; if (hasContextBreakdownPayload(fullDecoded.chatModel)) { - break; + if (Array.isArray(fullDecoded.stepIndices) && fullDecoded.stepIndices.length > 0) { + break; + } + foundUnindexedBreakdown = true; } } } catch { diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index ff316ac..c593c74 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -327,6 +327,146 @@ function normalizeOwnerAccount(value) { * - 已存在于旧缓存中的历史步骤保留原归属账号(兼容跨账号续聊同一会话); * - 切换账号后在该会话中新产生的步骤写入当前活跃账号 `step.accountName`,仅供「可用额度」按账号隔离统计。 */ +const MAX_PRESERVED_BREAKDOWN_STEPS = 64; + +function extractStaticContextFromStep(st) { + const bd = st?.contextBreakdown; + if (!bd || typeof bd !== 'object') return null; + const sysPrompt = Math.max(0, Number(bd.systemPromptTokens || 0)); + const sysTools = Math.max(0, Number(bd.systemToolsTokens || 0)); + const mcpTools = Math.max(0, Number(bd.mcpToolsTokens || 0)); + const skills = Math.max(0, Number(bd.skillsTokens || 0)); + const userRules = Math.max(0, Number(bd.userRulesTokens || 0)); + const staticSum = sysPrompt + sysTools + mcpTools + skills + userRules; + if (staticSum <= 0) return null; + + const rawTotal = + Number(bd.totalTokens || 0) || + staticSum + + Math.max(0, Number(bd.messagesTokens || 0)) || + staticSum + + Math.max(0, Number(bd.userInputTokens || 0)) + + Math.max(0, Number(bd.assistantTokens || 0)) + + Math.max(0, Number(bd.toolResultsTokens || 0)) + + Math.max(0, Number(bd.subagentTokens || 0)) + + Math.max(0, Number(bd.checkpointTokens || 0)); + const promptTokens = + Math.max(0, Number(st?.inputTokens || 0)) + Math.max(0, Number(st?.cacheReadTokens || 0)); + const scale = + rawTotal > 0 && promptTokens >= rawTotal * 0.5 ? promptTokens / rawTotal : 1; + + return { + systemPromptTokens: Math.round(sysPrompt * scale), + systemToolsTokens: Math.round(sysTools * scale), + mcpToolsTokens: Math.round(mcpTools * scale), + skillsTokens: Math.round(skills * scale), + userRulesTokens: Math.round(userRules * scale), + }; +} + +function isSameHistoricalStep(nextStep, prevStep) { + if (!nextStep || !prevStep || typeof nextStep !== 'object' || typeof prevStep !== 'object') { + return false; + } + if (Number(nextStep.stepIndex) !== Number(prevStep.stepIndex)) return false; + if (Boolean(nextStep.isCompactionStep) !== Boolean(prevStep.isCompactionStep)) return false; + if ( + Number(nextStep.inputTokens || 0) !== Number(prevStep.inputTokens || 0) || + Number(nextStep.cacheReadTokens || 0) !== Number(prevStep.cacheReadTokens || 0) || + Number(nextStep.outputTokens || 0) !== Number(prevStep.outputTokens || 0) + ) { + return false; + } + const nextTs = Number(nextStep.createdAtMs || 0); + const prevTs = Number(prevStep.createdAtMs || 0); + if (nextTs > 0 && prevTs > 0 && Math.abs(nextTs - prevTs) > 2000) { + return false; + } + return true; +} + +/** + * 宿主只保留末尾一条完整 `gen_metadata` 并裁剪历史拆解;对话运行或回退重扫时, + * 为当前活跃窗口内(最近压缩前锚点至末尾,最多保留 64 步)完全匹配的未变更历史步保留已缓存的 `contextBreakdown`, + * 同时维护紧凑的 5 通道静态基线,确保回退到任意较早轮次后上下文窗口拆解不归零。 + */ +function preserveCachedContextTelemetry(steps, prev) { + if (!Array.isArray(steps) || steps.length === 0) { + return { + steps, + lastKnownStaticContext: prev?.lastKnownStaticContext || null, + }; + } + + let preservedSteps = steps; + const prevSteps = Array.isArray(prev?.steps) ? prev.steps : []; + if (prevSteps.length > 0) { + const prevWithBdByIdx = new Map(); + for (const ps of prevSteps) { + if (!ps || typeof ps !== 'object' || !ps.contextBreakdown) continue; + const idx = Number(ps.stepIndex); + if (Number.isFinite(idx)) { + prevWithBdByIdx.set(idx, ps); + } + } + + if (prevWithBdByIdx.size > 0) { + let lastCompIdx = -1; + for (let i = steps.length - 1; i >= 0; i -= 1) { + if (steps[i]?.isCompactionStep) { + lastCompIdx = i; + break; + } + } + let keepStartIdx = Math.max(0, steps.length - MAX_PRESERVED_BREAKDOWN_STEPS); + if (lastCompIdx >= 0) { + const anchorIdx = Math.max(0, lastCompIdx - 1); + keepStartIdx = Math.max(keepStartIdx, anchorIdx); + } + + let mutated = false; + const nextList = steps.map((st, pos) => { + if (!st || st.isCompactionStep || st.contextBreakdown || pos < keepStartIdx) { + return st; + } + const idx = Number(st.stepIndex); + const matchedPrev = Number.isFinite(idx) ? prevWithBdByIdx.get(idx) : null; + if (!matchedPrev || !isSameHistoricalStep(st, matchedPrev)) { + return st; + } + mutated = true; + return { + ...st, + contextBreakdown: matchedPrev.contextBreakdown, + ...(!st.reportedContextLimitTokens && matchedPrev.reportedContextLimitTokens + ? { + reportedContextLimitTokens: matchedPrev.reportedContextLimitTokens, + maxContextBudgetTokens: matchedPrev.maxContextBudgetTokens, + } + : {}), + }; + }); + if (mutated) { + preservedSteps = nextList; + } + } + } + + let lastKnownStaticContext = null; + for (let i = preservedSteps.length - 1; i >= 0; i -= 1) { + const extracted = extractStaticContextFromStep(preservedSteps[i]); + if (extracted) { + lastKnownStaticContext = extracted; + break; + } + } + if (!lastKnownStaticContext && prev?.lastKnownStaticContext) { + lastKnownStaticContext = prev.lastKnownStaticContext; + } + + return { steps: preservedSteps, lastKnownStaticContext }; +} + function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountName) { if (!Array.isArray(steps) || steps.length === 0) return steps; const activeOwner = normalizeOwnerAccount(currentAccountName); @@ -2199,8 +2339,9 @@ export async function enumerateAndSyncConversations({ } const entryAccountName = prev?.accountName || currentAccountName || ''; + const contextPreserved = preserveCachedContextTelemetry(steps, prev); const stepsWithOwners = attachStepAccountOwners( - steps, + contextPreserved.steps, prev, currentAccountName, entryAccountName @@ -2218,9 +2359,12 @@ export async function enumerateAndSyncConversations({ speedClearedTelemetry: true, turnRailTelemetry: true, wakeupTurnTelemetry: true, - contextGroupsTelemetry: 2, + contextGroupsTelemetry: 3, anomalyTelemetry: 1, steps: stepsWithOwners, + ...(contextPreserved.lastKnownStaticContext + ? { lastKnownStaticContext: contextPreserved.lastKnownStaticContext } + : {}), subagentRefs, }; if (rpcSwarmMeta) cacheEntry.swarmMeta = rpcSwarmMeta; @@ -2246,6 +2390,10 @@ export async function enumerateAndSyncConversations({ !Array.isArray(prev?.subagentRefs) || JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) || !isDeepStrictEqual(prev?.swarmMeta || null, cacheEntry.swarmMeta || null) || + !isDeepStrictEqual( + prev?.lastKnownStaticContext || null, + cacheEntry.lastKnownStaticContext || null + ) || Boolean(prev?.parkedOnSwarmWait) !== Boolean(cacheEntry.parkedOnSwarmWait) || (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') || Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion); @@ -2257,7 +2405,7 @@ export async function enumerateAndSyncConversations({ !prev.contextLimitTelemetry || !prev.speedClearedTelemetry || !prev.turnRailTelemetry || - !prev.contextGroupsTelemetry || + Number(prev.contextGroupsTelemetry || 0) < 3 || !prev.anomalyTelemetry || metaChanged || !isDeepStrictEqual(prev.steps, stepsWithOwners); @@ -2307,8 +2455,9 @@ export async function enumerateAndSyncConversations({ const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles); const offlineAccountName = prev?.accountName || offlineFallback.accountName || currentAccountName || ''; + const offlinePreserved = preserveCachedContextTelemetry(offlineFallback.steps, prev); const offlineStepsWithOwners = attachStepAccountOwners( - offlineFallback.steps, + offlinePreserved.steps, prev, offlineFallback.accountName || currentAccountName, offlineAccountName @@ -2327,9 +2476,12 @@ export async function enumerateAndSyncConversations({ contextLimitTelemetry: true, speedClearedTelemetry: true, turnRailTelemetry: true, - contextGroupsTelemetry: 2, + contextGroupsTelemetry: 3, anomalyTelemetry: 1, steps: offlineStepsWithOwners, + ...(offlinePreserved.lastKnownStaticContext + ? { lastKnownStaticContext: offlinePreserved.lastKnownStaticContext } + : {}), subagentRefs: offlineFallback.subagentRefs, }; if (conv.isSubagent) { @@ -2441,8 +2593,12 @@ export async function enumerateAndSyncConversations({ return !Object.prototype.hasOwnProperty.call(lastCachedStep, 'turnIndex'); } function hasDroppedContextGroups(cached) { - if (cached?.contextGroupsTelemetry === 2) return false; + const grpVer = Number(cached?.contextGroupsTelemetry || 0); + if (grpVer >= 3) return false; const steps = cached?.steps || []; + if (grpVer === 2) { + return steps.length > 0 && !steps.some((st) => Boolean(st?.contextBreakdown)); + } if (steps.some((st) => st?.isCompactionStep)) { return true; } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index c9f78f2..ca4f86a 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -325,6 +325,35 @@ const CONTEXT_CHANNEL_KEYS = [ 'userRules', ]; +const STATIC_CONTEXT_CHANNEL_KEYS = [ + 'systemTools', + 'mcpTools', + 'skills', + 'systemPrompt', + 'userRules', +]; + +function applyFallbackStaticChannels(channels, fallbackStaticContext, capTotal = 0) { + if (!fallbackStaticContext || typeof fallbackStaticContext !== 'object') return 0; + let staticMap = { + systemTools: Math.max(0, Math.round(Number(fallbackStaticContext.systemToolsTokens || 0))), + mcpTools: Math.max(0, Math.round(Number(fallbackStaticContext.mcpToolsTokens || 0))), + skills: Math.max(0, Math.round(Number(fallbackStaticContext.skillsTokens || 0))), + systemPrompt: Math.max(0, Math.round(Number(fallbackStaticContext.systemPromptTokens || 0))), + userRules: Math.max(0, Math.round(Number(fallbackStaticContext.userRulesTokens || 0))), + }; + let staticSum = STATIC_CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + staticMap[k], 0); + if (staticSum <= 0) return 0; + if (capTotal > 0 && staticSum > capTotal) { + staticMap = scaleBucketsExact(staticMap, STATIC_CONTEXT_CHANNEL_KEYS, Math.round(capTotal)); + staticSum = STATIC_CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + staticMap[k], 0); + } + for (const k of STATIC_CONTEXT_CHANNEL_KEYS) { + channels[k] = staticMap[k]; + } + return staticSum; +} + function resolveStepOutputTokens(st) { const explicitOut = Number(st?.outputTokens || 0); if (explicitOut > 0) return explicitOut; @@ -388,7 +417,8 @@ function extractActiveContextTelemetry( enrichedActiveSteps, latestEnriched, sessionInputTokens, - sessionCacheReadTokens + sessionCacheReadTokens, + fallbackStaticContext = null ) { let lastCompactionIdx = -1; for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { @@ -470,6 +500,8 @@ function extractActiveContextTelemetry( channels.skills = preChannels.skills; channels.systemPrompt = preChannels.systemPrompt; channels.userRules = preChannels.userRules; + } else if (fallbackStaticContext) { + applyFallbackStaticChannels(channels, fallbackStaticContext, 0); } channels.userInput = 0; channels.assistant = 0; @@ -499,6 +531,59 @@ function extractActiveContextTelemetry( runningTotal = mPrompt + mOut; } } + } else if (enrichedActiveSteps.length > 0) { + // 当宿主回退或历史裁剪导致全部步骤均无 `contextBreakdown` 且未发生过压缩时, + // 基于缓存的 5 通道静态基线(如有)和各步真实计费增量重建上下文通道,避免进度条和 10 项图例全归零。 + let runningTotal = 0; + let seededInitial = false; + for (let m = 0; m < enrichedActiveSteps.length; m++) { + const stepM = enrichedActiveSteps[m]; + if (!stepM || stepM.isCompactionStep) continue; + const mPrompt = + Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); + const mOut = resolveStepOutputTokens(stepM); + if (!seededInitial) { + if (mPrompt <= 0 && mOut <= 0) continue; + seededInitial = true; + if (mPrompt > 0) { + const staticUsed = applyFallbackStaticChannels( + channels, + fallbackStaticContext, + mPrompt + ); + channels.userInput += Math.max(0, mPrompt - staticUsed); + } + channels.assistant += mOut; + runningTotal = mPrompt + mOut; + } else if (mPrompt > 0) { + if (mPrompt > runningTotal) { + const delta = mPrompt - runningTotal; + if (enrichedActiveSteps[m - 1]?.hasToolCalls) { + channels.toolResults += delta; + } else { + channels.userInput += delta; + } + } else if (mPrompt < runningTotal) { + channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt); + } + channels.assistant += mOut; + runningTotal = mPrompt + mOut; + } + } + if (runningTotal === 0) { + const estFallback = Math.max( + 0, + Math.round(Number(latestEnriched?.estimatedContextTokens || 0)) + ); + if (estFallback > 0) { + const staticUsed = applyFallbackStaticChannels( + channels, + fallbackStaticContext, + estFallback + ); + channels.userInput += Math.max(0, estFallback - staticUsed); + } + } } const ctxUserInput = channels.userInput; @@ -526,7 +611,7 @@ function extractActiveContextTelemetry( ? ctxBreakdownTotal : ctxBreakdownTotal > 0 ? ctxBreakdownTotal - : ctxCached + ctxFreshInput + ctxOut; + : ctxCached + ctxFreshInput + ctxOut || Number(latestEnriched?.estimatedContextTokens || 0); const compactionLimitTokens = Number( (isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0 ? fallbackPreCompactionLimit @@ -598,7 +683,14 @@ function sameFallbackUpstreams(prevMap, fallbackModelKeys, upstream) { return true; } -function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, reuseInputs) { +function prepareAgentSteps( + rawSteps, + resolveStepModel, + upstream, + agentFields, + reuseInputs, + fallbackStaticContext = null +) { const facts = readTrajectoryModelFacts(rawSteps); for (const [key, model] of facts.upstream) upstream.set(key, model); const canCache = Boolean(reuseInputs && Array.isArray(rawSteps)); @@ -610,6 +702,7 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re previous.catalogRevision === reuseInputs.catalogRevision && previous.phaseEpoch === reuseInputs.phaseEpoch && isDeepStrictEqual(previous.dynamicModelMap, reuseInputs.dynamicModelMap) && + isDeepStrictEqual(previous.fallbackStaticContext || null, fallbackStaticContext || null) && sameFallbackUpstreams(previous.fallbackUpstreams, facts.fallbackModelKeys, upstream) ) { return previous.prepared; @@ -620,8 +713,13 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re const prepared = { enrichedRes, recentSteps: taggedSteps.slice().reverse(), - ctxRes: extractActiveContextTelemetry(taggedSteps, enrichedRes.latestEnriched, - enrichedRes.sessionInputTokens, enrichedRes.sessionCacheReadTokens), + ctxRes: extractActiveContextTelemetry( + taggedSteps, + enrichedRes.latestEnriched, + enrichedRes.sessionInputTokens, + enrichedRes.sessionCacheReadTokens, + fallbackStaticContext + ), modelBreakdown: buildScopedModelBreakdown(taggedSteps, resolveStepModel), }; // 按 rawSteps 数组引用缓存各代理(含多代理子代理)步骤富化结果,步骤变更后由 WeakMap 自动淘汰。 @@ -631,6 +729,7 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re catalogRevision: reuseInputs.catalogRevision, phaseEpoch: reuseInputs.phaseEpoch, dynamicModelMap: reuseInputs.dynamicModelMap, + fallbackStaticContext: fallbackStaticContext || null, fallbackUpstreams: snapshotFallbackUpstreams(facts.fallbackModelKeys, upstream), prepared, }); @@ -660,6 +759,7 @@ export function buildAgentUnitTelemetry({ agentLabel, status, rawSteps, + fallbackStaticContext = null, liveActivity = null, fallbackLastModMs, resolveStepModel, @@ -684,7 +784,8 @@ export function buildAgentUnitTelemetry({ isSubagent: !isMain, ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), }, - reuseInputs + reuseInputs, + fallbackStaticContext ); const taggedSteps = enrichedRes.enrichedActiveSteps; const lastModifiedMs = @@ -951,6 +1052,7 @@ function buildActiveConversationAssembly({ activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0, activeConvSummary?.liveActivity?.signature || '', activeConvSummary?.liveActivity?.startedAtMs || 0, + activeEntry?.lastKnownStaticContext || null, subagentSummaries.map((subSum, idx) => { const subEntry = subEntries[idx]; const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; @@ -967,6 +1069,7 @@ function buildActiveConversationAssembly({ subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0, subSum.liveActivity?.signature || '', subSum.liveActivity?.startedAtMs || 0, + subEntry?.lastKnownStaticContext || null, subSpec?.role || '', subSpec?.typeName || '', ]; @@ -1007,6 +1110,7 @@ function buildActiveConversationAssembly({ agentLabel: '主代理', status: activeConvSummary?.status || 'IDLE', rawSteps: activeSteps, + fallbackStaticContext: activeEntry?.lastKnownStaticContext || null, liveActivity: activeConvSummary?.liveActivity || null, fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0, resolveStepModel, @@ -1088,6 +1192,7 @@ function buildActiveConversationAssembly({ agentLabel, status: subSum.status || 'IDLE', rawSteps: subRawSteps, + fallbackStaticContext: subEntry?.lastKnownStaticContext || null, liveActivity: subSum.liveActivity || null, fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0, resolveStepModel, @@ -1884,8 +1989,13 @@ export async function buildTelemetryPayloadInternal( let contextUsedPct = null; if (lastRootStep) { - contextUsedPct = extractActiveContextTelemetry(rootSteps, lastRootStep, 0, 0).context - .compactionUsedPct; + contextUsedPct = extractActiveContextTelemetry( + rootSteps, + lastRootStep, + 0, + 0, + rootEntry?.lastKnownStaticContext || null + ).context.compactionUsedPct; } let modelShort = ''; @@ -2338,10 +2448,13 @@ function resolveValidFastSnapshot(endpoint = null) { function entryNeedsLazyTelemetryUpgrade(entry) { if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) return false; + const grpVer = Number(entry.contextGroupsTelemetry || 0); + const needsUndoCtxUpgrade = + grpVer < 2 || (grpVer === 2 && !entry.steps.some((st) => Boolean(st?.contextBreakdown))); return ( !entry.turnRailTelemetry || !entry.anomalyTelemetry || - entry.contextGroupsTelemetry !== 2 + needsUndoCtxUpgrade ); } diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index dff6150..34820e8 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -3455,3 +3455,328 @@ test('CLI statusLine supports --style pill|bar|compact switching, flag persisten assert.equal(jsonSnap.quotas.pools[0].remaining5hPct, 40); assert.equal(jsonSnap.quotas.pools[0].remainingWeeklyPct, 80); }); + +test('conversation undo preserves 10-channel context breakdown across unindexed tail gen_metadata, stripped history, and cold fallback', async () => { + const baseMs = Date.parse('2026-11-23T17:00:00.000Z'); + const iso = (offsetSec) => new Date(baseMs + offsetSec * 1000).toISOString(); + + // Case 1: Undo after a prior compaction leaves trailing gen_metadata with stepIndices: [] and full tokenBreakdown + const undoPostCompactSteps = [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: iso(0), + completedAt: iso(2), + sourceTrajectoryStepInfo: { stepIndex: 10 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '180000', cacheReadTokens: '0', outputTokens: '800' }, + }, + plannerResponse: { response: 'before compact' }, + }, + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: iso(5), + completedAt: iso(7), + sourceTrajectoryStepInfo: { stepIndex: 11 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '181000', cacheReadTokens: '0', outputTokens: '3200', responseOutputTokens: '3100' }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: iso(15), + completedAt: iso(18), + sourceTrajectoryStepInfo: { stepIndex: 14 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '5000', cacheReadTokens: '95000', outputTokens: '1200' }, + }, + plannerResponse: { response: 'post compact step' }, + }, + { + type: 'CORTEX_STEP_TYPE_USER_INPUT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: iso(25), sourceTrajectoryStepInfo: { stepIndex: 15 } }, + userInput: { userResponse: 'undone prompt' }, + }, + ]; + const undoPostCompactGen = [ + { + stepIndices: [14], + chatModel: { + model: 'MODEL_PLACEHOLDER_M37', + chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 99000, maxContextTokens: 256000 } }, + }, + }, + { + stepIndices: [], + chatModel: { + model: 'MODEL_PLACEHOLDER_M37', + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 101200, + maxContextTokens: 256000, + tokenBreakdown: { + groups: [ + { type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 6000 }, + { type: 'TOKEN_TYPE_SKILLS', numTokens: 1800 }, + { type: 'TOKEN_TYPE_USER_RULES', numTokens: 2200 }, + { + type: 'TOKEN_TYPE_TOOLS', + numTokens: 7000, + children: [ + { name: 'read_file', numTokens: 6500 }, + { name: 'mcp_custom_tool', numTokens: 500 }, + ], + }, + { + type: 'TOKEN_TYPE_CHAT_MESSAGES', + numTokens: 84200, + children: [ + { name: '11: CHECKPOINT', numTokens: 3200 }, + { name: '12: USER_INPUT', numTokens: 1000 }, + { name: '13: GENERIC', numTokens: 45000 }, + { name: '14: PLANNER_RESPONSE', numTokens: 35000 }, + ], + }, + ], + }, + }, + }, + }, + }, + ]; + + const h1 = backendHarness({ + trajectories: { + 'conv-undo-si-empty': { + trajectory: { steps: undoPostCompactSteps, generatorMetadata: undoPostCompactGen }, + }, + }, + summaries: { + 'conv-undo-si-empty': { + annotations: { title: 'Undo Post Compact' }, + stepCount: 4, + lastModifiedTime: iso(25), + status: 'IDLE', + }, + }, + }); + const p1 = await h1.buildTelemetryPayloadInternal('conv-undo-si-empty'); + const ctx1 = p1.activeConversation.context; + assert.equal(ctx1.totalTokens, 101200); + assert.ok(ctx1.systemPromptTokens > 5500, `sysPrompt=${ctx1.systemPromptTokens}`); + assert.ok(ctx1.systemToolsTokens > 6000, `sysTools=${ctx1.systemToolsTokens}`); + assert.ok(ctx1.mcpToolsTokens > 400, `mcpTools=${ctx1.mcpToolsTokens}`); + assert.ok(ctx1.skillsTokens > 1500, `skills=${ctx1.skillsTokens}`); + assert.ok(ctx1.userRulesTokens > 2000, `rules=${ctx1.userRulesTokens}`); + assert.equal( + ctx1.userInputTokens + + ctx1.assistantTokens + + ctx1.toolResultsTokens + + ctx1.subagentTokens + + ctx1.checkpointTokens + + ctx1.systemToolsTokens + + ctx1.mcpToolsTokens + + ctx1.skillsTokens + + ctx1.systemPromptTokens + + ctx1.userRulesTokens, + 101200 + ); + + // Case 2: Trailing compaction step with unindexed pre-compaction gen_metadata inherits static channels without inflating checkpoint + const h2 = backendHarness({ + trajectories: { + 'conv-undo-tail-compact': { + trajectory: { + steps: undoPostCompactSteps.slice(0, 2), + generatorMetadata: [ + { + stepIndices: [10], + chatModel: { + model: 'MODEL_PLACEHOLDER_M37', + chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 180000, maxContextTokens: 512000 } }, + }, + }, + { + stepIndices: [], + chatModel: { + model: 'MODEL_PLACEHOLDER_M37', + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 180000, + maxContextTokens: 512000, + tokenBreakdown: { + groups: [ + { type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 10000 }, + { type: 'TOKEN_TYPE_TOOLS', numTokens: 8000 }, + { type: 'TOKEN_TYPE_SKILLS', numTokens: 2000 }, + { type: 'TOKEN_TYPE_USER_RULES', numTokens: 3000 }, + { type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 157000 }, + ], + }, + }, + }, + }, + }, + ], + }, + }, + }, + summaries: { + 'conv-undo-tail-compact': { + annotations: { title: 'Tail Compact' }, + stepCount: 2, + lastModifiedTime: iso(7), + status: 'IDLE', + }, + }, + }); + const p2 = await h2.buildTelemetryPayloadInternal('conv-undo-tail-compact'); + const ctx2 = p2.activeConversation.context; + assert.equal(ctx2.checkpointTokens, 3100); + assert.equal(ctx2.systemPromptTokens, 10000); + assert.equal(ctx2.systemToolsTokens, 8000); + assert.equal(ctx2.skillsTokens, 2000); + assert.equal(ctx2.userRulesTokens, 3000); + assert.equal(ctx2.userInputTokens, 0); + assert.equal(ctx2.totalTokens, 26100); + + // Case 3: Live multi-turn undo deletes tail gen_metadata leaving only stripped 1KB rows -> cached breakdown + static baseline survive + const step1 = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: iso(0), + completedAt: iso(2), + sourceTrajectoryStepInfo: { stepIndex: 1 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '20000', cacheReadTokens: '0', outputTokens: '1000' }, + }, + plannerResponse: { response: 'turn 1', toolCalls: [{ name: 'read_file' }] }, + }; + const step2 = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: iso(10), + completedAt: iso(12), + sourceTrajectoryStepInfo: { stepIndex: 3 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '5000', cacheReadTokens: '21000', outputTokens: '1500' }, + }, + plannerResponse: { response: 'turn 2' }, + }; + const step3 = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: iso(20), + completedAt: iso(22), + sourceTrajectoryStepInfo: { stepIndex: 5 }, + modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '4000', cacheReadTokens: '27500', outputTokens: '800' }, + }, + plannerResponse: { response: 'turn 3' }, + }; + const liveTraj = { + trajectory: { + steps: [step1, step2, step3], + generatorMetadata: [ + { stepIndices: [1], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 20000, maxContextTokens: 256000 } } } }, + { stepIndices: [3], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 26000, maxContextTokens: 256000 } } } }, + { + stepIndices: [5], + chatModel: { + model: 'MODEL_PLACEHOLDER_M37', + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 31500, + maxContextTokens: 256000, + tokenBreakdown: { + groups: [ + { type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 6000 }, + { type: 'TOKEN_TYPE_TOOLS', numTokens: 7000 }, + { type: 'TOKEN_TYPE_SKILLS', numTokens: 1500 }, + { type: 'TOKEN_TYPE_USER_RULES', numTokens: 2000 }, + { type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 15000 }, + ], + }, + }, + }, + }, + }, + ], + }, + }; + const liveSum = { + annotations: { title: 'Live Undo Session' }, + stepCount: 3, + lastModifiedTime: iso(22), + status: 'IDLE', + }; + const h3 = backendHarness({ + trajectories: { 'conv-live-undo': liveTraj }, + summaries: { 'conv-live-undo': liveSum }, + }); + const beforeUndo = await h3.buildTelemetryPayloadInternal('conv-live-undo'); + assert.equal(beforeUndo.activeConversation.context.totalTokens, 32300); + + // User clicks Confirm Undo back to step 2 -> step3 and its full gen_metadata[2] are deleted! + liveTraj.trajectory.steps = [step1, step2]; + liveTraj.trajectory.generatorMetadata = liveTraj.trajectory.generatorMetadata.slice(0, 2); + liveSum.stepCount = 2; + liveSum.lastModifiedTime = iso(30); + + const afterUndo = await h3.buildTelemetryPayloadInternal('conv-live-undo'); + const ctx3 = afterUndo.activeConversation.context; + assert.equal(ctx3.totalTokens, 27500); + assert.equal(ctx3.systemPromptTokens, 6000); + assert.equal(ctx3.systemToolsTokens, 7000); + assert.equal(ctx3.skillsTokens, 1500); + assert.equal(ctx3.userRulesTokens, 2000); + assert.equal(ctx3.assistantTokens, 2500); + assert.equal(ctx3.toolResultsTokens, 5000); + assert.equal(ctx3.userInputTokens, 3500); + assert.equal( + ctx3.userInputTokens + + ctx3.assistantTokens + + ctx3.toolResultsTokens + + ctx3.subagentTokens + + ctx3.checkpointTokens + + ctx3.systemToolsTokens + + ctx3.mcpToolsTokens + + ctx3.skillsTokens + + ctx3.systemPromptTokens + + ctx3.userRulesTokens, + 27500 + ); + + // Case 4: Cold start on an already-undone session with zero breakdowns and no compaction still populates channels (never all-0) + const h4 = backendHarness({ + trajectories: { + 'conv-cold-undo': { + trajectory: { + steps: [step1, step2], + generatorMetadata: [ + { stepIndices: [1], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 20000, maxContextTokens: 256000 } } } }, + { stepIndices: [3], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 26000, maxContextTokens: 256000 } } } }, + ], + }, + }, + }, + summaries: { + 'conv-cold-undo': { + annotations: { title: 'Cold Undo Session' }, + stepCount: 2, + lastModifiedTime: iso(12), + status: 'IDLE', + }, + }, + }); + const coldPayload = await h4.buildTelemetryPayloadInternal('conv-cold-undo'); + const ctx4 = coldPayload.activeConversation.context; + assert.equal(ctx4.totalTokens, 27500); + assert.equal(ctx4.assistantTokens, 2500); + assert.equal(ctx4.toolResultsTokens, 5000); + assert.equal(ctx4.userInputTokens, 20000); + assert.equal(ctx4.userInputTokens + ctx4.assistantTokens + ctx4.toolResultsTokens, 27500); +}); diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index 7c28e39..f921549 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -902,6 +902,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { }; let latestBreakdownChat = null; let latestBreakdownStepIdx = -1; + let latestBreakdownUnindexed = false; + let lastKnownGmStepIdx = -1; for (const gm of generatorMetadata || []) { collectOrchestratorExecModel(gm?.plannerConfig); @@ -916,9 +918,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { gmMaxIdx = numIdx; } } + if (gmMaxIdx >= 0) { + lastKnownGmStepIdx = Math.max(lastKnownGmStepIdx, gmMaxIdx); + } if (extractContextBreakdown(gm.chatModel)) { latestBreakdownChat = gm.chatModel; - latestBreakdownStepIdx = gmMaxIdx; + latestBreakdownStepIdx = gmMaxIdx >= 0 ? gmMaxIdx : lastKnownGmStepIdx; + latestBreakdownUnindexed = gmMaxIdx < 0; } } @@ -1401,26 +1407,61 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { } } - // 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐 - if ( - result.length > 0 && - !result[result.length - 1].isCompactionStep && - !result[result.length - 1].contextBreakdown && - latestBreakdownChat && - (lastCompactionStepIdx < 0 || latestBreakdownStepIdx > lastCompactionStepIdx) - ) { + // 末尾步骤上下文回填: + // 1. 末尾为普通步骤且缺少 contextBreakdown 时,只要最近有效 generatorMetadata 未跨过压缩边界即可补齐 + // (含回退/中断后末尾 `stepIndices: []` 沿前序位置继承的拆解;若未索引拆解规模显著高于当前步则跳过,避免放大已回退水位); + // 2. 末尾为压缩步骤且其前序压缩前锚点步骤缺少 contextBreakdown(常见于末尾 `stepIndices: []`)时,回填到该压缩前步骤, + // 确保压缩后仍可继承 5 个静态上下文通道(绝不直接写到压缩步自身)。 + if (result.length > 0 && latestBreakdownChat) { + const applyFallbackBreakdown = (targetStep) => { + const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat); + if (!fallbackBreakdown) return; + const targetPrompt = + Number(targetStep?.inputTokens || 0) + Number(targetStep?.cacheReadTokens || 0); + const bdTotal = Number(fallbackBreakdown.totalTokens || 0); + if ( + latestBreakdownUnindexed && + targetPrompt > 0 && + bdTotal > 0 && + targetPrompt < bdTotal * 0.5 + ) { + return; + } + const fallbackCtx = + latestBreakdownChat?.chatStartMetadata?.contextWindowMetadata; + targetStep.contextBreakdown = fallbackBreakdown; + if (!targetStep.estimatedContextTokens) { + targetStep.estimatedContextTokens = Number( + fallbackCtx?.estimatedTokensUsed || fallbackBreakdown?.totalTokens || 0 + ); + } + if (fallbackCtx?.maxContextTokens) { + targetStep.maxContextBudgetTokens = Number(fallbackCtx.maxContextTokens); + if (!targetStep.reportedContextLimitTokens) { + targetStep.reportedContextLimitTokens = Number(fallbackCtx.maxContextTokens); + } + } + }; + const lastStep = result[result.length - 1]; - const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat); - const fallbackCtx = - latestBreakdownChat?.chatStartMetadata?.contextWindowMetadata; - lastStep.contextBreakdown = fallbackBreakdown; - if (!lastStep.estimatedContextTokens) { - lastStep.estimatedContextTokens = Number( - fallbackCtx?.estimatedTokensUsed || fallbackBreakdown?.totalTokens || 0 - ); - } - if (fallbackCtx?.maxContextTokens) { - lastStep.maxContextBudgetTokens = Number(fallbackCtx.maxContextTokens); + if ( + !lastStep.isCompactionStep && + !lastStep.contextBreakdown && + (lastCompactionStepIdx < 0 || latestBreakdownStepIdx > lastCompactionStepIdx) + ) { + applyFallbackBreakdown(lastStep); + } else if ( + lastStep.isCompactionStep && + (latestBreakdownStepIdx < 0 || latestBreakdownStepIdx <= lastCompactionStepIdx) + ) { + for (let i = result.length - 2; i >= 0; i -= 1) { + const preStep = result[i]; + if (!preStep || preStep.isCompactionStep) break; + if (!preStep.contextBreakdown) { + applyFallbackBreakdown(preStep); + } + break; + } } } From 49e346c0ca4b342dee995c409b85e9813fe46378 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 02:59:32 +0900 Subject: [PATCH 05/30] fix(panel): eliminate hover flicker in monthly chart and breakdown rows - Replace the 3px .monthly-grid column gap with zero-gap column padding and hand off hover across adjacent active months without hiding or restarting the popover fade-in - Wrap the progress bar and model-name footer inside a single .cons-source-hover-zone across client sources, project ranking, and session ranking so crossing the vertical gap keeps the popover and highlight steady --- sidecars/panel/app.js | 240 +++++++++++------- sidecars/panel/index.html | 4 +- sidecars/panel/src/styles/modern-ui.css | 2 + .../panel/src/styles/views-consumption.css | 34 ++- sidecars/panel/src/views/ConsumptionView.js | 240 +++++++++++------- sidecars/panel/styles.css | 36 ++- sidecars/panel/test/consumption-bars.test.mjs | 30 ++- 7 files changed, 373 insertions(+), 213 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 4fcac35..2a1d626 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -29873,6 +29873,7 @@ const ConsumptionView = defineComponent({ }); let activeHoverTargetEl = null; + let activeHoverPayload = null; let cachedBreakdownRootRect = null; let cachedBreakdownAnchorRect = null; @@ -29889,6 +29890,7 @@ const ConsumptionView = defineComponent({ function hideBreakdownPopover() { cachedBreakdownRootRect = null; cachedBreakdownAnchorRect = null; + activeHoverPayload = null; if (activeHoverTargetEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); activeHoverTargetEl = null; @@ -29964,6 +29966,9 @@ const ConsumptionView = defineComponent({ hideBreakdownPopover(); return; } + const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); + const sameTargetAndPayload = + !wasHidden && activeHoverTargetEl === anchorEl && activeHoverPayload === payload; if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); cachedBreakdownAnchorRect = null; @@ -29972,22 +29977,24 @@ const ConsumptionView = defineComponent({ cachedBreakdownAnchorRect = null; } activeHoverTargetEl = anchorEl; + activeHoverPayload = payload; patchClasses(anchorEl, { 'is-hovered': true }); - popoverContent.update({ - title: payload.title || '—', - calls: payload.calls || 0, - totalTokens: payload.totalTokens || 0, - costText: payload.costText || '$0.00', - inputTokens: payload.inputTokens, - cacheReadTokens: payload.cacheReadTokens, - thinkingTokens: payload.thinkingTokens, - responseTokens: payload.responseTokens, - outputTokens: payload.outputTokens, - segments: Array.isArray(payload.segments) ? payload.segments : [], - }); + if (!sameTargetAndPayload) { + popoverContent.update({ + title: payload.title || '—', + calls: payload.calls || 0, + totalTokens: payload.totalTokens || 0, + costText: payload.costText || '$0.00', + inputTokens: payload.inputTokens, + cacheReadTokens: payload.cacheReadTokens, + thinkingTokens: payload.thinkingTokens, + responseTokens: payload.responseTokens, + outputTokens: payload.outputTokens, + segments: Array.isArray(payload.segments) ? payload.segments : [], + }); + } - const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); patchAttr(breakdownPopoverEl, 'hidden', false); positionBreakdownPopover(anchorEl, pointerClientX, pointerClientY); if (wasHidden) { @@ -30010,6 +30017,19 @@ const ConsumptionView = defineComponent({ return { el: segEl, refs: { segEl } }; } + let monthlyGridEl = null; + const monthlyColByEl = new Map(); + + function findMonthlyColForNode(node) { + let cur = node; + while (cur && cur !== monthlyGridEl) { + const hit = monthlyColByEl.get(cur); + if (hit) return hit; + cur = cur.parentNode || null; + } + return null; + } + const monthlyCols = Array.from({ length: 12 }, (_, idx) => { const costText = h('span', { className: 'month-cost text-mono', text: '' }); const stackWrap = h('div', { className: 'month-stack' }); @@ -30036,6 +30056,9 @@ const ConsumptionView = defineComponent({ e?.clientY ?? null ); } else { + if (activeHoverTargetEl && monthlyColByEl.has(activeHoverTargetEl)) { + hideBreakdownPopover(); + } e?.stopPropagation?.(); } }, @@ -30044,8 +30067,16 @@ const ConsumptionView = defineComponent({ positionBreakdownPopover(colEl, e?.clientX ?? null, e?.clientY ?? null); } }, - onMouseLeave: () => { - if (activeHoverTargetEl === colEl) hideBreakdownPopover(); + onMouseLeave: (e) => { + if (activeHoverTargetEl !== colEl) return; + const nextEl = e?.relatedTarget || null; + if (nextEl) { + const nextCol = findMonthlyColForNode(nextEl); + if ((nextCol && nextCol.colState.hoverPayload) || nextEl === monthlyGridEl) { + return; + } + } + hideBreakdownPopover(); }, }, [ @@ -30055,7 +30086,7 @@ const ConsumptionView = defineComponent({ tokText, ] ); - return { + const colRec = { el: colEl, costText, stackWrap, @@ -30064,8 +30095,23 @@ const ConsumptionView = defineComponent({ tokText, colState, }; + monthlyColByEl.set(colEl, colRec); + return colRec; }); + monthlyGridEl = h( + 'div', + { + className: 'monthly-grid', + onMouseLeave: () => { + if (activeHoverTargetEl && monthlyColByEl.has(activeHoverTargetEl)) { + hideBreakdownPopover(); + } + }, + }, + monthlyCols.map((c) => c.el) + ); + const monthlyPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -30074,11 +30120,7 @@ const ConsumptionView = defineComponent({ ]), monthlyHoverHint, ]), - h( - 'div', - { className: 'monthly-grid' }, - monthlyCols.map((c) => c.el) - ), + monthlyGridEl, ]); const scrollInner = h( @@ -30567,6 +30609,54 @@ const ConsumptionView = defineComponent({ /** * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。 */ + function isNodeInside(root, node) { + if (!root || !node) return false; + if (typeof root.contains === 'function') return root.contains(node); + let cur = node; + while (cur) { + if (cur === root) return true; + cur = cur.parentNode || null; + } + return false; + } + + function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) { + zoneEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { + positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mouseleave', () => { + if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); + }); + + for (const childEl of compatTargets) { + if (!childEl) continue; + childEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { + positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mouseleave', (e) => { + const nextEl = e?.relatedTarget || null; + if (isNodeInside(zoneEl, nextEl)) { + return; + } + if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); + }); + } + } + function createSourceBreakdownRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); @@ -30575,26 +30665,7 @@ const ConsumptionView = defineComponent({ const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { hoverPayload: null }; - const bindPopoverHover = (targetEl) => ({ - onMouseEnter: (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover( - targetEl, - rowState.hoverPayload, - e?.clientX ?? null, - e?.clientY ?? null - ); - } - }, - onMouseMove: (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === targetEl) { - positionBreakdownPopover(targetEl, e?.clientX ?? null, e?.clientY ?? null); - } - }, - onMouseLeave: () => { - if (activeHoverTargetEl === targetEl) hideBreakdownPopover(); - }, - }); + const barHitEl = h( 'div', { @@ -30602,20 +30673,23 @@ const ConsumptionView = defineComponent({ }, [trackEl] ); - const barHandlers = bindPopoverHover(barHitEl); - barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter); - barHitEl.addEventListener('mousemove', barHandlers.onMouseMove); - barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - const topHandlers = bindPopoverHover(topModelsEl); - topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter); - topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove); - topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave); const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + h('span', { className: 'legend-left cons-calls-stat' }, [ + callsLbl, + callsVal, + ]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ h('div', { className: 'panel-header' }, [ nameEl, @@ -30625,14 +30699,7 @@ const ConsumptionView = defineComponent({ costEl, ]), ]), - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), + hoverZoneEl, ]); return { @@ -30643,6 +30710,7 @@ const ConsumptionView = defineComponent({ pctBadge, totalTokEl, costEl, + hoverZoneEl, barHitEl, trackEl, topModelsEl, @@ -30746,6 +30814,7 @@ const ConsumptionView = defineComponent({ segments: partitioned, } : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); } function createTopConversationRow() { @@ -30761,43 +30830,26 @@ const ConsumptionView = defineComponent({ const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { cascadeId: '', canJump: false, hoverPayload: null }; - const bindPopoverHover = (targetEl) => ({ - onMouseEnter: (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover( - targetEl, - rowState.hoverPayload, - e?.clientX ?? null, - e?.clientY ?? null - ); - } - }, - onMouseMove: (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === targetEl) { - positionBreakdownPopover(targetEl, e?.clientX ?? null, e?.clientY ?? null); - } - }, - onMouseLeave: () => { - if (activeHoverTargetEl === targetEl) hideBreakdownPopover(); - }, - }); - const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); - const barHandlers = bindPopoverHover(barHitEl); - barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter); - barHitEl.addEventListener('mousemove', barHandlers.onMouseMove); - barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - const topHandlers = bindPopoverHover(topModelsEl); - topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter); - topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove); - topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave); const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true }); const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + fallbackMetaEl, + h('span', { className: 'legend-left cons-calls-stat' }, [ + callsLbl, + callsVal, + ]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + const rowEl = h( 'div', { @@ -30825,15 +30877,7 @@ const ConsumptionView = defineComponent({ costEl, ]), ]), - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - fallbackMetaEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), + hoverZoneEl, ] ); @@ -30847,6 +30891,7 @@ const ConsumptionView = defineComponent({ pctBadge, totalTokEl, costEl, + hoverZoneEl, barHitEl, trackEl, topModelsEl, @@ -31004,6 +31049,7 @@ const ConsumptionView = defineComponent({ segments: partitioned, } : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); } let latestSlice = null; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index c660904..ce16eb4 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index db02513..16b07de 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -479,6 +479,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border-top-color: color-mix(in srgb, var(--text-primary) 8%, transparent); } +[data-modern-ui="true"] .cons-source-hover-zone.is-interactive:hover .cons-source-model-bar, +[data-modern-ui="true"] .cons-source-hover-zone.is-hovered .cons-source-model-bar, [data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, [data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar, [data-modern-ui="true"] .month-col.is-interactive:hover .month-stack, diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 47ac6bb..3fdd144 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -891,12 +891,27 @@ container-type: inline-size; } -.cons-source-bar-hit { - padding: 5px 0; - margin: -5px 0; +.cons-source-hover-zone { + display: flex; + flex-direction: column; + gap: 5px; + padding: 4px 0 2px; + margin: -4px 0 -2px; + min-width: 0; +} + +.cons-source-hover-zone.is-interactive { cursor: pointer; } +.cons-source-bar-hit { + padding: 0; + margin: 0; + cursor: inherit; +} + +.cons-source-hover-zone.is-interactive:hover .cons-source-model-bar, +.cons-source-hover-zone.is-hovered .cons-source-model-bar, .cons-source-bar-hit:hover .cons-source-model-bar, .cons-source-bar-hit.is-hovered .cons-source-model-bar { box-shadow: 0 0 0 1px var(--border-strong); @@ -959,6 +974,8 @@ transition: color 120ms ease; } +.cons-source-hover-zone.is-interactive:hover .cons-source-top-name, +.cons-source-hover-zone.is-hovered .cons-source-top-name, .cons-source-top-models:hover .cons-source-top-name, .cons-source-top-models.is-hovered .cons-source-top-name { color: var(--text-primary); @@ -1236,17 +1253,20 @@ /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ .monthly-grid { display: grid; - grid-template-columns: repeat(12, 1fr); - gap: 3px; - align-items: end; - padding-top: var(--space-2); + grid-template-columns: repeat(12, minmax(0, 1fr)); + gap: 0; + align-items: stretch; + margin: var(--space-2) -1.5px 0; } .month-col { display: flex; flex-direction: column; align-items: center; + justify-content: flex-end; gap: 3px; + padding: 0 1.5px; + box-sizing: border-box; min-width: 0; } diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 383e6f7..967f104 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -538,6 +538,7 @@ export const ConsumptionView = defineComponent({ }); let activeHoverTargetEl = null; + let activeHoverPayload = null; let cachedBreakdownRootRect = null; let cachedBreakdownAnchorRect = null; @@ -554,6 +555,7 @@ export const ConsumptionView = defineComponent({ function hideBreakdownPopover() { cachedBreakdownRootRect = null; cachedBreakdownAnchorRect = null; + activeHoverPayload = null; if (activeHoverTargetEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); activeHoverTargetEl = null; @@ -629,6 +631,9 @@ export const ConsumptionView = defineComponent({ hideBreakdownPopover(); return; } + const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); + const sameTargetAndPayload = + !wasHidden && activeHoverTargetEl === anchorEl && activeHoverPayload === payload; if (activeHoverTargetEl && activeHoverTargetEl !== anchorEl) { patchClasses(activeHoverTargetEl, { 'is-hovered': false }); cachedBreakdownAnchorRect = null; @@ -637,22 +642,24 @@ export const ConsumptionView = defineComponent({ cachedBreakdownAnchorRect = null; } activeHoverTargetEl = anchorEl; + activeHoverPayload = payload; patchClasses(anchorEl, { 'is-hovered': true }); - popoverContent.update({ - title: payload.title || '—', - calls: payload.calls || 0, - totalTokens: payload.totalTokens || 0, - costText: payload.costText || '$0.00', - inputTokens: payload.inputTokens, - cacheReadTokens: payload.cacheReadTokens, - thinkingTokens: payload.thinkingTokens, - responseTokens: payload.responseTokens, - outputTokens: payload.outputTokens, - segments: Array.isArray(payload.segments) ? payload.segments : [], - }); + if (!sameTargetAndPayload) { + popoverContent.update({ + title: payload.title || '—', + calls: payload.calls || 0, + totalTokens: payload.totalTokens || 0, + costText: payload.costText || '$0.00', + inputTokens: payload.inputTokens, + cacheReadTokens: payload.cacheReadTokens, + thinkingTokens: payload.thinkingTokens, + responseTokens: payload.responseTokens, + outputTokens: payload.outputTokens, + segments: Array.isArray(payload.segments) ? payload.segments : [], + }); + } - const wasHidden = breakdownPopoverEl.hasAttribute('hidden'); patchAttr(breakdownPopoverEl, 'hidden', false); positionBreakdownPopover(anchorEl, pointerClientX, pointerClientY); if (wasHidden) { @@ -675,6 +682,19 @@ export const ConsumptionView = defineComponent({ return { el: segEl, refs: { segEl } }; } + let monthlyGridEl = null; + const monthlyColByEl = new Map(); + + function findMonthlyColForNode(node) { + let cur = node; + while (cur && cur !== monthlyGridEl) { + const hit = monthlyColByEl.get(cur); + if (hit) return hit; + cur = cur.parentNode || null; + } + return null; + } + const monthlyCols = Array.from({ length: 12 }, (_, idx) => { const costText = h('span', { className: 'month-cost text-mono', text: '' }); const stackWrap = h('div', { className: 'month-stack' }); @@ -701,6 +721,9 @@ export const ConsumptionView = defineComponent({ e?.clientY ?? null ); } else { + if (activeHoverTargetEl && monthlyColByEl.has(activeHoverTargetEl)) { + hideBreakdownPopover(); + } e?.stopPropagation?.(); } }, @@ -709,8 +732,16 @@ export const ConsumptionView = defineComponent({ positionBreakdownPopover(colEl, e?.clientX ?? null, e?.clientY ?? null); } }, - onMouseLeave: () => { - if (activeHoverTargetEl === colEl) hideBreakdownPopover(); + onMouseLeave: (e) => { + if (activeHoverTargetEl !== colEl) return; + const nextEl = e?.relatedTarget || null; + if (nextEl) { + const nextCol = findMonthlyColForNode(nextEl); + if ((nextCol && nextCol.colState.hoverPayload) || nextEl === monthlyGridEl) { + return; + } + } + hideBreakdownPopover(); }, }, [ @@ -720,7 +751,7 @@ export const ConsumptionView = defineComponent({ tokText, ] ); - return { + const colRec = { el: colEl, costText, stackWrap, @@ -729,8 +760,23 @@ export const ConsumptionView = defineComponent({ tokText, colState, }; + monthlyColByEl.set(colEl, colRec); + return colRec; }); + monthlyGridEl = h( + 'div', + { + className: 'monthly-grid', + onMouseLeave: () => { + if (activeHoverTargetEl && monthlyColByEl.has(activeHoverTargetEl)) { + hideBreakdownPopover(); + } + }, + }, + monthlyCols.map((c) => c.el) + ); + const monthlyPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -739,11 +785,7 @@ export const ConsumptionView = defineComponent({ ]), monthlyHoverHint, ]), - h( - 'div', - { className: 'monthly-grid' }, - monthlyCols.map((c) => c.el) - ), + monthlyGridEl, ]); const scrollInner = h( @@ -1232,6 +1274,54 @@ export const ConsumptionView = defineComponent({ /** * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。 */ + function isNodeInside(root, node) { + if (!root || !node) return false; + if (typeof root.contains === 'function') return root.contains(node); + let cur = node; + while (cur) { + if (cur === root) return true; + cur = cur.parentNode || null; + } + return false; + } + + function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) { + zoneEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { + positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mouseleave', () => { + if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); + }); + + for (const childEl of compatTargets) { + if (!childEl) continue; + childEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { + positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mouseleave', (e) => { + const nextEl = e?.relatedTarget || null; + if (isNodeInside(zoneEl, nextEl)) { + return; + } + if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); + }); + } + } + function createSourceBreakdownRow() { const nameTextEl = h('span', { className: 'cons-row-title-text' }); const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); @@ -1240,26 +1330,7 @@ export const ConsumptionView = defineComponent({ const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { hoverPayload: null }; - const bindPopoverHover = (targetEl) => ({ - onMouseEnter: (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover( - targetEl, - rowState.hoverPayload, - e?.clientX ?? null, - e?.clientY ?? null - ); - } - }, - onMouseMove: (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === targetEl) { - positionBreakdownPopover(targetEl, e?.clientX ?? null, e?.clientY ?? null); - } - }, - onMouseLeave: () => { - if (activeHoverTargetEl === targetEl) hideBreakdownPopover(); - }, - }); + const barHitEl = h( 'div', { @@ -1267,20 +1338,23 @@ export const ConsumptionView = defineComponent({ }, [trackEl] ); - const barHandlers = bindPopoverHover(barHitEl); - barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter); - barHitEl.addEventListener('mousemove', barHandlers.onMouseMove); - barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - const topHandlers = bindPopoverHover(topModelsEl); - topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter); - topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove); - topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave); const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + h('span', { className: 'legend-left cons-calls-stat' }, [ + callsLbl, + callsVal, + ]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ h('div', { className: 'panel-header' }, [ nameEl, @@ -1290,14 +1364,7 @@ export const ConsumptionView = defineComponent({ costEl, ]), ]), - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), + hoverZoneEl, ]); return { @@ -1308,6 +1375,7 @@ export const ConsumptionView = defineComponent({ pctBadge, totalTokEl, costEl, + hoverZoneEl, barHitEl, trackEl, topModelsEl, @@ -1411,6 +1479,7 @@ export const ConsumptionView = defineComponent({ segments: partitioned, } : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); } function createTopConversationRow() { @@ -1426,43 +1495,26 @@ export const ConsumptionView = defineComponent({ const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); const rowState = { cascadeId: '', canJump: false, hoverPayload: null }; - const bindPopoverHover = (targetEl) => ({ - onMouseEnter: (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover( - targetEl, - rowState.hoverPayload, - e?.clientX ?? null, - e?.clientY ?? null - ); - } - }, - onMouseMove: (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === targetEl) { - positionBreakdownPopover(targetEl, e?.clientX ?? null, e?.clientY ?? null); - } - }, - onMouseLeave: () => { - if (activeHoverTargetEl === targetEl) hideBreakdownPopover(); - }, - }); - const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); - const barHandlers = bindPopoverHover(barHitEl); - barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter); - barHitEl.addEventListener('mousemove', barHandlers.onMouseMove); - barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - const topHandlers = bindPopoverHover(topModelsEl); - topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter); - topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove); - topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave); const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true }); const callsLbl = h('span', { text: t('cons.footCalls') }); const callsVal = h('strong', { className: 'text-mono' }); + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + fallbackMetaEl, + h('span', { className: 'legend-left cons-calls-stat' }, [ + callsLbl, + callsVal, + ]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + const rowEl = h( 'div', { @@ -1490,15 +1542,7 @@ export const ConsumptionView = defineComponent({ costEl, ]), ]), - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - fallbackMetaEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), + hoverZoneEl, ] ); @@ -1512,6 +1556,7 @@ export const ConsumptionView = defineComponent({ pctBadge, totalTokEl, costEl, + hoverZoneEl, barHitEl, trackEl, topModelsEl, @@ -1669,6 +1714,7 @@ export const ConsumptionView = defineComponent({ segments: partitioned, } : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); } let latestSlice = null; diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 3419c81..061bf4d 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -3696,12 +3696,27 @@ html[data-standalone="true"] .app-shell { container-type: inline-size; } -.cons-source-bar-hit { - padding: 5px 0; - margin: -5px 0; +.cons-source-hover-zone { + display: flex; + flex-direction: column; + gap: 5px; + padding: 4px 0 2px; + margin: -4px 0 -2px; + min-width: 0; +} + +.cons-source-hover-zone.is-interactive { cursor: pointer; } +.cons-source-bar-hit { + padding: 0; + margin: 0; + cursor: inherit; +} + +.cons-source-hover-zone.is-interactive:hover .cons-source-model-bar, +.cons-source-hover-zone.is-hovered .cons-source-model-bar, .cons-source-bar-hit:hover .cons-source-model-bar, .cons-source-bar-hit.is-hovered .cons-source-model-bar { box-shadow: 0 0 0 1px var(--border-strong); @@ -3764,6 +3779,8 @@ html[data-standalone="true"] .app-shell { transition: color 120ms ease; } +.cons-source-hover-zone.is-interactive:hover .cons-source-top-name, +.cons-source-hover-zone.is-hovered .cons-source-top-name, .cons-source-top-models:hover .cons-source-top-name, .cons-source-top-models.is-hovered .cons-source-top-name { color: var(--text-primary); @@ -4041,17 +4058,20 @@ html[data-standalone="true"] .app-shell { /* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */ .monthly-grid { display: grid; - grid-template-columns: repeat(12, 1fr); - gap: 3px; - align-items: end; - padding-top: var(--space-2); + grid-template-columns: repeat(12, minmax(0, 1fr)); + gap: 0; + align-items: stretch; + margin: var(--space-2) -1.5px 0; } .month-col { display: flex; flex-direction: column; align-items: center; + justify-content: flex-end; gap: 3px; + padding: 0 1.5px; + box-sizing: border-box; min-width: 0; } @@ -8303,6 +8323,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border-top-color: color-mix(in srgb, var(--text-primary) 8%, transparent); } +[data-modern-ui="true"] .cons-source-hover-zone.is-interactive:hover .cons-source-model-bar, +[data-modern-ui="true"] .cons-source-hover-zone.is-hovered .cons-source-model-bar, [data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar, [data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar, [data-modern-ui="true"] .month-col.is-interactive:hover .month-stack, diff --git a/sidecars/panel/test/consumption-bars.test.mjs b/sidecars/panel/test/consumption-bars.test.mjs index 31e6d32..54042c6 100644 --- a/sidecars/panel/test/consumption-bars.test.mjs +++ b/sidecars/panel/test/consumption-bars.test.mjs @@ -486,25 +486,39 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources ['输入', '缓存', '思考', '输出'] ); + const appHoverZone = sourceRows[0].querySelector('.cons-source-hover-zone'); + const appTopModelsEl = sourceRows[0].querySelector('.cons-source-top-models'); + assert.ok(appHoverZone, 'Client source row should wrap bar and top models in a unified hover zone'); + + // Moving seamlessly from progress bar into gap / top-models keeps popover visible without flicker + appBarHit.dispatchEvent({ type: 'mouseleave', relatedTarget: appHoverZone }); + assert.equal(popover.hasAttribute('hidden'), false, 'Moving into unified hover zone gap must not hide popover'); + appBarHit.dispatchEvent({ type: 'mouseleave', relatedTarget: appTopModelsEl }); + assert.equal(popover.hasAttribute('hidden'), false, 'Moving from bar to model names must not hide popover'); + appBarHit.dispatchEvent({ type: 'mouseleave' }); assert.equal(popover.hasAttribute('hidden'), true); - const appTopModelsEl = sourceRows[0].querySelector('.cons-source-top-models'); appTopModelsEl.dispatchEvent({ type: 'mouseenter', clientX: 90 }); assert.equal(popover.hasAttribute('hidden'), false); assert.equal(popover.querySelector('.trend-tip-time')?.textContent, 'Antigravity App'); - appTopModelsEl.dispatchEvent({ type: 'mouseleave' }); + appTopModelsEl.dispatchEvent({ type: 'mouseleave', relatedTarget: appBarHit }); + assert.equal(popover.hasAttribute('hidden'), false, 'Moving back from model names to bar must not hide popover'); + appHoverZone.dispatchEvent({ type: 'mouseleave' }); assert.equal(popover.hasAttribute('hidden'), true); - // Verify single-line non-wrapping CSS rules exist for client source top models + // Verify single-line non-wrapping CSS rules and zero-gap hover layout rules const { readFileSync } = await import('node:fs'); const consCss = readFileSync(new URL('../src/styles/views-consumption.css', import.meta.url), 'utf8'); + assert.match(consCss, /\.cons-source-hover-zone\s*\{[\s\S]*flex-direction:\s*column/); assert.match(consCss, /\.cons-source-foot\s*\{[\s\S]*flex-wrap:\s*nowrap/); assert.match(consCss, /\.cons-source-top-models\s*\{[\s\S]*flex-wrap:\s*nowrap/); assert.match(consCss, /@container\s*\(max-width:\s*340px\)\s*\{\s*\.cons-source-top-item:nth-child\(n\s*\+\s*3\)/); + assert.match(consCss, /\.monthly-grid\s*\{[\s\S]*gap:\s*0/); // 3. Monthly Breakdown: old 4-channel legend removed; Nov column renders model-colored vertical segments & unified hover popover assert.equal(view.el.querySelectorAll('.monthly-legend').length, 0); + const monthlyGrid = view.el.querySelector('.monthly-grid'); const monthCols = view.el.querySelectorAll('.month-col'); const novCol = monthCols[10]; const novSegs = novCol.querySelectorAll('.month-seg.cons-model-seg'); @@ -520,6 +534,16 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources assert.equal(popover.querySelectorAll('.cons-pop-model-row').length, 4); assert.equal(popover.querySelector('.cons-pop-channels')?.hasAttribute('hidden'), false); + // Seam/sibling handoff inside monthly-grid keeps popover open; empty month or exiting grid hides it + novCol.dispatchEvent({ type: 'mouseleave', relatedTarget: monthlyGrid }); + assert.equal(popover.hasAttribute('hidden'), false, 'Sub-pixel seam inside monthly-grid must not flicker popover'); + monthCols[0].dispatchEvent({ type: 'mouseenter' }); + assert.equal(popover.hasAttribute('hidden'), true, 'Hovering zero-data month must hide popover'); + novCol.dispatchEvent({ type: 'mouseenter' }); + assert.equal(popover.hasAttribute('hidden'), false); + monthlyGrid.dispatchEvent({ type: 'mouseleave' }); + assert.equal(popover.hasAttribute('hidden'), true, 'Leaving monthly-grid must hide popover'); + // 4. Usage Trend: taller 184px viewBox & hovering x-axis tick opens redesigned tooltip (hero TOKEN, 4-seg model bars, no subtitle/dot clutter, bottom 4 channels) const trendSvg = view.el.querySelector('.trend-svg'); assert.match(trendSvg?.getAttribute('viewBox') || '', /\s184$/); From 49fe0b34572a02fb8f8028c4a9e2d03d17148a78 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 03:05:10 +0900 Subject: [PATCH 06/30] fix(panel): disable click-to-jump on project ranking rows --- sidecars/panel/app.js | 18 +++++++++--------- sidecars/panel/index.html | 4 ++-- sidecars/panel/src/i18n/en-US.js | 1 - sidecars/panel/src/i18n/zh-CN.js | 1 - sidecars/panel/src/views/ConsumptionView.js | 16 +++++++++------- .../panel/test/practical-enhancements.test.mjs | 9 ++++++--- 6 files changed, 26 insertions(+), 23 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 2a1d626..15ee1f7 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1546,7 +1546,6 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.rankTabWorkspacesCount': '项目排行 ({count})', 'cons.workspaceUnbound': '未绑定工作区', 'cons.workspaceSessions': '{count} 会话', - 'cons.workspaceJumpTip': '点击跳转到该项目最近会话', 'cons.exportMenuAria': '导出及报告选项', 'cons.exportXlsx': '导出 Excel (.xlsx)', 'cons.exportXlsxTip': '导出多工作表排版精美的 Excel 报表(自动列宽、千分位及对齐)', @@ -2440,7 +2439,6 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.rankTabWorkspacesCount': 'Projects ({count})', 'cons.workspaceUnbound': 'Unbound Workspace', 'cons.workspaceSessions': '{count} sessions', - 'cons.workspaceJumpTip': 'Click to inspect latest session in this project', 'cons.exportMenuAria': 'Export and report actions', 'cons.exportXlsx': 'Export Excel (.xlsx)', 'cons.exportXlsxTip': 'Export styled multi-sheet Excel workbook with auto column width and alignment', @@ -30855,7 +30853,7 @@ const ConsumptionView = defineComponent({ { className: 'cons-top-conv-row', onClick: () => { - if (!rowState.cascadeId) return; + if (!rowState.canJump || !rowState.cascadeId) return; hideBreakdownPopover(); selectConversation(rowState.cascadeId); uiStore.setState({ @@ -30911,10 +30909,9 @@ const ConsumptionView = defineComponent({ ? t('cons.workspaceUnbound') : String(item.label || item.workspacePath || '—').trim() : String(item.title || item.cascadeId || '—').trim(); - refs.rowState.cascadeId = String( - isWorkspaceRow ? item.latestCascadeId || '' : item.cascadeId || '' - ); - refs.rowState.canJump = item.canJump !== false && Boolean(refs.rowState.cascadeId); + refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || ''); + refs.rowState.canJump = + !isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId); patchClasses(refs.rowEl, { 'is-jumpable': refs.rowState.canJump, 'cons-workspace-row': isWorkspaceRow, @@ -30923,8 +30920,11 @@ const ConsumptionView = defineComponent({ isWorkspaceRow && item.workspacePath && item.workspacePath !== title ? `${title} (${item.workspacePath})` : title; - const jumpTip = isWorkspaceRow ? t('cons.workspaceJumpTip') : t('cons.topConvJumpTip'); - patchAttr(refs.rowEl, 'title', refs.rowState.canJump ? `${baseTip} — ${jumpTip}` : baseTip); + patchAttr( + refs.rowEl, + 'title', + refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip + ); patchText(refs.titleTextEl, title); if (refs.wsBadgeEl) { const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index ce16eb4..b27c977 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 8612394..4aa4ee9 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -287,7 +287,6 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.rankTabWorkspacesCount': 'Projects ({count})', 'cons.workspaceUnbound': 'Unbound Workspace', 'cons.workspaceSessions': '{count} sessions', - 'cons.workspaceJumpTip': 'Click to inspect latest session in this project', 'cons.exportMenuAria': 'Export and report actions', 'cons.exportXlsx': 'Export Excel (.xlsx)', 'cons.exportXlsxTip': 'Export styled multi-sheet Excel workbook with auto column width and alignment', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index e2481ae..ec80561 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -287,7 +287,6 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.rankTabWorkspacesCount': '项目排行 ({count})', 'cons.workspaceUnbound': '未绑定工作区', 'cons.workspaceSessions': '{count} 会话', - 'cons.workspaceJumpTip': '点击跳转到该项目最近会话', 'cons.exportMenuAria': '导出及报告选项', 'cons.exportXlsx': '导出 Excel (.xlsx)', 'cons.exportXlsxTip': '导出多工作表排版精美的 Excel 报表(自动列宽、千分位及对齐)', diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 967f104..224b73b 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -1520,7 +1520,7 @@ export const ConsumptionView = defineComponent({ { className: 'cons-top-conv-row', onClick: () => { - if (!rowState.cascadeId) return; + if (!rowState.canJump || !rowState.cascadeId) return; hideBreakdownPopover(); selectConversation(rowState.cascadeId); uiStore.setState({ @@ -1576,10 +1576,9 @@ export const ConsumptionView = defineComponent({ ? t('cons.workspaceUnbound') : String(item.label || item.workspacePath || '—').trim() : String(item.title || item.cascadeId || '—').trim(); - refs.rowState.cascadeId = String( - isWorkspaceRow ? item.latestCascadeId || '' : item.cascadeId || '' - ); - refs.rowState.canJump = item.canJump !== false && Boolean(refs.rowState.cascadeId); + refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || ''); + refs.rowState.canJump = + !isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId); patchClasses(refs.rowEl, { 'is-jumpable': refs.rowState.canJump, 'cons-workspace-row': isWorkspaceRow, @@ -1588,8 +1587,11 @@ export const ConsumptionView = defineComponent({ isWorkspaceRow && item.workspacePath && item.workspacePath !== title ? `${title} (${item.workspacePath})` : title; - const jumpTip = isWorkspaceRow ? t('cons.workspaceJumpTip') : t('cons.topConvJumpTip'); - patchAttr(refs.rowEl, 'title', refs.rowState.canJump ? `${baseTip} — ${jumpTip}` : baseTip); + patchAttr( + refs.rowEl, + 'title', + refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip + ); patchText(refs.titleTextEl, title); if (refs.wsBadgeEl) { const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0; diff --git a/sidecars/panel/test/practical-enhancements.test.mjs b/sidecars/panel/test/practical-enhancements.test.mjs index b1f3a26..bf7652b 100644 --- a/sidecars/panel/test/practical-enhancements.test.mjs +++ b/sidecars/panel/test/practical-enhancements.test.mjs @@ -1215,10 +1215,13 @@ test('Feature 9: workspace/project cost aggregation (full + fast paths) and Proj const wsRowsAfterSort = view.el.querySelectorAll('.cons-workspace-row'); assert.equal(wsRowsAfterSort[0].querySelector('.cons-row-title-text').textContent, 'docs-site'); - // Click workspace row jumps to its latest conversation in steps view + // Project rows are read-only breakdown cards and must not jump on click + assert.equal(wsRowsAfterSort[0].classList.contains('is-jumpable'), false); + const prevView = uiStore.getState().activeView; + const prevSelectedCid = telemetryStore.getState().selectedConversationId; wsRowsAfterSort[0].dispatchEvent({ type: 'click' }); - assert.equal(uiStore.getState().activeView, 'steps'); - assert.equal(telemetryStore.getState().selectedConversationId, 'ws-conv-b1'); + assert.equal(uiStore.getState().activeView, prevView); + assert.equal(telemetryStore.getState().selectedConversationId, prevSelectedCid); }); test('Feature 10: StepsDetailView live search, dynamic diagnostic chips, and click-to-inspect step drawer', async (t) => { From 7e6d11d7aa4087ec3d44846d781fd797f0e4a537 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 04:41:26 +0900 Subject: [PATCH 07/30] feat(panel): add sub-hour trend bucketing and smooth range switches - Enforce strict window bounds on usage trends without 6-hour out-of-window padding, subdividing sub-2h intraday spans into 1m, 5m, and 15m slots with stepMs cache invalidation and minute export labels - Morph SVG trend curves and areas continuously across varying slot counts via De Casteljau cubic Bezier knot subdivision, synchronized with peak pill glides, axis fades, and heatmap stage transitions - Coordinate consumption range, tab, and sort switches with opacity crossfades and @starting-style progress bar width transitions while respecting prefers-reduced-motion --- sidecars/panel/app.js | 668 ++++++++++++++++-- sidecars/panel/backend/usage-aggregator.mjs | 111 +-- sidecars/panel/index.html | 4 +- .../src/components/charts/TrendAreaChart.js | 415 ++++++++++- sidecars/panel/src/core/reportExporter.js | 22 +- sidecars/panel/src/i18n/en-US.js | 1 + sidecars/panel/src/i18n/zh-CN.js | 1 + sidecars/panel/src/store/telemetryStore.js | 2 + .../panel/src/styles/views-consumption.css | 109 ++- sidecars/panel/src/views/ConsumptionView.js | 227 ++++-- sidecars/panel/styles.css | 109 ++- sidecars/panel/test/backend.test.mjs | 121 ++++ 12 files changed, 1591 insertions(+), 199 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 15ee1f7..ee2e004 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1520,6 +1520,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.trendTitle': '用量趋势', 'cons.allTime': '全部时间', 'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看', + 'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看', 'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看', 'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看', 'cons.topModels': '模型排行', @@ -2413,6 +2414,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.trendTitle': 'Usage Trend', 'cons.allTime': 'All Time', 'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details', + 'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details', 'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details', 'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details', 'cons.topModels': 'Top Models', @@ -8025,8 +8027,11 @@ function buildConsumptionXlsx( let tTot = 0; let tCost = 0; const trendRows = trend.map((slot) => { + const isMinute = slot.granularity === 'minute'; const isHourly = - slot.granularity === 'hour' || String(slot.label || '').includes(':'); + isMinute || + slot.granularity === 'hour' || + String(slot.label || '').includes(':'); const calls = Math.max(0, Number(slot.calls || 0)); const inTok = Math.max(0, Number(slot.inputTokens || 0)); const cacheTok = Math.max(0, Number(slot.cacheReadTokens || 0)); @@ -8039,13 +8044,18 @@ function buildConsumptionXlsx( tOut += outTok; tTot += totTok; tCost += cost; - const granLabel = isHourly + const stepMins = Math.max(1, Number(slot.stepMinutes) || 5); + const granLabel = isMinute ? en - ? 'Hourly' - : '按小时' - : en - ? 'Daily' - : '按天'; + ? `${stepMins}m` + : `按 ${stepMins} 分钟` + : isHourly + ? en + ? 'Hourly' + : '按小时' + : en + ? 'Daily' + : '按天'; return [ formatTrendWindowLabel(slot, isHourly), granLabel, @@ -9779,6 +9789,8 @@ function isEquivalentTelemetry(prev, next) { pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens || pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens || pTrend[i]?.calls !== nTrend[i]?.calls || + pTrend[i]?.granularity !== nTrend[i]?.granularity || + pTrend[i]?.stepMinutes !== nTrend[i]?.stepMinutes || pTrend[i]?.label !== nTrend[i]?.label || pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || !areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models) @@ -13612,7 +13624,176 @@ function buildSmoothSplinePath(points) { } /** - * 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 + * 将采样点数组转为归一化横轴 `u` (`0..1`) 上的精确三次贝塞尔分段链, + * 控制点严格保持跟 `buildSmoothSplinePath` 一致的 `0.42` 水平张力。 + * + * @param {Array<{ y: number }>} pts + * @param {number} bottomY + * @returns {Array<{ u0: number, y0: number, cu1: number, cy1: number, cu2: number, cy2: number, u3: number, y3: number }>} + */ +function pointsToNormalizedCubicSegs(pts, bottomY) { + const n = pts.length; + if (n === 0) { + return [ + { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, + ]; + } + if (n === 1) { + const py = pts[0].y; + if (Math.abs(py - bottomY) < 0.01) { + return [ + { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, + ]; + } + return [ + { u0: 0, y0: bottomY, cu1: 0.21, cy1: bottomY, cu2: 0.29, cy2: py, u3: 0.5, y3: py }, + { u0: 0.5, y0: py, cu1: 0.71, cy1: py, cu2: 0.79, cy2: bottomY, u3: 1, y3: bottomY }, + ]; + } + const segs = new Array(n - 1); + for (let i = 0; i < n - 1; i++) { + const u0 = i / (n - 1); + const u3 = (i + 1) / (n - 1); + const du = u3 - u0; + const y0 = pts[i].y; + const y3 = pts[i + 1].y; + segs[i] = { + u0, + y0, + cu1: u0 + du * 0.42, + cy1: y0, + cu2: u3 - du * 0.42, + cy2: y3, + u3, + y3, + }; + } + return segs; +} + +function solveCubicParamForU(seg, targetU) { + if (targetU <= seg.u0) return 0; + if (targetU >= seg.u3) return 1; + let lo = 0; + let hi = 1; + for (let it = 0; it < 20; it++) { + const s = (lo + hi) * 0.5; + const inv = 1 - s; + const u = + inv * inv * inv * seg.u0 + + 3 * inv * inv * s * seg.cu1 + + 3 * inv * s * s * seg.cu2 + + s * s * s * seg.u3; + if (u < targetU) lo = s; + else hi = s; + } + return (lo + hi) * 0.5; +} + +function splitCubicAt(seg, s) { + const u01 = seg.u0 + (seg.cu1 - seg.u0) * s; + const y01 = seg.y0 + (seg.cy1 - seg.y0) * s; + const u12 = seg.cu1 + (seg.cu2 - seg.cu1) * s; + const y12 = seg.cy1 + (seg.cy2 - seg.cy1) * s; + const u23 = seg.cu2 + (seg.u3 - seg.cu2) * s; + const y23 = seg.cy2 + (seg.y3 - seg.cy2) * s; + + const u012 = u01 + (u12 - u01) * s; + const y012 = y01 + (y12 - y01) * s; + const u123 = u12 + (u23 - u12) * s; + const y123 = y12 + (y23 - y12) * s; + + const u0123 = u012 + (u123 - u012) * s; + const y0123 = y012 + (y123 - y012) * s; + + return [ + { u0: seg.u0, y0: seg.y0, cu1: u01, cy1: y01, cu2: u012, cy2: y012, u3: u0123, y3: y0123 }, + { u0: u0123, y0: y0123, cu1: u123, cy1: y123, cu2: u23, cy2: y23, u3: seg.u3, y3: seg.y3 }, + ]; +} + +function extractCubicSubsegment(seg, uStart, uEnd) { + const s0 = solveCubicParamForU(seg, uStart); + const s1 = solveCubicParamForU(seg, uEnd); + if (s0 <= 1e-7 && s1 >= 1 - 1e-7) return { ...seg }; + const [, right] = s0 <= 1e-7 ? [null, seg] : splitCubicAt(seg, s0); + const remSpan = 1 - s0; + const localS1 = remSpan > 1e-9 ? Math.min(1, Math.max(0, (s1 - s0) / remSpan)) : 1; + const [sub] = localS1 >= 1 - 1e-7 ? [right] : splitCubicAt(right, localS1); + sub.u0 = uStart; + sub.u3 = uEnd; + return sub; +} + +/** + * 合并两条贝塞尔链的断点(始终完整保留目标链 `toSegs` 全部断点,保证 `t=1` 零几何误差)。 + */ +function mergeNormalizedKnots(fromSegs, toSegs) { + const raw = [0, 1]; + for (let i = 0; i < toSegs.length; i++) raw.push(toSegs[i].u3); + if (fromSegs.length <= 64) { + for (let i = 0; i < fromSegs.length; i++) raw.push(fromSegs[i].u3); + } else { + const stride = Math.ceil(fromSegs.length / 48); + for (let i = 0; i < fromSegs.length; i += stride) raw.push(fromSegs[i].u3); + } + raw.sort((a, b) => a - b); + const uniq = [0]; + for (let i = 1; i < raw.length; i++) { + if (raw[i] - uniq[uniq.length - 1] > 1e-6) { + uniq.push(raw[i]); + } + } + uniq[uniq.length - 1] = 1; + return uniq; +} + +function subdivideChainToKnots(segs, knots) { + const out = new Array(knots.length - 1); + let j = 0; + for (let k = 0; k < knots.length - 1; k++) { + const a = knots[k]; + const b = knots[k + 1]; + const mid = (a + b) * 0.5; + while (j < segs.length - 1 && segs[j].u3 < mid) j++; + out[k] = extractCubicSubsegment(segs[j], a, b); + } + return out; +} + +function buildPathFromNormalizedSegs(segs, leftX, spanX) { + const xAt = (u) => (leftX + u * spanX).toFixed(1); + let d = `M ${xAt(segs[0].u0)} ${segs[0].y0.toFixed(1)}`; + for (let i = 0; i < segs.length; i++) { + const s = segs[i]; + d += ` C ${xAt(s.cu1)} ${s.cy1.toFixed(1)}, ${xAt(s.cu2)} ${s.cy2.toFixed(1)}, ${xAt(s.u3)} ${s.y3.toFixed(1)}`; + } + return d; +} + +/** + * 求解标准 CSS `cubic-bezier(x1, y1, x2, y2)` 在进度 `t` (`0..1`) 处的精确输出值, + * 确保 JS 曲线形变、峰值胶囊滑动及进度条宽度缩放严格同频。 + */ +function evalCubicBezier(x1, y1, x2, y2, t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + let lo = 0; + let hi = 1; + for (let i = 0; i < 16; i++) { + const s = (lo + hi) * 0.5; + const inv = 1 - s; + const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s; + if (bx < t) lo = s; + else hi = s; + } + const s = (lo + hi) * 0.5; + const inv = 1 - s; + return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s; +} + +/** + * 根据分桶总数及标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 * * @param {Array<{ label?: string }>} slots * @returns {number[]} @@ -13620,10 +13801,11 @@ function buildSmoothSplinePath(points) { function computeTickIndices(slots) { const n = slots.length; if (n <= 1) return [0]; - if (n <= 8) { + const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || ''); + const maxDirectTicks = sampleLabel.length > 6 ? 5 : 8; + if (n <= maxDirectTicks) { return Array.from({ length: n }, (_, i) => i); } - const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || ''); const maxTicks = sampleLabel.length > 6 ? 5 : 6; const set = new Set(); for (let k = 0; k < maxTicks; k++) { @@ -13942,7 +14124,163 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let hoveredCellEl = null; let lastPointer = null; let lastRenderSig = ''; + let lastTickLabelsSig = ''; + let hasRenderedOnce = false; + let hasRenderedLineOnce = false; + let peakReadyArmed = false; + let peakReadyRaf = 0; let tipTrackRaf = 0; + let morphRafId = 0; + let committedSegs = []; + let liveMorphSegs = null; + const transientClassTimers = new Map(); + + const CURVE_MORPH_DURATION_MS = 240; + + function cleanupTransientClass(el) { + const rec = transientClassTimers.get(el); + if (!rec) return; + clearTimeout(rec.tid); + el?.removeEventListener?.('animationend', rec.onEnd); + el?.classList?.remove(rec.cls); + transientClassTimers.delete(el); + } + + function triggerTransientClass(el, cls, fallbackMs = 650) { + if (!el || !el.classList) return; + cleanupTransientClass(el); + el.classList.remove(cls); + void el.offsetWidth; + const onEnd = (ev) => { + if (ev && ev.target && ev.target !== el) return; + cleanupTransientClass(el); + }; + const tid = setTimeout(() => cleanupTransientClass(el), fallbackMs); + transientClassTimers.set(el, { cls, tid, onEnd }); + el.addEventListener?.('animationend', onEnd); + el.classList.add(cls); + } + + function clearAllTransientTimers() { + for (const el of Array.from(transientClassTimers.keys())) { + cleanupTransientClass(el); + } + } + + function cancelCurveMorph() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; + } + + function cancelPeakReadyRaf() { + if ( + peakReadyRaf && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(peakReadyRaf); + } + peakReadyRaf = 0; + } + + function canAnimateInBrowser() { + if ( + typeof window === 'undefined' || + typeof window.requestAnimationFrame !== 'function' || + typeof window.getComputedStyle !== 'function' || + typeof performance === 'undefined' || + typeof performance.now !== 'function' + ) { + return false; + } + if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) { + return false; + } + return true; + } + + function startCurveMorph( + fromSegs, + toSegs, + { leftX, rightX, spanX, finalLineD, finalAreaD } + ) { + cancelCurveMorph(); + if (!canAnimateInBrowser() || fromSegs.length === 0 || toSegs.length === 0) { + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + patchAttr(areaPath, 'd', finalAreaD); + return; + } + + const knots = mergeNormalizedKnots(fromSegs, toSegs); + const alignedFrom = subdivideChainToKnots(fromSegs, knots); + const alignedTo = subdivideChainToKnots(toSegs, knots); + const segCount = alignedTo.length; + let maxDeltaY = 0; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + maxDeltaY = Math.max( + maxDeltaY, + Math.abs(b.y0 - a.y0), + Math.abs(b.cy1 - a.cy1), + Math.abs(b.cy2 - a.cy2), + Math.abs(b.y3 - a.y3) + ); + } + + if (maxDeltaY < 0.25) { + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + patchAttr(areaPath, 'd', finalAreaD); + return; + } + + const activeLive = alignedFrom.map((s) => ({ ...s })); + liveMorphSegs = activeLive; + const rightXFixed = rightX.toFixed(1); + const leftXFixed = leftX.toFixed(1); + const startTs = performance.now(); + + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / CURVE_MORPH_DURATION_MS); + if (rawT >= 1) { + morphRafId = 0; + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + patchAttr(areaPath, 'd', finalAreaD); + return; + } + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + const cur = activeLive[i]; + cur.u0 = a.u0 + (b.u0 - a.u0) * ease; + cur.y0 = a.y0 + (b.y0 - a.y0) * ease; + cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; + cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; + cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; + cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; + cur.u3 = a.u3 + (b.u3 - a.u3) * ease; + cur.y3 = a.y3 + (b.y3 - a.y3) * ease; + } + const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); + const morphAreaD = `${morphLineD} L ${rightXFixed} ${BOTTOM_Y} L ${leftXFixed} ${BOTTOM_Y} Z`; + patchAttr(linePath, 'd', morphLineD); + patchAttr(areaPath, 'd', morphAreaD); + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } function cancelTipTrackRaf() { if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { @@ -14452,6 +14790,9 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { function destroy() { cancelTipTrackRaf(); + cancelCurveMorph(); + cancelPeakReadyRaf(); + clearAllTransientTimers(); plotStage.removeEventListener('mousemove', handlePointerMove); plotStage.removeEventListener('click', handleLineClick); plotStage.removeEventListener('mouseleave', clearHover); @@ -14484,18 +14825,30 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { currentSlots = slots; const isHourly = - slots[0]?.granularity === 'hour' || String(slots[0]?.label || '').includes(':'); + slots[0]?.granularity === 'hour' || + slots[0]?.granularity === 'minute' || + String(slots[0]?.label || '').includes(':'); const useHeatmap = !isHourly && slots.length > HEATMAP_DAYS_THRESHOLD; const modeChanged = useHeatmap !== currentIsHeatmap; currentIsHeatmap = useHeatmap; if (modeChanged) { clearHover(); + cancelCurveMorph(); + liveMorphSegs = null; } patchClasses(chartWrap, { 'is-heatmap': useHeatmap }); patchAttr(plotStage, 'hidden', useHeatmap); patchAttr(xAxisEl, 'hidden', useHeatmap); patchAttr(heatmapStage, 'hidden', !useHeatmap); + if (hasRenderedOnce && modeChanged && canAnimateInBrowser()) { + if (useHeatmap) { + triggerTransientClass(heatmapStage, 'is-stage-entering'); + } else { + triggerTransientClass(plotStage, 'is-stage-entering'); + triggerTransientClass(xAxisEl, 'is-switching'); + } + } if (!useHeatmap) { syncViewWidth(); @@ -14641,10 +14994,11 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } else if (hoveredIdx >= 0) { showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer); } + hasRenderedOnce = true; return; } - // --- <= 90 天(或整点小时级):渲染平滑面积曲线图(1:1 贴边对齐) --- + // --- <= 90 天(或整点/分钟级):渲染平滑面积曲线图(1:1 贴边对齐 + 连续插值形变过渡) --- currentCellEls = []; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); const denom = Math.max(1, maxTokens); @@ -14660,23 +15014,59 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { }); currentPts = pts; + const nextSegs = pointsToNormalizedCubicSegs(pts, BOTTOM_Y); + if (sig !== lastRenderSig) { lastRenderSig = sig; let lineD; let areaD; if (isSingle) { - const yStr = pts[0].y.toFixed(1); - lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; + if (maxTokens > 0) { + lineD = buildSmoothSplinePath([ + { x: leftX, y: BOTTOM_Y }, + pts[0], + { x: rightX, y: BOTTOM_Y }, + ]); + } else { + const yStr = pts[0].y.toFixed(1); + lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; + } areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`; } else { lineD = buildSmoothSplinePath(pts); areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; } - patchAttr(linePath, 'd', lineD); - patchAttr(areaPath, 'd', areaD); - // 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边) + const prevSegs = liveMorphSegs || committedSegs; + committedSegs = nextSegs; + if (hasRenderedLineOnce && !modeChanged && prevSegs.length > 0) { + startCurveMorph(prevSegs, nextSegs, { + leftX, + rightX, + spanX, + finalLineD: lineD, + finalAreaD: areaD, + }); + } else { + cancelCurveMorph(); + liveMorphSegs = null; + patchAttr(linePath, 'd', lineD); + patchAttr(areaPath, 'd', areaD); + } + hasRenderedLineOnce = true; + + // 渲染对齐底部刻度的垂直参考网格线及 X 轴标签(起止标签严格左右贴边) const tickIndices = computeTickIndices(slots); + const nextTickLabelsSig = tickIndices + .map((tIdx) => `${tIdx}:${slots[tIdx]?.label || ''}`) + .join('|'); + const ticksChanged = + hasRenderedOnce && + !modeChanged && + lastTickLabelsSig !== '' && + nextTickLabelsSig !== lastTickLabelsSig; + lastTickLabelsSig = nextTickLabelsSig; + while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); tickElsByIdx = new Map(); @@ -14712,6 +15102,11 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } + + if (ticksChanged && canAnimateInBrowser()) { + triggerTransientClass(xAxisEl, 'is-switching'); + triggerTransientClass(vGridGroup, 'is-switching'); + } } const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; @@ -14727,12 +15122,24 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { patchText(peakPill, peakText); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + if (!peakReadyArmed) { + peakReadyArmed = true; + if (canAnimateInBrowser()) { + peakReadyRaf = window.requestAnimationFrame(() => { + peakReadyRaf = 0; + patchClasses(peakPill, { 'is-ready': true }); + }); + } else { + patchClasses(peakPill, { 'is-ready': true }); + } + } if (hoveredIdx >= slots.length) { clearHover(); } else if (hoveredIdx >= 0) { showLineHoverAtIndex(hoveredIdx, lastPointer); } + hasRenderedOnce = true; } return { el: chartWrap, update, destroy }; @@ -29613,6 +30020,61 @@ const ConsumptionView = defineComponent({ const cacheReadLabel = h('span', { text: t('cons.cacheRead') }); const outputUsageLabel = h('span', { text: t('cons.outputUsage') }); + const unifiedMatrixEl = h('div', { className: 'cons-box cons-unified-matrix' }, [ + h('div', { className: 'cons-split-3' }, [ + h('div', { className: 'cons-col' }, [ + totalTokensLabel, + h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + estCostLabel, + h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheHitRateLabel, + ]), + h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), + ]), + ]), + h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ + h('div', { className: 'cons-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-input' }), + newInputLabel, + ]), + inputSharePct, + ]), + inputMainTokens, + inputSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheReadLabel, + ]), + cacheSharePct, + ]), + cacheMainTokens, + cacheSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outputUsageLabel, + ]), + outputSharePct, + ]), + outputMainTokens, + outputSubText, + ]), + ]), + ]); + const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ h('span', { className: 'panel-title' }, [ @@ -29624,60 +30086,7 @@ const ConsumptionView = defineComponent({ ]), ]), customRangeBar, - h('div', { className: 'cons-box cons-unified-matrix' }, [ - h('div', { className: 'cons-split-3' }, [ - h('div', { className: 'cons-col' }, [ - totalTokensLabel, - h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - estCostLabel, - h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheHitRateLabel, - ]), - h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), - ]), - ]), - h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ - h('div', { className: 'cons-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-input' }), - newInputLabel, - ]), - inputSharePct, - ]), - inputMainTokens, - inputSubText, - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheReadLabel, - ]), - cacheSharePct, - ]), - cacheMainTokens, - cacheSubText, - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-output' }), - outputUsageLabel, - ]), - outputSharePct, - ]), - outputMainTokens, - outputSubText, - ]), - ]), - ]), + unifiedMatrixEl, overviewSegBar.el, ]); @@ -29732,6 +30141,54 @@ const ConsumptionView = defineComponent({ let lastModelsCount = 0; let lastWorkspacesCount = 0; let lastConvsCount = 0; + let hasCompletedInitialDraw = false; + let lastAnimatedRangeSig = ''; + let lastAnimatedRankingKey = ''; + let lastAnimatedSortSig = ''; + const consAnimTimers = new Map(); + const TRANSIENT_CONS_CLASSES = [ + 'is-range-switching', + 'is-tab-entering', + 'is-bars-revealing', + ]; + + function cleanupConsAnim(el) { + const rec = consAnimTimers.get(el); + if (!rec) return; + clearTimeout(rec.tid); + el?.removeEventListener?.('animationend', rec.onEnd); + el?.classList?.remove(...TRANSIENT_CONS_CLASSES); + consAnimTimers.delete(el); + } + + function triggerConsAnim(el, cls, fallbackMs = 650) { + if ( + !el || + !el.classList || + typeof window === 'undefined' || + typeof window.getComputedStyle !== 'function' || + window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches + ) { + return; + } + cleanupConsAnim(el); + el.classList.remove(...TRANSIENT_CONS_CLASSES); + void el.offsetWidth; + const onEnd = (ev) => { + if (ev && ev.target && ev.target !== el) return; + cleanupConsAnim(el); + }; + const tid = setTimeout(() => cleanupConsAnim(el), fallbackMs); + consAnimTimers.set(el, { cls, tid, onEnd }); + el.addEventListener?.('animationend', onEnd); + el.classList.add(cls); + } + + function clearConsAnimTimers() { + for (const el of Array.from(consAnimTimers.keys())) { + cleanupConsAnim(el); + } + } function getRankingTabOptions( modelsCount = lastModelsCount, @@ -31329,17 +31786,26 @@ const ConsumptionView = defineComponent({ t('cons.allTime') : preset?.label || rangeInfo.label || t('cons.allTime'); patchText(trendRangeBadge, rangeBadgeText); + const firstTrendSlot = rawTrendSeries[0] || null; + const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; const isHourlyTrend = - rawTrendSeries[0]?.granularity === 'hour' || - (rawTrendSeries[0]?.label || '').includes(':'); - const isHeatmapTrend = !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; + !isMinuteTrend && + (firstTrendSlot?.granularity === 'hour' || + (firstTrendSlot?.label || '').includes(':')); + const isHeatmapTrend = + !isMinuteTrend && !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; patchText( trendGranularityHint, isHeatmapTrend ? t('cons.trendHeatmapHint', { days: rawTrendSeries.length }) - : isHourlyTrend - ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) - : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) + : isMinuteTrend + ? t('cons.trendPointsHintMinute', { + minutes: Math.max(1, Number(firstTrendSlot?.stepMinutes) || 5), + points: rawTrendSeries.length || 0, + }) + : isHourlyTrend + ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) + : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) ); const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { const mergedSlotModels = trendMergedByIdx[idx]; @@ -31478,6 +31944,53 @@ const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); + const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRankingKey = showWorkspacesTab + ? 'workspaces' + : showSessionsTab + ? 'sessions' + : 'models'; + const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`; + const activeRankingEl = showWorkspacesTab + ? workspacesListEl + : showSessionsTab + ? sortedTopConvs.length > 0 + ? topConvsListEl + : topConvsEmptyEl + : modelsListEl; + + const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig; + const tabSwitched = + hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey; + const sortSwitched = + hasCompletedInitialDraw && + !rangeSwitched && + !tabSwitched && + nextSortSig !== lastAnimatedSortSig; + + if (rangeSwitched) { + triggerConsAnim(unifiedMatrixEl, 'is-range-switching'); + triggerConsAnim(activeRankingEl, 'is-range-switching'); + triggerConsAnim(sourcesListEl, 'is-range-switching'); + } else if (tabSwitched) { + triggerConsAnim(activeRankingEl, 'is-tab-entering'); + } else if (sortSwitched) { + triggerConsAnim(activeRankingEl, 'is-bars-revealing'); + } + if (!hasCompletedInitialDraw) { + hasCompletedInitialDraw = true; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + rootEl.classList?.add('is-ready'); + }); + } else { + rootEl.classList?.add('is-ready'); + } + } + lastAnimatedRangeSig = nextRangeSig; + lastAnimatedRankingKey = nextRankingKey; + lastAnimatedSortSig = nextSortSig; + // 5. 同步 12 个月垂直堆叠柱状图(按模型配色堆叠 + 长尾合并 + 悬停弹出明细浮层) patchText(monthlyYearBadge, String(monthlyYear)); const maxMonthTokens = Math.max( @@ -31679,6 +32192,7 @@ const ConsumptionView = defineComponent({ ); onCleanup(() => { + clearConsAnimTimers(); hideBreakdownPopover(); unsub(); unsubView(); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index c991a62..22d6655 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -857,43 +857,34 @@ function buildUsageTrendSeries( earliestSelectedStepMs, latestSelectedStepMs ); - const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend; + const { start: trendStartMs, end: trendEndMs, hourly: useHourly, stepMs: plannedStepMs } = trend; const pad2 = (n) => String(n).padStart(2, '0'); const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; const trendSeries = []; if (useHourly) { - let firstHourMs = trend.first; - let lastHourMs = trend.last; - if (selectedWindow.key === 'today') { - const minTodayEndMs = firstHourMs + 5 * 3600 * 1000; - if (lastHourMs < minTodayEndMs) { - lastHourMs = minTodayEndMs; - } - } else if (lastHourMs - firstHourMs < 5 * 3600 * 1000) { - firstHourMs = lastHourMs - 5 * 3600 * 1000; - } + const firstSlotMs = trend.first; + const lastSlotMs = trend.last; + const slotMs = Math.max(60 * 1000, Number(plannedStepMs) || 3600 * 1000); + const stepMinutes = Math.max(1, Math.round(slotMs / (60 * 1000))); + const isSubHour = stepMinutes < 60; + const slotCount = Math.max(1, Math.floor((lastSlotMs - firstSlotMs) / slotMs) + 1); - const totalHours = Math.max(2, Math.round((lastHourMs - firstHourMs) / (3600 * 1000)) + 1); - const stepHours = totalHours > 72 ? Math.ceil(totalHours / 48) : 1; - const slotMs = stepHours * 3600 * 1000; - const slotCount = Math.max(2, Math.ceil((lastHourMs - firstHourMs + 3600 * 1000) / slotMs)); - - const firstD = new Date(firstHourMs); - const lastD = new Date(firstHourMs + (slotCount - 1) * slotMs); + const firstD = new Date(firstSlotMs); + const lastD = new Date(firstSlotMs + (slotCount - 1) * slotMs); const isSameDay = firstD.getFullYear() === lastD.getFullYear() && firstD.getMonth() === lastD.getMonth() && firstD.getDate() === lastD.getDate(); for (let idx = 0; idx < slotCount; idx++) { - const sMs = firstHourMs + idx * slotMs; + const sMs = firstSlotMs + idx * slotMs; const eMs = sMs + slotMs; const sd = new Date(sMs); const ed = new Date(eMs); if (Number.isNaN(sd.getTime())) continue; - const hh = `${pad2(sd.getHours())}:00`; - const endHh = `${pad2(ed.getHours())}:00`; + const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; + const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; const dateStr = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; const axisLabel = isSameDay ? hh : `${dateStr} ${hh}`; const fullLabel = `${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`; @@ -901,7 +892,8 @@ function buildUsageTrendSeries( index: idx, startMs: sMs, endMs: eMs, - granularity: 'hour', + granularity: isSubHour ? 'minute' : 'hour', + ...(isSubHour ? { stepMinutes } : {}), label: axisLabel, fullLabel, tokens: 0, @@ -928,11 +920,10 @@ function buildUsageTrendSeries( cursor.setHours(0, 0, 0, 0); safety++; } - while (dayStarts.length < 2) { - const prev = new Date(dayStarts[0] || firstDayMs); - prev.setDate(prev.getDate() - 1); - prev.setHours(0, 0, 0, 0); - dayStarts.unshift(prev.getTime()); + if (dayStarts.length === 0) { + const fallbackDay = new Date(firstDayMs); + fallbackDay.setHours(0, 0, 0, 0); + dayStarts.push(fallbackDay.getTime()); } const firstYear = new Date(dayStarts[0]).getFullYear(); @@ -1082,26 +1073,61 @@ function buildUsageTrendSeries( return { trend, trendStartMs, trendEndMs, trendSeries }; } +function resolveIntradayStepMinutes(spanMs, windowKey = '') { + if (windowKey !== 'all') { + if (spanMs < 15 * 60 * 1000) return 1; + if (spanMs < 60 * 60 * 1000) return 5; + if (spanMs < 2 * 3600 * 1000) return 15; + } + const totalHours = Math.max(2, Math.floor(spanMs / (3600 * 1000)) + 1); + return totalHours > 72 ? Math.ceil(totalHours / 48) * 60 : 60; +} + +function floorToLocalTrendSlotMs(ms, stepMinutes) { + const d = new Date(ms); + if (stepMinutes < 60) { + const alignedMin = Math.floor(d.getMinutes() / stepMinutes) * stepMinutes; + d.setMinutes(alignedMin, 0, 0); + } else { + d.setMinutes(0, 0, 0); + } + return d.getTime(); +} + function planUsageTrend(window, nowMs, earliest, latest) { const safeMs = (value, fallback) => Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback; const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest); const defaultStart = end - 24 * 3600 * 1000; - const start = window.key === 'all' - ? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000) - : Math.min(safeMs(window.startMs, defaultStart), end); - const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' || - end - start <= 72 * 3600 * 1000; + const start = + window.key === 'all' + ? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000) + : Math.min(safeMs(window.startMs, defaultStart), end); + const spanMs = Math.max(0, end - start); + const hourly = + window.key === 'today' || + window.key === '24h' || + window.key === '5h' || + spanMs <= 72 * 3600 * 1000; + if (hourly) { + const stepMinutes = resolveIntradayStepMinutes(spanMs, window.key); + const stepMs = stepMinutes * 60 * 1000; + const first = floorToLocalTrendSlotMs(start, stepMinutes); + const last = floorToLocalTrendSlotMs(end, stepMinutes); + return { start, end, hourly, stepMs, first, last }; + } const first = new Date(start); const last = new Date(end); - if (hourly) { - first.setMinutes(0, 0, 0); - last.setMinutes(0, 0, 0); - } else { - first.setHours(0, 0, 0, 0); - last.setHours(0, 0, 0, 0); - } - return { start, end, hourly, first: first.getTime(), last: last.getTime() }; + first.setHours(0, 0, 0, 0); + last.setHours(0, 0, 0, 0); + return { + start, + end, + hourly, + stepMs: 24 * 3600 * 1000, + first: first.getTime(), + last: last.getTime(), + }; } function sameUsageEntries(previous, current) { @@ -1441,7 +1467,9 @@ export function aggregateMultiWindowUsage({ : selectedWindow; const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); if ( - trend.hourly === previous.trend.hourly && trend.first === previous.trend.first && + trend.hourly === previous.trend.hourly && + trend.stepMs === previous.trend.stepMs && + trend.first === previous.trend.first && trend.last === previous.trend.last && sameUsageWindows( previous.windows, @@ -1994,6 +2022,7 @@ export function aggregateSelectedWindowUsage({ const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest); if ( trend.hourly === candidate.trend.hourly && + trend.stepMs === candidate.trend.stepMs && trend.first === candidate.trend.first && trend.last === candidate.trend.last && sameUsageWindows( diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index b27c977..75d4058 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index dcb50cc..a04c397 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -49,7 +49,176 @@ function buildSmoothSplinePath(points) { } /** - * 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 + * 将采样点数组转为归一化横轴 `u` (`0..1`) 上的精确三次贝塞尔分段链, + * 控制点严格保持跟 `buildSmoothSplinePath` 一致的 `0.42` 水平张力。 + * + * @param {Array<{ y: number }>} pts + * @param {number} bottomY + * @returns {Array<{ u0: number, y0: number, cu1: number, cy1: number, cu2: number, cy2: number, u3: number, y3: number }>} + */ +function pointsToNormalizedCubicSegs(pts, bottomY) { + const n = pts.length; + if (n === 0) { + return [ + { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, + ]; + } + if (n === 1) { + const py = pts[0].y; + if (Math.abs(py - bottomY) < 0.01) { + return [ + { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, + ]; + } + return [ + { u0: 0, y0: bottomY, cu1: 0.21, cy1: bottomY, cu2: 0.29, cy2: py, u3: 0.5, y3: py }, + { u0: 0.5, y0: py, cu1: 0.71, cy1: py, cu2: 0.79, cy2: bottomY, u3: 1, y3: bottomY }, + ]; + } + const segs = new Array(n - 1); + for (let i = 0; i < n - 1; i++) { + const u0 = i / (n - 1); + const u3 = (i + 1) / (n - 1); + const du = u3 - u0; + const y0 = pts[i].y; + const y3 = pts[i + 1].y; + segs[i] = { + u0, + y0, + cu1: u0 + du * 0.42, + cy1: y0, + cu2: u3 - du * 0.42, + cy2: y3, + u3, + y3, + }; + } + return segs; +} + +function solveCubicParamForU(seg, targetU) { + if (targetU <= seg.u0) return 0; + if (targetU >= seg.u3) return 1; + let lo = 0; + let hi = 1; + for (let it = 0; it < 20; it++) { + const s = (lo + hi) * 0.5; + const inv = 1 - s; + const u = + inv * inv * inv * seg.u0 + + 3 * inv * inv * s * seg.cu1 + + 3 * inv * s * s * seg.cu2 + + s * s * s * seg.u3; + if (u < targetU) lo = s; + else hi = s; + } + return (lo + hi) * 0.5; +} + +function splitCubicAt(seg, s) { + const u01 = seg.u0 + (seg.cu1 - seg.u0) * s; + const y01 = seg.y0 + (seg.cy1 - seg.y0) * s; + const u12 = seg.cu1 + (seg.cu2 - seg.cu1) * s; + const y12 = seg.cy1 + (seg.cy2 - seg.cy1) * s; + const u23 = seg.cu2 + (seg.u3 - seg.cu2) * s; + const y23 = seg.cy2 + (seg.y3 - seg.cy2) * s; + + const u012 = u01 + (u12 - u01) * s; + const y012 = y01 + (y12 - y01) * s; + const u123 = u12 + (u23 - u12) * s; + const y123 = y12 + (y23 - y12) * s; + + const u0123 = u012 + (u123 - u012) * s; + const y0123 = y012 + (y123 - y012) * s; + + return [ + { u0: seg.u0, y0: seg.y0, cu1: u01, cy1: y01, cu2: u012, cy2: y012, u3: u0123, y3: y0123 }, + { u0: u0123, y0: y0123, cu1: u123, cy1: y123, cu2: u23, cy2: y23, u3: seg.u3, y3: seg.y3 }, + ]; +} + +function extractCubicSubsegment(seg, uStart, uEnd) { + const s0 = solveCubicParamForU(seg, uStart); + const s1 = solveCubicParamForU(seg, uEnd); + if (s0 <= 1e-7 && s1 >= 1 - 1e-7) return { ...seg }; + const [, right] = s0 <= 1e-7 ? [null, seg] : splitCubicAt(seg, s0); + const remSpan = 1 - s0; + const localS1 = remSpan > 1e-9 ? Math.min(1, Math.max(0, (s1 - s0) / remSpan)) : 1; + const [sub] = localS1 >= 1 - 1e-7 ? [right] : splitCubicAt(right, localS1); + sub.u0 = uStart; + sub.u3 = uEnd; + return sub; +} + +/** + * 合并两条贝塞尔链的断点(始终完整保留目标链 `toSegs` 全部断点,保证 `t=1` 零几何误差)。 + */ +function mergeNormalizedKnots(fromSegs, toSegs) { + const raw = [0, 1]; + for (let i = 0; i < toSegs.length; i++) raw.push(toSegs[i].u3); + if (fromSegs.length <= 64) { + for (let i = 0; i < fromSegs.length; i++) raw.push(fromSegs[i].u3); + } else { + const stride = Math.ceil(fromSegs.length / 48); + for (let i = 0; i < fromSegs.length; i += stride) raw.push(fromSegs[i].u3); + } + raw.sort((a, b) => a - b); + const uniq = [0]; + for (let i = 1; i < raw.length; i++) { + if (raw[i] - uniq[uniq.length - 1] > 1e-6) { + uniq.push(raw[i]); + } + } + uniq[uniq.length - 1] = 1; + return uniq; +} + +function subdivideChainToKnots(segs, knots) { + const out = new Array(knots.length - 1); + let j = 0; + for (let k = 0; k < knots.length - 1; k++) { + const a = knots[k]; + const b = knots[k + 1]; + const mid = (a + b) * 0.5; + while (j < segs.length - 1 && segs[j].u3 < mid) j++; + out[k] = extractCubicSubsegment(segs[j], a, b); + } + return out; +} + +function buildPathFromNormalizedSegs(segs, leftX, spanX) { + const xAt = (u) => (leftX + u * spanX).toFixed(1); + let d = `M ${xAt(segs[0].u0)} ${segs[0].y0.toFixed(1)}`; + for (let i = 0; i < segs.length; i++) { + const s = segs[i]; + d += ` C ${xAt(s.cu1)} ${s.cy1.toFixed(1)}, ${xAt(s.cu2)} ${s.cy2.toFixed(1)}, ${xAt(s.u3)} ${s.y3.toFixed(1)}`; + } + return d; +} + +/** + * 求解标准 CSS `cubic-bezier(x1, y1, x2, y2)` 在进度 `t` (`0..1`) 处的精确输出值, + * 确保 JS 曲线形变、峰值胶囊滑动及进度条宽度缩放严格同频。 + */ +function evalCubicBezier(x1, y1, x2, y2, t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + let lo = 0; + let hi = 1; + for (let i = 0; i < 16; i++) { + const s = (lo + hi) * 0.5; + const inv = 1 - s; + const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s; + if (bx < t) lo = s; + else hi = s; + } + const s = (lo + hi) * 0.5; + const inv = 1 - s; + return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s; +} + +/** + * 根据分桶总数及标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 * * @param {Array<{ label?: string }>} slots * @returns {number[]} @@ -57,10 +226,11 @@ function buildSmoothSplinePath(points) { function computeTickIndices(slots) { const n = slots.length; if (n <= 1) return [0]; - if (n <= 8) { + const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || ''); + const maxDirectTicks = sampleLabel.length > 6 ? 5 : 8; + if (n <= maxDirectTicks) { return Array.from({ length: n }, (_, i) => i); } - const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || ''); const maxTicks = sampleLabel.length > 6 ? 5 : 6; const set = new Set(); for (let k = 0; k < maxTicks; k++) { @@ -379,7 +549,163 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { let hoveredCellEl = null; let lastPointer = null; let lastRenderSig = ''; + let lastTickLabelsSig = ''; + let hasRenderedOnce = false; + let hasRenderedLineOnce = false; + let peakReadyArmed = false; + let peakReadyRaf = 0; let tipTrackRaf = 0; + let morphRafId = 0; + let committedSegs = []; + let liveMorphSegs = null; + const transientClassTimers = new Map(); + + const CURVE_MORPH_DURATION_MS = 240; + + function cleanupTransientClass(el) { + const rec = transientClassTimers.get(el); + if (!rec) return; + clearTimeout(rec.tid); + el?.removeEventListener?.('animationend', rec.onEnd); + el?.classList?.remove(rec.cls); + transientClassTimers.delete(el); + } + + function triggerTransientClass(el, cls, fallbackMs = 650) { + if (!el || !el.classList) return; + cleanupTransientClass(el); + el.classList.remove(cls); + void el.offsetWidth; + const onEnd = (ev) => { + if (ev && ev.target && ev.target !== el) return; + cleanupTransientClass(el); + }; + const tid = setTimeout(() => cleanupTransientClass(el), fallbackMs); + transientClassTimers.set(el, { cls, tid, onEnd }); + el.addEventListener?.('animationend', onEnd); + el.classList.add(cls); + } + + function clearAllTransientTimers() { + for (const el of Array.from(transientClassTimers.keys())) { + cleanupTransientClass(el); + } + } + + function cancelCurveMorph() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; + } + + function cancelPeakReadyRaf() { + if ( + peakReadyRaf && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(peakReadyRaf); + } + peakReadyRaf = 0; + } + + function canAnimateInBrowser() { + if ( + typeof window === 'undefined' || + typeof window.requestAnimationFrame !== 'function' || + typeof window.getComputedStyle !== 'function' || + typeof performance === 'undefined' || + typeof performance.now !== 'function' + ) { + return false; + } + if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) { + return false; + } + return true; + } + + function startCurveMorph( + fromSegs, + toSegs, + { leftX, rightX, spanX, finalLineD, finalAreaD } + ) { + cancelCurveMorph(); + if (!canAnimateInBrowser() || fromSegs.length === 0 || toSegs.length === 0) { + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + patchAttr(areaPath, 'd', finalAreaD); + return; + } + + const knots = mergeNormalizedKnots(fromSegs, toSegs); + const alignedFrom = subdivideChainToKnots(fromSegs, knots); + const alignedTo = subdivideChainToKnots(toSegs, knots); + const segCount = alignedTo.length; + let maxDeltaY = 0; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + maxDeltaY = Math.max( + maxDeltaY, + Math.abs(b.y0 - a.y0), + Math.abs(b.cy1 - a.cy1), + Math.abs(b.cy2 - a.cy2), + Math.abs(b.y3 - a.y3) + ); + } + + if (maxDeltaY < 0.25) { + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + patchAttr(areaPath, 'd', finalAreaD); + return; + } + + const activeLive = alignedFrom.map((s) => ({ ...s })); + liveMorphSegs = activeLive; + const rightXFixed = rightX.toFixed(1); + const leftXFixed = leftX.toFixed(1); + const startTs = performance.now(); + + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / CURVE_MORPH_DURATION_MS); + if (rawT >= 1) { + morphRafId = 0; + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + patchAttr(areaPath, 'd', finalAreaD); + return; + } + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + const cur = activeLive[i]; + cur.u0 = a.u0 + (b.u0 - a.u0) * ease; + cur.y0 = a.y0 + (b.y0 - a.y0) * ease; + cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; + cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; + cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; + cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; + cur.u3 = a.u3 + (b.u3 - a.u3) * ease; + cur.y3 = a.y3 + (b.y3 - a.y3) * ease; + } + const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); + const morphAreaD = `${morphLineD} L ${rightXFixed} ${BOTTOM_Y} L ${leftXFixed} ${BOTTOM_Y} Z`; + patchAttr(linePath, 'd', morphLineD); + patchAttr(areaPath, 'd', morphAreaD); + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } function cancelTipTrackRaf() { if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { @@ -889,6 +1215,9 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { function destroy() { cancelTipTrackRaf(); + cancelCurveMorph(); + cancelPeakReadyRaf(); + clearAllTransientTimers(); plotStage.removeEventListener('mousemove', handlePointerMove); plotStage.removeEventListener('click', handleLineClick); plotStage.removeEventListener('mouseleave', clearHover); @@ -921,18 +1250,30 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { currentSlots = slots; const isHourly = - slots[0]?.granularity === 'hour' || String(slots[0]?.label || '').includes(':'); + slots[0]?.granularity === 'hour' || + slots[0]?.granularity === 'minute' || + String(slots[0]?.label || '').includes(':'); const useHeatmap = !isHourly && slots.length > HEATMAP_DAYS_THRESHOLD; const modeChanged = useHeatmap !== currentIsHeatmap; currentIsHeatmap = useHeatmap; if (modeChanged) { clearHover(); + cancelCurveMorph(); + liveMorphSegs = null; } patchClasses(chartWrap, { 'is-heatmap': useHeatmap }); patchAttr(plotStage, 'hidden', useHeatmap); patchAttr(xAxisEl, 'hidden', useHeatmap); patchAttr(heatmapStage, 'hidden', !useHeatmap); + if (hasRenderedOnce && modeChanged && canAnimateInBrowser()) { + if (useHeatmap) { + triggerTransientClass(heatmapStage, 'is-stage-entering'); + } else { + triggerTransientClass(plotStage, 'is-stage-entering'); + triggerTransientClass(xAxisEl, 'is-switching'); + } + } if (!useHeatmap) { syncViewWidth(); @@ -1078,10 +1419,11 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } else if (hoveredIdx >= 0) { showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer); } + hasRenderedOnce = true; return; } - // --- <= 90 天(或整点小时级):渲染平滑面积曲线图(1:1 贴边对齐) --- + // --- <= 90 天(或整点/分钟级):渲染平滑面积曲线图(1:1 贴边对齐 + 连续插值形变过渡) --- currentCellEls = []; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); const denom = Math.max(1, maxTokens); @@ -1097,23 +1439,59 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { }); currentPts = pts; + const nextSegs = pointsToNormalizedCubicSegs(pts, BOTTOM_Y); + if (sig !== lastRenderSig) { lastRenderSig = sig; let lineD; let areaD; if (isSingle) { - const yStr = pts[0].y.toFixed(1); - lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; + if (maxTokens > 0) { + lineD = buildSmoothSplinePath([ + { x: leftX, y: BOTTOM_Y }, + pts[0], + { x: rightX, y: BOTTOM_Y }, + ]); + } else { + const yStr = pts[0].y.toFixed(1); + lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; + } areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`; } else { lineD = buildSmoothSplinePath(pts); areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; } - patchAttr(linePath, 'd', lineD); - patchAttr(areaPath, 'd', areaD); - // 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边) + const prevSegs = liveMorphSegs || committedSegs; + committedSegs = nextSegs; + if (hasRenderedLineOnce && !modeChanged && prevSegs.length > 0) { + startCurveMorph(prevSegs, nextSegs, { + leftX, + rightX, + spanX, + finalLineD: lineD, + finalAreaD: areaD, + }); + } else { + cancelCurveMorph(); + liveMorphSegs = null; + patchAttr(linePath, 'd', lineD); + patchAttr(areaPath, 'd', areaD); + } + hasRenderedLineOnce = true; + + // 渲染对齐底部刻度的垂直参考网格线及 X 轴标签(起止标签严格左右贴边) const tickIndices = computeTickIndices(slots); + const nextTickLabelsSig = tickIndices + .map((tIdx) => `${tIdx}:${slots[tIdx]?.label || ''}`) + .join('|'); + const ticksChanged = + hasRenderedOnce && + !modeChanged && + lastTickLabelsSig !== '' && + nextTickLabelsSig !== lastTickLabelsSig; + lastTickLabelsSig = nextTickLabelsSig; + while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild); while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); tickElsByIdx = new Map(); @@ -1149,6 +1527,11 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } + + if (ticksChanged && canAnimateInBrowser()) { + triggerTransientClass(xAxisEl, 'is-switching'); + triggerTransientClass(vGridGroup, 'is-switching'); + } } const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; @@ -1164,12 +1547,24 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { patchText(peakPill, peakText); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + if (!peakReadyArmed) { + peakReadyArmed = true; + if (canAnimateInBrowser()) { + peakReadyRaf = window.requestAnimationFrame(() => { + peakReadyRaf = 0; + patchClasses(peakPill, { 'is-ready': true }); + }); + } else { + patchClasses(peakPill, { 'is-ready': true }); + } + } if (hoveredIdx >= slots.length) { clearHover(); } else if (hoveredIdx >= 0) { showLineHoverAtIndex(hoveredIdx, lastPointer); } + hasRenderedOnce = true; } return { el: chartWrap, update, destroy }; diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index 9fba24f..f74e807 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -1307,8 +1307,11 @@ export function buildConsumptionXlsx( let tTot = 0; let tCost = 0; const trendRows = trend.map((slot) => { + const isMinute = slot.granularity === 'minute'; const isHourly = - slot.granularity === 'hour' || String(slot.label || '').includes(':'); + isMinute || + slot.granularity === 'hour' || + String(slot.label || '').includes(':'); const calls = Math.max(0, Number(slot.calls || 0)); const inTok = Math.max(0, Number(slot.inputTokens || 0)); const cacheTok = Math.max(0, Number(slot.cacheReadTokens || 0)); @@ -1321,13 +1324,18 @@ export function buildConsumptionXlsx( tOut += outTok; tTot += totTok; tCost += cost; - const granLabel = isHourly + const stepMins = Math.max(1, Number(slot.stepMinutes) || 5); + const granLabel = isMinute ? en - ? 'Hourly' - : '按小时' - : en - ? 'Daily' - : '按天'; + ? `${stepMins}m` + : `按 ${stepMins} 分钟` + : isHourly + ? en + ? 'Hourly' + : '按小时' + : en + ? 'Daily' + : '按天'; return [ formatTrendWindowLabel(slot, isHourly), granLabel, diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 4aa4ee9..7b356e0 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -261,6 +261,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.trendTitle': 'Usage Trend', 'cons.allTime': 'All Time', 'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details', + 'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details', 'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details', 'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details', 'cons.topModels': 'Top Models', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index ec80561..e20bf78 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -261,6 +261,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.trendTitle': '用量趋势', 'cons.allTime': '全部时间', 'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看', + 'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看', 'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看', 'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看', 'cons.topModels': '模型排行', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index bb26d0b..703ab12 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -967,6 +967,8 @@ export function isEquivalentTelemetry(prev, next) { pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens || pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens || pTrend[i]?.calls !== nTrend[i]?.calls || + pTrend[i]?.granularity !== nTrend[i]?.granularity || + pTrend[i]?.stepMinutes !== nTrend[i]?.stepMinutes || pTrend[i]?.label !== nTrend[i]?.label || pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel || !areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models) diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 3fdd144..899a5f8 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -387,6 +387,111 @@ z-index: 2; } +.cons-view-stage .progress-seg { + flex: 0 0 auto; + transition: + background-color 80ms ease, + width 240ms cubic-bezier(0.22, 1, 0.36, 1); +} + +.cons-view-stage .progress-fill { + transition: width 240ms cubic-bezier(0.22, 1, 0.36, 1); +} + +@starting-style { + .cons-view-stage.is-ready .progress-seg, + .cons-view-stage.is-ready .progress-fill { + width: 0%; + } +} + +.trend-peak-pill.is-ready { + transition: + left 240ms cubic-bezier(0.22, 1, 0.36, 1), + opacity 180ms cubic-bezier(0.22, 1, 0.36, 1); +} + +@keyframes anim-cons-axis-fade { + from { + opacity: 0.3; + } + to { + opacity: 1; + } +} + +@keyframes anim-cons-stage-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes anim-cons-content-switch { + from { + opacity: 0.52; + } + to { + opacity: 1; + } +} + +@keyframes anim-cons-bar-grow { + from { + transform: scaleX(0); + } + to { + transform: scaleX(1); + } +} + +.trend-x-axis.is-switching, +.trend-v-grid.is-switching { + animation: anim-cons-axis-fade 220ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.trend-plot-stage.is-stage-entering, +.trend-heatmap-stage.is-stage-entering, +.cons-item-list.is-tab-entering, +.cons-ranking-empty.is-tab-entering { + animation: anim-cons-stage-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.cons-unified-matrix.is-range-switching, +.cons-item-list.is-range-switching, +.cons-ranking-empty.is-range-switching { + animation: anim-cons-content-switch 220ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.cons-item-list.is-tab-entering .progress-track, +.cons-item-list.is-bars-revealing .progress-track { + transform-origin: left center; + animation: anim-cons-bar-grow 240ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +@media (prefers-reduced-motion: reduce) { + .cons-view-stage .progress-seg, + .cons-view-stage .progress-fill, + .trend-peak-pill.is-ready, + .trend-hm-cell { + transition: none !important; + } + .trend-x-axis.is-switching, + .trend-v-grid.is-switching, + .trend-plot-stage.is-stage-entering, + .trend-heatmap-stage.is-stage-entering, + .cons-item-list.is-tab-entering, + .cons-ranking-empty.is-tab-entering, + .cons-unified-matrix.is-range-switching, + .cons-item-list.is-range-switching, + .cons-ranking-empty.is-range-switching, + .cons-item-list.is-bars-revealing .progress-track { + animation: none !important; + } +} + .trend-tooltip { position: absolute; top: 2px; @@ -664,7 +769,9 @@ border-radius: 2px; box-sizing: border-box; cursor: pointer; - transition: transform var(--dur-instant) var(--ease-fast); + transition: + background-color 180ms ease-out, + transform var(--dur-instant) var(--ease-fast); } .trend-hm-cell.is-pad { diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 224b73b..fa87a5c 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -280,6 +280,61 @@ export const ConsumptionView = defineComponent({ const cacheReadLabel = h('span', { text: t('cons.cacheRead') }); const outputUsageLabel = h('span', { text: t('cons.outputUsage') }); + const unifiedMatrixEl = h('div', { className: 'cons-box cons-unified-matrix' }, [ + h('div', { className: 'cons-split-3' }, [ + h('div', { className: 'cons-col' }, [ + totalTokensLabel, + h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + estCostLabel, + h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheHitRateLabel, + ]), + h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), + ]), + ]), + h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ + h('div', { className: 'cons-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-input' }), + newInputLabel, + ]), + inputSharePct, + ]), + inputMainTokens, + inputSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheReadLabel, + ]), + cacheSharePct, + ]), + cacheMainTokens, + cacheSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outputUsageLabel, + ]), + outputSharePct, + ]), + outputMainTokens, + outputSubText, + ]), + ]), + ]); + const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ h('span', { className: 'panel-title' }, [ @@ -291,60 +346,7 @@ export const ConsumptionView = defineComponent({ ]), ]), customRangeBar, - h('div', { className: 'cons-box cons-unified-matrix' }, [ - h('div', { className: 'cons-split-3' }, [ - h('div', { className: 'cons-col' }, [ - totalTokensLabel, - h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - estCostLabel, - h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheHitRateLabel, - ]), - h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), - ]), - ]), - h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ - h('div', { className: 'cons-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-input' }), - newInputLabel, - ]), - inputSharePct, - ]), - inputMainTokens, - inputSubText, - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheReadLabel, - ]), - cacheSharePct, - ]), - cacheMainTokens, - cacheSubText, - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-output' }), - outputUsageLabel, - ]), - outputSharePct, - ]), - outputMainTokens, - outputSubText, - ]), - ]), - ]), + unifiedMatrixEl, overviewSegBar.el, ]); @@ -399,6 +401,54 @@ export const ConsumptionView = defineComponent({ let lastModelsCount = 0; let lastWorkspacesCount = 0; let lastConvsCount = 0; + let hasCompletedInitialDraw = false; + let lastAnimatedRangeSig = ''; + let lastAnimatedRankingKey = ''; + let lastAnimatedSortSig = ''; + const consAnimTimers = new Map(); + const TRANSIENT_CONS_CLASSES = [ + 'is-range-switching', + 'is-tab-entering', + 'is-bars-revealing', + ]; + + function cleanupConsAnim(el) { + const rec = consAnimTimers.get(el); + if (!rec) return; + clearTimeout(rec.tid); + el?.removeEventListener?.('animationend', rec.onEnd); + el?.classList?.remove(...TRANSIENT_CONS_CLASSES); + consAnimTimers.delete(el); + } + + function triggerConsAnim(el, cls, fallbackMs = 650) { + if ( + !el || + !el.classList || + typeof window === 'undefined' || + typeof window.getComputedStyle !== 'function' || + window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches + ) { + return; + } + cleanupConsAnim(el); + el.classList.remove(...TRANSIENT_CONS_CLASSES); + void el.offsetWidth; + const onEnd = (ev) => { + if (ev && ev.target && ev.target !== el) return; + cleanupConsAnim(el); + }; + const tid = setTimeout(() => cleanupConsAnim(el), fallbackMs); + consAnimTimers.set(el, { cls, tid, onEnd }); + el.addEventListener?.('animationend', onEnd); + el.classList.add(cls); + } + + function clearConsAnimTimers() { + for (const el of Array.from(consAnimTimers.keys())) { + cleanupConsAnim(el); + } + } function getRankingTabOptions( modelsCount = lastModelsCount, @@ -1996,17 +2046,26 @@ export const ConsumptionView = defineComponent({ t('cons.allTime') : preset?.label || rangeInfo.label || t('cons.allTime'); patchText(trendRangeBadge, rangeBadgeText); + const firstTrendSlot = rawTrendSeries[0] || null; + const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; const isHourlyTrend = - rawTrendSeries[0]?.granularity === 'hour' || - (rawTrendSeries[0]?.label || '').includes(':'); - const isHeatmapTrend = !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; + !isMinuteTrend && + (firstTrendSlot?.granularity === 'hour' || + (firstTrendSlot?.label || '').includes(':')); + const isHeatmapTrend = + !isMinuteTrend && !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; patchText( trendGranularityHint, isHeatmapTrend ? t('cons.trendHeatmapHint', { days: rawTrendSeries.length }) - : isHourlyTrend - ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) - : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) + : isMinuteTrend + ? t('cons.trendPointsHintMinute', { + minutes: Math.max(1, Number(firstTrendSlot?.stepMinutes) || 5), + points: rawTrendSeries.length || 0, + }) + : isHourlyTrend + ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) + : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) ); const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { const mergedSlotModels = trendMergedByIdx[idx]; @@ -2145,6 +2204,53 @@ export const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); + const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRankingKey = showWorkspacesTab + ? 'workspaces' + : showSessionsTab + ? 'sessions' + : 'models'; + const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`; + const activeRankingEl = showWorkspacesTab + ? workspacesListEl + : showSessionsTab + ? sortedTopConvs.length > 0 + ? topConvsListEl + : topConvsEmptyEl + : modelsListEl; + + const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig; + const tabSwitched = + hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey; + const sortSwitched = + hasCompletedInitialDraw && + !rangeSwitched && + !tabSwitched && + nextSortSig !== lastAnimatedSortSig; + + if (rangeSwitched) { + triggerConsAnim(unifiedMatrixEl, 'is-range-switching'); + triggerConsAnim(activeRankingEl, 'is-range-switching'); + triggerConsAnim(sourcesListEl, 'is-range-switching'); + } else if (tabSwitched) { + triggerConsAnim(activeRankingEl, 'is-tab-entering'); + } else if (sortSwitched) { + triggerConsAnim(activeRankingEl, 'is-bars-revealing'); + } + if (!hasCompletedInitialDraw) { + hasCompletedInitialDraw = true; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(() => { + rootEl.classList?.add('is-ready'); + }); + } else { + rootEl.classList?.add('is-ready'); + } + } + lastAnimatedRangeSig = nextRangeSig; + lastAnimatedRankingKey = nextRankingKey; + lastAnimatedSortSig = nextSortSig; + // 5. 同步 12 个月垂直堆叠柱状图(按模型配色堆叠 + 长尾合并 + 悬停弹出明细浮层) patchText(monthlyYearBadge, String(monthlyYear)); const maxMonthTokens = Math.max( @@ -2346,6 +2452,7 @@ export const ConsumptionView = defineComponent({ ); onCleanup(() => { + clearConsAnimTimers(); hideBreakdownPopover(); unsub(); unsubView(); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 061bf4d..d2d28ce 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -3192,6 +3192,111 @@ html[data-standalone="true"] .app-shell { z-index: 2; } +.cons-view-stage .progress-seg { + flex: 0 0 auto; + transition: + background-color 80ms ease, + width 240ms cubic-bezier(0.22, 1, 0.36, 1); +} + +.cons-view-stage .progress-fill { + transition: width 240ms cubic-bezier(0.22, 1, 0.36, 1); +} + +@starting-style { + .cons-view-stage.is-ready .progress-seg, + .cons-view-stage.is-ready .progress-fill { + width: 0%; + } +} + +.trend-peak-pill.is-ready { + transition: + left 240ms cubic-bezier(0.22, 1, 0.36, 1), + opacity 180ms cubic-bezier(0.22, 1, 0.36, 1); +} + +@keyframes anim-cons-axis-fade { + from { + opacity: 0.3; + } + to { + opacity: 1; + } +} + +@keyframes anim-cons-stage-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes anim-cons-content-switch { + from { + opacity: 0.52; + } + to { + opacity: 1; + } +} + +@keyframes anim-cons-bar-grow { + from { + transform: scaleX(0); + } + to { + transform: scaleX(1); + } +} + +.trend-x-axis.is-switching, +.trend-v-grid.is-switching { + animation: anim-cons-axis-fade 220ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.trend-plot-stage.is-stage-entering, +.trend-heatmap-stage.is-stage-entering, +.cons-item-list.is-tab-entering, +.cons-ranking-empty.is-tab-entering { + animation: anim-cons-stage-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.cons-unified-matrix.is-range-switching, +.cons-item-list.is-range-switching, +.cons-ranking-empty.is-range-switching { + animation: anim-cons-content-switch 220ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.cons-item-list.is-tab-entering .progress-track, +.cons-item-list.is-bars-revealing .progress-track { + transform-origin: left center; + animation: anim-cons-bar-grow 240ms cubic-bezier(0.22, 1, 0.36, 1) both; +} + +@media (prefers-reduced-motion: reduce) { + .cons-view-stage .progress-seg, + .cons-view-stage .progress-fill, + .trend-peak-pill.is-ready, + .trend-hm-cell { + transition: none !important; + } + .trend-x-axis.is-switching, + .trend-v-grid.is-switching, + .trend-plot-stage.is-stage-entering, + .trend-heatmap-stage.is-stage-entering, + .cons-item-list.is-tab-entering, + .cons-ranking-empty.is-tab-entering, + .cons-unified-matrix.is-range-switching, + .cons-item-list.is-range-switching, + .cons-ranking-empty.is-range-switching, + .cons-item-list.is-bars-revealing .progress-track { + animation: none !important; + } +} + .trend-tooltip { position: absolute; top: 2px; @@ -3469,7 +3574,9 @@ html[data-standalone="true"] .app-shell { border-radius: 2px; box-sizing: border-box; cursor: pointer; - transition: transform var(--dur-instant) var(--ease-fast); + transition: + background-color 180ms ease-out, + transform var(--dur-instant) var(--ease-fast); } .trend-hm-cell.is-pad { diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 34820e8..9a1ceb7 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -3780,3 +3780,124 @@ test('conversation undo preserves 10-channel context breakdown across unindexed assert.equal(ctx4.userInputTokens, 20000); assert.equal(ctx4.userInputTokens + ctx4.assistantTokens + ctx4.toolResultsTokens, 27500); }); + +test('trendSeries respects strict window bounds without 6h out-of-window padding and subdivides <2h spans into 1m/5m/15m slots', async () => { + const mkStep = (atMs, tok) => ({ + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date(atMs).toISOString(), + finishedGeneratingAt: new Date(atMs + 4000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: String(tok), + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + plannerResponse: { response: 'ok' }, + }); + + // Anchor clock to local 2026-11-24 03:27:40 (3h 27m into 'today'; 27m into a cycle reset at 03:00:00) + const dayStart = new Date(2026, 10, 24, 0, 0, 0, 0).getTime(); + let fakeNowMs = dayStart + 3 * 3600_000 + 27 * 60_000 + 40_000; + + const cycleStartMs = dayStart + 3 * 3600_000; + const weeklyResetIso = new Date(cycleStartMs + 7 * 24 * 3600_000).toISOString(); + const fiveHourResetIso = new Date(cycleStartMs + 5 * 3600_000).toISOString(); + + const h = backendHarness({ + clock: () => fakeNowMs, + userStatus: { + email: 'trend@example.com', + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 3.8 Flash (High)', + modelOrAlias: { model: 'MODEL_PLACEHOLDER_M37' }, + quotaInfo: { remainingFraction: 0.9, resetTime: fiveHourResetIso }, + }, + ], + }, + }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini', + buckets: [ + { remainingFraction: 0.9, resetTime: fiveHourResetIso }, + { remainingFraction: 0.95, resetTime: weeklyResetIso }, + ], + }, + ], + }, + trajectories: { + cTrend: { + trajectory: { + steps: [ + mkStep(dayStart + 2 * 3600_000 + 10 * 60_000, 30_000), // 02:10 (previous cycle) + mkStep(cycleStartMs + 18 * 60_000, 5_000), // 03:18 (current cycle) + ], + generatorMetadata: [], + }, + }, + }, + summaries: { + cTrend: { stepCount: 2, lastModifiedTime: new Date(fakeNowMs).toISOString(), status: 'IDLE' }, + }, + }); + + // 1. 'today' at 03:27 (>= 2h): strictly 4 hourly slots (00:00..03:00), never padded to future 04:00/05:00 + const pToday = await h.buildTelemetryPayloadInternal('cTrend', false, { range: 'today' }); + assert.deepEqual( + Array.from(pToday.consumption.trendSeries, (s) => s.label), + ['00:00', '01:00', '02:00', '03:00'] + ); + assert.equal(pToday.consumption.trendSeries[0].granularity, 'hour'); + assert.equal(pToday.consumption.trendSeries[2].tokens, 30_000); + assert.equal(pToday.consumption.trendSeries[3].tokens, 5_000); + + // 2. 'cycle' 27m after reset (< 1h): 6 five-minute slots (03:00..03:25), never reaching back to 22:00..02:00 + const pCycle = await h.buildTelemetryPayloadInternal('cTrend', false, { range: 'cycle' }); + assert.deepEqual( + Array.from(pCycle.consumption.trendSeries, (s) => s.label), + ['03:00', '03:05', '03:10', '03:15', '03:20', '03:25'] + ); + assert.equal(pCycle.consumption.trendSeries[0].granularity, 'minute'); + assert.equal(pCycle.consumption.trendSeries[0].stepMinutes, 5); + assert.equal(pCycle.consumption.trendSeries[3].tokens, 5_000); // 03:18 falls in 03:15 - 03:20 + + // 3. Rewind to 01:20 (< 2h) on a fresh harness and verify 15m -> 1h cache invalidation across the 2h boundary + fakeNowMs = dayStart + 1 * 3600_000 + 20 * 60_000; + const hTransition = backendHarness({ + clock: () => fakeNowMs, + trajectories: { + cEarly: { + trajectory: { + steps: [mkStep(dayStart + 35 * 60_000, 8_000)], + generatorMetadata: [], + }, + }, + }, + summaries: { + cEarly: { stepCount: 1, lastModifiedTime: new Date(fakeNowMs).toISOString(), status: 'IDLE' }, + }, + }); + const pEarly = await hTransition.buildTelemetryPayloadInternal('cEarly', false, { range: 'today' }); + assert.deepEqual( + Array.from(pEarly.consumption.trendSeries, (s) => s.label), + ['00:00', '00:15', '00:30', '00:45', '01:00', '01:15'] + ); + assert.equal(pEarly.consumption.trendSeries[0].granularity, 'minute'); + assert.equal(pEarly.consumption.trendSeries[0].stepMinutes, 15); + assert.equal(pEarly.consumption.trendSeries[2].tokens, 8_000); + + // Advance clock to 02:05 (>= 2h): snapshot cache must invalidate stepMs and switch to 3 hourly slots + fakeNowMs = dayStart + 2 * 3600_000 + 5 * 60_000; + const pAfter2h = await hTransition.buildTelemetryPayloadInternal('cEarly', false, { range: 'today' }); + assert.deepEqual( + Array.from(pAfter2h.consumption.trendSeries, (s) => s.label), + ['00:00', '01:00', '02:00'] + ); + assert.equal(pAfter2h.consumption.trendSeries[0].granularity, 'hour'); + assert.equal(pAfter2h.consumption.trendSeries[0].tokens, 8_000); +}); From 4fb7ec49582a90aa525380ecc63d04db16b9a998 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 11:24:45 +0900 Subject: [PATCH 08/30] feat(panel): add 3-tier weekly quota capacity and token estimates - Add a 3-tier pool burn-rate estimator (rolling median calibration, Theil-Sen net-burn slope, and solo cycle ratio) with cross-reset priced token density tracking to derive full-pool USD and token capacities plus account-wide weeklyCapacityEstimate - Render the Est. Weekly Quota summary banner, preliminary/partial badges, full-pool token equivalents, supplementary weekly fallback rows, and pool header capacity tooltips in QuotaPoolsWidget - Coalesce multi-pool state persistence across 5h/weekly buckets, suppress post-refund idle replica rebounds, and clamp externalUsedPct to physical local-spend bounds --- sidecars/panel/app.js | 325 ++++++- sidecars/panel/backend/quota-reservation.mjs | 774 ++++++++++++--- sidecars/panel/backend/telemetry-builder.mjs | 131 ++- sidecars/panel/backend/usage-aggregator.mjs | 36 + sidecars/panel/index.html | 4 +- .../components/widgets/QuotaPoolsWidget.js | 299 +++++- sidecars/panel/src/i18n/en-US.js | 10 +- sidecars/panel/src/i18n/zh-CN.js | 10 +- sidecars/panel/src/store/telemetryStore.js | 6 + sidecars/panel/src/styles/modern-ui.css | 2 + sidecars/panel/src/styles/views-overview.css | 73 +- sidecars/panel/styles.css | 75 +- .../panel/test/quota-reservation.test.mjs | 900 ++++++++++++++++++ 13 files changed, 2415 insertions(+), 230 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index ee2e004..09fc263 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1449,6 +1449,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', + 'quota.cycleFullSuffix': '满池约 {full}', 'quota.footTokensCustom': '本周累计: {tok} ({cost})', 'quota.footTokensCycle': '周期累计: {tok} ({cost})', 'quota.footCredits': 'AI 积分: {credits}', @@ -1460,13 +1461,18 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopTitle': '实测倍率预估', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': '当前账号', + 'quota.ratePopWkCapTitle': '预测周额度', + 'quota.ratePopWkCapPrelim': '· 初估', + 'quota.ratePopWkCapPartial': '· {ready}/{total} 池', 'quota.ratePopPoolFallback': '池综合均值', 'quota.ratePopEq5hLabel': '5h 满池', 'quota.ratePopEqWkLabel': '周限满池', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} 样本', - 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', - 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', + 'quota.ratePopPrelimSlope': '斜率初估', + 'quota.ratePopPrelimCycle': '周期初估', + 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。', + 'quota.ratePopNote': '按净消耗及精确计价折算,同池最省为 1x,按账号隔离。', 'quota.ratePopSharedBadge': '共享活跃', 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', @@ -2343,6 +2349,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ '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', + 'quota.cycleFullSuffix': 'Full ~{full}', 'quota.footTokensCustom': 'Week Total: {tok} ({cost})', 'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})', 'quota.footCredits': 'AI Credits: {credits}', @@ -2354,13 +2361,18 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopTitle': 'Estimated Burn Rates', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': 'Current account', + 'quota.ratePopWkCapTitle': 'Est. Weekly Quota', + 'quota.ratePopWkCapPrelim': '· est.', + 'quota.ratePopWkCapPartial': '· {ready}/{total} pools', 'quota.ratePopPoolFallback': 'Pool average', 'quota.ratePopEq5hLabel': '5h full', 'quota.ratePopEqWkLabel': 'Weekly full', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} samples', - 'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.', - 'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.', + 'quota.ratePopPrelimSlope': 'slope est.', + 'quota.ratePopPrelimCycle': 'cycle est.', + 'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).', + 'quota.ratePopNote': 'Measured from net burn & priced steps; lowest in pool = 1x. Account isolated.', 'quota.ratePopSharedBadge': 'Shared active', 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', @@ -9936,6 +9948,12 @@ function isEquivalentTelemetry(prev, next) { return false; } } + if ( + JSON.stringify(prev.quotas?.weeklyCapacityEstimate || null) !== + JSON.stringify(next.quotas?.weeklyCapacityEstimate || null) + ) { + return false; + } const pConvs = prev.conversations || []; const nConvs = next.conversations || []; @@ -19298,21 +19316,24 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.title5h, `5h (${poolLabel})`); const c5h = poolData?.cycle5h; + const est = poolData?.rateEstimate; if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) { const tok5h = formatTokens(c5h.tokens || 0); const cost5h = formatUsd(c5h.costUsd || 0); const calls5h = Number(c5h.calls || 0); + const full5hRef = formatPoolFullCapRef(est?.eqFull5hUsd, est?.eqFull5hTokens); + const baseTip5h = t('quota.cycle5hTitle', { + pool: poolLabel, + tok: tok5h, + cost: cost5h, + calls: calls5h, + }); refs.usage5h.hidden = false; patchText(refs.usage5h, `· ${tok5h} (${cost5h})`); patchAttr( refs.left5h, 'title', - t('quota.cycle5hTitle', { - pool: poolLabel, - tok: tok5h, - cost: cost5h, - calls: calls5h, - }) + full5hRef ? `${baseTip5h} · ${t('quota.cycleFullSuffix', { full: full5hRef })}` : baseTip5h ); } else { refs.usage5h.hidden = true; @@ -19345,19 +19366,23 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { const tokWk = formatTokens(cWk.tokens || 0); const costWk = formatUsd(cWk.costUsd || 0); const callsWk = Number(cWk.calls || 0); + const fullWkRef = !useCustomWeekly + ? formatPoolFullCapRef(est?.eqFullWeeklyUsd, est?.eqFullWeeklyTokens) + : ''; + const baseTipWk = useCustomWeekly + ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) + : t('quota.cycleWkPoolTitle', { + pool: poolLabel, + tok: tokWk, + cost: costWk, + calls: callsWk, + }); refs.usageWk.hidden = false; patchText(refs.usageWk, `· ${tokWk} (${costWk})`); patchAttr( refs.leftWk, 'title', - useCustomWeekly - ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) - : t('quota.cycleWkPoolTitle', { - pool: poolLabel, - tok: tokWk, - cost: costWk, - calls: callsWk, - }) + fullWkRef ? `${baseTipWk} · ${t('quota.cycleFullSuffix', { full: fullWkRef })}` : baseTipWk ); } else { refs.usageWk.hidden = true; @@ -19382,8 +19407,9 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { function quotaPoolRowSig(item, idx) { const c5h = item.poolData?.cycle5h; const cWk = item.poolData?.cycleWeekly; + const est = item.poolData?.rateEstimate; const fw = item.fallbackWeekly; - 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}`; + 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}:${est?.eqFull5hUsd}:${est?.eqFull5hTokens}:${est?.eqFullWeeklyUsd}:${est?.eqFullWeeklyTokens}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } /** @@ -19459,6 +19485,99 @@ function formatRateEqUsd(val) { return `$${Number(num.toFixed(1))}`; } +function formatPoolFullCapRef(eqUsd, eqTok) { + const usdNum = Number(eqUsd); + if (!Number.isFinite(usdNum) || usdNum <= 0) return ''; + const usdStr = formatRateEqUsd(usdNum); + const tokNum = Number(eqTok); + if (Number.isFinite(tokNum) && tokNum > 0) { + return `${usdStr} (${formatTokens(tokNum)})`; + } + return usdStr; +} + +function resolveWeeklyCapacitySummary(quotas) { + if (!quotas || typeof quotas !== 'object') return null; + if (quotas.weekly?.isOfficial === false) return null; + const direct = quotas.weeklyCapacityEstimate; + if (direct && typeof direct === 'object') { + if ( + direct.status === 'custom_mode' || + !Number.isFinite(Number(direct.totalEqWeeklyUsd)) || + Number(direct.totalEqWeeklyUsd) <= 0 + ) { + return null; + } + return direct; + } + + const rawPools = Array.isArray(quotas.pools) ? quotas.pools : []; + const candidatePools = rawPools.filter( + (p) => + p && + (p.hasWeekly || + p.weeklyUsedPct != null || + Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) + ); + const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; + if (targetPools.length === 0) return null; + + let sumUsd = 0; + let sumTokens = 0; + let readyPoolCount = 0; + let tokenReadyPoolCount = 0; + let hasPreliminary = false; + + for (const p of targetPools) { + const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; + let eqUsd = + Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 + ? Number(est.eqFullWeeklyUsd) + : null; + let eqTok = + Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 + ? Math.round(Number(est.eqFullWeeklyTokens)) + : null; + if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { + const wkModels = est.models.filter( + (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 + ); + if (wkModels.length > 0) { + eqUsd = + wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; + const tokModels = wkModels.filter( + (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 + ); + if (tokModels.length === wkModels.length) { + eqTok = Math.round( + tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length + ); + } + } + } + if (eqUsd !== null) { + readyPoolCount += 1; + sumUsd += eqUsd; + if (est?.isPreliminaryWeekly) hasPreliminary = true; + if (eqTok !== null) { + tokenReadyPoolCount += 1; + sumTokens += eqTok; + } + } + } + + if (readyPoolCount === 0) return null; + const totalPoolCount = targetPools.length; + return { + status: readyPoolCount < totalPoolCount ? 'partial' : 'ready', + totalEqWeeklyUsd: +sumUsd.toFixed(1), + totalEqWeeklyTokens: tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, + readyPoolCount, + totalPoolCount, + hasPreliminary, + }; +} + function formatRatePerUsdValue(rate) { const num = Number(rate); if (!Number.isFinite(num) || num <= 0) return '--'; @@ -19480,7 +19599,11 @@ function createRateModelCard({ rateWeeklyPctPerUsd = null, eqFull5hUsd = null, eqFullWeeklyUsd = null, + eqFull5hTokens = null, + eqFullWeeklyTokens = null, samples = 0, + source = null, + isPreliminary = false, }) { const leftNodes = [ h('span', { @@ -19509,32 +19632,50 @@ function createRateModelCard({ }) ); } - if (Number(samples) > 0) { + if (isPreliminary) { + subParts.push( + source === 'anchor_slope' ? t('quota.ratePopPrelimSlope') : t('quota.ratePopPrelimCycle') + ); + } else if (Number(samples) > 0) { subParts.push(t('quota.ratePopSamples', { n: Number(samples) })); } const eqCells = []; if (eqFull5hUsd != null) { - eqCells.push( - h('div', { className: 'quota-rate-eq-cell' }, [ - h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), + const cell5hChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFull5hTokens)) && Number(eqFull5hTokens) > 0) { + cell5hChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFull5hTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cell5hChildren)); } if (eqFullWeeklyUsd != null) { - eqCells.push( - h('div', { className: 'quota-rate-eq-cell' }, [ - h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + const cellWkChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFullWeeklyTokens)) && Number(eqFullWeeklyTokens) > 0) { + cellWkChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFullWeeklyTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cellWkChildren)); } const cardChildren = [ @@ -19561,11 +19702,13 @@ function createRateModelCard({ function buildRatePopoverSig(data) { const locale = getEffectiveLocale(); const acct = String(data?.account?.email || data?.account?.name || '').trim(); + const isOfficial = data?.quotas?.weekly?.isOfficial !== false; + const wkCapSig = JSON.stringify(data?.quotas?.weeklyCapacityEstimate || null); const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; const poolSig = pools .map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`) .join('|'); - return `${locale}|${acct}|${poolSig}`; + return `${locale}|${acct}|${isOfficial}|${wkCapSig}|${poolSig}`; } const QuotaPoolsWidget = defineComponent({ @@ -19583,6 +19726,27 @@ const QuotaPoolsWidget = defineComponent({ className: 'quota-rate-pop-account', text: t('quota.ratePopAccountCurrent'), }); + const ratePopWkLabelEl = h('span', { text: t('quota.ratePopWkCapTitle') }); + const ratePopWkSubEl = h('span', { + className: 'quota-rate-wk-sub', + hidden: true, + text: '', + }); + const ratePopWkUsdEl = h('span', { className: 'quota-rate-wk-usd text-mono', text: '--' }); + const ratePopWkTokEl = h('span', { + className: 'quota-rate-wk-tok text-mono', + hidden: true, + text: '', + }); + const ratePopWkSummaryEl = h( + 'div', + { className: 'quota-rate-wk-summary', hidden: true }, + [ + h('span', { className: 'quota-rate-wk-k' }, [ratePopWkLabelEl, ratePopWkSubEl]), + h('span', { className: 'quota-rate-wk-v' }, [ratePopWkUsdEl, ratePopWkTokEl]), + ] + ); + ratePopWkSummaryEl.hidden = true; const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); const ratePopNoteEl = h('div', { className: 'quota-rate-pop-note', @@ -19597,6 +19761,7 @@ const QuotaPoolsWidget = defineComponent({ }, [ h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), + ratePopWkSummaryEl, ratePopBodyEl, ratePopNoteEl, ] @@ -19688,6 +19853,38 @@ const QuotaPoolsWidget = defineComponent({ ); patchAttr(ratePopAccountEl, 'title', acctMasked || null); + const wkCap = resolveWeeklyCapacitySummary(data?.quotas); + if (wkCap) { + ratePopWkSummaryEl.hidden = false; + patchAttr(ratePopWkSummaryEl, 'hidden', false); + patchText(ratePopWkLabelEl, t('quota.ratePopWkCapTitle')); + const wkSubText = + wkCap.status === 'partial' && Number(wkCap.totalPoolCount) > 0 + ? t('quota.ratePopWkCapPartial', { + ready: Number(wkCap.readyPoolCount) || 0, + total: Number(wkCap.totalPoolCount) || 0, + }) + : wkCap.hasPreliminary + ? t('quota.ratePopWkCapPrelim') + : ''; + ratePopWkSubEl.hidden = !wkSubText; + patchAttr(ratePopWkSubEl, 'hidden', !wkSubText); + patchText(ratePopWkSubEl, wkSubText); + patchText(ratePopWkUsdEl, `≈ ${formatRateEqUsd(wkCap.totalEqWeeklyUsd)}`); + const hasWkTok = + Number.isFinite(Number(wkCap.totalEqWeeklyTokens)) && + Number(wkCap.totalEqWeeklyTokens) > 0; + ratePopWkTokEl.hidden = !hasWkTok; + patchAttr(ratePopWkTokEl, 'hidden', !hasWkTok); + patchText( + ratePopWkTokEl, + hasWkTok ? `· ${formatTokens(Number(wkCap.totalEqWeeklyTokens))}` : '' + ); + } else { + ratePopWkSummaryEl.hidden = true; + patchAttr(ratePopWkSummaryEl, 'hidden', true); + } + while (ratePopBodyEl.firstChild) { ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); } @@ -19706,19 +19903,45 @@ const QuotaPoolsWidget = defineComponent({ if (models.length === 0 && !hasPoolFallback && !ext) continue; const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; + const fallbackPrimaryIs5h = est.rate5hPctPerUsd != null; + const anyModelHasWeekly = models.some((m) => m?.eqFullWeeklyUsd != null); + const needsWeeklyFallbackRow = + models.length > 0 && + !anyModelHasWeekly && + Number.isFinite(est.rateWeeklyPctPerUsd) && + est.eqFullWeeklyUsd != null; const rows = models.length > 0 - ? models.map((item) => - createRateModelCard({ - name: item.model, - multiplier: item.multiplier, - rate5hPctPerUsd: item.rate5hPctPerUsd, - rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, - eqFull5hUsd: item.eqFull5hUsd, - eqFullWeeklyUsd: item.eqFullWeeklyUsd, - samples: item.samples, - }) - ) + ? [ + ...models.map((item) => + createRateModelCard({ + name: item.model, + multiplier: item.multiplier, + rate5hPctPerUsd: item.rate5hPctPerUsd, + rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, + eqFull5hUsd: item.eqFull5hUsd, + eqFullWeeklyUsd: item.eqFullWeeklyUsd, + eqFull5hTokens: item.eqFull5hTokens, + eqFullWeeklyTokens: item.eqFullWeeklyTokens, + samples: item.samples, + }) + ), + ...(needsWeeklyFallbackRow + ? [ + createRateModelCard({ + name: t('quota.ratePopPoolFallback'), + isMutedName: true, + isFallback: true, + rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, + eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, + samples: Number(est.samplesWeekly) || 0, + source: est.sourceWeekly || null, + isPreliminary: Boolean(est.isPreliminaryWeekly), + }), + ] + : []), + ] : hasPoolFallback ? [ createRateModelCard({ @@ -19729,7 +19952,13 @@ const QuotaPoolsWidget = defineComponent({ rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, eqFull5hUsd: est.eqFull5hUsd, eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFull5hTokens: est.eqFull5hTokens, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), + source: fallbackPrimaryIs5h ? est.source5h || null : est.sourceWeekly || null, + isPreliminary: fallbackPrimaryIs5h + ? Boolean(est.isPreliminary5h) + : Boolean(est.isPreliminaryWeekly), }), ] : []; diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs index 127b26f..8c61c62 100644 --- a/sidecars/panel/backend/quota-reservation.mjs +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -33,6 +33,7 @@ export const QR_IDLE_CONFIRM_REFUND_MS = 5 * 60 * 1000; export const QR_REFUND_CONFIRM_WINDOW_MS = 4 * 60 * 1000; export const QR_REFUND_CONFIRM_MIN_SAMPLES = 4; export const QR_RATE_BOUNCE_COOLDOWN_MS = 60 * 1000; +export const QR_REPLICA_BOUNCE_MEMORY_MS = 30 * 60 * 1000; export const QR_RATE_WINDOW_SIZE = 20; export const QR_RATE_OUTLIER_MIN_RATIO = 0.45; export const QR_RATE_OUTLIER_MAX_RATIO = 2.0; @@ -60,6 +61,21 @@ export const QR_TENTATIVE_LEASE_TTL_MS = 3 * 60 * 1000; const QR_MAX_MODELS_PER_BUCKET = 16; const QR_MAX_TRACKED_BUCKETS = 128; const QR_MAX_ACTIVE_LEASES = 16; +const QR_MAX_SLOPE_SAMPLES = 24; +const QR_SLOPE_MIN_DELTA_PCT = 0.25; +const QR_SLOPE_MIN_DELTA_COST_USD = 0.15; +const QR_SLOPE_UNLOCK_5H_PCT = 2.5; +const QR_SLOPE_UNLOCK_WK_PCT = 1.5; +const QR_SLOPE_UNLOCK_MIN_CALLS = 5; +const QR_COLD_RATIO_5H_PCT = 3.0; +const QR_COLD_RATIO_WK_PCT = 2.0; +const QR_COLD_RATIO_SOLO_PCT = 5.0; +const QR_COLD_RATIO_MIN_CALLS = 5; +const QR_COLD_RATIO_SOLO_MIN_CALLS = 3; +const QR_COLD_RATIO_5H_MIN_COST_USD = 0.15; +const QR_COLD_RATIO_WK_MIN_COST_USD = 0.25; +const QR_DENSITY_MIN_TOKENS = 10_000; +const QR_DENSITY_MIN_COST_USD = 0.05; const QR_MAX_EVENT_LOG = 500; const QR_PERSIST_MIN_INTERVAL_MS = 5000; const QR_STATE_SCHEMA_VERSION = 2; @@ -77,6 +93,172 @@ function qrClampRate(rate) { return qrClamp(rate, 0.005, 50); } +function qrClampUsdPerMTok(val) { + const num = Number(val); + if (!Number.isFinite(num) || num <= 0) return null; + return qrClamp(num, 0.02, 500); +} + +function qrBlendUsdPerMTok(prevDensity, costUsd, pricedTokens) { + const prev = qrClampUsdPerMTok(prevDensity); + const safeCost = Number(costUsd) || 0; + const safeTokens = Number(pricedTokens) || 0; + if (safeTokens < QR_DENSITY_MIN_TOKENS || safeCost < QR_DENSITY_MIN_COST_USD) { + return prev; + } + const curr = qrClampUsdPerMTok(safeCost / (safeTokens / 1_000_000)); + if (curr === null) return prev; + if (prev === null) return curr; + const w = safeCost / (safeCost + 1.0); + return qrClampUsdPerMTok(prev * (1 - w) + curr * w); +} + +function qrDeriveEqFullTokens(rawEqFullUsd, usdPerMTok) { + const usd = Number(rawEqFullUsd); + const density = qrClampUsdPerMTok(usdPerMTok); + if (!Number.isFinite(usd) || usd <= 0 || density === null) return null; + const tok = Math.round((usd / density) * 1_000_000); + return Number.isFinite(tok) && tok > 0 ? tok : null; +} + +function qrComputeTheilSenSlope(samples) { + if (!Array.isArray(samples) || samples.length < 2) return null; + if (samples.length === 2) { + const du = samples[1].u - samples[0].u; + const dc = samples[1].c - samples[0].c; + return dc >= 0.05 && du > 0 ? qrClampRate(du / dc) : null; + } + const slopes = []; + for (let i = 0; i < samples.length - 1; i += 1) { + for (let j = i + 1; j < samples.length; j += 1) { + const du = samples[j].u - samples[i].u; + const dc = samples[j].c - samples[i].c; + if (dc >= 0.05 && du > 0) { + const s = qrClampRate(du / dc); + if (s !== null) slopes.push(s); + } + } + } + return slopes.length > 0 ? qrClampRate(qrComputeMedian(slopes)) : null; +} + +function qrSanitizeSlopeSamples(raw) { + if (!Array.isArray(raw)) return []; + const out = []; + for (let i = 0; i < raw.length && out.length < QR_MAX_SLOPE_SAMPLES; i += 1) { + const item = raw[i]; + if (!item || typeof item !== 'object') continue; + const u = Number(item.u); + const c = Number(item.c); + const n = Math.floor(Number(item.n) || 0); + const unp = Math.max(0, Math.floor(Number(item.unp) || 0)); + if (!Number.isFinite(u) || u < 0 || !Number.isFinite(c) || c < 0 || n < 0) continue; + out.push({ u: qrClamp(u, 0, 100), c, n, ...(unp > 0 ? { unp } : {}) }); + } + return out; +} + +function qrSanitizeModelTokens(raw) { + const out = {}; + if (!raw || typeof raw !== 'object') return out; + for (const [k, v] of Object.entries(raw)) { + const cleanKey = String(k || '').trim(); + const num = Math.floor(Number(v) || 0); + if (cleanKey && Number.isFinite(num) && num > 0) { + out[cleanKey] = num; + } + } + return out; +} + +function qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens) { + if (!st || typeof st !== 'object') return; + const nextPoolDensity = qrBlendUsdPerMTok(st.priorUsdPerMTok, safeCost, safePricedTokens); + if (nextPoolDensity !== null) { + st.usdPerMTok = nextPoolDensity; + } + const priorModels = + st.priorModelUsdPerMTok && typeof st.priorModelUsdPerMTok === 'object' + ? st.priorModelUsdPerMTok + : {}; + const nextModels = { ...priorModels }; + if (safeModelCosts && safeModelTokens) { + for (const [mKey, mCost] of Object.entries(safeModelCosts)) { + const mTok = Number(safeModelTokens[mKey]) || 0; + const blended = qrBlendUsdPerMTok(priorModels[mKey] ?? null, mCost, mTok); + if (blended !== null) { + nextModels[mKey] = +blended.toFixed(4); + } + } + } + const entries = Object.entries(nextModels).slice(-QR_MAX_MODELS_PER_BUCKET); + st.modelUsdPerMTok = Object.fromEntries(entries); +} + +function qrComputeNetLocalUsedPct(st, officialUsedPct) { + const safeOfficial = qrClamp(Number(officialUsedPct) || 0, 0, 100); + if (!st || typeof st !== 'object') return safeOfficial; + const leaseSum = qrSumLeases(st.activeLeases || [], { includeTentative: true }); + const extPct = Math.max(0, Number(st.externalUsedPct) || 0); + return Math.max(0, safeOfficial - leaseSum - extPct); +} + +function qrSanitizeModelDensities(raw, { preserveRate = true } = {}) { + const out = {}; + if (!preserveRate || !raw || typeof raw !== 'object') return out; + const entries = Object.entries(raw).slice(-QR_MAX_MODELS_PER_BUCKET); + for (const [k, v] of entries) { + const cleanKey = String(k || '').trim(); + const clamped = qrClampUsdPerMTok(v); + if (cleanKey && clamped !== null) { + out[cleanKey] = +clamped.toFixed(4); + } + } + return out; +} + +function qrResetSlopeAnchor(st, netUsedPct, safeCost, safeCalls, safeUnpriced = 0) { + if (!st || typeof st !== 'object') return; + const calls = Math.max(0, Math.floor(Number(safeCalls) || 0)); + const unp = Math.max(0, Math.floor(Number(safeUnpriced) || 0)); + const u = qrClamp(Number(netUsedPct) || 0, 0, 100); + const c = Math.max(0, Number(safeCost) || 0); + st.slopeSamples = [{ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }]; +} + +function qrUpdateSlopeSamples(st, netUsedPct, safeCost, safeCalls, safeUnpriced = 0) { + if (!st || st.pendingDrop !== null) return; + const calls = Math.max(0, Math.floor(Number(safeCalls) || 0)); + const unp = Math.max(0, Math.floor(Number(safeUnpriced) || 0)); + const u = qrClamp(Number(netUsedPct) || 0, 0, 100); + const c = Math.max(0, Number(safeCost) || 0); + const arr = Array.isArray(st.slopeSamples) ? st.slopeSamples : (st.slopeSamples = []); + if (arr.length === 0) { + arr.push({ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }); + return; + } + const last = arr[arr.length - 1]; + const lastUnp = Math.max(0, Math.floor(Number(last.unp) || 0)); + if (u < last.u - 0.15 || c < last.c - 1e-4 || calls < last.n || unp !== lastUnp) { + st.slopeSamples = [{ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }]; + return; + } + const du = u - last.u; + const dc = c - last.c; + const dn = calls - last.n; + if ( + dn > 0 && + ((du >= QR_SLOPE_MIN_DELTA_PCT && dc >= 0.02) || + (dc >= QR_SLOPE_MIN_DELTA_COST_USD && du > 1e-3)) + ) { + arr.push({ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }); + if (arr.length > QR_MAX_SLOPE_SAMPLES) { + // 保留首锚点 arr[0] 以维持整周期跨度,淘汰最早的中间点 + arr.splice(1, arr.length - QR_MAX_SLOPE_SAMPLES); + } + } +} + function qrResolveExactUsedPct(poolObj, win) { const rawFrac = win === 'weekly' ? poolObj?.weeklyRemainingFraction : poolObj?.remainingFraction; @@ -184,8 +366,13 @@ function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { if (state.ratePctPerUsd !== null && Number.isFinite(state.ratePctPerUsd)) { return state.ratePctPerUsd; } - // 一旦检测到同池存在家庭组 / 其他设备外部消耗,禁止用累计总占比 / 本机花费做冷启动反推 - if (!state.hasExternalUsage && cycleCostUsd >= 0.5 && officialUsedPct >= 0.3) { + // 一旦检测到同池存在家庭组 / 其他设备外部消耗或未计价调用,禁止用累计总占比 / 本机花费做冷启动反推 + if ( + !state.hasExternalUsage && + (state.lastUnpricedCalls || 0) === 0 && + cycleCostUsd >= 0.5 && + officialUsedPct >= 0.3 + ) { return qrClampRate(officialUsedPct / cycleCostUsd); } return null; @@ -396,17 +583,93 @@ function qrEstimateModelWeightedPct(st, deltaModelCosts, totalDeltaCostUsd, fall return weightedPct + unattributedCost * fallbackRate; } +function qrResolveBucketDisplayRate(st, win) { + if (!st || typeof st !== 'object') return null; + const cleanWin = Array.isArray(st.rateWindow) ? st.rateWindow : []; + const calibratedSamples = cleanWin.length > 0 ? cleanWin.length : st.rateSamples; + if (calibratedSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st.ratePctPerUsd)) { + return { + rate: st.ratePctPerUsd, + source: 'calibrated', + isPreliminary: false, + samples: Math.max(cleanWin.length, st.rateSamples), + }; + } + + let tier2Rate = null; + const slopePts = Array.isArray(st.slopeSamples) ? st.slopeSamples : []; + if (slopePts.length >= 2) { + const first = slopePts[0]; + const last = slopePts[slopePts.length - 1]; + const spanPct = last.u - first.u; + const spanCost = last.c - first.c; + const spanCalls = last.n - first.n; + const minSpanPct = win === '5h' ? QR_SLOPE_UNLOCK_5H_PCT : QR_SLOPE_UNLOCK_WK_PCT; + if ( + spanPct >= minSpanPct && + spanCost >= QR_SLOPE_MIN_DELTA_COST_USD && + spanCalls >= QR_SLOPE_UNLOCK_MIN_CALLS + ) { + tier2Rate = qrComputeTheilSenSlope(slopePts); + } + } + + let tier3Rate = null; + if (!st.hasExternalUsage && (st.lastUnpricedCalls || 0) === 0 && st.lastOfficialUsedPct !== null) { + const out = qrFormatOutput(st, st.lastOfficialUsedPct); + const netUsedPct = Math.max( + 0, + st.lastOfficialUsedPct - out.reservedPct - (Number(st.externalUsedPct) || 0) + ); + const calls = Math.max(0, Number(st.lastCycleCalls) || 0); + const cost = Math.max(0, Number(st.lastCycleCostUsd) || 0); + const minCost = win === '5h' ? QR_COLD_RATIO_5H_MIN_COST_USD : QR_COLD_RATIO_WK_MIN_COST_USD; + const minPct = win === '5h' ? QR_COLD_RATIO_5H_PCT : QR_COLD_RATIO_WK_PCT; + const unlocked = + cost >= minCost && + ((netUsedPct >= minPct && calls >= QR_COLD_RATIO_MIN_CALLS) || + (netUsedPct >= QR_COLD_RATIO_SOLO_PCT && calls >= QR_COLD_RATIO_SOLO_MIN_CALLS)); + if (unlocked) { + tier3Rate = qrClampRate(netUsedPct / cost); + } + } + + const prelimRate = tier2Rate ?? tier3Rate; + if (prelimRate === null) return null; + const prelimSource = tier2Rate !== null ? 'anchor_slope' : 'cycle_ratio'; + if (cleanWin.length > 0) { + const cleanMed = qrComputeMedian(cleanWin); + if (cleanMed !== null) { + const w = cleanWin.length / (cleanWin.length + QR_MODEL_RATE_MIN_UI_SAMPLES); + const blended = qrClampRate(cleanMed * w + prelimRate * (1 - w)); + if (blended !== null) { + return { + rate: blended, + source: prelimSource, + isPreliminary: true, + samples: cleanWin.length, + }; + } + } + } + return { + rate: prelimRate, + source: prelimSource, + isPreliminary: true, + samples: 0, + }; +} + function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) { - const raw5hPool = - st5h && st5h.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st5h.ratePctPerUsd) - ? st5h.ratePctPerUsd - : null; - const rawWkPool = - stWk && stWk.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(stWk.ratePctPerUsd) - ? stWk.ratePctPerUsd - : null; + const resolved5h = qrResolveBucketDisplayRate(st5h, '5h'); + const resolvedWk = qrResolveBucketDisplayRate(stWk, 'weekly'); + const raw5hPool = resolved5h ? resolved5h.rate : null; + const rawWkPool = resolvedWk ? resolvedWk.rate : null; const rate5hPool = raw5hPool !== null ? +raw5hPool.toFixed(4) : null; const rateWkPool = rawWkPool !== null ? +rawWkPool.toFixed(4) : null; + const fallbackPoolDensity = stWk?.usdPerMTok ?? st5h?.usdPerMTok ?? null; + const density5hPool = st5h?.usdPerMTok ?? fallbackPoolDensity; + const densityWkPool = stWk?.usdPerMTok ?? fallbackPoolDensity; const modelKeys = new Set([ ...Object.keys(st5h?.modelRates || {}), @@ -425,12 +688,22 @@ function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) { ? mw.ratePctPerUsd : null; if (rawR5 === null && rawRw === null) continue; + const rawEq5hUsd = rawR5 ? 100 / rawR5 : null; + const rawEqWkUsd = rawRw ? 100 / rawRw : null; + const modelDensity5h = + st5h?.modelUsdPerMTok?.[model] ?? stWk?.modelUsdPerMTok?.[model] ?? density5hPool; + const modelDensityWk = + stWk?.modelUsdPerMTok?.[model] ?? st5h?.modelUsdPerMTok?.[model] ?? densityWkPool; + const eq5hTok = qrDeriveEqFullTokens(rawEq5hUsd, modelDensity5h); + const eqWkTok = qrDeriveEqFullTokens(rawEqWkUsd, modelDensityWk); models.push({ model, rate5hPctPerUsd: rawR5 !== null ? +rawR5.toFixed(4) : null, rateWeeklyPctPerUsd: rawRw !== null ? +rawRw.toFixed(4) : null, - eqFull5hUsd: rawR5 ? +(100 / rawR5).toFixed(1) : null, - eqFullWeeklyUsd: rawRw ? +(100 / rawRw).toFixed(1) : null, + eqFull5hUsd: rawEq5hUsd ? +rawEq5hUsd.toFixed(1) : null, + eqFullWeeklyUsd: rawEqWkUsd ? +rawEqWkUsd.toFixed(1) : null, + ...(eq5hTok !== null ? { eqFull5hTokens: eq5hTok } : {}), + ...(eqWkTok !== null ? { eqFullWeeklyTokens: eqWkTok } : {}), multiplier: null, samples: Math.max(m5?.rateSamples || 0, mw?.rateSamples || 0), _rawR5: rawR5, @@ -493,13 +766,24 @@ function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) { return null; } + const rawPoolEq5hUsd = raw5hPool ? 100 / raw5hPool : null; + const rawPoolEqWkUsd = rawWkPool ? 100 / rawWkPool : null; + const poolEq5hTok = qrDeriveEqFullTokens(rawPoolEq5hUsd, density5hPool); + const poolEqWkTok = qrDeriveEqFullTokens(rawPoolEqWkUsd, densityWkPool); + return { rate5hPctPerUsd: rate5hPool, rateWeeklyPctPerUsd: rateWkPool, - eqFull5hUsd: raw5hPool ? +(100 / raw5hPool).toFixed(1) : null, - eqFullWeeklyUsd: rawWkPool ? +(100 / rawWkPool).toFixed(1) : null, - samples5h: st5h?.rateSamples || 0, - samplesWeekly: stWk?.rateSamples || 0, + eqFull5hUsd: rawPoolEq5hUsd ? +rawPoolEq5hUsd.toFixed(1) : null, + eqFullWeeklyUsd: rawPoolEqWkUsd ? +rawPoolEqWkUsd.toFixed(1) : null, + ...(poolEq5hTok !== null ? { eqFull5hTokens: poolEq5hTok } : {}), + ...(poolEqWkTok !== null ? { eqFullWeeklyTokens: poolEqWkTok } : {}), + samples5h: resolved5h ? resolved5h.samples : st5h?.rateSamples || 0, + samplesWeekly: resolvedWk ? resolvedWk.samples : stWk?.rateSamples || 0, + source5h: resolved5h ? resolved5h.source : null, + sourceWeekly: resolvedWk ? resolvedWk.source : null, + isPreliminary5h: Boolean(resolved5h?.isPreliminary), + isPreliminaryWeekly: Boolean(resolvedWk?.isPreliminary), models, ...(externalUsage ? { externalUsage } : {}), }; @@ -578,6 +862,50 @@ function qrDetectProportionalExternalJump(st5h, stWk, params5h, paramsWk) { return usdRatio >= QR_CO_MOVE_MIN_USD_RATIO && usdRatio <= QR_CO_MOVE_MAX_USD_RATIO; } +function qrReconcileExternalUsageBound(st, safeUsed, safeCost, safeModelCosts, nowMs) { + if (!st || (!st.hasExternalUsage && !(Number(st.externalUsedPct) > 0))) return false; + const leaseSum = qrSumLeases(st.activeLeases || [], { includeTentative: true }); + const cleanWin = Array.isArray(st.rateWindow) ? st.rateWindow : []; + const isCalibrated = + cleanWin.length >= QR_MODEL_RATE_MIN_UI_SAMPLES && + (st.lastUnpricedCalls || 0) === 0 && + Number.isFinite(st.ratePctPerUsd) && + st.ratePctPerUsd > 0; + const localExpectedPct = isCalibrated + ? qrEstimateModelWeightedPct(st, safeModelCosts, safeCost, st.ratePctPerUsd) + : 0; + // 本周期累计外部消耗物理上不可能超过(官方累计已用 - 活跃租约 - 已校准本机保守下界) + const localConservativeFloor = localExpectedPct * 0.9; + const maxExternalBound = Math.max(0, safeUsed - leaseSum - localConservativeFloor); + let mutated = false; + const curExtPct = Number(st.externalUsedPct) || 0; + if (curExtPct > maxExternalBound + 1e-3) { + const clamped = maxExternalBound < QR_MIN_DISPLAY_RESERVED_PCT ? 0 : maxExternalBound; + if (Math.abs(curExtPct - clamped) > 1e-3) { + st.externalUsedPct = clamped; + mutated = true; + } + } + const recentExt = + (Number(st.lastExternalUsageAtMs) || 0) > 0 && + nowMs >= st.lastExternalUsageAtMs && + nowMs - st.lastExternalUsageAtMs <= QR_EXTERNAL_ACTIVE_WINDOW_MS; + if ( + isCalibrated && + st.hasExternalUsage && + !recentExt && + (Number(st.externalUsedPct) || 0) === 0 && + safeUsed >= 0.05 && + maxExternalBound < QR_EXTERNAL_MIN_IDLE_DELTA_PCT + ) { + st.hasExternalUsage = false; + st.externalEvents = 0; + st.lastExternalUsageAtMs = 0; + mutated = true; + } + return mutated; +} + function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { if (!raw || typeof raw !== 'object') return null; const lastOfficial = @@ -605,8 +933,20 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { lastQuotaTs: Math.max(0, Number(raw.lastQuotaTs) || 0), lastOfficialUsedPct: lastOfficial, lastCycleCostUsd: Math.max(0, Number(raw.lastCycleCostUsd) || 0), + lastCycleCalls: Math.max(0, Math.floor(Number(raw.lastCycleCalls) || 0)), + lastPricedTokens: Math.max(0, Math.floor(Number(raw.lastPricedTokens) || 0)), lastModelCostsUsd: qrSanitizeModelCosts(raw.lastModelCostsUsd), lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0), + usdPerMTok: preserveRate ? qrClampUsdPerMTok(raw.usdPerMTok) : null, + priorUsdPerMTok: preserveRate + ? qrClampUsdPerMTok(raw.priorUsdPerMTok ?? raw.usdPerMTok) + : null, + modelUsdPerMTok: qrSanitizeModelDensities(raw.modelUsdPerMTok, { preserveRate }), + priorModelUsdPerMTok: qrSanitizeModelDensities( + raw.priorModelUsdPerMTok ?? raw.modelUsdPerMTok, + { preserveRate } + ), + slopeSamples: preserveRate ? qrSanitizeSlopeSamples(raw.slopeSamples) : [], pendingCostUsd: 0, pendingCostAtMs: 0, pendingCostSinceMs: 0, @@ -622,6 +962,7 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0), lastRefundAtMs: Math.max(0, Number(raw.lastRefundAtMs) || 0), lastRefundPct: Math.max(0, Number(raw.lastRefundPct) || 0), + lastRefundHighWaterPct: qrClamp(Math.max(0, Number(raw.lastRefundHighWaterPct) || 0), 0, 100), hasExternalUsage: raw.hasExternalUsage === true, lastExternalUsageAtMs: Math.max(0, Number(raw.lastExternalUsageAtMs) || 0), externalUsedPct: Math.max(0, Number(raw.externalUsedPct) || 0), @@ -639,6 +980,8 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const eventLog = []; let hydrated = typeof loadState !== 'function'; let lastPersistMs = 0; + let batchingDepth = 0; + let batchPendingEvent = null; function ensureHydrated() { if (hydrated) return; @@ -686,8 +1029,25 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastQuotaTs: st.lastQuotaTs, lastOfficialUsedPct: st.lastOfficialUsedPct, lastCycleCostUsd: st.lastCycleCostUsd, + lastCycleCalls: st.lastCycleCalls || 0, + lastPricedTokens: st.lastPricedTokens || 0, lastModelCostsUsd: st.lastModelCostsUsd || {}, lastUnpricedCalls: st.lastUnpricedCalls, + ...(st.usdPerMTok !== null && Number.isFinite(st.usdPerMTok) + ? { usdPerMTok: +st.usdPerMTok.toFixed(4) } + : {}), + ...(st.priorUsdPerMTok !== null && Number.isFinite(st.priorUsdPerMTok) + ? { priorUsdPerMTok: +st.priorUsdPerMTok.toFixed(4) } + : {}), + ...(st.modelUsdPerMTok && Object.keys(st.modelUsdPerMTok).length > 0 + ? { modelUsdPerMTok: st.modelUsdPerMTok } + : {}), + ...(st.priorModelUsdPerMTok && Object.keys(st.priorModelUsdPerMTok).length > 0 + ? { priorModelUsdPerMTok: st.priorModelUsdPerMTok } + : {}), + ...(Array.isArray(st.slopeSamples) && st.slopeSamples.length > 0 + ? { slopeSamples: st.slopeSamples } + : {}), ratePctPerUsd: st.ratePctPerUsd, rateSamples: st.rateSamples, rateWindow: st.rateWindow, @@ -697,6 +1057,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastBounceAtMs: st.lastBounceAtMs, lastRefundAtMs: st.lastRefundAtMs, lastRefundPct: st.lastRefundPct, + ...(Number(st.lastRefundHighWaterPct) > 0 + ? { lastRefundHighWaterPct: +Number(st.lastRefundHighWaterPct).toFixed(4) } + : {}), hasExternalUsage: Boolean(st.hasExternalUsage), lastExternalUsageAtMs: st.lastExternalUsageAtMs || 0, externalUsedPct: +(Number(st.externalUsedPct) || 0).toFixed(3), @@ -730,6 +1093,12 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu eventKind === 'refund' || eventKind === 'reset' || eventKind === 'expire'; + if (batchingDepth > 0) { + if (isUrgent || !batchPendingEvent) { + batchPendingEvent = isUrgent ? 'lease' : eventKind; + } + return; + } if (!isUrgent && lastPersistMs > 0 && nowMs - lastPersistMs < QR_PERSIST_MIN_INTERVAL_MS) { return; } @@ -765,8 +1134,15 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastQuotaTs: 0, lastOfficialUsedPct: null, lastCycleCostUsd: 0, + lastCycleCalls: 0, + lastPricedTokens: 0, lastModelCostsUsd: {}, lastUnpricedCalls: 0, + usdPerMTok: null, + priorUsdPerMTok: null, + modelUsdPerMTok: {}, + priorModelUsdPerMTok: {}, + slopeSamples: [], pendingCostUsd: 0, pendingCostAtMs: 0, pendingCostSinceMs: 0, @@ -782,6 +1158,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastBounceAtMs: 0, lastRefundAtMs: 0, lastRefundPct: 0, + lastRefundHighWaterPct: 0, hasExternalUsage: false, lastExternalUsageAtMs: 0, externalUsedPct: 0, @@ -799,7 +1176,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu resetTimeMs = 0, quotaFetchedAtMs = 0, cycleCostUsd = 0, + cycleCalls = 0, + pricedTokens = 0, modelCostsUsd = null, + modelTokens = null, unpricedCalls = 0, poolLastActivityMs = 0, activeSessionCount10m = 0, @@ -815,7 +1195,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu ensureHydrated(); const safeUsed = qrClamp(Number(officialUsedPct), 0, 100); const safeCost = Math.max(0, Number(cycleCostUsd) || 0); + const safeCalls = Math.max(0, Math.floor(Number(cycleCalls) || 0)); + const safePricedTokens = Math.max(0, Math.floor(Number(pricedTokens) || 0)); const safeModelCosts = qrSanitizeModelCosts(modelCostsUsd); + const safeModelTokens = qrSanitizeModelTokens(modelTokens); const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0); const safeResetMs = Number(resetTimeMs) > 0 ? Number(resetTimeMs) : 0; const safeFetchTs = Number(quotaFetchedAtMs) > 0 ? Number(quotaFetchedAtMs) : nowMs; @@ -868,33 +1251,57 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastCycleCalls = safeCalls; + st.lastPricedTokens = safePricedTokens; st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; if (isIdleZeroDrift) { + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); return qrFormatOutput(st, safeUsed); } + if (st.usdPerMTok !== null && Number.isFinite(st.usdPerMTok)) { + st.priorUsdPerMTok = st.usdPerMTok; + } + if (st.modelUsdPerMTok && Object.keys(st.modelUsdPerMTok).length > 0) { + st.priorModelUsdPerMTok = { + ...(st.priorModelUsdPerMTok || {}), + ...st.modelUsdPerMTok, + }; + } + st.slopeSamples = []; st.pendingCostUsd = 0; st.pendingCostAtMs = 0; st.pendingCostSinceMs = 0; st.pendingModelCostsUsd = {}; st.activeLeases = []; st.pendingDrop = null; + st.lastRefundHighWaterPct = 0; st.hasExternalUsage = safeUsed >= QR_EXTERNAL_BASELINE_USED_PCT && safeCost < QR_EXTERNAL_BASELINE_MAX_LOCAL_COST_USD; st.externalUsedPct = 0; st.externalEvents = 0; + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + qrUpdateSlopeSamples( + st, + qrComputeNetLocalUsedPct(st, safeUsed), + safeCost, + safeCalls, + safeUnpriced + ); const out = qrFormatOutput(st, safeUsed); recordLog('reset', { deltaOfficial: safeUsed - prevUsed, ...out }); return out; } - // 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(检测到外部消耗时跳过累计比值反推) + // 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(检测到外部消耗或未计价调用时跳过累计比值反推) if (st.lastOfficialUsedPct === null) { st.resetTimeMs = safeResetMs; st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastCycleCalls = safeCalls; + st.lastPricedTokens = safePricedTokens; st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; if ( @@ -902,10 +1309,23 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu safeCost < QR_EXTERNAL_BASELINE_MAX_LOCAL_COST_USD ) { st.hasExternalUsage = true; - } else if (!st.hasExternalUsage && safeCost >= 0.5 && safeUsed >= 0.3) { + } else if ( + !st.hasExternalUsage && + safeUnpriced === 0 && + safeCost >= 0.5 && + safeUsed >= 0.3 + ) { st.ratePctPerUsd = qrClampRate(safeUsed / safeCost); st.rateSamples = 1; } + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + qrUpdateSlopeSamples( + st, + qrComputeNetLocalUsedPct(st, safeUsed), + safeCost, + safeCalls, + safeUnpriced + ); const out = qrFormatOutput(st, safeUsed); recordLog('baseline', out); return out; @@ -925,11 +1345,35 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu ) { st.lastModelCostsUsd = safeModelCosts; } + if (st.lastCycleCalls === 0 || Math.abs(safeCost - st.lastCycleCostUsd) <= 1e-4) { + st.lastCycleCalls = safeCalls; + } + st.lastPricedTokens = safePricedTokens; + const prevDensity = st.usdPerMTok; + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + const extReconciled = qrReconcileExternalUsageBound( + st, + safeUsed, + st.lastCycleCostUsd, + st.lastModelCostsUsd, + nowMs + ); const beforeCachePrune = st.activeLeases.length; qrPruneExpiredLeases(st, nowMs); const out = qrFormatOutput(st, safeUsed); if (beforeCachePrune > st.activeLeases.length) { + qrResetSlopeAnchor( + st, + qrComputeNetLocalUsedPct(st, safeUsed), + st.lastCycleCostUsd, + st.lastCycleCalls, + st.lastUnpricedCalls + ); recordLog('expire', out); + } else if (extReconciled) { + persistIfNeeded('external_usage', nowMs); + } else if (prevDensity === null && st.usdPerMTok !== null) { + persistIfNeeded('normal', nowMs); } return out; } @@ -1018,10 +1462,27 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingModelCostsUsd = {}; }; - const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => { + const confirmRefund = ( + refundedPct, + { keepPendingCost = false, preRefundHighPct = 0 } = {} + ) => { const amt = Math.max(0, Number(refundedPct) || 0); - if (amt > 0) { - qrConsumeLeasesFifo(st.activeLeases, amt); + const prevHighWater = + st.lastRefundAtMs > 0 && nowMs - st.lastRefundAtMs <= QR_REPLICA_BOUNCE_MEMORY_MS + ? Number(st.lastRefundHighWaterPct) || 0 + : 0; + st.lastRefundHighWaterPct = Math.max( + prevHighWater, + Number(preRefundHighPct) || 0, + Number(st.lastOfficialUsedPct) || 0 + ); + const leaseConsumed = amt > 0 ? qrConsumeLeasesFifo(st.activeLeases, amt) : 0; + const unbackedDrop = Math.max(0, amt - leaseConsumed); + if (unbackedDrop > 0 && (Number(st.externalUsedPct) || 0) > 0) { + st.externalUsedPct = Math.max(0, (Number(st.externalUsedPct) || 0) - unbackedDrop); + if (st.externalUsedPct < QR_MIN_DISPLAY_RESERVED_PCT) { + st.externalUsedPct = 0; + } } st.lastRefundAtMs = nowMs; st.lastRefundPct = amt; @@ -1049,7 +1510,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu clearPendingCost(); if (isIdleRefundReady) { - confirmRefund(totalDrop); + confirmRefund(totalDrop, { preRefundHighPct: prevHigh }); } else if (st.pendingDrop) { st.pendingDrop.preDropUsedPct = prevHigh; st.pendingDrop.lowestUsedPct = Math.min(st.pendingDrop.lowestUsedPct, safeUsed); @@ -1059,7 +1520,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingDrop.lowSamples >= QR_REFUND_CONFIRM_MIN_SAMPLES && nowMs - st.pendingDrop.droppedAtMs >= QR_REFUND_CONFIRM_WINDOW_MS ) { - confirmRefund(st.pendingDrop.dropPct); + confirmRefund(st.pendingDrop.dropPct, { preRefundHighPct: prevHigh }); } else { eventKind = 'drop_pending'; } @@ -1141,6 +1602,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const effectiveDrop = Math.max(0, pd.preDropUsedPct + expectedSinceDrop - safeUsed); confirmRefund(effectiveDrop > 0 ? Math.min(pd.dropPct, effectiveDrop) : pd.dropPct, { keepPendingCost: deltaOfficial <= 1e-3 && st.pendingCostUsd > 0, + preRefundHighPct: pd.preDropUsedPct, }); } else if (deltaOfficial > 1e-3) { clearPendingCost(); @@ -1154,9 +1616,19 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu } } } else if (deltaOfficial > 1e-3) { - // 4B. 官方已用比例上升:先筛除外部/家庭组消耗,再区分租约跳变、真实租约内消费及常规消耗 + // 4B. 官方已用比例上升:先筛除退还后多副本回弹及外部/家庭组消耗,再区分租约跳变、租约内消费及常规消耗 + const isPostRefundReplicaBounce = + !forceExternalJump && + !hasLocalPoolActivity && + st.lastRefundAtMs > 0 && + nowMs >= st.lastRefundAtMs && + nowMs - st.lastRefundAtMs <= QR_REPLICA_BOUNCE_MEMORY_MS && + (Number(st.lastRefundHighWaterPct) || 0) > 0 && + safeUsed <= (Number(st.lastRefundHighWaterPct) || 0) + QR_REFUND_EPSILON_PCT; const isIdleExternalUsage = - !hasLocalPoolActivity && deltaOfficial >= QR_EXTERNAL_MIN_IDLE_DELTA_PCT; + !isPostRefundReplicaBounce && + !hasLocalPoolActivity && + deltaOfficial >= QR_EXTERNAL_MIN_IDLE_DELTA_PCT; const detectedWithRate = rate !== null && excessPct >= QR_MIN_JUMP_EXCESS_PCT; const detectedColdStart = rate === null && @@ -1168,7 +1640,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu expectedDeltaPct > 0 && shortfall >= Math.max(QR_CONSUME_MIN_SHORTFALL_PCT, expectedDeltaPct * QR_CONSUME_SHORTFALL_RATIO); - if (forceExternalJump || isIdleExternalUsage) { + if (isPostRefundReplicaBounce) { + st.lastBounceAtMs = nowMs; + eventKind = 'replica_flip'; + } else if (forceExternalJump || isIdleExternalUsage) { const extAmt = forceExternalJump && excessPct > 0 ? excessPct : deltaOfficial; recordExternalDelta(extAmt); @@ -1323,16 +1798,35 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastCycleCalls = safeCalls; + st.lastPricedTokens = safePricedTokens; st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; // 5. 租约 TTL 超时兜底(租约本身超过 60 分钟无实质扣减或满 90 分钟自动清理) const beforePrune = st.activeLeases.length; qrPruneExpiredLeases(st, nowMs); - if (beforePrune > st.activeLeases.length && eventKind === 'idle') { + const prunedExpiredLeases = beforePrune > st.activeLeases.length; + if (prunedExpiredLeases && eventKind === 'idle') { eventKind = 'expire'; } + const prevDensity = st.usdPerMTok; + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + const extReconciled = qrReconcileExternalUsageBound( + st, + safeUsed, + safeCost, + safeModelCosts, + nowMs + ); + const netLocalUsed = qrComputeNetLocalUsedPct(st, safeUsed); + if (prunedExpiredLeases) { + qrResetSlopeAnchor(st, netLocalUsed, safeCost, safeCalls, safeUnpriced); + } else { + qrUpdateSlopeSamples(st, netLocalUsed, safeCost, safeCalls, safeUnpriced); + } + const out = qrFormatOutput(st, safeUsed); if (eventKind !== 'idle') { recordLog(eventKind, { @@ -1342,6 +1836,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu excessPct, ...out, }); + } else if (extReconciled) { + persistIfNeeded('external_usage', nowMs); + } else if (prevDensity === null && st.usdPerMTok !== null) { + persistIfNeeded('normal', nowMs); } return out; } @@ -1361,119 +1859,145 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const normalizedAccountScope = String(accountScope || '').trim().toLowerCase(); const scopePrefix = `${String(endpointId || 'local')}::${normalizedAccountScope}`; - 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 hasRunningLocalSession = Boolean( - hasUnknownRunningPool || - (runningPoolKeys instanceof Set && runningPoolKeys.has(poolKey)) - ); + batchingDepth += 1; + try { + 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 hasRunningLocalSession = Boolean( + hasUnknownRunningPool || + (runningPoolKeys instanceof Set && runningPoolKeys.has(poolKey)) + ); - const key5h = `${scopePrefix}::${poolKey}::5h`; - const keyWk = `${scopePrefix}::${poolKey}::weekly`; - const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null; - const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; - const reset5hMs = parseIsoMs(poolObj.resetTime); - const resetWkMs = parseIsoMs(poolObj.weeklyResetTime); - const cost5hUsd = pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0; - const costWkUsd = pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0; - const modelCosts5h = pStats?.modelCosts5h || null; - const modelCostsWk = pStats?.modelCostsWeekly || null; + const key5h = `${scopePrefix}::${poolKey}::5h`; + const keyWk = `${scopePrefix}::${poolKey}::weekly`; + const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null; + const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; + const reset5hMs = parseIsoMs(poolObj.resetTime); + const resetWkMs = parseIsoMs(poolObj.weeklyResetTime); + const cost5hUsd = pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0; + const costWkUsd = pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0; + const calls5h = pStats?.cycle5h?.calls || 0; + const callsWk = pStats?.cycleWeekly?.calls || 0; + const unpriced5h = pStats?.cycle5h?.unpricedCalls || 0; + const unpricedWk = pStats?.cycleWeekly?.unpricedCalls || 0; + const pricedTokens5h = + pStats?.pricedTokens5h ?? (unpriced5h === 0 ? pStats?.cycle5h?.tokens || 0 : 0); + const pricedTokensWk = + pStats?.pricedTokensWeekly ?? (unpricedWk === 0 ? pStats?.cycleWeekly?.tokens || 0 : 0); + const modelCosts5h = pStats?.modelCosts5h || null; + const modelCostsWk = pStats?.modelCostsWeekly || null; + const modelTokens5h = pStats?.modelTokens5h || null; + const modelTokensWk = pStats?.modelTokensWeekly || null; - const prev5hSt = buckets.get(key5h) || null; - const prevWkSt = buckets.get(keyWk) || null; - const peerExtTs5h = Number(prevWkSt?.lastExternalUsageAtMs) || 0; - const peerExtTsWk = Number(prev5hSt?.lastExternalUsageAtMs) || 0; + const prev5hSt = buckets.get(key5h) || null; + const prevWkSt = buckets.get(keyWk) || null; + const peerExtTs5h = Number(prevWkSt?.lastExternalUsageAtMs) || 0; + const peerExtTsWk = Number(prev5hSt?.lastExternalUsageAtMs) || 0; - // 第 2 层:同一快照下 5h / 周限按已校准费率等比同涨 -> 判定为同一笔家庭组/外部真实消耗而非租约 - const isProportionalExternal = - used5hExact !== null && usedWkExact !== null - ? qrDetectProportionalExternalJump( - prev5hSt, - prevWkSt, - { + // 第 2 层:同一快照下 5h / 周限按已校准费率等比同涨 -> 判定为同一笔家庭组/外部真实消耗而非租约 + const isProportionalExternal = + used5hExact !== null && usedWkExact !== null + ? qrDetectProportionalExternalJump( + prev5hSt, + prevWkSt, + { + officialUsedPct: used5hExact, + resetTimeMs: reset5hMs, + quotaFetchedAtMs, + cycleCostUsd: cost5hUsd, + modelCostsUsd: modelCosts5h, + nowMs, + }, + { + officialUsedPct: usedWkExact, + resetTimeMs: resetWkMs, + quotaFetchedAtMs, + cycleCostUsd: costWkUsd, + modelCostsUsd: modelCostsWk, + nowMs, + } + ) + : false; + + const res5h = + used5hExact !== null + ? observeBucket({ + bucketKey: key5h, + poolKey, + win: '5h', officialUsedPct: used5hExact, resetTimeMs: reset5hMs, quotaFetchedAtMs, cycleCostUsd: cost5hUsd, + cycleCalls: calls5h, + pricedTokens: pricedTokens5h, modelCostsUsd: modelCosts5h, + modelTokens: modelTokens5h, + unpricedCalls: unpriced5h, + poolLastActivityMs, + activeSessionCount10m, + recent10mCostUsd, + hasRunningLocalSession, + forceExternalJump: isProportionalExternal, + peerLastExternalUsageAtMs: peerExtTs5h, nowMs, - }, - { + }) + : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; + + const updated5hExtTs = Math.max( + peerExtTsWk, + Number(buckets.get(key5h)?.lastExternalUsageAtMs) || 0 + ); + + const resWk = + usedWkExact !== null + ? observeBucket({ + bucketKey: keyWk, + poolKey, + win: 'weekly', officialUsedPct: usedWkExact, resetTimeMs: resetWkMs, quotaFetchedAtMs, cycleCostUsd: costWkUsd, + cycleCalls: callsWk, + pricedTokens: pricedTokensWk, modelCostsUsd: modelCostsWk, + modelTokens: modelTokensWk, + unpricedCalls: unpricedWk, + poolLastActivityMs, + activeSessionCount10m, + recent10mCostUsd, + hasRunningLocalSession, + forceExternalJump: isProportionalExternal, + peerLastExternalUsageAtMs: updated5hExtTs, nowMs, - } - ) - : false; + }) + : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; - const res5h = - used5hExact !== null - ? observeBucket({ - bucketKey: key5h, - poolKey, - win: '5h', - officialUsedPct: used5hExact, - resetTimeMs: reset5hMs, - quotaFetchedAtMs, - cycleCostUsd: cost5hUsd, - modelCostsUsd: modelCosts5h, - unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0, - poolLastActivityMs, - activeSessionCount10m, - recent10mCostUsd, - hasRunningLocalSession, - forceExternalJump: isProportionalExternal, - peerLastExternalUsageAtMs: peerExtTs5h, - nowMs, - }) - : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; - - const updated5hExtTs = Math.max( - peerExtTsWk, - Number(buckets.get(key5h)?.lastExternalUsageAtMs) || 0 - ); - - const resWk = - usedWkExact !== null - ? observeBucket({ - bucketKey: keyWk, - poolKey, - win: 'weekly', - officialUsedPct: usedWkExact, - resetTimeMs: resetWkMs, - quotaFetchedAtMs, - cycleCostUsd: costWkUsd, - modelCostsUsd: modelCostsWk, - unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0, - poolLastActivityMs, - activeSessionCount10m, - recent10mCostUsd, - hasRunningLocalSession, - forceExternalJump: isProportionalExternal, - peerLastExternalUsageAtMs: updated5hExtTs, - 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; - poolObj.rateEstimate = qrBuildPoolRateEstimate( - buckets.get(key5h) || null, - buckets.get(keyWk) || null, - nowMs - ); + poolObj.reservedPct = res5h.reservedPct; + poolObj.reservedLeaseCount = res5h.reservedLeaseCount; + poolObj.reservedExpiresAtMs = res5h.reservedExpiresAtMs; + poolObj.weeklyReservedPct = resWk.reservedPct; + poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount; + poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs; + poolObj.rateEstimate = qrBuildPoolRateEstimate( + buckets.get(key5h) || null, + buckets.get(keyWk) || null, + nowMs + ); + } + } finally { + batchingDepth = Math.max(0, batchingDepth - 1); + if (batchingDepth === 0 && batchPendingEvent) { + const pending = batchPendingEvent; + batchPendingEvent = null; + persistIfNeeded(pending, nowMs); + } } } @@ -1525,6 +2049,8 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu buckets.clear(); eventLog.length = 0; lastPersistMs = 0; + batchingDepth = 0; + batchPendingEvent = null; hydrated = true; } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index ca4f86a..7a8d93e 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -2249,6 +2249,16 @@ export async function buildTelemetryPayloadInternal( }); } + const sortedQuotaPools = Array.from(quotaPoolsMap.values()).sort((a, b) => { + const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; + return (order[a.family] ?? 99) - (order[b.family] ?? 99); + }); + const weeklyCapacityEstimate = buildWeeklyCapacityEstimate({ + sortedPools: sortedQuotaPools, + isCustomWeeklyMode, + hasOfficialData: Boolean(officialQuotaInfo?.data), + }); + const finalPayload = { timestamp: new Date().toISOString(), hostPlatform: process.platform || 'unknown', @@ -2356,11 +2366,9 @@ export async function buildTelemetryPayloadInternal( errorMessage: officialQuotaInfo?.error || null, }, activePool: activePoolQuota, - pools: Array.from(quotaPoolsMap.values()).sort((a, b) => { - const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; - return (order[a.family] ?? 99) - (order[b.family] ?? 99); - }), + pools: sortedQuotaPools, weekly: weeklyQuota, + weeklyCapacityEstimate, }, modelBreakdown, }; @@ -2556,6 +2564,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { quotas: { activePool: activePoolQuota, weekly: weeklyQuota, + weeklyCapacityEstimate: snap.basePayload.quotas?.weeklyCapacityEstimate || null, }, consumption: { session: sessionUsage.finalizedSelectedSession, @@ -2565,6 +2574,120 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { }; } +function buildWeeklyCapacityEstimate({ + sortedPools = [], + isCustomWeeklyMode = false, + hasOfficialData = false, +} = {}) { + if (isCustomWeeklyMode) { + return { + status: 'custom_mode', + totalEqWeeklyUsd: null, + totalEqWeeklyTokens: null, + readyPoolCount: 0, + totalPoolCount: 0, + hasPreliminary: false, + pools: [], + }; + } + const rawPools = Array.isArray(sortedPools) ? sortedPools : []; + const candidatePools = rawPools.filter( + (p) => + p && + (p.hasWeekly || + p.weeklyUsedPct != null || + Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) + ); + const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; + if (!hasOfficialData && targetPools.length === 0) { + return { + status: 'unavailable', + totalEqWeeklyUsd: null, + totalEqWeeklyTokens: null, + readyPoolCount: 0, + totalPoolCount: 0, + hasPreliminary: false, + pools: [], + }; + } + + let sumUsd = 0; + let sumTokens = 0; + let readyPoolCount = 0; + let tokenReadyPoolCount = 0; + let hasPreliminary = false; + const pools = []; + + for (const p of targetPools) { + const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; + let eqUsd = + Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 + ? Number(est.eqFullWeeklyUsd) + : null; + let eqTok = + Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 + ? Math.round(Number(est.eqFullWeeklyTokens)) + : null; + if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { + const wkModels = est.models.filter( + (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 + ); + if (wkModels.length > 0) { + eqUsd = + wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; + const tokModels = wkModels.filter( + (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 + ); + if (tokModels.length === wkModels.length) { + eqTok = Math.round( + tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length + ); + } + } + } + + const isPrelim = Boolean(est?.isPreliminaryWeekly); + if (eqUsd !== null) { + readyPoolCount += 1; + sumUsd += eqUsd; + if (isPrelim) hasPreliminary = true; + if (eqTok !== null) { + tokenReadyPoolCount += 1; + sumTokens += eqTok; + } + } + + pools.push({ + poolKey: p.poolKey || p.family || '', + poolLabel: p.poolLabel || p.family || p.poolKey || 'Pool', + usedWeeklyPct: Number.isFinite(Number(p.weeklyUsedPct)) ? +Number(p.weeklyUsedPct).toFixed(1) : null, + eqFullWeeklyUsd: eqUsd !== null ? +eqUsd.toFixed(1) : null, + eqFullWeeklyTokens: eqTok, + source: est?.sourceWeekly || null, + isPreliminary: isPrelim, + }); + } + + const totalPoolCount = pools.length; + const status = + readyPoolCount === 0 + ? 'collecting' + : readyPoolCount < totalPoolCount + ? 'partial' + : 'ready'; + + return { + status, + totalEqWeeklyUsd: readyPoolCount > 0 ? +sumUsd.toFixed(1) : null, + totalEqWeeklyTokens: + readyPoolCount > 0 && tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, + readyPoolCount, + totalPoolCount, + hasPreliminary, + pools, + }; +} + function enrichTopConversationTitles(topList, convSummaries) { if (!Array.isArray(topList) || topList.length === 0) return []; const titleMap = new Map(); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 22d6655..60e4f6f 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -794,8 +794,12 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { startWkMs, b5h: createUsageBucket(), bWk: createUsageBucket(), + pricedTokens5h: 0, + pricedTokensWk: 0, modelCosts5h: new Map(), modelCostsWk: new Map(), + modelTokens5h: new Map(), + modelTokensWk: new Map(), lastActivityMs: 0, recent10mSessions: new Map(), }); @@ -1610,20 +1614,38 @@ export function aggregateMultiWindowUsage({ const quotaModelKey = mInfo.baseLabel || mInfo.label || ''; if (qMs >= poolBucketEntry.start5hMs) { accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); + if (stepUsage.resolvedCost > 0 && stepTotalTokens > 0) { + poolBucketEntry.pricedTokens5h += stepTotalTokens; + } if (quotaModelKey && stepUsage.resolvedCost > 0) { poolBucketEntry.modelCosts5h.set( quotaModelKey, (poolBucketEntry.modelCosts5h.get(quotaModelKey) || 0) + stepUsage.resolvedCost ); + if (stepTotalTokens > 0) { + poolBucketEntry.modelTokens5h.set( + quotaModelKey, + (poolBucketEntry.modelTokens5h.get(quotaModelKey) || 0) + stepTotalTokens + ); + } } } if (qMs >= poolBucketEntry.startWkMs) { accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); + if (stepUsage.resolvedCost > 0 && stepTotalTokens > 0) { + poolBucketEntry.pricedTokensWk += stepTotalTokens; + } if (quotaModelKey && stepUsage.resolvedCost > 0) { poolBucketEntry.modelCostsWk.set( quotaModelKey, (poolBucketEntry.modelCostsWk.get(quotaModelKey) || 0) + stepUsage.resolvedCost ); + if (stepTotalTokens > 0) { + poolBucketEntry.modelTokensWk.set( + quotaModelKey, + (poolBucketEntry.modelTokensWk.get(quotaModelKey) || 0) + stepTotalTokens + ); + } } } } @@ -1836,6 +1858,16 @@ export function aggregateMultiWindowUsage({ } return out; }; + const serializeModelTokens = (mMap) => { + const out = {}; + if (!(mMap instanceof Map)) return out; + for (const [mKey, tokVal] of mMap.entries()) { + if (mKey && Number.isFinite(tokVal) && tokVal > 0) { + out[mKey] = Math.round(tokVal); + } + } + return out; + }; for (const [poolKey, entry] of poolCycleBuckets.entries()) { let recent10mCostUsd = 0; for (const sStat of entry.recent10mSessions.values()) { @@ -1844,10 +1876,14 @@ export function aggregateMultiWindowUsage({ poolCycleStats.set(poolKey, { cycle5h: formatCycleSummary(entry.b5h), cycleWeekly: formatCycleSummary(entry.bWk), + pricedTokens5h: Math.round(entry.pricedTokens5h || 0), + pricedTokensWeekly: Math.round(entry.pricedTokensWk || 0), exactCost5hUsd: +entry.b5h.costUsd.toFixed(6), exactCostWeeklyUsd: +entry.bWk.costUsd.toFixed(6), modelCosts5h: serializeModelCosts(entry.modelCosts5h), modelCostsWeekly: serializeModelCosts(entry.modelCostsWk), + modelTokens5h: serializeModelTokens(entry.modelTokens5h), + modelTokensWeekly: serializeModelTokens(entry.modelTokensWk), recent10m: { lastActivityMs: entry.lastActivityMs, activeSessionCount: entry.recent10mSessions.size, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 75d4058..7ca2a9b 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index 2fcbd3a..157d4dc 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -244,21 +244,24 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.title5h, `5h (${poolLabel})`); const c5h = poolData?.cycle5h; + const est = poolData?.rateEstimate; if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) { const tok5h = formatTokens(c5h.tokens || 0); const cost5h = formatUsd(c5h.costUsd || 0); const calls5h = Number(c5h.calls || 0); + const full5hRef = formatPoolFullCapRef(est?.eqFull5hUsd, est?.eqFull5hTokens); + const baseTip5h = t('quota.cycle5hTitle', { + pool: poolLabel, + tok: tok5h, + cost: cost5h, + calls: calls5h, + }); refs.usage5h.hidden = false; patchText(refs.usage5h, `· ${tok5h} (${cost5h})`); patchAttr( refs.left5h, 'title', - t('quota.cycle5hTitle', { - pool: poolLabel, - tok: tok5h, - cost: cost5h, - calls: calls5h, - }) + full5hRef ? `${baseTip5h} · ${t('quota.cycleFullSuffix', { full: full5hRef })}` : baseTip5h ); } else { refs.usage5h.hidden = true; @@ -291,19 +294,23 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { const tokWk = formatTokens(cWk.tokens || 0); const costWk = formatUsd(cWk.costUsd || 0); const callsWk = Number(cWk.calls || 0); + const fullWkRef = !useCustomWeekly + ? formatPoolFullCapRef(est?.eqFullWeeklyUsd, est?.eqFullWeeklyTokens) + : ''; + const baseTipWk = useCustomWeekly + ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) + : t('quota.cycleWkPoolTitle', { + pool: poolLabel, + tok: tokWk, + cost: costWk, + calls: callsWk, + }); refs.usageWk.hidden = false; patchText(refs.usageWk, `· ${tokWk} (${costWk})`); patchAttr( refs.leftWk, 'title', - useCustomWeekly - ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) - : t('quota.cycleWkPoolTitle', { - pool: poolLabel, - tok: tokWk, - cost: costWk, - calls: callsWk, - }) + fullWkRef ? `${baseTipWk} · ${t('quota.cycleFullSuffix', { full: fullWkRef })}` : baseTipWk ); } else { refs.usageWk.hidden = true; @@ -328,8 +335,9 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { export function quotaPoolRowSig(item, idx) { const c5h = item.poolData?.cycle5h; const cWk = item.poolData?.cycleWeekly; + const est = item.poolData?.rateEstimate; const fw = item.fallbackWeekly; - 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}`; + 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}:${est?.eqFull5hUsd}:${est?.eqFull5hTokens}:${est?.eqFullWeeklyUsd}:${est?.eqFullWeeklyTokens}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } /** @@ -405,6 +413,99 @@ function formatRateEqUsd(val) { return `$${Number(num.toFixed(1))}`; } +function formatPoolFullCapRef(eqUsd, eqTok) { + const usdNum = Number(eqUsd); + if (!Number.isFinite(usdNum) || usdNum <= 0) return ''; + const usdStr = formatRateEqUsd(usdNum); + const tokNum = Number(eqTok); + if (Number.isFinite(tokNum) && tokNum > 0) { + return `${usdStr} (${formatTokens(tokNum)})`; + } + return usdStr; +} + +function resolveWeeklyCapacitySummary(quotas) { + if (!quotas || typeof quotas !== 'object') return null; + if (quotas.weekly?.isOfficial === false) return null; + const direct = quotas.weeklyCapacityEstimate; + if (direct && typeof direct === 'object') { + if ( + direct.status === 'custom_mode' || + !Number.isFinite(Number(direct.totalEqWeeklyUsd)) || + Number(direct.totalEqWeeklyUsd) <= 0 + ) { + return null; + } + return direct; + } + + const rawPools = Array.isArray(quotas.pools) ? quotas.pools : []; + const candidatePools = rawPools.filter( + (p) => + p && + (p.hasWeekly || + p.weeklyUsedPct != null || + Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) + ); + const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; + if (targetPools.length === 0) return null; + + let sumUsd = 0; + let sumTokens = 0; + let readyPoolCount = 0; + let tokenReadyPoolCount = 0; + let hasPreliminary = false; + + for (const p of targetPools) { + const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; + let eqUsd = + Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 + ? Number(est.eqFullWeeklyUsd) + : null; + let eqTok = + Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 + ? Math.round(Number(est.eqFullWeeklyTokens)) + : null; + if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { + const wkModels = est.models.filter( + (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 + ); + if (wkModels.length > 0) { + eqUsd = + wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; + const tokModels = wkModels.filter( + (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 + ); + if (tokModels.length === wkModels.length) { + eqTok = Math.round( + tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length + ); + } + } + } + if (eqUsd !== null) { + readyPoolCount += 1; + sumUsd += eqUsd; + if (est?.isPreliminaryWeekly) hasPreliminary = true; + if (eqTok !== null) { + tokenReadyPoolCount += 1; + sumTokens += eqTok; + } + } + } + + if (readyPoolCount === 0) return null; + const totalPoolCount = targetPools.length; + return { + status: readyPoolCount < totalPoolCount ? 'partial' : 'ready', + totalEqWeeklyUsd: +sumUsd.toFixed(1), + totalEqWeeklyTokens: tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, + readyPoolCount, + totalPoolCount, + hasPreliminary, + }; +} + function formatRatePerUsdValue(rate) { const num = Number(rate); if (!Number.isFinite(num) || num <= 0) return '--'; @@ -426,7 +527,11 @@ function createRateModelCard({ rateWeeklyPctPerUsd = null, eqFull5hUsd = null, eqFullWeeklyUsd = null, + eqFull5hTokens = null, + eqFullWeeklyTokens = null, samples = 0, + source = null, + isPreliminary = false, }) { const leftNodes = [ h('span', { @@ -455,32 +560,50 @@ function createRateModelCard({ }) ); } - if (Number(samples) > 0) { + if (isPreliminary) { + subParts.push( + source === 'anchor_slope' ? t('quota.ratePopPrelimSlope') : t('quota.ratePopPrelimCycle') + ); + } else if (Number(samples) > 0) { subParts.push(t('quota.ratePopSamples', { n: Number(samples) })); } const eqCells = []; if (eqFull5hUsd != null) { - eqCells.push( - h('div', { className: 'quota-rate-eq-cell' }, [ - h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), + const cell5hChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFull5hTokens)) && Number(eqFull5hTokens) > 0) { + cell5hChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFull5hTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cell5hChildren)); } if (eqFullWeeklyUsd != null) { - eqCells.push( - h('div', { className: 'quota-rate-eq-cell' }, [ - h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + const cellWkChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFullWeeklyTokens)) && Number(eqFullWeeklyTokens) > 0) { + cellWkChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFullWeeklyTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cellWkChildren)); } const cardChildren = [ @@ -507,11 +630,13 @@ function createRateModelCard({ function buildRatePopoverSig(data) { const locale = getEffectiveLocale(); const acct = String(data?.account?.email || data?.account?.name || '').trim(); + const isOfficial = data?.quotas?.weekly?.isOfficial !== false; + const wkCapSig = JSON.stringify(data?.quotas?.weeklyCapacityEstimate || null); const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; const poolSig = pools .map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`) .join('|'); - return `${locale}|${acct}|${poolSig}`; + return `${locale}|${acct}|${isOfficial}|${wkCapSig}|${poolSig}`; } export const QuotaPoolsWidget = defineComponent({ @@ -529,6 +654,27 @@ export const QuotaPoolsWidget = defineComponent({ className: 'quota-rate-pop-account', text: t('quota.ratePopAccountCurrent'), }); + const ratePopWkLabelEl = h('span', { text: t('quota.ratePopWkCapTitle') }); + const ratePopWkSubEl = h('span', { + className: 'quota-rate-wk-sub', + hidden: true, + text: '', + }); + const ratePopWkUsdEl = h('span', { className: 'quota-rate-wk-usd text-mono', text: '--' }); + const ratePopWkTokEl = h('span', { + className: 'quota-rate-wk-tok text-mono', + hidden: true, + text: '', + }); + const ratePopWkSummaryEl = h( + 'div', + { className: 'quota-rate-wk-summary', hidden: true }, + [ + h('span', { className: 'quota-rate-wk-k' }, [ratePopWkLabelEl, ratePopWkSubEl]), + h('span', { className: 'quota-rate-wk-v' }, [ratePopWkUsdEl, ratePopWkTokEl]), + ] + ); + ratePopWkSummaryEl.hidden = true; const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); const ratePopNoteEl = h('div', { className: 'quota-rate-pop-note', @@ -543,6 +689,7 @@ export const QuotaPoolsWidget = defineComponent({ }, [ h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), + ratePopWkSummaryEl, ratePopBodyEl, ratePopNoteEl, ] @@ -634,6 +781,38 @@ export const QuotaPoolsWidget = defineComponent({ ); patchAttr(ratePopAccountEl, 'title', acctMasked || null); + const wkCap = resolveWeeklyCapacitySummary(data?.quotas); + if (wkCap) { + ratePopWkSummaryEl.hidden = false; + patchAttr(ratePopWkSummaryEl, 'hidden', false); + patchText(ratePopWkLabelEl, t('quota.ratePopWkCapTitle')); + const wkSubText = + wkCap.status === 'partial' && Number(wkCap.totalPoolCount) > 0 + ? t('quota.ratePopWkCapPartial', { + ready: Number(wkCap.readyPoolCount) || 0, + total: Number(wkCap.totalPoolCount) || 0, + }) + : wkCap.hasPreliminary + ? t('quota.ratePopWkCapPrelim') + : ''; + ratePopWkSubEl.hidden = !wkSubText; + patchAttr(ratePopWkSubEl, 'hidden', !wkSubText); + patchText(ratePopWkSubEl, wkSubText); + patchText(ratePopWkUsdEl, `≈ ${formatRateEqUsd(wkCap.totalEqWeeklyUsd)}`); + const hasWkTok = + Number.isFinite(Number(wkCap.totalEqWeeklyTokens)) && + Number(wkCap.totalEqWeeklyTokens) > 0; + ratePopWkTokEl.hidden = !hasWkTok; + patchAttr(ratePopWkTokEl, 'hidden', !hasWkTok); + patchText( + ratePopWkTokEl, + hasWkTok ? `· ${formatTokens(Number(wkCap.totalEqWeeklyTokens))}` : '' + ); + } else { + ratePopWkSummaryEl.hidden = true; + patchAttr(ratePopWkSummaryEl, 'hidden', true); + } + while (ratePopBodyEl.firstChild) { ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); } @@ -652,19 +831,45 @@ export const QuotaPoolsWidget = defineComponent({ if (models.length === 0 && !hasPoolFallback && !ext) continue; const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; + const fallbackPrimaryIs5h = est.rate5hPctPerUsd != null; + const anyModelHasWeekly = models.some((m) => m?.eqFullWeeklyUsd != null); + const needsWeeklyFallbackRow = + models.length > 0 && + !anyModelHasWeekly && + Number.isFinite(est.rateWeeklyPctPerUsd) && + est.eqFullWeeklyUsd != null; const rows = models.length > 0 - ? models.map((item) => - createRateModelCard({ - name: item.model, - multiplier: item.multiplier, - rate5hPctPerUsd: item.rate5hPctPerUsd, - rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, - eqFull5hUsd: item.eqFull5hUsd, - eqFullWeeklyUsd: item.eqFullWeeklyUsd, - samples: item.samples, - }) - ) + ? [ + ...models.map((item) => + createRateModelCard({ + name: item.model, + multiplier: item.multiplier, + rate5hPctPerUsd: item.rate5hPctPerUsd, + rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, + eqFull5hUsd: item.eqFull5hUsd, + eqFullWeeklyUsd: item.eqFullWeeklyUsd, + eqFull5hTokens: item.eqFull5hTokens, + eqFullWeeklyTokens: item.eqFullWeeklyTokens, + samples: item.samples, + }) + ), + ...(needsWeeklyFallbackRow + ? [ + createRateModelCard({ + name: t('quota.ratePopPoolFallback'), + isMutedName: true, + isFallback: true, + rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, + eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, + samples: Number(est.samplesWeekly) || 0, + source: est.sourceWeekly || null, + isPreliminary: Boolean(est.isPreliminaryWeekly), + }), + ] + : []), + ] : hasPoolFallback ? [ createRateModelCard({ @@ -675,7 +880,13 @@ export const QuotaPoolsWidget = defineComponent({ rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, eqFull5hUsd: est.eqFull5hUsd, eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFull5hTokens: est.eqFull5hTokens, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), + source: fallbackPrimaryIs5h ? est.source5h || null : est.sourceWeekly || null, + isPreliminary: fallbackPrimaryIs5h + ? Boolean(est.isPreliminary5h) + : Boolean(est.isPreliminaryWeekly), }), ] : []; diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 7b356e0..6b8311f 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -190,6 +190,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ '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', + 'quota.cycleFullSuffix': 'Full ~{full}', 'quota.footTokensCustom': 'Week Total: {tok} ({cost})', 'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})', 'quota.footCredits': 'AI Credits: {credits}', @@ -201,13 +202,18 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopTitle': 'Estimated Burn Rates', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': 'Current account', + 'quota.ratePopWkCapTitle': 'Est. Weekly Quota', + 'quota.ratePopWkCapPrelim': '· est.', + 'quota.ratePopWkCapPartial': '· {ready}/{total} pools', 'quota.ratePopPoolFallback': 'Pool average', 'quota.ratePopEq5hLabel': '5h full', 'quota.ratePopEqWkLabel': 'Weekly full', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} samples', - 'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.', - 'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.', + 'quota.ratePopPrelimSlope': 'slope est.', + 'quota.ratePopPrelimCycle': 'cycle est.', + 'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).', + 'quota.ratePopNote': 'Measured from net burn & priced steps; lowest in pool = 1x. Account isolated.', 'quota.ratePopSharedBadge': 'Shared active', 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index e20bf78..58be7a0 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -190,6 +190,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', + 'quota.cycleFullSuffix': '满池约 {full}', 'quota.footTokensCustom': '本周累计: {tok} ({cost})', 'quota.footTokensCycle': '周期累计: {tok} ({cost})', 'quota.footCredits': 'AI 积分: {credits}', @@ -201,13 +202,18 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopTitle': '实测倍率预估', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': '当前账号', + 'quota.ratePopWkCapTitle': '预测周额度', + 'quota.ratePopWkCapPrelim': '· 初估', + 'quota.ratePopWkCapPartial': '· {ready}/{total} 池', 'quota.ratePopPoolFallback': '池综合均值', 'quota.ratePopEq5hLabel': '5h 满池', 'quota.ratePopEqWkLabel': '周限满池', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} 样本', - 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', - 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', + 'quota.ratePopPrelimSlope': '斜率初估', + 'quota.ratePopPrelimCycle': '周期初估', + 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。', + 'quota.ratePopNote': '按净消耗及精确计价折算,同池最省为 1x,按账号隔离。', 'quota.ratePopSharedBadge': '共享活跃', 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 703ab12..02433a7 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1114,6 +1114,12 @@ export function isEquivalentTelemetry(prev, next) { return false; } } + if ( + JSON.stringify(prev.quotas?.weeklyCapacityEstimate || null) !== + JSON.stringify(next.quotas?.weeklyCapacityEstimate || null) + ) { + return false; + } const pConvs = prev.conversations || []; const nConvs = next.conversations || []; diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 16b07de..2aa2d83 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -842,10 +842,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .step-anomaly-tip-list, [data-modern-ui="true"] .step-anomaly-tip-hint, [data-modern-ui="true"] .quota-rate-pop-head, +[data-modern-ui="true"] .quota-rate-wk-summary, [data-modern-ui="true"] .quota-rate-pool-group + .quota-rate-pool-group, [data-modern-ui="true"] .quota-rate-model-row + .quota-rate-model-row, [data-modern-ui="true"] .quota-rate-pop-note, :host([data-modern-ui="true"]) .quota-rate-pop-head, +:host([data-modern-ui="true"]) .quota-rate-wk-summary, :host([data-modern-ui="true"]) .quota-rate-pool-group + .quota-rate-pool-group, :host([data-modern-ui="true"]) .quota-rate-model-row + .quota-rate-model-row, :host([data-modern-ui="true"]) .quota-rate-pop-note { diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 929c862..32c9de0 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -676,7 +676,7 @@ position: absolute; top: 38px; left: 12px; - width: min(332px, calc(100% - 24px)); + width: min(352px, calc(100% - 24px)); z-index: 45; display: flex; flex-direction: column; @@ -721,10 +721,69 @@ min-width: 0; } +.quota-rate-wk-summary { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + min-width: 0; + padding-bottom: 7px; + border-bottom: 1px solid var(--border-hairline); +} + +.quota-rate-wk-summary[hidden] { + display: none; +} + +.quota-rate-wk-k { + display: inline-flex; + align-items: baseline; + gap: 5px; + min-width: 0; + font-size: var(--fs-sm); + font-weight: 500; + color: var(--text-secondary); + white-space: nowrap; +} + +.quota-rate-wk-sub { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + font-size: var(--fs-2xs); + font-weight: 400; + color: var(--text-muted); +} + +.quota-rate-wk-v { + display: inline-flex; + align-items: baseline; + gap: 4px; + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; +} + +.quota-rate-wk-usd { + font-size: var(--fs-md); + font-weight: 600; + color: var(--text-primary); +} + +.quota-rate-wk-tok { + font-size: var(--fs-xs); + font-weight: 400; + color: var(--text-muted); +} + .quota-rate-pop-body { display: flex; flex-direction: column; gap: 8px; + max-height: min(300px, 58vh); + overflow-x: hidden; + overflow-y: auto; + overscroll-behavior: contain; } .quota-rate-pool-group { @@ -855,9 +914,11 @@ .quota-rate-eq-grid { display: flex; + flex-wrap: wrap; align-items: baseline; justify-content: space-between; - gap: 12px; + column-gap: 10px; + row-gap: 3px; } .quota-rate-eq-grid.is-single { @@ -885,6 +946,14 @@ white-space: nowrap; } +.quota-rate-eq-tok { + font-size: var(--fs-xs); + font-weight: 400; + font-variant-numeric: tabular-nums; + color: var(--text-muted); + white-space: nowrap; +} + .quota-rate-pop-empty { font-size: var(--fs-sm); line-height: 1.5; diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index d2d28ce..235a641 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2394,7 +2394,7 @@ html[data-standalone="true"] .app-shell { position: absolute; top: 38px; left: 12px; - width: min(332px, calc(100% - 24px)); + width: min(352px, calc(100% - 24px)); z-index: 45; display: flex; flex-direction: column; @@ -2439,10 +2439,69 @@ html[data-standalone="true"] .app-shell { min-width: 0; } +.quota-rate-wk-summary { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + min-width: 0; + padding-bottom: 7px; + border-bottom: 1px solid var(--border-hairline); +} + +.quota-rate-wk-summary[hidden] { + display: none; +} + +.quota-rate-wk-k { + display: inline-flex; + align-items: baseline; + gap: 5px; + min-width: 0; + font-size: var(--fs-sm); + font-weight: 500; + color: var(--text-secondary); + white-space: nowrap; +} + +.quota-rate-wk-sub { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + font-size: var(--fs-2xs); + font-weight: 400; + color: var(--text-muted); +} + +.quota-rate-wk-v { + display: inline-flex; + align-items: baseline; + gap: 4px; + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; +} + +.quota-rate-wk-usd { + font-size: var(--fs-md); + font-weight: 600; + color: var(--text-primary); +} + +.quota-rate-wk-tok { + font-size: var(--fs-xs); + font-weight: 400; + color: var(--text-muted); +} + .quota-rate-pop-body { display: flex; flex-direction: column; gap: 8px; + max-height: min(300px, 58vh); + overflow-x: hidden; + overflow-y: auto; + overscroll-behavior: contain; } .quota-rate-pool-group { @@ -2573,9 +2632,11 @@ html[data-standalone="true"] .app-shell { .quota-rate-eq-grid { display: flex; + flex-wrap: wrap; align-items: baseline; justify-content: space-between; - gap: 12px; + column-gap: 10px; + row-gap: 3px; } .quota-rate-eq-grid.is-single { @@ -2603,6 +2664,14 @@ html[data-standalone="true"] .app-shell { white-space: nowrap; } +.quota-rate-eq-tok { + font-size: var(--fs-xs); + font-weight: 400; + font-variant-numeric: tabular-nums; + color: var(--text-muted); + white-space: nowrap; +} + .quota-rate-pop-empty { font-size: var(--fs-sm); line-height: 1.5; @@ -8793,10 +8862,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { [data-modern-ui="true"] .step-anomaly-tip-list, [data-modern-ui="true"] .step-anomaly-tip-hint, [data-modern-ui="true"] .quota-rate-pop-head, +[data-modern-ui="true"] .quota-rate-wk-summary, [data-modern-ui="true"] .quota-rate-pool-group + .quota-rate-pool-group, [data-modern-ui="true"] .quota-rate-model-row + .quota-rate-model-row, [data-modern-ui="true"] .quota-rate-pop-note, :host([data-modern-ui="true"]) .quota-rate-pop-head, +:host([data-modern-ui="true"]) .quota-rate-wk-summary, :host([data-modern-ui="true"]) .quota-rate-pool-group + .quota-rate-pool-group, :host([data-modern-ui="true"]) .quota-rate-model-row + .quota-rate-model-row, :host([data-modern-ui="true"]) .quota-rate-pop-note { diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs index 7d5e099..79f6bf6 100644 --- a/sidecars/panel/test/quota-reservation.test.mjs +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -1980,3 +1980,903 @@ test('QuotaPoolsWidget ? popover renders family-group/external usage banner and globalThis.window = origWindow; } }); + +test('quota-reservation: 3-tier hybrid estimator unlocks cycle_ratio & anchor_slope, derives full-pool tokens, and retains density across reset & restart', () => { + let storedPayload = null; + const tracker = createQuotaReservationTracker({ + saveState: (p) => { + storedPayload = JSON.parse(JSON.stringify(p)); + }, + }); + + const makePools = (used5h, usedWk, reset5h = RESET_5H, resetWk = RESET_WK) => + new Map([ + [ + 'Claude & GPT', + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - used5h / 100, + usedPct: used5h, + resetTime: new Date(reset5h).toISOString(), + weeklyRemainingFraction: 1 - usedWk / 100, + weeklyUsedPct: usedWk, + weeklyResetTime: new Date(resetWk).toISOString(), + }, + ], + ]); + + const makeStats = ({ + cost5h, + costWk, + calls5h, + callsWk, + tok5h, + tokWk, + modelCosts5h = {}, + modelCostsWk = {}, + modelTokens5h = {}, + modelTokensWk = {}, + ts = T0, + }) => + new Map([ + [ + 'Claude & GPT', + { + cycle5h: { costUsd: cost5h, calls: calls5h, tokens: tok5h, unpricedCalls: 0 }, + cycleWeekly: { costUsd: costWk, calls: callsWk, tokens: tokWk, unpricedCalls: 0 }, + pricedTokens5h: tok5h, + pricedTokensWeekly: tokWk, + exactCost5hUsd: cost5h, + exactCostWeeklyUsd: costWk, + modelCosts5h, + modelCostsWeekly: modelCostsWk, + modelTokens5h, + modelTokensWeekly: modelTokensWk, + recent10m: { lastActivityMs: ts, activeSessionCount: 1, costUsd: 0.2 }, + }, + ], + ]); + + // 1. Cold-start Tier 3 (cycle_ratio): solo account at 3.2% 5h / 2.4% weekly across 6 calls ($1.20, 300k tok -> $4/MTok) + // Unlocks immediately without waiting for 3 clean single-step diffs, while keeping reservedPct = 0 + const pCold = makePools(3.2, 2.4); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'tier3@example.com', + quotaPoolsMap: pCold, + poolCycleStats: makeStats({ + cost5h: 1.6, + costWk: 1.2, + calls5h: 6, + callsWk: 6, + tok5h: 400_000, + tokWk: 300_000, + modelCosts5h: { 'Claude Sonnet 4.6': 1.6 }, + modelCostsWk: { 'Claude Sonnet 4.6': 1.2 }, + modelTokens5h: { 'Claude Sonnet 4.6': 400_000 }, + modelTokensWk: { 'Claude Sonnet 4.6': 300_000 }, + ts: T0, + }), + quotaFetchedAtMs: T0, + nowMs: T0, + }); + const coldPool = pCold.get('Claude & GPT'); + assert.equal(coldPool.reservedPct, 0); + assert.equal(coldPool.weeklyReservedPct, 0); + assert.equal(coldPool.rateEstimate?.source5h, 'cycle_ratio'); + assert.equal(coldPool.rateEstimate?.sourceWeekly, 'cycle_ratio'); + assert.equal(coldPool.rateEstimate?.isPreliminary5h, true); + assert.equal(coldPool.rateEstimate?.isPreliminaryWeekly, true); + assert.equal(coldPool.rateEstimate?.eqFull5hUsd, 50); + assert.equal(coldPool.rateEstimate?.eqFullWeeklyUsd, 50); + assert.equal(coldPool.rateEstimate?.eqFull5hTokens, 12_500_000); + assert.equal(coldPool.rateEstimate?.eqFullWeeklyTokens, 12_500_000); + + // 2. Mid-cycle / shared-account Tier 2 (anchor_slope + Theil-Sen): + // Baseline starts at 28% weekly with $0 local cost -> hasExternalUsage = true, Tier 3 blocked + let ts = T0; + let u5 = 15.0; + let uw = 28.0; + let c = 0; + let n = 0; + let tok = 0; + const pExt0 = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pExt0, + poolCycleStats: makeStats({ cost5h: 0, costWk: 0, calls5h: 0, callsWk: 0, tok5h: 0, tokWk: 0, ts }), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pExt0.get('Claude & GPT').rateEstimate?.eqFullWeeklyUsd, null, 'Tier 3 blocked on external baseline'); + + // Local runs 3 multi-model batched checkpoints (+0.6% weekly / +$0.30 / +2 calls each; total +1.8% >= 1.5%, +6 calls >= 5, $4/MTok) + // Note: delta5h = +0.6% (>= 0.35% lease jump threshold on uncalibrated or multi-step), so clean single-step rateSamples stays 0, + // proving Tier 2 anchor_slope independently recovers 2.0 %/$ -> $50 full weekly! + let pSlope = null; + for (let step = 0; step < 3; step += 1) { + ts += 30_000; + c = +(c + 0.3).toFixed(4); + n += 2; + tok += 75_000; + u5 = +(u5 + 0.3).toFixed(4); + uw = +(uw + 0.6).toFixed(4); + pSlope = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pSlope, + poolCycleStats: makeStats({ + cost5h: c, + costWk: c, + calls5h: n, + callsWk: n, + tok5h: tok, + tokWk: tok, + modelCosts5h: { 'Claude Sonnet 4.6': c * 0.6, 'Claude Opus 4.6': c * 0.4 }, + modelCostsWk: { 'Claude Sonnet 4.6': c * 0.6, 'Claude Opus 4.6': c * 0.4 }, + modelTokens5h: { 'Claude Sonnet 4.6': Math.round(tok * 0.75), 'Claude Opus 4.6': Math.round(tok * 0.25) }, + modelTokensWk: { 'Claude Sonnet 4.6': Math.round(tok * 0.75), 'Claude Opus 4.6': Math.round(tok * 0.25) }, + ts, + }), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + } + const slopeEst = pSlope.get('Claude & GPT').rateEstimate; + assert.equal(slopeEst?.sourceWeekly, 'anchor_slope'); + assert.equal(slopeEst?.isPreliminaryWeekly, true); + assert.equal(slopeEst?.eqFullWeeklyUsd, 50); + assert.equal(slopeEst?.eqFullWeeklyTokens, 12_500_000); + + // 3. Three clean single-model steps on Sonnet ($0.10 -> +0.2% weekly = 2.0 %/$) promote pool & model to Tier 1 calibrated + let sonnetExtraCost = 0; + let sonnetExtraTok = 0; + let pCal = null; + for (let i = 0; i < 3; i += 1) { + ts += 20_000; + c = +(c + 0.1).toFixed(4); + sonnetExtraCost = +(sonnetExtraCost + 0.1).toFixed(4); + sonnetExtraTok += 25_000; + n += 1; + tok += 25_000; + u5 = +(u5 + 0.2).toFixed(4); + uw = +(uw + 0.2).toFixed(4); + pCal = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pCal, + poolCycleStats: makeStats({ + cost5h: c, + costWk: c, + calls5h: n, + callsWk: n, + tok5h: tok, + tokWk: tok, + modelCosts5h: { 'Claude Sonnet 4.6': 0.54 + sonnetExtraCost, 'Claude Opus 4.6': 0.36 }, + modelCostsWk: { 'Claude Sonnet 4.6': 0.54 + sonnetExtraCost, 'Claude Opus 4.6': 0.36 }, + modelTokens5h: { 'Claude Sonnet 4.6': 168_750 + sonnetExtraTok, 'Claude Opus 4.6': 56_250 }, + modelTokensWk: { 'Claude Sonnet 4.6': 168_750 + sonnetExtraTok, 'Claude Opus 4.6': 56_250 }, + ts, + }), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + } + const calEst = pCal.get('Claude & GPT').rateEstimate; + assert.equal(calEst?.sourceWeekly, 'calibrated'); + assert.equal(calEst?.isPreliminaryWeekly, false); + assert.equal(calEst?.eqFullWeeklyUsd, 50); + assert.equal(calEst?.eqFullWeeklyTokens, 12_500_000); + assert.ok(calEst?.models?.[0]?.eqFullWeeklyTokens > 10_000_000, 'per-model eqFullWeeklyTokens populated'); + + // 4. Weekly rollover reset back to 0% ($0 cost, 0 tokens) + reload from persisted v2 payload: + // priorUsdPerMTok preserves full-pool token capacity with zero Monday-reset amnesia! + ts += 7 * 24 * 3600 * 1000; + const pReset = makePools(0, 0, RESET_5H + 7 * 24 * 3600 * 1000, RESET_WK + 7 * 24 * 3600 * 1000); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pReset, + poolCycleStats: makeStats({ cost5h: 0, costWk: 0, calls5h: 0, callsWk: 0, tok5h: 0, tokWk: 0, ts }), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pReset.get('Claude & GPT').rateEstimate?.eqFullWeeklyUsd, 50); + assert.equal(pReset.get('Claude & GPT').rateEstimate?.eqFullWeeklyTokens, 12_500_000); + + assert.equal(storedPayload?.version, 2, 'keeps v2 schema version backward-compatible'); + const reloaded = createQuotaReservationTracker({ loadState: () => storedPayload }); + const pAfterRestart = makePools(0, 0, RESET_5H + 7 * 24 * 3600 * 1000, RESET_WK + 7 * 24 * 3600 * 1000); + reloaded.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pAfterRestart, + poolCycleStats: makeStats({ cost5h: 0, costWk: 0, calls5h: 0, callsWk: 0, tok5h: 0, tokWk: 0, ts }), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pAfterRestart.get('Claude & GPT').rateEstimate?.eqFullWeeklyUsd, 50); + assert.equal(pAfterRestart.get('Claude & GPT').rateEstimate?.eqFullWeeklyTokens, 12_500_000); +}); + +test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, preliminary labels, and full-pool token references', async () => { + const { document } = createMockDom(); + const origDocument = globalThis.document; + const origWindow = globalThis.window; + 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/' }, + }; + + try { + const [{ setI18nLanguage }, { QuotaPoolsWidget }] = await Promise.all([ + import('../src/i18n/index.js'), + import('../src/components/widgets/QuotaPoolsWidget.js'), + ]); + setI18nLanguage('zh-CN'); + + const widget = QuotaPoolsWidget(); + const popover = widget.refs.ratePopoverEl; + + // 1. Collecting state: top weekly summary hidden until at least 1 pool has a weekly capacity estimate + assert.equal(popover.querySelector('.quota-rate-wk-summary')?.hidden, true); + + // 2. Partial + Preliminary state (Claude ready via anchor_slope, Gemini still collecting) + widget.refs.update({ + data: { + account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Pro' }, + quotas: { + pools: [ + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + usedPct: 14, + remainingPct: 86, + weeklyUsedPct: 30, + weeklyRemainingPct: 70, + cycleWeekly: { tokens: 3_100_000, costUsd: 15, calls: 42 }, + rateEstimate: { + rate5hPctPerUsd: null, + rateWeeklyPctPerUsd: 2.0833, + eqFull5hUsd: null, + eqFullWeeklyUsd: 48, + eqFullWeeklyTokens: 9_900_000, + samples5h: 0, + samplesWeekly: 0, + sourceWeekly: 'anchor_slope', + isPreliminaryWeekly: true, + models: [], + }, + }, + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + hasWeekly: true, + weeklyUsedPct: 0.4, + weeklyRemainingPct: 99.6, + rateEstimate: null, + }, + ], + weekly: { isOfficial: true }, + }, + }, + minuteTick: 1, + }); + + const wkSummary = popover.querySelector('.quota-rate-wk-summary'); + assert.equal(wkSummary.hidden, false); + assert.match(wkSummary.textContent, /预测周额度.*· 1\/2 池.*≈ \$48.*· 9\.9M/); + const fallbackRow = popover.querySelector('.quota-rate-model-row.is-fallback'); + assert.ok(fallbackRow); + assert.match(fallbackRow.textContent, /池综合均值/); + assert.match(fallbackRow.textContent, /周限 2\.08%\/\$ · 斜率初估/); + assert.match(fallbackRow.textContent, /周限满池≈ \$48· 9\.9M/); + + const wkRowLeft = widget.refs.poolsListEl.querySelectorAll('.quota-win-left')[1]; + assert.match(wkRowLeft.getAttribute('title') || '', /满池约 \$48 \(9\.9M\)/); + + // 3. All pools calibrated & ready: sums USD + Tokens cleanly ($50 + $35 = $85, 10.3M + 14.2M = 24.5M) + const allReadyData = { + account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Pro' }, + quotas: { + pools: [ + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + usedPct: 14, + remainingPct: 86, + weeklyUsedPct: 30, + weeklyRemainingPct: 70, + cycleWeekly: { tokens: 3_100_000, costUsd: 15, calls: 42 }, + rateEstimate: { + rate5hPctPerUsd: 2, + rateWeeklyPctPerUsd: 2, + eqFull5hUsd: 50, + eqFullWeeklyUsd: 50, + eqFull5hTokens: 10_300_000, + eqFullWeeklyTokens: 10_300_000, + samples5h: 8, + samplesWeekly: 8, + source5h: 'calibrated', + sourceWeekly: 'calibrated', + isPreliminary5h: false, + isPreliminaryWeekly: false, + models: [ + { + model: 'Claude Sonnet 4.6', + rate5hPctPerUsd: 2, + rateWeeklyPctPerUsd: 2, + eqFull5hUsd: 50, + eqFullWeeklyUsd: 50, + eqFull5hTokens: 10_300_000, + eqFullWeeklyTokens: 10_300_000, + multiplier: null, + samples: 8, + }, + ], + }, + }, + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: true, + hasWeekly: true, + usedPct: 10, + remainingPct: 90, + weeklyUsedPct: 20, + weeklyRemainingPct: 80, + rateEstimate: { + rate5hPctPerUsd: 2.8571, + rateWeeklyPctPerUsd: 2.8571, + eqFull5hUsd: 35, + eqFullWeeklyUsd: 35, + eqFull5hTokens: 14_200_000, + eqFullWeeklyTokens: 14_200_000, + samples5h: 6, + samplesWeekly: 6, + source5h: 'calibrated', + sourceWeekly: 'calibrated', + isPreliminary5h: false, + isPreliminaryWeekly: false, + models: [], + }, + }, + ], + weekly: { isOfficial: true }, + }, + }; + widget.refs.update({ data: allReadyData, minuteTick: 2 }); + assert.equal(wkSummary.hidden, false); + assert.equal(wkSummary.querySelector('.quota-rate-wk-sub').hidden, true); + assert.match(wkSummary.textContent, /预测周额度≈ \$85· 24\.5M/); + + // 4. English locale switch updates weekly summary, model cards, and row title tooltip without reload + setI18nLanguage('en-US'); + widget.refs.update({ data: allReadyData, minuteTick: 3 }); + assert.match(wkSummary.textContent, /Est\. Weekly Quota≈ \$85· 24\.5M/); + assert.match( + widget.refs.poolsListEl.querySelectorAll('.quota-win-left')[1].getAttribute('title') || '', + /Full ~\$50 \(10\.3M\)/ + ); + + // 5. Custom local weekly budget mode hides official weekly capacity summary + widget.refs.update({ + data: { + ...allReadyData, + quotas: { + ...allReadyData.quotas, + weekly: { isOfficial: false }, + }, + }, + minuteTick: 4, + }); + assert.equal(wkSummary.hidden, true); + + // 6. Pool with 5h-only model card + pool-level preliminary weekly estimate renders supplementary weekly fallback row + setI18nLanguage('zh-CN'); + widget.refs.update({ + data: { + account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Pro' }, + quotas: { + pools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: true, + hasWeekly: true, + usedPct: 8, + remainingPct: 92, + weeklyUsedPct: 12, + weeklyRemainingPct: 88, + rateEstimate: { + rate5hPctPerUsd: 0.6667, + rateWeeklyPctPerUsd: 0.1667, + eqFull5hUsd: 150, + eqFullWeeklyUsd: 600, + eqFull5hTokens: 50_000_000, + eqFullWeeklyTokens: 200_000_000, + samples5h: 4, + samplesWeekly: 0, + source5h: 'calibrated', + sourceWeekly: 'anchor_slope', + isPreliminary5h: false, + isPreliminaryWeekly: true, + models: [ + { + model: 'Gemini 3.1 Pro', + rate5hPctPerUsd: 0.6667, + rateWeeklyPctPerUsd: null, + eqFull5hUsd: 150, + eqFullWeeklyUsd: null, + eqFull5hTokens: 50_000_000, + multiplier: null, + samples: 4, + }, + ], + }, + }, + ], + weekly: { isOfficial: true }, + }, + }, + minuteTick: 5, + }); + assert.equal(wkSummary.hidden, false); + assert.match(wkSummary.textContent, /预测周额度.*· 初估.*≈ \$600.*· 200\.0M/); + const mixedRows = popover.querySelectorAll('.quota-rate-model-row'); + assert.equal(mixedRows.length, 2, 'renders 5h model card + supplementary pool weekly fallback row'); + assert.match(mixedRows[0].textContent, /Gemini 3\.1 Pro.*5h 满池≈ \$150/); + assert.match(mixedRows[1].textContent, /池综合均值.*斜率初估.*周限满池≈ \$600· 200\.0M/); + + widget.destroy(); + } finally { + globalThis.document = origDocument; + globalThis.window = origWindow; + } +}); + +test('quota-reservation: batches multi-pool persistence and isolates slope/calibration from unpriced calls, lease expiry & cold-start', () => { + let saveCalls = 0; + let stored = null; + const tracker = createQuotaReservationTracker({ + saveState: (p) => { + saveCalls += 1; + stored = JSON.parse(JSON.stringify(p)); + }, + }); + + // 1. Batched persistence across multiple pools on non-urgent baseline/normal ticks: + // Both pools' 5h AND weekly buckets must be persisted in a single atomic save + let ts = T0; + const mkMultiPools = (c5, cw, g5, gw) => + new Map([ + [ + 'Claude & GPT', + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - c5 / 100, + usedPct: c5, + resetTime: new Date(RESET_5H).toISOString(), + weeklyRemainingFraction: 1 - cw / 100, + weeklyUsedPct: cw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + [ + 'Gemini', + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - g5 / 100, + usedPct: g5, + resetTime: new Date(RESET_5H).toISOString(), + weeklyRemainingFraction: 1 - gw / 100, + weeklyUsedPct: gw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + + const mkMultiStats = (cc, gc, cCalls, gCalls, cUnp = 0) => + new Map([ + [ + 'Claude & GPT', + { + cycle5h: { costUsd: cc, calls: cCalls, tokens: 300_000, unpricedCalls: cUnp }, + cycleWeekly: { costUsd: cc, calls: cCalls, tokens: 300_000, unpricedCalls: cUnp }, + pricedTokens5h: 300_000, + pricedTokensWeekly: 300_000, + exactCost5hUsd: cc, + exactCostWeeklyUsd: cc, + modelCosts5h: { 'Claude Sonnet 4.6': cc }, + modelCostsWeekly: { 'Claude Sonnet 4.6': cc }, + modelTokens5h: { 'Claude Sonnet 4.6': 300_000 }, + modelTokensWeekly: { 'Claude Sonnet 4.6': 300_000 }, + recent10m: { lastActivityMs: ts, activeSessionCount: 1, costUsd: 0.1 }, + }, + ], + [ + 'Gemini', + { + cycle5h: { costUsd: gc, calls: gCalls, tokens: 500_000, unpricedCalls: 0 }, + cycleWeekly: { costUsd: gc, calls: gCalls, tokens: 500_000, unpricedCalls: 0 }, + pricedTokens5h: 500_000, + pricedTokensWeekly: 500_000, + exactCost5hUsd: gc, + exactCostWeeklyUsd: gc, + modelCosts5h: { 'Gemini 3.1 Pro': gc }, + modelCostsWeekly: { 'Gemini 3.1 Pro': gc }, + modelTokens5h: { 'Gemini 3.1 Pro': 500_000 }, + modelTokensWeekly: { 'Gemini 3.1 Pro': 500_000 }, + recent10m: { lastActivityMs: ts, activeSessionCount: 1, costUsd: 0.1 }, + }, + ], + ]); + + tracker.updatePools({ + endpointId: 'local', + accountScope: 'batch@example.com', + quotaPoolsMap: mkMultiPools(2.0, 2.0, 1.0, 1.0), + poolCycleStats: mkMultiStats(1.0, 2.0, 5, 5), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(saveCalls, 1, 'updatePools coalesces multi-pool baseline into 1 disk write'); + assert.ok(stored?.buckets?.['local::batch@example.com::Claude & GPT::weekly'], 'Claude weekly persisted'); + assert.ok(stored?.buckets?.['local::batch@example.com::Gemini::weekly'], '2nd pool Gemini weekly persisted'); + assert.ok( + stored.buckets['local::batch@example.com::Gemini::weekly'].usdPerMTok > 0, + '2nd pool weekly token density persisted' + ); + + // 2. Cold-start seeded bucket (rateSamples = 1, rateWindow = []) requires 3 genuine clean steps before calibrated + for (let step = 1; step <= 2; step += 1) { + ts += 20_000; + const p2 = mkMultiPools(2.0 + step * 0.2, 2.0 + step * 0.2, 1.0, 1.0); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'batch@example.com', + quotaPoolsMap: p2, + poolCycleStats: mkMultiStats(1.0 + step * 0.1, 2.0, 5 + step, 5), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + const estStep = p2.get('Claude & GPT').rateEstimate; + assert.equal( + estStep?.isPreliminaryWeekly, + true, + `step ${step} (< 3 clean steps) stays preliminary despite cold-start seed` + ); + } + ts += 20_000; + const pStep3 = mkMultiPools(2.6, 2.6, 1.0, 1.0); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'batch@example.com', + quotaPoolsMap: pStep3, + poolCycleStats: mkMultiStats(1.3, 2.0, 8, 5), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pStep3.get('Claude & GPT').rateEstimate?.isPreliminaryWeekly, false, '3rd genuine clean step promotes to calibrated'); + assert.equal(stored?.buckets?.['local::batch@example.com::Claude & GPT::weekly']?.rateWindow?.length, 3, 'normal tick persisted weekly rateWindow'); + + // 3. Unpriced calls & expired leases do NOT poison Tier 2 anchor_slope + ts = T0; + const makeWkPool = (uw) => + new Map([ + [ + 'Argon', + { + poolKey: 'Argon', + poolLabel: 'Argon', + family: 'Argon', + has5h: false, + hasWeekly: true, + weeklyRemainingFraction: 1 - uw / 100, + weeklyUsedPct: uw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + const makeWkStats = (cost, calls, unp) => + new Map([ + [ + 'Argon', + { + cycle5h: { costUsd: 0, calls: 0, tokens: 0, unpricedCalls: 0 }, + cycleWeekly: { costUsd: cost, calls, tokens: 100_000, unpricedCalls: unp }, + pricedTokensWeekly: 100_000, + exactCostWeeklyUsd: cost, + recent10m: { lastActivityMs: ts, activeSessionCount: 2, costUsd: 0.1 }, + }, + ], + ]); + + // Baseline on shared pool (20% with $0 local -> Tier 3 blocked) + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: makeWkPool(20.0), + poolCycleStats: makeWkStats(0, 0, 0), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + // Unpriced burst burns +3.0% alongside tiny $0.03 priced spend -> must reset slope anchor, NOT record 100 %/$ + ts += 30_000; + const pUnp = makeWkPool(23.0); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: pUnp, + poolCycleStats: makeWkStats(0.03, 6, 5), + runningPoolKeys: new Set(['Argon']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pUnp.get('Argon').rateEstimate?.eqFullWeeklyUsd ?? null, null, 'unpriced burst does not unlock poisoned slope'); + + // Subsequent priced multi-step burn (+1.6% across +$0.80, 6 calls, unp stays 5) cleanly calibrates 2.0 %/$ -> $50! + for (let k = 1; k <= 2; k += 1) { + ts += 30_000; + const pPriced = makeWkPool(23.0 + k * 0.8); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: pPriced, + poolCycleStats: makeWkStats(0.03 + k * 0.4, 6 + k * 3, 5), + runningPoolKeys: new Set(['Argon']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + if (k === 2) { + assert.equal(pPriced.get('Argon').rateEstimate?.sourceWeekly, 'anchor_slope'); + assert.equal(pPriced.get('Argon').rateEstimate?.eqFullWeeklyUsd, 50); + } + } + + // Trigger a 2.0% cold-start/active lease jump, then let it expire after 91 minutes -> expiry jump must reset slope anchor + ts += 30_000; + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: makeWkPool(26.6), + poolCycleStats: makeWkStats(0.85, 13, 5), + runningPoolKeys: new Set(['Argon']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + const argonSt = tracker._buckets.get('local::guard@example.com::Argon::weekly'); + assert.ok(argonSt.activeLeases.length > 0, 'lease recorded before TTL expiry'); + ts += 91 * 60 * 1000; + const pExpired = makeWkPool(26.65); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: pExpired, + poolCycleStats: makeWkStats(0.88, 14, 5), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(argonSt.activeLeases.length, 0, 'lease expired'); + assert.equal(argonSt.slopeSamples.length, 1, 'slope anchor reset cleanly on lease TTL expiry'); +}); + +test('quota-reservation: suppresses post-refund idle replica ping-pong and self-heals false externalUsage while preserving real shared pools', () => { + const tracker = createQuotaReservationTracker(); + const keyWk = 'local::solo-bounce@example.com::Gemini::weekly'; + let ts = T0; + + // 1. Calibrate solo account cleanly at 0.125 %/$ ($800 full weekly): 3 clean steps + active lease up to 1.048% + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: 0.3, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 2.4, + cycleCalls: 30, + poolLastActivityMs: ts, + activeSessionCount10m: 1, + nowMs: ts, + }); + for (let i = 1; i <= 3; i += 1) { + ts += 20_000; + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: +(0.3 + i * 0.025).toFixed(4), + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: +(2.4 + i * 0.2).toFixed(4), + cycleCalls: 30 + i, + poolLastActivityMs: ts, + activeSessionCount10m: 1, + nowMs: ts, + }); + } + const lastActiveTs = ts; + // Active lease jumps 0.375% -> 1.048% + ts += 15_000; + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: 1.048, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 3.0688, + cycleCalls: 34, + poolLastActivityMs: lastActiveTs, + activeSessionCount10m: 1, + nowMs: ts, + }); + + // User goes idle for 10 min -> upstream settles down to 0.356%, then multi-replica LB bounces 1.048% <-> 0.356% repeatedly + const bounceSchedule = [ + [10 * 60 * 1000, 0.356], + [15 * 60 * 1000, 1.048], + [12 * 60 * 1000, 0.356], + [11 * 1000, 1.048], + [7 * 60 * 1000, 0.356], + ]; + for (const [dt, pct] of bounceSchedule) { + ts += dt; + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: pct, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 3.0688, + cycleCalls: 34, + poolLastActivityMs: lastActiveTs, + activeSessionCount10m: 0, + nowMs: ts, + }); + } + const stBounce = tracker._buckets.get(keyWk); + assert.equal(stBounce.hasExternalUsage, false, 'idle post-refund replica bounce must not flag external usage'); + assert.equal(stBounce.externalUsedPct, 0, 'ping-pong must never accumulate externalUsedPct'); + + // 2. Self-healing of already-polluted persisted state vs preservation of genuine shared state + let healedSaved = null; + const persisted = { + version: 2, + savedAt: new Date(T0).toISOString(), + buckets: { + 'local::polluted@example.com::Gemini::weekly': { + resetTimeMs: RESET_WK, + lastQuotaTs: T0, + lastOfficialUsedPct: 0.4012, + lastCycleCostUsd: 3.53, + lastCycleCalls: 44, + lastPricedTokens: 9_803_219, + lastUnpricedCalls: 0, + usdPerMTok: 0.36, + ratePctPerUsd: 0.125, + rateSamples: 20, + rateWindow: [0.125, 0.125, 0.125, 0.125], + hasExternalUsage: true, + lastExternalUsageAtMs: T0 - 3 * 3600 * 1000, + externalUsedPct: 2.018, + externalEvents: 4, + }, + 'local::shared@example.com::Gemini::weekly': { + resetTimeMs: RESET_WK, + lastQuotaTs: T0, + lastOfficialUsedPct: 49.82, + lastCycleCostUsd: 196.93, + lastCycleCalls: 120, + lastPricedTokens: 60_000_000, + lastUnpricedCalls: 0, + usdPerMTok: 3.28, + ratePctPerUsd: 0.1667, + rateSamples: 55, + rateWindow: [0.1667, 0.1667, 0.1667, 0.1667], + hasExternalUsage: true, + lastExternalUsageAtMs: T0 - 3 * 3600 * 1000, + externalUsedPct: 0.571, + externalEvents: 1, + }, + }, + events: [], + }; + const healer = createQuotaReservationTracker({ + loadState: () => persisted, + saveState: (p) => { + healedSaved = p; + }, + }); + const mkPollPools = (uw) => + new Map([ + [ + 'Gemini', + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: false, + hasWeekly: true, + weeklyUsedPct: uw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + const pPolluted = mkPollPools(0.4012); + healer.updatePools({ + endpointId: 'local', + accountScope: 'polluted@example.com', + quotaPoolsMap: pPolluted, + poolCycleStats: new Map([ + [ + 'Gemini', + { + cycleWeekly: { costUsd: 3.53, calls: 44, tokens: 9_803_219, unpricedCalls: 0 }, + pricedTokensWeekly: 9_803_219, + exactCostWeeklyUsd: 3.53, + }, + ], + ]), + quotaFetchedAtMs: T0, + nowMs: T0 + 60_000, + }); + assert.equal( + pPolluted.get('Gemini').rateEstimate?.externalUsage ?? null, + null, + 'polluted solo bucket self-heals false externalUsage banner immediately even on cached quota poll' + ); + assert.equal(healedSaved?.buckets?.['local::polluted@example.com::Gemini::weekly']?.hasExternalUsage, false); + assert.equal(healedSaved?.buckets?.['local::polluted@example.com::Gemini::weekly']?.externalUsedPct, 0); + + const pShared = mkPollPools(49.82); + healer.updatePools({ + endpointId: 'local', + accountScope: 'shared@example.com', + quotaPoolsMap: pShared, + poolCycleStats: new Map([ + [ + 'Gemini', + { + cycleWeekly: { costUsd: 196.93, calls: 120, tokens: 60_000_000, unpricedCalls: 0 }, + pricedTokensWeekly: 60_000_000, + exactCostWeeklyUsd: 196.93, + }, + ], + ]), + quotaFetchedAtMs: T0, + nowMs: T0 + 60_000, + }); + assert.equal( + pShared.get('Gemini').rateEstimate?.externalUsage?.detected, + true, + 'genuine shared pool with 17% unexplained burn retains externalUsage detection' + ); + assert.equal(pShared.get('Gemini').rateEstimate?.externalUsage?.usedWeeklyPct, 0.6); +}); From 8b025a969cab51cbd38034a05f5c1cb4a43d7ec8 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 12:46:39 +0900 Subject: [PATCH 09/30] feat(panel): detect and price built-in AI image generation steps - Decode SQLite step_payload 140.2.6 (GenerateImage) and inspect 32KB PNG/JPEG/WebP headers across SQLite and ConnectRPC trajectories, auto-upgrading cached image-generator subagent entries - Map Gemini 3.1 Flash Image, 3 Pro Image, and 2.5 Flash Image resolution tiers (0.5K/1K/2K/4K) and reference image inputs to Google AI Studio token counts and dedicated imageOutput rates - Surface generate_image steps with true startedAt-to-completedAt duration and localized live activity labels while isolating text LLM TPS, TTFT, context window gauges, compaction inference, and exported report averages --- pricing-catalog.json | 15 +- sidecars/panel/app.js | 19 +- sidecars/panel/backend/api-actions.mjs | 4 +- sidecars/panel/backend/cli-sqlite-reader.mjs | 282 +++++++++++- sidecars/panel/backend/local-scanner.mjs | 38 ++ sidecars/panel/backend/model-pricing.mjs | 31 +- sidecars/panel/backend/pricing-catalog.mjs | 16 +- sidecars/panel/backend/telemetry-builder.mjs | 51 ++- sidecars/panel/backend/usage-aggregator.mjs | 1 + sidecars/panel/index.html | 4 +- sidecars/panel/src/core/reportExporter.js | 17 +- sidecars/panel/src/i18n/en-US.js | 1 + sidecars/panel/src/i18n/zh-CN.js | 1 + sidecars/panel/test/model-identity.test.mjs | 419 +++++++++++++++++- .../sqlite-hybrid-and-side-question.test.mjs | 126 +++++- sidecars/panel/trajectory-metrics.mjs | 226 +++++++++- 16 files changed, 1196 insertions(+), 55 deletions(-) diff --git a/pricing-catalog.json b/pricing-catalog.json index 0f27733..877eff9 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.21.3", - "updatedAt": "2026-11-21T14:35:00+09:00", + "catalogVersion": "2026.11.24.1", + "updatedAt": "2026-11-24T11:35:00+09:00", "latestPluginVersion": "1.5.4", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", @@ -102,12 +102,16 @@ "gemini-3.1-flash-lite-preview": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" }, "gemini-3.1-flash-lite": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" }, "gemini-for-google-3.1-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1", "family": "Gemini" }, - "gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1-img", "family": "Gemini" }, + "gemini-3.1-flash-image-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "imageOutput": 60.0, "short": "flash-3.1-img", "family": "Gemini" }, + "gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "imageOutput": 60.0, "short": "flash-3.1-img", "family": "Gemini" }, "gemini-3-flash-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, "gemini-3-flash-c": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, "gemini-3-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, - "gemini-3-pro-image": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3-img", "family": "Gemini" }, + "gemini-3-pro-image-preview": { "input": 2.00, "cache": 0.20, "output": 12.0, "imageOutput": 120.0, "short": "pro-3-img", "family": "Gemini" }, + "gemini-3-pro-image": { "input": 2.00, "cache": 0.20, "output": 12.0, "imageOutput": 120.0, "short": "pro-3-img", "family": "Gemini" }, "gemini-2.5-pro": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "pro-2.5", "family": "Gemini" }, + "gemini-2.5-flash-image-preview": { "input": 0.30, "cache": 0.03, "output": 2.50, "imageOutput": 30.0, "short": "flash-2.5-img", "family": "Gemini" }, + "gemini-2.5-flash-image": { "input": 0.30, "cache": 0.03, "output": 2.50, "imageOutput": 30.0, "short": "flash-2.5-img", "family": "Gemini" }, "gemini-2.5-flash": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-2.5", "family": "Gemini" }, "gemini-2.5-flash-lite": { "input": 0.10, "cache": 0.01, "output": 0.40, "short": "flash-2.5-lite", "family": "Gemini" }, "claude-fable-5-2-max": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2-max", "family": "Claude" }, @@ -212,10 +216,13 @@ "MODEL_PLACEHOLDER_M50": { "modelId": "gemini-3.1-flash-lite", "label": "Gemini 3.1 Flash Lite" }, "MODEL_PLACEHOLDER_M59": { "modelId": "gemini-for-google-3.1-flash", "label": "Gemini for Google 3.1 Flash" }, "MODEL_PLACEHOLDER_M21": { "modelId": "gemini-3.1-flash-image", "label": "Gemini 3.1 Flash Image" }, + "MODEL_GOOGLE_GEMINI_3_1_FLASH_IMAGE_PREVIEW": { "modelId": "gemini-3.1-flash-image-preview", "label": "Gemini 3.1 Flash Image" }, "MODEL_PLACEHOLDER_M47": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" }, "MODEL_PLACEHOLDER_M18": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" }, "MODEL_PLACEHOLDER_M9": { "modelId": "gemini-3-pro-image", "label": "Gemini 3 Pro Image" }, + "MODEL_GOOGLE_GEMINI_3_PRO_IMAGE_PREVIEW": { "modelId": "gemini-3-pro-image-preview", "label": "Gemini 3 Pro Image" }, "MODEL_GOOGLE_GEMINI_2_5_PRO": { "modelId": "gemini-2.5-pro", "label": "Gemini 2.5 Pro" }, + "MODEL_GOOGLE_GEMINI_2_5_FLASH_IMAGE_PREVIEW": { "modelId": "gemini-2.5-flash-image-preview", "label": "Gemini 2.5 Flash Image" }, "MODEL_GOOGLE_GEMINI_2_5_FLASH": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash" }, "MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash (Thinking)" }, "MODEL_PLACEHOLDER_M330": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" }, diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 09fc263..bc1a20b 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -2067,6 +2067,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.schedule': '定时任务', 'live.act.ask_question': '等待用户选择', 'live.act.search_marketplace': '查询插件', + 'live.act.generate_image': '生成图片', 'live.act.mcp_tool': '调用 MCP', 'live.act.tool_call': '调用工具', 'live.act.thinking': '推理中', @@ -2967,6 +2968,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.schedule': 'Schedule Task', 'live.act.ask_question': 'Waiting for User Choice', 'live.act.search_marketplace': 'Search Plugins', + 'live.act.generate_image': 'Generate Image', 'live.act.mcp_tool': 'Call MCP Tool', 'live.act.tool_call': 'Call Tool', 'live.act.thinking': 'Thinking', @@ -6941,6 +6943,7 @@ function summarizeStepsForExport(list, displaySettings) { const validTps = !st.isCompactionStep && + !st.isImageGenStep && outTok >= 50 && !st.selectedSpeedReason && Number.isFinite(Number(st.tokPerSec)) && @@ -6951,7 +6954,11 @@ function summarizeStepsForExport(list, displaySettings) { : outTok / Number(st.tokPerSec) : 0; const validTtft = - !st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0; + !st.isCompactionStep && + !st.isImageGenStep && + st.ttftSec != null && + Number.isFinite(Number(st.ttftSec)) && + Number(st.ttftSec) >= 0; if (validTps && stepSpeedSec > 0) { tpsTokSum += outTok; tpsSecSum += stepSpeedSec; @@ -7282,9 +7289,13 @@ function buildStepsXlsx( ? en ? 'Compaction' : '自动压缩' - : en - ? 'Normal' - : '常规'; + : st.isImageGenStep + ? en + ? 'Image Gen' + : '生成图片' + : en + ? 'Normal' + : '常规'; const tone = anomCount > 0 ? 'danger' : st.isCompactionStep ? 'info' : ''; stepRows.push({ diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 54c93e1..bd7c7f5 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -90,7 +90,7 @@ function sanitizePositiveFiniteMs(val) { function projectDisplayStep(st) { const { - stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, + stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, anomaly, anomalySig, contextTokens, inputTokens, cacheReadTokens, @@ -103,7 +103,7 @@ function projectDisplayStep(st) { rootTurnMediaOnly, } = st; return { - stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel, + stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel, modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec, nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, ...(anomaly ? { anomaly, anomalySig } : {}), diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index ef95418..f424293 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -10,10 +10,13 @@ * 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。 */ -import { existsSync, readFileSync } from 'node:fs'; +import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs'; import { basename, join } from 'node:path'; import { extractShortPromptTitle } from '../shared/prompt-clean.mjs'; -import { parseWorkspaceUrisColumn } from '../shared/workspace-uri.mjs'; +import { + decodeWorkspaceFileUriToPath, + parseWorkspaceUrisColumn, +} from '../shared/workspace-uri.mjs'; import { parseIsoMs } from '../trajectory-metrics.mjs'; import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs'; import { @@ -1522,8 +1525,193 @@ function decodeProtoInvokeSubagentSlice(buf, state, end) { return { subagents, results }; } -function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { +const imageDimsMemo = new Map(); + +function parseImageBufferDimensions(buf) { + if (!buf || buf.length < 11) return null; + // PNG: 89 50 4E 47 0D 0A 1A 0A + IHDR + if ( + buf[0] === 0x89 && + buf[1] === 0x50 && + buf[2] === 0x4e && + buf[3] === 0x47 && + buf.length >= 24 + ) { + const width = buf.readUInt32BE(16); + const height = buf.readUInt32BE(20); + return width > 0 && height > 0 ? { width, height } : null; + } + // JPEG: FF D8 ... SOF0..SOF3 (FF C0..C3) + if (buf[0] === 0xff && buf[1] === 0xd8) { + let i = 2; + while (i + 9 <= buf.length) { + if (buf[i] !== 0xff) { + i += 1; + continue; + } + const marker = buf[i + 1]; + if (marker === 0xff) { + i += 1; + continue; + } + if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) { + i += 2; + continue; + } + if ( + (marker >= 0xc0 && marker <= 0xc3) || + (marker >= 0xc5 && marker <= 0xc7) || + (marker >= 0xc9 && marker <= 0xcb) || + (marker >= 0xcd && marker <= 0xcf) + ) { + const height = buf.readUInt16BE(i + 5); + const width = buf.readUInt16BE(i + 7); + return width > 0 && height > 0 ? { width, height } : null; + } + if (i + 4 > buf.length) break; + const segLen = buf.readUInt16BE(i + 2); + if (segLen < 2) break; + i += 2 + segLen; + } + return null; + } + // WebP: RIFF....WEBP + if ( + buf.length >= 30 && + buf[0] === 0x52 && + buf[1] === 0x49 && + buf[2] === 0x46 && + buf[3] === 0x46 && + buf[8] === 0x57 && + buf[9] === 0x45 && + buf[10] === 0x42 && + buf[11] === 0x50 + ) { + const chunk = buf.subarray(12, 16).toString('ascii'); + if (chunk === 'VP8X' && buf.length >= 30) { + const width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16)); + const height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16)); + return width > 0 && height > 0 ? { width, height } : null; + } + if (chunk === 'VP8 ' && buf.length >= 30) { + const width = buf.readUInt16LE(26) & 0x3fff; + const height = buf.readUInt16LE(28) & 0x3fff; + return width > 0 && height > 0 ? { width, height } : null; + } + if (chunk === 'VP8L' && buf.length >= 25) { + const bits = buf.readUInt32LE(21); + const width = (bits & 0x3fff) + 1; + const height = ((bits >>> 14) & 0x3fff) + 1; + return width > 0 && height > 0 ? { width, height } : null; + } + } + return null; +} + +/** + * 仅读取本地生成图片文件前 32KB 头部字节解析真实像素尺寸(PNG / JPEG / WebP),用于精确匹配图片分辨率计费档位。 + * + * @param {string} rawUri + * @returns {{ width: number, height: number } | null} + */ +export function readLocalImageDimensionsFromUri(rawUri) { + const localPath = decodeWorkspaceFileUriToPath(rawUri); + if (!localPath) return null; + if (imageDimsMemo.has(localPath)) { + return imageDimsMemo.get(localPath); + } + let dims = null; + try { + if (existsSync(localPath)) { + if (typeof openSync === 'function' && typeof readSync === 'function' && typeof closeSync === 'function') { + const fd = openSync(localPath, 'r'); + try { + const head = Buffer.allocUnsafe(32768); + const bytesRead = readSync(fd, head, 0, head.length, 0); + if (bytesRead >= 11) { + dims = parseImageBufferDimensions(head.subarray(0, bytesRead)); + } + } finally { + closeSync(fd); + } + } else if (typeof readFileSync === 'function') { + const raw = readFileSync(localPath); + const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw); + dims = parseImageBufferDimensions(buf); + } + } + } catch { + dims = null; + } + if (dims) { + if (imageDimsMemo.size >= 512) { + const firstKey = imageDimsMemo.keys().next().value; + if (firstKey !== undefined) imageDimsMemo.delete(firstKey); + } + imageDimsMemo.set(localPath, dims); + } + return dims; +} + +function decodeProtoGenerateImageSlice(buf, state, end) { + let prompt = ''; + let aspectRatio = ''; + let uri = ''; + let fileSizeBytes = 0; + let modelName = ''; + let imageName = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + prompt = readProtoString(buf, state, end); + } else if (fn === 3 && wt === 2) { + aspectRatio = readProtoString(buf, state, end); + } else if (fn === 4 && wt === 2) { + uri = readProtoString(buf, state, end); + } else if (fn === 5 && wt === 0) { + fileSizeBytes = Number(readProtoVarint(buf, state, end)); + } else if (fn === 6 && wt === 2) { + modelName = readProtoString(buf, state, end); + } else if (fn === 8 && wt === 2) { + imageName = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { prompt, aspectRatio, uri, fileSizeBytes, modelName, imageName }; +} + +function decodeProtoGeneratedMediaSlice(buf, state, end) { + let mimeType = ''; + let uri = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + mimeType = readProtoString(buf, state, end); + } else if (fn === 5 && wt === 2) { + uri = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return mimeType || uri ? { mimeType, uri } : null; +} + +function decodeProtoGenericStepToolPayloadSlice( + buf, + state, + end, + { wantInvokeSubagent = false, wantGenerateImage = false } = {} +) { let invokeSubagent = null; + let generateImage = null; + let mediaFallback = null; while (state.off < end) { const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; @@ -1532,7 +1720,11 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { const resEnd = readSubEnd(buf, state, end); while (state.off < resEnd) { const resTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd))); - if ((resTag >>> 3) === 6 && (resTag & 7) === 2) { + const rFn = resTag >>> 3; + const rWt = resTag & 7; + if (rFn === 4 && rWt === 2 && wantGenerateImage) { + mediaFallback = decodeProtoGeneratedMediaSlice(buf, state, readSubEnd(buf, state, resEnd)); + } else if (rFn === 6 && rWt === 2) { const anyEnd = readSubEnd(buf, state, resEnd); let typeUrl = ''; let valStart = 0; @@ -1550,15 +1742,23 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { } } state.off = anyEnd; - if ( - valEnd > valStart && - (typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') || - typeUrl === 'exa.cortex.core.tools.InvokeSubagent') - ) { - invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd); + if (valEnd > valStart) { + if ( + wantInvokeSubagent && + (typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') || + typeUrl === 'exa.cortex.core.tools.InvokeSubagent') + ) { + invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd); + } else if ( + wantGenerateImage && + (typeUrl.endsWith('/exa.cortex.core.tools.GenerateImage') || + typeUrl === 'exa.cortex.core.tools.GenerateImage') + ) { + generateImage = decodeProtoGenerateImageSlice(buf, { off: valStart }, valEnd); + } } } else { - skipProtoField(buf, state, resTag & 7, resEnd); + skipProtoField(buf, state, rWt, resEnd); } } state.off = resEnd; @@ -1567,7 +1767,27 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { } } state.off = end; - return invokeSubagent; + if (generateImage || mediaFallback) { + const resolvedUri = generateImage?.uri || mediaFallback?.uri || ''; + const dims = resolvedUri ? readLocalImageDimensionsFromUri(resolvedUri) : null; + generateImage = { + prompt: generateImage?.prompt || '', + imageName: generateImage?.imageName || '', + aspectRatio: generateImage?.aspectRatio || '', + modelName: generateImage?.modelName || '', + ...(generateImage?.fileSizeBytes > 0 ? { fileSizeBytes: generateImage.fileSizeBytes } : {}), + ...(resolvedUri || mediaFallback?.mimeType + ? { + generatedMedia: { + mimeType: mediaFallback?.mimeType || '', + uri: resolvedUri, + }, + } + : {}), + ...(dims ? { width: dims.width, height: dims.height } : {}), + }; + } + return { invokeSubagent, generateImage }; } function decodeProtoSystemMessageSlice(buf, state, end) { @@ -1588,7 +1808,13 @@ function decodeProtoSystemMessageSlice(buf, state, end) { function decodeProtoSelectiveStepPayload( rawBlob, - { stepTypeNum, isInvokeSubagent, includeSystemMessage = false, keepFullText } + { + stepTypeNum, + isInvokeSubagent, + isGenerateImage = false, + includeSystemMessage = false, + keepFullText, + } ) { const buf = toUint8Array(rawBlob); if (!buf || buf.length === 0) return {}; @@ -1616,9 +1842,15 @@ function decodeProtoSelectiveStepPayload( } else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) { const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end)); if (sysMsg) out.systemMessage = { message: sysMsg }; - } else if (fn === 140 && wt === 2 && isInvokeSubagent) { - const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); - if (inv) out.invokeSubagent = inv; + } else if (fn === 140 && wt === 2 && (isInvokeSubagent || isGenerateImage)) { + const toolParsed = decodeProtoGenericStepToolPayloadSlice( + buf, + state, + readSubEnd(buf, state, end), + { wantInvokeSubagent: isInvokeSubagent, wantGenerateImage: isGenerateImage } + ); + if (toolParsed.invokeSubagent) out.invokeSubagent = toolParsed.invokeSubagent; + if (toolParsed.generateImage) out.generateImage = toolParsed.generateImage; } else if (fn === 143 && wt === 2 && isInvokeSubagent) { out.invokeSubagent = decodeProtoInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); } else { @@ -1632,6 +1864,10 @@ function isInvokeSubagentToolName(rawName) { return /^(?:default_api:)?invoke_subagent$/i.test(String(rawName || '').trim()); } +function isGenerateImageToolName(rawName) { + return /^(?:default_api:)?generate_image$/i.test(String(rawName || '').trim()); +} + function mapRunningGenericToolStepType(rawToolName) { const name = String(rawToolName || '') .trim() @@ -1639,6 +1875,7 @@ function mapRunningGenericToolStepType(rawToolName) { .replace(/^default_api:/, ''); if (!name) return 'CORTEX_STEP_TYPE_GENERIC'; if (name === 'invoke_subagent') return 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + if (name === 'generate_image') return 'CORTEX_STEP_TYPE_GENERATE_IMAGE'; if (name === 'run_command') return 'CORTEX_STEP_TYPE_RUN_COMMAND'; if (name === 'command_status') return 'CORTEX_STEP_TYPE_COMMAND_STATUS'; if (name === 'send_command_input') return 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT'; @@ -1895,12 +2132,16 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { const isInvSub = rec.stepTypeNum === 127 || (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + const isGenImg = + rec.stepTypeNum === 91 || + (rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name)); if ( rec.stepTypeNum === 14 || rec.stepTypeNum === 15 || rec.stepTypeNum === 17 || (isChildTrajectory && rec.stepTypeNum === 101) || isInvSub || + isGenImg || (inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson)) ) { payloadIndices.push(rec.idx); @@ -1938,10 +2179,15 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { const isInvSub = rec.stepTypeNum === 127 || (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + const isGenImg = + rec.stepTypeNum === 91 || + (rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name)); let type = ''; if (isInvSub) { type = 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + } else if (isGenImg) { + type = 'CORTEX_STEP_TYPE_GENERATE_IMAGE'; } else if (rec.stepTypeNum === 132 && inRunningTail) { type = mapRunningGenericToolStepType(rec.metadata?.toolCall?.name); } else { @@ -1962,6 +2208,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, { stepTypeNum: rec.stepTypeNum, isInvokeSubagent: isInvSub, + isGenerateImage: isGenImg, includeSystemMessage: isChildTrajectory && rec.stepTypeNum === 101, keepFullText: inRunningTail, }); @@ -1987,6 +2234,9 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if (decodedPayload.invokeSubagent) { stepObj.invokeSubagent = decodedPayload.invokeSubagent; } + if (decodedPayload.generateImage) { + stepObj.generateImage = decodedPayload.generateImage; + } } catch { // 忽略单步载荷解析异常 } diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index c593c74..b674d33 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -37,6 +37,7 @@ import { computeSqliteWalSig, hasBuiltinNodeSqlite, readAnnotationTitleForCascade, + readLocalImageDimensionsFromUri, readLocalSqliteTrajectory, readLocalSummaryIndex, } from './cli-sqlite-reader.mjs'; @@ -2207,6 +2208,19 @@ export async function enumerateAndSyncConversations({ const { steps: rawSteps, generatorMeta } = loadedViaSqlite ? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta } : filterClonedTrajectorySteps(rawStepsUnfiltered, rawGenMeta, cidLower); + if (!isRemote && !loadedViaSqlite) { + for (const rawSt of rawSteps) { + const gi = rawSt?.generateImage; + const mediaUri = gi?.generatedMedia?.uri; + if (gi && mediaUri && !(Number(gi.width) > 0 && Number(gi.height) > 0)) { + const dims = readLocalImageDimensionsFromUri(mediaUri); + if (dims) { + gi.width = dims.width; + gi.height = dims.height; + } + } + } + } const steps = extractModelSteps(rawSteps, generatorMeta); const nextLast = steps[steps.length - 1]; @@ -2361,6 +2375,7 @@ export async function enumerateAndSyncConversations({ wakeupTurnTelemetry: true, contextGroupsTelemetry: 3, anomalyTelemetry: 1, + imageGenTelemetry: 1, steps: stepsWithOwners, ...(contextPreserved.lastKnownStaticContext ? { lastKnownStaticContext: contextPreserved.lastKnownStaticContext } @@ -2407,6 +2422,7 @@ export async function enumerateAndSyncConversations({ !prev.turnRailTelemetry || Number(prev.contextGroupsTelemetry || 0) < 3 || !prev.anomalyTelemetry || + !prev.imageGenTelemetry || metaChanged || !isDeepStrictEqual(prev.steps, stepsWithOwners); @@ -2641,6 +2657,18 @@ export async function enumerateAndSyncConversations({ lowerCid === selectedRootId || Boolean(conv.rootConversationId && conv.rootConversationId.toLowerCase() === selectedRootId); if (!cached.contextLimitTelemetry && lowerCid === contextTelemetryCascadeId) return true; + const isImgGenAgent = + String( + conv.subagentSpec?.typeName || + cached.subagentSpec?.typeName || + cached.agentTypeName || + '' + ) + .trim() + .toLowerCase() === 'image-generator'; + if (!cached.imageGenTelemetry && isImgGenAgent) { + return true; + } if ( (!cached.turnRailTelemetry || !cached.anomalyTelemetry || @@ -2860,6 +2888,15 @@ export async function enumerateAndSyncConversations({ const targetCacheKey = subConv.cascadeId; const existingSubCache = getEntry(targetCacheKey); const isSelectedSubFamily = rootId === selectedRootId; + const isImgGenSub = + String( + subConv.subagentSpec?.typeName || + existingSubCache?.subagentSpec?.typeName || + existingSubCache?.agentTypeName || + '' + ) + .trim() + .toLowerCase() === 'image-generator'; const hasValidSubCache = existingSubCache && !(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) && @@ -2869,6 +2906,7 @@ export async function enumerateAndSyncConversations({ : `${CACHE_SCHEMA_VERSION}:` ) && !hasMissingStepFields(existingSubCache) && + (!isImgGenSub || Boolean(existingSubCache.imageGenTelemetry)) && (!isSelectedSubFamily || (Boolean(existingSubCache.turnRailTelemetry) && Boolean(existingSubCache.anomalyTelemetry) && diff --git a/sidecars/panel/backend/model-pricing.mjs b/sidecars/panel/backend/model-pricing.mjs index 4e5c2c6..dcdec48 100644 --- a/sidecars/panel/backend/model-pricing.mjs +++ b/sidecars/panel/backend/model-pricing.mjs @@ -234,6 +234,16 @@ export function formatGenericModelSlug(slug = '') { if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash'; if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash'; if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro'; + const imgMatch = s.match( + /^gemini-(\d+(?:\.\d+)?)-(pro|flash)(?:-(lite))?-image(?:-(preview))?$/i + ); + if (imgMatch) { + const ver = imgMatch[1]; + const tier = imgMatch[2].charAt(0).toUpperCase() + imgMatch[2].slice(1).toLowerCase(); + const lite = imgMatch[3] ? ' Lite' : ''; + const prev = imgMatch[4] ? ' (Preview)' : ''; + return `Gemini ${ver} ${tier}${lite} Image${prev}`; + } const m = s.match( /^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|neon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i ); @@ -317,10 +327,12 @@ export function resolvePricingAt(pricingEntry, atMs) { ? parseIsoMs(ph.until.trim()) || Infinity : Infinity; if (tMs >= fromMs && tMs < untilMs) { + const nextImgOut = ph.imageOutput ?? baseEntry.imageOutput; if ( ph.input === baseEntry.input && ph.cache === baseEntry.cache && - ph.output === baseEntry.output + ph.output === baseEntry.output && + nextImgOut === baseEntry.imageOutput ) { return baseEntry; } @@ -329,6 +341,7 @@ export function resolvePricingAt(pricingEntry, atMs) { input: ph.input, cache: ph.cache, output: ph.output, + ...(nextImgOut !== undefined ? { imageOutput: nextImgOut } : {}), }; Object.defineProperty(resolved, '_basePricing', { value: baseEntry, @@ -641,6 +654,19 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) { * @param {{ input: number, cache: number, output: number } | null} pricing * @returns {number|null} */ +export function resolveEffectiveOutputRate(pricing, step) { + if (!pricing || typeof pricing !== 'object') return null; + if ( + step?.isImageGenStep && + typeof pricing.imageOutput === 'number' && + Number.isFinite(pricing.imageOutput) && + pricing.imageOutput > 0 + ) { + return pricing.imageOutput; + } + return pricing.output; +} + export function computeStepCost(step, pricing) { if (!pricing) return null; const stepMs = extractStepTimestampMs(step); @@ -652,8 +678,9 @@ export function computeStepCost(step, pricing) { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; }; + const outRate = resolveEffectiveOutputRate(effectivePricing, step); const inCost = (safeTok(step?.inputTokens) / 1_000_000) * effectivePricing.input; const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * effectivePricing.cache; - const outCost = (safeTok(step?.outputTokens) / 1_000_000) * effectivePricing.output; + const outCost = (safeTok(step?.outputTokens) / 1_000_000) * outRate; return inCost + cacheCost + outCost; } diff --git a/sidecars/panel/backend/pricing-catalog.mjs b/sidecars/panel/backend/pricing-catalog.mjs index 84b82dd..a63ba04 100644 --- a/sidecars/panel/backend/pricing-catalog.mjs +++ b/sidecars/panel/backend/pricing-catalog.mjs @@ -229,6 +229,10 @@ function isValidPricingRateTriplet(entry) { * 校验并归一化单个时间阶段单价配置(左闭右开 `[fromMs, untilMs)`)。 * 至少需声明合法的 `from` 或 `until` ISO 时间戳,且若同时声明须满足 `fromMs < untilMs`。 */ +function sanitizeOptionalImageOutputRate(val) { + return typeof val === 'number' && Number.isFinite(val) && val > 0 && val <= 10000 ? val : null; +} + function sanitizePricingPhase(rawPhase) { if (!isValidPricingRateTriplet(rawPhase)) return null; let from = null; @@ -251,12 +255,14 @@ function sanitizePricingPhase(rawPhase) { } if (from === null && until === null) return null; if (fromMs >= untilMs) return null; + const imageOutput = sanitizeOptionalImageOutputRate(rawPhase.imageOutput); return { ...(from !== null ? { from, fromMs } : {}), ...(until !== null ? { until, untilMs } : {}), input: rawPhase.input, cache: rawPhase.cache, output: rawPhase.output, + ...(imageOutput !== null ? { imageOutput } : {}), }; } @@ -305,10 +311,12 @@ export function sanitizeCatalogPayload(raw) { phases = cleanedPhases; } } + const imageOutput = sanitizeOptionalImageOutputRate(v.imageOutput); pricing[key] = { input: v.input, cache: v.cache, output: v.output, + ...(imageOutput !== null ? { imageOutput } : {}), short: String(v.short).trim(), family: normalizeModelFamily(v.family), ...(phases ? { phases } : {}), @@ -413,7 +421,13 @@ export function rebuildActiveCatalog() { : DEFAULT_ARCHIVE_FALLBACK_URL; for (const { kind, cat } of layers) { - Object.assign(nextPricing, cat.pricing); + for (const [pk, pv] of Object.entries(cat.pricing)) { + const prevImgOut = nextPricing[pk]?.imageOutput; + nextPricing[pk] = + prevImgOut !== undefined && pv.imageOutput === undefined + ? { ...pv, imageOutput: prevImgOut } + : pv; + } Object.assign(nextPlaceholders, cat.placeholders); if (kind === 'remote' || cat.catalogVersion || cat.updatedAt) { activeSource = kind; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 7a8d93e..f2cf633 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -130,7 +130,7 @@ function readTrajectoryModelFacts(steps) { fallbackModelKeys.add(step.modelKey); } } - if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) { + if (!step?.isCompactionStep && !step?.isImageGenStep && step?.reportedContextLimitTokens > 0) { sortableLimits &&= Number.isFinite(step.createdAtMs); rememberModelContextLimit(limits, step); } @@ -209,7 +209,15 @@ function enrichActiveConversationSteps( const cacheCostUsd = mInfo.pricing ? (st.cacheReadTokens / 1_000_000) * mInfo.pricing.cache : null; - const outCostUsd = mInfo.pricing ? (st.outputTokens / 1_000_000) * mInfo.pricing.output : null; + const effectiveOutRate = mInfo.pricing + ? st.isImageGenStep && + typeof mInfo.pricing.imageOutput === 'number' && + mInfo.pricing.imageOutput > 0 + ? mInfo.pricing.imageOutput + : mInfo.pricing.output + : null; + const outCostUsd = + effectiveOutRate !== null ? (st.outputTokens / 1_000_000) * effectiveOutRate : null; const resolvedResponseModel = st.responseModel || (st.modelKey && st.modelKey !== 'unknown' @@ -457,6 +465,7 @@ function extractActiveContextTelemetry( for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) { const stepM = enrichedActiveSteps[m]; if (!stepM || stepM.isCompactionStep) break; + if (stepM.isImageGenStep) continue; const mPrompt = Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); const mOut = resolveStepOutputTokens(stepM); @@ -512,7 +521,7 @@ function extractActiveContextTelemetry( let runningTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0); for (let m = lastCompactionIdx + 1; m < enrichedActiveSteps.length; m++) { const stepM = enrichedActiveSteps[m]; - if (!stepM || stepM.isCompactionStep) continue; + if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue; const mPrompt = Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); const mOut = resolveStepOutputTokens(stepM); @@ -538,7 +547,7 @@ function extractActiveContextTelemetry( let seededInitial = false; for (let m = 0; m < enrichedActiveSteps.length; m++) { const stepM = enrichedActiveSteps[m]; - if (!stepM || stepM.isCompactionStep) continue; + if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue; const mPrompt = Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); const mOut = resolveStepOutputTokens(stepM); @@ -601,25 +610,39 @@ function extractActiveContextTelemetry( const ctxBreakdownTotal = ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules; - const isLatestCompaction = Boolean(latestEnriched?.isCompactionStep); - const ctxCached = latestEnriched?.cacheReadTokens || 0; - const ctxFreshInput = latestEnriched?.inputTokens || 0; - const ctxThinking = latestEnriched?.thinkingTokens || 0; - const ctxResponse = latestEnriched?.responseTokens || 0; - const ctxOut = resolveStepOutputTokens(latestEnriched); + let ctxRefStep = latestEnriched; + if (ctxRefStep?.isImageGenStep) { + for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { + if (!enrichedActiveSteps[i]?.isImageGenStep) { + ctxRefStep = enrichedActiveSteps[i]; + break; + } + } + } + const isLatestCompaction = Boolean(ctxRefStep?.isCompactionStep); + const ctxCached = ctxRefStep?.cacheReadTokens || 0; + const ctxFreshInput = ctxRefStep?.inputTokens || 0; + const ctxThinking = ctxRefStep?.thinkingTokens || 0; + const ctxResponse = ctxRefStep?.responseTokens || 0; + const ctxOut = resolveStepOutputTokens(ctxRefStep); const ctxTotal = isLatestCompaction ? ctxBreakdownTotal : ctxBreakdownTotal > 0 ? ctxBreakdownTotal - : ctxCached + ctxFreshInput + ctxOut || Number(latestEnriched?.estimatedContextTokens || 0); + : (ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput + ctxOut) || + Number(ctxRefStep?.estimatedContextTokens || 0); const compactionLimitTokens = Number( - (isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0 + (isLatestCompaction && !ctxRefStep?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0 ? fallbackPreCompactionLimit - : latestEnriched?.maxContextBudgetTokens) || 256000 + : ctxRefStep?.maxContextBudgetTokens) || 256000 ); const compactionUsedTokens = isLatestCompaction ? Number(ctxTotal) - : Number(ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput); + : Number( + ctxTotal || + ctxRefStep?.estimatedContextTokens || + (ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput) + ); const compactionUsedPct = compactionLimitTokens > 0 ? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1)) diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 60e4f6f..8510c6b 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -348,6 +348,7 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) { accumulateSpeed(agg.speedAccumulator, st); if ( !st.isCompactionStep && + !st.isImageGenStep && st.measurementVersion === MEASUREMENT_VERSION && st.isComplete && Number.isFinite(st.totalDurationSec) && diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 7ca2a9b..9b4bd15 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index f74e807..29f5b86 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -209,6 +209,7 @@ function summarizeStepsForExport(list, displaySettings) { const validTps = !st.isCompactionStep && + !st.isImageGenStep && outTok >= 50 && !st.selectedSpeedReason && Number.isFinite(Number(st.tokPerSec)) && @@ -219,7 +220,11 @@ function summarizeStepsForExport(list, displaySettings) { : outTok / Number(st.tokPerSec) : 0; const validTtft = - !st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0; + !st.isCompactionStep && + !st.isImageGenStep && + st.ttftSec != null && + Number.isFinite(Number(st.ttftSec)) && + Number(st.ttftSec) >= 0; if (validTps && stepSpeedSec > 0) { tpsTokSum += outTok; tpsSecSum += stepSpeedSec; @@ -550,9 +555,13 @@ export function buildStepsXlsx( ? en ? 'Compaction' : '自动压缩' - : en - ? 'Normal' - : '常规'; + : st.isImageGenStep + ? en + ? 'Image Gen' + : '生成图片' + : en + ? 'Normal' + : '常规'; const tone = anomCount > 0 ? 'danger' : st.isCompactionStep ? 'info' : ''; stepRows.push({ diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 6b8311f..a2b25e2 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -808,6 +808,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.act.schedule': 'Schedule Task', 'live.act.ask_question': 'Waiting for User Choice', 'live.act.search_marketplace': 'Search Plugins', + 'live.act.generate_image': 'Generate Image', 'live.act.mcp_tool': 'Call MCP Tool', 'live.act.tool_call': 'Call Tool', 'live.act.thinking': 'Thinking', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 58be7a0..085b2ce 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -808,6 +808,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.act.schedule': '定时任务', 'live.act.ask_question': '等待用户选择', 'live.act.search_marketplace': '查询插件', + 'live.act.generate_image': '生成图片', 'live.act.mcp_tool': '调用 MCP', 'live.act.tool_call': '调用工具', 'live.act.thinking': '推理中', diff --git a/sidecars/panel/test/model-identity.test.mjs b/sidecars/panel/test/model-identity.test.mjs index a00f140..fef758b 100644 --- a/sidecars/panel/test/model-identity.test.mjs +++ b/sidecars/panel/test/model-identity.test.mjs @@ -1,12 +1,20 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { isEquivalentTelemetry } from '../src/store/telemetryStore.js'; -import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs'; import { + estimateImageGenStepUsage, + extractModelSteps, + normalizeCachedStep, + MODEL_IDENTITY_VERSION, +} from '../trajectory-metrics.mjs'; +import { + formatLiveActivityLabel, formatUsd, mergeModelsByDisplayName, resolveModelDisplayInfo, } from '../src/core/formatters.js'; +import { buildStepsMarkdownReport } from '../src/core/reportExporter.js'; +import { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; import { backendHarness } from './backend-harness.mjs'; const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418'; @@ -1102,3 +1110,412 @@ test('mergeModelsByDisplayName collapses distinct backend buckets that share the ); assert.equal(mergedShort.length, 2); }); + +test('Google AI Studio image resolution tiers and pricing map cleanly across Gemini 3.1 Flash Image, 3 Pro Image, and 2.5 Flash Image', () => { + const h = backendHarness({ clock: () => PROMO_CLOCK_MS }); + + // 1. Gemini 3.1 Flash Image: 0.5K (747), 1K (1120), 2K (1680), 4K (2520) @ $60/1M image output + const flash31_05k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3.1-flash-image', + prompt: 'tiny icon', + imageDimensions: { width: 512, height: 512 }, + }, + }); + assert.equal(flash31_05k.resolutionTier, '0.5K'); + assert.equal(flash31_05k.outputTokens, 747); + + const flash31_1k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3.1-flash-image', + prompt: 'cozy cat by rainy window', + aspectRatio: '4:3', + imageDimensions: { width: 1200, height: 896 }, + }, + }); + assert.equal(flash31_1k.resolutionTier, '1K'); + assert.equal(flash31_1k.outputTokens, 1120); + + const flash31_2k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3.1-flash-image-preview', + prompt: 'detailed wallpaper', + imageDimensions: { width: 2048, height: 1536 }, + }, + }); + assert.equal(flash31_2k.resolutionTier, '2K'); + assert.equal(flash31_2k.outputTokens, 1680); + + const flash31_4k = estimateImageGenStepUsage({ + metadata: { + toolCall: { + argumentsJson: JSON.stringify({ + Prompt: 'edit reference scene', + ImagePaths: ['a.png', 'b.png'], + }), + }, + }, + generateImage: { + modelName: 'gemini-3.1-flash-image', + imageDimensions: { width: 4096, height: 3072 }, + }, + }); + assert.equal(flash31_4k.resolutionTier, '4K'); + assert.equal(flash31_4k.outputTokens, 2520); + assert.ok(flash31_4k.inputTokens >= 1120, '2 reference images add 2 * 560 = 1120 input tokens'); + + // Canceled or failed step without generated result yields 0 image output tokens + const failedUsage = estimateImageGenStepUsage( + { generateImage: { modelName: 'gemini-3.1-flash-image', prompt: 'failed prompt' } }, + false + ); + assert.equal(failedUsage.outputTokens, 0); + + const mFlash31 = h.resolveModelInfo('gemini-3.1-flash-image'); + assert.equal(mFlash31.label, 'Gemini 3.1 Flash Image'); + assert.equal(mFlash31.shortName, 'flash-3.1-img'); + assert.equal(mFlash31.pricing.input, 0.5); + assert.equal(mFlash31.pricing.imageOutput, 60); + // 200 input * $0.50/M ($0.0001) + 1120 image output * $60/M ($0.0672) = $0.0673 + const costFlash31 = h.computeStepCost( + { isImageGenStep: true, inputTokens: 200, cacheReadTokens: 0, outputTokens: 1120 }, + mFlash31.pricing + ); + assert.ok(Math.abs(costFlash31 - 0.0673) < 1e-9); + + // 2. Gemini 3 Pro Image: 1K/2K -> 1120, 4K -> 2000 @ $120/1M image output ($0.1344 and $0.24) + const pro3_2k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3-pro-image-preview', + prompt: 'studio product render', + imageDimensions: { width: 2048, height: 2048 }, + }, + }); + const pro3_4k = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-3-pro-image', + prompt: 'studio product render 4k', + imageDimensions: { width: 4096, height: 4096 }, + }, + }); + assert.equal(pro3_2k.outputTokens, 1120); + assert.equal(pro3_4k.outputTokens, 2000); + const mPro3 = h.resolveModelInfo('MODEL_GOOGLE_GEMINI_3_PRO_IMAGE_PREVIEW'); + assert.equal(mPro3.shortName, 'pro-3-img'); + assert.equal(mPro3.pricing.imageOutput, 120); + assert.ok( + Math.abs( + h.computeStepCost( + { isImageGenStep: true, inputTokens: 0, cacheReadTokens: 0, outputTokens: 1120 }, + mPro3.pricing + ) - 0.1344 + ) < 1e-9 + ); + assert.ok( + Math.abs( + h.computeStepCost( + { isImageGenStep: true, inputTokens: 0, cacheReadTokens: 0, outputTokens: 2000 }, + mPro3.pricing + ) - 0.24 + ) < 1e-9 + ); + + // 3. Gemini 2.5 Flash Image: 1290 output tokens @ $30/1M ($0.0387) + const flash25 = estimateImageGenStepUsage({ + generateImage: { + modelName: 'gemini-2.5-flash-image', + prompt: 'sketch', + imageDimensions: { width: 1024, height: 1024 }, + }, + }); + assert.equal(flash25.outputTokens, 1290); + const mFlash25 = h.resolveModelInfo('MODEL_GOOGLE_GEMINI_2_5_FLASH_IMAGE_PREVIEW'); + assert.equal(mFlash25.label, 'Gemini 2.5 Flash Image'); + assert.equal(mFlash25.shortName, 'flash-2.5-img'); + assert.equal(mFlash25.pricing.imageOutput, 30); + assert.ok( + Math.abs( + h.computeStepCost( + { isImageGenStep: true, inputTokens: 0, cacheReadTokens: 0, outputTokens: 1290 }, + mFlash25.pricing + ) - 0.0387 + ) < 1e-9 + ); + + // 4. Structured live activity i18n + reportExporter null-TTFT isolation + const prevLang = i18nStore.getState().language; + try { + setI18nLanguage('zh-CN'); + assert.equal(formatLiveActivityLabel({ actionKey: 'generate_image' }), '生成图片'); + setI18nLanguage('en-US'); + assert.equal(formatLiveActivityLabel({ actionKey: 'generate_image' }), 'Generate Image'); + } finally { + setI18nLanguage(prevLang); + } + + const md = buildStepsMarkdownReport( + [ + { + stepIndex: 1, + modelLabel: 'Gemini 4 Hydrogen (High)', + modelShort: 'hydrogen-4-high', + inputTokens: 1000, + cacheReadTokens: 0, + outputTokens: 200, + tokPerSec: 50, + ttftSec: 4.0, + totalDurationSec: 4.0, + costUsd: 0.008, + }, + { + stepIndex: 2, + isImageGenStep: true, + modelLabel: 'Gemini 3.1 Flash Image', + modelShort: 'flash-3.1-img', + inputTokens: 200, + cacheReadTokens: 0, + outputTokens: 1120, + tokPerSec: 17.8, + selectedSpeedReason: 'image_gen', + ttftSec: null, + totalDurationSec: 62.785, + costUsd: 0.0673, + }, + ], + { locale: 'en-US' } + ); + // Avg TTFT must remain 4.0s (from step #1 only), NOT diluted to 2.0s by Number(null) === 0! + assert.match(md, /\*\*Avg Speed\*\*: 50\.0 tok\/s · \*\*Avg TTFT\*\*: 4\.0s/); +}); + +test('image-generator subagent surfaces generate_image step, isolates text TPS/TTFT/compaction/context, and auto-upgrades legacy cache', async () => { + const HYDROGEN_HIGH = 'MODEL_PLACEHOLDER_M424'; + const mainId = '57963098-ddca-4441-a6f1-c931bbf600d8'; + const subId = 'd369e740-1f52-4f06-90a3-2f88bc623e2e'; + const t0 = PROMO_CLOCK_MS - 120_000; + + const mainTraj = { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(t0).toISOString(), + completedAt: new Date(t0 + 5_000).toISOString(), + modelUsage: { + model: ARGON, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '15000', + cacheReadTokens: '0', + outputTokens: '500', + }, + }, + plannerResponse: { + toolCalls: [{ name: 'invoke_subagent', argumentsJson: '{"TypeName":"image-generator"}' }], + }, + }, + { + type: 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: new Date(t0 + 5_100).toISOString(), + completedAt: new Date(t0 + 75_000).toISOString(), + }, + invokeSubagent: { conversationId: subId }, + }, + ], + }, + }; + + const subTraj = { + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: new Date(t0 + 6_000).toISOString(), + completedAt: new Date(t0 + 10_000).toISOString(), + modelUsage: { + model: HYDROGEN_HIGH, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '3000', + cacheReadTokens: '0', + outputTokens: '400', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_GENERATE_IMAGE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: new Date(t0 + 11_000).toISOString(), + // finishedGeneratingAt is tool-call emission (~0.12s), whereas startedAt -> completedAt is 62.785s + finishedGeneratingAt: new Date(t0 + 11_120).toISOString(), + startedAt: new Date(t0 + 11_125).toISOString(), + completedAt: new Date(t0 + 73_910).toISOString(), + toolCall: { + name: 'generate_image', + argumentsJson: JSON.stringify({ + Prompt: + 'Warm cozy orange tabby cat sitting on wooden windowsill watching gentle rain outside, cinematic warm lamp lighting, detailed illustration', + AspectRatio: '4:3', + ImageName: 'cozy_cat_window', + }), + }, + }, + generateImage: { + prompt: + 'Warm cozy orange tabby cat sitting on wooden windowsill watching gentle rain outside, cinematic warm lamp lighting, detailed illustration', + aspectRatio: '4:3', + modelName: 'gemini-3.1-flash-image', + imageName: 'cozy_cat_window', + fileSizeBytes: 983509, + imageDimensions: { width: 1200, height: 896 }, + }, + }, + // Checkpoint right after generate_image must inherit HYDROGEN_HIGH, NOT gemini-3.1-flash-image! + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 3 }, + createdAt: new Date(t0 + 74_000).toISOString(), + completedAt: new Date(t0 + 74_500).toISOString(), + modelUsage: { + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '4000', + cacheReadTokens: '0', + outputTokens: '150', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 5 }, + createdAt: new Date(t0 + 74_600).toISOString(), + completedAt: new Date(t0 + 76_600).toISOString(), + modelUsage: { + model: HYDROGEN_HIGH, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '2800', + cacheReadTokens: '2200', + outputTokens: '200', + }, + }, + }, + ], + generatorMetadata: [ + { + stepIndices: [1], + chatModel: { + model: HYDROGEN_HIGH, + responseModel: 'gemini-4-hydrogen-preview', + modelDisplayName: 'Gemini 4 Hydrogen (High)', + timeToFirstToken: '2.0s', + chatStartMetadata: { + contextWindowMetadata: { estimatedTokensUsed: 3400, maxContextTokens: 512000 }, + }, + }, + }, + { + stepIndices: [5], + chatModel: { + model: HYDROGEN_HIGH, + responseModel: 'gemini-4-hydrogen-preview', + modelDisplayName: 'Gemini 4 Hydrogen (High)', + timeToFirstToken: '1.0s', + chatStartMetadata: { + contextWindowMetadata: { estimatedTokensUsed: 5200, maxContextTokens: 512000 }, + }, + }, + }, + ], + }, + }; + + // Seed legacy pre-image-gen cache entry lacking `imageGenTelemetry` to verify automatic cache upgrade + const h = backendHarness({ + clock: () => PROMO_CLOCK_MS, + cache: { + [subId]: { + stepCount: 6, + lastModifiedTime: new Date(t0 + 76_600).toISOString(), + parentConversationId: mainId, + agentTypeName: 'image-generator', + steps: [ + { + stepIndex: 1, + modelKey: HYDROGEN_HIGH, + inputTokens: 3000, + cacheReadTokens: 0, + outputTokens: 400, + }, + ], + }, + }, + summaries: { + [mainId]: { + stepCount: 3, + lastModifiedTime: new Date(t0 + 76_600).toISOString(), + }, + [subId]: { + stepCount: 6, + lastModifiedTime: new Date(t0 + 76_600).toISOString(), + parentConversationId: mainId, + trajectoryMetadata: { + parentConversationId: mainId, + subagentSpec: { typeName: 'image-generator', role: 'Image Generator' }, + }, + }, + }, + trajectories: { + [mainId]: mainTraj, + [subId]: subTraj, + }, + }); + + const p = await h.buildTelemetryPayloadInternal(mainId); + const subAgent = p.activeConversation.agents.find((a) => !a.isMain); + assert.ok(subAgent, 'image-generator subagent should be attached to activeConversation.agents'); + + const imgStep = subAgent.recentSteps.find((s) => s.stepIndex === 2); + assert.ok(imgStep, 'step #2 (generate_image) should be surfaced after auto-upgrading legacy cache'); + assert.equal(imgStep.isImageGenStep, true); + assert.equal(imgStep.modelShort, 'flash-3.1-img'); + assert.equal(imgStep.modelLabel, 'Gemini 3.1 Flash Image'); + assert.equal(imgStep.outputTokens, 1120); + assert.equal(imgStep.ttftSec, null); + assert.equal(imgStep.selectedSpeedReason, 'image_gen'); + assert.ok(Math.abs(imgStep.totalDurationSec - 62.785) < 0.01); + assert.equal(imgStep.tokPerSec, 17.8); + assert.equal(imgStep.outCostUsd, 0.0672); + assert.ok(imgStep.costUsd >= 0.0672 && imgStep.costUsd <= 0.0674); + + // Compaction step #3 must inherit Hydrogen High, NOT Gemini 3.1 Flash Image! + const cpStep = subAgent.recentSteps.find((s) => s.stepIndex === 3); + assert.ok(cpStep); + assert.equal(cpStep.modelKey, HYDROGEN_HIGH); + assert.equal(cpStep.modelSource, 'inferred_compaction'); + + // Subagent text LLM TPS & TTFT averages must exclude image-gen step #2 and compaction step #3 + assert.equal(subAgent.speedSummary.sampleCount, 2); + assert.equal(subAgent.ttftSummary.sampleCount, 2); + assert.equal(subAgent.ttftSummary.avgSec, 1.5); + assert.equal(subAgent.context.compactionLimitTokens, 512000); + + // Account & session model breakdowns include Gemini 3.1 Flash Image with 0 unpriced calls + const imgBreakdown = p.modelBreakdown.find((m) => m.shortName === 'flash-3.1-img'); + assert.ok(imgBreakdown); + assert.equal(imgBreakdown.label, 'Gemini 3.1 Flash Image'); + assert.equal(imgBreakdown.calls, 1); + assert.equal(imgBreakdown.outputTokens, 1120); + assert.equal(imgBreakdown.unpricedCalls, 0); +}); diff --git a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs index d37a5e1..be994eb 100644 --- a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs +++ b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs @@ -6,7 +6,12 @@ import { promisify } from 'node:util'; import { mkdtempSync, mkdirSync, rmSync, truncateSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { computeSqliteWalSig, readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs'; +import { + computeSqliteWalSig, + readLocalImageDimensionsFromUri, + readLocalSqliteTrajectory, +} from '../backend/cli-sqlite-reader.mjs'; +import { extractModelSteps } from '../trajectory-metrics.mjs'; import { backendHarness } from './backend-harness.mjs'; import { i18nStore } from '../src/i18n/index.js'; import { @@ -961,3 +966,122 @@ test('legacy pre-PR#38 empty-WAL sqlite cache signatures migrate in-place withou assert.ok(out.memSig.endsWith('|0:0'), `in-memory signature normalized to |0:0: ${out.memSig}`); assert.ok(out.diskSig.endsWith('|0:0'), `persisted signature normalized to |0:0: ${out.diskSig}`); }); + +test('readLocalImageDimensionsFromUri and readLocalSqliteTrajectory decode PNG/JPEG/WebP headers and step_type 132 GenerateImage protobuf (140.2.6)', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tempDir = mkdtempSync(join(tmpdir(), 'agy-imggen-sqlite-')); + t.after(() => { + try { + rmSync(tempDir, { recursive: true, force: true }); + } catch { + // ignore Windows WAL cleanup lock + } + }); + + // 1. Minimal valid PNG header (1200x896) + const pngPath = join(tempDir, 'cat_1k.png'); + const pngBuf = Buffer.alloc(32); + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(pngBuf, 0); + pngBuf.writeUInt32BE(13, 8); + pngBuf.write('IHDR', 12, 'ascii'); + pngBuf.writeUInt32BE(1200, 16); + pngBuf.writeUInt32BE(896, 20); + writeFileSync(pngPath, pngBuf); + + // 2. Minimal valid JPEG SOF2 header (2048x1536) after APP0 segment + const jpgPath = join(tempDir, 'scene_2k.jpg'); + const jpgBuf = Buffer.from([ + 0xff, 0xd8, // SOI + 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, // APP0 (len 4) + 0xff, 0xc2, 0x00, 0x0b, 0x08, 0x06, 0x00, 0x08, 0x00, 0x01, 0x01, 0x11, 0x00, // SOF2: height=1536 (0x0600), width=2048 (0x0800) + 0xff, 0xd9, + ]); + writeFileSync(jpgPath, jpgBuf); + + // 3. Minimal valid WebP VP8X header (4096x3072 -> minus-one LE24: 4095=0x000fff, 3071=0x000bff) + const webpPath = join(tempDir, 'poster_4k.webp'); + const webpBuf = Buffer.alloc(30); + webpBuf.write('RIFF', 0, 'ascii'); + webpBuf.writeUInt32LE(22, 4); + webpBuf.write('WEBP', 8, 'ascii'); + webpBuf.write('VP8X', 12, 'ascii'); + webpBuf.writeUInt32LE(10, 16); + webpBuf[24] = 0xff; + webpBuf[25] = 0x0f; + webpBuf[26] = 0x00; + webpBuf[27] = 0xff; + webpBuf[28] = 0x0b; + webpBuf[29] = 0x00; + writeFileSync(webpPath, webpBuf); + + const toFileUri = (p) => `file:///${p.replace(/\\/g, '/').replace(/^\/+/, '')}`; + assert.deepEqual(readLocalImageDimensionsFromUri(toFileUri(pngPath)), { width: 1200, height: 896 }); + assert.deepEqual(readLocalImageDimensionsFromUri(toFileUri(jpgPath)), { width: 2048, height: 1536 }); + assert.deepEqual(readLocalImageDimensionsFromUri(toFileUri(webpPath)), { width: 4096, height: 3072 }); + + // 4. SQLite trajectory with step_type=132 (GENERIC tool step, toolCall.name='generate_image', payload 140.2.6) + const cid = 'd369e740-1f52-4f06-90a3-2f88bc623e2e'; + const dbPath = join(tempDir, `${cid}.db`); + const db = new DatabaseSync(dbPath); + db.exec(` + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid); + + const baseSec = Math.floor(Date.parse('2026-11-24T01:50:21Z') / 1000); + const toolCallBytes = Buffer.concat([ + encodeFieldBytes(1, 'call_img_1'), + encodeFieldBytes(2, 'generate_image'), + encodeFieldBytes(3, JSON.stringify({ Prompt: '2K mountain sunrise', AspectRatio: '4:3' })), + ]); + const metaBytes = Buffer.concat([ + encodeFieldBytes(1, encodeTimestamp(baseSec, 217_000_000)), // createdAt + encodeFieldBytes(4, toolCallBytes), // toolCall + encodeFieldBytes(7, encodeTimestamp(baseSec, 337_000_000)), // finishedGeneratingAt (0.12s!) + encodeFieldBytes(8, encodeTimestamp(baseSec + 63, 127_000_000)), // completedAt (~62.785s!) + encodeFieldBytes(20, Buffer.concat([encodeFieldVarint(2, 2), encodeFieldBytes(4, cid)])), + encodeFieldBytes(32, encodeTimestamp(baseSec, 342_000_000)), // startedAt + ]); + + const genImgProto = Buffer.concat([ + encodeFieldBytes(1, '2K mountain sunrise'), + encodeFieldBytes(3, '4:3'), + encodeFieldBytes(4, toFileUri(jpgPath)), + encodeFieldVarint(5, jpgBuf.length), + encodeFieldBytes(6, 'gemini-3.1-flash-image'), + encodeFieldBytes(8, 'scene_2k'), + ]); + const anyProto = Buffer.concat([ + encodeFieldBytes(1, 'type.googleapis.com/exa.cortex.core.tools.GenerateImage'), + encodeFieldBytes(2, genImgProto), + ]); + const stepPayload140 = encodeFieldBytes(140, encodeFieldBytes(2, encodeFieldBytes(6, anyProto))); + + db.prepare('INSERT INTO steps VALUES (2, 132, 3, ?, ?)').run(metaBytes, stepPayload140); + db.close(); + + const decoded = readLocalSqliteTrajectory(dbPath, { cascadeId: cid }); + assert.ok(decoded); + assert.equal(decoded.steps.length, 1); + assert.equal(decoded.steps[0].type, 'CORTEX_STEP_TYPE_GENERATE_IMAGE'); + assert.equal(decoded.steps[0].generateImage.modelName, 'gemini-3.1-flash-image'); + assert.equal(decoded.steps[0].generateImage.width, 2048); + assert.equal(decoded.steps[0].generateImage.height, 1536); + + // Extract model steps -> 2048x1536 hits 2K tier -> 1680 output tokens and 62.785s duration! + const modelSteps = extractModelSteps(decoded.steps, decoded.generatorMetadata); + assert.equal(modelSteps.length, 1); + assert.equal(modelSteps[0].isImageGenStep, true); + assert.equal(modelSteps[0].modelKey, 'gemini-3.1-flash-image'); + assert.equal(modelSteps[0].outputTokens, 1680); + assert.equal(modelSteps[0].ttftSec, null); + assert.ok(Math.abs(modelSteps[0].totalDurationSec - 62.785) < 0.01); +}); diff --git a/sidecars/panel/trajectory-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs index f921549..0f42b96 100644 --- a/sidecars/panel/trajectory-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -881,6 +881,113 @@ function buildStepAnomalyRecord(step, meta, chat, pendingErrorSteps = []) { * @param {Array} [generatorMetadata=[]] 轨迹级生成器元数据列表 * @returns {Array} 标准化并完成压缩步骤模型推断的步骤指标列表 */ +const IMAGE_REF_INPUT_TOKENS = 560; + +function isGenerateImageStep(step) { + if (!step || typeof step !== 'object') return false; + if (step.generateImage && typeof step.generateImage === 'object') return true; + const t = String(step.type || '').trim().toUpperCase(); + if (t === 'CORTEX_STEP_TYPE_GENERATE_IMAGE' || t === 'GENERATE_IMAGE') return true; + const toolName = String(step?.metadata?.toolCall?.name || '') + .trim() + .replace(/^default_api:/i, '') + .toLowerCase(); + return toolName === 'generate_image'; +} + +function estimatePromptTextTokens(text) { + const s = String(text || '').trim(); + if (!s) return 0; + let asciiChars = 0; + let nonAsciiChars = 0; + for (let i = 0; i < s.length; i++) { + if (s.charCodeAt(i) <= 0x7f) asciiChars += 1; + else nonAsciiChars += 1; + } + return Math.max(1, Math.round(asciiChars * 0.25 + nonAsciiChars * 0.6)); +} + +function resolveImageGenResolutionTier(gi = {}, args = {}) { + const w = Number(gi?.width || gi?.imageDimensions?.width) || 0; + const h = Number(gi?.height || gi?.imageDimensions?.height) || 0; + const maxDim = Math.max(w, h); + const pixels = w > 0 && h > 0 ? w * h : 0; + if (maxDim > 0) { + if (maxDim <= 640 && (pixels === 0 || pixels <= 360_000)) return '0.5K'; + if (maxDim <= 1536 && (pixels === 0 || pixels <= 1_650_000)) return '1K'; + if (maxDim <= 2816 && (pixels === 0 || pixels <= 6_000_000)) return '2K'; + return '4K'; + } + const rawSize = String(gi?.imageSize || args?.ImageSize || args?.imageSize || '') + .trim() + .toUpperCase(); + if (rawSize === '0.5K' || rawSize === '512' || rawSize === '512PX') return '0.5K'; + if (rawSize === '2K' || rawSize === '2048' || rawSize === '2048PX') return '2K'; + if (rawSize === '4K' || rawSize === '4096' || rawSize === '4096PX') return '4K'; + return '1K'; +} + +function resolveImageGenOutputTokens(modelId, resTier) { + const m = String(modelId || '').toLowerCase(); + if (/2[._-]5[-_]flash[-_]image/.test(m)) { + return 1290; + } + if (/3(?:[._-]\d+)?[-_]pro[-_]image/.test(m)) { + return resTier === '4K' ? 2000 : 1120; + } + if (resTier === '0.5K') return 747; + if (resTier === '2K') return 1680; + if (resTier === '4K') return 2520; + return 1120; +} + +/** + * 按 Google AI Studio 官方图片生成计费口径估算 `generate_image` 步骤的输入及输出等价 Token。 + * + * @param {object} step + * @param {boolean} hasGeneratedResult + * @returns {{ modelName: string, inputTokens: number, outputTokens: number, aspectRatio: string, resolutionTier: string, imageName: string }} + */ +export function estimateImageGenStepUsage(step, hasGeneratedResult = true) { + const gi = step?.generateImage && typeof step.generateImage === 'object' ? step.generateImage : {}; + let args = {}; + const rawArgs = step?.metadata?.toolCall?.argumentsJson; + if (typeof rawArgs === 'string' && rawArgs.trim()) { + try { + const parsed = JSON.parse(rawArgs); + if (parsed && typeof parsed === 'object') args = parsed; + } catch { + // 忽略半流式未闭合参数 JSON + } + } else if (rawArgs && typeof rawArgs === 'object') { + args = rawArgs; + } + const modelName = + String(gi.modelName || gi.model || args?.Model || args?.model || '').trim() || + 'gemini-3.1-flash-image'; + const prompt = String(gi.prompt || args?.Prompt || args?.prompt || '').trim(); + const refImages = Array.isArray(args?.ImagePaths) + ? args.ImagePaths.length + : Array.isArray(args?.imagePaths) + ? args.imagePaths.length + : 0; + const inputTokens = estimatePromptTextTokens(prompt) + refImages * IMAGE_REF_INPUT_TOKENS; + const resolutionTier = resolveImageGenResolutionTier(gi, args); + const outputTokens = hasGeneratedResult + ? resolveImageGenOutputTokens(modelName, resolutionTier) + : 0; + const aspectRatio = String(gi.aspectRatio || args?.AspectRatio || args?.aspectRatio || '').trim(); + const imageName = String(gi.imageName || args?.ImageName || args?.imageName || '').trim(); + return { + modelName, + inputTokens, + outputTokens, + aspectRatio, + resolutionTier, + imageName, + }; +} + export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const genByStep = new Map(); const orchestratorExecModels = new Set(); @@ -1174,9 +1281,10 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { return; } - const m = s?.metadata; + const m = s?.metadata || {}; const u = m?.modelUsage || m?.retryInfos?.[0]?.usage; - if (!u) { + const isImageGen = !u && isGenerateImageStep(s); + if (!u && !isImageGen) { return; } const stepPendingErrors = pendingErrorSteps; @@ -1207,6 +1315,92 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { } const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index; + if (isImageGen) { + const isClearedImg = s.status === 'CORTEX_STEP_STATUS_CLEARED'; + const explicitlyIncompleteImg = Boolean( + s.status && s.status !== 'CORTEX_STEP_STATUS_DONE' && !isClearedImg + ); + const startIsoImg = m.startedAt || m.createdAt || null; + const startMsImg = parseIsoMs(m.createdAt || m.startedAt); + const measuredImgDuration = requestDuration( + startIsoImg, + isClearedImg ? null : m.completedAt + ); + const completeImg = !explicitlyIncompleteImg && measuredImgDuration !== null; + const hasGeneratedMedia = Boolean( + s?.generateImage?.generatedMedia?.uri || + (completeImg && + s.status !== 'CORTEX_STEP_STATUS_ERROR' && + s.status !== 'CORTEX_STEP_STATUS_CANCELED') + ); + const imgUsage = estimateImageGenStepUsage(s, hasGeneratedMedia); + const totalDurationSecImg = completeImg ? measuredImgDuration : null; + + let imgTimingReason = null; + if (s.status === 'CORTEX_STEP_STATUS_CANCELED') { + imgTimingReason = 'canceled'; + } else if (s.status === 'CORTEX_STEP_STATUS_ERROR') { + imgTimingReason = 'error'; + } else if (s.status === 'CORTEX_STEP_STATUS_INTERRUPTED') { + imgTimingReason = 'interrupted'; + } else if (!completeImg || !(totalDurationSecImg > 0)) { + imgTimingReason = 'incomplete_or_invalid_timing'; + } else if (!(imgUsage.outputTokens > 0)) { + imgTimingReason = 'invalid_output_tokens'; + } else if (totalDurationSecImg < MIN_SPEED_DURATION_SECONDS) { + imgTimingReason = 'short_timing'; + } + + const imgTokPerSec = + imgTimingReason === null ? imgUsage.outputTokens / totalDurationSecImg : null; + const anomalyRecImg = buildStepAnomalyRecord(s, m, null, stepPendingErrors); + + result.push({ + stepIndex, + isCompactionStep: false, + isImageGenStep: true, + modelKey: imgUsage.modelName, + modelSource: 'generateImage.modelName', + responseModel: imgUsage.modelName, + modelIdentityVersion: MODEL_IDENTITY_VERSION, + modelDisplayName: '', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + createdAt: m.createdAt || m.startedAt || null, + createdAtMs: Math.floor(startMsImg), + hasVisibleText: false, + hasToolCalls: false, + inputTokens: imgUsage.inputTokens, + cacheReadTokens: 0, + outputTokens: imgUsage.outputTokens, + thinkingTokens: 0, + responseTokens: imgUsage.outputTokens, + estimatedContextTokens: 0, + maxContextBudgetTokens: 0, + contextBreakdown: null, + measurementVersion: MEASUREMENT_VERSION, + isComplete: completeImg, + nativeTtftSec: null, + nativeStreamSec: null, + viewableDelaySec: elapsed(startMsImg, parseIsoMs(m.viewableAt)), + ttftSec: null, + ttftSource: 'unavailable', + thinkingDurationSec: null, + totalDurationSec: totalDurationSecImg, + totalTokPerSec: imgTokPerSec, + speedBasis: imgTokPerSec === null ? 'unavailable' : 'request_total', + speedSampleEligible: false, + speedReason: imgTimingReason || 'image_gen', + ...(anomalyRecImg + ? { anomaly: anomalyRecImg.anomaly, anomalySig: anomalyRecImg.anomalySig } + : {}), + turnIndex: activeTurnIndex, + isTurnStart: stepIsTurnStart, + ...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}), + ...(stepIsTurnStart && stepTurnPromptClean ? { turnPromptClean: stepTurnPromptClean } : {}), + ...(stepIsTurnStart ? { turnHasMedia: stepTurnHasMedia, turnMediaOnly: stepTurnMediaOnly } : {}), + }); + return; + } if (Array.isArray(m.generatorMetadata)) { for (const g of m.generatorMetadata) { collectOrchestratorExecModel(g?.plannerConfig); @@ -1490,6 +1684,7 @@ export function inferCompactionStepModels(steps) { const isExplicitDonor = (step) => Boolean( step && + !step.isImageGenStep && step.modelKey && step.modelKey !== 'unknown' && step.modelSource !== 'inferred_compaction' && @@ -1728,7 +1923,10 @@ export function speedMetric(step) { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec, - eligible: step.speedSampleEligible === true && !step.isCompactionStep, + eligible: + step.speedSampleEligible === true && + !step.isCompactionStep && + !step.isImageGenStep, reason: step.speedReason, }; } @@ -1755,7 +1953,7 @@ export function createSpeedAccumulator() { * @param {object} step 标准化步骤对象 */ export function accumulateSpeed(acc, step) { - if (step.isCompactionStep) { + if (step.isCompactionStep || step.isImageGenStep) { return; } const metric = speedMetric(step); @@ -1809,6 +2007,7 @@ export function summarizeTtft(steps) { .filter( (s) => !s.isCompactionStep && + !s.isImageGenStep && s.measurementVersion === MEASUREMENT_VERSION && s.isComplete && Number.isFinite(s.totalDurationSec) && @@ -2127,6 +2326,8 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { rawName = 'find_by_name'; } else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) { rawName = 'search_web'; + } else if (stepType.includes('GENERATE_IMAGE') || fallbackStep?.generateImage) { + rawName = 'generate_image'; } } @@ -2305,6 +2506,23 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { }; } + if (nameLower === 'generate_image') { + const imgName = + pickField(['ImageName', 'imageName']) || + String(fallbackStep?.generateImage?.imageName || '').trim(); + const ratio = + pickField(['AspectRatio', 'aspectRatio']) || + String(fallbackStep?.generateImage?.aspectRatio || '').trim(); + const detail = imgName && ratio ? `${imgName} (${ratio})` : imgName || ratio || ''; + return { + toolName: nameLower, + actionKey: 'generate_image', + isAskUser: false, + label: '生成图片', + detail, + }; + } + if (nameLower === 'invoke_subagent') { const subSpec = fallbackStep?.invokeSubagent?.subagents?.[0] || {}; const role = From 275955c37fe45323a2ec8f862a2988ec54e378fa Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 13:36:24 +0900 Subject: [PATCH 10/30] feat(panel): migrate trajectory cache to incremental SQLite ledger - Add short-connection WAL trajectory_store.sqlite (and remote ssh-*.sqlite) with transactional .json-to-.bak migration, O(delta) step UPSERTs, undo tail truncation, and ledger_epoch/write_seq cross-process sync - Split steps into string-interned compact accounting tuples (retaining anomaly and step account owners) and lazy detail_json with an explicit 24-session hot LRU and precomputed O(1) cold metadata flags - Archive deleted source conversations permanently across cache rebuilds and skip redundant 404 trajectory RPCs while un-archiving automatically if sources reappear --- sidecars/panel/backend/api-actions.mjs | 12 +- sidecars/panel/backend/config.mjs | 18 +- sidecars/panel/backend/endpoint-registry.mjs | 35 +- sidecars/panel/backend/local-scanner.mjs | 140 ++- sidecars/panel/backend/telemetry-builder.mjs | 33 +- .../panel/backend/trajectory-cache-store.mjs | 440 +++++++- .../backend/trajectory-sqlite-ledger.mjs | 954 ++++++++++++++++++ sidecars/panel/test/backend-harness.mjs | 3 +- .../sqlite-hybrid-and-side-question.test.mjs | 14 +- .../test/sqlite-trajectory-ledger.test.mjs | 511 ++++++++++ 10 files changed, 2104 insertions(+), 56 deletions(-) create mode 100644 sidecars/panel/backend/trajectory-sqlite-ledger.mjs create mode 100644 sidecars/panel/test/sqlite-trajectory-ledger.test.mjs diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index bd7c7f5..35b0c59 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -18,7 +18,10 @@ import { } from './endpoint-registry.mjs'; import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs'; import { revealLocalExportFile, writeLocalExportFile } from './file-exporter.mjs'; -import { clearScannerRuntimeMemos } from './local-scanner.mjs'; +import { + clearScannerRuntimeMemos, + collectAuthoritativeLiveCascadeIds, +} from './local-scanner.mjs'; import { SETTINGS_FILE, clearRuntimeCaches, @@ -556,9 +559,12 @@ export function executeRebuildCacheAction(data = undefined, opts = {}) { if (!epCtx.ok) { return buildEndpointErrorResponse(epCtx); } + const liveCascadeIds = collectAuthoritativeLiveCascadeIds( + epCtx.isRemote ? epCtx.endpoint : null + ); const ok = epCtx.isRemote - ? clearRemoteEndpointCaches(epCtx.id) - : clearRuntimeCaches(); + ? clearRemoteEndpointCaches(epCtx.id, { liveCascadeIds }) + : clearRuntimeCaches({ liveCascadeIds }); if (!ok) { return { ok: false, diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 9aee305..442074a 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -165,6 +165,7 @@ function resolveDefaultDataDir() { export const DATA_DIR = resolveDefaultDataDir(); export const SETTINGS_FILE = join(DATA_DIR, 'settings.json'); export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json'); +export const TRAJECTORY_DB_FILE = join(DATA_DIR, 'trajectory_store.sqlite'); export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json'); export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json'); export const QUOTA_RESERVATION_STATE_FILE = join(DATA_DIR, 'quota_reservation_state.json'); @@ -419,6 +420,7 @@ export function computeRuntimeCodeVersion(options = {}) { */ const localTrajectoryCacheStore = createTrajectoryCacheStore({ cacheFilePath: CACHE_FILE, + sqliteFilePath: TRAJECTORY_DB_FILE, loadJsonFn: loadJson, writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj), shouldBypassThrottleFn: (allowThrottleInTest) => @@ -426,6 +428,10 @@ const localTrajectoryCacheStore = createTrajectoryCacheStore({ registerExitHook: true, }); +export function getLocalTrajectoryCacheStore() { + return localTrajectoryCacheStore; +} + export function getCachedTrajectory(cascadeId) { return localTrajectoryCacheStore.getCachedTrajectory(cascadeId); } @@ -434,6 +440,14 @@ export function getCachedTrajectoryEntryByLower(cascadeId) { return localTrajectoryCacheStore.getCachedTrajectoryEntryByLower(cascadeId); } +export function getHydratedTrajectory(cascadeId) { + return localTrajectoryCacheStore.getHydratedTrajectory(cascadeId); +} + +export function getHydratedTrajectoryEntryByLower(cascadeId) { + return localTrajectoryCacheStore.getHydratedTrajectoryEntryByLower(cascadeId); +} + export function listCachedTrajectoryEntries() { return localTrajectoryCacheStore.listCachedTrajectoryEntries(); } @@ -518,8 +532,8 @@ export const pluginUpdateState = { * * @returns {boolean} 是否成功写回空白缓存文件 */ -export function clearRuntimeCaches() { - if (!localTrajectoryCacheStore.clearCache()) return false; +export function clearRuntimeCaches(options = {}) { + if (!localTrajectoryCacheStore.clearCache(options)) return false; externalDeepStatsMemo.sig = ''; externalDeepStatsMemo.convos.clear(); localSummaryMemo.sig = ''; diff --git a/sidecars/panel/backend/endpoint-registry.mjs b/sidecars/panel/backend/endpoint-registry.mjs index d43a24b..fd7e0a0 100644 --- a/sidecars/panel/backend/endpoint-registry.mjs +++ b/sidecars/panel/backend/endpoint-registry.mjs @@ -18,6 +18,8 @@ import { flushTrajectoryCacheNow, getCachedTrajectory, getCachedTrajectoryEntryByLower, + getHydratedTrajectory, + getHydratedTrajectoryEntryByLower, hasPendingTrajectoryCacheSave, listCachedTrajectoryEntries, loadJson, @@ -108,8 +110,8 @@ export function buildRemoteEndpointIdentity({ origin = '', hostLabel = '', stabl }; } -function buildRemoteCacheFilePath(stableHostKey) { - if (!stableHostKey) return ''; +function buildRemoteCacheFilePaths(stableHostKey) { + if (!stableHostKey) return { cacheFilePath: '', sqliteFilePath: '' }; const safePrefix = stableHostKey .toLowerCase() .replace(/[^a-z0-9._-]+/g, '_') @@ -117,7 +119,10 @@ function buildRemoteCacheFilePath(stableHostKey) { .slice(0, 32) || 'ssh'; const hash = createHash('sha256').update(stableHostKey.toLowerCase()).digest('hex').slice(0, 12); // 前缀加上 `ssh-` 可彻底规避 Windows 保留文件名(CON/NUL/PRN/AUX/COM1 等) - return join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`); + return { + cacheFilePath: join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`), + sqliteFilePath: join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.sqlite`), + }; } function createRemoteQuotaCache() { @@ -131,9 +136,10 @@ function createRemoteQuotaCache() { }; } -function createRemoteEndpointStore(cacheFilePath) { +function createRemoteEndpointStore(cacheFilePath, sqliteFilePath = '') { return createTrajectoryCacheStore({ cacheFilePath, + sqliteFilePath, loadJsonFn: loadJson, shouldBypassThrottleFn: (allowThrottleInTest) => lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest, @@ -175,9 +181,9 @@ export function registerRemoteEndpoint(info = {}) { let entry = remoteEndpointRegistry.get(identity.id); if (!entry) { - const cacheFilePath = identity.hasStableHostKey - ? buildRemoteCacheFilePath(identity.stableHostKey) - : ''; + const { cacheFilePath, sqliteFilePath } = identity.hasStableHostKey + ? buildRemoteCacheFilePaths(identity.stableHostKey) + : { cacheFilePath: '', sqliteFilePath: '' }; entry = { id: identity.id, instanceId: ++nextEndpointInstanceId, @@ -192,11 +198,12 @@ export function registerRemoteEndpoint(info = {}) { lastSeenMs: nowMs, preferTier2UntilMs: 0, inFlightCount: 0, - store: createRemoteEndpointStore(cacheFilePath), + store: createRemoteEndpointStore(cacheFilePath, sqliteFilePath), quotaSummaryCache: createRemoteQuotaCache(), contextModelCatalog: null, failedFetchCooldownMap: new Map(), liveActivityMemo: new Map(), + lastKnownLiveCascadeIds: null, }; remoteEndpointRegistry.set(identity.id, entry); } else { @@ -315,6 +322,8 @@ export function getEndpointCacheStore(endpointOrId = null) { endpointId: LOCAL_ENDPOINT_ID, getCachedTrajectory, getCachedTrajectoryEntryByLower, + getHydratedTrajectory, + getHydratedTrajectoryEntryByLower, listCachedTrajectoryEntries, setCachedTrajectory, removeCachedTrajectory, @@ -344,15 +353,21 @@ export function getEndpointQuotaCache(endpointOrId = null) { * 清空目标远端端点的内存与持久化缓存(包含配额、模型目录、扫描冷却表与实时活动缓存)。 * * @param {string} endpointId + * @param {{ liveCascadeIds?: Iterable | null }} [options] * @returns {boolean} */ -export function clearRemoteEndpointCaches(endpointId) { +export function clearRemoteEndpointCaches(endpointId, options = {}) { const ep = getRegisteredRemoteEndpoint(endpointId); if (!ep) return false; - const ok = ep.store.clearCache(); + const liveCascadeIds = + options && Object.prototype.hasOwnProperty.call(options, 'liveCascadeIds') + ? options.liveCascadeIds + : ep.lastKnownLiveCascadeIds; + const ok = ep.store.clearCache({ liveCascadeIds }); if (!ok) return false; ep.failedFetchCooldownMap.clear(); ep.liveActivityMemo.clear(); + ep.lastKnownLiveCascadeIds = null; ep.contextModelCatalog = null; ep.quotaSummaryCache.ts = 0; ep.quotaSummaryCache.lastAttemptTs = 0; diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index b674d33..1cea98c 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -31,6 +31,7 @@ import { DEEP_STATS_CACHE_CANDIDATES, externalDeepStatsMemo, loadJson, + localSummaryMemo, } from './config.mjs'; import { getEndpointCacheStore, getRegisteredRemoteEndpoint } from './endpoint-registry.mjs'; import { @@ -40,6 +41,7 @@ import { readLocalImageDimensionsFromUri, readLocalSqliteTrajectory, readLocalSummaryIndex, + readLocalSummarySnapshot, } from './cli-sqlite-reader.mjs'; import { callLsRpc } from './ls-rpc.mjs'; import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs'; @@ -551,6 +553,50 @@ const failedFetchCooldownMap = new Map(); const liveActivityMemo = new Map(); const transcriptTailMemo = new Map(); const swarmManifestMemo = new Map(); +let lastKnownLocalLiveCascadeIds = null; + +/** + * 收集目标端点当前仍存活的原始会话源 ID 集合(供「重建缓存」区分“存活待重扫会话”和“原对话已被删除需永久归档留存会话”)。 + * + * @param {object|null} [endpoint=null] + * @returns {Set | null} + */ +export function collectAuthoritativeLiveCascadeIds(endpoint = null) { + if (endpoint && endpoint.isRemote) { + return endpoint.lastKnownLiveCascadeIds instanceof Set + ? new Set(endpoint.lastKnownLiveCascadeIds) + : null; + } + const convDirs = + Array.isArray(CONVERSATION_DIRS) && CONVERSATION_DIRS.length > 0 + ? CONVERSATION_DIRS + : [CONVERSATIONS_DIR]; + const hasAnyLocalConvDir = convDirs.some((d) => Boolean(d && existsSync(d))); + localSummaryMemo.sig = ''; + localSummaryMemo.byRootsKey.clear(); + brainDirListingMemo.clear(); + knownExistingTranscriptPaths.clear(); + const diskConvMap = discoverLocalConversationFiles(); + const localSnap = readLocalSummarySnapshot(); + if (!hasAnyLocalConvDir && diskConvMap.size === 0 && !localSnap.available) { + return lastKnownLocalLiveCascadeIds instanceof Set + ? new Set(lastKnownLocalLiveCascadeIds) + : null; + } + const liveIds = new Set(); + for (const id of diskConvMap.keys()) liveIds.add(String(id).toLowerCase()); + for (const id of localSnap.byId.keys()) liveIds.add(String(id).toLowerCase()); + const localStore = getEndpointCacheStore(null); + for (const [rawKey, entry] of localStore.listCachedTrajectoryEntries()) { + const lower = String(rawKey || '').toLowerCase(); + if (!liveIds.has(lower)) continue; + for (const ref of entry?.subagentRefs || []) { + const refLower = String(ref?.cascadeId || '').trim().toLowerCase(); + if (refLower) liveIds.add(refLower); + } + } + return liveIds; +} export function clearScannerRuntimeMemos(endpointId = null) { if (endpointId && endpointId !== 'local') { @@ -558,6 +604,7 @@ export function clearScannerRuntimeMemos(endpointId = null) { if (ep) { ep.failedFetchCooldownMap.clear(); ep.liveActivityMemo.clear(); + ep.lastKnownLiveCascadeIds = null; } return; } @@ -568,6 +615,7 @@ export function clearScannerRuntimeMemos(endpointId = null) { brainDirListingMemo.clear(); knownExistingTranscriptPaths.clear(); knownBrainCascadeSet = null; + lastKnownLocalLiveCascadeIds = null; } function findSwarmMembersPath(cascadeId) { @@ -1700,6 +1748,10 @@ export async function enumerateAndSyncConversations({ const isRemote = Boolean(endpoint && endpoint.isRemote); const cacheStore = getEndpointCacheStore(endpoint); const getEntry = cacheStore.getCachedTrajectory; + const getHydratedEntry = + typeof cacheStore.getHydratedTrajectory === 'function' + ? cacheStore.getHydratedTrajectory + : getEntry; const setEntry = cacheStore.setCachedTrajectory; const removeEntry = cacheStore.removeCachedTrajectory; const listEntries = cacheStore.listCachedTrajectoryEntries; @@ -1828,6 +1880,29 @@ export async function enumerateAndSyncConversations({ const localSummaryByLower = isRemote ? new Map() : readLocalSummaryIndex(); const sqliteAvailable = isRemote ? false : hasBuiltinNodeSqlite(); + const observedLiveIds = new Set(); + for (const k of summariesByLower.keys()) observedLiveIds.add(k); + for (const k of localSummaryByLower.keys()) observedLiveIds.add(k); + for (const k of diskConvMap.keys()) observedLiveIds.add(k); + for (const [rawKey, entry] of listEntries()) { + const lower = String(rawKey || '').toLowerCase(); + if (!observedLiveIds.has(lower)) continue; + for (const ref of entry?.subagentRefs || []) { + const refCid = String(ref?.cascadeId || '').trim().toLowerCase(); + if (refCid) observedLiveIds.add(refCid); + } + } + const hasAuthoritativeSourceSnapshot = isRemote + ? summariesByLower.size > 0 + : summariesByLower.size > 0 || localSummaryByLower.size > 0 || diskConvMap.size > 0; + if (hasAuthoritativeSourceSnapshot) { + if (isRemote && endpoint) { + endpoint.lastKnownLiveCascadeIds = observedLiveIds; + } else if (!isRemote) { + lastKnownLocalLiveCascadeIds = observedLiveIds; + } + } + const normalizedPollAccount = normalizeOwnerAccount(currentAccountName); const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000; const reqLower = String(requestedConvId || '').trim().toLowerCase(); const rawConversations = []; @@ -2082,6 +2157,9 @@ export async function enumerateAndSyncConversations({ * 检查缓存条目是否缺少最新分解字段(含 10 通道上下文细分字段 `toolResultsTokens`)。 */ function hasMissingStepFields(cached) { + if (cached?._stepFlags) { + return Boolean(cached._stepFlags.hasMissingStepFields); + } const steps = cached?.steps || []; const lastCachedStep = steps[steps.length - 1]; if (!lastCachedStep) return false; @@ -2149,7 +2227,7 @@ export async function enumerateAndSyncConversations({ const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower); - const prev = getEntry(conv.cascadeId); + const prev = getHydratedEntry(conv.cascadeId); let partialTailSteps = []; let hasTailStepInfo = false; try { @@ -2222,6 +2300,15 @@ export async function enumerateAndSyncConversations({ } } const steps = extractModelSteps(rawSteps, generatorMeta); + if ( + steps.length === 0 && + (prev?.steps?.length || 0) > 0 && + !prev.offlineTranscriptFallback && + !conv.inSummaries && + !conv.dbPath + ) { + throw new Error('Empty orphan trajectory; retaining cached usage'); + } const nextLast = steps[steps.length - 1]; // 提取轨迹内携带的子代理归属元数据、旁路提问父归属与派生的子代理引用列表 @@ -2603,6 +2690,9 @@ export async function enumerateAndSyncConversations({ (c) => c.cascadeId.toLowerCase() === contextTelemetryCascadeId )?.rootConversationId || contextTelemetryCascadeId; function hasMissingTurnRailFields(cached) { + if (cached?._stepFlags) { + return Boolean(cached._stepFlags.hasMissingTurnRailFields); + } const steps = cached?.steps || []; const lastCachedStep = steps[steps.length - 1]; if (!lastCachedStep) return false; @@ -2613,6 +2703,9 @@ export async function enumerateAndSyncConversations({ if (grpVer >= 3) return false; const steps = cached?.steps || []; if (grpVer === 2) { + if (cached?._stepFlags) { + return steps.length > 0 && !cached._stepFlags.hasAnyContextBreakdown; + } return steps.length > 0 && !steps.some((st) => Boolean(st?.contextBreakdown)); } if (steps.some((st) => st?.isCompactionStep)) { @@ -2640,6 +2733,9 @@ export async function enumerateAndSyncConversations({ function needsWakeupTurnRefresh(conv, cached) { if (!conv?.isSubagent || conv.isSideQuestion || cached?.wakeupTurnTelemetry) return false; + if (cached?._stepFlags) { + return (cached.steps?.length || 0) > 0 && !cached._stepFlags.hasAnyTurnIndex; + } const steps = cached?.steps || []; return steps.length > 0 && steps.every((s) => !s?.turnIndex); } @@ -2649,9 +2745,44 @@ export async function enumerateAndSyncConversations({ const sig = buildConvSig(conv); if (isFetchInCooldown(conv, sig)) return false; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; - const cached = getEntry(conv.cascadeId); + let cached = getEntry(conv.cascadeId); if (!cached || conv.needsInitialLoad) return true; const lowerCid = conv.cascadeId.toLowerCase(); + const hasLiveBacking = Boolean( + conv.inSummaries || + conv.dbPath || + (diskConvMap.get(lowerCid)?.length || 0) > 0 || + observedLiveIds.has(lowerCid) + ); + if (cached.archived && hasLiveBacking) { + const unarchived = { ...cached }; + delete unarchived.archived; + setEntry(conv.cascadeId, unarchived); + cached = getEntry(conv.cascadeId) || unarchived; + cacheDirty = true; + } else if ( + !hasLiveBacking && + (cached.steps?.length || 0) > 0 && + !cached.offlineTranscriptFallback + ) { + if (cached.archived) { + return false; + } + if (hasAuthoritativeSourceSnapshot) { + const cachedOwner = normalizeOwnerAccount(cached.accountName); + const sameOrUnknownAccount = + !normalizedPollAccount || !cachedOwner || cachedOwner === normalizedPollAccount; + const parentRefLower = String( + conv.rootConversationId || conv.parentConversationId || '' + ).toLowerCase(); + const linkedToLiveParent = Boolean(parentRefLower && observedLiveIds.has(parentRefLower)); + if (sameOrUnknownAccount && !linkedToLiveParent) { + setEntry(conv.cascadeId, { ...cached, archived: true }); + cacheDirty = true; + return false; + } + } + } const isSelectedFamily = lowerCid === contextTelemetryCascadeId || lowerCid === selectedRootId || @@ -2748,7 +2879,10 @@ export async function enumerateAndSyncConversations({ } } // 保留已有效的历史测速,按批补读需要确认原始状态与生成结束时间的旧步骤。 - if (!cached.speedClearedTelemetry && readStepFieldChecks(cached.steps).hasIncompleteTiming) { + const hasIncompleteTiming = cached?._stepFlags + ? Boolean(cached._stepFlags.hasIncompleteTiming) + : readStepFieldChecks(cached.steps).hasIncompleteTiming; + if (!cached.speedClearedTelemetry && hasIncompleteTiming) { if (conv.cascadeId.toLowerCase() === selectedRootId || conv.rootConversationId === selectedRootId) return true; if (remainingTimingRefreshes > 0) { remainingTimingRefreshes -= 1; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index f2cf633..d1d0fa6 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -93,9 +93,16 @@ function roundSessionCost(val) { return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2); } -function findTrajectoryCacheEntry(cascadeId, cacheStore = null) { +function findTrajectoryCacheEntry(cascadeId, cacheStore = null, { hydrate = false } = {}) { if (!cascadeId) return null; const store = cacheStore || getEndpointCacheStore(null); + if (hydrate && typeof store.getHydratedTrajectoryEntryByLower === 'function') { + return store.getHydratedTrajectoryEntryByLower(cascadeId)?.entry || null; + } + if (hydrate && typeof store.getHydratedTrajectory === 'function') { + const hit = store.getHydratedTrajectory(cascadeId); + if (hit) return hit; + } if (typeof store.getCachedTrajectoryEntryByLower === 'function') { return store.getCachedTrajectoryEntryByLower(cascadeId)?.entry || null; } @@ -149,6 +156,16 @@ function buildKnownUpstreamModelMap(contextLimits, cacheStore = null) { const facts = readTrajectoryModelFacts(entry.steps); for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model); if (entry.subagentSpec) continue; + if (Array.isArray(entry._stepFlags?.modelLimits) && entry._stepFlags.modelLimits.length > 0) { + for (const [key, tokens, at] of entry._stepFlags.modelLimits) { + if (!key || !(tokens > 0)) continue; + const previous = contextLimits.get(key); + if (!previous || at > previous.at) { + contextLimits.set(key, { tokens, at }); + } + } + continue; + } if (facts.limits) { for (const [key, limit] of facts.limits) { const previous = contextLimits.get(key); @@ -1054,7 +1071,7 @@ function buildActiveConversationAssembly({ const cacheKey = `${epKey}::${String(activeCascadeId || '__empty__').toLowerCase()}`; const subEntries = subagentSummaries.map((subSum) => - findTrajectoryCacheEntry(subSum.cascadeId, cacheStore) + findTrajectoryCacheEntry(subSum.cascadeId, cacheStore, { hydrate: true }) ); const subRawStepsList = subEntries.map((entry) => entry?.steps || []); const combinedFallbackKeys = new Set(); @@ -1768,7 +1785,7 @@ export async function buildTelemetryPayloadInternal( // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 const reportedContextLimits = new Map(); const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, cacheStore); - const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore); + const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore, { hydrate: true }); const modelInputs = { catalogRevision: pricingCatalogRevision, phaseEpoch: getPricingPhaseEpoch(), @@ -1972,7 +1989,7 @@ export async function buildTelemetryPayloadInternal( if (cidKey && quickStatsMemo.has(cidKey)) { return quickStatsMemo.get(cidKey); } - const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore); + const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore, { hydrate: true }); const rootSteps = rootEntry?.steps || []; const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : []; @@ -2478,7 +2495,9 @@ function resolveValidFastSnapshot(endpoint = null) { } function entryNeedsLazyTelemetryUpgrade(entry) { - if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) return false; + if (!entry || entry.archived || !Array.isArray(entry.steps) || entry.steps.length === 0) { + return false; + } const grpVer = Number(entry.contextGroupsTelemetry || 0); const needsUndoCtxUpgrade = grpVer < 2 || (grpVer === 2 && !entry.steps.some((st) => Boolean(st?.contextBreakdown))); @@ -2508,7 +2527,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { if (!activeConvSummary?.cascadeId) return null; const activeCascadeId = activeConvSummary.cascadeId; - const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore); + const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore, { hydrate: true }); if (!activeEntry) return null; const subagentSummaries = Array.isArray(activeConvSummary.subagents) @@ -2523,7 +2542,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { needsBackgroundSync = true; break; } - const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore); + const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore, { hydrate: true }); if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) { needsBackgroundSync = true; break; diff --git a/sidecars/panel/backend/trajectory-cache-store.mjs b/sidecars/panel/backend/trajectory-cache-store.mjs index afd843f..e5d5ec3 100644 --- a/sidecars/panel/backend/trajectory-cache-store.mjs +++ b/sidecars/panel/backend/trajectory-cache-store.mjs @@ -1,15 +1,64 @@ /** * @fileoverview Shared lazy-loaded, $O(1)$ case-insensitive, 30s-throttled trajectory cache store * reused by both the local sidecar (`config.mjs`) and remote SSH endpoints (`endpoint-registry.mjs`). + * + * Supports dual persistence backends behind a 100% compatible API: + * - SQLite incremental ledger (`trajectory-sqlite-ledger.mjs`) with 24-session hot `detail` LRU + * and permanent archived ledger retention when conversations are deleted in Antigravity; + * - JSON/in-memory fallback for environments without `node:sqlite` or VM unit-test sandboxes. */ import { mkdirSync } from 'node:fs'; import { dirname } from 'node:path'; import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs'; import { isPlainObject } from './http-helpers.mjs'; +import { hasBuiltinNodeSqlite } from './sqlite-client.mjs'; import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs'; +import { + computePrecomputedStepFlags, + createTrajectorySqliteLedger, +} from './trajectory-sqlite-ledger.mjs'; export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000; +export const DEFAULT_HOT_SESSION_LRU_LIMIT = 24; +const TCS_WAL_SYNC_MIN_INTERVAL_MS = 250; + +function tcsMarkColdSlimSteps(steps) { + if (Array.isArray(steps)) { + Object.defineProperty(steps, '_isColdSlimSteps', { + value: true, + enumerable: false, + configurable: true, + writable: true, + }); + } + return steps; +} + +function tcsIsColdEntry(entry) { + return Boolean(entry && (entry._coldSteps === true || entry.steps?._isColdSlimSteps === true)); +} + +function tcsDefineHiddenProp(obj, key, value) { + if (!obj || typeof obj !== 'object') return; + Object.defineProperty(obj, key, { + value, + enumerable: false, + configurable: true, + writable: true, + }); +} + +function tcsAttachEntryStepFlags(entry, flags) { + if (!entry || typeof entry !== 'object') return; + const resolved = flags || entry._stepFlags || computePrecomputedStepFlags(entry.steps); + tcsDefineHiddenProp(entry, '_stepFlags', resolved); +} + +function tcsIsVirtualSandboxPath(filePath) { + const norm = String(filePath || '').replace(/\\/g, '/'); + return norm.startsWith('/test/') || norm.startsWith('/test-home/'); +} /** * Normalizes and repairs raw trajectory cache JSON into an unprototyped map. @@ -42,7 +91,9 @@ export function hydrateTrajectoryCacheObject(rawLoaded) { break; } } - cacheObj[id] = { ...entry, steps: finalSteps }; + const nextEntry = { ...entry, steps: finalSteps }; + tcsAttachEntryStepFlags(nextEntry, computePrecomputedStepFlags(finalSteps)); + cacheObj[id] = nextEntry; } } return { cacheObj, migrated }; @@ -50,26 +101,59 @@ export function hydrateTrajectoryCacheObject(rawLoaded) { /** * Creates an isolated trajectory cache store with lazy first-read hydration, - * case-insensitive canonical key index, and 30-second throttled disk flushes. + * case-insensitive canonical key index, 24-session hot detail LRU, and 30-second throttled disk flushes. * * @param {{ - * cacheFilePath: string, - * loadJsonFn: (filePath: string, fallback: any) => any, + * cacheFilePath?: string, + * sqliteFilePath?: string, + * enableSqlite?: boolean | null, + * hotSessionLimit?: number, + * loadJsonFn?: (filePath: string, fallback: any) => any, * writeCacheFn?: (filePath: string, cacheObj: Record) => boolean, * shouldBypassThrottleFn?: (allowThrottleInTest: boolean) => boolean, * registerExitHook?: boolean, * }} options */ export function createTrajectoryCacheStore({ - cacheFilePath, - loadJsonFn, + cacheFilePath = '', + sqliteFilePath = '', + enableSqlite = null, + hotSessionLimit = DEFAULT_HOT_SESSION_LRU_LIMIT, + loadJsonFn = null, writeCacheFn = null, shouldBypassThrottleFn = () => false, registerExitHook = false, }) { + const maxHotSessions = Math.max(1, Math.floor(Number(hotSessionLimit) || DEFAULT_HOT_SESSION_LRU_LIMIT)); + const useSqlite = + enableSqlite === true + ? Boolean(sqliteFilePath && hasBuiltinNodeSqlite()) + : enableSqlite === false + ? false + : Boolean( + sqliteFilePath && + hasBuiltinNodeSqlite() && + !tcsIsVirtualSandboxPath(sqliteFilePath) + ); + + const sqliteLedger = useSqlite + ? createTrajectorySqliteLedger({ + sqliteFilePath, + legacyJsonPath: cacheFilePath, + loadJsonFn, + }) + : null; + let cacheObj = Object.create(null); const byLower = new Map(); + // Map preserving insertion order (oldest -> newest) for hot hydrated sessions + const hotLru = new Map(); + const dirtyUpserts = new Set(); + const dirtyRemovals = new Set(); + let pendingEpochBump = false; let loadedOnce = false; + let lastWalSyncCheckMs = 0; + const state = { needsSave: false, lastSavedAtMs: 0, @@ -88,12 +172,85 @@ export function createTrajectoryCacheStore({ } } - const doWrite = writeCacheFn || defaultWriteCache; + const doWriteJson = writeCacheFn || defaultWriteCache; + + function finalizeColdEntryInPlace(entry) { + if (!entry || typeof entry !== 'object') return entry; + const preFlags = entry._stepFlags || null; + if (Object.prototype.hasOwnProperty.call(entry, '_coldSteps')) { + delete entry._coldSteps; + } + if (Object.prototype.hasOwnProperty.call(entry, '_stepFlags')) { + delete entry._stepFlags; + } + tcsDefineHiddenProp(entry, '_coldSteps', true); + if (preFlags) { + tcsDefineHiddenProp(entry, '_stepFlags', preFlags); + } + tcsMarkColdSlimSteps(entry.steps); + return entry; + } + + function touchHotSession(lower) { + if (!useSqlite || !lower) return; + if (hotLru.has(lower)) { + hotLru.delete(lower); + } + hotLru.set(lower, true); + evictOverflowHotSessions(); + } + + function dehydrateSingleSessionToCold(lower) { + if (!useSqlite || !sqliteLedger || !lower) return false; + if (dirtyUpserts.has(lower)) return false; + const canon = byLower.get(lower); + const entry = canon ? cacheObj[canon] : null; + if (!entry || entry.wasRunning) return false; + if (tcsIsColdEntry(entry)) { + hotLru.delete(lower); + return true; + } + const curSteps = Array.isArray(entry.steps) ? entry.steps : []; + const flags = entry._stepFlags || computePrecomputedStepFlags(curSteps); + const slimSteps = tcsMarkColdSlimSteps(curSteps.map((s) => sqliteLedger.dehydrateStep(s))); + entry.steps = slimSteps; + tcsDefineHiddenProp(entry, '_coldSteps', true); + tcsDefineHiddenProp(entry, '_stepFlags', flags); + hotLru.delete(lower); + return true; + } + + function evictOverflowHotSessions() { + if (!useSqlite || hotLru.size <= maxHotSessions) return; + for (const candidateLower of Array.from(hotLru.keys())) { + if (hotLru.size <= maxHotSessions) break; + dehydrateSingleSessionToCold(candidateLower); + } + } + + function rebuildLowerIndexFromCacheObj(markCold = false) { + byLower.clear(); + hotLru.clear(); + for (const key of Object.keys(cacheObj)) { + const lower = key.toLowerCase(); + byLower.set(lower, key); + if (markCold) { + finalizeColdEntryInPlace(cacheObj[key]); + } + } + } function ensureLoaded() { if (loadedOnce) return; loadedOnce = true; - if (!cacheFilePath) return; + if (useSqlite && sqliteLedger) { + const hydrated = sqliteLedger.openAndHydrateInitial(); + cacheObj = hydrated.cacheObj; + rebuildLowerIndexFromCacheObj(true); + lastWalSyncCheckMs = Date.now(); + return; + } + if (!cacheFilePath || typeof loadJsonFn !== 'function') return; const loaded = loadJsonFn(cacheFilePath, {}); const hydrated = hydrateTrajectoryCacheObject(loaded); cacheObj = hydrated.cacheObj; @@ -105,6 +262,63 @@ export function createTrajectoryCacheStore({ } } + function syncExternalChangesNow() { + if (!useSqlite || !sqliteLedger || !loadedOnce) return false; + lastWalSyncCheckMs = Date.now(); + let res; + try { + res = sqliteLedger.syncExternalChangesIfNeeded(); + } catch { + return false; + } + if (!res || !res.changed) return false; + if (res.fullReset && res.cacheObj) { + for (const [cid, entry] of Object.entries(res.cacheObj)) { + const lower = cid.toLowerCase(); + if (dirtyUpserts.has(lower)) continue; + finalizeColdEntryInPlace(entry); + } + // Preserve any local unflushed dirty entries on top of the peer reset + const preservedDirty = []; + for (const dirtyLower of dirtyUpserts) { + const canon = byLower.get(dirtyLower); + if (canon && cacheObj[canon]) { + preservedDirty.push([canon, cacheObj[canon]]); + } + } + cacheObj = res.cacheObj; + rebuildLowerIndexFromCacheObj(true); + for (const [canon, dirtyEntry] of preservedDirty) { + cacheObj[canon] = dirtyEntry; + byLower.set(canon.toLowerCase(), canon); + touchHotSession(canon.toLowerCase()); + } + return true; + } + if (Array.isArray(res.updatedEntries)) { + for (const { cascadeId, lowerId, entry } of res.updatedEntries) { + if (dirtyUpserts.has(lowerId) || dirtyRemovals.has(lowerId)) continue; + const prevCanon = byLower.get(lowerId); + if (prevCanon && prevCanon !== cascadeId) { + delete cacheObj[prevCanon]; + } + finalizeColdEntryInPlace(entry); + cacheObj[cascadeId] = entry; + byLower.set(lowerId, cascadeId); + hotLru.delete(lowerId); + } + return true; + } + return false; + } + + function syncExternalIfDue() { + if (!useSqlite || !loadedOnce) return; + const now = Date.now(); + if (now - lastWalSyncCheckMs < TCS_WAL_SYNC_MIN_INTERVAL_MS) return; + syncExternalChangesNow(); + } + function cancelFlushTimer() { if (state.flushTimer) { try { @@ -119,11 +333,47 @@ export function createTrajectoryCacheStore({ function flushTrajectoryCacheNow() { ensureLoaded(); cancelFlushTimer(); + + if (useSqlite && sqliteLedger) { + if (dirtyUpserts.size === 0 && dirtyRemovals.size === 0 && !pendingEpochBump) { + state.needsSave = false; + return true; + } + const upserts = []; + for (const lower of dirtyUpserts) { + const canon = byLower.get(lower); + const entry = canon ? cacheObj[canon] : null; + if (canon && entry) { + upserts.push({ cascadeId: canon, entry }); + } + } + const removals = Array.from(dirtyRemovals); + try { + sqliteLedger.flushDeltaBatch({ + upserts, + removals, + bumpEpoch: pendingEpochBump, + }); + dirtyUpserts.clear(); + dirtyRemovals.clear(); + pendingEpochBump = false; + state.needsSave = false; + state.lastSavedAtMs = Date.now(); + lastWalSyncCheckMs = state.lastSavedAtMs; + evictOverflowHotSessions(); + return true; + } catch (err) { + console.error(`Failed flushing trajectory SQLite ledger ${sqliteFilePath}: ${err.message}`); + state.needsSave = true; + return false; + } + } + if (!cacheFilePath) { state.needsSave = false; return true; } - const ok = doWrite(cacheFilePath, cacheObj); + const ok = doWriteJson(cacheFilePath, cacheObj); state.needsSave = !ok; if (ok) { state.lastSavedAtMs = Date.now(); @@ -135,7 +385,7 @@ export function createTrajectoryCacheStore({ hasRunningSessions = false, allowThrottleInTest = false, } = {}) { - if (!cacheFilePath) { + if (!useSqlite && !cacheFilePath) { state.needsSave = false; return; } @@ -169,16 +419,103 @@ export function createTrajectoryCacheStore({ } } - function clearCache() { - if (cacheFilePath && !doWrite(cacheFilePath, {})) { + function hydrateEntryInPlaceIfNeeded(canonId, entry) { + if (!canonId || !entry) return entry; + const lower = canonId.toLowerCase(); + if (!useSqlite || !sqliteLedger) return entry; + if (!tcsIsColdEntry(entry)) { + touchHotSession(lower); + return entry; + } + const fullSteps = sqliteLedger.loadHydratedStepsForConversation(canonId, entry); + if (Array.isArray(fullSteps)) { + const flags = entry._stepFlags || computePrecomputedStepFlags(fullSteps); + entry.steps = fullSteps; + tcsDefineHiddenProp(entry, '_coldSteps', false); + tcsDefineHiddenProp(entry, '_stepFlags', flags); + touchHotSession(lower); + } + return entry; + } + + /** + * Non-destructively clears live/empty cached entries to force fresh re-scanning, while + * permanently archiving & preserving any conversation with `steps.length > 0` whose source + * conversation has already been deleted (`!liveSet.has(lower)` or `entry.archived === true`). + * + * @param {{ liveCascadeIds?: Iterable | null }} [options] + */ + function clearCache({ liveCascadeIds = null } = {}) { + ensureLoaded(); + syncExternalChangesNow(); + + const liveSet = + liveCascadeIds !== null && liveCascadeIds !== undefined + ? new Set( + Array.from(liveCascadeIds, (id) => String(id || '').trim().toLowerCase()).filter( + Boolean + ) + ) + : null; + + const retainedEntries = Object.create(null); + const removedLowers = []; + const archivedUpserts = []; + + for (const [key, entry] of Object.entries(cacheObj)) { + const lower = key.toLowerCase(); + const hasSteps = Array.isArray(entry?.steps) && entry.steps.length > 0; + const isDeletedHistorical = + hasSteps && (entry.archived === true || (liveSet !== null && !liveSet.has(lower))); + if (isDeletedHistorical) { + const archivedEntry = entry.archived === true ? entry : { ...entry, archived: true }; + if (tcsIsColdEntry(entry)) { + tcsDefineHiddenProp(archivedEntry, '_coldSteps', true); + } + if (entry._stepFlags) { + tcsDefineHiddenProp(archivedEntry, '_stepFlags', entry._stepFlags); + } + retainedEntries[key] = archivedEntry; + if (entry.archived !== true || dirtyUpserts.has(lower)) { + archivedUpserts.push({ cascadeId: key, entry: archivedEntry }); + } + } else { + removedLowers.push(lower); + } + } + + if (useSqlite && sqliteLedger) { + try { + sqliteLedger.flushDeltaBatch({ + upserts: archivedUpserts, + removals: removedLowers, + bumpEpoch: true, + }); + } catch (err) { + console.error(`Failed clearing trajectory SQLite ledger ${sqliteFilePath}: ${err.message}`); + return false; + } + } else if (cacheFilePath && !doWriteJson(cacheFilePath, retainedEntries)) { return false; } + cancelFlushTimer(); loadedOnce = true; - for (const key of Object.keys(cacheObj)) { - delete cacheObj[key]; - } + cacheObj = retainedEntries; byLower.clear(); + for (const key of Object.keys(cacheObj)) { + const lower = key.toLowerCase(); + byLower.set(lower, key); + } + for (const remLower of removedLowers) { + hotLru.delete(remLower); + dirtyUpserts.delete(remLower); + dirtyRemovals.delete(remLower); + } + for (const { cascadeId } of archivedUpserts) { + dirtyUpserts.delete(cascadeId.toLowerCase()); + } + pendingEpochBump = false; state.needsSave = false; state.lastSavedAtMs = 0; return true; @@ -192,27 +529,57 @@ export function createTrajectoryCacheStore({ }); } + function lookupRawByLower(cascadeId) { + if (!cascadeId) return null; + ensureLoaded(); + syncExternalIfDue(); + const direct = cacheObj[cascadeId]; + if (direct) return { id: String(cascadeId), entry: direct }; + const canon = byLower.get(String(cascadeId).toLowerCase()); + if (canon && cacheObj[canon]) { + return { id: canon, entry: cacheObj[canon] }; + } + return null; + } + return { cacheFilePath, + sqliteFilePath: useSqlite ? sqliteFilePath : '', + isSqliteBacked: useSqlite, cacheState: state, cancelFlushTimer, + syncExternalChangesNow, + getHotSessionCount() { + return hotLru.size; + }, + isConversationCold(cascadeId) { + const hit = lookupRawByLower(cascadeId); + return hit ? tcsIsColdEntry(hit.entry) : false; + }, getCachedTrajectory(cascadeId) { ensureLoaded(); + syncExternalIfDue(); return cacheObj[cascadeId]; }, getCachedTrajectoryEntryByLower(cascadeId) { - if (!cascadeId) return null; - ensureLoaded(); - const direct = cacheObj[cascadeId]; - if (direct) return { id: String(cascadeId), entry: direct }; - const canon = byLower.get(String(cascadeId).toLowerCase()); - if (canon && cacheObj[canon]) { - return { id: canon, entry: cacheObj[canon] }; - } - return null; + return lookupRawByLower(cascadeId); + }, + getHydratedTrajectory(cascadeId) { + const hit = lookupRawByLower(cascadeId); + if (!hit) return undefined; + return hydrateEntryInPlaceIfNeeded(hit.id, hit.entry); + }, + getHydratedTrajectoryEntryByLower(cascadeId) { + const hit = lookupRawByLower(cascadeId); + if (!hit) return null; + return { + id: hit.id, + entry: hydrateEntryInPlaceIfNeeded(hit.id, hit.entry), + }; }, listCachedTrajectoryEntries() { ensureLoaded(); + syncExternalIfDue(); return Object.entries(cacheObj); }, setCachedTrajectory(cascadeId, entry) { @@ -226,6 +593,18 @@ export function createTrajectoryCacheStore({ ) { delete cacheObj[prevCanon]; } + if (entry && typeof entry === 'object') { + const isStillCold = Boolean(entry.steps?._isColdSlimSteps === true); + tcsDefineHiddenProp(entry, '_coldSteps', isStillCold); + tcsAttachEntryStepFlags(entry, entry._stepFlags || null); + if (useSqlite && lower) { + dirtyRemovals.delete(lower); + dirtyUpserts.add(lower); + if (!isStillCold) { + touchHotSession(lower); + } + } + } cacheObj[cascadeId] = entry; if (lower) { byLower.set(lower, String(cascadeId)); @@ -234,10 +613,19 @@ export function createTrajectoryCacheStore({ removeCachedTrajectory(cascadeId) { ensureLoaded(); const lower = String(cascadeId || '').toLowerCase(); - if (lower && byLower.get(lower) === cascadeId) { - byLower.delete(lower); + const canon = lower ? byLower.get(lower) : undefined; + if (canon && Object.prototype.hasOwnProperty.call(cacheObj, canon)) { + delete cacheObj[canon]; } delete cacheObj[cascadeId]; + if (lower) { + byLower.delete(lower); + hotLru.delete(lower); + if (useSqlite) { + dirtyUpserts.delete(lower); + dirtyRemovals.add(lower); + } + } }, hasPendingTrajectoryCacheSave() { ensureLoaded(); diff --git a/sidecars/panel/backend/trajectory-sqlite-ledger.mjs b/sidecars/panel/backend/trajectory-sqlite-ledger.mjs new file mode 100644 index 0000000..71eb996 --- /dev/null +++ b/sidecars/panel/backend/trajectory-sqlite-ledger.mjs @@ -0,0 +1,954 @@ +/** + * @fileoverview Incremental SQLite trajectory & permanent usage ledger engine (`trajectory-sqlite-ledger.mjs`). + * + * Architecture: + * 1. Short-lived connections (`open -> WAL/NORMAL/busy_timeout -> tx -> close` in `finally`) prevent Windows + * file-handle lock retention (`EBUSY`) across Sidecar, `bridge-daemon.mjs`, and `standalone.mjs`. + * 2. Two-tier step storage: + * - `accounting_json`: compact 21-slot tuple holding scalar billing/timing/model/anomaly fields; cold + * conversations keep only interned slim objects in V8 memory (`~80ms` startup for `57k+` steps). + * - `detail_json`: lossless remainder (`contextBreakdown`, `turnPrompt*`, ISO timestamps, context limits, etc.), + * lazily hydrated on demand (`~1ms`) only for active/inspected conversations via a 24-entry LRU. + * 3. Step-level `O(delta)` incremental `UPSERT` with tail truncation (`DELETE ... WHERE pos >= ?`) on conversation + * undo/branching, plus `ledger_epoch` + `write_seq` cross-process WAL synchronization. + */ + +import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs'; +import { dirname } from 'node:path'; +import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs'; +import { isPlainObject } from './http-helpers.mjs'; +import { + computeSqliteWalSig, + getNodeSqliteDatabaseSync, + isSqliteBusyError, +} from './sqlite-client.mjs'; + +export const LEDGER_SCHEMA_VERSION = '1'; +const TSL_BUSY_TIMEOUT_WRITE_MS = 3000; +const TSL_BUSY_TIMEOUT_READ_MS = 1500; +const TSL_MAX_BUSY_ATTEMPTS = 3; + +const TSL_FLAG_COMPACTION = 1 << 0; +const TSL_FLAG_IMAGE_GEN = 1 << 1; +const TSL_FLAG_COMPLETE = 1 << 2; +const TSL_FLAG_SPEED_ELIGIBLE = 1 << 3; +const TSL_FLAG_VISIBLE_TEXT = 1 << 4; +const TSL_FLAG_TOOL_CALLS = 1 << 5; + +const TSL_CORE_STEP_KEYS = new Set([ + 'stepIndex', + 'createdAtMs', + 'isCompactionStep', + 'isImageGenStep', + 'isComplete', + 'speedSampleEligible', + 'hasVisibleText', + 'hasToolCalls', + 'modelKey', + 'responseModel', + 'apiProvider', + 'modelDisplayName', + 'modelSource', + 'modelIdentityVersion', + 'inputTokens', + 'cacheReadTokens', + 'outputTokens', + 'thinkingTokens', + 'responseTokens', + 'totalDurationSec', + 'totalTokPerSec', + 'nativeTtftSec', + 'speedReason', + 'measurementVersion', + 'accountName', + 'anomaly', +]); + +function tslCreateInternPool() { + const pool = new Map(); + return function internString(val) { + if (typeof val !== 'string' || val.length === 0) return ''; + if (val.length > 96) return val; + const hit = pool.get(val); + if (hit !== undefined) return hit; + if (pool.size >= 4096) pool.clear(); + pool.set(val, val); + return val; + }; +} + +/** + * Computes conversation-level `O(1)` step completeness and model-limit metadata + * so scanner `toFetch` checks and `buildKnownUpstreamModelMap` never need to hydrate cold `detail_json`. + * + * @param {object[]} steps + * @returns {{ + * hasMissingStepFields: boolean, + * hasMissingTurnRailFields: boolean, + * hasAnyTurnIndex: boolean, + * hasIncompleteTiming: boolean, + * modelLimits: Array<[string, number, number]>, + * }} + */ +export function computePrecomputedStepFlags(steps) { + const list = Array.isArray(steps) ? steps : []; + if (list.length === 0) { + return { + hasMissingStepFields: false, + hasMissingTurnRailFields: false, + hasAnyTurnIndex: false, + hasAnyContextBreakdown: false, + hasIncompleteTiming: false, + modelLimits: [], + }; + } + const lastStep = list[list.length - 1]; + const lastHasContextBdProp = Boolean( + lastStep && Object.prototype.hasOwnProperty.call(lastStep, 'contextBreakdown') + ); + const lastHasTurnIdxProp = Boolean( + lastStep && Object.prototype.hasOwnProperty.call(lastStep, 'turnIndex') + ); + let missingResponseModel = false; + let missingToolResultsTokens = false; + let checkedLastBd = false; + let hasAnyTurnIndex = false; + let hasAnyContextBreakdown = false; + let hasIncompleteTiming = false; + const limitsMap = new Map(); + + for (let i = list.length - 1; i >= 0; i -= 1) { + const st = list[i]; + if (!st || typeof st !== 'object') continue; + if (st.contextBreakdown && typeof st.contextBreakdown === 'object') { + hasAnyContextBreakdown = true; + if (!checkedLastBd) { + checkedLastBd = true; + missingToolResultsTokens = !Object.prototype.hasOwnProperty.call( + st.contextBreakdown, + 'toolResultsTokens' + ); + } + } + if (!Object.prototype.hasOwnProperty.call(st, 'responseModel')) { + missingResponseModel = true; + } + if (st.turnIndex) { + hasAnyTurnIndex = true; + } + if (st.speedReason === 'incomplete_or_invalid_timing') { + hasIncompleteTiming = true; + } + if ( + !st.isCompactionStep && + !st.isImageGenStep && + Number(st.reportedContextLimitTokens) > 0 && + st.modelKey && + st.modelKey !== 'unknown' + ) { + const atMs = Number.isFinite(Number(st.createdAtMs)) ? Number(st.createdAtMs) : 0; + const prev = limitsMap.get(st.modelKey); + if (!prev || atMs > prev.at) { + limitsMap.set(st.modelKey, { + tokens: Number(st.reportedContextLimitTokens), + at: atMs, + }); + } + } + } + + const modelLimits = []; + for (const [modelKey, info] of limitsMap.entries()) { + modelLimits.push([modelKey, info.tokens, info.at]); + } + + return { + hasMissingStepFields: !lastHasContextBdProp || missingResponseModel || missingToolResultsTokens, + hasMissingTurnRailFields: !lastHasTurnIdxProp, + hasAnyTurnIndex, + hasAnyContextBreakdown, + hasIncompleteTiming, + modelLimits, + }; +} + +/** + * Splits a full normalized step object into a compact 21-slot accounting tuple and an optional detail object. + * + * @param {object} step + * @returns {{ accountingTuple: any[], detailObj: Record | null }} + */ +export function splitStepForStorage(step) { + const s = step && typeof step === 'object' ? step : {}; + let flags = 0; + if (s.isCompactionStep) flags |= TSL_FLAG_COMPACTION; + if (s.isImageGenStep) flags |= TSL_FLAG_IMAGE_GEN; + if (s.isComplete) flags |= TSL_FLAG_COMPLETE; + if (s.speedSampleEligible) flags |= TSL_FLAG_SPEED_ELIGIBLE; + if (s.hasVisibleText) flags |= TSL_FLAG_VISIBLE_TEXT; + if (s.hasToolCalls) flags |= TSL_FLAG_TOOL_CALLS; + + const accountingTuple = [ + s.stepIndex ?? null, + Number(s.createdAtMs || 0), + flags, + s.modelKey || '', + s.responseModel ?? '', + s.apiProvider || '', + s.modelDisplayName || '', + s.modelSource || '', + s.modelIdentityVersion ?? null, + Number(s.inputTokens || 0), + Number(s.cacheReadTokens || 0), + Number(s.outputTokens || 0), + Number(s.thinkingTokens || 0), + s.responseTokens !== undefined && s.responseTokens !== null + ? Number(s.responseTokens) + : Math.max(0, Number(s.outputTokens || 0) - Number(s.thinkingTokens || 0)), + s.totalDurationSec ?? null, + s.totalTokPerSec ?? null, + s.nativeTtftSec ?? null, + s.speedReason ?? null, + s.measurementVersion ?? null, + s.accountName ?? null, + s.anomaly ?? null, + ]; + + let detailObj = null; + for (const key of Object.keys(s)) { + if (TSL_CORE_STEP_KEYS.has(key)) continue; + if (s[key] === undefined) continue; + if (!detailObj) detailObj = {}; + detailObj[key] = s[key]; + } + return { accountingTuple, detailObj }; +} + +/** + * Rebuilds a fixed-shape slim step object from a compact accounting tuple (or legacy plain object). + * + * @param {any[] | Record} rawAccounting + * @param {(val: string) => string} [internFn] + * @returns {object} + */ +export function buildSlimStepFromAccounting(rawAccounting, internFn = (v) => v || '') { + if (!Array.isArray(rawAccounting)) { + if (isPlainObject(rawAccounting)) { + const { accountingTuple } = splitStepForStorage(rawAccounting); + return buildSlimStepFromAccounting(accountingTuple, internFn); + } + return {}; + } + const t = rawAccounting; + const flags = Number(t[2] || 0); + const slim = { + stepIndex: t[0] ?? null, + createdAtMs: Number(t[1] || 0), + isCompactionStep: Boolean(flags & TSL_FLAG_COMPACTION), + ...(flags & TSL_FLAG_IMAGE_GEN ? { isImageGenStep: true } : {}), + isComplete: Boolean(flags & TSL_FLAG_COMPLETE), + speedSampleEligible: Boolean(flags & TSL_FLAG_SPEED_ELIGIBLE), + hasVisibleText: Boolean(flags & TSL_FLAG_VISIBLE_TEXT), + hasToolCalls: Boolean(flags & TSL_FLAG_TOOL_CALLS), + modelKey: internFn(t[3] || ''), + responseModel: internFn(t[4] || ''), + apiProvider: internFn(t[5] || ''), + modelDisplayName: internFn(t[6] || ''), + modelSource: internFn(t[7] || ''), + modelIdentityVersion: t[8] ?? null, + inputTokens: Number(t[9] || 0), + cacheReadTokens: Number(t[10] || 0), + outputTokens: Number(t[11] || 0), + thinkingTokens: Number(t[12] || 0), + responseTokens: Number(t[13] || 0), + totalDurationSec: t[14] ?? null, + totalTokPerSec: t[15] ?? null, + nativeTtftSec: t[16] ?? null, + speedReason: t[17] ? internFn(t[17]) : null, + measurementVersion: t[18] ?? null, + }; + if (t[19]) { + slim.accountName = internFn(t[19]); + } + if (t[20]) { + slim.anomaly = t[20]; + } + return slim; +} + +/** + * Merges a slim accounting step and parsed `detail_json` object into a complete step object. + * + * @param {object | any[]} accountingOrSlim + * @param {Record | null | undefined} detailObj + * @param {(val: string) => string} [internFn] + * @returns {object} + */ +export function mergeStepFromStorage(accountingOrSlim, detailObj, internFn) { + const base = Array.isArray(accountingOrSlim) + ? buildSlimStepFromAccounting(accountingOrSlim, internFn) + : { ...(accountingOrSlim || {}) }; + if (detailObj && typeof detailObj === 'object' && !Array.isArray(detailObj)) { + return { ...base, ...detailObj }; + } + return base; +} + +/** + * Converts a hydrated in-memory step into its cold slim representation, releasing heavy `detail` properties. + * + * @param {object} step + * @param {(val: string) => string} [internFn] + * @returns {object} + */ +export function dehydrateStepForColdMemory(step, internFn) { + const { accountingTuple } = splitStepForStorage(step); + return buildSlimStepFromAccounting(accountingTuple, internFn); +} + +function tslSerializeEntryHeader(entry) { + const meta = {}; + for (const [k, v] of Object.entries(entry || {})) { + if (k === 'steps' || k === '_coldSteps') continue; + if (v !== undefined) meta[k] = v; + } + if (!meta._stepFlags && Array.isArray(entry?.steps) && !entry._coldSteps) { + meta._stepFlags = computePrecomputedStepFlags(entry.steps); + } + return meta; +} + +function tslWithSqliteConnection(dbPath, { readOnly = false }, fn) { + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) { + throw new Error('node:sqlite DatabaseSync unavailable'); + } + if (!readOnly) { + mkdirSync(dirname(dbPath), { recursive: true }); + } + for (let attempt = 0; attempt < TSL_MAX_BUSY_ATTEMPTS; attempt += 1) { + let db = null; + try { + db = readOnly ? new DatabaseSync(dbPath, { readOnly: true }) : new DatabaseSync(dbPath); + if (readOnly) { + db.exec(`PRAGMA busy_timeout = ${TSL_BUSY_TIMEOUT_READ_MS};`); + } else { + db.exec( + `PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA busy_timeout = ${TSL_BUSY_TIMEOUT_WRITE_MS};` + ); + } + return fn(db); + } catch (err) { + if (attempt + 1 < TSL_MAX_BUSY_ATTEMPTS && isSqliteBusyError(err)) { + continue; + } + throw err; + } finally { + if (db) { + try { + db.close(); + } catch { + // Ignore close error + } + } + } + } + return null; +} + +function tslEnsureSchema(db) { + db.exec(` + CREATE TABLE IF NOT EXISTS ledger_meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS conversations ( + cascade_id TEXT PRIMARY KEY, + lower_id TEXT NOT NULL UNIQUE, + is_archived INTEGER NOT NULL DEFAULT 0, + step_count INTEGER NOT NULL DEFAULT 0, + write_seq INTEGER NOT NULL DEFAULT 0, + updated_at_ms INTEGER NOT NULL DEFAULT 0, + meta_json TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_conv_write_seq ON conversations(write_seq); + CREATE INDEX IF NOT EXISTS idx_conv_updated ON conversations(updated_at_ms); + CREATE TABLE IF NOT EXISTS steps ( + cascade_id TEXT NOT NULL, + pos INTEGER NOT NULL, + accounting_json TEXT NOT NULL, + detail_json TEXT, + PRIMARY KEY (cascade_id, pos) + ); + `); + const verRow = db + .prepare("SELECT value FROM ledger_meta WHERE key = 'schema_version'") + .get(); + if (!verRow) { + db.prepare("INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('schema_version', ?)").run( + LEDGER_SCHEMA_VERSION + ); + } + const epochRow = db + .prepare("SELECT value FROM ledger_meta WHERE key = 'ledger_epoch'") + .get(); + if (!epochRow) { + db.prepare("INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('ledger_epoch', '1')").run(); + } + const seqRow = db + .prepare("SELECT value FROM ledger_meta WHERE key = 'last_write_seq'") + .get(); + if (!seqRow) { + db.prepare("INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('last_write_seq', '0')").run(); + } +} + +function tslReadMetaInt(db, key, fallback = 0) { + const row = db.prepare('SELECT value FROM ledger_meta WHERE key = ?').get(key); + const num = Number(row?.value); + return Number.isFinite(num) && num >= 0 ? Math.floor(num) : fallback; +} + +function tslArchiveLegacyJsonToBak(legacyJsonPath) { + if (!legacyJsonPath || !existsSync(legacyJsonPath)) return; + const bakPath = `${legacyJsonPath}.bak`; + try { + if (existsSync(bakPath)) { + rmSync(bakPath, { force: true }); + } + renameSync(legacyJsonPath, bakPath); + } catch (err) { + if (err && err.code === 'ENOENT') return; + } +} + +/** + * Creates a short-connection SQLite trajectory ledger controller for one database file. + * + * @param {{ + * sqliteFilePath: string, + * legacyJsonPath?: string, + * loadJsonFn?: (filePath: string, fallback: any) => any, + * }} options + */ +export function createTrajectorySqliteLedger({ + sqliteFilePath, + legacyJsonPath = '', + loadJsonFn = null, +}) { + const internString = tslCreateInternPool(); + // Tracks per-conversation persisted signatures (`{ metaJson, stepSigs: string[] }`) for O(delta) step writes + const persistedByLower = new Map(); + let localEpoch = 1; + let localWriteSeq = 0; + let lastSeenWalSig = ''; + + function refreshWalSigAfterOwnWrite() { + lastSeenWalSig = computeSqliteWalSig(sqliteFilePath).sig; + } + + function normalizeLegacyEntriesForMigration(rawLoaded) { + const dedupedByLower = new Map(); + if (!isPlainObject(rawLoaded)) return dedupedByLower; + for (const [rawId, rawEntry] of Object.entries(rawLoaded)) { + const id = String(rawId || '').trim(); + const lower = id.toLowerCase(); + if (!lower || !isPlainObject(rawEntry)) continue; + const rawSteps = Array.isArray(rawEntry.steps) ? rawEntry.steps.filter(isPlainObject) : []; + const normalized = inferCompactionStepModels( + rawSteps.map((s) => normalizeCachedStep(s)).filter(Boolean) + ); + const canonId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id) + ? lower + : id; + const prev = dedupedByLower.get(lower); + if (!prev || normalized.length >= prev.entry.steps.length) { + dedupedByLower.set(lower, { + cascadeId: canonId, + lowerId: lower, + entry: { ...rawEntry, steps: normalized }, + }); + } + } + return dedupedByLower; + } + + /** + * Initializes schema, migrates legacy `.json` inside a single `BEGIN IMMEDIATE` transaction if needed, + * and hydrates all conversations in cold slim accounting mode. + */ + function openAndHydrateInitial() { + let migratedLegacy = false; + const hasLegacyJsonOnDisk = Boolean( + legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath) + ); + const dbExistsBefore = existsSync(sqliteFilePath); + + if (!dbExistsBefore || hasLegacyJsonOnDisk) { + tslWithSqliteConnection(sqliteFilePath, { readOnly: false }, (db) => { + tslEnsureSchema(db); + const migRow = db + .prepare("SELECT value FROM ledger_meta WHERE key = 'migrated_legacy_json'") + .get(); + if (migRow?.value === '1') return; + + let rawLoaded = null; + if (legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath)) { + rawLoaded = loadJsonFn(legacyJsonPath, null); + } + + db.exec('BEGIN IMMEDIATE'); + try { + const migRowInTx = db + .prepare("SELECT value FROM ledger_meta WHERE key = 'migrated_legacy_json'") + .get(); + if (migRowInTx?.value !== '1') { + let seq = tslReadMetaInt(db, 'last_write_seq', 0); + const nowMs = Date.now(); + if (rawLoaded && isPlainObject(rawLoaded)) { + const deduped = normalizeLegacyEntriesForMigration(rawLoaded); + const insConv = db.prepare(` + INSERT OR REPLACE INTO conversations ( + cascade_id, lower_id, is_archived, step_count, write_seq, updated_at_ms, meta_json + ) VALUES (?, ?, ?, ?, ?, ?, ?) + `); + const insStep = db.prepare(` + INSERT OR REPLACE INTO steps (cascade_id, pos, accounting_json, detail_json) + VALUES (?, ?, ?, ?) + `); + for (const { cascadeId, lowerId, entry } of deduped.values()) { + seq += 1; + const steps = entry.steps || []; + const header = tslSerializeEntryHeader(entry); + const metaJson = JSON.stringify(header); + const archivedInt = entry.archived ? 1 : 0; + insConv.run(cascadeId, lowerId, archivedInt, steps.length, seq, nowMs, metaJson); + const stepSigs = new Array(steps.length); + for (let pos = 0; pos < steps.length; pos += 1) { + const { accountingTuple, detailObj } = splitStepForStorage(steps[pos]); + const accJson = JSON.stringify(accountingTuple); + const detJson = detailObj ? JSON.stringify(detailObj) : null; + insStep.run(cascadeId, pos, accJson, detJson); + stepSigs[pos] = detJson ? `${accJson}\n${detJson}` : accJson; + } + persistedByLower.set(lowerId, { + cascadeId, + metaJson, + archivedInt, + stepSigs, + }); + } + migratedLegacy = true; + } + db.prepare( + "INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('last_write_seq', ?)" + ).run(String(seq)); + db.prepare( + "INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('migrated_legacy_json', '1')" + ).run(); + } + db.exec('COMMIT'); + } catch (err) { + try { + db.exec('ROLLBACK'); + } catch { + // Ignore rollback error + } + throw err; + } + }); + + if (migratedLegacy || hasLegacyJsonOnDisk) { + tslArchiveLegacyJsonToBak(legacyJsonPath); + } + } + + return hydrateAllSlimFromDb(); + } + + function hydrateAllSlimFromDb() { + if (!existsSync(sqliteFilePath)) { + localEpoch = 1; + localWriteSeq = 0; + lastSeenWalSig = ''; + return { cacheObj: Object.create(null) }; + } + const cacheObj = Object.create(null); + tslWithSqliteConnection(sqliteFilePath, { readOnly: true }, (db) => { + localEpoch = tslReadMetaInt(db, 'ledger_epoch', 1); + localWriteSeq = tslReadMetaInt(db, 'last_write_seq', 0); + const convRows = db + .prepare( + 'SELECT cascade_id, lower_id, is_archived, step_count, meta_json FROM conversations' + ) + .all(); + const stepRows = db + .prepare('SELECT cascade_id, pos, accounting_json FROM steps ORDER BY cascade_id, pos ASC') + .all(); + + for (const row of convRows) { + let meta = {}; + try { + meta = JSON.parse(row.meta_json) || {}; + } catch { + meta = {}; + } + const entry = { + ...meta, + ...(row.is_archived ? { archived: true } : {}), + _coldSteps: true, + steps: [], + }; + if (!row.is_archived && entry.archived) { + delete entry.archived; + } + cacheObj[row.cascade_id] = entry; + if (!persistedByLower.has(row.lower_id)) { + persistedByLower.set(row.lower_id, { + cascadeId: row.cascade_id, + metaJson: row.meta_json, + archivedInt: row.is_archived ? 1 : 0, + stepSigs: null, + }); + } + } + + for (const sRow of stepRows) { + const target = cacheObj[sRow.cascade_id]; + if (!target) continue; + let parsedAcc = null; + try { + parsedAcc = JSON.parse(sRow.accounting_json); + } catch { + continue; + } + target.steps.push(buildSlimStepFromAccounting(parsedAcc, internString)); + } + }); + lastSeenWalSig = computeSqliteWalSig(sqliteFilePath).sig; + return { cacheObj }; + } + + /** + * Synchronously hydrates full `detail_json` rows for a single cold conversation (`<1.5ms`). + * + * @param {string} cascadeId + * @param {object} currentEntry + * @returns {object[] | null} + */ + function loadHydratedStepsForConversation(cascadeId, currentEntry) { + if (!cascadeId || !currentEntry || !existsSync(sqliteFilePath)) return null; + const slimSteps = Array.isArray(currentEntry.steps) ? currentEntry.steps : []; + if (slimSteps.length === 0) return []; + + return tslWithSqliteConnection(sqliteFilePath, { readOnly: true }, (db) => { + const lower = String(cascadeId).toLowerCase(); + const convRow = db + .prepare('SELECT cascade_id FROM conversations WHERE lower_id = ?') + .get(lower); + const dbCid = convRow?.cascade_id || cascadeId; + const detailRows = db + .prepare( + 'SELECT pos, accounting_json, detail_json FROM steps WHERE cascade_id = ? ORDER BY pos ASC' + ) + .all(dbCid); + if (!detailRows || detailRows.length === 0) { + return slimSteps.map((s) => ({ ...s })); + } + const hydrated = new Array(detailRows.length); + for (let i = 0; i < detailRows.length; i += 1) { + const r = detailRows[i]; + let acc = null; + let det = null; + try { + acc = JSON.parse(r.accounting_json); + } catch { + acc = slimSteps[i] || {}; + } + if (r.detail_json) { + try { + det = JSON.parse(r.detail_json); + } catch { + det = null; + } + } + hydrated[i] = mergeStepFromStorage(acc, det, internString); + } + return hydrated; + }); + } + + /** + * Persists dirty conversations and removals incrementally inside a single `BEGIN IMMEDIATE` transaction. + * + * @param {{ + * upserts: Array<{ cascadeId: string, entry: object }>, + * removals: string[], + * bumpEpoch?: boolean, + * }} batch + */ + function flushDeltaBatch({ upserts = [], removals = [], bumpEpoch = false } = {}) { + if (upserts.length === 0 && removals.length === 0 && !bumpEpoch) { + return true; + } + tslWithSqliteConnection(sqliteFilePath, { readOnly: false }, (db) => { + tslEnsureSchema(db); + db.exec('BEGIN IMMEDIATE'); + try { + let seq = tslReadMetaInt(db, 'last_write_seq', localWriteSeq); + let epoch = tslReadMetaInt(db, 'ledger_epoch', localEpoch); + const nowMs = Date.now(); + + if (bumpEpoch || removals.length > 0) { + epoch += 1; + db.prepare( + "INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('ledger_epoch', ?)" + ).run(String(epoch)); + } + + if (removals.length > 0) { + const selByLower = db.prepare( + 'SELECT cascade_id FROM conversations WHERE lower_id = ?' + ); + const delSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ?'); + const delConv = db.prepare('DELETE FROM conversations WHERE lower_id = ?'); + for (const rawRem of removals) { + const lower = String(rawRem || '').toLowerCase(); + if (!lower) continue; + const existing = selByLower.get(lower); + if (existing?.cascade_id) { + delSteps.run(existing.cascade_id); + } + delSteps.run(rawRem); + delConv.run(lower); + persistedByLower.delete(lower); + } + } + + if (upserts.length > 0) { + const selExisting = db.prepare( + 'SELECT cascade_id, step_count FROM conversations WHERE lower_id = ?' + ); + const upConv = db.prepare(` + INSERT OR REPLACE INTO conversations ( + cascade_id, lower_id, is_archived, step_count, write_seq, updated_at_ms, meta_json + ) VALUES (?, ?, ?, ?, ?, ?, ?) + `); + const upStep = db.prepare(` + INSERT OR REPLACE INTO steps (cascade_id, pos, accounting_json, detail_json) + VALUES (?, ?, ?, ?) + `); + const truncSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ? AND pos >= ?'); + const delOldCidSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ?'); + + for (const { cascadeId, entry } of upserts) { + if (!cascadeId || !entry || typeof entry !== 'object') continue; + const lower = String(cascadeId).toLowerCase(); + const prevDbRow = selExisting.get(lower); + if (prevDbRow?.cascade_id && prevDbRow.cascade_id !== cascadeId) { + delOldCidSteps.run(prevDbRow.cascade_id); + } + + const prevDigest = persistedByLower.get(lower) || null; + const header = tslSerializeEntryHeader(entry); + const metaJson = JSON.stringify(header); + const archivedInt = entry.archived ? 1 : 0; + const steps = Array.isArray(entry.steps) ? entry.steps : []; + + // When an entry is still in `_coldSteps` mode (only metadata such as `signature`, `title`, + // or `archived` changed without mutating steps), update ONLY `conversations` in O(1) + // without touching `steps` (`detail_json` on disk stays 100% intact)! + if (entry._coldSteps && prevDbRow && prevDbRow.step_count === steps.length) { + if ( + prevDigest && + prevDigest.cascadeId === cascadeId && + prevDigest.metaJson === metaJson && + prevDigest.archivedInt === archivedInt + ) { + continue; + } + seq += 1; + upConv.run(cascadeId, lower, archivedInt, steps.length, seq, nowMs, metaJson); + persistedByLower.set(lower, { + cascadeId, + metaJson, + archivedInt, + stepSigs: prevDigest?.stepSigs || null, + }); + continue; + } + + const prevStepSigs = + prevDigest?.cascadeId === cascadeId && Array.isArray(prevDigest.stepSigs) + ? prevDigest.stepSigs + : null; + const nextStepSigs = new Array(steps.length); + let anyStepWritten = false; + + for (let pos = 0; pos < steps.length; pos += 1) { + const { accountingTuple, detailObj } = splitStepForStorage(steps[pos]); + const accJson = JSON.stringify(accountingTuple); + const detJson = detailObj ? JSON.stringify(detailObj) : null; + const sig = detJson ? `${accJson}\n${detJson}` : accJson; + nextStepSigs[pos] = sig; + if (!prevStepSigs || prevStepSigs[pos] !== sig) { + upStep.run(cascadeId, pos, accJson, detJson); + anyStepWritten = true; + } + } + + const prevCount = prevDbRow + ? Number(prevDbRow.step_count || 0) + : prevStepSigs + ? prevStepSigs.length + : 0; + if (steps.length < prevCount) { + truncSteps.run(cascadeId, steps.length); + anyStepWritten = true; + } + + if ( + anyStepWritten || + !prevDigest || + prevDigest.cascadeId !== cascadeId || + prevDigest.metaJson !== metaJson || + prevDigest.archivedInt !== archivedInt || + prevCount !== steps.length + ) { + seq += 1; + upConv.run(cascadeId, lower, archivedInt, steps.length, seq, nowMs, metaJson); + } + + persistedByLower.set(lower, { + cascadeId, + metaJson, + archivedInt, + stepSigs: nextStepSigs, + }); + } + } + + db.prepare( + "INSERT OR REPLACE INTO ledger_meta (key, value) VALUES ('last_write_seq', ?)" + ).run(String(seq)); + db.exec('COMMIT'); + localEpoch = epoch; + localWriteSeq = seq; + } catch (err) { + try { + db.exec('ROLLBACK'); + } catch { + // Ignore rollback error + } + throw err; + } + }); + + refreshWalSigAfterOwnWrite(); + return true; + } + + /** + * Checks WAL composite signature and pulls incremental updates or epoch resets written by peer processes. + * + * @returns {{ + * changed: boolean, + * fullReset?: boolean, + * cacheObj?: Record, + * updatedEntries?: Array<{ cascadeId: string, lowerId: string, entry: object }>, + * }} + */ + function syncExternalChangesIfNeeded() { + const walInfo = computeSqliteWalSig(sqliteFilePath); + if (!walInfo.exists || !walInfo.sig || walInfo.sig === lastSeenWalSig) { + return { changed: false }; + } + + let fullResetNeeded = false; + const updatedEntries = []; + + tslWithSqliteConnection(sqliteFilePath, { readOnly: true }, (db) => { + const dbEpoch = tslReadMetaInt(db, 'ledger_epoch', 1); + const dbSeq = tslReadMetaInt(db, 'last_write_seq', 0); + if (dbEpoch !== localEpoch) { + fullResetNeeded = true; + return; + } + if (dbSeq <= localWriteSeq) { + localWriteSeq = dbSeq; + return; + } + const changedConvs = db + .prepare( + `SELECT cascade_id, lower_id, is_archived, step_count, write_seq, meta_json + FROM conversations + WHERE write_seq > ? + ORDER BY write_seq ASC` + ) + .all(localWriteSeq); + const selSteps = db.prepare( + 'SELECT pos, accounting_json FROM steps WHERE cascade_id = ? ORDER BY pos ASC' + ); + for (const row of changedConvs) { + let meta = {}; + try { + meta = JSON.parse(row.meta_json) || {}; + } catch { + meta = {}; + } + const sRows = selSteps.all(row.cascade_id); + const slimSteps = []; + for (const sr of sRows) { + try { + slimSteps.push(buildSlimStepFromAccounting(JSON.parse(sr.accounting_json), internString)); + } catch { + // Skip malformed step JSON + } + } + const entry = { + ...meta, + ...(row.is_archived ? { archived: true } : {}), + _coldSteps: true, + steps: slimSteps, + }; + if (!row.is_archived && entry.archived) { + delete entry.archived; + } + persistedByLower.set(row.lower_id, { + cascadeId: row.cascade_id, + metaJson: row.meta_json, + archivedInt: row.is_archived ? 1 : 0, + stepSigs: null, + }); + updatedEntries.push({ + cascadeId: row.cascade_id, + lowerId: row.lower_id, + entry, + }); + } + localWriteSeq = dbSeq; + }); + + if (fullResetNeeded) { + persistedByLower.clear(); + const full = hydrateAllSlimFromDb(); + return { changed: true, fullReset: true, cacheObj: full.cacheObj }; + } + + lastSeenWalSig = walInfo.sig; + if (updatedEntries.length === 0) { + return { changed: false }; + } + return { changed: true, fullReset: false, updatedEntries }; + } + + return { + sqliteFilePath, + internString, + openAndHydrateInitial, + loadHydratedStepsForConversation, + flushDeltaBatch, + syncExternalChangesIfNeeded, + dehydrateStep: (step) => dehydrateStepForColdMemory(step, internString), + }; +} diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index e245fda..50070a7 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -28,10 +28,11 @@ const BACKEND_MODULE_FILES = [ '../backend/account-switch.mjs', '../backend/http-helpers.mjs', '../backend/settings-schema.mjs', + '../backend/sqlite-client.mjs', + '../backend/trajectory-sqlite-ledger.mjs', '../backend/trajectory-cache-store.mjs', '../backend/config.mjs', '../backend/endpoint-registry.mjs', - '../backend/sqlite-client.mjs', '../backend/proto-wire.mjs', '../backend/cli-sqlite-reader.mjs', '../backend/cli-statusline-config.mjs', diff --git a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs index be994eb..3282620 100644 --- a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs +++ b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs @@ -936,16 +936,21 @@ test('legacy pre-PR#38 empty-WAL sqlite cache signatures migrate in-place withou const scannerUrl = new URL('../backend/local-scanner.mjs', import.meta.url).href; const configUrl = new URL('../backend/config.mjs', import.meta.url).href; const script = ` - import { readFileSync } from 'node:fs'; + import { existsSync } from 'node:fs'; import { enumerateAndSyncConversations } from ${JSON.stringify(scannerUrl)}; - import { CACHE_FILE, flushTrajectoryCacheNow, getCachedTrajectory } from ${JSON.stringify(configUrl)}; + import { CACHE_FILE, TRAJECTORY_DB_FILE, flushTrajectoryCacheNow, getCachedTrajectory } from ${JSON.stringify(configUrl)}; + const { DatabaseSync } = process.getBuiltinModule('node:sqlite'); await enumerateAndSyncConversations({ summariesObj: {}, requestedConvId: '' }); const entry = getCachedTrajectory(${JSON.stringify(cid)}); flushTrajectoryCacheNow(); - const onDisk = JSON.parse(readFileSync(CACHE_FILE, 'utf8')); + const db = new DatabaseSync(TRAJECTORY_DB_FILE, { readOnly: true }); + const row = db.prepare('SELECT meta_json FROM conversations WHERE lower_id = ?').get(${JSON.stringify(cid.toLowerCase())}); + db.close(); + const onDiskMeta = row?.meta_json ? JSON.parse(row.meta_json) : {}; console.log(JSON.stringify({ memSig: entry?.signature || '', - diskSig: onDisk[${JSON.stringify(cid)}]?.signature || '', + diskSig: onDiskMeta?.signature || '', + migratedBakExists: existsSync(CACHE_FILE + '.bak'), stepCount: entry?.steps?.length || 0, firstInput: entry?.steps?.[0]?.inputTokens || 0, })); @@ -961,6 +966,7 @@ test('legacy pre-PR#38 empty-WAL sqlite cache signatures migrate in-place withou }, }); const out = JSON.parse(stdout.trim().split('\n').pop()); + assert.equal(out.migratedBakExists, true, 'legacy JSON cache automatically migrated and archived to .bak'); assert.equal(out.stepCount, 1, 'cached sentinel step preserved (SQLite was NOT re-read)'); assert.equal(out.firstInput, 1234, 'cached usage preserved intact'); assert.ok(out.memSig.endsWith('|0:0'), `in-memory signature normalized to |0:0: ${out.memSig}`); diff --git a/sidecars/panel/test/sqlite-trajectory-ledger.test.mjs b/sidecars/panel/test/sqlite-trajectory-ledger.test.mjs new file mode 100644 index 0000000..a2e85d9 --- /dev/null +++ b/sidecars/panel/test/sqlite-trajectory-ledger.test.mjs @@ -0,0 +1,511 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { isDeepStrictEqual, promisify } from 'node:util'; +import { MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs'; +import { createTrajectoryCacheStore } from '../backend/trajectory-cache-store.mjs'; + +const execFileAsync = promisify(execFile); + +function loadJsonHelper(filePath, fallback = null) { + try { + if (!existsSync(filePath)) return fallback; + return JSON.parse(readFileSync(filePath, 'utf8')); + } catch { + return fallback; + } +} + +function makeRichStep(stepIndex, overrides = {}) { + const baseMs = Date.parse('2026-11-20T08:00:00Z') + stepIndex * 5_000; + return { + stepIndex, + isCompactionStep: false, + modelKey: 'MODEL_PLACEHOLDER_M429', + modelSource: 'generatorMetadata.chatModel.model', + responseModel: 'gemini-4-carbon-high', + modelIdentityVersion: MODEL_IDENTITY_VERSION, + modelDisplayName: 'Gemini 4 Carbon (High)', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + createdAt: new Date(baseMs).toISOString(), + createdAtMs: baseMs, + hasVisibleText: true, + hasToolCalls: false, + inputTokens: 10_000 + stepIndex * 100, + cacheReadTokens: 40_000, + outputTokens: 600, + thinkingTokens: 200, + responseTokens: 400, + estimatedContextTokens: 50_600, + maxContextBudgetTokens: 1_000_000, + reportedContextLimitTokens: 1_000_000, + contextBreakdown: { + totalTokens: 50_600, + messagesTokens: 32_000, + userInputTokens: 8_000, + assistantTokens: 14_000, + toolResultsTokens: 10_000, + subagentTokens: 0, + checkpointTokens: 0, + systemToolsTokens: 9_600, + mcpToolsTokens: 2_000, + skillsTokens: 3_000, + systemPromptTokens: 3_000, + userRulesTokens: 1_000, + }, + measurementVersion: 4, + isComplete: true, + nativeTtftSec: 1.5, + nativeStreamSec: 4.5, + viewableDelaySec: 1.6, + ttftSec: 1.5, + ttftSource: 'generator_metadata', + thinkingDurationSec: 1.2, + totalDurationSec: 6.0, + totalTokPerSec: 100, + speedBasis: 'request_total', + speedSampleEligible: true, + speedReason: null, + turnIndex: 1, + isTurnStart: stepIndex === 1, + turnPrompt: `Prompt for step ${stepIndex}`, + turnPromptClean: `Prompt for step ${stepIndex}`, + turnHasMedia: false, + turnMediaOnly: false, + ...overrides, + }; +} + +function encodeVarint(val) { + let v = BigInt(val); + if (v < 0n) v = BigInt.asUintN(64, v); + const out = []; + while (v >= 0x80n) { + out.push(Number((v & 0x7fn) | 0x80n)); + v >>= 7n; + } + out.push(Number(v)); + return Buffer.from(out); +} + +function encodeFieldVarint(fieldNo, val) { + return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]); +} + +function encodeFieldBytes(fieldNo, bufOrStr) { + const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8'); + return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]); +} + +function encodeTimestamp(sec) { + return encodeFieldBytes(1, Buffer.concat([encodeFieldVarint(1, sec)])).subarray(2); +} + +function encodeStepMeta({ createdSec, finishedSec, stepIndex, originCid, inputTokens, outputTokens }) { + const ts = (sec) => encodeFieldBytes(1, Buffer.concat([encodeFieldVarint(1, sec)])).subarray(2); + const mu = Buffer.concat([ + encodeFieldVarint(1, 1429), // MODEL_PLACEHOLDER_M429 (Carbon High) + encodeFieldVarint(2, inputTokens), + encodeFieldVarint(3, outputTokens), + encodeFieldVarint(6, 24), + ]); + return Buffer.concat([ + encodeFieldBytes(1, ts(createdSec)), + encodeFieldBytes(7, ts(finishedSec)), + encodeFieldBytes(9, mu), + encodeFieldBytes(20, Buffer.concat([encodeFieldVarint(2, stepIndex), encodeFieldBytes(4, originCid)])), + ]); +} + +test('SQLite ledger automatically migrates legacy trajectory_usage_cache.json to .sqlite, archives .bak, and preserves lossless details & anomalies', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-mig-')); + t.after(() => { + rmSync(tmp, { recursive: true, force: true }); + }); + + const legacyJson = join(tmp, 'trajectory_usage_cache.json'); + const sqliteFile = join(tmp, 'trajectory_store.sqlite'); + const mainCid = 'aaaaaaaa-1111-4111-8111-111111111111'; + const subCid = 'bbbbbbbb-2222-4222-8222-222222222222'; + + const step1 = makeRichStep(1, { + accountName: 'alice@example.com', + anomaly: { + count: 2, + severity: 'warn', + primaryKind: 'rate_limit', + totalDelaySec: 8.5, + kinds: { rate_limit: 2 }, + }, + anomalySig: 'rl:2', + }); + const cpStep = makeRichStep(2, { + isCompactionStep: true, + modelKey: undefined, + responseModel: '', + modelDisplayName: '', + contextBreakdown: null, + inputTokens: 5_000, + cacheReadTokens: 0, + outputTokens: 300, + thinkingTokens: 0, + responseTokens: 300, + }); + delete cpStep.modelKey; + + writeFileSync( + legacyJson, + JSON.stringify({ + [mainCid.toUpperCase()]: { + title: 'Legacy Migrated Root', + signature: 'v10-model-identity:sqlite:1::100:200|0:0', + accountName: 'bob@example.com', + workspaceUri: 'file:///f:/demo/project', + subagentRefs: [{ cascadeId: subCid, role: 'Researcher', typeName: 'research', spawnOrder: 0 }], + steps: [step1, cpStep], + }, + [subCid]: { + title: 'Researcher', + parentConversationId: mainCid, + rootConversationId: mainCid, + subagentSpec: { typeName: 'research', role: 'Researcher' }, + steps: [makeRichStep(1, { inputTokens: 2_000, outputTokens: 100 })], + }, + }), + 'utf8' + ); + + const store = createTrajectoryCacheStore({ + cacheFilePath: legacyJson, + sqliteFilePath: sqliteFile, + enableSqlite: true, + loadJsonFn: loadJsonHelper, + }); + + // Cold startup list reads slim accounting entries without hydrating detail_json + const entries = store.listCachedTrajectoryEntries(); + assert.equal(entries.length, 2); + assert.equal(existsSync(sqliteFile), true); + assert.equal(existsSync(legacyJson), false, 'legacy JSON moved out of active path'); + assert.equal(existsSync(`${legacyJson}.bak`), true, 'legacy JSON safely archived to .bak'); + + // Cold entry omits heavy contextBreakdown/turnPrompt, retains anomaly/accountName/inferred compaction model! + assert.equal(store.isConversationCold(mainCid), true); + const coldMain = store.getCachedTrajectoryEntryByLower(mainCid)?.entry; + assert.ok(coldMain); + assert.equal(coldMain.steps.length, 2); + assert.equal(coldMain.steps[0].contextBreakdown, undefined, 'cold step omits heavy contextBreakdown'); + assert.equal(coldMain.steps[0].turnPrompt, undefined, 'cold step omits heavy turnPrompt'); + assert.deepEqual(coldMain.steps[0].anomaly, step1.anomaly, 'cold step preserves anomaly for model ranking'); + assert.equal(coldMain.steps[0].accountName, 'alice@example.com'); + assert.equal(coldMain.steps[1].modelKey, 'MODEL_PLACEHOLDER_M429', 'compaction step inferred model during migration'); + + // Explicit hydration restores 100% lossless step details + const hydratedMain = store.getHydratedTrajectoryEntryByLower(mainCid)?.entry; + assert.equal(store.isConversationCold(mainCid), false); + assert.deepEqual(hydratedMain.steps[0].contextBreakdown, step1.contextBreakdown); + assert.equal(hydratedMain.steps[0].turnPrompt, 'Prompt for step 1'); + assert.equal(hydratedMain.steps[0].reportedContextLimitTokens, 1_000_000); +}); + +test('Hot 24-session LRU evicts cold detail memory, never thrashes during full-list scans, and re-hydrates on demand', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-lru-')); + t.after(() => { + rmSync(tmp, { recursive: true, force: true }); + }); + + const sqliteFile = join(tmp, 'trajectory_store.sqlite'); + const store = createTrajectoryCacheStore({ + sqliteFilePath: sqliteFile, + enableSqlite: true, + hotSessionLimit: 24, + }); + + const originalStep0 = makeRichStep(1, { + turnPrompt: 'Deep historical architecture prompt #0', + anomaly: { count: 1, severity: 'danger', primaryKind: 'timeout', totalDelaySec: 30, kinds: { timeout: 1 } }, + }); + + for (let i = 0; i < 32; i += 1) { + const cid = `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`; + store.setCachedTrajectory(cid, { + title: `Session #${i}`, + signature: `v10-model-identity:sqlite:1::${i}`, + wasRunning: false, + contextGroupsTelemetry: 3, + turnRailTelemetry: true, + anomalyTelemetry: 1, + steps: [i === 0 ? originalStep0 : makeRichStep(1, { turnPrompt: `Prompt #${i}` })], + }); + } + + // Before flush, dirty unflushed sessions MUST NOT drop detail_json prematurely! + const cid0 = '00000000-0000-4000-8000-000000000000'; + assert.ok(store.getCachedTrajectory(cid0).steps[0].contextBreakdown, 'dirty unflushed session retains detail'); + + // Flush writes all 32 to SQLite, then trims hot LRU down to 24! + assert.equal(store.flushTrajectoryCacheNow(), true); + assert.equal(store.getHotSessionCount(), 24); + assert.equal(store.isConversationCold(cid0), true, 'oldest session #0 evicted to cold slim mode'); + assert.equal(store.getCachedTrajectory(cid0).steps[0].contextBreakdown, undefined); + assert.deepEqual(store.getCachedTrajectory(cid0).steps[0].anomaly, originalStep0.anomaly); + + // Iterating all 32 conversations via getCachedTrajectory / listCachedTrajectoryEntries MUST NOT hydrate cold sessions! + for (const [cid] of store.listCachedTrajectoryEntries()) { + const e = store.getCachedTrajectory(cid); + assert.equal(e.steps.length, 1); + } + assert.equal(store.isConversationCold(cid0), true, 'scan loop caused zero cold SQLite reads'); + assert.equal(store.getHotSessionCount(), 24); + + // Explicit hydration of cold session #0 restores exact original step and evicts #8 + const hydrated0 = store.getHydratedTrajectory(cid0); + assert.equal(store.isConversationCold(cid0), false); + assert.equal(store.getHotSessionCount(), 24); + assert.equal(isDeepStrictEqual(hydrated0.steps[0], originalStep0), true); + assert.equal(store.isConversationCold('00000000-0000-4000-8000-000000000008'), true); +}); + +test('Step-level O(delta) UPSERT, conversation undo tail truncation, and cross-process WAL sync keep zero file locks', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-wal-')); + t.after(() => { + rmSync(tmp, { recursive: true, force: true }); + }); + + const sqliteFile = join(tmp, 'trajectory_store.sqlite'); + const storeWriter = createTrajectoryCacheStore({ sqliteFilePath: sqliteFile, enableSqlite: true }); + const storeReader = createTrajectoryCacheStore({ sqliteFilePath: sqliteFile, enableSqlite: true }); + + const cid = 'cccccccc-3333-4333-8333-333333333333'; + const s1 = makeRichStep(1, { inputTokens: 1_000 }); + const s2 = makeRichStep(2, { inputTokens: 2_000 }); + const s3 = makeRichStep(3, { inputTokens: 3_000 }); + storeWriter.setCachedTrajectory(cid, { + title: 'Incremental Session', + signature: 'sig-3', + steps: [s1, s2, s3], + }); + storeWriter.flushTrajectoryCacheNow(); + + // Reader hydrates initial 3 steps + assert.equal(storeReader.getCachedTrajectory(cid).steps.length, 3); + + // Append step #4: verify SQLite now has 4 rows and Reader picks up incremental write_seq update + const s4 = makeRichStep(4, { inputTokens: 4_000 }); + storeWriter.setCachedTrajectory(cid, { + title: 'Incremental Session', + signature: 'sig-4', + steps: [s1, s2, s3, s4], + }); + storeWriter.flushTrajectoryCacheNow(); + + storeReader.syncExternalChangesNow(); + assert.equal(storeReader.getCachedTrajectory(cid).steps.length, 4); + assert.equal(storeReader.getCachedTrajectory(cid).steps[3].inputTokens, 4_000); + + // Simulate Undo in Antigravity: steps shrink from 4 back to 2 -> pos 2 & 3 MUST be deleted from SQLite! + storeWriter.setCachedTrajectory(cid, { + title: 'Incremental Session (Undone)', + signature: 'sig-2', + steps: [s1, s2], + }); + storeWriter.flushTrajectoryCacheNow(); + + const dbCheck = new DatabaseSync(sqliteFile, { readOnly: true }); + const stepRowCount = dbCheck + .prepare('SELECT COUNT(*) AS cnt FROM steps WHERE cascade_id = ?') + .get(cid).cnt; + dbCheck.close(); + assert.equal(stepRowCount, 2, 'undone tail steps pos >= 2 truncated cleanly'); + + storeReader.syncExternalChangesNow(); + assert.equal(storeReader.getCachedTrajectory(cid).steps.length, 2); + + // Simulate clearCache on Writer (with cid live -> cleared): Reader syncs epoch bump and removes cid! + storeWriter.clearCache({ liveCascadeIds: [cid] }); + storeReader.syncExternalChangesNow(); + assert.equal(storeReader.getCachedTrajectory(cid), undefined); +}); + +test('Deleting source conversation in Antigravity + clicking Rebuild Cache permanently preserves deleted conversation tokens, costs, and details', async (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tmp = mkdtempSync(join(tmpdir(), 'agy-ledger-perm-')); + t.after(() => { + try { + rmSync(tmp, { recursive: true, force: true }); + } catch { + // Ignore Windows WAL cleanup race + } + }); + + const geminiDir = join(tmp, 'gemini'); + const agyDir = join(geminiDir, 'antigravity'); + const convDir = join(agyDir, 'conversations'); + const dataDir = join(tmp, 'panel-data'); + mkdirSync(convDir, { recursive: true }); + mkdirSync(dataDir, { recursive: true }); + + const cidDeleted = 'dddddddd-4444-4444-8444-444444444444'; + const cidLive = 'eeeeeeee-5555-4555-8555-555555555555'; + const baseSec = Math.floor(Date.parse('2026-11-18T00:00:00Z') / 1000); + + // Create conversation_summaries.db and both .db files + const sumDbPath = join(agyDir, 'conversation_summaries.db'); + const sumDb = new DatabaseSync(sumDbPath); + sumDb.exec(` + CREATE TABLE conversation_summaries ( + conversation_id TEXT PRIMARY KEY, + title TEXT, + preview TEXT, + status TEXT, + source TEXT, + parent_conversation_id TEXT, + nesting_depth INTEGER, + agent_name TEXT, + not_fully_idle INTEGER, + killed INTEGER, + step_count INTEGER, + last_modified_time TEXT, + app_data_dir TEXT, + raw_summary BLOB + ); + CREATE TABLE conversation_parents (conversation_id TEXT, parent_id TEXT); + `); + const insSum = sumDb.prepare( + "INSERT INTO conversation_summaries (conversation_id, title, status, parent_conversation_id, step_count, last_modified_time, app_data_dir, raw_summary) VALUES (?, ?, 'CASCADE_RUN_STATUS_IDLE', '', 2, '2026-11-18T00:01:00Z', 'antigravity', ?)" + ); + insSum.run(cidDeleted, 'Deleted Precious Ledger Task', Buffer.alloc(0)); + insSum.run(cidLive, 'Surviving Live Task', Buffer.alloc(0)); + sumDb.close(); + + const createConvSqlite = (cid, promptText, inTok, outTok) => { + const p = join(convDir, `${cid}.db`); + const db = new DatabaseSync(p); + db.exec(` + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid); + db.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)').run( + Buffer.concat([ + encodeFieldBytes(1, encodeTimestamp(baseSec + 1)), + encodeFieldBytes(20, Buffer.concat([encodeFieldVarint(2, 0), encodeFieldBytes(4, cid)])), + ]), + encodeFieldBytes(19, encodeFieldBytes(2, promptText)) + ); + db.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)').run( + encodeStepMeta({ + createdSec: baseSec + 10, + finishedSec: baseSec + 15, + stepIndex: 1, + originCid: cid, + inputTokens: inTok, + outputTokens: outTok, + }), + encodeFieldBytes(20, encodeFieldBytes(1, 'Completed task')) + ); + db.close(); + return p; + }; + + const deletedDbFile = createConvSqlite(cidDeleted, 'Keep my billing forever', 100_000, 10_000); + const liveDbFile = createConvSqlite(cidLive, 'Still working on this', 50_000, 5_000); + + const apiUrl = new URL('../backend/api-actions.mjs', import.meta.url).href; + const telUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href; + const cfgUrl = new URL('../backend/config.mjs', import.meta.url).href; + + const script = ` + import { unlinkSync } from 'node:fs'; + import { executeRebuildCacheAction } from ${JSON.stringify(apiUrl)}; + import { buildTelemetryPayloadInternal } from ${JSON.stringify(telUrl)}; + import { flushTrajectoryCacheNow, getCachedTrajectory, getHydratedTrajectory } from ${JSON.stringify(cfgUrl)}; + const { DatabaseSync } = process.getBuiltinModule('node:sqlite'); + + // 1. Initial scan records both conversations in trajectory_store.sqlite + const before = await buildTelemetryPayloadInternal(${JSON.stringify(cidLive)}, { range: 'all' }); + flushTrajectoryCacheNow(); + const totalTokensBefore = before.consumption.account.totalTokens; + + // 2. Delete cidDeleted completely from Antigravity (.db + summary row), and add a step to cidLive! + unlinkSync(${JSON.stringify(deletedDbFile)}); + const sdb = new DatabaseSync(${JSON.stringify(sumDbPath)}); + sdb.prepare('DELETE FROM conversation_summaries WHERE conversation_id = ?').run(${JSON.stringify(cidDeleted)}); + sdb.close(); + + // 3. Click Rebuild Cache TWICE in a row! + const r1 = executeRebuildCacheAction(); + const r2 = executeRebuildCacheAction(); + + // 4. Rebuild telemetry & inspect both cidLive and deleted cidDeleted + const afterLive = await buildTelemetryPayloadInternal(${JSON.stringify(cidLive)}, { range: 'all' }); + const afterDeleted = await buildTelemetryPayloadInternal(${JSON.stringify(cidDeleted)}, { range: 'all' }); + flushTrajectoryCacheNow(); + + const cachedDeleted = getCachedTrajectory(${JSON.stringify(cidDeleted)}); + const hydratedDeleted = getHydratedTrajectory(${JSON.stringify(cidDeleted)}); + + console.log(JSON.stringify({ + r1Ok: r1.ok, + r2Ok: r2.ok, + totalTokensBefore, + totalTokensAfter: afterLive.consumption.account.totalTokens, + deletedArchivedFlag: Boolean(cachedDeleted?.archived), + deletedStepCount: hydratedDeleted?.steps?.length || 0, + deletedTurnPrompt: hydratedDeleted?.steps?.[0]?.turnPrompt || '', + deletedViewSteps: afterDeleted.activeConversation?.recentSteps?.length || 0, + })); + `; + + const { stdout } = await execFileAsync(process.execPath, ['--input-type=module', '-e', script], { + env: { + ...process.env, + ANTIGRAVITY_GEMINI_DIR: geminiDir, + ANTIGRAVITY_APP_DATA_DIR: '', + USAGE_MONITOR_APP_DATA_DIR: '', + ANTIGRAVITY_EXECUTABLE_DATA_DIR: dataDir, + ANTIGRAVITY_LS_ADDRESS: 'test.invalid', + }, + }); + + const out = JSON.parse(stdout.trim().split('\n').pop()); + assert.equal(out.r1Ok, true); + assert.equal(out.r2Ok, true); + // 100k + 10k (cidDeleted) + 50k + 5k (cidLive) = 165,000 tokens -> 100% preserved after deleting cidDeleted + 2x Rebuild Cache! + assert.equal(out.totalTokensBefore, 165_000); + assert.equal(out.totalTokensAfter, 165_000, 'deleted conversation tokens & cost permanently preserved'); + assert.equal(out.deletedArchivedFlag, true, 'deleted conversation marked archived'); + assert.equal(out.deletedStepCount, 1); + assert.equal(out.deletedTurnPrompt, 'Keep my billing forever', 'deleted conversation detail_json preserved'); + assert.equal(out.deletedViewSteps, 1, 'clicking archived deleted conversation still renders step details'); + assert.equal(existsSync(liveDbFile), true); +}); From e4e597931df5e85cf3158f64d663387e61c2ce51 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 13:53:12 +0900 Subject: [PATCH 11/30] fix(panel): use native browser downloads for standalone web exports - Gate /api/export-file and /api/reveal-file calls behind isHostEmbeddedWebview so standalone browser sessions invoke showSaveFilePicker or Blob downloads directly without expiring user activation - Reject /api/export-file, /api/reveal-file, and __exportFileAction requests in standalone-server.mjs so ssh -L tunnels and local reverse proxies never write files or spawn xdg-open on the server host --- sidecars/panel/app.js | 38 +++++++++---------- sidecars/panel/backend/standalone-server.mjs | 19 +++------- sidecars/panel/index.html | 4 +- sidecars/panel/src/core/fileExportClient.js | 38 +++++++++---------- .../test/practical-enhancements.test.mjs | 37 ++++++++++++++++++ sidecars/panel/test/window-bridge.test.mjs | 25 ++++++++++++ 6 files changed, 107 insertions(+), 54 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index bc1a20b..0c3efc3 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -8677,7 +8677,7 @@ function getPickerTypesForFilename(filename, mimeType) { * @returns {Promise} */ async function revealExportedFile(filePath) { - if (!filePath) return false; + if (!filePath || !isHostEmbeddedWebview()) return false; try { const res = await callSidecarApi('/api/reveal-file', { method: 'POST', @@ -8749,25 +8749,25 @@ async function runExportPipelineWithFeedback({ backendPayload, writablePayload, }) { - const { res: localRes } = await requestLocalBackendExport(backendPayload); - if (localRes && localRes.ok && localRes.filePath) { - const savedPath = String(localRes.filePath); - const savedName = String(localRes.fileName || safeName); - showUiToast({ - message: t('export.savedLocal', { file: savedName }), - detail: savedPath, - actionLabel: t('export.openFolder'), - onAction: () => { - void revealExportedFile(savedPath); - }, - tone: 'ok', - durationMs: 7000, - }); - return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName }; - } - - // 在 Antigravity Sidecar / 双栖 Electron 宿主内, 会被静默吞掉,绝不误报“已下载到浏览器” if (isHostEmbeddedWebview()) { + const { res: localRes } = await requestLocalBackendExport(backendPayload); + if (localRes && localRes.ok && localRes.filePath) { + const savedPath = String(localRes.filePath); + const savedName = String(localRes.fileName || safeName); + showUiToast({ + message: t('export.savedLocal', { file: savedName }), + detail: savedPath, + actionLabel: t('export.openFolder'), + onAction: () => { + void revealExportedFile(savedPath); + }, + tone: 'ok', + durationMs: 7000, + }); + return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName }; + } + + // 在 Antigravity Sidecar / 双栖 Electron 宿主内, 会被静默吞掉,绝不误报“已下载到浏览器” showUiToast({ message: t('export.failed'), detail: t('export.hostUnavailable'), diff --git a/sidecars/panel/backend/standalone-server.mjs b/sidecars/panel/backend/standalone-server.mjs index 9e2df9a..3cb0a92 100644 --- a/sidecars/panel/backend/standalone-server.mjs +++ b/sidecars/panel/backend/standalone-server.mjs @@ -21,7 +21,6 @@ import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs'; import { syncCloudCatalog } from './plugin-updater.mjs'; const MAX_JSON_BODY_BYTES = 1024 * 1024; -const MAX_EXPORT_JSON_BODY_BYTES = 8 * 1024 * 1024; const AUTH_COOKIE_NAME = 'ag_um_token'; const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate', @@ -512,10 +511,7 @@ export function createStandaloneWebServer(options = {}) { } if (pathname.startsWith('/api/')) { - if ( - (pathname === '/api/export-file' || pathname === '/api/reveal-file') && - !isLoopbackRemoteAddress(req.socket?.remoteAddress) - ) { + if (pathname === '/api/export-file' || pathname === '/api/reveal-file') { sendResponse( res, 403, @@ -523,7 +519,7 @@ export function createStandaloneWebServer(options = {}) { JSON.stringify({ ok: false, fallbackBrowser: true, - error: 'Local file export is restricted to loopback clients', + error: 'Standalone web mode uses browser file download instead of server disk export', }) ); return; @@ -533,11 +529,7 @@ export function createStandaloneWebServer(options = {}) { data = Object.fromEntries(urlObj.searchParams.entries()); delete data.token; } else if (method === 'POST') { - const maxBody = - pathname === '/api/export-file' || pathname === '/api/settings' - ? MAX_EXPORT_JSON_BODY_BYTES - : MAX_JSON_BODY_BYTES; - const rawBody = await readRawBody(req, maxBody); + const rawBody = await readRawBody(req, MAX_JSON_BODY_BYTES); if (rawBody.trim()) { try { data = JSON.parse(rawBody); @@ -557,8 +549,7 @@ export function createStandaloneWebServer(options = {}) { pathname === '/api/settings' && data && typeof data === 'object' && - typeof data.__exportFileAction === 'string' && - !isLoopbackRemoteAddress(req.socket?.remoteAddress) + typeof data.__exportFileAction === 'string' ) { sendResponse( res, @@ -567,7 +558,7 @@ export function createStandaloneWebServer(options = {}) { JSON.stringify({ ok: false, fallbackBrowser: true, - error: 'Local file export is restricted to loopback clients', + error: 'Standalone web mode uses browser file download instead of server disk export', }) ); return; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 9b4bd15..62aad77 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/core/fileExportClient.js b/sidecars/panel/src/core/fileExportClient.js index f071e1f..dad2b79 100644 --- a/sidecars/panel/src/core/fileExportClient.js +++ b/sidecars/panel/src/core/fileExportClient.js @@ -46,7 +46,7 @@ function getPickerTypesForFilename(filename, mimeType) { * @returns {Promise} */ export async function revealExportedFile(filePath) { - if (!filePath) return false; + if (!filePath || !isHostEmbeddedWebview()) return false; try { const res = await callSidecarApi('/api/reveal-file', { method: 'POST', @@ -118,25 +118,25 @@ async function runExportPipelineWithFeedback({ backendPayload, writablePayload, }) { - const { res: localRes } = await requestLocalBackendExport(backendPayload); - if (localRes && localRes.ok && localRes.filePath) { - const savedPath = String(localRes.filePath); - const savedName = String(localRes.fileName || safeName); - showUiToast({ - message: t('export.savedLocal', { file: savedName }), - detail: savedPath, - actionLabel: t('export.openFolder'), - onAction: () => { - void revealExportedFile(savedPath); - }, - tone: 'ok', - durationMs: 7000, - }); - return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName }; - } - - // 在 Antigravity Sidecar / 双栖 Electron 宿主内,
会被静默吞掉,绝不误报“已下载到浏览器” if (isHostEmbeddedWebview()) { + const { res: localRes } = await requestLocalBackendExport(backendPayload); + if (localRes && localRes.ok && localRes.filePath) { + const savedPath = String(localRes.filePath); + const savedName = String(localRes.fileName || safeName); + showUiToast({ + message: t('export.savedLocal', { file: savedName }), + detail: savedPath, + actionLabel: t('export.openFolder'), + onAction: () => { + void revealExportedFile(savedPath); + }, + tone: 'ok', + durationMs: 7000, + }); + return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName }; + } + + // 在 Antigravity Sidecar / 双栖 Electron 宿主内, 会被静默吞掉,绝不误报“已下载到浏览器” showUiToast({ message: t('export.failed'), detail: t('export.hostUnavailable'), diff --git a/sidecars/panel/test/practical-enhancements.test.mjs b/sidecars/panel/test/practical-enhancements.test.mjs index bf7652b..4505917 100644 --- a/sidecars/panel/test/practical-enhancements.test.mjs +++ b/sidecars/panel/test/practical-enhancements.test.mjs @@ -1919,6 +1919,9 @@ test('Feature 14: compact vertical ActionMenu replaces export bars, backend expo const { document } = createMockDom(); globalThis.document = document; globalThis.window = { + sidecar: { + fetch: (url, init) => globalThis.fetch(url, init), + }, addEventListener: () => {}, removeEventListener: () => {}, requestAnimationFrame: (cb) => { @@ -2102,6 +2105,40 @@ test('Feature 14: compact vertical ActionMenu replaces export bars, backend expo assert.equal(failedRes.ok, false); assert.equal(failedRes.mode, 'failed'); assert.equal(uiStore.getState().toast?.tone, 'warn'); + + // 7. Standalone browser mode (no window.sidecar and no window bridge) skips /api/export-file + // completely (even over ssh -L / loopback reverse proxy) and invokes native Save Picker directly + delete globalThis.window.sidecar; + let browserExportBackendCalled = false; + globalThis.fetch = async () => { + browserExportBackendCalled = true; + return { ok: true, status: 200, json: async () => ({ ok: true, filePath: '/remote/Downloads/leak.json' }) }; + }; + let pickedSuggestedName = ''; + let pickedWrittenPayload = null; + globalThis.window.showSaveFilePicker = async (opts) => { + pickedSuggestedName = opts?.suggestedName || ''; + return { + name: pickedSuggestedName, + createWritable: async () => ({ + write: async (data) => { + pickedWrittenPayload = data; + }, + close: async () => {}, + }), + }; + }; + const standalonePickerRes = await exportTextFileWithFeedback( + 'standalone-report.md', + '# Hello Browser\n', + 'text/markdown' + ); + assert.equal(browserExportBackendCalled, false, 'Standalone browser must NOT call /api/export-file'); + assert.equal(standalonePickerRes.ok, true); + assert.equal(standalonePickerRes.mode, 'picker'); + assert.equal(pickedSuggestedName, 'standalone-report.md'); + assert.equal(pickedWrittenPayload, '# Hello Browser\n'); + assert.equal(await revealExportedFile('/remote/Downloads/leak.json'), false); }); test('P0 regression: V4 display-projected steps open inspector, preserve waterfall/diagnostics/XLSX duration, match anomaly events, compute harmonic speed, and clean up UI observers/i18n', async (t) => { diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index ee78cb0..e91da06 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -4417,6 +4417,31 @@ test('Standalone Web server enforces loopback/non-loopback security boundaries, data: { range: 'today' }, }); + // Loopback ssh -L / reverse-proxy requests to /api/export-file, /api/reveal-file, and __exportFileAction return 403 fallbackBrowser + const blockedExport = await fetch(`${st.url}/api/export-file`, { + method: 'POST', + headers: { Origin: st.url, 'Content-Type': 'application/json' }, + body: JSON.stringify({ filename: 'leak.json', content: '{}' }), + }); + assert.equal(blockedExport.status, 403); + assert.equal((await blockedExport.json()).fallbackBrowser, true); + + const blockedReveal = await fetch(`${st.url}/api/reveal-file`, { + method: 'POST', + headers: { Origin: st.url, 'Content-Type': 'application/json' }, + body: JSON.stringify({ filePath: '/tmp/leak.json' }), + }); + assert.equal(blockedReveal.status, 403); + assert.equal((await blockedReveal.json()).fallbackBrowser, true); + + const blockedSettingsExport = await fetch(`${st.url}/api/settings`, { + method: 'POST', + headers: { Origin: st.url, 'Content-Type': 'application/json' }, + body: JSON.stringify({ __exportFileAction: 'save', payload: { filename: 'leak.json', content: '{}' } }), + }); + assert.equal(blockedSettingsExport.status, 403); + assert.equal((await blockedSettingsExport.json()).fallbackBrowser, true); + // Cross-site Origin blocked with 403 const crossSiteRes = await fetch(`${st.url}/api/telemetry`, { headers: { Origin: 'https://evil.example' }, From 030d8949883f2aab0429a95a8e56ff72c0b9abbc Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 14:37:49 +0900 Subject: [PATCH 12/30] fix(panel): harden CloudCode proxy tunnels, pooling, and crash recovery - Support SOCKS5/SOCKS5h (RFC 1928/1929 auth + IPv4/domain/IPv6 targets), authenticated HTTP/HTTPS CONNECT proxies, tunnel timeouts, and Windows /wildcard NO_PROXY rules without mangling non-HTTP schemes - Pool upstream TLS tunnels via a Keep-Alive HTTPS agent with explicit http/1.1 ALPN and hop-by-hop header stripping instead of re-handshaking per request - Attach upfront stream and socket error guards across passthrough and rewrite paths and tear down active upstream requests immediately on client disconnect - Persist sticky local proxy port and switched state in cloudcode-proxy-state.json to reuse ports across reloads and self-heal orphaned SetCloudCodeURL after unexpected exits --- sidecars/panel/backend/cloudcode-proxy.mjs | 693 +++++++++++++++++-- sidecars/panel/test/context-windows.test.mjs | 428 ++++++++++++ 2 files changed, 1047 insertions(+), 74 deletions(-) diff --git a/sidecars/panel/backend/cloudcode-proxy.mjs b/sidecars/panel/backend/cloudcode-proxy.mjs index a6e3d6b..3ac190b 100644 --- a/sidecars/panel/backend/cloudcode-proxy.mjs +++ b/sidecars/panel/backend/cloudcode-proxy.mjs @@ -10,7 +10,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import { homedir } from 'node:os'; import { join } from 'node:path'; -import { lsRuntimeEndpoint } from './config.mjs'; +import { DATA_DIR, loadJson, lsRuntimeEndpoint, saveJson } from './config.mjs'; import { callLsRpc } from './ls-rpc.mjs'; export const DEFAULT_UPSTREAM_CLOUDCODE_URL = 'https://daily-cloudcode-pa.googleapis.com'; @@ -21,6 +21,18 @@ const CC_PROXY_CHECKPOINTER_PREFIX = `${CC_PROXY_CHECKPOINTER_KEY}/`; const CC_PROXY_MAX_LOG_READ_BYTES = 512 * 1024; const CC_PROXY_RETRY_COOLDOWN_MS = 15_000; const CC_PROXY_SYS_PROXY_CACHE_MS = 15_000; +const CC_PROXY_DEFAULT_TUNNEL_TIMEOUT_MS = 15_000; +const CC_PROXY_AGENT_FREE_SOCKET_TIMEOUT_MS = 25_000; +const CC_PROXY_HOP_BY_HOP_HEADERS = [ + 'connection', + 'keep-alive', + 'proxy-connection', + 'proxy-authorization', + 'te', + 'trailer', + 'upgrade', +]; +const ccProxyNoopSocketError = () => {}; let ccProxyNodeModulesPromise = null; @@ -29,13 +41,15 @@ async function loadCcProxyNodeModules() { ccProxyNodeModulesPromise = Promise.all([ import('node:http'), import('node:https'), + import('node:net'), import('node:tls'), import('node:zlib'), import('node:child_process'), import('node:fs'), - ]).then(([httpMod, httpsMod, tlsMod, zlibMod, cpMod, fsMod]) => ({ + ]).then(([httpMod, httpsMod, netMod, tlsMod, zlibMod, cpMod, fsMod]) => ({ http: httpMod.default || httpMod, https: httpsMod.default || httpsMod, + net: netMod.default || netMod, tls: tlsMod.default || tlsMod, zlib: zlibMod.default || zlibMod, execFile: cpMod.execFile, @@ -154,15 +168,32 @@ export function detectUpstreamCloudCodeUrl({ return DEFAULT_UPSTREAM_CLOUDCODE_URL; } -function shouldCcProxyBypassHost(hostname, noProxyRaw) { - const target = String(hostname || '').trim().toLowerCase(); +export function shouldCcProxyBypassHost(hostname, noProxyRaw) { + const target = String(hostname || '').trim().toLowerCase().replace(/^\[|\]$/g, ''); const list = String(noProxyRaw || '').trim(); if (!target || !list) return false; - for (const part of list.split(/[;,]/)) { + for (const part of list.split(/[;,\s]+/)) { const raw = part.trim().toLowerCase(); if (!raw) continue; if (raw === '*') return true; - const rule = raw.replace(/^\*\./, '.').replace(/:\d+$/, ''); + if (raw === '') { + if (isCcProxyLoopbackHost(target) || (!target.includes('.') && !target.includes(':'))) { + return true; + } + continue; + } + const strippedPort = raw.startsWith('[') + ? raw.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1') + : raw.includes(':') && raw.indexOf(':') === raw.lastIndexOf(':') + ? raw.replace(/:\d+$/, '') + : raw; + if (!strippedPort) continue; + if (strippedPort.includes('*') && !(strippedPort.startsWith('*.') && !strippedPort.slice(2).includes('*'))) { + const pattern = `^${strippedPort.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`; + if (new RegExp(pattern, 'i').test(target)) return true; + continue; + } + const rule = strippedPort.replace(/^\*\./, '.'); if (!rule) continue; if (rule.startsWith('.')) { if (target.endsWith(rule) || target === rule.slice(1)) return true; @@ -173,18 +204,48 @@ function shouldCcProxyBypassHost(hostname, noProxyRaw) { return false; } +export function normalizeCcProxyCandidateUrl(rawVal) { + let s = String(rawVal || '').trim(); + if (!s) return ''; + if (/^socks:\/\//i.test(s)) { + s = `socks5://${s.slice('socks://'.length)}`; + } + const hasExplicitScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(s); + if (hasExplicitScheme && !/^(?:https?|socks5h?):\/\//i.test(s)) { + return ''; + } + const candidate = hasExplicitScheme ? s : `http://${s}`; + try { + const parsed = new URL(candidate); + if (!parsed.hostname) return ''; + if (parsed.port) { + const p = Number(parsed.port); + if (!Number.isInteger(p) || p <= 0 || p > 65535) return ''; + } + return candidate; + } catch { + return ''; + } +} + function parseWindowsProxyServerValue(rawVal) { - let srv = String(rawVal || '').trim(); + const srv = String(rawVal || '').trim(); if (!srv) return ''; if (srv.includes('=')) { const parts = srv.split(';').map((p) => p.trim()).filter(Boolean); const httpsPart = parts.find((p) => p.toLowerCase().startsWith('https=')); const httpPart = parts.find((p) => p.toLowerCase().startsWith('http=')); - const chosen = httpsPart || httpPart || ''; - srv = chosen.slice(chosen.indexOf('=') + 1).trim(); + const socksPart = parts.find((p) => p.toLowerCase().startsWith('socks=')); + const chosen = httpsPart || httpPart || socksPart || ''; + if (!chosen) return ''; + const rawHostPort = chosen.slice(chosen.indexOf('=') + 1).trim(); + if (!rawHostPort) return ''; + if (chosen === socksPart && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(rawHostPort)) { + return normalizeCcProxyCandidateUrl(`socks5://${rawHostPort}`); + } + return normalizeCcProxyCandidateUrl(rawHostPort); } - if (!srv) return ''; - return /^https?:\/\//i.test(srv) ? srv : `http://${srv}`; + return normalizeCcProxyCandidateUrl(srv); } let winRegProxyMemo = { @@ -231,10 +292,16 @@ async function readWindowsInternetSettingsAsync() { export async function detectSystemHttpsProxy(targetHostname = '', { env = process.env, platform = process.platform } = {}) { const noProxy = env?.NO_PROXY || env?.no_proxy || ''; if (shouldCcProxyBypassHost(targetHostname, noProxy)) return ''; - const envProxy = String( - env?.HTTPS_PROXY || env?.https_proxy || env?.ALL_PROXY || env?.all_proxy || '' - ).trim(); - if (envProxy) return /^https?:\/\//i.test(envProxy) ? envProxy : `http://${envProxy}`; + const envCandidates = [ + env?.HTTPS_PROXY, + env?.https_proxy, + env?.ALL_PROXY, + env?.all_proxy, + ]; + for (const rawCandidate of envCandidates) { + const normalized = normalizeCcProxyCandidateUrl(rawCandidate); + if (normalized) return normalized; + } if (platform !== 'win32') return ''; try { const out = await readWindowsInternetSettingsAsync(); @@ -410,28 +477,311 @@ function decompressCcProxyBody(zlib, buf, encoding) { return buf; } -function openCcProxyTunnelSocket(http, tls, targetHost, targetPort, proxyUrl) { - if (!proxyUrl) return Promise.resolve(null); - const parsedProxy = new URL(proxyUrl); +function ccProxySafeDecodeUriPart(raw) { + if (!raw) return ''; + try { + return decodeURIComponent(raw); + } catch { + return String(raw); + } +} + +function ccProxyReadExactBytes(socket, count) { return new Promise((resolve, reject) => { - const connectReq = http.request({ - host: parsedProxy.hostname, - port: Number(parsedProxy.port || (parsedProxy.protocol === 'https:' ? 443 : 80)), - method: 'CONNECT', - path: `${targetHost}:${targetPort}`, - headers: { Host: `${targetHost}:${targetPort}` }, + let acc = Buffer.alloc(0); + const cleanup = () => { + socket.off('data', onData); + socket.off('error', onErr); + socket.off('close', onClose); + socket.off('end', onClose); + }; + const onErr = (err) => { + cleanup(); + reject(err); + }; + const onClose = () => { + cleanup(); + reject(new Error('SOCKS5 proxy closed connection prematurely')); + }; + const onData = (chunk) => { + acc = acc.length === 0 ? chunk : Buffer.concat([acc, chunk]); + if (acc.length >= count) { + cleanup(); + socket.pause(); + const needed = acc.subarray(0, count); + const rest = acc.subarray(count); + if (rest.length > 0) { + socket.unshift(rest); + } + resolve(needed); + } + }; + socket.on('data', onData); + socket.once('error', onErr); + socket.once('close', onClose); + socket.once('end', onClose); + socket.resume(); + }); +} + +function ccProxyEncodeIpv6Bytes(ipv6Str) { + let host = String(ipv6Str || '').trim().replace(/^\[|\]$/g, ''); + const zoneIdx = host.indexOf('%'); + if (zoneIdx !== -1) host = host.slice(0, zoneIdx); + const lastColon = host.lastIndexOf(':'); + if (lastColon !== -1 && host.slice(lastColon + 1).includes('.')) { + const v4Parts = host + .slice(lastColon + 1) + .split('.') + .map((n) => Number(n)); + if (v4Parts.length !== 4 || v4Parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) { + return null; + } + const hi = ((v4Parts[0] << 8) | v4Parts[1]).toString(16); + const lo = ((v4Parts[2] << 8) | v4Parts[3]).toString(16); + host = `${host.slice(0, lastColon)}:${hi}:${lo}`; + } + const dblParts = host.split('::'); + if (dblParts.length > 2) return null; + const left = dblParts[0] ? dblParts[0].split(':') : []; + const right = dblParts.length === 2 && dblParts[1] ? dblParts[1].split(':') : []; + const missing = 8 - (left.length + right.length); + if (dblParts.length === 1 ? left.length !== 8 : missing < 1) return null; + const groups = dblParts.length === 2 ? [...left, ...new Array(missing).fill('0'), ...right] : left; + if (groups.length !== 8) return null; + const buf = Buffer.allocUnsafe(16); + for (let i = 0; i < 8; i += 1) { + const val = Number.parseInt(groups[i], 16); + if (!Number.isInteger(val) || val < 0 || val > 0xffff) return null; + buf.writeUInt16BE(val, i * 2); + } + return buf; +} + +async function ccProxyConnectSocks5Socket(net, parsedProxy, targetHost, targetPort) { + const proxyHost = parsedProxy.hostname.replace(/^\[|\]$/g, ''); + const proxyPort = Number(parsedProxy.port || 1080); + const rawUser = ccProxySafeDecodeUriPart(parsedProxy.username); + const rawPass = ccProxySafeDecodeUriPart(parsedProxy.password); + const hasAuth = Boolean(rawUser || rawPass); + + const socket = await new Promise((resolve, reject) => { + const s = net.connect({ host: proxyHost, port: proxyPort }); + const onErr = (err) => { + s.destroy(); + reject(err); + }; + s.once('error', onErr); + s.once('connect', () => { + s.off('error', onErr); + s.on('error', ccProxyNoopSocketError); + resolve(s); }); - connectReq.on('connect', (res, socket) => { - if (res.statusCode !== 200) { + }); + + try { + // 1. Method negotiation (RFC 1928) + const greeting = hasAuth + ? Buffer.from([0x05, 0x02, 0x00, 0x02]) + : Buffer.from([0x05, 0x01, 0x00]); + socket.write(greeting); + const methodReply = await ccProxyReadExactBytes(socket, 2); + if (methodReply[0] !== 0x05 || methodReply[1] === 0xff) { + throw new Error('SOCKS5 proxy rejected authentication methods'); + } + if (methodReply[1] === 0x02) { + if (!hasAuth) { + throw new Error('SOCKS5 proxy requires username/password authentication'); + } + const userBuf = Buffer.from(rawUser, 'utf8'); + const passBuf = Buffer.from(rawPass, 'utf8'); + if (userBuf.length > 255 || passBuf.length > 255) { + throw new Error('SOCKS5 credentials exceed 255 bytes'); + } + const authReq = Buffer.concat([ + Buffer.from([0x01, userBuf.length]), + userBuf, + Buffer.from([passBuf.length]), + passBuf, + ]); + socket.write(authReq); + const authReply = await ccProxyReadExactBytes(socket, 2); + if (authReply[1] !== 0x00) { + throw new Error('SOCKS5 username/password authentication failed'); + } + } else if (methodReply[1] !== 0x00) { + throw new Error(`Unsupported SOCKS5 auth method (${methodReply[1]})`); + } + + // 2. CONNECT targetHost:targetPort + const cleanHost = String(targetHost || '').replace(/^\[|\]$/g, ''); + const ipVer = net.isIP(cleanHost); + let addrPart; + if (ipVer === 4) { + const octets = cleanHost.split('.').map((n) => Number(n)); + addrPart = Buffer.from([0x01, octets[0], octets[1], octets[2], octets[3]]); + } else if (ipVer === 6) { + const ipv6Bytes = ccProxyEncodeIpv6Bytes(cleanHost); + if (!ipv6Bytes) { + throw new Error('Invalid SOCKS5 target IPv6 address'); + } + addrPart = Buffer.concat([Buffer.from([0x04]), ipv6Bytes]); + } else { + const hostBuf = Buffer.from(cleanHost, 'utf8'); + if (hostBuf.length === 0 || hostBuf.length > 255) { + throw new Error('Invalid SOCKS5 target hostname'); + } + addrPart = Buffer.concat([Buffer.from([0x03, hostBuf.length]), hostBuf]); + } + const portBuf = Buffer.allocUnsafe(2); + portBuf.writeUInt16BE(Number(targetPort), 0); + socket.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), addrPart, portBuf])); + + const repHead = await ccProxyReadExactBytes(socket, 4); + if (repHead[0] !== 0x05 || repHead[1] !== 0x00) { + throw new Error(`SOCKS5 CONNECT failed (code ${repHead[1]})`); + } + const atyp = repHead[3]; + if (atyp === 0x01) { + await ccProxyReadExactBytes(socket, 4 + 2); + } else if (atyp === 0x03) { + const lenBuf = await ccProxyReadExactBytes(socket, 1); + await ccProxyReadExactBytes(socket, lenBuf[0] + 2); + } else if (atyp === 0x04) { + await ccProxyReadExactBytes(socket, 16 + 2); + } else { + throw new Error(`Unsupported SOCKS5 reply address type (${atyp})`); + } + socket.resume(); + return socket; + } catch (err) { + socket.destroy(); + throw err; + } +} + +export function openCcProxyTunnelSocket( + mods, + targetHost, + targetPort, + proxyUrl, + { timeoutMs = CC_PROXY_DEFAULT_TUNNEL_TIMEOUT_MS, tlsOptions = null } = {} +) { + const normalizedUrl = normalizeCcProxyCandidateUrl(proxyUrl); + if (!normalizedUrl) return Promise.resolve(null); + const parsedProxy = new URL(normalizedUrl); + const { http, https, net, tls } = mods; + const cleanTargetHost = String(targetHost || '').replace(/^\[|\]$/g, ''); + const sniOpts = net && net.isIP(cleanTargetHost) !== 0 ? {} : { servername: cleanTargetHost }; + const connectAuthority = cleanTargetHost.includes(':') + ? `[${cleanTargetHost}]:${targetPort}` + : `${cleanTargetHost}:${targetPort}`; + + return new Promise((resolve, reject) => { + let settled = false; + let connectReq = null; + let rawSocket = null; + let tlsSocket = null; + + const timer = + Number.isFinite(timeoutMs) && timeoutMs > 0 + ? setTimeout(() => { + fail(new Error(`Proxy tunnel timed out after ${timeoutMs}ms`)); + }, timeoutMs) + : null; + timer?.unref?.(); + + function cleanupTimer() { + if (timer) clearTimeout(timer); + } + + function fail(err) { + if (settled) return; + settled = true; + cleanupTimer(); + try { + connectReq?.destroy(); + } catch {} + try { + tlsSocket?.destroy(); + } catch {} + try { + rawSocket?.destroy(); + } catch {} + reject(err); + } + + function upgradeToTls(sock, headBuf = null) { + rawSocket = sock; + sock.on('error', ccProxyNoopSocketError); + if (headBuf && headBuf.length > 0) { + sock.unshift(headBuf); + } + tlsSocket = tls.connect({ + socket: sock, + ALPNProtocols: ['http/1.1'], + ...sniOpts, + ...(tlsOptions && typeof tlsOptions === 'object' ? tlsOptions : {}), + }); + tlsSocket.on('error', ccProxyNoopSocketError); + tlsSocket.once('secureConnect', () => { + if (settled) { + tlsSocket.destroy(); + return; + } + settled = true; + cleanupTimer(); + tlsSocket.off('error', fail); + resolve(tlsSocket); + }); + tlsSocket.once('error', fail); + } + + const proto = parsedProxy.protocol.toLowerCase(); + if (proto === 'socks5:' || proto === 'socks5h:') { + ccProxyConnectSocks5Socket(net, parsedProxy, cleanTargetHost, targetPort) + .then((sock) => { + if (settled) { + sock.destroy(); + return; + } + upgradeToTls(sock); + }) + .catch(fail); + return; + } + + const isHttpsProxy = proto === 'https:'; + const proxyTransport = isHttpsProxy ? https : http; + const headers = { Host: connectAuthority }; + if (parsedProxy.username || parsedProxy.password) { + const user = ccProxySafeDecodeUriPart(parsedProxy.username); + const pass = ccProxySafeDecodeUriPart(parsedProxy.password); + const token = Buffer.from(`${user}:${pass}`, 'utf8').toString('base64'); + headers['Proxy-Authorization'] = `Basic ${token}`; + } + + connectReq = proxyTransport.request({ + hostname: parsedProxy.hostname.replace(/^\[|\]$/g, ''), + port: Number(parsedProxy.port || (isHttpsProxy ? 443 : 80)), + method: 'CONNECT', + path: connectAuthority, + headers, + }); + connectReq.on('connect', (res, socket, head) => { + socket.on('error', ccProxyNoopSocketError); + if (settled) { socket.destroy(); - reject(new Error(`Proxy CONNECT failed (${res.statusCode})`)); return; } - const tlsSocket = tls.connect({ socket, servername: targetHost }); - tlsSocket.once('secureConnect', () => resolve(tlsSocket)); - tlsSocket.once('error', reject); + if (res.statusCode !== 200) { + socket.destroy(); + fail(new Error(`Proxy CONNECT failed (${res.statusCode})`)); + return; + } + upgradeToTls(socket, head); }); - connectReq.on('error', reject); + connectReq.on('error', fail); connectReq.end(); }); } @@ -449,17 +799,25 @@ export function createCloudCodeProxyController({ allowHttpUpstream = false, allowTestEndpoint = false, retryCooldownMs = CC_PROXY_RETRY_COOLDOWN_MS, + tunnelTimeoutMs = CC_PROXY_DEFAULT_TUNNEL_TIMEOUT_MS, + upstreamTlsOptions = null, + stateFilePath = '', + loadJsonFn = loadJson, + saveJsonFn = saveJson, } = {}) { let server = null; let localUrl = ''; + let preferredPort = 0; let upstreamUrl = ''; let lsSwitched = false; + let stateHydratedOnce = false; let activeRules = {}; let upstreamDefaults = {}; let appliedSig = ''; let lastFailedSig = ''; let lastErrorAtMs = 0; let cachedSysProxy = { url: '', checkedAtMs: 0, host: '' }; + let activeAgentEntry = null; let syncChain = Promise.resolve(); let status = { @@ -473,6 +831,99 @@ export function createCloudCodeProxyController({ error: '', }; + function hydratePersistedStateOnce() { + if (stateHydratedOnce) return; + stateHydratedOnce = true; + if (!stateFilePath || typeof loadJsonFn !== 'function') return; + try { + const saved = loadJsonFn(stateFilePath, null); + if (!saved || typeof saved !== 'object') return; + const savedPort = Number(saved.localPort || 0); + if (Number.isInteger(savedPort) && savedPort > 0 && savedPort <= 65535) { + preferredPort = savedPort; + } + const savedUpstream = String(saved.upstreamUrl || '').trim(); + if ( + savedUpstream && + !upstreamUrl && + isValidUpstreamCloudCodeUrl(savedUpstream, { allowHttp: allowHttpUpstream }) + ) { + upstreamUrl = savedUpstream.replace(/\/+$/, ''); + } + if (saved.switched === true) { + lsSwitched = true; + } + } catch { + // 忽略损坏的状态快照 + } + } + + function persistProxyStateSnapshot(switchedFlag) { + if (!stateFilePath || typeof saveJsonFn !== 'function') return; + try { + saveJsonFn(stateFilePath, { + switched: Boolean(switchedFlag), + localPort: preferredPort > 0 ? preferredPort : undefined, + localUrl: switchedFlag && localUrl ? localUrl : undefined, + upstreamUrl: upstreamUrl || DEFAULT_UPSTREAM_CLOUDCODE_URL, + updatedAtMs: Date.now(), + }); + } catch { + // 忽略持久化状态异常 + } + } + + function destroyActiveUpstreamAgent() { + if (!activeAgentEntry) return; + const prevAgent = activeAgentEntry.agent; + activeAgentEntry = null; + try { + prevAgent?.destroy?.(); + } catch { + // 忽略连接池销毁异常 + } + } + + function getPooledUpstreamAgent(mods, isUpstreamHttps, upstreamHost, upstreamPort, proxyUrl) { + const cleanProxy = isUpstreamHttps ? String(proxyUrl || '') : ''; + const key = `${isUpstreamHttps ? 'https' : 'http'}|${upstreamHost}:${upstreamPort}|${cleanProxy || 'direct'}`; + if (activeAgentEntry && activeAgentEntry.key === key) { + return activeAgentEntry.agent; + } + destroyActiveUpstreamAgent(); + + const baseAgentOpts = { + keepAlive: true, + keepAliveMsecs: 10_000, + maxSockets: 32, + maxFreeSockets: 4, + timeout: CC_PROXY_AGENT_FREE_SOCKET_TIMEOUT_MS, + ...(isUpstreamHttps && upstreamTlsOptions ? upstreamTlsOptions : {}), + }; + + let agent; + if (isUpstreamHttps && cleanProxy) { + class CcProxyTunnelHttpsAgent extends mods.https.Agent { + createConnection(_opts, callback) { + openCcProxyTunnelSocket(mods, upstreamHost, upstreamPort, cleanProxy, { + timeoutMs: tunnelTimeoutMs, + tlsOptions: upstreamTlsOptions, + }).then( + (tlsSock) => callback(null, tlsSock), + (err) => callback(err) + ); + return null; + } + } + agent = new CcProxyTunnelHttpsAgent(baseAgentOpts); + } else { + const AgentCtor = isUpstreamHttps ? mods.https.Agent : mods.http.Agent; + agent = new AgentCtor(baseAgentOpts); + } + activeAgentEntry = { key, agent }; + return agent; + } + function getStatus() { return { ...status, @@ -523,7 +974,8 @@ export function createCloudCodeProxyController({ } let proxyUrl = ''; if (typeof detectProxyFn === 'function') { - proxyUrl = String((await detectProxyFn(targetHostname)) || '').trim(); + const rawDetected = String((await detectProxyFn(targetHostname)) || '').trim(); + proxyUrl = normalizeCcProxyCandidateUrl(rawDetected); } else { proxyUrl = await detectSystemHttpsProxy(targetHostname); } @@ -532,6 +984,7 @@ export function createCloudCodeProxyController({ } async function closeProxyServer() { + destroyActiveUpstreamAgent(); const srv = server; server = null; localUrl = ''; @@ -552,7 +1005,8 @@ export function createCloudCodeProxyController({ async function ensureProxyServerStarted() { if (server && localUrl) return localUrl; - const { http, https, tls, zlib } = await loadCcProxyNodeModules(); + const mods = await loadCcProxyNodeModules(); + const { http, https, zlib } = mods; const targetBase = await resolveUpstreamUrl(); const upstreamParsed = new URL(targetBase); const isUpstreamHttps = upstreamParsed.protocol === 'https:'; @@ -561,38 +1015,79 @@ export function createCloudCodeProxyController({ const srv = http.createServer(async (req, res) => { const reqUrl = req.url || '/'; const isFetchModels = reqUrl.includes('fetchAvailableModels'); + let clientAborted = false; + let activeUpReq = null; + let activeUpRes = null; + + const abortUpstreamOnClientDisconnect = () => { + if (res.writableEnded) return; + clientAborted = true; + try { + activeUpRes?.destroy(); + } catch {} + try { + activeUpReq?.destroy(); + } catch {} + }; + req.once('aborted', abortUpstreamOnClientDisconnect); + res.once('close', abortUpstreamOnClientDisconnect); + req.on('error', abortUpstreamOnClientDisconnect); + res.on('error', abortUpstreamOnClientDisconnect); + try { const fwdHeaders = { ...req.headers, host: upstreamParsed.host }; + for (const hopKey of CC_PROXY_HOP_BY_HOP_HEADERS) { + delete fwdHeaders[hopKey]; + } if (isFetchModels) { delete fwdHeaders['accept-encoding']; } - let customSocket = null; - if (isUpstreamHttps) { - const proxyUrl = await resolveSystemProxyForHost(upstreamParsed.hostname); - if (proxyUrl) { - customSocket = await openCcProxyTunnelSocket( - http, - tls, - upstreamParsed.hostname, - upstreamPort, - proxyUrl - ); - } + const proxyUrl = isUpstreamHttps + ? await resolveSystemProxyForHost(upstreamParsed.hostname) + : ''; + if (clientAborted || req.destroyed || res.destroyed || res.writableEnded) { + return; } + const agent = getPooledUpstreamAgent( + mods, + isUpstreamHttps, + upstreamParsed.hostname, + upstreamPort, + proxyUrl + ); const upOpts = { hostname: upstreamParsed.hostname, port: upstreamPort, path: reqUrl, method: req.method, headers: fwdHeaders, - ...(customSocket ? { agent: false, createConnection: () => customSocket } : {}), + agent, + ...(isUpstreamHttps && upstreamTlsOptions ? upstreamTlsOptions : {}), }; req.setTimeout?.(0); const transport = isUpstreamHttps ? https : http; const upReq = transport.request(upOpts, (upRes) => { + activeUpRes = upRes; + upRes.on('error', (err) => { + if (clientAborted || res.destroyed || res.writableEnded) return; + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' }); + res.end(`Upstream stream error: ${err.message}`); + } else { + res.destroy(); + } + }); + if (clientAborted || res.destroyed || res.writableEnded) { + upRes.destroy(); + return; + } if (!isFetchModels || Number(upRes.statusCode || 0) !== 200) { - res.writeHead(upRes.statusCode || 502, upRes.headers); + const passthroughHeaders = { ...upRes.headers }; + for (const hopKey of CC_PROXY_HOP_BY_HOP_HEADERS) { + delete passthroughHeaders[hopKey]; + } + res.writeHead(upRes.statusCode || 502, passthroughHeaders); res.flushHeaders?.(); upRes.pipe(res); return; @@ -600,9 +1095,13 @@ export function createCloudCodeProxyController({ const chunks = []; upRes.on('data', (chunk) => chunks.push(chunk)); upRes.on('end', () => { + if (clientAborted || res.destroyed || res.writableEnded) return; const rawBuf = Buffer.concat(chunks); let outBuf = rawBuf; const outHeaders = { ...upRes.headers }; + for (const hopKey of CC_PROXY_HOP_BY_HOP_HEADERS) { + delete outHeaders[hopKey]; + } try { const plain = decompressCcProxyBody(zlib, rawBuf, upRes.headers['content-encoding']); const parsed = JSON.parse(plain.toString('utf8')); @@ -627,52 +1126,86 @@ export function createCloudCodeProxyController({ res.writeHead(upRes.statusCode || 200, outHeaders); res.end(outBuf); }); - upRes.on('error', (err) => { - if (!res.headersSent) res.writeHead(502); - res.end(`Upstream stream error: ${err.message}`); - }); }); + activeUpReq = upReq; upReq.setTimeout?.(0); upReq.on('error', (err) => { - if (!res.headersSent) res.writeHead(502); - res.end(`Proxy upstream error: ${err.message}`); + if (clientAborted || res.destroyed || res.writableEnded) return; + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' }); + res.end(`Proxy upstream error: ${err.message}`); + } else { + res.destroy(); + } }); req.pipe(upReq); } catch (err) { - if (!res.headersSent) res.writeHead(502); - res.end(`Proxy setup error: ${err.message}`); + if (clientAborted || res.destroyed || res.writableEnded) return; + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' }); + res.end(`Proxy setup error: ${err.message}`); + } else { + res.destroy(); + } } }); - await new Promise((resolve, reject) => { - srv.once('error', reject); - srv.listen(0, '127.0.0.1', () => { - srv.off('error', reject); - resolve(); + const tryListenOnPort = (candidatePort) => + new Promise((resolve, reject) => { + const onErr = (err) => { + srv.off('listening', onListening); + reject(err); + }; + const onListening = () => { + srv.off('error', onErr); + resolve(); + }; + srv.once('error', onErr); + srv.once('listening', onListening); + srv.listen(candidatePort, '127.0.0.1'); }); - }); + + if (preferredPort > 0) { + try { + await tryListenOnPort(preferredPort); + } catch { + await tryListenOnPort(0); + } + } else { + await tryListenOnPort(0); + } + srv.unref?.(); const addrInfo = srv.address(); const port = typeof addrInfo === 'object' && addrInfo ? Number(addrInfo.port || 0) : 0; + if (port > 0) { + preferredPort = port; + } server = srv; localUrl = `http://127.0.0.1:${port}`; return localUrl; } - async function restoreLsCloudCodeUrl() { - if (!lsSwitched) return; - lsSwitched = false; + async function restoreLsCloudCodeUrl({ timeoutMs = 4000, clearEvenOnFailure = false } = {}) { + if (!lsSwitched) return true; appliedSig = ''; - const targetRestore = upstreamUrl || DEFAULT_UPSTREAM_CLOUDCODE_URL; + const targetRestore = (await resolveUpstreamUrl().catch(() => '')) || DEFAULT_UPSTREAM_CLOUDCODE_URL; try { - await callRpcFn('SetCloudCodeURL', { url: targetRestore }, 4000); + await callRpcFn('SetCloudCodeURL', { url: targetRestore }, timeoutMs); + lsSwitched = false; + persistProxyStateSnapshot(false); + return true; } catch { - // 忽略 LS 已退出或暂不可达时的还原异常 + if (clearEvenOnFailure) { + lsSwitched = false; + } + return false; } } async function reconcileInternal({ enabled = false, rulesByModelId = {}, initialCatalogModels = null } = {}) { + hydratePersistedStateOnce(); if (initialCatalogModels) { seedUpstreamDefaultsFromCatalog(initialCatalogModels); } @@ -687,11 +1220,9 @@ export function createCloudCodeProxyController({ activeRules = {}; lastFailedSig = ''; lastErrorAtMs = 0; + appliedSig = ''; if (lsSwitched && hasUsableLs) { - await restoreLsCloudCodeUrl(); - } else { - lsSwitched = false; - appliedSig = ''; + await restoreLsCloudCodeUrl({ timeoutMs: 3000 }); } await closeProxyServer(); status = { @@ -742,11 +1273,13 @@ export function createCloudCodeProxyController({ try { const targetUpstream = await resolveUpstreamUrl(); const listenUrl = await ensureProxyServerStarted(); + persistProxyStateSnapshot(true); await callRpcFn('SetCloudCodeURL', { url: listenUrl }, 5000); lsSwitched = true; appliedSig = desiredSig; lastFailedSig = ''; lastErrorAtMs = 0; + persistProxyStateSnapshot(true); status = { state: 'active', active: true, @@ -761,6 +1294,7 @@ export function createCloudCodeProxyController({ lastFailedSig = desiredSig; lastErrorAtMs = Date.now(); if (!lsSwitched) { + persistProxyStateSnapshot(false); await closeProxyServer(); } status = { @@ -785,17 +1319,18 @@ export function createCloudCodeProxyController({ function stop() { syncChain = syncChain .then(async () => { + hydratePersistedStateOnce(); activeRules = {}; lastFailedSig = ''; lastErrorAtMs = 0; + appliedSig = ''; const ep = getEndpointFn() || {}; const hasUsableLs = Boolean(ep.baseUrl) && (allowTestEndpoint || String(ep.addr || '') !== 'test.invalid'); if (lsSwitched && hasUsableLs) { - await restoreLsCloudCodeUrl(); + await restoreLsCloudCodeUrl({ timeoutMs: 900, clearEvenOnFailure: true }); } else { lsSwitched = false; - appliedSig = ''; } await closeProxyServer(); status = { @@ -823,11 +1358,21 @@ export function createCloudCodeProxyController({ }; } +function resolveDefaultCloudCodeProxyStatePath() { + const normDir = String(DATA_DIR || '').replace(/\\/g, '/'); + if (!normDir || normDir.startsWith('/test/') || normDir.startsWith('/test-home/')) { + return ''; + } + return join(DATA_DIR, 'cloudcode-proxy-state.json'); +} + let defaultCloudCodeProxyController = null; export function getDefaultCloudCodeProxy() { if (!defaultCloudCodeProxyController) { - defaultCloudCodeProxyController = createCloudCodeProxyController(); + defaultCloudCodeProxyController = createCloudCodeProxyController({ + stateFilePath: resolveDefaultCloudCodeProxyStatePath(), + }); } return defaultCloudCodeProxyController; } diff --git a/sidecars/panel/test/context-windows.test.mjs b/sidecars/panel/test/context-windows.test.mjs index 297a2f4..5ed3ac8 100644 --- a/sidecars/panel/test/context-windows.test.mjs +++ b/sidecars/panel/test/context-windows.test.mjs @@ -1,13 +1,21 @@ import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; import http from 'node:http'; +import https from 'node:https'; +import net from 'node:net'; import test from 'node:test'; +import tls from 'node:tls'; import vm from 'node:vm'; import { createContextWindowSyncExpression } from '../backend/context-windows.mjs'; import { createCloudCodeProxyController, + detectSystemHttpsProxy, extractUpstreamCheckpointDefaults, isValidUpstreamCloudCodeUrl, + normalizeCcProxyCandidateUrl, + openCcProxyTunnelSocket, rewriteFetchAvailableModelsPayload, + shouldCcProxyBypassHost, } from '../backend/cloudcode-proxy.mjs'; import { createWindowBridgeController } from '../backend/window-bridge.mjs'; import { backendHarness } from './backend-harness.mjs'; @@ -784,3 +792,423 @@ test('SettingsOtherTab renders independent Main Agent and Subagents/Swarm switch globalThis.fetch = origFetch; } }); + +function createSelfSignedTlsFixture() { + const derLen = (len) => { + if (len < 0x80) return Buffer.from([len]); + const hex = len.toString(16).padStart(len > 0xff ? 4 : 2, '0'); + const bytes = Buffer.from(hex, 'hex'); + return Buffer.concat([Buffer.from([0x80 | bytes.length]), bytes]); + }; + const asn1 = (tag, body) => Buffer.concat([Buffer.from([tag]), derLen(body.length), body]); + const seq = (...items) => asn1(0x30, Buffer.concat(items)); + const set = (...items) => asn1(0x31, Buffer.concat(items)); + + const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { + namedCurve: 'prime256v1', + }); + const spkiDer = publicKey.export({ type: 'spki', format: 'der' }); + // ecdsa-with-SHA256 (1.2.840.10045.4.3.2) + const sigAlg = seq(Buffer.from([0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02])); + const cnAttr = seq( + Buffer.from([0x06, 0x03, 0x55, 0x04, 0x03]), + asn1(0x0c, Buffer.from('localhost', 'utf8')) + ); + const name = seq(set(cnAttr)); + const validity = seq( + asn1(0x17, Buffer.from('250101000000Z', 'ascii')), + asn1(0x17, Buffer.from('350101000000Z', 'ascii')) + ); + const tbs = seq( + asn1(0xa0, Buffer.from([0x02, 0x01, 0x02])), + asn1(0x02, Buffer.from([0x01])), + sigAlg, + name, + validity, + name, + spkiDer + ); + const sig = crypto.sign('sha256', tbs, privateKey); + const certDer = seq(tbs, sigAlg, asn1(0x03, Buffer.concat([Buffer.from([0x00]), sig]))); + const certPem = `-----BEGIN CERTIFICATE-----\n${certDer.toString('base64').match(/.{1,64}/g).join('\n')}\n-----END CERTIFICATE-----\n`; + const keyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }); + return { key: keyPem, cert: certPem }; +} + +test('cloudcode-proxy handles socks5:// and authenticated HTTP/HTTPS proxies, enforces tunnel timeouts, and destroys upstream requests on client abort', async () => { + // 1. Proxy URL normalization & environment detection (no http://socks5://... mangling!) + assert.equal(normalizeCcProxyCandidateUrl('socks5://127.0.0.1:1080'), 'socks5://127.0.0.1:1080'); + assert.equal( + normalizeCcProxyCandidateUrl('socks5h://dev:p%40ss@127.0.0.1:1080'), + 'socks5h://dev:p%40ss@127.0.0.1:1080' + ); + assert.equal(normalizeCcProxyCandidateUrl('socks://127.0.0.1:1080'), 'socks5://127.0.0.1:1080'); + assert.equal(normalizeCcProxyCandidateUrl('127.0.0.1:7890'), 'http://127.0.0.1:7890'); + assert.equal(normalizeCcProxyCandidateUrl('https://proxy.example:8443'), 'https://proxy.example:8443'); + assert.equal(normalizeCcProxyCandidateUrl('socks4://127.0.0.1:1080'), ''); + assert.equal(normalizeCcProxyCandidateUrl('pac+http://127.0.0.1/proxy.pac'), ''); + + assert.equal( + await detectSystemHttpsProxy('daily-cloudcode-pa.googleapis.com', { + env: { ALL_PROXY: 'socks5://127.0.0.1:1080' }, + platform: 'linux', + }), + 'socks5://127.0.0.1:1080' + ); + assert.equal( + await detectSystemHttpsProxy('daily-cloudcode-pa.googleapis.com', { + env: { ALL_PROXY: 'socks4://127.0.0.1:1080' }, + platform: 'linux', + }), + '' + ); + assert.equal(shouldCcProxyBypassHost('intranet-host', 'localhost;127.*;'), true); + assert.equal(shouldCcProxyBypassHost('127.0.0.1', 'localhost;127.*;'), true); + assert.equal(shouldCcProxyBypassHost('daily-cloudcode-pa.googleapis.com', 'localhost;127.*;'), false); + assert.equal(shouldCcProxyBypassHost('daily-cloudcode-pa.googleapis.com', '*.googleapis.com'), true); + assert.equal(shouldCcProxyBypassHost('[::1]', '[::1]:8080'), true); + + // 2. Real HTTPS upstream + pooled SOCKS5 proxy + mid-stream upstream reset + HTTP CONNECT auth + hung timeout + crash recovery + const tlsCreds = createSelfSignedTlsFixture(); + let resolveUpstreamAborted; + const upstreamAbortedPromise = new Promise((r) => { + resolveUpstreamAborted = r; + }); + + const httpsUpstream = https.createServer(tlsCreds, (req, res) => { + if (req.url?.includes('fetchAvailableModels')) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + models: { + 'gemini-4-carbon-high': { + model: carbon, + maxTokens: 1048576, + modelExperiments: { + experiments: { + CASCADE_USE_EXPERIMENT_CHECKPOINTER: { + stringValue: JSON.stringify({ max_token_limit: '512000' }), + }, + }, + }, + }, + }, + }) + ); + return; + } + if (req.url?.includes('slowStream')) { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.write('first-chunk\n'); + res.on('close', () => { + resolveUpstreamAborted(true); + }); + return; + } + if (req.url?.includes('upstreamMidStreamReset')) { + res.writeHead(200, { 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked' }); + res.write('partial-token-chunk\n', () => { + setTimeout(() => { + const rawTcp = res.socket?._parent || null; + if (rawTcp && typeof rawTcp.resetAndDestroy === 'function') { + rawTcp.resetAndDestroy(); + } else { + res.socket?.destroy(); + } + }, 15).unref(); + }); + return; + } + res.writeHead(200); + res.end('ok'); + }); + await new Promise((r) => httpsUpstream.listen(0, '127.0.0.1', r)); + const upstreamPort = httpsUpstream.address().port; + const upstreamHttpsUrl = `https://127.0.0.1:${upstreamPort}`; + + // Minimal RFC 1928 + RFC 1929 SOCKS5 test server requiring dev:s3cr3t (supports IPv4 0x01, domain 0x03, IPv6 0x04) + let socksConnectCount = 0; + let lastSocksAtyp = 0; + let lastSocksIpv6Hex = ''; + const testServerSockets = new Set(); + const trackSock = (s) => { + testServerSockets.add(s); + s.on('close', () => testServerSockets.delete(s)); + }; + httpsUpstream.on('connection', trackSock); + const socksServer = net.createServer((clientSock) => { + trackSock(clientSock); + let stage = 0; + clientSock.on('data', (buf) => { + if (stage === 0) { + assert.equal(buf[0], 0x05); + assert.ok(buf.subarray(2, 2 + buf[1]).includes(0x02), 'client offers RFC1929 user/pass'); + stage = 1; + clientSock.write(Buffer.from([0x05, 0x02])); + return; + } + if (stage === 1) { + const uLen = buf[1]; + const user = buf.subarray(2, 2 + uLen).toString('utf8'); + const pLen = buf[2 + uLen]; + const pass = buf.subarray(3 + uLen, 3 + uLen + pLen).toString('utf8'); + if (user !== 'dev' || pass !== 's3cr3t') { + clientSock.end(Buffer.from([0x01, 0x01])); + return; + } + stage = 2; + clientSock.write(Buffer.from([0x01, 0x00])); + return; + } + if (stage === 2) { + stage = 3; + socksConnectCount += 1; + lastSocksAtyp = buf[3]; + let portOffset = 4; + if (buf[3] === 0x01) portOffset = 8; + else if (buf[3] === 0x03) portOffset = 5 + buf[4]; + else if (buf[3] === 0x04) { + lastSocksIpv6Hex = buf.subarray(4, 20).toString('hex'); + portOffset = 20; + } + const dstPort = buf.readUInt16BE(portOffset); + const upstreamSock = net.connect({ host: '127.0.0.1', port: dstPort }, () => { + clientSock.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0])); + clientSock.pipe(upstreamSock); + upstreamSock.pipe(clientSock); + }); + trackSock(upstreamSock); + upstreamSock.on('error', () => clientSock.destroy()); + clientSock.on('error', () => upstreamSock.destroy()); + } + }); + }); + await new Promise((r) => socksServer.listen(0, '127.0.0.1', r)); + const socksPort = socksServer.address().port; + + // HTTP CONNECT proxy requiring Basic alice:p@ss + let seenProxyAuth = ''; + const httpProxyServer = http.createServer(); + httpProxyServer.on('connection', trackSock); + httpProxyServer.on('connect', (req, clientSock, head) => { + trackSock(clientSock); + seenProxyAuth = String(req.headers['proxy-authorization'] || ''); + const expected = `Basic ${Buffer.from('alice:p@ss', 'utf8').toString('base64')}`; + if (seenProxyAuth !== expected) { + clientSock.write('HTTP/1.1 407 Proxy Authentication Required\r\n\r\n'); + clientSock.destroy(); + return; + } + const [, rawPort] = String(req.url || '').split(':'); + const upSock = net.connect({ host: '127.0.0.1', port: Number(rawPort) }, () => { + clientSock.write('HTTP/1.1 200 Connection Established\r\n\r\n'); + if (head && head.length > 0) upSock.write(head); + clientSock.pipe(upSock); + upSock.pipe(clientSock); + }); + trackSock(upSock); + upSock.on('error', () => clientSock.destroy()); + clientSock.on('error', () => upSock.destroy()); + }); + await new Promise((r) => httpProxyServer.listen(0, '127.0.0.1', r)); + const httpProxyPort = httpProxyServer.address().port; + + // Hung proxy server that accepts TCP and never responds + const hungSockets = new Set(); + const hungProxyServer = net.createServer((s) => { + hungSockets.add(s); + s.on('close', () => hungSockets.delete(s)); + }); + await new Promise((r) => hungProxyServer.listen(0, '127.0.0.1', r)); + const hungPort = hungProxyServer.address().port; + + let activeProxyUrl = `socks5://dev:s3cr3t@127.0.0.1:${socksPort}`; + const makeProxyCtrl = (extraOpts = {}) => + createCloudCodeProxyController({ + allowHttpUpstream: true, + allowTestEndpoint: true, + tunnelTimeoutMs: 120, + upstreamTlsOptions: { rejectUnauthorized: false }, + detectUpstreamFn: () => upstreamHttpsUrl, + detectProxyFn: async () => activeProxyUrl, + getEndpointFn: () => ({ addr: '127.0.0.1:44444', baseUrl: 'http://127.0.0.1:44444', csrfToken: 'tok' }), + callRpcFn: async () => ({}), + ...extraOpts, + }); + + const ctrlSocks = makeProxyCtrl(); + const ctrlHttpAuth = makeProxyCtrl(); + const ctrlHung = makeProxyCtrl(); + + try { + // A. SOCKS5 tunnel rewrites fetchAvailableModels over real TLS and POOLS Keep-Alive tunnel across consecutive requests + const stSocks = await ctrlSocks.reconcile({ enabled: true, rulesByModelId: { [carbon]: 400000 } }); + const resSocks = await fetch(`${stSocks.localUrl}/v1internal:fetchAvailableModels`, { + method: 'POST', + body: '{}', + }); + const rawSocksBody = await resSocks.text(); + assert.equal(resSocks.status, 200, rawSocksBody); + assert.equal(socksConnectCount, 1); + const jsonSocks = JSON.parse(rawSocksBody); + assert.equal( + JSON.parse( + jsonSocks.models['gemini-4-carbon-high'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER + .stringValue + ).max_token_limit, + '400000' + ); + + const resPassReuse = await fetch(`${stSocks.localUrl}/v1internal:countTokens`, { + method: 'POST', + body: '{}', + }); + assert.equal(await resPassReuse.text(), 'ok'); + assert.equal(socksConnectCount, 1, 'Keep-Alive reuses warm SOCKS5 TLS tunnel without re-handshaking'); + + // B. Client mid-stream abort immediately closes upstream request/socket over SOCKS5 tunnel + await new Promise((resolve, reject) => { + const clientReq = http.request(`${stSocks.localUrl}/v1internal:slowStream`, { method: 'POST' }, (res) => { + res.once('data', () => { + clientReq.destroy(); + resolve(); + }); + }); + clientReq.on('error', () => {}); + clientReq.end('{}'); + setTimeout(() => reject(new Error('Did not receive first chunk')), 2000).unref(); + }); + const abortedCleanly = await Promise.race([ + upstreamAbortedPromise, + new Promise((_, rej) => setTimeout(() => rej(new Error('Upstream stream leaked after client abort')), 1500)), + ]); + assert.equal(abortedCleanly, true); + + // B2. Upstream mid-stream TCP reset in streaming passthrough terminates client response cleanly without unhandled error + const resetHandled = await new Promise((resolve, reject) => { + let seenChunk = ''; + const clientReq = http.request( + `${stSocks.localUrl}/v1internal:upstreamMidStreamReset`, + { method: 'POST' }, + (res) => { + res.on('data', (c) => { + seenChunk += c.toString('utf8'); + }); + res.on('error', () => resolve(seenChunk)); + res.on('aborted', () => resolve(seenChunk)); + res.on('close', () => resolve(seenChunk)); + } + ); + clientReq.on('error', () => resolve(seenChunk)); + clientReq.end('{}'); + setTimeout(() => reject(new Error('Mid-stream upstream reset hung client response')), 2000).unref(); + }); + assert.match(resetHandled, /partial-token-chunk/); + + // B3. SOCKS5 IPv6 target ([::1]) encodes ATYP = 0x04 16-byte binary address + const ipv6TlsSock = await openCcProxyTunnelSocket( + { http, https, net, tls }, + '[::1]', + upstreamPort, + `socks5://dev:s3cr3t@127.0.0.1:${socksPort}`, + { timeoutMs: 2000, tlsOptions: { rejectUnauthorized: false } } + ); + assert.equal(lastSocksAtyp, 0x04); + assert.equal(lastSocksIpv6Hex, '00000000000000000000000000000001'); + ipv6TlsSock.destroy(); + + // C. Authenticated HTTP CONNECT proxy sends Proxy-Authorization: Basic + activeProxyUrl = `http://alice:p%40ss@127.0.0.1:${httpProxyPort}`; + const stHttp = await ctrlHttpAuth.reconcile({ enabled: true, rulesByModelId: { [carbon]: 320000 } }); + const resHttp = await fetch(`${stHttp.localUrl}/v1internal:fetchAvailableModels`, { + method: 'POST', + body: '{}', + }); + assert.equal(resHttp.status, 200); + assert.ok(seenProxyAuth.startsWith('Basic '), 'Proxy-Authorization header sent'); + + // D. Hung proxy times out cleanly with 502 instead of hanging forever + activeProxyUrl = `http://127.0.0.1:${hungPort}`; + const stHung = await ctrlHung.reconcile({ enabled: true, rulesByModelId: { [carbon]: 320000 } }); + const resHung = await fetch(`${stHung.localUrl}/v1internal:fetchAvailableModels`, { + method: 'POST', + body: '{}', + }); + assert.equal(resHung.status, 502); + assert.match(await resHung.text(), /timed out/i); + + // E. Sticky localPort across reloads and automatic SetCloudCodeURL crash healing on next startup + activeProxyUrl = ''; + let diskState = null; + const crashRpcLog = []; + const ctrlBeforeReload = makeProxyCtrl({ + stateFilePath: '/virtual/cloudcode-proxy-state.json', + loadJsonFn: () => diskState, + saveJsonFn: (_p, data) => { + diskState = data; + }, + callRpcFn: async (method, body) => { + crashRpcLog.push({ method, body }); + return {}; + }, + }); + const stBefore = await ctrlBeforeReload.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } }); + const stickyPort = Number(new URL(stBefore.localUrl).port); + assert.equal(diskState?.switched, true); + assert.equal(diskState?.localPort, stickyPort); + await ctrlBeforeReload.stop(); + assert.equal(diskState?.switched, false); + assert.equal(diskState?.localPort, stickyPort); + + // Re-enabling in a new controller re-binds the exact same sticky port + const ctrlAfterReload = makeProxyCtrl({ + stateFilePath: '/virtual/cloudcode-proxy-state.json', + loadJsonFn: () => diskState, + saveJsonFn: (_p, data) => { + diskState = data; + }, + callRpcFn: async (method, body) => { + crashRpcLog.push({ method, body }); + return {}; + }, + }); + const stAfter = await ctrlAfterReload.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } }); + assert.equal(stAfter.localUrl, stBefore.localUrl, 'reuses sticky local port across worker reloads'); + await ctrlAfterReload.stop(); + + // Simulate hard crash where previous worker left switched=true on disk, then new worker boots with Swarm disabled + diskState = { switched: true, localPort: stickyPort, upstreamUrl: upstreamHttpsUrl, updatedAtMs: Date.now() }; + crashRpcLog.length = 0; + const ctrlHealer = makeProxyCtrl({ + stateFilePath: '/virtual/cloudcode-proxy-state.json', + loadJsonFn: () => diskState, + saveJsonFn: (_p, data) => { + diskState = data; + }, + callRpcFn: async (method, body) => { + crashRpcLog.push({ method, body }); + return {}; + }, + }); + await ctrlHealer.reconcile({ enabled: false, rulesByModelId: {} }); + assert.equal(crashRpcLog.length, 1); + assert.equal(crashRpcLog[0].method, 'SetCloudCodeURL'); + assert.equal(crashRpcLog[0].body.url, upstreamHttpsUrl, 'heals orphaned Language Server CloudCode URL'); + assert.equal(diskState?.switched, false); + await ctrlHealer.stop(); + } finally { + await ctrlSocks.stop(); + await ctrlHttpAuth.stop(); + await ctrlHung.stop(); + httpsUpstream.closeAllConnections?.(); + httpProxyServer.closeAllConnections?.(); + for (const s of hungSockets) s.destroy(); + for (const s of testServerSockets) s.destroy(); + await Promise.all([ + new Promise((r) => httpsUpstream.close(() => r())), + new Promise((r) => socksServer.close(() => r())), + new Promise((r) => httpProxyServer.close(() => r())), + new Promise((r) => hungProxyServer.close(() => r())), + ]); + } +}); From 173e21c607ba0cc12d78a0dbeb586bf3f35300c0 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 15:04:14 +0900 Subject: [PATCH 13/30] fix(panel): harden SQLite ledger concurrency, LRU sizing, and recovery - Preserve step detail_json and peer-appended rows during cold metadata flushes, slim-step spreads, and mixed-case UUID re-keying without triggering case-insensitive self-deletion - Raise default hot session LRU limit to 64 and prime stepSigs during on-demand hydration to avoid cyclic read thrashing across 30-session quick stats plus active subagents - Quarantine corrupt SQLite images to .corrupt. with automatic .json.bak recovery and defer latching loadedOnce until initial hydration succeeds - Flush pending throttled endpoint caches on worker/standalone stop, isolate unscoped node --test runs from live user data, and transitively retain nested subagents and side questions on cache rebuilds --- sidecars/panel/backend/config.mjs | 14 +- sidecars/panel/backend/endpoint-registry.mjs | 21 ++- sidecars/panel/backend/local-scanner.mjs | 68 ++++++-- sidecars/panel/backend/sidecar-worker.mjs | 6 + sidecars/panel/backend/standalone-server.mjs | 2 + .../panel/backend/trajectory-cache-store.mjs | 10 +- .../backend/trajectory-sqlite-ledger.mjs | 145 +++++++++++++--- .../test/sqlite-trajectory-ledger.test.mjs | 164 +++++++++++++++++- 8 files changed, 381 insertions(+), 49 deletions(-) diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 442074a..2964347 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -418,14 +418,22 @@ export function computeRuntimeCodeVersion(options = {}) { /** * 本机内存态轨迹步骤缓存容器(委托 `createTrajectoryCacheStore`,首次读取时惰性加载历史缓存)。 */ +const isUnscopedHostTestRunner = Boolean( + typeof process !== 'undefined' && + process?.env?.NODE_TEST_CONTEXT && + !process?.env?.USAGE_MONITOR_APP_DATA_DIR && + !process?.env?.ANTIGRAVITY_APP_DATA_DIR && + !process?.env?.ANTIGRAVITY_GEMINI_DIR +); + const localTrajectoryCacheStore = createTrajectoryCacheStore({ - cacheFilePath: CACHE_FILE, - sqliteFilePath: TRAJECTORY_DB_FILE, + cacheFilePath: isUnscopedHostTestRunner ? '' : CACHE_FILE, + sqliteFilePath: isUnscopedHostTestRunner ? '' : TRAJECTORY_DB_FILE, loadJsonFn: loadJson, writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj), shouldBypassThrottleFn: (allowThrottleInTest) => lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest, - registerExitHook: true, + registerExitHook: !isUnscopedHostTestRunner, }); export function getLocalTrajectoryCacheStore() { diff --git a/sidecars/panel/backend/endpoint-registry.mjs b/sidecars/panel/backend/endpoint-registry.mjs index fd7e0a0..71e90b2 100644 --- a/sidecars/panel/backend/endpoint-registry.mjs +++ b/sidecars/panel/backend/endpoint-registry.mjs @@ -476,13 +476,28 @@ export function getRemoteWindowRpcInvoker() { return registeredWindowRpcInvoker; } -if (typeof process !== 'undefined' && typeof process?.once === 'function') { - process.once('exit', () => { - for (const ep of remoteEndpointRegistry.values()) { +export function flushAllEndpointCachesNow() { + try { + if (hasPendingTrajectoryCacheSave()) { + flushTrajectoryCacheNow(); + } + } catch { + // 忽略关闭阶段本机刷盘异常 + } + for (const ep of remoteEndpointRegistry.values()) { + try { if (ep.store.hasPendingTrajectoryCacheSave()) { ep.store.flushTrajectoryCacheNow(); } ep.store.cancelFlushTimer(); + } catch { + // 忽略关闭阶段远端端点刷盘异常 } + } +} + +if (typeof process !== 'undefined' && typeof process?.once === 'function') { + process.once('exit', () => { + flushAllEndpointCachesNow(); }); } diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 1cea98c..064016b 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -587,12 +587,34 @@ export function collectAuthoritativeLiveCascadeIds(endpoint = null) { for (const id of diskConvMap.keys()) liveIds.add(String(id).toLowerCase()); for (const id of localSnap.byId.keys()) liveIds.add(String(id).toLowerCase()); const localStore = getEndpointCacheStore(null); - for (const [rawKey, entry] of localStore.listCachedTrajectoryEntries()) { - const lower = String(rawKey || '').toLowerCase(); - if (!liveIds.has(lower)) continue; - for (const ref of entry?.subagentRefs || []) { - const refLower = String(ref?.cascadeId || '').trim().toLowerCase(); - if (refLower) liveIds.add(refLower); + const cachedEntries = localStore.listCachedTrajectoryEntries(); + let expanded = true; + while (expanded) { + expanded = false; + for (const [rawKey, entry] of cachedEntries) { + const lower = String(rawKey || '').toLowerCase(); + if (!lower) continue; + if (liveIds.has(lower)) { + for (const ref of entry?.subagentRefs || []) { + const refLower = String(ref?.cascadeId || '').trim().toLowerCase(); + if (refLower && !liveIds.has(refLower)) { + liveIds.add(refLower); + expanded = true; + } + } + } else { + const parentLower = String(entry?.parentConversationId || entry?.parentCascadeId || '') + .trim() + .toLowerCase(); + const rootLower = String(entry?.rootConversationId || '').trim().toLowerCase(); + if ( + (parentLower && liveIds.has(parentLower)) || + (rootLower && liveIds.has(rootLower)) + ) { + liveIds.add(lower); + expanded = true; + } + } } } return liveIds; @@ -1846,19 +1868,24 @@ export async function enumerateAndSyncConversations({ // 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目 const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey; if (normalizedKey !== rawCacheKey) { - setEntry(normalizedKey, getEntry(rawCacheKey)); - removeEntry(rawCacheKey); - cacheDirty = true; + const prevVal = getEntry(rawCacheKey); + if (prevVal) { + setEntry(normalizedKey, prevVal); + cacheDirty = true; + } } canonicalIdByLower.set(lower, normalizedKey); } else if (existingCanon !== rawCacheKey) { const targetEntry = getEntry(existingCanon); const dupEntry = getEntry(rawCacheKey); - if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) { - setEntry(existingCanon, dupEntry); + const winner = + !targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0) + ? dupEntry + : targetEntry; + if (winner) { + setEntry(existingCanon, winner); + cacheDirty = true; } - removeEntry(rawCacheKey); - cacheDirty = true; } } @@ -3279,12 +3306,18 @@ export async function enumerateAndSyncConversations({ } if (!isMeaningfulTitle(rootConv.title, cid)) { const localSumTitle = localSummaryByLower.get(cid)?.title || ''; - const stepTurnTitle = extractFirstStepTurnTitle(rootCached?.steps); let recoveredTitle = pickFirstMeaningfulTitle(cid, [ localSumTitle, rootCached?.title, - stepTurnTitle, ]); + if (!recoveredTitle && rootCached) { + const titleSourceEntry = rootCached._coldSteps + ? getHydratedEntry(rootConv.cascadeId) || rootCached + : rootCached; + recoveredTitle = pickFirstMeaningfulTitle(cid, [ + extractFirstStepTurnTitle(titleSourceEntry?.steps), + ]); + } if (!recoveredTitle && !isRemote) { recoveredTitle = probeLocalFallbackTitle( cid, @@ -3293,8 +3326,9 @@ export async function enumerateAndSyncConversations({ } if (recoveredTitle) { rootConv.title = recoveredTitle; - if (rootCached && rootCached.title !== recoveredTitle) { - setEntry(rootConv.cascadeId, { ...rootCached, title: recoveredTitle }); + const curRootCached = getEntry(rootConv.cascadeId) || rootCached; + if (curRootCached && curRootCached.title !== recoveredTitle) { + setEntry(rootConv.cascadeId, { ...curRootCached, title: recoveredTitle }); titleBackfillDirty = true; } } diff --git a/sidecars/panel/backend/sidecar-worker.mjs b/sidecars/panel/backend/sidecar-worker.mjs index 80c5b6d..8923212 100644 --- a/sidecars/panel/backend/sidecar-worker.mjs +++ b/sidecars/panel/backend/sidecar-worker.mjs @@ -14,6 +14,7 @@ import { dispatchBridgeApiRequest, } from './api-actions.mjs'; import { computeRuntimeCodeVersion } from './config.mjs'; +import { flushAllEndpointCachesNow } from './endpoint-registry.mjs'; let shuttingDown = false; let reloadRequested = false; @@ -50,6 +51,11 @@ async function gracefulStop() { if (shuttingDown) return; shuttingDown = true; clearInterval(driftWatchTimer); + try { + flushAllEndpointCachesNow(); + } catch { + // Ignore cache flush errors + } try { await bridgeController?.stop?.({ disposeWindows: false }); } catch { diff --git a/sidecars/panel/backend/standalone-server.mjs b/sidecars/panel/backend/standalone-server.mjs index 3cb0a92..b0053d2 100644 --- a/sidecars/panel/backend/standalone-server.mjs +++ b/sidecars/panel/backend/standalone-server.mjs @@ -16,6 +16,7 @@ import { readLocalAsync, } from './api-actions.mjs'; import { loadSettings, lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs'; +import { flushAllEndpointCachesNow } from './endpoint-registry.mjs'; import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs'; import { syncCloudCatalog } from './plugin-updater.mjs'; @@ -643,6 +644,7 @@ export function createStandaloneWebServer(options = {}) { } async function stop() { + flushAllEndpointCachesNow(); const srv = server; server = null; boundPort = 0; diff --git a/sidecars/panel/backend/trajectory-cache-store.mjs b/sidecars/panel/backend/trajectory-cache-store.mjs index e5d5ec3..f3275cd 100644 --- a/sidecars/panel/backend/trajectory-cache-store.mjs +++ b/sidecars/panel/backend/trajectory-cache-store.mjs @@ -20,7 +20,7 @@ import { } from './trajectory-sqlite-ledger.mjs'; export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000; -export const DEFAULT_HOT_SESSION_LRU_LIMIT = 24; +export const DEFAULT_HOT_SESSION_LRU_LIMIT = 64; const TCS_WAL_SYNC_MIN_INTERVAL_MS = 250; function tcsMarkColdSlimSteps(steps) { @@ -242,18 +242,22 @@ export function createTrajectoryCacheStore({ function ensureLoaded() { if (loadedOnce) return; - loadedOnce = true; if (useSqlite && sqliteLedger) { const hydrated = sqliteLedger.openAndHydrateInitial(); cacheObj = hydrated.cacheObj; + loadedOnce = true; rebuildLowerIndexFromCacheObj(true); lastWalSyncCheckMs = Date.now(); return; } - if (!cacheFilePath || typeof loadJsonFn !== 'function') return; + if (!cacheFilePath || typeof loadJsonFn !== 'function') { + loadedOnce = true; + return; + } const loaded = loadJsonFn(cacheFilePath, {}); const hydrated = hydrateTrajectoryCacheObject(loaded); cacheObj = hydrated.cacheObj; + loadedOnce = true; for (const key of Object.keys(cacheObj)) { byLower.set(key.toLowerCase(), key); } diff --git a/sidecars/panel/backend/trajectory-sqlite-ledger.mjs b/sidecars/panel/backend/trajectory-sqlite-ledger.mjs index 71eb996..2bf7ea6 100644 --- a/sidecars/panel/backend/trajectory-sqlite-ledger.mjs +++ b/sidecars/panel/backend/trajectory-sqlite-ledger.mjs @@ -231,6 +231,33 @@ export function splitStepForStorage(step) { * @param {(val: string) => string} [internFn] * @returns {object} */ +function isSqliteCorruptError(err) { + const msg = String(err?.message || err?.errstr || err?.code || ''); + return /SQLITE_CORRUPT|SQLITE_NOTADB|database disk image is malformed|file is not a database/i.test( + msg + ); +} + +function tslQuarantineCorruptDbFiles(sqliteFilePath) { + if (!sqliteFilePath || !existsSync(sqliteFilePath)) return ''; + const stamp = Date.now(); + const quarantineBase = `${sqliteFilePath}.corrupt.${stamp}`; + for (const suffix of ['', '-wal', '-shm']) { + const src = `${sqliteFilePath}${suffix}`; + if (!existsSync(src)) continue; + try { + renameSync(src, `${quarantineBase}${suffix}`); + } catch { + try { + rmSync(src, { force: true }); + } catch { + // Ignore cleanup failure + } + } + } + return quarantineBase; +} + export function buildSlimStepFromAccounting(rawAccounting, internFn = (v) => v || '') { if (!Array.isArray(rawAccounting)) { if (isPlainObject(rawAccounting)) { @@ -273,6 +300,12 @@ export function buildSlimStepFromAccounting(rawAccounting, internFn = (v) => v | if (t[20]) { slim.anomaly = t[20]; } + Object.defineProperty(slim, '_isSlimStep', { + value: true, + enumerable: false, + configurable: true, + writable: true, + }); return slim; } @@ -473,12 +506,9 @@ export function createTrajectorySqliteLedger({ return dedupedByLower; } - /** - * Initializes schema, migrates legacy `.json` inside a single `BEGIN IMMEDIATE` transaction if needed, - * and hydrates all conversations in cold slim accounting mode. - */ - function openAndHydrateInitial() { + function openAndHydrateInitialCore() { let migratedLegacy = false; + const bakJsonPath = legacyJsonPath ? `${legacyJsonPath}.bak` : ''; const hasLegacyJsonOnDisk = Boolean( legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath) ); @@ -493,8 +523,12 @@ export function createTrajectorySqliteLedger({ if (migRow?.value === '1') return; let rawLoaded = null; - if (legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath)) { - rawLoaded = loadJsonFn(legacyJsonPath, null); + if (typeof loadJsonFn === 'function') { + if (legacyJsonPath && existsSync(legacyJsonPath)) { + rawLoaded = loadJsonFn(legacyJsonPath, null); + } else if (!dbExistsBefore && bakJsonPath && existsSync(bakJsonPath)) { + rawLoaded = loadJsonFn(bakJsonPath, null); + } } db.exec('BEGIN IMMEDIATE'); @@ -566,6 +600,27 @@ export function createTrajectorySqliteLedger({ return hydrateAllSlimFromDb(); } + /** + * Initializes schema, migrates legacy `.json` inside a single `BEGIN IMMEDIATE` transaction if needed, + * self-heals corrupted SQLite images by quarantining `.corrupt.` and recovering from `.json.bak`, + * and hydrates all conversations in cold slim accounting mode. + */ + function openAndHydrateInitial() { + try { + return openAndHydrateInitialCore(); + } catch (err) { + if (!isSqliteCorruptError(err)) { + throw err; + } + persistedByLower.clear(); + const quarantined = tslQuarantineCorruptDbFiles(sqliteFilePath); + console.error( + `Quarantined corrupt SQLite trajectory ledger (${quarantined || sqliteFilePath}): ${err.message}` + ); + return openAndHydrateInitialCore(); + } + } + function hydrateAllSlimFromDb() { if (!existsSync(sqliteFilePath)) { localEpoch = 1; @@ -656,8 +711,13 @@ export function createTrajectorySqliteLedger({ return slimSteps.map((s) => ({ ...s })); } const hydrated = new Array(detailRows.length); + const hydratedStepSigs = new Array(detailRows.length); + let posAligned = true; for (let i = 0; i < detailRows.length; i += 1) { const r = detailRows[i]; + if (Number(r.pos) !== i) { + posAligned = false; + } let acc = null; let det = null; try { @@ -672,8 +732,17 @@ export function createTrajectorySqliteLedger({ det = null; } } + hydratedStepSigs[i] = r.detail_json + ? `${r.accounting_json}\n${r.detail_json}` + : String(r.accounting_json || ''); hydrated[i] = mergeStepFromStorage(acc, det, internString); } + if (posAligned) { + const prevDigest = persistedByLower.get(lower); + if (prevDigest && prevDigest.cascadeId === dbCid && !prevDigest.stepSigs) { + prevDigest.stepSigs = hydratedStepSigs; + } + } return hydrated; }); } @@ -738,15 +807,21 @@ export function createTrajectorySqliteLedger({ INSERT OR REPLACE INTO steps (cascade_id, pos, accounting_json, detail_json) VALUES (?, ?, ?, ?) `); + const upSlimStepKeepDetail = db.prepare(` + INSERT INTO steps (cascade_id, pos, accounting_json, detail_json) + VALUES (?, ?, ?, NULL) + ON CONFLICT(cascade_id, pos) DO UPDATE SET + accounting_json = excluded.accounting_json + `); const truncSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ? AND pos >= ?'); - const delOldCidSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ?'); + const rekeyStepsCid = db.prepare('UPDATE steps SET cascade_id = ? WHERE cascade_id = ?'); for (const { cascadeId, entry } of upserts) { if (!cascadeId || !entry || typeof entry !== 'object') continue; const lower = String(cascadeId).toLowerCase(); const prevDbRow = selExisting.get(lower); if (prevDbRow?.cascade_id && prevDbRow.cascade_id !== cascadeId) { - delOldCidSteps.run(prevDbRow.cascade_id); + rekeyStepsCid.run(cascadeId, prevDbRow.cascade_id); } const prevDigest = persistedByLower.get(lower) || null; @@ -756,24 +831,46 @@ export function createTrajectorySqliteLedger({ const steps = Array.isArray(entry.steps) ? entry.steps : []; // When an entry is still in `_coldSteps` mode (only metadata such as `signature`, `title`, - // or `archived` changed without mutating steps), update ONLY `conversations` in O(1) - // without touching `steps` (`detail_json` on disk stays 100% intact)! - if (entry._coldSteps && prevDbRow && prevDbRow.step_count === steps.length) { - if ( - prevDigest && - prevDigest.cascadeId === cascadeId && - prevDigest.metaJson === metaJson && - prevDigest.archivedInt === archivedInt - ) { + // `workspaceUri`, or `archived` changed without hydrating `detail_json`), NEVER overwrite + // `detail_json` with NULL or truncate newer steps written concurrently by a peer process. + if (entry._coldSteps) { + if (prevDbRow) { + const preservedStepCount = Math.max(steps.length, Number(prevDbRow.step_count || 0)); + if ( + prevDigest && + prevDigest.cascadeId === cascadeId && + prevDigest.metaJson === metaJson && + prevDigest.archivedInt === archivedInt && + prevDbRow.cascade_id === cascadeId && + Number(prevDbRow.step_count || 0) === preservedStepCount + ) { + continue; + } + seq += 1; + upConv.run(cascadeId, lower, archivedInt, preservedStepCount, seq, nowMs, metaJson); + persistedByLower.set(lower, { + cascadeId, + metaJson, + archivedInt, + stepSigs: + preservedStepCount === steps.length ? prevDigest?.stepSigs || null : null, + }); continue; } + + // Cold entry flushed when row was absent in `conversations` (e.g. after external reset): + // insert accounting tuples without ever clobbering any existing `detail_json`. + for (let pos = 0; pos < steps.length; pos += 1) { + const { accountingTuple } = splitStepForStorage(steps[pos]); + upSlimStepKeepDetail.run(cascadeId, pos, JSON.stringify(accountingTuple)); + } seq += 1; upConv.run(cascadeId, lower, archivedInt, steps.length, seq, nowMs, metaJson); persistedByLower.set(lower, { cascadeId, metaJson, archivedInt, - stepSigs: prevDigest?.stepSigs || null, + stepSigs: null, }); continue; } @@ -786,13 +883,19 @@ export function createTrajectorySqliteLedger({ let anyStepWritten = false; for (let pos = 0; pos < steps.length; pos += 1) { - const { accountingTuple, detailObj } = splitStepForStorage(steps[pos]); + const rawStep = steps[pos]; + const { accountingTuple, detailObj } = splitStepForStorage(rawStep); const accJson = JSON.stringify(accountingTuple); const detJson = detailObj ? JSON.stringify(detailObj) : null; + const isUnexpandedSlim = Boolean(rawStep?._isSlimStep === true && detJson === null); const sig = detJson ? `${accJson}\n${detJson}` : accJson; nextStepSigs[pos] = sig; if (!prevStepSigs || prevStepSigs[pos] !== sig) { - upStep.run(cascadeId, pos, accJson, detJson); + if (isUnexpandedSlim) { + upSlimStepKeepDetail.run(cascadeId, pos, accJson); + } else { + upStep.run(cascadeId, pos, accJson, detJson); + } anyStepWritten = true; } } diff --git a/sidecars/panel/test/sqlite-trajectory-ledger.test.mjs b/sidecars/panel/test/sqlite-trajectory-ledger.test.mjs index a2e85d9..007a41a 100644 --- a/sidecars/panel/test/sqlite-trajectory-ledger.test.mjs +++ b/sidecars/panel/test/sqlite-trajectory-ledger.test.mjs @@ -1,12 +1,15 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { execFile } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { isDeepStrictEqual, promisify } from 'node:util'; import { MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs'; -import { createTrajectoryCacheStore } from '../backend/trajectory-cache-store.mjs'; +import { + DEFAULT_HOT_SESSION_LRU_LIMIT, + createTrajectoryCacheStore, +} from '../backend/trajectory-cache-store.mjs'; const execFileAsync = promisify(execFile); @@ -509,3 +512,160 @@ test('Deleting source conversation in Antigravity + clicking Rebuild Cache perma assert.equal(out.deletedViewSteps, 1, 'clicking archived deleted conversation still renders step details'); assert.equal(existsSync(liveDbFile), true); }); + +test('SQLite hardening: cold metadata vs peer append safety, mixed-case re-keying, corrupt DB quarantine + .bak recovery, and 64-session LRU', (t) => { + const dir = mkdtempSync(join(tmpdir(), 'ag-um-sqlite-hardening-')); + t.after(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + // 1. Default hot LRU comfortably holds 30 quick-stat sessions + active subagents without cyclic thrashing + assert.equal(DEFAULT_HOT_SESSION_LRU_LIMIT, 64); + + const dbPath = join(dir, 'trajectory_store.sqlite'); + const jsonPath = join(dir, 'trajectory_usage_cache.json'); + const mixedUpperCid = 'ABCDEF99-1111-4222-8333-444455556666'; + const mixedLowerCid = mixedUpperCid.toLowerCase(); + const conflictCid = '11112222-3333-4444-8555-666677778888'; + + // Seed initial DB via Store Writer + const writer = createTrajectoryCacheStore({ + cacheFilePath: jsonPath, + sqliteFilePath: dbPath, + enableSqlite: true, + loadJsonFn: loadJsonHelper, + }); + writer.setCachedTrajectory(mixedUpperCid, { + signature: 'v4:init', + title: 'Mixed Case Session', + steps: [makeRichStep(1, { turnPrompt: 'Mixed case prompt 1' })], + }); + writer.setCachedTrajectory(conflictCid, { + signature: 'v4:s2', + title: 'Initial Title', + steps: [ + makeRichStep(1, { turnPrompt: 'Step 1 intact' }), + makeRichStep(2, { turnPrompt: 'Step 2 intact' }), + ], + }); + assert.equal(writer.flushTrajectoryCacheNow(), true); + + // Open Peer A (cold reader/writer) BEFORE Peer B appends Step #3 + const peerA = createTrajectoryCacheStore({ + cacheFilePath: jsonPath, + sqliteFilePath: dbPath, + enableSqlite: true, + loadJsonFn: loadJsonHelper, + }); + const coldConflict = peerA.getCachedTrajectory(conflictCid); + assert.equal(coldConflict.steps.length, 2); + assert.equal(peerA.isConversationCold(conflictCid), true); + + // Peer B appends Step #3 (with rich detail_json) to conflictCid and flushes first + const peerB = createTrajectoryCacheStore({ + cacheFilePath: jsonPath, + sqliteFilePath: dbPath, + enableSqlite: true, + loadJsonFn: loadJsonHelper, + }); + const hydratedB = peerB.getHydratedTrajectory(conflictCid); + peerB.setCachedTrajectory(conflictCid, { + ...hydratedB, + signature: 'v4:s3', + steps: [...hydratedB.steps, makeRichStep(3, { turnPrompt: 'Step 3 from Peer B' })], + }); + assert.equal(peerB.flushTrajectoryCacheNow(), true); + + // Peer A (still holding stale 2-step cold entry!) updates metadata & re-keys mixedUpperCid -> mixedLowerCid + peerA.setCachedTrajectory(conflictCid, { + ...coldConflict, + workspaceUri: 'file:///workspace/project-a', + }); + const coldMixed = peerA.getCachedTrajectory(mixedUpperCid); + assert.equal(peerA.isConversationCold(mixedUpperCid), true); + peerA.setCachedTrajectory(mixedLowerCid, { ...coldMixed, title: 'Normalized Lower Title' }); + assert.equal(peerA.flushTrajectoryCacheNow(), true); + + // Also test array-copied slim steps ([...coldEntry.steps]) losing array-level _isColdSlimSteps + const peerC = createTrajectoryCacheStore({ + cacheFilePath: jsonPath, + sqliteFilePath: dbPath, + enableSqlite: true, + loadJsonFn: loadJsonHelper, + }); + const coldMixedC = peerC.getCachedTrajectory(mixedLowerCid); + peerC.setCachedTrajectory(mixedLowerCid, { + ...coldMixedC, + steps: [...coldMixedC.steps], + }); + assert.equal(peerC.flushTrajectoryCacheNow(), true); + + // Verify fresh reader sees ALL 3 steps + ALL detail_json on conflictCid AND preserved detail_json on mixedLowerCid! + const verifier = createTrajectoryCacheStore({ + cacheFilePath: jsonPath, + sqliteFilePath: dbPath, + enableSqlite: true, + loadJsonFn: loadJsonHelper, + }); + const verifiedConflict = verifier.getHydratedTrajectory(conflictCid); + assert.equal(verifiedConflict.steps.length, 3, 'Peer B step #3 was NOT truncated by Peer A cold metadata flush'); + assert.equal(verifiedConflict.steps[0].turnPrompt, 'Step 1 intact'); + assert.equal(verifiedConflict.steps[1].turnPrompt, 'Step 2 intact'); + assert.equal(verifiedConflict.steps[2].turnPrompt, 'Step 3 from Peer B'); + assert.equal(verifiedConflict.steps[2].contextBreakdown.totalTokens, 50_600); + + const verifiedMixed = verifier.getHydratedTrajectory(mixedLowerCid); + assert.equal(verifiedMixed.title, 'Normalized Lower Title'); + assert.equal(verifiedMixed.steps.length, 1); + assert.equal(verifiedMixed.steps[0].turnPrompt, 'Mixed case prompt 1', 'mixed-case re-keying + array-spread preserved detail_json'); + + // 2. Corrupt SQLite file self-healing + automatic recovery from trajectory_usage_cache.json.bak + const corruptDir = mkdtempSync(join(tmpdir(), 'ag-um-sqlite-corrupt-')); + t.after(() => { + rmSync(corruptDir, { recursive: true, force: true }); + }); + const corruptDbPath = join(corruptDir, 'trajectory_store.sqlite'); + const corruptJsonPath = join(corruptDir, 'trajectory_usage_cache.json'); + const bakCid = '99998888-7777-4666-8555-444433332222'; + writeFileSync(corruptDbPath, 'CORRUPT_HEADER_NOT_A_VALID_SQLITE_3_DATABASE_IMAGE', 'utf8'); + writeFileSync( + `${corruptJsonPath}.bak`, + JSON.stringify({ + [bakCid]: { + signature: 'v4:bak', + title: 'Recovered From Backup', + steps: [makeRichStep(1, { turnPrompt: 'Backup survived corruption' })], + }, + }), + 'utf8' + ); + + const healedStore = createTrajectoryCacheStore({ + cacheFilePath: corruptJsonPath, + sqliteFilePath: corruptDbPath, + enableSqlite: true, + loadJsonFn: loadJsonHelper, + }); + const recovered = healedStore.getHydratedTrajectory(bakCid); + assert.ok(recovered, 'corrupt SQLite quarantined and recovered from .json.bak'); + assert.equal(recovered.title, 'Recovered From Backup'); + assert.equal(recovered.steps[0].turnPrompt, 'Backup survived corruption'); + const quarantinedFiles = readdirSync(corruptDir).filter((f) => f.includes('.corrupt.')); + assert.equal(quarantinedFiles.length >= 1, true, 'corrupt DB preserved as .corrupt.'); + + // 3. Transient startup load error does NOT latch loadedOnce permanently + let failFirstLoad = true; + const retryStore = createTrajectoryCacheStore({ + cacheFilePath: '/virtual/retry.json', + enableSqlite: false, + loadJsonFn: () => { + if (failFirstLoad) { + failFirstLoad = false; + throw new Error('transient EBUSY'); + } + return { [bakCid]: { signature: 'v4:ok', steps: [makeRichStep(1)] } }; + }, + }); + assert.throws(() => retryStore.getCachedTrajectory(bakCid), /transient EBUSY/); + assert.equal(retryStore.getCachedTrajectory(bakCid)?.steps?.length, 1, 'second read succeeds cleanly'); +}); From 4da6420ac1990eb2edd49610d7c83b889bd67532 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 15:25:07 +0900 Subject: [PATCH 14/30] fix(panel): restore missing i18n keys and localize en-US trend/CSV dates - Add header.scopeAll and header.scopeAllShort in zh-CN and en-US and align StepTableWidget cost width estimation with formatUsd - Format trend chart hover titles, x-axis tick tooltips, and CSV summary/trend rows per active locale instead of hardcoded Chinese date labels - Add static t(...) key completeness and bilingual trend/CSV regression checks --- sidecars/panel/app.js | 91 ++++++++++-- sidecars/panel/index.html | 4 +- .../src/components/charts/TrendAreaChart.js | 10 +- .../src/components/widgets/StepTableWidget.js | 6 +- sidecars/panel/src/core/formatters.js | 61 ++++++++ sidecars/panel/src/core/reportExporter.js | 13 +- sidecars/panel/src/i18n/en-US.js | 2 + sidecars/panel/src/i18n/zh-CN.js | 2 + .../test/cross-module-regressions.test.mjs | 134 ++++++++++++++++++ 9 files changed, 298 insertions(+), 25 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 0c3efc3..c51f470 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1291,6 +1291,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', 'header.statusLive': '监控中', + 'header.scopeAll': '全部代理', + 'header.scopeAllShort': '全', 'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…', 'select.searchPlaceholder': '输入关键词筛选…', 'select.noMatches': '没有匹配的选项', @@ -2192,6 +2194,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', 'header.statusLive': 'Monitoring', + 'header.scopeAll': 'All Agents', + 'header.scopeAllShort': 'All', 'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…', 'select.searchPlaceholder': 'Filter options…', 'select.noMatches': 'No matching items', @@ -4062,7 +4066,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { +const { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatTrendSlotFullLabel, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -4074,6 +4078,14 @@ const EN_MONTH_SHORT = Object.freeze([ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]); +const ZH_WEEKDAY_SHORT = Object.freeze([ + '周日', '周一', '周二', '周三', '周四', '周五', '周六', +]); + +const EN_WEEKDAY_SHORT = Object.freeze([ + 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', +]); + function formatMetric(value, unit = '') { if (!Number.isFinite(value)) return '—'; const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1); @@ -4163,6 +4175,59 @@ function formatDateSpanBadge(startMs, endMs) { return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } +function formatTrendSlotFullLabel(slot, { locale, showFullYear = false } = {}) { + const en = + typeof locale === 'string' && locale.trim() + ? locale.trim().toLowerCase().startsWith('en') + : isEnglishLocale(); + const sMs = Number(slot?.startMs); + if (Number.isFinite(sMs) && sMs > 0) { + const sd = new Date(sMs); + const pad2 = (n) => String(n).padStart(2, '0'); + const rawFull = String(slot?.fullLabel || ''); + const includeYear = Boolean( + showFullYear || /^\d{4}年/.test(rawFull) || sd.getFullYear() !== new Date().getFullYear() + ); + const gran = String(slot?.granularity || '').toLowerCase(); + const isSubDay = + gran === 'minute' || + gran === 'hour' || + (!gran && Number(slot?.endMs) > sMs && Number(slot.endMs) - sMs <= 3600_000 * 2); + + if (isSubDay) { + const eMs = Number(slot?.endMs); + const ed = Number.isFinite(eMs) && eMs > 0 ? new Date(eMs) : new Date(sMs + 3600_000); + const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; + const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; + if (en) { + const mon = EN_MONTH_SHORT[sd.getMonth()] || ''; + return includeYear + ? `${mon} ${sd.getDate()}, ${sd.getFullYear()}, ${hh} - ${endHh}` + : `${mon} ${sd.getDate()}, ${hh} - ${endHh}`; + } + const yearPrefix = includeYear ? `${sd.getFullYear()}年` : ''; + return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`; + } + + if (en) { + const mon = EN_MONTH_SHORT[sd.getMonth()] || ''; + const wday = EN_WEEKDAY_SHORT[sd.getDay()] || ''; + return includeYear + ? `${mon} ${sd.getDate()}, ${sd.getFullYear()} (${wday})` + : `${mon} ${sd.getDate()} (${wday})`; + } + const yearPrefix = includeYear ? `${sd.getFullYear()}年` : ''; + return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${ZH_WEEKDAY_SHORT[sd.getDay()] || ''})`; + } + + const rawFull = String(slot?.fullLabel || '').trim(); + const rawShort = String(slot?.label || '').trim(); + if (en && rawFull && /[\u4e00-\u9fff]/.test(rawFull)) { + return rawShort || rawFull; + } + return rawFull || rawShort; +} + function formatUsd(amount, { precise = false } = {}) { if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending'); const val = Number(amount || 0); @@ -5428,7 +5493,7 @@ function buildDeterministicModelColorMap(models = []) { return colorMap; } -return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; +return { formatMetric, formatSpeedMetric, formatCachePct, formatPctNumber, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatTrendSlotFullLabel, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); // --- src/core/stepInspector.js --- @@ -6754,8 +6819,10 @@ const { escapeCsvCell, sanitizeExportFilename, buildConsumptionExportBaseName, b const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/; const RANGE_LABELS_ZH = Object.freeze({ + '5h': '近5小时', today: '今日', '24h': '近24小时', + week: '本周', '7d': '近7天', '14d': '近14天', '30d': '近30天', @@ -6765,8 +6832,10 @@ const RANGE_LABELS_ZH = Object.freeze({ }); const RANGE_LABELS_EN = Object.freeze({ + '5h': 'Last 5 Hours', today: 'Today', '24h': 'Last 24 Hours', + week: 'This Week', '7d': 'Last 7 Days', '14d': 'Last 14 Days', '30d': 'Last 30 Days', @@ -7567,8 +7636,10 @@ function buildStepsMarkdownReport( function buildConsumptionCsv( consumption, modelBreakdown = [], - { displaySettings = {}, includeBom = true } = {} + { displaySettings = {}, includeBom = true, locale } = {} ) { + const en = resolveExportEnglish(locale); + const effectiveLocale = en ? 'en-US' : 'zh-CN'; const cons = consumption || {}; const acc = cons.account || {}; const range = cons.selectedRange || {}; @@ -7594,7 +7665,7 @@ function buildConsumptionCsv( ]), csvRow([ 'summary', - range.label || range.key || 'all', + resolveLocalizedRangeLabel(range, en), Number(acc.calls || 0), Number(acc.inputTokens || 0), Number(acc.cacheReadTokens || 0), @@ -7662,7 +7733,7 @@ function buildConsumptionCsv( rows.push( csvRow([ 'trend', - slot.fullLabel || slot.label || '', + formatTrendSlotFullLabel(slot, { locale: effectiveLocale }) || slot.label || '', Number(slot.calls || 0), Number(slot.inputTokens || 0), Number(slot.cacheReadTokens || 0), @@ -14342,7 +14413,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const slotTok = safeSlotTokens(slot.tokens); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; tooltipContent.update({ - title: slot.fullLabel || slot.label || '--', + title: formatTrendSlotFullLabel(slot) || slot.label || '--', calls: slot.calls, totalTokens: slotTok, costText: formatUsd(slotCost, { @@ -15121,7 +15192,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const tickEl = h('span', { className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, text: slot.label || '', - title: slot.fullLabel || slot.label || '', + title: formatTrendSlotFullLabel(slot) || slot.label || '', }); patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); tickEl.onclick = () => { @@ -22324,11 +22395,7 @@ function estTokenChars(val) { } function estCostWidth(st) { - const c = st?.costUsd; - if (c == null || !Number.isFinite(Number(c))) { - return st?.isPricingPending ? estProportionalTextWidth(t('fmt.pricingPending')) : 1; - } - return estProportionalTextWidth(formatUsd(Number(c))); + return estProportionalTextWidth(formatUsd(st?.costUsd, { precise: true })); } function estSegmentChars(seg, st) { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 62aad77..7c9ed05 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index a04c397..90575c5 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -13,7 +13,11 @@ import { patchStyleVar, patchText, } from '../../core/domPatch.js'; -import { formatTokensPrecise, formatUsd } from '../../core/formatters.js'; +import { + formatTokensPrecise, + formatTrendSlotFullLabel, + formatUsd, +} from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js'; @@ -738,7 +742,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const slotTok = safeSlotTokens(slot.tokens); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; tooltipContent.update({ - title: slot.fullLabel || slot.label || '--', + title: formatTrendSlotFullLabel(slot) || slot.label || '--', calls: slot.calls, totalTokens: slotTok, costText: formatUsd(slotCost, { @@ -1517,7 +1521,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const tickEl = h('span', { className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, text: slot.label || '', - title: slot.fullLabel || slot.label || '', + title: formatTrendSlotFullLabel(slot) || slot.label || '', }); patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); tickEl.onclick = () => { diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index fa9c870..97f23ec 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -94,11 +94,7 @@ function estTokenChars(val) { } function estCostWidth(st) { - const c = st?.costUsd; - if (c == null || !Number.isFinite(Number(c))) { - return st?.isPricingPending ? estProportionalTextWidth(t('fmt.pricingPending')) : 1; - } - return estProportionalTextWidth(formatUsd(Number(c))); + return estProportionalTextWidth(formatUsd(st?.costUsd, { precise: true })); } function estSegmentChars(seg, st) { diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index e09a243..7749719 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -21,6 +21,14 @@ const EN_MONTH_SHORT = Object.freeze([ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]); +const ZH_WEEKDAY_SHORT = Object.freeze([ + '周日', '周一', '周二', '周三', '周四', '周五', '周六', +]); + +const EN_WEEKDAY_SHORT = Object.freeze([ + 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', +]); + export function formatMetric(value, unit = '') { if (!Number.isFinite(value)) return '—'; const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1); @@ -110,6 +118,59 @@ export function formatDateSpanBadge(startMs, endMs) { return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } +export function formatTrendSlotFullLabel(slot, { locale, showFullYear = false } = {}) { + const en = + typeof locale === 'string' && locale.trim() + ? locale.trim().toLowerCase().startsWith('en') + : isEnglishLocale(); + const sMs = Number(slot?.startMs); + if (Number.isFinite(sMs) && sMs > 0) { + const sd = new Date(sMs); + const pad2 = (n) => String(n).padStart(2, '0'); + const rawFull = String(slot?.fullLabel || ''); + const includeYear = Boolean( + showFullYear || /^\d{4}年/.test(rawFull) || sd.getFullYear() !== new Date().getFullYear() + ); + const gran = String(slot?.granularity || '').toLowerCase(); + const isSubDay = + gran === 'minute' || + gran === 'hour' || + (!gran && Number(slot?.endMs) > sMs && Number(slot.endMs) - sMs <= 3600_000 * 2); + + if (isSubDay) { + const eMs = Number(slot?.endMs); + const ed = Number.isFinite(eMs) && eMs > 0 ? new Date(eMs) : new Date(sMs + 3600_000); + const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; + const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; + if (en) { + const mon = EN_MONTH_SHORT[sd.getMonth()] || ''; + return includeYear + ? `${mon} ${sd.getDate()}, ${sd.getFullYear()}, ${hh} - ${endHh}` + : `${mon} ${sd.getDate()}, ${hh} - ${endHh}`; + } + const yearPrefix = includeYear ? `${sd.getFullYear()}年` : ''; + return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`; + } + + if (en) { + const mon = EN_MONTH_SHORT[sd.getMonth()] || ''; + const wday = EN_WEEKDAY_SHORT[sd.getDay()] || ''; + return includeYear + ? `${mon} ${sd.getDate()}, ${sd.getFullYear()} (${wday})` + : `${mon} ${sd.getDate()} (${wday})`; + } + const yearPrefix = includeYear ? `${sd.getFullYear()}年` : ''; + return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${ZH_WEEKDAY_SHORT[sd.getDay()] || ''})`; + } + + const rawFull = String(slot?.fullLabel || '').trim(); + const rawShort = String(slot?.label || '').trim(); + if (en && rawFull && /[\u4e00-\u9fff]/.test(rawFull)) { + return rawShort || rawFull; + } + return rawFull || rawShort; +} + export function formatUsd(amount, { precise = false } = {}) { if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending'); const val = Number(amount || 0); diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index 29f5b86..9ecfb99 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -11,6 +11,7 @@ import { formatPctNumber, formatSpeedMetric, formatTokensPrecise, + formatTrendSlotFullLabel, formatUsd, mergeModelsByDisplayName, resolveModelDisplayInfo, @@ -20,8 +21,10 @@ import { buildXlsxWorkbookBytes } from './xlsxBuilder.js'; const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/; const RANGE_LABELS_ZH = Object.freeze({ + '5h': '近5小时', today: '今日', '24h': '近24小时', + week: '本周', '7d': '近7天', '14d': '近14天', '30d': '近30天', @@ -31,8 +34,10 @@ const RANGE_LABELS_ZH = Object.freeze({ }); const RANGE_LABELS_EN = Object.freeze({ + '5h': 'Last 5 Hours', today: 'Today', '24h': 'Last 24 Hours', + week: 'This Week', '7d': 'Last 7 Days', '14d': 'Last 14 Days', '30d': 'Last 30 Days', @@ -833,8 +838,10 @@ export function buildStepsMarkdownReport( export function buildConsumptionCsv( consumption, modelBreakdown = [], - { displaySettings = {}, includeBom = true } = {} + { displaySettings = {}, includeBom = true, locale } = {} ) { + const en = resolveExportEnglish(locale); + const effectiveLocale = en ? 'en-US' : 'zh-CN'; const cons = consumption || {}; const acc = cons.account || {}; const range = cons.selectedRange || {}; @@ -860,7 +867,7 @@ export function buildConsumptionCsv( ]), csvRow([ 'summary', - range.label || range.key || 'all', + resolveLocalizedRangeLabel(range, en), Number(acc.calls || 0), Number(acc.inputTokens || 0), Number(acc.cacheReadTokens || 0), @@ -928,7 +935,7 @@ export function buildConsumptionCsv( rows.push( csvRow([ 'trend', - slot.fullLabel || slot.label || '', + formatTrendSlotFullLabel(slot, { locale: effectiveLocale }) || slot.label || '', Number(slot.calls || 0), Number(slot.inputTokens || 0), Number(slot.cacheReadTokens || 0), diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index a2b25e2..91eb943 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -32,6 +32,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'header.statusQuotaCached': 'Quota Cached', 'header.statusQuotaOffline': 'Quota Offline', 'header.statusLive': 'Monitoring', + 'header.scopeAll': 'All Agents', + 'header.scopeAllShort': 'All', 'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…', 'select.searchPlaceholder': 'Filter options…', 'select.noMatches': 'No matching items', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 085b2ce..f6632e6 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -32,6 +32,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'header.statusQuotaCached': '额度缓存', 'header.statusQuotaOffline': '额度离线', 'header.statusLive': '监控中', + 'header.scopeAll': '全部代理', + 'header.scopeAllShort': '全', 'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…', 'select.searchPlaceholder': '输入关键词筛选…', 'select.noMatches': '没有匹配的选项', diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 656898a..611360b 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1507,3 +1507,137 @@ test('5h quota cycle includes cycle-opening compaction CHECKPOINT and cross-boun assert.equal(payload.consumption.account.calls, 4); assert.equal(payload.consumption.account.totalTokens, 491_000); }); + +test('i18n static t(...) key completeness guard, scopeAll formatters, and localized en-US trend/CSV date labels', async () => { + const { I18N_MESSAGES_ZH_CN } = await import('../src/i18n/zh-CN.js'); + const { I18N_MESSAGES_EN_US } = await import('../src/i18n/en-US.js'); + const { setI18nLanguage } = await import('../src/i18n/index.js'); + const { + formatAgentBadgeText, + formatAgentLabel, + formatTrendSlotFullLabel, + } = await import('../src/core/formatters.js'); + const { buildStructurePreviewTelemetry } = await import('../src/components/settings/structurePreviewMock.js'); + const { buildConsumptionCsv } = await import('../src/core/reportExporter.js'); + const { createTrendAreaChart } = await import('../src/components/charts/TrendAreaChart.js'); + const { createMockDom } = await import('./mock-dom.mjs'); + + // 1. Every static t('...') call across sidecars/panel/src/** resolves in both zh-CN and en-US + const srcRoot = fileURLToPath(new URL('../src', import.meta.url)); + const walkJs = (dir) => { + const out = []; + for (const ent of fs.readdirSync(dir, { withFileTypes: true })) { + const p = join(dir, ent.name); + if (ent.isDirectory()) out.push(...walkJs(p)); + else if (ent.name.endsWith('.js') || ent.name.endsWith('.mjs')) out.push(p); + } + return out; + }; + const zhKeys = new Set(Object.keys(I18N_MESSAGES_ZH_CN)); + const enKeys = new Set(Object.keys(I18N_MESSAGES_EN_US)); + assert.deepEqual([...zhKeys].filter((k) => !enKeys.has(k)), []); + assert.deepEqual([...enKeys].filter((k) => !zhKeys.has(k)), []); + + const missingKeys = []; + for (const filePath of walkJs(srcRoot)) { + const srcText = fs.readFileSync(filePath, 'utf8'); + const re = /(? Date: Tue, 24 Nov 2026 15:48:18 +0900 Subject: [PATCH 15/30] fix(panel): filter summaryless subagent DBs by real metadata tags - Decode parentConversationId (fn 5), subagentSpec (fn 8), and nestingDepth (fn 17) in migratorDecodeMetaBlobLight instead of reading fn 9, and filter CORTEX_TRAJECTORY_SOURCE_SUBAGENT (source === 16) across summary and DB-fallback paths. - Reject non-root subagent and side-question sessions (non_root_session) at the migrateSessions execution boundary and drop obsolete fn 8 string UUID replacement branches. --- sidecars/panel/backend/session-migrator.mjs | 118 +++++++---- .../panel/test/session-migration.test.mjs | 188 +++++++++++++++++- 2 files changed, 263 insertions(+), 43 deletions(-) diff --git a/sidecars/panel/backend/session-migrator.mjs b/sidecars/panel/backend/session-migrator.mjs index f974e01..7631343 100644 --- a/sidecars/panel/backend/session-migrator.mjs +++ b/sidecars/panel/backend/session-migrator.mjs @@ -202,6 +202,8 @@ function migratorDecodeMetaBlobLight(rawBlob) { let workspaceUri = ''; let projectId = ''; let parentConversationId = ''; + let nestingDepth = 0; + let hasSubagentSpec = false; let createdMs = 0; for (const field of fields) { if (field.fn === 7 && field.wt === 2 && !workspaceUri) { @@ -212,8 +214,24 @@ function migratorDecodeMetaBlobLight(rawBlob) { if (fn1) workspaceUri = fn1.payload.toString('utf8').trim(); } else if (field.fn === 18 && field.wt === 2) { projectId = field.payload.toString('utf8').trim(); - } else if (field.fn === 9 && field.wt === 2) { + } else if (field.fn === 5 && field.wt === 2) { parentConversationId = field.payload.toString('utf8').trim().toLowerCase(); + } else if (field.fn === 8 && field.wt === 2 && field.payload.length > 0) { + const specFields = splitProtoRawFields(field.payload); + if ( + specFields.some( + (sf) => + (sf.fn === 1 || sf.fn === 2) && + sf.wt === 2 && + sf.payload.toString('utf8').trim().length > 0 + ) + ) { + hasSubagentSpec = true; + } + } else if (field.fn === 17 && field.wt === 0) { + const st = { off: 0 }; + const depth = Number(BigInt.asIntN(32, readProtoVarint(field.payload, st, field.payload.length))); + if (Number.isFinite(depth) && depth > 0) nestingDepth = depth; } else if (field.fn === 2 && field.wt === 2 && !createdMs) { const tsFields = splitProtoRawFields(field.payload); const secField = tsFields.find((item) => item.fn === 1 && item.wt === 0); @@ -224,7 +242,55 @@ function migratorDecodeMetaBlobLight(rawBlob) { } } } - return { workspaceUri, projectId, parentConversationId, createdMs }; + return { + workspaceUri, + projectId, + parentConversationId, + nestingDepth, + hasSubagentSpec, + createdMs, + }; +} + +function migratorIsDbLightNonRoot(dbLight) { + if (!dbLight) return false; + return Boolean( + dbLight.trajectoryType === 22 || + dbLight.sourceNum === 16 || + dbLight.parentConversationId || + Number(dbLight.nestingDepth || 0) > 0 || + dbLight.hasSubagentSpec + ); +} + +function migratorIsSummaryNonRoot(summary) { + if (!summary) return false; + const parentId = String(summary.parent_conversation_id || '').trim(); + const depth = Number(summary.nesting_depth || 0); + const sourceStr = String(summary.source || '').trim(); + if (parentId || depth > 0 || sourceStr === 'CORTEX_TRAJECTORY_SOURCE_SUBAGENT') { + return true; + } + if (summary.raw_summary) { + const rawFields = splitProtoRawFields(summary.raw_summary); + for (const f of rawFields) { + if (f.fn === 22 && f.wt === 0) { + const st = { off: 0 }; + const ttVal = Number(BigInt.asUintN(32, readProtoVarint(f.payload, st, f.payload.length))); + if (ttVal === 22) return true; // 旁路提问 + } else if (f.fn === 20 && f.wt === 0) { + const st = { off: 0 }; + const srcVal = Number(BigInt.asUintN(32, readProtoVarint(f.payload, st, f.payload.length))); + if (srcVal === 16) return true; // CORTEX_TRAJECTORY_SOURCE_SUBAGENT + } else if (f.fn === 17 && f.wt === 2) { + const sumMeta = migratorDecodeMetaBlobLight(f.payload); + if (sumMeta.parentConversationId || sumMeta.nestingDepth > 0 || sumMeta.hasSubagentSpec) { + return true; + } + } + } + } + return false; } function migratorInspectConversationDbLight(dbPath, { needPromptTitle = false } = {}) { @@ -271,7 +337,14 @@ function migratorInspectConversationDbLight(dbPath, { needPromptTitle = false } // 忽略步骤读取异常 } - let metaBlobInfo = { workspaceUri: '', projectId: '', parentConversationId: '', createdMs: 0 }; + let metaBlobInfo = { + workspaceUri: '', + projectId: '', + parentConversationId: '', + nestingDepth: 0, + hasSubagentSpec: false, + createdMs: 0, + }; try { const blobRow = db .prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main' LIMIT 1") @@ -488,20 +561,7 @@ function migratorListClientSessions(clientDef, clientRoot, summaryMap, runningSe if (sessions.length >= MIGRATOR_MAX_SESSIONS_PER_CLIENT) break; const { cid, summary, info } = cand; - if (summary) { - const parentId = String(summary.parent_conversation_id || '').trim(); - const depth = Number(summary.nesting_depth || 0); - if (parentId || depth > 0) continue; - if (summary.raw_summary) { - const rawFields = splitProtoRawFields(summary.raw_summary); - const ttField = rawFields.find((f) => f.fn === 22 && f.wt === 0); - if (ttField) { - const st = { off: 0 }; - const ttVal = Number(BigInt.asUintN(32, readProtoVarint(ttField.payload, st, ttField.payload.length))); - if (ttVal === 22) continue; // 跳过旁路提问 - } - } - } + if (migratorIsSummaryNonRoot(summary)) continue; const annTitle = migratorReadAnnotationTitle(clientRoot, cid); const sumTitle = String(summary?.title || '').trim(); @@ -519,9 +579,7 @@ function migratorListClientSessions(clientDef, clientRoot, summaryMap, runningSe }); } - if (dbLight) { - if (dbLight.trajectoryType === 22 || dbLight.parentConversationId) continue; - } + if (migratorIsDbLightNonRoot(dbLight)) continue; const stepCount = summaryStepCount >= 0 ? summaryStepCount : Math.max(0, Number(dbLight?.stepCount || 0)); @@ -691,7 +749,7 @@ function migratorBuildWorkspaceSubmessage(rawUri, targetClientId) { function migratorBuildSummaryMetaBlob( sourceMetaBlob, - { srcCid = '', newCid, targetClientId, targetProjectId, rawUri, encodedUri } + { newCid, targetClientId, targetProjectId, rawUri, encodedUri } ) { const wsBytes = migratorBuildWorkspaceSubmessage(rawUri, targetClientId); const primaryUri = targetClientId === 'cli' ? rawUri : encodedUri; @@ -703,12 +761,6 @@ function migratorBuildSummaryMetaBlob( [18, encodeProtoStringField(18, targetProjectId)], ]); if (sourceMetaBlob && sourceMetaBlob.byteLength > 0) { - if (srcCid) { - const fn8 = splitProtoRawFields(sourceMetaBlob).find((f) => f.fn === 8 && f.wt === 2); - if (fn8 && fn8.payload.toString('utf8').trim().toLowerCase() === srcCid) { - replacements.set(8, encodeProtoStringField(8, newCid)); - } - } return patchProtoMessageFields(sourceMetaBlob, replacements); } const parts = []; @@ -819,7 +871,6 @@ function migratorPatchGenMetadataOwnership(rawBlob, srcCid, newCid) { function migratorBuildPatchedRawSummary({ sourceRawSummary, sourceMetaBlob, - srcCid = '', newCid, newTid, title, @@ -845,7 +896,6 @@ function migratorBuildPatchedRawSummary({ const rawFields = splitProtoRawFields(sourceRawSummary); const fn17 = rawFields.find((f) => f.fn === 17 && f.wt === 2); const patchedFn17 = migratorBuildSummaryMetaBlob(fn17?.payload || sourceMetaBlob, { - srcCid, newCid, targetClientId, targetProjectId, @@ -875,7 +925,6 @@ function migratorBuildPatchedRawSummary({ const createdTsBytes = encodeProtoTimestamp(createdMs || nowMs); const lastUiTsBytes = encodeProtoTimestamp(lastUserInputMs || nowMs); const synthMeta = migratorBuildSummaryMetaBlob(sourceMetaBlob, { - srcCid, newCid, targetClientId, targetProjectId, @@ -1100,6 +1149,10 @@ export function migrateSessions(params = {}, options = {}) { const dbLight = migratorInspectConversationDbLight(srcDbPath, { needPromptTitle: !annTitle && !srcSummary?.title && !srcSummary?.preview, }); + if (migratorIsSummaryNonRoot(srcSummary) || migratorIsDbLightNonRoot(dbLight)) { + results.push({ ok: false, sourceCascadeId: srcCid, error: 'non_root_session' }); + continue; + } const stepCount = Math.max( 0, Number(srcSummary?.step_count ?? dbLight?.stepCount ?? 0) @@ -1186,10 +1239,6 @@ export function migrateSessions(params = {}, options = {}) { [7, primaryMetaUri ? encodeProtoStringField(7, primaryMetaUri) : null], [18, encodeProtoStringField(18, resolvedProjectId)], ]); - const fn8 = splitProtoRawFields(sourceMetaBlob).find((f) => f.fn === 8 && f.wt === 2); - if (fn8 && fn8.payload.toString('utf8').trim().toLowerCase() === srcCid) { - metaReplacements.set(8, encodeProtoStringField(8, newCid)); - } const patchedMeta = patchProtoMessageFields(sourceMetaBlob, metaReplacements); dstDb .prepare("UPDATE trajectory_metadata_blob SET data = ? WHERE id = 'main'") @@ -1304,7 +1353,6 @@ export function migrateSessions(params = {}, options = {}) { const patchedRawSummary = migratorBuildPatchedRawSummary({ sourceRawSummary: srcSummary?.raw_summary || null, sourceMetaBlob, - srcCid, newCid, newTid, title: finalTitle, diff --git a/sidecars/panel/test/session-migration.test.mjs b/sidecars/panel/test/session-migration.test.mjs index 1c9d958..25caa79 100644 --- a/sidecars/panel/test/session-migration.test.mjs +++ b/sidecars/panel/test/session-migration.test.mjs @@ -51,7 +51,24 @@ function initSummaryDb(dbPath) { return db; } -function createConvDb(dbPath, { cid, tid, source = 17, projectId = 'default-cli-project', wsUri = 'file:///C:/Users/Test', promptText = 'hello from cli', stepCount = 2, preserveTag15 = true }) { +function createConvDb( + dbPath, + { + cid, + tid, + trajectoryType = 4, + source = 17, + projectId = 'default-cli-project', + wsUri = 'file:///C:/Users/Test', + promptText = 'hello from cli', + stepCount = 2, + preserveTag15 = true, + parentConversationId = '', + rootConversationId = '', + nestingDepth = 0, + subagentSpec = null, + } +) { const db = new DatabaseSync(dbPath); db.exec(` CREATE TABLE trajectory_meta ( @@ -84,16 +101,35 @@ function createConvDb(dbPath, { cid, tid, source = 17, projectId = 'default-cli- CREATE TABLE battle_mode_infos (idx integer PRIMARY KEY, data blob); `); - db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 4, ?)').run(tid, cid, source); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, ?, ?)').run( + tid, + cid, + trajectoryType, + source + ); const wsSub = Buffer.concat([encodeProtoStringField(1, wsUri), encodeProtoStringField(3, '')]); const metaParts = [ encodeProtoBytesField(1, wsSub), encodeProtoBytesField(2, encodeProtoTimestamp(1795000000000)), - encodeProtoStringField(6, cid), - encodeProtoStringField(7, wsUri), - encodeProtoStringField(18, projectId), ]; + if (parentConversationId) { + metaParts.push(encodeProtoStringField(5, parentConversationId)); + } + metaParts.push( + encodeProtoStringField(6, rootConversationId || parentConversationId || cid), + encodeProtoStringField(7, wsUri) + ); + if (subagentSpec && (subagentSpec.typeName || subagentSpec.role)) { + const specParts = []; + if (subagentSpec.typeName) specParts.push(encodeProtoStringField(1, subagentSpec.typeName)); + if (subagentSpec.role) specParts.push(encodeProtoStringField(2, subagentSpec.role)); + metaParts.push(encodeProtoBytesField(8, Buffer.concat(specParts))); + } + if (nestingDepth > 0) { + metaParts.push(encodeProtoVarintField(17, nestingDepth)); + } + metaParts.push(encodeProtoStringField(18, projectId)); if (preserveTag15) { metaParts.push(encodeProtoBytesField(15, Buffer.from([0xde, 0xad, 0xbe, 0xef]))); } @@ -362,10 +398,18 @@ test('Cross-client session migration clones CLI/Legacy-IDE/Desktop SQLite sessio ); cliSum.close(); - // Legacy IDE (.db without conversation_summaries.db) + // Legacy IDE (.db without conversation_summaries.db), including subagent & side-question .db files const legacyRoot = join(geminiDir, 'antigravity-ide'); mkdirSync(join(legacyRoot, 'conversations'), { recursive: true }); const legacyCid = '33333333-3333-4333-8333-333333333331'; + const legacySubFn5Cid = '33333333-3333-4333-8333-333333333332'; + const legacySubFn8Cid = '33333333-3333-4333-8333-333333333333'; + const legacySubFn17Cid = '33333333-3333-4333-8333-333333333334'; + const legacySubSrc16Cid = '33333333-3333-4333-8333-333333333335'; + const legacySideQCid = '33333333-3333-4333-8333-333333333336'; + const cliOrphanSubCid = '22222222-2222-4222-8222-222222222225'; + const cliRawMetaSubCid = '22222222-2222-4222-8222-222222222226'; + createConvDb(join(legacyRoot, 'conversations', `${legacyCid}.db`), { cid: legacyCid, tid: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1', @@ -375,17 +419,145 @@ test('Cross-client session migration clones CLI/Legacy-IDE/Desktop SQLite sessio promptText: 'Refactor legacy sidebar', stepCount: 4, }); + createConvDb(join(legacyRoot, 'conversations', `${legacySubFn5Cid}.db`), { + cid: legacySubFn5Cid, + tid: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2', + source: 1, + parentConversationId: legacyCid, + promptText: 'Subagent via fn=5 parentConversationId', + stepCount: 2, + }); + createConvDb(join(legacyRoot, 'conversations', `${legacySubFn8Cid}.db`), { + cid: legacySubFn8Cid, + tid: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb3', + source: 1, + subagentSpec: { typeName: 'research', role: 'Codebase Auditor' }, + promptText: 'Subagent via fn=8 subagentSpec', + stepCount: 2, + }); + createConvDb(join(legacyRoot, 'conversations', `${legacySubFn17Cid}.db`), { + cid: legacySubFn17Cid, + tid: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb4', + source: 1, + nestingDepth: 1, + promptText: 'Subagent via fn=17 nestingDepth', + stepCount: 2, + }); + createConvDb(join(legacyRoot, 'conversations', `${legacySubSrc16Cid}.db`), { + cid: legacySubSrc16Cid, + tid: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb5', + source: 16, + promptText: 'Subagent via source=16 CORTEX_TRAJECTORY_SOURCE_SUBAGENT', + stepCount: 2, + }); + createConvDb(join(legacyRoot, 'conversations', `${legacySideQCid}.db`), { + cid: legacySideQCid, + tid: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb6', + trajectoryType: 22, + source: 1, + promptText: 'Side question via trajectory_type=22', + stepCount: 2, + }); + // Orphan subagent .db missing from CLI conversation_summaries.db + createConvDb(join(cliRoot, 'conversations', `${cliOrphanSubCid}.db`), { + cid: cliOrphanSubCid, + tid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa5', + source: 17, + parentConversationId: cliIdleCid, + subagentSpec: { typeName: 'research', role: 'Orphan Explorer' }, + nestingDepth: 1, + promptText: 'Orphan CLI subagent without summary row', + stepCount: 2, + }); + // Summary row with blank SQL parent_conversation_id/nesting_depth but subagentSpec in raw_summary.fn17 + createConvDb(join(cliRoot, 'conversations', `${cliRawMetaSubCid}.db`), { + cid: cliRawMetaSubCid, + tid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa6', + source: 17, + subagentSpec: { typeName: 'browser', role: 'Page Inspector' }, + promptText: 'CLI subagent flagged in raw_summary.fn17', + stepCount: 2, + }); + const cliSumExtra = new DatabaseSync(join(cliRoot, 'conversation_summaries.db')); + cliSumExtra + .prepare( + `INSERT INTO conversation_summaries ( + conversation_id, title, preview, step_count, last_modified_time, + workspace_uris, status, source, project_id, parent_conversation_id, + nesting_depth, not_fully_idle, killed, last_user_input_time, + last_user_input_step_index, app_data_dir, raw_summary + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .run( + cliRawMetaSubCid, + 'Browser Helper', + 'Browser Helper', + 2, + '2026-11-21 11:55:00.000000+00:00', + '["file:///C:/Users/Administrator"]', + 'CASCADE_RUN_STATUS_IDLE', + '', + 'default-cli-project', + '', + 0, + 0, + 0, + '2026-11-21 11:55:00.000000+00:00', + 0, + 'antigravity-cli', + Buffer.concat([ + encodeProtoVarintField(2, 2), + encodeProtoBytesField( + 17, + encodeProtoBytesField( + 8, + Buffer.concat([ + encodeProtoStringField(1, 'browser'), + encodeProtoStringField(2, 'Page Inspector'), + ]) + ) + ), + ]) + ); + cliSumExtra.close(); const cat = getSessionMigrationCatalog({ geminiDir }); assert.equal(cat.available, true, 'Multi-client setup exposes migration catalog'); - assert.equal(cat.sessionsByClient.cli.length, 2, 'Excludes subagent and 0-step empty CLI sessions'); + assert.equal( + cat.sessionsByClient.cli.length, + 2, + 'Excludes summary-flagged, raw_summary.fn17-flagged, orphan .db subagent, and 0-step CLI sessions' + ); const idleItem = cat.sessionsByClient.cli.find((s) => s.cascadeId === cliIdleCid); const runItem = cat.sessionsByClient.cli.find((s) => s.cascadeId === cliRunCid); assert.equal(idleItem.title, 'Fix Braille progress bar width', 'Falls back to cleaned first user prompt title'); assert.equal(idleItem.isRunning, false); assert.equal(runItem.isRunning, true); - assert.equal(cat.sessionsByClient.ide_legacy.length, 1); + assert.equal( + cat.sessionsByClient.ide_legacy.length, + 1, + 'Excludes fn=5, fn=8, fn=17, source=16 subagents and trajectory_type=22 side-questions in summaryless ide_legacy' + ); + assert.equal(cat.sessionsByClient.ide_legacy[0].cascadeId, legacyCid); assert.equal(cat.sessionsByClient.ide_legacy[0].title, 'Refactor legacy sidebar'); + + // Direct migrateSessions call rejects non-root subagent / side-question IDs even without summary DB + const nonRootMigRes = migrateSessions( + { + sourceClient: 'ide_legacy', + targetClient: 'desktop', + mode: 'clone', + cascadeIds: [legacySubFn5Cid, legacySubFn8Cid, legacySubFn17Cid, legacySubSrc16Cid, legacySideQCid], + }, + { geminiDir, backupDir } + ); + assert.equal(nonRootMigRes.ok, false); + assert.equal(nonRootMigRes.migratedCount, 0); + assert.equal(nonRootMigRes.results.length, 5); + for (const r of nonRootMigRes.results) { + assert.equal(r.ok, false); + assert.equal(r.error, 'non_root_session'); + } assert.ok(cat.desktopProjects.some((p) => p.projectId === projId && p.name === 'antigravity-usage-monitor')); assert.ok(cat.desktopProjects.some((p) => p.projectId === 'outside-of-project' && p.isOutsideProject)); From 0b700d1f9f3c3b3cd17e7616061fd48cfa75d829 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 16:13:42 +0900 Subject: [PATCH 16/30] fix(panel): align bridge export body limits and cap Excel cell text - Raise BRIDGE_MAX_EXPORT_BODY_BYTES to 12 MiB so 8 MiB Base64-encoded exports and verified __exportFileAction /api/settings fallbacks are not rejected with 413. - Cap xlsxBuilder inline string cells at Excel's 32,767 UTF-16 code unit limit without splitting surrogate pairs and replace lone surrogates. --- sidecars/panel/app.js | 32 +++++++++--- sidecars/panel/backend/window-bridge.mjs | 36 ++++++++++++-- sidecars/panel/index.html | 4 +- sidecars/panel/src/core/xlsxBuilder.js | 28 +++++++++-- .../test/cross-module-regressions.test.mjs | 32 ++++++++++++ sidecars/panel/test/window-bridge.test.mjs | 49 ++++++++++++++++++- 6 files changed, 165 insertions(+), 16 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index c51f470..c06b8f3 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -6161,7 +6161,7 @@ return { triggerBlobDownload, triggerTextFileDownload, buildExportableSettingsJs })(); // --- src/core/xlsxBuilder.js --- -const { uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { +const { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { /** * @fileoverview 零外部依赖原生 Excel (`.xlsx` / ECMA-376 OOXML) 多工作表构建器 (`xlsxBuilder.js`)。 * 内置标准 IEEE 802.3 CRC-32 及 ZIP STORE 封装,支持: @@ -6172,7 +6172,10 @@ const { uint8ArrayToBase64, buildXlsxWorkbookBytes } = (() => { * - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。 */ +const MAX_EXCEL_CELL_CHARS = 32767; const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g; +const LONE_SURROGATE_RE = + /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?= 0xd800 && prevCode <= 0xdbff) { + cut -= 1; + } + return `${clean.slice(0, cut)}…`; +} + +function escapeXmlText(val) { + return sanitizeExcelCellText(val) .replace(/&/g, '&') .replace(//g, '>') @@ -6390,10 +6408,12 @@ function columnIndexToLetter(index) { } /** - * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。 + * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽; + * 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。 */ function measureExcelVisualWidth(str) { - const s = String(str ?? '').replace(/\r?\n/g, ' '); + const raw = String(str ?? ''); + const s = (raw.length > 128 ? raw.slice(0, 128) : raw).replace(/\r?\n/g, ' '); let w = 0; for (let i = 0; i < s.length; i += 1) { const code = s.charCodeAt(i); @@ -6805,7 +6825,7 @@ function buildXlsxWorkbookBytes(sheets) { return buildZipStoreArchive(archiveEntries); } -return { uint8ArrayToBase64, buildXlsxWorkbookBytes }; +return { MAX_EXCEL_CELL_CHARS, uint8ArrayToBase64, buildXlsxWorkbookBytes }; })(); // --- src/core/reportExporter.js --- diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index bf96b6c..211fd8d 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -71,7 +71,8 @@ const overlayMethods = Object.fromEntries( ); const BRIDGE_MAX_BODY_BYTES = 64 * 1024; -const BRIDGE_MAX_EXPORT_BODY_BYTES = 8 * 1024 * 1024; +// 8 MiB 原始导出文件经 Base64 (4/3x) 编码和 JSON 封装后约 10.7 MiB,预留 12 MiB 请求体上限 +const BRIDGE_MAX_EXPORT_BODY_BYTES = 12 * 1024 * 1024; const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS); /** @@ -1343,17 +1344,34 @@ export function createWindowBridgeController(options) { return; } - const maxBodyBytes = + let maxBodyBytes = parsedUrl.pathname === '/api/export-file' ? BRIDGE_MAX_EXPORT_BODY_BYTES : BRIDGE_MAX_BODY_BYTES; const chunks = []; let totalBytes = 0; let aborted = false; + let checkedSettingsExportPrefix = false; req.on('data', (chunk) => { - totalBytes += chunk.length; + const nextTotal = totalBytes + chunk.length; + if ( + nextTotal > maxBodyBytes && + !checkedSettingsExportPrefix && + parsedUrl.pathname === '/api/settings' && + nextTotal <= BRIDGE_MAX_EXPORT_BODY_BYTES + ) { + checkedSettingsExportPrefix = true; + const sampleParts = chunks.length > 0 ? [...chunks, chunk] : [chunk]; + const headBuf = Buffer.concat(sampleParts, Math.min(nextTotal, 512)); + const headStr = headBuf.toString('utf8').trimStart(); + if (/^\{\s*"__exportFileAction"\s*:\s*"(?:save|reveal)"/.test(headStr)) { + maxBodyBytes = BRIDGE_MAX_EXPORT_BODY_BYTES; + } + } + totalBytes = nextTotal; if (totalBytes > maxBodyBytes) { aborted = true; + chunks.length = 0; res.writeHead(413, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Payload too large' })); req.destroy(); @@ -1372,6 +1390,18 @@ export function createWindowBridgeController(options) { res.end(JSON.stringify({ error: 'Invalid JSON body' })); return; } + if ( + totalBytes > BRIDGE_MAX_BODY_BYTES && + parsedUrl.pathname === '/api/settings' && + (!bodyObj || + typeof bodyObj !== 'object' || + Array.isArray(bodyObj) || + typeof bodyObj.__exportFileAction !== 'string') + ) { + res.writeHead(413, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Payload too large' })); + return; + } Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'POST', bodyObj, normalizedReqEndpoint)) .then((out) => { const hdrs = { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 7c9ed05..2cff9c0 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/core/xlsxBuilder.js b/sidecars/panel/src/core/xlsxBuilder.js index b9890f3..e1e1a30 100644 --- a/sidecars/panel/src/core/xlsxBuilder.js +++ b/sidecars/panel/src/core/xlsxBuilder.js @@ -8,7 +8,10 @@ * - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。 */ +export const MAX_EXCEL_CELL_CHARS = 32767; const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g; +const LONE_SURROGATE_RE = + /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?= 0xd800 && prevCode <= 0xdbff) { + cut -= 1; + } + return `${clean.slice(0, cut)}…`; +} + +function escapeXmlText(val) { + return sanitizeExcelCellText(val) .replace(/&/g, '&') .replace(//g, '>') @@ -226,10 +244,12 @@ function columnIndexToLetter(index) { } /** - * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。 + * 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽; + * 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。 */ function measureExcelVisualWidth(str) { - const s = String(str ?? '').replace(/\r?\n/g, ' '); + const raw = String(str ?? ''); + const s = (raw.length > 128 ? raw.slice(0, 128) : raw).replace(/\r?\n/g, ' '); let w = 0; for (let i = 0; i < s.length; i += 1) { const code = s.charCodeAt(i); diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 611360b..87ed9ec 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1641,3 +1641,35 @@ test('i18n static t(...) key completeness guard, scopeAll formatters, and locali globalThis.window = prevWin; } }); + +test('xlsxBuilder enforces 32,767 UTF-16 cell limit without splitting surrogate pairs or emitting lone surrogates', async () => { + const { buildXlsxWorkbookBytes, MAX_EXCEL_CELL_CHARS } = await import('../src/core/xlsxBuilder.js'); + assert.equal(MAX_EXCEL_CELL_CHARS, 32767); + + // Place an emoji ('😀' = \uD83D\uDE00, 2 UTF-16 code units) straddling index 32765..32766 + const boundaryEmojiText = `${'A'.repeat(32765)}😀${'B'.repeat(500)}`; + const loneSurrogateText = `ok\uD800mid\uDC00end`; + const bytes = buildXlsxWorkbookBytes([ + { + name: 'OverflowGuard', + columns: [{ header: 'TextCol', type: 'text' }], + rows: [[boundaryEmojiText], [loneSurrogateText]], + }, + ]); + + const rawArchiveStr = Buffer.from(bytes).toString('utf8'); + const cellMatches = [...rawArchiveStr.matchAll(/]*>]*>([\s\S]*?)<\/t><\/is><\/c>/g)]; + assert.equal(cellMatches.length, 2); + + const cellA2 = cellMatches[0][1]; + assert.ok( + cellA2.length <= MAX_EXCEL_CELL_CHARS, + `Expected <= 32767 UTF-16 code units, got ${cellA2.length}` + ); + assert.equal(cellA2.length, 32766, 'Backs off by 1 code unit before emoji high surrogate + ellipsis'); + assert.ok(cellA2.endsWith('…')); + assert.equal(/[\uD800-\uDFFF]/.test(cellA2), false, 'No split surrogate code unit remains'); + + const cellA3 = cellMatches[1][1]; + assert.equal(cellA3, 'ok\uFFFDmid\uFFFDend'); +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index e91da06..452bc8a 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -345,7 +345,8 @@ test('Loopback HTTP bridge enforces Origin, Private Network CORS, token auth, an assert.equal(postBody.echoData.enableWindowOverlay, false); assert.equal(receivedCalls.length, 3); - // 6. Oversized POST body -> 413 + // 6. Oversized POST body -> 413 for regular /api/settings (including spoofed nested strings), + // while legitimate __exportFileAction fallback (>64 KiB) and 8 MiB Base64 /api/export-file (~10.7 MiB JSON) succeed const hugePayload = JSON.stringify({ pad: 'x'.repeat(70 * 1024) }); const hugeRes = await fetch(`http://127.0.0.1:${port}/api/settings`, { method: 'POST', @@ -357,6 +358,52 @@ test('Loopback HTTP bridge enforces Origin, Private Network CORS, token auth, an body: hugePayload, }).catch(() => ({ status: 413 })); assert.equal(hugeRes.status, 413); + + const spoofedSettingsPayload = JSON.stringify({ + note: '{"__exportFileAction":"save"}', + pad: 'y'.repeat(70 * 1024), + }); + const spoofedRes = await fetch(`http://127.0.0.1:${port}/api/settings`, { + method: 'POST', + headers: { + Origin: validOrigin, + 'Content-Type': 'application/json', + 'X-Usage-Monitor-Token': token, + }, + body: spoofedSettingsPayload, + }).catch(() => ({ status: 413 })); + assert.equal(spoofedRes.status, 413); + + const fallbackExportRes = await fetch(`http://127.0.0.1:${port}/api/settings`, { + method: 'POST', + headers: { + Origin: validOrigin, + 'Content-Type': 'application/json', + 'X-Usage-Monitor-Token': token, + }, + body: JSON.stringify({ + __exportFileAction: 'save', + payload: { filename: 'fallback.xlsx', encoding: 'base64', content: 'A'.repeat(200 * 1024) }, + }), + }); + assert.equal(fallbackExportRes.status, 200); + + // 8 MiB binary encoded as Base64 (~10.67 MiB) fits within 12 MiB BRIDGE_MAX_EXPORT_BODY_BYTES + const eightMibBase64 = Buffer.alloc(8 * 1024 * 1024, 0x50).toString('base64'); + const maxExportRes = await fetch(`http://127.0.0.1:${port}/api/export-file`, { + method: 'POST', + headers: { + Origin: validOrigin, + 'Content-Type': 'application/json', + 'X-Usage-Monitor-Token': token, + }, + body: JSON.stringify({ + filename: 'max-8mib.xlsx', + encoding: 'base64', + content: eightMibBase64, + }), + }); + assert.equal(maxExportRes.status, 200); } finally { await controller.stop(); } From 1692599fd8d4d99916adb03ab9b79c5f98feab9a Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 19:23:38 +0900 Subject: [PATCH 17/30] fix(panel): remove range-switch font flicker and simplify rate popover - Drop transparent-container opacity animations on ConsumptionView and TrendAreaChart range switches that forced DirectWrite grayscale AA transitions, and pool trend X-axis ticks, grid lines, and heatmap cells in-place - Remove the redundant weekly quota summary row, internal hairlines, and bottom note from the QuotaPoolsWidget empirical burn-rate popover --- sidecars/panel/app.js | 409 ++++++------------ sidecars/panel/index.html | 4 +- .../src/components/charts/TrendAreaChart.js | 241 ++++++----- .../components/widgets/QuotaPoolsWidget.js | 146 +------ sidecars/panel/src/i18n/en-US.js | 4 - sidecars/panel/src/i18n/zh-CN.js | 4 - sidecars/panel/src/styles/modern-ui.css | 19 +- .../panel/src/styles/views-consumption.css | 59 +-- sidecars/panel/src/styles/views-overview.css | 79 +--- sidecars/panel/src/views/ConsumptionView.js | 14 +- sidecars/panel/styles.css | 157 +------ .../test/cross-module-regressions.test.mjs | 201 +++++++++ .../panel/test/quota-reservation.test.mjs | 42 +- 13 files changed, 505 insertions(+), 874 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index c06b8f3..126e59a 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1463,9 +1463,6 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopTitle': '实测倍率预估', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': '当前账号', - 'quota.ratePopWkCapTitle': '预测周额度', - 'quota.ratePopWkCapPrelim': '· 初估', - 'quota.ratePopWkCapPartial': '· {ready}/{total} 池', 'quota.ratePopPoolFallback': '池综合均值', 'quota.ratePopEq5hLabel': '5h 满池', 'quota.ratePopEqWkLabel': '周限满池', @@ -1474,7 +1471,6 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopPrelimSlope': '斜率初估', 'quota.ratePopPrelimCycle': '周期初估', 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。', - 'quota.ratePopNote': '按净消耗及精确计价折算,同池最省为 1x,按账号隔离。', 'quota.ratePopSharedBadge': '共享活跃', 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', @@ -2366,9 +2362,6 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopTitle': 'Estimated Burn Rates', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': 'Current account', - 'quota.ratePopWkCapTitle': 'Est. Weekly Quota', - 'quota.ratePopWkCapPrelim': '· est.', - 'quota.ratePopWkCapPartial': '· {ready}/{total} pools', 'quota.ratePopPoolFallback': 'Pool average', 'quota.ratePopEq5hLabel': '5h full', 'quota.ratePopEqWkLabel': 'Weekly full', @@ -2377,7 +2370,6 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopPrelimSlope': 'slope est.', 'quota.ratePopPrelimCycle': 'cycle est.', 'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).', - 'quota.ratePopNote': 'Measured from net burn & priced steps; lowest in pool = 1x. Account isolated.', 'quota.ratePopSharedBadge': 'Shared active', 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', @@ -14244,8 +14236,6 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let hoveredCellEl = null; let lastPointer = null; let lastRenderSig = ''; - let lastTickLabelsSig = ''; - let hasRenderedOnce = false; let hasRenderedLineOnce = false; let peakReadyArmed = false; let peakReadyRaf = 0; @@ -14253,40 +14243,13 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let morphRafId = 0; let committedSegs = []; let liveMorphSegs = null; - const transientClassTimers = new Map(); + const vGridLinePool = []; + const xAxisTickPool = []; + const hmMonthPool = []; + const hmCellPool = []; const CURVE_MORPH_DURATION_MS = 240; - function cleanupTransientClass(el) { - const rec = transientClassTimers.get(el); - if (!rec) return; - clearTimeout(rec.tid); - el?.removeEventListener?.('animationend', rec.onEnd); - el?.classList?.remove(rec.cls); - transientClassTimers.delete(el); - } - - function triggerTransientClass(el, cls, fallbackMs = 650) { - if (!el || !el.classList) return; - cleanupTransientClass(el); - el.classList.remove(cls); - void el.offsetWidth; - const onEnd = (ev) => { - if (ev && ev.target && ev.target !== el) return; - cleanupTransientClass(el); - }; - const tid = setTimeout(() => cleanupTransientClass(el), fallbackMs); - transientClassTimers.set(el, { cls, tid, onEnd }); - el.addEventListener?.('animationend', onEnd); - el.classList.add(cls); - } - - function clearAllTransientTimers() { - for (const el of Array.from(transientClassTimers.keys())) { - cleanupTransientClass(el); - } - } - function cancelCurveMorph() { if ( morphRafId && @@ -14912,7 +14875,6 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { cancelTipTrackRaf(); cancelCurveMorph(); cancelPeakReadyRaf(); - clearAllTransientTimers(); plotStage.removeEventListener('mousemove', handlePointerMove); plotStage.removeEventListener('click', handleLineClick); plotStage.removeEventListener('mouseleave', clearHover); @@ -14961,14 +14923,6 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { patchAttr(plotStage, 'hidden', useHeatmap); patchAttr(xAxisEl, 'hidden', useHeatmap); patchAttr(heatmapStage, 'hidden', !useHeatmap); - if (hasRenderedOnce && modeChanged && canAnimateInBrowser()) { - if (useHeatmap) { - triggerTransientClass(heatmapStage, 'is-stage-entering'); - } else { - triggerTransientClass(plotStage, 'is-stage-entering'); - triggerTransientClass(xAxisEl, 'is-switching'); - } - } if (!useHeatmap) { syncViewWidth(); @@ -15042,51 +14996,97 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks)); patchStyleVar(hmBodyEl, '--hm-gap', `${gapPx}px`); - // 重建顶部对齐月份标签 - while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild); + // 就地增量补丁顶部对齐月份标签,避免文字节点销毁重建 const monthTicks = buildHeatmapMonthTicks(slots, firstDow, totalWeeks); - for (const mt of monthTicks) { - const mEl = h('span', { className: 'trend-hm-month text-mono', text: mt.text }); + for (let i = 0; i < monthTicks.length; i++) { + const mt = monthTicks[i]; + let mEl = hmMonthPool[i]; + if (!mEl) { + mEl = h('span', { className: 'trend-hm-month text-mono' }); + hmMonthPool.push(mEl); + } + patchText(mEl, mt.text); patchStyleVar(mEl, '--hm-col', String(mt.col)); - hmMonthsEl.appendChild(mEl); + if (hmMonthsEl.children[i] !== mEl) { + hmMonthsEl.insertBefore(mEl, hmMonthsEl.children[i] || null); + } + } + while (hmMonthsEl.children.length > monthTicks.length) { + hmMonthsEl.removeChild(hmMonthsEl.lastChild); } - // 重建 7 行 × N 周列的每日小格子(一格一天),使用 DocumentFragment 一次性批量挂载减少重排 - while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild); - hoveredCellEl = null; + // 就地增量复用 7 行 × N 周列的每日小格子,首次批量新增节点使用 DocumentFragment 挂载 currentCellEls = new Array(slots.length); - const gridFrag = - typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function' + const prevMountedCount = hmGridEl.children.length; + const newCellsFrag = + totalCells > prevMountedCount && + typeof document !== 'undefined' && + typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : null; - const gridTarget = gridFrag || hmGridEl; - for (let pad = 0; pad < firstDow; pad++) { - gridTarget.appendChild( - h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' }) - ); + for (let nodeIdx = 0; nodeIdx < totalCells; nodeIdx++) { + let cellEl = hmCellPool[nodeIdx]; + if (!cellEl) { + cellEl = h('span', { className: 'trend-hm-cell' }); + hmCellPool.push(cellEl); + } + if (nodeIdx < firstDow) { + patchClasses(cellEl, { + 'is-pad': true, + 'is-hovered': false, + 'lv-0': false, + 'lv-1': false, + 'lv-2': false, + 'lv-3': false, + 'lv-4': false, + }); + patchAttr(cellEl, 'aria-hidden', 'true'); + patchAttr(cellEl, 'role', null); + patchAttr(cellEl, 'data-slot-idx', null); + patchAttr(cellEl, 'data-hm-col', null); + patchAttr(cellEl, 'data-hm-row', null); + } else { + const i = nodeIdx - firstDow; + const slot = slots[i]; + const tok = safeSlotTokens(slot?.tokens); + const lv = resolveHeatmapLevel(tok, thresholds); + const col = Math.floor(nodeIdx / 7); + const row = nodeIdx % 7; + patchClasses(cellEl, { + 'is-pad': false, + 'is-hovered': hoveredIdx === i, + 'lv-0': lv === 0, + 'lv-1': lv === 1, + 'lv-2': lv === 2, + 'lv-3': lv === 3, + 'lv-4': lv === 4, + }); + patchAttr(cellEl, 'aria-hidden', null); + patchAttr(cellEl, 'role', 'gridcell'); + patchAttr(cellEl, 'data-slot-idx', String(i)); + patchAttr(cellEl, 'data-hm-col', String(col)); + patchAttr(cellEl, 'data-hm-row', String(row)); + currentCellEls[i] = cellEl; + } + if (nodeIdx < prevMountedCount) { + if (hmGridEl.children[nodeIdx] !== cellEl) { + hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); + } + } else if (newCellsFrag) { + newCellsFrag.appendChild(cellEl); + } else { + hmGridEl.appendChild(cellEl); + } } - - for (let i = 0; i < slots.length; i++) { - const slot = slots[i]; - const tok = safeSlotTokens(slot?.tokens); - const lv = resolveHeatmapLevel(tok, thresholds); - const gridPos = firstDow + i; - const col = Math.floor(gridPos / 7); - const row = gridPos % 7; - const cellEl = h('span', { - className: `trend-hm-cell lv-${lv}`, - 'data-slot-idx': String(i), - 'data-hm-col': String(col), - 'data-hm-row': String(row), - role: 'gridcell', - }); - gridTarget.appendChild(cellEl); - currentCellEls[i] = cellEl; + if (newCellsFrag) { + hmGridEl.appendChild(newCellsFrag); } - if (gridFrag) { - hmGridEl.appendChild(gridFrag); + while (hmGridEl.children.length > totalCells) { + hmGridEl.removeChild(hmGridEl.lastChild); } + hoveredCellEl = + hoveredIdx >= 0 && hoveredIdx < slots.length ? currentCellEls[hoveredIdx] || null : null; if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => { @@ -15114,7 +15114,6 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } else if (hoveredIdx >= 0) { showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer); } - hasRenderedOnce = true; return; } @@ -15175,21 +15174,11 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } hasRenderedLineOnce = true; - // 渲染对齐底部刻度的垂直参考网格线及 X 轴标签(起止标签严格左右贴边) + // 就地增量补丁垂直参考网格线及底部 X 轴标签,保持文字常驻不重排不闪烁 const tickIndices = computeTickIndices(slots); - const nextTickLabelsSig = tickIndices - .map((tIdx) => `${tIdx}:${slots[tIdx]?.label || ''}`) - .join('|'); - const ticksChanged = - hasRenderedOnce && - !modeChanged && - lastTickLabelsSig !== '' && - nextTickLabelsSig !== lastTickLabelsSig; - lastTickLabelsSig = nextTickLabelsSig; - - while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild); - while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); tickElsByIdx = new Map(); + let vLineCount = 0; + let tickCount = 0; for (let i = 0; i < tickIndices.length; i++) { const tIdx = tickIndices[i]; @@ -15198,34 +15187,57 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { if (!pt || !slot) continue; if (i > 0 && i < tickIndices.length - 1) { - const vLine = document.createElementNS(SVG_NS, 'line'); - vLine.setAttribute('x1', pt.x.toFixed(1)); - vLine.setAttribute('y1', '16'); - vLine.setAttribute('x2', pt.x.toFixed(1)); - vLine.setAttribute('y2', String(BOTTOM_Y)); - vGridGroup.appendChild(vLine); + let vLine = vGridLinePool[vLineCount]; + if (!vLine) { + vLine = document.createElementNS(SVG_NS, 'line'); + vLine.setAttribute('y1', '16'); + vLine.setAttribute('y2', String(BOTTOM_Y)); + vGridLinePool.push(vLine); + } + const xFixed = pt.x.toFixed(1); + patchAttr(vLine, 'x1', xFixed); + patchAttr(vLine, 'x2', xFixed); + if (vGridGroup.children[vLineCount] !== vLine) { + vGridGroup.insertBefore(vLine, vGridGroup.children[vLineCount] || null); + } + vLineCount++; } const isFirst = !isSingle && i === 0; const isLast = !isSingle && i === tickIndices.length - 1; const pct = isFirst ? 0 : isLast ? 100 : (pt.x / viewW) * 100; - const tickEl = h('span', { - className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, - text: slot.label || '', - title: formatTrendSlotFullLabel(slot) || slot.label || '', + let tickRec = xAxisTickPool[tickCount]; + if (!tickRec) { + const el = h('span', { className: 'trend-x-tick text-mono' }); + const rec = { el, slotIdx: tIdx }; + el.onclick = () => { + lastPointer = null; + showLineHoverAtIndex(rec.slotIdx); + }; + tickRec = rec; + xAxisTickPool.push(tickRec); + } + tickRec.slotIdx = tIdx; + patchClasses(tickRec.el, { + 'is-start': isFirst, + 'is-end': isLast, + 'is-hovered': hoveredIdx === tIdx, }); - patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); - tickEl.onclick = () => { - lastPointer = null; - showLineHoverAtIndex(tIdx); - }; - xAxisEl.appendChild(tickEl); - tickElsByIdx.set(tIdx, tickEl); + patchText(tickRec.el, slot.label || ''); + patchAttr(tickRec.el, 'title', formatTrendSlotFullLabel(slot) || slot.label || ''); + patchStyleVar(tickRec.el, '--tick-x', `${pct.toFixed(2)}%`); + if (xAxisEl.children[tickCount] !== tickRec.el) { + xAxisEl.insertBefore(tickRec.el, xAxisEl.children[tickCount] || null); + } + tickElsByIdx.set(tIdx, tickRec.el); + tickCount++; } - if (ticksChanged && canAnimateInBrowser()) { - triggerTransientClass(xAxisEl, 'is-switching'); - triggerTransientClass(vGridGroup, 'is-switching'); + while (vGridGroup.children.length > vLineCount) { + vGridGroup.removeChild(vGridGroup.lastChild); + } + while (xAxisEl.children.length > tickCount) { + xAxisEl.removeChild(xAxisEl.lastChild); } } @@ -15259,7 +15271,6 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } else if (hoveredIdx >= 0) { showLineHoverAtIndex(hoveredIdx, lastPointer); } - hasRenderedOnce = true; } return { el: chartWrap, update, destroy }; @@ -19598,88 +19609,6 @@ function formatPoolFullCapRef(eqUsd, eqTok) { return usdStr; } -function resolveWeeklyCapacitySummary(quotas) { - if (!quotas || typeof quotas !== 'object') return null; - if (quotas.weekly?.isOfficial === false) return null; - const direct = quotas.weeklyCapacityEstimate; - if (direct && typeof direct === 'object') { - if ( - direct.status === 'custom_mode' || - !Number.isFinite(Number(direct.totalEqWeeklyUsd)) || - Number(direct.totalEqWeeklyUsd) <= 0 - ) { - return null; - } - return direct; - } - - const rawPools = Array.isArray(quotas.pools) ? quotas.pools : []; - const candidatePools = rawPools.filter( - (p) => - p && - (p.hasWeekly || - p.weeklyUsedPct != null || - Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) - ); - const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; - if (targetPools.length === 0) return null; - - let sumUsd = 0; - let sumTokens = 0; - let readyPoolCount = 0; - let tokenReadyPoolCount = 0; - let hasPreliminary = false; - - for (const p of targetPools) { - const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; - let eqUsd = - Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 - ? Number(est.eqFullWeeklyUsd) - : null; - let eqTok = - Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 - ? Math.round(Number(est.eqFullWeeklyTokens)) - : null; - if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { - const wkModels = est.models.filter( - (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 - ); - if (wkModels.length > 0) { - eqUsd = - wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; - const tokModels = wkModels.filter( - (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 - ); - if (tokModels.length === wkModels.length) { - eqTok = Math.round( - tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length - ); - } - } - } - if (eqUsd !== null) { - readyPoolCount += 1; - sumUsd += eqUsd; - if (est?.isPreliminaryWeekly) hasPreliminary = true; - if (eqTok !== null) { - tokenReadyPoolCount += 1; - sumTokens += eqTok; - } - } - } - - if (readyPoolCount === 0) return null; - const totalPoolCount = targetPools.length; - return { - status: readyPoolCount < totalPoolCount ? 'partial' : 'ready', - totalEqWeeklyUsd: +sumUsd.toFixed(1), - totalEqWeeklyTokens: tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, - readyPoolCount, - totalPoolCount, - hasPreliminary, - }; -} - function formatRatePerUsdValue(rate) { const num = Number(rate); if (!Number.isFinite(num) || num <= 0) return '--'; @@ -19804,13 +19733,11 @@ function createRateModelCard({ function buildRatePopoverSig(data) { const locale = getEffectiveLocale(); const acct = String(data?.account?.email || data?.account?.name || '').trim(); - const isOfficial = data?.quotas?.weekly?.isOfficial !== false; - const wkCapSig = JSON.stringify(data?.quotas?.weeklyCapacityEstimate || null); const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; const poolSig = pools .map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`) .join('|'); - return `${locale}|${acct}|${isOfficial}|${wkCapSig}|${poolSig}`; + return `${locale}|${acct}|${poolSig}`; } const QuotaPoolsWidget = defineComponent({ @@ -19828,32 +19755,7 @@ const QuotaPoolsWidget = defineComponent({ className: 'quota-rate-pop-account', text: t('quota.ratePopAccountCurrent'), }); - const ratePopWkLabelEl = h('span', { text: t('quota.ratePopWkCapTitle') }); - const ratePopWkSubEl = h('span', { - className: 'quota-rate-wk-sub', - hidden: true, - text: '', - }); - const ratePopWkUsdEl = h('span', { className: 'quota-rate-wk-usd text-mono', text: '--' }); - const ratePopWkTokEl = h('span', { - className: 'quota-rate-wk-tok text-mono', - hidden: true, - text: '', - }); - const ratePopWkSummaryEl = h( - 'div', - { className: 'quota-rate-wk-summary', hidden: true }, - [ - h('span', { className: 'quota-rate-wk-k' }, [ratePopWkLabelEl, ratePopWkSubEl]), - h('span', { className: 'quota-rate-wk-v' }, [ratePopWkUsdEl, ratePopWkTokEl]), - ] - ); - ratePopWkSummaryEl.hidden = true; const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); - const ratePopNoteEl = h('div', { - className: 'quota-rate-pop-note', - text: t('quota.ratePopNote'), - }); const ratePopoverEl = h( 'div', { @@ -19863,9 +19765,7 @@ const QuotaPoolsWidget = defineComponent({ }, [ h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), - ratePopWkSummaryEl, ratePopBodyEl, - ratePopNoteEl, ] ); ratePopoverEl.hidden = true; @@ -19943,7 +19843,6 @@ const QuotaPoolsWidget = defineComponent({ lastRatePopSig = sig; patchText(ratePopTitleEl, t('quota.ratePopTitle')); - patchText(ratePopNoteEl, t('quota.ratePopNote')); patchAttr(rateHelpBtn, 'aria-label', t('quota.rateHelpAria')); const acctMasked = maskAccountLabel(data?.account?.email || data?.account?.name || ''); @@ -19955,38 +19854,6 @@ const QuotaPoolsWidget = defineComponent({ ); patchAttr(ratePopAccountEl, 'title', acctMasked || null); - const wkCap = resolveWeeklyCapacitySummary(data?.quotas); - if (wkCap) { - ratePopWkSummaryEl.hidden = false; - patchAttr(ratePopWkSummaryEl, 'hidden', false); - patchText(ratePopWkLabelEl, t('quota.ratePopWkCapTitle')); - const wkSubText = - wkCap.status === 'partial' && Number(wkCap.totalPoolCount) > 0 - ? t('quota.ratePopWkCapPartial', { - ready: Number(wkCap.readyPoolCount) || 0, - total: Number(wkCap.totalPoolCount) || 0, - }) - : wkCap.hasPreliminary - ? t('quota.ratePopWkCapPrelim') - : ''; - ratePopWkSubEl.hidden = !wkSubText; - patchAttr(ratePopWkSubEl, 'hidden', !wkSubText); - patchText(ratePopWkSubEl, wkSubText); - patchText(ratePopWkUsdEl, `≈ ${formatRateEqUsd(wkCap.totalEqWeeklyUsd)}`); - const hasWkTok = - Number.isFinite(Number(wkCap.totalEqWeeklyTokens)) && - Number(wkCap.totalEqWeeklyTokens) > 0; - ratePopWkTokEl.hidden = !hasWkTok; - patchAttr(ratePopWkTokEl, 'hidden', !hasWkTok); - patchText( - ratePopWkTokEl, - hasWkTok ? `· ${formatTokens(Number(wkCap.totalEqWeeklyTokens))}` : '' - ); - } else { - ratePopWkSummaryEl.hidden = true; - patchAttr(ratePopWkSummaryEl, 'hidden', true); - } - while (ratePopBodyEl.firstChild) { ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); } @@ -30473,11 +30340,7 @@ const ConsumptionView = defineComponent({ let lastAnimatedRankingKey = ''; let lastAnimatedSortSig = ''; const consAnimTimers = new Map(); - const TRANSIENT_CONS_CLASSES = [ - 'is-range-switching', - 'is-tab-entering', - 'is-bars-revealing', - ]; + const TRANSIENT_CONS_CLASSES = ['is-bars-revealing']; function cleanupConsAnim(el) { const rec = consAnimTimers.get(el); @@ -32295,13 +32158,7 @@ const ConsumptionView = defineComponent({ !tabSwitched && nextSortSig !== lastAnimatedSortSig; - if (rangeSwitched) { - triggerConsAnim(unifiedMatrixEl, 'is-range-switching'); - triggerConsAnim(activeRankingEl, 'is-range-switching'); - triggerConsAnim(sourcesListEl, 'is-range-switching'); - } else if (tabSwitched) { - triggerConsAnim(activeRankingEl, 'is-tab-entering'); - } else if (sortSwitched) { + if (tabSwitched || sortSwitched) { triggerConsAnim(activeRankingEl, 'is-bars-revealing'); } if (!hasCompletedInitialDraw) { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 2cff9c0..f295268 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 90575c5..bb75c6f 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -553,8 +553,6 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { let hoveredCellEl = null; let lastPointer = null; let lastRenderSig = ''; - let lastTickLabelsSig = ''; - let hasRenderedOnce = false; let hasRenderedLineOnce = false; let peakReadyArmed = false; let peakReadyRaf = 0; @@ -562,40 +560,13 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { let morphRafId = 0; let committedSegs = []; let liveMorphSegs = null; - const transientClassTimers = new Map(); + const vGridLinePool = []; + const xAxisTickPool = []; + const hmMonthPool = []; + const hmCellPool = []; const CURVE_MORPH_DURATION_MS = 240; - function cleanupTransientClass(el) { - const rec = transientClassTimers.get(el); - if (!rec) return; - clearTimeout(rec.tid); - el?.removeEventListener?.('animationend', rec.onEnd); - el?.classList?.remove(rec.cls); - transientClassTimers.delete(el); - } - - function triggerTransientClass(el, cls, fallbackMs = 650) { - if (!el || !el.classList) return; - cleanupTransientClass(el); - el.classList.remove(cls); - void el.offsetWidth; - const onEnd = (ev) => { - if (ev && ev.target && ev.target !== el) return; - cleanupTransientClass(el); - }; - const tid = setTimeout(() => cleanupTransientClass(el), fallbackMs); - transientClassTimers.set(el, { cls, tid, onEnd }); - el.addEventListener?.('animationend', onEnd); - el.classList.add(cls); - } - - function clearAllTransientTimers() { - for (const el of Array.from(transientClassTimers.keys())) { - cleanupTransientClass(el); - } - } - function cancelCurveMorph() { if ( morphRafId && @@ -1221,7 +1192,6 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { cancelTipTrackRaf(); cancelCurveMorph(); cancelPeakReadyRaf(); - clearAllTransientTimers(); plotStage.removeEventListener('mousemove', handlePointerMove); plotStage.removeEventListener('click', handleLineClick); plotStage.removeEventListener('mouseleave', clearHover); @@ -1270,14 +1240,6 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { patchAttr(plotStage, 'hidden', useHeatmap); patchAttr(xAxisEl, 'hidden', useHeatmap); patchAttr(heatmapStage, 'hidden', !useHeatmap); - if (hasRenderedOnce && modeChanged && canAnimateInBrowser()) { - if (useHeatmap) { - triggerTransientClass(heatmapStage, 'is-stage-entering'); - } else { - triggerTransientClass(plotStage, 'is-stage-entering'); - triggerTransientClass(xAxisEl, 'is-switching'); - } - } if (!useHeatmap) { syncViewWidth(); @@ -1351,51 +1313,97 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks)); patchStyleVar(hmBodyEl, '--hm-gap', `${gapPx}px`); - // 重建顶部对齐月份标签 - while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild); + // 就地增量补丁顶部对齐月份标签,避免文字节点销毁重建 const monthTicks = buildHeatmapMonthTicks(slots, firstDow, totalWeeks); - for (const mt of monthTicks) { - const mEl = h('span', { className: 'trend-hm-month text-mono', text: mt.text }); + for (let i = 0; i < monthTicks.length; i++) { + const mt = monthTicks[i]; + let mEl = hmMonthPool[i]; + if (!mEl) { + mEl = h('span', { className: 'trend-hm-month text-mono' }); + hmMonthPool.push(mEl); + } + patchText(mEl, mt.text); patchStyleVar(mEl, '--hm-col', String(mt.col)); - hmMonthsEl.appendChild(mEl); + if (hmMonthsEl.children[i] !== mEl) { + hmMonthsEl.insertBefore(mEl, hmMonthsEl.children[i] || null); + } + } + while (hmMonthsEl.children.length > monthTicks.length) { + hmMonthsEl.removeChild(hmMonthsEl.lastChild); } - // 重建 7 行 × N 周列的每日小格子(一格一天),使用 DocumentFragment 一次性批量挂载减少重排 - while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild); - hoveredCellEl = null; + // 就地增量复用 7 行 × N 周列的每日小格子,首次批量新增节点使用 DocumentFragment 挂载 currentCellEls = new Array(slots.length); - const gridFrag = - typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function' + const prevMountedCount = hmGridEl.children.length; + const newCellsFrag = + totalCells > prevMountedCount && + typeof document !== 'undefined' && + typeof document.createDocumentFragment === 'function' ? document.createDocumentFragment() : null; - const gridTarget = gridFrag || hmGridEl; - for (let pad = 0; pad < firstDow; pad++) { - gridTarget.appendChild( - h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' }) - ); + for (let nodeIdx = 0; nodeIdx < totalCells; nodeIdx++) { + let cellEl = hmCellPool[nodeIdx]; + if (!cellEl) { + cellEl = h('span', { className: 'trend-hm-cell' }); + hmCellPool.push(cellEl); + } + if (nodeIdx < firstDow) { + patchClasses(cellEl, { + 'is-pad': true, + 'is-hovered': false, + 'lv-0': false, + 'lv-1': false, + 'lv-2': false, + 'lv-3': false, + 'lv-4': false, + }); + patchAttr(cellEl, 'aria-hidden', 'true'); + patchAttr(cellEl, 'role', null); + patchAttr(cellEl, 'data-slot-idx', null); + patchAttr(cellEl, 'data-hm-col', null); + patchAttr(cellEl, 'data-hm-row', null); + } else { + const i = nodeIdx - firstDow; + const slot = slots[i]; + const tok = safeSlotTokens(slot?.tokens); + const lv = resolveHeatmapLevel(tok, thresholds); + const col = Math.floor(nodeIdx / 7); + const row = nodeIdx % 7; + patchClasses(cellEl, { + 'is-pad': false, + 'is-hovered': hoveredIdx === i, + 'lv-0': lv === 0, + 'lv-1': lv === 1, + 'lv-2': lv === 2, + 'lv-3': lv === 3, + 'lv-4': lv === 4, + }); + patchAttr(cellEl, 'aria-hidden', null); + patchAttr(cellEl, 'role', 'gridcell'); + patchAttr(cellEl, 'data-slot-idx', String(i)); + patchAttr(cellEl, 'data-hm-col', String(col)); + patchAttr(cellEl, 'data-hm-row', String(row)); + currentCellEls[i] = cellEl; + } + if (nodeIdx < prevMountedCount) { + if (hmGridEl.children[nodeIdx] !== cellEl) { + hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); + } + } else if (newCellsFrag) { + newCellsFrag.appendChild(cellEl); + } else { + hmGridEl.appendChild(cellEl); + } } - - for (let i = 0; i < slots.length; i++) { - const slot = slots[i]; - const tok = safeSlotTokens(slot?.tokens); - const lv = resolveHeatmapLevel(tok, thresholds); - const gridPos = firstDow + i; - const col = Math.floor(gridPos / 7); - const row = gridPos % 7; - const cellEl = h('span', { - className: `trend-hm-cell lv-${lv}`, - 'data-slot-idx': String(i), - 'data-hm-col': String(col), - 'data-hm-row': String(row), - role: 'gridcell', - }); - gridTarget.appendChild(cellEl); - currentCellEls[i] = cellEl; + if (newCellsFrag) { + hmGridEl.appendChild(newCellsFrag); } - if (gridFrag) { - hmGridEl.appendChild(gridFrag); + while (hmGridEl.children.length > totalCells) { + hmGridEl.removeChild(hmGridEl.lastChild); } + hoveredCellEl = + hoveredIdx >= 0 && hoveredIdx < slots.length ? currentCellEls[hoveredIdx] || null : null; if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => { @@ -1423,7 +1431,6 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } else if (hoveredIdx >= 0) { showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer); } - hasRenderedOnce = true; return; } @@ -1484,21 +1491,11 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } hasRenderedLineOnce = true; - // 渲染对齐底部刻度的垂直参考网格线及 X 轴标签(起止标签严格左右贴边) + // 就地增量补丁垂直参考网格线及底部 X 轴标签,保持文字常驻不重排不闪烁 const tickIndices = computeTickIndices(slots); - const nextTickLabelsSig = tickIndices - .map((tIdx) => `${tIdx}:${slots[tIdx]?.label || ''}`) - .join('|'); - const ticksChanged = - hasRenderedOnce && - !modeChanged && - lastTickLabelsSig !== '' && - nextTickLabelsSig !== lastTickLabelsSig; - lastTickLabelsSig = nextTickLabelsSig; - - while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild); - while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); tickElsByIdx = new Map(); + let vLineCount = 0; + let tickCount = 0; for (let i = 0; i < tickIndices.length; i++) { const tIdx = tickIndices[i]; @@ -1507,34 +1504,57 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { if (!pt || !slot) continue; if (i > 0 && i < tickIndices.length - 1) { - const vLine = document.createElementNS(SVG_NS, 'line'); - vLine.setAttribute('x1', pt.x.toFixed(1)); - vLine.setAttribute('y1', '16'); - vLine.setAttribute('x2', pt.x.toFixed(1)); - vLine.setAttribute('y2', String(BOTTOM_Y)); - vGridGroup.appendChild(vLine); + let vLine = vGridLinePool[vLineCount]; + if (!vLine) { + vLine = document.createElementNS(SVG_NS, 'line'); + vLine.setAttribute('y1', '16'); + vLine.setAttribute('y2', String(BOTTOM_Y)); + vGridLinePool.push(vLine); + } + const xFixed = pt.x.toFixed(1); + patchAttr(vLine, 'x1', xFixed); + patchAttr(vLine, 'x2', xFixed); + if (vGridGroup.children[vLineCount] !== vLine) { + vGridGroup.insertBefore(vLine, vGridGroup.children[vLineCount] || null); + } + vLineCount++; } const isFirst = !isSingle && i === 0; const isLast = !isSingle && i === tickIndices.length - 1; const pct = isFirst ? 0 : isLast ? 100 : (pt.x / viewW) * 100; - const tickEl = h('span', { - className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, - text: slot.label || '', - title: formatTrendSlotFullLabel(slot) || slot.label || '', + let tickRec = xAxisTickPool[tickCount]; + if (!tickRec) { + const el = h('span', { className: 'trend-x-tick text-mono' }); + const rec = { el, slotIdx: tIdx }; + el.onclick = () => { + lastPointer = null; + showLineHoverAtIndex(rec.slotIdx); + }; + tickRec = rec; + xAxisTickPool.push(tickRec); + } + tickRec.slotIdx = tIdx; + patchClasses(tickRec.el, { + 'is-start': isFirst, + 'is-end': isLast, + 'is-hovered': hoveredIdx === tIdx, }); - patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); - tickEl.onclick = () => { - lastPointer = null; - showLineHoverAtIndex(tIdx); - }; - xAxisEl.appendChild(tickEl); - tickElsByIdx.set(tIdx, tickEl); + patchText(tickRec.el, slot.label || ''); + patchAttr(tickRec.el, 'title', formatTrendSlotFullLabel(slot) || slot.label || ''); + patchStyleVar(tickRec.el, '--tick-x', `${pct.toFixed(2)}%`); + if (xAxisEl.children[tickCount] !== tickRec.el) { + xAxisEl.insertBefore(tickRec.el, xAxisEl.children[tickCount] || null); + } + tickElsByIdx.set(tIdx, tickRec.el); + tickCount++; } - if (ticksChanged && canAnimateInBrowser()) { - triggerTransientClass(xAxisEl, 'is-switching'); - triggerTransientClass(vGridGroup, 'is-switching'); + while (vGridGroup.children.length > vLineCount) { + vGridGroup.removeChild(vGridGroup.lastChild); + } + while (xAxisEl.children.length > tickCount) { + xAxisEl.removeChild(xAxisEl.lastChild); } } @@ -1568,7 +1588,6 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } else if (hoveredIdx >= 0) { showLineHoverAtIndex(hoveredIdx, lastPointer); } - hasRenderedOnce = true; } return { el: chartWrap, update, destroy }; diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index 157d4dc..83614b4 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -424,88 +424,6 @@ function formatPoolFullCapRef(eqUsd, eqTok) { return usdStr; } -function resolveWeeklyCapacitySummary(quotas) { - if (!quotas || typeof quotas !== 'object') return null; - if (quotas.weekly?.isOfficial === false) return null; - const direct = quotas.weeklyCapacityEstimate; - if (direct && typeof direct === 'object') { - if ( - direct.status === 'custom_mode' || - !Number.isFinite(Number(direct.totalEqWeeklyUsd)) || - Number(direct.totalEqWeeklyUsd) <= 0 - ) { - return null; - } - return direct; - } - - const rawPools = Array.isArray(quotas.pools) ? quotas.pools : []; - const candidatePools = rawPools.filter( - (p) => - p && - (p.hasWeekly || - p.weeklyUsedPct != null || - Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) - ); - const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; - if (targetPools.length === 0) return null; - - let sumUsd = 0; - let sumTokens = 0; - let readyPoolCount = 0; - let tokenReadyPoolCount = 0; - let hasPreliminary = false; - - for (const p of targetPools) { - const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; - let eqUsd = - Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 - ? Number(est.eqFullWeeklyUsd) - : null; - let eqTok = - Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 - ? Math.round(Number(est.eqFullWeeklyTokens)) - : null; - if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { - const wkModels = est.models.filter( - (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 - ); - if (wkModels.length > 0) { - eqUsd = - wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; - const tokModels = wkModels.filter( - (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 - ); - if (tokModels.length === wkModels.length) { - eqTok = Math.round( - tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length - ); - } - } - } - if (eqUsd !== null) { - readyPoolCount += 1; - sumUsd += eqUsd; - if (est?.isPreliminaryWeekly) hasPreliminary = true; - if (eqTok !== null) { - tokenReadyPoolCount += 1; - sumTokens += eqTok; - } - } - } - - if (readyPoolCount === 0) return null; - const totalPoolCount = targetPools.length; - return { - status: readyPoolCount < totalPoolCount ? 'partial' : 'ready', - totalEqWeeklyUsd: +sumUsd.toFixed(1), - totalEqWeeklyTokens: tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, - readyPoolCount, - totalPoolCount, - hasPreliminary, - }; -} - function formatRatePerUsdValue(rate) { const num = Number(rate); if (!Number.isFinite(num) || num <= 0) return '--'; @@ -630,13 +548,11 @@ function createRateModelCard({ function buildRatePopoverSig(data) { const locale = getEffectiveLocale(); const acct = String(data?.account?.email || data?.account?.name || '').trim(); - const isOfficial = data?.quotas?.weekly?.isOfficial !== false; - const wkCapSig = JSON.stringify(data?.quotas?.weeklyCapacityEstimate || null); const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; const poolSig = pools .map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`) .join('|'); - return `${locale}|${acct}|${isOfficial}|${wkCapSig}|${poolSig}`; + return `${locale}|${acct}|${poolSig}`; } export const QuotaPoolsWidget = defineComponent({ @@ -654,32 +570,7 @@ export const QuotaPoolsWidget = defineComponent({ className: 'quota-rate-pop-account', text: t('quota.ratePopAccountCurrent'), }); - const ratePopWkLabelEl = h('span', { text: t('quota.ratePopWkCapTitle') }); - const ratePopWkSubEl = h('span', { - className: 'quota-rate-wk-sub', - hidden: true, - text: '', - }); - const ratePopWkUsdEl = h('span', { className: 'quota-rate-wk-usd text-mono', text: '--' }); - const ratePopWkTokEl = h('span', { - className: 'quota-rate-wk-tok text-mono', - hidden: true, - text: '', - }); - const ratePopWkSummaryEl = h( - 'div', - { className: 'quota-rate-wk-summary', hidden: true }, - [ - h('span', { className: 'quota-rate-wk-k' }, [ratePopWkLabelEl, ratePopWkSubEl]), - h('span', { className: 'quota-rate-wk-v' }, [ratePopWkUsdEl, ratePopWkTokEl]), - ] - ); - ratePopWkSummaryEl.hidden = true; const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); - const ratePopNoteEl = h('div', { - className: 'quota-rate-pop-note', - text: t('quota.ratePopNote'), - }); const ratePopoverEl = h( 'div', { @@ -689,9 +580,7 @@ export const QuotaPoolsWidget = defineComponent({ }, [ h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), - ratePopWkSummaryEl, ratePopBodyEl, - ratePopNoteEl, ] ); ratePopoverEl.hidden = true; @@ -769,7 +658,6 @@ export const QuotaPoolsWidget = defineComponent({ lastRatePopSig = sig; patchText(ratePopTitleEl, t('quota.ratePopTitle')); - patchText(ratePopNoteEl, t('quota.ratePopNote')); patchAttr(rateHelpBtn, 'aria-label', t('quota.rateHelpAria')); const acctMasked = maskAccountLabel(data?.account?.email || data?.account?.name || ''); @@ -781,38 +669,6 @@ export const QuotaPoolsWidget = defineComponent({ ); patchAttr(ratePopAccountEl, 'title', acctMasked || null); - const wkCap = resolveWeeklyCapacitySummary(data?.quotas); - if (wkCap) { - ratePopWkSummaryEl.hidden = false; - patchAttr(ratePopWkSummaryEl, 'hidden', false); - patchText(ratePopWkLabelEl, t('quota.ratePopWkCapTitle')); - const wkSubText = - wkCap.status === 'partial' && Number(wkCap.totalPoolCount) > 0 - ? t('quota.ratePopWkCapPartial', { - ready: Number(wkCap.readyPoolCount) || 0, - total: Number(wkCap.totalPoolCount) || 0, - }) - : wkCap.hasPreliminary - ? t('quota.ratePopWkCapPrelim') - : ''; - ratePopWkSubEl.hidden = !wkSubText; - patchAttr(ratePopWkSubEl, 'hidden', !wkSubText); - patchText(ratePopWkSubEl, wkSubText); - patchText(ratePopWkUsdEl, `≈ ${formatRateEqUsd(wkCap.totalEqWeeklyUsd)}`); - const hasWkTok = - Number.isFinite(Number(wkCap.totalEqWeeklyTokens)) && - Number(wkCap.totalEqWeeklyTokens) > 0; - ratePopWkTokEl.hidden = !hasWkTok; - patchAttr(ratePopWkTokEl, 'hidden', !hasWkTok); - patchText( - ratePopWkTokEl, - hasWkTok ? `· ${formatTokens(Number(wkCap.totalEqWeeklyTokens))}` : '' - ); - } else { - ratePopWkSummaryEl.hidden = true; - patchAttr(ratePopWkSummaryEl, 'hidden', true); - } - while (ratePopBodyEl.firstChild) { ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); } diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 91eb943..faebf89 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -204,9 +204,6 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopTitle': 'Estimated Burn Rates', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': 'Current account', - 'quota.ratePopWkCapTitle': 'Est. Weekly Quota', - 'quota.ratePopWkCapPrelim': '· est.', - 'quota.ratePopWkCapPartial': '· {ready}/{total} pools', 'quota.ratePopPoolFallback': 'Pool average', 'quota.ratePopEq5hLabel': '5h full', 'quota.ratePopEqWkLabel': 'Weekly full', @@ -215,7 +212,6 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopPrelimSlope': 'slope est.', 'quota.ratePopPrelimCycle': 'cycle est.', 'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).', - 'quota.ratePopNote': 'Measured from net burn & priced steps; lowest in pool = 1x. Account isolated.', 'quota.ratePopSharedBadge': 'Shared active', 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index f6632e6..845f698 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -204,9 +204,6 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopTitle': '实测倍率预估', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': '当前账号', - 'quota.ratePopWkCapTitle': '预测周额度', - 'quota.ratePopWkCapPrelim': '· 初估', - 'quota.ratePopWkCapPartial': '· {ready}/{total} 池', 'quota.ratePopPoolFallback': '池综合均值', 'quota.ratePopEq5hLabel': '5h 满池', 'quota.ratePopEqWkLabel': '周限满池', @@ -215,7 +212,6 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopPrelimSlope': '斜率初估', 'quota.ratePopPrelimCycle': '周期初估', 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。', - 'quota.ratePopNote': '按净消耗及精确计价折算,同池最省为 1x,按账号隔离。', 'quota.ratePopSharedBadge': '共享活跃', 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 2aa2d83..ace339a 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -840,20 +840,17 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .step-anomaly-tip-list, -[data-modern-ui="true"] .step-anomaly-tip-hint, -[data-modern-ui="true"] .quota-rate-pop-head, -[data-modern-ui="true"] .quota-rate-wk-summary, -[data-modern-ui="true"] .quota-rate-pool-group + .quota-rate-pool-group, -[data-modern-ui="true"] .quota-rate-model-row + .quota-rate-model-row, -[data-modern-ui="true"] .quota-rate-pop-note, -:host([data-modern-ui="true"]) .quota-rate-pop-head, -:host([data-modern-ui="true"]) .quota-rate-wk-summary, -:host([data-modern-ui="true"]) .quota-rate-pool-group + .quota-rate-pool-group, -:host([data-modern-ui="true"]) .quota-rate-model-row + .quota-rate-model-row, -:host([data-modern-ui="true"]) .quota-rate-pop-note { +[data-modern-ui="true"] .step-anomaly-tip-hint { border-color: var(--modern-surface-hover); } +[data-modern-ui="true"] .quota-rate-shared-badge, +[data-modern-ui="true"] .quota-rate-ext-banner, +:host([data-modern-ui="true"]) .quota-rate-shared-badge, +:host([data-modern-ui="true"]) .quota-rate-ext-banner { + border: none; +} + [data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown) { top: 2px; bottom: auto; diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 899a5f8..762d784 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -406,36 +406,7 @@ } .trend-peak-pill.is-ready { - transition: - left 240ms cubic-bezier(0.22, 1, 0.36, 1), - opacity 180ms cubic-bezier(0.22, 1, 0.36, 1); -} - -@keyframes anim-cons-axis-fade { - from { - opacity: 0.3; - } - to { - opacity: 1; - } -} - -@keyframes anim-cons-stage-in { - from { - opacity: 0; - } - to { - opacity: 1; - } -} - -@keyframes anim-cons-content-switch { - from { - opacity: 0.52; - } - to { - opacity: 1; - } + transition: left 240ms cubic-bezier(0.22, 1, 0.36, 1); } @keyframes anim-cons-bar-grow { @@ -447,25 +418,6 @@ } } -.trend-x-axis.is-switching, -.trend-v-grid.is-switching { - animation: anim-cons-axis-fade 220ms cubic-bezier(0.22, 1, 0.36, 1) both; -} - -.trend-plot-stage.is-stage-entering, -.trend-heatmap-stage.is-stage-entering, -.cons-item-list.is-tab-entering, -.cons-ranking-empty.is-tab-entering { - animation: anim-cons-stage-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both; -} - -.cons-unified-matrix.is-range-switching, -.cons-item-list.is-range-switching, -.cons-ranking-empty.is-range-switching { - animation: anim-cons-content-switch 220ms cubic-bezier(0.22, 1, 0.36, 1) both; -} - -.cons-item-list.is-tab-entering .progress-track, .cons-item-list.is-bars-revealing .progress-track { transform-origin: left center; animation: anim-cons-bar-grow 240ms cubic-bezier(0.22, 1, 0.36, 1) both; @@ -478,15 +430,6 @@ .trend-hm-cell { transition: none !important; } - .trend-x-axis.is-switching, - .trend-v-grid.is-switching, - .trend-plot-stage.is-stage-entering, - .trend-heatmap-stage.is-stage-entering, - .cons-item-list.is-tab-entering, - .cons-ranking-empty.is-tab-entering, - .cons-unified-matrix.is-range-switching, - .cons-item-list.is-range-switching, - .cons-ranking-empty.is-range-switching, .cons-item-list.is-bars-revealing .progress-track { animation: none !important; } diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 32c9de0..7fddd57 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -699,8 +699,6 @@ justify-content: space-between; gap: 10px; min-width: 0; - padding-bottom: 6px; - border-bottom: 1px solid var(--border-hairline); } .quota-rate-pop-title { @@ -721,65 +719,10 @@ min-width: 0; } -.quota-rate-wk-summary { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 8px; - min-width: 0; - padding-bottom: 7px; - border-bottom: 1px solid var(--border-hairline); -} - -.quota-rate-wk-summary[hidden] { - display: none; -} - -.quota-rate-wk-k { - display: inline-flex; - align-items: baseline; - gap: 5px; - min-width: 0; - font-size: var(--fs-sm); - font-weight: 500; - color: var(--text-secondary); - white-space: nowrap; -} - -.quota-rate-wk-sub { - font-family: var(--font-mono); - font-variant-numeric: tabular-nums; - font-size: var(--fs-2xs); - font-weight: 400; - color: var(--text-muted); -} - -.quota-rate-wk-v { - display: inline-flex; - align-items: baseline; - gap: 4px; - font-family: var(--font-mono); - font-variant-numeric: tabular-nums; - white-space: nowrap; - flex-shrink: 0; -} - -.quota-rate-wk-usd { - font-size: var(--fs-md); - font-weight: 600; - color: var(--text-primary); -} - -.quota-rate-wk-tok { - font-size: var(--fs-xs); - font-weight: 400; - color: var(--text-muted); -} - .quota-rate-pop-body { display: flex; flex-direction: column; - gap: 8px; + gap: 10px; max-height: min(300px, 58vh); overflow-x: hidden; overflow-y: auto; @@ -792,11 +735,6 @@ gap: 5px; } -.quota-rate-pool-group + .quota-rate-pool-group { - padding-top: 7px; - border-top: 1px solid var(--border-hairline); -} - .quota-rate-pool-head { display: flex; align-items: center; @@ -845,7 +783,7 @@ .quota-rate-model-list { display: flex; flex-direction: column; - gap: 7px; + gap: 8px; } .quota-rate-model-row { @@ -855,11 +793,6 @@ min-width: 0; } -.quota-rate-model-row + .quota-rate-model-row { - padding-top: 7px; - border-top: 1px solid var(--border-hairline); -} - .quota-rate-row-top { display: flex; align-items: baseline; @@ -960,14 +893,6 @@ color: var(--text-secondary); } -.quota-rate-pop-note { - padding-top: 6px; - border-top: 1px solid var(--border-hairline); - font-size: var(--fs-2xs); - line-height: 1.45; - color: var(--text-muted); -} - /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index fa87a5c..50384bb 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -406,11 +406,7 @@ export const ConsumptionView = defineComponent({ let lastAnimatedRankingKey = ''; let lastAnimatedSortSig = ''; const consAnimTimers = new Map(); - const TRANSIENT_CONS_CLASSES = [ - 'is-range-switching', - 'is-tab-entering', - 'is-bars-revealing', - ]; + const TRANSIENT_CONS_CLASSES = ['is-bars-revealing']; function cleanupConsAnim(el) { const rec = consAnimTimers.get(el); @@ -2228,13 +2224,7 @@ export const ConsumptionView = defineComponent({ !tabSwitched && nextSortSig !== lastAnimatedSortSig; - if (rangeSwitched) { - triggerConsAnim(unifiedMatrixEl, 'is-range-switching'); - triggerConsAnim(activeRankingEl, 'is-range-switching'); - triggerConsAnim(sourcesListEl, 'is-range-switching'); - } else if (tabSwitched) { - triggerConsAnim(activeRankingEl, 'is-tab-entering'); - } else if (sortSwitched) { + if (tabSwitched || sortSwitched) { triggerConsAnim(activeRankingEl, 'is-bars-revealing'); } if (!hasCompletedInitialDraw) { diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 235a641..4eac4b1 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2417,8 +2417,6 @@ html[data-standalone="true"] .app-shell { justify-content: space-between; gap: 10px; min-width: 0; - padding-bottom: 6px; - border-bottom: 1px solid var(--border-hairline); } .quota-rate-pop-title { @@ -2439,65 +2437,10 @@ html[data-standalone="true"] .app-shell { min-width: 0; } -.quota-rate-wk-summary { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 8px; - min-width: 0; - padding-bottom: 7px; - border-bottom: 1px solid var(--border-hairline); -} - -.quota-rate-wk-summary[hidden] { - display: none; -} - -.quota-rate-wk-k { - display: inline-flex; - align-items: baseline; - gap: 5px; - min-width: 0; - font-size: var(--fs-sm); - font-weight: 500; - color: var(--text-secondary); - white-space: nowrap; -} - -.quota-rate-wk-sub { - font-family: var(--font-mono); - font-variant-numeric: tabular-nums; - font-size: var(--fs-2xs); - font-weight: 400; - color: var(--text-muted); -} - -.quota-rate-wk-v { - display: inline-flex; - align-items: baseline; - gap: 4px; - font-family: var(--font-mono); - font-variant-numeric: tabular-nums; - white-space: nowrap; - flex-shrink: 0; -} - -.quota-rate-wk-usd { - font-size: var(--fs-md); - font-weight: 600; - color: var(--text-primary); -} - -.quota-rate-wk-tok { - font-size: var(--fs-xs); - font-weight: 400; - color: var(--text-muted); -} - .quota-rate-pop-body { display: flex; flex-direction: column; - gap: 8px; + gap: 10px; max-height: min(300px, 58vh); overflow-x: hidden; overflow-y: auto; @@ -2510,11 +2453,6 @@ html[data-standalone="true"] .app-shell { gap: 5px; } -.quota-rate-pool-group + .quota-rate-pool-group { - padding-top: 7px; - border-top: 1px solid var(--border-hairline); -} - .quota-rate-pool-head { display: flex; align-items: center; @@ -2563,7 +2501,7 @@ html[data-standalone="true"] .app-shell { .quota-rate-model-list { display: flex; flex-direction: column; - gap: 7px; + gap: 8px; } .quota-rate-model-row { @@ -2573,11 +2511,6 @@ html[data-standalone="true"] .app-shell { min-width: 0; } -.quota-rate-model-row + .quota-rate-model-row { - padding-top: 7px; - border-top: 1px solid var(--border-hairline); -} - .quota-rate-row-top { display: flex; align-items: baseline; @@ -2678,14 +2611,6 @@ html[data-standalone="true"] .app-shell { color: var(--text-secondary); } -.quota-rate-pop-note { - padding-top: 6px; - border-top: 1px solid var(--border-hairline); - font-size: var(--fs-2xs); - line-height: 1.45; - color: var(--text-muted); -} - /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; @@ -3280,36 +3205,7 @@ html[data-standalone="true"] .app-shell { } .trend-peak-pill.is-ready { - transition: - left 240ms cubic-bezier(0.22, 1, 0.36, 1), - opacity 180ms cubic-bezier(0.22, 1, 0.36, 1); -} - -@keyframes anim-cons-axis-fade { - from { - opacity: 0.3; - } - to { - opacity: 1; - } -} - -@keyframes anim-cons-stage-in { - from { - opacity: 0; - } - to { - opacity: 1; - } -} - -@keyframes anim-cons-content-switch { - from { - opacity: 0.52; - } - to { - opacity: 1; - } + transition: left 240ms cubic-bezier(0.22, 1, 0.36, 1); } @keyframes anim-cons-bar-grow { @@ -3321,25 +3217,6 @@ html[data-standalone="true"] .app-shell { } } -.trend-x-axis.is-switching, -.trend-v-grid.is-switching { - animation: anim-cons-axis-fade 220ms cubic-bezier(0.22, 1, 0.36, 1) both; -} - -.trend-plot-stage.is-stage-entering, -.trend-heatmap-stage.is-stage-entering, -.cons-item-list.is-tab-entering, -.cons-ranking-empty.is-tab-entering { - animation: anim-cons-stage-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both; -} - -.cons-unified-matrix.is-range-switching, -.cons-item-list.is-range-switching, -.cons-ranking-empty.is-range-switching { - animation: anim-cons-content-switch 220ms cubic-bezier(0.22, 1, 0.36, 1) both; -} - -.cons-item-list.is-tab-entering .progress-track, .cons-item-list.is-bars-revealing .progress-track { transform-origin: left center; animation: anim-cons-bar-grow 240ms cubic-bezier(0.22, 1, 0.36, 1) both; @@ -3352,15 +3229,6 @@ html[data-standalone="true"] .app-shell { .trend-hm-cell { transition: none !important; } - .trend-x-axis.is-switching, - .trend-v-grid.is-switching, - .trend-plot-stage.is-stage-entering, - .trend-heatmap-stage.is-stage-entering, - .cons-item-list.is-tab-entering, - .cons-ranking-empty.is-tab-entering, - .cons-unified-matrix.is-range-switching, - .cons-item-list.is-range-switching, - .cons-ranking-empty.is-range-switching, .cons-item-list.is-bars-revealing .progress-track { animation: none !important; } @@ -8860,20 +8728,17 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .step-anomaly-tip-list, -[data-modern-ui="true"] .step-anomaly-tip-hint, -[data-modern-ui="true"] .quota-rate-pop-head, -[data-modern-ui="true"] .quota-rate-wk-summary, -[data-modern-ui="true"] .quota-rate-pool-group + .quota-rate-pool-group, -[data-modern-ui="true"] .quota-rate-model-row + .quota-rate-model-row, -[data-modern-ui="true"] .quota-rate-pop-note, -:host([data-modern-ui="true"]) .quota-rate-pop-head, -:host([data-modern-ui="true"]) .quota-rate-wk-summary, -:host([data-modern-ui="true"]) .quota-rate-pool-group + .quota-rate-pool-group, -:host([data-modern-ui="true"]) .quota-rate-model-row + .quota-rate-model-row, -:host([data-modern-ui="true"]) .quota-rate-pop-note { +[data-modern-ui="true"] .step-anomaly-tip-hint { border-color: var(--modern-surface-hover); } +[data-modern-ui="true"] .quota-rate-shared-badge, +[data-modern-ui="true"] .quota-rate-ext-banner, +:host([data-modern-ui="true"]) .quota-rate-shared-badge, +:host([data-modern-ui="true"]) .quota-rate-ext-banner { + border: none; +} + [data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown) { top: 2px; bottom: auto; diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 87ed9ec..0701578 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1673,3 +1673,204 @@ test('xlsxBuilder enforces 32,767 UTF-16 cell limit without splitting surrogate const cellA3 = cellMatches[1][1]; assert.equal(cellA3, 'ok\uFFFDmid\uFFFDend'); }); + +test('ConsumptionView and TrendAreaChart patch text DOM nodes in-place without opacity flicker classes on date range switches', async () => { + const consCss = fs.readFileSync( + fileURLToPath(new URL('../src/styles/views-consumption.css', import.meta.url)), + 'utf8' + ); + for (const bannedToken of [ + 'is-range-switching', + 'is-tab-entering', + 'is-switching', + 'is-stage-entering', + 'anim-cons-content-switch', + 'anim-cons-axis-fade', + 'anim-cons-stage-in', + ]) { + assert.equal( + consCss.includes(bannedToken), + false, + `Expected views-consumption.css not to contain text-opacity flicker rule "${bannedToken}"` + ); + } + + const { createMockDom } = await import('./mock-dom.mjs'); + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + location: { origin: 'http://127.0.0.1:41234', href: 'http://127.0.0.1:41234/' }, + getComputedStyle: () => ({ overflow: 'visible', overflowX: 'visible', overflowY: 'visible' }), + matchMedia: () => ({ matches: false }), + requestAnimationFrame: (cb) => setTimeout(() => cb(performance.now()), 0), + cancelAnimationFrame: (id) => clearTimeout(id), + addEventListener() {}, + removeEventListener() {}, + }; + + try { + const { ConsumptionView } = await import('../src/views/ConsumptionView.js'); + const { telemetryStore } = await import('../src/store/telemetryStore.js'); + const { uiStore } = await import('../src/store/uiStore.js'); + const prevTelState = { ...telemetryStore.getState() }; + const prevUiState = { ...uiStore.getState() }; + + uiStore.setState( + { activeView: 'consumption', monitorVisible: true, settingsOpen: false }, + { sync: true } + ); + const view = ConsumptionView(); + document.body.appendChild(view.el); + + const makeRangePayload = (rangeKey, tokBase, labels) => ({ + settings: { modelDisplayMode: 'short', showUpstreamModel: false, orchestratorIdMode: 'label' }, + consumption: { + revision: 0, + selectedRange: { + key: rangeKey, + label: rangeKey, + startMs: 1_760_000_000_000, + endMs: 1_760_086_400_000, + }, + account: { + totalTokens: tokBase, + inputTokens: Math.round(tokBase * 0.2), + cacheReadTokens: Math.round(tokBase * 0.7), + outputTokens: Math.round(tokBase * 0.1), + responseTokens: Math.round(tokBase * 0.07), + thinkingTokens: Math.round(tokBase * 0.03), + calls: 12, + costUsd: 1.25, + savedCostUsd: 0.85, + cacheHitPct: 77.8, + }, + trendSeries: labels.map((lbl, idx) => ({ + index: idx, + startMs: 1_760_000_000_000 + idx * 3_600_000, + endMs: 1_760_000_000_000 + (idx + 1) * 3_600_000, + granularity: labels.length > 90 ? 'day' : 'hour', + label: lbl, + fullLabel: lbl, + tokens: 1_000 * (idx + 1), + calls: 1, + costUsd: 0.05, + })), + sourcesBreakdown: [ + { + name: 'antigravity', + label: 'Antigravity IDE', + totalTokens: tokBase, + calls: 12, + costUsd: 1.25, + models: [{ label: 'Claude Opus 4.6', shortName: 'Claude Opus 4.6', totalTokens: tokBase, calls: 12 }], + }, + ], + topConversations: [], + topWorkspaces: [], + monthlyYear: 2026, + monthlySeries: Array.from({ length: 12 }, (_, m) => ({ + month: m + 1, + totalTokens: m === 10 ? tokBase : 0, + costUsd: m === 10 ? 1.25 : 0, + calls: m === 10 ? 12 : 0, + })), + }, + modelBreakdown: [ + { + label: 'Claude Opus 4.6', + shortName: 'Claude Opus 4.6', + totalTokens: tokBase, + inputTokens: Math.round(tokBase * 0.2), + cacheReadTokens: Math.round(tokBase * 0.7), + responseTokens: Math.round(tokBase * 0.07), + thinkingTokens: Math.round(tokBase * 0.03), + outputTokens: Math.round(tokBase * 0.1), + calls: 12, + costUsd: 1.25, + }, + ], + }); + + telemetryStore.setState( + { + selectedTimeRange: 'today', + telemetry: makeRangePayload('today', 100_000, ['00:00', '06:00', '12:00', '18:00']), + }, + { sync: true } + ); + + const matrixEl = view.el.querySelector('.cons-unified-matrix'); + const heroNumEl = view.el.querySelector('.cons-hero-num'); + const modelRowEl = view.el.querySelector('.cons-item-row'); + const modelTitleTextEl = modelRowEl.querySelector('.cons-row-title-text'); + const sourceRowEl = view.el.querySelector('.cons-source-row'); + const xAxisEl = view.el.querySelector('.trend-x-axis'); + const initialTicks = xAxisEl.querySelectorAll('.trend-x-tick'); + assert.equal(initialTicks.length, 4); + + // Switch to 7d: same model, same source, updated numbers & tick labels -> all DOM nodes reused in-place, zero opacity flicker classes + telemetryStore.setState( + { + selectedTimeRange: '7d', + telemetry: makeRangePayload('7d', 450_000, ['11/18', '11/20', '11/22', '11/24']), + }, + { sync: true } + ); + + assert.equal(view.el.querySelector('.cons-hero-num'), heroNumEl, 'Hero token element persists'); + assert.equal(view.el.querySelector('.cons-item-row'), modelRowEl, 'Model row element persists'); + assert.equal( + view.el.querySelector('.cons-item-row .cons-row-title-text'), + modelTitleTextEl, + 'Model title text node persists' + ); + assert.equal(view.el.querySelector('.cons-source-row'), sourceRowEl, 'Source row element persists'); + + const nextTicks = xAxisEl.querySelectorAll('.trend-x-tick'); + assert.equal(nextTicks.length, 4); + for (let i = 0; i < 4; i++) { + assert.equal(nextTicks[i], initialTicks[i], `Trend X-axis tick #${i} reused in-place`); + } + assert.equal(nextTicks[0].textContent, '11/18'); + + for (const cls of ['is-range-switching', 'is-tab-entering', 'is-switching', 'is-stage-entering']) { + assert.equal(matrixEl.classList.contains(cls), false); + assert.equal(modelRowEl.parentNode.classList.contains(cls), false); + assert.equal(sourceRowEl.parentNode.classList.contains(cls), false); + assert.equal(xAxisEl.classList.contains(cls), false); + } + + // Switch to >90d heatmap and update counts -> month labels and grid cells reuse pooled nodes in-place + const hmLabelsA = Array.from({ length: 95 }, (_, idx) => `08/${String((idx % 28) + 1).padStart(2, '0')}`); + telemetryStore.setState( + { + selectedTimeRange: 'all', + telemetry: makeRangePayload('all', 900_000, hmLabelsA), + }, + { sync: true } + ); + const hmGridEl = view.el.querySelector('.trend-hm-grid'); + const firstGridCells = [...hmGridEl.children]; + assert.ok(firstGridCells.length >= 95); + + telemetryStore.setState( + { + selectedTimeRange: 'all', + telemetry: makeRangePayload('all', 950_000, hmLabelsA), + }, + { sync: true } + ); + const secondGridCells = [...hmGridEl.children]; + assert.equal(secondGridCells.length, firstGridCells.length); + assert.equal(secondGridCells[10], firstGridCells[10], 'Heatmap cell DOM node reused in-place'); + + view.destroy(); + telemetryStore.setState(prevTelState, { sync: true }); + uiStore.setState(prevUiState, { sync: true }); + } finally { + globalThis.document = prevDoc; + globalThis.window = prevWin; + } +}); diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs index 79f6bf6..3988e98 100644 --- a/sidecars/panel/test/quota-reservation.test.mjs +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -2208,7 +2208,7 @@ test('quota-reservation: 3-tier hybrid estimator unlocks cycle_ratio & anchor_sl assert.equal(pAfterRestart.get('Claude & GPT').rateEstimate?.eqFullWeeklyTokens, 12_500_000); }); -test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, preliminary labels, and full-pool token references', async () => { +test('QuotaPoolsWidget ? popover renders preliminary labels and full-pool token references without weekly summary row, footer note, or divider rules', async () => { const { document } = createMockDom(); const origDocument = globalThis.document; const origWindow = globalThis.window; @@ -2231,8 +2231,9 @@ test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, prelimin const widget = QuotaPoolsWidget(); const popover = widget.refs.ratePopoverEl; - // 1. Collecting state: top weekly summary hidden until at least 1 pool has a weekly capacity estimate - assert.equal(popover.querySelector('.quota-rate-wk-summary')?.hidden, true); + // 1. Minimalist layout: no redundant weekly summary row or footer note element + assert.equal(popover.querySelector('.quota-rate-wk-summary'), null); + assert.equal(popover.querySelector('.quota-rate-pop-note'), null); // 2. Partial + Preliminary state (Claude ready via anchor_slope, Gemini still collecting) widget.refs.update({ @@ -2280,9 +2281,8 @@ test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, prelimin minuteTick: 1, }); - const wkSummary = popover.querySelector('.quota-rate-wk-summary'); - assert.equal(wkSummary.hidden, false); - assert.match(wkSummary.textContent, /预测周额度.*· 1\/2 池.*≈ \$48.*· 9\.9M/); + assert.doesNotMatch(popover.textContent, /预测周额度/); + assert.doesNotMatch(popover.textContent, /同池最省/); const fallbackRow = popover.querySelector('.quota-rate-model-row.is-fallback'); assert.ok(fallbackRow); assert.match(fallbackRow.textContent, /池综合均值/); @@ -2292,7 +2292,7 @@ test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, prelimin const wkRowLeft = widget.refs.poolsListEl.querySelectorAll('.quota-win-left')[1]; assert.match(wkRowLeft.getAttribute('title') || '', /满池约 \$48 \(9\.9M\)/); - // 3. All pools calibrated & ready: sums USD + Tokens cleanly ($50 + $35 = $85, 10.3M + 14.2M = 24.5M) + // 3. All pools calibrated & ready: renders per-pool model & fallback cards cleanly const allReadyData = { account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Pro' }, quotas: { @@ -2367,33 +2367,21 @@ test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, prelimin }, }; widget.refs.update({ data: allReadyData, minuteTick: 2 }); - assert.equal(wkSummary.hidden, false); - assert.equal(wkSummary.querySelector('.quota-rate-wk-sub').hidden, true); - assert.match(wkSummary.textContent, /预测周额度≈ \$85· 24\.5M/); + assert.match(popover.textContent, /Claude Sonnet 4\.6.*5h 满池≈ \$50· 10\.3M.*周限满池≈ \$50· 10\.3M/); + assert.match(popover.textContent, /Gemini.*池综合均值.*5h 满池≈ \$35· 14\.2M/); - // 4. English locale switch updates weekly summary, model cards, and row title tooltip without reload + // 4. English locale switch updates model cards and row title tooltip without reload setI18nLanguage('en-US'); widget.refs.update({ data: allReadyData, minuteTick: 3 }); - assert.match(wkSummary.textContent, /Est\. Weekly Quota≈ \$85· 24\.5M/); + assert.doesNotMatch(popover.textContent, /Est\. Weekly Quota/); + assert.doesNotMatch(popover.textContent, /lowest in pool/); + assert.match(popover.textContent, /5h full≈ \$50· 10\.3M.*Weekly full≈ \$50· 10\.3M/); assert.match( widget.refs.poolsListEl.querySelectorAll('.quota-win-left')[1].getAttribute('title') || '', /Full ~\$50 \(10\.3M\)/ ); - // 5. Custom local weekly budget mode hides official weekly capacity summary - widget.refs.update({ - data: { - ...allReadyData, - quotas: { - ...allReadyData.quotas, - weekly: { isOfficial: false }, - }, - }, - minuteTick: 4, - }); - assert.equal(wkSummary.hidden, true); - - // 6. Pool with 5h-only model card + pool-level preliminary weekly estimate renders supplementary weekly fallback row + // 5. Pool with 5h-only model card + pool-level preliminary weekly estimate renders supplementary weekly fallback row setI18nLanguage('zh-CN'); widget.refs.update({ data: { @@ -2443,8 +2431,6 @@ test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, prelimin }, minuteTick: 5, }); - assert.equal(wkSummary.hidden, false); - assert.match(wkSummary.textContent, /预测周额度.*· 初估.*≈ \$600.*· 200\.0M/); const mixedRows = popover.querySelectorAll('.quota-rate-model-row'); assert.equal(mixedRows.length, 2, 'renders 5h model card + supplementary pool weekly fallback row'); assert.match(mixedRows[0].textContent, /Gemini 3\.1 Pro.*5h 满池≈ \$150/); From 02237692f701c7ded45072d0035dcc506372d3e0 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 19:30:53 +0900 Subject: [PATCH 18/30] feat(panel): add per-pool cycle filter and harden weekly reset anchors - Add a compact inline quota-pool selector on ConsumptionView when Cycle is active, pre-bundling per-pool cycle slices for instant switching and scoping range labels in exports - Classify >6h clientModelConfigs resetTime fallbacks as weekly anchors and advance usageRevision when official reset windows arrive or shift - Deduplicate same-day and same-month date span badges (e.g. Nov 24, Nov 24 ~ 25) --- sidecars/panel/app.js | 335 ++++++++++++++-- sidecars/panel/backend/api-actions.mjs | 2 + sidecars/panel/backend/quota-pools.mjs | 9 +- sidecars/panel/backend/telemetry-builder.mjs | 8 +- sidecars/panel/backend/usage-aggregator.mjs | 378 ++++++++++++++---- sidecars/panel/index.html | 4 +- .../panel/src/components/ui/CustomSelect.js | 4 +- sidecars/panel/src/core/formatters.js | 21 +- sidecars/panel/src/core/reportExporter.js | 12 +- sidecars/panel/src/i18n/en-US.js | 7 + sidecars/panel/src/i18n/zh-CN.js | 7 + sidecars/panel/src/store/telemetryStore.js | 96 ++++- sidecars/panel/src/styles/modern-ui.css | 3 + .../panel/src/styles/views-consumption.css | 47 +++ sidecars/panel/src/views/ConsumptionView.js | 186 ++++++++- sidecars/panel/styles.css | 50 +++ .../test/cross-module-regressions.test.mjs | 58 +++ sidecars/panel/test/quota-pools.test.mjs | 271 ++++++++++++- 18 files changed, 1346 insertions(+), 152 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 126e59a..8782357 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1499,6 +1499,13 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ // Consumption View 'cons.rangeCycle': '周期', + 'cons.cyclePoolAll': '全部池', + 'cons.cyclePoolAllShort': '全部', + 'cons.cyclePoolAria': '当前周期配额池筛选', + 'cons.cyclePoolRemMeta': '剩 {pct}', + 'cons.currentCycle': '当前周期', + 'cons.cycleFallbackWeek': '本周', + 'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', @@ -2398,6 +2405,13 @@ const I18N_MESSAGES_EN_US = Object.freeze({ // Consumption View 'cons.rangeCycle': 'Cycle', + 'cons.cyclePoolAll': 'All Pools', + 'cons.cyclePoolAllShort': 'All', + 'cons.cyclePoolAria': 'Filter current cycle by quota pool', + 'cons.cyclePoolRemMeta': '{pct} left', + 'cons.currentCycle': 'Current Cycle', + 'cons.cycleFallbackWeek': 'This Week', + 'cons.cycleFallbackWeekTip': 'Official weekly reset time unavailable; using calendar week from Monday', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', @@ -4153,17 +4167,34 @@ function formatCnyApprox(usdAmount, rate = 7.2) { function formatDateSpanBadge(startMs, endMs) { const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date(); + const sameYear = s.getFullYear() === e.getFullYear(); + const sameMonth = sameYear && s.getMonth() === e.getMonth(); + const sameDay = sameMonth && s.getDate() === e.getDate(); + if (isEnglishLocale()) { const sMon = EN_MONTH_SHORT[s.getMonth()] || ''; const eMon = EN_MONTH_SHORT[e.getMonth()] || ''; - if (s.getFullYear() !== e.getFullYear()) { + if (!sameYear) { return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`; } + if (sameDay) { + return `${sMon} ${s.getDate()}`; + } + if (sameMonth) { + return `${sMon} ${s.getDate()} ~ ${e.getDate()}`; + } return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`; } - if (s.getFullYear() !== e.getFullYear()) { + + if (!sameYear) { return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`; } + if (sameDay) { + return `${s.getMonth() + 1}月${s.getDate()}日`; + } + if (sameMonth) { + return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getDate()}日`; + } return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } @@ -6909,10 +6940,18 @@ function formatExportDate(ms) { function resolveLocalizedRangeLabel(range, en) { const r = range || {}; const key = String(r.key || '').trim().toLowerCase(); + const poolSuffix = + key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : ''; if (en) { - return RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + const baseEn = + key === 'cycle' && r.isFallbackWeek + ? 'This Week' + : RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + return `${baseEn}${poolSuffix}`; } - return r.label || RANGE_LABELS_ZH[key] || key || '全部时间'; + if (r.label) return r.label; + const baseZh = RANGE_LABELS_ZH[key] || key || '全部时间'; + return `${baseZh}${poolSuffix}`; } function resolveRangeSpanNote(range) { @@ -8989,7 +9028,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, 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 } = (() => { +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, selectConsumptionCyclePool, 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. @@ -9076,6 +9115,7 @@ const telemetryStore = createReactiveStore({ selectedConversationId: initialConversationId, hostRouteConversationId: extractHostRouteCascadeId(), selectedTimeRange: 'today', + selectedCyclePool: 'all', customStartMs: Date.now() - 24 * 3600 * 1000, customEndMs: Date.now(), syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' @@ -9097,7 +9137,7 @@ let inFlightTelemetryPoll = null; let inFlightPresetsPrefetch = null; let lastPrefetchedUsageRevision = 0; let consumptionCacheScopeSig = ''; -const MAX_CONSUMPTION_RANGE_CACHE = 12; +const MAX_CONSUMPTION_RANGE_CACHE = 24; const MAX_CONVERSATION_VIEW_CACHE = 12; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const consumptionRangeCache = new Map(); @@ -9119,11 +9159,19 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ 'enableWindowOverlay', ]); -function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { +function makeConsumptionRangeCacheKey( + range, + customStartMs = 0, + customEndMs = 0, + cyclePool = 'all' +) { const key = String(range || 'all'); if (key === 'custom') { return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; } + if (key === 'cycle' && cyclePool && cyclePool !== 'all') { + return `cycle:${String(cyclePool)}`; + } return key; } @@ -9150,6 +9198,17 @@ function buildConsumptionScopeSig(payload) { return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; } +function reconcileSelectedCyclePool(payload) { + const curPool = telemetryStore.getState().selectedCyclePool || 'all'; + if (curPool === 'all') return; + const pools = payload?.quotas?.pools; + if (!Array.isArray(pools) || pools.length === 0) return; + const exists = pools.some((p) => String(p?.poolKey || p?.family || '') === curPool); + if (!exists) { + telemetryStore.setState({ selectedCyclePool: 'all' }); + } +} + function syncConsumptionCacheScope(payload) { const nextSig = buildConsumptionScopeSig(payload); if (!nextSig) return; @@ -9158,6 +9217,7 @@ function syncConsumptionCacheScope(payload) { clearConversationViewCache(); } consumptionCacheScopeSig = nextSig; + reconcileSelectedCyclePool(payload); } function recordConversationViewToCache(payload) { @@ -9273,14 +9333,19 @@ function putConsumptionRangeCacheEntry(cacheKey, entry) { function recordConsumptionSliceToCache( cons, modelBreakdown, - { customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} + { customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {} ) { const rangeKey = String(cons?.selectedRange?.key || ''); if (!rangeKey) return; + const resolvedPool = + rangeKey === 'cycle' + ? String(cons?.selectedRange?.pool || cyclePool || 'all') + : 'all'; const cacheKey = makeConsumptionRangeCacheKey( rangeKey, rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, - rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0 + rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0, + resolvedPool ); putConsumptionRangeCacheEntry(cacheKey, { revision: Number(cons.revision ?? usageRevision ?? 0), @@ -9828,11 +9893,14 @@ function isEquivalentTelemetry(prev, next) { } } - // 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 + // 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费 const pRange = prev.consumption?.selectedRange; const nRange = next.consumption?.selectedRange; if (pRange?.key !== nRange?.key) return false; - if (nRange?.key === 'custom') { + if ((pRange?.pool || 'all') !== (nRange?.pool || 'all')) return false; + if ((pRange?.label || '') !== (nRange?.label || '')) return false; + if (Boolean(pRange?.isFallbackWeek) !== Boolean(nRange?.isFallbackWeek)) return false; + if (nRange?.key === 'custom' || nRange?.key === 'cycle') { if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false; } @@ -10159,6 +10227,13 @@ async function fetchTelemetry({ force = false } = {}) { const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -10206,6 +10281,7 @@ async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; const reqSettingsRev = settingsRevision; const reqRange = String(params.get('range') || ''); + const reqPool = String(params.get('pool') || 'all'); const reqStartMs = Number(params.get('startMs') || 0); const reqEndMs = Number(params.get('endMs') || 0); const startMs = Date.now(); @@ -10265,14 +10341,17 @@ async function requestTelemetry(params, force) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: reqStartMs, customEndMs: reqEndMs, + cyclePool: reqPool, }); } const latestSt = telemetryStore.getState(); const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); + const activePoolPref = latestSt.selectedCyclePool || 'all'; const matchesCurrentRange = !reqRange || (reqRange === latestSt.selectedTimeRange && + (reqRange !== 'cycle' || reqPool === activePoolPref) && (reqRange !== 'custom' || (reqStartMs === Number(latestSt.customStartMs || 0) && reqEndMs === Number(latestSt.customEndMs || 0)))); @@ -10284,7 +10363,8 @@ async function requestTelemetry(params, force) { const activeKey = makeConsumptionRangeCacheKey( latestSt.selectedTimeRange, latestSt.customStartMs, - latestSt.customEndMs + latestSt.customEndMs, + activePoolPref ); const cachedActive = consumptionRangeCache.get(activeKey); if (cachedActive) { @@ -10293,7 +10373,9 @@ async function requestTelemetry(params, force) { needsSilentRangeRevalidate = true; } } else if ( - latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange + latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange && + (latestSt.selectedTimeRange !== 'cycle' || + (latestSt.telemetry?.consumption?.selectedRange?.pool || 'all') === activePoolPref) ) { resolvedPayload = { ...resolvedPayload, @@ -10345,6 +10427,7 @@ async function requestTelemetry(params, force) { range: latestSt.selectedTimeRange, customStartMs: latestSt.customStartMs, customEndMs: latestSt.customEndMs, + cyclePool: latestSt.selectedCyclePool || 'all', }); } return resolvedPayload; @@ -10370,15 +10453,20 @@ async function fetchConsumptionRangeSlice({ range, customStartMs = 0, customEndMs = 0, + cyclePool = 'all', } = {}) { const reqEpoch = endpointSwitchEpoch; const reqSeq = ++latestConsumptionReqSeq; const targetRange = String(range || 'today'); + const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all'; const current = telemetryStore.getState(); const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('range', targetRange); + if (targetRange === 'cycle' && targetPool !== 'all') { + params.set('pool', targetPool); + } if (targetRange === 'custom') { if (customStartMs > 0) params.set('startMs', String(customStartMs)); if (customEndMs > 0) params.set('endMs', String(customEndMs)); @@ -10397,6 +10485,7 @@ async function fetchConsumptionRangeSlice({ recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { customStartMs, customEndMs, + cyclePool: targetPool, usageRevision: usageRev, }); if (reqSeq !== latestConsumptionReqSeq) return payload; @@ -10404,6 +10493,7 @@ async function fetchConsumptionRangeSlice({ const latestSt = telemetryStore.getState(); const stillMatches = latestSt.selectedTimeRange === targetRange && + (targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) && (targetRange !== 'custom' || (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); @@ -10509,6 +10599,13 @@ async function selectConversation( const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -10615,7 +10712,7 @@ async function selectConversation( */ function selectConsumptionTimeRange( nextRange, - { customStartMs = undefined, customEndMs = undefined } = {} + { customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {} ) { const targetRange = String(nextRange || 'today'); const prevSt = telemetryStore.getState(); @@ -10627,14 +10724,26 @@ function selectConsumptionTimeRange( targetRange === 'custom' ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) : prevSt.customEndMs; + const nextCyclePool = + targetRange === 'cycle' + ? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all') + : prevSt.selectedCyclePool || 'all'; const statePatch = { selectedTimeRange: targetRange }; + if (cyclePool !== undefined) { + statePatch.selectedCyclePool = nextCyclePool; + } if (targetRange === 'custom') { statePatch.customStartMs = nextStartMs; statePatch.customEndMs = nextEndMs; } - const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs); + const cacheKey = makeConsumptionRangeCacheKey( + targetRange, + nextStartMs, + nextEndMs, + targetRange === 'cycle' ? nextCyclePool : 'all' + ); const cached = consumptionRangeCache.get(cacheKey); const prevTelemetry = prevSt.telemetry; @@ -10653,6 +10762,7 @@ function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } @@ -10661,9 +10771,14 @@ function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } +function selectConsumptionCyclePool(nextPool = 'all') { + return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') }); +} + /** * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 */ @@ -11338,7 +11453,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, 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 }; +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, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -12044,8 +12159,8 @@ const CustomSelect = defineComponent({ const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder; - labelText = selectedOpt ? selectedOpt.label : fallbackText; - titleText = labelText; + labelText = selectedOpt ? selectedOpt.shortLabel || selectedOpt.label : fallbackText; + titleText = selectedOpt ? selectedOpt.title || selectedOpt.label : fallbackText; } patchText(triggerLabel, labelText); @@ -30029,6 +30144,86 @@ function ceilToEndOfMinuteMs(ms) { return d.getTime(); } +function formatCyclePoolShortLabel(poolKey, poolLabel) { + if (poolKey === 'Argon') return 'Argon'; + if (poolKey === 'Carbon') return 'Carbon'; + if (poolKey === 'Claude & GPT') return 'Claude/GPT'; + return poolLabel || poolKey; +} + +function buildCyclePoolSelectOptions(pools, isCustomWeeklyMode = false) { + const list = Array.isArray(pools) ? pools : []; + let sumCycleCost = 0; + let hasAnyCycleCost = false; + for (let i = 0; i < list.length; i++) { + const c = Number(list[i]?.cycleWeekly?.costUsd); + if (Number.isFinite(c) && c >= 0 && list[i]?.cycleWeekly) { + sumCycleCost += c; + hasAnyCycleCost = true; + } + } + const allLabel = t('cons.cyclePoolAll'); + const opts = [ + { + value: 'all', + label: allLabel, + shortLabel: t('cons.cyclePoolAllShort'), + meta: !isCustomWeeklyMode && hasAnyCycleCost ? formatUsd(sumCycleCost) : '', + title: allLabel, + }, + ]; + for (let i = 0; i < list.length; i++) { + const p = list[i]; + const key = String(p?.poolKey || p?.family || '').trim(); + if (!key || key === 'Unknown') continue; + const label = String(p?.poolLabel || key).trim(); + const shortLabel = formatCyclePoolShortLabel(key, label); + const metaParts = []; + if ( + !isCustomWeeklyMode && + p?.weeklyRemainingPct != null && + Number.isFinite(Number(p.weeklyRemainingPct)) + ) { + metaParts.push( + t('cons.cyclePoolRemMeta', { + pct: formatPctNumber(p.weeklyRemainingPct, { withSymbol: true }), + }) + ); + } + if (!isCustomWeeklyMode && p?.cycleWeekly && Number.isFinite(Number(p.cycleWeekly.costUsd))) { + metaParts.push(formatUsd(p.cycleWeekly.costUsd)); + } + const meta = metaParts.join(' · '); + opts.push({ + value: key, + label, + shortLabel, + meta, + title: meta ? `${label} (${meta})` : label, + }); + } + return opts; +} + +function formatCycleMinuteSpanTip(startMs, endMs, isFallbackWeek = false) { + const s = Number(startMs); + const e = Number(endMs); + if (!(s > 0 && e > 0 && Number.isFinite(s) && Number.isFinite(e))) return null; + const sd = new Date(s); + const ed = new Date(e); + const pad2 = (n) => String(n).padStart(2, '0'); + const sTime = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; + const eTime = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; + const sameDay = + sd.getFullYear() === ed.getFullYear() && + sd.getMonth() === ed.getMonth() && + sd.getDate() === ed.getDate(); + const sDate = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; + const eDate = `${ed.getMonth() + 1}/${pad2(ed.getDate())}`; + const base = sameDay ? `${sDate} ${sTime} ~ ${eTime}` : `${sDate} ${sTime} ~ ${eDate} ${eTime}`; + return isFallbackWeek ? `${base} · ${t('cons.cycleFallbackWeekTip')}` : base; +} + const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -30134,6 +30329,16 @@ const ConsumptionView = defineComponent({ // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); + const cyclePoolSelect = CustomSelect({ + className: 'cons-cycle-pool-select', + modelValue: telemetryStore.getState().selectedCyclePool || 'all', + options: buildCyclePoolSelectOptions([]), + onUpdateModelValue: (nextPool) => { + selectConsumptionCyclePool(nextPool || 'all'); + }, + }); + patchAttr(cyclePoolSelect.el, 'hidden', true); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) }); const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); @@ -30271,8 +30476,9 @@ const ConsumptionView = defineComponent({ const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ - h('span', { className: 'panel-title' }, [ + h('span', { className: 'panel-title cons-overview-title' }, [ dateSpanBadge, + cyclePoolSelect.el, ]), h('div', { className: 'cons-overview-controls' }, [ timeFilterSwitch.el, @@ -31725,7 +31931,7 @@ const ConsumptionView = defineComponent({ const cons = slice.consumption || {}; const rangeInfo = cons.selectedRange || {}; - // 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 + // 始终在 0ms 同步顶部时间段滑块、周期池选择器及自定义日期条显隐,给予即刻交互反馈 timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); if (!hasUncommittedCustomDraft) { @@ -31735,17 +31941,45 @@ const ConsumptionView = defineComponent({ endPicker.setValue(draftEndMs); } + const isCustomWeeklyMode = + slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost'; + const cyclePoolOptions = + slice.range === 'cycle' + ? buildCyclePoolSelectOptions(slice.quotaPools, isCustomWeeklyMode) + : []; + const activePoolFilter = slice.range === 'cycle' ? slice.cyclePool || 'all' : 'all'; + const showCyclePoolSelect = slice.range === 'cycle' && cyclePoolOptions.length > 2; + if (!showCyclePoolSelect) { + cyclePoolSelect.close?.(); + patchAttr(cyclePoolSelect.el, 'hidden', true); + } else { + cyclePoolSelect.setProps({ + modelValue: activePoolFilter, + options: cyclePoolOptions, + }); + patchAttr(cyclePoolSelect.el, 'hidden', false); + } + // 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制 - if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) { + const payloadPool = rangeInfo.key === 'cycle' ? rangeInfo.pool || 'all' : 'all'; + if ( + (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) || + (slice.range === 'cycle' && rangeInfo.pool && payloadPool !== activePoolFilter) + ) { return; } const preset = - slice.range !== 'custom' && cons.presets?.[slice.range] + slice.range !== 'custom' && + !(slice.range === 'cycle' && activePoolFilter !== 'all') && + cons.presets?.[slice.range] ? cons.presets[slice.range] : null; const acct = cons.account || preset?.account || {}; const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); + const cycleOptionsSig = showCyclePoolSelect + ? cyclePoolOptions.map((o) => `${o.value}:${o.label}:${o.meta || ''}`).join('|') + : ''; const now = new Date(); const currentMonthIdx = now.getMonth(); const monthlyYear = cons.monthlyYear || now.getFullYear(); @@ -31753,6 +31987,9 @@ const ConsumptionView = defineComponent({ const renderTuple = [ locale, slice.range, + activePoolFilter, + cycleOptionsSig, + Boolean(rangeInfo.isFallbackWeek), slice.customStartMs, slice.customEndMs, slice.modelDisplayMode, @@ -31773,13 +32010,36 @@ const ConsumptionView = defineComponent({ cons.monthlySeries, ]; if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; - drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); + drawConsumptionData(slice, { + cons, + preset, + acct, + rangeInfo, + activePoolFilter, + dateSpan, + currentMonthIdx, + monthlyYear, + }); lastRenderedTuple = renderTuple; } - function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { - // 1. 同步用量概览矩阵与顶部 4 段比例条 + function drawConsumptionData( + slice, + { cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear } + ) { + // 1. 同步用量概览矩阵及顶部 4 段比例条 patchText(dateSpanBadge, dateSpan); + patchAttr( + dateSpanBadge, + 'title', + slice.range === 'cycle' + ? formatCycleMinuteSpanTip( + rangeInfo.startMs, + rangeInfo.endMs, + Boolean(rangeInfo.isFallbackWeek) + ) + : null + ); const totalTokens = Number(acct.totalTokens || 0); const inputTokens = Number(acct.inputTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0); @@ -31970,11 +32230,18 @@ const ConsumptionView = defineComponent({ ...allTrendMergedModels, ]); - // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 - const rangeBadgeText = isEnglishLocale() - ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || - t('cons.allTime') - : preset?.label || rangeInfo.label || t('cons.allTime'); + // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)及悬停分模型浮层 + const rangeBadgeText = + slice.range === 'cycle' + ? `${rangeInfo.isFallbackWeek || slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost' ? t('cons.cycleFallbackWeek') : t('cons.currentCycle')}${ + activePoolFilter && activePoolFilter !== 'all' + ? ` · ${rangeInfo.poolLabel || activePoolFilter}` + : '' + }` + : isEnglishLocale() + ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || + t('cons.allTime') + : preset?.label || rangeInfo.label || t('cons.allTime'); patchText(trendRangeBadge, rangeBadgeText); const firstTrendSlot = rawTrendSeries[0] || null; const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; @@ -32134,7 +32401,7 @@ const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; const nextRankingKey = showWorkspacesTab ? 'workspaces' : showSessionsTab @@ -32270,8 +32537,11 @@ const ConsumptionView = defineComponent({ const unsub = telemetryStore.subscribe( (st) => ({ range: st.selectedTimeRange, + cyclePool: st.selectedCyclePool || 'all', customStartMs: st.customStartMs, customEndMs: st.customEndMs, + quotaPools: st.telemetry?.quotas?.pools, + weeklyLimitMode: st.telemetry?.settings?.weeklyLimitMode, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, modelDisplayMode: normalizeModelDisplayMode( @@ -32325,6 +32595,7 @@ const ConsumptionView = defineComponent({ ariaLabel: t('cons.rangeAria'), options: getConsumptionTimeRangeOptions(), }); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); patchText(applyCustomBtnLabel, t('cons.applyFilter')); patchText(rangeToSpan, t('cons.rangeTo')); patchText(totalTokensLabel, t('cons.totalTokens')); @@ -32382,6 +32653,7 @@ const ConsumptionView = defineComponent({ unsubView(); unsubI18n(); consExportMenu.destroy(); + cyclePoolSelect.destroy(); trendChart.destroy?.(); rankingTabSwitch.destroy(); modelsSortSwitch.destroy(); @@ -32396,6 +32668,7 @@ const ConsumptionView = defineComponent({ el: rootEl, refs: { timeFilterSwitch, + cyclePoolSelect, startPicker, endPicker, viewScrollbar, diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 35b0c59..15d05fc 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -258,8 +258,10 @@ export async function executeTelemetryAction(data, opts = {}) { rawScope === 'conversation' ? rawScope : ''; + const rawPool = typeof data?.pool === 'string' ? data.pool.trim().slice(0, 48) : ''; const filterOpts = { range: data?.range || 'all', + ...(rawPool ? { pool: rawPool } : {}), startMs: sanitizePositiveFiniteMs(data?.startMs), endMs: sanitizePositiveFiniteMs(data?.endMs), ...(scope ? { scope } : {}), diff --git a/sidecars/panel/backend/quota-pools.mjs b/sidecars/panel/backend/quota-pools.mjs index c8dd7fe..11a7175 100644 --- a/sidecars/panel/backend/quota-pools.mjs +++ b/sidecars/panel/backend/quota-pools.mjs @@ -370,9 +370,14 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { } const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs); + const cfgResetMs = parseIsoMs(cfgQuota?.resetTime); + const isCfgWeekly = + targetIdent.poolKey === 'Argon' || + targetIdent.poolKey === 'Carbon' || + cfgResetMs > nowForQuotaMs + 6 * 3600 * 1000; if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) { - if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') { - builder.bucketWeekly = cfgQuota; + if (isCfgWeekly) { + builder.bucketWeekly = { ...cfgQuota, window: 'weekly' }; } else { builder.fallback5h = cfgQuota; } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index d1d0fa6..4be4357 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -2382,6 +2382,9 @@ export async function buildTelemetryPayloadInternal( revision: usageRevision, selectedRange: { key: selectedWindow.key, + ...(selectedWindow.pool ? { pool: selectedWindow.pool } : {}), + ...(selectedWindow.poolLabel ? { poolLabel: selectedWindow.poolLabel } : {}), + ...(selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}), label: selectedWindow.label, startMs: trendStartMs, endMs: trendEndMs, @@ -2802,6 +2805,9 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) { revision: agg.usageRevision, selectedRange: { key: agg.selectedWindow.key, + ...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}), + ...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}), + ...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}), label: agg.selectedWindow.label, startMs: agg.trendStartMs, endMs: agg.trendEndMs, @@ -2969,7 +2975,7 @@ export function buildTelemetryPayload( } } } - const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`; + const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.pool || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`; const key = `${endpointKey}::${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`; if (inFlightRequests.has(key)) { return inFlightRequests.get(key); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 8510c6b..a41686f 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -786,13 +786,14 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { ? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000) : nowMs - 5 * 3600 * 1000; const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0; - const startWkMs = - resetWkMs > nowMs - ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) - : weekFallbackStartMs; + const hasOfficialWk = resetWkMs > nowMs; + const startWkMs = hasOfficialWk + ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) + : weekFallbackStartMs; poolCycleBuckets.set(poolKey, { start5hMs, startWkMs, + hasOfficialWk, b5h: createUsageBucket(), bWk: createUsageBucket(), pricedTokens5h: 0, @@ -809,7 +810,27 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { return poolCycleBuckets; } -function resolvePoolBucketForStep( +export function normalizeCyclePoolFilter(rawPool, availablePoolKeys = null) { + const raw = typeof rawPool === 'string' ? rawPool.trim() : ''; + if (!raw || raw.toLowerCase() === 'all') return 'all'; + const lower = raw.toLowerCase(); + let canonical = raw; + if (lower === 'gemini') canonical = 'Gemini'; + else if (lower === 'argon' || lower === 'gemini 4 argon') canonical = 'Argon'; + else if (lower === 'carbon' || lower === 'gemini 4 carbon') canonical = 'Carbon'; + else if (lower === 'claude & gpt' || lower === 'claude' || lower === 'gpt') { + canonical = 'Claude & GPT'; + } + if (availablePoolKeys && availablePoolKeys.size > 0 && !availablePoolKeys.has(canonical)) { + for (const k of availablePoolKeys.keys()) { + if (String(k).toLowerCase() === lower) return k; + } + return 'all'; + } + return canonical; +} + +function resolveStepPoolAssignment( st, mInfo, poolCycleBuckets, @@ -817,7 +838,6 @@ function resolvePoolBucketForStep( hasDedicatedCarbonPool, hasDedicatedArgonPool ) { - if (poolCycleBuckets.size === 0) return null; let cachedPool = poolByModel.get(mInfo); if ( !cachedPool || @@ -841,11 +861,68 @@ function resolvePoolBucketForStep( key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName, - bucket: poolCycleBuckets.get(poolKey) || null, + poolKey, + bucket: poolKey && poolCycleBuckets.size > 0 ? poolCycleBuckets.get(poolKey) || null : null, }; poolByModel.set(mInfo, cachedPool); } - return cachedPool.bucket; + return cachedPool; +} + +function resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool = 'all', + isCustomWeeklyMode = false, + cycleAnchors = {}, + nowMs = Date.now(), + poolCycleBuckets, + quotaPoolsMap = null, + earliestActiveCyclePoolStartMs = Infinity, + earliestSelectedStepMs = Infinity, +}) { + if (!selectedWindow || selectedWindow.key !== 'cycle') return selectedWindow; + if (effectiveCyclePool !== 'all') { + const poolBucket = poolCycleBuckets?.get?.(effectiveCyclePool) || null; + const poolMeta = quotaPoolsMap instanceof Map ? quotaPoolsMap.get(effectiveCyclePool) : null; + const poolLabel = poolMeta?.poolLabel || effectiveCyclePool; + const baseStartMs = + !isCustomWeeklyMode && poolBucket ? poolBucket.startWkMs : selectedWindow.startMs; + const startMs = + Number.isFinite(earliestSelectedStepMs) && earliestSelectedStepMs < Infinity + ? Math.min(baseStartMs, earliestSelectedStepMs) + : baseStartMs; + const isFallbackWeek = !isCustomWeeklyMode && !poolBucket?.hasOfficialWk; + return { + ...selectedWindow, + pool: effectiveCyclePool, + poolLabel, + isFallbackWeek, + label: `${isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期'} · ${poolLabel}`, + startMs, + }; + } + let hasAnyOfficialWk = !isCustomWeeklyMode && (cycleAnchors?.weeklyResetMs || 0) > nowMs; + if (!hasAnyOfficialWk && poolCycleBuckets instanceof Map) { + for (const b of poolCycleBuckets.values()) { + if (b?.hasOfficialWk) { + hasAnyOfficialWk = true; + break; + } + } + } + const isFallbackWeek = !isCustomWeeklyMode && !hasAnyOfficialWk; + const startMs = + Number.isFinite(earliestActiveCyclePoolStartMs) && earliestActiveCyclePoolStartMs < Infinity + ? Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs) + : selectedWindow.startMs; + return { + ...selectedWindow, + pool: 'all', + poolLabel: '', + isFallbackWeek, + label: isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期', + startMs, + }; } function buildUsageTrendSeries( @@ -1155,6 +1232,7 @@ function computeFamilySessionBuckets({ presetKeys = [], presetWindows = {}, selectedWindow, + effectiveCyclePool = 'all', isCustomWeeklyMode = false, poolCycleBuckets = new Map(), normalizedQuotaAccount = '', @@ -1166,8 +1244,11 @@ function computeFamilySessionBuckets({ for (const k of presetKeys) { sessionBuckets[k] = createUsageBucket(); } + const isScopedCyclePool = selectedWindow?.key === 'cycle' && effectiveCyclePool !== 'all'; const selectedSessionBucket = - (selectedWindow?.key && sessionBuckets[selectedWindow.key]) || createUsageBucket(); + selectedWindow?.key && !isScopedCyclePool && sessionBuckets[selectedWindow.key] + ? sessionBuckets[selectedWindow.key] + : createUsageBucket(); if (!(familySet instanceof Set) || familySet.size === 0) { const sessionPresets = {}; for (const k of presetKeys) { @@ -1233,17 +1314,15 @@ function computeFamilySessionBuckets({ unpriced, }; - const poolBucketEntry = - poolCycleBuckets.size > 0 - ? resolvePoolBucketForStep( - st, - mInfo, - poolCycleBuckets, - poolByModel, - hasDedicatedCarbonPool, - hasDedicatedArgonPool - ) - : null; + const stepPool = resolveStepPoolAssignment( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool + ); + const poolBucketEntry = stepPool.bucket; let inCurrentCycle = false; if (qMs > 0 && qMs <= nowMs) { @@ -1273,14 +1352,19 @@ function computeFamilySessionBuckets({ } } - if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) { + if ( + selectedWindow && + (!sessionBuckets[selectedWindow.key] || + selectedWindow.key === 'custom' || + isScopedCyclePool) + ) { const selCmpMs = selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs; const inSelectedWindow = selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' - ? inCurrentCycle + ? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool) : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId); @@ -1407,16 +1491,30 @@ export function aggregateMultiWindowUsage({ sessionBuckets[k] = createUsageBucket(); } - // 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口) + // 为每个配额池建立独立的 5h 及周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口) const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); + const effectiveCyclePool = + selectedWindow.key === 'cycle' + ? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets) + : 'all'; + const isScopedCyclePool = selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all'; + const selectedRangeCacheKey = isScopedCyclePool + ? `cycle:${effectiveCyclePool}` + : selectedWindow.key; const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const poolByModel = new Map(); const quotaWeekBucket = createUsageBucket(); const normalizedQuotaAccount = currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); - const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket(); - const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket(); + const selectedAccountBucket = + !isScopedCyclePool && accountBuckets[selectedWindow.key] + ? accountBuckets[selectedWindow.key] + : createUsageBucket(); + const selectedSessionBucket = + !isScopedCyclePool && sessionBuckets[selectedWindow.key] + ? sessionBuckets[selectedWindow.key] + : createUsageBucket(); const perModelStats = new Map(); const perConvStats = new Map(); const perWorkspaceStats = new Map(); @@ -1463,15 +1561,31 @@ export function aggregateMultiWindowUsage({ modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && sameUsageEntries(snapshot.entries, allEntriesToAggregate); - const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; + const previous = sameSnapshot ? snapshot.ranges.get(selectedRangeCacheKey) : null; if (previous) { // 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。 + const probeEffectiveWin = + selectedWindow.key === 'cycle' + ? resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs: previous.earliestActiveCyclePoolStartMs, + earliestSelectedStepMs: previous.earliest, + }) + : selectedWindow; const effectivePrevWin = selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow - ? { ...previous.effectiveSelectedWindow, endMs: nowMs } + ? { ...probeEffectiveWin, endMs: nowMs } : selectedWindow; const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); if ( + Boolean(effectivePrevWin.isFallbackWeek) === + Boolean(previous.effectiveSelectedWindow?.isFallbackWeek) && trend.hourly === previous.trend.hourly && trend.stepMs === previous.trend.stepMs && trend.first === previous.trend.first && @@ -1483,8 +1597,8 @@ export function aggregateMultiWindowUsage({ (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) ) ) { - snapshot.ranges.delete(selectedWindow.key); - snapshot.ranges.set(selectedWindow.key, previous); + snapshot.ranges.delete(selectedRangeCacheKey); + snapshot.ranges.set(selectedRangeCacheKey, previous); if (previous.familySig === familySig) { return { ...previous.result, @@ -1501,6 +1615,7 @@ export function aggregateMultiWindowUsage({ presetKeys, presetWindows, selectedWindow, + effectiveCyclePool, isCustomWeeklyMode, poolCycleBuckets, normalizedQuotaAccount, @@ -1588,7 +1703,7 @@ export function aggregateMultiWindowUsage({ } } - const poolBucketEntry = resolvePoolBucketForStep( + const stepPool = resolveStepPoolAssignment( st, mInfo, poolCycleBuckets, @@ -1596,6 +1711,7 @@ export function aggregateMultiWindowUsage({ hasDedicatedCarbonPool, hasDedicatedArgonPool ); + const poolBucketEntry = stepPool.bucket; if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) { if (qMs > poolBucketEntry.lastActivityMs) { @@ -1691,7 +1807,7 @@ export function aggregateMultiWindowUsage({ selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' - ? inCurrentCycle + ? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool) : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { @@ -1703,7 +1819,7 @@ export function aggregateMultiWindowUsage({ ) { earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; } - if (selectedWindow.key === 'custom') { + if (selectedWindow.key === 'custom' || isScopedCyclePool) { accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); if (isCurrentConv) { accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId); @@ -1785,15 +1901,17 @@ export function aggregateMultiWindowUsage({ ); // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) - const effectiveSelectedWindow = - selectedWindow.key === 'cycle' && - Number.isFinite(earliestActiveCyclePoolStartMs) && - earliestActiveCyclePoolStartMs < Infinity - ? { - ...selectedWindow, - startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), - } - : selectedWindow; + const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs, + earliestSelectedStepMs, + }); const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( selectedWindow, effectiveSelectedWindow, @@ -1929,6 +2047,11 @@ export function aggregateMultiWindowUsage({ if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey); } lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap); + } else if (previous) { + resolvedUsageRevision = ++usageSnapshotRevisionSeq; + activeSnap.revision = resolvedUsageRevision; + activeSnap.ranges.clear(); + activeSnap.selectedRanges?.clear?.(); } else { resolvedUsageRevision = activeSnap.revision; } @@ -1959,19 +2082,20 @@ export function aggregateMultiWindowUsage({ }; if (modelInputs && activeSnap) { const { ranges } = activeSnap; - ranges.delete(selectedWindow.key); - ranges.set(selectedWindow.key, { + ranges.delete(selectedRangeCacheKey); + ranges.set(selectedRangeCacheKey, { familySig, windows, selectedWindow, effectiveSelectedWindow, + earliestActiveCyclePoolStartMs, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs, }); // 缓存各时间窗口的完整多窗口聚合结果,同快照复用时亚毫秒命中。 - if (ranges.size > 10) ranges.delete(ranges.keys().next().value); + if (ranges.size > 16) ranges.delete(ranges.keys().next().value); } return result; } @@ -2019,6 +2143,14 @@ export function aggregateSelectedWindowUsage({ : 0; const poolCycleBuckets = selectedWindow.key === 'cycle' ? buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) : new Map(); + const effectiveCyclePool = + selectedWindow.key === 'cycle' + ? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets) + : 'all'; + const selectedRangeCacheKey = + selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all' + ? `cycle:${effectiveCyclePool}` + : selectedWindow.key; const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const poolByModel = new Map(); @@ -2032,6 +2164,19 @@ export function aggregateSelectedWindowUsage({ const currentYear = new Date(nowMs).getFullYear(); const timeZone = modelInputs ? resolveCachedLocalTimeZone() : ''; + const currentCheckWindows = + selectedWindow.key === 'cycle' + ? [ + selectedWindow, + ...Array.from(poolCycleBuckets, ([key, { startWkMs }]) => ({ + key: `${key}:week`, + label: `${key}:week`, + startMs: startWkMs, + endMs: nowMs, + })), + ] + : [selectedWindow]; + const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null; const sameSnapshot = Boolean( modelInputs && @@ -2047,24 +2192,45 @@ export function aggregateSelectedWindowUsage({ if (sameSnapshot) { snapshot.selectedRanges ??= new Map(); - const cachedFull = snapshot.ranges.get(selectedWindow.key); - const cachedLite = snapshot.selectedRanges.get(selectedWindow.key); + const cachedFull = snapshot.ranges.get(selectedRangeCacheKey); + const cachedLite = snapshot.selectedRanges.get(selectedRangeCacheKey); const candidate = cachedFull || cachedLite; if (candidate) { const prevWin = candidate.selectedWindow || candidate.windows?.[0] || selectedWindow; + const probeEffectiveWin = + selectedWindow.key === 'cycle' + ? resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs: candidate.earliestActiveCyclePoolStartMs, + earliestSelectedStepMs: candidate.earliest, + }) + : selectedWindow; const effectivePrevWin = selectedWindow.key === 'cycle' && candidate.effectiveSelectedWindow - ? { ...candidate.effectiveSelectedWindow, endMs: nowMs } + ? { ...probeEffectiveWin, endMs: nowMs } : selectedWindow; const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest); + const prevCheckWindows = candidate.checkWindows || [prevWin]; + const compareNextWindows = + prevCheckWindows.length === currentCheckWindows.length + ? currentCheckWindows + : [selectedWindow]; if ( + Boolean(effectivePrevWin.isFallbackWeek) === + Boolean(candidate.effectiveSelectedWindow?.isFallbackWeek) && trend.hourly === candidate.trend.hourly && trend.stepMs === candidate.trend.stepMs && trend.first === candidate.trend.first && trend.last === candidate.trend.last && sameUsageWindows( - [prevWin], - [selectedWindow], + prevCheckWindows.length === compareNextWindows.length ? prevCheckWindows : [prevWin], + compareNextWindows, (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)), (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) ) @@ -2079,6 +2245,7 @@ export function aggregateSelectedWindowUsage({ presetKeys: [], presetWindows: {}, selectedWindow, + effectiveCyclePool, isCustomWeeklyMode, poolCycleBuckets, normalizedQuotaAccount, @@ -2100,6 +2267,9 @@ export function aggregateSelectedWindowUsage({ topWorkspaces: res.topWorkspaces || [], }; } + snapshot.revision = ++usageSnapshotRevisionSeq; + snapshot.ranges.clear(); + snapshot.selectedRanges.clear(); } } @@ -2115,6 +2285,11 @@ export function aggregateSelectedWindowUsage({ maxCutoffMs = nowMs; if (isCustomWeeklyMode) { minCutoffMs = weekStartMs; + } else if (effectiveCyclePool !== 'all' && poolCycleBuckets.has(effectiveCyclePool)) { + minCutoffMs = Math.max( + 0, + poolCycleBuckets.get(effectiveCyclePool).startWkMs - maxSettlementSlackMs + ); } else if (poolCycleBuckets.size > 0) { minCutoffMs = selectedWindow.startMs; for (const entry of poolCycleBuckets.values()) { @@ -2190,20 +2365,24 @@ export function aggregateSelectedWindowUsage({ : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; + mInfo = resolveStepModel(st); + const stepPool = resolveStepPoolAssignment( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool + ); + poolBucketEntry = stepPool.bucket; + if (effectiveCyclePool !== 'all' && stepPool.poolKey !== effectiveCyclePool) { + continue; + } let inCurrentCycle = false; if (isCustomWeeklyMode) { inCurrentCycle = tMs >= weekStartMs; } else if (poolCycleBuckets.size > 0) { if (!includeInQuotaPools) continue; - mInfo = resolveStepModel(st); - poolBucketEntry = resolvePoolBucketForStep( - st, - mInfo, - poolCycleBuckets, - poolByModel, - hasDedicatedCarbonPool, - hasDedicatedArgonPool - ); const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : selectedWindow.startMs; @@ -2320,15 +2499,17 @@ export function aggregateSelectedWindowUsage({ } } - const effectiveSelectedWindow = - selectedWindow.key === 'cycle' && - Number.isFinite(earliestActiveCyclePoolStartMs) && - earliestActiveCyclePoolStartMs < Infinity - ? { - ...selectedWindow, - startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), - } - : selectedWindow; + const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs, + earliestSelectedStepMs, + }); const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( selectedWindow, @@ -2369,17 +2550,19 @@ export function aggregateSelectedWindowUsage({ if (sameSnapshot) { snapshot.selectedRanges ??= new Map(); - snapshot.selectedRanges.delete(selectedWindow.key); - snapshot.selectedRanges.set(selectedWindow.key, { + snapshot.selectedRanges.delete(selectedRangeCacheKey); + snapshot.selectedRanges.set(selectedRangeCacheKey, { familySig, + checkWindows: currentCheckWindows, selectedWindow, effectiveSelectedWindow, + earliestActiveCyclePoolStartMs, trend, result: sliceResult, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs, }); - if (snapshot.selectedRanges.size > 12) { + if (snapshot.selectedRanges.size > 16) { snapshot.selectedRanges.delete(snapshot.selectedRanges.keys().next().value); } } @@ -2426,6 +2609,10 @@ export function aggregateSessionUsageForFamily({ presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); } const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); + const effectiveCyclePool = + selectedWindow.key === 'cycle' + ? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets) + : 'all'; const normalizedQuotaAccount = currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); @@ -2464,6 +2651,7 @@ export function aggregateSessionUsageForFamily({ presetKeys, presetWindows, selectedWindow, + effectiveCyclePool, isCustomWeeklyMode, poolCycleBuckets, normalizedQuotaAccount, @@ -2473,7 +2661,7 @@ export function aggregateSessionUsageForFamily({ } /** - * 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 + * 批量预聚合全部 7 个用量页预设区间及各配额池独立周期(复用同一次条目收集和时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 */ export function aggregateConsumptionPresetBundle(params) { const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {}; @@ -2488,6 +2676,25 @@ export function aggregateConsumptionPresetBundle(params) { const ranges = {}; let usageRevision = usageSnapshotRevisionSeq; + const packSlice = (agg) => ({ + selectedRange: { + key: agg.selectedWindow.key, + ...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}), + ...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}), + ...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}), + label: agg.selectedWindow.label, + startMs: agg.trendStartMs, + endMs: agg.trendEndMs, + }, + session: agg.finalizedSelectedSession, + account: agg.finalizedSelectedAccount, + trendSeries: agg.trendSeries, + sourcesBreakdown: agg.sourcesBreakdown, + modelBreakdown: agg.modelBreakdown, + topConversations: agg.topConversations || [], + topWorkspaces: agg.topWorkspaces || [], + }); + for (const rangeKey of CONSUMPTION_PRESET_RANGE_KEYS) { const agg = aggregateSelectedWindowUsage({ ...params, @@ -2495,21 +2702,20 @@ export function aggregateConsumptionPresetBundle(params) { precollectedEntries, }); usageRevision = agg.usageRevision; - ranges[rangeKey] = { - selectedRange: { - key: agg.selectedWindow.key, - label: agg.selectedWindow.label, - startMs: agg.trendStartMs, - endMs: agg.trendEndMs, - }, - session: agg.finalizedSelectedSession, - account: agg.finalizedSelectedAccount, - trendSeries: agg.trendSeries, - sourcesBreakdown: agg.sourcesBreakdown, - modelBreakdown: agg.modelBreakdown, - topConversations: agg.topConversations || [], - topWorkspaces: agg.topWorkspaces || [], - }; + ranges[rangeKey] = packSlice(agg); + } + + if (params?.quotaPoolsMap instanceof Map) { + for (const poolKey of params.quotaPoolsMap.keys()) { + if (!poolKey || poolKey === 'all') continue; + const agg = aggregateSelectedWindowUsage({ + ...params, + filterOpts: { range: 'cycle', pool: poolKey }, + precollectedEntries, + }); + usageRevision = agg.usageRevision; + ranges[`cycle:${poolKey}`] = packSlice(agg); + } } return { usageRevision, ranges }; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index f295268..9fef7dd 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/ui/CustomSelect.js b/sidecars/panel/src/components/ui/CustomSelect.js index bc83a23..bfcf8be 100644 --- a/sidecars/panel/src/components/ui/CustomSelect.js +++ b/sidecars/panel/src/components/ui/CustomSelect.js @@ -469,8 +469,8 @@ export const CustomSelect = defineComponent({ const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder; - labelText = selectedOpt ? selectedOpt.label : fallbackText; - titleText = labelText; + labelText = selectedOpt ? selectedOpt.shortLabel || selectedOpt.label : fallbackText; + titleText = selectedOpt ? selectedOpt.title || selectedOpt.label : fallbackText; } patchText(triggerLabel, labelText); diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 7749719..13c6ca5 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -104,17 +104,34 @@ export function formatCnyApprox(usdAmount, rate = 7.2) { export function formatDateSpanBadge(startMs, endMs) { const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date(); + const sameYear = s.getFullYear() === e.getFullYear(); + const sameMonth = sameYear && s.getMonth() === e.getMonth(); + const sameDay = sameMonth && s.getDate() === e.getDate(); + if (isEnglishLocale()) { const sMon = EN_MONTH_SHORT[s.getMonth()] || ''; const eMon = EN_MONTH_SHORT[e.getMonth()] || ''; - if (s.getFullYear() !== e.getFullYear()) { + if (!sameYear) { return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`; } + if (sameDay) { + return `${sMon} ${s.getDate()}`; + } + if (sameMonth) { + return `${sMon} ${s.getDate()} ~ ${e.getDate()}`; + } return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`; } - if (s.getFullYear() !== e.getFullYear()) { + + if (!sameYear) { return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`; } + if (sameDay) { + return `${s.getMonth() + 1}月${s.getDate()}日`; + } + if (sameMonth) { + return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getDate()}日`; + } return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index 9ecfb99..9ec25db 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -99,10 +99,18 @@ function formatExportDate(ms) { function resolveLocalizedRangeLabel(range, en) { const r = range || {}; const key = String(r.key || '').trim().toLowerCase(); + const poolSuffix = + key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : ''; if (en) { - return RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + const baseEn = + key === 'cycle' && r.isFallbackWeek + ? 'This Week' + : RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + return `${baseEn}${poolSuffix}`; } - return r.label || RANGE_LABELS_ZH[key] || key || '全部时间'; + if (r.label) return r.label; + const baseZh = RANGE_LABELS_ZH[key] || key || '全部时间'; + return `${baseZh}${poolSuffix}`; } function resolveRangeSpanNote(range) { diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index faebf89..ff228e5 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -240,6 +240,13 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ // Consumption View 'cons.rangeCycle': 'Cycle', + 'cons.cyclePoolAll': 'All Pools', + 'cons.cyclePoolAllShort': 'All', + 'cons.cyclePoolAria': 'Filter current cycle by quota pool', + 'cons.cyclePoolRemMeta': '{pct} left', + 'cons.currentCycle': 'Current Cycle', + 'cons.cycleFallbackWeek': 'This Week', + 'cons.cycleFallbackWeekTip': 'Official weekly reset time unavailable; using calendar week from Monday', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 845f698..5860f14 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -240,6 +240,13 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ // Consumption View 'cons.rangeCycle': '周期', + 'cons.cyclePoolAll': '全部池', + 'cons.cyclePoolAllShort': '全部', + 'cons.cyclePoolAria': '当前周期配额池筛选', + 'cons.cyclePoolRemMeta': '剩 {pct}', + 'cons.currentCycle': '当前周期', + 'cons.cycleFallbackWeek': '本周', + 'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 02433a7..7159175 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -148,6 +148,7 @@ export const telemetryStore = createReactiveStore({ selectedConversationId: initialConversationId, hostRouteConversationId: extractHostRouteCascadeId(), selectedTimeRange: 'today', + selectedCyclePool: 'all', customStartMs: Date.now() - 24 * 3600 * 1000, customEndMs: Date.now(), syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' @@ -169,7 +170,7 @@ let inFlightTelemetryPoll = null; let inFlightPresetsPrefetch = null; let lastPrefetchedUsageRevision = 0; let consumptionCacheScopeSig = ''; -const MAX_CONSUMPTION_RANGE_CACHE = 12; +const MAX_CONSUMPTION_RANGE_CACHE = 24; const MAX_CONVERSATION_VIEW_CACHE = 12; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const consumptionRangeCache = new Map(); @@ -191,11 +192,19 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ 'enableWindowOverlay', ]); -function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { +function makeConsumptionRangeCacheKey( + range, + customStartMs = 0, + customEndMs = 0, + cyclePool = 'all' +) { const key = String(range || 'all'); if (key === 'custom') { return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; } + if (key === 'cycle' && cyclePool && cyclePool !== 'all') { + return `cycle:${String(cyclePool)}`; + } return key; } @@ -222,6 +231,17 @@ function buildConsumptionScopeSig(payload) { return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; } +function reconcileSelectedCyclePool(payload) { + const curPool = telemetryStore.getState().selectedCyclePool || 'all'; + if (curPool === 'all') return; + const pools = payload?.quotas?.pools; + if (!Array.isArray(pools) || pools.length === 0) return; + const exists = pools.some((p) => String(p?.poolKey || p?.family || '') === curPool); + if (!exists) { + telemetryStore.setState({ selectedCyclePool: 'all' }); + } +} + function syncConsumptionCacheScope(payload) { const nextSig = buildConsumptionScopeSig(payload); if (!nextSig) return; @@ -230,6 +250,7 @@ function syncConsumptionCacheScope(payload) { clearConversationViewCache(); } consumptionCacheScopeSig = nextSig; + reconcileSelectedCyclePool(payload); } function recordConversationViewToCache(payload) { @@ -345,14 +366,19 @@ function putConsumptionRangeCacheEntry(cacheKey, entry) { function recordConsumptionSliceToCache( cons, modelBreakdown, - { customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} + { customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {} ) { const rangeKey = String(cons?.selectedRange?.key || ''); if (!rangeKey) return; + const resolvedPool = + rangeKey === 'cycle' + ? String(cons?.selectedRange?.pool || cyclePool || 'all') + : 'all'; const cacheKey = makeConsumptionRangeCacheKey( rangeKey, rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, - rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0 + rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0, + resolvedPool ); putConsumptionRangeCacheEntry(cacheKey, { revision: Number(cons.revision ?? usageRevision ?? 0), @@ -900,11 +926,14 @@ export function isEquivalentTelemetry(prev, next) { } } - // 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 + // 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费 const pRange = prev.consumption?.selectedRange; const nRange = next.consumption?.selectedRange; if (pRange?.key !== nRange?.key) return false; - if (nRange?.key === 'custom') { + if ((pRange?.pool || 'all') !== (nRange?.pool || 'all')) return false; + if ((pRange?.label || '') !== (nRange?.label || '')) return false; + if (Boolean(pRange?.isFallbackWeek) !== Boolean(nRange?.isFallbackWeek)) return false; + if (nRange?.key === 'custom' || nRange?.key === 'cycle') { if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false; } @@ -1231,6 +1260,13 @@ export async function fetchTelemetry({ force = false } = {}) { const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -1278,6 +1314,7 @@ async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; const reqSettingsRev = settingsRevision; const reqRange = String(params.get('range') || ''); + const reqPool = String(params.get('pool') || 'all'); const reqStartMs = Number(params.get('startMs') || 0); const reqEndMs = Number(params.get('endMs') || 0); const startMs = Date.now(); @@ -1337,14 +1374,17 @@ async function requestTelemetry(params, force) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: reqStartMs, customEndMs: reqEndMs, + cyclePool: reqPool, }); } const latestSt = telemetryStore.getState(); const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); + const activePoolPref = latestSt.selectedCyclePool || 'all'; const matchesCurrentRange = !reqRange || (reqRange === latestSt.selectedTimeRange && + (reqRange !== 'cycle' || reqPool === activePoolPref) && (reqRange !== 'custom' || (reqStartMs === Number(latestSt.customStartMs || 0) && reqEndMs === Number(latestSt.customEndMs || 0)))); @@ -1356,7 +1396,8 @@ async function requestTelemetry(params, force) { const activeKey = makeConsumptionRangeCacheKey( latestSt.selectedTimeRange, latestSt.customStartMs, - latestSt.customEndMs + latestSt.customEndMs, + activePoolPref ); const cachedActive = consumptionRangeCache.get(activeKey); if (cachedActive) { @@ -1365,7 +1406,9 @@ async function requestTelemetry(params, force) { needsSilentRangeRevalidate = true; } } else if ( - latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange + latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange && + (latestSt.selectedTimeRange !== 'cycle' || + (latestSt.telemetry?.consumption?.selectedRange?.pool || 'all') === activePoolPref) ) { resolvedPayload = { ...resolvedPayload, @@ -1417,6 +1460,7 @@ async function requestTelemetry(params, force) { range: latestSt.selectedTimeRange, customStartMs: latestSt.customStartMs, customEndMs: latestSt.customEndMs, + cyclePool: latestSt.selectedCyclePool || 'all', }); } return resolvedPayload; @@ -1442,15 +1486,20 @@ async function fetchConsumptionRangeSlice({ range, customStartMs = 0, customEndMs = 0, + cyclePool = 'all', } = {}) { const reqEpoch = endpointSwitchEpoch; const reqSeq = ++latestConsumptionReqSeq; const targetRange = String(range || 'today'); + const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all'; const current = telemetryStore.getState(); const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('range', targetRange); + if (targetRange === 'cycle' && targetPool !== 'all') { + params.set('pool', targetPool); + } if (targetRange === 'custom') { if (customStartMs > 0) params.set('startMs', String(customStartMs)); if (customEndMs > 0) params.set('endMs', String(customEndMs)); @@ -1469,6 +1518,7 @@ async function fetchConsumptionRangeSlice({ recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { customStartMs, customEndMs, + cyclePool: targetPool, usageRevision: usageRev, }); if (reqSeq !== latestConsumptionReqSeq) return payload; @@ -1476,6 +1526,7 @@ async function fetchConsumptionRangeSlice({ const latestSt = telemetryStore.getState(); const stillMatches = latestSt.selectedTimeRange === targetRange && + (targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) && (targetRange !== 'custom' || (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); @@ -1581,6 +1632,13 @@ export async function selectConversation( const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -1687,7 +1745,7 @@ export async function selectConversation( */ export function selectConsumptionTimeRange( nextRange, - { customStartMs = undefined, customEndMs = undefined } = {} + { customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {} ) { const targetRange = String(nextRange || 'today'); const prevSt = telemetryStore.getState(); @@ -1699,14 +1757,26 @@ export function selectConsumptionTimeRange( targetRange === 'custom' ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) : prevSt.customEndMs; + const nextCyclePool = + targetRange === 'cycle' + ? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all') + : prevSt.selectedCyclePool || 'all'; const statePatch = { selectedTimeRange: targetRange }; + if (cyclePool !== undefined) { + statePatch.selectedCyclePool = nextCyclePool; + } if (targetRange === 'custom') { statePatch.customStartMs = nextStartMs; statePatch.customEndMs = nextEndMs; } - const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs); + const cacheKey = makeConsumptionRangeCacheKey( + targetRange, + nextStartMs, + nextEndMs, + targetRange === 'cycle' ? nextCyclePool : 'all' + ); const cached = consumptionRangeCache.get(cacheKey); const prevTelemetry = prevSt.telemetry; @@ -1725,6 +1795,7 @@ export function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } @@ -1733,9 +1804,14 @@ export function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } +export function selectConsumptionCyclePool(nextPool = 'all') { + return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') }); +} + /** * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 */ diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index ace339a..6cdd8fa 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -570,6 +570,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { @@ -580,6 +581,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover { @@ -587,6 +589,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger { diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 762d784..29c22ae 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -14,6 +14,53 @@ gap: 6px; } +.cons-overview-title { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.cons-cycle-pool-select { + flex: 0 1 auto; + width: auto; + min-width: 0; + max-width: 112px; +} + +.cons-cycle-pool-select .select-trigger { + width: auto; + min-height: calc(20px * var(--ui-font-scale, 1)); + height: auto; + padding: 1px 7px; + gap: 4px; + font-size: var(--fs-sm); + line-height: 1.25; + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger .svg-icon { + width: 11px; + height: 11px; +} + +.cons-cycle-pool-select .select-menu { + right: auto; + min-width: 224px; + width: max-content; + max-width: 280px; +} + .cons-overview-controls { display: inline-flex; align-items: center; diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 50384bb..2cba9e5 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -50,6 +50,7 @@ import { ActionMenu } from '../components/ui/ActionMenu.js'; import { getDefaultCtxInspectorAgentId, prefetchConsumptionPresets, + selectConsumptionCyclePool, selectConsumptionTimeRange, selectConversation, telemetryStore, @@ -61,6 +62,7 @@ import { } from '../components/charts/TrendAreaChart.js'; import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; +import { CustomSelect } from '../components/ui/CustomSelect.js'; import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js'; import { createConsumptionBreakdownContent } from '../components/ui/ConsumptionTooltipContent.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js'; @@ -95,6 +97,86 @@ function ceilToEndOfMinuteMs(ms) { return d.getTime(); } +function formatCyclePoolShortLabel(poolKey, poolLabel) { + if (poolKey === 'Argon') return 'Argon'; + if (poolKey === 'Carbon') return 'Carbon'; + if (poolKey === 'Claude & GPT') return 'Claude/GPT'; + return poolLabel || poolKey; +} + +function buildCyclePoolSelectOptions(pools, isCustomWeeklyMode = false) { + const list = Array.isArray(pools) ? pools : []; + let sumCycleCost = 0; + let hasAnyCycleCost = false; + for (let i = 0; i < list.length; i++) { + const c = Number(list[i]?.cycleWeekly?.costUsd); + if (Number.isFinite(c) && c >= 0 && list[i]?.cycleWeekly) { + sumCycleCost += c; + hasAnyCycleCost = true; + } + } + const allLabel = t('cons.cyclePoolAll'); + const opts = [ + { + value: 'all', + label: allLabel, + shortLabel: t('cons.cyclePoolAllShort'), + meta: !isCustomWeeklyMode && hasAnyCycleCost ? formatUsd(sumCycleCost) : '', + title: allLabel, + }, + ]; + for (let i = 0; i < list.length; i++) { + const p = list[i]; + const key = String(p?.poolKey || p?.family || '').trim(); + if (!key || key === 'Unknown') continue; + const label = String(p?.poolLabel || key).trim(); + const shortLabel = formatCyclePoolShortLabel(key, label); + const metaParts = []; + if ( + !isCustomWeeklyMode && + p?.weeklyRemainingPct != null && + Number.isFinite(Number(p.weeklyRemainingPct)) + ) { + metaParts.push( + t('cons.cyclePoolRemMeta', { + pct: formatPctNumber(p.weeklyRemainingPct, { withSymbol: true }), + }) + ); + } + if (!isCustomWeeklyMode && p?.cycleWeekly && Number.isFinite(Number(p.cycleWeekly.costUsd))) { + metaParts.push(formatUsd(p.cycleWeekly.costUsd)); + } + const meta = metaParts.join(' · '); + opts.push({ + value: key, + label, + shortLabel, + meta, + title: meta ? `${label} (${meta})` : label, + }); + } + return opts; +} + +function formatCycleMinuteSpanTip(startMs, endMs, isFallbackWeek = false) { + const s = Number(startMs); + const e = Number(endMs); + if (!(s > 0 && e > 0 && Number.isFinite(s) && Number.isFinite(e))) return null; + const sd = new Date(s); + const ed = new Date(e); + const pad2 = (n) => String(n).padStart(2, '0'); + const sTime = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; + const eTime = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; + const sameDay = + sd.getFullYear() === ed.getFullYear() && + sd.getMonth() === ed.getMonth() && + sd.getDate() === ed.getDate(); + const sDate = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; + const eDate = `${ed.getMonth() + 1}/${pad2(ed.getDate())}`; + const base = sameDay ? `${sDate} ${sTime} ~ ${eTime}` : `${sDate} ${sTime} ~ ${eDate} ${eTime}`; + return isFallbackWeek ? `${base} · ${t('cons.cycleFallbackWeekTip')}` : base; +} + export const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -200,6 +282,16 @@ export const ConsumptionView = defineComponent({ // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); + const cyclePoolSelect = CustomSelect({ + className: 'cons-cycle-pool-select', + modelValue: telemetryStore.getState().selectedCyclePool || 'all', + options: buildCyclePoolSelectOptions([]), + onUpdateModelValue: (nextPool) => { + selectConsumptionCyclePool(nextPool || 'all'); + }, + }); + patchAttr(cyclePoolSelect.el, 'hidden', true); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) }); const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); @@ -337,8 +429,9 @@ export const ConsumptionView = defineComponent({ const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ - h('span', { className: 'panel-title' }, [ + h('span', { className: 'panel-title cons-overview-title' }, [ dateSpanBadge, + cyclePoolSelect.el, ]), h('div', { className: 'cons-overview-controls' }, [ timeFilterSwitch.el, @@ -1791,7 +1884,7 @@ export const ConsumptionView = defineComponent({ const cons = slice.consumption || {}; const rangeInfo = cons.selectedRange || {}; - // 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 + // 始终在 0ms 同步顶部时间段滑块、周期池选择器及自定义日期条显隐,给予即刻交互反馈 timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); if (!hasUncommittedCustomDraft) { @@ -1801,17 +1894,45 @@ export const ConsumptionView = defineComponent({ endPicker.setValue(draftEndMs); } + const isCustomWeeklyMode = + slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost'; + const cyclePoolOptions = + slice.range === 'cycle' + ? buildCyclePoolSelectOptions(slice.quotaPools, isCustomWeeklyMode) + : []; + const activePoolFilter = slice.range === 'cycle' ? slice.cyclePool || 'all' : 'all'; + const showCyclePoolSelect = slice.range === 'cycle' && cyclePoolOptions.length > 2; + if (!showCyclePoolSelect) { + cyclePoolSelect.close?.(); + patchAttr(cyclePoolSelect.el, 'hidden', true); + } else { + cyclePoolSelect.setProps({ + modelValue: activePoolFilter, + options: cyclePoolOptions, + }); + patchAttr(cyclePoolSelect.el, 'hidden', false); + } + // 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制 - if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) { + const payloadPool = rangeInfo.key === 'cycle' ? rangeInfo.pool || 'all' : 'all'; + if ( + (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) || + (slice.range === 'cycle' && rangeInfo.pool && payloadPool !== activePoolFilter) + ) { return; } const preset = - slice.range !== 'custom' && cons.presets?.[slice.range] + slice.range !== 'custom' && + !(slice.range === 'cycle' && activePoolFilter !== 'all') && + cons.presets?.[slice.range] ? cons.presets[slice.range] : null; const acct = cons.account || preset?.account || {}; const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); + const cycleOptionsSig = showCyclePoolSelect + ? cyclePoolOptions.map((o) => `${o.value}:${o.label}:${o.meta || ''}`).join('|') + : ''; const now = new Date(); const currentMonthIdx = now.getMonth(); const monthlyYear = cons.monthlyYear || now.getFullYear(); @@ -1819,6 +1940,9 @@ export const ConsumptionView = defineComponent({ const renderTuple = [ locale, slice.range, + activePoolFilter, + cycleOptionsSig, + Boolean(rangeInfo.isFallbackWeek), slice.customStartMs, slice.customEndMs, slice.modelDisplayMode, @@ -1839,13 +1963,36 @@ export const ConsumptionView = defineComponent({ cons.monthlySeries, ]; if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; - drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); + drawConsumptionData(slice, { + cons, + preset, + acct, + rangeInfo, + activePoolFilter, + dateSpan, + currentMonthIdx, + monthlyYear, + }); lastRenderedTuple = renderTuple; } - function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { - // 1. 同步用量概览矩阵与顶部 4 段比例条 + function drawConsumptionData( + slice, + { cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear } + ) { + // 1. 同步用量概览矩阵及顶部 4 段比例条 patchText(dateSpanBadge, dateSpan); + patchAttr( + dateSpanBadge, + 'title', + slice.range === 'cycle' + ? formatCycleMinuteSpanTip( + rangeInfo.startMs, + rangeInfo.endMs, + Boolean(rangeInfo.isFallbackWeek) + ) + : null + ); const totalTokens = Number(acct.totalTokens || 0); const inputTokens = Number(acct.inputTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0); @@ -2036,11 +2183,18 @@ export const ConsumptionView = defineComponent({ ...allTrendMergedModels, ]); - // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 - const rangeBadgeText = isEnglishLocale() - ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || - t('cons.allTime') - : preset?.label || rangeInfo.label || t('cons.allTime'); + // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)及悬停分模型浮层 + const rangeBadgeText = + slice.range === 'cycle' + ? `${rangeInfo.isFallbackWeek || slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost' ? t('cons.cycleFallbackWeek') : t('cons.currentCycle')}${ + activePoolFilter && activePoolFilter !== 'all' + ? ` · ${rangeInfo.poolLabel || activePoolFilter}` + : '' + }` + : isEnglishLocale() + ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || + t('cons.allTime') + : preset?.label || rangeInfo.label || t('cons.allTime'); patchText(trendRangeBadge, rangeBadgeText); const firstTrendSlot = rawTrendSeries[0] || null; const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; @@ -2200,7 +2354,7 @@ export const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; const nextRankingKey = showWorkspacesTab ? 'workspaces' : showSessionsTab @@ -2336,8 +2490,11 @@ export const ConsumptionView = defineComponent({ const unsub = telemetryStore.subscribe( (st) => ({ range: st.selectedTimeRange, + cyclePool: st.selectedCyclePool || 'all', customStartMs: st.customStartMs, customEndMs: st.customEndMs, + quotaPools: st.telemetry?.quotas?.pools, + weeklyLimitMode: st.telemetry?.settings?.weeklyLimitMode, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, modelDisplayMode: normalizeModelDisplayMode( @@ -2391,6 +2548,7 @@ export const ConsumptionView = defineComponent({ ariaLabel: t('cons.rangeAria'), options: getConsumptionTimeRangeOptions(), }); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); patchText(applyCustomBtnLabel, t('cons.applyFilter')); patchText(rangeToSpan, t('cons.rangeTo')); patchText(totalTokensLabel, t('cons.totalTokens')); @@ -2448,6 +2606,7 @@ export const ConsumptionView = defineComponent({ unsubView(); unsubI18n(); consExportMenu.destroy(); + cyclePoolSelect.destroy(); trendChart.destroy?.(); rankingTabSwitch.destroy(); modelsSortSwitch.destroy(); @@ -2462,6 +2621,7 @@ export const ConsumptionView = defineComponent({ el: rootEl, refs: { timeFilterSwitch, + cyclePoolSelect, startPicker, endPicker, viewScrollbar, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 4eac4b1..cc3e0d5 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2813,6 +2813,53 @@ html[data-standalone="true"] .app-shell { gap: 6px; } +.cons-overview-title { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.cons-cycle-pool-select { + flex: 0 1 auto; + width: auto; + min-width: 0; + max-width: 112px; +} + +.cons-cycle-pool-select .select-trigger { + width: auto; + min-height: calc(20px * var(--ui-font-scale, 1)); + height: auto; + padding: 1px 7px; + gap: 4px; + font-size: var(--fs-sm); + line-height: 1.25; + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger .svg-icon { + width: 11px; + height: 11px; +} + +.cons-cycle-pool-select .select-menu { + right: auto; + min-width: 224px; + width: max-content; + max-width: 280px; +} + .cons-overview-controls { display: inline-flex; align-items: center; @@ -8458,6 +8505,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { @@ -8468,6 +8516,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover { @@ -8475,6 +8524,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger { diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 0701578..a591a4f 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1866,6 +1866,64 @@ test('ConsumptionView and TrendAreaChart patch text DOM nodes in-place without o assert.equal(secondGridCells.length, firstGridCells.length); assert.equal(secondGridCells[10], firstGridCells[10], 'Heatmap cell DOM node reused in-place'); + // Switch to 'cycle' with multiple quota pools -> compact inline pool selector becomes visible (and stays hidden on 'today'/'all') + assert.equal(view.refs.cyclePoolSelect.el.hasAttribute('hidden'), true, 'Hidden outside cycle range'); + const cyclePoolsFixture = [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + weeklyRemainingPct: 99.7, + cycleWeekly: { calls: 12, tokens: 2_480_000, costUsd: 0.86 }, + }, + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + weeklyRemainingPct: 38.0, + cycleWeekly: { calls: 690, tokens: 172_580_000, costUsd: 61.38 }, + }, + ]; + const baseCyclePayload = makeRangePayload('cycle', 2_480_000, ['12:00', '14:00', '16:00', '18:00']); + baseCyclePayload.quotas = { pools: cyclePoolsFixture }; + baseCyclePayload.consumption.selectedRange = { + key: 'cycle', + pool: 'Gemini', + poolLabel: 'Gemini', + label: '当前周期 · Gemini', + startMs: 1_760_040_000_000, + endMs: 1_760_061_600_000, + }; + telemetryStore.setState( + { + selectedTimeRange: 'cycle', + selectedCyclePool: 'Gemini', + telemetry: baseCyclePayload, + }, + { sync: true } + ); + assert.equal(view.refs.cyclePoolSelect.el.hasAttribute('hidden'), false, 'Shown on cycle with >=2 pools'); + assert.equal(view.refs.cyclePoolSelect.refs.triggerLabel.textContent, 'Gemini'); + const badges = view.el.querySelectorAll('.cons-badge'); + assert.match(badges[1]?.textContent || '', /当前周期 · Gemini/); + + // Open dropdown and verify localized pool metadata + switch back to 'today' hides dropdown + view.refs.cyclePoolSelect.open(); + const optTexts = [...view.refs.cyclePoolSelect.refs.optionsListEl.children].map( + (btn) => btn.textContent + ); + assert.equal(optTexts.length, 3); + assert.match(optTexts[0], /全部池.*\$62\.24/); + assert.match(optTexts[1], /Gemini.*剩 99\.7% · \$0\.86/); + assert.match(optTexts[2], /Claude & GPT.*剩 38\.0% · \$61\.38/); + + telemetryStore.setState( + { + selectedTimeRange: 'today', + telemetry: makeRangePayload('today', 100_000, ['00:00', '06:00', '12:00', '18:00']), + }, + { sync: true } + ); + assert.equal(view.refs.cyclePoolSelect.el.hasAttribute('hidden'), true, 'Re-hidden on today'); + view.destroy(); telemetryStore.setState(prevTelState, { sync: true }); uiStore.setState(prevUiState, { sync: true }); diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index 4ae9a9d..63b5bc2 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -824,7 +824,8 @@ test('argon_weekly capsule & CLI slot enables only when user has an Argon weekly }); test('formatPctNumber collapses boundary 0.0 -> 0 and 100.0 -> 100 while preserving intermediate decimals', async () => { - const { formatPctNumber } = await import('../src/core/formatters.js'); + const { formatDateSpanBadge, formatPctNumber } = await import('../src/core/formatters.js'); + const { setI18nLanguage } = await import('../src/i18n/index.js'); assert.equal(formatPctNumber(0), '0'); assert.equal(formatPctNumber(0, { withSymbol: true }), '0%'); assert.equal(formatPctNumber(0.04, { withSymbol: true }), '0%'); @@ -836,4 +837,272 @@ test('formatPctNumber collapses boundary 0.0 -> 0 and 100.0 -> 100 while preserv assert.equal(formatPctNumber(1.0, { withSymbol: true }), '1.0%'); assert.equal(formatPctNumber(50.0, { withSymbol: true }), '50.0%'); assert.equal(formatPctNumber(99.9, { withSymbol: true }), '99.9%'); + + const d24Morning = new Date(2026, 10, 24, 9, 0).getTime(); + const d24Evening = new Date(2026, 10, 24, 19, 30).getTime(); + const d25Evening = new Date(2026, 10, 25, 18, 0).getTime(); + const dOct28 = new Date(2026, 9, 28, 10, 0).getTime(); + const dPrevYear = new Date(2025, 11, 28, 10, 0).getTime(); + + setI18nLanguage('zh-CN'); + assert.equal(formatDateSpanBadge(d24Morning, d24Evening), '11月24日'); + assert.equal(formatDateSpanBadge(d24Morning, d25Evening), '11月24日 ~ 25日'); + assert.equal(formatDateSpanBadge(dOct28, d24Evening), '10月28日 ~ 11月24日'); + assert.equal(formatDateSpanBadge(dPrevYear, d24Evening), '2025年12月28日 ~ 2026年11月24日'); + + setI18nLanguage('en-US'); + assert.equal(formatDateSpanBadge(d24Morning, d24Evening), 'Nov 24'); + assert.equal(formatDateSpanBadge(d24Morning, d25Evening), 'Nov 24 ~ 25'); + assert.equal(formatDateSpanBadge(dOct28, d24Evening), 'Oct 28 ~ Nov 24'); + assert.equal(formatDateSpanBadge(dPrevYear, d24Evening), 'Dec 28, 2025 ~ Nov 24, 2026'); + setI18nLanguage('zh-CN'); +}); + +test('Consumption cycle pool filter isolates Gemini vs Claude & GPT vs Argon across full, consumption, and presets scopes', async () => { + const now = Date.now(); + const CLAUDE_SONNET = 'MODEL_CLAUDE_4_5_SONNET'; + // Gemini weekly cycle refreshed 6h ago (resets in +162h) + const geminiWkReset = new Date(now + 162 * 3600_000).toISOString(); + const gemini5hReset = new Date(now + 2 * 3600_000).toISOString(); + // Argon weekly cycle started 4d ago (resets in +72h) + const argonWkReset = new Date(now + 72 * 3600_000).toISOString(); + // Claude & GPT weekly cycle started 30h ago (resets in +138h) + const claudeWkReset = new Date(now + 138 * 3600_000).toISOString(); + + const makeTimedStep = (idx, model, ageMs, provider, tok) => { + const t = now - ageMs; + return { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx }, + createdAt: new Date(t).toISOString(), + completedAt: new Date(t + 2_000).toISOString(), + modelUsage: { + model, + apiProvider: provider, + inputTokens: String(tok), + cacheReadTokens: '0', + outputTokens: '1000', + }, + }, + }; + }; + + const h = backendHarness({ + summaries: { convPoolSplit: { stepCount: 4 } }, + trajectories: { + convPoolSplit: { + trajectory: { + steps: [ + // 1. Gemini 2h ago -> inside Gemini 6h weekly window (11,000 tok) + makeTimedStep(1, FLASH, 2 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 10_000), + // 2. Gemini 24h ago -> OUTSIDE Gemini 6h weekly window! + makeTimedStep(2, FLASH, 24 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 90_000), + // 3. Claude 24h ago -> INSIDE Claude 30h weekly window (51,000 tok) + makeTimedStep(3, CLAUDE_SONNET, 24 * 3600_000, 'API_PROVIDER_ANTHROPIC', 50_000), + // 4. Argon 48h ago -> INSIDE Argon 4d weekly window (31,000 tok) + makeTimedStep(4, ARGON, 48 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 30_000), + ], + }, + }, + }, + userStatus: { + userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' }, + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 3.8 Flash (High)', + modelId: 'gemini-3.8-flash-high', + modelOrAlias: { model: FLASH }, + quotaInfo: { remainingFraction: 0.9968, resetTime: gemini5hReset }, + }, + { + label: 'Gemini 4 Argon (High)', + modelId: 'gemini-4-argon-high', + modelOrAlias: { model: ARGON }, + quotaInfo: { remainingFraction: 0.62, resetTime: argonWkReset }, + }, + { + label: 'Claude 4.5 Sonnet', + modelId: 'claude-sonnet-4-5', + modelOrAlias: { model: CLAUDE_SONNET }, + quotaInfo: { remainingFraction: 0.38, resetTime: claudeWkReset }, + }, + ], + }, + }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.99, resetTime: gemini5hReset }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.9968, resetTime: geminiWkReset }, + ], + }, + { + displayName: 'Gemini 4 Argon', + buckets: [ + { bucketId: 'argon-weekly', window: 'weekly', remainingFraction: 0.62, resetTime: argonWkReset }, + ], + }, + { + displayName: 'Claude and GPT models', + buckets: [ + { bucketId: '3p-weekly', window: 'weekly', remainingFraction: 0.38, resetTime: claudeWkReset }, + ], + }, + ], + }, + }); + + // 1. All-pools cycle: includes step 1 (11k) + step 3 (51k) + step 4 (31k) = 93k + const allCycle = await h.buildTelemetryPayloadInternal('convPoolSplit', false, { range: 'cycle' }); + assert.equal(allCycle.consumption.selectedRange.key, 'cycle'); + assert.equal(allCycle.consumption.selectedRange.pool, 'all'); + assert.equal(allCycle.consumption.account.calls, 3); + assert.equal(allCycle.consumption.account.totalTokens, 93_000); + + // 2. Gemini-only cycle: strictly isolates Gemini post-reset window (11k, start anchored ~6h ago, NOT 30h/48h ago!) + const gemCycle = JSON.parse( + (await h.executeTelemetryAction({ conversationId: 'convPoolSplit', range: 'cycle', pool: 'Gemini', scope: 'consumption' })).body + ); + assert.equal(gemCycle.scope, 'consumption'); + assert.equal(gemCycle.consumption.selectedRange.pool, 'Gemini'); + assert.equal(gemCycle.consumption.selectedRange.poolLabel, 'Gemini'); + assert.equal(gemCycle.consumption.account.calls, 1); + assert.equal(gemCycle.consumption.account.totalTokens, 11_000); + assert.equal(gemCycle.modelBreakdown.length, 1); + assert.match(gemCycle.modelBreakdown[0].label, /Gemini/); + assert.ok( + gemCycle.consumption.selectedRange.startMs >= now - 7 * 3600_000, + 'Gemini cycle startMs must anchor to Gemini 6h-ago reset rather than Claude/Argon earlier cycles' + ); + + // 3. Claude & GPT cycle: strictly isolates Claude 30h window (51k) while global presets.cycle stays 93k on full payload + const claudeFull = await h.buildTelemetryPayloadInternal('convPoolSplit', false, { + range: 'cycle', + pool: 'Claude & GPT', + }); + assert.equal(claudeFull.consumption.selectedRange.pool, 'Claude & GPT'); + assert.equal(claudeFull.consumption.account.calls, 1); + assert.equal(claudeFull.consumption.account.totalTokens, 51_000); + assert.equal(claudeFull.consumption.presets.cycle.account.totalTokens, 93_000); + assert.equal(claudeFull.quotas.weekly.tokens, 93_000); + + // 4. Presets bundle pre-computes cycle: slices for 0ms frontend switching + const presetsBundle = JSON.parse( + (await h.executeTelemetryAction({ conversationId: 'convPoolSplit', scope: 'consumption-presets' })).body + ); + assert.equal(presetsBundle.scope, 'consumption-presets'); + assert.equal(presetsBundle.ranges.cycle.account.totalTokens, 93_000); + assert.equal(presetsBundle.ranges['cycle:Gemini'].account.totalTokens, 11_000); + assert.equal(presetsBundle.ranges['cycle:Argon'].account.totalTokens, 31_000); + assert.equal(presetsBundle.ranges['cycle:Claude & GPT'].account.totalTokens, 51_000); +}); + +test('GetUserStatus >6h weekly resetTime fallback and usageRevision bump when official weekly anchor arrives', async () => { + const now = Date.now(); + const wkResetIso = new Date(now + 161 * 3600_000).toISOString(); // refreshed 7h ago + const recentStepTs = now - 2 * 3600_000; + const preResetStepTs = now - 20 * 3600_000; + + const makeStepAt = (idx, ts, tok) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx }, + createdAt: new Date(ts).toISOString(), + completedAt: new Date(ts + 2_000).toISOString(), + modelUsage: { + model: FLASH, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: String(tok), + cacheReadTokens: '0', + outputTokens: '500', + }, + }, + }); + + // Case A: RetrieveUserQuotaSummary failed (null), only GetUserStatus returned >6h weekly resetTime + const hFallback = backendHarness({ + summaries: { convFb: { stepCount: 2 } }, + trajectories: { + convFb: { + trajectory: { + steps: [ + makeStepAt(1, preResetStepTs, 80_000), + makeStepAt(2, recentStepTs, 10_000), + ], + }, + }, + }, + userStatus: { + email: 'cli-user@example.com', + userTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' }, + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 3.8 Flash (High)', + modelId: 'gemini-3.8-flash-high', + modelOrAlias: { model: FLASH }, + quotaInfo: { remainingFraction: 0.9968, resetTime: wkResetIso }, + }, + ], + }, + }, + quotaSummary: null, + }); + + const pFb = await hFallback.buildTelemetryPayloadInternal('convFb', false, { range: 'cycle' }); + const gemPoolFb = pFb.quotas.pools.find((p) => p.poolKey === 'Gemini'); + assert.equal(gemPoolFb.weeklyResetTime, wkResetIso, '>6h quotaInfo resetTime must classify as weeklyResetTime'); + assert.equal(gemPoolFb.has5h, false); + assert.equal(pFb.consumption.selectedRange.isFallbackWeek, undefined); + assert.equal(pFb.consumption.account.calls, 1, 'Excludes 20h-ago pre-reset step'); + assert.equal(pFb.consumption.account.totalTokens, 10_500); + + // Case B: Cold start without official weekly anchor -> later official quotaSummary arrives -> usageRevision advances + const hRev = backendHarness({ + summaries: { convRev: { stepCount: 2 } }, + trajectories: { + convRev: { + trajectory: { + steps: [ + makeStepAt(1, preResetStepTs, 80_000), + makeStepAt(2, recentStepTs, 10_000), + ], + }, + }, + }, + userStatus: { + email: 'rev-user@example.com', + userTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' }, + cascadeModelConfigData: { clientModelConfigs: [] }, + }, + quotaSummary: null, + }); + + const coldPayload = await hRev.buildTelemetryPayloadInternal('convRev', false, { range: 'cycle' }); + assert.equal(coldPayload.consumption.selectedRange.isFallbackWeek, true); + const revBefore = coldPayload.consumption.revision; + + hRev.state.quotaSummary = { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.9968, resetTime: wkResetIso }, + ], + }, + ], + }; + const warmPayload = await hRev.buildTelemetryPayloadInternal('convRev', true, { range: 'cycle' }); + assert.equal(warmPayload.consumption.selectedRange.isFallbackWeek, undefined); + assert.equal(warmPayload.consumption.account.calls, 1); + assert.ok( + warmPayload.consumption.revision > revBefore, + 'usageRevision must increment when official weekly reset anchor arrives and alters cycle window' + ); }); From b9dc2b960c637375b141024ffaee075fd0b4fbc3 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 20:14:32 +0900 Subject: [PATCH 19/30] feat(panel): add 4-mode LED matrix switcher to usage heatmap - Replace the static daily hint on >90d usage heatmaps with a Day / Week / Month / Total segmented switcher while keeping the 7xW grid geometry fixed in-place - Render bottom-up proportional LED bars for weekly, monthly, and cumulative views with aggregated per-model breakdown tooltips and click-to-drill-down --- sidecars/panel/app.js | 896 +++++++++++++++--- sidecars/panel/index.html | 4 +- .../src/components/charts/TrendAreaChart.js | 799 +++++++++++++--- sidecars/panel/src/i18n/en-US.js | 12 +- sidecars/panel/src/i18n/zh-CN.js | 12 +- .../panel/src/styles/views-consumption.css | 39 + sidecars/panel/src/views/ConsumptionView.js | 76 +- sidecars/panel/styles.css | 39 + sidecars/panel/test/consumption-bars.test.mjs | 232 +++++ 9 files changed, 1856 insertions(+), 253 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 8782357..5db436b 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1530,7 +1530,11 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.replyAndThink': '思考 {think} · 回复 {resp}', 'cons.trendTitle': '用量趋势', 'cons.allTime': '全部时间', - 'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看', + 'cons.hmModeAria': '热力图查看维度', + 'cons.hmModeDay': '日', + 'cons.hmModeWeek': '周', + 'cons.hmModeMonth': '月', + 'cons.hmModeAll': '全部', 'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看', 'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看', 'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看', @@ -2141,6 +2145,12 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'chart.trend.hmMore': '多', 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', 'chart.trend.hmActiveZero': '活跃 0/{total} 天', + 'chart.trend.hmWeekPeak': '活跃 {active}/{total} 周 · 峰值 {label} · {tokens}', + 'chart.trend.hmWeekZero': '活跃 0/{total} 周', + 'chart.trend.hmMonthPeak': '活跃 {active}/{total} 月 · 峰值 {label} · {tokens}', + 'chart.trend.hmMonthZero': '活跃 0/{total} 月', + 'chart.trend.hmCumSummary': '累计 {days} 天 · 总计 {tokens} · {cost}', + 'chart.trend.hmCumThrough': '截至 {date} 累计', 'chart.trend.peakPill': '峰值 {label} · {tokens}', // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) @@ -2436,7 +2446,11 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.replyAndThink': 'Think {think} · Reply {resp}', 'cons.trendTitle': 'Usage Trend', 'cons.allTime': 'All Time', - 'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details', + 'cons.hmModeAria': 'Heatmap view mode', + 'cons.hmModeDay': 'Day', + 'cons.hmModeWeek': 'Week', + 'cons.hmModeMonth': 'Month', + 'cons.hmModeAll': 'Total', 'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details', 'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details', 'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details', @@ -3047,6 +3061,12 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'chart.trend.hmMore': 'More', 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', 'chart.trend.hmActiveZero': 'Active 0/{total}d', + 'chart.trend.hmWeekPeak': 'Active {active}/{total}w · Peak {label} · {tokens}', + 'chart.trend.hmWeekZero': 'Active 0/{total}w', + 'chart.trend.hmMonthPeak': 'Active {active}/{total}m · Peak {label} · {tokens}', + 'chart.trend.hmMonthZero': 'Active 0/{total}m', + 'chart.trend.hmCumSummary': 'Cumulative {days}d · Total {tokens} · {cost}', + 'chart.trend.hmCumThrough': 'Cumulative through {date}', 'chart.trend.peakPill': 'Peak {label} · {tokens}', // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) @@ -14165,6 +14185,332 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { return ticks; } +const EN_SHORT_MONTHS = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', +]; + +function normalizeHeatmapMode(mode) { + return mode === 'week' || mode === 'month' || mode === 'all' ? mode : 'day'; +} + +function createHeatmapAggAcc(extra = {}) { + return { + tokens: 0, + inputTokens: 0, + cacheReadTokens: 0, + thinkingTokens: 0, + responseTokens: 0, + outputTokens: 0, + costUsd: 0, + calls: 0, + minStartMs: Infinity, + maxEndMs: 0, + firstLabel: '', + lastLabel: '', + modelMap: new Map(), + ...extra, + }; +} + +function mergeSlotIntoHeatmapAcc(acc, slot) { + if (!slot) return; + const tok = safeSlotTokens(slot.tokens); + const inTok = safeSlotTokens(slot.inputTokens); + const cacheTok = safeSlotTokens(slot.cacheReadTokens); + const thinkTok = safeSlotTokens(slot.thinkingTokens); + const respTok = safeSlotTokens(slot.responseTokens); + const outTok = + slot.outputTokens !== undefined && slot.outputTokens !== null + ? safeSlotTokens(slot.outputTokens) + : thinkTok + respTok; + acc.tokens += tok; + acc.inputTokens += inTok; + acc.cacheReadTokens += cacheTok; + acc.thinkingTokens += thinkTok; + acc.responseTokens += respTok; + acc.outputTokens += outTok; + acc.costUsd += Math.max(0, Number(slot.costUsd || 0)); + acc.calls += Math.max(0, Number(slot.calls || 0)); + + const sMs = Number(slot.startMs); + const eMs = Number(slot.endMs); + if (Number.isFinite(sMs) && sMs > 0 && sMs < acc.minStartMs) { + acc.minStartMs = sMs; + } + if (Number.isFinite(eMs) && eMs > acc.maxEndMs) { + acc.maxEndMs = eMs; + } else if (Number.isFinite(sMs) && sMs > 0 && sMs + 86_400_000 > acc.maxEndMs) { + acc.maxEndMs = sMs + 86_400_000; + } + const lbl = String(slot.label || ''); + if (!acc.firstLabel && lbl) acc.firstLabel = lbl; + if (lbl) acc.lastLabel = lbl; + + const srcModels = Array.isArray(slot.mergedModels) + ? slot.mergedModels + : Array.isArray(slot.models) + ? slot.models + : null; + if (srcModels) { + for (let i = 0; i < srcModels.length; i++) { + const m = srcModels[i]; + if (!m) continue; + const key = String(m.displayText || m.label || m.shortName || ''); + if (!key) continue; + let cur = acc.modelMap.get(key); + if (!cur) { + cur = { + ...m, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + thinkingTokens: 0, + responseTokens: 0, + outputTokens: 0, + totalTokens: 0, + costUsd: 0, + }; + acc.modelMap.set(key, cur); + } + cur.calls += Math.max(0, Number(m.calls || 0)); + cur.inputTokens += safeSlotTokens(m.inputTokens); + cur.cacheReadTokens += safeSlotTokens(m.cacheReadTokens); + cur.thinkingTokens += safeSlotTokens(m.thinkingTokens); + cur.responseTokens += safeSlotTokens(m.responseTokens); + cur.outputTokens += safeSlotTokens(m.outputTokens); + cur.totalTokens += safeSlotTokens(m.totalTokens); + cur.costUsd += Math.max(0, Number(m.costUsd || 0)); + } + } +} + +function finalizeHeatmapBucket(acc, customTitle, shortLabel, buildSegmentsFn) { + const hasStart = Number.isFinite(acc.minStartMs) && acc.minStartMs < Infinity && acc.minStartMs > 0; + const startMs = hasStart ? acc.minStartMs : 0; + const endMs = + hasStart && acc.maxEndMs > startMs + ? Math.max(startMs + 60_000, acc.maxEndMs - 1) + : 0; + let modelSegments = []; + if (typeof buildSegmentsFn === 'function' && acc.modelMap.size > 0) { + const mergedList = Array.from(acc.modelMap.values(), (m) => ({ ...m })).sort( + (a, b) => (b.totalTokens || 0) - (a.totalTokens || 0) || (b.calls || 0) - (a.calls || 0) + ); + modelSegments = buildSegmentsFn(mergedList) || []; + } + return { + startMs, + endMs, + label: shortLabel || customTitle, + fullLabel: customTitle, + customTitle, + tokens: acc.tokens, + inputTokens: acc.inputTokens, + cacheReadTokens: acc.cacheReadTokens, + thinkingTokens: acc.thinkingTokens, + responseTokens: acc.responseTokens, + outputTokens: acc.outputTokens, + costUsd: +acc.costUsd.toFixed(4), + calls: acc.calls, + modelSegments, + }; +} + +function buildHeatmapBarView(slots, firstDow, totalWeeks, mode, buildSegmentsFn) { + if (mode === 'week') { + const weekAccs = Array.from({ length: totalWeeks }, () => createHeatmapAggAcc()); + for (let i = 0; i < slots.length; i++) { + const col = Math.floor((firstDow + i) / 7); + if (col >= 0 && col < totalWeeks) { + mergeSlotIntoHeatmapAcc(weekAccs[col], slots[i]); + } + } + let maxTok = 0; + let peakIdx = 0; + let activeWeeks = 0; + const nonZero = []; + const buckets = weekAccs.map((acc, idx) => { + if (acc.tokens > 0) { + activeWeeks++; + nonZero.push(acc.tokens); + } + if (acc.tokens >= maxTok) { + maxTok = acc.tokens; + peakIdx = idx; + } + const hasValidRange = Number.isFinite(acc.minStartMs) && acc.minStartMs < Infinity && acc.minStartMs > 0; + const spanTitle = hasValidRange + ? formatDateSpanBadge(acc.minStartMs, Math.max(acc.minStartMs, acc.maxEndMs - 1)) + : acc.firstLabel && acc.lastLabel && acc.firstLabel !== acc.lastLabel + ? `${acc.firstLabel} ~ ${acc.lastLabel}` + : acc.firstLabel || '--'; + const shortLbl = + acc.firstLabel && acc.lastLabel && acc.firstLabel !== acc.lastLabel + ? `${acc.firstLabel}~${acc.lastLabel.split('/').pop()}` + : acc.firstLabel || spanTitle; + return finalizeHeatmapBucket(acc, spanTitle, shortLbl, buildSegmentsFn); + }); + nonZero.sort((a, b) => a - b); + const thresholds = computeHeatmapThresholds(nonZero, maxTok); + const colSpecs = buckets.map((b, col) => { + const litRows = + b.tokens > 0 && maxTok > 0 ? Math.max(1, Math.min(7, Math.ceil((b.tokens / maxTok) * 7))) : 0; + return { + bucketIdx: col, + litRows, + lv: litRows > 0 ? resolveHeatmapLevel(b.tokens, thresholds) : 0, + isMonthEdge: false, + }; + }); + const peakB = buckets[peakIdx]; + const summaryText = + maxTok > 0 && peakB + ? t('chart.trend.hmWeekPeak', { + active: activeWeeks, + total: totalWeeks, + label: peakB.label, + tokens: formatTokensPrecise(maxTok), + }) + : t('chart.trend.hmWeekZero', { total: totalWeeks }); + return { buckets, colSpecs, summaryText }; + } + + if (mode === 'month') { + const monthIndexByKey = new Map(); + const monthAccs = []; + const colMonthCounts = Array.from({ length: totalWeeks }, () => new Map()); + + for (let i = 0; i < slots.length; i++) { + const slot = slots[i]; + const parts = parseSlotCalendarParts(slot); + const mKey = `${parts.year}-${parts.month}`; + let mIdx = monthIndexByKey.get(mKey); + if (mIdx === undefined) { + mIdx = monthAccs.length; + monthIndexByKey.set(mKey, mIdx); + monthAccs.push(createHeatmapAggAcc({ year: parts.year, month: parts.month })); + } + mergeSlotIntoHeatmapAcc(monthAccs[mIdx], slot); + const col = Math.floor((firstDow + i) / 7); + if (col >= 0 && col < totalWeeks) { + colMonthCounts[col].set(mIdx, (colMonthCounts[col].get(mIdx) || 0) + 1); + } + } + + const colMonthIdx = new Array(totalWeeks).fill(0); + for (let col = 0; col < totalWeeks; col++) { + let bestM = col > 0 ? colMonthIdx[col - 1] : 0; + let bestCnt = -1; + for (const [mIdx, cnt] of colMonthCounts[col].entries()) { + if (cnt >= bestCnt) { + bestCnt = cnt; + bestM = mIdx; + } + } + colMonthIdx[col] = bestM; + } + if (monthAccs.length > 0 && totalWeeks >= monthAccs.length) { + colMonthIdx[0] = 0; + colMonthIdx[totalWeeks - 1] = monthAccs.length - 1; + } + + let maxTok = 0; + let peakIdx = 0; + let activeMonths = 0; + const nonZero = []; + const en = isEnglishLocale(); + const buckets = monthAccs.map((acc, idx) => { + if (acc.tokens > 0) { + activeMonths++; + nonZero.push(acc.tokens); + } + if (acc.tokens >= maxTok) { + maxTok = acc.tokens; + peakIdx = idx; + } + const mNum = acc.month || 1; + const enShort = EN_SHORT_MONTHS[mNum - 1] || `M${mNum}`; + const fullTitle = en ? `${enShort} ${acc.year}` : t('cons.monthFullLabel', { year: acc.year, m: mNum }); + const shortLbl = en ? enShort : t('cons.monthLabel', { m: mNum }); + return finalizeHeatmapBucket(acc, fullTitle, shortLbl, buildSegmentsFn); + }); + nonZero.sort((a, b) => a - b); + const thresholds = computeHeatmapThresholds(nonZero, maxTok); + const colSpecs = colMonthIdx.map((mIdx, col) => { + const b = buckets[mIdx] || { tokens: 0 }; + const litRows = + b.tokens > 0 && maxTok > 0 ? Math.max(1, Math.min(7, Math.ceil((b.tokens / maxTok) * 7))) : 0; + return { + bucketIdx: mIdx, + litRows, + lv: litRows > 0 ? resolveHeatmapLevel(b.tokens, thresholds) : 0, + isMonthEdge: col > 0 && mIdx !== colMonthIdx[col - 1], + }; + }); + const peakB = buckets[peakIdx]; + const summaryText = + maxTok > 0 && peakB + ? t('chart.trend.hmMonthPeak', { + active: activeMonths, + total: buckets.length, + label: peakB.label, + tokens: formatTokensPrecise(maxTok), + }) + : t('chart.trend.hmMonthZero', { total: Math.max(1, buckets.length) }); + return { buckets, colSpecs, summaryText }; + } + + // mode === 'all' (累计总量爬升柱阵) + const runAcc = createHeatmapAggAcc(); + const buckets = new Array(totalWeeks); + for (let col = 0; col < totalWeeks; col++) { + for (let row = 0; row < 7; row++) { + const sIdx = col * 7 + row - firstDow; + if (sIdx >= 0 && sIdx < slots.length) { + mergeSlotIntoHeatmapAcc(runAcc, slots[sIdx]); + } + } + const hasEnd = Number.isFinite(runAcc.minStartMs) && runAcc.minStartMs < Infinity && runAcc.maxEndMs > 0; + const endDayMs = hasEnd ? Math.max(runAcc.minStartMs, runAcc.maxEndMs - 1) : 0; + const endDateStr = endDayMs > 0 ? formatDateSpanBadge(endDayMs, endDayMs) : runAcc.lastLabel || '--'; + const cumTitle = t('chart.trend.hmCumThrough', { date: endDateStr }); + buckets[col] = finalizeHeatmapBucket(runAcc, cumTitle, endDateStr, buildSegmentsFn); + } + const grandTotal = buckets[totalWeeks - 1]?.tokens || 0; + const grandCost = buckets[totalWeeks - 1]?.costUsd || 0; + const colSpecs = buckets.map((b, col) => { + const litRows = + b.tokens > 0 && grandTotal > 0 + ? Math.max(1, Math.min(7, Math.ceil((b.tokens / grandTotal) * 7))) + : 0; + const ratio = grandTotal > 0 ? b.tokens / grandTotal : 0; + const lv = litRows === 0 ? 0 : ratio > 0.75 ? 4 : ratio > 0.5 ? 3 : ratio > 0.25 ? 2 : 1; + return { + bucketIdx: col, + litRows, + lv, + isMonthEdge: false, + }; + }); + const summaryText = t('chart.trend.hmCumSummary', { + days: slots.length, + tokens: formatTokensPrecise(grandTotal), + cost: formatUsd(grandCost), + }); + return { buckets, colSpecs, summaryText }; +} + /** * 创建交互式历史趋势组件(<=90 天为 SVG 平滑曲线图,>90 天自动切换为类 GitHub 每日小格子热力图)。 * @@ -14342,10 +14688,18 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let currentSlots = []; let currentPts = []; let currentIsHeatmap = false; + let currentHmMode = 'day'; + let lastBuildSegmentsFn = null; let currentHeatmapWeeks = 0; let currentHeatmapFirstDow = 0; let currentHeatmapGapPx = 2; let currentCellEls = []; + let currentHmBuckets = []; + let currentHmBucketCells = []; + let currentHmAnchorCells = []; + let currentColBucketIdx = []; + let hoveredHighlightEls = []; + let lastHeatmapSummaryText = ''; let tickElsByIdx = new Map(); let hoveredIdx = -1; let hoveredCellEl = null; @@ -14511,7 +14865,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const slotTok = safeSlotTokens(slot.tokens); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; tooltipContent.update({ - title: formatTrendSlotFullLabel(slot) || slot.label || '--', + title: slot.customTitle || formatTrendSlotFullLabel(slot) || slot.label || '--', calls: slot.calls, totalTokens: slotTok, costText: formatUsd(slotCost, { @@ -14652,11 +15006,14 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) { - if (!currentIsHeatmap || idx < 0 || idx >= currentSlots.length) { + if (!currentIsHeatmap || idx < 0 || idx >= currentHmBuckets.length) { clearHover(); return; } - const targetCell = cellEl || currentCellEls[idx] || null; + const isBarMode = currentHmMode !== 'day'; + const targetCell = isBarMode + ? currentHmAnchorCells[idx] || cellEl || null + : cellEl || currentHmAnchorCells[idx] || currentCellEls[idx] || null; if (!targetCell) { clearHover(); return; @@ -14667,13 +15024,29 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { if (pointer) { lastPointer = pointer; } - if (hoveredCellEl && hoveredCellEl !== targetCell) { - patchClasses(hoveredCellEl, { 'is-hovered': false }); - } - hoveredCellEl = targetCell; - patchClasses(targetCell, { 'is-hovered': true }); - const slot = currentSlots[idx]; + if (changedCell || hoveredHighlightEls.length === 0) { + for (let i = 0; i < hoveredHighlightEls.length; i++) { + patchClasses(hoveredHighlightEls[i], { + 'is-hovered': false, + 'is-bar-hovered': false, + }); + } + const nextHighlight = + currentHmBucketCells[idx] && currentHmBucketCells[idx].length > 0 + ? currentHmBucketCells[idx] + : [targetCell]; + for (let i = 0; i < nextHighlight.length; i++) { + patchClasses(nextHighlight[i], { + 'is-hovered': !isBarMode, + 'is-bar-hovered': isBarMode, + }); + } + hoveredHighlightEls = nextHighlight; + hoveredCellEl = targetCell; + } + + const slot = currentHmBuckets[idx]; const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); @@ -14696,18 +15069,32 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let fallbackX = currentHeatmapWeeks > 0 ? ((col + 0.5) / currentHeatmapWeeks) * wrapW : wrapW / 2; let fallbackY = 20 + row * 14; - if ( + const hasValidCellRect = Boolean( wrapRect && - wrapRect.width > 0 && - cellRect && - cellRect.width > 0 && - cellRect.width < wrapRect.width - ) { + wrapRect.width > 0 && + cellRect && + cellRect.width > 0 && + cellRect.width < wrapRect.width + ); + if (hasValidCellRect) { fallbackX = cellRect.left + cellRect.width / 2 - wrapRect.left; fallbackY = cellRect.top + cellRect.height / 2 - wrapRect.top; } - positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer); + const rawPtr = pointer || lastPointer; + const effectivePtr = + isBarMode && + rawPtr && + hasValidCellRect && + Number.isFinite(Number(rawPtr.clientX)) && + Number.isFinite(Number(rawPtr.clientY)) + ? { + clientX: Number(rawPtr.clientX), + clientY: Math.min(Number(rawPtr.clientY), cellRect.top + 2), + } + : rawPtr; + + positionTooltipNearAnchor(fallbackX, fallbackY, effectivePtr); armTooltipTracking(wasHidden); } @@ -14729,8 +15116,17 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } + if (hoveredHighlightEls.length > 0) { + for (let i = 0; i < hoveredHighlightEls.length; i++) { + patchClasses(hoveredHighlightEls[i], { + 'is-hovered': false, + 'is-bar-hovered': false, + }); + } + hoveredHighlightEls = []; + } if (hoveredCellEl) { - patchClasses(hoveredCellEl, { 'is-hovered': false }); + patchClasses(hoveredCellEl, { 'is-hovered': false, 'is-bar-hovered': false }); hoveredCellEl = null; } for (const el of tickElsByIdx.values()) { @@ -14787,8 +15183,10 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const idxAttr = cur.getAttribute?.('data-slot-idx'); if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') { const idx = Number(idxAttr); - if (Number.isFinite(idx) && idx >= 0 && idx < currentSlots.length) { - return { idx, cellEl: cur }; + if (Number.isFinite(idx) && idx >= 0 && idx < currentHmBuckets.length) { + const cellEl = + currentHmMode !== 'day' ? currentHmAnchorCells[idx] || cur : cur; + return { idx, cellEl }; } } cur = cur.parentNode || null; @@ -14803,8 +15201,12 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const clientX = Number(e?.clientX); const clientY = Number(e?.clientY); if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) { - if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { - return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + if ( + hoveredIdx >= 0 && + hoveredIdx < currentHmBuckets.length && + currentHmAnchorCells[hoveredIdx] + ) { + return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; } return null; } @@ -14815,8 +15217,12 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const rect = cachedHmGridRect; if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) { cachedHmGridRect = null; - if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { - return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + if ( + hoveredIdx >= 0 && + hoveredIdx < currentHmBuckets.length && + currentHmAnchorCells[hoveredIdx] + ) { + return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; } return null; } @@ -14839,6 +15245,36 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const cellW = Math.max(1, pitchX - G); const cellH = Math.max(1, pitchY - G); + // 柱阵模式下按列定位分桶,并在列间隙保持原高亮防闪烁 + if (currentHmMode !== 'day') { + const approxCol = Math.max(0, Math.min(W - 1, Math.floor((relX + G * 0.5) / pitchX))); + if ( + hoveredIdx >= 0 && + hoveredIdx < currentHmBuckets.length && + currentColBucketIdx[approxCol] !== hoveredIdx + ) { + for (const dc of [-1, 1]) { + const nc = approxCol + dc; + if (nc < 0 || nc >= W || currentColBucketIdx[nc] !== hoveredIdx) continue; + const x0 = nc * pitchX; + const dx = relX < x0 ? x0 - relX : relX > x0 + cellW ? relX - (x0 + cellW) : 0; + if (dx <= G + 0.75 && currentHmAnchorCells[hoveredIdx]) { + return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; + } + } + } + const bIdx = currentColBucketIdx[approxCol]; + if ( + Number.isFinite(bIdx) && + bIdx >= 0 && + bIdx < currentHmBuckets.length && + currentHmAnchorCells[bIdx] + ) { + return { idx: bIdx, cellEl: currentHmAnchorCells[bIdx] }; + } + return null; + } + function distanceToCell(c, r) { const x0 = c * pitchX; const y0 = r * pitchY; @@ -14847,7 +15283,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { return { chebyshev: Math.max(dx, dy), distSq: dx * dx + dy * dy }; } - // 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁与边缘微抖 + // 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁和边缘微抖 if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { const curGridPos = currentHeatmapFirstDow + hoveredIdx; const curCol = Math.floor(curGridPos / 7); @@ -14894,7 +15330,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } function handleHeatmapPointer(e) { - if (!currentIsHeatmap || !currentSlots.length) return; + if (!currentIsHeatmap || !currentHmBuckets.length) return; const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) { clearHover(); @@ -14946,10 +15382,10 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { function handleHeatmapClick(e) { handleHeatmapPointer(e); - if (!currentIsHeatmap || !currentSlots.length || typeof onSelectSlot !== 'function') return; + if (!currentIsHeatmap || !currentHmBuckets.length || typeof onSelectSlot !== 'function') return; const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) return; - const slot = currentSlots[hit.idx]; + const slot = currentHmBuckets[hit.idx]; if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) { onSelectSlot(slot); } @@ -15007,9 +15443,20 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } /** - * 根据最新时间分桶序列重绘平滑曲线(<=90天/小时级)或类 GitHub 每日小格子热力图(>90天)。 + * 根据最新时间分桶序列重绘平滑曲线(<=90天/小时级)或 7×W 矩阵热力图(>90天,支持日/周/月/全部四档)。 */ - function update(series = []) { + function update(series = [], opts = {}) { + if (opts && opts.heatmapMode !== undefined) { + const nextHmMode = normalizeHeatmapMode(opts.heatmapMode); + if (nextHmMode !== currentHmMode) { + clearHover(); + currentHmMode = nextHmMode; + } + } + if (opts && typeof opts.buildModelSegments === 'function') { + lastBuildSegmentsFn = opts.buildModelSegments; + } + const slots = Array.isArray(series) && series.length >= 1 ? series @@ -15070,7 +15517,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { patchText(hmMoreEl, t('chart.trend.hmMore')); const sig = - `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + + `${locale}|${useHeatmap ? `hm:${currentHmMode}` : `line:${viewW}`}|` + slots .map((s) => { const mSig = Array.isArray(s?.modelSegments) @@ -15081,21 +15528,19 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { ) .join(',') : ''; - return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${safeSlotTokens(s?.inputTokens)}:${safeSlotTokens(s?.cacheReadTokens)}:${safeSlotTokens(s?.thinkingTokens)}:${safeSlotTokens(s?.responseTokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`; + const mergedCnt = Array.isArray(s?.mergedModels) ? s.mergedModels.length : 0; + return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${safeSlotTokens(s?.inputTokens)}:${safeSlotTokens(s?.cacheReadTokens)}:${safeSlotTokens(s?.thinkingTokens)}:${safeSlotTokens(s?.responseTokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mergedCnt}:${mSig}`; }) .join('|'); - if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) { - populateTooltipContent(slots[hoveredIdx]); - } - if (useHeatmap) { currentPts = []; + const isBarMode = currentHmMode !== 'day'; + hmWeekdaysEl.style.visibility = isBarMode ? 'hidden' : ''; + patchClasses(heatmapStage, { 'is-bar-mode': isBarMode }); + if (sig !== lastRenderSig) { lastRenderSig = sig; - nonZeroVals.sort((a, b) => a - b); - const thresholds = computeHeatmapThresholds(nonZeroVals, maxTokens); - const firstStartMs = Number(slots[0]?.startMs); const firstDow = Number.isFinite(firstStartMs) && firstStartMs > 0 @@ -15104,6 +15549,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { const totalCells = firstDow + slots.length; const totalWeeks = Math.max(1, Math.ceil(totalCells / 7)); const gapPx = totalWeeks > 42 ? 1.5 : 2; + const shouldAutoScrollRight = modeChanged || currentHeatmapWeeks !== totalWeeks; currentHeatmapWeeks = totalWeeks; currentHeatmapFirstDow = firstDow; currentHeatmapGapPx = gapPx; @@ -15130,47 +15576,156 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { hmMonthsEl.removeChild(hmMonthsEl.lastChild); } - // 就地增量复用 7 行 × N 周列的每日小格子,首次批量新增节点使用 DocumentFragment 挂载 - currentCellEls = new Array(slots.length); const prevMountedCount = hmGridEl.children.length; - const newCellsFrag = - totalCells > prevMountedCount && - typeof document !== 'undefined' && - typeof document.createDocumentFragment === 'function' - ? document.createDocumentFragment() - : null; - for (let nodeIdx = 0; nodeIdx < totalCells; nodeIdx++) { - let cellEl = hmCellPool[nodeIdx]; - if (!cellEl) { - cellEl = h('span', { className: 'trend-hm-cell' }); - hmCellPool.push(cellEl); + if (!isBarMode) { + nonZeroVals.sort((a, b) => a - b); + const thresholds = computeHeatmapThresholds(nonZeroVals, maxTokens); + + // 就地增量复用 7 行 × N 周列的每日小格子,首次批量新增节点使用 DocumentFragment 挂载 + currentCellEls = new Array(slots.length); + const newCellsFrag = + totalCells > prevMountedCount && + typeof document !== 'undefined' && + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : null; + + for (let nodeIdx = 0; nodeIdx < totalCells; nodeIdx++) { + let cellEl = hmCellPool[nodeIdx]; + if (!cellEl) { + cellEl = h('span', { className: 'trend-hm-cell' }); + hmCellPool.push(cellEl); + } + if (nodeIdx < firstDow) { + patchClasses(cellEl, { + 'is-pad': true, + 'is-hovered': false, + 'is-bar-hovered': false, + 'is-month-edge': false, + 'lv-0': false, + 'lv-1': false, + 'lv-2': false, + 'lv-3': false, + 'lv-4': false, + }); + patchAttr(cellEl, 'aria-hidden', 'true'); + patchAttr(cellEl, 'role', null); + patchAttr(cellEl, 'data-slot-idx', null); + patchAttr(cellEl, 'data-hm-col', null); + patchAttr(cellEl, 'data-hm-row', null); + } else { + const i = nodeIdx - firstDow; + const slot = slots[i]; + const tok = safeSlotTokens(slot?.tokens); + const lv = resolveHeatmapLevel(tok, thresholds); + const col = Math.floor(nodeIdx / 7); + const row = nodeIdx % 7; + patchClasses(cellEl, { + 'is-pad': false, + 'is-hovered': hoveredIdx === i, + 'is-bar-hovered': false, + 'is-month-edge': false, + 'lv-0': lv === 0, + 'lv-1': lv === 1, + 'lv-2': lv === 2, + 'lv-3': lv === 3, + 'lv-4': lv === 4, + }); + patchAttr(cellEl, 'aria-hidden', null); + patchAttr(cellEl, 'role', 'gridcell'); + patchAttr(cellEl, 'data-slot-idx', String(i)); + patchAttr(cellEl, 'data-hm-col', String(col)); + patchAttr(cellEl, 'data-hm-row', String(row)); + currentCellEls[i] = cellEl; + } + if (nodeIdx < prevMountedCount) { + if (hmGridEl.children[nodeIdx] !== cellEl) { + hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); + } + } else if (newCellsFrag) { + newCellsFrag.appendChild(cellEl); + } else { + hmGridEl.appendChild(cellEl); + } } - if (nodeIdx < firstDow) { - patchClasses(cellEl, { - 'is-pad': true, - 'is-hovered': false, - 'lv-0': false, - 'lv-1': false, - 'lv-2': false, - 'lv-3': false, - 'lv-4': false, - }); - patchAttr(cellEl, 'aria-hidden', 'true'); - patchAttr(cellEl, 'role', null); - patchAttr(cellEl, 'data-slot-idx', null); - patchAttr(cellEl, 'data-hm-col', null); - patchAttr(cellEl, 'data-hm-row', null); - } else { - const i = nodeIdx - firstDow; - const slot = slots[i]; - const tok = safeSlotTokens(slot?.tokens); - const lv = resolveHeatmapLevel(tok, thresholds); + if (newCellsFrag) { + hmGridEl.appendChild(newCellsFrag); + } + while (hmGridEl.children.length > totalCells) { + hmGridEl.removeChild(hmGridEl.lastChild); + } + + currentHmBuckets = slots; + currentHmBucketCells = currentCellEls.map((el) => (el ? [el] : [])); + currentHmAnchorCells = currentCellEls.slice(); + currentColBucketIdx = []; + hoveredCellEl = + hoveredIdx >= 0 && hoveredIdx < slots.length ? currentCellEls[hoveredIdx] || null : null; + hoveredHighlightEls = hoveredCellEl ? [hoveredCellEl] : []; + + const peakSlot = slots[peakIdx]; + lastHeatmapSummaryText = + maxTokens > 0 && peakSlot?.label + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); + } else { + // 周 / 月 / 全部柱阵模式:保持 7 行 × N 周列点阵几何不变,自底向上点亮对应格数 + const barView = buildHeatmapBarView( + slots, + firstDow, + totalWeeks, + currentHmMode, + lastBuildSegmentsFn + ); + const totalGridCells = totalWeeks * 7; + currentCellEls = []; + currentHmBuckets = barView.buckets; + currentColBucketIdx = barView.colSpecs.map((s) => s.bucketIdx); + + const bucketCount = barView.buckets.length; + const bucketLitCells = Array.from({ length: bucketCount }, () => []); + const bucketBottomCells = Array.from({ length: bucketCount }, () => []); + const bucketTopRowCells = Array.from({ length: bucketCount }, () => []); + + const newCellsFrag = + totalGridCells > prevMountedCount && + typeof document !== 'undefined' && + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : null; + + for (let nodeIdx = 0; nodeIdx < totalGridCells; nodeIdx++) { + let cellEl = hmCellPool[nodeIdx]; + if (!cellEl) { + cellEl = h('span', { className: 'trend-hm-cell' }); + hmCellPool.push(cellEl); + } const col = Math.floor(nodeIdx / 7); const row = nodeIdx % 7; + const spec = barView.colSpecs[col] || { + bucketIdx: 0, + litRows: 0, + lv: 0, + isMonthEdge: false, + }; + const bIdx = spec.bucketIdx; + const topLitRow = spec.litRows > 0 ? 7 - spec.litRows : 6; + const isLit = spec.litRows > 0 && row >= topLitRow; + const lv = isLit ? spec.lv : 0; + const isBarHovered = + hoveredIdx === bIdx && (isLit || (spec.litRows === 0 && row === 6)); + patchClasses(cellEl, { 'is-pad': false, - 'is-hovered': hoveredIdx === i, + 'is-hovered': false, + 'is-bar-hovered': isBarHovered, + 'is-month-edge': Boolean(spec.isMonthEdge), 'lv-0': lv === 0, 'lv-1': lv === 1, 'lv-2': lv === 2, @@ -15179,59 +15734,88 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { }); patchAttr(cellEl, 'aria-hidden', null); patchAttr(cellEl, 'role', 'gridcell'); - patchAttr(cellEl, 'data-slot-idx', String(i)); + patchAttr(cellEl, 'data-slot-idx', String(bIdx)); patchAttr(cellEl, 'data-hm-col', String(col)); patchAttr(cellEl, 'data-hm-row', String(row)); - currentCellEls[i] = cellEl; - } - if (nodeIdx < prevMountedCount) { - if (hmGridEl.children[nodeIdx] !== cellEl) { - hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); - } - } else if (newCellsFrag) { - newCellsFrag.appendChild(cellEl); - } else { - hmGridEl.appendChild(cellEl); - } - } - if (newCellsFrag) { - hmGridEl.appendChild(newCellsFrag); - } - while (hmGridEl.children.length > totalCells) { - hmGridEl.removeChild(hmGridEl.lastChild); - } - hoveredCellEl = - hoveredIdx >= 0 && hoveredIdx < slots.length ? currentCellEls[hoveredIdx] || null : null; - if (typeof requestAnimationFrame === 'function') { + if (bIdx >= 0 && bIdx < bucketCount) { + if (isLit) bucketLitCells[bIdx].push(cellEl); + if (row === 6) bucketBottomCells[bIdx].push(cellEl); + if (row === topLitRow) bucketTopRowCells[bIdx].push(cellEl); + } + + if (nodeIdx < prevMountedCount) { + if (hmGridEl.children[nodeIdx] !== cellEl) { + hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); + } + } else if (newCellsFrag) { + newCellsFrag.appendChild(cellEl); + } else { + hmGridEl.appendChild(cellEl); + } + } + if (newCellsFrag) { + hmGridEl.appendChild(newCellsFrag); + } + while (hmGridEl.children.length > totalGridCells) { + hmGridEl.removeChild(hmGridEl.lastChild); + } + + currentHmBucketCells = barView.buckets.map((_, bIdx) => + bucketLitCells[bIdx].length > 0 ? bucketLitCells[bIdx] : bucketBottomCells[bIdx] + ); + currentHmAnchorCells = barView.buckets.map((_, bIdx) => { + const tops = bucketTopRowCells[bIdx]; + return tops.length > 0 ? tops[Math.floor(tops.length / 2)] : null; + }); + hoveredCellEl = + hoveredIdx >= 0 && hoveredIdx < bucketCount + ? currentHmAnchorCells[hoveredIdx] || null + : null; + hoveredHighlightEls = + hoveredIdx >= 0 && hoveredIdx < bucketCount + ? currentHmBucketCells[hoveredIdx] || [] + : []; + lastHeatmapSummaryText = barView.summaryText; + } + + if (shouldAutoScrollRight && typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => { if (hmScrollEl.scrollWidth > hmScrollEl.clientWidth) { hmScrollEl.scrollLeft = hmScrollEl.scrollWidth; } }); } + } else if (currentHmMode === 'day') { + const peakSlot = slots[peakIdx]; + lastHeatmapSummaryText = + maxTokens > 0 && peakSlot?.label + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); } - const peakSlot = slots[peakIdx]; - const summaryText = - maxTokens > 0 && peakSlot?.label - ? t('chart.trend.hmActivePeak', { - active: activeDays, - total: slots.length, - label: peakSlot.label, - tokens: formatTokensPrecise(maxTokens), - }) - : t('chart.trend.hmActiveZero', { total: slots.length }); - patchText(hmSummaryEl, summaryText); + patchText(hmSummaryEl, lastHeatmapSummaryText); - if (hoveredIdx >= slots.length) { + if (hoveredIdx >= currentHmBuckets.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer); + if (!tooltipEl.hasAttribute('hidden') && currentHmBuckets[hoveredIdx]) { + populateTooltipContent(currentHmBuckets[hoveredIdx]); + } + showHeatmapHoverAtIndex(hoveredIdx, currentHmAnchorCells[hoveredIdx], lastPointer); } return; } + if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) { + populateTooltipContent(slots[hoveredIdx]); + } + // --- <= 90 天(或整点/分钟级):渲染平滑面积曲线图(1:1 贴边对齐 + 连续插值形变过渡) --- currentCellEls = []; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); @@ -15388,7 +15972,23 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } } - return { el: chartWrap, update, destroy }; + function setHeatmapMode(nextMode) { + const norm = normalizeHeatmapMode(nextMode); + if (norm === currentHmMode) return; + clearHover(); + currentHmMode = norm; + if (currentSlots.length > 0) { + update(currentSlots); + } + } + + return { + el: chartWrap, + update, + setHeatmapMode, + getHeatmapMode: () => currentHmMode, + destroy, + }; } return { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart }; })(); @@ -30128,6 +30728,16 @@ function getConsumptionTimeRangeOptions() { ]; } +/** 热力图顶栏支持的四档聚合视图选项 */ +function getHeatmapModeOptions() { + return [ + { value: 'day', label: t('cons.hmModeDay') }, + { value: 'week', label: t('cons.hmModeWeek') }, + { value: 'month', label: t('cons.hmModeMonth') }, + { value: 'all', label: t('cons.hmModeAll') }, + ]; +} + function floorToStartOfMinuteMs(ms) { const n = Number(ms); if (!(n > 0)) return 0; @@ -30507,14 +31117,29 @@ const ConsumptionView = defineComponent({ }); } - // --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 + 悬停精确日期/小时浮层 + 点击时段下钻) --- + // --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 / 7×W 四态热力格子图 + 悬停明细浮层 + 点击时段下钻) --- + let heatmapViewMode = 'day'; const trendTitleSpan = h('span', { text: t('cons.trendTitle') }); const trendRangeBadge = h('span', { className: 'cons-badge', text: t('cons.allTime') }); const trendGranularityHint = h('span', { - className: 'text-muted text-mono', + className: 'cons-trend-hint text-muted text-mono', style: 'font-size: var(--fs-sm);', text: t('cons.trendPointsHintHourly', { points: 0 }), }); + const heatmapModeSwitch = SegmentedControl({ + ariaLabel: t('cons.hmModeAria'), + modelValue: heatmapViewMode, + options: getHeatmapModeOptions(), + onUpdateModelValue: (nextMode) => { + if (!['day', 'week', 'month', 'all'].includes(nextMode)) return; + heatmapViewMode = nextMode; + heatmapModeSwitch.setValue(nextMode); + trendChart.setHeatmapMode(nextMode); + }, + }); + heatmapModeSwitch.el.classList.add('cons-hm-mode-switch'); + patchAttr(heatmapModeSwitch.el, 'hidden', true); + const trendChart = createTrendAreaChart({ onSelectSlot: (slot) => { if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) { @@ -30524,12 +31149,15 @@ const ConsumptionView = defineComponent({ }); const trendPanel = h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [ + h('div', { className: 'panel-header cons-trend-head' }, [ h('span', { className: 'panel-title' }, [ trendTitleSpan, trendRangeBadge, ]), - trendGranularityHint, + h('div', { className: 'cons-trend-head-right' }, [ + trendGranularityHint, + heatmapModeSwitch.el, + ]), ]), trendChart.el, ]); @@ -32251,11 +32879,12 @@ const ConsumptionView = defineComponent({ (firstTrendSlot?.label || '').includes(':')); const isHeatmapTrend = !isMinuteTrend && !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; - patchText( - trendGranularityHint, - isHeatmapTrend - ? t('cons.trendHeatmapHint', { days: rawTrendSeries.length }) - : isMinuteTrend + patchAttr(trendGranularityHint, 'hidden', isHeatmapTrend); + patchAttr(heatmapModeSwitch.el, 'hidden', !isHeatmapTrend); + if (!isHeatmapTrend) { + patchText( + trendGranularityHint, + isMinuteTrend ? t('cons.trendPointsHintMinute', { minutes: Math.max(1, Number(firstTrendSlot?.stepMinutes) || 5), points: rawTrendSeries.length || 0, @@ -32263,19 +32892,28 @@ const ConsumptionView = defineComponent({ : isHourlyTrend ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) - ); + ); + } else { + heatmapModeSwitch.setValue(heatmapViewMode); + } + const buildTrendModelSegments = (mergedSlotModels) => + partitionModelSegments(mergedSlotModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { const mergedSlotModels = trendMergedByIdx[idx]; if (!mergedSlotModels || mergedSlotModels.length === 0) return slot; return { ...slot, - modelSegments: partitionModelSegments(mergedSlotModels, modelColorMap, { - maxMain: 5, - minSharePct: 1.5, - }), + mergedModels: mergedSlotModels, + modelSegments: buildTrendModelSegments(mergedSlotModels), }; }); - trendChart.update(enrichedTrendSeries); + trendChart.update(enrichedTrendSeries, { + heatmapMode: heatmapViewMode, + buildModelSegments: buildTrendModelSegments, + }); // 3. 同步统一排行卡片(分段切换「模型排行 | 项目排行 | 会话排行」及对应排序控制) const sortedTopConvs = [...topConvsWithModels].sort((a, b) => @@ -32610,6 +33248,11 @@ const ConsumptionView = defineComponent({ md: { label: t('cons.exportMd'), title: t('cons.exportMdTip') }, }); patchText(trendTitleSpan, t('cons.trendTitle')); + heatmapModeSwitch.setProps({ + ariaLabel: t('cons.hmModeAria'), + modelValue: heatmapViewMode, + options: getHeatmapModeOptions(), + }); rankingTabSwitch.setProps({ ariaLabel: t('cons.rankTabAria'), modelValue: activeRankingTab, @@ -32654,6 +33297,7 @@ const ConsumptionView = defineComponent({ unsubI18n(); consExportMenu.destroy(); cyclePoolSelect.destroy(); + heatmapModeSwitch.destroy(); trendChart.destroy?.(); rankingTabSwitch.destroy(); modelsSortSwitch.destroy(); @@ -32669,6 +33313,8 @@ const ConsumptionView = defineComponent({ refs: { timeFilterSwitch, cyclePoolSelect, + heatmapModeSwitch, + trendChart, startPicker, endPicker, viewScrollbar, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 9fef7dd..b507de1 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index bb75c6f..530e326 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -14,12 +14,13 @@ import { patchText, } from '../../core/domPatch.js'; import { + formatDateSpanBadge, formatTokensPrecise, formatTrendSlotFullLabel, formatUsd, } from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; -import { getEffectiveLocale, t } from '../../i18n/index.js'; +import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js'; import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js'; /** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ @@ -367,6 +368,332 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { return ticks; } +const EN_SHORT_MONTHS = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', +]; + +function normalizeHeatmapMode(mode) { + return mode === 'week' || mode === 'month' || mode === 'all' ? mode : 'day'; +} + +function createHeatmapAggAcc(extra = {}) { + return { + tokens: 0, + inputTokens: 0, + cacheReadTokens: 0, + thinkingTokens: 0, + responseTokens: 0, + outputTokens: 0, + costUsd: 0, + calls: 0, + minStartMs: Infinity, + maxEndMs: 0, + firstLabel: '', + lastLabel: '', + modelMap: new Map(), + ...extra, + }; +} + +function mergeSlotIntoHeatmapAcc(acc, slot) { + if (!slot) return; + const tok = safeSlotTokens(slot.tokens); + const inTok = safeSlotTokens(slot.inputTokens); + const cacheTok = safeSlotTokens(slot.cacheReadTokens); + const thinkTok = safeSlotTokens(slot.thinkingTokens); + const respTok = safeSlotTokens(slot.responseTokens); + const outTok = + slot.outputTokens !== undefined && slot.outputTokens !== null + ? safeSlotTokens(slot.outputTokens) + : thinkTok + respTok; + acc.tokens += tok; + acc.inputTokens += inTok; + acc.cacheReadTokens += cacheTok; + acc.thinkingTokens += thinkTok; + acc.responseTokens += respTok; + acc.outputTokens += outTok; + acc.costUsd += Math.max(0, Number(slot.costUsd || 0)); + acc.calls += Math.max(0, Number(slot.calls || 0)); + + const sMs = Number(slot.startMs); + const eMs = Number(slot.endMs); + if (Number.isFinite(sMs) && sMs > 0 && sMs < acc.minStartMs) { + acc.minStartMs = sMs; + } + if (Number.isFinite(eMs) && eMs > acc.maxEndMs) { + acc.maxEndMs = eMs; + } else if (Number.isFinite(sMs) && sMs > 0 && sMs + 86_400_000 > acc.maxEndMs) { + acc.maxEndMs = sMs + 86_400_000; + } + const lbl = String(slot.label || ''); + if (!acc.firstLabel && lbl) acc.firstLabel = lbl; + if (lbl) acc.lastLabel = lbl; + + const srcModels = Array.isArray(slot.mergedModels) + ? slot.mergedModels + : Array.isArray(slot.models) + ? slot.models + : null; + if (srcModels) { + for (let i = 0; i < srcModels.length; i++) { + const m = srcModels[i]; + if (!m) continue; + const key = String(m.displayText || m.label || m.shortName || ''); + if (!key) continue; + let cur = acc.modelMap.get(key); + if (!cur) { + cur = { + ...m, + calls: 0, + inputTokens: 0, + cacheReadTokens: 0, + thinkingTokens: 0, + responseTokens: 0, + outputTokens: 0, + totalTokens: 0, + costUsd: 0, + }; + acc.modelMap.set(key, cur); + } + cur.calls += Math.max(0, Number(m.calls || 0)); + cur.inputTokens += safeSlotTokens(m.inputTokens); + cur.cacheReadTokens += safeSlotTokens(m.cacheReadTokens); + cur.thinkingTokens += safeSlotTokens(m.thinkingTokens); + cur.responseTokens += safeSlotTokens(m.responseTokens); + cur.outputTokens += safeSlotTokens(m.outputTokens); + cur.totalTokens += safeSlotTokens(m.totalTokens); + cur.costUsd += Math.max(0, Number(m.costUsd || 0)); + } + } +} + +function finalizeHeatmapBucket(acc, customTitle, shortLabel, buildSegmentsFn) { + const hasStart = Number.isFinite(acc.minStartMs) && acc.minStartMs < Infinity && acc.minStartMs > 0; + const startMs = hasStart ? acc.minStartMs : 0; + const endMs = + hasStart && acc.maxEndMs > startMs + ? Math.max(startMs + 60_000, acc.maxEndMs - 1) + : 0; + let modelSegments = []; + if (typeof buildSegmentsFn === 'function' && acc.modelMap.size > 0) { + const mergedList = Array.from(acc.modelMap.values(), (m) => ({ ...m })).sort( + (a, b) => (b.totalTokens || 0) - (a.totalTokens || 0) || (b.calls || 0) - (a.calls || 0) + ); + modelSegments = buildSegmentsFn(mergedList) || []; + } + return { + startMs, + endMs, + label: shortLabel || customTitle, + fullLabel: customTitle, + customTitle, + tokens: acc.tokens, + inputTokens: acc.inputTokens, + cacheReadTokens: acc.cacheReadTokens, + thinkingTokens: acc.thinkingTokens, + responseTokens: acc.responseTokens, + outputTokens: acc.outputTokens, + costUsd: +acc.costUsd.toFixed(4), + calls: acc.calls, + modelSegments, + }; +} + +function buildHeatmapBarView(slots, firstDow, totalWeeks, mode, buildSegmentsFn) { + if (mode === 'week') { + const weekAccs = Array.from({ length: totalWeeks }, () => createHeatmapAggAcc()); + for (let i = 0; i < slots.length; i++) { + const col = Math.floor((firstDow + i) / 7); + if (col >= 0 && col < totalWeeks) { + mergeSlotIntoHeatmapAcc(weekAccs[col], slots[i]); + } + } + let maxTok = 0; + let peakIdx = 0; + let activeWeeks = 0; + const nonZero = []; + const buckets = weekAccs.map((acc, idx) => { + if (acc.tokens > 0) { + activeWeeks++; + nonZero.push(acc.tokens); + } + if (acc.tokens >= maxTok) { + maxTok = acc.tokens; + peakIdx = idx; + } + const hasValidRange = Number.isFinite(acc.minStartMs) && acc.minStartMs < Infinity && acc.minStartMs > 0; + const spanTitle = hasValidRange + ? formatDateSpanBadge(acc.minStartMs, Math.max(acc.minStartMs, acc.maxEndMs - 1)) + : acc.firstLabel && acc.lastLabel && acc.firstLabel !== acc.lastLabel + ? `${acc.firstLabel} ~ ${acc.lastLabel}` + : acc.firstLabel || '--'; + const shortLbl = + acc.firstLabel && acc.lastLabel && acc.firstLabel !== acc.lastLabel + ? `${acc.firstLabel}~${acc.lastLabel.split('/').pop()}` + : acc.firstLabel || spanTitle; + return finalizeHeatmapBucket(acc, spanTitle, shortLbl, buildSegmentsFn); + }); + nonZero.sort((a, b) => a - b); + const thresholds = computeHeatmapThresholds(nonZero, maxTok); + const colSpecs = buckets.map((b, col) => { + const litRows = + b.tokens > 0 && maxTok > 0 ? Math.max(1, Math.min(7, Math.ceil((b.tokens / maxTok) * 7))) : 0; + return { + bucketIdx: col, + litRows, + lv: litRows > 0 ? resolveHeatmapLevel(b.tokens, thresholds) : 0, + isMonthEdge: false, + }; + }); + const peakB = buckets[peakIdx]; + const summaryText = + maxTok > 0 && peakB + ? t('chart.trend.hmWeekPeak', { + active: activeWeeks, + total: totalWeeks, + label: peakB.label, + tokens: formatTokensPrecise(maxTok), + }) + : t('chart.trend.hmWeekZero', { total: totalWeeks }); + return { buckets, colSpecs, summaryText }; + } + + if (mode === 'month') { + const monthIndexByKey = new Map(); + const monthAccs = []; + const colMonthCounts = Array.from({ length: totalWeeks }, () => new Map()); + + for (let i = 0; i < slots.length; i++) { + const slot = slots[i]; + const parts = parseSlotCalendarParts(slot); + const mKey = `${parts.year}-${parts.month}`; + let mIdx = monthIndexByKey.get(mKey); + if (mIdx === undefined) { + mIdx = monthAccs.length; + monthIndexByKey.set(mKey, mIdx); + monthAccs.push(createHeatmapAggAcc({ year: parts.year, month: parts.month })); + } + mergeSlotIntoHeatmapAcc(monthAccs[mIdx], slot); + const col = Math.floor((firstDow + i) / 7); + if (col >= 0 && col < totalWeeks) { + colMonthCounts[col].set(mIdx, (colMonthCounts[col].get(mIdx) || 0) + 1); + } + } + + const colMonthIdx = new Array(totalWeeks).fill(0); + for (let col = 0; col < totalWeeks; col++) { + let bestM = col > 0 ? colMonthIdx[col - 1] : 0; + let bestCnt = -1; + for (const [mIdx, cnt] of colMonthCounts[col].entries()) { + if (cnt >= bestCnt) { + bestCnt = cnt; + bestM = mIdx; + } + } + colMonthIdx[col] = bestM; + } + if (monthAccs.length > 0 && totalWeeks >= monthAccs.length) { + colMonthIdx[0] = 0; + colMonthIdx[totalWeeks - 1] = monthAccs.length - 1; + } + + let maxTok = 0; + let peakIdx = 0; + let activeMonths = 0; + const nonZero = []; + const en = isEnglishLocale(); + const buckets = monthAccs.map((acc, idx) => { + if (acc.tokens > 0) { + activeMonths++; + nonZero.push(acc.tokens); + } + if (acc.tokens >= maxTok) { + maxTok = acc.tokens; + peakIdx = idx; + } + const mNum = acc.month || 1; + const enShort = EN_SHORT_MONTHS[mNum - 1] || `M${mNum}`; + const fullTitle = en ? `${enShort} ${acc.year}` : t('cons.monthFullLabel', { year: acc.year, m: mNum }); + const shortLbl = en ? enShort : t('cons.monthLabel', { m: mNum }); + return finalizeHeatmapBucket(acc, fullTitle, shortLbl, buildSegmentsFn); + }); + nonZero.sort((a, b) => a - b); + const thresholds = computeHeatmapThresholds(nonZero, maxTok); + const colSpecs = colMonthIdx.map((mIdx, col) => { + const b = buckets[mIdx] || { tokens: 0 }; + const litRows = + b.tokens > 0 && maxTok > 0 ? Math.max(1, Math.min(7, Math.ceil((b.tokens / maxTok) * 7))) : 0; + return { + bucketIdx: mIdx, + litRows, + lv: litRows > 0 ? resolveHeatmapLevel(b.tokens, thresholds) : 0, + isMonthEdge: col > 0 && mIdx !== colMonthIdx[col - 1], + }; + }); + const peakB = buckets[peakIdx]; + const summaryText = + maxTok > 0 && peakB + ? t('chart.trend.hmMonthPeak', { + active: activeMonths, + total: buckets.length, + label: peakB.label, + tokens: formatTokensPrecise(maxTok), + }) + : t('chart.trend.hmMonthZero', { total: Math.max(1, buckets.length) }); + return { buckets, colSpecs, summaryText }; + } + + // mode === 'all' (累计总量爬升柱阵) + const runAcc = createHeatmapAggAcc(); + const buckets = new Array(totalWeeks); + for (let col = 0; col < totalWeeks; col++) { + for (let row = 0; row < 7; row++) { + const sIdx = col * 7 + row - firstDow; + if (sIdx >= 0 && sIdx < slots.length) { + mergeSlotIntoHeatmapAcc(runAcc, slots[sIdx]); + } + } + const hasEnd = Number.isFinite(runAcc.minStartMs) && runAcc.minStartMs < Infinity && runAcc.maxEndMs > 0; + const endDayMs = hasEnd ? Math.max(runAcc.minStartMs, runAcc.maxEndMs - 1) : 0; + const endDateStr = endDayMs > 0 ? formatDateSpanBadge(endDayMs, endDayMs) : runAcc.lastLabel || '--'; + const cumTitle = t('chart.trend.hmCumThrough', { date: endDateStr }); + buckets[col] = finalizeHeatmapBucket(runAcc, cumTitle, endDateStr, buildSegmentsFn); + } + const grandTotal = buckets[totalWeeks - 1]?.tokens || 0; + const grandCost = buckets[totalWeeks - 1]?.costUsd || 0; + const colSpecs = buckets.map((b, col) => { + const litRows = + b.tokens > 0 && grandTotal > 0 + ? Math.max(1, Math.min(7, Math.ceil((b.tokens / grandTotal) * 7))) + : 0; + const ratio = grandTotal > 0 ? b.tokens / grandTotal : 0; + const lv = litRows === 0 ? 0 : ratio > 0.75 ? 4 : ratio > 0.5 ? 3 : ratio > 0.25 ? 2 : 1; + return { + bucketIdx: col, + litRows, + lv, + isMonthEdge: false, + }; + }); + const summaryText = t('chart.trend.hmCumSummary', { + days: slots.length, + tokens: formatTokensPrecise(grandTotal), + cost: formatUsd(grandCost), + }); + return { buckets, colSpecs, summaryText }; +} + /** * 创建交互式历史趋势组件(<=90 天为 SVG 平滑曲线图,>90 天自动切换为类 GitHub 每日小格子热力图)。 * @@ -544,10 +871,18 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { let currentSlots = []; let currentPts = []; let currentIsHeatmap = false; + let currentHmMode = 'day'; + let lastBuildSegmentsFn = null; let currentHeatmapWeeks = 0; let currentHeatmapFirstDow = 0; let currentHeatmapGapPx = 2; let currentCellEls = []; + let currentHmBuckets = []; + let currentHmBucketCells = []; + let currentHmAnchorCells = []; + let currentColBucketIdx = []; + let hoveredHighlightEls = []; + let lastHeatmapSummaryText = ''; let tickElsByIdx = new Map(); let hoveredIdx = -1; let hoveredCellEl = null; @@ -713,7 +1048,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const slotTok = safeSlotTokens(slot.tokens); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; tooltipContent.update({ - title: formatTrendSlotFullLabel(slot) || slot.label || '--', + title: slot.customTitle || formatTrendSlotFullLabel(slot) || slot.label || '--', calls: slot.calls, totalTokens: slotTok, costText: formatUsd(slotCost, { @@ -854,11 +1189,14 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) { - if (!currentIsHeatmap || idx < 0 || idx >= currentSlots.length) { + if (!currentIsHeatmap || idx < 0 || idx >= currentHmBuckets.length) { clearHover(); return; } - const targetCell = cellEl || currentCellEls[idx] || null; + const isBarMode = currentHmMode !== 'day'; + const targetCell = isBarMode + ? currentHmAnchorCells[idx] || cellEl || null + : cellEl || currentHmAnchorCells[idx] || currentCellEls[idx] || null; if (!targetCell) { clearHover(); return; @@ -869,13 +1207,29 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { if (pointer) { lastPointer = pointer; } - if (hoveredCellEl && hoveredCellEl !== targetCell) { - patchClasses(hoveredCellEl, { 'is-hovered': false }); - } - hoveredCellEl = targetCell; - patchClasses(targetCell, { 'is-hovered': true }); - const slot = currentSlots[idx]; + if (changedCell || hoveredHighlightEls.length === 0) { + for (let i = 0; i < hoveredHighlightEls.length; i++) { + patchClasses(hoveredHighlightEls[i], { + 'is-hovered': false, + 'is-bar-hovered': false, + }); + } + const nextHighlight = + currentHmBucketCells[idx] && currentHmBucketCells[idx].length > 0 + ? currentHmBucketCells[idx] + : [targetCell]; + for (let i = 0; i < nextHighlight.length; i++) { + patchClasses(nextHighlight[i], { + 'is-hovered': !isBarMode, + 'is-bar-hovered': isBarMode, + }); + } + hoveredHighlightEls = nextHighlight; + hoveredCellEl = targetCell; + } + + const slot = currentHmBuckets[idx]; const row = Number(targetCell.getAttribute('data-hm-row') || 0); const col = Number(targetCell.getAttribute('data-hm-col') || 0); @@ -898,18 +1252,32 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { let fallbackX = currentHeatmapWeeks > 0 ? ((col + 0.5) / currentHeatmapWeeks) * wrapW : wrapW / 2; let fallbackY = 20 + row * 14; - if ( + const hasValidCellRect = Boolean( wrapRect && - wrapRect.width > 0 && - cellRect && - cellRect.width > 0 && - cellRect.width < wrapRect.width - ) { + wrapRect.width > 0 && + cellRect && + cellRect.width > 0 && + cellRect.width < wrapRect.width + ); + if (hasValidCellRect) { fallbackX = cellRect.left + cellRect.width / 2 - wrapRect.left; fallbackY = cellRect.top + cellRect.height / 2 - wrapRect.top; } - positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer); + const rawPtr = pointer || lastPointer; + const effectivePtr = + isBarMode && + rawPtr && + hasValidCellRect && + Number.isFinite(Number(rawPtr.clientX)) && + Number.isFinite(Number(rawPtr.clientY)) + ? { + clientX: Number(rawPtr.clientX), + clientY: Math.min(Number(rawPtr.clientY), cellRect.top + 2), + } + : rawPtr; + + positionTooltipNearAnchor(fallbackX, fallbackY, effectivePtr); armTooltipTracking(wasHidden); } @@ -931,8 +1299,17 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { if (!currentIsHeatmap) { patchAttr(peakPill, 'hidden', false); } + if (hoveredHighlightEls.length > 0) { + for (let i = 0; i < hoveredHighlightEls.length; i++) { + patchClasses(hoveredHighlightEls[i], { + 'is-hovered': false, + 'is-bar-hovered': false, + }); + } + hoveredHighlightEls = []; + } if (hoveredCellEl) { - patchClasses(hoveredCellEl, { 'is-hovered': false }); + patchClasses(hoveredCellEl, { 'is-hovered': false, 'is-bar-hovered': false }); hoveredCellEl = null; } for (const el of tickElsByIdx.values()) { @@ -989,8 +1366,10 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const idxAttr = cur.getAttribute?.('data-slot-idx'); if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') { const idx = Number(idxAttr); - if (Number.isFinite(idx) && idx >= 0 && idx < currentSlots.length) { - return { idx, cellEl: cur }; + if (Number.isFinite(idx) && idx >= 0 && idx < currentHmBuckets.length) { + const cellEl = + currentHmMode !== 'day' ? currentHmAnchorCells[idx] || cur : cur; + return { idx, cellEl }; } } cur = cur.parentNode || null; @@ -1005,8 +1384,12 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const clientX = Number(e?.clientX); const clientY = Number(e?.clientY); if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) { - if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { - return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + if ( + hoveredIdx >= 0 && + hoveredIdx < currentHmBuckets.length && + currentHmAnchorCells[hoveredIdx] + ) { + return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; } return null; } @@ -1017,8 +1400,12 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const rect = cachedHmGridRect; if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) { cachedHmGridRect = null; - if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { - return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + if ( + hoveredIdx >= 0 && + hoveredIdx < currentHmBuckets.length && + currentHmAnchorCells[hoveredIdx] + ) { + return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; } return null; } @@ -1041,6 +1428,36 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const cellW = Math.max(1, pitchX - G); const cellH = Math.max(1, pitchY - G); + // 柱阵模式下按列定位分桶,并在列间隙保持原高亮防闪烁 + if (currentHmMode !== 'day') { + const approxCol = Math.max(0, Math.min(W - 1, Math.floor((relX + G * 0.5) / pitchX))); + if ( + hoveredIdx >= 0 && + hoveredIdx < currentHmBuckets.length && + currentColBucketIdx[approxCol] !== hoveredIdx + ) { + for (const dc of [-1, 1]) { + const nc = approxCol + dc; + if (nc < 0 || nc >= W || currentColBucketIdx[nc] !== hoveredIdx) continue; + const x0 = nc * pitchX; + const dx = relX < x0 ? x0 - relX : relX > x0 + cellW ? relX - (x0 + cellW) : 0; + if (dx <= G + 0.75 && currentHmAnchorCells[hoveredIdx]) { + return { idx: hoveredIdx, cellEl: currentHmAnchorCells[hoveredIdx] }; + } + } + } + const bIdx = currentColBucketIdx[approxCol]; + if ( + Number.isFinite(bIdx) && + bIdx >= 0 && + bIdx < currentHmBuckets.length && + currentHmAnchorCells[bIdx] + ) { + return { idx: bIdx, cellEl: currentHmAnchorCells[bIdx] }; + } + return null; + } + function distanceToCell(c, r) { const x0 = c * pitchX; const y0 = r * pitchY; @@ -1049,7 +1466,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { return { chebyshev: Math.max(dx, dy), distSq: dx * dx + dy * dy }; } - // 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁与边缘微抖 + // 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁和边缘微抖 if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { const curGridPos = currentHeatmapFirstDow + hoveredIdx; const curCol = Math.floor(curGridPos / 7); @@ -1096,7 +1513,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } function handleHeatmapPointer(e) { - if (!currentIsHeatmap || !currentSlots.length) return; + if (!currentIsHeatmap || !currentHmBuckets.length) return; const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) { clearHover(); @@ -1148,10 +1565,10 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { function handleHeatmapClick(e) { handleHeatmapPointer(e); - if (!currentIsHeatmap || !currentSlots.length || typeof onSelectSlot !== 'function') return; + if (!currentIsHeatmap || !currentHmBuckets.length || typeof onSelectSlot !== 'function') return; const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) return; - const slot = currentSlots[hit.idx]; + const slot = currentHmBuckets[hit.idx]; if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) { onSelectSlot(slot); } @@ -1209,9 +1626,20 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } /** - * 根据最新时间分桶序列重绘平滑曲线(<=90天/小时级)或类 GitHub 每日小格子热力图(>90天)。 + * 根据最新时间分桶序列重绘平滑曲线(<=90天/小时级)或 7×W 矩阵热力图(>90天,支持日/周/月/全部四档)。 */ - function update(series = []) { + function update(series = [], opts = {}) { + if (opts && opts.heatmapMode !== undefined) { + const nextHmMode = normalizeHeatmapMode(opts.heatmapMode); + if (nextHmMode !== currentHmMode) { + clearHover(); + currentHmMode = nextHmMode; + } + } + if (opts && typeof opts.buildModelSegments === 'function') { + lastBuildSegmentsFn = opts.buildModelSegments; + } + const slots = Array.isArray(series) && series.length >= 1 ? series @@ -1272,7 +1700,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { patchText(hmMoreEl, t('chart.trend.hmMore')); const sig = - `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + + `${locale}|${useHeatmap ? `hm:${currentHmMode}` : `line:${viewW}`}|` + slots .map((s) => { const mSig = Array.isArray(s?.modelSegments) @@ -1283,21 +1711,19 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { ) .join(',') : ''; - return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${safeSlotTokens(s?.inputTokens)}:${safeSlotTokens(s?.cacheReadTokens)}:${safeSlotTokens(s?.thinkingTokens)}:${safeSlotTokens(s?.responseTokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`; + const mergedCnt = Array.isArray(s?.mergedModels) ? s.mergedModels.length : 0; + return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${safeSlotTokens(s?.inputTokens)}:${safeSlotTokens(s?.cacheReadTokens)}:${safeSlotTokens(s?.thinkingTokens)}:${safeSlotTokens(s?.responseTokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mergedCnt}:${mSig}`; }) .join('|'); - if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) { - populateTooltipContent(slots[hoveredIdx]); - } - if (useHeatmap) { currentPts = []; + const isBarMode = currentHmMode !== 'day'; + hmWeekdaysEl.style.visibility = isBarMode ? 'hidden' : ''; + patchClasses(heatmapStage, { 'is-bar-mode': isBarMode }); + if (sig !== lastRenderSig) { lastRenderSig = sig; - nonZeroVals.sort((a, b) => a - b); - const thresholds = computeHeatmapThresholds(nonZeroVals, maxTokens); - const firstStartMs = Number(slots[0]?.startMs); const firstDow = Number.isFinite(firstStartMs) && firstStartMs > 0 @@ -1306,6 +1732,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { const totalCells = firstDow + slots.length; const totalWeeks = Math.max(1, Math.ceil(totalCells / 7)); const gapPx = totalWeeks > 42 ? 1.5 : 2; + const shouldAutoScrollRight = modeChanged || currentHeatmapWeeks !== totalWeeks; currentHeatmapWeeks = totalWeeks; currentHeatmapFirstDow = firstDow; currentHeatmapGapPx = gapPx; @@ -1332,47 +1759,156 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { hmMonthsEl.removeChild(hmMonthsEl.lastChild); } - // 就地增量复用 7 行 × N 周列的每日小格子,首次批量新增节点使用 DocumentFragment 挂载 - currentCellEls = new Array(slots.length); const prevMountedCount = hmGridEl.children.length; - const newCellsFrag = - totalCells > prevMountedCount && - typeof document !== 'undefined' && - typeof document.createDocumentFragment === 'function' - ? document.createDocumentFragment() - : null; - for (let nodeIdx = 0; nodeIdx < totalCells; nodeIdx++) { - let cellEl = hmCellPool[nodeIdx]; - if (!cellEl) { - cellEl = h('span', { className: 'trend-hm-cell' }); - hmCellPool.push(cellEl); + if (!isBarMode) { + nonZeroVals.sort((a, b) => a - b); + const thresholds = computeHeatmapThresholds(nonZeroVals, maxTokens); + + // 就地增量复用 7 行 × N 周列的每日小格子,首次批量新增节点使用 DocumentFragment 挂载 + currentCellEls = new Array(slots.length); + const newCellsFrag = + totalCells > prevMountedCount && + typeof document !== 'undefined' && + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : null; + + for (let nodeIdx = 0; nodeIdx < totalCells; nodeIdx++) { + let cellEl = hmCellPool[nodeIdx]; + if (!cellEl) { + cellEl = h('span', { className: 'trend-hm-cell' }); + hmCellPool.push(cellEl); + } + if (nodeIdx < firstDow) { + patchClasses(cellEl, { + 'is-pad': true, + 'is-hovered': false, + 'is-bar-hovered': false, + 'is-month-edge': false, + 'lv-0': false, + 'lv-1': false, + 'lv-2': false, + 'lv-3': false, + 'lv-4': false, + }); + patchAttr(cellEl, 'aria-hidden', 'true'); + patchAttr(cellEl, 'role', null); + patchAttr(cellEl, 'data-slot-idx', null); + patchAttr(cellEl, 'data-hm-col', null); + patchAttr(cellEl, 'data-hm-row', null); + } else { + const i = nodeIdx - firstDow; + const slot = slots[i]; + const tok = safeSlotTokens(slot?.tokens); + const lv = resolveHeatmapLevel(tok, thresholds); + const col = Math.floor(nodeIdx / 7); + const row = nodeIdx % 7; + patchClasses(cellEl, { + 'is-pad': false, + 'is-hovered': hoveredIdx === i, + 'is-bar-hovered': false, + 'is-month-edge': false, + 'lv-0': lv === 0, + 'lv-1': lv === 1, + 'lv-2': lv === 2, + 'lv-3': lv === 3, + 'lv-4': lv === 4, + }); + patchAttr(cellEl, 'aria-hidden', null); + patchAttr(cellEl, 'role', 'gridcell'); + patchAttr(cellEl, 'data-slot-idx', String(i)); + patchAttr(cellEl, 'data-hm-col', String(col)); + patchAttr(cellEl, 'data-hm-row', String(row)); + currentCellEls[i] = cellEl; + } + if (nodeIdx < prevMountedCount) { + if (hmGridEl.children[nodeIdx] !== cellEl) { + hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); + } + } else if (newCellsFrag) { + newCellsFrag.appendChild(cellEl); + } else { + hmGridEl.appendChild(cellEl); + } } - if (nodeIdx < firstDow) { - patchClasses(cellEl, { - 'is-pad': true, - 'is-hovered': false, - 'lv-0': false, - 'lv-1': false, - 'lv-2': false, - 'lv-3': false, - 'lv-4': false, - }); - patchAttr(cellEl, 'aria-hidden', 'true'); - patchAttr(cellEl, 'role', null); - patchAttr(cellEl, 'data-slot-idx', null); - patchAttr(cellEl, 'data-hm-col', null); - patchAttr(cellEl, 'data-hm-row', null); - } else { - const i = nodeIdx - firstDow; - const slot = slots[i]; - const tok = safeSlotTokens(slot?.tokens); - const lv = resolveHeatmapLevel(tok, thresholds); + if (newCellsFrag) { + hmGridEl.appendChild(newCellsFrag); + } + while (hmGridEl.children.length > totalCells) { + hmGridEl.removeChild(hmGridEl.lastChild); + } + + currentHmBuckets = slots; + currentHmBucketCells = currentCellEls.map((el) => (el ? [el] : [])); + currentHmAnchorCells = currentCellEls.slice(); + currentColBucketIdx = []; + hoveredCellEl = + hoveredIdx >= 0 && hoveredIdx < slots.length ? currentCellEls[hoveredIdx] || null : null; + hoveredHighlightEls = hoveredCellEl ? [hoveredCellEl] : []; + + const peakSlot = slots[peakIdx]; + lastHeatmapSummaryText = + maxTokens > 0 && peakSlot?.label + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); + } else { + // 周 / 月 / 全部柱阵模式:保持 7 行 × N 周列点阵几何不变,自底向上点亮对应格数 + const barView = buildHeatmapBarView( + slots, + firstDow, + totalWeeks, + currentHmMode, + lastBuildSegmentsFn + ); + const totalGridCells = totalWeeks * 7; + currentCellEls = []; + currentHmBuckets = barView.buckets; + currentColBucketIdx = barView.colSpecs.map((s) => s.bucketIdx); + + const bucketCount = barView.buckets.length; + const bucketLitCells = Array.from({ length: bucketCount }, () => []); + const bucketBottomCells = Array.from({ length: bucketCount }, () => []); + const bucketTopRowCells = Array.from({ length: bucketCount }, () => []); + + const newCellsFrag = + totalGridCells > prevMountedCount && + typeof document !== 'undefined' && + typeof document.createDocumentFragment === 'function' + ? document.createDocumentFragment() + : null; + + for (let nodeIdx = 0; nodeIdx < totalGridCells; nodeIdx++) { + let cellEl = hmCellPool[nodeIdx]; + if (!cellEl) { + cellEl = h('span', { className: 'trend-hm-cell' }); + hmCellPool.push(cellEl); + } const col = Math.floor(nodeIdx / 7); const row = nodeIdx % 7; + const spec = barView.colSpecs[col] || { + bucketIdx: 0, + litRows: 0, + lv: 0, + isMonthEdge: false, + }; + const bIdx = spec.bucketIdx; + const topLitRow = spec.litRows > 0 ? 7 - spec.litRows : 6; + const isLit = spec.litRows > 0 && row >= topLitRow; + const lv = isLit ? spec.lv : 0; + const isBarHovered = + hoveredIdx === bIdx && (isLit || (spec.litRows === 0 && row === 6)); + patchClasses(cellEl, { 'is-pad': false, - 'is-hovered': hoveredIdx === i, + 'is-hovered': false, + 'is-bar-hovered': isBarHovered, + 'is-month-edge': Boolean(spec.isMonthEdge), 'lv-0': lv === 0, 'lv-1': lv === 1, 'lv-2': lv === 2, @@ -1381,59 +1917,88 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { }); patchAttr(cellEl, 'aria-hidden', null); patchAttr(cellEl, 'role', 'gridcell'); - patchAttr(cellEl, 'data-slot-idx', String(i)); + patchAttr(cellEl, 'data-slot-idx', String(bIdx)); patchAttr(cellEl, 'data-hm-col', String(col)); patchAttr(cellEl, 'data-hm-row', String(row)); - currentCellEls[i] = cellEl; - } - if (nodeIdx < prevMountedCount) { - if (hmGridEl.children[nodeIdx] !== cellEl) { - hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); - } - } else if (newCellsFrag) { - newCellsFrag.appendChild(cellEl); - } else { - hmGridEl.appendChild(cellEl); - } - } - if (newCellsFrag) { - hmGridEl.appendChild(newCellsFrag); - } - while (hmGridEl.children.length > totalCells) { - hmGridEl.removeChild(hmGridEl.lastChild); - } - hoveredCellEl = - hoveredIdx >= 0 && hoveredIdx < slots.length ? currentCellEls[hoveredIdx] || null : null; - if (typeof requestAnimationFrame === 'function') { + if (bIdx >= 0 && bIdx < bucketCount) { + if (isLit) bucketLitCells[bIdx].push(cellEl); + if (row === 6) bucketBottomCells[bIdx].push(cellEl); + if (row === topLitRow) bucketTopRowCells[bIdx].push(cellEl); + } + + if (nodeIdx < prevMountedCount) { + if (hmGridEl.children[nodeIdx] !== cellEl) { + hmGridEl.insertBefore(cellEl, hmGridEl.children[nodeIdx] || null); + } + } else if (newCellsFrag) { + newCellsFrag.appendChild(cellEl); + } else { + hmGridEl.appendChild(cellEl); + } + } + if (newCellsFrag) { + hmGridEl.appendChild(newCellsFrag); + } + while (hmGridEl.children.length > totalGridCells) { + hmGridEl.removeChild(hmGridEl.lastChild); + } + + currentHmBucketCells = barView.buckets.map((_, bIdx) => + bucketLitCells[bIdx].length > 0 ? bucketLitCells[bIdx] : bucketBottomCells[bIdx] + ); + currentHmAnchorCells = barView.buckets.map((_, bIdx) => { + const tops = bucketTopRowCells[bIdx]; + return tops.length > 0 ? tops[Math.floor(tops.length / 2)] : null; + }); + hoveredCellEl = + hoveredIdx >= 0 && hoveredIdx < bucketCount + ? currentHmAnchorCells[hoveredIdx] || null + : null; + hoveredHighlightEls = + hoveredIdx >= 0 && hoveredIdx < bucketCount + ? currentHmBucketCells[hoveredIdx] || [] + : []; + lastHeatmapSummaryText = barView.summaryText; + } + + if (shouldAutoScrollRight && typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => { if (hmScrollEl.scrollWidth > hmScrollEl.clientWidth) { hmScrollEl.scrollLeft = hmScrollEl.scrollWidth; } }); } + } else if (currentHmMode === 'day') { + const peakSlot = slots[peakIdx]; + lastHeatmapSummaryText = + maxTokens > 0 && peakSlot?.label + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); } - const peakSlot = slots[peakIdx]; - const summaryText = - maxTokens > 0 && peakSlot?.label - ? t('chart.trend.hmActivePeak', { - active: activeDays, - total: slots.length, - label: peakSlot.label, - tokens: formatTokensPrecise(maxTokens), - }) - : t('chart.trend.hmActiveZero', { total: slots.length }); - patchText(hmSummaryEl, summaryText); + patchText(hmSummaryEl, lastHeatmapSummaryText); - if (hoveredIdx >= slots.length) { + if (hoveredIdx >= currentHmBuckets.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer); + if (!tooltipEl.hasAttribute('hidden') && currentHmBuckets[hoveredIdx]) { + populateTooltipContent(currentHmBuckets[hoveredIdx]); + } + showHeatmapHoverAtIndex(hoveredIdx, currentHmAnchorCells[hoveredIdx], lastPointer); } return; } + if (hoveredIdx >= 0 && hoveredIdx < slots.length && !tooltipEl.hasAttribute('hidden')) { + populateTooltipContent(slots[hoveredIdx]); + } + // --- <= 90 天(或整点/分钟级):渲染平滑面积曲线图(1:1 贴边对齐 + 连续插值形变过渡) --- currentCellEls = []; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); @@ -1590,5 +2155,21 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } } - return { el: chartWrap, update, destroy }; + function setHeatmapMode(nextMode) { + const norm = normalizeHeatmapMode(nextMode); + if (norm === currentHmMode) return; + clearHover(); + currentHmMode = norm; + if (currentSlots.length > 0) { + update(currentSlots); + } + } + + return { + el: chartWrap, + update, + setHeatmapMode, + getHeatmapMode: () => currentHmMode, + destroy, + }; } diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index ff228e5..933105d 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -271,7 +271,11 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'cons.replyAndThink': 'Think {think} · Reply {resp}', 'cons.trendTitle': 'Usage Trend', 'cons.allTime': 'All Time', - 'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details', + 'cons.hmModeAria': 'Heatmap view mode', + 'cons.hmModeDay': 'Day', + 'cons.hmModeWeek': 'Week', + 'cons.hmModeMonth': 'Month', + 'cons.hmModeAll': 'Total', 'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details', 'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details', 'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details', @@ -882,6 +886,12 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'chart.trend.hmMore': 'More', 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', 'chart.trend.hmActiveZero': 'Active 0/{total}d', + 'chart.trend.hmWeekPeak': 'Active {active}/{total}w · Peak {label} · {tokens}', + 'chart.trend.hmWeekZero': 'Active 0/{total}w', + 'chart.trend.hmMonthPeak': 'Active {active}/{total}m · Peak {label} · {tokens}', + 'chart.trend.hmMonthZero': 'Active 0/{total}m', + 'chart.trend.hmCumSummary': 'Cumulative {days}d · Total {tokens} · {cost}', + 'chart.trend.hmCumThrough': 'Cumulative through {date}', 'chart.trend.peakPill': 'Peak {label} · {tokens}', // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 5860f14..5eb38d4 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -271,7 +271,11 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'cons.replyAndThink': '思考 {think} · 回复 {resp}', 'cons.trendTitle': '用量趋势', 'cons.allTime': '全部时间', - 'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看', + 'cons.hmModeAria': '热力图查看维度', + 'cons.hmModeDay': '日', + 'cons.hmModeWeek': '周', + 'cons.hmModeMonth': '月', + 'cons.hmModeAll': '全部', 'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看', 'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看', 'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看', @@ -882,6 +886,12 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'chart.trend.hmMore': '多', 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', 'chart.trend.hmActiveZero': '活跃 0/{total} 天', + 'chart.trend.hmWeekPeak': '活跃 {active}/{total} 周 · 峰值 {label} · {tokens}', + 'chart.trend.hmWeekZero': '活跃 0/{total} 周', + 'chart.trend.hmMonthPeak': '活跃 {active}/{total} 月 · 峰值 {label} · {tokens}', + 'chart.trend.hmMonthZero': '活跃 0/{total} 月', + 'chart.trend.hmCumSummary': '累计 {days} 天 · 总计 {tokens} · {cost}', + 'chart.trend.hmCumThrough': '截至 {date} 累计', 'chart.trend.peakPill': '峰值 {label} · {tokens}', // Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl) diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 29c22ae..cc7e829 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -352,6 +352,31 @@ } /* --- 4. 历史趋势交互式 SVG 平滑曲线图 (Interactive Historical Trend SVG Chart) --- */ +.cons-trend-head { + flex-wrap: wrap; + gap: 6px; +} + +.cons-trend-head-right { + display: inline-flex; + align-items: center; + margin-left: auto; +} + +.cons-trend-hint[hidden], +.cons-hm-mode-switch[hidden] { + display: none !important; +} + +.cons-hm-mode-switch.segmented { + gap: 1px; +} + +.cons-hm-mode-switch .seg-btn { + padding: 1px 7px; + font-size: var(--fs-xs); +} + .trend-chart-wrap { position: relative; width: 100%; @@ -801,6 +826,20 @@ z-index: 2; } +.trend-hm-cell.is-bar-hovered { + filter: brightness(1.22); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 52%, transparent); + z-index: 2; +} + +.trend-hm-cell.is-month-edge:not(.lv-0) { + box-shadow: inset 1px 0 0 color-mix(in srgb, var(--surface-panel) 55%, transparent); +} + +.trend-hm-cell.is-month-edge.is-bar-hovered:not(.lv-0) { + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 52%, transparent); +} + .trend-hm-footer { display: flex; align-items: center; diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 2cba9e5..73a3d0b 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -81,6 +81,16 @@ function getConsumptionTimeRangeOptions() { ]; } +/** 热力图顶栏支持的四档聚合视图选项 */ +function getHeatmapModeOptions() { + return [ + { value: 'day', label: t('cons.hmModeDay') }, + { value: 'week', label: t('cons.hmModeWeek') }, + { value: 'month', label: t('cons.hmModeMonth') }, + { value: 'all', label: t('cons.hmModeAll') }, + ]; +} + function floorToStartOfMinuteMs(ms) { const n = Number(ms); if (!(n > 0)) return 0; @@ -460,14 +470,29 @@ export const ConsumptionView = defineComponent({ }); } - // --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 + 悬停精确日期/小时浮层 + 点击时段下钻) --- + // --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 / 7×W 四态热力格子图 + 悬停明细浮层 + 点击时段下钻) --- + let heatmapViewMode = 'day'; const trendTitleSpan = h('span', { text: t('cons.trendTitle') }); const trendRangeBadge = h('span', { className: 'cons-badge', text: t('cons.allTime') }); const trendGranularityHint = h('span', { - className: 'text-muted text-mono', + className: 'cons-trend-hint text-muted text-mono', style: 'font-size: var(--fs-sm);', text: t('cons.trendPointsHintHourly', { points: 0 }), }); + const heatmapModeSwitch = SegmentedControl({ + ariaLabel: t('cons.hmModeAria'), + modelValue: heatmapViewMode, + options: getHeatmapModeOptions(), + onUpdateModelValue: (nextMode) => { + if (!['day', 'week', 'month', 'all'].includes(nextMode)) return; + heatmapViewMode = nextMode; + heatmapModeSwitch.setValue(nextMode); + trendChart.setHeatmapMode(nextMode); + }, + }); + heatmapModeSwitch.el.classList.add('cons-hm-mode-switch'); + patchAttr(heatmapModeSwitch.el, 'hidden', true); + const trendChart = createTrendAreaChart({ onSelectSlot: (slot) => { if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) { @@ -477,12 +502,15 @@ export const ConsumptionView = defineComponent({ }); const trendPanel = h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [ + h('div', { className: 'panel-header cons-trend-head' }, [ h('span', { className: 'panel-title' }, [ trendTitleSpan, trendRangeBadge, ]), - trendGranularityHint, + h('div', { className: 'cons-trend-head-right' }, [ + trendGranularityHint, + heatmapModeSwitch.el, + ]), ]), trendChart.el, ]); @@ -2204,11 +2232,12 @@ export const ConsumptionView = defineComponent({ (firstTrendSlot?.label || '').includes(':')); const isHeatmapTrend = !isMinuteTrend && !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD; - patchText( - trendGranularityHint, - isHeatmapTrend - ? t('cons.trendHeatmapHint', { days: rawTrendSeries.length }) - : isMinuteTrend + patchAttr(trendGranularityHint, 'hidden', isHeatmapTrend); + patchAttr(heatmapModeSwitch.el, 'hidden', !isHeatmapTrend); + if (!isHeatmapTrend) { + patchText( + trendGranularityHint, + isMinuteTrend ? t('cons.trendPointsHintMinute', { minutes: Math.max(1, Number(firstTrendSlot?.stepMinutes) || 5), points: rawTrendSeries.length || 0, @@ -2216,19 +2245,28 @@ export const ConsumptionView = defineComponent({ : isHourlyTrend ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) - ); + ); + } else { + heatmapModeSwitch.setValue(heatmapViewMode); + } + const buildTrendModelSegments = (mergedSlotModels) => + partitionModelSegments(mergedSlotModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { const mergedSlotModels = trendMergedByIdx[idx]; if (!mergedSlotModels || mergedSlotModels.length === 0) return slot; return { ...slot, - modelSegments: partitionModelSegments(mergedSlotModels, modelColorMap, { - maxMain: 5, - minSharePct: 1.5, - }), + mergedModels: mergedSlotModels, + modelSegments: buildTrendModelSegments(mergedSlotModels), }; }); - trendChart.update(enrichedTrendSeries); + trendChart.update(enrichedTrendSeries, { + heatmapMode: heatmapViewMode, + buildModelSegments: buildTrendModelSegments, + }); // 3. 同步统一排行卡片(分段切换「模型排行 | 项目排行 | 会话排行」及对应排序控制) const sortedTopConvs = [...topConvsWithModels].sort((a, b) => @@ -2563,6 +2601,11 @@ export const ConsumptionView = defineComponent({ md: { label: t('cons.exportMd'), title: t('cons.exportMdTip') }, }); patchText(trendTitleSpan, t('cons.trendTitle')); + heatmapModeSwitch.setProps({ + ariaLabel: t('cons.hmModeAria'), + modelValue: heatmapViewMode, + options: getHeatmapModeOptions(), + }); rankingTabSwitch.setProps({ ariaLabel: t('cons.rankTabAria'), modelValue: activeRankingTab, @@ -2607,6 +2650,7 @@ export const ConsumptionView = defineComponent({ unsubI18n(); consExportMenu.destroy(); cyclePoolSelect.destroy(); + heatmapModeSwitch.destroy(); trendChart.destroy?.(); rankingTabSwitch.destroy(); modelsSortSwitch.destroy(); @@ -2622,6 +2666,8 @@ export const ConsumptionView = defineComponent({ refs: { timeFilterSwitch, cyclePoolSelect, + heatmapModeSwitch, + trendChart, startPicker, endPicker, viewScrollbar, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index cc3e0d5..5834754 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -3151,6 +3151,31 @@ html[data-standalone="true"] .app-shell { } /* --- 4. 历史趋势交互式 SVG 平滑曲线图 (Interactive Historical Trend SVG Chart) --- */ +.cons-trend-head { + flex-wrap: wrap; + gap: 6px; +} + +.cons-trend-head-right { + display: inline-flex; + align-items: center; + margin-left: auto; +} + +.cons-trend-hint[hidden], +.cons-hm-mode-switch[hidden] { + display: none !important; +} + +.cons-hm-mode-switch.segmented { + gap: 1px; +} + +.cons-hm-mode-switch .seg-btn { + padding: 1px 7px; + font-size: var(--fs-xs); +} + .trend-chart-wrap { position: relative; width: 100%; @@ -3600,6 +3625,20 @@ html[data-standalone="true"] .app-shell { z-index: 2; } +.trend-hm-cell.is-bar-hovered { + filter: brightness(1.22); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 52%, transparent); + z-index: 2; +} + +.trend-hm-cell.is-month-edge:not(.lv-0) { + box-shadow: inset 1px 0 0 color-mix(in srgb, var(--surface-panel) 55%, transparent); +} + +.trend-hm-cell.is-month-edge.is-bar-hovered:not(.lv-0) { + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 52%, transparent); +} + .trend-hm-footer { display: flex; align-items: center; diff --git a/sidecars/panel/test/consumption-bars.test.mjs b/sidecars/panel/test/consumption-bars.test.mjs index 54042c6..d602619 100644 --- a/sidecars/panel/test/consumption-bars.test.mjs +++ b/sidecars/panel/test/consumption-bars.test.mjs @@ -736,3 +736,235 @@ test('selectConsumptionTimeRange serves prefetched presets with 0 network calls, ); chart.destroy(); }); + +test('ConsumptionView >90d heatmap replaces static hint with Day/Week/Month/Total 7xW LED matrix switcher, rich tooltips, and drill-down', async (t) => { + const prevLocale = i18nStore.getState().locale; + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const prevTelState = { ...telemetryStore.getState() }; + const prevUiState = { ...uiStore.getState() }; + + const { document } = createMockDom(); + globalThis.document = document; + globalThis.window = { + location: { pathname: '/' }, + addEventListener() {}, + removeEventListener() {}, + requestAnimationFrame: (cb) => setTimeout(cb, 0), + cancelAnimationFrame: (id) => clearTimeout(id), + }; + + let view = null; + t.after(() => { + stopAsyncTelemetryLoop(); + clearConsumptionRangeCache(); + if (view) view.destroy(); + setI18nLanguage(prevLocale); + telemetryStore.setState(prevTelState, { sync: true }); + uiStore.setState(prevUiState, { sync: true }); + globalThis.document = prevDoc; + globalThis.window = prevWin; + }); + + t.mock.method(globalThis, 'fetch', async () => ({ + ok: true, + json: async () => ({ scope: 'noop' }), + })); + + setI18nLanguage('zh-CN'); + uiStore.setState( + { monitorVisible: true, activeView: 'consumption', settingsOpen: false }, + { sync: true } + ); + + // Build 105 daily slots (15 exact weeks starting Monday 2026-08-03 local midnight) + const firstMondayMs = new Date(2026, 7, 3, 0, 0, 0, 0).getTime(); + const dayMs = 86_400_000; + const pad2 = (n) => String(n).padStart(2, '0'); + const trendSlots = Array.from({ length: 105 }, (_, i) => { + const sMs = firstMondayMs + i * dayMs; + const d = new Date(sMs); + const lbl = `${pad2(d.getMonth() + 1)}/${pad2(d.getDate())}`; + const weekIdx = Math.floor(i / 7); + // Week 0 = 0 tokens; Week 1 = 20k/day (140k total); Week 2 = peak 100k/day (700k total); others = 40k/day + const dailyTok = + weekIdx === 0 ? 0 : weekIdx === 1 ? 20_000 : weekIdx === 2 ? 100_000 : 40_000; + return { + index: i, + granularity: 'day', + startMs: sMs, + endMs: sMs + dayMs, + label: lbl, + fullLabel: lbl, + tokens: dailyTok, + inputTokens: Math.floor(dailyTok * 0.25), + cacheReadTokens: Math.floor(dailyTok * 0.5), + thinkingTokens: Math.floor(dailyTok * 0.1), + responseTokens: Math.floor(dailyTok * 0.15), + outputTokens: Math.floor(dailyTok * 0.25), + calls: dailyTok > 0 ? 4 : 0, + costUsd: dailyTok > 0 ? +(dailyTok / 100_000).toFixed(2) : 0, + models: + dailyTok > 0 + ? [ + { + label: 'Claude Opus 4.6', + shortName: 'Opus 4.6', + upstreamName: 'opus-4-6', + calls: 4, + inputTokens: Math.floor(dailyTok * 0.25), + cacheReadTokens: Math.floor(dailyTok * 0.5), + thinkingTokens: Math.floor(dailyTok * 0.1), + responseTokens: Math.floor(dailyTok * 0.15), + outputTokens: Math.floor(dailyTok * 0.25), + totalTokens: dailyTok, + costUsd: +(dailyTok / 100_000).toFixed(2), + }, + ] + : undefined, + }; + }); + + const makePayload = (rangeKey, slots) => ({ + settings: { language: 'zh-CN', modelDisplayMode: 'short' }, + modelBreakdown: [], + consumption: { + revision: 1, + selectedRange: { + key: rangeKey, + label: rangeKey === 'all' ? '全部时间' : '近 7 天', + startMs: slots[0].startMs, + endMs: slots[slots.length - 1].endMs - 1, + }, + account: { + totalTokens: 4_480_000, + inputTokens: 1_120_000, + cacheReadTokens: 2_240_000, + outputTokens: 1_120_000, + responseTokens: 672_000, + thinkingTokens: 448_000, + calls: 392, + costUsd: 44.8, + savedCostUsd: 12.0, + cacheHitPct: 66.7, + }, + trendSeries: slots, + monthlyYear: 2026, + monthlySeries: [], + sourcesBreakdown: [], + }, + }); + + // 1. <=90d (7 days): static hint visible, heatmap switcher hidden + telemetryStore.setState( + { selectedTimeRange: '7d', telemetry: makePayload('7d', trendSlots.slice(0, 7)) }, + { sync: true } + ); + view = ConsumptionView({}); + document.body.appendChild(view.el); + await Promise.resolve(); + + const trendHintEl = view.el.querySelector('.cons-trend-hint'); + const hmSwitchEl = view.refs.heatmapModeSwitch.el; + assert.equal(trendHintEl.hasAttribute('hidden'), false); + assert.equal(hmSwitchEl.hasAttribute('hidden'), true); + + // 2. >90d (105 days = 15 weeks): static hint hidden, 4-way switcher visible ('日' / '周' / '月' / '全部') + telemetryStore.setState( + { selectedTimeRange: 'all', telemetry: makePayload('all', trendSlots) }, + { sync: true } + ); + await Promise.resolve(); + + assert.equal(trendHintEl.hasAttribute('hidden'), true, 'Static heatmap hint must be hidden on >90d'); + assert.equal(hmSwitchEl.hasAttribute('hidden'), false, '4-mode switcher must be shown on >90d'); + const modeBtns = hmSwitchEl.querySelectorAll('.seg-btn'); + assert.deepEqual( + modeBtns.map((b) => b.textContent), + ['日', '周', '月', '全部'] + ); + + const hmWeekdaysEl = view.el.querySelector('.trend-hm-weekdays'); + const hmGridEl = view.el.querySelector('.trend-hm-grid'); + const hmSummaryEl = view.el.querySelector('.trend-hm-summary'); + const trendTip = view.el.querySelector('.trend-tooltip'); + + // Default 'day' mode: weekday labels visible, 105 cells + assert.equal(view.refs.trendChart.getHeatmapMode(), 'day'); + assert.equal(hmWeekdaysEl.style.visibility, ''); + assert.equal(hmGridEl.children.length, 105); + assert.match(hmSummaryEl.textContent || '', /活跃 98\/105 天/); + + // 3. Switch to 'week' mode: keeps exact 105-cell (7x15) grid, hides weekday labels in-place, lights bottom-up LED columns + modeBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(view.refs.trendChart.getHeatmapMode(), 'week'); + assert.equal(hmWeekdaysEl.style.visibility, 'hidden'); + assert.equal(hmGridEl.children.length, 105); + assert.match(hmSummaryEl.textContent || '', /活跃 14\/15 周/); + + const colCells = (col) => + [...hmGridEl.children].filter((c) => Number(c.getAttribute('data-hm-col')) === col); + const litRowsInCol = (col) => + colCells(col) + .filter((c) => !c.classList.contains('lv-0')) + .map((c) => Number(c.getAttribute('data-hm-row'))); + + // Week 0 has 0 tokens -> 0 lit rows; Week 1 has 140k/700k = 20% -> ceil(1.4) = 2 bottom rows [5, 6]; Week 2 is peak 700k -> all 7 rows [0..6] + assert.deepEqual(litRowsInCol(0), []); + assert.deepEqual(litRowsInCol(1), [5, 6]); + assert.deepEqual(litRowsInCol(2), [0, 1, 2, 3, 4, 5, 6]); + + // Hovering top unlit cell (row 0) of Week 1 still highlights Week 1's lit bar [row 5, row 6] and shows aggregated weekly tooltip + hmGridEl.dispatchEvent({ type: 'mouseover', target: colCells(1)[0], clientX: 40, clientY: 20 }); + assert.equal(trendTip.hasAttribute('hidden'), false); + assert.equal(trendTip.querySelector('.trend-tip-time')?.textContent, '8月10日 ~ 16日'); + assert.match(trendTip.querySelector('.trend-tip-tokens')?.textContent || '', /140\.0k TOKEN/); + assert.equal(trendTip.querySelectorAll('.cons-pop-model-row').length, 1); + assert.equal(colCells(1)[5].classList.contains('is-bar-hovered'), true); + assert.equal(colCells(1)[6].classList.contains('is-bar-hovered'), true); + assert.equal(colCells(1)[0].classList.contains('is-bar-hovered'), false); + + // 4. Switch to 'month' mode: columns group by dominant calendar month with month-edge markers and monthly tooltip + modeBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(view.refs.trendChart.getHeatmapMode(), 'month'); + assert.equal(hmGridEl.children.length, 105); + assert.match(hmSummaryEl.textContent || '', /月 · 峰值/); + assert.ok( + [...hmGridEl.children].some((c) => c.classList.contains('is-month-edge')), + 'Month mode should mark boundary columns between adjacent months' + ); + hmGridEl.dispatchEvent({ type: 'mouseover', target: colCells(0)[6], clientX: 20, clientY: 60 }); + assert.equal(trendTip.querySelector('.trend-tip-time')?.textContent, '2026年 8月'); + + // 5. Switch to 'all' (cumulative) mode: monotonic bottom-up growth ramp reaching 7 rows on last column + modeBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(view.refs.trendChart.getHeatmapMode(), 'all'); + assert.equal(hmGridEl.children.length, 105); + let prevLitCount = 0; + for (let col = 0; col < 15; col++) { + const cnt = litRowsInCol(col).length; + assert.ok(cnt >= prevLitCount, `Cumulative column ${col} must be non-decreasing`); + prevLitCount = cnt; + } + assert.equal(prevLitCount, 7, 'Final cumulative column must reach full 7-row height'); + hmGridEl.dispatchEvent({ type: 'mouseover', target: colCells(14)[0], clientX: 200, clientY: 20 }); + assert.match(trendTip.querySelector('.trend-tip-time')?.textContent || '', /^截至 .+ 累计$/); + assert.match(hmSummaryEl.textContent || '', /^累计 105 天/); + + // 6. Locale switch updates switcher labels ('Day' / 'Week' / 'Month' / 'Total') and summary text + setI18nLanguage('en-US'); + await Promise.resolve(); + assert.deepEqual( + hmSwitchEl.querySelectorAll('.seg-btn').map((b) => b.textContent), + ['Day', 'Week', 'Month', 'Total'] + ); + assert.match(hmSummaryEl.textContent || '', /^Cumulative 105d/); + + // 7. Clicking a week bar in 'week' mode drills down into custom time range for that week + setI18nLanguage('zh-CN'); + await Promise.resolve(); + hmSwitchEl.querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} }); + hmGridEl.dispatchEvent({ type: 'click', target: colCells(2)[3], clientX: 60, clientY: 40 }); + assert.equal(telemetryStore.getState().selectedTimeRange, 'custom'); + assert.equal(telemetryStore.getState().customStartMs, firstMondayMs + 14 * dayMs); +}); From 20bd48d363a64986ce912003625ffd8144192eef Mon Sep 17 00:00:00 2001 From: Ya6e <141900348+Ya6e@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:04:43 +0800 Subject: [PATCH 20/30] fix(panel): probe live IDE chat iframe DOM route in dual mount mode --- sidecars/panel/backend/window-bridge.mjs | 100 ++++++++- sidecars/panel/test/window-bridge.test.mjs | 239 +++++++++++++++++++++ 2 files changed, 337 insertions(+), 2 deletions(-) diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index bf96b6c..a76dbd8 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -2248,6 +2248,98 @@ export function createWindowBridgeController(options) { } })()`; + const ideChatRouteProbeExpr = `(() => { + try { + const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + const visible = Boolean( + (window.innerWidth === undefined || Number(window.innerWidth) > 80) && + (window.innerHeight === undefined || Number(window.innerHeight) > 80) && + !(typeof document !== 'undefined' && document?.hidden === true) + ); + const focused = Boolean( + typeof document !== 'undefined' && typeof document.hasFocus === 'function' && document.hasFocus() + ); + let routeCascadeId = ''; + const m = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i); + if (m && uuidRe.test(m[1])) { + routeCascadeId = m[1]; + } else if (typeof document !== 'undefined' && typeof document.querySelector === 'function') { + const selectedRow = document.querySelector( + '[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]' + ); + const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim(); + if (typeof document.querySelectorAll === 'function') { + const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]'); + const visibleIds = []; + let focusedId = ''; + const activeEl = document.activeElement || null; + for (const viewEl of views) { + const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim(); + if (!uuidRe.test(cid)) continue; + if (viewEl.hasAttribute?.('hidden')) continue; + if (viewEl.getBoundingClientRect) { + const r = viewEl.getBoundingClientRect(); + if (r.width <= 0 && r.height <= 0) continue; + } + visibleIds.push(cid); + if (activeEl && viewEl.contains?.(activeEl)) { + focusedId = cid; + } + } + if (focusedId) { + routeCascadeId = focusedId; + } else if ( + selectedRowId && + uuidRe.test(selectedRowId) && + visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase()) + ) { + routeCascadeId = selectedRowId; + } else if (visibleIds.length > 0) { + routeCascadeId = visibleIds[0]; + } + } + if (!routeCascadeId) { + const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]'); + const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim(); + if (uuidRe.test(singleViewId)) { + routeCascadeId = singleViewId; + } else if (uuidRe.test(selectedRowId)) { + routeCascadeId = selectedRowId; + } + } + } + return { routeCascadeId, visible, focused }; + } catch { + return { routeCascadeId: '', visible: false, focused: false }; + } + })()`; + + async function resolveIdeWorkbenchRouteId(targetObj) { + const staticRouteId = String(targetObj?.ideRouteCascadeId || '').trim(); + const chatList = Array.isArray(targetObj?.ideChatTargets) ? targetObj.ideChatTargets : []; + let bestRouteId = ''; + let bestRank = 0; + for (const chatTarget of chatList) { + const chatWsUrl = String(chatTarget?.webSocketDebuggerUrl || '').trim(); + if (!chatWsUrl) continue; + try { + const res = await evaluateOnTarget(chatWsUrl, ideChatRouteProbeExpr); + const val = res?.result?.result?.value; + const cid = String(val?.routeCascadeId || '').trim(); + if (!cid) continue; + const rank = val?.focused && val?.visible ? 3 : val?.visible ? 2 : 1; + if (rank > bestRank) { + bestRank = rank; + bestRouteId = cid; + if (bestRank === 3) break; + } + } catch { + // 单个聊天子视图探测异常不阻断其他视图与静态路由兜底 + } + } + return bestRouteId || staticRouteId; + } + let cachedAssets = null; let injected = 0; let aliveCount = 0; @@ -2456,12 +2548,16 @@ export function createWindowBridgeController(options) { if (chatComposerActive) { await disposeSingleTarget(target.webSocketDebuggerUrl); } else { - await syncSingleTarget(target); + const ideRouteOverride = await resolveIdeWorkbenchRouteId(target); + await syncSingleTarget(target, { ideRouteOverride }); } continue; } - await syncSingleTarget(target); + const ideRouteOverride = target.isIdeWorkbench + ? await resolveIdeWorkbenchRouteId(target) + : ''; + await syncSingleTarget(target, { ideRouteOverride }); } catch { // 单个窗口注入异常不阻断其他窗口 } diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index ee78cb0..61b9ade 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -6323,3 +6323,242 @@ test('Issue #35: topbar capsule and hover HUD lock to main agent by default, tog ov?.dispose?.(); } }); + +test('Antigravity IDE dual mode (双栖挂载) probes live chat iframe DOM cascade ID and syncs workbench.html on conversation switch', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-ide-dual-route-')); + const roamingDir = path.join(tmpDir, 'Roaming'); + fs.mkdirSync(path.join(roamingDir, 'Antigravity IDE'), { recursive: true }); + + const convA = '11111111-aaaa-4bbb-8ccc-111111111111'; + const convB = '22222222-bbbb-4ccc-8ddd-222222222222'; + const convC = '33333333-cccc-4ddd-8eee-333333333333'; + const convHidden = '44444444-dddd-4eee-8fff-444444444444'; + + function makeChatFrameCtx({ cascadeId, width = 760, height = 1200, hidden = false, focused = false }) { + const state = { cascadeId, width, height, hidden, focused }; + const makeConvEl = () => ({ + getAttribute: (name) => (name === 'data-cascade-id' ? state.cascadeId : null), + hasAttribute: (name) => (name === 'hidden' ? state.hidden : false), + getBoundingClientRect: () => ({ + width: state.hidden ? 0 : state.width, + height: state.hidden ? 0 : state.height, + }), + contains: () => false, + }); + const winObj = { + get innerWidth() { + return state.hidden ? 0 : state.width; + }, + get innerHeight() { + return state.hidden ? 0 : state.height; + }, + location: { pathname: '/', href: 'http://127.0.0.1:56598/?extensionView=true&extensionVariant=vs-code' }, + }; + const docObj = { + get hidden() { + return state.hidden; + }, + activeElement: null, + hasFocus: () => state.focused, + querySelector: (sel) => { + if (!state.cascadeId) return null; + if (sel.includes('conversation-view') || sel.includes('conversation-row-')) { + return makeConvEl(); + } + return null; + }, + querySelectorAll: (sel) => { + if (!state.cascadeId || !sel.includes('conversation-view')) return []; + return [makeConvEl()]; + }, + }; + const ctx = vm.createContext({ window: winObj, document: docObj, console }); + ctx.window.window = ctx.window; + ctx.window.document = docObj; + return { ctx, state }; + } + + const wbWin = { + innerWidth: 1440, + innerHeight: 900, + location: { pathname: '/out/vs/code/electron-browser/workbench/workbench.html' }, + }; + const wbCtx = vm.createContext({ + window: wbWin, + document: { hidden: false, querySelector: () => null, querySelectorAll: () => [] }, + console, + }); + wbCtx.window.window = wbCtx.window; + + const chat1 = makeChatFrameCtx({ cascadeId: convA, focused: true }); + const chat2 = makeChatFrameCtx({ cascadeId: convHidden, hidden: true, focused: false }); + let includeSecondChat = false; + + const ctxByPath = { + '/devtools/page/WB-1': wbCtx, + '/devtools/page/CHAT-1': chat1.ctx, + '/devtools/page/CHAT-2': chat2.ctx, + }; + + class DualRouteMockWS { + constructor(url) { + this.url = url; + this.listeners = new Map(); + queueMicrotask(() => this._emit('open', {})); + } + addEventListener(type, fn) { + if (!this.listeners.has(type)) this.listeners.set(type, []); + this.listeners.get(type).push(fn); + } + send(raw) { + const msg = JSON.parse(raw); + if (msg.method === 'Runtime.evaluate') { + const pathname = new URL(this.url).pathname; + const targetCtx = ctxByPath[pathname]; + try { + const val = vm.runInContext(msg.params.expression, targetCtx); + queueMicrotask(() => + this._emit('message', { + data: JSON.stringify({ id: msg.id, result: { result: { value: val } } }), + }) + ); + } catch (err) { + queueMicrotask(() => + this._emit('message', { + data: JSON.stringify({ + id: msg.id, + result: { exceptionDetails: { text: err.message } }, + }), + }) + ); + } + } + } + close() {} + _emit(type, ev) { + for (const fn of this.listeners.get(type) || []) fn(ev); + } + } + + const cdpSrv = http.createServer((req, res) => { + if (req.url === '/json/list') { + const p = cdpSrv.address().port; + const targets = [ + { + id: 'WB-1', + type: 'page', + url: 'vscode-file://vscode-app/c:/Antigravity%20IDE/resources/app/out/vs/code/electron-browser/workbench/workbench.html', + webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/WB-1`, + }, + { + id: 'WV-1', + parentId: 'WB-1', + type: 'iframe', + url: 'vscode-webview://1234/index.html?purpose=webviewView', + }, + { + id: 'CHAT-1', + parentId: 'WV-1', + type: 'iframe', + url: 'http://127.0.0.1:56598/?extensionView=true&extensionVariant=vs-code&hostVariant=antigravity-ide', + webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/CHAT-1`, + }, + ]; + if (includeSecondChat) { + targets.splice(2, 0, { + id: 'CHAT-2', + parentId: 'WV-1', + type: 'iframe', + url: 'http://127.0.0.1:56598/?extensionView=true&extensionVariant=vs-code&hostVariant=antigravity-ide', + webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/CHAT-2`, + }); + } + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(targets)); + return; + } + res.writeHead(404); + res.end(); + }); + + await new Promise((resolve) => cdpSrv.listen(0, '127.0.0.1', resolve)); + fs.writeFileSync( + path.join(roamingDir, 'Antigravity IDE', 'DevToolsActivePort'), + `${cdpSrv.address().port}\n/devtools/browser/ide-dual-route`, + 'utf8' + ); + + const requestedConvIds = []; + const mockDualAppJs = ` + (() => { + const br = window.__AGUsageMonitorBridge; + let alive = true; + window.__syncHostRouteHistory = []; + window.__AGUsageMonitorOverlay = { + bundleVersion: br.bundleVersion, + ensureAlive: () => alive, + getDockKind: () => 'ide-titlebar', + getMountMode: () => 'dual', + applyMountMode: () => alive, + syncHostRoute: () => { + window.__syncHostRouteHistory.push(String(br.hostRouteCascadeId || '')); + }, + dispose: () => { alive = false; }, + }; + })(); + `; + + const bridgeCtrl = createWindowBridgeController({ + handleApiRequest: async (apiPath, _method, body) => { + if (apiPath === '/api/telemetry') { + requestedConvIds.push(String(body?.conversationId || '')); + } + return { + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + settings: { windowMountMode: 'dual', enableWindowOverlay: true }, + }), + }; + }, + readAssetFn: async (rel) => (rel === 'styles.css' ? ':host{}' : mockDualAppJs), + getSettingsFn: () => ({ windowMountMode: 'dual', enableWindowOverlay: true }), + getBundleVersionFn: () => 'dual-route-v1', + env: { APPDATA: roamingDir, LOCALAPPDATA: tmpDir }, + platform: 'win32', + homeDir: tmpDir, + WebSocketImpl: DualRouteMockWS, + }); + + try { + // 1. Initial sync in dual mode: chat iframe URL has no /c/, route is probed from DOM + await bridgeCtrl.syncAllWindows(); + assert.equal(requestedConvIds[0], convA, 'Initial telemetry prefetch uses live DOM cascade ID from IDE chat iframe'); + assert.equal(wbCtx.window.__AGUsageMonitorBridge.hostRouteCascadeId, convA); + assert.equal(Boolean(chat1.ctx.window.__AGUsageMonitorOverlay), false, 'Chat iframe is not injected in dual mode'); + + // 2. User switches conversation inside IDE chat iframe (URL stays /?extensionView=true, DOM updates to convB) + chat1.state.cascadeId = convB; + await bridgeCtrl.syncAllWindows(); + assert.equal(wbCtx.window.__AGUsageMonitorBridge.hostRouteCascadeId, convB); + assert.deepEqual( + Array.from(wbCtx.window.__syncHostRouteHistory), + [convB], + 'syncHostRoute() is invoked on workbench.html after conversation switch' + ); + + // 3. When a hidden chat iframe appears ahead of the visible/focused chat iframe, prefer visible/focused + includeSecondChat = true; + chat1.state.cascadeId = convC; + chat1.state.focused = true; + chat2.state.cascadeId = convHidden; + chat2.state.hidden = true; + await bridgeCtrl.syncAllWindows(); + assert.equal(wbCtx.window.__AGUsageMonitorBridge.hostRouteCascadeId, convC); + assert.deepEqual(Array.from(wbCtx.window.__syncHostRouteHistory), [convB, convC]); + } finally { + await bridgeCtrl.stop(); + await new Promise((resolve) => cdpSrv.close(resolve)); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); From 1330b31ef7d02a5fef3b1963e9213f9e527c0c4d Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 22:38:24 +0900 Subject: [PATCH 21/30] feat(account): add multi-account switcher and passphrase vault - Enable Windows multi-account sign-in via loopback PKCE OAuth and unified borderless quota cards with Ultra 5x/20x tier detection and instant cached-list preloading - Keep active-account quota strictly on live host telemetry while supporting configurable background OAuth refresh intervals (10m-24h, default 1h) for saved backup accounts - Add optional scrypt + AES-256-GCM secondary passphrase encryption with per-email AAD binding, unlock backoff, key zeroing, at-rest token minimization, and OAuth client_id allowlisting - Harden account mutations with inline two-step switch/remove confirmations, HMAC action nonces, Webview context checks, standalone web 403 isolation, and user-only vault directory ACLs --- README.md | 1 + README.zh-CN.md | 1 + sidecars/panel/app.js | 1577 ++++++++++++++++- .../panel/backend/account-credentials.ps1 | 337 +++- sidecars/panel/backend/account-http.mjs | 67 + sidecars/panel/backend/account-login.mjs | 168 ++ sidecars/panel/backend/account-oauth.mjs | 513 +++++- sidecars/panel/backend/account-switch.mjs | 804 ++++++++- .../panel/backend/account-vault-crypto.mjs | 245 +++ sidecars/panel/backend/api-actions.mjs | 48 +- sidecars/panel/backend/settings-schema.mjs | 10 + sidecars/panel/backend/standalone-server.mjs | 13 + sidecars/panel/index.html | 4 +- sidecars/panel/main.mjs | 12 + sidecars/panel/scripts/build-bundle.mjs | 1 + .../panel/shared/settings-normalization.mjs | 16 + sidecars/panel/src/core/settingsBackup.js | 2 + sidecars/panel/src/i18n/en-US.js | 72 +- sidecars/panel/src/i18n/zh-CN.js | 74 +- sidecars/panel/src/icons/svgRegistry.js | 9 + sidecars/panel/src/store/telemetryStore.js | 13 + sidecars/panel/src/styles/views-settings.css | 478 +++++ sidecars/panel/src/views/SettingsView.js | 17 +- .../src/views/settings/SettingsAccountTab.js | 1415 +++++++++++++-- sidecars/panel/styles.css | 478 +++++ sidecars/panel/test/account-login.test.mjs | 131 ++ sidecars/panel/test/account-switch.test.mjs | 497 +++++- sidecars/panel/test/backend-harness.mjs | 15 +- .../test/cross-module-regressions.test.mjs | 8 +- .../test/practical-enhancements.test.mjs | 6 +- sidecars/panel/test/release-pack.test.mjs | 4 +- sidecars/panel/test/window-bridge.test.mjs | 65 +- 32 files changed, 6737 insertions(+), 364 deletions(-) create mode 100644 sidecars/panel/backend/account-http.mjs create mode 100644 sidecars/panel/backend/account-login.mjs create mode 100644 sidecars/panel/backend/account-vault-crypto.mjs create mode 100644 sidecars/panel/test/account-login.test.mjs diff --git a/README.md b/README.md index 66790d1..495a55b 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ English · [简体中文](README.zh-CN.md) - **Live Metrics & Customizable Layout**: Tracks output speed (`tok/s`), time-to-first-token (`TTFT`), session average speed, step/session USD cost, cache hit rate, tightest remaining quota, and session tokens. You can choose and reorder the overview metric cards (4 shown by default out of 9 options) and section blocks. - **10-Category Context Breakdown**: Shows the token breakdown of the latest request across assistant replies, tool results, user messages, subagent notifications, checkpoints, system prompts, system tools, MCP tools, skills, and user rules, with a switcher between the main agent and spawned subagents. - **Quota Pool Tracking, Lease Reservation & Burn-Rate Reference**: Reads 5-hour and weekly quotas, reset timers, and cycle consumption across `Gemini`, `Gemini 4 Argon`, `Gemini 4 Carbon`, and `Claude & GPT` pools (plus Ultra `5x / 20x` tier badges), renders an in-flight lease reservation segment with an account-isolated per-model burn-rate & equivalent full-pool cost popover (`?`), and preserves cached quota data with a stale notice when upstream is temporarily unavailable. +- **Account Sign-in and Switching on Windows**: Choose Sign in with Google under Preferences → Account. Browser authorization automatically adds the account and loads its quota. Existing refresh tokens and OAuth JSON can also be imported. Switch and restart closes and reopens the App and newer IDE sharing its sign-in. Save your work before switching. - **Main Agent, Subagents, Swarm & SSH Isolation**: Merges main agent, subagent, and Native Swarm worker steps in chronological order (or filters by individual agent), renders optional turn rails, expands running tasks inline, and isolates per-window caches and quotas across multiple SSH Remote windows (`endpointId`). - **Call Details, Timing Tooltips & Anomaly Chips**: Includes **By Step** and **By Model** tabs (with multi-model LOESS throughput/TTFT fit charts), clickable column sorting, hover TTFT/duration stage breakdowns, accent-highlighted compaction rows with diagnostic tooltips, and an optional live search & 9-category anomaly/compaction/low-cache/slow-TTFT filter toolbar. Supports 2–14 configurable columns and custom token DSL strings such as `context:in:cache`. - **Historical Usage, Project Attribution & Heatmap**: Summarizes tokens, uncached input vs. cache-read savings, thinking/output split, smooth hourly/daily trend curves (switching automatically to a GitHub-style daily calendar heatmap over `>90` days), **Model / Project (Workspace) / Session** rankings, client attribution (`Desktop App` / `IDE` / `CLI`), and monthly bar charts with pointer-following breakdown popovers across `Today`, `1d`, `7d`, `14d`, `30d`, `All`, or custom date/time ranges. diff --git a/README.zh-CN.md b/README.zh-CN.md index 77b89f0..847a489 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -34,6 +34,7 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、 - **实时指标与版面编排**:统计单步输出速度(`tok/s`)、首字延迟(`TTFT`)、会话平均速度、单步/累计费用、缓存命中率、最紧缺配额与已用 Token;可在设置中从 9 项指标中自由勾选并拖拽排序(默认展示 4 项),并调整实时监控各模块顺序。 - **10 类上下文窗口构成**:展示最近一次请求的上下文占比,按占用列出模型回复、工具结果、用户消息、子代理通知、压缩摘要、系统提示词、系统工具、MCP 工具、Skill 与用户规则,支持在主代理与任意子代理之间切换查看。 - **配额池监控、预占估算及速率参考**:追踪 `Gemini`、`Gemini 4 Argon`、`Gemini 4 Carbon` 及 `Claude & GPT` 配额池的 5 小时及每周用量、重置倒计时、周期累计消耗及 Ultra `5x / 20x` 倍率标识;内置租约预占斜纹指示段及按账号隔离的模型消耗速率/等效满池费用悬浮卡(`?`),上游暂未返回新数据时保留缓存状态及提示。 +- **账号登录及切换(Windows)**:在「偏好设置 → 账号」点击「使用 Google 登录」,通过浏览器授权后自动保存账号并查询额度;也支持导入已有刷新令牌或 OAuth JSON。「切换并重启」关闭并重开 App 和共享登录的新版 IDE,以载入选定凭证,切换前请保存工作。 - **主/子代理、Swarm 蜂群及 SSH 多远端隔离**:按时间归并展示主代理、子代理及原生 Swarm Worker 调用步骤(也可按单一代理过滤),支持轮次分组导轨及运行中任务原地展开,并对多个 SSH Remote 远端窗口按端点独立隔离轨迹缓存及配额状态。 - **调用明细、耗时拆解及异常筛选**:包含「按步查看」及「按模型汇总」(含多模型 LOESS 吞吐/TTFT 拟合曲线);支持表头点击排序、首字延迟/总耗时分阶段悬停拆解、压缩行强调色高亮及悬停诊断、可选实时搜索及 9 类异常/慢首字/低缓存快捷诊断筛选条;支持定制 2–14 列及 `context:in:cache` 等自定义 Token 语法。 - **历史用量、项目工作区归因及日历热力图**:按今天、1 天、7 天、14 天、30 天、全部或自定义时间窗统计总 Token、缓存节省金额、输出/思考拆分、平滑小时/日趋势折线(跨度 `>90` 天自动切换为每日日历热力图)、**模型 / 项目工作区 / 会话**三合一排行、客户端来源(App / IDE / CLI)及月度堆叠柱状图,均配备跟手悬浮明细卡。 diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 5db436b..e9a6cde 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, normalizeExperimentalQuotaReservation, 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, ACCOUNT_QUOTA_REFRESH_MINUTES, DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, normalizeAccountQuotaRefreshMinutes, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi } = (() => { /** * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 */ @@ -551,6 +551,22 @@ function normalizeModernUi(val) { const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']); const DEFAULT_CONTEXT_AGENT_MODE = 'main'; +const ACCOUNT_QUOTA_REFRESH_MINUTES = Object.freeze([10, 30, 60, 180, 360, 720, 1440]); +const DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES = 60; + +/** + * 归一化非当前账号的后台配额刷新间隔(分钟,默认 `60` 即 1 小时)。 + * + * @param {unknown} raw + * @returns {10|30|60|180|360|720|1440} + */ +function normalizeAccountQuotaRefreshMinutes(raw) { + const num = Number(raw); + return ACCOUNT_QUOTA_REFRESH_MINUTES.includes(num) + ? /** @type {any} */ (num) + : DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES; +} + /** * 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'main'` 锁定主代理,可选 `'auto'` 跟随活跃)。 * @@ -592,7 +608,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, normalizeExperimentalQuotaReservation, 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, ACCOUNT_QUOTA_REFRESH_MINUTES, DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, normalizeAccountQuotaRefreshMinutes, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, normalizeExperimentalModernUi }; })(); // --- shared/telemetry-display-rules.mjs --- @@ -1079,6 +1095,15 @@ const SVG_ICON_DEFS = Object.freeze({ { tag: 'circle', attrs: { cx: '6', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } }, ], + lock: [ + { tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } }, + { tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.6 0V7' } }, + { tag: 'circle', attrs: { cx: '8', cy: '10.5', r: '0.9', fill: 'currentColor', stroke: 'none' } }, + ], + unlock: [ + { tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } }, + { tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.3-1.2' } }, + ], }); return { SVG_ICON_DEFS }; })(); @@ -1752,26 +1777,54 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.account.signedOut': '未登录', 'settings.account.unknown': '暂未获取账号状态', 'settings.account.email': '账号邮箱', + 'settings.account.googleLogin': '使用 Google 登录', + 'settings.account.loginHint': '通过浏览器登录 Google,完成后账号会自动添加到列表。', + 'settings.account.loginWaiting': '请在浏览器中选择 Google 账号并完成授权,完成后这里会自动更新。', + 'settings.account.loginFinishing': '授权已收到,正在保存账号…', + 'settings.account.loginSuccess': '登录成功,账号已添加。', + 'settings.account.loginCancelled': '已取消本次登录。', + 'settings.account.loginExpired': '登录已超时,请重新点击「使用 Google 登录」。', + 'settings.account.loginDenied': 'Google 授权已取消,请重新登录。', + 'settings.account.loginStartFailed': '未能开始登录,请重试。', + 'settings.account.loginExchangeFailed': '未能完成登录,请检查网络后重新授权。', + 'settings.account.openLoginPage': '重新打开 Google 授权页面', + 'settings.account.cancelLogin': '取消登录', + 'settings.account.importExisting': '导入已有凭证', 'settings.account.credential': 'OAuth 凭证', + 'settings.account.credentialPlaceholder': '粘贴 1// 刷新令牌或 OAuth JSON…', 'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。', 'settings.account.save': '导入凭证', 'settings.account.capture': '保存当前凭证', 'settings.account.reload': '刷新列表', - 'settings.account.switch': '切换', + 'settings.account.switch': '切换并重启', + 'settings.account.switchHint': '切换会关闭并重新打开 Antigravity App 和共享登录的 IDE,请先保存工作。', + 'settings.account.restarting': '正在重启 Antigravity 并应用所选账号…', + 'settings.account.switchStartFailed': '未能启动切号,请刷新列表后重试。', + 'settings.account.clientCloseFailed': 'Antigravity 未能完全退出,切换未完成。', + 'settings.account.clientRestartFailed': '凭证已更新,但自动重新打开失败,请手动打开 Antigravity。', 'settings.account.remove': '移除', 'settings.account.active': '当前使用', + 'settings.account.savedBadge': '已备份', 'settings.account.written': '凭证已写入', 'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。', - 'settings.account.savedCredentials': '已保存的凭证', + 'settings.account.savedCredentials': '已保存的账号', 'settings.account.empty': '暂无已保存的凭证。', 'settings.account.loading': '正在读取已保存的凭证…', 'settings.account.saved': '凭证已保存。', 'settings.account.removed': '已移除保存的凭证。', 'settings.account.switched': '已切换账号,正在刷新当前额度。', - 'settings.account.switching': '正在替换凭证并确认宿主账号…', + 'settings.account.switching': '正在验证凭证并准备重启…', 'settings.account.verifying': '正在验证凭证所属账号…', 'settings.account.loadQuota': '查额度', - 'settings.account.loadingQuota': '正在查询此凭证的额度…', + 'settings.account.loadingQuota': '查询中…', + 'settings.account.refreshFreqAria': '非当前账号配额刷新间隔', + 'settings.account.refresh10m': '10 分钟', + 'settings.account.refresh30m': '30 分钟', + 'settings.account.refresh1h': '1 小时', + 'settings.account.refresh3h': '3 小时', + 'settings.account.refresh6h': '6 小时', + 'settings.account.refresh12h': '12 小时', + 'settings.account.refresh24h': '24 小时', 'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。', 'settings.account.quota': '额度池剩余', 'settings.account.quota5h': '5 小时 {percent}%', @@ -1790,10 +1843,46 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。', 'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。', 'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。', - 'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。', + 'settings.account.identityMismatch': '凭证所属账号跟宿主或保存的账号不一致,请重新导入该凭证。', 'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。', 'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。', 'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。', + 'settings.account.switchConfirm': '确认切换', + 'settings.account.removeConfirm': '确认移除', + 'settings.account.pwdBtnSet': '二级密码', + 'settings.account.pwdBtnManage': '密码设置', + 'settings.account.lockNow': '锁定', + 'settings.account.lockNowTip': '立即锁定凭证库', + 'settings.account.unlockBtn': '解锁', + 'settings.account.unlockPlaceholder': '输入二级密码解锁…', + 'settings.account.vaultLockedHint': '凭证库已加密锁定,输入二级密码后可切换账号、管理凭证和刷新后台配额。', + 'settings.account.forgotPwdToggle': '忘记密码?', + 'settings.account.resetVaultHint': '二级密码采用真实密钥派生加密,遗忘后无法解密旧备份(不影响当前正在使用的账号),可清空凭证库后重新添加。', + 'settings.account.resetVaultBtn': '清空凭证库', + 'settings.account.resetVaultConfirm': '确认清空重置', + 'settings.account.pwdTabChange': '修改密码', + 'settings.account.pwdTabDisable': '关闭密码', + 'settings.account.pwdCurrentPlaceholder': '当前二级密码…', + 'settings.account.pwdNewPlaceholder': '设置二级密码(4~128 位)…', + 'settings.account.pwdConfirmPlaceholder': '再次确认密码…', + 'settings.account.pwdEnableSubmit': '启用加密', + 'settings.account.pwdChangeSubmit': '更新密码', + 'settings.account.pwdDisableSubmit': '关闭保护', + 'settings.account.pwdSetHint': '使用二级密码对所有已存刷新令牌追加一层加密,每次启动首次操作时解锁一次;请牢记密码,遗忘后无法找回备份。', + 'settings.account.pwdManageHint': '验证当前二级密码后可更换新密码,或退回系统默认加密。', + 'settings.account.pwdEnabledToast': '已启用二级密码加密。', + 'settings.account.pwdChangedToast': '二级密码已更新。', + 'settings.account.pwdDisabledToast': '已关闭二级密码保护。', + 'settings.account.vaultUnlockedToast': '凭证库已解锁。', + 'settings.account.vaultLockedToast': '凭证库已锁定。', + 'settings.account.vaultResetToast': '凭证库已清空重置。', + 'settings.account.vaultLocked': '请先输入二级密码解锁凭证库。', + 'settings.account.wrongPassword': '二级密码不正确,请核对后重试。', + 'settings.account.invalidPassword': '密码长度需在 4 到 128 个字符之间且不能全为空格。', + 'settings.account.passwordMismatch': '两次输入的密码不一致。', + 'settings.account.passwordRateLimited': '密码连续输错次数过多,请稍候再试。', + 'settings.account.vaultDecryptFailed': '凭证解密校验失败,请确认密码或重置凭证库。', + 'settings.account.invalidActionNonce': '安全校验令牌已过期,请重试。', 'settings.saving': '保存中…', 'settings.saved': '已保存', 'settings.saveFailed': '保存失败', @@ -2667,26 +2756,54 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.account.signedOut': 'Signed out', 'settings.account.unknown': 'Account status unavailable', 'settings.account.email': 'Account email', + 'settings.account.googleLogin': 'Sign in with Google', + 'settings.account.loginHint': 'Sign in with Google in your browser. The account will appear in this list automatically.', + 'settings.account.loginWaiting': 'Choose a Google account and complete authorization in your browser. This list will update automatically.', + 'settings.account.loginFinishing': 'Authorization received. Saving the account…', + 'settings.account.loginSuccess': 'Signed in. The account has been added.', + 'settings.account.loginCancelled': 'Sign-in cancelled.', + 'settings.account.loginExpired': 'Sign-in expired. Click Sign in with Google to try again.', + 'settings.account.loginDenied': 'Google authorization was cancelled. Try signing in again.', + 'settings.account.loginStartFailed': 'Sign-in could not start. Try again.', + 'settings.account.loginExchangeFailed': 'Sign-in could not finish. Check your connection and authorize again.', + 'settings.account.openLoginPage': 'Reopen Google authorization', + 'settings.account.cancelLogin': 'Cancel sign-in', + 'settings.account.importExisting': 'Import existing credentials', 'settings.account.credential': 'OAuth credential', + 'settings.account.credentialPlaceholder': 'Paste 1// refresh token or OAuth JSON…', 'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.', 'settings.account.save': 'Import credential', 'settings.account.capture': 'Save current credential', 'settings.account.reload': 'Refresh list', - 'settings.account.switch': 'Switch', + 'settings.account.switch': 'Switch and restart', + 'settings.account.switchHint': 'Switching closes and reopens Antigravity App and the IDE sharing its sign-in. Save your work first.', + 'settings.account.restarting': 'Restarting Antigravity with the selected account…', + 'settings.account.switchStartFailed': 'The account switch could not start. Refresh the list and try again.', + 'settings.account.clientCloseFailed': 'Antigravity could not fully exit. The switch is incomplete.', + 'settings.account.clientRestartFailed': 'The credential was updated. Open Antigravity manually to finish switching.', 'settings.account.remove': 'Remove', 'settings.account.active': 'In use', + 'settings.account.savedBadge': 'Backed up', 'settings.account.written': 'Credential written', 'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.', - 'settings.account.savedCredentials': 'Saved credentials', + 'settings.account.savedCredentials': 'Saved accounts', 'settings.account.empty': 'No saved credentials.', 'settings.account.loading': 'Loading saved credentials…', 'settings.account.saved': 'Credential saved.', 'settings.account.removed': 'Saved credential removed.', 'settings.account.switched': 'Account switched. Refreshing the current quota.', - 'settings.account.switching': 'Replacing the credential and confirming the active account…', + 'settings.account.switching': 'Verifying the credential and preparing to restart…', 'settings.account.verifying': 'Verifying the credential owner…', 'settings.account.loadQuota': 'Check quota', - 'settings.account.loadingQuota': 'Checking quota for this credential…', + 'settings.account.loadingQuota': 'Checking…', + 'settings.account.refreshFreqAria': 'Background account quota refresh interval', + 'settings.account.refresh10m': '10 min', + 'settings.account.refresh30m': '30 min', + 'settings.account.refresh1h': '1 hr', + 'settings.account.refresh3h': '3 hr', + 'settings.account.refresh6h': '6 hr', + 'settings.account.refresh12h': '12 hr', + 'settings.account.refresh24h': '24 hr', 'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.', 'settings.account.quota': 'Quota remaining by pool', 'settings.account.quota5h': '5 hours {percent}%', @@ -2709,6 +2826,42 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.', 'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.', 'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.', + 'settings.account.switchConfirm': 'Confirm switch', + 'settings.account.removeConfirm': 'Confirm remove', + 'settings.account.pwdBtnSet': 'Passphrase', + 'settings.account.pwdBtnManage': 'Passphrase', + 'settings.account.lockNow': 'Lock', + 'settings.account.lockNowTip': 'Lock credential vault now', + 'settings.account.unlockBtn': 'Unlock', + 'settings.account.unlockPlaceholder': 'Enter passphrase to unlock…', + 'settings.account.vaultLockedHint': 'Credential vault is locked. Enter your passphrase to switch accounts, manage credentials, or refresh quotas.', + 'settings.account.forgotPwdToggle': 'Forgot?', + 'settings.account.resetVaultHint': 'Encrypted backups cannot be recovered without the passphrase (your active IDE sign-in is unaffected). You can clear and reset the vault.', + 'settings.account.resetVaultBtn': 'Reset vault', + 'settings.account.resetVaultConfirm': 'Confirm reset', + 'settings.account.pwdTabChange': 'Change passphrase', + 'settings.account.pwdTabDisable': 'Remove passphrase', + 'settings.account.pwdCurrentPlaceholder': 'Current passphrase…', + 'settings.account.pwdNewPlaceholder': 'New passphrase (4–128 chars)…', + 'settings.account.pwdConfirmPlaceholder': 'Confirm passphrase…', + 'settings.account.pwdEnableSubmit': 'Enable', + 'settings.account.pwdChangeSubmit': 'Update', + 'settings.account.pwdDisableSubmit': 'Disable', + 'settings.account.pwdSetHint': 'Adds passphrase encryption to all saved refresh tokens. Asked once per session when managing accounts; cannot be recovered if forgotten.', + 'settings.account.pwdManageHint': 'Verify your current passphrase to set a new one or return to default OS encryption.', + 'settings.account.pwdEnabledToast': 'Passphrase encryption enabled.', + 'settings.account.pwdChangedToast': 'Passphrase updated.', + 'settings.account.pwdDisabledToast': 'Passphrase protection disabled.', + 'settings.account.vaultUnlockedToast': 'Credential vault unlocked.', + 'settings.account.vaultLockedToast': 'Credential vault locked.', + 'settings.account.vaultResetToast': 'Credential vault cleared and reset.', + 'settings.account.vaultLocked': 'Enter your passphrase to unlock the vault first.', + 'settings.account.wrongPassword': 'Incorrect passphrase. Try again.', + 'settings.account.invalidPassword': 'Passphrase must be 4–128 characters and not blank.', + 'settings.account.passwordMismatch': 'Passphrases do not match.', + 'settings.account.passwordRateLimited': 'Too many failed attempts. Wait a moment and try again.', + 'settings.account.vaultDecryptFailed': 'Vault decryption check failed.', + 'settings.account.invalidActionNonce': 'Security token expired. Please try again.', 'settings.subTab.aria': 'Preferences category tabs', 'settings.saving': 'Saving…', 'settings.saved': 'Saved', @@ -6138,6 +6291,7 @@ const PORTABLE_SETTING_DESCRIPTORS = Object.freeze([ normField('stepTokenComboFormat', normalizeStepTokenComboFormat), arrayField('stepTableColumns', normalizeStepTableColumns), normField('experimentalQuotaReservation', normalizeExperimentalQuotaReservation), + normField('accountQuotaRefreshMinutes', normalizeAccountQuotaRefreshMinutes), ]); /** @@ -9048,7 +9202,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, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, 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, normalizeClientAccountQuotaRefreshMinutes, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, 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. @@ -9483,6 +9637,7 @@ const normalizeClientModelDisplayMode = normalizeModelDisplayMode; const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; const normalizeClientContextAgentMode = normalizeContextAgentMode; const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation; +const normalizeClientAccountQuotaRefreshMinutes = normalizeAccountQuotaRefreshMinutes; const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots; /** @@ -9641,6 +9796,12 @@ function isEquivalentTelemetry(prev, next) { ) { return false; } + if ( + normalizeClientAccountQuotaRefreshMinutes(pSet?.accountQuotaRefreshMinutes) !== + normalizeClientAccountQuotaRefreshMinutes(nSet?.accountQuotaRefreshMinutes) + ) { + 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; @@ -10900,6 +11061,11 @@ async function saveSettingsPatch(patch) { safePatch.experimentalQuotaReservation ); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'accountQuotaRefreshMinutes')) { + safePatch.accountQuotaRefreshMinutes = normalizeClientAccountQuotaRefreshMinutes( + safePatch.accountQuotaRefreshMinutes + ); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } @@ -11473,7 +11639,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, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, 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, normalizeClientAccountQuotaRefreshMinutes, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -29171,6 +29337,1375 @@ const SettingsStructureTab = defineComponent({ return { SettingsStructureTab }; })(); +// --- src/views/settings/SettingsAccountTab.js --- +const { SettingsAccountTab } = (() => { +/** @fileoverview Unified multi-account switcher, passphrase vault UI, and per-pool quota cards. */ + + +const key = (name) => `settings.account.${name}`; +const fmtPct = (v) => String(+Number(v).toFixed(1)); + +let warmAccountCache = null; + +const errors = new Set([ + 'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound', + 'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied', + 'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable', + 'oauthUnavailable', 'quotaUnavailable', + 'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed', + 'loginStartFailed', 'loginExchangeFailed', 'loginExpired', 'loginDenied', + 'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordMismatch', + 'passwordRateLimited', 'vaultDecryptFailed', 'invalidActionNonce', +]); + +const okToastKeys = new Set([ + 'saved', 'removed', 'switched', + 'pwdEnabledToast', 'pwdChangedToast', 'pwdDisabledToast', + 'vaultUnlockedToast', 'vaultLockedToast', 'vaultResetToast', +]); + +function getAccountRefreshOptions() { + return [ + { value: 10, label: t(key('refresh10m')) }, + { value: 30, label: t(key('refresh30m')) }, + { value: 60, label: t(key('refresh1h')) }, + { value: 180, label: t(key('refresh3h')) }, + { value: 360, label: t(key('refresh6h')) }, + { value: 720, label: t(key('refresh12h')) }, + { value: 1440, label: t(key('refresh24h')) }, + ]; +} + +function formatValidCountdown(isoTime) { + if (!isoTime) return ''; + const ms = Date.parse(isoTime); + if (!Number.isFinite(ms) || ms <= Date.now()) return ''; + return formatCountdown(isoTime); +} + +function syncRemainingMeter(wrapEl, quotaLabelEl, resetEl, fillEl, hasData, labelText, remVal, resetTime) { + patchAttr(wrapEl, 'hidden', !hasData); + if (!hasData) return; + const clamped = Math.max(0, Math.min(100, Number(remVal) || 0)); + patchText(quotaLabelEl, labelText); + const cd = formatValidCountdown(resetTime); + patchText(resetEl, cd); + patchAttr(resetEl, 'hidden', !cd); + patchStyleVar(fillEl, '--fill-w', `${+clamped.toFixed(1)}%`); + patchClasses(fillEl, { + 'tone-warn': clamped > 15 && clamped <= 30, + 'tone-danger': clamped <= 15, + }); +} + +function renderQuotaRows(container, quotaPools) { + const locale = getEffectiveLocale(); + const pools = (Array.isArray(quotaPools) ? quotaPools : []).filter( + (pool) => Number.isFinite(pool?.remainingPct) || Number.isFinite(pool?.weeklyRemainingPct) + ); + patchKeyedList(container, pools, { + keyFn: (pool) => pool.poolKey || pool.poolLabel, + sigFn: (pool) => + JSON.stringify([ + locale, + pool.poolLabel, + pool.remainingPct, + pool.weeklyRemainingPct, + pool.resetTime, + pool.weeklyResetTime, + ]), + createRow: () => { + const poolTitle = h('div', { className: 'account-pool-name' }); + + const label5h = h('span', { className: 'settings-account-quota text-mono' }); + const reset5h = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const fill5h = h('div', { className: 'progress-fill' }); + const meter5h = h('div', { className: 'account-meter-col' }, [ + h('div', { className: 'account-meter-head' }, [label5h, reset5h]), + h('div', { className: 'progress-track account-progress-track' }, [fill5h]), + ]); + + const labelWk = h('span', { className: 'settings-account-quota text-mono' }); + const resetWk = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const fillWk = h('div', { className: 'progress-fill' }); + const meterWk = h('div', { className: 'account-meter-col' }, [ + h('div', { className: 'account-meter-head' }, [labelWk, resetWk]), + h('div', { className: 'progress-track account-progress-track' }, [fillWk]), + ]); + + const gridEl = h('div', { className: 'account-pool-meters' }, [meter5h, meterWk]); + const el = h('div', { className: 'account-pool-group' }, [poolTitle, gridEl]); + return { + el, + refs: { poolTitle, gridEl, meter5h, label5h, reset5h, fill5h, meterWk, labelWk, resetWk, fillWk }, + }; + }, + updateRow: (refs, pool) => { + patchText(refs.poolTitle, pool.poolLabel || pool.poolKey); + const has5h = Number.isFinite(pool.remainingPct); + const hasWk = Number.isFinite(pool.weeklyRemainingPct); + patchClasses(refs.gridEl, { 'is-single': (has5h ? 1 : 0) + (hasWk ? 1 : 0) <= 1 }); + + syncRemainingMeter( + refs.meter5h, + refs.label5h, + refs.reset5h, + refs.fill5h, + has5h, + has5h ? t(key('quota5h'), { percent: fmtPct(pool.remainingPct) }) : '', + pool.remainingPct, + pool.resetTime + ); + syncRemainingMeter( + refs.meterWk, + refs.labelWk, + refs.resetWk, + refs.fillWk, + hasWk, + hasWk ? t(key('quotaWeekly'), { percent: fmtPct(pool.weeklyRemainingPct) }) : '', + pool.weeklyRemainingPct, + pool.weeklyResetTime + ); + }, + }); + patchAttr(container, 'hidden', pools.length === 0); + return pools.length; +} + +function needsLegacyUltraTierRefresh(cached) { + if (!cached || cached.tierId || cached.tierMultiplier) return false; + const name = String(cached.tierName || ''); + return /\bultra\b/i.test(name) && !/\b(?:5x|20x)\b/i.test(name); +} + +function isValidVaultPassphrase(raw) { + return typeof raw === 'string' && raw.length >= 4 && raw.length <= 128 && Boolean(raw.trim()); +} + +const SettingsAccountTab = defineComponent({ + name: 'SettingsAccountTab', + setup({ props, onCleanup }) { + let account = null; + let quotas = null; + let refreshMinutes = normalizeAccountQuotaRefreshMinutes( + telemetryStore.getState().telemetry?.settings?.accountQuotaRefreshMinutes ?? + DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES + ); + let accounts = warmAccountCache ? [...warmAccountCache.accounts] : []; + let selectedEmail = warmAccountCache ? warmAccountCache.selectedEmail : ''; + let supported = warmAccountCache ? warmAccountCache.supported : null; + let vaultSecurity = warmAccountCache?.vaultSecurity + ? { ...warmAccountCache.vaultSecurity } + : { enabled: false, unlocked: true }; + let actionNonce = warmAccountCache?.actionNonce || ''; + let operation = ''; + let status = ''; + let statusClearTimer = null; + let confirmTarget = null; + let confirmClearTimer = null; + let switchState = null; + let importOpen = false; + let pwdDrawerOpen = false; + let pwdManageMode = 'change'; + let forgotResetOpen = false; + let refreshingSavedQuotas = false; + let disposed = false; + let loginSession = null; + let loginTimer; + let loginGeneration = 0; + let loginRefreshEmail = ''; + const savedQuotas = new Map(warmAccountCache ? warmAccountCache.savedQuotasEntries : []); + const quotaInFlight = new Set(); + const quotaVisibleLoading = new Set(); + const quotaErrors = new Map(); + + function isVaultLocked() { + return Boolean(vaultSecurity?.enabled && !vaultSecurity?.unlocked); + } + + function syncWarmCache() { + if (supported !== true) return; + warmAccountCache = { + supported, + accounts: [...accounts], + selectedEmail, + savedQuotasEntries: [...savedQuotas.entries()], + vaultSecurity: { ...vaultSecurity }, + actionNonce, + }; + } + + function clearConfirmTarget(shouldRender = false) { + if (confirmClearTimer) { + clearTimeout(confirmClearTimer); + confirmClearTimer = null; + } + if (!confirmTarget) return; + confirmTarget = null; + if (shouldRender && !disposed) render(); + } + + function armOrRunConfirm(type, targetKey, runFn) { + if (confirmTarget && confirmTarget.type === type && confirmTarget.key === targetKey) { + clearConfirmTarget(false); + runFn(); + return; + } + if (confirmClearTimer) clearTimeout(confirmClearTimer); + confirmTarget = { type, key: targetKey }; + confirmClearTimer = setTimeout(() => clearConfirmTarget(true), 4500); + render(); + } + + function setTransientStatus(nextStatus, autoClearMs = 0) { + if (statusClearTimer) { + clearTimeout(statusClearTimer); + statusClearTimer = null; + } + status = nextStatus; + if (nextStatus && autoClearMs > 0) { + statusClearTimer = setTimeout(() => { + statusClearTimer = null; + if (!disposed && status === nextStatus) { + status = ''; + render(); + } + }, autoClearMs); + } + } + + function clearPasswordInputs() { + unlockInput.value = ''; + pwdCurrentInput.value = ''; + pwdNewInput.value = ''; + pwdConfirmInput.value = ''; + } + + const loginBtnLabel = h('span'); + const loginButton = h( + 'button', + { + type: 'button', + className: 'btn-primary settings-account-login account-toolbar-btn', + onClick: () => { + clearConfirmTarget(false); + void request('loginStart', { language: getEffectiveLocale() }); + }, + }, + [createSvgIcon('plus', { size: 12 }), loginBtnLabel] + ); + const cancelLogin = h('button', { + type: 'button', + className: 'btn-secondary settings-account-login-cancel account-toolbar-btn', + hidden: true, + onClick: () => request('loginCancel', { id: loginSession?.id }), + }); + const importToggleLabel = h('span'); + const importToggleBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary account-toolbar-btn', + onClick: () => { + clearConfirmTarget(false); + importOpen = !importOpen; + if (importOpen) { + pwdDrawerOpen = false; + clearPasswordInputs(); + } + render(); + if (importOpen) credential.focus?.(); + }, + }, + [importToggleLabel] + ); + + const pwdToggleIcon = createSvgIcon('lock', { size: 12 }); + const pwdToggleLabel = h('span'); + const pwdToggleBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary account-toolbar-btn settings-account-pwd-toggle', + onClick: () => { + clearConfirmTarget(false); + pwdDrawerOpen = !pwdDrawerOpen; + if (pwdDrawerOpen) { + importOpen = false; + pwdManageMode = 'change'; + } + clearPasswordInputs(); + render(); + if (pwdDrawerOpen) { + (vaultSecurity.enabled ? pwdCurrentInput : pwdNewInput).focus?.(); + } + }, + }, + [pwdToggleIcon, pwdToggleLabel] + ); + + const lockNowLabel = h('span'); + const lockNowBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary account-toolbar-btn settings-account-lock-now', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + pwdDrawerOpen = false; + importOpen = false; + clearPasswordInputs(); + void request('lockVault'); + }, + }, + [createSvgIcon('lock', { size: 12 }), lockNowLabel] + ); + + const feedback = h('span', { + className: 'settings-action-desc account-status-inline', + role: 'status', + hidden: true, + }); + const refreshIntervalSelect = CustomSelect({ + className: 'account-refresh-select', + icon: 'clock', + modelValue: refreshMinutes, + options: getAccountRefreshOptions(), + onUpdateModelValue: async (nextVal) => { + const nextMins = normalizeAccountQuotaRefreshMinutes(nextVal); + refreshMinutes = nextMins; + refreshIntervalSelect.setValue(nextMins); + void refreshSavedQuotas(); + try { + await saveSettingsPatch({ accountQuotaRefreshMinutes: nextMins }); + } catch { + // Keep selected interval locally if save fails transiently + } + }, + }); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'aria-label', t(key('refreshFreqAria'))); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'title', t(key('refreshFreqAria'))); + + const reload = h( + 'button', + { + type: 'button', + className: 'icon-btn account-reload-btn', + onClick: () => request('list'), + }, + [createSvgIcon('refresh', { size: 13 })] + ); + + // --- Locked Vault Unlock Strip --- + const unlockHintLabel = h('span'); + const forgotToggleBtn = h('button', { + type: 'button', + className: 'account-link-btn settings-account-forgot-btn', + onClick: () => { + forgotResetOpen = !forgotResetOpen; + clearConfirmTarget(false); + render(); + }, + }); + const unlockInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-unlock-input', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + }); + const unlockSubmitBtn = h('button', { + type: 'submit', + className: 'btn-primary account-toolbar-btn settings-account-unlock-submit', + }); + const unlockForm = h( + 'form', + { + className: 'account-import-row', + autocomplete: 'off', + onSubmit: submitUnlock, + }, + [unlockInput, unlockSubmitBtn] + ); + const resetHintEl = h('span', { className: 'settings-action-desc' }); + const resetVaultBtn = h('button', { + type: 'button', + className: 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-reset-vault', + onClick: () => { + armOrRunConfirm('resetVault', 'vault', () => { + void request('resetVault', { confirmReset: 'RESET' }); + }); + }, + }); + const resetRow = h('div', { className: 'account-reset-row', hidden: true }, [ + resetHintEl, + resetVaultBtn, + ]); + const unlockBox = h('div', { className: 'account-unlock-box settings-account-unlock-box', hidden: true }, [ + h('div', { className: 'account-unlock-head' }, [ + h('span', { className: 'account-unlock-title' }, [ + createSvgIcon('lock', { size: 13 }), + unlockHintLabel, + ]), + forgotToggleBtn, + ]), + unlockForm, + resetRow, + ]); + + // --- Passphrase Setup / Manage Drawer --- + const pwdTabChangeBtn = h('button', { + type: 'button', + className: 'account-pwd-tab', + onClick: () => { + pwdManageMode = 'change'; + clearPasswordInputs(); + render(); + }, + }); + const pwdTabDisableBtn = h('button', { + type: 'button', + className: 'account-pwd-tab', + onClick: () => { + pwdManageMode = 'disable'; + clearPasswordInputs(); + render(); + }, + }); + const pwdTabsWrap = h('div', { className: 'account-pwd-tabs', hidden: true }, [ + pwdTabChangeBtn, + pwdTabDisableBtn, + ]); + const pwdCurrentInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-pwd-current', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + hidden: true, + }); + const pwdNewInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-pwd-new', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + }); + const pwdConfirmInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-pwd-confirm', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + }); + const pwdSubmitBtn = h('button', { + type: 'submit', + className: 'btn-primary account-toolbar-btn settings-account-pwd-submit', + }); + const pwdHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const pwdForm = h( + 'form', + { + className: 'account-import-drawer settings-account-pwd-form', + autocomplete: 'off', + hidden: true, + onSubmit: submitPasswordDrawer, + }, + [ + pwdTabsWrap, + h('div', { className: 'account-import-row' }, [ + pwdCurrentInput, + pwdNewInput, + pwdConfirmInput, + pwdSubmitBtn, + ]), + pwdHint, + ] + ); + + // --- Credential Import Drawer --- + const credential = h('input', { + type: 'password', + className: 'settings-text-input account-import-input', + required: true, + autocomplete: 'off', + spellcheck: 'false', + maxlength: 16384, + }); + const save = h('button', { + type: 'submit', + className: 'btn-primary account-toolbar-btn', + }); + const importHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const form = h( + 'form', + { + className: 'settings-account-form account-import-drawer', + autocomplete: 'off', + hidden: true, + onSubmit: importCredential, + }, + [ + h('div', { className: 'account-import-row' }, [credential, save]), + importHint, + ] + ); + + const loginMessage = h('div', { + className: 'settings-action-desc account-flow-msg', + role: 'status', + hidden: true, + }); + const loginLink = h('a', { + className: 'account-flow-link', + target: '_blank', + rel: 'noopener noreferrer', + hidden: true, + }); + const loginStrip = h('div', { className: 'account-flow-strip', hidden: true }, [ + loginMessage, + loginLink, + ]); + const pending = h('div', { + className: 'settings-action-desc account-flow-strip is-warn', + role: 'status', + hidden: true, + }); + + const toolbarPanel = h('section', { className: 'panel account-toolbar-panel' }, [ + h('div', { className: 'account-toolbar-row' }, [ + h('div', { className: 'account-toolbar-left' }, [ + loginButton, + cancelLogin, + importToggleBtn, + pwdToggleBtn, + lockNowBtn, + ]), + h('div', { className: 'account-toolbar-right' }, [ + feedback, + refreshIntervalSelect.el, + reload, + ]), + ]), + unlockBox, + pwdForm, + form, + loginStrip, + pending, + ]); + + const cardsHost = h('div', { className: 'account-cards-stack' }); + const emptyPanel = h('section', { className: 'panel account-empty-panel', hidden: true }, [ + h('div', { className: 'settings-action-desc account-empty-text' }), + ]); + const emptyTextEl = emptyPanel.firstChild; + + function resolveActiveEmail() { + return account?.status === 'signedIn' ? (account.email || '').trim().toLowerCase() : ''; + } + + function buildUnifiedAccountEntries(activeEmail) { + const entries = []; + if (activeEmail) { + entries.push({ + email: activeEmail, + isActive: true, + isSaved: accounts.includes(activeEmail), + }); + } + for (let i = 0; i < accounts.length; i++) { + const addr = accounts[i]; + if (addr && addr !== activeEmail) { + entries.push({ + email: addr, + isActive: false, + isSaved: true, + }); + } + } + return entries; + } + + function render() { + const signedIn = account?.status === 'signedIn'; + const activeEmail = resolveActiveEmail(); + if (activeEmail && selectedEmail === activeEmail && switchState?.state !== 'starting') { + selectedEmail = ''; + } + const vaultLocked = isVaultLocked(); + const canOperateVault = + supported === true && + !operation && + status !== 'restarting' && + switchState?.state !== 'starting'; + const canWrite = canOperateVault && !vaultLocked; + const locale = getEffectiveLocale(); + const activeTierBadge = + signedIn && (account?.tierName || account?.planName) + ? formatAccountTierBadge(account) + : ''; + + const loginActive = ['waiting', 'exchanging', 'saving'].includes(loginSession?.status); + patchText(loginBtnLabel, t(key('googleLogin'))); + patchAttr(loginButton, 'disabled', !canWrite || loginActive); + patchText(cancelLogin, t(key('cancelLogin'))); + patchAttr(cancelLogin, 'hidden', !loginActive); + patchAttr(cancelLogin, 'disabled', Boolean(operation) || loginSession?.status === 'saving'); + + patchText(importToggleLabel, t(key('importExisting'))); + patchClasses(importToggleBtn, { 'is-open': importOpen }); + patchAttr(importToggleBtn, 'hidden', supported === false); + patchAttr(importToggleBtn, 'disabled', !canWrite); + + patchSvgIcon(pwdToggleIcon, vaultSecurity.enabled ? 'unlock' : 'lock'); + patchText(pwdToggleLabel, t(key(vaultSecurity.enabled ? 'pwdBtnManage' : 'pwdBtnSet'))); + patchClasses(pwdToggleBtn, { 'is-open': pwdDrawerOpen }); + patchAttr(pwdToggleBtn, 'hidden', supported === false || vaultLocked); + patchAttr(pwdToggleBtn, 'disabled', !canOperateVault); + + patchText(lockNowLabel, t(key('lockNow'))); + patchAttr(lockNowBtn, 'title', t(key('lockNowTip'))); + patchAttr(lockNowBtn, 'hidden', !vaultSecurity.enabled || vaultLocked || supported === false); + patchAttr(lockNowBtn, 'disabled', !canOperateVault); + + // Unlock strip (only when passphrase enabled & locked) + patchAttr(unlockBox, 'hidden', supported !== true || !vaultLocked); + patchText(unlockHintLabel, t(key('vaultLockedHint'))); + patchText(forgotToggleBtn, t(key('forgotPwdToggle'))); + patchAttr(unlockInput, 'placeholder', t(key('unlockPlaceholder'))); + patchAttr(unlockInput, 'disabled', !canOperateVault); + patchText(unlockSubmitBtn, t(key('unlockBtn'))); + patchAttr(unlockSubmitBtn, 'disabled', !canOperateVault); + patchAttr(resetRow, 'hidden', !forgotResetOpen || !vaultLocked); + patchText(resetHintEl, t(key('resetVaultHint'))); + const armedVaultReset = + confirmTarget?.type === 'resetVault' && confirmTarget.key === 'vault'; + patchText(resetVaultBtn, t(key(armedVaultReset ? 'resetVaultConfirm' : 'resetVaultBtn'))); + patchAttr(resetVaultBtn, 'disabled', !canOperateVault); + + // Passphrase setup / manage drawer + const showPwdDrawer = pwdDrawerOpen && !vaultLocked && supported === true; + patchAttr(pwdForm, 'hidden', !showPwdDrawer); + if (showPwdDrawer) { + const isSetNew = !vaultSecurity.enabled; + const isDisableMode = !isSetNew && pwdManageMode === 'disable'; + patchAttr(pwdTabsWrap, 'hidden', isSetNew); + patchText(pwdTabChangeBtn, t(key('pwdTabChange'))); + patchClasses(pwdTabChangeBtn, { 'is-active': pwdManageMode === 'change' }); + patchText(pwdTabDisableBtn, t(key('pwdTabDisable'))); + patchClasses(pwdTabDisableBtn, { 'is-active': isDisableMode }); + + patchAttr(pwdCurrentInput, 'hidden', isSetNew); + patchAttr(pwdCurrentInput, 'placeholder', t(key('pwdCurrentPlaceholder'))); + patchAttr(pwdCurrentInput, 'disabled', !canOperateVault); + + patchAttr(pwdNewInput, 'hidden', isDisableMode); + patchAttr(pwdNewInput, 'placeholder', t(key('pwdNewPlaceholder'))); + patchAttr(pwdNewInput, 'disabled', !canOperateVault); + + patchAttr(pwdConfirmInput, 'hidden', isDisableMode); + patchAttr(pwdConfirmInput, 'placeholder', t(key('pwdConfirmPlaceholder'))); + patchAttr(pwdConfirmInput, 'disabled', !canOperateVault); + + patchText( + pwdSubmitBtn, + t(key(isSetNew ? 'pwdEnableSubmit' : isDisableMode ? 'pwdDisableSubmit' : 'pwdChangeSubmit')) + ); + patchClasses(pwdSubmitBtn, { + 'btn-primary': !isDisableMode, + 'btn-secondary': isDisableMode, + 'account-confirm-danger-btn': isDisableMode, + }); + patchAttr(pwdSubmitBtn, 'disabled', !canOperateVault); + patchText(pwdHint, t(key(isSetNew ? 'pwdSetHint' : 'pwdManageHint'))); + } + + refreshIntervalSelect.setProps({ + modelValue: refreshMinutes, + options: getAccountRefreshOptions(), + }); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'aria-label', t(key('refreshFreqAria'))); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'title', t(key('refreshFreqAria'))); + patchAttr(refreshIntervalSelect.el, 'hidden', supported === false); + + patchAttr(reload, 'title', t(key('reload'))); + patchAttr(reload, 'aria-label', t(key('reload'))); + patchAttr(reload, 'disabled', Boolean(operation)); + patchClasses(reload, { 'is-spinning': operation === 'list' }); + + patchAttr(form, 'hidden', !importOpen || vaultLocked || supported === false); + patchAttr(credential, 'placeholder', t(key('credentialPlaceholder'))); + patchAttr(credential, 'disabled', !canWrite); + patchText(save, t(key('save'))); + patchAttr(save, 'disabled', !canWrite); + patchText(importHint, t(key('importHint'))); + + const loginStatusKeys = { + waiting: 'loginWaiting', + exchanging: 'loginFinishing', + saving: 'loginFinishing', + success: 'loginSuccess', + cancelled: 'loginCancelled', + expired: 'loginExpired', + }; + const hasLoginSession = Boolean(loginSession?.status); + const loginIsError = + loginSession?.status === 'error' || + loginSession?.status === 'expired' || + loginSession?.error === 'loginDenied'; + const loginMessageKey = + loginSession?.status === 'error' + ? errors.has(loginSession.error) + ? loginSession.error + : 'loginExchangeFailed' + : loginSession?.error === 'loginDenied' + ? 'loginDenied' + : loginStatusKeys[loginSession?.status] || ''; + patchText(loginMessage, loginMessageKey ? t(key(loginMessageKey)) : ''); + patchAttr(loginMessage, 'hidden', !loginMessageKey); + + const authUrl = + loginSession?.status === 'waiting' && + loginSession.url?.startsWith('https://accounts.google.com/o/oauth2/v2/auth?') + ? loginSession.url + : ''; + patchText(loginLink, t(key('openLoginPage'))); + patchAttr(loginLink, 'href', authUrl || null); + patchAttr(loginLink, 'hidden', !authUrl); + patchClasses(loginStrip, { + 'is-error': loginIsError, + 'is-ok': loginSession?.status === 'success', + 'is-info': loginActive, + }); + patchAttr(loginStrip, 'hidden', !hasLoginSession || !loginMessageKey); + + const failedSwitch = + switchState?.state === 'failed' && errors.has(switchState.error) ? switchState.error : ''; + const message = + status || + failedSwitch || + (operation === 'switch' + ? 'switching' + : operation === 'save' || operation === 'capture' + ? 'verifying' + : ''); + const isFeedbackError = Boolean(errors.has(message)); + const isFeedbackOk = okToastKeys.has(message); + patchText(feedback, message ? t(key(message)) : ''); + patchAttr(feedback, 'title', message ? t(key(message)) : null); + patchClasses(feedback, { + 'is-error': isFeedbackError, + 'is-ok': isFeedbackOk, + 'is-info': !isFeedbackError && !isFeedbackOk && Boolean(message), + }); + patchAttr(feedback, 'hidden', !message); + + const waiting = + Boolean(selectedEmail) && + activeEmail !== selectedEmail && + switchState?.state === 'written' && + status !== 'restarting'; + patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : ''); + patchAttr(pending, 'hidden', !waiting); + + const entries = buildUnifiedAccountEntries(activeEmail); + patchAttr(cardsHost, 'hidden', entries.length === 0); + patchText( + emptyTextEl, + t( + key( + supported === null + ? 'loading' + : account?.status === 'signedOut' + ? 'signedOut' + : 'empty' + ) + ) + ); + patchAttr(emptyPanel, 'hidden', entries.length > 0); + + patchKeyedList(cardsHost, entries, { + keyFn: (entry) => entry.email, + sigFn: (entry) => + JSON.stringify([ + locale, + entry.isActive, + entry.isSaved, + selectedEmail, + switchState?.state || '', + canWrite, + confirmTarget?.key === entry.email ? confirmTarget.type : '', + entry.isActive ? null : savedQuotas.get(entry.email), + quotaVisibleLoading.has(entry.email), + entry.isActive ? null : quotaErrors.get(entry.email), + entry.isActive ? quotas : null, + entry.isActive ? activeTierBadge : '', + ]), + createRow: (entry) => { + const activeDot = h('span', { className: 'dot-swatch account-active-dot', hidden: true }); + const emailEl = h('span', { + className: 'settings-account-identity account-card-email', + text: entry.email, + title: entry.email, + }); + const tierPill = h('span', { className: 'account-tag is-tier', hidden: true }); + const statePill = h('span', { className: 'account-tag', hidden: true }); + + const captureBtn = h('button', { + type: 'button', + className: 'btn-secondary account-card-btn', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('capture'); + }, + }); + const selectBtn = h('button', { + type: 'button', + className: 'btn-secondary account-card-btn', + hidden: true, + onClick: () => { + armOrRunConfirm('switch', entry.email, () => { + const curActive = resolveActiveEmail(); + void request('switch', { + email: entry.email, + ...(curActive ? { activeEmail: curActive } : {}), + }); + }); + }, + }); + const loadQuotaBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn settings-account-load-quota account-icon-btn', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('quota', { email: entry.email, manual: true }); + }, + }, + [createSvgIcon('refresh', { size: 12 })] + ); + const removeBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn slot-remove-btn settings-account-remove account-icon-btn', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }, + [createSvgIcon('close', { size: 12 })] + ); + const removeConfirmBtn = h('button', { + type: 'button', + className: + 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-remove-confirm', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }); + + const poolsWrap = h('div', { className: 'account-pools-stack' }); + const noteEl = h('div', { className: 'settings-action-desc account-card-note', hidden: true }); + + const cardEl = h('section', { className: 'panel account-card' }, [ + h('div', { className: 'panel-header account-card-head' }, [ + h('div', { className: 'account-card-meta' }, [ + activeDot, + emailEl, + tierPill, + statePill, + ]), + h('div', { className: 'account-card-actions' }, [ + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + ]), + ]), + poolsWrap, + noteEl, + ]); + return { + el: cardEl, + refs: { + cardEl, + activeDot, + emailEl, + tierPill, + statePill, + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + poolsWrap, + noteEl, + }, + }; + }, + updateRow: (row, entry) => { + const addr = entry.email; + const active = entry.isActive; + const isSaved = entry.isSaved; + const written = addr === selectedEmail && !active && switchState?.state === 'written'; + const cached = active ? null : savedQuotas.get(addr); + const tierText = active + ? activeTierBadge + : cached?.tierName || cached?.tierId + ? formatAccountTierBadge({ + tierId: cached.tierId, + tierName: cached.tierName, + tierMultiplier: cached.tierMultiplier, + }) + : ''; + const isSpinning = !active && quotaVisibleLoading.has(addr); + const canSwitch = !active && isSaved; + const armedSwitch = confirmTarget?.type === 'switch' && confirmTarget.key === addr; + const armedRemove = confirmTarget?.type === 'remove' && confirmTarget.key === addr; + + patchClasses(row.cardEl, { 'is-active-account': active }); + patchAttr(row.activeDot, 'hidden', !active); + patchText(row.emailEl, addr); + patchAttr(row.emailEl, 'title', addr); + + patchText(row.tierPill, tierText); + patchAttr(row.tierPill, 'hidden', !tierText); + + patchText(row.statePill, active ? t(key('active')) : written ? t(key('written')) : ''); + patchClasses(row.statePill, { 'is-active': active, 'is-written': written }); + patchAttr(row.statePill, 'hidden', !active && !written); + + patchText(row.captureBtn, t(key('capture'))); + patchAttr(row.captureBtn, 'hidden', !active || isSaved || supported === false); + patchAttr(row.captureBtn, 'disabled', !canWrite); + + patchText(row.selectBtn, t(key(armedSwitch ? 'switchConfirm' : 'switch'))); + patchAttr(row.selectBtn, 'title', t(key('switchHint'))); + patchClasses(row.selectBtn, { + 'settings-account-switch': canSwitch, + 'is-confirm-warn': armedSwitch, + }); + patchAttr(row.selectBtn, 'hidden', !canSwitch); + patchAttr(row.selectBtn, 'disabled', !canWrite); + + patchAttr(row.loadQuotaBtn, 'title', t(key(isSpinning ? 'loadingQuota' : 'loadQuota'))); + patchAttr(row.loadQuotaBtn, 'aria-label', t(key('loadQuota'))); + patchClasses(row.loadQuotaBtn, { 'is-spinning': isSpinning }); + // Active account exclusively uses host telemetry — hide OAuth quota refresh on active card + patchAttr(row.loadQuotaBtn, 'hidden', active || !isSaved); + patchAttr(row.loadQuotaBtn, 'disabled', !canWrite || isSpinning); + + patchAttr(row.removeBtn, 'title', t(key('remove'))); + patchAttr(row.removeBtn, 'aria-label', t(key('remove'))); + patchAttr(row.removeBtn, 'hidden', !isSaved || armedRemove); + patchAttr(row.removeBtn, 'disabled', !canWrite); + + patchText(row.removeConfirmBtn, t(key('removeConfirm'))); + patchAttr(row.removeConfirmBtn, 'hidden', !isSaved || !armedRemove); + patchAttr(row.removeConfirmBtn, 'disabled', !canWrite); + + const displayedPools = active ? quotas?.pools || [] : cached?.pools || []; + const poolCount = renderQuotaRows(row.poolsWrap, displayedPools); + const quotaError = active ? '' : quotaErrors.get(addr); + + let noteText = ''; + if (quotaError) { + noteText = t(key(quotaError)); + } else if (active && poolCount > 0 && quotas?.meta?.isStale) { + noteText = t(key('quotaStale')); + } else if (active && poolCount === 0) { + noteText = t(key('noQuota')); + } else if (!active && cached && poolCount === 0) { + noteText = t(key('emptyCredentialQuota')); + } + patchText(row.noteEl, noteText); + patchClasses(row.noteEl, { 'is-error': Boolean(quotaError) }); + patchAttr(row.noteEl, 'hidden', !noteText); + }, + }); + + props.onLayoutChange?.(); + } + + async function dispatchAccountPost(action, fields) { + let res = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { + action, + ...fields, + ...(actionNonce ? { actionNonce } : {}), + }, + cdpTimeoutMs: 40000, + }); + if (res?.actionNonce) { + actionNonce = res.actionNonce; + } + if (res?.error === 'invalidActionNonce' && actionNonce) { + res = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { + action, + ...fields, + actionNonce, + }, + cdpTimeoutMs: 40000, + }); + if (res?.actionNonce) { + actionNonce = res.actionNonce; + } + } + return res; + } + + async function request(action, fields = {}) { + if (action === 'quota') return refreshQuota(fields.email, Boolean(fields.manual)); + if (operation) return; + operation = action; + if (action === 'loginStart' || action === 'loginCancel') { + clearTimeout(loginTimer); + loginGeneration += 1; + } + setTransientStatus(''); + render(); + try { + const result = + action === 'list' + ? await callSidecarApi('/api/accounts') + : await dispatchAccountPost(action, fields); + if (disposed) return; + if (typeof result?.actionNonce === 'string' && result.actionNonce) { + actionNonce = result.actionNonce; + } + if (result?.error) { + if (result.error === 'unsupported') supported = false; + if (result.error === 'vaultLocked') { + vaultSecurity = { enabled: true, unlocked: false }; + syncWarmCache(); + } + setTransientStatus(errors.has(result.error) ? result.error : 'storeFailed', 3600); + return; + } + if (action === 'loginStart' || action === 'loginCancel') { + applyLogin(result.login); + if (result.login?.status === 'success') loginRefreshEmail = result.login.email; + return; + } + supported = result?.supported === true; + accounts = result?.accounts || []; + selectedEmail = result?.selectedEmail || ''; + switchState = result?.switchState || null; + if (result?.security) { + vaultSecurity = { + enabled: Boolean(result.security.enabled), + unlocked: result.security.unlocked !== false, + }; + } else { + vaultSecurity = { enabled: false, unlocked: true }; + } + if (result.login) applyLogin(result.login); + if (action === 'resetVault') { + savedQuotas.clear(); + quotaErrors.clear(); + } + for (const [addr, snapshot] of Object.entries(result?.quotas || {})) { + savedQuotas.set(addr, snapshot); + } + syncWarmCache(); + if (action !== 'switch' && !isVaultLocked()) { + void refreshSavedQuotas(); + } + if (action === 'save' || action === 'capture') { + importOpen = false; + setTransientStatus('saved', 2600); + } else if (action === 'remove') { + savedQuotas.delete(fields.email); + quotaErrors.delete(fields.email); + syncWarmCache(); + setTransientStatus('removed', 2600); + } else if (action === 'switch') { + setTransientStatus(result.restarting ? 'restarting' : 'switchStartFailed'); + } else if (action === 'setPassword') { + pwdDrawerOpen = false; + setTransientStatus('pwdEnabledToast', 2600); + } else if (action === 'changePassword') { + pwdDrawerOpen = false; + setTransientStatus('pwdChangedToast', 2600); + } else if (action === 'disablePassword') { + pwdDrawerOpen = false; + setTransientStatus('pwdDisabledToast', 2600); + } else if (action === 'unlockVault') { + forgotResetOpen = false; + quotaErrors.clear(); + setTransientStatus('vaultUnlockedToast', 2200); + } else if (action === 'lockVault') { + pwdDrawerOpen = false; + importOpen = false; + setTransientStatus('vaultLockedToast', 2200); + } else if (action === 'resetVault') { + forgotResetOpen = false; + setTransientStatus('vaultResetToast', 2600); + } + } catch { + setTransientStatus('storeFailed', 3200); + } finally { + operation = ''; + if (!disposed) { + render(); + if (loginRefreshEmail) { + const email = loginRefreshEmail; + loginRefreshEmail = ''; + void refreshLoginAccount(email); + } + } + } + } + + async function refreshLoginAccount(email) { + if (disposed || !email) return; + if (operation) { + loginRefreshEmail = email; + return; + } + await request('list'); + if (!disposed && !isVaultLocked() && email !== resolveActiveEmail()) { + void refreshQuota(email, false); + } + } + + function applyLogin(session) { + loginSession = session; + clearTimeout(loginTimer); + if (['waiting', 'exchanging', 'saving'].includes(session?.status)) { + loginTimer = setTimeout(() => pollLogin(session.id, loginGeneration), 1000); + } + } + + async function pollLogin(id, generation) { + try { + const result = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { action: 'loginStatus', id, ...(actionNonce ? { actionNonce } : {}) }, + cdpTimeoutMs: 10000, + }); + if (disposed || generation !== loginGeneration) return; + if (typeof result?.actionNonce === 'string' && result.actionNonce) { + actionNonce = result.actionNonce; + } + if (result.error) throw new Error(result.error); + applyLogin(result.login); + if (loginSession?.status === 'success') await refreshLoginAccount(loginSession.email); + } catch { + if (disposed || generation !== loginGeneration) return; + loginSession = { id, status: 'error', error: 'loginStartFailed' }; + } + if (!disposed) render(); + } + + async function refreshSavedQuotas() { + if (refreshingSavedQuotas || isVaultLocked()) return; + refreshingSavedQuotas = true; + try { + const activeEmail = resolveActiveEmail(); + const ttlMs = refreshMinutes * 60_000; + const staleTargets = accounts.filter((addr) => { + // Active account exclusively uses host telemetry — never poll via OAuth + if (!addr || addr === activeEmail) return false; + const cached = savedQuotas.get(addr); + if (needsLegacyUltraTierRefresh(cached)) return true; + return Date.now() - (cached?.fetchedAt || 0) >= ttlMs; + }); + const BATCH_SIZE = 3; + for (let i = 0; i < staleTargets.length; i += BATCH_SIZE) { + if (disposed || operation === 'switch' || isVaultLocked()) break; + const batch = staleTargets.slice(i, i + BATCH_SIZE); + await Promise.all(batch.map((addr) => refreshQuota(addr, false))); + } + } finally { + refreshingSavedQuotas = false; + } + } + + async function refreshQuota(addr, manual = false) { + const activeEmail = resolveActiveEmail(); + if (!addr || addr === activeEmail || isVaultLocked() || quotaInFlight.has(addr) || disposed) { + return; + } + const hasCachedPools = Boolean(savedQuotas.get(addr)?.pools?.length); + const showSpinner = manual || !hasCachedPools; + quotaInFlight.add(addr); + if (showSpinner) quotaVisibleLoading.add(addr); + quotaErrors.delete(addr); + if (showSpinner || quotaErrors.size > 0) render(); + try { + const result = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { action: 'quota', email: addr, ...(actionNonce ? { actionNonce } : {}) }, + cdpTimeoutMs: 40000, + }); + if (typeof result?.actionNonce === 'string' && result.actionNonce) { + actionNonce = result.actionNonce; + } + if (result?.error === 'vaultLocked') { + vaultSecurity = { enabled: true, unlocked: false }; + syncWarmCache(); + return; + } + if (result?.error) { + if (manual || !hasCachedPools) { + quotaErrors.set(addr, errors.has(result.error) ? result.error : 'quotaUnavailable'); + } + } else { + const prev = savedQuotas.get(addr) || {}; + const nextTierId = result.tierId || prev.tierId || ''; + const nextTierName = result.tierName || prev.tierName || ''; + const nextTierMult = result.tierMultiplier || prev.tierMultiplier || ''; + savedQuotas.set(addr, { + pools: result.pools, + fetchedAt: result.fetchedAt || Date.now(), + ...(nextTierId ? { tierId: nextTierId } : {}), + ...(nextTierName ? { tierName: nextTierName } : {}), + ...(nextTierMult ? { tierMultiplier: nextTierMult } : {}), + }); + syncWarmCache(); + } + } catch { + if (manual || !hasCachedPools) { + quotaErrors.set(addr, 'quotaUnavailable'); + } + } finally { + quotaInFlight.delete(addr); + quotaVisibleLoading.delete(addr); + if (!disposed) render(); + } + } + + function submitUnlock(event) { + event.preventDefault(); + if (operation) return; + const pwd = unlockInput.value; + unlockInput.value = ''; + if (!isValidVaultPassphrase(pwd)) { + setTransientStatus('wrongPassword', 3000); + render(); + return; + } + void request('unlockVault', { password: pwd }); + } + + function submitPasswordDrawer(event) { + event.preventDefault(); + if (operation) return; + const curPwd = pwdCurrentInput.value; + const nextPwd = pwdNewInput.value; + const confirmPwd = pwdConfirmInput.value; + clearPasswordInputs(); + + if (!vaultSecurity.enabled) { + if (!isValidVaultPassphrase(nextPwd)) { + setTransientStatus('invalidPassword', 3200); + render(); + return; + } + if (nextPwd !== confirmPwd) { + setTransientStatus('passwordMismatch', 3200); + render(); + return; + } + void request('setPassword', { newPassword: nextPwd }); + return; + } + + if (!isValidVaultPassphrase(curPwd)) { + setTransientStatus('wrongPassword', 3000); + render(); + return; + } + if (pwdManageMode === 'disable') { + void request('disablePassword', { currentPassword: curPwd }); + return; + } + if (!isValidVaultPassphrase(nextPwd)) { + setTransientStatus('invalidPassword', 3200); + render(); + return; + } + if (nextPwd !== confirmPwd) { + setTransientStatus('passwordMismatch', 3200); + render(); + return; + } + void request('changePassword', { currentPassword: curPwd, newPassword: nextPwd }); + } + + function importCredential(event) { + event.preventDefault(); + if (operation) return; + const input = credential.value; + credential.value = ''; + void request('save', { credential: input }); + } + + function renderAccount(value, quotaData, settingsData) { + const nextRefreshMins = + settingsData?.accountQuotaRefreshMinutes !== undefined + ? normalizeAccountQuotaRefreshMinutes(settingsData.accountQuotaRefreshMinutes) + : refreshMinutes; + if (account === value && quotas === quotaData && refreshMinutes === nextRefreshMins) return; + account = value; + quotas = quotaData; + refreshMinutes = nextRefreshMins; + render(); + } + + const quotaScheduleTimer = setInterval(() => { + if (!disposed && accounts.length > 0 && !operation && !isVaultLocked()) { + void refreshSavedQuotas(); + } + }, 60_000); + quotaScheduleTimer.unref?.(); + + const root = h('div', { className: 'settings-tab-stack settings-account-root' }, [ + toolbarPanel, + cardsHost, + emptyPanel, + ]); + render(); + onCleanup(() => { + disposed = true; + clearTimeout(loginTimer); + clearInterval(quotaScheduleTimer); + if (statusClearTimer) clearTimeout(statusClearTimer); + if (confirmClearTimer) clearTimeout(confirmClearTimer); + refreshIntervalSelect.destroy(); + loginGeneration += 1; + credential.value = ''; + clearPasswordInputs(); + }); + return { + el: root, + refs: { + renderAccount, + refreshLabels: render, + preload: () => (supported === null ? request('list') : Promise.resolve()), + load: () => (supported === null ? request('list') : refreshSavedQuotas()), + }, + }; + }, +}); +return { SettingsAccountTab }; +})(); + // --- src/views/settings/SettingsOtherTab.js --- const { SettingsOtherTab } = (() => { /** @@ -35119,7 +36654,7 @@ const { SHOW_ACCOUNT_TAB, SettingsView } = (() => { */ -const SHOW_ACCOUNT_TAB = false; +const SHOW_ACCOUNT_TAB = true; function getSettingsSubTabOptions() { return [ @@ -35155,10 +36690,11 @@ const SettingsView = defineComponent({ const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll }); const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll }); - const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in + const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll }); const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll }); let showingAccount = false; + let preloadedAccountOnce = false; function applyActiveSubTab(subTab, activeView) { const target = subTab === 'structure' || @@ -35173,6 +36709,10 @@ const SettingsView = defineComponent({ patchAttr(otherTab.el, 'hidden', target !== 'other'); if (accountTab) { patchAttr(accountTab.el, 'hidden', target !== 'account'); + if (activeView === 'settings' && !preloadedAccountOnce) { + preloadedAccountOnce = true; + void accountTab.refs.preload?.(); + } const nextShowingAccount = target === 'account' && activeView === 'settings'; if (nextShowingAccount && !showingAccount) void accountTab.refs.load(); showingAccount = nextShowingAccount; @@ -35206,6 +36746,9 @@ const SettingsView = defineComponent({ if (getVisibleMonitorView(ui) !== 'settings') return; const telemetry = telemetryStore.getState().telemetry; const settings = telemetry?.settings; + if (accountTab) { + accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas, settings); + } if (settingsSubTab === 'structure') { if (settings) { structureTab.refs.renderSettings( @@ -35226,9 +36769,7 @@ const SettingsView = defineComponent({ telemetry?.cloudCodeProxy ); } - } else if (accountTab && settingsSubTab === 'account') { - accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas); - } else { + } else if (settingsSubTab !== 'account') { if (settings) generalTab.refs.renderSettings(settings); if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus); } diff --git a/sidecars/panel/backend/account-credentials.ps1 b/sidecars/panel/backend/account-credentials.ps1 index 744e0e0..2309513 100644 --- a/sidecars/panel/backend/account-credentials.ps1 +++ b/sidecars/panel/backend/account-credentials.ps1 @@ -1,7 +1,11 @@ +param([string]$JobPath = '') + $ErrorActionPreference = 'Stop' [Console]::InputEncoding = [Text.UTF8Encoding]::new($false) [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) $utf8 = [Console]::OutputEncoding +$script:clientsToRestart = @() +$script:clientsStopped = $false function Test-AccountFile($path) { if (-not (Test-Path -LiteralPath $path)) { return $false } @@ -26,11 +30,168 @@ function Write-AccountFile($path, [byte[]]$bytes) { } } +function Ensure-VaultDirectory($path) { + $dir = [IO.Path]::GetDirectoryName($path) + if (-not $dir) { return } + [void][IO.Directory]::CreateDirectory($dir) + if ([IO.Path]::GetFileName($dir) -ieq 'AntigravityUsageMonitor') { + try { + $acl = Get-Acl -LiteralPath $dir + if (-not $acl.AreAccessRulesProtected) { + $userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User + $sysSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18') + $admSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') + $inherit = [Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit' + $prop = [Security.AccessControl.PropagationFlags]::None + $right = [Security.AccessControl.FileSystemRights]::FullControl + $allow = [Security.AccessControl.AccessControlType]::Allow + $acl.SetAccessRuleProtection($true, $false) + foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRule($rule) } + foreach ($sid in @($userSid, $sysSid, $admSid)) { + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, $right, $inherit, $prop, $allow)) + } + Set-Acl -LiteralPath $dir -AclObject $acl + } + } catch {} + } + try { + $cutoff = [DateTime]::UtcNow.AddMinutes(-10) + Get-ChildItem -LiteralPath $dir -Filter 'switch-*.dpapi' -File -ErrorAction SilentlyContinue | + Where-Object { $_.LastWriteTimeUtc -lt $cutoff } | + ForEach-Object { [IO.File]::Delete($_.FullName) } + } catch {} +} + function Save-Vault($path, $vault) { - $bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 4 -Compress)) - $encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser') - [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path)) - Write-AccountFile $path $encrypted + $bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 10 -Compress)) + try { + $encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser') + Ensure-VaultDirectory $path + Write-AccountFile $path $encrypted + } finally { + if ($bytes) { [Array]::Clear($bytes, 0, $bytes.Length) } + } +} + +function Write-SwitchState($request, $state, $errorCode = '') { + $data = @{ email = $request.email; state = $state; error = $errorCode; updatedAt = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() } + Write-AccountFile $request.statusFile ($utf8.GetBytes((ConvertTo-Json -InputObject $data -Compress))) +} + +function Get-AccountClients { + $sessionId = (Get-Process -Id $PID).SessionId + $userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $candidates = @(Get-CimInstance Win32_Process -Filter "Name = 'Antigravity.exe' OR Name = 'Antigravity IDE.exe' OR Name = 'agy.exe' OR Name = 'language_server.exe'") + $owned = @($candidates | Where-Object { + $_.SessionId -eq $sessionId -and $_.ExecutablePath -and (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $userSid + }) + $roots = @($owned | Where-Object { + $_.Name -in @('Antigravity.exe', 'Antigravity IDE.exe') -and + $_.CommandLine -notmatch '(?:^|\s)(?:--type|--import|--inspect|--inspect-brk|--ms-enable-electron-run-as-node)(?:=|\s)' -and + $_.CommandLine -notmatch 'sidecar_sdk[\\/]register_loader\.js' -and + [Diagnostics.FileVersionInfo]::GetVersionInfo($_.ExecutablePath).ProductName -like 'Antigravity*' + }) + $installDirectories = @($roots | ForEach-Object { [IO.Path]::GetDirectoryName($_.ExecutablePath) + [IO.Path]::DirectorySeparatorChar } | Select-Object -Unique) + $agyCliHubPath = [IO.Path]::GetFullPath((Join-Path $env:USERPROFILE '.gemini\bin\agy.exe')) + $hubs = @($owned | Where-Object { + $candidate = $_ + $trustedPath = [string]::Equals($candidate.ExecutablePath, $agyCliHubPath, [StringComparison]::OrdinalIgnoreCase) -or + @($installDirectories | Where-Object { $candidate.ExecutablePath.StartsWith($_, [StringComparison]::OrdinalIgnoreCase) }).Count -gt 0 + ($candidate.Name -eq 'language_server.exe' -or + ($candidate.Name -eq 'agy.exe' -and $candidate.CommandLine -match '(?:^|\s)--hub(?:\s|$)')) -and $trustedPath + }) + return @{ roots = $roots; hubs = $hubs; sessionId = $sessionId } +} + +function Stop-AccountClients { + $snapshot = Get-AccountClients + $roots = $snapshot.roots + $hubs = $snapshot.hubs + $sessionId = $snapshot.sessionId + $byExe = @{} + $launch = @() + foreach ($root in $roots) { + $exeKey = $root.ExecutablePath.ToLowerInvariant() + $hasDebugPort = $root.CommandLine -match '(?:^|\s)--remote-debugging-port(?:=|\s)' + if (-not $byExe.ContainsKey($exeKey)) { + $entry = @{ path = $root.ExecutablePath; useDebugPort = [bool]$hasDebugPort } + $byExe[$exeKey] = $entry + $launch += $entry + } elseif ($hasDebugPort) { + $byExe[$exeKey].useDebugPort = $true + } + } + $script:clientsToRestart = $launch + $script:clientsStopped = $true + foreach ($root in $roots) { + $process = Get-Process -Id $root.ProcessId -ErrorAction SilentlyContinue + if ($process -and $process.MainWindowHandle -ne 0) { [void]$process.CloseMainWindow() } + } + $clientPaths = @($launch | ForEach-Object { $_.path }) + if ($roots.Count) { + for ($i = 0; $i -lt 10; $i++) { + $aliveRoots = @(Get-Process -Id @($roots.ProcessId) -ErrorAction SilentlyContinue) + if ($aliveRoots.Count -eq 0) { break } + Start-Sleep -Milliseconds 150 + } + } + $remaining = @(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sessionId -and $_.Path -in $clientPaths }) + foreach ($process in $remaining) { Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue } + foreach ($hub in $hubs) { + if (Get-Process -Id $hub.ProcessId -ErrorAction SilentlyContinue) { Stop-Process -Id $hub.ProcessId -Force -ErrorAction SilentlyContinue } + } + foreach ($processId in @($remaining.Id) + @($hubs.ProcessId)) { + if ($processId) { Wait-Process -Id $processId -Timeout 10 -ErrorAction SilentlyContinue } + } + if (@(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sessionId -and $_.Path -in $clientPaths }).Count) { + throw 'clientCloseFailed' + } + foreach ($hub in $hubs) { + if (Get-Process -Id $hub.ProcessId -ErrorAction SilentlyContinue) { throw 'clientCloseFailed' } + } +} + +function Start-AccountClients { + foreach ($envVar in @('ELECTRON_RUN_AS_NODE', 'ELECTRON_NO_ATTACH_CONSOLE', 'VSCODE_IPC_HOOK', 'CHROME_CRASHPAD_PIPE_NAME')) { + Remove-Item -Path ("Env:\" + $envVar) -ErrorAction SilentlyContinue + } + foreach ($client in $script:clientsToRestart) { + $start = @{ FilePath = $client.path; WorkingDirectory = [IO.Path]::GetDirectoryName($client.path) } + if ($client.useDebugPort) { $start.ArgumentList = '--remote-debugging-port=0' } + [void](Start-Process @start -PassThru) + } + $script:clientsToRestart = @() + $script:clientsStopped = $false +} + +function Schedule-AccountSwitch($request) { + if (Test-AccountFile $request.statusFile) { + $status = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile)) + if ($status.state -eq 'starting' -and ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $status.updatedAt) -lt 120000) { + return @{ error = 'busy' } + } + } + $request.action = 'switch' + $request | Add-Member -NotePropertyName restartClients -NotePropertyValue $true -Force + $job = Join-Path ([IO.Path]::GetDirectoryName($request.vault)) ('switch-' + [guid]::NewGuid().ToString() + '.dpapi') + Save-Vault $job $request + Write-SwitchState $request 'starting' + $scriptPath = $request.scriptPath.Replace("'", "''") + $jobLiteral = $job.Replace("'", "''") + $code = "& '$scriptPath' -JobPath '$jobLiteral'" + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code)) + $shell = Join-Path $env:SystemRoot 'System32/WindowsPowerShell/v1.0/powershell.exe' + $command = '"' + $shell + '" -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand ' + $encoded + try { + # WMI starts the worker outside the client job so closing the App cannot terminate the switch. + $started = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $command } + if ($started.ReturnValue -ne 0) { throw 'switchStartFailed' } + } catch { + [IO.File]::Delete($job) + Write-SwitchState $request 'failed' 'switchStartFailed' + return @{ error = 'switchStartFailed' } + } + return @{ scheduled = $true; accounts = @(); selectedEmail = $request.email } } function Add-NativeCredentialType { @@ -114,91 +275,201 @@ function Invoke-AccountAction($request) { $vault = @{ entries = @(); selectedEmail = '' } if (Test-AccountFile $request.vault) { $plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($request.vault), $null, 'CurrentUser') - $vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain)) + try { + $vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain)) + } finally { + if ($plain) { [Array]::Clear($plain, 0, $plain.Length) } + } } + $vaultSecured = [bool]($vault.security -and $vault.security.enabled) $entry = $vault.entries | Where-Object { $_.email -eq $request.email } | Select-Object -First 1 if ($null -ne $request.expectedCredential -and $entry.credential -cne $request.expectedCredential) { return @{ error = 'credentialChanged' } } switch ($request.action) { + 'inspectClients' { + $clients = Get-AccountClients + return @{ clients = @($clients.roots | ForEach-Object { @{ name = $_.Name; path = $_.ExecutablePath } }); hubs = $clients.hubs.Count } + } + 'readVault' { + return @{ + entries = @($vault.entries) + selectedEmail = [string]$vault.selectedEmail + security = $vault.security + } + } + 'writeVault' { + $nextVault = @{ + entries = @($request.entries) + selectedEmail = [string]$request.selectedEmail + } + if ($request.security) { + $nextVault.security = $request.security + } + Save-Vault $request.vault $nextVault + $vault = $nextVault + $vaultSecured = [bool]($vault.security -and $vault.security.enabled) + if ($request.clearStatus -and $request.statusFile -and (Test-AccountFile $request.statusFile)) { + try { [IO.File]::Delete($request.statusFile) } catch {} + } + } + 'scheduleSwitch' { + if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) { + return @{ error = 'vaultLocked' } + } + if (-not $entry) { return @{ error = 'notFound' } } + $scheduled = Schedule-AccountSwitch $request + $scheduled.accounts = @($vault.entries | ForEach-Object { $_.email }) + if ($vaultSecured) { + $scheduled.security = @{ enabled = $true; salt = [string]$vault.security.salt } + } + return $scheduled + } 'readCurrent' { Add-NativeCredentialType $bytes = [NativeAccountCredential]::Read($request.target) - if (-not $bytes) { - foreach ($path in $request.fallbacks) { - if (Test-AccountFile $path) { - $bytes = [IO.File]::ReadAllBytes($path) - if ($bytes) { break } + try { + if (-not $bytes) { + foreach ($path in $request.fallbacks) { + if (Test-AccountFile $path) { + $bytes = [IO.File]::ReadAllBytes($path) + if ($bytes) { break } + } } } + if (-not $bytes) { return @{ error = 'noCurrentCredential' } } + return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() } + } finally { + if ($bytes) { [Array]::Clear($bytes, 0, $bytes.Length) } } - if (-not $bytes) { return @{ error = 'noCurrentCredential' } } - return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() } } 'read' { if (-not $entry) { return @{ error = 'notFound' } } - return @{ credential = $entry.credential } + $readOut = @{ credential = $entry.credential } + if ($vaultSecured) { + $readOut.security = @{ enabled = $true; salt = [string]$vault.security.salt } + } + return $readOut } 'save' { + if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) { + return @{ error = 'vaultLocked' } + } if ($entry) { $entry.credential = $request.credential } else { $vault.entries = @($vault.entries) + @(@{ email = $request.email; credential = $request.credential }) } Save-Vault $request.vault $vault } + 'saveQuota' { + if (-not $entry) { return @{ error = 'notFound' } } + $entry | Add-Member -NotePropertyName quota -NotePropertyValue $request.quota -Force + Save-Vault $request.vault $vault + } 'switch' { if (-not $entry) { return @{ error = 'notFound' } } $replacement = $utf8.GetBytes($request.credential) - if ($replacement.Length -gt 2560) { return @{ error = 'credentialTooLarge' } } + if ($replacement.Length -gt 2560) { + [Array]::Clear($replacement, 0, $replacement.Length) + return @{ error = 'credentialTooLarge' } + } Add-NativeCredentialType + if ($request.restartClients) { Stop-AccountClients } $previous = [NativeAccountCredential]::Read($request.target) $fallbacks = @(foreach ($path in $request.fallbacks) { if (Test-AccountFile $path) { @{ path = $path; original = [IO.File]::ReadAllBytes($path) } } + elseif ([IO.Directory]::Exists([IO.Path]::GetDirectoryName($path))) { @{ path = $path; original = $null } } }) $written = @() - [NativeAccountCredential]::Write($request.target, $replacement) try { - foreach ($fallback in $fallbacks) { - Write-AccountFile $fallback.path $replacement - $written += $fallback + [NativeAccountCredential]::Write($request.target, $replacement) + try { + foreach ($fallback in $fallbacks) { + Write-AccountFile $fallback.path $replacement + $written += $fallback + } + $entry.credential = if ($request.vaultCredential) { $request.vaultCredential } else { $entry.credential } + $vault.selectedEmail = $request.email + Save-Vault $request.vault $vault + } catch { + $restored = $true + try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false } + foreach ($fallback in $written) { + try { + if ($null -eq $fallback.original) { [IO.File]::Delete($fallback.path) } + else { Write-AccountFile $fallback.path $fallback.original } + } catch { $restored = $false } + } + if (-not $restored) { return @{ error = 'rollbackFailed' } } + throw } - $entry.credential = $request.credential - $vault.selectedEmail = $request.email - Save-Vault $request.vault $vault - } catch { - $restored = $true - try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false } - foreach ($fallback in $written) { - try { Write-AccountFile $fallback.path $fallback.original } catch { $restored = $false } - } - if (-not $restored) { return @{ error = 'rollbackFailed' } } - throw + } finally { + if ($replacement) { [Array]::Clear($replacement, 0, $replacement.Length) } + if ($previous) { [Array]::Clear($previous, 0, $previous.Length) } } } 'remove' { + if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) { + return @{ error = 'vaultLocked' } + } if (-not $entry) { return @{ error = 'notFound' } } $vault.entries = @($vault.entries | Where-Object { $_.email -ne $request.email }) if ($vault.selectedEmail -eq $request.email) { $vault.selectedEmail = '' } Save-Vault $request.vault $vault + if ($request.statusFile -and (Test-AccountFile $request.statusFile)) { + try { + $st = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile)) + if ($st.email -eq $request.email -and $st.state -ne 'starting') { [IO.File]::Delete($request.statusFile) } + } catch {} + } } } - return @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail } + $quotas = @{} + foreach ($account in $vault.entries) { if ($account.quota) { $quotas[$account.email] = $account.quota } } + $result = @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail; quotas = $quotas } + if ($vaultSecured) { + $result.security = @{ enabled = $true; salt = [string]$vault.security.salt } + } + if ($request.statusFile -and (Test-AccountFile $request.statusFile)) { + try { $result.switchState = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile)) } catch {} + } + return $result } $mutex = $null $locked = $false try { - $request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd()) + if ($JobPath) { + Add-Type -AssemblyName System.Security + $jobPlain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($JobPath), $null, 'CurrentUser') + try { + $request = ConvertFrom-Json -InputObject ($utf8.GetString($jobPlain)) + } finally { + if ($jobPlain) { [Array]::Clear($jobPlain, 0, $jobPlain.Length) } + } + } else { + $request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd()) + } $mutex = [Threading.Mutex]::new($false, 'Local\AntigravityUsageMonitor.AccountCredentials') - try { $locked = $mutex.WaitOne(4000) } catch [Threading.AbandonedMutexException] { $locked = $true } + $waitTimeoutMs = if ($JobPath) { 15000 } else { 5000 } + try { $locked = $mutex.WaitOne($waitTimeoutMs) } catch [Threading.AbandonedMutexException] { $locked = $true } $result = if ($locked) { Invoke-AccountAction $request } else { @{ error = 'busy' } } + if ($JobPath) { Write-SwitchState $request $(if ($result.error) { 'failed' } else { 'written' }) $result.error } } catch { $result = @{ error = 'storeFailed' } $nativeError = $_.Exception.InnerException if ($nativeError -is [ComponentModel.Win32Exception] -and $nativeError.NativeErrorCode -in 5, 1312) { $result.error = 'credentialAccessDenied' } + if ($_.Exception.Message -match 'clientCloseFailed') { $result.error = 'clientCloseFailed' } + if ($JobPath -and $request) { Write-SwitchState $request 'failed' $result.error } } finally { + if ($JobPath) { + if ($script:clientsStopped) { + try { Start-AccountClients } catch { Write-SwitchState $request 'failed' 'clientRestartFailed' } + } + [IO.File]::Delete($JobPath) + } if ($locked) { $mutex.ReleaseMutex() } if ($mutex) { $mutex.Dispose() } } -[Console]::Write((ConvertTo-Json -InputObject $result -Compress)) +[Console]::Write((ConvertTo-Json -InputObject $result -Depth 10 -Compress)) diff --git a/sidecars/panel/backend/account-http.mjs b/sidecars/panel/backend/account-http.mjs new file mode 100644 index 0000000..78610c2 --- /dev/null +++ b/sidecars/panel/backend/account-http.mjs @@ -0,0 +1,67 @@ +/** @fileoverview Google account requests using the panel's system proxy transport. */ + +import * as http from 'node:http'; +import * as https from 'node:https'; +import * as net from 'node:net'; +import * as tls from 'node:tls'; +import { detectSystemHttpsProxy, openCcProxyTunnelSocket } from './cloudcode-proxy.mjs'; + +export async function fetchGoogleAccount(url, { method = 'GET', body, headers = {}, signal } = {}) { + const target = new URL(url); + if (target.protocol !== 'https:' || !/^(?:oauth2|www|cloudcode-pa|daily-cloudcode-pa(?:\.sandbox)?)\.googleapis\.com$/.test(target.hostname)) { + throw new Error('Unsupported Google account endpoint'); + } + signal?.throwIfAborted(); + const proxy = await detectSystemHttpsProxy(target.hostname); + signal?.throwIfAborted(); + const socket = proxy + ? await openCcProxyTunnelSocket({ http, https, net, tls }, target.hostname, 443, proxy, { timeoutMs: 4500 }) + : null; + if (signal?.aborted) { + socket?.destroy(); + signal.throwIfAborted(); + } + const textBody = body === undefined ? undefined : String(body); + const requestHeaders = { Accept: 'application/json', ...headers }; + if (body instanceof URLSearchParams) requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded'; + if (textBody !== undefined) requestHeaders['Content-Length'] = Buffer.byteLength(textBody); + let socketConsumed = false; + const agent = socket ? new https.Agent({ keepAlive: false }) : null; + if (agent) { + agent.createConnection = () => { + socketConsumed = true; + return socket; + }; + } + const onAbort = () => { + if (!socketConsumed) socket?.destroy(); + }; + signal?.addEventListener?.('abort', onAbort, { once: true }); + + return new Promise((resolve, reject) => { + const request = https.request(target, { method, headers: requestHeaders, signal, ...(agent ? { agent } : {}) }, (response) => { + const chunks = []; + let bytes = 0; + response.on('data', (chunk) => { + bytes += chunk.length; + if (bytes > 4 * 1024 * 1024) return request.destroy(new Error('Account response too large')); + chunks.push(chunk); + }); + response.on('error', reject); + response.on('end', () => { + const raw = Buffer.concat(chunks).toString('utf8'); + const status = response.statusCode || 0; + resolve({ status, ok: status >= 200 && status < 300, json: async () => JSON.parse(raw) }); + }); + }); + request.on('error', (err) => { + if (!socketConsumed) socket?.destroy(); + reject(err); + }); + request.on('close', () => { + signal?.removeEventListener?.('abort', onAbort); + agent?.destroy(); + }); + request.end(textBody); + }); +} diff --git a/sidecars/panel/backend/account-login.mjs b/sidecars/panel/backend/account-login.mjs new file mode 100644 index 0000000..d0d40ed --- /dev/null +++ b/sidecars/panel/backend/account-login.mjs @@ -0,0 +1,168 @@ +/** @fileoverview Browser authorization and loopback callbacks for adding Google accounts. */ + +import { execFile } from 'node:child_process'; +import { createHash, randomBytes, randomUUID } from 'node:crypto'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; +import { buildGoogleAccountLoginUrl, exchangeGoogleAccountCode } from './account-oauth.mjs'; + +function openGoogleAccountBrowser(url) { + const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'); + return new Promise((resolve) => { + execFile(shell, ['-NoProfile', '-NonInteractive', '-Command', 'Start-Process -FilePath $env:USAGE_MONITOR_LOGIN_URL'], { + windowsHide: true, timeout: 5000, + env: { ...process.env, USAGE_MONITOR_LOGIN_URL: url }, + }, (error) => resolve(!error)); + }); +} + +function loginCallbackPage(language, success) { + const english = language === 'en-US'; + const title = english ? success ? 'Account added' : 'Sign-in incomplete' : success ? '账号已添加' : '登录未完成'; + const detail = english ? 'Return to the Antigravity account page. You can close this browser tab.' : '请返回 Antigravity 的账号页,可关闭此浏览器标签页。'; + return `${title}

${title}

${detail}

`; +} + +export function createAccountLoginController({ + openBrowser = openGoogleAccountBrowser, + buildLoginUrl = buildGoogleAccountLoginUrl, + exchangeCode = exchangeGoogleAccountCode, + getClients, + timeoutMs = 10 * 60 * 1000, +} = {}) { + let current = null; + let starting = null; + + function snapshot(flow = current) { + if (!flow) return null; + return { id: flow.id, status: flow.status, error: flow.error || '', + ...(flow.status === 'waiting' ? { url: flow.url, opened: flow.opened } : {}), + ...(flow.email ? { email: flow.email } : {}) }; + } + + function finish(flow, status, error = '') { + clearTimeout(flow.timer); + flow.status = status; + flow.error = error; + flow.server?.close(); + flow.codeVerifier = ''; + } + + function cancel(id) { + if (!current || current.id !== id) return null; + if (current.status === 'waiting' || current.status === 'exchanging') finish(current, 'cancelled'); + return snapshot(); + } + + async function start(onCredential, language = 'zh-CN') { + if (starting) return starting; + if (current && ['waiting', 'exchanging', 'saving'].includes(current.status)) return snapshot(); + starting = prepare(onCredential, language).finally(() => { starting = null; }); + return starting; + } + + async function prepare(onCredential, language) { + const flow = { id: randomUUID(), state: randomBytes(32).toString('base64url'), + codeVerifier: randomBytes(32).toString('base64url'), status: 'waiting', opened: false }; + current = flow; + const server = createServer({ maxHeaderSize: 16384 }, async (request, response) => { + response.setHeader('Cache-Control', 'no-store'); + response.setHeader('Referrer-Policy', 'no-referrer'); + response.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"); + let url; + try { url = new URL(request.url || '/', 'http://127.0.0.1'); } catch { + response.writeHead(400).end(); + return; + } + if (!flow.redirectUri || request.method !== 'GET' || request.headers.host !== new URL(flow.redirectUri).host || url.pathname !== '/oauth-callback') { + response.writeHead(404).end(); + return; + } + if (url.searchParams.get('state') !== flow.state) { + response.writeHead(400).end(); + return; + } + if (current !== flow || flow.status !== 'waiting') { + response.writeHead(409).end(); + return; + } + response.setHeader('Content-Type', 'text/html; charset=utf-8'); + if (url.searchParams.has('error')) { + finish(flow, 'cancelled', 'loginDenied'); + response.writeHead(200).end(loginCallbackPage(language, false)); + return; + } + const code = url.searchParams.get('code'); + if (!code || code.length > 4096) { + response.writeHead(400).end(loginCallbackPage(language, false)); + return; + } + flow.status = 'exchanging'; + try { + const credential = await exchangeCode( + code, + flow.redirectUri, + flow.codeVerifier, + getClients ? { getClients } : undefined + ); + if (current !== flow || flow.status !== 'exchanging') { + response.writeHead(409).end(loginCallbackPage(language, false)); + return; + } + flow.status = 'saving'; + await onCredential(credential); + flow.email = credential.email; + finish(flow, 'success'); + response.writeHead(200).end(loginCallbackPage(language, true)); + } catch (error) { + if (current === flow && ['exchanging', 'saving'].includes(flow.status)) { + const preservedError = [ + 'storeFailed', + 'credentialTooLarge', + 'credentialAccessDenied', + 'busy', + 'oauthClientUnavailable', + ].includes(error?.message); + finish(flow, 'error', preservedError ? error.message : 'loginExchangeFailed'); + } + response.writeHead(500).end(loginCallbackPage(language, false)); + } + }); + flow.server = server; + server.headersTimeout = 10000; + server.requestTimeout = 30000; + server.keepAliveTimeout = 1000; + try { + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { server.off('error', reject); resolve(); }); + }); + flow.redirectUri = `http://127.0.0.1:${server.address().port}/oauth-callback`; + const challenge = createHash('sha256').update(flow.codeVerifier).digest('base64url'); + flow.url = await buildLoginUrl( + flow.redirectUri, + flow.state, + challenge, + getClients ? { getClients } : undefined + ); + server.unref(); + flow.timer = setTimeout(() => { + if (current === flow && ['waiting', 'exchanging'].includes(flow.status)) finish(flow, 'expired', 'loginExpired'); + }, timeoutMs); + flow.timer.unref?.(); + flow.opened = await openBrowser(flow.url).catch(() => false); + return snapshot(flow); + } catch (error) { + finish( + flow, + 'error', + error?.message === 'oauthClientUnavailable' ? 'oauthClientUnavailable' : 'loginStartFailed' + ); + return snapshot(flow); + } + } + + return { start, cancel, getStatus: (id) => !id || current?.id === id ? snapshot() : null }; +} + +export const accountLoginController = createAccountLoginController(); diff --git a/sidecars/panel/backend/account-oauth.mjs b/sidecars/panel/backend/account-oauth.mjs index 28c8daf..84e133e 100644 --- a/sidecars/panel/backend/account-oauth.mjs +++ b/sidecars/panel/backend/account-oauth.mjs @@ -1,86 +1,413 @@ /** @fileoverview Google OAuth identity and quota queries for saved Antigravity credentials. */ -import { readFile } from 'node:fs/promises'; +import { execFile } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, promises as fsPromises } from 'node:fs'; import { homedir } from 'node:os'; -import { join } from 'node:path'; +import { basename, dirname, join } from 'node:path'; +import { fetchGoogleAccount } from './account-http.mjs'; import { buildOfficialQuotaPools } from './quota-pools.mjs'; const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token'; const OAUTH_USER_URL = 'https://www.googleapis.com/oauth2/v2/userinfo'; -const CLOUD_CODE_HOSTS = ['cloudcode-pa.googleapis.com', 'daily-cloudcode-pa.googleapis.com']; -let nativeOAuthClients; +const CLOUD_CODE_HOSTS = [ + 'daily-cloudcode-pa.googleapis.com', + 'cloudcode-pa.googleapis.com', + 'daily-cloudcode-pa.sandbox.googleapis.com', +]; +const OAUTH_CLIENT_ID_RE = /^\d+-[\w-]+\.apps\.googleusercontent\.com$/; +const OAUTH_CLIENT_SECRET_RE = /^GOCSPX-[\w-]+$/; +// One-way SHA-256 digest of the official Antigravity desktop OAuth client_id for synchronous allowlist checks +// without embedding plaintext OAuth credentials in source control. +const OFFICIAL_OAUTH_CLIENT_ID_HASHES = Object.freeze( + new Set(['bf00c418024ba6bf606ccdc37120976e41bc429dd1d46ecf16a729aa532626ea']) +); +const ACCOUNT_USER_AGENT = `antigravity/hub/4.3.0 (os_type=${process.platform === 'win32' ? 'windows' : process.platform}; arch=${process.arch === 'x64' ? 'amd64' : process.arch})`; + +const PE_ID_LEN_OP = Buffer.from([0x48, 0xc7, 0x40, 0x08]); +const PE_LEA_RIP_OP = Buffer.from([0x48, 0x8d, 0x0d]); +const PE_BETWEEN_OP = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]); + +let nativeOAuthClientsPromise = null; +const discoveredAllowedClientIds = new Set(); + +function sha256Hex(value) { + return createHash('sha256').update(String(value || ''), 'utf8').digest('hex'); +} + +function parsePeTextAndRdata(headerBuf) { + if (!Buffer.isBuffer(headerBuf) || headerBuf.length < 64) return null; + const pe = headerBuf.readUInt16LE(0) === 0x5a4d ? headerBuf.readUInt32LE(60) : 0; + if (!pe || pe + 24 > headerBuf.length || headerBuf.readUInt32LE(pe) !== 0x4550 || headerBuf.readUInt16LE(pe + 4) !== 0x8664) { + return null; + } + const count = headerBuf.readUInt16LE(pe + 6); + const table = pe + 24 + headerBuf.readUInt16LE(pe + 20); + if (table + count * 40 > headerBuf.length) return null; + + let text = null; + let rodata = null; + for (let i = 0; i < count; i += 1) { + const offset = table + i * 40; + const name = headerBuf.toString('ascii', offset, offset + 8).replace(/\0+$/, ''); + const section = { + name, + rva: headerBuf.readUInt32LE(offset + 12), + size: headerBuf.readUInt32LE(offset + 16), + start: headerBuf.readUInt32LE(offset + 20), + }; + if (name === '.text') text = section; + else if (name === '.rdata') rodata = section; + } + return text && rodata ? { text, rodata } : null; +} + +// Go's x64 OAuth config initializer stores ClientID and ClientSecret as two consecutive pointer/length pairs. +function scanGoOAuthInitializerMatches(machineCode, textRva, rodata) { + const matches = []; + for ( + let i = machineCode.indexOf(PE_ID_LEN_OP); + i >= 0 && i + 33 <= machineCode.length; + i = machineCode.indexOf(PE_ID_LEN_OP, i + 1) + ) { + if ( + !machineCode.subarray(i + 8, i + 11).equals(PE_LEA_RIP_OP) || + !machineCode.subarray(i + 15, i + 22).equals(PE_BETWEEN_OP) || + !machineCode.subarray(i + 26, i + 29).equals(PE_LEA_RIP_OP) + ) { + continue; + } + const idLen = machineCode.readUInt32LE(i + 4); + const secretLen = machineCode.readUInt32LE(i + 22); + if (idLen <= 0 || idLen > 100 || secretLen <= 0 || secretLen > 100) continue; + const idRva = textRva + (i + 11) + 4 + machineCode.readInt32LE(i + 11); + const secretRva = textRva + (i + 29) + 4 + machineCode.readInt32LE(i + 29); + const idOffset = idRva - rodata.rva; + const secretOffset = secretRva - rodata.rva; + if ( + idOffset < 0 || + idOffset + idLen > rodata.size || + secretOffset < 0 || + secretOffset + secretLen > rodata.size + ) { + continue; + } + matches.push({ idOffset, idLen, secretOffset, secretLen }); + } + return matches; +} export function extractNativeOAuthClients(binary) { - const pe = binary.length >= 64 && binary.readUInt16LE(0) === 0x5a4d ? binary.readUInt32LE(60) : 0; - if (!pe || pe + 24 > binary.length || binary.readUInt32LE(pe) !== 0x4550 || binary.readUInt16LE(pe + 4) !== 0x8664) return []; - const count = binary.readUInt16LE(pe + 6); - const table = pe + 24 + binary.readUInt16LE(pe + 20); - if (table + count * 40 > binary.length) return []; - - const sections = Array.from({ length: count }, (_, i) => { - const offset = table + i * 40; - return { - name: binary.toString('ascii', offset, offset + 8).replace(/\0+$/, ''), - rva: binary.readUInt32LE(offset + 12), - size: binary.readUInt32LE(offset + 16), - start: binary.readUInt32LE(offset + 20), - }; - }); - const text = sections.find(({ name }) => name === '.text'); - const rodata = sections.find(({ name }) => name === '.rdata'); - if (!text || !rodata || text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) return []; - const machineCode = binary.subarray(text.start, text.start + text.size); - - function readLiteral(displacementOffset, length) { - const rva = text.rva + displacementOffset + 4 + machineCode.readInt32LE(displacementOffset); - const offset = rva - rodata.rva; - if (length > 100 || offset < 0 || offset + length > rodata.size) return ''; - return binary.toString('ascii', rodata.start + offset, rodata.start + offset + length); + const sections = parsePeTextAndRdata(binary); + if (!sections) return []; + const { text, rodata } = sections; + if (text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) { + return []; } - - // Go's x64 OAuth config initializer sets ClientID and ClientSecret as two consecutive pointer/length pairs. - const idLength = Buffer.from([0x48, 0xc7, 0x40, 0x08]); - const loadAndStoreId = Buffer.from([0x48, 0x8d, 0x0d]); - const betweenLiterals = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]); + const machineCode = binary.subarray(text.start, text.start + text.size); const clients = new Map(); - for (let i = machineCode.indexOf(idLength); i >= 0 && i + 33 <= machineCode.length; i = machineCode.indexOf(idLength, i + 1)) { - if (!machineCode.subarray(i + 8, i + 11).equals(loadAndStoreId) || - !machineCode.subarray(i + 15, i + 22).equals(betweenLiterals) || - !machineCode.subarray(i + 26, i + 29).equals(loadAndStoreId)) continue; - const id = readLiteral(i + 11, machineCode.readUInt32LE(i + 4)); - const secret = readLiteral(i + 29, machineCode.readUInt32LE(i + 22)); - if (/^\d+-[\w-]+\.apps\.googleusercontent\.com$/.test(id) && /^GOCSPX-[\w-]+$/.test(secret)) { + for (const m of scanGoOAuthInitializerMatches(machineCode, text.rva, rodata)) { + const id = binary.toString('ascii', rodata.start + m.idOffset, rodata.start + m.idOffset + m.idLen); + const secret = binary.toString('ascii', rodata.start + m.secretOffset, rodata.start + m.secretOffset + m.secretLen); + if (OAUTH_CLIENT_ID_RE.test(id) && OAUTH_CLIENT_SECRET_RE.test(secret)) { clients.set(id, { id, secret }); } } return Array.from(clients.values()).reverse(); } -async function loadNativeOAuthClients() { - if (!nativeOAuthClients) { - nativeOAuthClients = (async () => { - const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'); - const binaries = [ - join(local, 'Programs', 'Antigravity', 'resources', 'bin', 'language_server.exe'), - join(homedir(), '.gemini', 'bin', 'agy.exe'), - ]; - for (const filename of binaries) { - const binary = await readFile(filename).catch(() => null); - const clients = binary ? extractNativeOAuthClients(binary) : []; - if (clients.length) return clients; +async function extractNativeOAuthClientsFromFile(filePath) { + if (typeof fsPromises === 'undefined' || typeof fsPromises?.open !== 'function') { + return []; + } + let handle = null; + try { + handle = await fsPromises.open(filePath, 'r'); + const st = await handle.stat(); + if (!st.isFile() || st.size < 64) return []; + const headerLen = Math.min(4096, st.size); + const headerBuf = Buffer.alloc(headerLen); + await handle.read(headerBuf, 0, headerLen, 0); + const sections = parsePeTextAndRdata(headerBuf); + if (!sections) return []; + const { text, rodata } = sections; + if (text.start + text.size > st.size || rodata.start + rodata.size > st.size) { + return []; + } + // Read only .text into memory and fetch matching <=100B literals directly from .rdata on demand. + const textBuf = Buffer.allocUnsafe(text.size); + let offset = 0; + while (offset < text.size) { + const { bytesRead } = await handle.read(textBuf, offset, text.size - offset, text.start + offset); + if (bytesRead <= 0) return []; + offset += bytesRead; + } + const matches = scanGoOAuthInitializerMatches(textBuf, text.rva, rodata); + const clients = new Map(); + for (const m of matches) { + const idBuf = Buffer.allocUnsafe(m.idLen); + const secBuf = Buffer.allocUnsafe(m.secretLen); + const [idRead, secRead] = await Promise.all([ + handle.read(idBuf, 0, m.idLen, rodata.start + m.idOffset), + handle.read(secBuf, 0, m.secretLen, rodata.start + m.secretOffset), + ]); + if (idRead.bytesRead !== m.idLen || secRead.bytesRead !== m.secretLen) continue; + const id = idBuf.toString('ascii'); + const secret = secBuf.toString('ascii'); + if (OAUTH_CLIENT_ID_RE.test(id) && OAUTH_CLIENT_SECRET_RE.test(secret)) { + clients.set(id, { id, secret }); + } + } + return Array.from(clients.values()).reverse(); + } catch { + return []; + } finally { + await handle?.close?.().catch(() => {}); + } +} + +export function collectNativeOAuthBinaryCandidates({ + env = process.env, + homeDir = homedir(), + existsFn = existsSync, +} = {}) { + const seen = new Set(); + const candidates = []; + const add = (filePath) => { + const clean = String(filePath || '').trim(); + if (!clean) return; + const key = clean.toLowerCase(); + if (seen.has(key)) return; + seen.add(key); + candidates.push(clean); + }; + const addFromInstallRoot = (installRoot) => { + if (!installRoot) return; + add(join(installRoot, 'resources', 'bin', 'language_server.exe')); + add(join(installRoot, 'resources', 'app', 'extensions', 'antigravity', 'bin', 'language_server_windows_x64.exe')); + }; + + add(env?.ANTIGRAVITY_LS_BIN); + const hints = [ + env?.USAGE_MONITOR_HOST_EXE, + env?.ANTIGRAVITY_AGENTAPI_EXE, + env?.CHROME_DEVTOOLS_MCP_JS, + ]; + for (const rawHint of hints) { + const hint = String(rawHint || '').trim(); + if (!hint) continue; + const leaf = basename(hint).toLowerCase(); + if (/^(?:language_server.*|agy)\.exe$/i.test(leaf)) { + add(hint); + continue; + } + if (/\.exe$/i.test(leaf)) { + addFromInstallRoot(dirname(hint)); + } + let cur = hint; + for (let depth = 0; depth < 8 && cur && dirname(cur) !== cur; depth += 1) { + if (basename(cur).toLowerCase() === 'resources') { + addFromInstallRoot(dirname(cur)); + break; + } + cur = dirname(cur); + } + } + + const localAppData = String(env?.LOCALAPPDATA || '').trim() || join(homeDir, 'AppData', 'Local'); + const programFiles = String(env?.ProgramFiles || '').trim() || 'C:\\Program Files'; + const geminiBase = String(env?.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homeDir, '.gemini'); + addFromInstallRoot(join(localAppData, 'Programs', 'Antigravity')); + addFromInstallRoot(join(localAppData, 'Programs', 'Antigravity IDE')); + addFromInstallRoot(join(programFiles, 'Antigravity')); + addFromInstallRoot(join(programFiles, 'Antigravity IDE')); + add(join(geminiBase, 'bin', 'agy.exe')); + + if (typeof existsFn !== 'function') return candidates; + return candidates.filter((p) => { + try { + return Boolean(existsFn(p)); + } catch { + return false; + } + }); +} + +function discoverRunningOAuthBinaryPaths() { + if (process.platform !== 'win32' || typeof execFile !== 'function') { + return Promise.resolve([]); + } + const shell = join( + process.env.SystemRoot || 'C:/Windows', + 'System32', + 'WindowsPowerShell', + 'v1.0', + 'powershell.exe' + ); + const cmd = + "Get-CimInstance Win32_Process -Filter \"Name LIKE 'language_server%' OR Name LIKE 'agy%'\" | Select-Object -ExpandProperty ExecutablePath -Unique"; + return new Promise((resolve) => { + execFile( + shell, + ['-NoProfile', '-NonInteractive', '-Command', cmd], + { windowsHide: true, timeout: 3000, encoding: 'utf8' }, + (err, stdout) => { + if (err || !stdout) { + resolve([]); + return; + } + const paths = String(stdout) + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((p) => /^(?:language_server.*|agy)\.exe$/i.test(basename(p))); + resolve(paths); } - return []; - })(); + ); + }); +} + +function rememberDiscoveredClients(clients) { + for (const client of clients) { + if (client?.id) discoveredAllowedClientIds.add(client.id); + } + return Object.freeze(clients.map((c) => Object.freeze({ id: c.id, secret: c.secret }))); +} + +export async function loadNativeOAuthClients(options = undefined) { + const customRun = Boolean(options && Object.keys(options).length > 0); + const env = options?.env ?? process.env; + const overrideId = String(env?.USAGE_MONITOR_OAUTH_CLIENT_ID || '').trim(); + const overrideSecret = String(env?.USAGE_MONITOR_OAUTH_CLIENT_SECRET || '').trim(); + if (OAUTH_CLIENT_ID_RE.test(overrideId) && OAUTH_CLIENT_SECRET_RE.test(overrideSecret)) { + return rememberDiscoveredClients([{ id: overrideId, secret: overrideSecret }]); + } + + const runLoad = async () => { + const extractFromFileFn = options?.extractFromFileFn || extractNativeOAuthClientsFromFile; + const discoverRunningFn = options?.discoverRunningFn || discoverRunningOAuthBinaryPaths; + const candidates = collectNativeOAuthBinaryCandidates({ + env, + homeDir: options?.homeDir ?? homedir(), + existsFn: options?.existsFn ?? existsSync, + }); + const tried = new Set(); + for (const filePath of candidates) { + tried.add(filePath.toLowerCase()); + const clients = await extractFromFileFn(filePath); + if (Array.isArray(clients) && clients.length > 0) { + return rememberDiscoveredClients(clients); + } + } + const runningPaths = await discoverRunningFn().catch(() => []); + for (const filePath of runningPaths) { + const key = String(filePath || '').trim().toLowerCase(); + if (!key || tried.has(key)) continue; + tried.add(key); + const clients = await extractFromFileFn(filePath); + if (Array.isArray(clients) && clients.length > 0) { + return rememberDiscoveredClients(clients); + } + } + return Object.freeze([]); + }; + + if (customRun) { + return runLoad(); + } + if (!nativeOAuthClientsPromise) { + nativeOAuthClientsPromise = runLoad(); + } + const clients = await nativeOAuthClientsPromise; + if (!clients.length) { + nativeOAuthClientsPromise = null; } - const clients = await nativeOAuthClients; - if (!clients.length) nativeOAuthClients = null; return clients; } -export async function resolveGoogleCredential(credential, { refresh = false, fetchFn = fetch, getClients = loadNativeOAuthClients } = {}) { +export function isAllowedOAuthClientId(clientId, allowedIds = null) { + if (typeof clientId !== 'string') return false; + const clean = clientId.trim(); + if (!clean) return false; + if (allowedIds) { + if (allowedIds instanceof Set && allowedIds.has(clean)) return true; + if (Array.isArray(allowedIds) && allowedIds.includes(clean)) return true; + } + if (discoveredAllowedClientIds.has(clean)) return true; + return OFFICIAL_OAUTH_CLIENT_ID_HASHES.has(sha256Hex(clean)); +} + +export async function buildGoogleAccountLoginUrl( + redirectUri, + state, + codeChallenge, + { getClients = loadNativeOAuthClients } = {} +) { + const clients = await getClients(); + if (!Array.isArray(clients) || !clients.length || !clients[0]?.id) { + throw new Error('oauthClientUnavailable'); + } + const url = new URL('https://accounts.google.com/o/oauth2/v2/auth'); + url.search = new URLSearchParams({ + client_id: clients[0].id, + redirect_uri: redirectUri, + response_type: 'code', + scope: [ + 'openid', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/aicode', + 'https://www.googleapis.com/auth/userinfo.email', + 'https://www.googleapis.com/auth/userinfo.profile', + 'https://www.googleapis.com/auth/cclog', + 'https://www.googleapis.com/auth/experimentsandconfigs', + ].join(' '), + access_type: 'offline', + prompt: 'consent select_account', + state, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }).toString(); + return url.toString(); +} + +export async function exchangeGoogleAccountCode( + code, + redirectUri, + codeVerifier, + { fetchFn = fetchGoogleAccount, getClients = loadNativeOAuthClients } = {} +) { + const clients = await getClients(); + if (!Array.isArray(clients) || !clients.length || !clients[0]?.id || !clients[0]?.secret) { + throw new Error('oauthClientUnavailable'); + } + const client = clients[0]; + const response = await fetchFn(OAUTH_TOKEN_URL, { + method: 'POST', redirect: 'error', signal: AbortSignal.timeout(15000), + headers: { 'User-Agent': ACCOUNT_USER_AGENT }, + body: new URLSearchParams({ + client_id: client.id, + client_secret: client.secret, + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + code_verifier: codeVerifier, + }), + }); + const result = await response.json(); + if (!response.ok || !result.access_token || !result.refresh_token || + !Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error('loginExchangeFailed'); + return resolveGoogleCredential({ + token: { ...result, expiry: new Date(Date.now() + result.expires_in * 1000).toISOString() }, + ...(result.id_token ? { id_token: result.id_token } : {}), + }, { fetchFn, getClients: async () => clients }); +} + +export async function resolveGoogleCredential( + credential, + { refresh = false, fetchFn = fetchGoogleAccount, getClients = loadNativeOAuthClients } = {} +) { let { access_token: accessToken, refresh_token: refreshToken, expiry } = credential.token; let idToken = credential.id_token; - if (refresh || !accessToken || Date.parse(expiry) <= Date.now() + 60_000) { + if (refresh || !accessToken || !Number.isFinite(Date.parse(expiry)) || Date.parse(expiry) <= Date.now() + 60_000) { const clients = await getClients(); if (!clients.length) throw new Error('oauthClientUnavailable'); let refreshed = false; @@ -117,23 +444,67 @@ export async function resolveGoogleCredential(credential, { refresh = false, fet auth_method: 'consumer', id_token_email: user.email, ...(idToken ? { id_token: idToken } : {}), + ...(Number.isSafeInteger(credential.aicode_scope_sign_out_attempted_at) && + credential.aicode_scope_sign_out_attempted_at > 0 + ? { aicode_scope_sign_out_attempted_at: credential.aicode_scope_sign_out_attempted_at } + : {}), }, }; } -export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) { - async function post(method, data) { - for (const host of CLOUD_CODE_HOSTS) { +export function resolveSetupTierInfo(setup) { + const tierObj = setup?.paidTier || setup?.currentTier || setup?.userTier || null; + if (!tierObj) return null; + const tierId = String(tierObj?.id || '').trim(); + const rawName = String(tierObj?.name || '').trim(); + const rawDesc = String(tierObj?.description || '').trim(); + const tierIdLower = tierId.toLowerCase(); + const tierText = `${tierId} ${rawName} ${rawDesc}`; + const tierMultiplier = /(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(tierText) + ? '5x' + : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(tierText) || + tierIdLower === 'g1-ultra-tier' || + (/^g1-ultra(?:-[a-z0-9]+)?-tier$/i.test(tierIdLower) && !/lite|5x/i.test(tierIdLower)) + ? '20x' + : ''; + const tierName = + rawName || + (/ultra/i.test(tierIdLower) + ? 'Google AI Ultra' + : /pro/i.test(tierIdLower) + ? 'Google AI Pro' + : /free|standard/i.test(tierIdLower) + ? 'Google AI Free' + : ''); + if (!tierName && !tierId) return null; + return { tierId, tierName: tierName || 'Google AI', tierMultiplier }; +} + +export async function retrieveCredentialQuota(accessToken, fetchFn = fetchGoogleAccount) { + let preferredHost = ''; + async function post(method, data, retryWithoutProject = true) { + const hosts = preferredHost + ? [preferredHost, ...CLOUD_CODE_HOSTS.filter((h) => h !== preferredHost)] + : CLOUD_CODE_HOSTS; + for (const host of hosts) { const response = await fetchFn(`https://${host}/v1internal:${method}`, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4500), - headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, + headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json', 'User-Agent': ACCOUNT_USER_AGENT }, body: JSON.stringify(data), }).catch(() => null); if (response?.ok) { const payload = await response.json().catch(() => null); - if (payload) return payload.response ?? payload; + const result = payload?.response ?? payload; + const valid = method === 'loadCodeAssist' ? result && typeof result === 'object' : + method === 'fetchAvailableModels' ? result?.models && typeof result.models === 'object' : + Array.isArray(result?.groups) || Array.isArray(result?.quotaSummary?.groups) || Array.isArray(result?.buckets); + if (valid) { + preferredHost = host; + return result; + } } - if (response?.status === 401 || response?.status === 403) break; + if (response?.status === 401) throw new Error('credentialRejected'); + if (response?.status === 403 && data.project && retryWithoutProject) return post(method, {}, false); } return null; } @@ -141,9 +512,8 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) { const setup = await post('loadCodeAssist', { metadata: { ideType: 'ANTIGRAVITY' } }); const project = setup?.cloudaicompanionProject?.id || setup?.cloudaicompanionProject; if (!setup) throw new Error('quotaUnavailable'); - const request = { - project: typeof project === 'string' && project ? project : 'cloudaicompanion-enterprise', - }; + const tierInfo = resolveSetupTierInfo(setup); + const request = typeof project === 'string' && project ? { project } : {}; const clientConfigs = setup.cascadeModelConfigData?.clientModelConfigs; const [summary, available] = await Promise.all([ post('retrieveUserQuotaSummary', request), @@ -167,7 +537,7 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) { buckets: adaptBuckets(raw?.buckets), }; const { quotaPoolsMap } = buildOfficialQuotaPools(quota, configs); - return Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({ + const pools = Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({ poolKey: pool.poolKey, poolLabel: pool.poolLabel, remainingPct: pool.remainingPct, @@ -175,4 +545,9 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) { resetTime: pool.resetTime, weeklyResetTime: pool.weeklyResetTime, })); + if (tierInfo) { + Object.defineProperty(pools, 'tierInfo', { value: tierInfo, enumerable: false }); + Object.defineProperty(pools, 'tierName', { value: tierInfo.tierName, enumerable: false }); + } + return pools; } diff --git a/sidecars/panel/backend/account-switch.mjs b/sidecars/panel/backend/account-switch.mjs index 1f426b6..4b86355 100644 --- a/sidecars/panel/backend/account-switch.mjs +++ b/sidecars/panel/backend/account-switch.mjs @@ -1,11 +1,31 @@ /** @fileoverview Antigravity shared credentials and the plugin's Windows credential vault. */ import { spawn } from 'node:child_process'; -import { readFileSync } from 'node:fs'; +import { statSync } from 'node:fs'; import { homedir } from 'node:os'; import { join } from 'node:path'; -import { setTimeout as delay } from 'node:timers/promises'; -import { resolveGoogleCredential, retrieveCredentialQuota } from './account-oauth.mjs'; +import { accountLoginController } from './account-login.mjs'; +import { + isAllowedOAuthClientId, + loadNativeOAuthClients, + resolveGoogleCredential, + retrieveCredentialQuota, +} from './account-oauth.mjs'; +import { + checkVaultUnlockCooldown, + createVaultSecurityMetadata, + decryptVaultEntryCredential, + encryptVaultEntryCredential, + getUnlockedVaultSessionKey, + isEncryptedVaultCredential, + isVaultSessionUnlocked, + lockVaultSession, + normalizeVaultPassword, + recordVaultUnlockFailure, + resetVaultUnlockFailures, + setUnlockedVaultSessionKey, + verifyVaultPassword, +} from './account-vault-crypto.mjs'; import { HERE } from './config.mjs'; import { callLsRpc } from './ls-rpc.mjs'; @@ -14,33 +34,113 @@ const ACCOUNT_ERRORS = new Set([ 'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied', 'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable', 'oauthUnavailable', 'quotaUnavailable', + 'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed', + 'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordRateLimited', + 'vaultDecryptFailed', 'invalidActionNonce', ]); +const ALLOWED_ACTIONS = new Set([ + 'list', 'save', 'capture', 'switch', 'remove', 'quota', + 'loginStart', 'loginStatus', 'loginCancel', + 'setPassword', 'unlockVault', 'lockVault', 'changePassword', 'disablePassword', 'resetVault', +]); + +const MAX_TRANSIENT_TOKENS = 32; +const transientAccessTokens = new Map(); +const vaultSecurityByPath = new Map(); + +export function clearAccountVaultRuntimeState() { + lockVaultSession(); + resetVaultUnlockFailures(); + transientAccessTokens.clear(); + vaultSecurityByPath.clear(); +} + +function rememberTransientAccessToken(email, credential) { + const addr = normalizeAccountEmail(email); + const tok = credential?.token; + if (!addr || !tok?.access_token || !tok?.refresh_token) return; + const expiryMs = Date.parse(tok.expiry || ''); + if (!Number.isFinite(expiryMs) || expiryMs <= Date.now() + 60_000) return; + if (!transientAccessTokens.has(addr) && transientAccessTokens.size >= MAX_TRANSIENT_TOKENS) { + const oldestKey = transientAccessTokens.keys().next().value; + if (oldestKey !== undefined) transientAccessTokens.delete(oldestKey); + } + transientAccessTokens.set(addr, { + refreshToken: tok.refresh_token, + accessToken: tok.access_token, + expiry: tok.expiry, + ...(typeof credential.id_token === 'string' && credential.id_token + ? { idToken: credential.id_token } + : {}), + }); +} + +function clearTransientAccessTokens(email = '') { + if (email) { + transientAccessTokens.delete(normalizeAccountEmail(email)); + return; + } + transientAccessTokens.clear(); +} + export function normalizeAccountEmail(value) { const email = typeof value === 'string' ? value.trim().toLowerCase() : ''; return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : ''; } -export function normalizeAccountCredential(input) { +export function normalizeAccountCredential(input, { allowedClientIds = null } = {}) { if (typeof input !== 'string' || Buffer.byteLength(input, 'utf8') > 16384) return null; const text = input.trim(); let source; - try { source = JSON.parse(text); } catch { + try { + source = JSON.parse(text); + } catch { if (!/^1\/{1,2}[\w.-]{20,}$/.test(text)) return null; source = { refresh_token: text }; } + if (!source || typeof source !== 'object' || Array.isArray(source)) return null; + if ( + source.type !== undefined && + !['authorized_user', 'oauth2'].includes(String(source.type).trim().toLowerCase()) + ) { + return null; + } + const explicitClientId = + source.client_id ?? + source.token?.client_id ?? + source.installed?.client_id ?? + source.web?.client_id; + if (explicitClientId !== undefined && explicitClientId !== null && String(explicitClientId).trim() !== '') { + if ( + typeof explicitClientId !== 'string' || + !isAllowedOAuthClientId(explicitClientId, allowedClientIds) + ) { + return null; + } + } const token = source?.token || source; - if (!token || (source.auth_method && source.auth_method !== 'consumer') || - typeof token.refresh_token !== 'string' || !token.refresh_token.trim() || - /\s/.test(token.refresh_token) || (token.token_type && !/^bearer$/i.test(token.token_type))) return null; - const timestamp = token.expiry_date ?? (Number(token.expiry_timestamp) * 1000); - const expiry = token.expiry || (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999 - ? new Date(timestamp).toISOString() : '1970-01-01T00:00:00Z'); + if ( + !token || + (source.auth_method && source.auth_method !== 'consumer') || + typeof token.refresh_token !== 'string' || + !token.refresh_token.trim() || + /\s/.test(token.refresh_token) || + (token.token_type && !/^bearer$/i.test(token.token_type)) + ) { + return null; + } + const timestamp = token.expiry_date ?? Number(token.expiry_timestamp) * 1000; + const expiry = + token.expiry || + (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999 + ? new Date(timestamp).toISOString() + : '1970-01-01T00:00:00Z'); if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return null; const payload = { token: { access_token: typeof token.access_token === 'string' ? token.access_token : '', - refresh_token: token.refresh_token, + refresh_token: token.refresh_token.trim(), token_type: 'Bearer', expiry: new Date(expiry).toISOString(), }, @@ -48,125 +148,711 @@ export function normalizeAccountCredential(input) { }; const idToken = source.id_token || token.id_token; if (typeof idToken === 'string' && idToken) payload.id_token = idToken; + if ( + Number.isSafeInteger(source.aicode_scope_sign_out_attempted_at) && + source.aicode_scope_sign_out_attempted_at > 0 + ) { + payload.aicode_scope_sign_out_attempted_at = source.aicode_scope_sign_out_attempted_at; + } return JSON.stringify(payload); } +/** + * At-rest minimization: strips short-lived `access_token`, `id_token`, `expiry`, + * and any extra fields before persisting to `accounts.dpapi`. + */ +export function serializeVaultCredential(credential) { + const refreshToken = String(credential?.token?.refresh_token || '').trim(); + if (!refreshToken || /\s/.test(refreshToken)) { + throw new Error('invalidCredential'); + } + return JSON.stringify({ + token: { refresh_token: refreshToken, token_type: 'Bearer' }, + auth_method: 'consumer', + }); +} + export function runWindowsCredentialStore(request) { - const script = readFileSync(join(HERE, 'backend', 'account-credentials.ps1'), 'utf8'); - const encoded = Buffer.from(script, 'utf16le').toString('base64'); - const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'); + const scriptPath = join(HERE, 'backend', 'account-credentials.ps1'); + const shell = join( + process.env.SystemRoot || 'C:/Windows', + 'System32', + 'WindowsPowerShell', + 'v1.0', + 'powershell.exe' + ); return new Promise((resolve, reject) => { // The helper exchanges private data over its pipes, keeping it out of process arguments. - const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] }); + const child = spawn( + shell, + ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', scriptPath], + { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] } + ); let output = ''; child.stdout.setEncoding('utf8'); - child.stdout.on('data', (chunk) => { output += chunk; }); + child.stdout.on('data', (chunk) => { + output += chunk; + }); child.on('error', reject); child.stdin.on('error', reject); child.on('close', (code) => { if (code !== 0) return reject(new Error('storeFailed')); - try { resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); } catch { reject(new Error('storeFailed')); } + try { + resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); + } catch { + reject(new Error('storeFailed')); + } }); child.stdin.end(JSON.stringify(request), 'utf8'); }); } -function serializeHostCredential(credential) { - let payload = JSON.stringify(credential); - if (Buffer.byteLength(payload, 'utf8') > 2560 && credential.id_token) { - const { id_token, ...compact } = credential; +function serializeHostCredential(credential, { forHostSwitch = false } = {}) { + const target = + forHostSwitch && !credential.aicode_scope_sign_out_attempted_at + ? { ...credential, aicode_scope_sign_out_attempted_at: Math.floor(Date.now() / 1000) } + : credential; + let payload = JSON.stringify(target); + if (Buffer.byteLength(payload, 'utf8') > 2560 && target.id_token) { + const { id_token: _ignored, ...compact } = target; payload = JSON.stringify(compact); } if (Buffer.byteLength(payload, 'utf8') > 2560) throw new Error('credentialTooLarge'); return payload; } -async function confirmHostCredential(email, rpc) { - for (let attempt = 0; attempt < 3; attempt += 1) { - await rpc('GetAuthStatus', {}, 1200).catch(() => null); - const status = await rpc('GetUserStatus', {}, 1200).catch(() => null); - if (normalizeAccountEmail(status?.userStatus?.email) === email) return true; - if (attempt < 2) await delay(300); +let cachedPublicVaultState = null; +let cachedPublicVaultSig = ''; + +function computePublicVaultDiskSig(config) { + try { + const vStat = statSync(config.vault, { throwIfNoEntry: false }); + const sStat = config.statusFile ? statSync(config.statusFile, { throwIfNoEntry: false }) : null; + return `${config.vault}|${vStat ? `${vStat.size}:${vStat.mtimeMs}` : '0'}|${sStat ? `${sStat.size}:${sStat.mtimeMs}` : '0'}`; + } catch { + return ''; } - return false; } -export async function handleAccountCredentialAction(data, { - platform = process.platform, - store = runWindowsCredentialStore, - rpc = callLsRpc, - resolveCredential = resolveGoogleCredential, - getQuota = retrieveCredentialQuota, -} = {}) { +function recordKnownVaultSecurity(vaultPath, security) { + if (!vaultPath) return; + if (security?.enabled) { + vaultSecurityByPath.set(vaultPath, { enabled: true, salt: String(security.salt || '') }); + } else { + vaultSecurityByPath.delete(vaultPath); + } +} + +function cacheSanitizedVaultState(config, result) { + const sig = computePublicVaultDiskSig(config); + if (!sig || !result || !Array.isArray(result.accounts)) return; + cachedPublicVaultSig = sig; + cachedPublicVaultState = { + accounts: [...result.accounts], + selectedEmail: result.selectedEmail || '', + quotas: result.quotas ? { ...result.quotas } : {}, + ...(result.security?.enabled + ? { security: { enabled: true, salt: String(result.security.salt || '') } } + : {}), + ...(result.switchState ? { switchState: { ...result.switchState } } : {}), + }; +} + +export async function warmAccountPublicListCache() { + if (process.platform !== 'win32') return; + await handleAccountCredentialAction({ action: 'list' }).catch(() => null); +} + +function openStoredVaultCredential(storedRaw, email, vaultSecurity) { + let jsonText = storedRaw; + if (isEncryptedVaultCredential(storedRaw)) { + const keyBuf = getUnlockedVaultSessionKey(vaultSecurity?.salt || ''); + if (!keyBuf) throw new Error('vaultLocked'); + jsonText = decryptVaultEntryCredential(storedRaw, keyBuf, email); + } else if (vaultSecurity?.enabled && !isVaultSessionUnlocked(vaultSecurity)) { + throw new Error('vaultLocked'); + } + const normalized = normalizeAccountCredential(jsonText); + if (!normalized) throw new Error('invalidCredential'); + const parsed = JSON.parse(normalized); + if (!parsed.token.access_token) { + const cached = transientAccessTokens.get(normalizeAccountEmail(email)); + if ( + cached && + cached.refreshToken === parsed.token.refresh_token && + Date.parse(cached.expiry) > Date.now() + 60_000 + ) { + parsed.token.access_token = cached.accessToken; + parsed.token.expiry = cached.expiry; + if (cached.idToken && !parsed.id_token) parsed.id_token = cached.idToken; + } + } + return parsed; +} + +function sealVaultCredential(credentialObj, email, vaultSecurity) { + const minJson = serializeVaultCredential(credentialObj); + if (vaultSecurity?.enabled) { + const keyBuf = getUnlockedVaultSessionKey(vaultSecurity.salt); + if (!keyBuf) throw new Error('vaultLocked'); + return { + stored: encryptVaultEntryCredential(minJson, keyBuf, email), + vaultUnlocked: true, + expectedSecuritySalt: String(vaultSecurity.salt), + }; + } + return { stored: minJson, vaultUnlocked: false, expectedSecuritySalt: '' }; +} + +export async function handleAccountCredentialAction( + data, + { + platform = process.platform, + store = runWindowsCredentialStore, + rpc = callLsRpc, + resolveCredential = resolveGoogleCredential, + getQuota = retrieveCredentialQuota, + login = accountLoginController, + } = {} +) { if (platform !== 'win32') return { supported: false, accounts: [], error: 'unsupported' }; const action = data?.action || 'list'; - if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' }; + if (!ALLOWED_ACTIONS.has(action)) return { error: 'invalidCredential' }; const email = normalizeAccountEmail(data?.email); if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' }; + const gemini = String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homedir(), '.gemini'); const config = { target: 'gemini:antigravity', - vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'), - fallbacks: [join(gemini, 'jetski-standalone-oauth-token'), join(gemini, 'antigravity-cli', 'antigravity-oauth-token')], + vault: join( + process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), + 'AntigravityUsageMonitor', + 'accounts.dpapi' + ), + statusFile: join( + process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), + 'AntigravityUsageMonitor', + 'switch-state.json' + ), + scriptPath: join(HERE, 'backend', 'account-credentials.ps1'), + fallbacks: [ + join(gemini, 'jetski-standalone-oauth-token'), + join(gemini, 'antigravity-cli', 'antigravity-oauth-token'), + ], }; + + const useDiskSigCache = store === runWindowsCredentialStore; + async function runStore(fields) { const result = await store({ ...config, ...fields }); if (!result || result.error) throw new Error(result?.error || 'storeFailed'); + if (['list', 'read', 'readVault', 'writeVault', 'scheduleSwitch'].includes(fields.action)) { + recordKnownVaultSecurity(config.vault, result.security); + } + if (useDiskSigCache) { + if (fields.action === 'scheduleSwitch') { + cachedPublicVaultState = null; + cachedPublicVaultSig = ''; + } else if (['list', 'save', 'remove', 'saveQuota', 'writeVault'].includes(fields.action)) { + cacheSanitizedVaultState(config, result); + } + } return result; } + function resolveKnownVaultSecurity() { + if (useDiskSigCache && cachedPublicVaultState) { + return cachedPublicVaultState.security || null; + } + return vaultSecurityByPath.get(config.vault) || null; + } + + async function ensureUnlockedVaultContext() { + if (useDiskSigCache && !cachedPublicVaultState) { + await runStore({ action: 'list', email: '' }); + } + const sec = resolveKnownVaultSecurity(); + if (sec?.enabled && !isVaultSessionUnlocked(sec)) { + throw new Error('vaultLocked'); + } + return sec; + } + function publicList(result) { + const rawSwitchState = result.switchState; + const switchAgeMs = rawSwitchState ? Date.now() - Number(rawSwitchState.updatedAt || 0) : Infinity; + const stalled = rawSwitchState?.state === 'starting' && switchAgeMs > 120000; + const expiredSwitchState = + rawSwitchState && rawSwitchState.state !== 'starting' && switchAgeMs > 5 * 60 * 1000; + const switchState = expiredSwitchState ? null : rawSwitchState; + const sec = result.security?.enabled ? result.security : null; + const cooldownSec = checkVaultUnlockCooldown(); return { supported: true, - accounts: (Array.isArray(result.accounts) ? result.accounts : []).map(normalizeAccountEmail).filter(Boolean), - selectedEmail: normalizeAccountEmail(result.selectedEmail), + accounts: (Array.isArray(result.accounts) ? result.accounts : []) + .map(normalizeAccountEmail) + .filter(Boolean), + selectedEmail: expiredSwitchState ? '' : normalizeAccountEmail(result.selectedEmail), + quotas: result.quotas || {}, + ...(sec || data?.includeSecurity + ? { + security: { + enabled: Boolean(sec?.enabled), + unlocked: isVaultSessionUnlocked(sec), + ...(cooldownSec > 0 ? { cooldownSec } : {}), + }, + } + : {}), + ...(login.getStatus() ? { login: login.getStatus() } : {}), + ...(switchState + ? { + switchState: { + email: normalizeAccountEmail(switchState.email), + state: + !stalled && ['starting', 'written', 'failed'].includes(switchState.state) + ? switchState.state + : 'failed', + error: stalled + ? 'switchStartFailed' + : ACCOUNT_ERRORS.has(switchState.error) + ? switchState.error + : '', + }, + } + : {}), }; } - async function verifyCredential(raw, refresh = false) { - const normalized = normalizeAccountCredential(raw); - if (!normalized) throw new Error('invalidCredential'); + async function verifyCredentialObj(parsedObj, refresh = false) { let result; try { - result = await resolveCredential(JSON.parse(normalized), { refresh }); + result = await resolveCredential(parsedObj, { refresh }); } catch (error) { throw new Error(ACCOUNT_ERRORS.has(error?.message) ? error.message : 'oauthUnavailable'); } result.email = normalizeAccountEmail(result.email); if (!result.email) throw new Error('credentialRejected'); + rememberTransientAccessToken(result.email, result.credential); return result; } - try { - if (action === 'list' || action === 'remove') return publicList(await runStore({ action, email })); - if (action === 'save') { - const verified = await verifyCredential(data.credential, true); - return publicList(await runStore({ action, email: verified.email, credential: serializeHostCredential(verified.credential) })); + async function verifyCredential(raw, refresh = false) { + let normalized = normalizeAccountCredential(raw); + if (!normalized && typeof raw === 'string' && raw.includes('client_id')) { + const liveClients = await loadNativeOAuthClients().catch(() => []); + if (liveClients.length > 0) { + normalized = normalizeAccountCredential(raw, { + allowedClientIds: liveClients.map((c) => c.id), + }); + } } + if (!normalized) throw new Error('invalidCredential'); + return verifyCredentialObj(JSON.parse(normalized), refresh); + } + + try { + if (action === 'list') { + if (useDiskSigCache && cachedPublicVaultState) { + const curSig = computePublicVaultDiskSig(config); + if (curSig && curSig === cachedPublicVaultSig) { + return publicList(cachedPublicVaultState); + } + } + return publicList(await runStore({ action, email })); + } + + if (action === 'setPassword') { + const vaultData = await runStore({ action: 'readVault' }); + if (vaultData.security?.enabled) throw new Error('credentialChanged'); + const { security, keyBuf } = await createVaultSecurityMetadata( + data?.newPassword ?? data?.password + ); + try { + const nextEntries = (Array.isArray(vaultData.entries) ? vaultData.entries : []).map((entry) => { + const entryEmail = normalizeAccountEmail(entry?.email); + if (!entryEmail) throw new Error('invalidEmail'); + const norm = normalizeAccountCredential(entry.credential); + if (!norm) throw new Error('invalidCredential'); + const minJson = serializeVaultCredential(JSON.parse(norm)); + return { + ...entry, + email: entryEmail, + credential: encryptVaultEntryCredential(minJson, keyBuf, entryEmail), + }; + }); + const savedVault = await runStore({ + action: 'writeVault', + entries: nextEntries, + selectedEmail: vaultData.selectedEmail || '', + security, + }); + setUnlockedVaultSessionKey(security.salt, keyBuf); + resetVaultUnlockFailures(); + return publicList(savedVault); + } finally { + keyBuf.fill(0); + } + } + + if (action === 'unlockVault') { + const cooldownSec = checkVaultUnlockCooldown(); + if (cooldownSec > 0) { + return { error: 'passwordRateLimited', retryAfterSec: cooldownSec }; + } + const vaultData = await runStore({ action: 'readVault' }); + if (!vaultData.security?.enabled) { + return publicList({ + accounts: (vaultData.entries || []).map((e) => e.email), + selectedEmail: vaultData.selectedEmail || '', + quotas: Object.fromEntries( + (vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota]) + ), + }); + } + let keyBuf = null; + try { + keyBuf = await verifyVaultPassword(data?.password, vaultData.security); + } catch (err) { + if (err?.message === 'wrongPassword') { + const waitSec = recordVaultUnlockFailure(); + return waitSec > 0 + ? { error: 'passwordRateLimited', retryAfterSec: waitSec } + : { error: 'wrongPassword' }; + } + throw err; + } + try { + const firstEnc = (vaultData.entries || []).find((e) => + isEncryptedVaultCredential(e?.credential) + ); + if (firstEnc) { + decryptVaultEntryCredential(firstEnc.credential, keyBuf, firstEnc.email); + } + setUnlockedVaultSessionKey(vaultData.security.salt, keyBuf); + resetVaultUnlockFailures(); + return publicList({ + accounts: (vaultData.entries || []).map((e) => e.email), + selectedEmail: vaultData.selectedEmail || '', + quotas: Object.fromEntries( + (vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota]) + ), + security: { enabled: true, salt: vaultData.security.salt }, + }); + } finally { + keyBuf.fill(0); + } + } + + if (action === 'lockVault') { + lockVaultSession(); + clearTransientAccessTokens(); + const curLogin = login.getStatus(); + if (curLogin?.id && curLogin.status === 'waiting') { + login.cancel(curLogin.id); + } + return publicList(await runStore({ action: 'list', email: '' })); + } + + if (action === 'changePassword') { + const cooldownSec = checkVaultUnlockCooldown(); + if (cooldownSec > 0) { + return { error: 'passwordRateLimited', retryAfterSec: cooldownSec }; + } + if (!normalizeVaultPassword(data?.newPassword)) { + throw new Error('invalidPassword'); + } + const vaultData = await runStore({ action: 'readVault' }); + if (!vaultData.security?.enabled) throw new Error('notFound'); + let oldKeyBuf = null; + try { + oldKeyBuf = await verifyVaultPassword(data?.currentPassword, vaultData.security); + } catch (err) { + if (err?.message === 'wrongPassword') { + const waitSec = recordVaultUnlockFailure(); + return waitSec > 0 + ? { error: 'passwordRateLimited', retryAfterSec: waitSec } + : { error: 'wrongPassword' }; + } + throw err; + } + resetVaultUnlockFailures(); + let newKeyBuf = null; + try { + const created = await createVaultSecurityMetadata(data.newPassword); + newKeyBuf = created.keyBuf; + const nextEntries = (vaultData.entries || []).map((entry) => { + const entryEmail = normalizeAccountEmail(entry?.email); + if (!entryEmail) throw new Error('invalidEmail'); + const plainJson = isEncryptedVaultCredential(entry.credential) + ? decryptVaultEntryCredential(entry.credential, oldKeyBuf, entryEmail) + : entry.credential; + const norm = normalizeAccountCredential(plainJson); + if (!norm) throw new Error('invalidCredential'); + const minJson = serializeVaultCredential(JSON.parse(norm)); + return { + ...entry, + email: entryEmail, + credential: encryptVaultEntryCredential(minJson, newKeyBuf, entryEmail), + }; + }); + const savedVault = await runStore({ + action: 'writeVault', + entries: nextEntries, + selectedEmail: vaultData.selectedEmail || '', + security: created.security, + }); + clearTransientAccessTokens(); + setUnlockedVaultSessionKey(created.security.salt, newKeyBuf); + return publicList(savedVault); + } finally { + oldKeyBuf?.fill(0); + newKeyBuf?.fill(0); + } + } + + if (action === 'disablePassword') { + const cooldownSec = checkVaultUnlockCooldown(); + if (cooldownSec > 0) { + return { error: 'passwordRateLimited', retryAfterSec: cooldownSec }; + } + const vaultData = await runStore({ action: 'readVault' }); + if (!vaultData.security?.enabled) { + return publicList({ + accounts: (vaultData.entries || []).map((e) => e.email), + selectedEmail: vaultData.selectedEmail || '', + quotas: Object.fromEntries( + (vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota]) + ), + }); + } + let oldKeyBuf = null; + try { + oldKeyBuf = await verifyVaultPassword(data?.currentPassword, vaultData.security); + } catch (err) { + if (err?.message === 'wrongPassword') { + const waitSec = recordVaultUnlockFailure(); + return waitSec > 0 + ? { error: 'passwordRateLimited', retryAfterSec: waitSec } + : { error: 'wrongPassword' }; + } + throw err; + } + resetVaultUnlockFailures(); + try { + const plainEntries = (vaultData.entries || []).map((entry) => { + const entryEmail = normalizeAccountEmail(entry?.email); + if (!entryEmail) throw new Error('invalidEmail'); + const plainJson = isEncryptedVaultCredential(entry.credential) + ? decryptVaultEntryCredential(entry.credential, oldKeyBuf, entryEmail) + : entry.credential; + const norm = normalizeAccountCredential(plainJson); + if (!norm) throw new Error('invalidCredential'); + return { + ...entry, + email: entryEmail, + credential: serializeVaultCredential(JSON.parse(norm)), + }; + }); + const savedVault = await runStore({ + action: 'writeVault', + entries: plainEntries, + selectedEmail: vaultData.selectedEmail || '', + security: null, + }); + lockVaultSession(); + clearTransientAccessTokens(); + return publicList(savedVault); + } finally { + oldKeyBuf?.fill(0); + } + } + + if (action === 'resetVault') { + if (data?.confirmReset !== 'RESET') throw new Error('invalidCredential'); + lockVaultSession(); + clearTransientAccessTokens(); + resetVaultUnlockFailures(); + const curLogin = login.getStatus(); + if (curLogin?.id && curLogin.status === 'waiting') { + login.cancel(curLogin.id); + } + const savedVault = await runStore({ + action: 'writeVault', + entries: [], + selectedEmail: '', + security: null, + clearStatus: true, + }); + return publicList(savedVault); + } + + if (action === 'loginStart') { + await ensureUnlockedVaultContext(); + const session = await login.start(async (verified) => { + const address = normalizeAccountEmail(verified.email); + if (!address) throw new Error('credentialRejected'); + rememberTransientAccessToken(address, verified.credential); + const activeSec = await ensureUnlockedVaultContext(); + const sealed = sealVaultCredential(verified.credential, address, activeSec); + await runStore({ + action: 'save', + email: address, + credential: sealed.stored, + ...(sealed.vaultUnlocked + ? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt } + : {}), + }); + }, data.language); + return { supported: true, login: session }; + } + + if (action === 'loginStatus' || action === 'loginCancel') { + const session = action === 'loginCancel' ? login.cancel(data.id) : login.getStatus(data.id); + return { + supported: true, + login: session || { id: data.id, status: 'expired', error: 'loginExpired' }, + }; + } + + if (action === 'remove') { + const activeSec = await ensureUnlockedVaultContext(); + clearTransientAccessTokens(email); + return publicList( + await runStore({ + action, + email, + ...(activeSec?.enabled + ? { vaultUnlocked: true, expectedSecuritySalt: String(activeSec.salt) } + : {}), + }) + ); + } + + if (action === 'save') { + const activeSec = await ensureUnlockedVaultContext(); + const verified = await verifyCredential(data.credential, true); + const sealed = sealVaultCredential(verified.credential, verified.email, activeSec); + return publicList( + await runStore({ + action, + email: verified.email, + credential: sealed.stored, + ...(sealed.vaultUnlocked + ? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt } + : {}), + }) + ); + } + if (action === 'capture') { + const activeSec = await ensureUnlockedVaultContext(); const status = await rpc('GetUserStatus', {}, 2000).catch(() => null); const activeEmail = normalizeAccountEmail(status?.userStatus?.email); if (!activeEmail) throw new Error('noCurrentCredential'); const { credential } = await runStore({ action: 'readCurrent' }); const verified = await verifyCredential(credential); if (verified.email !== activeEmail) throw new Error('identityMismatch'); - return publicList(await runStore({ action: 'save', email: activeEmail, credential: serializeHostCredential(verified.credential) })); + const sealed = sealVaultCredential(verified.credential, activeEmail, activeSec); + return publicList( + await runStore({ + action: 'save', + email: activeEmail, + credential: sealed.stored, + ...(sealed.vaultUnlocked + ? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt } + : {}), + }) + ); } const saved = await runStore({ action: 'read', email }); - const verified = await verifyCredential(saved.credential); + const entrySec = saved.security || resolveKnownVaultSecurity(); + const openedObj = openStoredVaultCredential(saved.credential, email, entrySec); + const verified = await verifyCredentialObj(openedObj); if (verified.email !== email) throw new Error('identityMismatch'); - const credential = serializeHostCredential(verified.credential); + + const sealedCurrent = sealVaultCredential(verified.credential, email, entrySec); if (action === 'quota') { - if (credential !== saved.credential) { - await runStore({ action: 'save', email, credential, expectedCredential: saved.credential }); + const tokenRotated = + verified.credential.token.refresh_token !== openedObj.token.refresh_token; + const legacyUnminimized = + useDiskSigCache && !entrySec?.enabled && saved.credential !== sealedCurrent.stored; + let expectedCredForQuota = saved.credential; + if (tokenRotated || legacyUnminimized) { + await runStore({ + action: 'save', + email, + credential: sealedCurrent.stored, + expectedCredential: saved.credential, + ...(sealedCurrent.vaultUnlocked + ? { vaultUnlocked: true, expectedSecuritySalt: sealedCurrent.expectedSecuritySalt } + : {}), + }); + expectedCredForQuota = sealedCurrent.stored; } const pools = await getQuota(verified.credential.token.access_token); - return { email, pools }; + const tierInfo = pools?.tierInfo || null; + const tierName = tierInfo?.tierName || (typeof pools?.tierName === 'string' ? pools.tierName : ''); + const tierMeta = { + ...(tierInfo?.tierId ? { tierId: tierInfo.tierId } : {}), + ...(tierName ? { tierName } : {}), + ...(tierInfo?.tierMultiplier ? { tierMultiplier: tierInfo.tierMultiplier } : {}), + }; + const fetchedAt = Date.now(); + const quotaPayload = { pools, fetchedAt, ...tierMeta }; + await runStore({ + action: 'saveQuota', + email, + expectedCredential: expectedCredForQuota, + quota: quotaPayload, + }); + return { email, pools, fetchedAt, ...tierMeta }; } - const updated = await runStore({ action: 'switch', email, credential, expectedCredential: saved.credential }); - const confirmed = await confirmHostCredential(email, rpc); - return { ...publicList(updated), confirmed }; + + const prevActiveEmail = normalizeAccountEmail(data?.activeEmail); + if (prevActiveEmail && prevActiveEmail !== email) { + try { + const existingPrev = await store({ ...config, action: 'read', email: prevActiveEmail }); + if (!existingPrev || existingPrev.error === 'notFound') { + const currentHost = await store({ ...config, action: 'readCurrent' }); + if (currentHost?.credential) { + const verifiedPrev = await verifyCredential(currentHost.credential); + if (verifiedPrev.email === prevActiveEmail) { + const sealedPrev = sealVaultCredential( + verifiedPrev.credential, + prevActiveEmail, + entrySec + ); + await runStore({ + action: 'save', + email: prevActiveEmail, + credential: sealedPrev.stored, + ...(sealedPrev.vaultUnlocked + ? { vaultUnlocked: true, expectedSecuritySalt: sealedPrev.expectedSecuritySalt } + : {}), + }); + } + } + } + } catch { + // Best-effort backup of active host login before switching away + } + } + + const hostSwitchCredential = serializeHostCredential(verified.credential, { + forHostSwitch: true, + }); + const updated = await runStore({ + action: 'scheduleSwitch', + email, + credential: hostSwitchCredential, + vaultCredential: sealedCurrent.stored, + expectedCredential: saved.credential, + ...(sealedCurrent.vaultUnlocked + ? { vaultUnlocked: true, expectedSecuritySalt: sealedCurrent.expectedSecuritySalt } + : {}), + }); + return { ...publicList(updated), restarting: updated.scheduled === true }; } catch (error) { return { error: ACCOUNT_ERRORS.has(error?.message) ? error.message : 'storeFailed' }; } diff --git a/sidecars/panel/backend/account-vault-crypto.mjs b/sidecars/panel/backend/account-vault-crypto.mjs new file mode 100644 index 0000000..4288c4b --- /dev/null +++ b/sidecars/panel/backend/account-vault-crypto.mjs @@ -0,0 +1,245 @@ +/** + * @fileoverview Inner envelope encryption (scrypt + AES-256-GCM) for saved account + * credentials, in-memory session unlock lifecycle, unlock rate-limiting, and + * HMAC action nonces against local CSRF / blind mutation requests. + */ + +import { + createCipheriv, + createDecipheriv, + createHmac, + randomBytes, + scrypt, + timingSafeEqual, +} from 'node:crypto'; + +export const VAULT_CIPHER_PREFIX = 'agv1:'; +const VAULT_VERIFIER_CHALLENGE = 'ag-vault-v1:ok'; +const VAULT_VERIFIER_AAD = 'ag-vault-verifier:v1'; +const VAULT_ENTRY_AAD_PREFIX = 'ag-vault-entry:v1:'; + +const VAULT_SCRYPT_N = 16384; +const VAULT_SCRYPT_R = 8; +const VAULT_SCRYPT_P = 1; +const VAULT_KEY_LEN = 32; +const VAULT_SCRYPT_MAXMEM = 64 * 1024 * 1024; + +export const VAULT_PASSWORD_MIN_LEN = 4; +export const VAULT_PASSWORD_MAX_LEN = 128; + +const ACTION_NONCE_SECRET = randomBytes(32); +const ACTION_NONCE_BUCKET_MS = 10 * 60 * 1000; + +let activeVaultKeyState = null; +let unlockFailureCount = 0; +let unlockCooldownUntilMs = 0; + +export function normalizeVaultPassword(raw) { + if (typeof raw !== 'string') return null; + if (raw.length < VAULT_PASSWORD_MIN_LEN || raw.length > VAULT_PASSWORD_MAX_LEN) return null; + if (!raw.trim()) return null; + return raw; +} + +export function isEncryptedVaultCredential(raw) { + return typeof raw === 'string' && raw.startsWith(VAULT_CIPHER_PREFIX); +} + +function isPowerOfTwo(n) { + return Number.isInteger(n) && n >= 1024 && n <= 65536 && (n & (n - 1)) === 0; +} + +function deriveVaultKey(password, saltBuf, params = {}) { + const N = isPowerOfTwo(params.N) ? params.N : VAULT_SCRYPT_N; + const r = Number.isInteger(params.r) && params.r >= 1 && params.r <= 16 ? params.r : VAULT_SCRYPT_R; + const p = Number.isInteger(params.p) && params.p >= 1 && params.p <= 8 ? params.p : VAULT_SCRYPT_P; + return new Promise((resolve, reject) => { + scrypt( + Buffer.from(password, 'utf8'), + saltBuf, + VAULT_KEY_LEN, + { N, r, p, maxmem: VAULT_SCRYPT_MAXMEM }, + (err, derivedKey) => { + if (err) reject(err); + else resolve(derivedKey); + } + ); + }); +} + +function aeadSeal(plaintextUtf8, keyBuf, aadUtf8) { + const iv = randomBytes(12); + const cipher = createCipheriv('aes-256-gcm', keyBuf, iv); + cipher.setAAD(Buffer.from(aadUtf8, 'utf8')); + const enc = Buffer.concat([cipher.update(plaintextUtf8, 'utf8'), cipher.final()]); + const tag = cipher.getAuthTag(); + return Buffer.concat([iv, tag, enc]).toString('base64'); +} + +function aeadOpen(b64Payload, keyBuf, aadUtf8) { + const raw = Buffer.from(String(b64Payload || ''), 'base64'); + if (raw.length < 28) { + throw new Error('vaultDecryptFailed'); + } + const iv = raw.subarray(0, 12); + const tag = raw.subarray(12, 28); + const enc = raw.subarray(28); + const decipher = createDecipheriv('aes-256-gcm', keyBuf, iv, { authTagLength: 16 }); + decipher.setAAD(Buffer.from(aadUtf8, 'utf8')); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8'); +} + +export async function createVaultSecurityMetadata(password) { + const validPassword = normalizeVaultPassword(password); + if (!validPassword) { + throw new Error('invalidPassword'); + } + const saltBuf = randomBytes(16); + const salt = saltBuf.toString('base64'); + const keyBuf = await deriveVaultKey(validPassword, saltBuf); + const verifier = aeadSeal(VAULT_VERIFIER_CHALLENGE, keyBuf, VAULT_VERIFIER_AAD); + return { + security: { + enabled: true, + version: 1, + kdf: 'scrypt', + salt, + N: VAULT_SCRYPT_N, + r: VAULT_SCRYPT_R, + p: VAULT_SCRYPT_P, + verifier, + }, + keyBuf, + }; +} + +export async function verifyVaultPassword(password, security) { + if (!security?.enabled || typeof security.salt !== 'string' || typeof security.verifier !== 'string') { + throw new Error('storeFailed'); + } + const validPassword = normalizeVaultPassword(password); + if (!validPassword) { + throw new Error('wrongPassword'); + } + const saltBuf = Buffer.from(security.salt, 'base64'); + if (saltBuf.length < 16) { + throw new Error('storeFailed'); + } + const keyBuf = await deriveVaultKey(validPassword, saltBuf, security); + try { + const opened = aeadOpen(security.verifier, keyBuf, VAULT_VERIFIER_AAD); + if (opened !== VAULT_VERIFIER_CHALLENGE) { + keyBuf.fill(0); + throw new Error('wrongPassword'); + } + return keyBuf; + } catch { + keyBuf.fill(0); + throw new Error('wrongPassword'); + } +} + +export function encryptVaultEntryCredential(plainJson, keyBuf, email) { + const normalizedEmail = String(email || '').trim().toLowerCase(); + if (!normalizedEmail || !Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) { + throw new Error('storeFailed'); + } + return `${VAULT_CIPHER_PREFIX}${aeadSeal(plainJson, keyBuf, `${VAULT_ENTRY_AAD_PREFIX}${normalizedEmail}`)}`; +} + +export function decryptVaultEntryCredential(storedText, keyBuf, email) { + const normalizedEmail = String(email || '').trim().toLowerCase(); + if (!isEncryptedVaultCredential(storedText) || !normalizedEmail) { + throw new Error('vaultDecryptFailed'); + } + if (!Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) { + throw new Error('vaultLocked'); + } + const payload = storedText.slice(VAULT_CIPHER_PREFIX.length); + try { + return aeadOpen(payload, keyBuf, `${VAULT_ENTRY_AAD_PREFIX}${normalizedEmail}`); + } catch { + throw new Error('vaultDecryptFailed'); + } +} + +export function setUnlockedVaultSessionKey(salt, keyBuf) { + if (!salt || !Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) { + throw new Error('storeFailed'); + } + const nextCopy = Buffer.from(keyBuf); + if (activeVaultKeyState?.keyBuf) { + activeVaultKeyState.keyBuf.fill(0); + } + activeVaultKeyState = { salt: String(salt), keyBuf: nextCopy }; +} + +export function lockVaultSession() { + if (activeVaultKeyState?.keyBuf) { + activeVaultKeyState.keyBuf.fill(0); + } + activeVaultKeyState = null; +} + +export function getUnlockedVaultSessionKey(expectedSalt = '') { + if (!activeVaultKeyState?.keyBuf) return null; + if (expectedSalt && activeVaultKeyState.salt !== String(expectedSalt)) { + lockVaultSession(); + return null; + } + return activeVaultKeyState.keyBuf; +} + +export function isVaultSessionUnlocked(security) { + if (!security?.enabled) return true; + return Boolean(getUnlockedVaultSessionKey(security.salt)); +} + +export function checkVaultUnlockCooldown(nowMs = Date.now()) { + if (unlockCooldownUntilMs <= nowMs) return 0; + return Math.max(1, Math.ceil((unlockCooldownUntilMs - nowMs) / 1000)); +} + +export function recordVaultUnlockFailure(nowMs = Date.now()) { + unlockFailureCount += 1; + if (unlockFailureCount >= 5) { + const delayMs = Math.min(60_000, 5_000 * 2 ** Math.min(4, unlockFailureCount - 5)); + unlockCooldownUntilMs = nowMs + delayMs; + } + return checkVaultUnlockCooldown(nowMs); +} + +export function resetVaultUnlockFailures() { + unlockFailureCount = 0; + unlockCooldownUntilMs = 0; +} + +function computeBucketNonceMac(bucket) { + return createHmac('sha256', ACTION_NONCE_SECRET) + .update(`ag-acct-nonce:${bucket}`) + .digest('base64url') + .slice(0, 32); +} + +export function issueAccountActionNonce(nowMs = Date.now()) { + const bucket = Math.floor(nowMs / ACTION_NONCE_BUCKET_MS).toString(36); + return `${bucket}.${computeBucketNonceMac(bucket)}`; +} + +export function verifyAccountActionNonce(token, nowMs = Date.now()) { + if (typeof token !== 'string' || token.length < 16 || token.length > 96) return false; + const dotIdx = token.indexOf('.'); + if (dotIdx <= 0) return false; + const bucketStr = token.slice(0, dotIdx); + const macStr = token.slice(dotIdx + 1); + const bucketNum = Number.parseInt(bucketStr, 36); + if (!Number.isSafeInteger(bucketNum) || bucketNum <= 0) return false; + const curBucket = Math.floor(nowMs / ACTION_NONCE_BUCKET_MS); + if (Math.abs(curBucket - bucketNum) > 1) return false; + const expectedMac = computeBucketNonceMac(bucketNum.toString(36)); + const a = Buffer.from(macStr, 'utf8'); + const b = Buffer.from(expectedMac, 'utf8'); + if (a.length !== b.length) return false; + return timingSafeEqual(a, b); +} diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 15d05fc..b278ab9 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -9,7 +9,8 @@ import { randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; import { BRIDGE_API_ROUTE_DEFS, LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs'; -import { handleAccountCredentialAction } from './account-switch.mjs'; +import { handleAccountCredentialAction, warmAccountPublicListCache } from './account-switch.mjs'; +import { issueAccountActionNonce, verifyAccountActionNonce } from './account-vault-crypto.mjs'; import { clearRemoteEndpointCaches, resolveEndpointContext, @@ -614,6 +615,20 @@ export async function executePluginUpdateAction() { }; } +const NONCE_PROTECTED_ACCOUNT_ACTIONS = new Set([ + 'save', + 'capture', + 'switch', + 'remove', + 'loginStart', + 'setPassword', + 'unlockVault', + 'lockVault', + 'changePassword', + 'disablePassword', + 'resetVault', +]); + export async function executeAccountCredentialAction(data, opts = {}) { const epCtx = resolveActionEndpoint(data, opts); if (!epCtx.ok) { @@ -628,15 +643,35 @@ export async function executeAccountCredentialAction(data, opts = {}) { }; } const cleanData = stripEndpointField(data); - const result = await handleAccountCredentialAction(cleanData); - if (cleanData?.action === 'switch') { + const action = cleanData?.action || 'list'; + if (NONCE_PROTECTED_ACCOUNT_ACTIONS.has(action) && !verifyAccountActionNonce(cleanData?.actionNonce)) { + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ + error: 'invalidActionNonce', + actionNonce: issueAccountActionNonce(), + }), + }; + } + const result = await handleAccountCredentialAction({ + ...(isPlainObject(cleanData) ? cleanData : {}), + action, + includeSecurity: true, + }); + if (action === 'switch' && !result?.error) { clearTelemetryBuilderMemo(LOCAL_ENDPOINT_ID); } + const enriched = + result && typeof result === 'object' + ? { ...result, actionNonce: issueAccountActionNonce() } + : result; return { status: 200, contentType: 'application/json', headers: { 'Cache-Control': 'no-store' }, - body: JSON.stringify(result), + body: JSON.stringify(enriched), }; } @@ -870,6 +905,11 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu if (!allowDynamicLs && !lsRuntimeEndpoint.addr) return null; ensureCliStatusLineConfigured({ enabled: loadSettings().enableCliStatusLine !== false }); + if (allowDynamicLs) { + setTimeout(() => { + void warmAccountPublicListCache(); + }, 80).unref?.(); + } const triggerRestart = typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150); diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index f4399e6..b89a792 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -6,8 +6,10 @@ import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs'; import { + ACCOUNT_QUOTA_REFRESH_MINUTES, CLI_STATUSLINE_PRESETS, CONTEXT_AGENT_MODES, + DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, DEFAULT_CLI_STATUSLINE_SLOTS, DEFAULT_CONTEXT_AGENT_MODE, DEFAULT_HOVER_MODULES, @@ -32,6 +34,7 @@ import { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeAccountQuotaRefreshMinutes, normalizeCliStatusLineSlots, normalizeContextAgentMode, normalizeExperimentalModernUi, @@ -59,8 +62,10 @@ import { } from '../shared/settings-normalization.mjs'; export { + ACCOUNT_QUOTA_REFRESH_MINUTES, CLI_STATUSLINE_PRESETS, CONTEXT_AGENT_MODES, + DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, DEFAULT_CLI_STATUSLINE_SLOTS, DEFAULT_CONTEXT_AGENT_MODE, DEFAULT_HOVER_MODULES, @@ -85,6 +90,7 @@ export { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, + normalizeAccountQuotaRefreshMinutes, normalizeCliStatusLineSlots, normalizeContextAgentMode, normalizeExperimentalModernUi, @@ -162,6 +168,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ stepTokenComboFormat: DEFAULT_STEP_TOKEN_COMBO_FORMAT, stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS, experimentalQuotaReservation: true, + accountQuotaRefreshMinutes: DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, contextWindowRiskAccepted: false, contextWindowMainEnabled: true, contextWindowSwarmEnabled: false, @@ -246,6 +253,9 @@ export function normalizeFullSettings(rawInput) { experimentalQuotaReservation: normalizeExperimentalQuotaReservation( safeRaw.experimentalQuotaReservation ), + accountQuotaRefreshMinutes: normalizeAccountQuotaRefreshMinutes( + safeRaw.accountQuotaRefreshMinutes + ), contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true, contextWindowMainEnabled: safeRaw.contextWindowMainEnabled !== false, contextWindowSwarmEnabled: safeRaw.contextWindowSwarmEnabled === true, diff --git a/sidecars/panel/backend/standalone-server.mjs b/sidecars/panel/backend/standalone-server.mjs index b0053d2..006b4e8 100644 --- a/sidecars/panel/backend/standalone-server.mjs +++ b/sidecars/panel/backend/standalone-server.mjs @@ -512,6 +512,19 @@ export function createStandaloneWebServer(options = {}) { } if (pathname.startsWith('/api/')) { + if (pathname === '/api/accounts' || pathname === '/api/accounts/update') { + sendResponse( + res, + 403, + 'application/json; charset=utf-8', + JSON.stringify({ + supported: false, + accounts: [], + error: 'unsupported', + }) + ); + return; + } if (pathname === '/api/export-file' || pathname === '/api/reveal-file') { sendResponse( res, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index b507de1..fe7191d 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index 82e83e5..f1d9148 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -175,6 +175,18 @@ async function handleProtectedApi(pathname, method, data, req) { contentType: 'application/json', }); } + if ( + !isTestHarnessEnv && + pathname === '/api/accounts/update' && + req?.headers && + !req.headers.origin && + !req.headers['sec-fetch-site'] + ) { + return new Response(JSON.stringify({ error: 'Forbidden non-webview account mutation' }), { + status: 403, + contentType: 'application/json', + }); + } const out = await forwardApiCall(pathname, method, data); return new Response(out.body, { status: out.status, diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index 44f2630..cb2a1ea 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -641,6 +641,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/components/settings/SessionMigrationCard.js', 'src/views/settings/SettingsGeneralTab.js', 'src/views/settings/SettingsStructureTab.js', + 'src/views/settings/SettingsAccountTab.js', 'src/views/settings/SettingsOtherTab.js', 'src/components/layout/TopSessionHeader.js', 'src/views/LiveOverviewView.js', diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs index 5ea0336..b6490fd 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -546,6 +546,22 @@ export function normalizeModernUi(val) { export const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']); export const DEFAULT_CONTEXT_AGENT_MODE = 'main'; +export const ACCOUNT_QUOTA_REFRESH_MINUTES = Object.freeze([10, 30, 60, 180, 360, 720, 1440]); +export const DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES = 60; + +/** + * 归一化非当前账号的后台配额刷新间隔(分钟,默认 `60` 即 1 小时)。 + * + * @param {unknown} raw + * @returns {10|30|60|180|360|720|1440} + */ +export function normalizeAccountQuotaRefreshMinutes(raw) { + const num = Number(raw); + return ACCOUNT_QUOTA_REFRESH_MINUTES.includes(num) + ? /** @type {any} */ (num) + : DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES; +} + /** * 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'main'` 锁定主代理,可选 `'auto'` 跟随活跃)。 * diff --git a/sidecars/panel/src/core/settingsBackup.js b/sidecars/panel/src/core/settingsBackup.js index 676eb3c..e894861 100644 --- a/sidecars/panel/src/core/settingsBackup.js +++ b/sidecars/panel/src/core/settingsBackup.js @@ -4,6 +4,7 @@ */ import { + normalizeAccountQuotaRefreshMinutes, normalizeCliStatusLineSlots, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, @@ -212,6 +213,7 @@ const PORTABLE_SETTING_DESCRIPTORS = Object.freeze([ normField('stepTokenComboFormat', normalizeStepTokenComboFormat), arrayField('stepTableColumns', normalizeStepTableColumns), normField('experimentalQuotaReservation', normalizeExperimentalQuotaReservation), + normField('accountQuotaRefreshMinutes', normalizeAccountQuotaRefreshMinutes), ]); /** diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 933105d..2aafe9e 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -492,26 +492,54 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.account.signedOut': 'Signed out', 'settings.account.unknown': 'Account status unavailable', 'settings.account.email': 'Account email', + 'settings.account.googleLogin': 'Sign in with Google', + 'settings.account.loginHint': 'Sign in with Google in your browser. The account will appear in this list automatically.', + 'settings.account.loginWaiting': 'Choose a Google account and complete authorization in your browser. This list will update automatically.', + 'settings.account.loginFinishing': 'Authorization received. Saving the account…', + 'settings.account.loginSuccess': 'Signed in. The account has been added.', + 'settings.account.loginCancelled': 'Sign-in cancelled.', + 'settings.account.loginExpired': 'Sign-in expired. Click Sign in with Google to try again.', + 'settings.account.loginDenied': 'Google authorization was cancelled. Try signing in again.', + 'settings.account.loginStartFailed': 'Sign-in could not start. Try again.', + 'settings.account.loginExchangeFailed': 'Sign-in could not finish. Check your connection and authorize again.', + 'settings.account.openLoginPage': 'Reopen Google authorization', + 'settings.account.cancelLogin': 'Cancel sign-in', + 'settings.account.importExisting': 'Import existing credentials', 'settings.account.credential': 'OAuth credential', + 'settings.account.credentialPlaceholder': 'Paste 1// refresh token or OAuth JSON…', 'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.', 'settings.account.save': 'Import credential', 'settings.account.capture': 'Save current credential', 'settings.account.reload': 'Refresh list', - 'settings.account.switch': 'Switch', + 'settings.account.switch': 'Switch and restart', + 'settings.account.switchHint': 'Switching closes and reopens Antigravity App and the IDE sharing its sign-in. Save your work first.', + 'settings.account.restarting': 'Restarting Antigravity with the selected account…', + 'settings.account.switchStartFailed': 'The account switch could not start. Refresh the list and try again.', + 'settings.account.clientCloseFailed': 'Antigravity could not fully exit. The switch is incomplete.', + 'settings.account.clientRestartFailed': 'The credential was updated. Open Antigravity manually to finish switching.', 'settings.account.remove': 'Remove', 'settings.account.active': 'In use', + 'settings.account.savedBadge': 'Backed up', 'settings.account.written': 'Credential written', 'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.', - 'settings.account.savedCredentials': 'Saved credentials', + 'settings.account.savedCredentials': 'Saved accounts', 'settings.account.empty': 'No saved credentials.', 'settings.account.loading': 'Loading saved credentials…', 'settings.account.saved': 'Credential saved.', 'settings.account.removed': 'Saved credential removed.', 'settings.account.switched': 'Account switched. Refreshing the current quota.', - 'settings.account.switching': 'Replacing the credential and confirming the active account…', + 'settings.account.switching': 'Verifying the credential and preparing to restart…', 'settings.account.verifying': 'Verifying the credential owner…', 'settings.account.loadQuota': 'Check quota', - 'settings.account.loadingQuota': 'Checking quota for this credential…', + 'settings.account.loadingQuota': 'Checking…', + 'settings.account.refreshFreqAria': 'Background account quota refresh interval', + 'settings.account.refresh10m': '10 min', + 'settings.account.refresh30m': '30 min', + 'settings.account.refresh1h': '1 hr', + 'settings.account.refresh3h': '3 hr', + 'settings.account.refresh6h': '6 hr', + 'settings.account.refresh12h': '12 hr', + 'settings.account.refresh24h': '24 hr', 'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.', 'settings.account.quota': 'Quota remaining by pool', 'settings.account.quota5h': '5 hours {percent}%', @@ -534,6 +562,42 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.', 'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.', 'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.', + 'settings.account.switchConfirm': 'Confirm switch', + 'settings.account.removeConfirm': 'Confirm remove', + 'settings.account.pwdBtnSet': 'Passphrase', + 'settings.account.pwdBtnManage': 'Passphrase', + 'settings.account.lockNow': 'Lock', + 'settings.account.lockNowTip': 'Lock credential vault now', + 'settings.account.unlockBtn': 'Unlock', + 'settings.account.unlockPlaceholder': 'Enter passphrase to unlock…', + 'settings.account.vaultLockedHint': 'Credential vault is locked. Enter your passphrase to switch accounts, manage credentials, or refresh quotas.', + 'settings.account.forgotPwdToggle': 'Forgot?', + 'settings.account.resetVaultHint': 'Encrypted backups cannot be recovered without the passphrase (your active IDE sign-in is unaffected). You can clear and reset the vault.', + 'settings.account.resetVaultBtn': 'Reset vault', + 'settings.account.resetVaultConfirm': 'Confirm reset', + 'settings.account.pwdTabChange': 'Change passphrase', + 'settings.account.pwdTabDisable': 'Remove passphrase', + 'settings.account.pwdCurrentPlaceholder': 'Current passphrase…', + 'settings.account.pwdNewPlaceholder': 'New passphrase (4–128 chars)…', + 'settings.account.pwdConfirmPlaceholder': 'Confirm passphrase…', + 'settings.account.pwdEnableSubmit': 'Enable', + 'settings.account.pwdChangeSubmit': 'Update', + 'settings.account.pwdDisableSubmit': 'Disable', + 'settings.account.pwdSetHint': 'Adds passphrase encryption to all saved refresh tokens. Asked once per session when managing accounts; cannot be recovered if forgotten.', + 'settings.account.pwdManageHint': 'Verify your current passphrase to set a new one or return to default OS encryption.', + 'settings.account.pwdEnabledToast': 'Passphrase encryption enabled.', + 'settings.account.pwdChangedToast': 'Passphrase updated.', + 'settings.account.pwdDisabledToast': 'Passphrase protection disabled.', + 'settings.account.vaultUnlockedToast': 'Credential vault unlocked.', + 'settings.account.vaultLockedToast': 'Credential vault locked.', + 'settings.account.vaultResetToast': 'Credential vault cleared and reset.', + 'settings.account.vaultLocked': 'Enter your passphrase to unlock the vault first.', + 'settings.account.wrongPassword': 'Incorrect passphrase. Try again.', + 'settings.account.invalidPassword': 'Passphrase must be 4–128 characters and not blank.', + 'settings.account.passwordMismatch': 'Passphrases do not match.', + 'settings.account.passwordRateLimited': 'Too many failed attempts. Wait a moment and try again.', + 'settings.account.vaultDecryptFailed': 'Vault decryption check failed.', + 'settings.account.invalidActionNonce': 'Security token expired. Please try again.', 'settings.subTab.aria': 'Preferences category tabs', 'settings.saving': 'Saving…', 'settings.saved': 'Saved', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 5eb38d4..26911b4 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -493,26 +493,54 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.account.signedOut': '未登录', 'settings.account.unknown': '暂未获取账号状态', 'settings.account.email': '账号邮箱', + 'settings.account.googleLogin': '使用 Google 登录', + 'settings.account.loginHint': '通过浏览器登录 Google,完成后账号会自动添加到列表。', + 'settings.account.loginWaiting': '请在浏览器中选择 Google 账号并完成授权,完成后这里会自动更新。', + 'settings.account.loginFinishing': '授权已收到,正在保存账号…', + 'settings.account.loginSuccess': '登录成功,账号已添加。', + 'settings.account.loginCancelled': '已取消本次登录。', + 'settings.account.loginExpired': '登录已超时,请重新点击「使用 Google 登录」。', + 'settings.account.loginDenied': 'Google 授权已取消,请重新登录。', + 'settings.account.loginStartFailed': '未能开始登录,请重试。', + 'settings.account.loginExchangeFailed': '未能完成登录,请检查网络后重新授权。', + 'settings.account.openLoginPage': '重新打开 Google 授权页面', + 'settings.account.cancelLogin': '取消登录', + 'settings.account.importExisting': '导入已有凭证', 'settings.account.credential': 'OAuth 凭证', + 'settings.account.credentialPlaceholder': '粘贴 1// 刷新令牌或 OAuth JSON…', 'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。', 'settings.account.save': '导入凭证', 'settings.account.capture': '保存当前凭证', 'settings.account.reload': '刷新列表', - 'settings.account.switch': '切换', + 'settings.account.switch': '切换并重启', + 'settings.account.switchHint': '切换会关闭并重新打开 Antigravity App 和共享登录的 IDE,请先保存工作。', + 'settings.account.restarting': '正在重启 Antigravity 并应用所选账号…', + 'settings.account.switchStartFailed': '未能启动切号,请刷新列表后重试。', + 'settings.account.clientCloseFailed': 'Antigravity 未能完全退出,切换未完成。', + 'settings.account.clientRestartFailed': '凭证已更新,但自动重新打开失败,请手动打开 Antigravity。', 'settings.account.remove': '移除', 'settings.account.active': '当前使用', + 'settings.account.savedBadge': '已备份', 'settings.account.written': '凭证已写入', 'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。', - 'settings.account.savedCredentials': '已保存的凭证', + 'settings.account.savedCredentials': '已保存的账号', 'settings.account.empty': '暂无已保存的凭证。', 'settings.account.loading': '正在读取已保存的凭证…', 'settings.account.saved': '凭证已保存。', 'settings.account.removed': '已移除保存的凭证。', 'settings.account.switched': '已切换账号,正在刷新当前额度。', - 'settings.account.switching': '正在替换凭证并确认宿主账号…', + 'settings.account.switching': '正在验证凭证并准备重启…', 'settings.account.verifying': '正在验证凭证所属账号…', 'settings.account.loadQuota': '查额度', - 'settings.account.loadingQuota': '正在查询此凭证的额度…', + 'settings.account.loadingQuota': '查询中…', + 'settings.account.refreshFreqAria': '非当前账号配额刷新间隔', + 'settings.account.refresh10m': '10 分钟', + 'settings.account.refresh30m': '30 分钟', + 'settings.account.refresh1h': '1 小时', + 'settings.account.refresh3h': '3 小时', + 'settings.account.refresh6h': '6 小时', + 'settings.account.refresh12h': '12 小时', + 'settings.account.refresh24h': '24 小时', 'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。', 'settings.account.quota': '额度池剩余', 'settings.account.quota5h': '5 小时 {percent}%', @@ -531,10 +559,46 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。', 'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。', 'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。', - 'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。', + 'settings.account.identityMismatch': '凭证所属账号跟宿主或保存的账号不一致,请重新导入该凭证。', 'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。', 'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。', 'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。', + 'settings.account.switchConfirm': '确认切换', + 'settings.account.removeConfirm': '确认移除', + 'settings.account.pwdBtnSet': '二级密码', + 'settings.account.pwdBtnManage': '密码设置', + 'settings.account.lockNow': '锁定', + 'settings.account.lockNowTip': '立即锁定凭证库', + 'settings.account.unlockBtn': '解锁', + 'settings.account.unlockPlaceholder': '输入二级密码解锁…', + 'settings.account.vaultLockedHint': '凭证库已加密锁定,输入二级密码后可切换账号、管理凭证和刷新后台配额。', + 'settings.account.forgotPwdToggle': '忘记密码?', + 'settings.account.resetVaultHint': '二级密码采用真实密钥派生加密,遗忘后无法解密旧备份(不影响当前正在使用的账号),可清空凭证库后重新添加。', + 'settings.account.resetVaultBtn': '清空凭证库', + 'settings.account.resetVaultConfirm': '确认清空重置', + 'settings.account.pwdTabChange': '修改密码', + 'settings.account.pwdTabDisable': '关闭密码', + 'settings.account.pwdCurrentPlaceholder': '当前二级密码…', + 'settings.account.pwdNewPlaceholder': '设置二级密码(4~128 位)…', + 'settings.account.pwdConfirmPlaceholder': '再次确认密码…', + 'settings.account.pwdEnableSubmit': '启用加密', + 'settings.account.pwdChangeSubmit': '更新密码', + 'settings.account.pwdDisableSubmit': '关闭保护', + 'settings.account.pwdSetHint': '使用二级密码对所有已存刷新令牌追加一层加密,每次启动首次操作时解锁一次;请牢记密码,遗忘后无法找回备份。', + 'settings.account.pwdManageHint': '验证当前二级密码后可更换新密码,或退回系统默认加密。', + 'settings.account.pwdEnabledToast': '已启用二级密码加密。', + 'settings.account.pwdChangedToast': '二级密码已更新。', + 'settings.account.pwdDisabledToast': '已关闭二级密码保护。', + 'settings.account.vaultUnlockedToast': '凭证库已解锁。', + 'settings.account.vaultLockedToast': '凭证库已锁定。', + 'settings.account.vaultResetToast': '凭证库已清空重置。', + 'settings.account.vaultLocked': '请先输入二级密码解锁凭证库。', + 'settings.account.wrongPassword': '二级密码不正确,请核对后重试。', + 'settings.account.invalidPassword': '密码长度需在 4 到 128 个字符之间且不能全为空格。', + 'settings.account.passwordMismatch': '两次输入的密码不一致。', + 'settings.account.passwordRateLimited': '密码连续输错次数过多,请稍候再试。', + 'settings.account.vaultDecryptFailed': '凭证解密校验失败,请确认密码或重置凭证库。', + 'settings.account.invalidActionNonce': '安全校验令牌已过期,请重试。', 'settings.saving': '保存中…', 'settings.saved': '已保存', 'settings.saveFailed': '保存失败', diff --git a/sidecars/panel/src/icons/svgRegistry.js b/sidecars/panel/src/icons/svgRegistry.js index ee2ec5f..d1c775b 100644 --- a/sidecars/panel/src/icons/svgRegistry.js +++ b/sidecars/panel/src/icons/svgRegistry.js @@ -131,4 +131,13 @@ export const SVG_ICON_DEFS = Object.freeze({ { tag: 'circle', attrs: { cx: '6', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } }, ], + lock: [ + { tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } }, + { tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.6 0V7' } }, + { tag: 'circle', attrs: { cx: '8', cy: '10.5', r: '0.9', fill: 'currentColor', stroke: 'none' } }, + ], + unlock: [ + { tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } }, + { tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.3-1.2' } }, + ], }); diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 7159175..355d4aa 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -42,6 +42,7 @@ import { OVERVIEW_MODULE_KEYS, STEP_TABLE_COLUMN_KEYS, TOPBAR_SLOT_KEYS, + normalizeAccountQuotaRefreshMinutes, normalizeCliStatusLineSlots, normalizeContextAgentMode, normalizeExperimentalQuotaReservation, @@ -496,6 +497,7 @@ export const normalizeClientModelDisplayMode = normalizeModelDisplayMode; export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; export const normalizeClientContextAgentMode = normalizeContextAgentMode; export const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation; +export const normalizeClientAccountQuotaRefreshMinutes = normalizeAccountQuotaRefreshMinutes; export const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots; /** @@ -654,6 +656,12 @@ export function isEquivalentTelemetry(prev, next) { ) { return false; } + if ( + normalizeClientAccountQuotaRefreshMinutes(pSet?.accountQuotaRefreshMinutes) !== + normalizeClientAccountQuotaRefreshMinutes(nSet?.accountQuotaRefreshMinutes) + ) { + 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; @@ -1913,6 +1921,11 @@ export async function saveSettingsPatch(patch) { safePatch.experimentalQuotaReservation ); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'accountQuotaRefreshMinutes')) { + safePatch.accountQuotaRefreshMinutes = normalizeClientAccountQuotaRefreshMinutes( + safePatch.accountQuotaRefreshMinutes + ); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 251592f..68f0fe0 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -641,6 +641,484 @@ line-height: 1.35; } +.settings-account-root [hidden] { + display: none !important; +} + +.account-toolbar-panel { + padding: 9px 12px; + gap: 8px; +} + +.account-toolbar-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + flex-wrap: wrap; +} + +.account-toolbar-left, +.account-toolbar-right { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.account-toolbar-right { + margin-left: auto; +} + +.account-toolbar-btn { + display: inline-flex; + align-items: center; + gap: 5px; + min-height: calc(25px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 10px; + font-size: var(--fs-md); + font-weight: 500; + border-radius: var(--radius-xs); + white-space: nowrap; +} + +.account-toolbar-btn.is-open { + color: var(--accent-primary); + background: var(--accent-primary-soft); +} + +.account-reload-btn { + width: calc(25px * var(--ui-font-scale, 1)); + height: calc(25px * var(--ui-font-scale, 1)); + padding: 0; + border-radius: var(--radius-xs); + flex-shrink: 0; +} + +.account-refresh-select { + flex: 0 0 auto; + width: auto; + min-width: 0; +} + +.account-refresh-select .select-trigger { + width: auto; + min-height: calc(25px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 8px; + gap: 5px; + font-size: var(--fs-sm); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + background: var(--surface-subtle); +} + +[data-modern-ui="true"] .account-refresh-select .select-trigger { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .account-refresh-select .select-trigger:hover, +[data-modern-ui="true"] .account-refresh-select.is-open .select-trigger { + background: var(--modern-surface-hover); +} + +.account-refresh-select .select-menu { + right: 0; + left: auto; + min-width: 108px; + width: max-content; +} + +.account-status-inline { + font-size: var(--fs-sm); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 210px; +} + +.account-status-inline.is-ok { + color: var(--metric-ok); +} + +.account-status-inline.is-error, +.account-card-note.is-error { + color: var(--metric-danger); +} + +.account-status-inline.is-info { + color: var(--text-secondary); +} + +.account-import-drawer { + display: flex; + flex-direction: column; + gap: 5px; + padding-top: 2px; +} + +.account-import-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; +} + +.account-import-input { + flex: 1 1 150px; + min-width: 0; + min-height: calc(26px * var(--ui-font-scale, 1)); +} + +.account-import-hint { + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.account-unlock-box { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px 10px; + border-radius: var(--radius-xs); + background: var(--surface-subtle); +} + +.account-unlock-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.account-unlock-title { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: var(--fs-sm); + color: var(--text-secondary); +} + +.account-unlock-title .svg-icon { + color: var(--metric-warn); + flex-shrink: 0; +} + +.account-link-btn { + padding: 0; + border: none; + background: transparent; + font-size: var(--fs-xs); + color: var(--text-muted); + cursor: pointer; + white-space: nowrap; +} + +.account-link-btn:hover { + color: var(--text-primary); + text-decoration: underline; +} + +.account-reset-row { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 6px 10px; + padding-top: 4px; +} + +.account-reset-row .settings-action-desc { + flex: 1 1 180px; + font-size: var(--fs-xs); +} + +.account-pwd-tabs { + display: inline-flex; + align-items: center; + align-self: flex-start; + gap: 4px; + padding: 2px; + border-radius: var(--radius-xs); + background: var(--surface-subtle); +} + +.account-pwd-tab { + padding: 2px 8px; + border: none; + border-radius: var(--radius-xs); + background: transparent; + font-size: var(--fs-xs); + font-weight: 500; + color: var(--text-secondary); + cursor: pointer; +} + +.account-pwd-tab.is-active { + background: var(--bg-elevated); + color: var(--text-primary); +} + +.account-card-btn.is-confirm-warn { + color: var(--accent-primary); + background: var(--accent-primary-soft); + font-weight: 600; +} + +.account-confirm-danger-btn { + color: var(--metric-danger); + background: color-mix(in srgb, var(--metric-danger) 12%, transparent); + font-weight: 600; +} + +.account-confirm-danger-btn:hover:not(:disabled) { + background: color-mix(in srgb, var(--metric-danger) 20%, transparent); +} + +.account-flow-strip { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 6px 10px; + padding: 6px 9px; + border-radius: var(--radius-xs); + background: var(--surface-subtle); + font-size: var(--fs-sm); +} + +.account-flow-strip.is-info { + background: var(--accent-primary-soft); +} + +.account-flow-strip.is-info .account-flow-msg { + color: var(--accent-primary); +} + +.account-flow-strip.is-ok { + background: color-mix(in srgb, var(--metric-ok) 10%, transparent); +} + +.account-flow-strip.is-ok .account-flow-msg { + color: var(--metric-ok); +} + +.account-flow-strip.is-warn { + background: color-mix(in srgb, var(--metric-warn) 10%, transparent); + color: var(--metric-warn); +} + +.account-flow-strip.is-error { + background: color-mix(in srgb, var(--metric-danger) 10%, transparent); +} + +.account-flow-strip.is-error .account-flow-msg { + color: var(--metric-danger); +} + +.account-flow-link { + font-size: var(--fs-sm); + font-weight: 500; + color: var(--accent-primary); + text-decoration: none; + white-space: nowrap; +} + +.account-flow-link:hover { + text-decoration: underline; +} + +.account-cards-stack { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.account-card { + gap: 10px; + padding: 11px 14px; +} + +.account-card-head { + gap: 8px; + flex-wrap: wrap; +} + +.account-card-meta { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + min-width: 0; + flex: 1 1 150px; +} + +.account-active-dot { + background: var(--metric-ok); + box-shadow: 0 0 0 2px color-mix(in srgb, var(--metric-ok) 20%, transparent); +} + +.account-card-email { + font-size: var(--fs-base); + font-weight: 600; + color: var(--text-primary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 100%; +} + +.account-tag { + display: inline-flex; + align-items: center; + min-height: calc(18px * var(--ui-font-scale, 1)); + padding: 1px 6px; + font-size: var(--fs-xs); + font-weight: 600; + line-height: 1.2; + border-radius: var(--radius-xs); + border: none; + white-space: nowrap; +} + +.account-tag.is-active { + color: var(--metric-ok); + background: color-mix(in srgb, var(--metric-ok) 12%, transparent); +} + +.account-tag.is-tier { + color: var(--accent-primary); + background: var(--accent-primary-soft); +} + +.account-tag.is-written { + color: var(--metric-warn); + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); +} + +.account-card-actions { + display: inline-flex; + align-items: center; + gap: 5px; + flex-shrink: 0; + margin-left: auto; +} + +.account-card-btn { + min-height: calc(23px * var(--ui-font-scale, 1)); + height: auto; + padding: 1px 8px; + font-size: var(--fs-sm); + font-weight: 500; + border-radius: var(--radius-xs); + white-space: nowrap; +} + +.account-icon-btn { + width: calc(23px * var(--ui-font-scale, 1)); + height: calc(23px * var(--ui-font-scale, 1)); + padding: 0; + border-radius: var(--radius-xs); +} + +.account-pools-stack { + display: flex; + flex-direction: column; + gap: 9px; +} + +.account-pool-group { + display: flex; + flex-direction: column; + gap: 4px; +} + +.account-pool-name { + font-size: var(--fs-xs); + font-weight: 600; + color: var(--text-muted); + line-height: 1.25; + letter-spacing: 0.01em; +} + +.account-pool-meters { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px 14px; +} + +.account-pool-meters.is-single { + grid-template-columns: minmax(0, 1fr); +} + +@media (max-width: 310px) { + .account-pool-meters { + grid-template-columns: minmax(0, 1fr); + } +} + +.account-meter-col { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.account-meter-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 6px; + min-width: 0; +} + +.settings-account-quota { + font-size: var(--fs-sm); + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; +} + +.account-meter-reset { + font-size: var(--fs-2xs); + color: var(--text-muted); + white-space: nowrap; + flex-shrink: 0; +} + +.account-progress-track { + height: 5px; +} + +.account-empty-panel { + padding: 18px 14px; + align-items: center; + justify-content: center; +} + +.account-empty-text { + text-align: center; + color: var(--text-muted); +} + +@keyframes anim-account-spin { + to { + transform: rotate(360deg); + } +} + +.icon-btn.is-spinning .svg-icon { + animation: anim-account-spin 0.8s linear infinite; +} + +@media (prefers-reduced-motion: reduce) { + .icon-btn.is-spinning .svg-icon { + animation: none !important; + } +} + .settings-context-model .select-option-meta { max-width: 62%; text-align: right; diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index dc27d12..6f8e9dc 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -11,11 +11,12 @@ import { telemetryStore } from '../store/telemetryStore.js'; import { getVisibleMonitorView, uiStore } from '../store/uiStore.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js'; +import { SettingsAccountTab } from './settings/SettingsAccountTab.js'; import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js'; import { SettingsOtherTab } from './settings/SettingsOtherTab.js'; import { SettingsStructureTab } from './settings/SettingsStructureTab.js'; -export const SHOW_ACCOUNT_TAB = false; +export const SHOW_ACCOUNT_TAB = true; function getSettingsSubTabOptions() { return [ @@ -51,10 +52,11 @@ export const SettingsView = defineComponent({ const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll }); const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll }); - const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in + const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll }); const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll }); let showingAccount = false; + let preloadedAccountOnce = false; function applyActiveSubTab(subTab, activeView) { const target = subTab === 'structure' || @@ -69,6 +71,10 @@ export const SettingsView = defineComponent({ patchAttr(otherTab.el, 'hidden', target !== 'other'); if (accountTab) { patchAttr(accountTab.el, 'hidden', target !== 'account'); + if (activeView === 'settings' && !preloadedAccountOnce) { + preloadedAccountOnce = true; + void accountTab.refs.preload?.(); + } const nextShowingAccount = target === 'account' && activeView === 'settings'; if (nextShowingAccount && !showingAccount) void accountTab.refs.load(); showingAccount = nextShowingAccount; @@ -102,6 +108,9 @@ export const SettingsView = defineComponent({ if (getVisibleMonitorView(ui) !== 'settings') return; const telemetry = telemetryStore.getState().telemetry; const settings = telemetry?.settings; + if (accountTab) { + accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas, settings); + } if (settingsSubTab === 'structure') { if (settings) { structureTab.refs.renderSettings( @@ -122,9 +131,7 @@ export const SettingsView = defineComponent({ telemetry?.cloudCodeProxy ); } - } else if (accountTab && settingsSubTab === 'account') { - accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas); - } else { + } else if (settingsSubTab !== 'account') { if (settings) generalTab.refs.renderSettings(settings); if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus); } diff --git a/sidecars/panel/src/views/settings/SettingsAccountTab.js b/sidecars/panel/src/views/settings/SettingsAccountTab.js index efb9018..602ff7f 100644 --- a/sidecars/panel/src/views/settings/SettingsAccountTab.js +++ b/sidecars/panel/src/views/settings/SettingsAccountTab.js @@ -1,201 +1,1332 @@ -/** @fileoverview Saved account credentials and the host's active account quota. */ +/** @fileoverview Unified multi-account switcher, passphrase vault UI, and per-pool quota cards. */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchKeyedList, patchText } from '../../core/domPatch.js'; +import { + h, + patchAttr, + patchClasses, + patchKeyedList, + patchStyleVar, + patchText, +} from '../../core/domPatch.js'; +import { formatCountdown } from '../../core/formatters.js'; import { callSidecarApi } from '../../core/httpClient.js'; +import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; -import { fetchTelemetry } from '../../store/telemetryStore.js'; +import { CustomSelect } from '../../components/ui/CustomSelect.js'; +import { formatAccountTierBadge } from '../../components/widgets/QuotaPoolsWidget.js'; +import { + DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, + normalizeAccountQuotaRefreshMinutes, +} from '../../../shared/settings-normalization.mjs'; +import { saveSettingsPatch, telemetryStore } from '../../store/telemetryStore.js'; const key = (name) => `settings.account.${name}`; +const fmtPct = (v) => String(+Number(v).toFixed(1)); + +let warmAccountCache = null; + const errors = new Set([ 'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound', 'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied', 'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable', 'oauthUnavailable', 'quotaUnavailable', + 'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed', + 'loginStartFailed', 'loginExchangeFailed', 'loginExpired', 'loginDenied', + 'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordMismatch', + 'passwordRateLimited', 'vaultDecryptFailed', 'invalidActionNonce', ]); +const okToastKeys = new Set([ + 'saved', 'removed', 'switched', + 'pwdEnabledToast', 'pwdChangedToast', 'pwdDisabledToast', + 'vaultUnlockedToast', 'vaultLockedToast', 'vaultResetToast', +]); + +function getAccountRefreshOptions() { + return [ + { value: 10, label: t(key('refresh10m')) }, + { value: 30, label: t(key('refresh30m')) }, + { value: 60, label: t(key('refresh1h')) }, + { value: 180, label: t(key('refresh3h')) }, + { value: 360, label: t(key('refresh6h')) }, + { value: 720, label: t(key('refresh12h')) }, + { value: 1440, label: t(key('refresh24h')) }, + ]; +} + +function formatValidCountdown(isoTime) { + if (!isoTime) return ''; + const ms = Date.parse(isoTime); + if (!Number.isFinite(ms) || ms <= Date.now()) return ''; + return formatCountdown(isoTime); +} + +function syncRemainingMeter(wrapEl, quotaLabelEl, resetEl, fillEl, hasData, labelText, remVal, resetTime) { + patchAttr(wrapEl, 'hidden', !hasData); + if (!hasData) return; + const clamped = Math.max(0, Math.min(100, Number(remVal) || 0)); + patchText(quotaLabelEl, labelText); + const cd = formatValidCountdown(resetTime); + patchText(resetEl, cd); + patchAttr(resetEl, 'hidden', !cd); + patchStyleVar(fillEl, '--fill-w', `${+clamped.toFixed(1)}%`); + patchClasses(fillEl, { + 'tone-warn': clamped > 15 && clamped <= 30, + 'tone-danger': clamped <= 15, + }); +} + function renderQuotaRows(container, quotaPools) { const locale = getEffectiveLocale(); - const pools = quotaPools.filter((pool) => Number.isFinite(pool.remainingPct) || Number.isFinite(pool.weeklyRemainingPct)); + const pools = (Array.isArray(quotaPools) ? quotaPools : []).filter( + (pool) => Number.isFinite(pool?.remainingPct) || Number.isFinite(pool?.weeklyRemainingPct) + ); patchKeyedList(container, pools, { keyFn: (pool) => pool.poolKey || pool.poolLabel, - sigFn: (pool) => JSON.stringify([locale, pool.poolLabel, pool.remainingPct, pool.weeklyRemainingPct]), + sigFn: (pool) => + JSON.stringify([ + locale, + pool.poolLabel, + pool.remainingPct, + pool.weeklyRemainingPct, + pool.resetTime, + pool.weeklyResetTime, + ]), createRow: () => { - const label = h('span'); - const remaining = h('span', { className: 'settings-account-quota' }); - return { el: h('div', { className: 'settings-action-block' }, [label, remaining]), refs: { label, remaining } }; + const poolTitle = h('div', { className: 'account-pool-name' }); + + const label5h = h('span', { className: 'settings-account-quota text-mono' }); + const reset5h = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const fill5h = h('div', { className: 'progress-fill' }); + const meter5h = h('div', { className: 'account-meter-col' }, [ + h('div', { className: 'account-meter-head' }, [label5h, reset5h]), + h('div', { className: 'progress-track account-progress-track' }, [fill5h]), + ]); + + const labelWk = h('span', { className: 'settings-account-quota text-mono' }); + const resetWk = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const fillWk = h('div', { className: 'progress-fill' }); + const meterWk = h('div', { className: 'account-meter-col' }, [ + h('div', { className: 'account-meter-head' }, [labelWk, resetWk]), + h('div', { className: 'progress-track account-progress-track' }, [fillWk]), + ]); + + const gridEl = h('div', { className: 'account-pool-meters' }, [meter5h, meterWk]); + const el = h('div', { className: 'account-pool-group' }, [poolTitle, gridEl]); + return { + el, + refs: { poolTitle, gridEl, meter5h, label5h, reset5h, fill5h, meterWk, labelWk, resetWk, fillWk }, + }; }, - updateRow: ({ label, remaining }, pool) => { - patchText(label, pool.poolLabel || pool.poolKey); - const values = []; - if (Number.isFinite(pool.remainingPct)) values.push(t(key('quota5h'), { percent: pool.remainingPct })); - if (Number.isFinite(pool.weeklyRemainingPct)) values.push(t(key('quotaWeekly'), { percent: pool.weeklyRemainingPct })); - patchText(remaining, values.join(' · ')); + updateRow: (refs, pool) => { + patchText(refs.poolTitle, pool.poolLabel || pool.poolKey); + const has5h = Number.isFinite(pool.remainingPct); + const hasWk = Number.isFinite(pool.weeklyRemainingPct); + patchClasses(refs.gridEl, { 'is-single': (has5h ? 1 : 0) + (hasWk ? 1 : 0) <= 1 }); + + syncRemainingMeter( + refs.meter5h, + refs.label5h, + refs.reset5h, + refs.fill5h, + has5h, + has5h ? t(key('quota5h'), { percent: fmtPct(pool.remainingPct) }) : '', + pool.remainingPct, + pool.resetTime + ); + syncRemainingMeter( + refs.meterWk, + refs.labelWk, + refs.resetWk, + refs.fillWk, + hasWk, + hasWk ? t(key('quotaWeekly'), { percent: fmtPct(pool.weeklyRemainingPct) }) : '', + pool.weeklyRemainingPct, + pool.weeklyResetTime + ); }, }); + patchAttr(container, 'hidden', pools.length === 0); return pools.length; } +function needsLegacyUltraTierRefresh(cached) { + if (!cached || cached.tierId || cached.tierMultiplier) return false; + const name = String(cached.tierName || ''); + return /\bultra\b/i.test(name) && !/\b(?:5x|20x)\b/i.test(name); +} + +function isValidVaultPassphrase(raw) { + return typeof raw === 'string' && raw.length >= 4 && raw.length <= 128 && Boolean(raw.trim()); +} + export const SettingsAccountTab = defineComponent({ name: 'SettingsAccountTab', setup({ props, onCleanup }) { let account = null; let quotas = null; - let accounts = []; - let selectedEmail = ''; - let supported = null; + let refreshMinutes = normalizeAccountQuotaRefreshMinutes( + telemetryStore.getState().telemetry?.settings?.accountQuotaRefreshMinutes ?? + DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES + ); + let accounts = warmAccountCache ? [...warmAccountCache.accounts] : []; + let selectedEmail = warmAccountCache ? warmAccountCache.selectedEmail : ''; + let supported = warmAccountCache ? warmAccountCache.supported : null; + let vaultSecurity = warmAccountCache?.vaultSecurity + ? { ...warmAccountCache.vaultSecurity } + : { enabled: false, unlocked: true }; + let actionNonce = warmAccountCache?.actionNonce || ''; let operation = ''; let status = ''; + let statusClearTimer = null; + let confirmTarget = null; + let confirmClearTimer = null; + let switchState = null; + let importOpen = false; + let pwdDrawerOpen = false; + let pwdManageMode = 'change'; + let forgotResetOpen = false; + let refreshingSavedQuotas = false; let disposed = false; - const savedQuotas = new Map(); + let loginSession = null; + let loginTimer; + let loginGeneration = 0; + let loginRefreshEmail = ''; + const savedQuotas = new Map(warmAccountCache ? warmAccountCache.savedQuotasEntries : []); + const quotaInFlight = new Set(); + const quotaVisibleLoading = new Set(); + const quotaErrors = new Map(); - const title = h('span', { className: 'panel-title' }); - const identityLabel = h('div', { className: 'settings-action-title' }); - const identity = h('div', { className: 'settings-action-desc settings-account-identity' }); - const plan = h('div', { className: 'settings-action-desc' }); - const quotaTitle = h('div', { className: 'settings-action-title' }); - const quotaRows = h('div', { className: 'settings-account-list' }); - const quotaMessage = h('div', { className: 'settings-action-desc' }); - const savedTitle = h('span', { className: 'panel-title' }); - const savedRows = h('div', { className: 'settings-account-list' }); - const savedMessage = h('div', { className: 'settings-action-desc' }); - const pending = h('div', { className: 'settings-action-desc', role: 'status' }); - const feedback = h('div', { className: 'settings-action-desc', role: 'status' }); - const capture = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('capture') }); - const reload = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('list') }); - const credentialLabel = h('span'); - const importHint = h('div', { className: 'settings-action-desc' }); - const credential = h('input', { type: 'password', required: true, autocomplete: 'off', spellcheck: 'false', maxlength: 16384 }); - const save = h('button', { type: 'submit', className: 'btn-secondary' }); - const form = h('form', { className: 'settings-account-form', autocomplete: 'off', onSubmit: importCredential }, [ - h('label', {}, [credentialLabel, credential]), - importHint, - save, + function isVaultLocked() { + return Boolean(vaultSecurity?.enabled && !vaultSecurity?.unlocked); + } + + function syncWarmCache() { + if (supported !== true) return; + warmAccountCache = { + supported, + accounts: [...accounts], + selectedEmail, + savedQuotasEntries: [...savedQuotas.entries()], + vaultSecurity: { ...vaultSecurity }, + actionNonce, + }; + } + + function clearConfirmTarget(shouldRender = false) { + if (confirmClearTimer) { + clearTimeout(confirmClearTimer); + confirmClearTimer = null; + } + if (!confirmTarget) return; + confirmTarget = null; + if (shouldRender && !disposed) render(); + } + + function armOrRunConfirm(type, targetKey, runFn) { + if (confirmTarget && confirmTarget.type === type && confirmTarget.key === targetKey) { + clearConfirmTarget(false); + runFn(); + return; + } + if (confirmClearTimer) clearTimeout(confirmClearTimer); + confirmTarget = { type, key: targetKey }; + confirmClearTimer = setTimeout(() => clearConfirmTarget(true), 4500); + render(); + } + + function setTransientStatus(nextStatus, autoClearMs = 0) { + if (statusClearTimer) { + clearTimeout(statusClearTimer); + statusClearTimer = null; + } + status = nextStatus; + if (nextStatus && autoClearMs > 0) { + statusClearTimer = setTimeout(() => { + statusClearTimer = null; + if (!disposed && status === nextStatus) { + status = ''; + render(); + } + }, autoClearMs); + } + } + + function clearPasswordInputs() { + unlockInput.value = ''; + pwdCurrentInput.value = ''; + pwdNewInput.value = ''; + pwdConfirmInput.value = ''; + } + + const loginBtnLabel = h('span'); + const loginButton = h( + 'button', + { + type: 'button', + className: 'btn-primary settings-account-login account-toolbar-btn', + onClick: () => { + clearConfirmTarget(false); + void request('loginStart', { language: getEffectiveLocale() }); + }, + }, + [createSvgIcon('plus', { size: 12 }), loginBtnLabel] + ); + const cancelLogin = h('button', { + type: 'button', + className: 'btn-secondary settings-account-login-cancel account-toolbar-btn', + hidden: true, + onClick: () => request('loginCancel', { id: loginSession?.id }), + }); + const importToggleLabel = h('span'); + const importToggleBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary account-toolbar-btn', + onClick: () => { + clearConfirmTarget(false); + importOpen = !importOpen; + if (importOpen) { + pwdDrawerOpen = false; + clearPasswordInputs(); + } + render(); + if (importOpen) credential.focus?.(); + }, + }, + [importToggleLabel] + ); + + const pwdToggleIcon = createSvgIcon('lock', { size: 12 }); + const pwdToggleLabel = h('span'); + const pwdToggleBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary account-toolbar-btn settings-account-pwd-toggle', + onClick: () => { + clearConfirmTarget(false); + pwdDrawerOpen = !pwdDrawerOpen; + if (pwdDrawerOpen) { + importOpen = false; + pwdManageMode = 'change'; + } + clearPasswordInputs(); + render(); + if (pwdDrawerOpen) { + (vaultSecurity.enabled ? pwdCurrentInput : pwdNewInput).focus?.(); + } + }, + }, + [pwdToggleIcon, pwdToggleLabel] + ); + + const lockNowLabel = h('span'); + const lockNowBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary account-toolbar-btn settings-account-lock-now', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + pwdDrawerOpen = false; + importOpen = false; + clearPasswordInputs(); + void request('lockVault'); + }, + }, + [createSvgIcon('lock', { size: 12 }), lockNowLabel] + ); + + const feedback = h('span', { + className: 'settings-action-desc account-status-inline', + role: 'status', + hidden: true, + }); + const refreshIntervalSelect = CustomSelect({ + className: 'account-refresh-select', + icon: 'clock', + modelValue: refreshMinutes, + options: getAccountRefreshOptions(), + onUpdateModelValue: async (nextVal) => { + const nextMins = normalizeAccountQuotaRefreshMinutes(nextVal); + refreshMinutes = nextMins; + refreshIntervalSelect.setValue(nextMins); + void refreshSavedQuotas(); + try { + await saveSettingsPatch({ accountQuotaRefreshMinutes: nextMins }); + } catch { + // Keep selected interval locally if save fails transiently + } + }, + }); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'aria-label', t(key('refreshFreqAria'))); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'title', t(key('refreshFreqAria'))); + + const reload = h( + 'button', + { + type: 'button', + className: 'icon-btn account-reload-btn', + onClick: () => request('list'), + }, + [createSvgIcon('refresh', { size: 13 })] + ); + + // --- Locked Vault Unlock Strip --- + const unlockHintLabel = h('span'); + const forgotToggleBtn = h('button', { + type: 'button', + className: 'account-link-btn settings-account-forgot-btn', + onClick: () => { + forgotResetOpen = !forgotResetOpen; + clearConfirmTarget(false); + render(); + }, + }); + const unlockInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-unlock-input', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + }); + const unlockSubmitBtn = h('button', { + type: 'submit', + className: 'btn-primary account-toolbar-btn settings-account-unlock-submit', + }); + const unlockForm = h( + 'form', + { + className: 'account-import-row', + autocomplete: 'off', + onSubmit: submitUnlock, + }, + [unlockInput, unlockSubmitBtn] + ); + const resetHintEl = h('span', { className: 'settings-action-desc' }); + const resetVaultBtn = h('button', { + type: 'button', + className: 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-reset-vault', + onClick: () => { + armOrRunConfirm('resetVault', 'vault', () => { + void request('resetVault', { confirmReset: 'RESET' }); + }); + }, + }); + const resetRow = h('div', { className: 'account-reset-row', hidden: true }, [ + resetHintEl, + resetVaultBtn, ]); + const unlockBox = h('div', { className: 'account-unlock-box settings-account-unlock-box', hidden: true }, [ + h('div', { className: 'account-unlock-head' }, [ + h('span', { className: 'account-unlock-title' }, [ + createSvgIcon('lock', { size: 13 }), + unlockHintLabel, + ]), + forgotToggleBtn, + ]), + unlockForm, + resetRow, + ]); + + // --- Passphrase Setup / Manage Drawer --- + const pwdTabChangeBtn = h('button', { + type: 'button', + className: 'account-pwd-tab', + onClick: () => { + pwdManageMode = 'change'; + clearPasswordInputs(); + render(); + }, + }); + const pwdTabDisableBtn = h('button', { + type: 'button', + className: 'account-pwd-tab', + onClick: () => { + pwdManageMode = 'disable'; + clearPasswordInputs(); + render(); + }, + }); + const pwdTabsWrap = h('div', { className: 'account-pwd-tabs', hidden: true }, [ + pwdTabChangeBtn, + pwdTabDisableBtn, + ]); + const pwdCurrentInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-pwd-current', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + hidden: true, + }); + const pwdNewInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-pwd-new', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + }); + const pwdConfirmInput = h('input', { + type: 'password', + className: 'settings-text-input account-import-input settings-account-pwd-confirm', + autocomplete: 'off', + spellcheck: 'false', + maxlength: 128, + }); + const pwdSubmitBtn = h('button', { + type: 'submit', + className: 'btn-primary account-toolbar-btn settings-account-pwd-submit', + }); + const pwdHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const pwdForm = h( + 'form', + { + className: 'account-import-drawer settings-account-pwd-form', + autocomplete: 'off', + hidden: true, + onSubmit: submitPasswordDrawer, + }, + [ + pwdTabsWrap, + h('div', { className: 'account-import-row' }, [ + pwdCurrentInput, + pwdNewInput, + pwdConfirmInput, + pwdSubmitBtn, + ]), + pwdHint, + ] + ); + + // --- Credential Import Drawer --- + const credential = h('input', { + type: 'password', + className: 'settings-text-input account-import-input', + required: true, + autocomplete: 'off', + spellcheck: 'false', + maxlength: 16384, + }); + const save = h('button', { + type: 'submit', + className: 'btn-primary account-toolbar-btn', + }); + const importHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const form = h( + 'form', + { + className: 'settings-account-form account-import-drawer', + autocomplete: 'off', + hidden: true, + onSubmit: importCredential, + }, + [ + h('div', { className: 'account-import-row' }, [credential, save]), + importHint, + ] + ); + + const loginMessage = h('div', { + className: 'settings-action-desc account-flow-msg', + role: 'status', + hidden: true, + }); + const loginLink = h('a', { + className: 'account-flow-link', + target: '_blank', + rel: 'noopener noreferrer', + hidden: true, + }); + const loginStrip = h('div', { className: 'account-flow-strip', hidden: true }, [ + loginMessage, + loginLink, + ]); + const pending = h('div', { + className: 'settings-action-desc account-flow-strip is-warn', + role: 'status', + hidden: true, + }); + + const toolbarPanel = h('section', { className: 'panel account-toolbar-panel' }, [ + h('div', { className: 'account-toolbar-row' }, [ + h('div', { className: 'account-toolbar-left' }, [ + loginButton, + cancelLogin, + importToggleBtn, + pwdToggleBtn, + lockNowBtn, + ]), + h('div', { className: 'account-toolbar-right' }, [ + feedback, + refreshIntervalSelect.el, + reload, + ]), + ]), + unlockBox, + pwdForm, + form, + loginStrip, + pending, + ]); + + const cardsHost = h('div', { className: 'account-cards-stack' }); + const emptyPanel = h('section', { className: 'panel account-empty-panel', hidden: true }, [ + h('div', { className: 'settings-action-desc account-empty-text' }), + ]); + const emptyTextEl = emptyPanel.firstChild; + + function resolveActiveEmail() { + return account?.status === 'signedIn' ? (account.email || '').trim().toLowerCase() : ''; + } + + function buildUnifiedAccountEntries(activeEmail) { + const entries = []; + if (activeEmail) { + entries.push({ + email: activeEmail, + isActive: true, + isSaved: accounts.includes(activeEmail), + }); + } + for (let i = 0; i < accounts.length; i++) { + const addr = accounts[i]; + if (addr && addr !== activeEmail) { + entries.push({ + email: addr, + isActive: false, + isSaved: true, + }); + } + } + return entries; + } function render() { const signedIn = account?.status === 'signedIn'; - const activeEmail = signedIn ? account.email?.trim().toLowerCase() : ''; - const canWrite = supported === true && !operation; + const activeEmail = resolveActiveEmail(); + if (activeEmail && selectedEmail === activeEmail && switchState?.state !== 'starting') { + selectedEmail = ''; + } + const vaultLocked = isVaultLocked(); + const canOperateVault = + supported === true && + !operation && + status !== 'restarting' && + switchState?.state !== 'starting'; + const canWrite = canOperateVault && !vaultLocked; const locale = getEffectiveLocale(); - patchText(title, t(key('current'))); - patchText(identityLabel, t(key('email'))); - patchText(identity, signedIn ? account.email || account.name : - t(key(account?.status === 'signedOut' ? 'signedOut' : 'unknown'))); - patchText(plan, signedIn ? account.tierName || account.planName || '' : ''); - patchAttr(plan, 'hidden', !plan.textContent); + const activeTierBadge = + signedIn && (account?.tierName || account?.planName) + ? formatAccountTierBadge(account) + : ''; - patchText(quotaTitle, t(key('quota'))); - const poolCount = renderQuotaRows(quotaRows, signedIn ? quotas?.pools || [] : []); - patchText(quotaMessage, t(key(poolCount ? 'quotaStale' : 'noQuota'))); - patchAttr(quotaMessage, 'hidden', poolCount > 0 && !quotas?.meta?.isStale); + const loginActive = ['waiting', 'exchanging', 'saving'].includes(loginSession?.status); + patchText(loginBtnLabel, t(key('googleLogin'))); + patchAttr(loginButton, 'disabled', !canWrite || loginActive); + patchText(cancelLogin, t(key('cancelLogin'))); + patchAttr(cancelLogin, 'hidden', !loginActive); + patchAttr(cancelLogin, 'disabled', Boolean(operation) || loginSession?.status === 'saving'); - patchText(savedTitle, t(key('savedCredentials'))); - patchText(capture, t(key('capture'))); - patchText(reload, t(key('reload'))); - patchText(save, t(key('save'))); - patchText(credentialLabel, t(key('credential'))); - patchText(importHint, t(key('importHint'))); - patchAttr(capture, 'disabled', !canWrite || !activeEmail); + patchText(importToggleLabel, t(key('importExisting'))); + patchClasses(importToggleBtn, { 'is-open': importOpen }); + patchAttr(importToggleBtn, 'hidden', supported === false); + patchAttr(importToggleBtn, 'disabled', !canWrite); + + patchSvgIcon(pwdToggleIcon, vaultSecurity.enabled ? 'unlock' : 'lock'); + patchText(pwdToggleLabel, t(key(vaultSecurity.enabled ? 'pwdBtnManage' : 'pwdBtnSet'))); + patchClasses(pwdToggleBtn, { 'is-open': pwdDrawerOpen }); + patchAttr(pwdToggleBtn, 'hidden', supported === false || vaultLocked); + patchAttr(pwdToggleBtn, 'disabled', !canOperateVault); + + patchText(lockNowLabel, t(key('lockNow'))); + patchAttr(lockNowBtn, 'title', t(key('lockNowTip'))); + patchAttr(lockNowBtn, 'hidden', !vaultSecurity.enabled || vaultLocked || supported === false); + patchAttr(lockNowBtn, 'disabled', !canOperateVault); + + // Unlock strip (only when passphrase enabled & locked) + patchAttr(unlockBox, 'hidden', supported !== true || !vaultLocked); + patchText(unlockHintLabel, t(key('vaultLockedHint'))); + patchText(forgotToggleBtn, t(key('forgotPwdToggle'))); + patchAttr(unlockInput, 'placeholder', t(key('unlockPlaceholder'))); + patchAttr(unlockInput, 'disabled', !canOperateVault); + patchText(unlockSubmitBtn, t(key('unlockBtn'))); + patchAttr(unlockSubmitBtn, 'disabled', !canOperateVault); + patchAttr(resetRow, 'hidden', !forgotResetOpen || !vaultLocked); + patchText(resetHintEl, t(key('resetVaultHint'))); + const armedVaultReset = + confirmTarget?.type === 'resetVault' && confirmTarget.key === 'vault'; + patchText(resetVaultBtn, t(key(armedVaultReset ? 'resetVaultConfirm' : 'resetVaultBtn'))); + patchAttr(resetVaultBtn, 'disabled', !canOperateVault); + + // Passphrase setup / manage drawer + const showPwdDrawer = pwdDrawerOpen && !vaultLocked && supported === true; + patchAttr(pwdForm, 'hidden', !showPwdDrawer); + if (showPwdDrawer) { + const isSetNew = !vaultSecurity.enabled; + const isDisableMode = !isSetNew && pwdManageMode === 'disable'; + patchAttr(pwdTabsWrap, 'hidden', isSetNew); + patchText(pwdTabChangeBtn, t(key('pwdTabChange'))); + patchClasses(pwdTabChangeBtn, { 'is-active': pwdManageMode === 'change' }); + patchText(pwdTabDisableBtn, t(key('pwdTabDisable'))); + patchClasses(pwdTabDisableBtn, { 'is-active': isDisableMode }); + + patchAttr(pwdCurrentInput, 'hidden', isSetNew); + patchAttr(pwdCurrentInput, 'placeholder', t(key('pwdCurrentPlaceholder'))); + patchAttr(pwdCurrentInput, 'disabled', !canOperateVault); + + patchAttr(pwdNewInput, 'hidden', isDisableMode); + patchAttr(pwdNewInput, 'placeholder', t(key('pwdNewPlaceholder'))); + patchAttr(pwdNewInput, 'disabled', !canOperateVault); + + patchAttr(pwdConfirmInput, 'hidden', isDisableMode); + patchAttr(pwdConfirmInput, 'placeholder', t(key('pwdConfirmPlaceholder'))); + patchAttr(pwdConfirmInput, 'disabled', !canOperateVault); + + patchText( + pwdSubmitBtn, + t(key(isSetNew ? 'pwdEnableSubmit' : isDisableMode ? 'pwdDisableSubmit' : 'pwdChangeSubmit')) + ); + patchClasses(pwdSubmitBtn, { + 'btn-primary': !isDisableMode, + 'btn-secondary': isDisableMode, + 'account-confirm-danger-btn': isDisableMode, + }); + patchAttr(pwdSubmitBtn, 'disabled', !canOperateVault); + patchText(pwdHint, t(key(isSetNew ? 'pwdSetHint' : 'pwdManageHint'))); + } + + refreshIntervalSelect.setProps({ + modelValue: refreshMinutes, + options: getAccountRefreshOptions(), + }); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'aria-label', t(key('refreshFreqAria'))); + patchAttr(refreshIntervalSelect.refs.triggerBtn, 'title', t(key('refreshFreqAria'))); + patchAttr(refreshIntervalSelect.el, 'hidden', supported === false); + + patchAttr(reload, 'title', t(key('reload'))); + patchAttr(reload, 'aria-label', t(key('reload'))); patchAttr(reload, 'disabled', Boolean(operation)); - patchAttr(form, 'hidden', supported === false); - patchAttr(save, 'disabled', !canWrite); + patchClasses(reload, { 'is-spinning': operation === 'list' }); + + patchAttr(form, 'hidden', !importOpen || vaultLocked || supported === false); + patchAttr(credential, 'placeholder', t(key('credentialPlaceholder'))); patchAttr(credential, 'disabled', !canWrite); - patchText(savedMessage, t(key(supported === null ? 'loading' : 'empty'))); - patchAttr(savedMessage, 'hidden', accounts.length > 0 || supported === false || Boolean(status)); - const message = status || (operation === 'switch' ? 'switching' : operation === 'quota' ? 'loadingQuota' : - operation === 'save' || operation === 'capture' ? 'verifying' : ''); + patchText(save, t(key('save'))); + patchAttr(save, 'disabled', !canWrite); + patchText(importHint, t(key('importHint'))); + + const loginStatusKeys = { + waiting: 'loginWaiting', + exchanging: 'loginFinishing', + saving: 'loginFinishing', + success: 'loginSuccess', + cancelled: 'loginCancelled', + expired: 'loginExpired', + }; + const hasLoginSession = Boolean(loginSession?.status); + const loginIsError = + loginSession?.status === 'error' || + loginSession?.status === 'expired' || + loginSession?.error === 'loginDenied'; + const loginMessageKey = + loginSession?.status === 'error' + ? errors.has(loginSession.error) + ? loginSession.error + : 'loginExchangeFailed' + : loginSession?.error === 'loginDenied' + ? 'loginDenied' + : loginStatusKeys[loginSession?.status] || ''; + patchText(loginMessage, loginMessageKey ? t(key(loginMessageKey)) : ''); + patchAttr(loginMessage, 'hidden', !loginMessageKey); + + const authUrl = + loginSession?.status === 'waiting' && + loginSession.url?.startsWith('https://accounts.google.com/o/oauth2/v2/auth?') + ? loginSession.url + : ''; + patchText(loginLink, t(key('openLoginPage'))); + patchAttr(loginLink, 'href', authUrl || null); + patchAttr(loginLink, 'hidden', !authUrl); + patchClasses(loginStrip, { + 'is-error': loginIsError, + 'is-ok': loginSession?.status === 'success', + 'is-info': loginActive, + }); + patchAttr(loginStrip, 'hidden', !hasLoginSession || !loginMessageKey); + + const failedSwitch = + switchState?.state === 'failed' && errors.has(switchState.error) ? switchState.error : ''; + const message = + status || + failedSwitch || + (operation === 'switch' + ? 'switching' + : operation === 'save' || operation === 'capture' + ? 'verifying' + : ''); + const isFeedbackError = Boolean(errors.has(message)); + const isFeedbackOk = okToastKeys.has(message); patchText(feedback, message ? t(key(message)) : ''); + patchAttr(feedback, 'title', message ? t(key(message)) : null); + patchClasses(feedback, { + 'is-error': isFeedbackError, + 'is-ok': isFeedbackOk, + 'is-info': !isFeedbackError && !isFeedbackOk && Boolean(message), + }); patchAttr(feedback, 'hidden', !message); - const waiting = selectedEmail && activeEmail !== selectedEmail; + + const waiting = + Boolean(selectedEmail) && + activeEmail !== selectedEmail && + switchState?.state === 'written' && + status !== 'restarting'; patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : ''); patchAttr(pending, 'hidden', !waiting); - patchKeyedList(savedRows, accounts, { - keyFn: (addr) => addr, - sigFn: (addr) => JSON.stringify([locale, activeEmail, selectedEmail, canWrite, savedQuotas.get(addr)]), - createRow: (addr) => { - const state = h('div', { className: 'settings-action-desc' }); - const select = h('button', { - type: 'button', className: 'btn-secondary settings-account-switch', onClick: () => request('switch', { email: addr }), + const entries = buildUnifiedAccountEntries(activeEmail); + patchAttr(cardsHost, 'hidden', entries.length === 0); + patchText( + emptyTextEl, + t( + key( + supported === null + ? 'loading' + : account?.status === 'signedOut' + ? 'signedOut' + : 'empty' + ) + ) + ); + patchAttr(emptyPanel, 'hidden', entries.length > 0); + + patchKeyedList(cardsHost, entries, { + keyFn: (entry) => entry.email, + sigFn: (entry) => + JSON.stringify([ + locale, + entry.isActive, + entry.isSaved, + selectedEmail, + switchState?.state || '', + canWrite, + confirmTarget?.key === entry.email ? confirmTarget.type : '', + entry.isActive ? null : savedQuotas.get(entry.email), + quotaVisibleLoading.has(entry.email), + entry.isActive ? null : quotaErrors.get(entry.email), + entry.isActive ? quotas : null, + entry.isActive ? activeTierBadge : '', + ]), + createRow: (entry) => { + const activeDot = h('span', { className: 'dot-swatch account-active-dot', hidden: true }); + const emailEl = h('span', { + className: 'settings-account-identity account-card-email', + text: entry.email, + title: entry.email, }); - const remove = h('button', { - type: 'button', className: 'btn-secondary', onClick: () => request('remove', { email: addr }), + const tierPill = h('span', { className: 'account-tag is-tier', hidden: true }); + const statePill = h('span', { className: 'account-tag', hidden: true }); + + const captureBtn = h('button', { + type: 'button', + className: 'btn-secondary account-card-btn', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('capture'); + }, }); - const loadQuota = h('button', { - type: 'button', className: 'btn-secondary settings-account-load-quota', onClick: () => request('quota', { email: addr }), + const selectBtn = h('button', { + type: 'button', + className: 'btn-secondary account-card-btn', + hidden: true, + onClick: () => { + armOrRunConfirm('switch', entry.email, () => { + const curActive = resolveActiveEmail(); + void request('switch', { + email: entry.email, + ...(curActive ? { activeEmail: curActive } : {}), + }); + }); + }, }); - const rows = h('div', { className: 'settings-account-list' }); - const empty = h('div', { className: 'settings-action-desc' }); - return { - el: h('div', { className: 'settings-account-entry' }, [ - h('div', { className: 'settings-action-block' }, [ - h('div', { className: 'settings-action-info' }, [h('div', { className: 'settings-account-identity', text: addr }), state]), - h('div', { className: 'settings-account-buttons' }, [loadQuota, select, remove]), - ]), rows, empty, + const loadQuotaBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn settings-account-load-quota account-icon-btn', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('quota', { email: entry.email, manual: true }); + }, + }, + [createSvgIcon('refresh', { size: 12 })] + ); + const removeBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn slot-remove-btn settings-account-remove account-icon-btn', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }, + [createSvgIcon('close', { size: 12 })] + ); + const removeConfirmBtn = h('button', { + type: 'button', + className: + 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-remove-confirm', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }); + + const poolsWrap = h('div', { className: 'account-pools-stack' }); + const noteEl = h('div', { className: 'settings-action-desc account-card-note', hidden: true }); + + const cardEl = h('section', { className: 'panel account-card' }, [ + h('div', { className: 'panel-header account-card-head' }, [ + h('div', { className: 'account-card-meta' }, [ + activeDot, + emailEl, + tierPill, + statePill, + ]), + h('div', { className: 'account-card-actions' }, [ + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + ]), ]), - refs: { state, select, remove, loadQuota, rows, empty }, + poolsWrap, + noteEl, + ]); + return { + el: cardEl, + refs: { + cardEl, + activeDot, + emailEl, + tierPill, + statePill, + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + poolsWrap, + noteEl, + }, }; }, - updateRow: (row, addr) => { - const active = addr === activeEmail; - const written = addr === selectedEmail && !active; - patchText(row.state, active ? t(key('active')) : written ? t(key('written')) : ''); - patchAttr(row.state, 'hidden', !active && !written); - patchText(row.select, t(key('switch'))); - patchText(row.remove, t(key('remove'))); - patchText(row.loadQuota, t(key('loadQuota'))); - patchAttr(row.select, 'disabled', !canWrite); - patchAttr(row.remove, 'disabled', !canWrite); - patchAttr(row.loadQuota, 'disabled', !canWrite); - const cached = savedQuotas.get(addr); - const count = renderQuotaRows(row.rows, cached || []); - patchText(row.empty, t(key('emptyCredentialQuota'))); - patchAttr(row.empty, 'hidden', !cached || count > 0); + updateRow: (row, entry) => { + const addr = entry.email; + const active = entry.isActive; + const isSaved = entry.isSaved; + const written = addr === selectedEmail && !active && switchState?.state === 'written'; + const cached = active ? null : savedQuotas.get(addr); + const tierText = active + ? activeTierBadge + : cached?.tierName || cached?.tierId + ? formatAccountTierBadge({ + tierId: cached.tierId, + tierName: cached.tierName, + tierMultiplier: cached.tierMultiplier, + }) + : ''; + const isSpinning = !active && quotaVisibleLoading.has(addr); + const canSwitch = !active && isSaved; + const armedSwitch = confirmTarget?.type === 'switch' && confirmTarget.key === addr; + const armedRemove = confirmTarget?.type === 'remove' && confirmTarget.key === addr; + + patchClasses(row.cardEl, { 'is-active-account': active }); + patchAttr(row.activeDot, 'hidden', !active); + patchText(row.emailEl, addr); + patchAttr(row.emailEl, 'title', addr); + + patchText(row.tierPill, tierText); + patchAttr(row.tierPill, 'hidden', !tierText); + + patchText(row.statePill, active ? t(key('active')) : written ? t(key('written')) : ''); + patchClasses(row.statePill, { 'is-active': active, 'is-written': written }); + patchAttr(row.statePill, 'hidden', !active && !written); + + patchText(row.captureBtn, t(key('capture'))); + patchAttr(row.captureBtn, 'hidden', !active || isSaved || supported === false); + patchAttr(row.captureBtn, 'disabled', !canWrite); + + patchText(row.selectBtn, t(key(armedSwitch ? 'switchConfirm' : 'switch'))); + patchAttr(row.selectBtn, 'title', t(key('switchHint'))); + patchClasses(row.selectBtn, { + 'settings-account-switch': canSwitch, + 'is-confirm-warn': armedSwitch, + }); + patchAttr(row.selectBtn, 'hidden', !canSwitch); + patchAttr(row.selectBtn, 'disabled', !canWrite); + + patchAttr(row.loadQuotaBtn, 'title', t(key(isSpinning ? 'loadingQuota' : 'loadQuota'))); + patchAttr(row.loadQuotaBtn, 'aria-label', t(key('loadQuota'))); + patchClasses(row.loadQuotaBtn, { 'is-spinning': isSpinning }); + // Active account exclusively uses host telemetry — hide OAuth quota refresh on active card + patchAttr(row.loadQuotaBtn, 'hidden', active || !isSaved); + patchAttr(row.loadQuotaBtn, 'disabled', !canWrite || isSpinning); + + patchAttr(row.removeBtn, 'title', t(key('remove'))); + patchAttr(row.removeBtn, 'aria-label', t(key('remove'))); + patchAttr(row.removeBtn, 'hidden', !isSaved || armedRemove); + patchAttr(row.removeBtn, 'disabled', !canWrite); + + patchText(row.removeConfirmBtn, t(key('removeConfirm'))); + patchAttr(row.removeConfirmBtn, 'hidden', !isSaved || !armedRemove); + patchAttr(row.removeConfirmBtn, 'disabled', !canWrite); + + const displayedPools = active ? quotas?.pools || [] : cached?.pools || []; + const poolCount = renderQuotaRows(row.poolsWrap, displayedPools); + const quotaError = active ? '' : quotaErrors.get(addr); + + let noteText = ''; + if (quotaError) { + noteText = t(key(quotaError)); + } else if (active && poolCount > 0 && quotas?.meta?.isStale) { + noteText = t(key('quotaStale')); + } else if (active && poolCount === 0) { + noteText = t(key('noQuota')); + } else if (!active && cached && poolCount === 0) { + noteText = t(key('emptyCredentialQuota')); + } + patchText(row.noteEl, noteText); + patchClasses(row.noteEl, { 'is-error': Boolean(quotaError) }); + patchAttr(row.noteEl, 'hidden', !noteText); }, }); + props.onLayoutChange?.(); } - async function request(action, fields) { + async function dispatchAccountPost(action, fields) { + let res = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { + action, + ...fields, + ...(actionNonce ? { actionNonce } : {}), + }, + cdpTimeoutMs: 40000, + }); + if (res?.actionNonce) { + actionNonce = res.actionNonce; + } + if (res?.error === 'invalidActionNonce' && actionNonce) { + res = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { + action, + ...fields, + actionNonce, + }, + cdpTimeoutMs: 40000, + }); + if (res?.actionNonce) { + actionNonce = res.actionNonce; + } + } + return res; + } + + async function request(action, fields = {}) { + if (action === 'quota') return refreshQuota(fields.email, Boolean(fields.manual)); if (operation) return; operation = action; - status = ''; + if (action === 'loginStart' || action === 'loginCancel') { + clearTimeout(loginTimer); + loginGeneration += 1; + } + setTransientStatus(''); render(); try { - const result = action === 'list' - ? await callSidecarApi('/api/accounts') - : await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields }, cdpTimeoutMs: 40000 }); + const result = + action === 'list' + ? await callSidecarApi('/api/accounts') + : await dispatchAccountPost(action, fields); if (disposed) return; + if (typeof result?.actionNonce === 'string' && result.actionNonce) { + actionNonce = result.actionNonce; + } if (result?.error) { if (result.error === 'unsupported') supported = false; - status = errors.has(result.error) ? result.error : 'storeFailed'; + if (result.error === 'vaultLocked') { + vaultSecurity = { enabled: true, unlocked: false }; + syncWarmCache(); + } + setTransientStatus(errors.has(result.error) ? result.error : 'storeFailed', 3600); return; } - if (action === 'quota') { - savedQuotas.set(result.email, result.pools); + if (action === 'loginStart' || action === 'loginCancel') { + applyLogin(result.login); + if (result.login?.status === 'success') loginRefreshEmail = result.login.email; return; } supported = result?.supported === true; accounts = result?.accounts || []; selectedEmail = result?.selectedEmail || ''; - if (action === 'save' || action === 'capture') status = 'saved'; - if (action === 'remove') { - savedQuotas.delete(fields.email); - status = 'removed'; + switchState = result?.switchState || null; + if (result?.security) { + vaultSecurity = { + enabled: Boolean(result.security.enabled), + unlocked: result.security.unlocked !== false, + }; + } else { + vaultSecurity = { enabled: false, unlocked: true }; } - if (action === 'switch') { - status = result.confirmed ? 'switched' : ''; - void fetchTelemetry({ force: true }).catch(() => {}); + if (result.login) applyLogin(result.login); + if (action === 'resetVault') { + savedQuotas.clear(); + quotaErrors.clear(); + } + for (const [addr, snapshot] of Object.entries(result?.quotas || {})) { + savedQuotas.set(addr, snapshot); + } + syncWarmCache(); + if (action !== 'switch' && !isVaultLocked()) { + void refreshSavedQuotas(); + } + if (action === 'save' || action === 'capture') { + importOpen = false; + setTransientStatus('saved', 2600); + } else if (action === 'remove') { + savedQuotas.delete(fields.email); + quotaErrors.delete(fields.email); + syncWarmCache(); + setTransientStatus('removed', 2600); + } else if (action === 'switch') { + setTransientStatus(result.restarting ? 'restarting' : 'switchStartFailed'); + } else if (action === 'setPassword') { + pwdDrawerOpen = false; + setTransientStatus('pwdEnabledToast', 2600); + } else if (action === 'changePassword') { + pwdDrawerOpen = false; + setTransientStatus('pwdChangedToast', 2600); + } else if (action === 'disablePassword') { + pwdDrawerOpen = false; + setTransientStatus('pwdDisabledToast', 2600); + } else if (action === 'unlockVault') { + forgotResetOpen = false; + quotaErrors.clear(); + setTransientStatus('vaultUnlockedToast', 2200); + } else if (action === 'lockVault') { + pwdDrawerOpen = false; + importOpen = false; + setTransientStatus('vaultLockedToast', 2200); + } else if (action === 'resetVault') { + forgotResetOpen = false; + setTransientStatus('vaultResetToast', 2600); } } catch { - status = 'storeFailed'; + setTransientStatus('storeFailed', 3200); } finally { operation = ''; + if (!disposed) { + render(); + if (loginRefreshEmail) { + const email = loginRefreshEmail; + loginRefreshEmail = ''; + void refreshLoginAccount(email); + } + } + } + } + + async function refreshLoginAccount(email) { + if (disposed || !email) return; + if (operation) { + loginRefreshEmail = email; + return; + } + await request('list'); + if (!disposed && !isVaultLocked() && email !== resolveActiveEmail()) { + void refreshQuota(email, false); + } + } + + function applyLogin(session) { + loginSession = session; + clearTimeout(loginTimer); + if (['waiting', 'exchanging', 'saving'].includes(session?.status)) { + loginTimer = setTimeout(() => pollLogin(session.id, loginGeneration), 1000); + } + } + + async function pollLogin(id, generation) { + try { + const result = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { action: 'loginStatus', id, ...(actionNonce ? { actionNonce } : {}) }, + cdpTimeoutMs: 10000, + }); + if (disposed || generation !== loginGeneration) return; + if (typeof result?.actionNonce === 'string' && result.actionNonce) { + actionNonce = result.actionNonce; + } + if (result.error) throw new Error(result.error); + applyLogin(result.login); + if (loginSession?.status === 'success') await refreshLoginAccount(loginSession.email); + } catch { + if (disposed || generation !== loginGeneration) return; + loginSession = { id, status: 'error', error: 'loginStartFailed' }; + } + if (!disposed) render(); + } + + async function refreshSavedQuotas() { + if (refreshingSavedQuotas || isVaultLocked()) return; + refreshingSavedQuotas = true; + try { + const activeEmail = resolveActiveEmail(); + const ttlMs = refreshMinutes * 60_000; + const staleTargets = accounts.filter((addr) => { + // Active account exclusively uses host telemetry — never poll via OAuth + if (!addr || addr === activeEmail) return false; + const cached = savedQuotas.get(addr); + if (needsLegacyUltraTierRefresh(cached)) return true; + return Date.now() - (cached?.fetchedAt || 0) >= ttlMs; + }); + const BATCH_SIZE = 3; + for (let i = 0; i < staleTargets.length; i += BATCH_SIZE) { + if (disposed || operation === 'switch' || isVaultLocked()) break; + const batch = staleTargets.slice(i, i + BATCH_SIZE); + await Promise.all(batch.map((addr) => refreshQuota(addr, false))); + } + } finally { + refreshingSavedQuotas = false; + } + } + + async function refreshQuota(addr, manual = false) { + const activeEmail = resolveActiveEmail(); + if (!addr || addr === activeEmail || isVaultLocked() || quotaInFlight.has(addr) || disposed) { + return; + } + const hasCachedPools = Boolean(savedQuotas.get(addr)?.pools?.length); + const showSpinner = manual || !hasCachedPools; + quotaInFlight.add(addr); + if (showSpinner) quotaVisibleLoading.add(addr); + quotaErrors.delete(addr); + if (showSpinner || quotaErrors.size > 0) render(); + try { + const result = await callSidecarApi('/api/accounts/update', { + method: 'POST', + body: { action: 'quota', email: addr, ...(actionNonce ? { actionNonce } : {}) }, + cdpTimeoutMs: 40000, + }); + if (typeof result?.actionNonce === 'string' && result.actionNonce) { + actionNonce = result.actionNonce; + } + if (result?.error === 'vaultLocked') { + vaultSecurity = { enabled: true, unlocked: false }; + syncWarmCache(); + return; + } + if (result?.error) { + if (manual || !hasCachedPools) { + quotaErrors.set(addr, errors.has(result.error) ? result.error : 'quotaUnavailable'); + } + } else { + const prev = savedQuotas.get(addr) || {}; + const nextTierId = result.tierId || prev.tierId || ''; + const nextTierName = result.tierName || prev.tierName || ''; + const nextTierMult = result.tierMultiplier || prev.tierMultiplier || ''; + savedQuotas.set(addr, { + pools: result.pools, + fetchedAt: result.fetchedAt || Date.now(), + ...(nextTierId ? { tierId: nextTierId } : {}), + ...(nextTierName ? { tierName: nextTierName } : {}), + ...(nextTierMult ? { tierMultiplier: nextTierMult } : {}), + }); + syncWarmCache(); + } + } catch { + if (manual || !hasCachedPools) { + quotaErrors.set(addr, 'quotaUnavailable'); + } + } finally { + quotaInFlight.delete(addr); + quotaVisibleLoading.delete(addr); if (!disposed) render(); } } + function submitUnlock(event) { + event.preventDefault(); + if (operation) return; + const pwd = unlockInput.value; + unlockInput.value = ''; + if (!isValidVaultPassphrase(pwd)) { + setTransientStatus('wrongPassword', 3000); + render(); + return; + } + void request('unlockVault', { password: pwd }); + } + + function submitPasswordDrawer(event) { + event.preventDefault(); + if (operation) return; + const curPwd = pwdCurrentInput.value; + const nextPwd = pwdNewInput.value; + const confirmPwd = pwdConfirmInput.value; + clearPasswordInputs(); + + if (!vaultSecurity.enabled) { + if (!isValidVaultPassphrase(nextPwd)) { + setTransientStatus('invalidPassword', 3200); + render(); + return; + } + if (nextPwd !== confirmPwd) { + setTransientStatus('passwordMismatch', 3200); + render(); + return; + } + void request('setPassword', { newPassword: nextPwd }); + return; + } + + if (!isValidVaultPassphrase(curPwd)) { + setTransientStatus('wrongPassword', 3000); + render(); + return; + } + if (pwdManageMode === 'disable') { + void request('disablePassword', { currentPassword: curPwd }); + return; + } + if (!isValidVaultPassphrase(nextPwd)) { + setTransientStatus('invalidPassword', 3200); + render(); + return; + } + if (nextPwd !== confirmPwd) { + setTransientStatus('passwordMismatch', 3200); + render(); + return; + } + void request('changePassword', { currentPassword: curPwd, newPassword: nextPwd }); + } + function importCredential(event) { event.preventDefault(); if (operation) return; @@ -204,32 +1335,50 @@ export const SettingsAccountTab = defineComponent({ void request('save', { credential: input }); } - function renderAccount(value, quotaData) { - if (account === value && quotas === quotaData) return; + function renderAccount(value, quotaData, settingsData) { + const nextRefreshMins = + settingsData?.accountQuotaRefreshMinutes !== undefined + ? normalizeAccountQuotaRefreshMinutes(settingsData.accountQuotaRefreshMinutes) + : refreshMinutes; + if (account === value && quotas === quotaData && refreshMinutes === nextRefreshMins) return; account = value; quotas = quotaData; + refreshMinutes = nextRefreshMins; render(); } - const root = h('div', { className: 'settings-tab-stack' }, [ - h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [title]), - h('div', { className: 'settings-action-block' }, [ - h('div', { className: 'settings-action-info' }, [identityLabel, identity, plan]), - ]), - quotaTitle, quotaRows, quotaMessage, pending, - ]), - h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [savedTitle]), - h('div', { className: 'settings-account-buttons' }, [capture, reload]), - savedRows, savedMessage, form, feedback, - ]), + const quotaScheduleTimer = setInterval(() => { + if (!disposed && accounts.length > 0 && !operation && !isVaultLocked()) { + void refreshSavedQuotas(); + } + }, 60_000); + quotaScheduleTimer.unref?.(); + + const root = h('div', { className: 'settings-tab-stack settings-account-root' }, [ + toolbarPanel, + cardsHost, + emptyPanel, ]); render(); onCleanup(() => { disposed = true; + clearTimeout(loginTimer); + clearInterval(quotaScheduleTimer); + if (statusClearTimer) clearTimeout(statusClearTimer); + if (confirmClearTimer) clearTimeout(confirmClearTimer); + refreshIntervalSelect.destroy(); + loginGeneration += 1; credential.value = ''; + clearPasswordInputs(); }); - return { el: root, refs: { renderAccount, refreshLabels: render, load: () => request('list') } }; + return { + el: root, + refs: { + renderAccount, + refreshLabels: render, + preload: () => (supported === null ? request('list') : Promise.resolve()), + load: () => (supported === null ? request('list') : refreshSavedQuotas()), + }, + }; }, }); diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 5834754..0f49bde 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -6266,6 +6266,484 @@ html[data-standalone="true"] .app-shell { line-height: 1.35; } +.settings-account-root [hidden] { + display: none !important; +} + +.account-toolbar-panel { + padding: 9px 12px; + gap: 8px; +} + +.account-toolbar-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + flex-wrap: wrap; +} + +.account-toolbar-left, +.account-toolbar-right { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.account-toolbar-right { + margin-left: auto; +} + +.account-toolbar-btn { + display: inline-flex; + align-items: center; + gap: 5px; + min-height: calc(25px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 10px; + font-size: var(--fs-md); + font-weight: 500; + border-radius: var(--radius-xs); + white-space: nowrap; +} + +.account-toolbar-btn.is-open { + color: var(--accent-primary); + background: var(--accent-primary-soft); +} + +.account-reload-btn { + width: calc(25px * var(--ui-font-scale, 1)); + height: calc(25px * var(--ui-font-scale, 1)); + padding: 0; + border-radius: var(--radius-xs); + flex-shrink: 0; +} + +.account-refresh-select { + flex: 0 0 auto; + width: auto; + min-width: 0; +} + +.account-refresh-select .select-trigger { + width: auto; + min-height: calc(25px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 8px; + gap: 5px; + font-size: var(--fs-sm); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + background: var(--surface-subtle); +} + +[data-modern-ui="true"] .account-refresh-select .select-trigger { + border: none; + background: var(--modern-surface-subtle); +} + +[data-modern-ui="true"] .account-refresh-select .select-trigger:hover, +[data-modern-ui="true"] .account-refresh-select.is-open .select-trigger { + background: var(--modern-surface-hover); +} + +.account-refresh-select .select-menu { + right: 0; + left: auto; + min-width: 108px; + width: max-content; +} + +.account-status-inline { + font-size: var(--fs-sm); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 210px; +} + +.account-status-inline.is-ok { + color: var(--metric-ok); +} + +.account-status-inline.is-error, +.account-card-note.is-error { + color: var(--metric-danger); +} + +.account-status-inline.is-info { + color: var(--text-secondary); +} + +.account-import-drawer { + display: flex; + flex-direction: column; + gap: 5px; + padding-top: 2px; +} + +.account-import-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; +} + +.account-import-input { + flex: 1 1 150px; + min-width: 0; + min-height: calc(26px * var(--ui-font-scale, 1)); +} + +.account-import-hint { + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.account-unlock-box { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px 10px; + border-radius: var(--radius-xs); + background: var(--surface-subtle); +} + +.account-unlock-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.account-unlock-title { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: var(--fs-sm); + color: var(--text-secondary); +} + +.account-unlock-title .svg-icon { + color: var(--metric-warn); + flex-shrink: 0; +} + +.account-link-btn { + padding: 0; + border: none; + background: transparent; + font-size: var(--fs-xs); + color: var(--text-muted); + cursor: pointer; + white-space: nowrap; +} + +.account-link-btn:hover { + color: var(--text-primary); + text-decoration: underline; +} + +.account-reset-row { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 6px 10px; + padding-top: 4px; +} + +.account-reset-row .settings-action-desc { + flex: 1 1 180px; + font-size: var(--fs-xs); +} + +.account-pwd-tabs { + display: inline-flex; + align-items: center; + align-self: flex-start; + gap: 4px; + padding: 2px; + border-radius: var(--radius-xs); + background: var(--surface-subtle); +} + +.account-pwd-tab { + padding: 2px 8px; + border: none; + border-radius: var(--radius-xs); + background: transparent; + font-size: var(--fs-xs); + font-weight: 500; + color: var(--text-secondary); + cursor: pointer; +} + +.account-pwd-tab.is-active { + background: var(--bg-elevated); + color: var(--text-primary); +} + +.account-card-btn.is-confirm-warn { + color: var(--accent-primary); + background: var(--accent-primary-soft); + font-weight: 600; +} + +.account-confirm-danger-btn { + color: var(--metric-danger); + background: color-mix(in srgb, var(--metric-danger) 12%, transparent); + font-weight: 600; +} + +.account-confirm-danger-btn:hover:not(:disabled) { + background: color-mix(in srgb, var(--metric-danger) 20%, transparent); +} + +.account-flow-strip { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 6px 10px; + padding: 6px 9px; + border-radius: var(--radius-xs); + background: var(--surface-subtle); + font-size: var(--fs-sm); +} + +.account-flow-strip.is-info { + background: var(--accent-primary-soft); +} + +.account-flow-strip.is-info .account-flow-msg { + color: var(--accent-primary); +} + +.account-flow-strip.is-ok { + background: color-mix(in srgb, var(--metric-ok) 10%, transparent); +} + +.account-flow-strip.is-ok .account-flow-msg { + color: var(--metric-ok); +} + +.account-flow-strip.is-warn { + background: color-mix(in srgb, var(--metric-warn) 10%, transparent); + color: var(--metric-warn); +} + +.account-flow-strip.is-error { + background: color-mix(in srgb, var(--metric-danger) 10%, transparent); +} + +.account-flow-strip.is-error .account-flow-msg { + color: var(--metric-danger); +} + +.account-flow-link { + font-size: var(--fs-sm); + font-weight: 500; + color: var(--accent-primary); + text-decoration: none; + white-space: nowrap; +} + +.account-flow-link:hover { + text-decoration: underline; +} + +.account-cards-stack { + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.account-card { + gap: 10px; + padding: 11px 14px; +} + +.account-card-head { + gap: 8px; + flex-wrap: wrap; +} + +.account-card-meta { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + min-width: 0; + flex: 1 1 150px; +} + +.account-active-dot { + background: var(--metric-ok); + box-shadow: 0 0 0 2px color-mix(in srgb, var(--metric-ok) 20%, transparent); +} + +.account-card-email { + font-size: var(--fs-base); + font-weight: 600; + color: var(--text-primary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 100%; +} + +.account-tag { + display: inline-flex; + align-items: center; + min-height: calc(18px * var(--ui-font-scale, 1)); + padding: 1px 6px; + font-size: var(--fs-xs); + font-weight: 600; + line-height: 1.2; + border-radius: var(--radius-xs); + border: none; + white-space: nowrap; +} + +.account-tag.is-active { + color: var(--metric-ok); + background: color-mix(in srgb, var(--metric-ok) 12%, transparent); +} + +.account-tag.is-tier { + color: var(--accent-primary); + background: var(--accent-primary-soft); +} + +.account-tag.is-written { + color: var(--metric-warn); + background: color-mix(in srgb, var(--metric-warn) 12%, transparent); +} + +.account-card-actions { + display: inline-flex; + align-items: center; + gap: 5px; + flex-shrink: 0; + margin-left: auto; +} + +.account-card-btn { + min-height: calc(23px * var(--ui-font-scale, 1)); + height: auto; + padding: 1px 8px; + font-size: var(--fs-sm); + font-weight: 500; + border-radius: var(--radius-xs); + white-space: nowrap; +} + +.account-icon-btn { + width: calc(23px * var(--ui-font-scale, 1)); + height: calc(23px * var(--ui-font-scale, 1)); + padding: 0; + border-radius: var(--radius-xs); +} + +.account-pools-stack { + display: flex; + flex-direction: column; + gap: 9px; +} + +.account-pool-group { + display: flex; + flex-direction: column; + gap: 4px; +} + +.account-pool-name { + font-size: var(--fs-xs); + font-weight: 600; + color: var(--text-muted); + line-height: 1.25; + letter-spacing: 0.01em; +} + +.account-pool-meters { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px 14px; +} + +.account-pool-meters.is-single { + grid-template-columns: minmax(0, 1fr); +} + +@media (max-width: 310px) { + .account-pool-meters { + grid-template-columns: minmax(0, 1fr); + } +} + +.account-meter-col { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.account-meter-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 6px; + min-width: 0; +} + +.settings-account-quota { + font-size: var(--fs-sm); + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; +} + +.account-meter-reset { + font-size: var(--fs-2xs); + color: var(--text-muted); + white-space: nowrap; + flex-shrink: 0; +} + +.account-progress-track { + height: 5px; +} + +.account-empty-panel { + padding: 18px 14px; + align-items: center; + justify-content: center; +} + +.account-empty-text { + text-align: center; + color: var(--text-muted); +} + +@keyframes anim-account-spin { + to { + transform: rotate(360deg); + } +} + +.icon-btn.is-spinning .svg-icon { + animation: anim-account-spin 0.8s linear infinite; +} + +@media (prefers-reduced-motion: reduce) { + .icon-btn.is-spinning .svg-icon { + animation: none !important; + } +} + .settings-context-model .select-option-meta { max-width: 62%; text-align: right; diff --git a/sidecars/panel/test/account-login.test.mjs b/sidecars/panel/test/account-login.test.mjs new file mode 100644 index 0000000..83eee72 --- /dev/null +++ b/sidecars/panel/test/account-login.test.mjs @@ -0,0 +1,131 @@ +import assert from 'node:assert/strict'; +import { setTimeout as delay } from 'node:timers/promises'; +import test from 'node:test'; +import { createAccountLoginController } from '../backend/account-login.mjs'; +import { exchangeGoogleAccountCode } from '../backend/account-oauth.mjs'; + +const TEST_OAUTH_CLIENTS = async () => [ + { + id: '1234567890-synthetic-test.apps.googleusercontent.com', + secret: 'synthetic-test-secret', + }, +]; + +function callbackUrl(session, values) { + const authorization = new URL(session.url); + const callback = new URL(authorization.searchParams.get('redirect_uri')); + callback.search = new URLSearchParams({ state: authorization.searchParams.get('state'), ...values }).toString(); + return callback; +} + +test('browser login accepts its loopback callback once and saves the verified account before reporting success', async () => { + const saved = []; + let opened; + let exchanges = 0; + const controller = createAccountLoginController({ + getClients: TEST_OAUTH_CLIENTS, + openBrowser: async (url) => { opened = url; return true; }, + exchangeCode: async (code, redirectUri, verifier) => { + exchanges += 1; + assert.equal(code, 'synthetic-code'); + assert.match(redirectUri, /^http:\/\/127\.0\.0\.1:\d+\/oauth-callback$/); + assert.match(verifier, /^[\w-]{43,128}$/); + return { email: 'verified@example.com', credential: { token: { refresh_token: 'synthetic-private' } } }; + }, + }); + const session = await controller.start(async (account) => { saved.push(account.email); }); + try { + assert.equal(session.opened, true); + const authorization = new URL(opened); + assert.equal(authorization.origin, 'https://accounts.google.com'); + assert.equal(authorization.searchParams.get('access_type'), 'offline'); + assert.equal(authorization.searchParams.get('code_challenge_method'), 'S256'); + assert.match(authorization.searchParams.get('prompt'), /select_account/); + const invalid = await fetch(callbackUrl(session, { state: 'unrelated', code: 'bad-code' })); + assert.equal(invalid.status, 400); + assert.equal(controller.getStatus(session.id).status, 'waiting'); + assert.equal(exchanges, 0); + const response = await fetch(callbackUrl(session, { code: 'synthetic-code' })); + const page = await response.text(); + assert.equal(response.status, 200); + assert.match(page, /账号已添加/); + assert.equal(page.includes('synthetic-code'), false); + assert.equal(page.includes('synthetic-private'), false); + assert.deepEqual(saved, ['verified@example.com']); + assert.deepEqual(controller.getStatus(session.id), { id: session.id, status: 'success', error: '', email: 'verified@example.com' }); + assert.equal(exchanges, 1); + } finally { + controller.cancel(session.id); + } +}); + +test('login offers a usable browser link when opening fails, and cancellation closes the listener', async () => { + const controller = createAccountLoginController({ + getClients: TEST_OAUTH_CLIENTS, + openBrowser: async () => false, + }); + const session = await controller.start(async () => { assert.fail('cancelled login must not save credentials'); }); + assert.equal(session.opened, false); + assert.match(session.url, /^https:\/\/accounts\.google\.com\//); + assert.equal((await controller.start(async () => {})).id, session.id); + assert.equal(controller.cancel(session.id).status, 'cancelled'); + await delay(10); + await assert.rejects(fetch(callbackUrl(session, { code: 'unused' }))); +}); + +test('denied authorization and expired sessions never save an account', async () => { + const controller = createAccountLoginController({ + getClients: TEST_OAUTH_CLIENTS, + openBrowser: async () => true, + timeoutMs: 50, + }); + const denied = await controller.start(async () => { assert.fail('denied authorization'); }, 'en-US'); + const response = await fetch(callbackUrl(denied, { error: 'access_denied' })); + assert.equal(response.status, 200); + assert.match(await response.text(), /Sign-in incomplete/); + assert.equal(controller.getStatus(denied.id).status, 'cancelled'); + const expired = await controller.start(async () => { assert.fail('expired authorization'); }); + await delay(100); + assert.equal(controller.getStatus(expired.id).status, 'expired'); + await assert.rejects(fetch(callbackUrl(expired, { code: 'late' }))); +}); + +test('cancelled code exchange cannot add an account after the next login starts', async () => { + let release; + let exchangeStarted; + const started = new Promise((resolve) => { exchangeStarted = resolve; }); + const credential = new Promise((resolve) => { release = resolve; }); + const controller = createAccountLoginController({ + getClients: TEST_OAUTH_CLIENTS, + openBrowser: async () => true, + exchangeCode: async () => { exchangeStarted(); return credential; }, + }); + const original = await controller.start(async () => { assert.fail('old login was cancelled'); }); + const request = fetch(callbackUrl(original, { code: 'pending' })); + await started; + controller.cancel(original.id); + const replacement = await controller.start(async () => {}); + release({ email: 'old@example.com', credential: {} }); + assert.equal((await request).status, 409); + assert.equal(controller.getStatus(replacement.id).status, 'waiting'); + controller.cancel(replacement.id); +}); + +test('authorization code exchange sends the callback and verifier, then identifies the Google account', async () => { + const verified = await exchangeGoogleAccountCode('synthetic-code', 'http://127.0.0.1:12345/oauth-callback', 'synthetic-verifier', { + getClients: TEST_OAUTH_CLIENTS, + fetchFn: async (url, request) => { + if (url.endsWith('/token')) { + assert.equal(request.body.get('grant_type'), 'authorization_code'); + assert.equal(request.body.get('code'), 'synthetic-code'); + assert.equal(request.body.get('code_verifier'), 'synthetic-verifier'); + assert.equal(request.body.get('redirect_uri'), 'http://127.0.0.1:12345/oauth-callback'); + return { ok: true, json: async () => ({ access_token: 'test-access', refresh_token: 'test-refresh', expires_in: 3600 }) }; + } + assert.equal(request.headers.Authorization, 'Bearer test-access'); + return { ok: true, json: async () => ({ email: 'verified@example.com', verified_email: true }) }; + }, + }); + assert.equal(verified.email, 'verified@example.com'); + assert.equal(verified.credential.token.refresh_token, 'test-refresh'); +}); diff --git a/sidecars/panel/test/account-switch.test.mjs b/sidecars/panel/test/account-switch.test.mjs index 3eff6ac..a66f73f 100644 --- a/sidecars/panel/test/account-switch.test.mjs +++ b/sidecars/panel/test/account-switch.test.mjs @@ -3,8 +3,28 @@ import { mkdtemp, readFile, rmdir, unlink } from 'node:fs/promises'; import { join } from 'node:path'; import test from 'node:test'; import { fileURLToPath } from 'node:url'; -import { resolveGoogleCredential, retrieveCredentialQuota } from '../backend/account-oauth.mjs'; -import { handleAccountCredentialAction, normalizeAccountCredential, runWindowsCredentialStore } from '../backend/account-switch.mjs'; +import { createAccountLoginController } from '../backend/account-login.mjs'; +import { + buildGoogleAccountLoginUrl, + collectNativeOAuthBinaryCandidates, + extractNativeOAuthClients, + resolveGoogleCredential, + retrieveCredentialQuota, +} from '../backend/account-oauth.mjs'; +import { + clearAccountVaultRuntimeState, + handleAccountCredentialAction, + normalizeAccountCredential, + runWindowsCredentialStore, + serializeVaultCredential, +} from '../backend/account-switch.mjs'; +import { + decryptVaultEntryCredential, + issueAccountActionNonce, + resetVaultUnlockFailures, + verifyAccountActionNonce, +} from '../backend/account-vault-crypto.mjs'; +import { executeAccountCredentialAction } from '../backend/api-actions.mjs'; test('accepts a shared OAuth credential or refresh token, and rejects other credential types', () => { const refreshToken = '1//synthetic-refresh-token-for-test'; @@ -42,17 +62,17 @@ test('import uses the verified email and switches only after checking the creden if (request.action === 'read') return { credential: saved }; assert.equal(request.target, 'gemini:antigravity'); assert.equal(request.email, 'next@example.com'); - if (request.action === 'switch') assert.equal(request.expectedCredential, saved); - return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved }; + if (request.action === 'scheduleSwitch') assert.equal(request.expectedCredential, saved); + return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved, scheduled: request.action === 'scheduleSwitch' }; }, }; assert.deepEqual(await handleAccountCredentialAction({ action: 'save', email: 'ignored@example.com', credential: input }, options), { - supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', + supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', quotas: {}, }); assert.deepEqual(calls.splice(0), ['refresh-identity', 'save']); const result = await handleAccountCredentialAction({ action: 'switch', email: 'NEXT@example.com' }, options); - assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', confirmed: true }); - assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'switch', 'GetAuthStatus', 'GetUserStatus']); + assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', quotas: {}, restarting: true }); + assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'scheduleSwitch']); verifiedEmail = 'different@example.com'; assert.deepEqual(await handleAccountCredentialAction({ action: 'switch', email: 'next@example.com' }, options), { error: 'identityMismatch' }); assert.deepEqual(calls, ['read', 'verify-identity']); @@ -64,7 +84,7 @@ test('a saved credential can query its quota without replacing the active login' const result = await handleAccountCredentialAction({ action: 'quota', email: 'next@example.com' }, { platform: 'win32', store: async (request) => { - assert.equal(request.action, 'read'); + assert.ok(['read', 'saveQuota'].includes(request.action)); return { credential }; }, resolveCredential: async (stored) => ({ email: 'next@example.com', credential: stored }), @@ -73,7 +93,8 @@ test('a saved credential can query its quota without replacing the active login' return pools; }, }); - assert.deepEqual(result, { email: 'next@example.com', pools }); + assert.deepEqual({ email: result.email, pools: result.pools }, { email: 'next@example.com', pools }); + assert.ok(result.fetchedAt > 0); }); test('Google OAuth confirms the email and the same account token retrieves quota pools', async () => { @@ -89,6 +110,7 @@ test('Google OAuth confirms the email and the same account token retrieves quota } assert.equal(request.headers.Authorization, 'Bearer new-access'); if (url.endsWith('/userinfo')) return { ok: true, json: async () => ({ email: 'owner@example.com', verified_email: true }) }; + assert.match(request.headers['User-Agent'], /^antigravity\/hub\//); if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: { id: 'test-project' } }) }; assert.equal(JSON.parse(request.body).project, 'test-project'); if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) }; @@ -107,22 +129,469 @@ test('Google OAuth confirms the email and the same account token retrieves quota assert.equal(endpoints.length, 5); }); +test('quota queries keep the native header and omit project when Google did not return one', async () => { + const requests = []; + const pools = await retrieveCredentialQuota('native-access', async (url, request) => { + const body = JSON.parse(request.body); + requests.push({ url, body }); + assert.match(request.headers['User-Agent'], /^antigravity\/hub\//); + if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ allowedTiers: [] }) }; + assert.deepEqual(body, {}); + if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) }; + return { ok: true, json: async () => ({ groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.42 }] }] }) }; + }); + assert.equal(pools[0].weeklyRemainingPct, 42); + assert.equal(requests.length, 3); +}); + +test('a forbidden project is retried without that project before another endpoint', async () => { + let retried = 0; + const pools = await retrieveCredentialQuota('native-access', async (url, request) => { + const body = JSON.parse(request.body); + if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: 'stale-project' }) }; + if (body.project) return { ok: false, status: 403 }; + retried += 1; + if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) }; + return { ok: true, json: async () => ({ groups: [{ displayName: 'Claude and GPT models', buckets: [{ window: '5h', remainingFraction: 0 }] }] }) }; + }); + assert.equal(retried, 2); + assert.equal(pools[0].remainingPct, 0); +}); + test('Windows vault atomically saves, reloads and removes encrypted entries', { skip: process.platform !== 'win32' }, async () => { const directory = await mkdtemp(fileURLToPath(new URL('../.account-test-', import.meta.url))); const vault = join(directory, 'test.dpapi'); const run = (action, email, credential) => runWindowsCredentialStore({ action, email, credential, vault }); try { const credential = normalizeAccountCredential('1//synthetic-refresh-token-for-test'); - assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '' }); - assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '' }); - assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' }); + assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '', quotas: {} }); + assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '', quotas: {} }); + assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '', quotas: {} }); assert.deepEqual(await run('read', 'next@example.com'), { credential }); assert.deepEqual(await runWindowsCredentialStore({ action: 'save', email: 'next@example.com', credential, expectedCredential: 'stale', vault }), { error: 'credentialChanged' }); assert.equal((await readFile(vault)).includes('synthetic-refresh-token-for-test'), false); - assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' }); - assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '' }); + assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '', quotas: {} }); + const quota = { fetchedAt: 100, pools: [{ poolKey: 'Gemini', remainingPct: 0, weeklyRemainingPct: 70 }] }; + await runWindowsCredentialStore({ action: 'saveQuota', email: 'active@example.com', expectedCredential: credential, quota, vault }); + assert.deepEqual((await run('list')).quotas, { 'active@example.com': quota }); + assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '', quotas: { 'active@example.com': quota } }); } finally { await unlink(vault).catch((err) => { if (err.code !== 'ENOENT') throw err; }); await rmdir(directory); } }); + +test('browser authorization adds a credential through the normal account actions and encrypted vault', { skip: process.platform !== 'win32' }, async () => { + const directory = await mkdtemp(fileURLToPath(new URL('../.account-login-test-', import.meta.url))); + const vault = join(directory, 'test.dpapi'); + const credential = JSON.parse(normalizeAccountCredential('1//synthetic-browser-authorized-credential')); + const login = createAccountLoginController({ + getClients: async () => [ + { id: '1234567890-synthetic-test.apps.googleusercontent.com', secret: 'synthetic-test-secret' }, + ], + openBrowser: async () => true, + exchangeCode: async () => ({ email: 'browser@example.com', credential }), + }); + const options = { platform: 'win32', login, store: (request) => runWindowsCredentialStore({ ...request, vault, statusFile: '' }) }; + let id; + try { + const result = await handleAccountCredentialAction({ action: 'loginStart', language: 'zh-CN' }, options); + assert.equal(result.supported, true); + assert.equal(result.login.status, 'waiting'); + id = result.login.id; + const authorization = new URL(result.login.url); + const callback = new URL(authorization.searchParams.get('redirect_uri')); + callback.search = new URLSearchParams({ state: authorization.searchParams.get('state'), code: 'synthetic-code' }).toString(); + assert.equal((await fetch(callback)).status, 200); + assert.equal((await handleAccountCredentialAction({ action: 'loginStatus', id }, options)).login.status, 'success'); + const accounts = await handleAccountCredentialAction({ action: 'list' }, options); + assert.deepEqual(accounts.accounts, ['browser@example.com']); + assert.equal(accounts.selectedEmail, ''); + assert.equal(JSON.stringify(accounts).includes('synthetic-browser-authorized-credential'), false); + assert.equal((await readFile(vault)).includes('synthetic-browser-authorized-credential'), false); + } finally { + if (id) login.cancel(id); + await unlink(vault).catch((error) => { if (error.code !== 'ENOENT') throw error; }); + await rmdir(directory); + } +}); + +test('login scope includes auth/aicode, switch auto-backs-up unsaved active login with 2.34 signout guard, and quota extracts tierName', async () => { + const loginUrl = new URL( + await buildGoogleAccountLoginUrl('http://127.0.0.1:9999/oauth-callback', 'st', 'ch', { + getClients: async () => [ + { id: '1234567890-synthetic-test.apps.googleusercontent.com', secret: 'synthetic-test-secret' }, + ], + }) + ); + const scopes = (loginUrl.searchParams.get('scope') || '').split(/\s+/); + assert.ok(scopes.includes('https://www.googleapis.com/auth/aicode')); + + const savedEntries = new Map([ + ['target@example.com', normalizeAccountCredential('1//target-refresh-token-value-1234567890')], + ]); + const liveCurrent = normalizeAccountCredential('1//active-host-refresh-token-value-1234567890'); + let scheduledPayload = null; + + const res = await handleAccountCredentialAction( + { action: 'switch', email: 'target@example.com', activeEmail: 'current@example.com' }, + { + platform: 'win32', + resolveCredential: async (cred) => ({ + email: cred.token.refresh_token.includes('active-host') + ? 'current@example.com' + : 'target@example.com', + credential: cred, + }), + store: async (req) => { + if (req.action === 'read') { + const hit = savedEntries.get(req.email); + return hit ? { credential: hit } : { error: 'notFound' }; + } + if (req.action === 'readCurrent') { + return { credential: liveCurrent }; + } + if (req.action === 'save') { + savedEntries.set(req.email, req.credential); + return { accounts: [...savedEntries.keys()], selectedEmail: '' }; + } + if (req.action === 'scheduleSwitch') { + scheduledPayload = JSON.parse(req.credential); + return { + scheduled: true, + accounts: [...savedEntries.keys()], + selectedEmail: req.email, + }; + } + return { error: 'storeFailed' }; + }, + } + ); + + assert.equal(res.restarting, true); + assert.ok(savedEntries.has('current@example.com'), 'Active host account must be auto-backed-up before switching away'); + assert.ok( + Number.isSafeInteger(scheduledPayload?.aicode_scope_sign_out_attempted_at) && + scheduledPayload.aicode_scope_sign_out_attempted_at > 0, + 'Switched host credential must include 2.34 aicode_scope_sign_out_attempted_at guard' + ); + + const pools = await retrieveCredentialQuota('tok', async (url) => { + if (url.endsWith(':loadCodeAssist')) { + return { + ok: true, + json: async () => ({ + paidTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' }, + cloudaicompanionProject: 'p1', + }), + }; + } + if (url.endsWith(':fetchAvailableModels')) { + return { ok: true, json: async () => ({ models: {} }) }; + } + return { + ok: true, + json: async () => ({ + groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.85 }] }], + }), + }; + }); + assert.equal(pools.tierName, 'Google AI Ultra'); + assert.equal(pools.tierInfo.tierMultiplier, '20x'); + assert.equal(pools[0].weeklyRemainingPct, 85); + + const litePools = await retrieveCredentialQuota('tok-5x', async (url) => { + if (url.endsWith(':loadCodeAssist')) { + return { + ok: true, + json: async () => ({ + paidTier: { id: 'g1-ultra-lite-tier', name: 'Google AI Ultra' }, + cloudaicompanionProject: 'p2', + }), + }; + } + if (url.endsWith(':fetchAvailableModels')) { + return { ok: true, json: async () => ({ models: {} }) }; + } + return { + ok: true, + json: async () => ({ + groups: [{ displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.91 }] }], + }), + }; + }); + assert.deepEqual(litePools.tierInfo, { + tierId: 'g1-ultra-lite-tier', + tierName: 'Google AI Ultra', + tierMultiplier: '5x', + }); +}); + +test('enforces OAuth client_id allowlist, minimizes at-rest vault payload, and validates actionNonce on mutations', async () => { + const rt = '1//synthetic-refresh-token-for-allowlist-check'; + assert.equal( + normalizeAccountCredential( + JSON.stringify({ client_id: 'evil-third-party.apps.googleusercontent.com', refresh_token: rt }) + ), + null, + 'Must reject unknown third-party OAuth client_id' + ); + assert.equal( + normalizeAccountCredential( + JSON.stringify({ type: 'service_account', refresh_token: rt }) + ), + null, + 'Must reject non-user OAuth credential types' + ); + const syntheticOfficialId = '1234567890-synthetic-test.apps.googleusercontent.com'; + const validWithOfficialClient = normalizeAccountCredential( + JSON.stringify({ + client_id: syntheticOfficialId, + client_secret: 'should-be-stripped', + access_token: 'ephemeral-access-token', + id_token: 'ephemeral-id-token', + refresh_token: rt, + }), + { allowedClientIds: [syntheticOfficialId] } + ); + assert.ok(validWithOfficialClient, 'Allowlisted Antigravity OAuth client_id must be accepted'); + assert.equal(validWithOfficialClient.includes('should-be-stripped'), false); + + // Verify PE .text/.rdata native OAuth client extraction & multi-path candidate discovery + const fakeId = '9876543210-unit-test-client.apps.googleusercontent.com'; + const fakeSecret = 'GOCSPX-unit-test'; + const peBuf = Buffer.alloc(1024); + peBuf.writeUInt16LE(0x5a4d, 0); + peBuf.writeUInt32LE(0x80, 60); + peBuf.writeUInt32LE(0x4550, 0x80); + peBuf.writeUInt16LE(0x8664, 0x84); + peBuf.writeUInt16LE(2, 0x86); + peBuf.writeUInt16LE(0, 0x94); + const secTable = 0x80 + 24; + peBuf.write('.text', secTable, 'ascii'); + peBuf.writeUInt32LE(0x1000, secTable + 12); + peBuf.writeUInt32LE(0x100, secTable + 16); + peBuf.writeUInt32LE(0x200, secTable + 20); + peBuf.write('.rdata', secTable + 40, 'ascii'); + peBuf.writeUInt32LE(0x2000, secTable + 52); + peBuf.writeUInt32LE(0x100, secTable + 56); + peBuf.writeUInt32LE(0x300, secTable + 60); + peBuf.write(fakeId + fakeSecret + 'trailing-go-str', 0x300, 'ascii'); + const codeStart = 0x200; + Buffer.from([0x48, 0xc7, 0x40, 0x08]).copy(peBuf, codeStart); + peBuf.writeUInt32LE(fakeId.length, codeStart + 4); + Buffer.from([0x48, 0x8d, 0x0d]).copy(peBuf, codeStart + 8); + peBuf.writeInt32LE(0x2000 - (0x1000 + 11 + 4), codeStart + 11); + Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]).copy(peBuf, codeStart + 15); + peBuf.writeUInt32LE(fakeSecret.length, codeStart + 22); + Buffer.from([0x48, 0x8d, 0x0d]).copy(peBuf, codeStart + 26); + peBuf.writeInt32LE(0x2000 + fakeId.length - (0x1000 + 29 + 4), codeStart + 29); + assert.deepEqual(extractNativeOAuthClients(peBuf), [{ id: fakeId, secret: fakeSecret }]); + + const discoveredCands = collectNativeOAuthBinaryCandidates({ + env: { + USAGE_MONITOR_HOST_EXE: 'D:\\Custom\\Antigravity\\Antigravity.exe', + ANTIGRAVITY_GEMINI_DIR: 'D:\\CustomGemini', + }, + homeDir: 'C:\\Users\\Test', + existsFn: null, + }); + assert.ok(discoveredCands.some((p) => /D:\\Custom\\Antigravity\\resources\\bin\\language_server\.exe$/i.test(p))); + assert.ok(discoveredCands.some((p) => /D:\\CustomGemini\\bin\\agy\.exe$/i.test(p))); + + const minStored = serializeVaultCredential(JSON.parse(validWithOfficialClient)); + assert.equal(minStored.includes('ephemeral-access-token'), false); + assert.equal(minStored.includes('ephemeral-id-token'), false); + assert.deepEqual(JSON.parse(minStored), { + token: { refresh_token: rt, token_type: 'Bearer' }, + auth_method: 'consumer', + }); + + const nonce = issueAccountActionNonce(1_700_000_000_000); + assert.equal(verifyAccountActionNonce(nonce, 1_700_000_000_000), true); + assert.equal(verifyAccountActionNonce(`${nonce}x`, 1_700_000_000_000), false); + assert.equal(verifyAccountActionNonce(nonce, 1_700_000_000_000 + 45 * 60_000), false); + + const missingNonceRes = await executeAccountCredentialAction({ + action: 'remove', + email: 'a@example.com', + }); + const missingBody = JSON.parse(missingNonceRes.body); + assert.equal(missingBody.error, 'invalidActionNonce'); + assert.equal(typeof missingBody.actionNonce, 'string'); +}); + +test('secondary passphrase encrypts credentials with scrypt + AES-256-GCM, preserves cached list while locked, throttles brute force, and rotates/resets cleanly', { skip: process.platform !== 'win32' }, async (t) => { + const directory = await mkdtemp(fileURLToPath(new URL('../.account-sec-test-', import.meta.url))); + const vault = join(directory, 'sec-test.dpapi'); + t.after(async () => { + clearAccountVaultRuntimeState(); + await unlink(vault).catch((err) => { + if (err.code !== 'ENOENT') throw err; + }); + await rmdir(directory); + }); + + clearAccountVaultRuntimeState(); + const options = { + platform: 'win32', + resolveCredential: async (cred) => { + const rt = cred.token.refresh_token; + const email = rt.includes('alpha') ? 'alpha@example.com' : 'beta@example.com'; + return { + email, + credential: { + token: { + access_token: `live-access-for-${email}`, + refresh_token: rt, + token_type: 'Bearer', + expiry: new Date(Date.now() + 3600_000).toISOString(), + }, + auth_method: 'consumer', + id_token: 'live-jwt-id-token', + }, + }; + }, + getQuota: async () => [{ poolKey: 'Gemini', remainingPct: 88, weeklyRemainingPct: 92 }], + store: (req) => { + if (req.action === 'scheduleSwitch') { + // Verify host receives live access_token while vault receives encrypted agv1: ciphertext + assert.equal(req.credential.includes('live-access-for-'), true); + assert.equal(String(req.vaultCredential || '').startsWith('agv1:'), true); + return Promise.resolve({ + scheduled: true, + accounts: ['alpha@example.com', 'beta@example.com'], + selectedEmail: req.email, + security: { enabled: true, salt: req.expectedSecuritySalt }, + }); + } + return runWindowsCredentialStore({ ...req, vault, statusFile: '' }); + }, + }; + + await handleAccountCredentialAction( + { action: 'save', credential: '1//alpha-refresh-token-1234567890123456' }, + options + ); + await handleAccountCredentialAction( + { action: 'save', credential: '1//beta-refresh-token-1234567890123456' }, + options + ); + await handleAccountCredentialAction({ action: 'quota', email: 'alpha@example.com' }, options); + + // Set secondary passphrase -> encrypts all saved entries inside DPAPI vault + const setRes = await handleAccountCredentialAction( + { action: 'setPassword', newPassword: 'correct-horse-battery' }, + options + ); + assert.deepEqual(setRes.security, { enabled: true, unlocked: true }); + + const rawVaultAfterSet = await runWindowsCredentialStore({ action: 'readVault', vault }); + assert.equal(rawVaultAfterSet.entries.length, 2); + for (const entry of rawVaultAfterSet.entries) { + assert.equal(entry.credential.startsWith('agv1:'), true); + assert.equal(entry.credential.includes('refresh-token'), false); + assert.equal(entry.credential.includes('live-access'), false); + } + // AAD binds ciphertext to email: swapping ciphertext onto another email must fail decryption + assert.throws( + () => + decryptVaultEntryCredential( + rawVaultAfterSet.entries[0].credential, + Buffer.alloc(32, 1), + 'beta@example.com' + ), + /vaultDecryptFailed/ + ); + + // Lock session -> emails & cached quotas remain readable, all mutations/decryptions blocked + const lockedList = await handleAccountCredentialAction({ action: 'lockVault' }, options); + assert.deepEqual(lockedList.security, { enabled: true, unlocked: false }); + assert.deepEqual(lockedList.accounts, ['alpha@example.com', 'beta@example.com']); + assert.equal(lockedList.quotas['alpha@example.com'].pools[0].remainingPct, 88); + + for (const blockedAction of [ + { action: 'switch', email: 'alpha@example.com' }, + { action: 'remove', email: 'beta@example.com' }, + { action: 'quota', email: 'alpha@example.com' }, + { action: 'save', credential: '1//alpha-refresh-token-1234567890123456' }, + { action: 'loginStart', language: 'zh-CN' }, + ]) { + const blocked = await handleAccountCredentialAction(blockedAction, options); + assert.equal(blocked.error, 'vaultLocked', `Action ${blockedAction.action} must reject while locked`); + } + + // Wrong passphrase -> wrongPassword, then rate-limited on 5th consecutive failure + for (let i = 0; i < 4; i++) { + const bad = await handleAccountCredentialAction( + { action: 'unlockVault', password: `wrong-pass-${i}` }, + options + ); + assert.equal(bad.error, 'wrongPassword'); + } + const throttled = await handleAccountCredentialAction( + { action: 'unlockVault', password: 'wrong-pass-5' }, + options + ); + assert.equal(throttled.error, 'passwordRateLimited'); + assert.ok(throttled.retryAfterSec >= 1); + + resetVaultUnlockFailures(); + const unlockedRes = await handleAccountCredentialAction( + { action: 'unlockVault', password: 'correct-horse-battery' }, + options + ); + assert.deepEqual(unlockedRes.security, { enabled: true, unlocked: true }); + + // Switch while unlocked keeps vault entry encrypted + const switched = await handleAccountCredentialAction( + { action: 'switch', email: 'alpha@example.com' }, + options + ); + assert.equal(switched.restarting, true); + + // Change passphrase -> old password rejected, new password works + const changed = await handleAccountCredentialAction( + { + action: 'changePassword', + currentPassword: 'correct-horse-battery', + newPassword: 'new-passphrase-9876', + }, + options + ); + assert.deepEqual(changed.security, { enabled: true, unlocked: true }); + await handleAccountCredentialAction({ action: 'lockVault' }, options); + assert.equal( + (await handleAccountCredentialAction({ action: 'unlockVault', password: 'correct-horse-battery' }, options)).error, + 'wrongPassword' + ); + assert.deepEqual( + (await handleAccountCredentialAction({ action: 'unlockVault', password: 'new-passphrase-9876' }, options)).security, + { enabled: true, unlocked: true } + ); + + // Disable passphrase requires valid current password + assert.equal( + (await handleAccountCredentialAction({ action: 'disablePassword', currentPassword: 'wrong-current' }, options)).error, + 'wrongPassword' + ); + const disabled = await handleAccountCredentialAction( + { action: 'disablePassword', currentPassword: 'new-passphrase-9876', includeSecurity: true }, + options + ); + assert.deepEqual(disabled.security, { enabled: false, unlocked: true }); + const rawAfterDisable = await runWindowsCredentialStore({ action: 'readVault', vault }); + assert.equal(rawAfterDisable.entries[0].credential.startsWith('agv1:'), false); + assert.equal(rawAfterDisable.entries[0].credential.includes('live-access'), false); + + // Reset vault clears entries only when confirmReset === 'RESET' + assert.equal( + (await handleAccountCredentialAction({ action: 'resetVault' }, options)).error, + 'invalidCredential' + ); + const resetRes = await handleAccountCredentialAction( + { action: 'resetVault', confirmReset: 'RESET' }, + options + ); + assert.deepEqual(resetRes.accounts, []); +}); diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 50070a7..fb4dfda 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -2,7 +2,16 @@ import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import vm from 'node:vm'; -import { createHash, randomUUID } from 'node:crypto'; +import { + createCipheriv, + createDecipheriv, + createHash, + createHmac, + randomBytes, + randomUUID, + scrypt, + timingSafeEqual, +} from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; import * as metrics from '../trajectory-metrics.mjs'; import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; @@ -25,6 +34,8 @@ const BACKEND_MODULE_FILES = [ '../backend/fs-atomic.mjs', '../backend/context-windows.mjs', '../backend/account-oauth.mjs', + '../backend/account-login.mjs', + '../backend/account-vault-crypto.mjs', '../backend/account-switch.mjs', '../backend/http-helpers.mjs', '../backend/settings-schema.mjs', @@ -106,7 +117,7 @@ export function backendHarness({ } }; const ctx={ - ...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createHash, randomUUID, + ...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, scrypt, timingSafeEqual, ...(clock ? { Date: class extends Date { constructor(...args) { super(...(args.length ? args : [clock()])); } static now() { return clock(); } diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index a591a4f..1be3958 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1123,7 +1123,7 @@ test('P0 audit fixes: main/bridge-daemon import isolation, standalone lsAddr, du assert.doesNotMatch(renderBody, /\buiStore\.setState\b/); }); -test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and dead SettingsAccountTab exclusion', async () => { +test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and account preferences inclusion', async () => { const { normalizeI18nLanguage } = await import('../src/i18n/index.js'); const { resolveSpecificQuotaSlotSummary } = await import('../src/registries/metricRegistry.js'); const { resolveScopedConversation, isEquivalentTelemetry } = await import( @@ -1188,7 +1188,7 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen assert.equal(scoped.aggregated.recentSteps.length, 2); assert.equal(scoped.mainAgent.recentSteps.length, 1); - // 3. structurePreviewMock schema completeness & dead SettingsAccountTab exclusion from app.js + // 3. structurePreviewMock schema completeness & account preferences bundled for use const mock = buildStructurePreviewTelemetry(); assert.equal(typeof mock.activeConversation.context.compactionUsedTokens, 'number'); assert.equal(mock.activeConversation.aggregated.agentId, 'all'); @@ -1196,8 +1196,8 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen assert.equal(mock.quotas.meta.hasOfficialData, true); const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); - assert.equal(appJs.includes('SettingsAccountTab.js'), false); - assert.equal(appJs.includes('function renderQuotaRows('), false); + assert.equal(appJs.includes('SettingsAccountTab.js'), true); + assert.equal(appJs.includes('function renderQuotaRows('), true); }); test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveActivity/agent/media i18n, full en-US SVG charts, controlled LiveActivityWidget reuse, and shared Mock DOM', async () => { diff --git a/sidecars/panel/test/practical-enhancements.test.mjs b/sidecars/panel/test/practical-enhancements.test.mjs index 4505917..0e18376 100644 --- a/sidecars/panel/test/practical-enhancements.test.mjs +++ b/sidecars/panel/test/practical-enhancements.test.mjs @@ -2859,7 +2859,7 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic assert.equal(latestQuery, ''); assert.equal(sBox.clearBtnEl.hasAttribute('hidden'), true); - // 4. Declarative settingsBackup round-trips all 30 portable keys + coupled legacy flags + // 4. Declarative settingsBackup round-trips all 31 portable keys + coupled legacy flags const exported = buildExportableSettingsJson({ language: 'en-US', modernUi: false, @@ -2868,9 +2868,10 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic windowMountMode: 'composer', showStepFilterToolbar: true, experimentalQuotaReservation: true, + accountQuotaRefreshMinutes: 180, }); const parsedExport = JSON.parse(exported); - assert.equal(Object.keys(parsedExport.settings).length, 30); + assert.equal(Object.keys(parsedExport.settings).length, 31); const reimported = parseImportedSettingsJson(exported); assert.equal(reimported.ok, true); assert.equal(reimported.patch.modernUi, false); @@ -2883,4 +2884,5 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic assert.equal(reimported.patch.enableWindowOverlay, true); assert.equal(reimported.patch.showStepFilterToolbar, true); assert.equal(reimported.patch.experimentalQuotaReservation, true); + assert.equal(reimported.patch.accountQuotaRefreshMinutes, 180); }); diff --git a/sidecars/panel/test/release-pack.test.mjs b/sidecars/panel/test/release-pack.test.mjs index 0cfec53..53bee0e 100644 --- a/sidecars/panel/test/release-pack.test.mjs +++ b/sidecars/panel/test/release-pack.test.mjs @@ -64,8 +64,8 @@ test('pack-release-zip ships only runtime-essential files, excludes dev bloat, a assert.ok(existsSync(zipPath)); assert.ok(summary.zipBytes > 100 * 1024, 'ZIP should contain compiled assets and backend'); assert.ok( - summary.zipBytes < 750 * 1024, - `Runtime-only ZIP should stay compact (<750 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB` + summary.zipBytes < 900 * 1024, + `Runtime-only ZIP should stay compact (<900 KB), got ${(summary.zipBytes / 1024).toFixed(1)} KB` ); // Extract via OS-native expander (same path used by plugin-updater.mjs, where extractDir already exists) diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 452bc8a..437e030 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -720,6 +720,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const mockSettings = { ...defaultMockSettings }; let cacheRebuildCalls = 0; let selectedEmail = ''; + let browserAccountAdded = false; + let browserLoginStarts = 0; const accountRequests = []; const mockWindow = { @@ -752,12 +754,23 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro if (opts.method === 'POST') { const update = JSON.parse(opts.body); accountRequests.push(update); + if (update.action === 'loginStart') { + browserLoginStarts += 1; + if (browserLoginStarts > 1) { + browserAccountAdded = true; + return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: 'browser-login', status: 'success', email: 'browser@example.com' } }) }; + } + return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: 'browser-login', status: 'waiting', url: 'https://accounts.google.com/o/oauth2/v2/auth?state=synthetic', opened: true } }) }; + } + if (update.action === 'loginCancel') { + return { ok: true, status: 200, json: async () => ({ supported: true, login: { id: update.id, status: 'cancelled' } }) }; + } if (update.action === 'quota') { return { ok: true, status: 200, json: async () => ({ email: update.email, pools: [{ poolKey: 'Gemini', remainingPct: 70 }] }) }; } if (update.action === 'switch') selectedEmail = update.email; } - return { ok: true, status: 200, json: async () => ({ supported: true, accounts: ['next@example.com'], selectedEmail }) }; + return { ok: true, status: 200, json: async () => ({ supported: true, accounts: browserAccountAdded ? ['next@example.com', 'browser@example.com'] : ['next@example.com'], selectedEmail, restarting: opts.method === 'POST' && JSON.parse(opts.body).action === 'switch' }) }; } if (urlStr.includes('/api/settings/reset') && String(opts.method || '').toUpperCase() === 'POST') { for (const k of Object.keys(mockSettings)) delete mockSettings[k]; @@ -1437,7 +1450,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(selectRoot.classList.contains('is-open'), true, 'CustomSelect stays open via composedPath'); selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} }); - // Verify modular 3-tab SettingsView (常规 / 结构 / 其他) with Account tab hidden + // Verify account preferences are reachable between Structure and Other. const pillTabs = popoverEl.querySelectorAll('.pill-tab'); pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 15)); @@ -1445,13 +1458,13 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const allPanes = popoverEl.querySelectorAll('.view-pane'); const settingsRoot = popoverEl.querySelector('.settings-view-root'); const subNavBtns = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn'); - assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '其他']); + assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '账号', '其他']); assert.match( stylesCss, /\.settings-subnav-bar\s+\.segmented\s*\{[^}]*grid-auto-flow:\s*column;[^}]*grid-auto-columns:\s*minmax\(0,\s*1fr\);/, 'Settings subnav uses auto-sized equal columns regardless of visible tab count' ); - const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack'); + const [generalPane, structurePane, accountPane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack'); const thirdNavBar = settingsRoot.querySelector('.settings-thirdnav-bar'); assert.ok(thirdNavBar, '3rd-level structure menu bar mounted in SettingsView'); assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when General tab is active'); @@ -1538,7 +1551,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(pillTabs[3].querySelector('.pill-tab-label').textContent, 'Settings'); assert.equal(subNavBtns[0].textContent, 'General'); assert.equal(subNavBtns[1].textContent, 'Structure'); - assert.equal(subNavBtns[2].textContent, 'Other'); + assert.equal(subNavBtns[2].textContent, 'Account'); + assert.equal(subNavBtns[3].textContent, 'Other'); langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.language, 'auto'); @@ -2044,8 +2058,43 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro 'Section reset restores monochrome speed classes in preview step table' ); - // --- 其他 (model format, context limits, cache rebuild, reset) --- subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 35)); + assert.equal(accountPane.hasAttribute('hidden'), false); + assert.equal(accountPane.querySelector('.settings-account-identity').textContent, 'test@example.com'); + assert.ok(accountPane.querySelectorAll('.settings-account-quota').some((el) => el.textContent === '5 小时 70%')); + assert.ok(accountRequests.some((item) => item.action === 'quota' && item.email === 'next@example.com')); + const googleLogin = accountPane.querySelector('.settings-account-login'); + assert.equal(googleLogin.textContent, '使用 Google 登录'); + googleLogin.dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 20)); + assert.ok(accountRequests.some((item) => item.action === 'loginStart' && item.language === 'zh-CN')); + assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent.includes('请在浏览器中选择 Google 账号'))); + assert.equal(accountPane.querySelector('.settings-account-login-cancel').hasAttribute('hidden'), false); + assert.equal(accountPane.querySelector('a').getAttribute('href'), 'https://accounts.google.com/o/oauth2/v2/auth?state=synthetic'); + accountPane.querySelector('.settings-account-login-cancel').dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 20)); + assert.ok(accountRequests.some((item) => item.action === 'loginCancel' && item.id === 'browser-login')); + assert.equal(accountPane.querySelector('.settings-account-login-cancel').hasAttribute('hidden'), true); + assert.equal(googleLogin.hasAttribute('disabled'), false); + googleLogin.dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 20)); + assert.ok(accountPane.querySelectorAll('.settings-account-identity').some((el) => el.textContent === 'browser@example.com')); + assert.ok(accountRequests.some((item) => item.action === 'quota' && item.email === 'browser@example.com')); + assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent === '登录成功,账号已添加。')); + const switchButton = accountPane.querySelector('.settings-account-switch'); + assert.equal(switchButton.textContent, '切换并重启'); + switchButton.dispatchEvent({ type: 'click', stopPropagation() {} }); + assert.equal(switchButton.textContent, '确认切换'); + assert.equal(accountRequests.some((item) => item.action === 'switch'), false); + switchButton.dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 20)); + assert.ok(accountRequests.some((item) => item.action === 'switch' && item.email === 'next@example.com')); + assert.equal(accountPane.querySelector('.settings-account-identity').textContent, 'test@example.com'); + assert.ok(accountPane.querySelectorAll('.settings-action-desc').some((el) => el.textContent.includes('正在重启 Antigravity'))); + + // --- 其他 (model format, context limits, cache rebuild, reset) --- + subNavBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 15)); assert.equal(otherPane.hasAttribute('hidden'), false); assert.equal(thirdNavBar.hasAttribute('hidden'), true, '3rd-level menu hidden when switching to Other tab'); @@ -2752,8 +2801,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro 'Hover legend updates strictly in-place without DOM node replacement or appendChild' ); - assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), false); - assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), false); + assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), true); + assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), true); // Verify in-place bridge port rotation preserves exact DOM host nodes without remount fetchShouldFail = false; From e520efe84ebf890abdf2a0514c77c65b80f426e5 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Wed, 25 Nov 2026 00:01:46 +0900 Subject: [PATCH 22/30] feat(account): add quota trend chart and multi-account risk gate - Gate multi-account login, import, switch, backup quota polling, and vault controls behind explicit risk consent (accountSwitchRiskAccepted), restricting unaccepted sessions to active-account quota viewing - Add collinear-compressed per-account quota history tracking and a full-bleed 184px AccountQuotaTrendCard supporting cycle, preset, all-time, and custom ranges with cycle-boundary pre-reset filtering and isolated impulse spike sanitization - Unify Account tab controls onto shared SegmentedControl, CustomSelect, CustomDateTimePicker, .ctx-risk-mask, and global status/button primitives while removing bespoke .account-* CSS and balancing card padding --- sidecars/panel/app.js | 1938 ++++++++++++++--- .../panel/backend/account-quota-history.mjs | 477 ++++ sidecars/panel/backend/account-switch.mjs | 10 +- sidecars/panel/backend/api-actions.mjs | 59 +- sidecars/panel/backend/config.mjs | 1 + sidecars/panel/backend/settings-schema.mjs | 2 + sidecars/panel/backend/sidecar-worker.mjs | 2 + sidecars/panel/backend/telemetry-builder.mjs | 15 + sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 1 + .../widgets/AccountQuotaTrendCard.js | 1084 +++++++++ sidecars/panel/src/i18n/en-US.js | 7 + sidecars/panel/src/i18n/zh-CN.js | 7 + sidecars/panel/src/store/telemetryStore.js | 6 + sidecars/panel/src/styles/views-settings.css | 337 +-- .../src/views/settings/SettingsAccountTab.js | 846 ++++--- sidecars/panel/styles.css | 337 +-- sidecars/panel/test/account-switch.test.mjs | 172 +- sidecars/panel/test/backend-harness.mjs | 9 +- sidecars/panel/test/window-bridge.test.mjs | 24 + 20 files changed, 4103 insertions(+), 1235 deletions(-) create mode 100644 sidecars/panel/backend/account-quota-history.mjs create mode 100644 sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index e9a6cde..c903e24 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1883,6 +1883,13 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.account.passwordRateLimited': '密码连续输错次数过多,请稍候再试。', 'settings.account.vaultDecryptFailed': '凭证解密校验失败,请确认密码或重置凭证库。', 'settings.account.invalidActionNonce': '安全校验令牌已过期,请重试。', + 'settings.account.riskNotAccepted': '请先确认并接受非官方能力风险提示。', + 'settings.account.riskBody': 'Google 官方并未授权在 Antigravity App / IDE 中通过第三方插件导入、保存、切换账号凭证或后台查询多账号配额。擅自启用可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', + 'settings.account.trendTitle': '额度变化', + 'settings.account.trendWinAria': '配额窗口切换', + 'settings.account.win5h': '5 小时', + 'settings.account.winWeekly': '每周', + 'settings.account.trendEmpty': '当前时间范围内暂无配额记录。', 'settings.saving': '保存中…', 'settings.saved': '已保存', 'settings.saveFailed': '保存失败', @@ -2862,6 +2869,13 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.account.passwordRateLimited': 'Too many failed attempts. Wait a moment and try again.', 'settings.account.vaultDecryptFailed': 'Vault decryption check failed.', 'settings.account.invalidActionNonce': 'Security token expired. Please try again.', + 'settings.account.riskNotAccepted': 'Acknowledge the unofficial feature risk warning first.', + 'settings.account.riskBody': 'Google has not authorized importing, storing, or switching Antigravity credentials or polling multi-account quotas in Antigravity App / IDE. Enabling multi-account management may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', + 'settings.account.trendTitle': 'Quota Trend', + 'settings.account.trendWinAria': 'Quota window selector', + 'settings.account.win5h': '5 Hours', + 'settings.account.winWeekly': 'Weekly', + 'settings.account.trendEmpty': 'No quota history recorded in the selected time range.', 'settings.subTab.aria': 'Preferences category tabs', 'settings.saving': 'Saving…', 'settings.saved': 'Saved', @@ -9802,6 +9816,9 @@ function isEquivalentTelemetry(prev, next) { ) { return false; } + if (Boolean(pSet?.accountSwitchRiskAccepted) !== Boolean(nSet?.accountSwitchRiskAccepted)) { + 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; @@ -11066,6 +11083,9 @@ async function saveSettingsPatch(patch) { safePatch.accountQuotaRefreshMinutes ); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'accountSwitchRiskAccepted')) { + safePatch.accountSwitchRiskAccepted = Boolean(safePatch.accountSwitchRiskAccepted); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } @@ -20959,6 +20979,1080 @@ const QuotaPoolsWidget = defineComponent({ return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, maskAccountLabel, QuotaPoolsWidget }; })(); +// --- src/components/widgets/AccountQuotaTrendCard.js --- +const { resolveQuotaWindowBounds, buildQuotaWindowSeries, AccountQuotaTrendCard } = (() => { +/** + * @fileoverview Per-account quota remaining-% trajectory chart (`AccountQuotaTrendCard.js`). + * Full-bleed edge-to-edge plot (`x = 1 .. viewW - 1`), X-axis clamped to earliest recorded + * sample when history is shorter than the selected preset, and adaptive integer Y-scale so + * real quota movements never compress into a tiny corner with wasted whitespace. + */ + + +const POOL_COLORS = Object.freeze({ + Gemini: 'var(--accent-primary)', + 'Claude & GPT': 'var(--metric-ok)', + Argon: 'var(--ctx-thinking)', + Carbon: 'var(--metric-warn)', +}); + +const POOL_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; + +let quotaChartUid = 0; + +function floorMinute(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(0, 0); + return d.getTime(); +} + +function ceilMinute(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(59, 999); + return d.getTime(); +} + +function pad2(n) { + return String(n).padStart(2, '0'); +} + +function formatAxisTickTime(ms, spanMs) { + const d = new Date(ms); + const hm = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; + if (spanMs <= 36 * 3600_000) { + return hm; + } + const md = `${d.getMonth() + 1}/${pad2(d.getDate())}`; + if (spanMs <= 7 * 86400_000) { + return `${md} ${pad2(d.getHours())}h`; + } + return md; +} + +function formatHoverTimestamp(ms) { + const d = new Date(ms); + return `${d.getMonth() + 1}/${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; +} + +function buildHorizontalTangentSpline(pts) { + if (pts.length === 0) return ''; + if (pts.length === 1) return `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`; + let d = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`; + for (let i = 0; i < pts.length - 1; i++) { + const p0 = pts[i]; + const p1 = pts[i + 1]; + const dx = (p1.x - p0.x) * 0.38; + d += ` C ${(p0.x + dx).toFixed(1)} ${p0.y.toFixed(1)}, ${(p1.x - dx).toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; + } + return d; +} + +/** + * Computes tight, integer-aligned `[yMin, yMid, yMax]` bounds (`0..100%`) around + * observed `[dataMin, dataMax]` so small-to-moderate quota changes use the full + * vertical canvas instead of leaving 80%+ empty bottom space. + */ +function computeAdaptiveQuotaScale(dataMin, dataMax) { + const lo = Math.max(0, Math.min(100, Number.isFinite(dataMin) ? dataMin : 0)); + const hi = Math.max(lo, Math.min(100, Number.isFinite(dataMax) ? dataMax : 100)); + const rawSpan = hi - lo; + const pad = Math.max(1.5, rawSpan * 0.14); + + let yMax = hi >= 98.5 ? 100 : Math.min(100, Math.ceil((hi + pad) / 10) * 10); + let yMin = lo <= 2 ? 0 : Math.max(0, Math.floor((lo - pad) / 10) * 10); + + if (yMax - yMin < 10) { + if (yMax >= 100) { + yMax = 100; + yMin = 90; + } else if (yMin <= 0) { + yMin = 0; + yMax = 10; + } else { + yMin = Math.max(0, yMax - 10); + } + } + // Ensure `(yMax - yMin)` is even so midpoint tick is always an exact integer + if ((yMax - yMin) % 2 !== 0) { + if (yMin > 0) yMin -= 1; + else if (yMax < 100) yMax += 1; + } + const yMid = Math.round((yMin + yMax) / 2); + return { yMin, yMid, yMax, span: Math.max(1, yMax - yMin) }; +} + +const IMPULSE_GLITCH_MAX_SPAN_MS = 20 * 60_000; +const IMPULSE_GLITCH_MIN_JUMP_PCT = 3; +const IMPULSE_GLITCH_MAX_NEIGHBOR_DIFF_PCT = 1.2; +const CYCLE_RESET_JUMP_MIN_PCT = 3.5; + +function stripIsolatedImpulseSpikes(pts) { + if (pts.length < 3) return pts; + const out = pts.slice(); + let i = 1; + while (i < out.length - 1) { + const prev = out[i - 1]; + const cur = out[i]; + const next = out[i + 1]; + const spanMs = next.ts - prev.ts; + if ( + spanMs >= 0 && + spanMs <= IMPULSE_GLITCH_MAX_SPAN_MS && + cur.val - prev.val >= IMPULSE_GLITCH_MIN_JUMP_PCT && + cur.val - next.val >= IMPULSE_GLITCH_MIN_JUMP_PCT && + Math.abs(next.val - prev.val) <= IMPULSE_GLITCH_MAX_NEIGHBOR_DIFF_PCT + ) { + out.splice(i, 1); + if (i > 1) i -= 1; + continue; + } + i += 1; + } + return out; +} + +function resolveQuotaWindowBounds({ + pools, + selectedRange, + selectedWin, + selectedPool, + customStartMs = 0, + customEndMs = 0, + nowMs = Date.now(), +}) { + if (selectedRange === 'custom') { + return { + startMs: Math.min(customStartMs, customEndMs), + endMs: Math.max(customStartMs, customEndMs), + }; + } + if (selectedRange === 'today') { + const d = new Date(nowMs); + d.setHours(0, 0, 0, 0); + return { startMs: d.getTime(), endMs: nowMs }; + } + if (selectedRange === '24h') return { startMs: nowMs - 24 * 3600_000, endMs: nowMs }; + if (selectedRange === '7d') return { startMs: nowMs - 7 * 86400_000, endMs: nowMs }; + if (selectedRange === '14d') return { startMs: nowMs - 14 * 86400_000, endMs: nowMs }; + if (selectedRange === '30d') return { startMs: nowMs - 30 * 86400_000, endMs: nowMs }; + if (selectedRange === 'all') { + let minTs = Infinity; + for (const p of pools) { + for (const pt of p.points) { + if (pt[0] > 0 && pt[0] < minTs) minTs = pt[0]; + } + } + const safeStart = + Number.isFinite(minTs) && minTs < nowMs - 60_000 ? minTs : nowMs - 5 * 3600_000; + return { startMs: safeStart, endMs: nowMs }; + } + + const targetPools = + selectedPool !== 'all' ? pools.filter((p) => p.poolKey === selectedPool) : pools; + const refPools = targetPools.length ? targetPools : pools; + const isWeekly = selectedWin === 'weekly'; + const winDurationMs = isWeekly ? 7 * 86400_000 : 5 * 3600_000; + + let activeMinResetMs = Infinity; + let anyMinResetMs = Infinity; + for (const p of refPools) { + const rMs = isWeekly ? p.resetWeeklyMs : p.reset5hMs; + const liveVal = isWeekly ? p.liveWk : p.live5h; + if (!(rMs > nowMs)) continue; + if (rMs < anyMinResetMs) anyMinResetMs = rMs; + if (liveVal !== null && liveVal !== undefined && liveVal < 99.95 && rMs < activeMinResetMs) { + activeMinResetMs = rMs; + } + } + const chosenResetMs = Number.isFinite(activeMinResetMs) + ? activeMinResetMs + : Number.isFinite(anyMinResetMs) + ? anyMinResetMs + : 0; + const startMs = chosenResetMs > nowMs ? chosenResetMs - winDurationMs : nowMs - winDurationMs; + return { startMs: Math.min(startMs, nowMs - 60_000), endMs: nowMs }; +} + +/** + * Extracts per-pool trajectories for the requested window, ensuring `'cycle'` mode + * strictly excludes pre-reset points from any previous expired cycle (eliminating + * artificial `84% -> 100%` vertical reset spikes at cycle start). + */ +function buildQuotaWindowSeries({ + visiblePools, + rawBounds, + selectedRange, + selectedWin, + nowMs = Date.now(), +}) { + const isCycleMode = selectedRange === 'cycle'; + const isWeekly = selectedWin === 'weekly'; + const valIdx = isWeekly ? 2 : 1; + const winDurationMs = isWeekly ? 7 * 86400_000 : 5 * 3600_000; + + const staged = []; + let hasStartAnchor = false; + let earliestInWinTs = Infinity; + + for (const p of visiblePools) { + const cleanedAll = []; + for (let i = 0; i < p.points.length; i++) { + const pt = p.points[i]; + const v = pt[valIdx]; + if (v === null || v === undefined || !Number.isFinite(Number(v))) continue; + cleanedAll.push({ + ts: pt[0], + val: Math.max(0, Math.min(100, Number(v))), + }); + } + const sanitized = stripIsolatedImpulseSpikes(cleanedAll); + if (sanitized.length === 0) continue; + + const pResetMs = isWeekly ? p.resetWeeklyMs : p.reset5hMs; + const pLiveVal = isWeekly ? p.liveWk : p.live5h; + const poolCutoffMs = + isCycleMode && pResetMs > nowMs && pLiveVal !== null && pLiveVal < 99.95 + ? Math.max(rawBounds.startMs, pResetMs - winDurationMs) + : rawBounds.startMs; + + let carryBefore = null; + let inWinPts = []; + for (let i = 0; i < sanitized.length; i++) { + const sp = sanitized[i]; + if (sp.ts <= poolCutoffMs) { + carryBefore = sp; + } else if (sp.ts <= rawBounds.endMs) { + inWinPts.push(sp); + } + } + + // In `'cycle'` mode, `< 99.95%` observations at or before `poolCutoffMs` belong + // to the previous expired cycle and must never carry forward into the new cycle. + if (isCycleMode && carryBefore && carryBefore.val < 99.95) { + carryBefore = null; + } + + let hadResetInWindow = false; + if (isCycleMode && inWinPts.length >= 2) { + let lastResetIdx = 0; + for (let k = 1; k < inWinPts.length; k++) { + const prev = inWinPts[k - 1].val; + const cur = inWinPts[k].val; + if (cur - prev >= CYCLE_RESET_JUMP_MIN_PCT || (cur >= 99.5 && prev <= 98.5)) { + lastResetIdx = k; + } + } + if (lastResetIdx > 0) { + inWinPts = inWinPts.slice(lastResetIdx); + carryBefore = null; + hadResetInWindow = true; + } + } + + const isMidWindowReset = hadResetInWindow && inWinPts[0].ts - poolCutoffMs > 5 * 60_000; + const anchorsCycleOrigin = + isCycleMode && + !isMidWindowReset && + !carryBefore && + inWinPts.length > 0 && + inWinPts[0].ts - poolCutoffMs <= 3 * 60_000; + + if (carryBefore || (anchorsCycleOrigin && poolCutoffMs <= rawBounds.startMs + 5000)) { + hasStartAnchor = true; + } + if (inWinPts.length > 0 && inWinPts[0].ts < earliestInWinTs) { + earliestInWinTs = inWinPts[0].ts; + } + + staged.push({ + pool: p, + poolCutoffMs, + carryBefore, + inWinPts, + isMidWindowReset, + anchorsCycleOrigin, + }); + } + + let plottedStartMs = rawBounds.startMs; + if ( + !hasStartAnchor && + selectedRange !== 'custom' && + Number.isFinite(earliestInWinTs) && + earliestInWinTs > rawBounds.startMs + ) { + plottedStartMs = + rawBounds.endMs - earliestInWinTs >= 60_000 + ? earliestInWinTs + : Math.max(rawBounds.startMs, rawBounds.endMs - 5 * 60_000); + } + const plottedEndMs = Math.max(plottedStartMs + 60_000, rawBounds.endMs); + + const rawBuilt = []; + let dataMin = Infinity; + let dataMax = -Infinity; + + for (const item of staged) { + const { pool, poolCutoffMs, carryBefore, inWinPts, isMidWindowReset, anchorsCycleOrigin } = item; + const seriesPts = []; + const anchorStartTs = Math.max(plottedStartMs, poolCutoffMs); + + if (carryBefore) { + seriesPts.push({ ts: anchorStartTs, val: carryBefore.val }); + } else if (anchorsCycleOrigin) { + const originVal = Math.max(100, inWinPts[0].val); + if (inWinPts[0].ts > anchorStartTs) { + seriesPts.push({ ts: anchorStartTs, val: Math.min(100, originVal) }); + } + } else if ( + !isMidWindowReset && + inWinPts.length > 0 && + inWinPts[0].ts > plottedStartMs && + (inWinPts.length === 1 || inWinPts[0].val >= 99.95) + ) { + seriesPts.push({ ts: plottedStartMs, val: inWinPts[0].val }); + } + + for (let i = 0; i < inWinPts.length; i++) { + const vp = inWinPts[i]; + if (vp.ts >= plottedStartMs) { + seriesPts.push(vp); + } + } + + if (seriesPts.length > 0 && plottedEndMs <= nowMs + 60_000) { + const tail = seriesPts[seriesPts.length - 1]; + const tailEnd = Math.min(plottedEndMs, nowMs); + if (tailEnd > tail.ts + 1000) { + seriesPts.push({ ts: tailEnd, val: tail.val }); + } + } + if (seriesPts.length === 0) continue; + + for (let i = 0; i < seriesPts.length; i++) { + const v = seriesPts[i].val; + if (v < dataMin) dataMin = v; + if (v > dataMax) dataMax = v; + } + rawBuilt.push({ + poolKey: pool.poolKey, + label: pool.label, + color: POOL_COLORS[pool.poolKey] || 'var(--accent-primary)', + rawPoints: seriesPts, + latestVal: seriesPts[seriesPts.length - 1].val, + }); + } + + return { + plottedStartMs, + plottedEndMs, + rawBuilt, + yScale: rawBuilt.length > 0 ? computeAdaptiveQuotaScale(dataMin, dataMax) : null, + }; +} + +function getTimeRangeOptions() { + return [ + { value: 'cycle', label: t('cons.rangeCycle') }, + { value: 'today', label: t('cons.rangeToday') }, + { value: '24h', label: t('cons.range24h') }, + { value: '7d', label: t('cons.range7d') }, + { value: '14d', label: t('cons.range14d') }, + { value: '30d', label: t('cons.range30d') }, + { value: 'all', label: t('cons.rangeAll') }, + { value: 'custom', label: t('cons.rangeCustom') }, + ]; +} + +function getQuotaWindowOptions() { + return [ + { value: '5h', label: t('settings.account.win5h') }, + { value: 'weekly', label: t('settings.account.winWeekly') }, + ]; +} + +const AccountQuotaTrendCard = defineComponent({ + name: 'AccountQuotaTrendCard', + setup({ onCleanup }) { + const VIEW_H = 184; + const TOP_Y = 18; + const BOTTOM_Y = 166; + const SPAN_Y = BOTTOM_Y - TOP_Y; + const LEFT_X = 1; + const RIGHT_PAD = 1; + + let viewW = 460; + let selectedRange = 'cycle'; + let selectedWin = '5h'; + let selectedPool = 'all'; + let selectedAccountEmail = ''; + + const initNow = Date.now(); + let customStartMs = floorMinute(initNow - 24 * 3600_000); + let customEndMs = ceilMinute(initNow); + let draftStartMs = customStartMs; + let draftEndMs = customEndMs; + + let latestState = { + activeEmail: '', + activePools: [], + riskAccepted: false, + accounts: [], + savedQuotas: new Map(), + quotaHistory: {}, + }; + + let plottedSeries = []; + let plottedStartMs = 0; + let plottedEndMs = 0; + let plottedYScale = { yMin: 0, yMid: 50, yMax: 100, span: 100 }; + + const cardTitleText = h('span', { text: t('settings.account.trendTitle') }); + const spanBadgeEl = h('span', { className: 'cons-badge text-mono', text: '' }); + + const accountSelect = CustomSelect({ + className: 'cons-cycle-pool-select account-trend-email-select', + modelValue: '', + options: [], + onUpdateModelValue: (val) => { + selectedAccountEmail = String(val || '').trim().toLowerCase(); + renderChart(); + }, + }); + patchAttr(accountSelect.el, 'hidden', true); + + const poolSelect = CustomSelect({ + className: 'cons-cycle-pool-select', + modelValue: 'all', + options: [{ value: 'all', label: t('cons.cyclePoolAll') }], + onUpdateModelValue: (val) => { + selectedPool = val || 'all'; + renderChart(); + }, + }); + + const winSwitch = SegmentedControl({ + ariaLabel: t('settings.account.trendWinAria'), + modelValue: selectedWin, + options: getQuotaWindowOptions(), + onUpdateModelValue: (val) => { + selectedWin = val === 'weekly' ? 'weekly' : '5h'; + winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); + renderChart(); + }, + }); + + const rangeSwitch = SegmentedControl({ + ariaLabel: t('cons.rangeAria'), + modelValue: selectedRange, + options: getTimeRangeOptions(), + onUpdateModelValue: (nextRange) => { + selectedRange = nextRange || 'cycle'; + if (selectedRange === 'custom') { + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + } + rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); + renderChart(); + }, + }); + + const startPicker = CustomDateTimePicker({ + modelValue: draftStartMs, + onUpdateModelValue: (ms) => { + draftStartMs = ms; + startPicker.setValue(ms); + }, + }); + const endPicker = CustomDateTimePicker({ + modelValue: draftEndMs, + onUpdateModelValue: (ms) => { + draftEndMs = ms; + endPicker.setValue(ms); + }, + }); + const applyCustomLabel = h('span', { text: t('cons.applyFilter') }); + const applyCustomBtn = h( + 'button', + { + type: 'button', + className: 'btn-primary', + onClick: () => { + const s = Number(draftStartMs || 0); + const e = Number(draftEndMs || 0); + const lo = floorMinute(s > 0 && e > 0 ? Math.min(s, e) : s); + const hi = ceilMinute(s > 0 && e > 0 ? Math.max(s, e) : e); + if (lo > 0 && hi > lo) { + customStartMs = lo; + customEndMs = hi; + draftStartMs = lo; + draftEndMs = hi; + startPicker.setValue(lo); + endPicker.setValue(hi); + renderChart(); + } + }, + }, + [createSvgIcon('check', { size: 12 }), applyCustomLabel] + ); + const rangeToEl = h('span', { className: 'text-muted', text: t('cons.rangeTo') }); + const customRangeBar = h('div', { className: 'cons-custom-range-bar', hidden: true }, [ + startPicker.el, + rangeToEl, + endPicker.el, + applyCustomBtn, + ]); + + // --- Full-Bleed Edge-to-Edge 184px SVG Stage (reusing TrendAreaChart `.trend-svg`) --- + const uid = ++quotaChartUid; + const gradId = `acct-quota-grad-${uid}`; + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); + svg.setAttribute('class', 'trend-svg'); + svg.setAttribute('aria-hidden', 'true'); + + const defs = document.createElementNS(SVG_NS, 'defs'); + const grad = document.createElementNS(SVG_NS, 'linearGradient'); + grad.setAttribute('id', gradId); + grad.setAttribute('x1', '0'); + grad.setAttribute('y1', '0'); + grad.setAttribute('x2', '0'); + grad.setAttribute('y2', '1'); + const stopTop = document.createElementNS(SVG_NS, 'stop'); + stopTop.setAttribute('offset', '0%'); + stopTop.setAttribute('stop-color', 'var(--accent-primary)'); + stopTop.setAttribute('stop-opacity', '0.24'); + const stopBot = document.createElementNS(SVG_NS, 'stop'); + stopBot.setAttribute('offset', '100%'); + stopBot.setAttribute('stop-color', 'var(--accent-primary)'); + stopBot.setAttribute('stop-opacity', '0.0'); + grad.appendChild(stopTop); + grad.appendChild(stopBot); + defs.appendChild(grad); + svg.appendChild(defs); + + const gridGroup = document.createElementNS(SVG_NS, 'g'); + gridGroup.setAttribute('class', 'trend-grid'); + const gridRowSpecs = [ + { y: TOP_Y, dy: 3, labeled: true }, + { y: Math.round(TOP_Y + SPAN_Y * 0.25), dy: 0, labeled: false }, + { y: Math.round(TOP_Y + SPAN_Y * 0.5), dy: 3, labeled: true }, + { y: Math.round(TOP_Y + SPAN_Y * 0.75), dy: 0, labeled: false }, + { y: BOTTOM_Y, dy: -3, labeled: true }, + ]; + const gridLines = []; + const yLabels = []; + for (const row of gridRowSpecs) { + const line = document.createElementNS(SVG_NS, 'line'); + line.setAttribute('x1', '0'); + line.setAttribute('y1', String(row.y)); + line.setAttribute('x2', String(viewW)); + line.setAttribute('y2', String(row.y)); + gridGroup.appendChild(line); + gridLines.push(line); + + if (row.labeled) { + const lbl = document.createElementNS(SVG_NS, 'text'); + lbl.setAttribute('class', 'sstep-axis-label is-y-inline'); + lbl.setAttribute('x', '3'); + lbl.setAttribute('y', String(row.y + row.dy)); + lbl.setAttribute('text-anchor', 'start'); + yLabels.push(lbl); + } + } + svg.appendChild(gridGroup); + + const seriesGroup = document.createElementNS(SVG_NS, 'g'); + svg.appendChild(seriesGroup); + + // Append inline Y labels above series fills so halo stroke keeps text crisp + const yLabelOverlay = document.createElementNS(SVG_NS, 'g'); + for (const lbl of yLabels) { + yLabelOverlay.appendChild(lbl); + } + svg.appendChild(yLabelOverlay); + + const hoverLine = document.createElementNS(SVG_NS, 'line'); + hoverLine.setAttribute('class', 'trend-hover-line'); + hoverLine.setAttribute('y1', String(TOP_Y)); + hoverLine.setAttribute('y2', String(BOTTOM_Y)); + hoverLine.setAttribute('hidden', ''); + svg.appendChild(hoverLine); + + const hoverDotsGroup = document.createElementNS(SVG_NS, 'g'); + hoverDotsGroup.setAttribute('hidden', ''); + svg.appendChild(hoverDotsGroup); + + const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' }); + const tipWinEl = h('span', { className: 'trend-tip-calls' }); + const tipRowsHost = h('div', { className: 'account-trend-tip-rows' }); + const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ + h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipWinEl]), + tipRowsHost, + ]); + + const xAxisEl = h('div', { className: 'trend-x-axis' }); + const legendRowEl = h('div', { className: 'account-trend-legend' }); + const emptyStateEl = h('div', { className: 'smodel-empty settings-action-desc', hidden: true }); + + const plotStage = h( + 'div', + { + className: 'trend-plot-stage', + onPointermove: handlePointerMove, + onPointerleave: hideHover, + }, + [svg, tooltipEl] + ); + const chartWrap = h('div', { className: 'trend-chart-wrap' }, [ + plotStage, + xAxisEl, + legendRowEl, + ]); + + const rootEl = h('section', { className: 'panel account-quota-trend-panel' }, [ + h('div', { className: 'panel-header account-trend-toprow' }, [ + h('span', { className: 'panel-title cons-overview-title' }, [ + createSvgIcon('pulse', { size: 13 }), + cardTitleText, + accountSelect.el, + poolSelect.el, + ]), + winSwitch.el, + ]), + h('div', { className: 'panel-header cons-overview-head account-trend-subbar' }, [ + spanBadgeEl, + h('div', { className: 'cons-overview-controls' }, [rangeSwitch.el]), + ]), + customRangeBar, + chartWrap, + emptyStateEl, + ]); + + function valueToSvgY(val) { + const clamped = Math.max(plottedYScale.yMin, Math.min(plottedYScale.yMax, val)); + return BOTTOM_Y - ((clamped - plottedYScale.yMin) / plottedYScale.span) * SPAN_Y; + } + + function hideHover() { + hoverLine.setAttribute('hidden', ''); + hoverDotsGroup.setAttribute('hidden', ''); + patchAttr(tooltipEl, 'hidden', true); + } + + function sampleSeriesValueAt(points, targetMs) { + if (!points.length) return null; + if (targetMs < points[0].ts - 1000) return null; + if (targetMs <= points[0].ts) return points[0].val; + const last = points[points.length - 1]; + if (targetMs > last.ts + 60_000) return null; + if (targetMs >= last.ts) return last.val; + let lo = 0; + let hi = points.length - 1; + while (lo + 1 < hi) { + const mid = (lo + hi) >> 1; + if (points[mid].ts <= targetMs) lo = mid; + else hi = mid; + } + const a = points[lo]; + const b = points[hi]; + const span = b.ts - a.ts; + if (span <= 0) return b.val; + return a.val + (b.val - a.val) * ((targetMs - a.ts) / span); + } + + function handlePointerMove(ev) { + if (!plottedSeries.length || !(plottedEndMs > plottedStartMs)) { + hideHover(); + return; + } + const rect = svg.getBoundingClientRect?.(); + const widthPx = Number(rect?.width || viewW); + if (!(widthPx > 0)) return; + const offsetX = Number(ev.clientX || 0) - Number(rect?.left || 0); + const svgX = (offsetX / widthPx) * viewW; + const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); + const u = Math.max(0, Math.min(1, (svgX - LEFT_X) / plotW)); + const clampedX = LEFT_X + u * plotW; + const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs)); + + hoverLine.setAttribute('x1', clampedX.toFixed(1)); + hoverLine.setAttribute('x2', clampedX.toFixed(1)); + + while (hoverDotsGroup.firstChild) hoverDotsGroup.removeChild(hoverDotsGroup.firstChild); + const tipItems = []; + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + const val = sampleSeriesValueAt(s.rawPoints, targetMs); + if (val === null) continue; + const y = valueToSvgY(val); + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', clampedX.toFixed(1)); + dot.setAttribute('cy', y.toFixed(1)); + dot.setAttribute('r', '3.2'); + dot.setAttribute('fill', 'var(--surface-panel)'); + dot.setAttribute('stroke', s.color); + dot.setAttribute('stroke-width', '1.8'); + hoverDotsGroup.appendChild(dot); + tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val }); + } + if (tipItems.length === 0) { + hideHover(); + return; + } + hoverLine.removeAttribute('hidden'); + hoverDotsGroup.removeAttribute('hidden'); + + patchText(tipTimeEl, formatHoverTimestamp(targetMs)); + patchText(tipWinEl, t(selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h')); + patchKeyedList(tipRowsHost, tipItems, { + keyFn: (it) => it.key, + sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`, + createRow: () => { + const sw = h('span', { className: 'dot-swatch' }); + const nm = h('span', { className: 'account-trend-tip-name' }); + const vl = h('strong', { className: 'text-mono' }); + const row = h('div', { className: 'account-trend-tip-row' }, [ + h('span', { className: 'legend-left' }, [sw, nm]), + vl, + ]); + return { el: row, refs: { sw, nm, vl } }; + }, + updateRow: (r, it) => { + r.sw.style.background = it.color; + patchText(r.nm, it.label); + patchText(r.vl, `${+it.val.toFixed(1)}%`); + }, + }); + + const pctX = (clampedX / viewW) * 100; + const shift = pctX < 24 ? '0%' : pctX > 76 ? '-100%' : '-50%'; + patchStyleVar(tooltipEl, '--tip-x', `${pctX.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-shift', shift); + patchAttr(tooltipEl, 'hidden', false); + } + + function resolveTargetAccountEmail() { + const { activeEmail, riskAccepted, accounts } = latestState; + if (!riskAccepted) { + return activeEmail || ''; + } + const candidates = []; + if (activeEmail) candidates.push(activeEmail); + for (const addr of accounts) { + if (addr && !candidates.includes(addr)) candidates.push(addr); + } + if (selectedAccountEmail && candidates.includes(selectedAccountEmail)) { + return selectedAccountEmail; + } + selectedAccountEmail = candidates[0] || ''; + return selectedAccountEmail; + } + + function buildMergedPoolsForEmail(email, nowMs) { + const histPools = latestState.quotaHistory?.[email]?.pools || {}; + const livePools = + email && email === latestState.activeEmail + ? latestState.activePools || [] + : latestState.savedQuotas.get(email)?.pools || []; + + const merged = new Map(); + for (const [pk, hEntry] of Object.entries(histPools)) { + merged.set(pk, { + poolKey: pk, + label: hEntry.label || pk, + reset5hMs: Number(hEntry.reset5hMs) || 0, + resetWeeklyMs: Number(hEntry.resetWeeklyMs) || 0, + points: Array.isArray(hEntry.points) ? hEntry.points.slice() : [], + live5h: null, + liveWk: null, + }); + } + + for (const lp of livePools) { + const pk = String(lp?.poolKey || lp?.family || lp?.poolLabel || '').trim(); + if (!pk || pk === 'Unknown') continue; + let item = merged.get(pk); + if (!item) { + item = { + poolKey: pk, + label: String(lp?.poolLabel || pk), + reset5hMs: 0, + resetWeeklyMs: 0, + points: [], + live5h: null, + liveWk: null, + }; + merged.set(pk, item); + } + if (lp?.poolLabel) item.label = String(lp.poolLabel); + const r5Ms = Date.parse(lp?.resetTime || ''); + const rWMs = Date.parse(lp?.weeklyResetTime || ''); + if (Number.isFinite(r5Ms) && r5Ms > 0) item.reset5hMs = r5Ms; + if (Number.isFinite(rWMs) && rWMs > 0) item.resetWeeklyMs = rWMs; + if (Number.isFinite(lp?.remainingPct)) item.live5h = +Number(lp.remainingPct).toFixed(1); + if (Number.isFinite(lp?.weeklyRemainingPct)) { + item.liveWk = +Number(lp.weeklyRemainingPct).toFixed(1); + } + if (item.live5h !== null || item.liveWk !== null) { + const last = item.points[item.points.length - 1]; + if (!last || nowMs >= last[0]) { + item.points.push([ + nowMs, + item.live5h ?? (last ? last[1] : null), + item.liveWk ?? (last ? last[2] : null), + ]); + } + } + } + + return Array.from(merged.values()).sort( + (a, b) => + (POOL_ORDER.indexOf(a.poolKey) === -1 ? 99 : POOL_ORDER.indexOf(a.poolKey)) - + (POOL_ORDER.indexOf(b.poolKey) === -1 ? 99 : POOL_ORDER.indexOf(b.poolKey)) + ); + } + + function renderChart() { + hideHover(); + const nowMs = Date.now(); + void getEffectiveLocale(); + + patchText(cardTitleText, t('settings.account.trendTitle')); + patchText(rangeToEl, t('cons.rangeTo')); + patchText(applyCustomLabel, t('cons.applyFilter')); + winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); + rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); + patchAttr(customRangeBar, 'hidden', selectedRange !== 'custom'); + + const targetEmail = resolveTargetAccountEmail(); + const candidateEmails = []; + if (latestState.activeEmail) candidateEmails.push(latestState.activeEmail); + if (latestState.riskAccepted) { + for (const addr of latestState.accounts) { + if (addr && !candidateEmails.includes(addr)) candidateEmails.push(addr); + } + } + const showAccountPicker = latestState.riskAccepted && candidateEmails.length > 1; + patchAttr(accountSelect.el, 'hidden', !showAccountPicker); + if (showAccountPicker) { + accountSelect.setProps({ + modelValue: targetEmail, + options: candidateEmails.map((addr) => ({ + value: addr, + label: addr.split('@')[0] || addr, + title: addr, + })), + }); + } + + const mergedPools = targetEmail ? buildMergedPoolsForEmail(targetEmail, nowMs) : []; + if (selectedPool !== 'all' && !mergedPools.some((p) => p.poolKey === selectedPool)) { + selectedPool = 'all'; + } + const poolOpts = [ + { + value: 'all', + label: t('cons.cyclePoolAll'), + }, + ...mergedPools.map((p) => ({ + value: p.poolKey, + label: p.poolKey === 'Claude & GPT' ? 'Claude/GPT' : p.label, + title: p.label, + })), + ]; + poolSelect.setProps({ modelValue: selectedPool, options: poolOpts }); + patchAttr(poolSelect.el, 'hidden', mergedPools.length <= 1); + + const rawBounds = resolveQuotaWindowBounds({ + pools: mergedPools, + selectedRange, + selectedWin, + selectedPool, + customStartMs, + customEndMs, + nowMs, + }); + const visiblePools = + selectedPool === 'all' + ? mergedPools + : mergedPools.filter((p) => p.poolKey === selectedPool); + + const built = buildQuotaWindowSeries({ + visiblePools, + rawBounds, + selectedRange, + selectedWin, + nowMs, + }); + plottedStartMs = built.plottedStartMs; + plottedEndMs = built.plottedEndMs; + const spanMs = plottedEndMs - plottedStartMs; + patchText(spanBadgeEl, formatDateSpanBadge(plottedStartMs, plottedEndMs)); + + const rawBuilt = built.rawBuilt; + const hasPlot = rawBuilt.length > 0; + patchAttr(chartWrap, 'hidden', !hasPlot); + patchAttr(emptyStateEl, 'hidden', hasPlot); + if (!hasPlot) { + plottedSeries = []; + patchText(emptyStateEl, t('settings.account.trendEmpty')); + return; + } + + plottedYScale = built.yScale; + yLabels[0].textContent = `${plottedYScale.yMax}%`; + yLabels[1].textContent = `${plottedYScale.yMid}%`; + yLabels[2].textContent = `${plottedYScale.yMin}%`; + + const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); + svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); + for (const gl of gridLines) { + gl.setAttribute('x2', String(viewW)); + } + + plottedSeries = rawBuilt.map((rb) => ({ + ...rb, + svgPts: rb.rawPoints.map((sp) => { + const u = Math.max(0, Math.min(1, (sp.ts - plottedStartMs) / spanMs)); + return { + x: LEFT_X + u * plotW, + y: valueToSvgY(sp.val), + val: sp.val, + ts: sp.ts, + }; + }), + })); + + while (seriesGroup.firstChild) seriesGroup.removeChild(seriesGroup.firstChild); + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + const lineD = buildHorizontalTangentSpline(s.svgPts); + if (s.svgPts.length >= 2) { + const first = s.svgPts[0]; + const last = s.svgPts[s.svgPts.length - 1]; + const areaEl = document.createElementNS(SVG_NS, 'path'); + areaEl.setAttribute( + 'd', + `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z` + ); + if (plottedSeries.length === 1) { + stopTop.setAttribute('stop-color', s.color); + stopBot.setAttribute('stop-color', s.color); + areaEl.setAttribute('fill', `url(#${gradId})`); + } else { + areaEl.setAttribute('class', 'sstep-multi-area'); + areaEl.style.setProperty('--sstep-series-color', s.color); + } + seriesGroup.appendChild(areaEl); + } + const pathEl = document.createElementNS(SVG_NS, 'path'); + pathEl.setAttribute('d', lineD); + pathEl.setAttribute('fill', 'none'); + pathEl.setAttribute('stroke', s.color); + pathEl.setAttribute('stroke-width', '1.9'); + pathEl.setAttribute('stroke-linecap', 'round'); + seriesGroup.appendChild(pathEl); + + const endPt = s.svgPts[s.svgPts.length - 1]; + const endDot = document.createElementNS(SVG_NS, 'circle'); + endDot.setAttribute('cx', endPt.x.toFixed(1)); + endDot.setAttribute('cy', endPt.y.toFixed(1)); + endDot.setAttribute('r', '2.7'); + endDot.setAttribute('fill', s.color); + seriesGroup.appendChild(endDot); + } + + // Edge-to-edge X-axis ticks (`0% .. 100%`) + const tickCount = 5; + const ticks = []; + for (let k = 0; k < tickCount; k++) { + const ratio = k / (tickCount - 1); + const tickMs = Math.round(plottedStartMs + ratio * spanMs); + const leftPct = ratio * 100; + ticks.push({ + idx: k, + leftPct, + label: formatAxisTickTime(tickMs, spanMs), + edge: k === 0 ? 'start' : k === tickCount - 1 ? 'end' : '', + }); + } + patchKeyedList(xAxisEl, ticks, { + keyFn: (tk) => tk.idx, + sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}`, + createRow: () => { + const el = h('span', { className: 'trend-x-tick text-mono' }); + return { el, refs: { el } }; + }, + updateRow: (r, tk) => { + patchText(r.el, tk.label); + patchStyleVar(r.el, '--tick-x', `${tk.leftPct.toFixed(2)}%`); + patchClasses(r.el, { + 'is-start': tk.edge === 'start', + 'is-end': tk.edge === 'end', + }); + }, + }); + + patchKeyedList(legendRowEl, plottedSeries, { + keyFn: (s) => s.poolKey, + sigFn: (s) => `${s.label}:${s.latestVal.toFixed(1)}:${s.color}`, + createRow: () => { + const sw = h('span', { className: 'dot-swatch' }); + const nm = h('span', { className: 'account-trend-leg-name' }); + const vl = h('strong', { className: 'text-mono' }); + const el = h('span', { className: 'account-trend-leg-item' }, [sw, nm, vl]); + return { el, refs: { sw, nm, vl } }; + }, + updateRow: (r, s) => { + r.sw.style.background = s.color; + patchText(r.nm, s.label); + patchText(r.vl, `${+s.latestVal.toFixed(1)}%`); + }, + }); + } + + let resizeObs = null; + if (typeof ResizeObserver === 'function') { + resizeObs = new ResizeObserver((entries) => { + const w = Math.floor(Number(entries?.[0]?.contentRect?.width || 0)); + if (w >= 180 && Math.abs(w - viewW) >= 2) { + viewW = w; + renderChart(); + } + }); + resizeObs.observe(plotStage); + } + + onCleanup(() => { + resizeObs?.disconnect(); + accountSelect.destroy(); + poolSelect.destroy(); + winSwitch.destroy(); + rangeSwitch.destroy(); + startPicker.destroy(); + endPicker.destroy(); + }); + + function update(nextState) { + latestState = { ...latestState, ...nextState }; + renderChart(); + } + + renderChart(); + return { + el: rootEl, + refs: { update, refreshLabels: renderChart }, + }; + }, +}); +return { resolveQuotaWindowBounds, buildQuotaWindowSeries, AccountQuotaTrendCard }; +})(); + // --- src/components/widgets/LiveActivityWidget.js --- const { buildFallbackRunningConversations, LiveActivityWidget } = (() => { /** @@ -29339,7 +30433,11 @@ return { SettingsStructureTab }; // --- src/views/settings/SettingsAccountTab.js --- const { SettingsAccountTab } = (() => { -/** @fileoverview Unified multi-account switcher, passphrase vault UI, and per-pool quota cards. */ +/** + * @fileoverview Multi-account switcher, quota trajectory chart, risk gate, and passphrase vault UI. + * Reuses `SegmentedControl`, `CustomSelect`, `AccountQuotaTrendCard`, `.ctx-risk-mask`, + * `.settings-bridge-notice`, `.status-tag`, `.btn-ghost-sm`, `.btn-danger-confirm`, and `.quota-pool-row`. + */ const key = (name) => `settings.account.${name}`; @@ -29355,7 +30453,7 @@ const errors = new Set([ 'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed', 'loginStartFailed', 'loginExchangeFailed', 'loginExpired', 'loginDenied', 'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordMismatch', - 'passwordRateLimited', 'vaultDecryptFailed', 'invalidActionNonce', + 'passwordRateLimited', 'vaultDecryptFailed', 'invalidActionNonce', 'riskNotAccepted', ]); const okToastKeys = new Set([ @@ -29376,6 +30474,13 @@ function getAccountRefreshOptions() { ]; } +function getPwdModeOptions() { + return [ + { value: 'change', label: t(key('pwdTabChange')) }, + { value: 'disable', label: t(key('pwdTabDisable')) }, + ]; +} + function formatValidCountdown(isoTime) { if (!isoTime) return ''; const ms = Date.parse(isoTime); @@ -29405,8 +30510,9 @@ function renderQuotaRows(container, quotaPools) { ); patchKeyedList(container, pools, { keyFn: (pool) => pool.poolKey || pool.poolLabel, - sigFn: (pool) => + sigFn: (pool, idx) => JSON.stringify([ + idx > 0, locale, pool.poolLabel, pool.remainingPct, @@ -29415,32 +30521,39 @@ function renderQuotaRows(container, quotaPools) { pool.weeklyResetTime, ]), createRow: () => { - const poolTitle = h('div', { className: 'account-pool-name' }); + const poolTitle = h('div', { className: 'account-pool-label' }); - const label5h = h('span', { className: 'settings-account-quota text-mono' }); - const reset5h = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const label5h = h('span', { className: 'quota-win-title settings-account-quota text-mono' }); + const reset5h = h('span', { className: 'panel-meta quota-win-meta text-mono', hidden: true }); const fill5h = h('div', { className: 'progress-fill' }); const meter5h = h('div', { className: 'account-meter-col' }, [ - h('div', { className: 'account-meter-head' }, [label5h, reset5h]), - h('div', { className: 'progress-track account-progress-track' }, [fill5h]), + h('div', { className: 'panel-header quota-win-head' }, [ + h('span', { className: 'quota-win-left' }, [label5h]), + reset5h, + ]), + h('div', { className: 'progress-track' }, [fill5h]), ]); - const labelWk = h('span', { className: 'settings-account-quota text-mono' }); - const resetWk = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const labelWk = h('span', { className: 'quota-win-title settings-account-quota text-mono' }); + const resetWk = h('span', { className: 'panel-meta quota-win-meta text-mono', hidden: true }); const fillWk = h('div', { className: 'progress-fill' }); const meterWk = h('div', { className: 'account-meter-col' }, [ - h('div', { className: 'account-meter-head' }, [labelWk, resetWk]), - h('div', { className: 'progress-track account-progress-track' }, [fillWk]), + h('div', { className: 'panel-header quota-win-head' }, [ + h('span', { className: 'quota-win-left' }, [labelWk]), + resetWk, + ]), + h('div', { className: 'progress-track' }, [fillWk]), ]); const gridEl = h('div', { className: 'account-pool-meters' }, [meter5h, meterWk]); - const el = h('div', { className: 'account-pool-group' }, [poolTitle, gridEl]); + const el = h('div', { className: 'quota-pool-row' }, [poolTitle, gridEl]); return { el, - refs: { poolTitle, gridEl, meter5h, label5h, reset5h, fill5h, meterWk, labelWk, resetWk, fillWk }, + refs: { el, poolTitle, gridEl, meter5h, label5h, reset5h, fill5h, meterWk, labelWk, resetWk, fillWk }, }; }, - updateRow: (refs, pool) => { + updateRow: (refs, pool, idx) => { + patchClasses(refs.el, { 'has-divider': idx > 0 }); patchText(refs.poolTitle, pool.poolLabel || pool.poolKey); const has5h = Number.isFinite(pool.remainingPct); const hasWk = Number.isFinite(pool.weeklyRemainingPct); @@ -29485,18 +30598,22 @@ function isValidVaultPassphrase(raw) { const SettingsAccountTab = defineComponent({ name: 'SettingsAccountTab', setup({ props, onCleanup }) { + const initialSettings = telemetryStore.getState().telemetry?.settings; let account = null; let quotas = null; let refreshMinutes = normalizeAccountQuotaRefreshMinutes( - telemetryStore.getState().telemetry?.settings?.accountQuotaRefreshMinutes ?? - DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES + initialSettings?.accountQuotaRefreshMinutes ?? DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES ); + let draftRiskAccepted = Boolean(initialSettings?.accountSwitchRiskAccepted); + let acceptingRisk = false; + let riskLockedFromServer = warmAccountCache ? Boolean(warmAccountCache.riskLocked) : true; let accounts = warmAccountCache ? [...warmAccountCache.accounts] : []; let selectedEmail = warmAccountCache ? warmAccountCache.selectedEmail : ''; let supported = warmAccountCache ? warmAccountCache.supported : null; let vaultSecurity = warmAccountCache?.vaultSecurity ? { ...warmAccountCache.vaultSecurity } : { enabled: false, unlocked: true }; + let quotaHistory = warmAccountCache?.quotaHistory ? { ...warmAccountCache.quotaHistory } : {}; let actionNonce = warmAccountCache?.actionNonce || ''; let operation = ''; let status = ''; @@ -29527,10 +30644,12 @@ const SettingsAccountTab = defineComponent({ if (supported !== true) return; warmAccountCache = { supported, + riskLocked: riskLockedFromServer, accounts: [...accounts], selectedEmail, savedQuotasEntries: [...savedQuotas.entries()], vaultSecurity: { ...vaultSecurity }, + quotaHistory: { ...quotaHistory }, actionNonce, }; } @@ -29581,12 +30700,19 @@ const SettingsAccountTab = defineComponent({ pwdConfirmInput.value = ''; } + // --- Section 1: Active Account Card Host --- + const activeCardHost = h('div', { className: 'account-cards-stack' }); + + // --- Section 2: Quota Trend Line Chart Card --- + const quotaTrendCard = AccountQuotaTrendCard(); + + // --- Section 3: Multi-Account Toolbar, Drawers, Backup Cards & Risk Gate --- const loginBtnLabel = h('span'); const loginButton = h( 'button', { type: 'button', - className: 'btn-primary settings-account-login account-toolbar-btn', + className: 'btn-primary settings-account-login', onClick: () => { clearConfirmTarget(false); void request('loginStart', { language: getEffectiveLocale() }); @@ -29596,7 +30722,7 @@ const SettingsAccountTab = defineComponent({ ); const cancelLogin = h('button', { type: 'button', - className: 'btn-secondary settings-account-login-cancel account-toolbar-btn', + className: 'btn-secondary settings-account-login-cancel', hidden: true, onClick: () => request('loginCancel', { id: loginSession?.id }), }); @@ -29605,7 +30731,7 @@ const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'btn-secondary account-toolbar-btn', + className: 'btn-secondary', onClick: () => { clearConfirmTarget(false); importOpen = !importOpen; @@ -29626,13 +30752,14 @@ const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'btn-secondary account-toolbar-btn settings-account-pwd-toggle', + className: 'btn-secondary settings-account-pwd-toggle', onClick: () => { clearConfirmTarget(false); pwdDrawerOpen = !pwdDrawerOpen; if (pwdDrawerOpen) { importOpen = false; pwdManageMode = 'change'; + pwdModeSegment.setProps({ modelValue: 'change', options: getPwdModeOptions() }); } clearPasswordInputs(); render(); @@ -29649,7 +30776,7 @@ const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'btn-secondary account-toolbar-btn settings-account-lock-now', + className: 'btn-secondary settings-account-lock-now', hidden: true, onClick: () => { clearConfirmTarget(false); @@ -29691,17 +30818,17 @@ const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'icon-btn account-reload-btn', + className: 'icon-btn', onClick: () => request('list'), }, [createSvgIcon('refresh', { size: 13 })] ); - // --- Locked Vault Unlock Strip --- - const unlockHintLabel = h('span'); + // Locked Vault Notice (reusing `.settings-bridge-notice`) + const unlockHintLabel = h('span', { className: 'settings-bridge-title' }); const forgotToggleBtn = h('button', { type: 'button', - className: 'account-link-btn settings-account-forgot-btn', + className: 'btn-ghost-sm settings-account-forgot-btn', onClick: () => { forgotResetOpen = !forgotResetOpen; clearConfirmTarget(false); @@ -29717,7 +30844,7 @@ const SettingsAccountTab = defineComponent({ }); const unlockSubmitBtn = h('button', { type: 'submit', - className: 'btn-primary account-toolbar-btn settings-account-unlock-submit', + className: 'btn-primary settings-account-unlock-submit', }); const unlockForm = h( 'form', @@ -29728,55 +30855,47 @@ const SettingsAccountTab = defineComponent({ }, [unlockInput, unlockSubmitBtn] ); - const resetHintEl = h('span', { className: 'settings-action-desc' }); + const resetHintEl = h('p', { className: 'settings-bridge-desc', hidden: true }); const resetVaultBtn = h('button', { type: 'button', - className: 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-reset-vault', + className: 'btn-secondary btn-danger-confirm settings-account-reset-vault', + hidden: true, onClick: () => { armOrRunConfirm('resetVault', 'vault', () => { void request('resetVault', { confirmReset: 'RESET' }); }); }, }); - const resetRow = h('div', { className: 'account-reset-row', hidden: true }, [ - resetHintEl, - resetVaultBtn, - ]); - const unlockBox = h('div', { className: 'account-unlock-box settings-account-unlock-box', hidden: true }, [ - h('div', { className: 'account-unlock-head' }, [ - h('span', { className: 'account-unlock-title' }, [ - createSvgIcon('lock', { size: 13 }), - unlockHintLabel, + const unlockBox = h( + 'div', + { className: 'settings-bridge-notice settings-account-unlock-box', hidden: true }, + [ + h('div', { className: 'settings-bridge-head' }, [ + h('span', { className: 'settings-bridge-head-main' }, [ + createSvgIcon('lock', { size: 13, className: 'settings-bridge-icon' }), + unlockHintLabel, + ]), + forgotToggleBtn, ]), - forgotToggleBtn, - ]), - unlockForm, - resetRow, - ]); + unlockForm, + resetHintEl, + h('div', { className: 'settings-bridge-actions', hidden: true }, [resetVaultBtn]), + ] + ); + const resetActionsWrap = resetVaultBtn.parentElement; - // --- Passphrase Setup / Manage Drawer --- - const pwdTabChangeBtn = h('button', { - type: 'button', - className: 'account-pwd-tab', - onClick: () => { - pwdManageMode = 'change'; + // Passphrase Setup / Manage Drawer (reusing `SegmentedControl`!) + const pwdModeSegment = SegmentedControl({ + ariaLabel: t(key('pwdBtnManage')), + modelValue: pwdManageMode, + options: getPwdModeOptions(), + onUpdateModelValue: (val) => { + pwdManageMode = val === 'disable' ? 'disable' : 'change'; + pwdModeSegment.setProps({ modelValue: pwdManageMode, options: getPwdModeOptions() }); clearPasswordInputs(); render(); }, }); - const pwdTabDisableBtn = h('button', { - type: 'button', - className: 'account-pwd-tab', - onClick: () => { - pwdManageMode = 'disable'; - clearPasswordInputs(); - render(); - }, - }); - const pwdTabsWrap = h('div', { className: 'account-pwd-tabs', hidden: true }, [ - pwdTabChangeBtn, - pwdTabDisableBtn, - ]); const pwdCurrentInput = h('input', { type: 'password', className: 'settings-text-input account-import-input settings-account-pwd-current', @@ -29801,9 +30920,9 @@ const SettingsAccountTab = defineComponent({ }); const pwdSubmitBtn = h('button', { type: 'submit', - className: 'btn-primary account-toolbar-btn settings-account-pwd-submit', + className: 'btn-primary settings-account-pwd-submit', }); - const pwdHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const pwdHint = h('div', { className: 'settings-action-desc' }); const pwdForm = h( 'form', { @@ -29813,7 +30932,7 @@ const SettingsAccountTab = defineComponent({ onSubmit: submitPasswordDrawer, }, [ - pwdTabsWrap, + pwdModeSegment.el, h('div', { className: 'account-import-row' }, [ pwdCurrentInput, pwdNewInput, @@ -29824,7 +30943,7 @@ const SettingsAccountTab = defineComponent({ ] ); - // --- Credential Import Drawer --- + // Credential Import Drawer const credential = h('input', { type: 'password', className: 'settings-text-input account-import-input', @@ -29835,9 +30954,9 @@ const SettingsAccountTab = defineComponent({ }); const save = h('button', { type: 'submit', - className: 'btn-primary account-toolbar-btn', + className: 'btn-primary', }); - const importHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const importHint = h('div', { className: 'settings-action-desc' }); const form = h( 'form', { @@ -29852,26 +30971,27 @@ const SettingsAccountTab = defineComponent({ ] ); - const loginMessage = h('div', { - className: 'settings-action-desc account-flow-msg', + // OAuth Browser Login & Switch Notices (reusing `.settings-bridge-notice`) + const loginMessage = h('p', { + className: 'settings-bridge-desc settings-action-desc', role: 'status', hidden: true, }); const loginLink = h('a', { - className: 'account-flow-link', + className: 'settings-bridge-relaunch-btn', target: '_blank', rel: 'noopener noreferrer', hidden: true, }); - const loginStrip = h('div', { className: 'account-flow-strip', hidden: true }, [ - loginMessage, - loginLink, - ]); - const pending = h('div', { - className: 'settings-action-desc account-flow-strip is-warn', - role: 'status', - hidden: true, - }); + const loginStrip = h( + 'div', + { className: 'settings-bridge-notice is-restart', hidden: true }, + [loginMessage, h('div', { className: 'settings-bridge-actions' }, [loginLink])] + ); + const loginLinkWrap = loginLink.parentElement; + + const pendingDesc = h('p', { className: 'settings-bridge-desc', role: 'status' }); + const pending = h('div', { className: 'settings-bridge-notice', hidden: true }, [pendingDesc]); const toolbarPanel = h('section', { className: 'panel account-toolbar-panel' }, [ h('div', { className: 'account-toolbar-row' }, [ @@ -29895,36 +31015,261 @@ const SettingsAccountTab = defineComponent({ pending, ]); - const cardsHost = h('div', { className: 'account-cards-stack' }); + const backupCardsHost = h('div', { className: 'account-cards-stack' }); const emptyPanel = h('section', { className: 'panel account-empty-panel', hidden: true }, [ h('div', { className: 'settings-action-desc account-empty-text' }), ]); const emptyTextEl = emptyPanel.firstChild; + // Risk Gate Stage (100% shared `.ctx-risk-stage` / `.ctx-risk-mask` with `SettingsOtherTab`) + const riskTitleEl = h('strong', { + className: 'ctx-risk-title', + text: t('settings.oth.ctxRiskTitle'), + }); + const riskBodyEl = h('p', { + className: 'ctx-risk-desc', + text: t(key('riskBody')), + }); + const riskAcceptBtnText = h('span', { text: t('settings.oth.ctxRiskAcceptBtn') }); + const riskAcceptBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary btn-danger-confirm ctx-risk-accept-btn settings-account-risk-accept', + onClick: async () => { + if (acceptingRisk || draftRiskAccepted) return; + acceptingRisk = true; + draftRiskAccepted = true; + render(); + try { + await saveSettingsPatch({ accountSwitchRiskAccepted: true }); + await request('list'); + } catch { + draftRiskAccepted = false; + setTransientStatus('storeFailed', 2800); + } finally { + acceptingRisk = false; + if (!disposed) render(); + } + }, + }, + [createSvgIcon('warning', { size: 12 }), riskAcceptBtnText] + ); + const riskMask = h( + 'div', + { + className: 'ctx-risk-mask settings-account-risk-mask', + role: 'region', + 'aria-label': t('settings.oth.ctxRiskTitle'), + }, + [ + h('div', { className: 'ctx-risk-head' }, [ + createSvgIcon('warning', { size: 14, className: 'ctx-risk-icon' }), + riskTitleEl, + ]), + riskBodyEl, + riskAcceptBtn, + ] + ); + const managedControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ + toolbarPanel, + backupCardsHost, + ]); + const riskStage = h('div', { className: 'ctx-risk-stage' }, [managedControlsBody, riskMask]); + function resolveActiveEmail() { return account?.status === 'signedIn' ? (account.email || '').trim().toLowerCase() : ''; } - function buildUnifiedAccountEntries(activeEmail) { - const entries = []; - if (activeEmail) { - entries.push({ - email: activeEmail, - isActive: true, - isSaved: accounts.includes(activeEmail), - }); - } - for (let i = 0; i < accounts.length; i++) { - const addr = accounts[i]; - if (addr && addr !== activeEmail) { - entries.push({ - email: addr, - isActive: false, - isSaved: true, + function createAccountCardDom(entry) { + const emailEl = h('span', { + className: 'settings-account-identity account-card-email', + text: entry.email, + title: entry.email, + }); + const tierPill = h('span', { className: 'status-tag state-synced', hidden: true }); + const statePill = h('span', { className: 'status-tag', hidden: true }); + + const captureBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('capture'); + }, + }); + const selectBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm', + hidden: true, + onClick: () => { + armOrRunConfirm('switch', entry.email, () => { + const curActive = resolveActiveEmail(); + void request('switch', { + email: entry.email, + ...(curActive ? { activeEmail: curActive } : {}), + }); }); - } + }, + }); + const loadQuotaBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn settings-account-load-quota', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('quota', { email: entry.email, manual: true }); + }, + }, + [createSvgIcon('refresh', { size: 12 })] + ); + const removeBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn slot-remove-btn settings-account-remove', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }, + [createSvgIcon('close', { size: 12 })] + ); + const removeConfirmBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm btn-danger-confirm settings-account-remove-confirm', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }); + + const actionsWrap = h('div', { className: 'account-card-actions' }, [ + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + ]); + const poolsWrap = h('div', { className: 'account-pools-stack' }); + const noteEl = h('div', { className: 'settings-action-desc account-card-note', hidden: true }); + + const cardEl = h('section', { className: 'panel account-card' }, [ + h('div', { className: 'panel-header account-card-head' }, [ + h('div', { className: 'account-card-meta' }, [emailEl, tierPill, statePill]), + actionsWrap, + ]), + poolsWrap, + noteEl, + ]); + return { + el: cardEl, + refs: { + cardEl, + emailEl, + tierPill, + statePill, + actionsWrap, + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + poolsWrap, + noteEl, + }, + }; + } + + function updateAccountCardDom(row, entry, ctx) { + const addr = entry.email; + const active = entry.isActive; + const isSaved = entry.isSaved; + const written = addr === selectedEmail && !active && switchState?.state === 'written'; + const cached = active ? null : savedQuotas.get(addr); + const tierText = active + ? ctx.activeTierBadge + : cached?.tierName || cached?.tierId + ? formatAccountTierBadge({ + tierId: cached.tierId, + tierName: cached.tierName, + tierMultiplier: cached.tierMultiplier, + }) + : ''; + const isSpinning = !active && quotaVisibleLoading.has(addr); + const canSwitch = !active && isSaved && ctx.riskAccepted; + const armedSwitch = confirmTarget?.type === 'switch' && confirmTarget.key === addr; + const armedRemove = confirmTarget?.type === 'remove' && confirmTarget.key === addr; + + patchClasses(row.cardEl, { 'is-active-account': active }); + patchText(row.emailEl, addr); + patchAttr(row.emailEl, 'title', addr); + + patchText(row.tierPill, tierText); + patchAttr(row.tierPill, 'hidden', !tierText); + + patchText(row.statePill, active ? t(key('active')) : written ? t(key('written')) : ''); + patchClasses(row.statePill, { 'state-warn': written && !active }); + patchAttr(row.statePill, 'hidden', !active && !written); + + const showCapture = active && !isSaved && ctx.riskAccepted && supported !== false; + const showRemove = isSaved && ctx.riskAccepted; + const showQuotaRefresh = !active && isSaved && ctx.riskAccepted; + const hasAnyAction = showCapture || canSwitch || showQuotaRefresh || showRemove; + patchAttr(row.actionsWrap, 'hidden', !hasAnyAction); + + patchText(row.captureBtn, t(key('capture'))); + patchAttr(row.captureBtn, 'hidden', !showCapture); + patchAttr(row.captureBtn, 'disabled', !ctx.canWrite); + + patchText(row.selectBtn, t(key(armedSwitch ? 'switchConfirm' : 'switch'))); + patchAttr(row.selectBtn, 'title', t(key('switchHint'))); + patchClasses(row.selectBtn, { + 'settings-account-switch': canSwitch, + 'btn-danger-confirm': armedSwitch, + }); + patchAttr(row.selectBtn, 'hidden', !canSwitch); + patchAttr(row.selectBtn, 'disabled', !ctx.canWrite); + + patchAttr(row.loadQuotaBtn, 'title', t(key(isSpinning ? 'loadingQuota' : 'loadQuota'))); + patchAttr(row.loadQuotaBtn, 'aria-label', t(key('loadQuota'))); + patchClasses(row.loadQuotaBtn, { 'is-spinning': isSpinning }); + patchAttr(row.loadQuotaBtn, 'hidden', !showQuotaRefresh); + patchAttr(row.loadQuotaBtn, 'disabled', !ctx.canWrite || isSpinning); + + patchAttr(row.removeBtn, 'title', t(key('remove'))); + patchAttr(row.removeBtn, 'aria-label', t(key('remove'))); + patchAttr(row.removeBtn, 'hidden', !showRemove || armedRemove); + patchAttr(row.removeBtn, 'disabled', !ctx.canWrite); + + patchText(row.removeConfirmBtn, t(key('removeConfirm'))); + patchAttr(row.removeConfirmBtn, 'hidden', !showRemove || !armedRemove); + patchAttr(row.removeConfirmBtn, 'disabled', !ctx.canWrite); + + const displayedPools = active ? quotas?.pools || [] : cached?.pools || []; + const poolCount = renderQuotaRows(row.poolsWrap, displayedPools); + const quotaError = active ? '' : quotaErrors.get(addr); + + let noteText = ''; + if (quotaError) { + noteText = t(key(quotaError)); + } else if (active && poolCount > 0 && quotas?.meta?.isStale) { + noteText = t(key('quotaStale')); + } else if (active && poolCount === 0) { + noteText = t(key('noQuota')); + } else if (!active && cached && poolCount === 0) { + noteText = t(key('emptyCredentialQuota')); } - return entries; + patchText(row.noteEl, noteText); + patchClasses(row.noteEl, { 'is-error': Boolean(quotaError) }); + patchAttr(row.noteEl, 'hidden', !noteText); } function render() { @@ -29933,8 +31278,13 @@ const SettingsAccountTab = defineComponent({ if (activeEmail && selectedEmail === activeEmail && switchState?.state !== 'starting') { selectedEmail = ''; } + const riskAccepted = Boolean(draftRiskAccepted); + if (!riskAccepted) { + refreshIntervalSelect.close?.(); + } const vaultLocked = isVaultLocked(); const canOperateVault = + riskAccepted && supported === true && !operation && status !== 'restarting' && @@ -29945,6 +31295,55 @@ const SettingsAccountTab = defineComponent({ signedIn && (account?.tierName || account?.planName) ? formatAccountTierBadge(account) : ''; + const cardCtx = { riskAccepted, canWrite, activeTierBadge }; + + // 1. Active Logged-in Account Card + const activeEntries = activeEmail + ? [ + { + email: activeEmail, + isActive: true, + isSaved: riskAccepted && accounts.includes(activeEmail), + }, + ] + : []; + patchAttr(activeCardHost, 'hidden', activeEntries.length === 0); + patchKeyedList(activeCardHost, activeEntries, { + keyFn: (entry) => entry.email, + sigFn: (entry) => + JSON.stringify([ + locale, + entry.isSaved, + riskAccepted, + canWrite, + confirmTarget?.key === entry.email ? confirmTarget.type : '', + quotas, + activeTierBadge, + ]), + createRow: createAccountCardDom, + updateRow: (row, entry) => updateAccountCardDom(row, entry, cardCtx), + }); + + // 2. Quota Trend Line Chart Card (always visible; locked to activeEmail when !riskAccepted) + quotaTrendCard.refs.update({ + activeEmail, + activePools: quotas?.pools || [], + riskAccepted, + accounts, + savedQuotas, + quotaHistory, + }); + + // 3. Risk Gate Stage & Multi-Account Controls + patchClasses(managedControlsBody, { 'is-locked': !riskAccepted }); + patchAttr(managedControlsBody, 'inert', !riskAccepted); + patchAttr(managedControlsBody, 'aria-hidden', riskAccepted ? null : 'true'); + patchAttr(riskMask, 'hidden', riskAccepted); + patchAttr(riskMask, 'aria-label', t('settings.oth.ctxRiskTitle')); + patchText(riskTitleEl, t('settings.oth.ctxRiskTitle')); + patchText(riskBodyEl, t(key('riskBody'))); + patchText(riskAcceptBtnText, t('settings.oth.ctxRiskAcceptBtn')); + patchAttr(riskAcceptBtn, 'disabled', acceptingRisk); const loginActive = ['waiting', 'exchanging', 'saving'].includes(loginSession?.status); patchText(loginBtnLabel, t(key('googleLogin'))); @@ -29969,32 +31368,34 @@ const SettingsAccountTab = defineComponent({ patchAttr(lockNowBtn, 'hidden', !vaultSecurity.enabled || vaultLocked || supported === false); patchAttr(lockNowBtn, 'disabled', !canOperateVault); - // Unlock strip (only when passphrase enabled & locked) - patchAttr(unlockBox, 'hidden', supported !== true || !vaultLocked); + // Unlock Notice + patchAttr(unlockBox, 'hidden', !riskAccepted || supported !== true || !vaultLocked); patchText(unlockHintLabel, t(key('vaultLockedHint'))); patchText(forgotToggleBtn, t(key('forgotPwdToggle'))); patchAttr(unlockInput, 'placeholder', t(key('unlockPlaceholder'))); patchAttr(unlockInput, 'disabled', !canOperateVault); patchText(unlockSubmitBtn, t(key('unlockBtn'))); patchAttr(unlockSubmitBtn, 'disabled', !canOperateVault); - patchAttr(resetRow, 'hidden', !forgotResetOpen || !vaultLocked); + const showResetSection = forgotResetOpen && vaultLocked; + patchAttr(resetHintEl, 'hidden', !showResetSection); + patchAttr(resetActionsWrap, 'hidden', !showResetSection); + patchAttr(resetVaultBtn, 'hidden', !showResetSection); patchText(resetHintEl, t(key('resetVaultHint'))); const armedVaultReset = confirmTarget?.type === 'resetVault' && confirmTarget.key === 'vault'; patchText(resetVaultBtn, t(key(armedVaultReset ? 'resetVaultConfirm' : 'resetVaultBtn'))); patchAttr(resetVaultBtn, 'disabled', !canOperateVault); - // Passphrase setup / manage drawer - const showPwdDrawer = pwdDrawerOpen && !vaultLocked && supported === true; + // Passphrase Drawer (`SegmentedControl` for Change / Disable) + const showPwdDrawer = riskAccepted && pwdDrawerOpen && !vaultLocked && supported === true; patchAttr(pwdForm, 'hidden', !showPwdDrawer); if (showPwdDrawer) { const isSetNew = !vaultSecurity.enabled; const isDisableMode = !isSetNew && pwdManageMode === 'disable'; - patchAttr(pwdTabsWrap, 'hidden', isSetNew); - patchText(pwdTabChangeBtn, t(key('pwdTabChange'))); - patchClasses(pwdTabChangeBtn, { 'is-active': pwdManageMode === 'change' }); - patchText(pwdTabDisableBtn, t(key('pwdTabDisable'))); - patchClasses(pwdTabDisableBtn, { 'is-active': isDisableMode }); + patchAttr(pwdModeSegment.el, 'hidden', isSetNew); + if (!isSetNew) { + pwdModeSegment.setProps({ modelValue: pwdManageMode, options: getPwdModeOptions() }); + } patchAttr(pwdCurrentInput, 'hidden', isSetNew); patchAttr(pwdCurrentInput, 'placeholder', t(key('pwdCurrentPlaceholder'))); @@ -30015,7 +31416,7 @@ const SettingsAccountTab = defineComponent({ patchClasses(pwdSubmitBtn, { 'btn-primary': !isDisableMode, 'btn-secondary': isDisableMode, - 'account-confirm-danger-btn': isDisableMode, + 'btn-danger-confirm': isDisableMode, }); patchAttr(pwdSubmitBtn, 'disabled', !canOperateVault); patchText(pwdHint, t(key(isSetNew ? 'pwdSetHint' : 'pwdManageHint'))); @@ -30034,7 +31435,7 @@ const SettingsAccountTab = defineComponent({ patchAttr(reload, 'disabled', Boolean(operation)); patchClasses(reload, { 'is-spinning': operation === 'list' }); - patchAttr(form, 'hidden', !importOpen || vaultLocked || supported === false); + patchAttr(form, 'hidden', !riskAccepted || !importOpen || vaultLocked || supported === false); patchAttr(credential, 'placeholder', t(key('credentialPlaceholder'))); patchAttr(credential, 'disabled', !canWrite); patchText(save, t(key('save'))); @@ -30073,11 +31474,8 @@ const SettingsAccountTab = defineComponent({ patchText(loginLink, t(key('openLoginPage'))); patchAttr(loginLink, 'href', authUrl || null); patchAttr(loginLink, 'hidden', !authUrl); - patchClasses(loginStrip, { - 'is-error': loginIsError, - 'is-ok': loginSession?.status === 'success', - 'is-info': loginActive, - }); + patchAttr(loginLinkWrap, 'hidden', !authUrl); + patchClasses(loginStrip, { 'is-restart': !loginIsError }); patchAttr(loginStrip, 'hidden', !hasLoginSession || !loginMessageKey); const failedSwitch = @@ -30097,7 +31495,6 @@ const SettingsAccountTab = defineComponent({ patchClasses(feedback, { 'is-error': isFeedbackError, 'is-ok': isFeedbackOk, - 'is-info': !isFeedbackError && !isFeedbackOk && Boolean(message), }); patchAttr(feedback, 'hidden', !message); @@ -30106,16 +31503,38 @@ const SettingsAccountTab = defineComponent({ activeEmail !== selectedEmail && switchState?.state === 'written' && status !== 'restarting'; - patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : ''); + patchText(pendingDesc, waiting ? t(key('pending'), { email: selectedEmail }) : ''); patchAttr(pending, 'hidden', !waiting); - const entries = buildUnifiedAccountEntries(activeEmail); - patchAttr(cardsHost, 'hidden', entries.length === 0); + const backupEntries = riskAccepted + ? accounts + .filter((addr) => addr && addr !== activeEmail) + .map((addr) => ({ email: addr, isActive: false, isSaved: true })) + : []; + patchAttr(backupCardsHost, 'hidden', backupEntries.length === 0); + patchKeyedList(backupCardsHost, backupEntries, { + keyFn: (entry) => entry.email, + sigFn: (entry) => + JSON.stringify([ + locale, + selectedEmail, + switchState?.state || '', + canWrite, + confirmTarget?.key === entry.email ? confirmTarget.type : '', + savedQuotas.get(entry.email), + quotaVisibleLoading.has(entry.email), + quotaErrors.get(entry.email), + ]), + createRow: createAccountCardDom, + updateRow: (row, entry) => updateAccountCardDom(row, entry, cardCtx), + }); + + const showEmpty = !activeEmail && (!riskAccepted || backupEntries.length === 0); patchText( emptyTextEl, t( key( - supported === null + supported === null && !activeEmail ? 'loading' : account?.status === 'signedOut' ? 'signedOut' @@ -30123,217 +31542,7 @@ const SettingsAccountTab = defineComponent({ ) ) ); - patchAttr(emptyPanel, 'hidden', entries.length > 0); - - patchKeyedList(cardsHost, entries, { - keyFn: (entry) => entry.email, - sigFn: (entry) => - JSON.stringify([ - locale, - entry.isActive, - entry.isSaved, - selectedEmail, - switchState?.state || '', - canWrite, - confirmTarget?.key === entry.email ? confirmTarget.type : '', - entry.isActive ? null : savedQuotas.get(entry.email), - quotaVisibleLoading.has(entry.email), - entry.isActive ? null : quotaErrors.get(entry.email), - entry.isActive ? quotas : null, - entry.isActive ? activeTierBadge : '', - ]), - createRow: (entry) => { - const activeDot = h('span', { className: 'dot-swatch account-active-dot', hidden: true }); - const emailEl = h('span', { - className: 'settings-account-identity account-card-email', - text: entry.email, - title: entry.email, - }); - const tierPill = h('span', { className: 'account-tag is-tier', hidden: true }); - const statePill = h('span', { className: 'account-tag', hidden: true }); - - const captureBtn = h('button', { - type: 'button', - className: 'btn-secondary account-card-btn', - hidden: true, - onClick: () => { - clearConfirmTarget(false); - void request('capture'); - }, - }); - const selectBtn = h('button', { - type: 'button', - className: 'btn-secondary account-card-btn', - hidden: true, - onClick: () => { - armOrRunConfirm('switch', entry.email, () => { - const curActive = resolveActiveEmail(); - void request('switch', { - email: entry.email, - ...(curActive ? { activeEmail: curActive } : {}), - }); - }); - }, - }); - const loadQuotaBtn = h( - 'button', - { - type: 'button', - className: 'icon-btn settings-account-load-quota account-icon-btn', - hidden: true, - onClick: () => { - clearConfirmTarget(false); - void request('quota', { email: entry.email, manual: true }); - }, - }, - [createSvgIcon('refresh', { size: 12 })] - ); - const removeBtn = h( - 'button', - { - type: 'button', - className: 'icon-btn slot-remove-btn settings-account-remove account-icon-btn', - hidden: true, - onClick: () => { - armOrRunConfirm('remove', entry.email, () => { - void request('remove', { email: entry.email }); - }); - }, - }, - [createSvgIcon('close', { size: 12 })] - ); - const removeConfirmBtn = h('button', { - type: 'button', - className: - 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-remove-confirm', - hidden: true, - onClick: () => { - armOrRunConfirm('remove', entry.email, () => { - void request('remove', { email: entry.email }); - }); - }, - }); - - const poolsWrap = h('div', { className: 'account-pools-stack' }); - const noteEl = h('div', { className: 'settings-action-desc account-card-note', hidden: true }); - - const cardEl = h('section', { className: 'panel account-card' }, [ - h('div', { className: 'panel-header account-card-head' }, [ - h('div', { className: 'account-card-meta' }, [ - activeDot, - emailEl, - tierPill, - statePill, - ]), - h('div', { className: 'account-card-actions' }, [ - captureBtn, - selectBtn, - loadQuotaBtn, - removeBtn, - removeConfirmBtn, - ]), - ]), - poolsWrap, - noteEl, - ]); - return { - el: cardEl, - refs: { - cardEl, - activeDot, - emailEl, - tierPill, - statePill, - captureBtn, - selectBtn, - loadQuotaBtn, - removeBtn, - removeConfirmBtn, - poolsWrap, - noteEl, - }, - }; - }, - updateRow: (row, entry) => { - const addr = entry.email; - const active = entry.isActive; - const isSaved = entry.isSaved; - const written = addr === selectedEmail && !active && switchState?.state === 'written'; - const cached = active ? null : savedQuotas.get(addr); - const tierText = active - ? activeTierBadge - : cached?.tierName || cached?.tierId - ? formatAccountTierBadge({ - tierId: cached.tierId, - tierName: cached.tierName, - tierMultiplier: cached.tierMultiplier, - }) - : ''; - const isSpinning = !active && quotaVisibleLoading.has(addr); - const canSwitch = !active && isSaved; - const armedSwitch = confirmTarget?.type === 'switch' && confirmTarget.key === addr; - const armedRemove = confirmTarget?.type === 'remove' && confirmTarget.key === addr; - - patchClasses(row.cardEl, { 'is-active-account': active }); - patchAttr(row.activeDot, 'hidden', !active); - patchText(row.emailEl, addr); - patchAttr(row.emailEl, 'title', addr); - - patchText(row.tierPill, tierText); - patchAttr(row.tierPill, 'hidden', !tierText); - - patchText(row.statePill, active ? t(key('active')) : written ? t(key('written')) : ''); - patchClasses(row.statePill, { 'is-active': active, 'is-written': written }); - patchAttr(row.statePill, 'hidden', !active && !written); - - patchText(row.captureBtn, t(key('capture'))); - patchAttr(row.captureBtn, 'hidden', !active || isSaved || supported === false); - patchAttr(row.captureBtn, 'disabled', !canWrite); - - patchText(row.selectBtn, t(key(armedSwitch ? 'switchConfirm' : 'switch'))); - patchAttr(row.selectBtn, 'title', t(key('switchHint'))); - patchClasses(row.selectBtn, { - 'settings-account-switch': canSwitch, - 'is-confirm-warn': armedSwitch, - }); - patchAttr(row.selectBtn, 'hidden', !canSwitch); - patchAttr(row.selectBtn, 'disabled', !canWrite); - - patchAttr(row.loadQuotaBtn, 'title', t(key(isSpinning ? 'loadingQuota' : 'loadQuota'))); - patchAttr(row.loadQuotaBtn, 'aria-label', t(key('loadQuota'))); - patchClasses(row.loadQuotaBtn, { 'is-spinning': isSpinning }); - // Active account exclusively uses host telemetry — hide OAuth quota refresh on active card - patchAttr(row.loadQuotaBtn, 'hidden', active || !isSaved); - patchAttr(row.loadQuotaBtn, 'disabled', !canWrite || isSpinning); - - patchAttr(row.removeBtn, 'title', t(key('remove'))); - patchAttr(row.removeBtn, 'aria-label', t(key('remove'))); - patchAttr(row.removeBtn, 'hidden', !isSaved || armedRemove); - patchAttr(row.removeBtn, 'disabled', !canWrite); - - patchText(row.removeConfirmBtn, t(key('removeConfirm'))); - patchAttr(row.removeConfirmBtn, 'hidden', !isSaved || !armedRemove); - patchAttr(row.removeConfirmBtn, 'disabled', !canWrite); - - const displayedPools = active ? quotas?.pools || [] : cached?.pools || []; - const poolCount = renderQuotaRows(row.poolsWrap, displayedPools); - const quotaError = active ? '' : quotaErrors.get(addr); - - let noteText = ''; - if (quotaError) { - noteText = t(key(quotaError)); - } else if (active && poolCount > 0 && quotas?.meta?.isStale) { - noteText = t(key('quotaStale')); - } else if (active && poolCount === 0) { - noteText = t(key('noQuota')); - } else if (!active && cached && poolCount === 0) { - noteText = t(key('emptyCredentialQuota')); - } - patchText(row.noteEl, noteText); - patchClasses(row.noteEl, { 'is-error': Boolean(quotaError) }); - patchAttr(row.noteEl, 'hidden', !noteText); - }, - }); + patchAttr(emptyPanel, 'hidden', !showEmpty); props.onLayoutChange?.(); } @@ -30369,6 +31578,7 @@ const SettingsAccountTab = defineComponent({ } async function request(action, fields = {}) { + if (action !== 'list' && !draftRiskAccepted) return; if (action === 'quota') return refreshQuota(fields.email, Boolean(fields.manual)); if (operation) return; operation = action; @@ -30387,6 +31597,9 @@ const SettingsAccountTab = defineComponent({ if (typeof result?.actionNonce === 'string' && result.actionNonce) { actionNonce = result.actionNonce; } + if (result?.quotaHistory && typeof result.quotaHistory === 'object') { + quotaHistory = { ...quotaHistory, ...result.quotaHistory }; + } if (result?.error) { if (result.error === 'unsupported') supported = false; if (result.error === 'vaultLocked') { @@ -30402,6 +31615,7 @@ const SettingsAccountTab = defineComponent({ return; } supported = result?.supported === true; + riskLockedFromServer = Boolean(result?.riskLocked); accounts = result?.accounts || []; selectedEmail = result?.selectedEmail || ''; switchState = result?.switchState || null; @@ -30422,7 +31636,7 @@ const SettingsAccountTab = defineComponent({ savedQuotas.set(addr, snapshot); } syncWarmCache(); - if (action !== 'switch' && !isVaultLocked()) { + if (action !== 'switch' && draftRiskAccepted && !riskLockedFromServer && !isVaultLocked()) { void refreshSavedQuotas(); } if (action === 'save' || action === 'capture') { @@ -30478,7 +31692,7 @@ const SettingsAccountTab = defineComponent({ return; } await request('list'); - if (!disposed && !isVaultLocked() && email !== resolveActiveEmail()) { + if (!disposed && draftRiskAccepted && !isVaultLocked() && email !== resolveActiveEmail()) { void refreshQuota(email, false); } } @@ -30513,13 +31727,12 @@ const SettingsAccountTab = defineComponent({ } async function refreshSavedQuotas() { - if (refreshingSavedQuotas || isVaultLocked()) return; + if (refreshingSavedQuotas || !draftRiskAccepted || isVaultLocked()) return; refreshingSavedQuotas = true; try { const activeEmail = resolveActiveEmail(); const ttlMs = refreshMinutes * 60_000; const staleTargets = accounts.filter((addr) => { - // Active account exclusively uses host telemetry — never poll via OAuth if (!addr || addr === activeEmail) return false; const cached = savedQuotas.get(addr); if (needsLegacyUltraTierRefresh(cached)) return true; @@ -30527,7 +31740,7 @@ const SettingsAccountTab = defineComponent({ }); const BATCH_SIZE = 3; for (let i = 0; i < staleTargets.length; i += BATCH_SIZE) { - if (disposed || operation === 'switch' || isVaultLocked()) break; + if (disposed || operation === 'switch' || !draftRiskAccepted || isVaultLocked()) break; const batch = staleTargets.slice(i, i + BATCH_SIZE); await Promise.all(batch.map((addr) => refreshQuota(addr, false))); } @@ -30538,7 +31751,14 @@ const SettingsAccountTab = defineComponent({ async function refreshQuota(addr, manual = false) { const activeEmail = resolveActiveEmail(); - if (!addr || addr === activeEmail || isVaultLocked() || quotaInFlight.has(addr) || disposed) { + if ( + !addr || + addr === activeEmail || + !draftRiskAccepted || + isVaultLocked() || + quotaInFlight.has(addr) || + disposed + ) { return; } const hasCachedPools = Boolean(savedQuotas.get(addr)?.pools?.length); @@ -30570,9 +31790,10 @@ const SettingsAccountTab = defineComponent({ const nextTierId = result.tierId || prev.tierId || ''; const nextTierName = result.tierName || prev.tierName || ''; const nextTierMult = result.tierMultiplier || prev.tierMultiplier || ''; + const fetchedAt = result.fetchedAt || Date.now(); savedQuotas.set(addr, { pools: result.pools, - fetchedAt: result.fetchedAt || Date.now(), + fetchedAt, ...(nextTierId ? { tierId: nextTierId } : {}), ...(nextTierName ? { tierName: nextTierName } : {}), ...(nextTierMult ? { tierMultiplier: nextTierMult } : {}), @@ -30661,24 +31882,41 @@ const SettingsAccountTab = defineComponent({ settingsData?.accountQuotaRefreshMinutes !== undefined ? normalizeAccountQuotaRefreshMinutes(settingsData.accountQuotaRefreshMinutes) : refreshMinutes; - if (account === value && quotas === quotaData && refreshMinutes === nextRefreshMins) return; + const nextRiskAccepted = + acceptingRisk || settingsData?.accountSwitchRiskAccepted === undefined + ? draftRiskAccepted + : Boolean(settingsData.accountSwitchRiskAccepted); + if ( + account === value && + quotas === quotaData && + refreshMinutes === nextRefreshMins && + draftRiskAccepted === nextRiskAccepted + ) { + return; + } + const becameRiskUnlocked = !draftRiskAccepted && nextRiskAccepted; account = value; quotas = quotaData; refreshMinutes = nextRefreshMins; + draftRiskAccepted = nextRiskAccepted; render(); + if (becameRiskUnlocked && riskLockedFromServer && !operation) { + void request('list'); + } } const quotaScheduleTimer = setInterval(() => { - if (!disposed && accounts.length > 0 && !operation && !isVaultLocked()) { + if (!disposed && draftRiskAccepted && accounts.length > 0 && !operation && !isVaultLocked()) { void refreshSavedQuotas(); } }, 60_000); quotaScheduleTimer.unref?.(); const root = h('div', { className: 'settings-tab-stack settings-account-root' }, [ - toolbarPanel, - cardsHost, + quotaTrendCard.el, + activeCardHost, emptyPanel, + riskStage, ]); render(); onCleanup(() => { @@ -30688,6 +31926,8 @@ const SettingsAccountTab = defineComponent({ if (statusClearTimer) clearTimeout(statusClearTimer); if (confirmClearTimer) clearTimeout(confirmClearTimer); refreshIntervalSelect.destroy(); + pwdModeSegment.destroy(); + quotaTrendCard.destroy(); loginGeneration += 1; credential.value = ''; clearPasswordInputs(); @@ -30696,9 +31936,17 @@ const SettingsAccountTab = defineComponent({ el: root, refs: { renderAccount, - refreshLabels: render, + refreshLabels: () => { + quotaTrendCard.refs.refreshLabels(); + render(); + }, preload: () => (supported === null ? request('list') : Promise.resolve()), - load: () => (supported === null ? request('list') : refreshSavedQuotas()), + load: () => + supported === null || (draftRiskAccepted && riskLockedFromServer) + ? request('list') + : draftRiskAccepted + ? refreshSavedQuotas() + : Promise.resolve(), }, }; }, diff --git a/sidecars/panel/backend/account-quota-history.mjs b/sidecars/panel/backend/account-quota-history.mjs new file mode 100644 index 0000000..07e28e0 --- /dev/null +++ b/sidecars/panel/backend/account-quota-history.mjs @@ -0,0 +1,477 @@ +/** + * @fileoverview Compact, collinear-compressed per-account quota history store + * (`account-quota-history.mjs`). + * + * Records 5-hour and weekly remaining-percentage trajectories across quota pools + * for the active host account (from live telemetry) and saved backup accounts + * (from scheduled OAuth refreshes). Bootstraps initial history from existing + * `quota_reservation_state.json` observations when available. + */ + +import { parseIsoMs } from '../trajectory-metrics.mjs'; +import { + ACCOUNT_QUOTA_HISTORY_FILE, + QUOTA_RESERVATION_STATE_FILE, + loadJson, + lsRuntimeEndpoint, + saveJson, +} from './config.mjs'; + +const AQH_SCHEMA_VERSION = 1; +const AQH_MAX_ACCOUNTS = 32; +const AQH_MAX_POOLS_PER_ACCOUNT = 8; +const AQH_MAX_POINTS_PER_POOL = 1600; +const AQH_PERSIST_MIN_INTERVAL_MS = 5000; +const AQH_CHANGE_EPSILON_PCT = 0.05; +const AQH_MAX_FLAT_MERGE_GAP_MS = 6 * 3600 * 1000; + +function aqhClampPct(val) { + if (val === null || val === undefined || val === '') return null; + const num = Number(val); + if (!Number.isFinite(num)) return null; + return Math.round(Math.max(0, Math.min(100, num)) * 10) / 10; +} + +function aqhNormEmail(raw) { + return typeof raw === 'string' ? raw.trim().toLowerCase() : ''; +} + +function aqhSameVal(a, b) { + if (a === null && b === null) return true; + if (a === null || b === null) return false; + return Math.abs(a - b) < AQH_CHANGE_EPSILON_PCT; +} + +const AQH_IMPULSE_MAX_SPAN_MS = 20 * 60_000; +const AQH_IMPULSE_MIN_JUMP_PCT = 3; +const AQH_IMPULSE_MAX_NEIGHBOR_DIFF_PCT = 1.2; + +function aqhIsIsolatedUpwardImpulse(prevVal, curVal, nextVal) { + if (prevVal === null || curVal === null || nextVal === null) return false; + return ( + curVal - prevVal >= AQH_IMPULSE_MIN_JUMP_PCT && + curVal - nextVal >= AQH_IMPULSE_MIN_JUMP_PCT && + Math.abs(nextVal - prevVal) <= AQH_IMPULSE_MAX_NEIGHBOR_DIFF_PCT + ); +} + +/** + * Removes isolated single-sample upward spikes (e.g. cross-account `init` seed events + * where remaining % momentarily jumps `94.8 -> 100 -> 94.7` within minutes and snaps + * right back to the pre-spike trajectory). + */ +export function sanitizeQuotaHistoryPoints(points) { + if (!Array.isArray(points) || points.length < 3) return false; + let removed = false; + let i = 1; + while (i < points.length - 1) { + const prev = points[i - 1]; + const cur = points[i]; + const next = points[i + 1]; + const spanMs = next[0] - prev[0]; + if ( + spanMs >= 0 && + spanMs <= AQH_IMPULSE_MAX_SPAN_MS && + (aqhIsIsolatedUpwardImpulse(prev[1], cur[1], next[1]) || + aqhIsIsolatedUpwardImpulse(prev[2], cur[2], next[2])) + ) { + points.splice(i, 1); + removed = true; + if (i > 1) i -= 1; + continue; + } + i += 1; + } + return removed; +} + +function aqhDownsamplePoints(points, targetLen) { + if (points.length <= targetLen) return points; + const keepRecent = Math.floor(targetLen * 0.65); + const oldEnd = points.length - keepRecent; + const oldQuota = Math.max(2, targetLen - keepRecent); + const stride = Math.max(2, Math.ceil(oldEnd / oldQuota)); + const compacted = []; + for (let i = 0; i < oldEnd; i += stride) { + const sliceEnd = Math.min(oldEnd, i + stride); + let minPt = points[i]; + let maxPt = points[i]; + for (let j = i + 1; j < sliceEnd; j++) { + const p = points[j]; + const v = p[1] ?? p[2] ?? 100; + if (v < (minPt[1] ?? minPt[2] ?? 100)) minPt = p; + if (v > (maxPt[1] ?? maxPt[2] ?? 0)) maxPt = p; + } + if (minPt === maxPt) { + compacted.push(minPt); + } else if (minPt[0] <= maxPt[0]) { + compacted.push(minPt, maxPt); + } else { + compacted.push(maxPt, minPt); + } + } + for (let i = oldEnd; i < points.length; i++) { + compacted.push(points[i]); + } + return compacted; +} + +function aqhAppendPoint(points, tsMs, r5h, rWk) { + const len = points.length; + if (len === 0) { + points.push([tsMs, r5h, rWk]); + return true; + } + const last = points[len - 1]; + if (tsMs < last[0]) { + return false; + } + const resolved5h = r5h !== null ? r5h : last[1]; + const resolvedWk = rWk !== null ? rWk : last[2]; + if (tsMs === last[0]) { + if (!aqhSameVal(last[1], resolved5h) || !aqhSameVal(last[2], resolvedWk)) { + last[1] = resolved5h; + last[2] = resolvedWk; + return true; + } + return false; + } + const unchanged = aqhSameVal(last[1], resolved5h) && aqhSameVal(last[2], resolvedWk); + if (unchanged && len >= 2) { + const prev = points[len - 2]; + const prevSame = aqhSameVal(prev[1], resolved5h) && aqhSameVal(prev[2], resolvedWk); + if (prevSame && tsMs - prev[0] <= AQH_MAX_FLAT_MERGE_GAP_MS) { + // Collinear flat segment: advance trailing endpoint timestamp in place + if (tsMs - last[0] < 60_000) return false; + last[0] = tsMs; + return true; + } + } + if (unchanged && tsMs - last[0] < 10 * 60_000) { + return false; + } + points.push([tsMs, resolved5h, resolvedWk]); + if (points.length > AQH_MAX_POINTS_PER_POOL) { + const trimmed = aqhDownsamplePoints(points, Math.floor(AQH_MAX_POINTS_PER_POOL * 0.8)); + points.length = 0; + for (let i = 0; i < trimmed.length; i++) points.push(trimmed[i]); + } + return true; +} + +export function createAccountQuotaHistoryTracker({ + loadState = () => null, + saveState = () => {}, + loadSeedEvents = () => null, +} = {}) { + const accountsMap = new Map(); + let latestHostEmail = ''; + let hydrated = false; + let seededFromQr = false; + let lastPersistMs = 0; + let dirty = false; + + function ensureAccountEntry(email, nowMs) { + let acc = accountsMap.get(email); + if (acc) { + acc.updatedAtMs = nowMs; + return acc; + } + if (accountsMap.size >= AQH_MAX_ACCOUNTS) { + let oldestEmail = null; + let oldestTs = Infinity; + for (const [k, v] of accountsMap.entries()) { + if ((v.updatedAtMs || 0) < oldestTs) { + oldestTs = v.updatedAtMs || 0; + oldestEmail = k; + } + } + if (oldestEmail) accountsMap.delete(oldestEmail); + } + acc = { updatedAtMs: nowMs, pools: new Map() }; + accountsMap.set(email, acc); + return acc; + } + + function hydrate() { + if (hydrated) return; + hydrated = true; + try { + const raw = loadState(); + if (raw && typeof raw === 'object' && raw.accounts && typeof raw.accounts === 'object') { + seededFromQr = Boolean(raw.seededFromQr); + for (const [rawEmail, accVal] of Object.entries(raw.accounts)) { + const email = aqhNormEmail(rawEmail); + if (!email || !accVal || typeof accVal !== 'object') continue; + const poolsMap = new Map(); + for (const [pk, pVal] of Object.entries(accVal.pools || {})) { + if (!pk || !pVal || !Array.isArray(pVal.points)) continue; + const cleanPts = []; + for (let i = 0; i < pVal.points.length; i++) { + const pt = pVal.points[i]; + if (!Array.isArray(pt) || !(Number(pt[0]) > 0)) continue; + const r5 = aqhClampPct(pt[1]); + const rw = aqhClampPct(pt[2]); + if (r5 === null && rw === null) continue; + cleanPts.push([Math.floor(Number(pt[0])), r5, rw]); + } + if (cleanPts.length > 0) { + if (sanitizeQuotaHistoryPoints(cleanPts)) { + dirty = true; + } + poolsMap.set(pk, { + label: String(pVal.label || pk), + reset5hMs: Number(pVal.reset5hMs) > 0 ? Math.floor(Number(pVal.reset5hMs)) : 0, + resetWeeklyMs: + Number(pVal.resetWeeklyMs) > 0 ? Math.floor(Number(pVal.resetWeeklyMs)) : 0, + points: cleanPts.slice(-AQH_MAX_POINTS_PER_POOL), + }); + } + } + if (poolsMap.size > 0) { + accountsMap.set(email, { + updatedAtMs: Number(accVal.updatedAtMs) || Date.now(), + pools: poolsMap, + }); + } + } + } + } catch { + // Ignore corrupt history file and start fresh + } + } + + function seedFromReservationEventsIfEmpty(activeEmail) { + if (seededFromQr || !activeEmail) return; + const existing = accountsMap.get(activeEmail); + if (existing && existing.pools.size > 0) { + seededFromQr = true; + return; + } + seededFromQr = true; + try { + const qr = loadSeedEvents(); + const events = Array.isArray(qr?.events) ? qr.events : []; + if (events.length === 0) return; + const acc = ensureAccountEntry(activeEmail, Date.now()); + for (let i = 0; i < events.length; i++) { + const ev = events[i]; + const pk = String(ev?.pool || '').trim(); + const win = String(ev?.win || '').trim(); + const tsMs = parseIsoMs(ev?.ts); + const used = Number(ev?.usedPct); + if (!pk || !(tsMs > 0) || !Number.isFinite(used)) continue; + const rem = aqhClampPct(100 - used); + if (rem === null) continue; + let poolEntry = acc.pools.get(pk); + if (!poolEntry) { + if (acc.pools.size >= AQH_MAX_POOLS_PER_ACCOUNT) continue; + poolEntry = { label: pk, reset5hMs: 0, resetWeeklyMs: 0, points: [] }; + acc.pools.set(pk, poolEntry); + } + if (ev?.event === 'init' && poolEntry.points.length > 0) { + const lastPt = poolEntry.points[poolEntry.points.length - 1]; + const prevVal = win === 'weekly' ? lastPt[2] : lastPt[1]; + if (prevVal !== null && rem - prevVal >= AQH_IMPULSE_MIN_JUMP_PCT) { + continue; + } + } + aqhAppendPoint( + poolEntry.points, + tsMs, + win === '5h' ? rem : null, + win === 'weekly' ? rem : null + ); + dirty = true; + } + for (const poolEntry of acc.pools.values()) { + sanitizeQuotaHistoryPoints(poolEntry.points); + } + } catch { + // Optional seed is best-effort + } + } + + function persistIfNeeded(nowMs, force = false) { + if (!dirty) return; + if (!force && lastPersistMs > 0 && nowMs - lastPersistMs < AQH_PERSIST_MIN_INTERVAL_MS) { + return; + } + lastPersistMs = nowMs; + dirty = false; + const serializedAccounts = {}; + for (const [email, acc] of accountsMap.entries()) { + const poolsObj = {}; + for (const [pk, pVal] of acc.pools.entries()) { + if (!pVal.points.length) continue; + poolsObj[pk] = { + label: pVal.label, + ...(pVal.reset5hMs > 0 ? { reset5hMs: pVal.reset5hMs } : {}), + ...(pVal.resetWeeklyMs > 0 ? { resetWeeklyMs: pVal.resetWeeklyMs } : {}), + points: pVal.points, + }; + } + if (Object.keys(poolsObj).length > 0) { + serializedAccounts[email] = { + updatedAtMs: acc.updatedAtMs, + pools: poolsObj, + }; + } + } + try { + saveState({ + schemaVersion: AQH_SCHEMA_VERSION, + seededFromQr, + updatedAt: new Date(nowMs).toISOString(), + accounts: serializedAccounts, + }); + } catch { + // Best-effort persistence + } + } + + function recordSnapshot(rawEmail, pools, nowMs = Date.now(), { isActiveHost = false } = {}) { + const email = aqhNormEmail(rawEmail); + if (!email || !Array.isArray(pools) || pools.length === 0) return; + hydrate(); + if (isActiveHost) { + latestHostEmail = email; + seedFromReservationEventsIfEmpty(email); + } + const tsMs = Number.isFinite(Number(nowMs)) && Number(nowMs) > 0 ? Math.floor(Number(nowMs)) : Date.now(); + const acc = ensureAccountEntry(email, tsMs); + let anyChanged = false; + + for (let i = 0; i < pools.length; i++) { + const p = pools[i]; + const pk = String(p?.poolKey || p?.family || p?.poolLabel || '').trim(); + if (!pk || pk === 'Unknown') continue; + const r5h = aqhClampPct(p?.remainingPct ?? p?.remaining5hPct); + const rWk = aqhClampPct(p?.weeklyRemainingPct ?? p?.remainingWeeklyPct); + if (r5h === null && rWk === null) continue; + + let poolEntry = acc.pools.get(pk); + if (!poolEntry) { + if (acc.pools.size >= AQH_MAX_POOLS_PER_ACCOUNT) continue; + poolEntry = { + label: String(p?.poolLabel || pk), + reset5hMs: 0, + resetWeeklyMs: 0, + points: [], + }; + acc.pools.set(pk, poolEntry); + } + if (p?.poolLabel) poolEntry.label = String(p.poolLabel); + const nextReset5h = parseIsoMs(p?.resetTime || p?.reset5h); + const nextResetWk = parseIsoMs(p?.weeklyResetTime || p?.resetWeekly); + if (nextReset5h > 0 && nextReset5h !== poolEntry.reset5hMs) { + poolEntry.reset5hMs = nextReset5h; + anyChanged = true; + } + if (nextResetWk > 0 && nextResetWk !== poolEntry.resetWeeklyMs) { + poolEntry.resetWeeklyMs = nextResetWk; + anyChanged = true; + } + if (aqhAppendPoint(poolEntry.points, tsMs, r5h, rWk)) { + anyChanged = true; + } + } + + if (anyChanged) { + dirty = true; + persistIfNeeded(tsMs, false); + } + } + + function removeAccount(rawEmail, nowMs = Date.now()) { + const email = aqhNormEmail(rawEmail); + if (!email) return; + hydrate(); + if (accountsMap.delete(email)) { + dirty = true; + persistIfNeeded(nowMs, true); + } + } + + function getHistoryPayload({ allowedEmails = null } = {}) { + hydrate(); + const allowSet = Array.isArray(allowedEmails) + ? new Set(allowedEmails.map(aqhNormEmail).filter(Boolean)) + : null; + const out = {}; + for (const [email, acc] of accountsMap.entries()) { + if (allowSet && !allowSet.has(email)) continue; + const poolsObj = {}; + for (const [pk, pVal] of acc.pools.entries()) { + if (!pVal.points.length) continue; + poolsObj[pk] = { + label: pVal.label, + ...(pVal.reset5hMs > 0 ? { reset5hMs: pVal.reset5hMs } : {}), + ...(pVal.resetWeeklyMs > 0 ? { resetWeeklyMs: pVal.resetWeeklyMs } : {}), + points: pVal.points, + }; + } + if (Object.keys(poolsObj).length > 0) { + out[email] = { pools: poolsObj }; + } + } + return out; + } + + function reset() { + accountsMap.clear(); + latestHostEmail = ''; + hydrated = true; + seededFromQr = false; + lastPersistMs = 0; + dirty = false; + } + + return { + recordSnapshot, + removeAccount, + getHistoryPayload, + getLatestHostEmail: () => latestHostEmail, + flush: (nowMs = Date.now()) => persistIfNeeded(nowMs, true), + reset, + }; +} + +function aqhIsTestRuntime() { + return ( + lsRuntimeEndpoint?.addr === 'test.invalid' || + String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid' + ); +} + +const defaultAccountQuotaHistoryTracker = createAccountQuotaHistoryTracker({ + loadState: () => (aqhIsTestRuntime() ? null : loadJson(ACCOUNT_QUOTA_HISTORY_FILE, null)), + saveState: (payload) => { + if (!aqhIsTestRuntime()) saveJson(ACCOUNT_QUOTA_HISTORY_FILE, payload); + }, + loadSeedEvents: () => (aqhIsTestRuntime() ? null : loadJson(QUOTA_RESERVATION_STATE_FILE, null)), +}); + +export function recordAccountQuotaSnapshot(email, pools, nowMs = Date.now(), opts = {}) { + defaultAccountQuotaHistoryTracker.recordSnapshot(email, pools, nowMs, opts); +} + +export function removeAccountQuotaHistory(email, nowMs = Date.now()) { + defaultAccountQuotaHistoryTracker.removeAccount(email, nowMs); +} + +export function getAccountQuotaHistoryPayload(opts = {}) { + return defaultAccountQuotaHistoryTracker.getHistoryPayload(opts); +} + +export function getLatestRecordedHostEmail() { + return defaultAccountQuotaHistoryTracker.getLatestHostEmail(); +} + +export function flushAccountQuotaHistoryNow(nowMs = Date.now()) { + defaultAccountQuotaHistoryTracker.flush(nowMs); +} + +export function resetAccountQuotaHistoryState() { + defaultAccountQuotaHistoryTracker.reset(); +} diff --git a/sidecars/panel/backend/account-switch.mjs b/sidecars/panel/backend/account-switch.mjs index 4b86355..b682dc5 100644 --- a/sidecars/panel/backend/account-switch.mjs +++ b/sidecars/panel/backend/account-switch.mjs @@ -11,6 +11,10 @@ import { resolveGoogleCredential, retrieveCredentialQuota, } from './account-oauth.mjs'; +import { + recordAccountQuotaSnapshot, + removeAccountQuotaHistory, +} from './account-quota-history.mjs'; import { checkVaultUnlockCooldown, createVaultSecurityMetadata, @@ -36,7 +40,7 @@ const ACCOUNT_ERRORS = new Set([ 'oauthUnavailable', 'quotaUnavailable', 'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed', 'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordRateLimited', - 'vaultDecryptFailed', 'invalidActionNonce', + 'vaultDecryptFailed', 'invalidActionNonce', 'riskNotAccepted', ]); const ALLOWED_ACTIONS = new Set([ @@ -717,6 +721,7 @@ export async function handleAccountCredentialAction( if (action === 'remove') { const activeSec = await ensureUnlockedVaultContext(); clearTransientAccessTokens(email); + removeAccountQuotaHistory(email); return publicList( await runStore({ action, @@ -806,6 +811,9 @@ export async function handleAccountCredentialAction( expectedCredential: expectedCredForQuota, quota: quotaPayload, }); + if (useDiskSigCache) { + recordAccountQuotaSnapshot(email, pools, fetchedAt, { isActiveHost: false }); + } return { email, pools, fetchedAt, ...tierMeta }; } diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index b278ab9..f71d756 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -9,6 +9,10 @@ import { randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; import { BRIDGE_API_ROUTE_DEFS, LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs'; +import { + getAccountQuotaHistoryPayload, + getLatestRecordedHostEmail, +} from './account-quota-history.mjs'; import { handleAccountCredentialAction, warmAccountPublicListCache } from './account-switch.mjs'; import { issueAccountActionNonce, verifyAccountActionNonce } from './account-vault-crypto.mjs'; import { @@ -644,6 +648,38 @@ export async function executeAccountCredentialAction(data, opts = {}) { } const cleanData = stripEndpointField(data); const action = cleanData?.action || 'list'; + const riskAccepted = + opts?.bypassRiskCheck === true || loadSettings().accountSwitchRiskAccepted === true; + if (!riskAccepted) { + if (action !== 'list') { + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ + error: 'riskNotAccepted', + actionNonce: issueAccountActionNonce(), + }), + }; + } + const hostEmail = getLatestRecordedHostEmail(); + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ + supported: process.platform === 'win32', + riskLocked: true, + accounts: [], + selectedEmail: '', + quotas: {}, + quotaHistory: getAccountQuotaHistoryPayload({ + allowedEmails: hostEmail ? [hostEmail] : [], + }), + actionNonce: issueAccountActionNonce(), + }), + }; + } if (NONCE_PROTECTED_ACCOUNT_ACTIONS.has(action) && !verifyAccountActionNonce(cleanData?.actionNonce)) { return { status: 200, @@ -663,9 +699,25 @@ export async function executeAccountCredentialAction(data, opts = {}) { if (action === 'switch' && !result?.error) { clearTelemetryBuilderMemo(LOCAL_ENDPOINT_ID); } + const hostEmail = getLatestRecordedHostEmail(); + const allowedHistoryEmails = Array.isArray(result?.accounts) + ? [...new Set([...result.accounts, ...(hostEmail ? [hostEmail] : [])])] + : hostEmail + ? [hostEmail] + : null; const enriched = result && typeof result === 'object' - ? { ...result, actionNonce: issueAccountActionNonce() } + ? { + ...result, + ...(action === 'list' || Array.isArray(result.accounts) + ? { + quotaHistory: getAccountQuotaHistoryPayload({ + allowedEmails: allowedHistoryEmails, + }), + } + : {}), + actionNonce: issueAccountActionNonce(), + } : result; return { status: 200, @@ -904,8 +956,9 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu if (lsRuntimeEndpoint.addr === 'test.invalid') return null; if (!allowDynamicLs && !lsRuntimeEndpoint.addr) return null; - ensureCliStatusLineConfigured({ enabled: loadSettings().enableCliStatusLine !== false }); - if (allowDynamicLs) { + const bootSettings = loadSettings(); + ensureCliStatusLineConfigured({ enabled: bootSettings.enableCliStatusLine !== false }); + if (allowDynamicLs && bootSettings.accountSwitchRiskAccepted === true) { setTimeout(() => { void warmAccountPublicListCache(); }, 80).unref?.(); diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 2964347..fc649df 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -169,6 +169,7 @@ export const TRAJECTORY_DB_FILE = join(DATA_DIR, 'trajectory_store.sqlite'); export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json'); export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json'); export const QUOTA_RESERVATION_STATE_FILE = join(DATA_DIR, 'quota_reservation_state.json'); +export const ACCOUNT_QUOTA_HISTORY_FILE = join(DATA_DIR, 'account_quota_history.json'); /** * 本地对话记录目录、脑图日志目录、守护发现目录与跨端深层统计缓存路径候选列表(联合覆盖 Desktop / CLI / IDE)。 diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index b89a792..2ed5ad6 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -169,6 +169,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS, experimentalQuotaReservation: true, accountQuotaRefreshMinutes: DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, + accountSwitchRiskAccepted: false, contextWindowRiskAccepted: false, contextWindowMainEnabled: true, contextWindowSwarmEnabled: false, @@ -256,6 +257,7 @@ export function normalizeFullSettings(rawInput) { accountQuotaRefreshMinutes: normalizeAccountQuotaRefreshMinutes( safeRaw.accountQuotaRefreshMinutes ), + accountSwitchRiskAccepted: safeRaw.accountSwitchRiskAccepted === true, contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true, contextWindowMainEnabled: safeRaw.contextWindowMainEnabled !== false, contextWindowSwarmEnabled: safeRaw.contextWindowSwarmEnabled === true, diff --git a/sidecars/panel/backend/sidecar-worker.mjs b/sidecars/panel/backend/sidecar-worker.mjs index 8923212..a49230a 100644 --- a/sidecars/panel/backend/sidecar-worker.mjs +++ b/sidecars/panel/backend/sidecar-worker.mjs @@ -14,6 +14,7 @@ import { dispatchBridgeApiRequest, } from './api-actions.mjs'; import { computeRuntimeCodeVersion } from './config.mjs'; +import { flushAccountQuotaHistoryNow } from './account-quota-history.mjs'; import { flushAllEndpointCachesNow } from './endpoint-registry.mjs'; let shuttingDown = false; @@ -52,6 +53,7 @@ async function gracefulStop() { shuttingDown = true; clearInterval(driftWatchTimer); try { + flushAccountQuotaHistoryNow(); flushAllEndpointCachesNow(); } catch { // Ignore cache flush errors diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 4be4357..f4e0974 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 { recordAccountQuotaSnapshot } from './account-quota-history.mjs'; import { updatePoolQuotaReservationEstimates } from './quota-reservation.mjs'; import { getDefaultCloudCodeProxyStatus } from './cloudcode-proxy.mjs'; import { getDefaultWindowBridgeStatus } from './window-bridge.mjs'; @@ -2293,6 +2294,20 @@ export async function buildTelemetryPayloadInternal( const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; return (order[a.family] ?? 99) - (order[b.family] ?? 99); }); + if ( + !isRemote && + accountStatus === 'signedIn' && + userStatus?.email && + officialQuotaInfo?.data && + !officialQuotaInfo.isStale + ) { + recordAccountQuotaSnapshot( + userStatus.email, + sortedQuotaPools, + officialQuotaInfo.fetchedAtMs || Date.now(), + { isActiveHost: true } + ); + } const weeklyCapacityEstimate = buildWeeklyCapacityEstimate({ sortedPools: sortedQuotaPools, isCustomWeeklyMode, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index fe7191d..c37c1f1 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index cb2a1ea..4c7cb2c 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -628,6 +628,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/components/widgets/MetricMatrixWidget.js', 'src/components/widgets/ContextWindowWidget.js', 'src/components/widgets/QuotaPoolsWidget.js', + 'src/components/widgets/AccountQuotaTrendCard.js', 'src/components/widgets/LiveActivityWidget.js', 'src/registries/widgetRegistry.js', 'src/registries/stepColumnRegistry.js', diff --git a/sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js b/sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js new file mode 100644 index 0000000..bd07d2b --- /dev/null +++ b/sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js @@ -0,0 +1,1084 @@ +/** + * @fileoverview Per-account quota remaining-% trajectory chart (`AccountQuotaTrendCard.js`). + * Full-bleed edge-to-edge plot (`x = 1 .. viewW - 1`), X-axis clamped to earliest recorded + * sample when history is shorter than the selected preset, and adaptive integer Y-scale so + * real quota movements never compress into a tiny corner with wasted whitespace. + */ + +import { defineComponent } from '../../core/component.js'; +import { + h, + patchAttr, + patchClasses, + patchKeyedList, + patchStyleVar, + patchText, +} from '../../core/domPatch.js'; +import { formatDateSpanBadge } from '../../core/formatters.js'; +import { SVG_NS, createSvgIcon } from '../../icons/SvgIcon.js'; +import { getEffectiveLocale, t } from '../../i18n/index.js'; +import { CustomDateTimePicker } from '../ui/CustomDateTimePicker.js'; +import { CustomSelect } from '../ui/CustomSelect.js'; +import { SegmentedControl } from '../ui/SegmentedControl.js'; + +const POOL_COLORS = Object.freeze({ + Gemini: 'var(--accent-primary)', + 'Claude & GPT': 'var(--metric-ok)', + Argon: 'var(--ctx-thinking)', + Carbon: 'var(--metric-warn)', +}); + +const POOL_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; + +let quotaChartUid = 0; + +function floorMinute(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(0, 0); + return d.getTime(); +} + +function ceilMinute(ms) { + const n = Number(ms); + if (!(n > 0)) return 0; + const d = new Date(n); + d.setSeconds(59, 999); + return d.getTime(); +} + +function pad2(n) { + return String(n).padStart(2, '0'); +} + +function formatAxisTickTime(ms, spanMs) { + const d = new Date(ms); + const hm = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; + if (spanMs <= 36 * 3600_000) { + return hm; + } + const md = `${d.getMonth() + 1}/${pad2(d.getDate())}`; + if (spanMs <= 7 * 86400_000) { + return `${md} ${pad2(d.getHours())}h`; + } + return md; +} + +function formatHoverTimestamp(ms) { + const d = new Date(ms); + return `${d.getMonth() + 1}/${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; +} + +function buildHorizontalTangentSpline(pts) { + if (pts.length === 0) return ''; + if (pts.length === 1) return `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`; + let d = `M ${pts[0].x.toFixed(1)} ${pts[0].y.toFixed(1)}`; + for (let i = 0; i < pts.length - 1; i++) { + const p0 = pts[i]; + const p1 = pts[i + 1]; + const dx = (p1.x - p0.x) * 0.38; + d += ` C ${(p0.x + dx).toFixed(1)} ${p0.y.toFixed(1)}, ${(p1.x - dx).toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; + } + return d; +} + +/** + * Computes tight, integer-aligned `[yMin, yMid, yMax]` bounds (`0..100%`) around + * observed `[dataMin, dataMax]` so small-to-moderate quota changes use the full + * vertical canvas instead of leaving 80%+ empty bottom space. + */ +function computeAdaptiveQuotaScale(dataMin, dataMax) { + const lo = Math.max(0, Math.min(100, Number.isFinite(dataMin) ? dataMin : 0)); + const hi = Math.max(lo, Math.min(100, Number.isFinite(dataMax) ? dataMax : 100)); + const rawSpan = hi - lo; + const pad = Math.max(1.5, rawSpan * 0.14); + + let yMax = hi >= 98.5 ? 100 : Math.min(100, Math.ceil((hi + pad) / 10) * 10); + let yMin = lo <= 2 ? 0 : Math.max(0, Math.floor((lo - pad) / 10) * 10); + + if (yMax - yMin < 10) { + if (yMax >= 100) { + yMax = 100; + yMin = 90; + } else if (yMin <= 0) { + yMin = 0; + yMax = 10; + } else { + yMin = Math.max(0, yMax - 10); + } + } + // Ensure `(yMax - yMin)` is even so midpoint tick is always an exact integer + if ((yMax - yMin) % 2 !== 0) { + if (yMin > 0) yMin -= 1; + else if (yMax < 100) yMax += 1; + } + const yMid = Math.round((yMin + yMax) / 2); + return { yMin, yMid, yMax, span: Math.max(1, yMax - yMin) }; +} + +const IMPULSE_GLITCH_MAX_SPAN_MS = 20 * 60_000; +const IMPULSE_GLITCH_MIN_JUMP_PCT = 3; +const IMPULSE_GLITCH_MAX_NEIGHBOR_DIFF_PCT = 1.2; +const CYCLE_RESET_JUMP_MIN_PCT = 3.5; + +function stripIsolatedImpulseSpikes(pts) { + if (pts.length < 3) return pts; + const out = pts.slice(); + let i = 1; + while (i < out.length - 1) { + const prev = out[i - 1]; + const cur = out[i]; + const next = out[i + 1]; + const spanMs = next.ts - prev.ts; + if ( + spanMs >= 0 && + spanMs <= IMPULSE_GLITCH_MAX_SPAN_MS && + cur.val - prev.val >= IMPULSE_GLITCH_MIN_JUMP_PCT && + cur.val - next.val >= IMPULSE_GLITCH_MIN_JUMP_PCT && + Math.abs(next.val - prev.val) <= IMPULSE_GLITCH_MAX_NEIGHBOR_DIFF_PCT + ) { + out.splice(i, 1); + if (i > 1) i -= 1; + continue; + } + i += 1; + } + return out; +} + +export function resolveQuotaWindowBounds({ + pools, + selectedRange, + selectedWin, + selectedPool, + customStartMs = 0, + customEndMs = 0, + nowMs = Date.now(), +}) { + if (selectedRange === 'custom') { + return { + startMs: Math.min(customStartMs, customEndMs), + endMs: Math.max(customStartMs, customEndMs), + }; + } + if (selectedRange === 'today') { + const d = new Date(nowMs); + d.setHours(0, 0, 0, 0); + return { startMs: d.getTime(), endMs: nowMs }; + } + if (selectedRange === '24h') return { startMs: nowMs - 24 * 3600_000, endMs: nowMs }; + if (selectedRange === '7d') return { startMs: nowMs - 7 * 86400_000, endMs: nowMs }; + if (selectedRange === '14d') return { startMs: nowMs - 14 * 86400_000, endMs: nowMs }; + if (selectedRange === '30d') return { startMs: nowMs - 30 * 86400_000, endMs: nowMs }; + if (selectedRange === 'all') { + let minTs = Infinity; + for (const p of pools) { + for (const pt of p.points) { + if (pt[0] > 0 && pt[0] < minTs) minTs = pt[0]; + } + } + const safeStart = + Number.isFinite(minTs) && minTs < nowMs - 60_000 ? minTs : nowMs - 5 * 3600_000; + return { startMs: safeStart, endMs: nowMs }; + } + + const targetPools = + selectedPool !== 'all' ? pools.filter((p) => p.poolKey === selectedPool) : pools; + const refPools = targetPools.length ? targetPools : pools; + const isWeekly = selectedWin === 'weekly'; + const winDurationMs = isWeekly ? 7 * 86400_000 : 5 * 3600_000; + + let activeMinResetMs = Infinity; + let anyMinResetMs = Infinity; + for (const p of refPools) { + const rMs = isWeekly ? p.resetWeeklyMs : p.reset5hMs; + const liveVal = isWeekly ? p.liveWk : p.live5h; + if (!(rMs > nowMs)) continue; + if (rMs < anyMinResetMs) anyMinResetMs = rMs; + if (liveVal !== null && liveVal !== undefined && liveVal < 99.95 && rMs < activeMinResetMs) { + activeMinResetMs = rMs; + } + } + const chosenResetMs = Number.isFinite(activeMinResetMs) + ? activeMinResetMs + : Number.isFinite(anyMinResetMs) + ? anyMinResetMs + : 0; + const startMs = chosenResetMs > nowMs ? chosenResetMs - winDurationMs : nowMs - winDurationMs; + return { startMs: Math.min(startMs, nowMs - 60_000), endMs: nowMs }; +} + +/** + * Extracts per-pool trajectories for the requested window, ensuring `'cycle'` mode + * strictly excludes pre-reset points from any previous expired cycle (eliminating + * artificial `84% -> 100%` vertical reset spikes at cycle start). + */ +export function buildQuotaWindowSeries({ + visiblePools, + rawBounds, + selectedRange, + selectedWin, + nowMs = Date.now(), +}) { + const isCycleMode = selectedRange === 'cycle'; + const isWeekly = selectedWin === 'weekly'; + const valIdx = isWeekly ? 2 : 1; + const winDurationMs = isWeekly ? 7 * 86400_000 : 5 * 3600_000; + + const staged = []; + let hasStartAnchor = false; + let earliestInWinTs = Infinity; + + for (const p of visiblePools) { + const cleanedAll = []; + for (let i = 0; i < p.points.length; i++) { + const pt = p.points[i]; + const v = pt[valIdx]; + if (v === null || v === undefined || !Number.isFinite(Number(v))) continue; + cleanedAll.push({ + ts: pt[0], + val: Math.max(0, Math.min(100, Number(v))), + }); + } + const sanitized = stripIsolatedImpulseSpikes(cleanedAll); + if (sanitized.length === 0) continue; + + const pResetMs = isWeekly ? p.resetWeeklyMs : p.reset5hMs; + const pLiveVal = isWeekly ? p.liveWk : p.live5h; + const poolCutoffMs = + isCycleMode && pResetMs > nowMs && pLiveVal !== null && pLiveVal < 99.95 + ? Math.max(rawBounds.startMs, pResetMs - winDurationMs) + : rawBounds.startMs; + + let carryBefore = null; + let inWinPts = []; + for (let i = 0; i < sanitized.length; i++) { + const sp = sanitized[i]; + if (sp.ts <= poolCutoffMs) { + carryBefore = sp; + } else if (sp.ts <= rawBounds.endMs) { + inWinPts.push(sp); + } + } + + // In `'cycle'` mode, `< 99.95%` observations at or before `poolCutoffMs` belong + // to the previous expired cycle and must never carry forward into the new cycle. + if (isCycleMode && carryBefore && carryBefore.val < 99.95) { + carryBefore = null; + } + + let hadResetInWindow = false; + if (isCycleMode && inWinPts.length >= 2) { + let lastResetIdx = 0; + for (let k = 1; k < inWinPts.length; k++) { + const prev = inWinPts[k - 1].val; + const cur = inWinPts[k].val; + if (cur - prev >= CYCLE_RESET_JUMP_MIN_PCT || (cur >= 99.5 && prev <= 98.5)) { + lastResetIdx = k; + } + } + if (lastResetIdx > 0) { + inWinPts = inWinPts.slice(lastResetIdx); + carryBefore = null; + hadResetInWindow = true; + } + } + + const isMidWindowReset = hadResetInWindow && inWinPts[0].ts - poolCutoffMs > 5 * 60_000; + const anchorsCycleOrigin = + isCycleMode && + !isMidWindowReset && + !carryBefore && + inWinPts.length > 0 && + inWinPts[0].ts - poolCutoffMs <= 3 * 60_000; + + if (carryBefore || (anchorsCycleOrigin && poolCutoffMs <= rawBounds.startMs + 5000)) { + hasStartAnchor = true; + } + if (inWinPts.length > 0 && inWinPts[0].ts < earliestInWinTs) { + earliestInWinTs = inWinPts[0].ts; + } + + staged.push({ + pool: p, + poolCutoffMs, + carryBefore, + inWinPts, + isMidWindowReset, + anchorsCycleOrigin, + }); + } + + let plottedStartMs = rawBounds.startMs; + if ( + !hasStartAnchor && + selectedRange !== 'custom' && + Number.isFinite(earliestInWinTs) && + earliestInWinTs > rawBounds.startMs + ) { + plottedStartMs = + rawBounds.endMs - earliestInWinTs >= 60_000 + ? earliestInWinTs + : Math.max(rawBounds.startMs, rawBounds.endMs - 5 * 60_000); + } + const plottedEndMs = Math.max(plottedStartMs + 60_000, rawBounds.endMs); + + const rawBuilt = []; + let dataMin = Infinity; + let dataMax = -Infinity; + + for (const item of staged) { + const { pool, poolCutoffMs, carryBefore, inWinPts, isMidWindowReset, anchorsCycleOrigin } = item; + const seriesPts = []; + const anchorStartTs = Math.max(plottedStartMs, poolCutoffMs); + + if (carryBefore) { + seriesPts.push({ ts: anchorStartTs, val: carryBefore.val }); + } else if (anchorsCycleOrigin) { + const originVal = Math.max(100, inWinPts[0].val); + if (inWinPts[0].ts > anchorStartTs) { + seriesPts.push({ ts: anchorStartTs, val: Math.min(100, originVal) }); + } + } else if ( + !isMidWindowReset && + inWinPts.length > 0 && + inWinPts[0].ts > plottedStartMs && + (inWinPts.length === 1 || inWinPts[0].val >= 99.95) + ) { + seriesPts.push({ ts: plottedStartMs, val: inWinPts[0].val }); + } + + for (let i = 0; i < inWinPts.length; i++) { + const vp = inWinPts[i]; + if (vp.ts >= plottedStartMs) { + seriesPts.push(vp); + } + } + + if (seriesPts.length > 0 && plottedEndMs <= nowMs + 60_000) { + const tail = seriesPts[seriesPts.length - 1]; + const tailEnd = Math.min(plottedEndMs, nowMs); + if (tailEnd > tail.ts + 1000) { + seriesPts.push({ ts: tailEnd, val: tail.val }); + } + } + if (seriesPts.length === 0) continue; + + for (let i = 0; i < seriesPts.length; i++) { + const v = seriesPts[i].val; + if (v < dataMin) dataMin = v; + if (v > dataMax) dataMax = v; + } + rawBuilt.push({ + poolKey: pool.poolKey, + label: pool.label, + color: POOL_COLORS[pool.poolKey] || 'var(--accent-primary)', + rawPoints: seriesPts, + latestVal: seriesPts[seriesPts.length - 1].val, + }); + } + + return { + plottedStartMs, + plottedEndMs, + rawBuilt, + yScale: rawBuilt.length > 0 ? computeAdaptiveQuotaScale(dataMin, dataMax) : null, + }; +} + +function getTimeRangeOptions() { + return [ + { value: 'cycle', label: t('cons.rangeCycle') }, + { value: 'today', label: t('cons.rangeToday') }, + { value: '24h', label: t('cons.range24h') }, + { value: '7d', label: t('cons.range7d') }, + { value: '14d', label: t('cons.range14d') }, + { value: '30d', label: t('cons.range30d') }, + { value: 'all', label: t('cons.rangeAll') }, + { value: 'custom', label: t('cons.rangeCustom') }, + ]; +} + +function getQuotaWindowOptions() { + return [ + { value: '5h', label: t('settings.account.win5h') }, + { value: 'weekly', label: t('settings.account.winWeekly') }, + ]; +} + +export const AccountQuotaTrendCard = defineComponent({ + name: 'AccountQuotaTrendCard', + setup({ onCleanup }) { + const VIEW_H = 184; + const TOP_Y = 18; + const BOTTOM_Y = 166; + const SPAN_Y = BOTTOM_Y - TOP_Y; + const LEFT_X = 1; + const RIGHT_PAD = 1; + + let viewW = 460; + let selectedRange = 'cycle'; + let selectedWin = '5h'; + let selectedPool = 'all'; + let selectedAccountEmail = ''; + + const initNow = Date.now(); + let customStartMs = floorMinute(initNow - 24 * 3600_000); + let customEndMs = ceilMinute(initNow); + let draftStartMs = customStartMs; + let draftEndMs = customEndMs; + + let latestState = { + activeEmail: '', + activePools: [], + riskAccepted: false, + accounts: [], + savedQuotas: new Map(), + quotaHistory: {}, + }; + + let plottedSeries = []; + let plottedStartMs = 0; + let plottedEndMs = 0; + let plottedYScale = { yMin: 0, yMid: 50, yMax: 100, span: 100 }; + + const cardTitleText = h('span', { text: t('settings.account.trendTitle') }); + const spanBadgeEl = h('span', { className: 'cons-badge text-mono', text: '' }); + + const accountSelect = CustomSelect({ + className: 'cons-cycle-pool-select account-trend-email-select', + modelValue: '', + options: [], + onUpdateModelValue: (val) => { + selectedAccountEmail = String(val || '').trim().toLowerCase(); + renderChart(); + }, + }); + patchAttr(accountSelect.el, 'hidden', true); + + const poolSelect = CustomSelect({ + className: 'cons-cycle-pool-select', + modelValue: 'all', + options: [{ value: 'all', label: t('cons.cyclePoolAll') }], + onUpdateModelValue: (val) => { + selectedPool = val || 'all'; + renderChart(); + }, + }); + + const winSwitch = SegmentedControl({ + ariaLabel: t('settings.account.trendWinAria'), + modelValue: selectedWin, + options: getQuotaWindowOptions(), + onUpdateModelValue: (val) => { + selectedWin = val === 'weekly' ? 'weekly' : '5h'; + winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); + renderChart(); + }, + }); + + const rangeSwitch = SegmentedControl({ + ariaLabel: t('cons.rangeAria'), + modelValue: selectedRange, + options: getTimeRangeOptions(), + onUpdateModelValue: (nextRange) => { + selectedRange = nextRange || 'cycle'; + if (selectedRange === 'custom') { + startPicker.setValue(draftStartMs); + endPicker.setValue(draftEndMs); + } + rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); + renderChart(); + }, + }); + + const startPicker = CustomDateTimePicker({ + modelValue: draftStartMs, + onUpdateModelValue: (ms) => { + draftStartMs = ms; + startPicker.setValue(ms); + }, + }); + const endPicker = CustomDateTimePicker({ + modelValue: draftEndMs, + onUpdateModelValue: (ms) => { + draftEndMs = ms; + endPicker.setValue(ms); + }, + }); + const applyCustomLabel = h('span', { text: t('cons.applyFilter') }); + const applyCustomBtn = h( + 'button', + { + type: 'button', + className: 'btn-primary', + onClick: () => { + const s = Number(draftStartMs || 0); + const e = Number(draftEndMs || 0); + const lo = floorMinute(s > 0 && e > 0 ? Math.min(s, e) : s); + const hi = ceilMinute(s > 0 && e > 0 ? Math.max(s, e) : e); + if (lo > 0 && hi > lo) { + customStartMs = lo; + customEndMs = hi; + draftStartMs = lo; + draftEndMs = hi; + startPicker.setValue(lo); + endPicker.setValue(hi); + renderChart(); + } + }, + }, + [createSvgIcon('check', { size: 12 }), applyCustomLabel] + ); + const rangeToEl = h('span', { className: 'text-muted', text: t('cons.rangeTo') }); + const customRangeBar = h('div', { className: 'cons-custom-range-bar', hidden: true }, [ + startPicker.el, + rangeToEl, + endPicker.el, + applyCustomBtn, + ]); + + // --- Full-Bleed Edge-to-Edge 184px SVG Stage (reusing TrendAreaChart `.trend-svg`) --- + const uid = ++quotaChartUid; + const gradId = `acct-quota-grad-${uid}`; + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); + svg.setAttribute('class', 'trend-svg'); + svg.setAttribute('aria-hidden', 'true'); + + const defs = document.createElementNS(SVG_NS, 'defs'); + const grad = document.createElementNS(SVG_NS, 'linearGradient'); + grad.setAttribute('id', gradId); + grad.setAttribute('x1', '0'); + grad.setAttribute('y1', '0'); + grad.setAttribute('x2', '0'); + grad.setAttribute('y2', '1'); + const stopTop = document.createElementNS(SVG_NS, 'stop'); + stopTop.setAttribute('offset', '0%'); + stopTop.setAttribute('stop-color', 'var(--accent-primary)'); + stopTop.setAttribute('stop-opacity', '0.24'); + const stopBot = document.createElementNS(SVG_NS, 'stop'); + stopBot.setAttribute('offset', '100%'); + stopBot.setAttribute('stop-color', 'var(--accent-primary)'); + stopBot.setAttribute('stop-opacity', '0.0'); + grad.appendChild(stopTop); + grad.appendChild(stopBot); + defs.appendChild(grad); + svg.appendChild(defs); + + const gridGroup = document.createElementNS(SVG_NS, 'g'); + gridGroup.setAttribute('class', 'trend-grid'); + const gridRowSpecs = [ + { y: TOP_Y, dy: 3, labeled: true }, + { y: Math.round(TOP_Y + SPAN_Y * 0.25), dy: 0, labeled: false }, + { y: Math.round(TOP_Y + SPAN_Y * 0.5), dy: 3, labeled: true }, + { y: Math.round(TOP_Y + SPAN_Y * 0.75), dy: 0, labeled: false }, + { y: BOTTOM_Y, dy: -3, labeled: true }, + ]; + const gridLines = []; + const yLabels = []; + for (const row of gridRowSpecs) { + const line = document.createElementNS(SVG_NS, 'line'); + line.setAttribute('x1', '0'); + line.setAttribute('y1', String(row.y)); + line.setAttribute('x2', String(viewW)); + line.setAttribute('y2', String(row.y)); + gridGroup.appendChild(line); + gridLines.push(line); + + if (row.labeled) { + const lbl = document.createElementNS(SVG_NS, 'text'); + lbl.setAttribute('class', 'sstep-axis-label is-y-inline'); + lbl.setAttribute('x', '3'); + lbl.setAttribute('y', String(row.y + row.dy)); + lbl.setAttribute('text-anchor', 'start'); + yLabels.push(lbl); + } + } + svg.appendChild(gridGroup); + + const seriesGroup = document.createElementNS(SVG_NS, 'g'); + svg.appendChild(seriesGroup); + + // Append inline Y labels above series fills so halo stroke keeps text crisp + const yLabelOverlay = document.createElementNS(SVG_NS, 'g'); + for (const lbl of yLabels) { + yLabelOverlay.appendChild(lbl); + } + svg.appendChild(yLabelOverlay); + + const hoverLine = document.createElementNS(SVG_NS, 'line'); + hoverLine.setAttribute('class', 'trend-hover-line'); + hoverLine.setAttribute('y1', String(TOP_Y)); + hoverLine.setAttribute('y2', String(BOTTOM_Y)); + hoverLine.setAttribute('hidden', ''); + svg.appendChild(hoverLine); + + const hoverDotsGroup = document.createElementNS(SVG_NS, 'g'); + hoverDotsGroup.setAttribute('hidden', ''); + svg.appendChild(hoverDotsGroup); + + const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' }); + const tipWinEl = h('span', { className: 'trend-tip-calls' }); + const tipRowsHost = h('div', { className: 'account-trend-tip-rows' }); + const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [ + h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipWinEl]), + tipRowsHost, + ]); + + const xAxisEl = h('div', { className: 'trend-x-axis' }); + const legendRowEl = h('div', { className: 'account-trend-legend' }); + const emptyStateEl = h('div', { className: 'smodel-empty settings-action-desc', hidden: true }); + + const plotStage = h( + 'div', + { + className: 'trend-plot-stage', + onPointermove: handlePointerMove, + onPointerleave: hideHover, + }, + [svg, tooltipEl] + ); + const chartWrap = h('div', { className: 'trend-chart-wrap' }, [ + plotStage, + xAxisEl, + legendRowEl, + ]); + + const rootEl = h('section', { className: 'panel account-quota-trend-panel' }, [ + h('div', { className: 'panel-header account-trend-toprow' }, [ + h('span', { className: 'panel-title cons-overview-title' }, [ + createSvgIcon('pulse', { size: 13 }), + cardTitleText, + accountSelect.el, + poolSelect.el, + ]), + winSwitch.el, + ]), + h('div', { className: 'panel-header cons-overview-head account-trend-subbar' }, [ + spanBadgeEl, + h('div', { className: 'cons-overview-controls' }, [rangeSwitch.el]), + ]), + customRangeBar, + chartWrap, + emptyStateEl, + ]); + + function valueToSvgY(val) { + const clamped = Math.max(plottedYScale.yMin, Math.min(plottedYScale.yMax, val)); + return BOTTOM_Y - ((clamped - plottedYScale.yMin) / plottedYScale.span) * SPAN_Y; + } + + function hideHover() { + hoverLine.setAttribute('hidden', ''); + hoverDotsGroup.setAttribute('hidden', ''); + patchAttr(tooltipEl, 'hidden', true); + } + + function sampleSeriesValueAt(points, targetMs) { + if (!points.length) return null; + if (targetMs < points[0].ts - 1000) return null; + if (targetMs <= points[0].ts) return points[0].val; + const last = points[points.length - 1]; + if (targetMs > last.ts + 60_000) return null; + if (targetMs >= last.ts) return last.val; + let lo = 0; + let hi = points.length - 1; + while (lo + 1 < hi) { + const mid = (lo + hi) >> 1; + if (points[mid].ts <= targetMs) lo = mid; + else hi = mid; + } + const a = points[lo]; + const b = points[hi]; + const span = b.ts - a.ts; + if (span <= 0) return b.val; + return a.val + (b.val - a.val) * ((targetMs - a.ts) / span); + } + + function handlePointerMove(ev) { + if (!plottedSeries.length || !(plottedEndMs > plottedStartMs)) { + hideHover(); + return; + } + const rect = svg.getBoundingClientRect?.(); + const widthPx = Number(rect?.width || viewW); + if (!(widthPx > 0)) return; + const offsetX = Number(ev.clientX || 0) - Number(rect?.left || 0); + const svgX = (offsetX / widthPx) * viewW; + const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); + const u = Math.max(0, Math.min(1, (svgX - LEFT_X) / plotW)); + const clampedX = LEFT_X + u * plotW; + const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs)); + + hoverLine.setAttribute('x1', clampedX.toFixed(1)); + hoverLine.setAttribute('x2', clampedX.toFixed(1)); + + while (hoverDotsGroup.firstChild) hoverDotsGroup.removeChild(hoverDotsGroup.firstChild); + const tipItems = []; + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + const val = sampleSeriesValueAt(s.rawPoints, targetMs); + if (val === null) continue; + const y = valueToSvgY(val); + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', clampedX.toFixed(1)); + dot.setAttribute('cy', y.toFixed(1)); + dot.setAttribute('r', '3.2'); + dot.setAttribute('fill', 'var(--surface-panel)'); + dot.setAttribute('stroke', s.color); + dot.setAttribute('stroke-width', '1.8'); + hoverDotsGroup.appendChild(dot); + tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val }); + } + if (tipItems.length === 0) { + hideHover(); + return; + } + hoverLine.removeAttribute('hidden'); + hoverDotsGroup.removeAttribute('hidden'); + + patchText(tipTimeEl, formatHoverTimestamp(targetMs)); + patchText(tipWinEl, t(selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h')); + patchKeyedList(tipRowsHost, tipItems, { + keyFn: (it) => it.key, + sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`, + createRow: () => { + const sw = h('span', { className: 'dot-swatch' }); + const nm = h('span', { className: 'account-trend-tip-name' }); + const vl = h('strong', { className: 'text-mono' }); + const row = h('div', { className: 'account-trend-tip-row' }, [ + h('span', { className: 'legend-left' }, [sw, nm]), + vl, + ]); + return { el: row, refs: { sw, nm, vl } }; + }, + updateRow: (r, it) => { + r.sw.style.background = it.color; + patchText(r.nm, it.label); + patchText(r.vl, `${+it.val.toFixed(1)}%`); + }, + }); + + const pctX = (clampedX / viewW) * 100; + const shift = pctX < 24 ? '0%' : pctX > 76 ? '-100%' : '-50%'; + patchStyleVar(tooltipEl, '--tip-x', `${pctX.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-shift', shift); + patchAttr(tooltipEl, 'hidden', false); + } + + function resolveTargetAccountEmail() { + const { activeEmail, riskAccepted, accounts } = latestState; + if (!riskAccepted) { + return activeEmail || ''; + } + const candidates = []; + if (activeEmail) candidates.push(activeEmail); + for (const addr of accounts) { + if (addr && !candidates.includes(addr)) candidates.push(addr); + } + if (selectedAccountEmail && candidates.includes(selectedAccountEmail)) { + return selectedAccountEmail; + } + selectedAccountEmail = candidates[0] || ''; + return selectedAccountEmail; + } + + function buildMergedPoolsForEmail(email, nowMs) { + const histPools = latestState.quotaHistory?.[email]?.pools || {}; + const livePools = + email && email === latestState.activeEmail + ? latestState.activePools || [] + : latestState.savedQuotas.get(email)?.pools || []; + + const merged = new Map(); + for (const [pk, hEntry] of Object.entries(histPools)) { + merged.set(pk, { + poolKey: pk, + label: hEntry.label || pk, + reset5hMs: Number(hEntry.reset5hMs) || 0, + resetWeeklyMs: Number(hEntry.resetWeeklyMs) || 0, + points: Array.isArray(hEntry.points) ? hEntry.points.slice() : [], + live5h: null, + liveWk: null, + }); + } + + for (const lp of livePools) { + const pk = String(lp?.poolKey || lp?.family || lp?.poolLabel || '').trim(); + if (!pk || pk === 'Unknown') continue; + let item = merged.get(pk); + if (!item) { + item = { + poolKey: pk, + label: String(lp?.poolLabel || pk), + reset5hMs: 0, + resetWeeklyMs: 0, + points: [], + live5h: null, + liveWk: null, + }; + merged.set(pk, item); + } + if (lp?.poolLabel) item.label = String(lp.poolLabel); + const r5Ms = Date.parse(lp?.resetTime || ''); + const rWMs = Date.parse(lp?.weeklyResetTime || ''); + if (Number.isFinite(r5Ms) && r5Ms > 0) item.reset5hMs = r5Ms; + if (Number.isFinite(rWMs) && rWMs > 0) item.resetWeeklyMs = rWMs; + if (Number.isFinite(lp?.remainingPct)) item.live5h = +Number(lp.remainingPct).toFixed(1); + if (Number.isFinite(lp?.weeklyRemainingPct)) { + item.liveWk = +Number(lp.weeklyRemainingPct).toFixed(1); + } + if (item.live5h !== null || item.liveWk !== null) { + const last = item.points[item.points.length - 1]; + if (!last || nowMs >= last[0]) { + item.points.push([ + nowMs, + item.live5h ?? (last ? last[1] : null), + item.liveWk ?? (last ? last[2] : null), + ]); + } + } + } + + return Array.from(merged.values()).sort( + (a, b) => + (POOL_ORDER.indexOf(a.poolKey) === -1 ? 99 : POOL_ORDER.indexOf(a.poolKey)) - + (POOL_ORDER.indexOf(b.poolKey) === -1 ? 99 : POOL_ORDER.indexOf(b.poolKey)) + ); + } + + function renderChart() { + hideHover(); + const nowMs = Date.now(); + void getEffectiveLocale(); + + patchText(cardTitleText, t('settings.account.trendTitle')); + patchText(rangeToEl, t('cons.rangeTo')); + patchText(applyCustomLabel, t('cons.applyFilter')); + winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); + rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); + patchAttr(customRangeBar, 'hidden', selectedRange !== 'custom'); + + const targetEmail = resolveTargetAccountEmail(); + const candidateEmails = []; + if (latestState.activeEmail) candidateEmails.push(latestState.activeEmail); + if (latestState.riskAccepted) { + for (const addr of latestState.accounts) { + if (addr && !candidateEmails.includes(addr)) candidateEmails.push(addr); + } + } + const showAccountPicker = latestState.riskAccepted && candidateEmails.length > 1; + patchAttr(accountSelect.el, 'hidden', !showAccountPicker); + if (showAccountPicker) { + accountSelect.setProps({ + modelValue: targetEmail, + options: candidateEmails.map((addr) => ({ + value: addr, + label: addr.split('@')[0] || addr, + title: addr, + })), + }); + } + + const mergedPools = targetEmail ? buildMergedPoolsForEmail(targetEmail, nowMs) : []; + if (selectedPool !== 'all' && !mergedPools.some((p) => p.poolKey === selectedPool)) { + selectedPool = 'all'; + } + const poolOpts = [ + { + value: 'all', + label: t('cons.cyclePoolAll'), + }, + ...mergedPools.map((p) => ({ + value: p.poolKey, + label: p.poolKey === 'Claude & GPT' ? 'Claude/GPT' : p.label, + title: p.label, + })), + ]; + poolSelect.setProps({ modelValue: selectedPool, options: poolOpts }); + patchAttr(poolSelect.el, 'hidden', mergedPools.length <= 1); + + const rawBounds = resolveQuotaWindowBounds({ + pools: mergedPools, + selectedRange, + selectedWin, + selectedPool, + customStartMs, + customEndMs, + nowMs, + }); + const visiblePools = + selectedPool === 'all' + ? mergedPools + : mergedPools.filter((p) => p.poolKey === selectedPool); + + const built = buildQuotaWindowSeries({ + visiblePools, + rawBounds, + selectedRange, + selectedWin, + nowMs, + }); + plottedStartMs = built.plottedStartMs; + plottedEndMs = built.plottedEndMs; + const spanMs = plottedEndMs - plottedStartMs; + patchText(spanBadgeEl, formatDateSpanBadge(plottedStartMs, plottedEndMs)); + + const rawBuilt = built.rawBuilt; + const hasPlot = rawBuilt.length > 0; + patchAttr(chartWrap, 'hidden', !hasPlot); + patchAttr(emptyStateEl, 'hidden', hasPlot); + if (!hasPlot) { + plottedSeries = []; + patchText(emptyStateEl, t('settings.account.trendEmpty')); + return; + } + + plottedYScale = built.yScale; + yLabels[0].textContent = `${plottedYScale.yMax}%`; + yLabels[1].textContent = `${plottedYScale.yMid}%`; + yLabels[2].textContent = `${plottedYScale.yMin}%`; + + const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); + svg.setAttribute('viewBox', `0 0 ${viewW} ${VIEW_H}`); + for (const gl of gridLines) { + gl.setAttribute('x2', String(viewW)); + } + + plottedSeries = rawBuilt.map((rb) => ({ + ...rb, + svgPts: rb.rawPoints.map((sp) => { + const u = Math.max(0, Math.min(1, (sp.ts - plottedStartMs) / spanMs)); + return { + x: LEFT_X + u * plotW, + y: valueToSvgY(sp.val), + val: sp.val, + ts: sp.ts, + }; + }), + })); + + while (seriesGroup.firstChild) seriesGroup.removeChild(seriesGroup.firstChild); + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + const lineD = buildHorizontalTangentSpline(s.svgPts); + if (s.svgPts.length >= 2) { + const first = s.svgPts[0]; + const last = s.svgPts[s.svgPts.length - 1]; + const areaEl = document.createElementNS(SVG_NS, 'path'); + areaEl.setAttribute( + 'd', + `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z` + ); + if (plottedSeries.length === 1) { + stopTop.setAttribute('stop-color', s.color); + stopBot.setAttribute('stop-color', s.color); + areaEl.setAttribute('fill', `url(#${gradId})`); + } else { + areaEl.setAttribute('class', 'sstep-multi-area'); + areaEl.style.setProperty('--sstep-series-color', s.color); + } + seriesGroup.appendChild(areaEl); + } + const pathEl = document.createElementNS(SVG_NS, 'path'); + pathEl.setAttribute('d', lineD); + pathEl.setAttribute('fill', 'none'); + pathEl.setAttribute('stroke', s.color); + pathEl.setAttribute('stroke-width', '1.9'); + pathEl.setAttribute('stroke-linecap', 'round'); + seriesGroup.appendChild(pathEl); + + const endPt = s.svgPts[s.svgPts.length - 1]; + const endDot = document.createElementNS(SVG_NS, 'circle'); + endDot.setAttribute('cx', endPt.x.toFixed(1)); + endDot.setAttribute('cy', endPt.y.toFixed(1)); + endDot.setAttribute('r', '2.7'); + endDot.setAttribute('fill', s.color); + seriesGroup.appendChild(endDot); + } + + // Edge-to-edge X-axis ticks (`0% .. 100%`) + const tickCount = 5; + const ticks = []; + for (let k = 0; k < tickCount; k++) { + const ratio = k / (tickCount - 1); + const tickMs = Math.round(plottedStartMs + ratio * spanMs); + const leftPct = ratio * 100; + ticks.push({ + idx: k, + leftPct, + label: formatAxisTickTime(tickMs, spanMs), + edge: k === 0 ? 'start' : k === tickCount - 1 ? 'end' : '', + }); + } + patchKeyedList(xAxisEl, ticks, { + keyFn: (tk) => tk.idx, + sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}`, + createRow: () => { + const el = h('span', { className: 'trend-x-tick text-mono' }); + return { el, refs: { el } }; + }, + updateRow: (r, tk) => { + patchText(r.el, tk.label); + patchStyleVar(r.el, '--tick-x', `${tk.leftPct.toFixed(2)}%`); + patchClasses(r.el, { + 'is-start': tk.edge === 'start', + 'is-end': tk.edge === 'end', + }); + }, + }); + + patchKeyedList(legendRowEl, plottedSeries, { + keyFn: (s) => s.poolKey, + sigFn: (s) => `${s.label}:${s.latestVal.toFixed(1)}:${s.color}`, + createRow: () => { + const sw = h('span', { className: 'dot-swatch' }); + const nm = h('span', { className: 'account-trend-leg-name' }); + const vl = h('strong', { className: 'text-mono' }); + const el = h('span', { className: 'account-trend-leg-item' }, [sw, nm, vl]); + return { el, refs: { sw, nm, vl } }; + }, + updateRow: (r, s) => { + r.sw.style.background = s.color; + patchText(r.nm, s.label); + patchText(r.vl, `${+s.latestVal.toFixed(1)}%`); + }, + }); + } + + let resizeObs = null; + if (typeof ResizeObserver === 'function') { + resizeObs = new ResizeObserver((entries) => { + const w = Math.floor(Number(entries?.[0]?.contentRect?.width || 0)); + if (w >= 180 && Math.abs(w - viewW) >= 2) { + viewW = w; + renderChart(); + } + }); + resizeObs.observe(plotStage); + } + + onCleanup(() => { + resizeObs?.disconnect(); + accountSelect.destroy(); + poolSelect.destroy(); + winSwitch.destroy(); + rangeSwitch.destroy(); + startPicker.destroy(); + endPicker.destroy(); + }); + + function update(nextState) { + latestState = { ...latestState, ...nextState }; + renderChart(); + } + + renderChart(); + return { + el: rootEl, + refs: { update, refreshLabels: renderChart }, + }; + }, +}); diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 2aafe9e..92f3d91 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -598,6 +598,13 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.account.passwordRateLimited': 'Too many failed attempts. Wait a moment and try again.', 'settings.account.vaultDecryptFailed': 'Vault decryption check failed.', 'settings.account.invalidActionNonce': 'Security token expired. Please try again.', + 'settings.account.riskNotAccepted': 'Acknowledge the unofficial feature risk warning first.', + 'settings.account.riskBody': 'Google has not authorized importing, storing, or switching Antigravity credentials or polling multi-account quotas in Antigravity App / IDE. Enabling multi-account management may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!', + 'settings.account.trendTitle': 'Quota Trend', + 'settings.account.trendWinAria': 'Quota window selector', + 'settings.account.win5h': '5 Hours', + 'settings.account.winWeekly': 'Weekly', + 'settings.account.trendEmpty': 'No quota history recorded in the selected time range.', 'settings.subTab.aria': 'Preferences category tabs', 'settings.saving': 'Saving…', 'settings.saved': 'Saved', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 26911b4..c594b72 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -599,6 +599,13 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.account.passwordRateLimited': '密码连续输错次数过多,请稍候再试。', 'settings.account.vaultDecryptFailed': '凭证解密校验失败,请确认密码或重置凭证库。', 'settings.account.invalidActionNonce': '安全校验令牌已过期,请重试。', + 'settings.account.riskNotAccepted': '请先确认并接受非官方能力风险提示。', + 'settings.account.riskBody': 'Google 官方并未授权在 Antigravity App / IDE 中通过第三方插件导入、保存、切换账号凭证或后台查询多账号配额。擅自启用可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!', + 'settings.account.trendTitle': '额度变化', + 'settings.account.trendWinAria': '配额窗口切换', + 'settings.account.win5h': '5 小时', + 'settings.account.winWeekly': '每周', + 'settings.account.trendEmpty': '当前时间范围内暂无配额记录。', 'settings.saving': '保存中…', 'settings.saved': '已保存', 'settings.saveFailed': '保存失败', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 355d4aa..709360e 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -662,6 +662,9 @@ export function isEquivalentTelemetry(prev, next) { ) { return false; } + if (Boolean(pSet?.accountSwitchRiskAccepted) !== Boolean(nSet?.accountSwitchRiskAccepted)) { + 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; @@ -1926,6 +1929,9 @@ export async function saveSettingsPatch(patch) { safePatch.accountQuotaRefreshMinutes ); } + if (Object.prototype.hasOwnProperty.call(safePatch, 'accountSwitchRiskAccepted')) { + safePatch.accountSwitchRiskAccepted = Boolean(safePatch.accountSwitchRiskAccepted); + } if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) { safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots); } diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 68f0fe0..e7a6c61 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -646,15 +646,15 @@ } .account-toolbar-panel { - padding: 9px 12px; - gap: 8px; + padding: var(--space-3) var(--space-5); + gap: var(--space-2); } .account-toolbar-row { display: flex; align-items: center; justify-content: space-between; - gap: 8px; + gap: var(--space-2); flex-wrap: wrap; } @@ -662,6 +662,7 @@ .account-toolbar-right { display: inline-flex; align-items: center; + flex-wrap: wrap; gap: 6px; min-width: 0; } @@ -670,32 +671,19 @@ margin-left: auto; } -.account-toolbar-btn { - display: inline-flex; - align-items: center; - gap: 5px; - min-height: calc(25px * var(--ui-font-scale, 1)); - height: auto; +.account-toolbar-panel .btn-primary, +.account-toolbar-panel .btn-secondary { + min-height: calc(26px * var(--ui-font-scale, 1)); padding: 2px 10px; font-size: var(--fs-md); - font-weight: 500; - border-radius: var(--radius-xs); white-space: nowrap; } -.account-toolbar-btn.is-open { +.account-toolbar-panel .btn-secondary.is-open { color: var(--accent-primary); background: var(--accent-primary-soft); } -.account-reload-btn { - width: calc(25px * var(--ui-font-scale, 1)); - height: calc(25px * var(--ui-font-scale, 1)); - padding: 0; - border-radius: var(--radius-xs); - flex-shrink: 0; -} - .account-refresh-select { flex: 0 0 auto; width: auto; @@ -704,24 +692,11 @@ .account-refresh-select .select-trigger { width: auto; - min-height: calc(25px * var(--ui-font-scale, 1)); + min-height: calc(26px * var(--ui-font-scale, 1)); height: auto; padding: 2px 8px; gap: 5px; font-size: var(--fs-sm); - border: 1px solid var(--border-hairline); - border-radius: var(--radius-xs); - background: var(--surface-subtle); -} - -[data-modern-ui="true"] .account-refresh-select .select-trigger { - border: none; - background: var(--modern-surface-subtle); -} - -[data-modern-ui="true"] .account-refresh-select .select-trigger:hover, -[data-modern-ui="true"] .account-refresh-select.is-open .select-trigger { - background: var(--modern-surface-hover); } .account-refresh-select .select-menu { @@ -748,17 +723,18 @@ color: var(--metric-danger); } -.account-status-inline.is-info { - color: var(--text-secondary); -} - .account-import-drawer { display: flex; flex-direction: column; - gap: 5px; + align-items: stretch; + gap: 6px; padding-top: 2px; } +.account-import-drawer > .segmented { + align-self: flex-start; +} + .account-import-row { display: flex; align-items: center; @@ -772,176 +748,20 @@ min-height: calc(26px * var(--ui-font-scale, 1)); } -.account-import-hint { - font-size: var(--fs-xs); - color: var(--text-muted); -} - -.account-unlock-box { - display: flex; - flex-direction: column; - gap: 6px; - padding: 8px 10px; - border-radius: var(--radius-xs); - background: var(--surface-subtle); -} - -.account-unlock-head { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; -} - -.account-unlock-title { - display: inline-flex; - align-items: center; - gap: 6px; - font-size: var(--fs-sm); - color: var(--text-secondary); -} - -.account-unlock-title .svg-icon { - color: var(--metric-warn); - flex-shrink: 0; -} - -.account-link-btn { - padding: 0; - border: none; - background: transparent; - font-size: var(--fs-xs); - color: var(--text-muted); - cursor: pointer; - white-space: nowrap; -} - -.account-link-btn:hover { - color: var(--text-primary); - text-decoration: underline; -} - -.account-reset-row { - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 6px 10px; - padding-top: 4px; -} - -.account-reset-row .settings-action-desc { - flex: 1 1 180px; - font-size: var(--fs-xs); -} - -.account-pwd-tabs { - display: inline-flex; - align-items: center; - align-self: flex-start; - gap: 4px; - padding: 2px; - border-radius: var(--radius-xs); - background: var(--surface-subtle); -} - -.account-pwd-tab { - padding: 2px 8px; - border: none; - border-radius: var(--radius-xs); - background: transparent; - font-size: var(--fs-xs); - font-weight: 500; - color: var(--text-secondary); - cursor: pointer; -} - -.account-pwd-tab.is-active { - background: var(--bg-elevated); - color: var(--text-primary); -} - -.account-card-btn.is-confirm-warn { - color: var(--accent-primary); - background: var(--accent-primary-soft); - font-weight: 600; -} - -.account-confirm-danger-btn { - color: var(--metric-danger); - background: color-mix(in srgb, var(--metric-danger) 12%, transparent); - font-weight: 600; -} - -.account-confirm-danger-btn:hover:not(:disabled) { - background: color-mix(in srgb, var(--metric-danger) 20%, transparent); -} - -.account-flow-strip { - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 6px 10px; - padding: 6px 9px; - border-radius: var(--radius-xs); - background: var(--surface-subtle); - font-size: var(--fs-sm); -} - -.account-flow-strip.is-info { - background: var(--accent-primary-soft); -} - -.account-flow-strip.is-info .account-flow-msg { - color: var(--accent-primary); -} - -.account-flow-strip.is-ok { - background: color-mix(in srgb, var(--metric-ok) 10%, transparent); -} - -.account-flow-strip.is-ok .account-flow-msg { - color: var(--metric-ok); -} - -.account-flow-strip.is-warn { - background: color-mix(in srgb, var(--metric-warn) 10%, transparent); - color: var(--metric-warn); -} - -.account-flow-strip.is-error { - background: color-mix(in srgb, var(--metric-danger) 10%, transparent); -} - -.account-flow-strip.is-error .account-flow-msg { - color: var(--metric-danger); -} - -.account-flow-link { - font-size: var(--fs-sm); - font-weight: 500; - color: var(--accent-primary); - text-decoration: none; - white-space: nowrap; -} - -.account-flow-link:hover { - text-decoration: underline; -} - .account-cards-stack { display: flex; flex-direction: column; gap: var(--space-3); } +/* Optically symmetrical vertical padding: 11px + 3px header leading == 14px bottom bar-to-edge */ .account-card { gap: 10px; - padding: 11px 14px; + padding: 11px var(--space-5) 14px; } .account-card-head { + min-height: calc(22px * var(--ui-font-scale, 1)); gap: 8px; flex-wrap: wrap; } @@ -955,14 +775,10 @@ flex: 1 1 150px; } -.account-active-dot { - background: var(--metric-ok); - box-shadow: 0 0 0 2px color-mix(in srgb, var(--metric-ok) 20%, transparent); -} - .account-card-email { font-size: var(--fs-base); font-weight: 600; + line-height: 1.3; color: var(--text-primary); overflow: hidden; text-overflow: ellipsis; @@ -970,34 +786,6 @@ max-width: 100%; } -.account-tag { - display: inline-flex; - align-items: center; - min-height: calc(18px * var(--ui-font-scale, 1)); - padding: 1px 6px; - font-size: var(--fs-xs); - font-weight: 600; - line-height: 1.2; - border-radius: var(--radius-xs); - border: none; - white-space: nowrap; -} - -.account-tag.is-active { - color: var(--metric-ok); - background: color-mix(in srgb, var(--metric-ok) 12%, transparent); -} - -.account-tag.is-tier { - color: var(--accent-primary); - background: var(--accent-primary-soft); -} - -.account-tag.is-written { - color: var(--metric-warn); - background: color-mix(in srgb, var(--metric-warn) 12%, transparent); -} - .account-card-actions { display: inline-flex; align-items: center; @@ -1006,21 +794,16 @@ margin-left: auto; } -.account-card-btn { - min-height: calc(23px * var(--ui-font-scale, 1)); - height: auto; +.account-card-actions .btn-ghost-sm { + min-height: calc(22px * var(--ui-font-scale, 1)); padding: 1px 8px; - font-size: var(--fs-sm); - font-weight: 500; - border-radius: var(--radius-xs); - white-space: nowrap; } -.account-icon-btn { - width: calc(23px * var(--ui-font-scale, 1)); - height: calc(23px * var(--ui-font-scale, 1)); +.account-card-actions .icon-btn { + width: calc(22px * var(--ui-font-scale, 1)); + height: calc(22px * var(--ui-font-scale, 1)); + min-width: calc(22px * var(--ui-font-scale, 1)); padding: 0; - border-radius: var(--radius-xs); } .account-pools-stack { @@ -1029,18 +812,11 @@ gap: 9px; } -.account-pool-group { - display: flex; - flex-direction: column; - gap: 4px; -} - -.account-pool-name { +.account-pool-label { font-size: var(--fs-xs); font-weight: 600; color: var(--text-muted); line-height: 1.25; - letter-spacing: 0.01em; } .account-pool-meters { @@ -1066,34 +842,61 @@ min-width: 0; } -.account-meter-head { +/* Quota Trend Card minor layout helpers */ +.account-trend-toprow { + gap: var(--space-2); + flex-wrap: wrap; +} + +.account-trend-toprow .cons-cycle-pool-select { + flex: 0 0 auto; +} + +.account-trend-subbar { + gap: 6px 8px; + flex-wrap: wrap; +} + +.account-trend-email-select { + max-width: 156px; +} + +.account-trend-legend { display: flex; - align-items: baseline; - justify-content: space-between; - gap: 6px; - min-width: 0; + align-items: center; + flex-wrap: wrap; + gap: 6px 12px; + padding-top: 2px; } -.settings-account-quota { - font-size: var(--fs-sm); - font-weight: 600; +.account-trend-leg-item { + display: inline-flex; + align-items: center; + gap: 5px; + font-size: var(--fs-xs); + color: var(--text-secondary); +} + +.account-trend-leg-item strong { color: var(--text-primary); - white-space: nowrap; } -.account-meter-reset { - font-size: var(--fs-2xs); - color: var(--text-muted); - white-space: nowrap; - flex-shrink: 0; +.account-trend-tip-rows { + display: flex; + flex-direction: column; + gap: 4px; } -.account-progress-track { - height: 5px; +.account-trend-tip-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + font-size: var(--fs-xs); } .account-empty-panel { - padding: 18px 14px; + padding: 16px var(--space-5); align-items: center; justify-content: center; } diff --git a/sidecars/panel/src/views/settings/SettingsAccountTab.js b/sidecars/panel/src/views/settings/SettingsAccountTab.js index 602ff7f..fe54634 100644 --- a/sidecars/panel/src/views/settings/SettingsAccountTab.js +++ b/sidecars/panel/src/views/settings/SettingsAccountTab.js @@ -1,4 +1,8 @@ -/** @fileoverview Unified multi-account switcher, passphrase vault UI, and per-pool quota cards. */ +/** + * @fileoverview Multi-account switcher, quota trajectory chart, risk gate, and passphrase vault UI. + * Reuses `SegmentedControl`, `CustomSelect`, `AccountQuotaTrendCard`, `.ctx-risk-mask`, + * `.settings-bridge-notice`, `.status-tag`, `.btn-ghost-sm`, `.btn-danger-confirm`, and `.quota-pool-row`. + */ import { defineComponent } from '../../core/component.js'; import { @@ -14,6 +18,8 @@ import { callSidecarApi } from '../../core/httpClient.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { CustomSelect } from '../../components/ui/CustomSelect.js'; +import { SegmentedControl } from '../../components/ui/SegmentedControl.js'; +import { AccountQuotaTrendCard } from '../../components/widgets/AccountQuotaTrendCard.js'; import { formatAccountTierBadge } from '../../components/widgets/QuotaPoolsWidget.js'; import { DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES, @@ -34,7 +40,7 @@ const errors = new Set([ 'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed', 'loginStartFailed', 'loginExchangeFailed', 'loginExpired', 'loginDenied', 'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordMismatch', - 'passwordRateLimited', 'vaultDecryptFailed', 'invalidActionNonce', + 'passwordRateLimited', 'vaultDecryptFailed', 'invalidActionNonce', 'riskNotAccepted', ]); const okToastKeys = new Set([ @@ -55,6 +61,13 @@ function getAccountRefreshOptions() { ]; } +function getPwdModeOptions() { + return [ + { value: 'change', label: t(key('pwdTabChange')) }, + { value: 'disable', label: t(key('pwdTabDisable')) }, + ]; +} + function formatValidCountdown(isoTime) { if (!isoTime) return ''; const ms = Date.parse(isoTime); @@ -84,8 +97,9 @@ function renderQuotaRows(container, quotaPools) { ); patchKeyedList(container, pools, { keyFn: (pool) => pool.poolKey || pool.poolLabel, - sigFn: (pool) => + sigFn: (pool, idx) => JSON.stringify([ + idx > 0, locale, pool.poolLabel, pool.remainingPct, @@ -94,32 +108,39 @@ function renderQuotaRows(container, quotaPools) { pool.weeklyResetTime, ]), createRow: () => { - const poolTitle = h('div', { className: 'account-pool-name' }); + const poolTitle = h('div', { className: 'account-pool-label' }); - const label5h = h('span', { className: 'settings-account-quota text-mono' }); - const reset5h = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const label5h = h('span', { className: 'quota-win-title settings-account-quota text-mono' }); + const reset5h = h('span', { className: 'panel-meta quota-win-meta text-mono', hidden: true }); const fill5h = h('div', { className: 'progress-fill' }); const meter5h = h('div', { className: 'account-meter-col' }, [ - h('div', { className: 'account-meter-head' }, [label5h, reset5h]), - h('div', { className: 'progress-track account-progress-track' }, [fill5h]), + h('div', { className: 'panel-header quota-win-head' }, [ + h('span', { className: 'quota-win-left' }, [label5h]), + reset5h, + ]), + h('div', { className: 'progress-track' }, [fill5h]), ]); - const labelWk = h('span', { className: 'settings-account-quota text-mono' }); - const resetWk = h('span', { className: 'account-meter-reset text-mono', hidden: true }); + const labelWk = h('span', { className: 'quota-win-title settings-account-quota text-mono' }); + const resetWk = h('span', { className: 'panel-meta quota-win-meta text-mono', hidden: true }); const fillWk = h('div', { className: 'progress-fill' }); const meterWk = h('div', { className: 'account-meter-col' }, [ - h('div', { className: 'account-meter-head' }, [labelWk, resetWk]), - h('div', { className: 'progress-track account-progress-track' }, [fillWk]), + h('div', { className: 'panel-header quota-win-head' }, [ + h('span', { className: 'quota-win-left' }, [labelWk]), + resetWk, + ]), + h('div', { className: 'progress-track' }, [fillWk]), ]); const gridEl = h('div', { className: 'account-pool-meters' }, [meter5h, meterWk]); - const el = h('div', { className: 'account-pool-group' }, [poolTitle, gridEl]); + const el = h('div', { className: 'quota-pool-row' }, [poolTitle, gridEl]); return { el, - refs: { poolTitle, gridEl, meter5h, label5h, reset5h, fill5h, meterWk, labelWk, resetWk, fillWk }, + refs: { el, poolTitle, gridEl, meter5h, label5h, reset5h, fill5h, meterWk, labelWk, resetWk, fillWk }, }; }, - updateRow: (refs, pool) => { + updateRow: (refs, pool, idx) => { + patchClasses(refs.el, { 'has-divider': idx > 0 }); patchText(refs.poolTitle, pool.poolLabel || pool.poolKey); const has5h = Number.isFinite(pool.remainingPct); const hasWk = Number.isFinite(pool.weeklyRemainingPct); @@ -164,18 +185,22 @@ function isValidVaultPassphrase(raw) { export const SettingsAccountTab = defineComponent({ name: 'SettingsAccountTab', setup({ props, onCleanup }) { + const initialSettings = telemetryStore.getState().telemetry?.settings; let account = null; let quotas = null; let refreshMinutes = normalizeAccountQuotaRefreshMinutes( - telemetryStore.getState().telemetry?.settings?.accountQuotaRefreshMinutes ?? - DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES + initialSettings?.accountQuotaRefreshMinutes ?? DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES ); + let draftRiskAccepted = Boolean(initialSettings?.accountSwitchRiskAccepted); + let acceptingRisk = false; + let riskLockedFromServer = warmAccountCache ? Boolean(warmAccountCache.riskLocked) : true; let accounts = warmAccountCache ? [...warmAccountCache.accounts] : []; let selectedEmail = warmAccountCache ? warmAccountCache.selectedEmail : ''; let supported = warmAccountCache ? warmAccountCache.supported : null; let vaultSecurity = warmAccountCache?.vaultSecurity ? { ...warmAccountCache.vaultSecurity } : { enabled: false, unlocked: true }; + let quotaHistory = warmAccountCache?.quotaHistory ? { ...warmAccountCache.quotaHistory } : {}; let actionNonce = warmAccountCache?.actionNonce || ''; let operation = ''; let status = ''; @@ -206,10 +231,12 @@ export const SettingsAccountTab = defineComponent({ if (supported !== true) return; warmAccountCache = { supported, + riskLocked: riskLockedFromServer, accounts: [...accounts], selectedEmail, savedQuotasEntries: [...savedQuotas.entries()], vaultSecurity: { ...vaultSecurity }, + quotaHistory: { ...quotaHistory }, actionNonce, }; } @@ -260,12 +287,19 @@ export const SettingsAccountTab = defineComponent({ pwdConfirmInput.value = ''; } + // --- Section 1: Active Account Card Host --- + const activeCardHost = h('div', { className: 'account-cards-stack' }); + + // --- Section 2: Quota Trend Line Chart Card --- + const quotaTrendCard = AccountQuotaTrendCard(); + + // --- Section 3: Multi-Account Toolbar, Drawers, Backup Cards & Risk Gate --- const loginBtnLabel = h('span'); const loginButton = h( 'button', { type: 'button', - className: 'btn-primary settings-account-login account-toolbar-btn', + className: 'btn-primary settings-account-login', onClick: () => { clearConfirmTarget(false); void request('loginStart', { language: getEffectiveLocale() }); @@ -275,7 +309,7 @@ export const SettingsAccountTab = defineComponent({ ); const cancelLogin = h('button', { type: 'button', - className: 'btn-secondary settings-account-login-cancel account-toolbar-btn', + className: 'btn-secondary settings-account-login-cancel', hidden: true, onClick: () => request('loginCancel', { id: loginSession?.id }), }); @@ -284,7 +318,7 @@ export const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'btn-secondary account-toolbar-btn', + className: 'btn-secondary', onClick: () => { clearConfirmTarget(false); importOpen = !importOpen; @@ -305,13 +339,14 @@ export const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'btn-secondary account-toolbar-btn settings-account-pwd-toggle', + className: 'btn-secondary settings-account-pwd-toggle', onClick: () => { clearConfirmTarget(false); pwdDrawerOpen = !pwdDrawerOpen; if (pwdDrawerOpen) { importOpen = false; pwdManageMode = 'change'; + pwdModeSegment.setProps({ modelValue: 'change', options: getPwdModeOptions() }); } clearPasswordInputs(); render(); @@ -328,7 +363,7 @@ export const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'btn-secondary account-toolbar-btn settings-account-lock-now', + className: 'btn-secondary settings-account-lock-now', hidden: true, onClick: () => { clearConfirmTarget(false); @@ -370,17 +405,17 @@ export const SettingsAccountTab = defineComponent({ 'button', { type: 'button', - className: 'icon-btn account-reload-btn', + className: 'icon-btn', onClick: () => request('list'), }, [createSvgIcon('refresh', { size: 13 })] ); - // --- Locked Vault Unlock Strip --- - const unlockHintLabel = h('span'); + // Locked Vault Notice (reusing `.settings-bridge-notice`) + const unlockHintLabel = h('span', { className: 'settings-bridge-title' }); const forgotToggleBtn = h('button', { type: 'button', - className: 'account-link-btn settings-account-forgot-btn', + className: 'btn-ghost-sm settings-account-forgot-btn', onClick: () => { forgotResetOpen = !forgotResetOpen; clearConfirmTarget(false); @@ -396,7 +431,7 @@ export const SettingsAccountTab = defineComponent({ }); const unlockSubmitBtn = h('button', { type: 'submit', - className: 'btn-primary account-toolbar-btn settings-account-unlock-submit', + className: 'btn-primary settings-account-unlock-submit', }); const unlockForm = h( 'form', @@ -407,55 +442,47 @@ export const SettingsAccountTab = defineComponent({ }, [unlockInput, unlockSubmitBtn] ); - const resetHintEl = h('span', { className: 'settings-action-desc' }); + const resetHintEl = h('p', { className: 'settings-bridge-desc', hidden: true }); const resetVaultBtn = h('button', { type: 'button', - className: 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-reset-vault', + className: 'btn-secondary btn-danger-confirm settings-account-reset-vault', + hidden: true, onClick: () => { armOrRunConfirm('resetVault', 'vault', () => { void request('resetVault', { confirmReset: 'RESET' }); }); }, }); - const resetRow = h('div', { className: 'account-reset-row', hidden: true }, [ - resetHintEl, - resetVaultBtn, - ]); - const unlockBox = h('div', { className: 'account-unlock-box settings-account-unlock-box', hidden: true }, [ - h('div', { className: 'account-unlock-head' }, [ - h('span', { className: 'account-unlock-title' }, [ - createSvgIcon('lock', { size: 13 }), - unlockHintLabel, + const unlockBox = h( + 'div', + { className: 'settings-bridge-notice settings-account-unlock-box', hidden: true }, + [ + h('div', { className: 'settings-bridge-head' }, [ + h('span', { className: 'settings-bridge-head-main' }, [ + createSvgIcon('lock', { size: 13, className: 'settings-bridge-icon' }), + unlockHintLabel, + ]), + forgotToggleBtn, ]), - forgotToggleBtn, - ]), - unlockForm, - resetRow, - ]); + unlockForm, + resetHintEl, + h('div', { className: 'settings-bridge-actions', hidden: true }, [resetVaultBtn]), + ] + ); + const resetActionsWrap = resetVaultBtn.parentElement; - // --- Passphrase Setup / Manage Drawer --- - const pwdTabChangeBtn = h('button', { - type: 'button', - className: 'account-pwd-tab', - onClick: () => { - pwdManageMode = 'change'; + // Passphrase Setup / Manage Drawer (reusing `SegmentedControl`!) + const pwdModeSegment = SegmentedControl({ + ariaLabel: t(key('pwdBtnManage')), + modelValue: pwdManageMode, + options: getPwdModeOptions(), + onUpdateModelValue: (val) => { + pwdManageMode = val === 'disable' ? 'disable' : 'change'; + pwdModeSegment.setProps({ modelValue: pwdManageMode, options: getPwdModeOptions() }); clearPasswordInputs(); render(); }, }); - const pwdTabDisableBtn = h('button', { - type: 'button', - className: 'account-pwd-tab', - onClick: () => { - pwdManageMode = 'disable'; - clearPasswordInputs(); - render(); - }, - }); - const pwdTabsWrap = h('div', { className: 'account-pwd-tabs', hidden: true }, [ - pwdTabChangeBtn, - pwdTabDisableBtn, - ]); const pwdCurrentInput = h('input', { type: 'password', className: 'settings-text-input account-import-input settings-account-pwd-current', @@ -480,9 +507,9 @@ export const SettingsAccountTab = defineComponent({ }); const pwdSubmitBtn = h('button', { type: 'submit', - className: 'btn-primary account-toolbar-btn settings-account-pwd-submit', + className: 'btn-primary settings-account-pwd-submit', }); - const pwdHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const pwdHint = h('div', { className: 'settings-action-desc' }); const pwdForm = h( 'form', { @@ -492,7 +519,7 @@ export const SettingsAccountTab = defineComponent({ onSubmit: submitPasswordDrawer, }, [ - pwdTabsWrap, + pwdModeSegment.el, h('div', { className: 'account-import-row' }, [ pwdCurrentInput, pwdNewInput, @@ -503,7 +530,7 @@ export const SettingsAccountTab = defineComponent({ ] ); - // --- Credential Import Drawer --- + // Credential Import Drawer const credential = h('input', { type: 'password', className: 'settings-text-input account-import-input', @@ -514,9 +541,9 @@ export const SettingsAccountTab = defineComponent({ }); const save = h('button', { type: 'submit', - className: 'btn-primary account-toolbar-btn', + className: 'btn-primary', }); - const importHint = h('div', { className: 'settings-action-desc account-import-hint' }); + const importHint = h('div', { className: 'settings-action-desc' }); const form = h( 'form', { @@ -531,26 +558,27 @@ export const SettingsAccountTab = defineComponent({ ] ); - const loginMessage = h('div', { - className: 'settings-action-desc account-flow-msg', + // OAuth Browser Login & Switch Notices (reusing `.settings-bridge-notice`) + const loginMessage = h('p', { + className: 'settings-bridge-desc settings-action-desc', role: 'status', hidden: true, }); const loginLink = h('a', { - className: 'account-flow-link', + className: 'settings-bridge-relaunch-btn', target: '_blank', rel: 'noopener noreferrer', hidden: true, }); - const loginStrip = h('div', { className: 'account-flow-strip', hidden: true }, [ - loginMessage, - loginLink, - ]); - const pending = h('div', { - className: 'settings-action-desc account-flow-strip is-warn', - role: 'status', - hidden: true, - }); + const loginStrip = h( + 'div', + { className: 'settings-bridge-notice is-restart', hidden: true }, + [loginMessage, h('div', { className: 'settings-bridge-actions' }, [loginLink])] + ); + const loginLinkWrap = loginLink.parentElement; + + const pendingDesc = h('p', { className: 'settings-bridge-desc', role: 'status' }); + const pending = h('div', { className: 'settings-bridge-notice', hidden: true }, [pendingDesc]); const toolbarPanel = h('section', { className: 'panel account-toolbar-panel' }, [ h('div', { className: 'account-toolbar-row' }, [ @@ -574,36 +602,261 @@ export const SettingsAccountTab = defineComponent({ pending, ]); - const cardsHost = h('div', { className: 'account-cards-stack' }); + const backupCardsHost = h('div', { className: 'account-cards-stack' }); const emptyPanel = h('section', { className: 'panel account-empty-panel', hidden: true }, [ h('div', { className: 'settings-action-desc account-empty-text' }), ]); const emptyTextEl = emptyPanel.firstChild; + // Risk Gate Stage (100% shared `.ctx-risk-stage` / `.ctx-risk-mask` with `SettingsOtherTab`) + const riskTitleEl = h('strong', { + className: 'ctx-risk-title', + text: t('settings.oth.ctxRiskTitle'), + }); + const riskBodyEl = h('p', { + className: 'ctx-risk-desc', + text: t(key('riskBody')), + }); + const riskAcceptBtnText = h('span', { text: t('settings.oth.ctxRiskAcceptBtn') }); + const riskAcceptBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary btn-danger-confirm ctx-risk-accept-btn settings-account-risk-accept', + onClick: async () => { + if (acceptingRisk || draftRiskAccepted) return; + acceptingRisk = true; + draftRiskAccepted = true; + render(); + try { + await saveSettingsPatch({ accountSwitchRiskAccepted: true }); + await request('list'); + } catch { + draftRiskAccepted = false; + setTransientStatus('storeFailed', 2800); + } finally { + acceptingRisk = false; + if (!disposed) render(); + } + }, + }, + [createSvgIcon('warning', { size: 12 }), riskAcceptBtnText] + ); + const riskMask = h( + 'div', + { + className: 'ctx-risk-mask settings-account-risk-mask', + role: 'region', + 'aria-label': t('settings.oth.ctxRiskTitle'), + }, + [ + h('div', { className: 'ctx-risk-head' }, [ + createSvgIcon('warning', { size: 14, className: 'ctx-risk-icon' }), + riskTitleEl, + ]), + riskBodyEl, + riskAcceptBtn, + ] + ); + const managedControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ + toolbarPanel, + backupCardsHost, + ]); + const riskStage = h('div', { className: 'ctx-risk-stage' }, [managedControlsBody, riskMask]); + function resolveActiveEmail() { return account?.status === 'signedIn' ? (account.email || '').trim().toLowerCase() : ''; } - function buildUnifiedAccountEntries(activeEmail) { - const entries = []; - if (activeEmail) { - entries.push({ - email: activeEmail, - isActive: true, - isSaved: accounts.includes(activeEmail), - }); - } - for (let i = 0; i < accounts.length; i++) { - const addr = accounts[i]; - if (addr && addr !== activeEmail) { - entries.push({ - email: addr, - isActive: false, - isSaved: true, + function createAccountCardDom(entry) { + const emailEl = h('span', { + className: 'settings-account-identity account-card-email', + text: entry.email, + title: entry.email, + }); + const tierPill = h('span', { className: 'status-tag state-synced', hidden: true }); + const statePill = h('span', { className: 'status-tag', hidden: true }); + + const captureBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('capture'); + }, + }); + const selectBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm', + hidden: true, + onClick: () => { + armOrRunConfirm('switch', entry.email, () => { + const curActive = resolveActiveEmail(); + void request('switch', { + email: entry.email, + ...(curActive ? { activeEmail: curActive } : {}), + }); }); - } + }, + }); + const loadQuotaBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn settings-account-load-quota', + hidden: true, + onClick: () => { + clearConfirmTarget(false); + void request('quota', { email: entry.email, manual: true }); + }, + }, + [createSvgIcon('refresh', { size: 12 })] + ); + const removeBtn = h( + 'button', + { + type: 'button', + className: 'icon-btn slot-remove-btn settings-account-remove', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }, + [createSvgIcon('close', { size: 12 })] + ); + const removeConfirmBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm btn-danger-confirm settings-account-remove-confirm', + hidden: true, + onClick: () => { + armOrRunConfirm('remove', entry.email, () => { + void request('remove', { email: entry.email }); + }); + }, + }); + + const actionsWrap = h('div', { className: 'account-card-actions' }, [ + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + ]); + const poolsWrap = h('div', { className: 'account-pools-stack' }); + const noteEl = h('div', { className: 'settings-action-desc account-card-note', hidden: true }); + + const cardEl = h('section', { className: 'panel account-card' }, [ + h('div', { className: 'panel-header account-card-head' }, [ + h('div', { className: 'account-card-meta' }, [emailEl, tierPill, statePill]), + actionsWrap, + ]), + poolsWrap, + noteEl, + ]); + return { + el: cardEl, + refs: { + cardEl, + emailEl, + tierPill, + statePill, + actionsWrap, + captureBtn, + selectBtn, + loadQuotaBtn, + removeBtn, + removeConfirmBtn, + poolsWrap, + noteEl, + }, + }; + } + + function updateAccountCardDom(row, entry, ctx) { + const addr = entry.email; + const active = entry.isActive; + const isSaved = entry.isSaved; + const written = addr === selectedEmail && !active && switchState?.state === 'written'; + const cached = active ? null : savedQuotas.get(addr); + const tierText = active + ? ctx.activeTierBadge + : cached?.tierName || cached?.tierId + ? formatAccountTierBadge({ + tierId: cached.tierId, + tierName: cached.tierName, + tierMultiplier: cached.tierMultiplier, + }) + : ''; + const isSpinning = !active && quotaVisibleLoading.has(addr); + const canSwitch = !active && isSaved && ctx.riskAccepted; + const armedSwitch = confirmTarget?.type === 'switch' && confirmTarget.key === addr; + const armedRemove = confirmTarget?.type === 'remove' && confirmTarget.key === addr; + + patchClasses(row.cardEl, { 'is-active-account': active }); + patchText(row.emailEl, addr); + patchAttr(row.emailEl, 'title', addr); + + patchText(row.tierPill, tierText); + patchAttr(row.tierPill, 'hidden', !tierText); + + patchText(row.statePill, active ? t(key('active')) : written ? t(key('written')) : ''); + patchClasses(row.statePill, { 'state-warn': written && !active }); + patchAttr(row.statePill, 'hidden', !active && !written); + + const showCapture = active && !isSaved && ctx.riskAccepted && supported !== false; + const showRemove = isSaved && ctx.riskAccepted; + const showQuotaRefresh = !active && isSaved && ctx.riskAccepted; + const hasAnyAction = showCapture || canSwitch || showQuotaRefresh || showRemove; + patchAttr(row.actionsWrap, 'hidden', !hasAnyAction); + + patchText(row.captureBtn, t(key('capture'))); + patchAttr(row.captureBtn, 'hidden', !showCapture); + patchAttr(row.captureBtn, 'disabled', !ctx.canWrite); + + patchText(row.selectBtn, t(key(armedSwitch ? 'switchConfirm' : 'switch'))); + patchAttr(row.selectBtn, 'title', t(key('switchHint'))); + patchClasses(row.selectBtn, { + 'settings-account-switch': canSwitch, + 'btn-danger-confirm': armedSwitch, + }); + patchAttr(row.selectBtn, 'hidden', !canSwitch); + patchAttr(row.selectBtn, 'disabled', !ctx.canWrite); + + patchAttr(row.loadQuotaBtn, 'title', t(key(isSpinning ? 'loadingQuota' : 'loadQuota'))); + patchAttr(row.loadQuotaBtn, 'aria-label', t(key('loadQuota'))); + patchClasses(row.loadQuotaBtn, { 'is-spinning': isSpinning }); + patchAttr(row.loadQuotaBtn, 'hidden', !showQuotaRefresh); + patchAttr(row.loadQuotaBtn, 'disabled', !ctx.canWrite || isSpinning); + + patchAttr(row.removeBtn, 'title', t(key('remove'))); + patchAttr(row.removeBtn, 'aria-label', t(key('remove'))); + patchAttr(row.removeBtn, 'hidden', !showRemove || armedRemove); + patchAttr(row.removeBtn, 'disabled', !ctx.canWrite); + + patchText(row.removeConfirmBtn, t(key('removeConfirm'))); + patchAttr(row.removeConfirmBtn, 'hidden', !showRemove || !armedRemove); + patchAttr(row.removeConfirmBtn, 'disabled', !ctx.canWrite); + + const displayedPools = active ? quotas?.pools || [] : cached?.pools || []; + const poolCount = renderQuotaRows(row.poolsWrap, displayedPools); + const quotaError = active ? '' : quotaErrors.get(addr); + + let noteText = ''; + if (quotaError) { + noteText = t(key(quotaError)); + } else if (active && poolCount > 0 && quotas?.meta?.isStale) { + noteText = t(key('quotaStale')); + } else if (active && poolCount === 0) { + noteText = t(key('noQuota')); + } else if (!active && cached && poolCount === 0) { + noteText = t(key('emptyCredentialQuota')); } - return entries; + patchText(row.noteEl, noteText); + patchClasses(row.noteEl, { 'is-error': Boolean(quotaError) }); + patchAttr(row.noteEl, 'hidden', !noteText); } function render() { @@ -612,8 +865,13 @@ export const SettingsAccountTab = defineComponent({ if (activeEmail && selectedEmail === activeEmail && switchState?.state !== 'starting') { selectedEmail = ''; } + const riskAccepted = Boolean(draftRiskAccepted); + if (!riskAccepted) { + refreshIntervalSelect.close?.(); + } const vaultLocked = isVaultLocked(); const canOperateVault = + riskAccepted && supported === true && !operation && status !== 'restarting' && @@ -624,6 +882,55 @@ export const SettingsAccountTab = defineComponent({ signedIn && (account?.tierName || account?.planName) ? formatAccountTierBadge(account) : ''; + const cardCtx = { riskAccepted, canWrite, activeTierBadge }; + + // 1. Active Logged-in Account Card + const activeEntries = activeEmail + ? [ + { + email: activeEmail, + isActive: true, + isSaved: riskAccepted && accounts.includes(activeEmail), + }, + ] + : []; + patchAttr(activeCardHost, 'hidden', activeEntries.length === 0); + patchKeyedList(activeCardHost, activeEntries, { + keyFn: (entry) => entry.email, + sigFn: (entry) => + JSON.stringify([ + locale, + entry.isSaved, + riskAccepted, + canWrite, + confirmTarget?.key === entry.email ? confirmTarget.type : '', + quotas, + activeTierBadge, + ]), + createRow: createAccountCardDom, + updateRow: (row, entry) => updateAccountCardDom(row, entry, cardCtx), + }); + + // 2. Quota Trend Line Chart Card (always visible; locked to activeEmail when !riskAccepted) + quotaTrendCard.refs.update({ + activeEmail, + activePools: quotas?.pools || [], + riskAccepted, + accounts, + savedQuotas, + quotaHistory, + }); + + // 3. Risk Gate Stage & Multi-Account Controls + patchClasses(managedControlsBody, { 'is-locked': !riskAccepted }); + patchAttr(managedControlsBody, 'inert', !riskAccepted); + patchAttr(managedControlsBody, 'aria-hidden', riskAccepted ? null : 'true'); + patchAttr(riskMask, 'hidden', riskAccepted); + patchAttr(riskMask, 'aria-label', t('settings.oth.ctxRiskTitle')); + patchText(riskTitleEl, t('settings.oth.ctxRiskTitle')); + patchText(riskBodyEl, t(key('riskBody'))); + patchText(riskAcceptBtnText, t('settings.oth.ctxRiskAcceptBtn')); + patchAttr(riskAcceptBtn, 'disabled', acceptingRisk); const loginActive = ['waiting', 'exchanging', 'saving'].includes(loginSession?.status); patchText(loginBtnLabel, t(key('googleLogin'))); @@ -648,32 +955,34 @@ export const SettingsAccountTab = defineComponent({ patchAttr(lockNowBtn, 'hidden', !vaultSecurity.enabled || vaultLocked || supported === false); patchAttr(lockNowBtn, 'disabled', !canOperateVault); - // Unlock strip (only when passphrase enabled & locked) - patchAttr(unlockBox, 'hidden', supported !== true || !vaultLocked); + // Unlock Notice + patchAttr(unlockBox, 'hidden', !riskAccepted || supported !== true || !vaultLocked); patchText(unlockHintLabel, t(key('vaultLockedHint'))); patchText(forgotToggleBtn, t(key('forgotPwdToggle'))); patchAttr(unlockInput, 'placeholder', t(key('unlockPlaceholder'))); patchAttr(unlockInput, 'disabled', !canOperateVault); patchText(unlockSubmitBtn, t(key('unlockBtn'))); patchAttr(unlockSubmitBtn, 'disabled', !canOperateVault); - patchAttr(resetRow, 'hidden', !forgotResetOpen || !vaultLocked); + const showResetSection = forgotResetOpen && vaultLocked; + patchAttr(resetHintEl, 'hidden', !showResetSection); + patchAttr(resetActionsWrap, 'hidden', !showResetSection); + patchAttr(resetVaultBtn, 'hidden', !showResetSection); patchText(resetHintEl, t(key('resetVaultHint'))); const armedVaultReset = confirmTarget?.type === 'resetVault' && confirmTarget.key === 'vault'; patchText(resetVaultBtn, t(key(armedVaultReset ? 'resetVaultConfirm' : 'resetVaultBtn'))); patchAttr(resetVaultBtn, 'disabled', !canOperateVault); - // Passphrase setup / manage drawer - const showPwdDrawer = pwdDrawerOpen && !vaultLocked && supported === true; + // Passphrase Drawer (`SegmentedControl` for Change / Disable) + const showPwdDrawer = riskAccepted && pwdDrawerOpen && !vaultLocked && supported === true; patchAttr(pwdForm, 'hidden', !showPwdDrawer); if (showPwdDrawer) { const isSetNew = !vaultSecurity.enabled; const isDisableMode = !isSetNew && pwdManageMode === 'disable'; - patchAttr(pwdTabsWrap, 'hidden', isSetNew); - patchText(pwdTabChangeBtn, t(key('pwdTabChange'))); - patchClasses(pwdTabChangeBtn, { 'is-active': pwdManageMode === 'change' }); - patchText(pwdTabDisableBtn, t(key('pwdTabDisable'))); - patchClasses(pwdTabDisableBtn, { 'is-active': isDisableMode }); + patchAttr(pwdModeSegment.el, 'hidden', isSetNew); + if (!isSetNew) { + pwdModeSegment.setProps({ modelValue: pwdManageMode, options: getPwdModeOptions() }); + } patchAttr(pwdCurrentInput, 'hidden', isSetNew); patchAttr(pwdCurrentInput, 'placeholder', t(key('pwdCurrentPlaceholder'))); @@ -694,7 +1003,7 @@ export const SettingsAccountTab = defineComponent({ patchClasses(pwdSubmitBtn, { 'btn-primary': !isDisableMode, 'btn-secondary': isDisableMode, - 'account-confirm-danger-btn': isDisableMode, + 'btn-danger-confirm': isDisableMode, }); patchAttr(pwdSubmitBtn, 'disabled', !canOperateVault); patchText(pwdHint, t(key(isSetNew ? 'pwdSetHint' : 'pwdManageHint'))); @@ -713,7 +1022,7 @@ export const SettingsAccountTab = defineComponent({ patchAttr(reload, 'disabled', Boolean(operation)); patchClasses(reload, { 'is-spinning': operation === 'list' }); - patchAttr(form, 'hidden', !importOpen || vaultLocked || supported === false); + patchAttr(form, 'hidden', !riskAccepted || !importOpen || vaultLocked || supported === false); patchAttr(credential, 'placeholder', t(key('credentialPlaceholder'))); patchAttr(credential, 'disabled', !canWrite); patchText(save, t(key('save'))); @@ -752,11 +1061,8 @@ export const SettingsAccountTab = defineComponent({ patchText(loginLink, t(key('openLoginPage'))); patchAttr(loginLink, 'href', authUrl || null); patchAttr(loginLink, 'hidden', !authUrl); - patchClasses(loginStrip, { - 'is-error': loginIsError, - 'is-ok': loginSession?.status === 'success', - 'is-info': loginActive, - }); + patchAttr(loginLinkWrap, 'hidden', !authUrl); + patchClasses(loginStrip, { 'is-restart': !loginIsError }); patchAttr(loginStrip, 'hidden', !hasLoginSession || !loginMessageKey); const failedSwitch = @@ -776,7 +1082,6 @@ export const SettingsAccountTab = defineComponent({ patchClasses(feedback, { 'is-error': isFeedbackError, 'is-ok': isFeedbackOk, - 'is-info': !isFeedbackError && !isFeedbackOk && Boolean(message), }); patchAttr(feedback, 'hidden', !message); @@ -785,16 +1090,38 @@ export const SettingsAccountTab = defineComponent({ activeEmail !== selectedEmail && switchState?.state === 'written' && status !== 'restarting'; - patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : ''); + patchText(pendingDesc, waiting ? t(key('pending'), { email: selectedEmail }) : ''); patchAttr(pending, 'hidden', !waiting); - const entries = buildUnifiedAccountEntries(activeEmail); - patchAttr(cardsHost, 'hidden', entries.length === 0); + const backupEntries = riskAccepted + ? accounts + .filter((addr) => addr && addr !== activeEmail) + .map((addr) => ({ email: addr, isActive: false, isSaved: true })) + : []; + patchAttr(backupCardsHost, 'hidden', backupEntries.length === 0); + patchKeyedList(backupCardsHost, backupEntries, { + keyFn: (entry) => entry.email, + sigFn: (entry) => + JSON.stringify([ + locale, + selectedEmail, + switchState?.state || '', + canWrite, + confirmTarget?.key === entry.email ? confirmTarget.type : '', + savedQuotas.get(entry.email), + quotaVisibleLoading.has(entry.email), + quotaErrors.get(entry.email), + ]), + createRow: createAccountCardDom, + updateRow: (row, entry) => updateAccountCardDom(row, entry, cardCtx), + }); + + const showEmpty = !activeEmail && (!riskAccepted || backupEntries.length === 0); patchText( emptyTextEl, t( key( - supported === null + supported === null && !activeEmail ? 'loading' : account?.status === 'signedOut' ? 'signedOut' @@ -802,217 +1129,7 @@ export const SettingsAccountTab = defineComponent({ ) ) ); - patchAttr(emptyPanel, 'hidden', entries.length > 0); - - patchKeyedList(cardsHost, entries, { - keyFn: (entry) => entry.email, - sigFn: (entry) => - JSON.stringify([ - locale, - entry.isActive, - entry.isSaved, - selectedEmail, - switchState?.state || '', - canWrite, - confirmTarget?.key === entry.email ? confirmTarget.type : '', - entry.isActive ? null : savedQuotas.get(entry.email), - quotaVisibleLoading.has(entry.email), - entry.isActive ? null : quotaErrors.get(entry.email), - entry.isActive ? quotas : null, - entry.isActive ? activeTierBadge : '', - ]), - createRow: (entry) => { - const activeDot = h('span', { className: 'dot-swatch account-active-dot', hidden: true }); - const emailEl = h('span', { - className: 'settings-account-identity account-card-email', - text: entry.email, - title: entry.email, - }); - const tierPill = h('span', { className: 'account-tag is-tier', hidden: true }); - const statePill = h('span', { className: 'account-tag', hidden: true }); - - const captureBtn = h('button', { - type: 'button', - className: 'btn-secondary account-card-btn', - hidden: true, - onClick: () => { - clearConfirmTarget(false); - void request('capture'); - }, - }); - const selectBtn = h('button', { - type: 'button', - className: 'btn-secondary account-card-btn', - hidden: true, - onClick: () => { - armOrRunConfirm('switch', entry.email, () => { - const curActive = resolveActiveEmail(); - void request('switch', { - email: entry.email, - ...(curActive ? { activeEmail: curActive } : {}), - }); - }); - }, - }); - const loadQuotaBtn = h( - 'button', - { - type: 'button', - className: 'icon-btn settings-account-load-quota account-icon-btn', - hidden: true, - onClick: () => { - clearConfirmTarget(false); - void request('quota', { email: entry.email, manual: true }); - }, - }, - [createSvgIcon('refresh', { size: 12 })] - ); - const removeBtn = h( - 'button', - { - type: 'button', - className: 'icon-btn slot-remove-btn settings-account-remove account-icon-btn', - hidden: true, - onClick: () => { - armOrRunConfirm('remove', entry.email, () => { - void request('remove', { email: entry.email }); - }); - }, - }, - [createSvgIcon('close', { size: 12 })] - ); - const removeConfirmBtn = h('button', { - type: 'button', - className: - 'btn-secondary account-card-btn account-confirm-danger-btn settings-account-remove-confirm', - hidden: true, - onClick: () => { - armOrRunConfirm('remove', entry.email, () => { - void request('remove', { email: entry.email }); - }); - }, - }); - - const poolsWrap = h('div', { className: 'account-pools-stack' }); - const noteEl = h('div', { className: 'settings-action-desc account-card-note', hidden: true }); - - const cardEl = h('section', { className: 'panel account-card' }, [ - h('div', { className: 'panel-header account-card-head' }, [ - h('div', { className: 'account-card-meta' }, [ - activeDot, - emailEl, - tierPill, - statePill, - ]), - h('div', { className: 'account-card-actions' }, [ - captureBtn, - selectBtn, - loadQuotaBtn, - removeBtn, - removeConfirmBtn, - ]), - ]), - poolsWrap, - noteEl, - ]); - return { - el: cardEl, - refs: { - cardEl, - activeDot, - emailEl, - tierPill, - statePill, - captureBtn, - selectBtn, - loadQuotaBtn, - removeBtn, - removeConfirmBtn, - poolsWrap, - noteEl, - }, - }; - }, - updateRow: (row, entry) => { - const addr = entry.email; - const active = entry.isActive; - const isSaved = entry.isSaved; - const written = addr === selectedEmail && !active && switchState?.state === 'written'; - const cached = active ? null : savedQuotas.get(addr); - const tierText = active - ? activeTierBadge - : cached?.tierName || cached?.tierId - ? formatAccountTierBadge({ - tierId: cached.tierId, - tierName: cached.tierName, - tierMultiplier: cached.tierMultiplier, - }) - : ''; - const isSpinning = !active && quotaVisibleLoading.has(addr); - const canSwitch = !active && isSaved; - const armedSwitch = confirmTarget?.type === 'switch' && confirmTarget.key === addr; - const armedRemove = confirmTarget?.type === 'remove' && confirmTarget.key === addr; - - patchClasses(row.cardEl, { 'is-active-account': active }); - patchAttr(row.activeDot, 'hidden', !active); - patchText(row.emailEl, addr); - patchAttr(row.emailEl, 'title', addr); - - patchText(row.tierPill, tierText); - patchAttr(row.tierPill, 'hidden', !tierText); - - patchText(row.statePill, active ? t(key('active')) : written ? t(key('written')) : ''); - patchClasses(row.statePill, { 'is-active': active, 'is-written': written }); - patchAttr(row.statePill, 'hidden', !active && !written); - - patchText(row.captureBtn, t(key('capture'))); - patchAttr(row.captureBtn, 'hidden', !active || isSaved || supported === false); - patchAttr(row.captureBtn, 'disabled', !canWrite); - - patchText(row.selectBtn, t(key(armedSwitch ? 'switchConfirm' : 'switch'))); - patchAttr(row.selectBtn, 'title', t(key('switchHint'))); - patchClasses(row.selectBtn, { - 'settings-account-switch': canSwitch, - 'is-confirm-warn': armedSwitch, - }); - patchAttr(row.selectBtn, 'hidden', !canSwitch); - patchAttr(row.selectBtn, 'disabled', !canWrite); - - patchAttr(row.loadQuotaBtn, 'title', t(key(isSpinning ? 'loadingQuota' : 'loadQuota'))); - patchAttr(row.loadQuotaBtn, 'aria-label', t(key('loadQuota'))); - patchClasses(row.loadQuotaBtn, { 'is-spinning': isSpinning }); - // Active account exclusively uses host telemetry — hide OAuth quota refresh on active card - patchAttr(row.loadQuotaBtn, 'hidden', active || !isSaved); - patchAttr(row.loadQuotaBtn, 'disabled', !canWrite || isSpinning); - - patchAttr(row.removeBtn, 'title', t(key('remove'))); - patchAttr(row.removeBtn, 'aria-label', t(key('remove'))); - patchAttr(row.removeBtn, 'hidden', !isSaved || armedRemove); - patchAttr(row.removeBtn, 'disabled', !canWrite); - - patchText(row.removeConfirmBtn, t(key('removeConfirm'))); - patchAttr(row.removeConfirmBtn, 'hidden', !isSaved || !armedRemove); - patchAttr(row.removeConfirmBtn, 'disabled', !canWrite); - - const displayedPools = active ? quotas?.pools || [] : cached?.pools || []; - const poolCount = renderQuotaRows(row.poolsWrap, displayedPools); - const quotaError = active ? '' : quotaErrors.get(addr); - - let noteText = ''; - if (quotaError) { - noteText = t(key(quotaError)); - } else if (active && poolCount > 0 && quotas?.meta?.isStale) { - noteText = t(key('quotaStale')); - } else if (active && poolCount === 0) { - noteText = t(key('noQuota')); - } else if (!active && cached && poolCount === 0) { - noteText = t(key('emptyCredentialQuota')); - } - patchText(row.noteEl, noteText); - patchClasses(row.noteEl, { 'is-error': Boolean(quotaError) }); - patchAttr(row.noteEl, 'hidden', !noteText); - }, - }); + patchAttr(emptyPanel, 'hidden', !showEmpty); props.onLayoutChange?.(); } @@ -1048,6 +1165,7 @@ export const SettingsAccountTab = defineComponent({ } async function request(action, fields = {}) { + if (action !== 'list' && !draftRiskAccepted) return; if (action === 'quota') return refreshQuota(fields.email, Boolean(fields.manual)); if (operation) return; operation = action; @@ -1066,6 +1184,9 @@ export const SettingsAccountTab = defineComponent({ if (typeof result?.actionNonce === 'string' && result.actionNonce) { actionNonce = result.actionNonce; } + if (result?.quotaHistory && typeof result.quotaHistory === 'object') { + quotaHistory = { ...quotaHistory, ...result.quotaHistory }; + } if (result?.error) { if (result.error === 'unsupported') supported = false; if (result.error === 'vaultLocked') { @@ -1081,6 +1202,7 @@ export const SettingsAccountTab = defineComponent({ return; } supported = result?.supported === true; + riskLockedFromServer = Boolean(result?.riskLocked); accounts = result?.accounts || []; selectedEmail = result?.selectedEmail || ''; switchState = result?.switchState || null; @@ -1101,7 +1223,7 @@ export const SettingsAccountTab = defineComponent({ savedQuotas.set(addr, snapshot); } syncWarmCache(); - if (action !== 'switch' && !isVaultLocked()) { + if (action !== 'switch' && draftRiskAccepted && !riskLockedFromServer && !isVaultLocked()) { void refreshSavedQuotas(); } if (action === 'save' || action === 'capture') { @@ -1157,7 +1279,7 @@ export const SettingsAccountTab = defineComponent({ return; } await request('list'); - if (!disposed && !isVaultLocked() && email !== resolveActiveEmail()) { + if (!disposed && draftRiskAccepted && !isVaultLocked() && email !== resolveActiveEmail()) { void refreshQuota(email, false); } } @@ -1192,13 +1314,12 @@ export const SettingsAccountTab = defineComponent({ } async function refreshSavedQuotas() { - if (refreshingSavedQuotas || isVaultLocked()) return; + if (refreshingSavedQuotas || !draftRiskAccepted || isVaultLocked()) return; refreshingSavedQuotas = true; try { const activeEmail = resolveActiveEmail(); const ttlMs = refreshMinutes * 60_000; const staleTargets = accounts.filter((addr) => { - // Active account exclusively uses host telemetry — never poll via OAuth if (!addr || addr === activeEmail) return false; const cached = savedQuotas.get(addr); if (needsLegacyUltraTierRefresh(cached)) return true; @@ -1206,7 +1327,7 @@ export const SettingsAccountTab = defineComponent({ }); const BATCH_SIZE = 3; for (let i = 0; i < staleTargets.length; i += BATCH_SIZE) { - if (disposed || operation === 'switch' || isVaultLocked()) break; + if (disposed || operation === 'switch' || !draftRiskAccepted || isVaultLocked()) break; const batch = staleTargets.slice(i, i + BATCH_SIZE); await Promise.all(batch.map((addr) => refreshQuota(addr, false))); } @@ -1217,7 +1338,14 @@ export const SettingsAccountTab = defineComponent({ async function refreshQuota(addr, manual = false) { const activeEmail = resolveActiveEmail(); - if (!addr || addr === activeEmail || isVaultLocked() || quotaInFlight.has(addr) || disposed) { + if ( + !addr || + addr === activeEmail || + !draftRiskAccepted || + isVaultLocked() || + quotaInFlight.has(addr) || + disposed + ) { return; } const hasCachedPools = Boolean(savedQuotas.get(addr)?.pools?.length); @@ -1249,9 +1377,10 @@ export const SettingsAccountTab = defineComponent({ const nextTierId = result.tierId || prev.tierId || ''; const nextTierName = result.tierName || prev.tierName || ''; const nextTierMult = result.tierMultiplier || prev.tierMultiplier || ''; + const fetchedAt = result.fetchedAt || Date.now(); savedQuotas.set(addr, { pools: result.pools, - fetchedAt: result.fetchedAt || Date.now(), + fetchedAt, ...(nextTierId ? { tierId: nextTierId } : {}), ...(nextTierName ? { tierName: nextTierName } : {}), ...(nextTierMult ? { tierMultiplier: nextTierMult } : {}), @@ -1340,24 +1469,41 @@ export const SettingsAccountTab = defineComponent({ settingsData?.accountQuotaRefreshMinutes !== undefined ? normalizeAccountQuotaRefreshMinutes(settingsData.accountQuotaRefreshMinutes) : refreshMinutes; - if (account === value && quotas === quotaData && refreshMinutes === nextRefreshMins) return; + const nextRiskAccepted = + acceptingRisk || settingsData?.accountSwitchRiskAccepted === undefined + ? draftRiskAccepted + : Boolean(settingsData.accountSwitchRiskAccepted); + if ( + account === value && + quotas === quotaData && + refreshMinutes === nextRefreshMins && + draftRiskAccepted === nextRiskAccepted + ) { + return; + } + const becameRiskUnlocked = !draftRiskAccepted && nextRiskAccepted; account = value; quotas = quotaData; refreshMinutes = nextRefreshMins; + draftRiskAccepted = nextRiskAccepted; render(); + if (becameRiskUnlocked && riskLockedFromServer && !operation) { + void request('list'); + } } const quotaScheduleTimer = setInterval(() => { - if (!disposed && accounts.length > 0 && !operation && !isVaultLocked()) { + if (!disposed && draftRiskAccepted && accounts.length > 0 && !operation && !isVaultLocked()) { void refreshSavedQuotas(); } }, 60_000); quotaScheduleTimer.unref?.(); const root = h('div', { className: 'settings-tab-stack settings-account-root' }, [ - toolbarPanel, - cardsHost, + quotaTrendCard.el, + activeCardHost, emptyPanel, + riskStage, ]); render(); onCleanup(() => { @@ -1367,6 +1513,8 @@ export const SettingsAccountTab = defineComponent({ if (statusClearTimer) clearTimeout(statusClearTimer); if (confirmClearTimer) clearTimeout(confirmClearTimer); refreshIntervalSelect.destroy(); + pwdModeSegment.destroy(); + quotaTrendCard.destroy(); loginGeneration += 1; credential.value = ''; clearPasswordInputs(); @@ -1375,9 +1523,17 @@ export const SettingsAccountTab = defineComponent({ el: root, refs: { renderAccount, - refreshLabels: render, + refreshLabels: () => { + quotaTrendCard.refs.refreshLabels(); + render(); + }, preload: () => (supported === null ? request('list') : Promise.resolve()), - load: () => (supported === null ? request('list') : refreshSavedQuotas()), + load: () => + supported === null || (draftRiskAccepted && riskLockedFromServer) + ? request('list') + : draftRiskAccepted + ? refreshSavedQuotas() + : Promise.resolve(), }, }; }, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 0f49bde..7095733 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -6271,15 +6271,15 @@ html[data-standalone="true"] .app-shell { } .account-toolbar-panel { - padding: 9px 12px; - gap: 8px; + padding: var(--space-3) var(--space-5); + gap: var(--space-2); } .account-toolbar-row { display: flex; align-items: center; justify-content: space-between; - gap: 8px; + gap: var(--space-2); flex-wrap: wrap; } @@ -6287,6 +6287,7 @@ html[data-standalone="true"] .app-shell { .account-toolbar-right { display: inline-flex; align-items: center; + flex-wrap: wrap; gap: 6px; min-width: 0; } @@ -6295,32 +6296,19 @@ html[data-standalone="true"] .app-shell { margin-left: auto; } -.account-toolbar-btn { - display: inline-flex; - align-items: center; - gap: 5px; - min-height: calc(25px * var(--ui-font-scale, 1)); - height: auto; +.account-toolbar-panel .btn-primary, +.account-toolbar-panel .btn-secondary { + min-height: calc(26px * var(--ui-font-scale, 1)); padding: 2px 10px; font-size: var(--fs-md); - font-weight: 500; - border-radius: var(--radius-xs); white-space: nowrap; } -.account-toolbar-btn.is-open { +.account-toolbar-panel .btn-secondary.is-open { color: var(--accent-primary); background: var(--accent-primary-soft); } -.account-reload-btn { - width: calc(25px * var(--ui-font-scale, 1)); - height: calc(25px * var(--ui-font-scale, 1)); - padding: 0; - border-radius: var(--radius-xs); - flex-shrink: 0; -} - .account-refresh-select { flex: 0 0 auto; width: auto; @@ -6329,24 +6317,11 @@ html[data-standalone="true"] .app-shell { .account-refresh-select .select-trigger { width: auto; - min-height: calc(25px * var(--ui-font-scale, 1)); + min-height: calc(26px * var(--ui-font-scale, 1)); height: auto; padding: 2px 8px; gap: 5px; font-size: var(--fs-sm); - border: 1px solid var(--border-hairline); - border-radius: var(--radius-xs); - background: var(--surface-subtle); -} - -[data-modern-ui="true"] .account-refresh-select .select-trigger { - border: none; - background: var(--modern-surface-subtle); -} - -[data-modern-ui="true"] .account-refresh-select .select-trigger:hover, -[data-modern-ui="true"] .account-refresh-select.is-open .select-trigger { - background: var(--modern-surface-hover); } .account-refresh-select .select-menu { @@ -6373,17 +6348,18 @@ html[data-standalone="true"] .app-shell { color: var(--metric-danger); } -.account-status-inline.is-info { - color: var(--text-secondary); -} - .account-import-drawer { display: flex; flex-direction: column; - gap: 5px; + align-items: stretch; + gap: 6px; padding-top: 2px; } +.account-import-drawer > .segmented { + align-self: flex-start; +} + .account-import-row { display: flex; align-items: center; @@ -6397,176 +6373,20 @@ html[data-standalone="true"] .app-shell { min-height: calc(26px * var(--ui-font-scale, 1)); } -.account-import-hint { - font-size: var(--fs-xs); - color: var(--text-muted); -} - -.account-unlock-box { - display: flex; - flex-direction: column; - gap: 6px; - padding: 8px 10px; - border-radius: var(--radius-xs); - background: var(--surface-subtle); -} - -.account-unlock-head { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; -} - -.account-unlock-title { - display: inline-flex; - align-items: center; - gap: 6px; - font-size: var(--fs-sm); - color: var(--text-secondary); -} - -.account-unlock-title .svg-icon { - color: var(--metric-warn); - flex-shrink: 0; -} - -.account-link-btn { - padding: 0; - border: none; - background: transparent; - font-size: var(--fs-xs); - color: var(--text-muted); - cursor: pointer; - white-space: nowrap; -} - -.account-link-btn:hover { - color: var(--text-primary); - text-decoration: underline; -} - -.account-reset-row { - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 6px 10px; - padding-top: 4px; -} - -.account-reset-row .settings-action-desc { - flex: 1 1 180px; - font-size: var(--fs-xs); -} - -.account-pwd-tabs { - display: inline-flex; - align-items: center; - align-self: flex-start; - gap: 4px; - padding: 2px; - border-radius: var(--radius-xs); - background: var(--surface-subtle); -} - -.account-pwd-tab { - padding: 2px 8px; - border: none; - border-radius: var(--radius-xs); - background: transparent; - font-size: var(--fs-xs); - font-weight: 500; - color: var(--text-secondary); - cursor: pointer; -} - -.account-pwd-tab.is-active { - background: var(--bg-elevated); - color: var(--text-primary); -} - -.account-card-btn.is-confirm-warn { - color: var(--accent-primary); - background: var(--accent-primary-soft); - font-weight: 600; -} - -.account-confirm-danger-btn { - color: var(--metric-danger); - background: color-mix(in srgb, var(--metric-danger) 12%, transparent); - font-weight: 600; -} - -.account-confirm-danger-btn:hover:not(:disabled) { - background: color-mix(in srgb, var(--metric-danger) 20%, transparent); -} - -.account-flow-strip { - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 6px 10px; - padding: 6px 9px; - border-radius: var(--radius-xs); - background: var(--surface-subtle); - font-size: var(--fs-sm); -} - -.account-flow-strip.is-info { - background: var(--accent-primary-soft); -} - -.account-flow-strip.is-info .account-flow-msg { - color: var(--accent-primary); -} - -.account-flow-strip.is-ok { - background: color-mix(in srgb, var(--metric-ok) 10%, transparent); -} - -.account-flow-strip.is-ok .account-flow-msg { - color: var(--metric-ok); -} - -.account-flow-strip.is-warn { - background: color-mix(in srgb, var(--metric-warn) 10%, transparent); - color: var(--metric-warn); -} - -.account-flow-strip.is-error { - background: color-mix(in srgb, var(--metric-danger) 10%, transparent); -} - -.account-flow-strip.is-error .account-flow-msg { - color: var(--metric-danger); -} - -.account-flow-link { - font-size: var(--fs-sm); - font-weight: 500; - color: var(--accent-primary); - text-decoration: none; - white-space: nowrap; -} - -.account-flow-link:hover { - text-decoration: underline; -} - .account-cards-stack { display: flex; flex-direction: column; gap: var(--space-3); } +/* Optically symmetrical vertical padding: 11px + 3px header leading == 14px bottom bar-to-edge */ .account-card { gap: 10px; - padding: 11px 14px; + padding: 11px var(--space-5) 14px; } .account-card-head { + min-height: calc(22px * var(--ui-font-scale, 1)); gap: 8px; flex-wrap: wrap; } @@ -6580,14 +6400,10 @@ html[data-standalone="true"] .app-shell { flex: 1 1 150px; } -.account-active-dot { - background: var(--metric-ok); - box-shadow: 0 0 0 2px color-mix(in srgb, var(--metric-ok) 20%, transparent); -} - .account-card-email { font-size: var(--fs-base); font-weight: 600; + line-height: 1.3; color: var(--text-primary); overflow: hidden; text-overflow: ellipsis; @@ -6595,34 +6411,6 @@ html[data-standalone="true"] .app-shell { max-width: 100%; } -.account-tag { - display: inline-flex; - align-items: center; - min-height: calc(18px * var(--ui-font-scale, 1)); - padding: 1px 6px; - font-size: var(--fs-xs); - font-weight: 600; - line-height: 1.2; - border-radius: var(--radius-xs); - border: none; - white-space: nowrap; -} - -.account-tag.is-active { - color: var(--metric-ok); - background: color-mix(in srgb, var(--metric-ok) 12%, transparent); -} - -.account-tag.is-tier { - color: var(--accent-primary); - background: var(--accent-primary-soft); -} - -.account-tag.is-written { - color: var(--metric-warn); - background: color-mix(in srgb, var(--metric-warn) 12%, transparent); -} - .account-card-actions { display: inline-flex; align-items: center; @@ -6631,21 +6419,16 @@ html[data-standalone="true"] .app-shell { margin-left: auto; } -.account-card-btn { - min-height: calc(23px * var(--ui-font-scale, 1)); - height: auto; +.account-card-actions .btn-ghost-sm { + min-height: calc(22px * var(--ui-font-scale, 1)); padding: 1px 8px; - font-size: var(--fs-sm); - font-weight: 500; - border-radius: var(--radius-xs); - white-space: nowrap; } -.account-icon-btn { - width: calc(23px * var(--ui-font-scale, 1)); - height: calc(23px * var(--ui-font-scale, 1)); +.account-card-actions .icon-btn { + width: calc(22px * var(--ui-font-scale, 1)); + height: calc(22px * var(--ui-font-scale, 1)); + min-width: calc(22px * var(--ui-font-scale, 1)); padding: 0; - border-radius: var(--radius-xs); } .account-pools-stack { @@ -6654,18 +6437,11 @@ html[data-standalone="true"] .app-shell { gap: 9px; } -.account-pool-group { - display: flex; - flex-direction: column; - gap: 4px; -} - -.account-pool-name { +.account-pool-label { font-size: var(--fs-xs); font-weight: 600; color: var(--text-muted); line-height: 1.25; - letter-spacing: 0.01em; } .account-pool-meters { @@ -6691,34 +6467,61 @@ html[data-standalone="true"] .app-shell { min-width: 0; } -.account-meter-head { +/* Quota Trend Card minor layout helpers */ +.account-trend-toprow { + gap: var(--space-2); + flex-wrap: wrap; +} + +.account-trend-toprow .cons-cycle-pool-select { + flex: 0 0 auto; +} + +.account-trend-subbar { + gap: 6px 8px; + flex-wrap: wrap; +} + +.account-trend-email-select { + max-width: 156px; +} + +.account-trend-legend { display: flex; - align-items: baseline; - justify-content: space-between; - gap: 6px; - min-width: 0; + align-items: center; + flex-wrap: wrap; + gap: 6px 12px; + padding-top: 2px; } -.settings-account-quota { - font-size: var(--fs-sm); - font-weight: 600; +.account-trend-leg-item { + display: inline-flex; + align-items: center; + gap: 5px; + font-size: var(--fs-xs); + color: var(--text-secondary); +} + +.account-trend-leg-item strong { color: var(--text-primary); - white-space: nowrap; } -.account-meter-reset { - font-size: var(--fs-2xs); - color: var(--text-muted); - white-space: nowrap; - flex-shrink: 0; +.account-trend-tip-rows { + display: flex; + flex-direction: column; + gap: 4px; } -.account-progress-track { - height: 5px; +.account-trend-tip-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + font-size: var(--fs-xs); } .account-empty-panel { - padding: 18px 14px; + padding: 16px var(--space-5); align-items: center; justify-content: center; } diff --git a/sidecars/panel/test/account-switch.test.mjs b/sidecars/panel/test/account-switch.test.mjs index a66f73f..590188f 100644 --- a/sidecars/panel/test/account-switch.test.mjs +++ b/sidecars/panel/test/account-switch.test.mjs @@ -24,7 +24,15 @@ import { resetVaultUnlockFailures, verifyAccountActionNonce, } from '../backend/account-vault-crypto.mjs'; +import { + createAccountQuotaHistoryTracker, + sanitizeQuotaHistoryPoints, +} from '../backend/account-quota-history.mjs'; import { executeAccountCredentialAction } from '../backend/api-actions.mjs'; +import { + buildQuotaWindowSeries, + resolveQuotaWindowBounds, +} from '../src/components/widgets/AccountQuotaTrendCard.js'; test('accepts a shared OAuth credential or refresh token, and rejects other credential types', () => { const refreshToken = '1//synthetic-refresh-token-for-test'; @@ -412,13 +420,70 @@ test('enforces OAuth client_id allowlist, minimizes at-rest vault payload, and v assert.equal(verifyAccountActionNonce(`${nonce}x`, 1_700_000_000_000), false); assert.equal(verifyAccountActionNonce(nonce, 1_700_000_000_000 + 45 * 60_000), false); - const missingNonceRes = await executeAccountCredentialAction({ + // Default risk gate blocks mutations until accepted, and list returns riskLocked without vault access + const riskBlockedRes = await executeAccountCredentialAction({ action: 'remove', email: 'a@example.com', }); + assert.equal(JSON.parse(riskBlockedRes.body).error, 'riskNotAccepted'); + + const riskLockedList = JSON.parse((await executeAccountCredentialAction(undefined)).body); + assert.equal(riskLockedList.riskLocked, true); + assert.deepEqual(riskLockedList.accounts, []); + + // Once risk check passes, mutations still require a valid HMAC actionNonce + const missingNonceRes = await executeAccountCredentialAction( + { action: 'remove', email: 'a@example.com' }, + { bypassRiskCheck: true } + ); const missingBody = JSON.parse(missingNonceRes.body); assert.equal(missingBody.error, 'invalidActionNonce'); assert.equal(typeof missingBody.actionNonce, 'string'); + + // Quota history tracker compresses flat heartbeats while preserving real dips and QR seeds + let persistedHistory = null; + const histTracker = createAccountQuotaHistoryTracker({ + loadState: () => null, + saveState: (p) => { + persistedHistory = p; + }, + loadSeedEvents: () => ({ + events: [ + { ts: '2026-11-24T08:00:00.000Z', pool: 'Gemini', win: '5h', usedPct: 4.0 }, + { ts: '2026-11-24T09:00:00.000Z', pool: 'Gemini', win: '5h', usedPct: 10.4 }, + ], + }), + }); + const baseTs = Date.parse('2026-11-24T10:00:00.000Z'); + histTracker.recordSnapshot( + 'owner@example.com', + [ + { poolKey: 'Gemini', remainingPct: 89.6, weeklyRemainingPct: 89.4 }, + { poolKey: 'Claude & GPT', remainingPct: 100, weeklyRemainingPct: 100 }, + ], + baseTs, + { isActiveHost: true } + ); + histTracker.recordSnapshot( + 'owner@example.com', + [{ poolKey: 'Claude & GPT', remainingPct: 100, weeklyRemainingPct: 100 }], + baseTs + 20 * 60_000 + ); + histTracker.recordSnapshot( + 'owner@example.com', + [{ poolKey: 'Claude & GPT', remainingPct: 100, weeklyRemainingPct: 100 }], + baseTs + 40 * 60_000 + ); + histTracker.flush(baseTs + 40 * 60_000); + const payload = histTracker.getHistoryPayload({ allowedEmails: ['owner@example.com'] }); + assert.equal( + payload['owner@example.com'].pools['Claude & GPT'].points.length, + 2, + 'Collinear flat heartbeats must compress in-place to start + latest endpoints' + ); + assert.equal(payload['owner@example.com'].pools.Gemini.points[0][1], 96); + assert.equal(payload['owner@example.com'].pools.Gemini.points.at(-1)[1], 89.6); + assert.ok(persistedHistory?.accounts?.['owner@example.com']); }); test('secondary passphrase encrypts credentials with scrypt + AES-256-GCM, preserves cached list while locked, throttles brute force, and rotates/resets cleanly', { skip: process.platform !== 'win32' }, async (t) => { @@ -595,3 +660,108 @@ test('secondary passphrase encrypts credentials with scrypt + AES-256-GCM, prese ); assert.deepEqual(resetRes.accounts, []); }); + +test('cycle quota chart strips pre-reset tail points and cross-account impulse spikes', () => { + const cycleStartMs = 1795518262000; // 20:04:22 + const reset5hMs = cycleStartMs + 5 * 3600_000; // 01:04:22 + const nowMs = cycleStartMs + 3.5 * 3600_000; + + // Unused 100% pool appears first with rolling reset (now + 5h), active Gemini pool second + const pools = [ + { + poolKey: 'Argon', + label: 'Argon', + reset5hMs: nowMs + 5 * 3600_000 - 15_000, + resetWeeklyMs: nowMs + 7 * 86400_000, + live5h: 100, + liveWk: 100, + points: [[nowMs, 100, 100]], + }, + { + poolKey: 'Gemini', + label: 'Gemini', + reset5hMs, + resetWeeklyMs: nowMs + 6 * 86400_000, + live5h: 88.2, + liveWk: 89.2, + points: [ + [cycleStartMs - 47_000, 84.5, 92.4], // 20:03:35 pre-reset old cycle point + [cycleStartMs + 3_582, 100, 92.4], // 20:04:25 fresh cycle reset + [cycleStartMs + 58 * 60_000, 94.8, 90.6], // 21:02:00 + [cycleStartMs + 61 * 60_000, 100, 100], // 21:05:19 isolated cross-account init spike + [cycleStartMs + 63 * 60_000, 94.7, 90.6], // 21:07:33 back to real slope + [nowMs, 88.2, 89.2], + ], + }, + ]; + + const bounds = resolveQuotaWindowBounds({ + pools, + selectedRange: 'cycle', + selectedWin: '5h', + selectedPool: 'all', + nowMs, + }); + assert.equal(bounds.startMs, cycleStartMs, 'Active consumed pool must anchor cycle start'); + + const built = buildQuotaWindowSeries({ + visiblePools: pools, + rawBounds: bounds, + selectedRange: 'cycle', + selectedWin: '5h', + nowMs, + }); + const geminiSeries = built.rawBuilt.find((s) => s.poolKey === 'Gemini'); + assert.ok(geminiSeries); + assert.equal( + geminiSeries.rawPoints[0].val, + 100, + 'Cycle start must begin at 100% without carrying 84.5% from the expired cycle' + ); + for (let i = 1; i < geminiSeries.rawPoints.length; i++) { + const jump = geminiSeries.rawPoints[i].val - geminiSeries.rawPoints[i - 1].val; + assert.ok(jump < 1, `Unexpected upward spike inside cycle series: +${jump}`); + } + + // Even when a stale pre-reset poll lands slightly inside cycleStartMs due to clock jitter, + // cycle mode must slice after the reset jump instead of drawing an upward vertical wall. + const jitterBuilt = buildQuotaWindowSeries({ + visiblePools: [ + { + poolKey: 'Gemini', + label: 'Gemini', + reset5hMs, + resetWeeklyMs: 0, + live5h: 95, + liveWk: null, + points: [ + [cycleStartMs + 2_000, 84.5, 92.4], + [cycleStartMs + 15_000, 100, 92.4], + [nowMs, 95, 91.8], + ], + }, + ], + rawBounds: bounds, + selectedRange: 'cycle', + selectedWin: '5h', + nowMs, + }); + assert.equal(jitterBuilt.rawBuilt[0].rawPoints[0].val, 100); + + // Backend history sanitizer removes isolated cross-account impulse spikes while keeping real resets + const persistedPts = [ + [cycleStartMs - 60_000, 84.5, 92.4], + [cycleStartMs + 3_000, 100, 92.4], + [cycleStartMs + 58 * 60_000, 94.8, 90.6], + [cycleStartMs + 61 * 60_000, 100, 100], + [cycleStartMs + 63 * 60_000, 94.7, 90.6], + ]; + assert.equal(sanitizeQuotaHistoryPoints(persistedPts), true); + assert.equal(persistedPts.length, 4); + assert.equal(persistedPts[1][1], 100, 'Genuine 5h reset stays intact for multi-cycle views'); + assert.equal( + persistedPts.some((p) => p[0] === cycleStartMs + 61 * 60_000), + false, + 'Isolated cross-account [100, 100] spike is removed' + ); +}); diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index fb4dfda..641ef63 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -33,16 +33,17 @@ const BACKEND_MODULE_FILES = [ '../shared/prompt-clean.mjs', '../backend/fs-atomic.mjs', '../backend/context-windows.mjs', - '../backend/account-oauth.mjs', - '../backend/account-login.mjs', - '../backend/account-vault-crypto.mjs', - '../backend/account-switch.mjs', '../backend/http-helpers.mjs', '../backend/settings-schema.mjs', '../backend/sqlite-client.mjs', '../backend/trajectory-sqlite-ledger.mjs', '../backend/trajectory-cache-store.mjs', '../backend/config.mjs', + '../backend/account-quota-history.mjs', + '../backend/account-oauth.mjs', + '../backend/account-login.mjs', + '../backend/account-vault-crypto.mjs', + '../backend/account-switch.mjs', '../backend/endpoint-registry.mjs', '../backend/proto-wire.mjs', '../backend/cli-sqlite-reader.mjs', diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 437e030..be84a3f 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -2062,6 +2062,30 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro await new Promise((r) => setTimeout(r, 35)); assert.equal(accountPane.hasAttribute('hidden'), false); assert.equal(accountPane.querySelector('.settings-account-identity').textContent, 'test@example.com'); + assert.equal(accountPane.querySelector('.account-active-dot'), null, 'Active account must not render a green dot'); + + // Quota trend chart is visible even before risk acceptance, using full 184px .trend-svg height and all 8 presets + const quotaTrendPanel = accountPane.querySelector('.account-quota-trend-panel'); + assert.ok(quotaTrendPanel && !quotaTrendPanel.hasAttribute('hidden'), 'Quota trend chart card must be visible'); + const quotaTrendSvg = quotaTrendPanel.querySelector('svg.trend-svg'); + assert.ok(quotaTrendSvg, 'Quota trend chart must reuse 184px .trend-svg'); + assert.equal(quotaTrendSvg.getAttribute('viewBox'), '0 0 460 184'); + const trendSegLabels = quotaTrendPanel.querySelectorAll('.seg-btn').map((b) => b.textContent); + for (const expectedRange of ['周期', '今天', '1天', '7天', '14天', '30天', '全部', '自定义']) { + assert.ok(trendSegLabels.includes(expectedRange), `Quota trend chart must include ${expectedRange}`); + } + + // Default risk gate locks multi-account management until explicitly accepted + const accountRiskMask = accountPane.querySelector('.settings-account-risk-mask'); + assert.ok(accountRiskMask && !accountRiskMask.hasAttribute('hidden'), 'Multi-account risk mask must be visible by default'); + assert.equal(accountRequests.some((item) => item.action === 'quota'), false, 'Must not poll backup quotas before risk acceptance'); + + const accountRiskAcceptBtn = accountPane.querySelector('.settings-account-risk-accept'); + accountRiskAcceptBtn.dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 35)); + assert.equal(mockSettings.accountSwitchRiskAccepted, true); + assert.equal(accountRiskMask.hasAttribute('hidden'), true); + assert.ok(accountPane.querySelectorAll('.settings-account-quota').some((el) => el.textContent === '5 小时 70%')); assert.ok(accountRequests.some((item) => item.action === 'quota' && item.email === 'next@example.com')); const googleLogin = accountPane.querySelector('.settings-account-login'); From e8616ab0c32dfc413f6c6233917ab9a4ecf0488f Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Wed, 25 Nov 2026 01:32:00 +0900 Subject: [PATCH 23/30] feat(panel): unify chart motion and preserve pending TTFT reel roll - Extract shared chartMotion and stepChartMath modules to bring GPU 2D pointer-following tooltips, cached tooltip geometry, cubic curve/band morphing, and quantized hover hit-testing to Summary step/fit charts and AccountQuotaTrendCard - Hide chart peak pills whenever all plotted values are zero and keep them hidden across hover and mouseleave transitions - Hold the active conversation's last valid TTFT and mounted odometer digit reels while a new step's TTFT is still pending, and add @starting-style reel entry transitions --- sidecars/panel/app.js | 2715 ++++++++++++----- sidecars/panel/backend/telemetry-builder.mjs | 27 + sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 2 + .../components/charts/SessionStepCharts.js | 1339 +++----- .../src/components/charts/TrendAreaChart.js | 513 +--- .../src/components/charts/chartMotion.js | 1080 +++++++ .../src/components/charts/stepChartMath.js | 665 ++++ .../widgets/AccountQuotaTrendCard.js | 478 ++- .../components/widgets/CapsuleBarWidget.js | 67 +- sidecars/panel/src/store/telemetryStore.js | 3 + sidecars/panel/src/styles/modern-ui.css | 24 +- .../panel/src/styles/views-consumption.css | 40 +- sidecars/panel/src/styles/views-tables.css | 1 + sidecars/panel/styles.css | 65 +- sidecars/panel/test/modern-ui.test.mjs | 280 +- 16 files changed, 5105 insertions(+), 2198 deletions(-) create mode 100644 sidecars/panel/src/components/charts/chartMotion.js create mode 100644 sidecars/panel/src/components/charts/stepChartMath.js diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index c903e24..5dd7476 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -9910,6 +9910,7 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false; if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false; if (pAct?.aggregated?.latestTtftSec !== nAct?.aggregated?.latestTtftSec) return false; + if (pAct?.aggregated?.lastKnownTtftSec !== nAct?.aggregated?.lastKnownTtftSec) return false; if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false; if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false; if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false; @@ -9921,6 +9922,7 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.lastKnownTtftSec !== nAct?.lastKnownTtftSec) return false; if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false; if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false; if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false; @@ -9959,6 +9961,7 @@ function isEquivalentTelemetry(prev, next) { pa?.liveActivity?.signature !== na?.liveActivity?.signature || pa?.latestTokPerSec !== na?.latestTokPerSec || pa?.latestTtftSec !== na?.latestTtftSec || + pa?.lastKnownTtftSec !== na?.lastKnownTtftSec || pa?.avgTokPerSec !== na?.avgTokPerSec || pa?.latestCacheHitPct !== na?.latestCacheHitPct || pa?.sessionCacheHitPct !== na?.sessionCacheHitPct || @@ -14015,91 +14018,218 @@ function createConsumptionBreakdownContent({ return { createConsumptionBreakdownContent }; })(); -// --- src/components/charts/TrendAreaChart.js --- -const { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart } = (() => { +// --- src/components/charts/chartMotion.js --- +const { CHART_CURVE_MORPH_MS, canAnimateChartInBrowser, evalCubicBezier, createReadyClassArmer, pointsToNormalizedCubicSegs, buildPathFromNormalizedSegs, createCubicCurveMorphController, createMultiSeriesCurveMorphController, createFitGridMorphController, createFloatingChartTooltipController } = (() => { /** - * @fileoverview 交互式历史用量趋势图组件 (TrendAreaChart). - * 支持双模式自适应切换: - * 1. <= 90 天(或整点小时分桶):渲染三次贝塞尔平滑曲线面积图、峰值气泡与对齐多刻度时间轴; - * 2. > 90 天(自然日分桶):自动切换为类 GitHub 贡献日历的小格子热力排列(一格一天,7 行星期 × 周列、月份刻度、分位数 5 档热力色阶与底部图例); - * 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。 - */ - - -/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ -const HEATMAP_DAYS_THRESHOLD = 90; - -let chartUidCounter = 0; - -function safeSlotTokens(v) { - const n = Number(v); - return Number.isFinite(n) && n > 0 ? n : 0; -} - -/** - * 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。 - * 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平, - * 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。 + * @fileoverview Shared interactive chart motion & 2D mouse-following tooltip primitives (`chartMotion.js`). * - * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组(长度 >= 2) - * @returns {string} SVG `` 的 `d` 属性字符串 + * Reused across: + * 1. `TrendAreaChart.js` (ConsumptionView usage trend & heatmap); + * 2. `SessionStepCharts.js` (StepsDetailView summary step line chart & LOESS model fit chart); + * 3. `AccountQuotaTrendCard.js` (SettingsAccountTab per-account quota trajectory chart). + * + * Provides: + * - GPU-composited 2D pointer-following floating tooltip (`translate3d`) with 4-way collision + * avoidance, viewport clipping, cached layout rects, and `150ms` `.is-tracking` arming + * synchronized with SVG focus dots (`.trend-hover-dot` / `.sstep-hover-raw-dot`); + * - Exact CSS `cubic-bezier` solver (`evalCubicBezier`) and `240ms` normalized cubic-Bezier + * chain subdivision morphing for single-series and multi-series curves + area fills; + * - Smooth `240ms` LOESS curve, `95% CI` confidence band, and OLS line morphing; + * - Next-frame `.is-ready` transition arming for sliding peak badges (`.trend-peak-pill`). */ -function buildSmoothSplinePath(points) { - let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; - for (let i = 0; i < points.length - 1; i++) { - const p0 = points[i]; - const p1 = points[i + 1]; - const cpx1 = p0.x + (p1.x - p0.x) * 0.42; - const cpx2 = p1.x - (p1.x - p0.x) * 0.42; - d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; + + +const CHART_CURVE_MORPH_MS = 240; + +/** + * Checks whether smooth `requestAnimationFrame` chart animations should run in the current + * environment (browser runtime with `prefers-reduced-motion` not enabled). + */ +function canAnimateChartInBrowser() { + if ( + typeof window === 'undefined' || + typeof window.requestAnimationFrame !== 'function' || + typeof window.getComputedStyle !== 'function' || + typeof performance === 'undefined' || + typeof performance.now !== 'function' + ) { + return false; } - return d; + if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) { + return false; + } + return true; } /** - * 将采样点数组转为归一化横轴 `u` (`0..1`) 上的精确三次贝塞尔分段链, - * 控制点严格保持跟 `buildSmoothSplinePath` 一致的 `0.42` 水平张力。 - * - * @param {Array<{ y: number }>} pts - * @param {number} bottomY - * @returns {Array<{ u0: number, y0: number, cu1: number, cy1: number, cu2: number, cy2: number, u3: number, y3: number }>} + * Solves standard CSS `cubic-bezier(x1, y1, x2, y2)` at progress `t` (`0..1`) + * so JS path morphing, peak-pill gliding, and CSS bar transitions stay in lockstep. */ -function pointsToNormalizedCubicSegs(pts, bottomY) { - const n = pts.length; +function evalCubicBezier(x1, y1, x2, y2, t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + let lo = 0; + let hi = 1; + for (let i = 0; i < 16; i++) { + const s = (lo + hi) * 0.5; + const inv = 1 - s; + const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s; + if (bx < t) lo = s; + else hi = s; + } + const s = (lo + hi) * 0.5; + const inv = 1 - s; + return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s; +} + +/** + * Arms a CSS transition readiness class (e.g. `.is-ready` on `.trend-peak-pill`) on the next + * animation frame so initial placement snaps cleanly without sliding in from `50%`. + */ +function createReadyClassArmer(el, readyClass = 'is-ready') { + let armed = false; + let rafId = 0; + + function cancel() { + if (rafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(rafId); + } + rafId = 0; + } + + function arm() { + if (armed) return; + armed = true; + if (canAnimateChartInBrowser()) { + rafId = window.requestAnimationFrame(() => { + rafId = 0; + patchClasses(el, { [readyClass]: true }); + }); + } else { + patchClasses(el, { [readyClass]: true }); + } + } + + return { arm, cancel }; +} + +/** + * Converts 2D SVG points into a normalized horizontal (`u` in `0..1`) cubic-Bezier chain + * with horizontal endpoint tangents (`0.42` tension by default, zero vertical overshoot). + * Supports both uniform slot spacing and arbitrary timestamp/x coordinates via `leftX` + `spanX`. + * + * @param {Array<{ x?: number, y: number }>} pts + * @param {number} bottomY + * @param {{ leftX?: number, spanX?: number, tension?: number }} [opts] + */ +function pointsToNormalizedCubicSegs( + pts, + bottomY, + { leftX = 0, spanX = 0, tension = 0.42 } = {} +) { + const n = Array.isArray(pts) ? pts.length : 0; + const invT = 1 - tension; if (n === 0) { return [ - { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, + { + u0: 0, + y0: bottomY, + cu1: tension, + cy1: bottomY, + cu2: invT, + cy2: bottomY, + u3: 1, + y3: bottomY, + }, ]; } if (n === 1) { const py = pts[0].y; + const uMid = + spanX > 0 && Number.isFinite(pts[0].x) + ? Math.max(0, Math.min(1, (pts[0].x - leftX) / spanX)) + : 0.5; if (Math.abs(py - bottomY) < 0.01) { return [ - { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, + { + u0: 0, + y0: bottomY, + cu1: tension, + cy1: bottomY, + cu2: invT, + cy2: bottomY, + u3: 1, + y3: bottomY, + }, ]; } return [ - { u0: 0, y0: bottomY, cu1: 0.21, cy1: bottomY, cu2: 0.29, cy2: py, u3: 0.5, y3: py }, - { u0: 0.5, y0: py, cu1: 0.71, cy1: py, cu2: 0.79, cy2: bottomY, u3: 1, y3: bottomY }, + { + u0: 0, + y0: bottomY, + cu1: uMid * tension, + cy1: bottomY, + cu2: uMid * invT, + cy2: py, + u3: uMid, + y3: py, + }, + { + u0: uMid, + y0: py, + cu1: uMid + (1 - uMid) * tension, + cy1: py, + cu2: uMid + (1 - uMid) * invT, + cy2: bottomY, + u3: 1, + y3: bottomY, + }, ]; } - const segs = new Array(n - 1); - for (let i = 0; i < n - 1; i++) { - const u0 = i / (n - 1); - const u3 = (i + 1) / (n - 1); - const du = u3 - u0; - const y0 = pts[i].y; - const y3 = pts[i + 1].y; - segs[i] = { - u0, - y0, - cu1: u0 + du * 0.42, - cy1: y0, - cu2: u3 - du * 0.42, + + const useCoordU = spanX > 0 && Number.isFinite(pts[0].x); + const segs = []; + let prevU = useCoordU ? Math.max(0, Math.min(1, (pts[0].x - leftX) / spanX)) : 0; + let prevY = pts[0].y; + + for (let i = 1; i < n; i++) { + const rawU = useCoordU + ? Math.max(0, Math.min(1, (pts[i].x - leftX) / spanX)) + : i / (n - 1); + const u3 = Math.max(prevU, rawU); + const y3 = pts[i].y; + if (u3 - prevU <= 1e-6 && i < n - 1 && Math.abs(y3 - prevY) < 0.05) { + continue; + } + const safeU3 = u3 - prevU <= 1e-6 ? Math.min(1, prevU + 1e-5) : u3; + const du = safeU3 - prevU; + segs.push({ + u0: prevU, + y0: prevY, + cu1: prevU + du * tension, + cy1: prevY, + cu2: safeU3 - du * tension, cy2: y3, - u3, + u3: safeU3, y3, - }; + }); + prevU = safeU3; + prevY = y3; + } + + if (segs.length === 0) { + return [ + { + u0: prevU, + y0: prevY, + cu1: prevU, + cy1: prevY, + cu2: prevU, + cy2: prevY, + u3: prevU, + y3: prevY, + }, + ]; } return segs; } @@ -14159,39 +14289,79 @@ function extractCubicSubsegment(seg, uStart, uEnd) { } /** - * 合并两条贝塞尔链的断点(始终完整保留目标链 `toSegs` 全部断点,保证 `t=1` 零几何误差)。 + * Aligns two cubic-Bezier chains (`fromSegs` and `toSegs`, even when their horizontal `[uStart, uEnd]` + * spans differ) onto a shared normalized `[0..1]` knot partition so every segment pair interpolates + * smoothly without endpoint snapping. */ -function mergeNormalizedKnots(fromSegs, toSegs) { - const raw = [0, 1]; - for (let i = 0; i < toSegs.length; i++) raw.push(toSegs[i].u3); - if (fromSegs.length <= 64) { - for (let i = 0; i < fromSegs.length; i++) raw.push(fromSegs[i].u3); - } else { - const stride = Math.ceil(fromSegs.length / 48); - for (let i = 0; i < fromSegs.length; i += stride) raw.push(fromSegs[i].u3); - } - raw.sort((a, b) => a - b); - const uniq = [0]; - for (let i = 1; i < raw.length; i++) { - if (raw[i] - uniq[uniq.length - 1] > 1e-6) { - uniq.push(raw[i]); +function alignCubicChainsForMorph(fromSegs, toSegs) { + const fStart = fromSegs[0].u0; + const fEnd = fromSegs[fromSegs.length - 1].u3; + const fSpan = fEnd - fStart; + + const tStart = toSegs[0].u0; + const tEnd = toSegs[toSegs.length - 1].u3; + const tSpan = tEnd - tStart; + + const rawTau = [0, 1]; + const pushChainKnots = (segs, start, span, cap) => { + if (!(span > 1e-6)) return; + if (segs.length <= cap) { + for (let i = 0; i < segs.length; i++) { + rawTau.push(Math.max(0, Math.min(1, (segs[i].u3 - start) / span))); + } + } else { + const stride = Math.ceil(segs.length / cap); + for (let i = 0; i < segs.length; i += stride) { + rawTau.push(Math.max(0, Math.min(1, (segs[i].u3 - start) / span))); + } + } + }; + pushChainKnots(toSegs, tStart, tSpan, 96); + pushChainKnots(fromSegs, fStart, fSpan, 48); + + rawTau.sort((a, b) => a - b); + const tauKnots = [0]; + for (let i = 1; i < rawTau.length; i++) { + if (rawTau[i] - tauKnots[tauKnots.length - 1] > 1e-5) { + tauKnots.push(rawTau[i]); } } - uniq[uniq.length - 1] = 1; - return uniq; -} + if (tauKnots.length === 1) tauKnots.push(1); + else tauKnots[tauKnots.length - 1] = 1; -function subdivideChainToKnots(segs, knots) { - const out = new Array(knots.length - 1); - let j = 0; - for (let k = 0; k < knots.length - 1; k++) { - const a = knots[k]; - const b = knots[k + 1]; - const mid = (a + b) * 0.5; - while (j < segs.length - 1 && segs[j].u3 < mid) j++; - out[k] = extractCubicSubsegment(segs[j], a, b); - } - return out; + const subdivideOnTau = (segs, start, span) => { + const out = new Array(tauKnots.length - 1); + let j = 0; + for (let k = 0; k < tauKnots.length - 1; k++) { + const ta = tauKnots[k]; + const tb = tauKnots[k + 1]; + if (!(span > 1e-6)) { + const s0 = segs[0]; + out[k] = { + u0: start, + y0: s0.y0, + cu1: start, + cy1: s0.y0, + cu2: start, + cy2: s0.y3, + u3: start, + y3: s0.y3, + }; + continue; + } + const ua = start + ta * span; + const ub = start + tb * span; + const umid = (ua + ub) * 0.5; + while (j < segs.length - 1 && segs[j].u3 < umid) j++; + out[k] = extractCubicSubsegment(segs[j], ua, ub); + } + return out; + }; + + return { + alignedFrom: subdivideOnTau(fromSegs, fStart, fSpan), + alignedTo: subdivideOnTau(toSegs, tStart, tSpan), + }; } function buildPathFromNormalizedSegs(segs, leftX, spanX) { @@ -14205,24 +14375,772 @@ function buildPathFromNormalizedSegs(segs, leftX, spanX) { } /** - * 求解标准 CSS `cubic-bezier(x1, y1, x2, y2)` 在进度 `t` (`0..1`) 处的精确输出值, - * 确保 JS 曲线形变、峰值胶囊滑动及进度条宽度缩放严格同频。 + * Single-series cubic-Bezier curve + area fill morph controller (used by `TrendAreaChart` and + * single-series `SessionStepCharts`). */ -function evalCubicBezier(x1, y1, x2, y2, t) { - if (t <= 0) return 0; - if (t >= 1) return 1; - let lo = 0; - let hi = 1; - for (let i = 0; i < 16; i++) { - const s = (lo + hi) * 0.5; - const inv = 1 - s; - const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s; - if (bx < t) lo = s; - else hi = s; +function createCubicCurveMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { + let morphRafId = 0; + let committedSegs = []; + let liveMorphSegs = null; + let hasRenderedOnce = false; + + function cancel() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; } - const s = (lo + hi) * 0.5; - const inv = 1 - s; - return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s; + + function reset() { + cancel(); + committedSegs = []; + liveMorphSegs = null; + hasRenderedOnce = false; + } + + function morphTo({ + nextSegs, + leftX, + spanX, + bottomY, + linePath, + areaPath = null, + finalLineD, + finalAreaD = '', + skipMorph = false, + }) { + const prevSegs = liveMorphSegs || committedSegs; + committedSegs = nextSegs; + + if ( + skipMorph || + !hasRenderedOnce || + !canAnimateChartInBrowser() || + prevSegs.length === 0 || + nextSegs.length === 0 + ) { + hasRenderedOnce = true; + cancel(); + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + if (areaPath) patchAttr(areaPath, 'd', finalAreaD); + return; + } + hasRenderedOnce = true; + cancel(); + + const { alignedFrom, alignedTo } = alignCubicChainsForMorph(prevSegs, nextSegs); + const segCount = alignedTo.length; + let maxDelta = 0; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + maxDelta = Math.max( + maxDelta, + Math.abs(b.y0 - a.y0), + Math.abs(b.cy1 - a.cy1), + Math.abs(b.cy2 - a.cy2), + Math.abs(b.y3 - a.y3), + Math.abs(b.u0 - a.u0) * spanX, + Math.abs(b.u3 - a.u3) * spanX + ); + } + + if (maxDelta < 0.25) { + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + if (areaPath) patchAttr(areaPath, 'd', finalAreaD); + return; + } + + const activeLive = alignedFrom.map((s) => ({ ...s })); + liveMorphSegs = activeLive; + const startTs = performance.now(); + + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / durationMs); + if (rawT >= 1) { + morphRafId = 0; + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + if (areaPath) patchAttr(areaPath, 'd', finalAreaD); + return; + } + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + const cur = activeLive[i]; + cur.u0 = a.u0 + (b.u0 - a.u0) * ease; + cur.y0 = a.y0 + (b.y0 - a.y0) * ease; + cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; + cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; + cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; + cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; + cur.u3 = a.u3 + (b.u3 - a.u3) * ease; + cur.y3 = a.y3 + (b.y3 - a.y3) * ease; + } + const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); + patchAttr(linePath, 'd', morphLineD); + if (areaPath) { + const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); + const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); + patchAttr(areaPath, 'd', `${morphLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); + } + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } + + return { morphTo, cancel, reset }; +} + +/** + * Coalesced multi-series cubic-Bezier curve, area fill, and endpoint dot morph controller + * (used by `AccountQuotaTrendCard` and multi-model `SessionStepCharts`). + */ +function createMultiSeriesCurveMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { + let morphRafId = 0; + const stateByKey = new Map(); + + function cancel() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; + } + + function reset() { + cancel(); + stateByKey.clear(); + } + + function morphSeries({ + items, + leftX, + spanX, + bottomY, + skipMorph = false, + }) { + cancel(); + const canAnim = !skipMorph && canAnimateChartInBrowser(); + const activeSet = new Set(); + const jobs = []; + + for (let idx = 0; idx < items.length; idx++) { + const it = items[idx]; + activeSet.add(it.key); + const prevEntry = stateByKey.get(it.key); + const prevSegs = prevEntry ? prevEntry.liveSegs || prevEntry.committedSegs : null; + + if (!canAnim || !prevSegs || prevSegs.length === 0 || it.nextSegs.length === 0) { + stateByKey.set(it.key, { + committedSegs: it.nextSegs, + liveSegs: null, + endX: it.endX, + endY: it.endY, + }); + patchAttr(it.lineEl, 'd', it.finalLineD); + if (it.areaEl) patchAttr(it.areaEl, 'd', it.finalAreaD || ''); + if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { + patchAttr(it.endDotEl, 'cx', it.endX.toFixed(1)); + patchAttr(it.endDotEl, 'cy', it.endY.toFixed(1)); + } + continue; + } + + const { alignedFrom, alignedTo } = alignCubicChainsForMorph(prevSegs, it.nextSegs); + const segCount = alignedTo.length; + let maxDelta = 0; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + maxDelta = Math.max( + maxDelta, + Math.abs(b.y0 - a.y0), + Math.abs(b.cy1 - a.cy1), + Math.abs(b.cy2 - a.cy2), + Math.abs(b.y3 - a.y3), + Math.abs(b.u0 - a.u0) * spanX, + Math.abs(b.u3 - a.u3) * spanX + ); + } + + if (maxDelta < 0.25) { + stateByKey.set(it.key, { + committedSegs: it.nextSegs, + liveSegs: null, + endX: it.endX, + endY: it.endY, + }); + patchAttr(it.lineEl, 'd', it.finalLineD); + if (it.areaEl) patchAttr(it.areaEl, 'd', it.finalAreaD || ''); + if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { + patchAttr(it.endDotEl, 'cx', it.endX.toFixed(1)); + patchAttr(it.endDotEl, 'cy', it.endY.toFixed(1)); + } + continue; + } + + const activeLive = alignedFrom.map((s) => ({ ...s })); + const fromEndX = Number.isFinite(prevEntry?.endX) + ? prevEntry.endX + : leftX + alignedFrom[segCount - 1].u3 * spanX; + const fromEndY = Number.isFinite(prevEntry?.endY) + ? prevEntry.endY + : alignedFrom[segCount - 1].y3; + const stateRec = { + committedSegs: it.nextSegs, + liveSegs: activeLive, + endX: fromEndX, + endY: fromEndY, + }; + stateByKey.set(it.key, stateRec); + jobs.push({ + it, + alignedFrom, + alignedTo, + activeLive, + segCount, + fromEndX, + fromEndY, + stateRec, + }); + } + + for (const k of Array.from(stateByKey.keys())) { + if (!activeSet.has(k)) stateByKey.delete(k); + } + + if (jobs.length === 0) return; + + const startTs = performance.now(); + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / durationMs); + if (rawT >= 1) { + morphRafId = 0; + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + jb.stateRec.liveSegs = null; + jb.stateRec.endX = jb.it.endX; + jb.stateRec.endY = jb.it.endY; + patchAttr(jb.it.lineEl, 'd', jb.it.finalLineD); + if (jb.it.areaEl) patchAttr(jb.it.areaEl, 'd', jb.it.finalAreaD || ''); + if (jb.it.endDotEl && Number.isFinite(jb.it.endX) && Number.isFinite(jb.it.endY)) { + patchAttr(jb.it.endDotEl, 'cx', jb.it.endX.toFixed(1)); + patchAttr(jb.it.endDotEl, 'cy', jb.it.endY.toFixed(1)); + } + } + return; + } + + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + const { alignedFrom, alignedTo, activeLive, segCount, it } = jb; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + const cur = activeLive[i]; + cur.u0 = a.u0 + (b.u0 - a.u0) * ease; + cur.y0 = a.y0 + (b.y0 - a.y0) * ease; + cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; + cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; + cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; + cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; + cur.u3 = a.u3 + (b.u3 - a.u3) * ease; + cur.y3 = a.y3 + (b.y3 - a.y3) * ease; + } + const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); + patchAttr(it.lineEl, 'd', morphLineD); + if (it.areaEl && it.finalAreaD) { + const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); + const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); + patchAttr(it.areaEl, 'd', `${morphLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); + } + if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { + const cx = jb.fromEndX + (it.endX - jb.fromEndX) * ease; + const cy = jb.fromEndY + (it.endY - jb.fromEndY) * ease; + jb.stateRec.endX = cx; + jb.stateRec.endY = cy; + patchAttr(it.endDotEl, 'cx', cx.toFixed(1)); + patchAttr(it.endDotEl, 'cy', cy.toFixed(1)); + } + } + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } + + return { morphSeries, cancel, reset }; +} + +function buildGridFitPolylineD(grid) { + if (!grid.length) return ''; + let d = `M ${grid[0].x.toFixed(1)} ${grid[0].fitY.toFixed(1)}`; + for (let i = 1; i < grid.length; i++) { + d += ` L ${grid[i].x.toFixed(1)} ${grid[i].fitY.toFixed(1)}`; + } + return d; +} + +function buildGridCiBandD(grid) { + if (grid.length < 2) return ''; + let d = `M ${grid[0].x.toFixed(1)} ${grid[0].highY.toFixed(1)}`; + for (let i = 1; i < grid.length; i++) { + d += ` L ${grid[i].x.toFixed(1)} ${grid[i].highY.toFixed(1)}`; + } + for (let i = grid.length - 1; i >= 0; i--) { + d += ` L ${grid[i].x.toFixed(1)} ${grid[i].lowY.toFixed(1)}`; + } + return `${d} Z`; +} + +/** + * Smoothly morphs LOESS fit polylines, `95% CI` confidence bands, and optional OLS lines + * across metric/model switches in `createModelFitChart`. + */ +function createFitGridMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { + let morphRafId = 0; + const stateByKey = new Map(); + + function cancel() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; + } + + function reset() { + cancel(); + stateByKey.clear(); + } + + function morphFits({ items, skipMorph = false }) { + cancel(); + const canAnim = !skipMorph && canAnimateChartInBrowser(); + const activeSet = new Set(); + const jobs = []; + + for (let idx = 0; idx < items.length; idx++) { + const it = items[idx]; + activeSet.add(it.key); + const prevEntry = stateByKey.get(it.key); + const prevGrid = prevEntry ? prevEntry.liveGrid || prevEntry.committedGrid : null; + + if ( + !canAnim || + !prevGrid || + prevGrid.length !== it.gridPts.length || + it.gridPts.length < 2 + ) { + stateByKey.set(it.key, { + committedGrid: it.gridPts, + liveGrid: null, + ols: it.olsCoords || null, + }); + patchAttr(it.curveEl, 'd', it.finalCurveD); + if (it.bandEl) patchAttr(it.bandEl, 'd', it.finalBandD || ''); + if (it.olsEl && it.olsCoords) { + patchAttr(it.olsEl, 'x1', it.olsCoords.x1.toFixed(1)); + patchAttr(it.olsEl, 'y1', it.olsCoords.y1.toFixed(1)); + patchAttr(it.olsEl, 'x2', it.olsCoords.x2.toFixed(1)); + patchAttr(it.olsEl, 'y2', it.olsCoords.y2.toFixed(1)); + } + continue; + } + + let maxDelta = 0; + for (let i = 0; i < it.gridPts.length; i++) { + const a = prevGrid[i]; + const b = it.gridPts[i]; + maxDelta = Math.max( + maxDelta, + Math.abs(b.fitY - a.fitY), + Math.abs(b.highY - a.highY), + Math.abs(b.lowY - a.lowY), + Math.abs(b.x - a.x) + ); + } + if (maxDelta < 0.25) { + stateByKey.set(it.key, { + committedGrid: it.gridPts, + liveGrid: null, + ols: it.olsCoords || null, + }); + patchAttr(it.curveEl, 'd', it.finalCurveD); + if (it.bandEl) patchAttr(it.bandEl, 'd', it.finalBandD || ''); + if (it.olsEl && it.olsCoords) { + patchAttr(it.olsEl, 'x1', it.olsCoords.x1.toFixed(1)); + patchAttr(it.olsEl, 'y1', it.olsCoords.y1.toFixed(1)); + patchAttr(it.olsEl, 'x2', it.olsCoords.x2.toFixed(1)); + patchAttr(it.olsEl, 'y2', it.olsCoords.y2.toFixed(1)); + } + continue; + } + + const activeLive = prevGrid.map((g) => ({ ...g })); + const fromOls = prevEntry?.ols || it.olsCoords || null; + const stateRec = { + committedGrid: it.gridPts, + liveGrid: activeLive, + ols: fromOls ? { ...fromOls } : null, + }; + stateByKey.set(it.key, stateRec); + jobs.push({ it, fromGrid: prevGrid, activeLive, fromOls, stateRec }); + } + + for (const k of Array.from(stateByKey.keys())) { + if (!activeSet.has(k)) stateByKey.delete(k); + } + + if (jobs.length === 0) return; + + const startTs = performance.now(); + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / durationMs); + if (rawT >= 1) { + morphRafId = 0; + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + jb.stateRec.liveGrid = null; + jb.stateRec.ols = jb.it.olsCoords || null; + patchAttr(jb.it.curveEl, 'd', jb.it.finalCurveD); + if (jb.it.bandEl) patchAttr(jb.it.bandEl, 'd', jb.it.finalBandD || ''); + if (jb.it.olsEl && jb.it.olsCoords) { + patchAttr(jb.it.olsEl, 'x1', jb.it.olsCoords.x1.toFixed(1)); + patchAttr(jb.it.olsEl, 'y1', jb.it.olsCoords.y1.toFixed(1)); + patchAttr(jb.it.olsEl, 'x2', jb.it.olsCoords.x2.toFixed(1)); + patchAttr(jb.it.olsEl, 'y2', jb.it.olsCoords.y2.toFixed(1)); + } + } + return; + } + + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + const { fromGrid, activeLive, it } = jb; + for (let i = 0; i < activeLive.length; i++) { + const a = fromGrid[i]; + const b = it.gridPts[i]; + const cur = activeLive[i]; + cur.x = a.x + (b.x - a.x) * ease; + cur.fitY = a.fitY + (b.fitY - a.fitY) * ease; + cur.highY = a.highY + (b.highY - a.highY) * ease; + cur.lowY = a.lowY + (b.lowY - a.lowY) * ease; + } + patchAttr(it.curveEl, 'd', buildGridFitPolylineD(activeLive)); + if (it.bandEl && it.finalBandD) { + patchAttr(it.bandEl, 'd', buildGridCiBandD(activeLive)); + } + if (it.olsEl && it.olsCoords && jb.fromOls) { + const ox1 = jb.fromOls.x1 + (it.olsCoords.x1 - jb.fromOls.x1) * ease; + const oy1 = jb.fromOls.y1 + (it.olsCoords.y1 - jb.fromOls.y1) * ease; + const ox2 = jb.fromOls.x2 + (it.olsCoords.x2 - jb.fromOls.x2) * ease; + const oy2 = jb.fromOls.y2 + (it.olsCoords.y2 - jb.fromOls.y2) * ease; + jb.stateRec.ols = { x1: ox1, y1: oy1, x2: ox2, y2: oy2 }; + patchAttr(it.olsEl, 'x1', ox1.toFixed(1)); + patchAttr(it.olsEl, 'y1', oy1.toFixed(1)); + patchAttr(it.olsEl, 'x2', ox2.toFixed(1)); + patchAttr(it.olsEl, 'y2', oy2.toFixed(1)); + } + } + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } + + return { morphFits, cancel, reset }; +} + +/** + * Shared 2D pointer-following floating tooltip & focus-dot tracking controller. + * Positions `.trend-tooltip` smoothly around the pointer (`above -> right -> left -> below`), + * clamps inside the nearest scrollable viewport container, and arms `.is-tracking` (`150ms`) + * on both the tooltip and active SVG focus dots after the initial reveal frame. + */ +function createFloatingChartTooltipController({ + containerEl, + tooltipEl, + defaultTipWidth = 216, + defaultTipHeight = 96, + defaultViewWidth = 460, + defaultViewHeight = 184, + clipSelector = '.view-pane, .cons-view-stage, .models-analytics-pane, .table-viewport', + useFloatingClass = true, +}) { + if (useFloatingClass) { + tooltipEl.classList.add('is-floating-tip'); + } + + let cachedWrapRect = null; + let cachedClipRect = undefined; + let cachedTipW = 0; + let cachedTipH = 0; + let lastSizeKey = null; + let tipTrackRaf = 0; + let activeTrackedDots = []; + + function cancelTrackRaf() { + if ( + tipTrackRaf && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(tipTrackRaf); + } + tipTrackRaf = 0; + } + + function invalidateRects() { + cachedWrapRect = null; + cachedClipRect = undefined; + cachedTipW = 0; + cachedTipH = 0; + lastSizeKey = null; + } + + function getWrapRect() { + if (!cachedWrapRect) { + cachedWrapRect = containerEl.getBoundingClientRect?.() || null; + } + return cachedWrapRect; + } + + function syncTrackedDots(nextDots, isTrackingActive) { + const nextList = Array.isArray(nextDots) ? nextDots.filter(Boolean) : []; + for (let i = 0; i < activeTrackedDots.length; i++) { + const prevDot = activeTrackedDots[i]; + if (!nextList.includes(prevDot)) { + patchClasses(prevDot, { 'is-tracking': false }); + } + } + if (isTrackingActive) { + for (let i = 0; i < nextList.length; i++) { + patchClasses(nextList[i], { 'is-tracking': true }); + } + } + activeTrackedDots = nextList; + } + + function armTracking(wasHidden, nextDots) { + if (!wasHidden) { + syncTrackedDots(nextDots, tooltipEl.classList.contains('is-tracking')); + return; + } + patchClasses(tooltipEl, { 'is-tracking': false }); + const dotList = Array.isArray(nextDots) ? nextDots.filter(Boolean) : []; + for (let i = 0; i < dotList.length; i++) { + patchClasses(dotList[i], { 'is-tracking': false }); + } + activeTrackedDots = dotList; + void tooltipEl.offsetWidth; + cancelTrackRaf(); + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + tipTrackRaf = window.requestAnimationFrame(() => { + tipTrackRaf = 0; + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + for (let i = 0; i < activeTrackedDots.length; i++) { + patchClasses(activeTrackedDots[i], { 'is-tracking': true }); + } + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + for (let i = 0; i < activeTrackedDots.length; i++) { + patchClasses(activeTrackedDots[i], { 'is-tracking': true }); + } + } + } + + function positionNearAnchor({ + fallbackX, + fallbackY, + pointer = null, + viewWidth = defaultViewWidth, + viewHeight = defaultViewHeight, + remeasureTip = false, + }) { + const wrapRect = getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(containerEl.clientWidth || viewWidth || defaultViewWidth); + const wrapH = + wrapRect && wrapRect.height > 0 + ? wrapRect.height + : Number(containerEl.offsetHeight || viewHeight || defaultViewHeight); + + if (remeasureTip || !(cachedTipW > 0) || !(cachedTipH > 0)) { + cachedTipW = Number(tooltipEl.offsetWidth || 0) || defaultTipWidth; + cachedTipH = Number(tooltipEl.offsetHeight || 0) || defaultTipHeight; + } + const tipW = cachedTipW; + const tipH = cachedTipH; + + const hasPointer = + pointer && + Number.isFinite(Number(pointer.clientX)) && + Number.isFinite(Number(pointer.clientY)) && + wrapRect && + wrapRect.width > 0 && + wrapRect.height > 0; + + const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX; + const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY; + + if (cachedClipRect === undefined) { + const clipEl = containerEl.closest?.(clipSelector) || null; + cachedClipRect = clipEl?.getBoundingClientRect?.() || null; + } + const clipRect = cachedClipRect; + const hasClip = Boolean( + clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0 + ); + const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16; + const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16; + + const maxLeft = Math.max(4, wrapW - tipW - 4); + let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2)); + const aboveY = anchorY - tipH - 14; + let topPx; + + if (aboveY >= minY) { + topPx = Math.min(maxY, aboveY); + } else if (anchorX + 16 + tipW <= wrapW - 4) { + leftPx = anchorX + 16; + topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); + } else if (anchorX - 16 - tipW >= 4) { + leftPx = anchorX - 16 - tipW; + topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); + } else { + topPx = Math.max(minY, Math.min(maxY, anchorY + 18)); + } + + patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`); + patchStyleVar(tooltipEl, '--tip-shift', '0px'); + patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`); + } + + function show({ + fallbackX, + fallbackY, + pointer = null, + trackedDots = [], + viewWidth = defaultViewWidth, + viewHeight = defaultViewHeight, + sizeKey = '', + }) { + const wasHidden = tooltipEl.hasAttribute('hidden'); + if (wasHidden) { + patchAttr(tooltipEl, 'hidden', false); + } + const normalizedKey = String(sizeKey || ''); + const shouldRemeasure = wasHidden || normalizedKey !== lastSizeKey; + lastSizeKey = normalizedKey; + positionNearAnchor({ + fallbackX, + fallbackY, + pointer, + viewWidth, + viewHeight, + remeasureTip: shouldRemeasure, + }); + armTracking(wasHidden, trackedDots); + } + + function hide() { + invalidateRects(); + cancelTrackRaf(); + patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': false, + 'is-tracking': false, + }); + for (let i = 0; i < activeTrackedDots.length; i++) { + patchClasses(activeTrackedDots[i], { 'is-tracking': false }); + } + activeTrackedDots = []; + } + + function destroy() { + cancelTrackRaf(); + invalidateRects(); + activeTrackedDots = []; + } + + return { + show, + hide, + getWrapRect, + invalidateRects, + destroy, + }; +} +return { CHART_CURVE_MORPH_MS, canAnimateChartInBrowser, evalCubicBezier, createReadyClassArmer, pointsToNormalizedCubicSegs, buildPathFromNormalizedSegs, createCubicCurveMorphController, createMultiSeriesCurveMorphController, createFitGridMorphController, createFloatingChartTooltipController }; +})(); + +// --- src/components/charts/TrendAreaChart.js --- +const { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart } = (() => { +/** + * @fileoverview 交互式历史用量趋势图组件 (TrendAreaChart). + * 支持双模式自适应切换: + * 1. <= 90 天(或整点小时分桶):渲染三次贝塞尔平滑曲线面积图、峰值气泡与对齐多刻度时间轴; + * 2. > 90 天(自然日分桶):自动切换为类 GitHub 贡献日历的小格子热力排列(一格一天,7 行星期 × 周列、月份刻度、分位数 5 档热力色阶与底部图例); + * 3. 两种模式共享自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数)。 + */ + + +/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ +const HEATMAP_DAYS_THRESHOLD = 90; + +let chartUidCounter = 0; + +function safeSlotTokens(v) { + const n = Number(v); + return Number.isFinite(n) && n > 0 ? n : 0; +} + +/** + * 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。 + * 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平, + * 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。 + * + * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组(长度 >= 2) + * @returns {string} SVG `` 的 `d` 属性字符串 + */ +function buildSmoothSplinePath(points) { + let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; + for (let i = 0; i < points.length - 1; i++) { + const p0 = points[i]; + const p1 = points[i + 1]; + const cpx1 = p0.x + (p1.x - p0.x) * 0.42; + const cpx2 = p1.x - (p1.x - p0.x) * 0.42; + d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; + } + return d; } /** @@ -14799,7 +15717,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { hoverDot.setAttribute('hidden', 'true'); svg.appendChild(hoverDot); - const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); + const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0', hidden: true }); // 共享悬停详情浮层卡片(曲线图和热力格子图共用,含分模型四段进度条及底部四通道明细) const tooltipContent = createConsumptionBreakdownContent({ @@ -14873,6 +15791,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let currentSlots = []; let currentPts = []; + let currentMaxTokens = 0; let currentIsHeatmap = false; let currentHmMode = 'day'; let lastBuildSegmentsFn = null; @@ -14891,161 +15810,22 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { let hoveredCellEl = null; let lastPointer = null; let lastRenderSig = ''; - let hasRenderedLineOnce = false; - let peakReadyArmed = false; - let peakReadyRaf = 0; - let tipTrackRaf = 0; - let morphRafId = 0; - let committedSegs = []; - let liveMorphSegs = null; const vGridLinePool = []; const xAxisTickPool = []; const hmMonthPool = []; const hmCellPool = []; - const CURVE_MORPH_DURATION_MS = 240; - - function cancelCurveMorph() { - if ( - morphRafId && - typeof window !== 'undefined' && - typeof window.cancelAnimationFrame === 'function' - ) { - window.cancelAnimationFrame(morphRafId); - } - morphRafId = 0; - } - - function cancelPeakReadyRaf() { - if ( - peakReadyRaf && - typeof window !== 'undefined' && - typeof window.cancelAnimationFrame === 'function' - ) { - window.cancelAnimationFrame(peakReadyRaf); - } - peakReadyRaf = 0; - } - - function canAnimateInBrowser() { - if ( - typeof window === 'undefined' || - typeof window.requestAnimationFrame !== 'function' || - typeof window.getComputedStyle !== 'function' || - typeof performance === 'undefined' || - typeof performance.now !== 'function' - ) { - return false; - } - if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) { - return false; - } - return true; - } - - function startCurveMorph( - fromSegs, - toSegs, - { leftX, rightX, spanX, finalLineD, finalAreaD } - ) { - cancelCurveMorph(); - if (!canAnimateInBrowser() || fromSegs.length === 0 || toSegs.length === 0) { - liveMorphSegs = null; - patchAttr(linePath, 'd', finalLineD); - patchAttr(areaPath, 'd', finalAreaD); - return; - } - - const knots = mergeNormalizedKnots(fromSegs, toSegs); - const alignedFrom = subdivideChainToKnots(fromSegs, knots); - const alignedTo = subdivideChainToKnots(toSegs, knots); - const segCount = alignedTo.length; - let maxDeltaY = 0; - for (let i = 0; i < segCount; i++) { - const a = alignedFrom[i]; - const b = alignedTo[i]; - maxDeltaY = Math.max( - maxDeltaY, - Math.abs(b.y0 - a.y0), - Math.abs(b.cy1 - a.cy1), - Math.abs(b.cy2 - a.cy2), - Math.abs(b.y3 - a.y3) - ); - } - - if (maxDeltaY < 0.25) { - liveMorphSegs = null; - patchAttr(linePath, 'd', finalLineD); - patchAttr(areaPath, 'd', finalAreaD); - return; - } - - const activeLive = alignedFrom.map((s) => ({ ...s })); - liveMorphSegs = activeLive; - const rightXFixed = rightX.toFixed(1); - const leftXFixed = leftX.toFixed(1); - const startTs = performance.now(); - - const step = (nowTs) => { - const elapsed = Math.max(0, nowTs - startTs); - const rawT = Math.min(1, elapsed / CURVE_MORPH_DURATION_MS); - if (rawT >= 1) { - morphRafId = 0; - liveMorphSegs = null; - patchAttr(linePath, 'd', finalLineD); - patchAttr(areaPath, 'd', finalAreaD); - return; - } - const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); - for (let i = 0; i < segCount; i++) { - const a = alignedFrom[i]; - const b = alignedTo[i]; - const cur = activeLive[i]; - cur.u0 = a.u0 + (b.u0 - a.u0) * ease; - cur.y0 = a.y0 + (b.y0 - a.y0) * ease; - cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; - cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; - cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; - cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; - cur.u3 = a.u3 + (b.u3 - a.u3) * ease; - cur.y3 = a.y3 + (b.y3 - a.y3) * ease; - } - const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); - const morphAreaD = `${morphLineD} L ${rightXFixed} ${BOTTOM_Y} L ${leftXFixed} ${BOTTOM_Y} Z`; - patchAttr(linePath, 'd', morphLineD); - patchAttr(areaPath, 'd', morphAreaD); - morphRafId = window.requestAnimationFrame(step); - }; - - morphRafId = window.requestAnimationFrame(step); - } - - function cancelTipTrackRaf() { - if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { - window.cancelAnimationFrame(tipTrackRaf); - } - tipTrackRaf = 0; - } - - function armTooltipTracking(wasHidden) { - if (!wasHidden) return; - patchClasses(tooltipEl, { 'is-tracking': false }); - patchClasses(hoverDot, { 'is-tracking': false }); - void tooltipEl.offsetWidth; - cancelTipTrackRaf(); - if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { - tipTrackRaf = window.requestAnimationFrame(() => { - tipTrackRaf = 0; - if (!tooltipEl.hasAttribute('hidden')) { - patchClasses(tooltipEl, { 'is-tracking': true }); - patchClasses(hoverDot, { 'is-tracking': true }); - } - }); - } else { - patchClasses(tooltipEl, { 'is-tracking': true }); - patchClasses(hoverDot, { 'is-tracking': true }); - } - } + const curveMorphCtrl = createCubicCurveMorphController(); + const peakReadyArmer = createReadyClassArmer(peakPill, 'is-ready'); + const tooltipCtrl = createFloatingChartTooltipController({ + containerEl: chartWrap, + tooltipEl, + defaultTipWidth: 216, + defaultTipHeight: 104, + defaultViewWidth: DEFAULT_VIEW_W, + defaultViewHeight: VIEW_H, + useFloatingClass: false, + }); function populateTooltipContent(slot) { const slotTok = safeSlotTokens(slot.tokens); @@ -15066,81 +15846,13 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { }); } - let cachedWrapRect = null; let cachedSvgRect = null; let cachedHmGridRect = null; - let cachedClipRect = undefined; function invalidateHoverRects() { - cachedWrapRect = null; + tooltipCtrl.invalidateRects(); cachedSvgRect = null; cachedHmGridRect = null; - cachedClipRect = undefined; - } - - function getCachedWrapRect() { - if (!cachedWrapRect) { - cachedWrapRect = chartWrap.getBoundingClientRect?.() || null; - } - return cachedWrapRect; - } - - function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) { - const wrapRect = getCachedWrapRect(); - const wrapW = - wrapRect && wrapRect.width > 0 - ? wrapRect.width - : Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W); - const wrapH = - wrapRect && wrapRect.height > 0 - ? wrapRect.height - : Number(chartWrap.offsetHeight || VIEW_H); - - const tipW = Number(tooltipEl.offsetWidth || 0) || 216; - const tipH = Number(tooltipEl.offsetHeight || 0) || 104; - - const hasPointer = - pointer && - Number.isFinite(Number(pointer.clientX)) && - Number.isFinite(Number(pointer.clientY)) && - wrapRect && - wrapRect.width > 0 && - wrapRect.height > 0; - - const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX; - const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY; - - if (cachedClipRect === undefined) { - const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null; - cachedClipRect = clipEl?.getBoundingClientRect?.() || null; - } - const clipRect = cachedClipRect; - const hasClip = Boolean( - clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0 - ); - const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16; - const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16; - - const maxLeft = Math.max(4, wrapW - tipW - 4); - let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2)); - const aboveY = anchorY - tipH - 14; - let topPx; - - if (aboveY >= minY) { - topPx = Math.min(maxY, aboveY); - } else if (anchorX + 16 + tipW <= wrapW - 4) { - leftPx = anchorX + 16; - topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); - } else if (anchorX - 16 - tipW >= 4) { - leftPx = anchorX - 16 - tipW; - topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); - } else { - topPx = Math.max(minY, Math.min(maxY, anchorY + 18)); - } - - patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`); - patchStyleVar(tooltipEl, '--tip-shift', '0px'); - patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`); } function showLineHoverAtIndex(idx, pointer = null) { @@ -15172,7 +15884,6 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { 'is-hm-top': false, 'is-line-low': false, }); - patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); for (const [tIdx, el] of tickElsByIdx.entries()) { @@ -15180,15 +15891,21 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } } - const wrapRect = getCachedWrapRect(); + const wrapRect = tooltipCtrl.getWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W); const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW; const fallbackY = pt.y + 6; - positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer); - armTooltipTracking(wasHidden); + tooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: pointer || lastPointer, + trackedDots: [hoverDot], + viewWidth: viewW, + viewHeight: VIEW_H, + }); } function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) { @@ -15242,11 +15959,10 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { 'is-hm-top': false, 'is-line-low': false, }); - patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); } - const wrapRect = getCachedWrapRect(); + const wrapRect = tooltipCtrl.getWrapRect(); const cellRect = targetCell.getBoundingClientRect?.() || null; const wrapW = wrapRect && wrapRect.width > 0 @@ -15280,26 +15996,25 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } : rawPtr; - positionTooltipNearAnchor(fallbackX, fallbackY, effectivePtr); - armTooltipTracking(wasHidden); + tooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: effectivePtr, + trackedDots: [], + viewWidth: viewW, + viewHeight: VIEW_H, + }); } function clearHover() { invalidateHoverRects(); - cancelTipTrackRaf(); + tooltipCtrl.hide(); hoveredIdx = -1; lastPointer = null; patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); - patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { - 'is-hm-bottom': false, - 'is-hm-top': false, - 'is-line-low': false, - 'is-tracking': false, - }); patchClasses(hoverDot, { 'is-tracking': false }); - if (!currentIsHeatmap) { + if (!currentIsHeatmap && currentMaxTokens > 0) { patchAttr(peakPill, 'hidden', false); } if (hoveredHighlightEls.length > 0) { @@ -15609,9 +16324,9 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } function destroy() { - cancelTipTrackRaf(); - cancelCurveMorph(); - cancelPeakReadyRaf(); + tooltipCtrl.destroy(); + curveMorphCtrl.cancel(); + peakReadyArmer.cancel(); plotStage.removeEventListener('mousemove', handlePointerMove); plotStage.removeEventListener('click', handleLineClick); plotStage.removeEventListener('mouseleave', clearHover); @@ -15664,8 +16379,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { if (modeChanged) { clearHover(); - cancelCurveMorph(); - liveMorphSegs = null; + curveMorphCtrl.cancel(); } patchClasses(chartWrap, { 'is-heatmap': useHeatmap }); patchAttr(plotStage, 'hidden', useHeatmap); @@ -15692,6 +16406,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { peakIdx = i; } } + currentMaxTokens = maxTokens; const locale = getEffectiveLocale(); patchText(wdayMonEl, t('chart.trend.wdayMon')); @@ -16041,23 +16756,17 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; } - const prevSegs = liveMorphSegs || committedSegs; - committedSegs = nextSegs; - if (hasRenderedLineOnce && !modeChanged && prevSegs.length > 0) { - startCurveMorph(prevSegs, nextSegs, { - leftX, - rightX, - spanX, - finalLineD: lineD, - finalAreaD: areaD, - }); - } else { - cancelCurveMorph(); - liveMorphSegs = null; - patchAttr(linePath, 'd', lineD); - patchAttr(areaPath, 'd', areaD); - } - hasRenderedLineOnce = true; + curveMorphCtrl.morphTo({ + nextSegs, + leftX, + spanX, + bottomY: BOTTOM_Y, + linePath, + areaPath, + finalLineD: lineD, + finalAreaD: areaD, + skipMorph: modeChanged, + }); // 就地增量补丁垂直参考网格线及底部 X 轴标签,保持文字常驻不重排不闪烁 const tickIndices = computeTickIndices(slots); @@ -16126,29 +16835,24 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { } } - const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; - - const peakSlot = slots[peakIdx]; - const peakText = - maxTokens > 0 && peakSlot?.label + if (maxTokens > 0) { + const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; + const peakSlot = slots[peakIdx]; + const peakText = peakSlot?.label ? t('chart.trend.peakPill', { label: peakSlot.label, tokens: formatTokensPrecise(maxTokens), }) : formatTokensPrecise(maxTokens); - patchText(peakPill, peakText); - const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); - patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); - if (!peakReadyArmed) { - peakReadyArmed = true; - if (canAnimateInBrowser()) { - peakReadyRaf = window.requestAnimationFrame(() => { - peakReadyRaf = 0; - patchClasses(peakPill, { 'is-ready': true }); - }); - } else { - patchClasses(peakPill, { 'is-ready': true }); + patchText(peakPill, peakText); + const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); + patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + peakReadyArmer.arm(); + if (hoveredIdx < 0) { + patchAttr(peakPill, 'hidden', false); } + } else { + patchAttr(peakPill, 'hidden', true); } if (hoveredIdx >= slots.length) { @@ -16179,22 +16883,15 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { return { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart }; })(); -// --- src/components/charts/SessionStepCharts.js --- -const { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, computeLinearFit, computePublicationFit, createSessionLineChart, createModelFitChart } = (() => { +// --- src/components/charts/stepChartMath.js --- +const { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, clampValue, computeLinearFit, computePublicationFit, niceStepNumber, computeNiceYScale, computeNiceXStepTicks, formatYAxisTick, buildPolylinePath, buildSplinePath, computeStepTickIndices, formatStepAxisTag, formatChartMetricValue, formatChartMetricCompact } = (() => { /** - * @fileoverview 当前会话步骤级线性走势图与模型趋势拟合图组件 (SessionStepCharts). - * - * 包含两部分能力: - * 1. `createSessionLineChart`:查看当前会话(支持主代理 / 子代理 / 全部汇总)所有模型的步进变化, - * 支持切换 `总Token`(累计调用总量)、`上下文`(单步上下文体积)、`TPS`、`首字`、`费用` 五大维度; - * 2. `createModelFitChart`:查看指定模型或全部模型的 `TPS`、`首字`、`缓存`、`费用` 散点与鲁棒局部加权线性回归(LOWESS + OLS 基准)拟合曲线, - * 内置视图级模型锁定状态机,进入视图时自动锚定当前调用模型,停留在视图期间绝不随轮询跳变。 + * @fileoverview Pure regression math (OLS + IRLS-LOESS), nice axis tick generators, + * SVG spline/polyline path builders, and step metric formatters extracted from SessionStepCharts.js. */ -let sessionChartUid = 0; - -/** 多模型节点与多曲线对比语义调色板(全部取自 tokens.css 语义变量,兼顾设计一致性与交叉曲线区分度) */ +/** 多模型节点和多曲线对比语义调色板(全部取自 tokens.css 语义变量,兼顾设计一致性和交叉曲线区分度) */ const MODEL_COLOR_VARS = Object.freeze([ 'var(--ctx-cached)', 'var(--ctx-skills)', @@ -16205,7 +16902,7 @@ const MODEL_COLOR_VARS = Object.freeze([ ]); /** - * 提取步骤所属的基础模型分组键(与后端 `usage-aggregator.mjs` 中 `modelBreakdown[].label` 严格一致), + * 提取步骤所属的基础模型分组键(和后端 `usage-aggregator.mjs` 中 `modelBreakdown[].label` 严格一致), * 且不受“精简代号 / 原始模型 ID”或“自动压缩”后缀切换影响。 * * @param {object|null|undefined} step @@ -16317,8 +17014,8 @@ function computeLinearFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) } /** - * 学术论文级回归与 95% 置信带计算引擎(Cleveland & Devlin 高斯局部加权线性回归 LOESS + 精确帽子矩阵标准误, - * 小样本 n <= 5 时自动采用精确 OLS 线性回归与双曲 t 分布 95% 置信区间,等同于 R `ggplot2::geom_smooth(se = TRUE)`)。 + * 学术论文级回归和 95% 置信带计算引擎(Cleveland & Devlin 高斯局部加权线性回归 LOESS + 精确帽子矩阵标准误, + * 小样本 n <= 5 时自动采用精确 OLS 线性回归和双曲 t 分布 95% 置信区间,等同于 R `ggplot2::geom_smooth(se = TRUE)`)。 * * @param {number[]} xs 严格递增或单调的样本横坐标序列 * @param {number[]} ys 样本纵坐标序列 @@ -16379,7 +17076,7 @@ function computePublicationFit( const M = Math.max(2, gridSize); const gridXs = Array.from({ length: M }, (_, k) => xMin + (k / (M - 1)) * xSpan); - // 小样本(n <= 5):采用精确 OLS 线性回归与 Student-t 双曲 95% CI 置信带 + // 小样本(n <= 5):采用精确 OLS 线性回归和 Student-t 双曲 95% CI 置信带 if (n <= 5) { const meanX = xs.reduce((a, b) => a + b, 0) / n; let sxx = 0; @@ -16538,8 +17235,8 @@ function computePublicationFit( let traceL = 0; let precomputedGridEval = null; - // 大样本(n > 200 且 x 单调有序)采用与 R `stats::loess(surface = "interpolate")` 一致的网格插值加速: - // 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值与杠杆度,避免 O(N²) 阻塞主线程。 + // 大样本(n > 200 且 x 单调有序)采用和 R `stats::loess(surface = "interpolate")` 一致的网格插值加速: + // 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值和杠杆度,避免 O(N²) 阻塞主线程。 if (n > 200 && sortedXs && M >= 2) { const gridRawFit = new Float64Array(M); const gridLevSq = new Float64Array(M); @@ -16843,6 +17540,25 @@ function formatChartMetricCompact(metric, val) { return String(val); } } +return { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, clampValue, computeLinearFit, computePublicationFit, niceStepNumber, computeNiceYScale, computeNiceXStepTicks, formatYAxisTick, buildPolylinePath, buildSplinePath, computeStepTickIndices, formatStepAxisTag, formatChartMetricValue, formatChartMetricCompact }; +})(); + +// --- src/components/charts/SessionStepCharts.js --- +const { createSessionLineChart, createModelFitChart } = (() => { +/** + * @fileoverview 当前会话步骤级线性走势图与模型趋势拟合图组件 (SessionStepCharts). + * + * 包含两部分能力: + * 1. `createSessionLineChart`:查看当前会话(支持主代理 / 子代理 / 全部汇总)所有模型的步进变化, + * 支持切换 `总Token`(累计调用总量)、`上下文`(单步上下文体积)、`TPS`、`首字`、`费用` 五大维度; + * 2. `createModelFitChart`:查看指定模型或全部模型的 `TPS`、`首字`、`缓存`、`费用` 散点与鲁棒局部加权线性回归(LOWESS + OLS 基准)拟合曲线, + * 内置视图级模型锁定状态机,进入视图时自动锚定当前调用模型,停留在视图期间绝不随轮询跳变。 + */ + + + + +let sessionChartUid = 0; /** * 创建会话全模型线性走势图(支持 `totalTokens` | `context` | `tps` | `ttft` | `cost`,全宽 1:1 贴边对齐)。 @@ -16977,27 +17693,43 @@ function createSessionLineChart() { const plotStage = h('div', { className: 'sstep-plot-stage' }, [ peakPill, emptyHintEl, - tooltipEl, svg, ]); const rootEl = h('div', { className: 'sstep-chart-wrap' }, [ plotStage, xAxisEl, modelLegendEl, + tooltipEl, ]); let currentPoints = []; + let currentMaxVal = 0; let currentMetric = 'totalTokens'; let hoveredIdx = -1; + let lastPointer = null; let tickElsByIdx = new Map(); let lastSig = ''; let lastPreSig = ''; let lastSummaryBadge = ''; let lastUpdateParams = null; let cachedPlotSvgRect = null; + const multiSeriesNodesByKey = new Map(); + + const singleCurveMorphCtrl = createCubicCurveMorphController(); + const multiCurveMorphCtrl = createMultiSeriesCurveMorphController(); + const peakReadyArmer = createReadyClassArmer(peakPill, 'is-ready'); + const lineTooltipCtrl = createFloatingChartTooltipController({ + containerEl: rootEl, + tooltipEl, + defaultTipWidth: 212, + defaultTipHeight: 86, + defaultViewWidth: DEFAULT_VIEW_W, + defaultViewHeight: VIEW_H, + }); function invalidatePlotSvgRect() { cachedPlotSvgRect = null; + lineTooltipCtrl.invalidateRects(); } function syncViewWidth() { @@ -17019,89 +17751,94 @@ function createSessionLineChart() { return false; } - function showHoverAt(idx) { + function showHoverAt(idx, pointer = null, { forceRefresh = false } = {}) { if (idx < 0 || idx >= currentPoints.length) { clearHover(); return; } const wasHidden = tooltipEl.hasAttribute('hidden'); + const changedIdx = forceRefresh || wasHidden || idx !== hoveredIdx; hoveredIdx = idx; + if (pointer) { + lastPointer = pointer; + } const pt = currentPoints[idx]; - patchAttr(hoverLine, 'hidden', false); - patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); - patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); - - patchAttr(hoverDot, 'hidden', false); - patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); - patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); - const hoverAccent = pt.anomalySummary - ? pt.anomalySeverity === 'danger' - ? 'var(--metric-danger)' - : 'var(--metric-warn)' - : pt.hoverColor || 'var(--ctx-cached)'; - patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent); - - patchAttr(peakPill, 'hidden', true); - patchAttr(tooltipEl, 'hidden', false); - - patchText(tipHeadLeft, pt.stepTag); - patchText(tipHeadRight, pt.modelText); - patchText( - tipMainLeft, - pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') - ); - patchText(tipMainRight, pt.secondaryRight || ''); const hasIoParts = Boolean(pt.ioParts); - patchAttr(tipIoGrid, 'hidden', !hasIoParts); - if (hasIoParts) { - patchText(tipInLabelEl, t('cons.legInput')); - patchText(tipCacheLabelEl, t('cons.legCache')); - patchText(tipOutLabelEl, t('cons.legOutput')); - patchText(tipInValEl, pt.ioParts.inTok); - patchText(tipCacheValEl, pt.ioParts.cacheTok); - patchText(tipOutValEl, pt.ioParts.outTok); - } - patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail); - if (!hasIoParts && pt.subDetail) { - patchText(tipSub, pt.subDetail); - } - patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); - if (pt.anomalySummary) { - patchText(tipAnomaly, pt.anomalySummary); - patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' }); - } - const rawPct = (pt.x / viewW) * 100; - const clampedPct = Math.max(1, Math.min(99, rawPct)); - patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-y', '0px'); - if (wasHidden) { - patchClasses(tooltipEl, { 'is-tracking': false }); - void tooltipEl.offsetWidth; - if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { - window.requestAnimationFrame(() => { - if (!tooltipEl.hasAttribute('hidden')) { - patchClasses(tooltipEl, { 'is-tracking': true }); - } - }); - } else { - patchClasses(tooltipEl, { 'is-tracking': true }); + if (changedIdx) { + patchAttr(hoverLine, 'hidden', false); + patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); + patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); + + patchAttr(hoverDot, 'hidden', false); + patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); + patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + const hoverAccent = pt.anomalySummary + ? pt.anomalySeverity === 'danger' + ? 'var(--metric-danger)' + : 'var(--metric-warn)' + : pt.hoverColor || 'var(--ctx-cached)'; + patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent); + + patchAttr(peakPill, 'hidden', true); + + patchText(tipHeadLeft, pt.stepTag); + patchText(tipHeadRight, pt.modelText); + patchText( + tipMainLeft, + pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') + ); + patchText(tipMainRight, pt.secondaryRight || ''); + patchAttr(tipIoGrid, 'hidden', !hasIoParts); + if (hasIoParts) { + patchText(tipInLabelEl, t('cons.legInput')); + patchText(tipCacheLabelEl, t('cons.legCache')); + patchText(tipOutLabelEl, t('cons.legOutput')); + patchText(tipInValEl, pt.ioParts.inTok); + patchText(tipCacheValEl, pt.ioParts.cacheTok); + patchText(tipOutValEl, pt.ioParts.outTok); + } + patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail); + if (!hasIoParts && pt.subDetail) { + patchText(tipSub, pt.subDetail); + } + patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); + if (pt.anomalySummary) { + patchText(tipAnomaly, pt.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' }); + } + + for (const [tIdx, el] of tickElsByIdx.entries()) { + patchClasses(el, { 'is-hovered': tIdx === idx }); } } - for (const [tIdx, el] of tickElsByIdx.entries()) { - patchClasses(el, { 'is-hovered': tIdx === idx }); - } + const wrapRect = lineTooltipCtrl.getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(rootEl.clientWidth || viewW || DEFAULT_VIEW_W); + const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW; + const fallbackY = pt.y + 4; + lineTooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: pointer || lastPointer, + trackedDots: [hoverDot], + viewWidth: viewW, + viewHeight: VIEW_H, + sizeKey: `${hasIoParts ? 'io' : pt.subDetail ? 'sub' : 'min'}:${pt.anomalySummary ? 'a' : '0'}`, + }); } function clearHover() { hoveredIdx = -1; + lastPointer = null; + lineTooltipCtrl.hide(); patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); - patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-tracking': false }); - if (currentPoints.some((p) => p.valid)) { + patchClasses(hoverDot, { 'is-tracking': false }); + if (currentMaxVal > 0 && currentPoints.some((p) => p.valid)) { patchAttr(peakPill, 'hidden', false); } for (const el of tickElsByIdx.values()) { @@ -17126,7 +17863,11 @@ function createSessionLineChart() { 0, Math.min(currentPoints.length - 1, Math.round(ratio * (currentPoints.length - 1))) ); - showHoverAt(idx); + const pointer = + Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) + ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } + : null; + showHoverAt(idx, pointer); }); plotStage.addEventListener('mouseleave', () => { invalidatePlotSvgRect(); @@ -17141,7 +17882,7 @@ function createSessionLineChart() { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; lastPreSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }); resizeObs.observe(plotStage); @@ -17149,13 +17890,17 @@ function createSessionLineChart() { onWinResize = () => { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }; window.addEventListener('resize', onWinResize); } function destroy() { + singleCurveMorphCtrl.cancel(); + multiCurveMorphCtrl.cancel(); + peakReadyArmer.cancel(); + lineTooltipCtrl.destroy(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { @@ -17184,6 +17929,7 @@ function createSessionLineChart() { metric = 'totalTokens', showAgentPrefix = false, displaySettings = {}, + _skipMorph = false, } = {}) { lastUpdateParams = { steps, @@ -17442,6 +18188,7 @@ function createSessionLineChart() { peakIdx = i; } } + currentMaxVal = maxVal; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); const denom = maxVal > 0 ? maxVal : 1; @@ -17473,14 +18220,22 @@ function createSessionLineChart() { if (sig !== lastSig) { lastSig = sig; - while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); - while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild); while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild); if (isMultiCompare) { + singleCurveMorphCtrl.reset(); patchAttr(linePath, 'd', ''); patchAttr(areaPath, 'd', ''); + for (let ci = multiLineGroup.children.length - 1; ci >= 0; ci--) { + const ch = multiLineGroup.children[ci]; + if (ch.getAttribute?.('class') === 'sstep-series-single-dot') { + ch.remove(); + } + } + + const activeGks = new Set(); + const morphItems = []; for (const gk of targetKeys) { const seriesColor = modelColorMap.get(gk) || accentColor; @@ -17496,57 +18251,105 @@ function createSessionLineChart() { patchStyleVar(singleDot, '--sstep-series-color', seriesColor); multiLineGroup.appendChild(singleDot); } else { + activeGks.add(gk); + let nodes = multiSeriesNodesByKey.get(gk); + if (!nodes) { + const mArea = document.createElementNS(SVG_NS, 'path'); + mArea.setAttribute('class', 'sstep-multi-area'); + const mLine = document.createElementNS(SVG_NS, 'path'); + mLine.setAttribute('class', 'sstep-fit-line'); + mLine.setAttribute('fill', 'none'); + nodes = { mArea, mLine }; + multiSeriesNodesByKey.set(gk, nodes); + } + patchStyleVar(nodes.mArea, '--sstep-series-color', seriesColor); + patchStyleVar(nodes.mLine, '--sstep-fit-accent', seriesColor); + multiAreaGroup.appendChild(nodes.mArea); + multiLineGroup.appendChild(nodes.mLine); + const seriesLineD = buildSplinePath(seriesPts); const firstX = seriesPts[0].x.toFixed(1); const lastX = seriesPts[seriesPts.length - 1].x.toFixed(1); + const seriesAreaD = `${seriesLineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`; - const mArea = document.createElementNS(SVG_NS, 'path'); - mArea.setAttribute('class', 'sstep-multi-area'); - mArea.setAttribute( - 'd', - `${seriesLineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z` - ); - patchStyleVar(mArea, '--sstep-series-color', seriesColor); - multiAreaGroup.appendChild(mArea); - - const mLine = document.createElementNS(SVG_NS, 'path'); - mLine.setAttribute('class', 'sstep-fit-line'); - mLine.setAttribute('fill', 'none'); - mLine.setAttribute('d', seriesLineD); - patchStyleVar(mLine, '--sstep-fit-accent', seriesColor); - multiLineGroup.appendChild(mLine); - - if (seriesPts.length === 1) { - const pt = seriesPts[0]; - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - dot.setAttribute('r', '2.1'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar(dot, '--dot-stroke', seriesColor); - dotsGroup.appendChild(dot); - } + morphItems.push({ + key: gk, + nextSegs: pointsToNormalizedCubicSegs(seriesPts, BOTTOM_Y, { + leftX, + spanX, + tension: 0.42, + }), + lineEl: nodes.mLine, + areaEl: nodes.mArea, + endDotEl: null, + endX: NaN, + endY: NaN, + finalLineD: seriesLineD, + finalAreaD: seriesAreaD, + }); } } + + for (const [gk, nodes] of multiSeriesNodesByKey.entries()) { + if (!activeGks.has(gk)) { + nodes.mArea.remove(); + nodes.mLine.remove(); + } + } + + multiCurveMorphCtrl.morphSeries({ + items: morphItems, + leftX, + spanX, + bottomY: BOTTOM_Y, + skipMorph: _skipMorph, + }); } else { + multiCurveMorphCtrl.reset(); + for (const nodes of multiSeriesNodesByKey.values()) { + nodes.mArea.remove(); + nodes.mLine.remove(); + } if (validPoints.length === 0) { + singleCurveMorphCtrl.reset(); patchAttr(linePath, 'd', ''); patchAttr(areaPath, 'd', ''); } else if (validPoints.length === 1) { - const yStr = validPoints[0].y.toFixed(1); + const yVal = validPoints[0].y; + const yStr = yVal.toFixed(1); const lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; - patchAttr(linePath, 'd', lineD); - patchAttr( + const areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`; + const flatPts = [ + { x: leftX, y: yVal }, + { x: rightX, y: yVal }, + ]; + singleCurveMorphCtrl.morphTo({ + nextSegs: pointsToNormalizedCubicSegs(flatPts, BOTTOM_Y, { leftX, spanX }), + leftX, + spanX, + bottomY: BOTTOM_Y, + linePath, areaPath, - 'd', - `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z` - ); + finalLineD: lineD, + finalAreaD: areaD, + skipMorph: _skipMorph, + }); } else { const lineD = buildSplinePath(validPoints); const firstX = validPoints[0].x.toFixed(1); const lastX = validPoints[validPoints.length - 1].x.toFixed(1); - patchAttr(linePath, 'd', lineD); - patchAttr(areaPath, 'd', `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`); + const areaD = `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`; + singleCurveMorphCtrl.morphTo({ + nextSegs: pointsToNormalizedCubicSegs(validPoints, BOTTOM_Y, { leftX, spanX }), + leftX, + spanX, + bottomY: BOTTOM_Y, + linePath, + areaPath, + finalLineD: lineD, + finalAreaD: areaD, + skipMorph: _skipMorph, + }); } } @@ -17590,7 +18393,10 @@ function createSessionLineChart() { title: `${pt.stepTag} · ${pt.modelText}`, }); patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); - tickEl.onclick = () => showHoverAt(tIdx); + tickEl.onclick = () => { + lastPointer = null; + showHoverAt(tIdx, null); + }; xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } @@ -17643,7 +18449,7 @@ function createSessionLineChart() { } } - if (peakIdx >= 0 && validPoints.length > 0) { + if (peakIdx >= 0 && validPoints.length > 0 && maxVal > 0) { const peakPt = points[peakIdx]; patchText( peakPill, @@ -17655,6 +18461,7 @@ function createSessionLineChart() { patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + peakReadyArmer.arm(); if (hoveredIdx < 0) patchAttr(peakPill, 'hidden', false); } else { patchAttr(peakPill, 'hidden', true); @@ -17663,7 +18470,7 @@ function createSessionLineChart() { if (hoveredIdx >= points.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHoverAt(hoveredIdx); + showHoverAt(hoveredIdx, lastPointer, { forceRefresh: true }); } let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length }); @@ -17836,16 +18643,28 @@ function createModelFitChart() { fitStatsEl, ]); - const plotStage = h('div', { className: 'sstep-plot-stage' }, [emptyHintEl, tooltipEl, svg]); - const rootEl = h('div', { className: 'sstep-chart-wrap' }, [plotStage, fitLegendFoot]); + const plotStage = h('div', { className: 'sstep-plot-stage' }, [emptyHintEl, svg]); + const rootEl = h('div', { className: 'sstep-chart-wrap' }, [plotStage, fitLegendFoot, tooltipEl]); let currentSamples = []; let currentMetric = 'tps'; let hoveredIdx = -1; + let lastFitPointer = null; let lastSig = ''; let lastUpdateParams = null; let fitCacheMetric = ''; const fitCache = new Map(); + const multiFitNodesByKey = new Map(); + + const fitMorphCtrl = createFitGridMorphController(); + const fitTooltipCtrl = createFloatingChartTooltipController({ + containerEl: rootEl, + tooltipEl, + defaultTipWidth: 216, + defaultTipHeight: 82, + defaultViewWidth: DEFAULT_VIEW_W, + defaultViewHeight: VIEW_H, + }); function reusePublicationFit(key, xs, ys, maxVal, isMultiCompare) { const previous = fitCache.get(key); @@ -17880,94 +18699,100 @@ function createModelFitChart() { return false; } - function showHoverAt(idx) { + function showHoverAt(idx, pointer = null, { forceRefresh = false } = {}) { if (idx < 0 || idx >= currentSamples.length) { clearHover(); return; } - hoveredIdx = idx; - const sp = currentSamples[idx]; - patchAttr(hoverLine, 'hidden', false); - patchAttr(hoverLine, 'x1', sp.x.toFixed(1)); - patchAttr(hoverLine, 'x2', sp.x.toFixed(1)); - - patchAttr(hoverFitDot, 'hidden', false); - patchAttr(hoverFitDot, 'cx', sp.x.toFixed(1)); - patchAttr(hoverFitDot, 'cy', sp.fitY.toFixed(1)); - patchStyleVar(hoverFitDot, '--hover-dot-color', sp.seriesColor || 'var(--accent-primary)'); - - patchAttr(hoverRawDot, 'hidden', false); - patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); - patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); - patchClasses(hoverRawDot, { - 'is-anomaly': Boolean(sp.anomalySummary), - 'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'), - }); - const wasHidden = tooltipEl.hasAttribute('hidden'); - patchAttr(tooltipEl, 'hidden', false); - patchText(tipHeadLeft, sp.stepTag); - patchText(tipHeadRight, sp.modelText); - patchText( - tipMainLeft, - t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) - ); - patchText( - tipMainRight, - t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) - ); - - patchAttr(tipSub, 'hidden', false); - if (sp.compareHint) { - patchText(tipSub, sp.compareHint); - } else if (currentSamples.length >= 3 && sp.ciHalf > 0) { - patchText( - tipSub, - `95% CI [${formatChartMetricCompact(currentMetric, sp.ciLow)}, ${formatChartMetricCompact(currentMetric, sp.ciHigh)}]` - ); - } else { - const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); - patchText( - tipSub, - t('chart.step.ctxAndCache', { - ctxTok: formatTokens(ctxTok), - pct: Number(sp.st?.cacheHitPct ?? 0), - }) - ); - } - patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary); - if (sp.anomalySummary) { - patchText(tipAnomaly, sp.anomalySummary); - patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' }); + const changedIdx = forceRefresh || wasHidden || idx !== hoveredIdx; + hoveredIdx = idx; + if (pointer) { + lastFitPointer = pointer; } + const sp = currentSamples[idx]; - const rawPct = (sp.x / viewW) * 100; - const clampedPct = Math.max(1, Math.min(99, rawPct)); - patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-y', '0px'); - if (wasHidden) { - patchClasses(tooltipEl, { 'is-tracking': false }); - void tooltipEl.offsetWidth; - if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { - window.requestAnimationFrame(() => { - if (!tooltipEl.hasAttribute('hidden')) { - patchClasses(tooltipEl, { 'is-tracking': true }); - } - }); + if (changedIdx) { + patchAttr(hoverLine, 'hidden', false); + patchAttr(hoverLine, 'x1', sp.x.toFixed(1)); + patchAttr(hoverLine, 'x2', sp.x.toFixed(1)); + + patchAttr(hoverFitDot, 'hidden', false); + patchAttr(hoverFitDot, 'cx', sp.x.toFixed(1)); + patchAttr(hoverFitDot, 'cy', sp.fitY.toFixed(1)); + patchStyleVar(hoverFitDot, '--hover-dot-color', sp.seriesColor || 'var(--accent-primary)'); + + patchAttr(hoverRawDot, 'hidden', false); + patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); + patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + patchClasses(hoverRawDot, { + 'is-anomaly': Boolean(sp.anomalySummary), + 'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'), + }); + + patchText(tipHeadLeft, sp.stepTag); + patchText(tipHeadRight, sp.modelText); + patchText( + tipMainLeft, + t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) + ); + patchText( + tipMainRight, + t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) + ); + + patchAttr(tipSub, 'hidden', false); + if (sp.compareHint) { + patchText(tipSub, sp.compareHint); + } else if (currentSamples.length >= 3 && sp.ciHalf > 0) { + patchText( + tipSub, + `95% CI [${formatChartMetricCompact(currentMetric, sp.ciLow)}, ${formatChartMetricCompact(currentMetric, sp.ciHigh)}]` + ); } else { - patchClasses(tooltipEl, { 'is-tracking': true }); + const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); + patchText( + tipSub, + t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(sp.st?.cacheHitPct ?? 0), + }) + ); + } + patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary); + if (sp.anomalySummary) { + patchText(tipAnomaly, sp.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' }); } } + + const wrapRect = fitTooltipCtrl.getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(rootEl.clientWidth || viewW || DEFAULT_VIEW_W); + const fallbackX = (sp.x / Math.max(1, viewW)) * wrapW; + const fallbackY = sp.fitY + 4; + fitTooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: pointer || lastFitPointer, + trackedDots: [hoverFitDot, hoverRawDot], + viewWidth: viewW, + viewHeight: VIEW_H, + sizeKey: sp.anomalySummary ? 'fit:a' : 'fit:0', + }); } function clearHover() { hoveredIdx = -1; + lastFitPointer = null; + fitTooltipCtrl.hide(); patchAttr(hoverLine, 'hidden', true); patchAttr(hoverFitDot, 'hidden', true); patchAttr(hoverRawDot, 'hidden', true); - patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-tracking': false }); + patchClasses(hoverFitDot, { 'is-tracking': false }); + patchClasses(hoverRawDot, { 'is-tracking': false }); } let cachedFitSvgRect = null; @@ -17996,10 +18821,15 @@ function createModelFitChart() { ) { bestIdx = lo - 1; } - showHoverAt(bestIdx); + const pointer = + Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) + ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } + : null; + showHoverAt(bestIdx, pointer); }); plotStage.addEventListener('mouseleave', () => { cachedFitSvgRect = null; + fitTooltipCtrl.invalidateRects(); clearHover(); }); @@ -18008,9 +18838,10 @@ function createModelFitChart() { if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { cachedFitSvgRect = null; + fitTooltipCtrl.invalidateRects(); if (syncViewWidth() && lastUpdateParams) { lastSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }); resizeObs.observe(plotStage); @@ -18018,13 +18849,15 @@ function createModelFitChart() { onWinResize = () => { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }; window.addEventListener('resize', onWinResize); } function destroy() { + fitMorphCtrl.cancel(); + fitTooltipCtrl.destroy(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { @@ -18170,6 +19003,7 @@ function createModelFitChart() { metric = 'tps', showAgentPrefix = false, displaySettings = {}, + _skipMorph = false, } = {}) { lastUpdateParams = { steps, @@ -18256,13 +19090,16 @@ function createModelFitChart() { if (matchedItems.length === 0) { fitCache.clear(); + fitMorphCtrl.reset(); currentSamples = []; lastSig = 'empty'; patchAttr(ciBandPath, 'd', ''); patchAttr(fitPath, 'd', ''); patchAttr(olsLine, 'hidden', true); - while (multiBandGroup.firstChild) multiBandGroup.removeChild(multiBandGroup.firstChild); - while (multiCurveGroup.firstChild) multiCurveGroup.removeChild(multiCurveGroup.firstChild); + for (const nodes of multiFitNodesByKey.values()) { + nodes.bandEl.remove(); + nodes.curveEl.remove(); + } while (gridGroup.firstChild) gridGroup.removeChild(gridGroup.firstChild); while (axesGroup.firstChild) axesGroup.removeChild(axesGroup.firstChild); while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); @@ -18413,9 +19250,7 @@ function createModelFitChart() { showAgentPrefix, }); - while (multiBandGroup.firstChild) multiBandGroup.removeChild(multiBandGroup.firstChild); while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); - while (multiCurveGroup.firstChild) multiCurveGroup.removeChild(multiCurveGroup.firstChild); const dotRadius = combinedSamples.length > 80 ? '1.8' : combinedSamples.length > 36 ? '2.1' : '2.4'; @@ -18425,6 +19260,8 @@ function createModelFitChart() { ? document.createDocumentFragment() : scatterGroup; const anomalyOverlayDots = []; + const activeFitKeys = new Set(); + const fitMorphItems = []; for (const s of seriesList) { const binCounts = dedupOverdraw ? new Map() : null; @@ -18448,18 +19285,43 @@ function createModelFitChart() { scatterTarget.appendChild(dot); } + activeFitKeys.add(s.key); + let nodes = multiFitNodesByKey.get(s.key); + if (!nodes) { + const bandEl = document.createElementNS(SVG_NS, 'path'); + bandEl.setAttribute('class', 'sstep-ci-band is-multi'); + const curveEl = document.createElementNS(SVG_NS, 'path'); + curveEl.setAttribute('class', 'sstep-fit-line'); + curveEl.setAttribute('fill', 'none'); + nodes = { bandEl, curveEl }; + multiFitNodesByKey.set(s.key, nodes); + } + patchStyleVar(nodes.bandEl, '--sstep-fit-accent', s.colorVar); + patchStyleVar(nodes.curveEl, '--sstep-fit-accent', s.colorVar); + if (s.samples.length === 1) { const sp = s.samples[0]; const segHalf = Math.min(12, plotSpanX * 0.04); - const x1 = Math.max(plotLeft, sp.x - segHalf).toFixed(1); - const x2 = Math.min(plotRight, sp.x + segHalf).toFixed(1); + const x1 = Math.max(plotLeft, sp.x - segHalf); + const x2 = Math.min(plotRight, sp.x + segHalf); const yStr = sp.fitY.toFixed(1); - const lineEl = document.createElementNS(SVG_NS, 'path'); - lineEl.setAttribute('class', 'sstep-fit-line'); - lineEl.setAttribute('fill', 'none'); - lineEl.setAttribute('d', `M ${x1} ${yStr} L ${x2} ${yStr}`); - patchStyleVar(lineEl, '--sstep-fit-accent', s.colorVar); - multiCurveGroup.appendChild(lineEl); + const flatCurveD = `M ${x1.toFixed(1)} ${yStr} L ${x2.toFixed(1)} ${yStr}`; + nodes.bandEl.setAttribute('d', ''); + nodes.bandEl.remove(); + multiCurveGroup.appendChild(nodes.curveEl); + fitMorphItems.push({ + key: `multi:${s.key}`, + gridPts: [ + { x: x1, fitY: sp.fitY, lowY: sp.fitY, highY: sp.fitY }, + { x: x2, fitY: sp.fitY, lowY: sp.fitY, highY: sp.fitY }, + ], + curveEl: nodes.curveEl, + bandEl: null, + olsEl: null, + olsCoords: null, + finalCurveD: flatCurveD, + finalBandD: '', + }); } else { const gridPts = s.pubFit.grid.map((g) => ({ x: mapX(g.x), @@ -18468,8 +19330,9 @@ function createModelFitChart() { highY: mapY(g.ciHigh), })); + let bandD = ''; if (s.samples.length >= 3) { - let bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; + bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; for (let i = 1; i < gridPts.length; i++) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].highY.toFixed(1)}`; } @@ -18477,24 +19340,34 @@ function createModelFitChart() { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].lowY.toFixed(1)}`; } bandD += ' Z'; - const bandEl = document.createElementNS(SVG_NS, 'path'); - bandEl.setAttribute('class', 'sstep-ci-band is-multi'); - bandEl.setAttribute('d', bandD); - patchStyleVar(bandEl, '--sstep-fit-accent', s.colorVar); - multiBandGroup.appendChild(bandEl); + multiBandGroup.appendChild(nodes.bandEl); + } else { + nodes.bandEl.setAttribute('d', ''); + nodes.bandEl.remove(); } - const curveEl = document.createElementNS(SVG_NS, 'path'); - curveEl.setAttribute('class', 'sstep-fit-line'); - curveEl.setAttribute('fill', 'none'); - curveEl.setAttribute( - 'd', - buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))) - ); - patchStyleVar(curveEl, '--sstep-fit-accent', s.colorVar); - multiCurveGroup.appendChild(curveEl); + const curveD = buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))); + multiCurveGroup.appendChild(nodes.curveEl); + fitMorphItems.push({ + key: `multi:${s.key}`, + gridPts, + curveEl: nodes.curveEl, + bandEl: bandD ? nodes.bandEl : null, + olsEl: null, + olsCoords: null, + finalCurveD: curveD, + finalBandD: bandD, + }); } } + + for (const [k, nodes] of multiFitNodesByKey.entries()) { + if (!activeFitKeys.has(k)) { + nodes.bandEl.remove(); + nodes.curveEl.remove(); + } + } + fitMorphCtrl.morphFits({ items: fitMorphItems, skipMorph: _skipMorph }); anomalyOverlayDots.sort((a, b) => a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 ); @@ -18545,7 +19418,7 @@ function createModelFitChart() { if (hoveredIdx >= currentSamples.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHoverAt(hoveredIdx); + showHoverAt(hoveredIdx, lastFitPointer, { forceRefresh: true }); } return { @@ -18558,8 +19431,10 @@ function createModelFitChart() { } // 分支 B:单模型或整体合并单曲线模式 - while (multiBandGroup.firstChild) multiBandGroup.removeChild(multiBandGroup.firstChild); - while (multiCurveGroup.firstChild) multiCurveGroup.removeChild(multiCurveGroup.firstChild); + for (const nodes of multiFitNodesByKey.values()) { + nodes.bandEl.remove(); + nodes.curveEl.remove(); + } patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); @@ -18690,12 +19565,34 @@ function createModelFitChart() { scatterGroup.appendChild(scatterTarget); } - // 3. 绘制 95% CI 置信带闭合多边形与回归拟合曲线(绝不向底部 X 轴填充面积!) + // 3. 绘制 95% CI 置信带闭合多边形和回归拟合曲线(支持 240ms 平滑连续形变,绝不向底部 X 轴填充面积) if (isSingle) { - const yStr = samples[0].fitY.toFixed(1); - patchAttr(fitPath, 'd', `M ${plotLeft.toFixed(1)} ${yStr} L ${plotRight.toFixed(1)} ${yStr}`); + const yVal = samples[0].fitY; + const yStr = yVal.toFixed(1); + const flatCurveD = `M ${plotLeft.toFixed(1)} ${yStr} L ${plotRight.toFixed(1)} ${yStr}`; patchAttr(ciBandPath, 'd', ''); patchAttr(olsLine, 'hidden', true); + const flatGrid = Array.from({ length: 64 }, (_, gi) => ({ + x: plotLeft + (gi / 63) * plotSpanX, + fitY: yVal, + lowY: yVal, + highY: yVal, + })); + fitMorphCtrl.morphFits({ + items: [ + { + key: 'single', + gridPts: flatGrid, + curveEl: fitPath, + bandEl: null, + olsEl: null, + olsCoords: null, + finalCurveD: flatCurveD, + finalBandD: '', + }, + ], + skipMorph: _skipMorph, + }); } else { const gridPts = pubFit.grid.map((g) => ({ x: mapX(g.x), @@ -18704,14 +19601,10 @@ function createModelFitChart() { highY: mapY(g.ciHigh), })); - patchAttr( - fitPath, - 'd', - buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))) - ); - + const curveD = buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))); + let bandD = ''; if (samples.length >= 3) { - let bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; + bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; for (let i = 1; i < gridPts.length; i++) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].highY.toFixed(1)}`; } @@ -18719,21 +19612,39 @@ function createModelFitChart() { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].lowY.toFixed(1)}`; } bandD += ' Z'; - patchAttr(ciBandPath, 'd', bandD); } else { patchAttr(ciBandPath, 'd', ''); } const showOlsRef = samples.length >= 6; patchAttr(olsLine, 'hidden', !showOlsRef); + let olsCoords = null; if (showOlsRef) { const olsStartVal = clampValue(pubFit.intercept + pubFit.slope * xMin, minBound, maxBound); const olsEndVal = clampValue(pubFit.intercept + pubFit.slope * xMax, minBound, maxBound); - patchAttr(olsLine, 'x1', plotLeft.toFixed(1)); - patchAttr(olsLine, 'y1', mapY(olsStartVal).toFixed(1)); - patchAttr(olsLine, 'x2', plotRight.toFixed(1)); - patchAttr(olsLine, 'y2', mapY(olsEndVal).toFixed(1)); + olsCoords = { + x1: plotLeft, + y1: mapY(olsStartVal), + x2: plotRight, + y2: mapY(olsEndVal), + }; } + + fitMorphCtrl.morphFits({ + items: [ + { + key: 'single', + gridPts, + curveEl: fitPath, + bandEl: bandD ? ciBandPath : null, + olsEl: showOlsRef ? olsLine : null, + olsCoords, + finalCurveD: curveD, + finalBandD: bandD, + }, + ], + skipMorph: _skipMorph, + }); } } @@ -18762,7 +19673,7 @@ function createModelFitChart() { if (hoveredIdx >= samples.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHoverAt(hoveredIdx); + showHoverAt(hoveredIdx, lastFitPointer, { forceRefresh: true }); } return { sampleCount: samples.length, summaryBadge }; @@ -18770,7 +19681,7 @@ function createModelFitChart() { return { el: rootEl, update, destroy }; } -return { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, computeLinearFit, computePublicationFit, createSessionLineChart, createModelFitChart }; +return { createSessionLineChart, createModelFitChart }; })(); // --- src/registries/metricRegistry.js --- @@ -21051,6 +21962,44 @@ function buildHorizontalTangentSpline(pts) { return d; } +const HOVER_SLOT_COUNT = 96; +const MAX_SVG_COLUMN_BUCKETS = 96; + +/** + * Downsamples dense sub-pixel SVG points (e.g. 12s poll bursts) into `<= maxCols` + * min/max-preserving visual knots so curve rasterization and morphing stay crisp and fast, + * while `rawPoints` remain intact for exact timestamp interpolation. + */ +function simplifySvgPointsForRender(svgPts, leftX, plotW, maxCols = MAX_SVG_COLUMN_BUCKETS) { + if (svgPts.length <= maxCols) return svgPts; + const colW = Math.max(1, plotW) / maxCols; + const out = [svgPts[0]]; + let idx = 1; + const endIdx = svgPts.length - 1; + while (idx < endIdx) { + const col = Math.floor((svgPts[idx].x - leftX) / colW); + let minPt = svgPts[idx]; + let maxPt = svgPts[idx]; + let j = idx + 1; + while (j < endIdx && Math.floor((svgPts[j].x - leftX) / colW) === col) { + const cand = svgPts[j]; + if (cand.y < minPt.y) minPt = cand; + if (cand.y > maxPt.y) maxPt = cand; + j += 1; + } + if (minPt === maxPt) { + out.push(minPt); + } else if (minPt.x <= maxPt.x) { + out.push(minPt, maxPt); + } else { + out.push(maxPt, minPt); + } + idx = j; + } + out.push(svgPts[endIdx]); + return out; +} + /** * Computes tight, integer-aligned `[yMin, yMid, yMax]` bounds (`0..100%`) around * observed `[dataMin, dataMax]` so small-to-moderate quota changes use the full @@ -21420,6 +22369,7 @@ const AccountQuotaTrendCard = defineComponent({ options: [], onUpdateModelValue: (val) => { selectedAccountEmail = String(val || '').trim().toLowerCase(); + hideHover(); renderChart(); }, }); @@ -21431,6 +22381,7 @@ const AccountQuotaTrendCard = defineComponent({ options: [{ value: 'all', label: t('cons.cyclePoolAll') }], onUpdateModelValue: (val) => { selectedPool = val || 'all'; + hideHover(); renderChart(); }, }); @@ -21442,6 +22393,7 @@ const AccountQuotaTrendCard = defineComponent({ onUpdateModelValue: (val) => { selectedWin = val === 'weekly' ? 'weekly' : '5h'; winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); + hideHover(); renderChart(); }, }); @@ -21457,6 +22409,7 @@ const AccountQuotaTrendCard = defineComponent({ endPicker.setValue(draftEndMs); } rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); + hideHover(); renderChart(); }, }); @@ -21603,17 +22556,42 @@ const AccountQuotaTrendCard = defineComponent({ 'div', { className: 'trend-plot-stage', - onPointermove: handlePointerMove, - onPointerleave: hideHover, + onMousemove: handlePointerMove, + onMouseleave: hideHover, }, - [svg, tooltipEl] + [svg] ); const chartWrap = h('div', { className: 'trend-chart-wrap' }, [ plotStage, xAxisEl, legendRowEl, + tooltipEl, ]); + const tooltipCtrl = createFloatingChartTooltipController({ + containerEl: chartWrap, + tooltipEl, + defaultTipWidth: 204, + defaultTipHeight: 78, + defaultViewWidth: 460, + defaultViewHeight: VIEW_H, + }); + const seriesMorphCtrl = createMultiSeriesCurveMorphController(); + const seriesNodePoolByKey = new Map(); + const hoverDotPoolByKey = new Map(); + let xTickElements = []; + let hoveredSlotIdx = -1; + let lastActiveDots = []; + let lastFallbackX = 0; + let lastFallbackY = 0; + let lastSizeKey = ''; + let lastTipTimeStr = ''; + let lastTipWinStr = ''; + let lastHoveredTickIdx = -1; + let lastPointer = null; + let cachedSvgRect = null; + let lastPlotSig = ''; + const rootEl = h('section', { className: 'panel account-quota-trend-panel' }, [ h('div', { className: 'panel-header account-trend-toprow' }, [ h('span', { className: 'panel-title cons-overview-title' }, [ @@ -21638,10 +22616,29 @@ const AccountQuotaTrendCard = defineComponent({ return BOTTOM_Y - ((clamped - plottedYScale.yMin) / plottedYScale.span) * SPAN_Y; } + function syncHoveredTickClass(activeTickIdx) { + if (activeTickIdx === lastHoveredTickIdx) return; + lastHoveredTickIdx = activeTickIdx; + for (let i = 0; i < xTickElements.length; i++) { + patchClasses(xTickElements[i], { 'is-hovered': i === activeTickIdx }); + } + } + function hideHover() { + cachedSvgRect = null; + hoveredSlotIdx = -1; + lastActiveDots = []; + lastTipTimeStr = ''; + lastTipWinStr = ''; + lastPointer = null; + tooltipCtrl.hide(); hoverLine.setAttribute('hidden', ''); hoverDotsGroup.setAttribute('hidden', ''); - patchAttr(tooltipEl, 'hidden', true); + for (const dot of hoverDotPoolByKey.values()) { + dot.setAttribute('hidden', ''); + patchClasses(dot, { 'is-tracking': false }); + } + syncHoveredTickClass(-1); } function sampleSeriesValueAt(points, targetMs) { @@ -21665,75 +22662,159 @@ const AccountQuotaTrendCard = defineComponent({ return a.val + (b.val - a.val) * ((targetMs - a.ts) / span); } + function showHoverAtSlot(slotIdx, pointer = null, { forceRefresh = false } = {}) { + if (!plottedSeries.length || !(plottedEndMs > plottedStartMs) || slotIdx < 0) { + hideHover(); + return; + } + const clampedSlot = Math.max(0, Math.min(HOVER_SLOT_COUNT, slotIdx)); + const wasHidden = tooltipEl.hasAttribute('hidden'); + const changedSlot = forceRefresh || wasHidden || clampedSlot !== hoveredSlotIdx; + hoveredSlotIdx = clampedSlot; + if (pointer) lastPointer = pointer; + + if (changedSlot) { + const u = clampedSlot / HOVER_SLOT_COUNT; + const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); + const clampedX = LEFT_X + u * plotW; + const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs)); + + hoverLine.setAttribute('x1', clampedX.toFixed(1)); + hoverLine.setAttribute('x2', clampedX.toFixed(1)); + + const tipItems = []; + const activeDots = []; + let sumY = 0; + const usedKeys = new Set(); + + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + const val = sampleSeriesValueAt(s.rawPoints, targetMs); + if (val === null) continue; + usedKeys.add(s.poolKey); + const y = valueToSvgY(val); + sumY += y; + + let dot = hoverDotPoolByKey.get(s.poolKey); + if (!dot) { + dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('class', 'trend-hover-dot'); + dot.setAttribute('r', '3.2'); + dot.style.fill = 'var(--surface-panel)'; + hoverDotPoolByKey.set(s.poolKey, dot); + hoverDotsGroup.appendChild(dot); + } + if (dot._lastColor !== s.color) { + dot._lastColor = s.color; + dot.style.stroke = s.color; + } + dot.setAttribute('cx', clampedX.toFixed(1)); + dot.setAttribute('cy', y.toFixed(1)); + if (dot.hasAttribute('hidden')) dot.removeAttribute('hidden'); + activeDots.push(dot); + tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val }); + } + + for (const [k, dot] of hoverDotPoolByKey.entries()) { + if (!usedKeys.has(k) && !dot.hasAttribute('hidden')) { + dot.setAttribute('hidden', ''); + patchClasses(dot, { 'is-tracking': false }); + } + } + + if (tipItems.length === 0) { + hideHover(); + return; + } + if (hoverLine.hasAttribute('hidden')) hoverLine.removeAttribute('hidden'); + if (hoverDotsGroup.hasAttribute('hidden')) hoverDotsGroup.removeAttribute('hidden'); + + if (xTickElements.length > 1) { + syncHoveredTickClass(Math.round(u * (xTickElements.length - 1))); + } + + const nextTimeStr = formatHoverTimestamp(targetMs); + if (nextTimeStr !== lastTipTimeStr) { + lastTipTimeStr = nextTimeStr; + patchText(tipTimeEl, nextTimeStr); + } + const nextWinStr = t( + selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h' + ); + if (nextWinStr !== lastTipWinStr) { + lastTipWinStr = nextWinStr; + patchText(tipWinEl, nextWinStr); + } + + patchKeyedList(tipRowsHost, tipItems, { + keyFn: (it) => it.key, + sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`, + createRow: () => { + const sw = h('span', { className: 'dot-swatch' }); + const nm = h('span', { className: 'account-trend-tip-name' }); + const vl = h('strong', { className: 'text-mono' }); + const row = h('div', { className: 'account-trend-tip-row' }, [ + h('span', { className: 'legend-left' }, [sw, nm]), + vl, + ]); + return { el: row, refs: { sw, nm, vl } }; + }, + updateRow: (r, it) => { + if (r.sw._lastBg !== it.color) { + r.sw._lastBg = it.color; + r.sw.style.background = it.color; + } + patchText(r.nm, it.label); + patchText(r.vl, `${+it.val.toFixed(1)}%`); + }, + }); + + const wrapRect = tooltipCtrl.getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(chartWrap.clientWidth || viewW || 460); + lastFallbackX = (clampedX / Math.max(1, viewW)) * wrapW; + lastFallbackY = sumY / activeDots.length + 6; + lastActiveDots = activeDots; + lastSizeKey = `rows:${tipItems.length}`; + } + + tooltipCtrl.show({ + fallbackX: lastFallbackX, + fallbackY: lastFallbackY, + pointer: pointer || lastPointer, + trackedDots: lastActiveDots, + viewWidth: viewW, + viewHeight: VIEW_H, + sizeKey: lastSizeKey, + }); + } + function handlePointerMove(ev) { if (!plottedSeries.length || !(plottedEndMs > plottedStartMs)) { hideHover(); return; } - const rect = svg.getBoundingClientRect?.(); + if (!cachedSvgRect) { + cachedSvgRect = svg.getBoundingClientRect?.() || null; + } + const rect = cachedSvgRect; const widthPx = Number(rect?.width || viewW); - if (!(widthPx > 0)) return; + if (!(widthPx > 0)) { + cachedSvgRect = null; + return; + } const offsetX = Number(ev.clientX || 0) - Number(rect?.left || 0); const svgX = (offsetX / widthPx) * viewW; const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); const u = Math.max(0, Math.min(1, (svgX - LEFT_X) / plotW)); - const clampedX = LEFT_X + u * plotW; - const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs)); - - hoverLine.setAttribute('x1', clampedX.toFixed(1)); - hoverLine.setAttribute('x2', clampedX.toFixed(1)); - - while (hoverDotsGroup.firstChild) hoverDotsGroup.removeChild(hoverDotsGroup.firstChild); - const tipItems = []; - for (let i = 0; i < plottedSeries.length; i++) { - const s = plottedSeries[i]; - const val = sampleSeriesValueAt(s.rawPoints, targetMs); - if (val === null) continue; - const y = valueToSvgY(val); - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', clampedX.toFixed(1)); - dot.setAttribute('cy', y.toFixed(1)); - dot.setAttribute('r', '3.2'); - dot.setAttribute('fill', 'var(--surface-panel)'); - dot.setAttribute('stroke', s.color); - dot.setAttribute('stroke-width', '1.8'); - hoverDotsGroup.appendChild(dot); - tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val }); - } - if (tipItems.length === 0) { - hideHover(); - return; - } - hoverLine.removeAttribute('hidden'); - hoverDotsGroup.removeAttribute('hidden'); - - patchText(tipTimeEl, formatHoverTimestamp(targetMs)); - patchText(tipWinEl, t(selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h')); - patchKeyedList(tipRowsHost, tipItems, { - keyFn: (it) => it.key, - sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`, - createRow: () => { - const sw = h('span', { className: 'dot-swatch' }); - const nm = h('span', { className: 'account-trend-tip-name' }); - const vl = h('strong', { className: 'text-mono' }); - const row = h('div', { className: 'account-trend-tip-row' }, [ - h('span', { className: 'legend-left' }, [sw, nm]), - vl, - ]); - return { el: row, refs: { sw, nm, vl } }; - }, - updateRow: (r, it) => { - r.sw.style.background = it.color; - patchText(r.nm, it.label); - patchText(r.vl, `${+it.val.toFixed(1)}%`); - }, - }); - - const pctX = (clampedX / viewW) * 100; - const shift = pctX < 24 ? '0%' : pctX > 76 ? '-100%' : '-50%'; - patchStyleVar(tooltipEl, '--tip-x', `${pctX.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-shift', shift); - patchAttr(tooltipEl, 'hidden', false); + const slotIdx = Math.round(u * HOVER_SLOT_COUNT); + const pointer = + Number.isFinite(Number(ev?.clientX)) && Number.isFinite(Number(ev?.clientY)) + ? { clientX: Number(ev.clientX), clientY: Number(ev.clientY) } + : null; + showHoverAtSlot(slotIdx, pointer); } function resolveTargetAccountEmail() { @@ -21817,10 +22898,9 @@ const AccountQuotaTrendCard = defineComponent({ ); } - function renderChart() { - hideHover(); + function renderChart({ skipMorph = false } = {}) { const nowMs = Date.now(); - void getEffectiveLocale(); + const locale = getEffectiveLocale(); patchText(cardTitleText, t('settings.account.trendTitle')); patchText(rangeToEl, t('cons.rangeTo')); @@ -21900,6 +22980,9 @@ const AccountQuotaTrendCard = defineComponent({ patchAttr(emptyStateEl, 'hidden', hasPlot); if (!hasPlot) { plottedSeries = []; + lastPlotSig = ''; + seriesMorphCtrl.reset(); + hideHover(); patchText(emptyStateEl, t('settings.account.trendEmpty')); return; } @@ -21915,9 +22998,8 @@ const AccountQuotaTrendCard = defineComponent({ gl.setAttribute('x2', String(viewW)); } - plottedSeries = rawBuilt.map((rb) => ({ - ...rb, - svgPts: rb.rawPoints.map((sp) => { + plottedSeries = rawBuilt.map((rb) => { + const fullSvgPts = rb.rawPoints.map((sp) => { const u = Math.max(0, Math.min(1, (sp.ts - plottedStartMs) / spanMs)); return { x: LEFT_X + u * plotW, @@ -21925,50 +23007,112 @@ const AccountQuotaTrendCard = defineComponent({ val: sp.val, ts: sp.ts, }; - }), - })); + }); + return { + ...rb, + svgPts: simplifySvgPointsForRender(fullSvgPts, LEFT_X, plotW), + }; + }); - while (seriesGroup.firstChild) seriesGroup.removeChild(seriesGroup.firstChild); - for (let i = 0; i < plottedSeries.length; i++) { - const s = plottedSeries[i]; - const lineD = buildHorizontalTangentSpline(s.svgPts); - if (s.svgPts.length >= 2) { - const first = s.svgPts[0]; - const last = s.svgPts[s.svgPts.length - 1]; - const areaEl = document.createElementNS(SVG_NS, 'path'); - areaEl.setAttribute( - 'd', - `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z` - ); - if (plottedSeries.length === 1) { - stopTop.setAttribute('stop-color', s.color); - stopBot.setAttribute('stop-color', s.color); - areaEl.setAttribute('fill', `url(#${gradId})`); - } else { - areaEl.setAttribute('class', 'sstep-multi-area'); - areaEl.style.setProperty('--sstep-series-color', s.color); + const plotSig = + `${locale}|${viewW}|${targetEmail}|${selectedWin}|${selectedRange}|${selectedPool}|${plottedYScale.yMin}-${plottedYScale.yMax}|` + + plottedSeries + .map( + (s) => + `${s.poolKey}:${s.svgPts.length}:${s.svgPts[0]?.x.toFixed(1)}:${s.svgPts[0]?.y.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.x.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.y.toFixed(1)}` + ) + .join('|'); + + if (plotSig !== lastPlotSig) { + lastPlotSig = plotSig; + const activePoolKeys = new Set(); + const morphItems = []; + + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + activePoolKeys.add(s.poolKey); + let nodes = seriesNodePoolByKey.get(s.poolKey); + if (!nodes) { + const areaEl = document.createElementNS(SVG_NS, 'path'); + const lineEl = document.createElementNS(SVG_NS, 'path'); + lineEl.setAttribute('fill', 'none'); + lineEl.setAttribute('stroke-width', '1.9'); + lineEl.setAttribute('stroke-linecap', 'round'); + const endDotEl = document.createElementNS(SVG_NS, 'circle'); + endDotEl.setAttribute('r', '2.7'); + nodes = { areaEl, lineEl, endDotEl }; + seriesNodePoolByKey.set(s.poolKey, nodes); } - seriesGroup.appendChild(areaEl); - } - const pathEl = document.createElementNS(SVG_NS, 'path'); - pathEl.setAttribute('d', lineD); - pathEl.setAttribute('fill', 'none'); - pathEl.setAttribute('stroke', s.color); - pathEl.setAttribute('stroke-width', '1.9'); - pathEl.setAttribute('stroke-linecap', 'round'); - seriesGroup.appendChild(pathEl); - const endPt = s.svgPts[s.svgPts.length - 1]; - const endDot = document.createElementNS(SVG_NS, 'circle'); - endDot.setAttribute('cx', endPt.x.toFixed(1)); - endDot.setAttribute('cy', endPt.y.toFixed(1)); - endDot.setAttribute('r', '2.7'); - endDot.setAttribute('fill', s.color); - seriesGroup.appendChild(endDot); + const lineD = buildHorizontalTangentSpline(s.svgPts); + let areaD = ''; + if (s.svgPts.length >= 2) { + const first = s.svgPts[0]; + const last = s.svgPts[s.svgPts.length - 1]; + areaD = `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z`; + if (plottedSeries.length === 1) { + stopTop.setAttribute('stop-color', s.color); + stopBot.setAttribute('stop-color', s.color); + nodes.areaEl.removeAttribute('class'); + nodes.areaEl.style.removeProperty('--sstep-series-color'); + nodes.areaEl.setAttribute('fill', `url(#${gradId})`); + } else { + nodes.areaEl.removeAttribute('fill'); + nodes.areaEl.setAttribute('class', 'sstep-multi-area'); + nodes.areaEl.style.setProperty('--sstep-series-color', s.color); + } + nodes.areaEl.removeAttribute('hidden'); + } else { + nodes.areaEl.setAttribute('d', ''); + nodes.areaEl.setAttribute('hidden', ''); + } + + nodes.lineEl.setAttribute('stroke', s.color); + nodes.endDotEl.setAttribute('fill', s.color); + + seriesGroup.appendChild(nodes.areaEl); + seriesGroup.appendChild(nodes.lineEl); + seriesGroup.appendChild(nodes.endDotEl); + + const endPt = s.svgPts[s.svgPts.length - 1]; + morphItems.push({ + key: s.poolKey, + nextSegs: pointsToNormalizedCubicSegs(s.svgPts, BOTTOM_Y, { + leftX: LEFT_X, + spanX: plotW, + tension: 0.38, + }), + lineEl: nodes.lineEl, + areaEl: areaD ? nodes.areaEl : null, + endDotEl: nodes.endDotEl, + endX: endPt.x, + endY: endPt.y, + finalLineD: lineD, + finalAreaD: areaD, + }); + } + + for (const [k, nodes] of seriesNodePoolByKey.entries()) { + if (!activePoolKeys.has(k)) { + nodes.areaEl.remove(); + nodes.lineEl.remove(); + nodes.endDotEl.remove(); + } + } + + seriesMorphCtrl.morphSeries({ + items: morphItems, + leftX: LEFT_X, + spanX: plotW, + bottomY: BOTTOM_Y, + skipMorph, + }); } - // Edge-to-edge X-axis ticks (`0% .. 100%`) + // Edge-to-edge X-axis ticks (`0% .. 100%`) with active hover highlight & click-to-inspect const tickCount = 5; + const activeTickIdx = + hoveredSlotIdx >= 0 ? Math.round((hoveredSlotIdx / HOVER_SLOT_COUNT) * (tickCount - 1)) : -1; const ticks = []; for (let k = 0; k < tickCount; k++) { const ratio = k / (tickCount - 1); @@ -21976,25 +23120,37 @@ const AccountQuotaTrendCard = defineComponent({ const leftPct = ratio * 100; ticks.push({ idx: k, + slotIdx: Math.round(ratio * HOVER_SLOT_COUNT), leftPct, label: formatAxisTickTime(tickMs, spanMs), + fullTitle: formatHoverTimestamp(tickMs), edge: k === 0 ? 'start' : k === tickCount - 1 ? 'end' : '', + isHovered: k === activeTickIdx, }); } + xTickElements = []; + lastHoveredTickIdx = activeTickIdx; patchKeyedList(xAxisEl, ticks, { keyFn: (tk) => tk.idx, - sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}`, + sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}:${tk.isHovered}`, createRow: () => { const el = h('span', { className: 'trend-x-tick text-mono' }); return { el, refs: { el } }; }, updateRow: (r, tk) => { patchText(r.el, tk.label); + patchAttr(r.el, 'title', tk.fullTitle); patchStyleVar(r.el, '--tick-x', `${tk.leftPct.toFixed(2)}%`); patchClasses(r.el, { 'is-start': tk.edge === 'start', 'is-end': tk.edge === 'end', + 'is-hovered': tk.isHovered, }); + r.el.onclick = () => { + lastPointer = null; + showHoverAtSlot(tk.slotIdx, null, { forceRefresh: true }); + }; + xTickElements[tk.idx] = r.el; }, }); @@ -22014,21 +23170,29 @@ const AccountQuotaTrendCard = defineComponent({ patchText(r.vl, `${+s.latestVal.toFixed(1)}%`); }, }); + + if (hoveredSlotIdx >= 0) { + showHoverAtSlot(hoveredSlotIdx, lastPointer, { forceRefresh: true }); + } } let resizeObs = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver((entries) => { + cachedSvgRect = null; + tooltipCtrl.invalidateRects(); const w = Math.floor(Number(entries?.[0]?.contentRect?.width || 0)); if (w >= 180 && Math.abs(w - viewW) >= 2) { viewW = w; - renderChart(); + renderChart({ skipMorph: true }); } }); resizeObs.observe(plotStage); } onCleanup(() => { + seriesMorphCtrl.cancel(); + tooltipCtrl.destroy(); resizeObs?.disconnect(); accountSelect.destroy(); poolSelect.destroy(); @@ -22046,7 +23210,7 @@ const AccountQuotaTrendCard = defineComponent({ renderChart(); return { el: rootEl, - refs: { update, refreshLabels: renderChart }, + refs: { update, refreshLabels: () => renderChart() }, }; }, }); @@ -23782,6 +24946,28 @@ function patchCapsuleOdometerText( return true; } +function isValidTtftSec(val) { + return val != null && Number.isFinite(Number(val)) && Number(val) >= 0; +} + +function findFallbackRecentStepTtft(steps) { + if (!Array.isArray(steps) || steps.length === 0) return null; + const firstIdx = Number(steps[0]?.stepIndex ?? 0); + const lastIdx = Number(steps[steps.length - 1]?.stepIndex ?? 0); + if (firstIdx >= lastIdx) { + for (let i = 0; i < steps.length; i += 1) { + const candidate = steps[i]?.ttftSec; + if (isValidTtftSec(candidate)) return Number(candidate); + } + return null; + } + for (let i = steps.length - 1; i >= 0; i -= 1) { + const candidate = steps[i]?.ttftSec; + if (isValidTtftSec(candidate)) return Number(candidate); + } + return null; +} + /** * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. */ @@ -23804,11 +24990,29 @@ function buildCapsuleSlotContext( ).toFixed(2); const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const convId = String(capActive.cascadeId || activeConv.cascadeId || '') + .trim() + .toLowerCase(); + const scopeId = String(scopedConv?.agentId || aggregated?.agentId || 'main'); + const conversationKey = convId ? `${convId}::${scopeId}` : ''; + const stepCount = Math.max(0, Number(capActive.stepCount ?? activeConv.stepCount ?? 0)); + + const rawTtft = + scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null; + const fallbackTtft = isValidTtftSec(rawTtft) + ? Number(rawTtft) + : scopedConv?.lastKnownTtftSec ?? + findFallbackRecentStepTtft(scopedConv?.recentSteps) ?? + aggregated?.lastKnownTtftSec ?? + activeConv.lastKnownTtftSec ?? + findFallbackRecentStepTtft(activeConv.recentSteps); + const resolvedTtft = isValidTtftSec(fallbackTtft) ? Number(fallbackTtft) : null; + const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); const sessionTokens = - Number(capActive.stepCount || 0) > 0 || + stepCount > 0 || capActive.totalTokens != null || capInTok + capCacheTok + capOutTok > 0 ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) @@ -23816,12 +25020,14 @@ function buildCapsuleSlotContext( return { hasTelemetry: true, + conversationKey, + stepCount, usedPct, dashOffset, isRunning, tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null, avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null, - ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null, + ttft: resolvedTtft, stepCost: scopedConv?.latestStepCostUsd ?? aggregated?.latestStepCostUsd ?? @@ -23951,6 +25157,7 @@ function createCapsuleSlotNode(slotIndex, initialMetric) { textSpan, ringMounted: isCtx, prefixMounted: false, + heldTtft: null, }; } @@ -23963,7 +25170,25 @@ function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx) { for (let i = 0; i < capsuleSlots.length; i += 1) { const slot = capsuleSlots[i]; const metricKey = i < slotKeys.length ? slotKeys[i] : 'none'; - const pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE); + if (!slotCtx?.hasTelemetry || metricKey !== 'ttft') { + slot.heldTtft = null; + } + let pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE); + if (metricKey === 'ttft' && slotCtx?.hasTelemetry) { + const convKey = String(slotCtx.conversationKey || ''); + if (isValidTtftSec(slotCtx.ttft)) { + slot.heldTtft = convKey ? { conversationKey: convKey, pres } : null; + } else if ( + convKey && + slot.heldTtft && + slot.heldTtft.conversationKey === convKey && + (slotCtx.isRunning || Number(slotCtx.stepCount) > 0) + ) { + pres = { ...slot.heldTtft.pres, running: Boolean(slotCtx.isRunning) }; + } else { + slot.heldTtft = null; + } + } if (pres.hidden) { patchAttr(slot.el, 'hidden', true); patchAttr(slot.el, 'data-metric', 'none'); diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index f4e0974..ec4a6c5 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -322,11 +322,13 @@ function enrichActiveConversationSteps( const latestEnriched = enrichedActiveSteps.length > 0 ? enrichedActiveSteps[enrichedActiveSteps.length - 1] : null; + const lastKnownTtftSec = findLastValidStepTtft(enrichedActiveSteps); const sessionAvgTokPerSec = roundMetric(sessionSpeed.avgTokPerSec); return { enrichedActiveSteps, latestEnriched, + lastKnownTtftSec, sessionSpeed, sessionTtft, sessionAvgTokPerSec, @@ -338,6 +340,21 @@ function enrichActiveConversationSteps( }; } +function findLastValidStepTtft(steps) { + if (!Array.isArray(steps)) return null; + for (let i = steps.length - 1; i >= 0; i -= 1) { + const candidateTtft = steps[i]?.ttftSec; + if ( + candidateTtft != null && + Number.isFinite(Number(candidateTtft)) && + Number(candidateTtft) >= 0 + ) { + return Number(candidateTtft); + } + } + return null; +} + const CONTEXT_CHANNEL_KEYS = [ 'userInput', 'assistant', @@ -863,6 +880,7 @@ export function buildAgentUnitTelemetry({ stepCount: taggedSteps.length, latestTokPerSec: enrichedRes.latestEnriched?.tokPerSec ?? null, latestTtftSec: enrichedRes.latestEnriched?.ttftSec ?? null, + lastKnownTtftSec: enrichedRes.lastKnownTtftSec ?? null, latestSpeedReason: enrichedRes.latestEnriched?.selectedSpeedReason ?? null, avgTokPerSec: enrichedRes.sessionAvgTokPerSec, speedSummary: enrichedRes.sessionSpeed, @@ -1415,6 +1433,11 @@ function buildActiveConversationAssembly({ } : null; + const combinedLastKnownTtftSec = + findLastValidStepTtft(allCombinedEnrichedSteps) ?? + latestMetricAgent.lastKnownTtftSec ?? + null; + aggregatedTelemetry = { agentId: 'all', cascadeId: activeCascadeId, @@ -1438,6 +1461,7 @@ function buildActiveConversationAssembly({ stepCount: allCombinedEnrichedSteps.length, latestTokPerSec: latestMetricAgent.latestTokPerSec, latestTtftSec: latestMetricAgent.latestTtftSec, + lastKnownTtftSec: combinedLastKnownTtftSec, latestSpeedReason: latestMetricAgent.latestSpeedReason, avgTokPerSec: combinedAvgTokPerSec, speedSummary: combinedSpeed, @@ -1487,6 +1511,8 @@ function buildActiveConversationAssembly({ : enrichedActiveSteps.length, latestTokPerSec: latestEnriched?.tokPerSec ?? null, latestTtftSec: latestEnriched?.ttftSec ?? null, + lastKnownTtftSec: + mainAgentTelemetry.lastKnownTtftSec ?? findLastValidStepTtft(enrichedActiveSteps), latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null, avgTokPerSec: sessionAvgTokPerSec, speedSummary: sessionSpeed, @@ -2929,6 +2955,7 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) { latestTokPerSec: capSource.latestTokPerSec ?? ac.latestTokPerSec ?? null, avgTokPerSec: capSource.avgTokPerSec ?? ac.avgTokPerSec ?? null, latestTtftSec: capSource.latestTtftSec ?? ac.latestTtftSec ?? null, + lastKnownTtftSec: capSource.lastKnownTtftSec ?? ac.lastKnownTtftSec ?? null, latestStepCostUsd: capSource.latestStepCostUsd ?? ac.latestStepCostUsd ?? null, sessionCostUsd: capSource.sessionCostUsd ?? ac.sessionCostUsd ?? null, latestCacheHitPct: capSource.latestCacheHitPct ?? ac.latestCacheHitPct ?? null, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index c37c1f1..676c489 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index 4c7cb2c..b8fea9d 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -622,7 +622,9 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/components/ui/ContextSegmentMeter.js', 'src/components/ui/FourSegmentBar.js', 'src/components/ui/ConsumptionTooltipContent.js', + 'src/components/charts/chartMotion.js', 'src/components/charts/TrendAreaChart.js', + 'src/components/charts/stepChartMath.js', 'src/components/charts/SessionStepCharts.js', 'src/registries/metricRegistry.js', 'src/components/widgets/MetricMatrixWidget.js', diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 8521edc..2267045 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -24,658 +24,42 @@ import { import { SVG_NS } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; +import { + MODEL_COLOR_VARS, + buildPolylinePath, + buildSplinePath, + clampValue, + computeLinearFit, + computeNiceXStepTicks, + computeNiceYScale, + computePublicationFit, + computeStepTickIndices, + formatChartMetricCompact, + formatChartMetricValue, + formatStepAxisTag, + formatYAxisTick, + getStepModelGroupKey, + toChronologicalSteps, +} from './stepChartMath.js'; +import { + createCubicCurveMorphController, + createFitGridMorphController, + createFloatingChartTooltipController, + createMultiSeriesCurveMorphController, + createReadyClassArmer, + pointsToNormalizedCubicSegs, +} from './chartMotion.js'; + +export { + MODEL_COLOR_VARS, + computeLinearFit, + computePublicationFit, + getStepModelGroupKey, + toChronologicalSteps, +}; + let sessionChartUid = 0; -/** 多模型节点与多曲线对比语义调色板(全部取自 tokens.css 语义变量,兼顾设计一致性与交叉曲线区分度) */ -export const MODEL_COLOR_VARS = Object.freeze([ - 'var(--ctx-cached)', - 'var(--ctx-skills)', - 'var(--ctx-user-input)', - 'var(--ctx-checkpoint)', - 'var(--ctx-tool-results)', - 'var(--ctx-subagent-msg)', -]); - -/** - * 提取步骤所属的基础模型分组键(与后端 `usage-aggregator.mjs` 中 `modelBreakdown[].label` 严格一致), - * 且不受“精简代号 / 原始模型 ID”或“自动压缩”后缀切换影响。 - * - * @param {object|null|undefined} step - * @returns {string} - */ -export function getStepModelGroupKey(step) { - if (!step || typeof step !== 'object') return t('fmt.unknownModel'); - const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '') - .replace(/\s*\[自动压缩\]\s*$/u, '') - .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') - .trim(); - if (rawLabel) return rawLabel; - const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '') - .replace(/·(?:压缩|Compact)\s*$/iu, '') - .trim(); - return rawShort || t('fmt.unknownModel'); -} - -/** - * 将逆序或混合代理的步骤列表归一化为严格时间升序序列(最旧 -> 最新)。 - * - * @param {Array} steps - * @param {boolean} isMergedAllAgents - * @returns {Array} - */ -export function toChronologicalSteps(steps, isMergedAllAgents = false) { - if (!Array.isArray(steps) || steps.length === 0) return []; - const copy = steps.slice(); - if (isMergedAllAgents) { - copy.sort( - (a, b) => - (Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) || - (Number(a?.agentIndex) || 0) - (Number(b?.agentIndex) || 0) || - (Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) - ); - return copy; - } - copy.sort( - (a, b) => - (Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) || - (Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) - ); - return copy; -} - -function clampValue(v, minVal = 0, maxVal = Infinity) { - if (!Number.isFinite(v)) return minVal; - return Math.max(minVal, Math.min(maxVal, v)); -} - -/** - * 双侧 95% 置信区间对应的 Student-t 临界值近似表(t_{0.975, df})。 - * - * @param {number} df 残差自由度 - * @returns {number} - */ -function tCritical95(df) { - if (!Number.isFinite(df) || df <= 1.5) return 3.182; - if (df <= 2.5) return 3.182 + (2.5 - df) * 0.9; - if (df <= 3.5) return 2.776 + (3.5 - df) * 0.406; - if (df <= 4.5) return 2.571 + (4.5 - df) * 0.205; - if (df <= 6) return 2.447; - if (df <= 8) return 2.306; - if (df <= 10) return 2.228; - if (df <= 15) return 2.131; - if (df <= 20) return 2.086; - if (df <= 30) return 2.042; - if (df <= 60) return 2.0; - if (df <= 120) return 1.98; - return 1.96; -} - -/** - * 计算普通最小二乘线性回归(OLS: y = intercept + slope * x)。 - * - * @param {number[]} ys 样本纵坐标序列 - * @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [options] - * @returns {{ values: number[], slope: number, intercept: number, mean: number, r: number, r2: number }} - */ -export function computeLinearFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) { - const n = Array.isArray(ys) ? ys.length : 0; - if (n === 0) { - return { values: [], slope: 0, intercept: 0, mean: 0, r: 0, r2: 0 }; - } - const xArr = - Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx); - const meanY = ys.reduce((acc, v) => acc + v, 0) / n; - if (n === 1) { - const c = clampValue(ys[0], minVal, maxVal); - return { values: [c], slope: 0, intercept: c, mean: c, r: 0, r2: 0 }; - } - const meanX = xArr.reduce((acc, v) => acc + v, 0) / n; - let sxx = 0; - let sxy = 0; - let syy = 0; - for (let i = 0; i < n; i++) { - const dx = xArr[i] - meanX; - const dy = ys[i] - meanY; - sxx += dx * dx; - sxy += dx * dy; - syy += dy * dy; - } - const slope = sxx > 1e-12 ? sxy / sxx : 0; - const intercept = meanY - slope * meanX; - const r = - sxx > 1e-12 && syy > 1e-12 ? clampValue(sxy / Math.sqrt(sxx * syy), -1, 1) : 0; - const values = xArr.map((x) => clampValue(intercept + slope * x, minVal, maxVal)); - return { values, slope, intercept, mean: meanY, r, r2: r * r }; -} - -/** - * 学术论文级回归与 95% 置信带计算引擎(Cleveland & Devlin 高斯局部加权线性回归 LOESS + 精确帽子矩阵标准误, - * 小样本 n <= 5 时自动采用精确 OLS 线性回归与双曲 t 分布 95% 置信区间,等同于 R `ggplot2::geom_smooth(se = TRUE)`)。 - * - * @param {number[]} xs 严格递增或单调的样本横坐标序列 - * @param {number[]} ys 样本纵坐标序列 - * @param {{ minVal?: number, maxVal?: number, gridSize?: number, span?: number }} [options] - */ -export function computePublicationFit( - xs, - ys, - { minVal = 0, maxVal = Infinity, gridSize = 64, span = 0.5 } = {} -) { - const n = Math.min(Array.isArray(xs) ? xs.length : 0, Array.isArray(ys) ? ys.length : 0); - if (n === 0) { - return { - method: 'OLS', - mean: 0, - sd: 0, - slope: 0, - intercept: 0, - r: 0, - r2: 0, - sampleFits: [], - sampleCiLow: [], - sampleCiHigh: [], - sampleCiHalf: [], - grid: [], - }; - } - - const ols = computeLinearFit(ys, { minVal, maxVal, xs }); - let syy = 0; - for (let i = 0; i < n; i++) { - const dy = ys[i] - ols.mean; - syy += dy * dy; - } - const sd = n > 1 ? Math.sqrt(syy / (n - 1)) : 0; - - if (n === 1) { - const val = clampValue(ys[0], minVal, maxVal); - return { - method: 'OLS', - mean: val, - sd: 0, - slope: 0, - intercept: val, - r: 0, - r2: 0, - sampleFits: [val], - sampleCiLow: [val], - sampleCiHigh: [val], - sampleCiHalf: [0], - grid: [{ x: xs[0], fit: val, ciLow: val, ciHigh: val }], - }; - } - - const xMin = xs[0]; - const xMax = xs[n - 1]; - const xSpan = Math.max(1e-9, xMax - xMin); - const M = Math.max(2, gridSize); - const gridXs = Array.from({ length: M }, (_, k) => xMin + (k / (M - 1)) * xSpan); - - // 小样本(n <= 5):采用精确 OLS 线性回归与 Student-t 双曲 95% CI 置信带 - if (n <= 5) { - const meanX = xs.reduce((a, b) => a + b, 0) / n; - let sxx = 0; - let sse = 0; - for (let i = 0; i < n; i++) { - const dx = xs[i] - meanX; - sxx += dx * dx; - const resid = ys[i] - (ols.intercept + ols.slope * xs[i]); - sse += resid * resid; - } - const df = n - 2; - const seResid = df >= 1 ? Math.sqrt(sse / df) : 0; - const tCrit = df >= 1 ? tCritical95(df) : 0; - - const evalOlsAt = (x0) => { - const rawFit = ols.intercept + ols.slope * x0; - const sePred = - seResid > 0 - ? seResid * Math.sqrt(1 / n + (sxx > 1e-12 ? ((x0 - meanX) * (x0 - meanX)) / sxx : 0)) - : 0; - const half = tCrit * sePred; - return { - fit: clampValue(rawFit, minVal, maxVal), - ciLow: clampValue(rawFit - half, minVal, maxVal), - ciHigh: clampValue(rawFit + half, minVal, maxVal), - half, - }; - }; - - const sampleEval = xs.map(evalOlsAt); - const grid = gridXs.map((gx) => { - const g = evalOlsAt(gx); - return { x: gx, fit: g.fit, ciLow: g.ciLow, ciHigh: g.ciHigh }; - }); - - return { - method: 'OLS', - mean: ols.mean, - sd, - slope: ols.slope, - intercept: ols.intercept, - r: ols.r, - r2: ols.r2, - sampleFits: sampleEval.map((e) => e.fit), - sampleCiLow: sampleEval.map((e) => e.ciLow), - sampleCiHigh: sampleEval.map((e) => e.ciHigh), - sampleCiHalf: sampleEval.map((e) => e.half), - grid, - }; - } - - // n >= 6:Cleveland 高斯局部加权一阶线性回归(LOESS)+ 精确帽子矩阵杠杆度 95% CI 置信带 - const q = Math.max(5, Math.min(n, Math.ceil(span * n))); - const wBuf = new Float64Array(n); - const sortedXs = q <= n && xs.slice(0, n).every( - (x, i) => Number.isFinite(x) && (i === 0 || xs[i - 1] <= x) - ); - - function loessBandwidth(x0) { - // 有序 x 上的 q 个最近样本可取连续区间;二分比较两端,避免每个拟合点都排序。 - let left = 0; - let right = n - q; - while (left < right) { - const mid = (left + right) >>> 1; - if (x0 - xs[mid] > xs[mid + q] - x0) { - left = mid + 1; - } else { - right = mid; - } - } - return Math.max(Math.abs(xs[left] - x0), Math.abs(xs[left + q - 1] - x0)); - } - - function evalLoessPoint(x0, diagIdx = -1) { - let h; - if (sortedXs) { - h = loessBandwidth(x0); - if (h <= 1e-9) { - h = Math.max(Math.abs(xs[0] - x0), Math.abs(xs[n - 1] - x0), xSpan * 0.05, 1e-6); - } - } else { - const sortedDists = Array.from({ length: n }, (_, j) => Math.abs(xs[j] - x0)).sort((a, b) => a - b); - h = sortedDists[q - 1]; - if (h <= 1e-9) { - h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6); - } - } - const maxDist = h * 1.0001; - let start = 0; - let end = n; - if (sortedXs) { - // 三次权重的支持区间之外权重为零,保留区间内样本原来的累加顺序。 - let right = n; - while (start < right) { - const mid = (start + right) >>> 1; - if (x0 - xs[mid] >= maxDist) start = mid + 1; - else right = mid; - } - let left = start; - while (left < end) { - const mid = (left + end) >>> 1; - if (xs[mid] - x0 < maxDist) left = mid + 1; - else end = mid; - } - } - - let sw = 0; - let swx = 0; - for (let j = start; j < end; j++) { - const u = Math.abs(xs[j] - x0) / maxDist; - const base = 1 - u * u * u; - const w = u >= 1 ? 0 : base * base * base; - wBuf[j] = w; - sw += w; - swx += w * xs[j]; - } - - if (sw <= 1e-12) { - const fallbackVal = ols.intercept + ols.slope * x0; - return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n }; - } - - const mx = swx / sw; - let sxxW = 0; - for (let j = start; j < end; j++) { - const w = wBuf[j]; - if (w <= 0) continue; - const dx = xs[j] - mx; - sxxW += w * dx * dx; - } - - const dx0 = x0 - mx; - const useSlope = sxxW > 1e-12; - const inverseWeightSum = 1 / sw; - const slopeScale = useSlope ? dx0 / sxxW : 0; - const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0); - let rawFit = 0; - let leverageNormSq = 0; - let diagHat = 0; - - for (let j = start; j < end; j++) { - const w = wBuf[j]; - if (w <= 0) continue; - const lj = w * inverseWeightSum + (useSlope ? w * (xs[j] - mx) * slopeScale : 0); - rawFit += lj * ys[j]; - leverageNormSq += lj * lj; - if (j === diagIdx) diagHat = lj; - } - - return { rawFit, leverageNormSq, diagHat, localHatDiag }; - } - - const rawSampleFits = new Float64Array(n); - const sampleLevSq = new Float64Array(n); - let sse = 0; - let traceL = 0; - let precomputedGridEval = null; - - // 大样本(n > 200 且 x 单调有序)采用与 R `stats::loess(surface = "interpolate")` 一致的网格插值加速: - // 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值与杠杆度,避免 O(N²) 阻塞主线程。 - if (n > 200 && sortedXs && M >= 2) { - const gridRawFit = new Float64Array(M); - const gridLevSq = new Float64Array(M); - const gridHatDiag = new Float64Array(M); - for (let k = 0; k < M; k++) { - const res = evalLoessPoint(gridXs[k], -1); - gridRawFit[k] = res.rawFit; - gridLevSq[k] = res.leverageNormSq; - gridHatDiag[k] = res.localHatDiag; - } - precomputedGridEval = { gridRawFit, gridLevSq }; - - const invSpan = (M - 1) / xSpan; - const maxK0 = M - 2; - for (let i = 0; i < n; i++) { - const u = (xs[i] - xMin) * invSpan; - const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u); - const frac = Math.max(0, Math.min(1, u - k0)); - const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]); - const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0])); - const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]); - rawSampleFits[i] = rf; - sampleLevSq[i] = ls; - traceL += hd; - const diff = ys[i] - rf; - sse += diff * diff; - } - } else { - for (let i = 0; i < n; i++) { - const res = evalLoessPoint(xs[i], i); - rawSampleFits[i] = res.rawFit; - sampleLevSq[i] = res.leverageNormSq; - traceL += res.diagHat; - const diff = ys[i] - res.rawFit; - sse += diff * diff; - } - } - - const dfRes = Math.max(1, n - traceL); - const sigmaHat = Math.sqrt(sse / dfRes); - const tCrit = tCritical95(dfRes); - - const sampleFits = new Array(n); - const sampleCiLow = new Array(n); - const sampleCiHigh = new Array(n); - const sampleCiHalf = new Array(n); - let clampedSse = 0; - - for (let i = 0; i < n; i++) { - const fitVal = clampValue(rawSampleFits[i], minVal, maxVal); - const half = tCrit * sigmaHat * Math.sqrt(sampleLevSq[i]); - sampleFits[i] = fitVal; - sampleCiLow[i] = clampValue(rawSampleFits[i] - half, minVal, maxVal); - sampleCiHigh[i] = clampValue(rawSampleFits[i] + half, minVal, maxVal); - sampleCiHalf[i] = half; - const d = ys[i] - fitVal; - clampedSse += d * d; - } - - const grid = precomputedGridEval - ? gridXs.map((gx, k) => { - const rf = precomputedGridEval.gridRawFit[k]; - const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k])); - return { - x: gx, - fit: clampValue(rf, minVal, maxVal), - ciLow: clampValue(rf - half, minVal, maxVal), - ciHigh: clampValue(rf + half, minVal, maxVal), - }; - }) - : gridXs.map((gx) => { - const res = evalLoessPoint(gx, -1); - const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq); - return { - x: gx, - fit: clampValue(res.rawFit, minVal, maxVal), - ciLow: clampValue(res.rawFit - half, minVal, maxVal), - ciHigh: clampValue(res.rawFit + half, minVal, maxVal), - }; - }); - - const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1; - - return { - method: 'LOESS', - mean: ols.mean, - sd, - slope: ols.slope, - intercept: ols.intercept, - r: ols.r, - r2: r2Loess, - sampleFits, - sampleCiLow, - sampleCiHigh, - sampleCiHalf, - grid, - }; -} - -/** - * Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。 - */ -function niceStepNumber(range, round) { - if (!Number.isFinite(range) || range <= 0) return 1; - const exponent = Math.floor(Math.log10(range)); - const fraction = range / 10 ** exponent; - let niceFraction; - if (round) { - if (fraction < 1.5) niceFraction = 1; - else if (fraction < 3) niceFraction = 2; - else if (fraction < 7) niceFraction = 5; - else niceFraction = 10; - } else if (fraction <= 1) niceFraction = 1; - else if (fraction <= 2) niceFraction = 2; - else if (fraction <= 5) niceFraction = 5; - else niceFraction = 10; - return niceFraction * 10 ** exponent; -} - -function computeNiceYScale(dataMin, dataMax, { minBound = 0, maxBound = Infinity, tickCount = 4 } = {}) { - let lo = Number.isFinite(dataMin) ? dataMin : 0; - let hi = Number.isFinite(dataMax) ? dataMax : 1; - if (minBound === 0 && lo >= 0 && hi > 0 && lo <= hi * 0.32) { - lo = 0; - } - if (hi - lo <= 1e-9) { - const pad = lo > 0 ? lo * 0.15 : 1; - lo = Math.max(minBound, lo - pad); - hi = Math.min(maxBound, hi + pad); - if (hi - lo <= 1e-9) { - lo = Math.max(minBound, hi - 1); - } - } else { - const pad = (hi - lo) * 0.05; - lo = Math.max(minBound, lo - (lo === 0 ? 0 : pad)); - hi = Math.min(maxBound, hi + pad); - } - - const rawRange = niceStepNumber(hi - lo, false); - const step = niceStepNumber(rawRange / Math.max(2, tickCount - 1), true); - let graphMin = Math.max(minBound, Math.floor(lo / step) * step); - let graphMax = Math.min(maxBound, Math.ceil(hi / step) * step); - if (graphMax - graphMin <= 1e-9) { - graphMax = graphMin + step; - } - - const ticks = []; - for (let v = graphMin; v <= graphMax + step * 0.25; v += step) { - const clamped = clampValue(+v.toPrecision(10), minBound, maxBound); - if (ticks.length === 0 || Math.abs(clamped - ticks[ticks.length - 1]) > step * 1e-4) { - ticks.push(clamped); - } - if (ticks.length >= 8) break; - } - return { - min: ticks[0] ?? graphMin, - max: ticks[ticks.length - 1] ?? graphMax, - step, - ticks, - }; -} - -function computeNiceXStepTicks(xs) { - const n = xs.length; - if (n === 0) return []; - if (n <= 5) { - return Array.from(new Set(xs.map((x) => Math.round(x)))); - } - const xMin = xs[0]; - const xMax = xs[n - 1]; - const span = xMax - xMin; - if (span <= 5) { - return Array.from(new Set(xs.map((x) => Math.round(x)))); - } - const step = Math.max(1, Math.round(niceStepNumber(span / 4.5, true))); - const firstTick = Math.ceil(xMin / step) * step; - const ticks = []; - if (firstTick - xMin > step * 0.45) { - ticks.push(Math.round(xMin)); - } - for (let v = firstTick; v <= xMax + 1e-6; v += step) { - ticks.push(Math.round(v)); - if (ticks.length >= 7) break; - } - if (ticks.length === 0) { - return [Math.round(xMin), Math.round(xMax)]; - } - return ticks; -} - -function formatYAxisTick(metric, val, step) { - if (!Number.isFinite(val)) return ''; - if (Math.abs(val) < 1e-9) { - return metric === 'cost' ? '$0' : metric === 'cache' ? '0%' : metric === 'ttft' ? '0s' : '0'; - } - if (metric === 'tps') { - return step >= 1 ? `${Math.round(val)}` : val.toFixed(1); - } - if (metric === 'ttft') { - return step >= 1 ? `${Math.round(val)}s` : `${val.toFixed(1)}s`; - } - if (metric === 'cache') { - return step >= 1 ? `${Math.round(val)}%` : formatPctNumber(val, { withSymbol: true }); - } - if (metric === 'cost') { - if (step >= 1) return `$${Math.round(val)}`; - if (step >= 0.1) return `$${val.toFixed(1)}`; - if (step >= 0.01) return `$${val.toFixed(2)}`; - return `$${val.toFixed(3)}`; - } - return String(val); -} - -function buildPolylinePath(points) { - if (!points.length) return ''; - let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; - for (let i = 1; i < points.length; i++) { - d += ` L ${points[i].x.toFixed(1)} ${points[i].y.toFixed(1)}`; - } - return d; -} - -function buildSplinePath(points) { - if (!points.length) return ''; - if (points.length === 1) { - return `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; - } - let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; - for (let i = 0; i < points.length - 1; i++) { - const p0 = points[i]; - const p1 = points[i + 1]; - const cpx1 = p0.x + (p1.x - p0.x) * 0.38; - const cpx2 = p1.x - (p1.x - p0.x) * 0.38; - d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; - } - return d; -} - -function computeStepTickIndices(count) { - if (count <= 0) return []; - if (count <= 6) return Array.from({ length: count }, (_, i) => i); - const maxTicks = 6; - const set = new Set(); - for (let k = 0; k < maxTicks; k++) { - set.add(Math.round((k / (maxTicks - 1)) * (count - 1))); - } - return Array.from(set).sort((a, b) => a - b); -} - -function formatStepAxisTag(st, showAgentPrefix) { - const num = `#${Number(st?.stepIndex ?? 0)}`; - if (!showAgentPrefix) return num; - const badge = formatAgentBadgeText({ - agentKind: - st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), - agentOrdinal: - st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), - isMain: !st?.isSubagent, - isSideQuestion: Boolean(st?.isSideQuestion), - sideIndex: st?.sideIndex || 0, - index: st?.agentIndex || 0, - badgeText: st?.agentBadge, - }); - return `${badge}${num}`; -} - -function formatChartMetricValue(metric, val) { - if (!Number.isFinite(val)) return '—'; - switch (metric) { - case 'totalTokens': - case 'context': - return `${formatTokensPrecise(val)} tok`; - case 'tps': - return formatSpeedMetric(val, ' tok/s'); - case 'ttft': - return formatMetric(val, 's'); - case 'cache': - return formatPctNumber(val, { withSymbol: true }); - case 'cost': - return formatUsd(val, { precise: true }); - default: - return String(val); - } -} - -function formatChartMetricCompact(metric, val) { - if (!Number.isFinite(val)) return '—'; - switch (metric) { - case 'totalTokens': - case 'context': - return formatTokens(val); - case 'tps': - return formatSpeedMetric(val, ' tok/s'); - case 'ttft': - return formatMetric(val, 's'); - case 'cache': - return formatPctNumber(val, { withSymbol: true }); - case 'cost': - return formatUsd(val, { precise: true }); - default: - return String(val); - } -} - /** * 创建会话全模型线性走势图(支持 `totalTokens` | `context` | `tps` | `ttft` | `cost`,全宽 1:1 贴边对齐)。 */ @@ -809,27 +193,43 @@ export function createSessionLineChart() { const plotStage = h('div', { className: 'sstep-plot-stage' }, [ peakPill, emptyHintEl, - tooltipEl, svg, ]); const rootEl = h('div', { className: 'sstep-chart-wrap' }, [ plotStage, xAxisEl, modelLegendEl, + tooltipEl, ]); let currentPoints = []; + let currentMaxVal = 0; let currentMetric = 'totalTokens'; let hoveredIdx = -1; + let lastPointer = null; let tickElsByIdx = new Map(); let lastSig = ''; let lastPreSig = ''; let lastSummaryBadge = ''; let lastUpdateParams = null; let cachedPlotSvgRect = null; + const multiSeriesNodesByKey = new Map(); + + const singleCurveMorphCtrl = createCubicCurveMorphController(); + const multiCurveMorphCtrl = createMultiSeriesCurveMorphController(); + const peakReadyArmer = createReadyClassArmer(peakPill, 'is-ready'); + const lineTooltipCtrl = createFloatingChartTooltipController({ + containerEl: rootEl, + tooltipEl, + defaultTipWidth: 212, + defaultTipHeight: 86, + defaultViewWidth: DEFAULT_VIEW_W, + defaultViewHeight: VIEW_H, + }); function invalidatePlotSvgRect() { cachedPlotSvgRect = null; + lineTooltipCtrl.invalidateRects(); } function syncViewWidth() { @@ -851,89 +251,94 @@ export function createSessionLineChart() { return false; } - function showHoverAt(idx) { + function showHoverAt(idx, pointer = null, { forceRefresh = false } = {}) { if (idx < 0 || idx >= currentPoints.length) { clearHover(); return; } const wasHidden = tooltipEl.hasAttribute('hidden'); + const changedIdx = forceRefresh || wasHidden || idx !== hoveredIdx; hoveredIdx = idx; + if (pointer) { + lastPointer = pointer; + } const pt = currentPoints[idx]; - patchAttr(hoverLine, 'hidden', false); - patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); - patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); - - patchAttr(hoverDot, 'hidden', false); - patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); - patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); - const hoverAccent = pt.anomalySummary - ? pt.anomalySeverity === 'danger' - ? 'var(--metric-danger)' - : 'var(--metric-warn)' - : pt.hoverColor || 'var(--ctx-cached)'; - patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent); - - patchAttr(peakPill, 'hidden', true); - patchAttr(tooltipEl, 'hidden', false); - - patchText(tipHeadLeft, pt.stepTag); - patchText(tipHeadRight, pt.modelText); - patchText( - tipMainLeft, - pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') - ); - patchText(tipMainRight, pt.secondaryRight || ''); const hasIoParts = Boolean(pt.ioParts); - patchAttr(tipIoGrid, 'hidden', !hasIoParts); - if (hasIoParts) { - patchText(tipInLabelEl, t('cons.legInput')); - patchText(tipCacheLabelEl, t('cons.legCache')); - patchText(tipOutLabelEl, t('cons.legOutput')); - patchText(tipInValEl, pt.ioParts.inTok); - patchText(tipCacheValEl, pt.ioParts.cacheTok); - patchText(tipOutValEl, pt.ioParts.outTok); - } - patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail); - if (!hasIoParts && pt.subDetail) { - patchText(tipSub, pt.subDetail); - } - patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); - if (pt.anomalySummary) { - patchText(tipAnomaly, pt.anomalySummary); - patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' }); - } - const rawPct = (pt.x / viewW) * 100; - const clampedPct = Math.max(1, Math.min(99, rawPct)); - patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-y', '0px'); - if (wasHidden) { - patchClasses(tooltipEl, { 'is-tracking': false }); - void tooltipEl.offsetWidth; - if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { - window.requestAnimationFrame(() => { - if (!tooltipEl.hasAttribute('hidden')) { - patchClasses(tooltipEl, { 'is-tracking': true }); - } - }); - } else { - patchClasses(tooltipEl, { 'is-tracking': true }); + if (changedIdx) { + patchAttr(hoverLine, 'hidden', false); + patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); + patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); + + patchAttr(hoverDot, 'hidden', false); + patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); + patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + const hoverAccent = pt.anomalySummary + ? pt.anomalySeverity === 'danger' + ? 'var(--metric-danger)' + : 'var(--metric-warn)' + : pt.hoverColor || 'var(--ctx-cached)'; + patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent); + + patchAttr(peakPill, 'hidden', true); + + patchText(tipHeadLeft, pt.stepTag); + patchText(tipHeadRight, pt.modelText); + patchText( + tipMainLeft, + pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') + ); + patchText(tipMainRight, pt.secondaryRight || ''); + patchAttr(tipIoGrid, 'hidden', !hasIoParts); + if (hasIoParts) { + patchText(tipInLabelEl, t('cons.legInput')); + patchText(tipCacheLabelEl, t('cons.legCache')); + patchText(tipOutLabelEl, t('cons.legOutput')); + patchText(tipInValEl, pt.ioParts.inTok); + patchText(tipCacheValEl, pt.ioParts.cacheTok); + patchText(tipOutValEl, pt.ioParts.outTok); + } + patchAttr(tipSub, 'hidden', hasIoParts || !pt.subDetail); + if (!hasIoParts && pt.subDetail) { + patchText(tipSub, pt.subDetail); + } + patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary); + if (pt.anomalySummary) { + patchText(tipAnomaly, pt.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' }); + } + + for (const [tIdx, el] of tickElsByIdx.entries()) { + patchClasses(el, { 'is-hovered': tIdx === idx }); } } - for (const [tIdx, el] of tickElsByIdx.entries()) { - patchClasses(el, { 'is-hovered': tIdx === idx }); - } + const wrapRect = lineTooltipCtrl.getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(rootEl.clientWidth || viewW || DEFAULT_VIEW_W); + const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW; + const fallbackY = pt.y + 4; + lineTooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: pointer || lastPointer, + trackedDots: [hoverDot], + viewWidth: viewW, + viewHeight: VIEW_H, + sizeKey: `${hasIoParts ? 'io' : pt.subDetail ? 'sub' : 'min'}:${pt.anomalySummary ? 'a' : '0'}`, + }); } function clearHover() { hoveredIdx = -1; + lastPointer = null; + lineTooltipCtrl.hide(); patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); - patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-tracking': false }); - if (currentPoints.some((p) => p.valid)) { + patchClasses(hoverDot, { 'is-tracking': false }); + if (currentMaxVal > 0 && currentPoints.some((p) => p.valid)) { patchAttr(peakPill, 'hidden', false); } for (const el of tickElsByIdx.values()) { @@ -958,7 +363,11 @@ export function createSessionLineChart() { 0, Math.min(currentPoints.length - 1, Math.round(ratio * (currentPoints.length - 1))) ); - showHoverAt(idx); + const pointer = + Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) + ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } + : null; + showHoverAt(idx, pointer); }); plotStage.addEventListener('mouseleave', () => { invalidatePlotSvgRect(); @@ -973,7 +382,7 @@ export function createSessionLineChart() { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; lastPreSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }); resizeObs.observe(plotStage); @@ -981,13 +390,17 @@ export function createSessionLineChart() { onWinResize = () => { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }; window.addEventListener('resize', onWinResize); } function destroy() { + singleCurveMorphCtrl.cancel(); + multiCurveMorphCtrl.cancel(); + peakReadyArmer.cancel(); + lineTooltipCtrl.destroy(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { @@ -1016,6 +429,7 @@ export function createSessionLineChart() { metric = 'totalTokens', showAgentPrefix = false, displaySettings = {}, + _skipMorph = false, } = {}) { lastUpdateParams = { steps, @@ -1274,6 +688,7 @@ export function createSessionLineChart() { peakIdx = i; } } + currentMaxVal = maxVal; const { leftX, rightX, spanX } = resolvePlotBounds(viewW); const denom = maxVal > 0 ? maxVal : 1; @@ -1305,14 +720,22 @@ export function createSessionLineChart() { if (sig !== lastSig) { lastSig = sig; - while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild); - while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild); while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild); if (isMultiCompare) { + singleCurveMorphCtrl.reset(); patchAttr(linePath, 'd', ''); patchAttr(areaPath, 'd', ''); + for (let ci = multiLineGroup.children.length - 1; ci >= 0; ci--) { + const ch = multiLineGroup.children[ci]; + if (ch.getAttribute?.('class') === 'sstep-series-single-dot') { + ch.remove(); + } + } + + const activeGks = new Set(); + const morphItems = []; for (const gk of targetKeys) { const seriesColor = modelColorMap.get(gk) || accentColor; @@ -1328,57 +751,105 @@ export function createSessionLineChart() { patchStyleVar(singleDot, '--sstep-series-color', seriesColor); multiLineGroup.appendChild(singleDot); } else { + activeGks.add(gk); + let nodes = multiSeriesNodesByKey.get(gk); + if (!nodes) { + const mArea = document.createElementNS(SVG_NS, 'path'); + mArea.setAttribute('class', 'sstep-multi-area'); + const mLine = document.createElementNS(SVG_NS, 'path'); + mLine.setAttribute('class', 'sstep-fit-line'); + mLine.setAttribute('fill', 'none'); + nodes = { mArea, mLine }; + multiSeriesNodesByKey.set(gk, nodes); + } + patchStyleVar(nodes.mArea, '--sstep-series-color', seriesColor); + patchStyleVar(nodes.mLine, '--sstep-fit-accent', seriesColor); + multiAreaGroup.appendChild(nodes.mArea); + multiLineGroup.appendChild(nodes.mLine); + const seriesLineD = buildSplinePath(seriesPts); const firstX = seriesPts[0].x.toFixed(1); const lastX = seriesPts[seriesPts.length - 1].x.toFixed(1); + const seriesAreaD = `${seriesLineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`; - const mArea = document.createElementNS(SVG_NS, 'path'); - mArea.setAttribute('class', 'sstep-multi-area'); - mArea.setAttribute( - 'd', - `${seriesLineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z` - ); - patchStyleVar(mArea, '--sstep-series-color', seriesColor); - multiAreaGroup.appendChild(mArea); - - const mLine = document.createElementNS(SVG_NS, 'path'); - mLine.setAttribute('class', 'sstep-fit-line'); - mLine.setAttribute('fill', 'none'); - mLine.setAttribute('d', seriesLineD); - patchStyleVar(mLine, '--sstep-fit-accent', seriesColor); - multiLineGroup.appendChild(mLine); - - if (seriesPts.length === 1) { - const pt = seriesPts[0]; - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - dot.setAttribute('r', '2.1'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar(dot, '--dot-stroke', seriesColor); - dotsGroup.appendChild(dot); - } + morphItems.push({ + key: gk, + nextSegs: pointsToNormalizedCubicSegs(seriesPts, BOTTOM_Y, { + leftX, + spanX, + tension: 0.42, + }), + lineEl: nodes.mLine, + areaEl: nodes.mArea, + endDotEl: null, + endX: NaN, + endY: NaN, + finalLineD: seriesLineD, + finalAreaD: seriesAreaD, + }); } } + + for (const [gk, nodes] of multiSeriesNodesByKey.entries()) { + if (!activeGks.has(gk)) { + nodes.mArea.remove(); + nodes.mLine.remove(); + } + } + + multiCurveMorphCtrl.morphSeries({ + items: morphItems, + leftX, + spanX, + bottomY: BOTTOM_Y, + skipMorph: _skipMorph, + }); } else { + multiCurveMorphCtrl.reset(); + for (const nodes of multiSeriesNodesByKey.values()) { + nodes.mArea.remove(); + nodes.mLine.remove(); + } if (validPoints.length === 0) { + singleCurveMorphCtrl.reset(); patchAttr(linePath, 'd', ''); patchAttr(areaPath, 'd', ''); } else if (validPoints.length === 1) { - const yStr = validPoints[0].y.toFixed(1); + const yVal = validPoints[0].y; + const yStr = yVal.toFixed(1); const lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; - patchAttr(linePath, 'd', lineD); - patchAttr( + const areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`; + const flatPts = [ + { x: leftX, y: yVal }, + { x: rightX, y: yVal }, + ]; + singleCurveMorphCtrl.morphTo({ + nextSegs: pointsToNormalizedCubicSegs(flatPts, BOTTOM_Y, { leftX, spanX }), + leftX, + spanX, + bottomY: BOTTOM_Y, + linePath, areaPath, - 'd', - `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z` - ); + finalLineD: lineD, + finalAreaD: areaD, + skipMorph: _skipMorph, + }); } else { const lineD = buildSplinePath(validPoints); const firstX = validPoints[0].x.toFixed(1); const lastX = validPoints[validPoints.length - 1].x.toFixed(1); - patchAttr(linePath, 'd', lineD); - patchAttr(areaPath, 'd', `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`); + const areaD = `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`; + singleCurveMorphCtrl.morphTo({ + nextSegs: pointsToNormalizedCubicSegs(validPoints, BOTTOM_Y, { leftX, spanX }), + leftX, + spanX, + bottomY: BOTTOM_Y, + linePath, + areaPath, + finalLineD: lineD, + finalAreaD: areaD, + skipMorph: _skipMorph, + }); } } @@ -1422,7 +893,10 @@ export function createSessionLineChart() { title: `${pt.stepTag} · ${pt.modelText}`, }); patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); - tickEl.onclick = () => showHoverAt(tIdx); + tickEl.onclick = () => { + lastPointer = null; + showHoverAt(tIdx, null); + }; xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } @@ -1475,7 +949,7 @@ export function createSessionLineChart() { } } - if (peakIdx >= 0 && validPoints.length > 0) { + if (peakIdx >= 0 && validPoints.length > 0 && maxVal > 0) { const peakPt = points[peakIdx]; patchText( peakPill, @@ -1487,6 +961,7 @@ export function createSessionLineChart() { patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + peakReadyArmer.arm(); if (hoveredIdx < 0) patchAttr(peakPill, 'hidden', false); } else { patchAttr(peakPill, 'hidden', true); @@ -1495,7 +970,7 @@ export function createSessionLineChart() { if (hoveredIdx >= points.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHoverAt(hoveredIdx); + showHoverAt(hoveredIdx, lastPointer, { forceRefresh: true }); } let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length }); @@ -1668,16 +1143,28 @@ export function createModelFitChart() { fitStatsEl, ]); - const plotStage = h('div', { className: 'sstep-plot-stage' }, [emptyHintEl, tooltipEl, svg]); - const rootEl = h('div', { className: 'sstep-chart-wrap' }, [plotStage, fitLegendFoot]); + const plotStage = h('div', { className: 'sstep-plot-stage' }, [emptyHintEl, svg]); + const rootEl = h('div', { className: 'sstep-chart-wrap' }, [plotStage, fitLegendFoot, tooltipEl]); let currentSamples = []; let currentMetric = 'tps'; let hoveredIdx = -1; + let lastFitPointer = null; let lastSig = ''; let lastUpdateParams = null; let fitCacheMetric = ''; const fitCache = new Map(); + const multiFitNodesByKey = new Map(); + + const fitMorphCtrl = createFitGridMorphController(); + const fitTooltipCtrl = createFloatingChartTooltipController({ + containerEl: rootEl, + tooltipEl, + defaultTipWidth: 216, + defaultTipHeight: 82, + defaultViewWidth: DEFAULT_VIEW_W, + defaultViewHeight: VIEW_H, + }); function reusePublicationFit(key, xs, ys, maxVal, isMultiCompare) { const previous = fitCache.get(key); @@ -1712,94 +1199,100 @@ export function createModelFitChart() { return false; } - function showHoverAt(idx) { + function showHoverAt(idx, pointer = null, { forceRefresh = false } = {}) { if (idx < 0 || idx >= currentSamples.length) { clearHover(); return; } - hoveredIdx = idx; - const sp = currentSamples[idx]; - patchAttr(hoverLine, 'hidden', false); - patchAttr(hoverLine, 'x1', sp.x.toFixed(1)); - patchAttr(hoverLine, 'x2', sp.x.toFixed(1)); - - patchAttr(hoverFitDot, 'hidden', false); - patchAttr(hoverFitDot, 'cx', sp.x.toFixed(1)); - patchAttr(hoverFitDot, 'cy', sp.fitY.toFixed(1)); - patchStyleVar(hoverFitDot, '--hover-dot-color', sp.seriesColor || 'var(--accent-primary)'); - - patchAttr(hoverRawDot, 'hidden', false); - patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); - patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); - patchClasses(hoverRawDot, { - 'is-anomaly': Boolean(sp.anomalySummary), - 'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'), - }); - const wasHidden = tooltipEl.hasAttribute('hidden'); - patchAttr(tooltipEl, 'hidden', false); - patchText(tipHeadLeft, sp.stepTag); - patchText(tipHeadRight, sp.modelText); - patchText( - tipMainLeft, - t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) - ); - patchText( - tipMainRight, - t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) - ); - - patchAttr(tipSub, 'hidden', false); - if (sp.compareHint) { - patchText(tipSub, sp.compareHint); - } else if (currentSamples.length >= 3 && sp.ciHalf > 0) { - patchText( - tipSub, - `95% CI [${formatChartMetricCompact(currentMetric, sp.ciLow)}, ${formatChartMetricCompact(currentMetric, sp.ciHigh)}]` - ); - } else { - const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); - patchText( - tipSub, - t('chart.step.ctxAndCache', { - ctxTok: formatTokens(ctxTok), - pct: Number(sp.st?.cacheHitPct ?? 0), - }) - ); - } - patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary); - if (sp.anomalySummary) { - patchText(tipAnomaly, sp.anomalySummary); - patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' }); + const changedIdx = forceRefresh || wasHidden || idx !== hoveredIdx; + hoveredIdx = idx; + if (pointer) { + lastFitPointer = pointer; } + const sp = currentSamples[idx]; - const rawPct = (sp.x / viewW) * 100; - const clampedPct = Math.max(1, Math.min(99, rawPct)); - patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-y', '0px'); - if (wasHidden) { - patchClasses(tooltipEl, { 'is-tracking': false }); - void tooltipEl.offsetWidth; - if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { - window.requestAnimationFrame(() => { - if (!tooltipEl.hasAttribute('hidden')) { - patchClasses(tooltipEl, { 'is-tracking': true }); - } - }); + if (changedIdx) { + patchAttr(hoverLine, 'hidden', false); + patchAttr(hoverLine, 'x1', sp.x.toFixed(1)); + patchAttr(hoverLine, 'x2', sp.x.toFixed(1)); + + patchAttr(hoverFitDot, 'hidden', false); + patchAttr(hoverFitDot, 'cx', sp.x.toFixed(1)); + patchAttr(hoverFitDot, 'cy', sp.fitY.toFixed(1)); + patchStyleVar(hoverFitDot, '--hover-dot-color', sp.seriesColor || 'var(--accent-primary)'); + + patchAttr(hoverRawDot, 'hidden', false); + patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1)); + patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1)); + patchClasses(hoverRawDot, { + 'is-anomaly': Boolean(sp.anomalySummary), + 'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'), + }); + + patchText(tipHeadLeft, sp.stepTag); + patchText(tipHeadRight, sp.modelText); + patchText( + tipMainLeft, + t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) + ); + patchText( + tipMainRight, + t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) + ); + + patchAttr(tipSub, 'hidden', false); + if (sp.compareHint) { + patchText(tipSub, sp.compareHint); + } else if (currentSamples.length >= 3 && sp.ciHalf > 0) { + patchText( + tipSub, + `95% CI [${formatChartMetricCompact(currentMetric, sp.ciLow)}, ${formatChartMetricCompact(currentMetric, sp.ciHigh)}]` + ); } else { - patchClasses(tooltipEl, { 'is-tracking': true }); + const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); + patchText( + tipSub, + t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(sp.st?.cacheHitPct ?? 0), + }) + ); + } + patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary); + if (sp.anomalySummary) { + patchText(tipAnomaly, sp.anomalySummary); + patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' }); } } + + const wrapRect = fitTooltipCtrl.getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(rootEl.clientWidth || viewW || DEFAULT_VIEW_W); + const fallbackX = (sp.x / Math.max(1, viewW)) * wrapW; + const fallbackY = sp.fitY + 4; + fitTooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: pointer || lastFitPointer, + trackedDots: [hoverFitDot, hoverRawDot], + viewWidth: viewW, + viewHeight: VIEW_H, + sizeKey: sp.anomalySummary ? 'fit:a' : 'fit:0', + }); } function clearHover() { hoveredIdx = -1; + lastFitPointer = null; + fitTooltipCtrl.hide(); patchAttr(hoverLine, 'hidden', true); patchAttr(hoverFitDot, 'hidden', true); patchAttr(hoverRawDot, 'hidden', true); - patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { 'is-tracking': false }); + patchClasses(hoverFitDot, { 'is-tracking': false }); + patchClasses(hoverRawDot, { 'is-tracking': false }); } let cachedFitSvgRect = null; @@ -1828,10 +1321,15 @@ export function createModelFitChart() { ) { bestIdx = lo - 1; } - showHoverAt(bestIdx); + const pointer = + Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY)) + ? { clientX: Number(e.clientX), clientY: Number(e.clientY) } + : null; + showHoverAt(bestIdx, pointer); }); plotStage.addEventListener('mouseleave', () => { cachedFitSvgRect = null; + fitTooltipCtrl.invalidateRects(); clearHover(); }); @@ -1840,9 +1338,10 @@ export function createModelFitChart() { if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver(() => { cachedFitSvgRect = null; + fitTooltipCtrl.invalidateRects(); if (syncViewWidth() && lastUpdateParams) { lastSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }); resizeObs.observe(plotStage); @@ -1850,13 +1349,15 @@ export function createModelFitChart() { onWinResize = () => { if (syncViewWidth() && lastUpdateParams) { lastSig = ''; - update(lastUpdateParams); + update({ ...lastUpdateParams, _skipMorph: true }); } }; window.addEventListener('resize', onWinResize); } function destroy() { + fitMorphCtrl.cancel(); + fitTooltipCtrl.destroy(); resizeObs?.disconnect(); resizeObs = null; if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') { @@ -2002,6 +1503,7 @@ export function createModelFitChart() { metric = 'tps', showAgentPrefix = false, displaySettings = {}, + _skipMorph = false, } = {}) { lastUpdateParams = { steps, @@ -2088,13 +1590,16 @@ export function createModelFitChart() { if (matchedItems.length === 0) { fitCache.clear(); + fitMorphCtrl.reset(); currentSamples = []; lastSig = 'empty'; patchAttr(ciBandPath, 'd', ''); patchAttr(fitPath, 'd', ''); patchAttr(olsLine, 'hidden', true); - while (multiBandGroup.firstChild) multiBandGroup.removeChild(multiBandGroup.firstChild); - while (multiCurveGroup.firstChild) multiCurveGroup.removeChild(multiCurveGroup.firstChild); + for (const nodes of multiFitNodesByKey.values()) { + nodes.bandEl.remove(); + nodes.curveEl.remove(); + } while (gridGroup.firstChild) gridGroup.removeChild(gridGroup.firstChild); while (axesGroup.firstChild) axesGroup.removeChild(axesGroup.firstChild); while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); @@ -2245,9 +1750,7 @@ export function createModelFitChart() { showAgentPrefix, }); - while (multiBandGroup.firstChild) multiBandGroup.removeChild(multiBandGroup.firstChild); while (scatterGroup.firstChild) scatterGroup.removeChild(scatterGroup.firstChild); - while (multiCurveGroup.firstChild) multiCurveGroup.removeChild(multiCurveGroup.firstChild); const dotRadius = combinedSamples.length > 80 ? '1.8' : combinedSamples.length > 36 ? '2.1' : '2.4'; @@ -2257,6 +1760,8 @@ export function createModelFitChart() { ? document.createDocumentFragment() : scatterGroup; const anomalyOverlayDots = []; + const activeFitKeys = new Set(); + const fitMorphItems = []; for (const s of seriesList) { const binCounts = dedupOverdraw ? new Map() : null; @@ -2280,18 +1785,43 @@ export function createModelFitChart() { scatterTarget.appendChild(dot); } + activeFitKeys.add(s.key); + let nodes = multiFitNodesByKey.get(s.key); + if (!nodes) { + const bandEl = document.createElementNS(SVG_NS, 'path'); + bandEl.setAttribute('class', 'sstep-ci-band is-multi'); + const curveEl = document.createElementNS(SVG_NS, 'path'); + curveEl.setAttribute('class', 'sstep-fit-line'); + curveEl.setAttribute('fill', 'none'); + nodes = { bandEl, curveEl }; + multiFitNodesByKey.set(s.key, nodes); + } + patchStyleVar(nodes.bandEl, '--sstep-fit-accent', s.colorVar); + patchStyleVar(nodes.curveEl, '--sstep-fit-accent', s.colorVar); + if (s.samples.length === 1) { const sp = s.samples[0]; const segHalf = Math.min(12, plotSpanX * 0.04); - const x1 = Math.max(plotLeft, sp.x - segHalf).toFixed(1); - const x2 = Math.min(plotRight, sp.x + segHalf).toFixed(1); + const x1 = Math.max(plotLeft, sp.x - segHalf); + const x2 = Math.min(plotRight, sp.x + segHalf); const yStr = sp.fitY.toFixed(1); - const lineEl = document.createElementNS(SVG_NS, 'path'); - lineEl.setAttribute('class', 'sstep-fit-line'); - lineEl.setAttribute('fill', 'none'); - lineEl.setAttribute('d', `M ${x1} ${yStr} L ${x2} ${yStr}`); - patchStyleVar(lineEl, '--sstep-fit-accent', s.colorVar); - multiCurveGroup.appendChild(lineEl); + const flatCurveD = `M ${x1.toFixed(1)} ${yStr} L ${x2.toFixed(1)} ${yStr}`; + nodes.bandEl.setAttribute('d', ''); + nodes.bandEl.remove(); + multiCurveGroup.appendChild(nodes.curveEl); + fitMorphItems.push({ + key: `multi:${s.key}`, + gridPts: [ + { x: x1, fitY: sp.fitY, lowY: sp.fitY, highY: sp.fitY }, + { x: x2, fitY: sp.fitY, lowY: sp.fitY, highY: sp.fitY }, + ], + curveEl: nodes.curveEl, + bandEl: null, + olsEl: null, + olsCoords: null, + finalCurveD: flatCurveD, + finalBandD: '', + }); } else { const gridPts = s.pubFit.grid.map((g) => ({ x: mapX(g.x), @@ -2300,8 +1830,9 @@ export function createModelFitChart() { highY: mapY(g.ciHigh), })); + let bandD = ''; if (s.samples.length >= 3) { - let bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; + bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; for (let i = 1; i < gridPts.length; i++) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].highY.toFixed(1)}`; } @@ -2309,24 +1840,34 @@ export function createModelFitChart() { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].lowY.toFixed(1)}`; } bandD += ' Z'; - const bandEl = document.createElementNS(SVG_NS, 'path'); - bandEl.setAttribute('class', 'sstep-ci-band is-multi'); - bandEl.setAttribute('d', bandD); - patchStyleVar(bandEl, '--sstep-fit-accent', s.colorVar); - multiBandGroup.appendChild(bandEl); + multiBandGroup.appendChild(nodes.bandEl); + } else { + nodes.bandEl.setAttribute('d', ''); + nodes.bandEl.remove(); } - const curveEl = document.createElementNS(SVG_NS, 'path'); - curveEl.setAttribute('class', 'sstep-fit-line'); - curveEl.setAttribute('fill', 'none'); - curveEl.setAttribute( - 'd', - buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))) - ); - patchStyleVar(curveEl, '--sstep-fit-accent', s.colorVar); - multiCurveGroup.appendChild(curveEl); + const curveD = buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))); + multiCurveGroup.appendChild(nodes.curveEl); + fitMorphItems.push({ + key: `multi:${s.key}`, + gridPts, + curveEl: nodes.curveEl, + bandEl: bandD ? nodes.bandEl : null, + olsEl: null, + olsCoords: null, + finalCurveD: curveD, + finalBandD: bandD, + }); } } + + for (const [k, nodes] of multiFitNodesByKey.entries()) { + if (!activeFitKeys.has(k)) { + nodes.bandEl.remove(); + nodes.curveEl.remove(); + } + } + fitMorphCtrl.morphFits({ items: fitMorphItems, skipMorph: _skipMorph }); anomalyOverlayDots.sort((a, b) => a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 ); @@ -2377,7 +1918,7 @@ export function createModelFitChart() { if (hoveredIdx >= currentSamples.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHoverAt(hoveredIdx); + showHoverAt(hoveredIdx, lastFitPointer, { forceRefresh: true }); } return { @@ -2390,8 +1931,10 @@ export function createModelFitChart() { } // 分支 B:单模型或整体合并单曲线模式 - while (multiBandGroup.firstChild) multiBandGroup.removeChild(multiBandGroup.firstChild); - while (multiCurveGroup.firstChild) multiCurveGroup.removeChild(multiCurveGroup.firstChild); + for (const nodes of multiFitNodesByKey.values()) { + nodes.bandEl.remove(); + nodes.curveEl.remove(); + } patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); @@ -2522,12 +2065,34 @@ export function createModelFitChart() { scatterGroup.appendChild(scatterTarget); } - // 3. 绘制 95% CI 置信带闭合多边形与回归拟合曲线(绝不向底部 X 轴填充面积!) + // 3. 绘制 95% CI 置信带闭合多边形和回归拟合曲线(支持 240ms 平滑连续形变,绝不向底部 X 轴填充面积) if (isSingle) { - const yStr = samples[0].fitY.toFixed(1); - patchAttr(fitPath, 'd', `M ${plotLeft.toFixed(1)} ${yStr} L ${plotRight.toFixed(1)} ${yStr}`); + const yVal = samples[0].fitY; + const yStr = yVal.toFixed(1); + const flatCurveD = `M ${plotLeft.toFixed(1)} ${yStr} L ${plotRight.toFixed(1)} ${yStr}`; patchAttr(ciBandPath, 'd', ''); patchAttr(olsLine, 'hidden', true); + const flatGrid = Array.from({ length: 64 }, (_, gi) => ({ + x: plotLeft + (gi / 63) * plotSpanX, + fitY: yVal, + lowY: yVal, + highY: yVal, + })); + fitMorphCtrl.morphFits({ + items: [ + { + key: 'single', + gridPts: flatGrid, + curveEl: fitPath, + bandEl: null, + olsEl: null, + olsCoords: null, + finalCurveD: flatCurveD, + finalBandD: '', + }, + ], + skipMorph: _skipMorph, + }); } else { const gridPts = pubFit.grid.map((g) => ({ x: mapX(g.x), @@ -2536,14 +2101,10 @@ export function createModelFitChart() { highY: mapY(g.ciHigh), })); - patchAttr( - fitPath, - 'd', - buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))) - ); - + const curveD = buildPolylinePath(gridPts.map((p) => ({ x: p.x, y: p.fitY }))); + let bandD = ''; if (samples.length >= 3) { - let bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; + bandD = `M ${gridPts[0].x.toFixed(1)} ${gridPts[0].highY.toFixed(1)}`; for (let i = 1; i < gridPts.length; i++) { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].highY.toFixed(1)}`; } @@ -2551,21 +2112,39 @@ export function createModelFitChart() { bandD += ` L ${gridPts[i].x.toFixed(1)} ${gridPts[i].lowY.toFixed(1)}`; } bandD += ' Z'; - patchAttr(ciBandPath, 'd', bandD); } else { patchAttr(ciBandPath, 'd', ''); } const showOlsRef = samples.length >= 6; patchAttr(olsLine, 'hidden', !showOlsRef); + let olsCoords = null; if (showOlsRef) { const olsStartVal = clampValue(pubFit.intercept + pubFit.slope * xMin, minBound, maxBound); const olsEndVal = clampValue(pubFit.intercept + pubFit.slope * xMax, minBound, maxBound); - patchAttr(olsLine, 'x1', plotLeft.toFixed(1)); - patchAttr(olsLine, 'y1', mapY(olsStartVal).toFixed(1)); - patchAttr(olsLine, 'x2', plotRight.toFixed(1)); - patchAttr(olsLine, 'y2', mapY(olsEndVal).toFixed(1)); + olsCoords = { + x1: plotLeft, + y1: mapY(olsStartVal), + x2: plotRight, + y2: mapY(olsEndVal), + }; } + + fitMorphCtrl.morphFits({ + items: [ + { + key: 'single', + gridPts, + curveEl: fitPath, + bandEl: bandD ? ciBandPath : null, + olsEl: showOlsRef ? olsLine : null, + olsCoords, + finalCurveD: curveD, + finalBandD: bandD, + }, + ], + skipMorph: _skipMorph, + }); } } @@ -2594,7 +2173,7 @@ export function createModelFitChart() { if (hoveredIdx >= samples.length) { clearHover(); } else if (hoveredIdx >= 0) { - showHoverAt(hoveredIdx); + showHoverAt(hoveredIdx, lastFitPointer, { forceRefresh: true }); } return { sampleCount: samples.length, summaryBadge }; diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 530e326..e56792d 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -22,6 +22,12 @@ import { import { SVG_NS } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js'; import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js'; +import { + createCubicCurveMorphController, + createFloatingChartTooltipController, + createReadyClassArmer, + pointsToNormalizedCubicSegs, +} from './chartMotion.js'; /** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ export const HEATMAP_DAYS_THRESHOLD = 90; @@ -53,175 +59,6 @@ function buildSmoothSplinePath(points) { return d; } -/** - * 将采样点数组转为归一化横轴 `u` (`0..1`) 上的精确三次贝塞尔分段链, - * 控制点严格保持跟 `buildSmoothSplinePath` 一致的 `0.42` 水平张力。 - * - * @param {Array<{ y: number }>} pts - * @param {number} bottomY - * @returns {Array<{ u0: number, y0: number, cu1: number, cy1: number, cu2: number, cy2: number, u3: number, y3: number }>} - */ -function pointsToNormalizedCubicSegs(pts, bottomY) { - const n = pts.length; - if (n === 0) { - return [ - { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, - ]; - } - if (n === 1) { - const py = pts[0].y; - if (Math.abs(py - bottomY) < 0.01) { - return [ - { u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY }, - ]; - } - return [ - { u0: 0, y0: bottomY, cu1: 0.21, cy1: bottomY, cu2: 0.29, cy2: py, u3: 0.5, y3: py }, - { u0: 0.5, y0: py, cu1: 0.71, cy1: py, cu2: 0.79, cy2: bottomY, u3: 1, y3: bottomY }, - ]; - } - const segs = new Array(n - 1); - for (let i = 0; i < n - 1; i++) { - const u0 = i / (n - 1); - const u3 = (i + 1) / (n - 1); - const du = u3 - u0; - const y0 = pts[i].y; - const y3 = pts[i + 1].y; - segs[i] = { - u0, - y0, - cu1: u0 + du * 0.42, - cy1: y0, - cu2: u3 - du * 0.42, - cy2: y3, - u3, - y3, - }; - } - return segs; -} - -function solveCubicParamForU(seg, targetU) { - if (targetU <= seg.u0) return 0; - if (targetU >= seg.u3) return 1; - let lo = 0; - let hi = 1; - for (let it = 0; it < 20; it++) { - const s = (lo + hi) * 0.5; - const inv = 1 - s; - const u = - inv * inv * inv * seg.u0 + - 3 * inv * inv * s * seg.cu1 + - 3 * inv * s * s * seg.cu2 + - s * s * s * seg.u3; - if (u < targetU) lo = s; - else hi = s; - } - return (lo + hi) * 0.5; -} - -function splitCubicAt(seg, s) { - const u01 = seg.u0 + (seg.cu1 - seg.u0) * s; - const y01 = seg.y0 + (seg.cy1 - seg.y0) * s; - const u12 = seg.cu1 + (seg.cu2 - seg.cu1) * s; - const y12 = seg.cy1 + (seg.cy2 - seg.cy1) * s; - const u23 = seg.cu2 + (seg.u3 - seg.cu2) * s; - const y23 = seg.cy2 + (seg.y3 - seg.cy2) * s; - - const u012 = u01 + (u12 - u01) * s; - const y012 = y01 + (y12 - y01) * s; - const u123 = u12 + (u23 - u12) * s; - const y123 = y12 + (y23 - y12) * s; - - const u0123 = u012 + (u123 - u012) * s; - const y0123 = y012 + (y123 - y012) * s; - - return [ - { u0: seg.u0, y0: seg.y0, cu1: u01, cy1: y01, cu2: u012, cy2: y012, u3: u0123, y3: y0123 }, - { u0: u0123, y0: y0123, cu1: u123, cy1: y123, cu2: u23, cy2: y23, u3: seg.u3, y3: seg.y3 }, - ]; -} - -function extractCubicSubsegment(seg, uStart, uEnd) { - const s0 = solveCubicParamForU(seg, uStart); - const s1 = solveCubicParamForU(seg, uEnd); - if (s0 <= 1e-7 && s1 >= 1 - 1e-7) return { ...seg }; - const [, right] = s0 <= 1e-7 ? [null, seg] : splitCubicAt(seg, s0); - const remSpan = 1 - s0; - const localS1 = remSpan > 1e-9 ? Math.min(1, Math.max(0, (s1 - s0) / remSpan)) : 1; - const [sub] = localS1 >= 1 - 1e-7 ? [right] : splitCubicAt(right, localS1); - sub.u0 = uStart; - sub.u3 = uEnd; - return sub; -} - -/** - * 合并两条贝塞尔链的断点(始终完整保留目标链 `toSegs` 全部断点,保证 `t=1` 零几何误差)。 - */ -function mergeNormalizedKnots(fromSegs, toSegs) { - const raw = [0, 1]; - for (let i = 0; i < toSegs.length; i++) raw.push(toSegs[i].u3); - if (fromSegs.length <= 64) { - for (let i = 0; i < fromSegs.length; i++) raw.push(fromSegs[i].u3); - } else { - const stride = Math.ceil(fromSegs.length / 48); - for (let i = 0; i < fromSegs.length; i += stride) raw.push(fromSegs[i].u3); - } - raw.sort((a, b) => a - b); - const uniq = [0]; - for (let i = 1; i < raw.length; i++) { - if (raw[i] - uniq[uniq.length - 1] > 1e-6) { - uniq.push(raw[i]); - } - } - uniq[uniq.length - 1] = 1; - return uniq; -} - -function subdivideChainToKnots(segs, knots) { - const out = new Array(knots.length - 1); - let j = 0; - for (let k = 0; k < knots.length - 1; k++) { - const a = knots[k]; - const b = knots[k + 1]; - const mid = (a + b) * 0.5; - while (j < segs.length - 1 && segs[j].u3 < mid) j++; - out[k] = extractCubicSubsegment(segs[j], a, b); - } - return out; -} - -function buildPathFromNormalizedSegs(segs, leftX, spanX) { - const xAt = (u) => (leftX + u * spanX).toFixed(1); - let d = `M ${xAt(segs[0].u0)} ${segs[0].y0.toFixed(1)}`; - for (let i = 0; i < segs.length; i++) { - const s = segs[i]; - d += ` C ${xAt(s.cu1)} ${s.cy1.toFixed(1)}, ${xAt(s.cu2)} ${s.cy2.toFixed(1)}, ${xAt(s.u3)} ${s.y3.toFixed(1)}`; - } - return d; -} - -/** - * 求解标准 CSS `cubic-bezier(x1, y1, x2, y2)` 在进度 `t` (`0..1`) 处的精确输出值, - * 确保 JS 曲线形变、峰值胶囊滑动及进度条宽度缩放严格同频。 - */ -function evalCubicBezier(x1, y1, x2, y2, t) { - if (t <= 0) return 0; - if (t >= 1) return 1; - let lo = 0; - let hi = 1; - for (let i = 0; i < 16; i++) { - const s = (lo + hi) * 0.5; - const inv = 1 - s; - const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s; - if (bx < t) lo = s; - else hi = s; - } - const s = (lo + hi) * 0.5; - const inv = 1 - s; - return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s; -} - /** * 根据分桶总数及标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 * @@ -796,7 +633,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { hoverDot.setAttribute('hidden', 'true'); svg.appendChild(hoverDot); - const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); + const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0', hidden: true }); // 共享悬停详情浮层卡片(曲线图和热力格子图共用,含分模型四段进度条及底部四通道明细) const tooltipContent = createConsumptionBreakdownContent({ @@ -870,6 +707,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { let currentSlots = []; let currentPts = []; + let currentMaxTokens = 0; let currentIsHeatmap = false; let currentHmMode = 'day'; let lastBuildSegmentsFn = null; @@ -888,161 +726,22 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { let hoveredCellEl = null; let lastPointer = null; let lastRenderSig = ''; - let hasRenderedLineOnce = false; - let peakReadyArmed = false; - let peakReadyRaf = 0; - let tipTrackRaf = 0; - let morphRafId = 0; - let committedSegs = []; - let liveMorphSegs = null; const vGridLinePool = []; const xAxisTickPool = []; const hmMonthPool = []; const hmCellPool = []; - const CURVE_MORPH_DURATION_MS = 240; - - function cancelCurveMorph() { - if ( - morphRafId && - typeof window !== 'undefined' && - typeof window.cancelAnimationFrame === 'function' - ) { - window.cancelAnimationFrame(morphRafId); - } - morphRafId = 0; - } - - function cancelPeakReadyRaf() { - if ( - peakReadyRaf && - typeof window !== 'undefined' && - typeof window.cancelAnimationFrame === 'function' - ) { - window.cancelAnimationFrame(peakReadyRaf); - } - peakReadyRaf = 0; - } - - function canAnimateInBrowser() { - if ( - typeof window === 'undefined' || - typeof window.requestAnimationFrame !== 'function' || - typeof window.getComputedStyle !== 'function' || - typeof performance === 'undefined' || - typeof performance.now !== 'function' - ) { - return false; - } - if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) { - return false; - } - return true; - } - - function startCurveMorph( - fromSegs, - toSegs, - { leftX, rightX, spanX, finalLineD, finalAreaD } - ) { - cancelCurveMorph(); - if (!canAnimateInBrowser() || fromSegs.length === 0 || toSegs.length === 0) { - liveMorphSegs = null; - patchAttr(linePath, 'd', finalLineD); - patchAttr(areaPath, 'd', finalAreaD); - return; - } - - const knots = mergeNormalizedKnots(fromSegs, toSegs); - const alignedFrom = subdivideChainToKnots(fromSegs, knots); - const alignedTo = subdivideChainToKnots(toSegs, knots); - const segCount = alignedTo.length; - let maxDeltaY = 0; - for (let i = 0; i < segCount; i++) { - const a = alignedFrom[i]; - const b = alignedTo[i]; - maxDeltaY = Math.max( - maxDeltaY, - Math.abs(b.y0 - a.y0), - Math.abs(b.cy1 - a.cy1), - Math.abs(b.cy2 - a.cy2), - Math.abs(b.y3 - a.y3) - ); - } - - if (maxDeltaY < 0.25) { - liveMorphSegs = null; - patchAttr(linePath, 'd', finalLineD); - patchAttr(areaPath, 'd', finalAreaD); - return; - } - - const activeLive = alignedFrom.map((s) => ({ ...s })); - liveMorphSegs = activeLive; - const rightXFixed = rightX.toFixed(1); - const leftXFixed = leftX.toFixed(1); - const startTs = performance.now(); - - const step = (nowTs) => { - const elapsed = Math.max(0, nowTs - startTs); - const rawT = Math.min(1, elapsed / CURVE_MORPH_DURATION_MS); - if (rawT >= 1) { - morphRafId = 0; - liveMorphSegs = null; - patchAttr(linePath, 'd', finalLineD); - patchAttr(areaPath, 'd', finalAreaD); - return; - } - const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); - for (let i = 0; i < segCount; i++) { - const a = alignedFrom[i]; - const b = alignedTo[i]; - const cur = activeLive[i]; - cur.u0 = a.u0 + (b.u0 - a.u0) * ease; - cur.y0 = a.y0 + (b.y0 - a.y0) * ease; - cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; - cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; - cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; - cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; - cur.u3 = a.u3 + (b.u3 - a.u3) * ease; - cur.y3 = a.y3 + (b.y3 - a.y3) * ease; - } - const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); - const morphAreaD = `${morphLineD} L ${rightXFixed} ${BOTTOM_Y} L ${leftXFixed} ${BOTTOM_Y} Z`; - patchAttr(linePath, 'd', morphLineD); - patchAttr(areaPath, 'd', morphAreaD); - morphRafId = window.requestAnimationFrame(step); - }; - - morphRafId = window.requestAnimationFrame(step); - } - - function cancelTipTrackRaf() { - if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { - window.cancelAnimationFrame(tipTrackRaf); - } - tipTrackRaf = 0; - } - - function armTooltipTracking(wasHidden) { - if (!wasHidden) return; - patchClasses(tooltipEl, { 'is-tracking': false }); - patchClasses(hoverDot, { 'is-tracking': false }); - void tooltipEl.offsetWidth; - cancelTipTrackRaf(); - if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { - tipTrackRaf = window.requestAnimationFrame(() => { - tipTrackRaf = 0; - if (!tooltipEl.hasAttribute('hidden')) { - patchClasses(tooltipEl, { 'is-tracking': true }); - patchClasses(hoverDot, { 'is-tracking': true }); - } - }); - } else { - patchClasses(tooltipEl, { 'is-tracking': true }); - patchClasses(hoverDot, { 'is-tracking': true }); - } - } + const curveMorphCtrl = createCubicCurveMorphController(); + const peakReadyArmer = createReadyClassArmer(peakPill, 'is-ready'); + const tooltipCtrl = createFloatingChartTooltipController({ + containerEl: chartWrap, + tooltipEl, + defaultTipWidth: 216, + defaultTipHeight: 104, + defaultViewWidth: DEFAULT_VIEW_W, + defaultViewHeight: VIEW_H, + useFloatingClass: false, + }); function populateTooltipContent(slot) { const slotTok = safeSlotTokens(slot.tokens); @@ -1063,81 +762,13 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { }); } - let cachedWrapRect = null; let cachedSvgRect = null; let cachedHmGridRect = null; - let cachedClipRect = undefined; function invalidateHoverRects() { - cachedWrapRect = null; + tooltipCtrl.invalidateRects(); cachedSvgRect = null; cachedHmGridRect = null; - cachedClipRect = undefined; - } - - function getCachedWrapRect() { - if (!cachedWrapRect) { - cachedWrapRect = chartWrap.getBoundingClientRect?.() || null; - } - return cachedWrapRect; - } - - function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) { - const wrapRect = getCachedWrapRect(); - const wrapW = - wrapRect && wrapRect.width > 0 - ? wrapRect.width - : Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W); - const wrapH = - wrapRect && wrapRect.height > 0 - ? wrapRect.height - : Number(chartWrap.offsetHeight || VIEW_H); - - const tipW = Number(tooltipEl.offsetWidth || 0) || 216; - const tipH = Number(tooltipEl.offsetHeight || 0) || 104; - - const hasPointer = - pointer && - Number.isFinite(Number(pointer.clientX)) && - Number.isFinite(Number(pointer.clientY)) && - wrapRect && - wrapRect.width > 0 && - wrapRect.height > 0; - - const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX; - const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY; - - if (cachedClipRect === undefined) { - const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null; - cachedClipRect = clipEl?.getBoundingClientRect?.() || null; - } - const clipRect = cachedClipRect; - const hasClip = Boolean( - clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0 - ); - const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16; - const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16; - - const maxLeft = Math.max(4, wrapW - tipW - 4); - let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2)); - const aboveY = anchorY - tipH - 14; - let topPx; - - if (aboveY >= minY) { - topPx = Math.min(maxY, aboveY); - } else if (anchorX + 16 + tipW <= wrapW - 4) { - leftPx = anchorX + 16; - topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); - } else if (anchorX - 16 - tipW >= 4) { - leftPx = anchorX - 16 - tipW; - topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); - } else { - topPx = Math.max(minY, Math.min(maxY, anchorY + 18)); - } - - patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`); - patchStyleVar(tooltipEl, '--tip-shift', '0px'); - patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`); } function showLineHoverAtIndex(idx, pointer = null) { @@ -1169,7 +800,6 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { 'is-hm-top': false, 'is-line-low': false, }); - patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); for (const [tIdx, el] of tickElsByIdx.entries()) { @@ -1177,15 +807,21 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } } - const wrapRect = getCachedWrapRect(); + const wrapRect = tooltipCtrl.getWrapRect(); const wrapW = wrapRect && wrapRect.width > 0 ? wrapRect.width : Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W); const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW; const fallbackY = pt.y + 6; - positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer); - armTooltipTracking(wasHidden); + tooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: pointer || lastPointer, + trackedDots: [hoverDot], + viewWidth: viewW, + viewHeight: VIEW_H, + }); } function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) { @@ -1239,11 +875,10 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { 'is-hm-top': false, 'is-line-low': false, }); - patchAttr(tooltipEl, 'hidden', false); populateTooltipContent(slot); } - const wrapRect = getCachedWrapRect(); + const wrapRect = tooltipCtrl.getWrapRect(); const cellRect = targetCell.getBoundingClientRect?.() || null; const wrapW = wrapRect && wrapRect.width > 0 @@ -1277,26 +912,25 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } : rawPtr; - positionTooltipNearAnchor(fallbackX, fallbackY, effectivePtr); - armTooltipTracking(wasHidden); + tooltipCtrl.show({ + fallbackX, + fallbackY, + pointer: effectivePtr, + trackedDots: [], + viewWidth: viewW, + viewHeight: VIEW_H, + }); } function clearHover() { invalidateHoverRects(); - cancelTipTrackRaf(); + tooltipCtrl.hide(); hoveredIdx = -1; lastPointer = null; patchAttr(hoverLine, 'hidden', true); patchAttr(hoverDot, 'hidden', true); - patchAttr(tooltipEl, 'hidden', true); - patchClasses(tooltipEl, { - 'is-hm-bottom': false, - 'is-hm-top': false, - 'is-line-low': false, - 'is-tracking': false, - }); patchClasses(hoverDot, { 'is-tracking': false }); - if (!currentIsHeatmap) { + if (!currentIsHeatmap && currentMaxTokens > 0) { patchAttr(peakPill, 'hidden', false); } if (hoveredHighlightEls.length > 0) { @@ -1606,9 +1240,9 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } function destroy() { - cancelTipTrackRaf(); - cancelCurveMorph(); - cancelPeakReadyRaf(); + tooltipCtrl.destroy(); + curveMorphCtrl.cancel(); + peakReadyArmer.cancel(); plotStage.removeEventListener('mousemove', handlePointerMove); plotStage.removeEventListener('click', handleLineClick); plotStage.removeEventListener('mouseleave', clearHover); @@ -1661,8 +1295,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { if (modeChanged) { clearHover(); - cancelCurveMorph(); - liveMorphSegs = null; + curveMorphCtrl.cancel(); } patchClasses(chartWrap, { 'is-heatmap': useHeatmap }); patchAttr(plotStage, 'hidden', useHeatmap); @@ -1689,6 +1322,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { peakIdx = i; } } + currentMaxTokens = maxTokens; const locale = getEffectiveLocale(); patchText(wdayMonEl, t('chart.trend.wdayMon')); @@ -2038,23 +1672,17 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; } - const prevSegs = liveMorphSegs || committedSegs; - committedSegs = nextSegs; - if (hasRenderedLineOnce && !modeChanged && prevSegs.length > 0) { - startCurveMorph(prevSegs, nextSegs, { - leftX, - rightX, - spanX, - finalLineD: lineD, - finalAreaD: areaD, - }); - } else { - cancelCurveMorph(); - liveMorphSegs = null; - patchAttr(linePath, 'd', lineD); - patchAttr(areaPath, 'd', areaD); - } - hasRenderedLineOnce = true; + curveMorphCtrl.morphTo({ + nextSegs, + leftX, + spanX, + bottomY: BOTTOM_Y, + linePath, + areaPath, + finalLineD: lineD, + finalAreaD: areaD, + skipMorph: modeChanged, + }); // 就地增量补丁垂直参考网格线及底部 X 轴标签,保持文字常驻不重排不闪烁 const tickIndices = computeTickIndices(slots); @@ -2123,29 +1751,24 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { } } - const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; - - const peakSlot = slots[peakIdx]; - const peakText = - maxTokens > 0 && peakSlot?.label + if (maxTokens > 0) { + const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; + const peakSlot = slots[peakIdx]; + const peakText = peakSlot?.label ? t('chart.trend.peakPill', { label: peakSlot.label, tokens: formatTokensPrecise(maxTokens), }) : formatTokensPrecise(maxTokens); - patchText(peakPill, peakText); - const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); - patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); - if (!peakReadyArmed) { - peakReadyArmed = true; - if (canAnimateInBrowser()) { - peakReadyRaf = window.requestAnimationFrame(() => { - peakReadyRaf = 0; - patchClasses(peakPill, { 'is-ready': true }); - }); - } else { - patchClasses(peakPill, { 'is-ready': true }); + patchText(peakPill, peakText); + const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); + patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + peakReadyArmer.arm(); + if (hoveredIdx < 0) { + patchAttr(peakPill, 'hidden', false); } + } else { + patchAttr(peakPill, 'hidden', true); } if (hoveredIdx >= slots.length) { diff --git a/sidecars/panel/src/components/charts/chartMotion.js b/sidecars/panel/src/components/charts/chartMotion.js new file mode 100644 index 0000000..a7b0d32 --- /dev/null +++ b/sidecars/panel/src/components/charts/chartMotion.js @@ -0,0 +1,1080 @@ +/** + * @fileoverview Shared interactive chart motion & 2D mouse-following tooltip primitives (`chartMotion.js`). + * + * Reused across: + * 1. `TrendAreaChart.js` (ConsumptionView usage trend & heatmap); + * 2. `SessionStepCharts.js` (StepsDetailView summary step line chart & LOESS model fit chart); + * 3. `AccountQuotaTrendCard.js` (SettingsAccountTab per-account quota trajectory chart). + * + * Provides: + * - GPU-composited 2D pointer-following floating tooltip (`translate3d`) with 4-way collision + * avoidance, viewport clipping, cached layout rects, and `150ms` `.is-tracking` arming + * synchronized with SVG focus dots (`.trend-hover-dot` / `.sstep-hover-raw-dot`); + * - Exact CSS `cubic-bezier` solver (`evalCubicBezier`) and `240ms` normalized cubic-Bezier + * chain subdivision morphing for single-series and multi-series curves + area fills; + * - Smooth `240ms` LOESS curve, `95% CI` confidence band, and OLS line morphing; + * - Next-frame `.is-ready` transition arming for sliding peak badges (`.trend-peak-pill`). + */ + +import { patchAttr, patchClasses, patchStyleVar } from '../../core/domPatch.js'; + +export const CHART_CURVE_MORPH_MS = 240; + +/** + * Checks whether smooth `requestAnimationFrame` chart animations should run in the current + * environment (browser runtime with `prefers-reduced-motion` not enabled). + */ +export function canAnimateChartInBrowser() { + if ( + typeof window === 'undefined' || + typeof window.requestAnimationFrame !== 'function' || + typeof window.getComputedStyle !== 'function' || + typeof performance === 'undefined' || + typeof performance.now !== 'function' + ) { + return false; + } + if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) { + return false; + } + return true; +} + +/** + * Solves standard CSS `cubic-bezier(x1, y1, x2, y2)` at progress `t` (`0..1`) + * so JS path morphing, peak-pill gliding, and CSS bar transitions stay in lockstep. + */ +export function evalCubicBezier(x1, y1, x2, y2, t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + let lo = 0; + let hi = 1; + for (let i = 0; i < 16; i++) { + const s = (lo + hi) * 0.5; + const inv = 1 - s; + const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s; + if (bx < t) lo = s; + else hi = s; + } + const s = (lo + hi) * 0.5; + const inv = 1 - s; + return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s; +} + +/** + * Arms a CSS transition readiness class (e.g. `.is-ready` on `.trend-peak-pill`) on the next + * animation frame so initial placement snaps cleanly without sliding in from `50%`. + */ +export function createReadyClassArmer(el, readyClass = 'is-ready') { + let armed = false; + let rafId = 0; + + function cancel() { + if (rafId && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') { + window.cancelAnimationFrame(rafId); + } + rafId = 0; + } + + function arm() { + if (armed) return; + armed = true; + if (canAnimateChartInBrowser()) { + rafId = window.requestAnimationFrame(() => { + rafId = 0; + patchClasses(el, { [readyClass]: true }); + }); + } else { + patchClasses(el, { [readyClass]: true }); + } + } + + return { arm, cancel }; +} + +/** + * Converts 2D SVG points into a normalized horizontal (`u` in `0..1`) cubic-Bezier chain + * with horizontal endpoint tangents (`0.42` tension by default, zero vertical overshoot). + * Supports both uniform slot spacing and arbitrary timestamp/x coordinates via `leftX` + `spanX`. + * + * @param {Array<{ x?: number, y: number }>} pts + * @param {number} bottomY + * @param {{ leftX?: number, spanX?: number, tension?: number }} [opts] + */ +export function pointsToNormalizedCubicSegs( + pts, + bottomY, + { leftX = 0, spanX = 0, tension = 0.42 } = {} +) { + const n = Array.isArray(pts) ? pts.length : 0; + const invT = 1 - tension; + if (n === 0) { + return [ + { + u0: 0, + y0: bottomY, + cu1: tension, + cy1: bottomY, + cu2: invT, + cy2: bottomY, + u3: 1, + y3: bottomY, + }, + ]; + } + if (n === 1) { + const py = pts[0].y; + const uMid = + spanX > 0 && Number.isFinite(pts[0].x) + ? Math.max(0, Math.min(1, (pts[0].x - leftX) / spanX)) + : 0.5; + if (Math.abs(py - bottomY) < 0.01) { + return [ + { + u0: 0, + y0: bottomY, + cu1: tension, + cy1: bottomY, + cu2: invT, + cy2: bottomY, + u3: 1, + y3: bottomY, + }, + ]; + } + return [ + { + u0: 0, + y0: bottomY, + cu1: uMid * tension, + cy1: bottomY, + cu2: uMid * invT, + cy2: py, + u3: uMid, + y3: py, + }, + { + u0: uMid, + y0: py, + cu1: uMid + (1 - uMid) * tension, + cy1: py, + cu2: uMid + (1 - uMid) * invT, + cy2: bottomY, + u3: 1, + y3: bottomY, + }, + ]; + } + + const useCoordU = spanX > 0 && Number.isFinite(pts[0].x); + const segs = []; + let prevU = useCoordU ? Math.max(0, Math.min(1, (pts[0].x - leftX) / spanX)) : 0; + let prevY = pts[0].y; + + for (let i = 1; i < n; i++) { + const rawU = useCoordU + ? Math.max(0, Math.min(1, (pts[i].x - leftX) / spanX)) + : i / (n - 1); + const u3 = Math.max(prevU, rawU); + const y3 = pts[i].y; + if (u3 - prevU <= 1e-6 && i < n - 1 && Math.abs(y3 - prevY) < 0.05) { + continue; + } + const safeU3 = u3 - prevU <= 1e-6 ? Math.min(1, prevU + 1e-5) : u3; + const du = safeU3 - prevU; + segs.push({ + u0: prevU, + y0: prevY, + cu1: prevU + du * tension, + cy1: prevY, + cu2: safeU3 - du * tension, + cy2: y3, + u3: safeU3, + y3, + }); + prevU = safeU3; + prevY = y3; + } + + if (segs.length === 0) { + return [ + { + u0: prevU, + y0: prevY, + cu1: prevU, + cy1: prevY, + cu2: prevU, + cy2: prevY, + u3: prevU, + y3: prevY, + }, + ]; + } + return segs; +} + +function solveCubicParamForU(seg, targetU) { + if (targetU <= seg.u0) return 0; + if (targetU >= seg.u3) return 1; + let lo = 0; + let hi = 1; + for (let it = 0; it < 20; it++) { + const s = (lo + hi) * 0.5; + const inv = 1 - s; + const u = + inv * inv * inv * seg.u0 + + 3 * inv * inv * s * seg.cu1 + + 3 * inv * s * s * seg.cu2 + + s * s * s * seg.u3; + if (u < targetU) lo = s; + else hi = s; + } + return (lo + hi) * 0.5; +} + +function splitCubicAt(seg, s) { + const u01 = seg.u0 + (seg.cu1 - seg.u0) * s; + const y01 = seg.y0 + (seg.cy1 - seg.y0) * s; + const u12 = seg.cu1 + (seg.cu2 - seg.cu1) * s; + const y12 = seg.cy1 + (seg.cy2 - seg.cy1) * s; + const u23 = seg.cu2 + (seg.u3 - seg.cu2) * s; + const y23 = seg.cy2 + (seg.y3 - seg.cy2) * s; + + const u012 = u01 + (u12 - u01) * s; + const y012 = y01 + (y12 - y01) * s; + const u123 = u12 + (u23 - u12) * s; + const y123 = y12 + (y23 - y12) * s; + + const u0123 = u012 + (u123 - u012) * s; + const y0123 = y012 + (y123 - y012) * s; + + return [ + { u0: seg.u0, y0: seg.y0, cu1: u01, cy1: y01, cu2: u012, cy2: y012, u3: u0123, y3: y0123 }, + { u0: u0123, y0: y0123, cu1: u123, cy1: y123, cu2: u23, cy2: y23, u3: seg.u3, y3: seg.y3 }, + ]; +} + +function extractCubicSubsegment(seg, uStart, uEnd) { + const s0 = solveCubicParamForU(seg, uStart); + const s1 = solveCubicParamForU(seg, uEnd); + if (s0 <= 1e-7 && s1 >= 1 - 1e-7) return { ...seg }; + const [, right] = s0 <= 1e-7 ? [null, seg] : splitCubicAt(seg, s0); + const remSpan = 1 - s0; + const localS1 = remSpan > 1e-9 ? Math.min(1, Math.max(0, (s1 - s0) / remSpan)) : 1; + const [sub] = localS1 >= 1 - 1e-7 ? [right] : splitCubicAt(right, localS1); + sub.u0 = uStart; + sub.u3 = uEnd; + return sub; +} + +/** + * Aligns two cubic-Bezier chains (`fromSegs` and `toSegs`, even when their horizontal `[uStart, uEnd]` + * spans differ) onto a shared normalized `[0..1]` knot partition so every segment pair interpolates + * smoothly without endpoint snapping. + */ +function alignCubicChainsForMorph(fromSegs, toSegs) { + const fStart = fromSegs[0].u0; + const fEnd = fromSegs[fromSegs.length - 1].u3; + const fSpan = fEnd - fStart; + + const tStart = toSegs[0].u0; + const tEnd = toSegs[toSegs.length - 1].u3; + const tSpan = tEnd - tStart; + + const rawTau = [0, 1]; + const pushChainKnots = (segs, start, span, cap) => { + if (!(span > 1e-6)) return; + if (segs.length <= cap) { + for (let i = 0; i < segs.length; i++) { + rawTau.push(Math.max(0, Math.min(1, (segs[i].u3 - start) / span))); + } + } else { + const stride = Math.ceil(segs.length / cap); + for (let i = 0; i < segs.length; i += stride) { + rawTau.push(Math.max(0, Math.min(1, (segs[i].u3 - start) / span))); + } + } + }; + pushChainKnots(toSegs, tStart, tSpan, 96); + pushChainKnots(fromSegs, fStart, fSpan, 48); + + rawTau.sort((a, b) => a - b); + const tauKnots = [0]; + for (let i = 1; i < rawTau.length; i++) { + if (rawTau[i] - tauKnots[tauKnots.length - 1] > 1e-5) { + tauKnots.push(rawTau[i]); + } + } + if (tauKnots.length === 1) tauKnots.push(1); + else tauKnots[tauKnots.length - 1] = 1; + + const subdivideOnTau = (segs, start, span) => { + const out = new Array(tauKnots.length - 1); + let j = 0; + for (let k = 0; k < tauKnots.length - 1; k++) { + const ta = tauKnots[k]; + const tb = tauKnots[k + 1]; + if (!(span > 1e-6)) { + const s0 = segs[0]; + out[k] = { + u0: start, + y0: s0.y0, + cu1: start, + cy1: s0.y0, + cu2: start, + cy2: s0.y3, + u3: start, + y3: s0.y3, + }; + continue; + } + const ua = start + ta * span; + const ub = start + tb * span; + const umid = (ua + ub) * 0.5; + while (j < segs.length - 1 && segs[j].u3 < umid) j++; + out[k] = extractCubicSubsegment(segs[j], ua, ub); + } + return out; + }; + + return { + alignedFrom: subdivideOnTau(fromSegs, fStart, fSpan), + alignedTo: subdivideOnTau(toSegs, tStart, tSpan), + }; +} + +export function buildPathFromNormalizedSegs(segs, leftX, spanX) { + const xAt = (u) => (leftX + u * spanX).toFixed(1); + let d = `M ${xAt(segs[0].u0)} ${segs[0].y0.toFixed(1)}`; + for (let i = 0; i < segs.length; i++) { + const s = segs[i]; + d += ` C ${xAt(s.cu1)} ${s.cy1.toFixed(1)}, ${xAt(s.cu2)} ${s.cy2.toFixed(1)}, ${xAt(s.u3)} ${s.y3.toFixed(1)}`; + } + return d; +} + +/** + * Single-series cubic-Bezier curve + area fill morph controller (used by `TrendAreaChart` and + * single-series `SessionStepCharts`). + */ +export function createCubicCurveMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { + let morphRafId = 0; + let committedSegs = []; + let liveMorphSegs = null; + let hasRenderedOnce = false; + + function cancel() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; + } + + function reset() { + cancel(); + committedSegs = []; + liveMorphSegs = null; + hasRenderedOnce = false; + } + + function morphTo({ + nextSegs, + leftX, + spanX, + bottomY, + linePath, + areaPath = null, + finalLineD, + finalAreaD = '', + skipMorph = false, + }) { + const prevSegs = liveMorphSegs || committedSegs; + committedSegs = nextSegs; + + if ( + skipMorph || + !hasRenderedOnce || + !canAnimateChartInBrowser() || + prevSegs.length === 0 || + nextSegs.length === 0 + ) { + hasRenderedOnce = true; + cancel(); + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + if (areaPath) patchAttr(areaPath, 'd', finalAreaD); + return; + } + hasRenderedOnce = true; + cancel(); + + const { alignedFrom, alignedTo } = alignCubicChainsForMorph(prevSegs, nextSegs); + const segCount = alignedTo.length; + let maxDelta = 0; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + maxDelta = Math.max( + maxDelta, + Math.abs(b.y0 - a.y0), + Math.abs(b.cy1 - a.cy1), + Math.abs(b.cy2 - a.cy2), + Math.abs(b.y3 - a.y3), + Math.abs(b.u0 - a.u0) * spanX, + Math.abs(b.u3 - a.u3) * spanX + ); + } + + if (maxDelta < 0.25) { + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + if (areaPath) patchAttr(areaPath, 'd', finalAreaD); + return; + } + + const activeLive = alignedFrom.map((s) => ({ ...s })); + liveMorphSegs = activeLive; + const startTs = performance.now(); + + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / durationMs); + if (rawT >= 1) { + morphRafId = 0; + liveMorphSegs = null; + patchAttr(linePath, 'd', finalLineD); + if (areaPath) patchAttr(areaPath, 'd', finalAreaD); + return; + } + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + const cur = activeLive[i]; + cur.u0 = a.u0 + (b.u0 - a.u0) * ease; + cur.y0 = a.y0 + (b.y0 - a.y0) * ease; + cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; + cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; + cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; + cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; + cur.u3 = a.u3 + (b.u3 - a.u3) * ease; + cur.y3 = a.y3 + (b.y3 - a.y3) * ease; + } + const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); + patchAttr(linePath, 'd', morphLineD); + if (areaPath) { + const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); + const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); + patchAttr(areaPath, 'd', `${morphLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); + } + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } + + return { morphTo, cancel, reset }; +} + +/** + * Coalesced multi-series cubic-Bezier curve, area fill, and endpoint dot morph controller + * (used by `AccountQuotaTrendCard` and multi-model `SessionStepCharts`). + */ +export function createMultiSeriesCurveMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { + let morphRafId = 0; + const stateByKey = new Map(); + + function cancel() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; + } + + function reset() { + cancel(); + stateByKey.clear(); + } + + function morphSeries({ + items, + leftX, + spanX, + bottomY, + skipMorph = false, + }) { + cancel(); + const canAnim = !skipMorph && canAnimateChartInBrowser(); + const activeSet = new Set(); + const jobs = []; + + for (let idx = 0; idx < items.length; idx++) { + const it = items[idx]; + activeSet.add(it.key); + const prevEntry = stateByKey.get(it.key); + const prevSegs = prevEntry ? prevEntry.liveSegs || prevEntry.committedSegs : null; + + if (!canAnim || !prevSegs || prevSegs.length === 0 || it.nextSegs.length === 0) { + stateByKey.set(it.key, { + committedSegs: it.nextSegs, + liveSegs: null, + endX: it.endX, + endY: it.endY, + }); + patchAttr(it.lineEl, 'd', it.finalLineD); + if (it.areaEl) patchAttr(it.areaEl, 'd', it.finalAreaD || ''); + if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { + patchAttr(it.endDotEl, 'cx', it.endX.toFixed(1)); + patchAttr(it.endDotEl, 'cy', it.endY.toFixed(1)); + } + continue; + } + + const { alignedFrom, alignedTo } = alignCubicChainsForMorph(prevSegs, it.nextSegs); + const segCount = alignedTo.length; + let maxDelta = 0; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + maxDelta = Math.max( + maxDelta, + Math.abs(b.y0 - a.y0), + Math.abs(b.cy1 - a.cy1), + Math.abs(b.cy2 - a.cy2), + Math.abs(b.y3 - a.y3), + Math.abs(b.u0 - a.u0) * spanX, + Math.abs(b.u3 - a.u3) * spanX + ); + } + + if (maxDelta < 0.25) { + stateByKey.set(it.key, { + committedSegs: it.nextSegs, + liveSegs: null, + endX: it.endX, + endY: it.endY, + }); + patchAttr(it.lineEl, 'd', it.finalLineD); + if (it.areaEl) patchAttr(it.areaEl, 'd', it.finalAreaD || ''); + if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { + patchAttr(it.endDotEl, 'cx', it.endX.toFixed(1)); + patchAttr(it.endDotEl, 'cy', it.endY.toFixed(1)); + } + continue; + } + + const activeLive = alignedFrom.map((s) => ({ ...s })); + const fromEndX = Number.isFinite(prevEntry?.endX) + ? prevEntry.endX + : leftX + alignedFrom[segCount - 1].u3 * spanX; + const fromEndY = Number.isFinite(prevEntry?.endY) + ? prevEntry.endY + : alignedFrom[segCount - 1].y3; + const stateRec = { + committedSegs: it.nextSegs, + liveSegs: activeLive, + endX: fromEndX, + endY: fromEndY, + }; + stateByKey.set(it.key, stateRec); + jobs.push({ + it, + alignedFrom, + alignedTo, + activeLive, + segCount, + fromEndX, + fromEndY, + stateRec, + }); + } + + for (const k of Array.from(stateByKey.keys())) { + if (!activeSet.has(k)) stateByKey.delete(k); + } + + if (jobs.length === 0) return; + + const startTs = performance.now(); + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / durationMs); + if (rawT >= 1) { + morphRafId = 0; + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + jb.stateRec.liveSegs = null; + jb.stateRec.endX = jb.it.endX; + jb.stateRec.endY = jb.it.endY; + patchAttr(jb.it.lineEl, 'd', jb.it.finalLineD); + if (jb.it.areaEl) patchAttr(jb.it.areaEl, 'd', jb.it.finalAreaD || ''); + if (jb.it.endDotEl && Number.isFinite(jb.it.endX) && Number.isFinite(jb.it.endY)) { + patchAttr(jb.it.endDotEl, 'cx', jb.it.endX.toFixed(1)); + patchAttr(jb.it.endDotEl, 'cy', jb.it.endY.toFixed(1)); + } + } + return; + } + + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + const { alignedFrom, alignedTo, activeLive, segCount, it } = jb; + for (let i = 0; i < segCount; i++) { + const a = alignedFrom[i]; + const b = alignedTo[i]; + const cur = activeLive[i]; + cur.u0 = a.u0 + (b.u0 - a.u0) * ease; + cur.y0 = a.y0 + (b.y0 - a.y0) * ease; + cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease; + cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease; + cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease; + cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease; + cur.u3 = a.u3 + (b.u3 - a.u3) * ease; + cur.y3 = a.y3 + (b.y3 - a.y3) * ease; + } + const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX); + patchAttr(it.lineEl, 'd', morphLineD); + if (it.areaEl && it.finalAreaD) { + const firstX = (leftX + activeLive[0].u0 * spanX).toFixed(1); + const lastX = (leftX + activeLive[segCount - 1].u3 * spanX).toFixed(1); + patchAttr(it.areaEl, 'd', `${morphLineD} L ${lastX} ${bottomY} L ${firstX} ${bottomY} Z`); + } + if (it.endDotEl && Number.isFinite(it.endX) && Number.isFinite(it.endY)) { + const cx = jb.fromEndX + (it.endX - jb.fromEndX) * ease; + const cy = jb.fromEndY + (it.endY - jb.fromEndY) * ease; + jb.stateRec.endX = cx; + jb.stateRec.endY = cy; + patchAttr(it.endDotEl, 'cx', cx.toFixed(1)); + patchAttr(it.endDotEl, 'cy', cy.toFixed(1)); + } + } + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } + + return { morphSeries, cancel, reset }; +} + +function buildGridFitPolylineD(grid) { + if (!grid.length) return ''; + let d = `M ${grid[0].x.toFixed(1)} ${grid[0].fitY.toFixed(1)}`; + for (let i = 1; i < grid.length; i++) { + d += ` L ${grid[i].x.toFixed(1)} ${grid[i].fitY.toFixed(1)}`; + } + return d; +} + +function buildGridCiBandD(grid) { + if (grid.length < 2) return ''; + let d = `M ${grid[0].x.toFixed(1)} ${grid[0].highY.toFixed(1)}`; + for (let i = 1; i < grid.length; i++) { + d += ` L ${grid[i].x.toFixed(1)} ${grid[i].highY.toFixed(1)}`; + } + for (let i = grid.length - 1; i >= 0; i--) { + d += ` L ${grid[i].x.toFixed(1)} ${grid[i].lowY.toFixed(1)}`; + } + return `${d} Z`; +} + +/** + * Smoothly morphs LOESS fit polylines, `95% CI` confidence bands, and optional OLS lines + * across metric/model switches in `createModelFitChart`. + */ +export function createFitGridMorphController({ durationMs = CHART_CURVE_MORPH_MS } = {}) { + let morphRafId = 0; + const stateByKey = new Map(); + + function cancel() { + if ( + morphRafId && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(morphRafId); + } + morphRafId = 0; + } + + function reset() { + cancel(); + stateByKey.clear(); + } + + function morphFits({ items, skipMorph = false }) { + cancel(); + const canAnim = !skipMorph && canAnimateChartInBrowser(); + const activeSet = new Set(); + const jobs = []; + + for (let idx = 0; idx < items.length; idx++) { + const it = items[idx]; + activeSet.add(it.key); + const prevEntry = stateByKey.get(it.key); + const prevGrid = prevEntry ? prevEntry.liveGrid || prevEntry.committedGrid : null; + + if ( + !canAnim || + !prevGrid || + prevGrid.length !== it.gridPts.length || + it.gridPts.length < 2 + ) { + stateByKey.set(it.key, { + committedGrid: it.gridPts, + liveGrid: null, + ols: it.olsCoords || null, + }); + patchAttr(it.curveEl, 'd', it.finalCurveD); + if (it.bandEl) patchAttr(it.bandEl, 'd', it.finalBandD || ''); + if (it.olsEl && it.olsCoords) { + patchAttr(it.olsEl, 'x1', it.olsCoords.x1.toFixed(1)); + patchAttr(it.olsEl, 'y1', it.olsCoords.y1.toFixed(1)); + patchAttr(it.olsEl, 'x2', it.olsCoords.x2.toFixed(1)); + patchAttr(it.olsEl, 'y2', it.olsCoords.y2.toFixed(1)); + } + continue; + } + + let maxDelta = 0; + for (let i = 0; i < it.gridPts.length; i++) { + const a = prevGrid[i]; + const b = it.gridPts[i]; + maxDelta = Math.max( + maxDelta, + Math.abs(b.fitY - a.fitY), + Math.abs(b.highY - a.highY), + Math.abs(b.lowY - a.lowY), + Math.abs(b.x - a.x) + ); + } + if (maxDelta < 0.25) { + stateByKey.set(it.key, { + committedGrid: it.gridPts, + liveGrid: null, + ols: it.olsCoords || null, + }); + patchAttr(it.curveEl, 'd', it.finalCurveD); + if (it.bandEl) patchAttr(it.bandEl, 'd', it.finalBandD || ''); + if (it.olsEl && it.olsCoords) { + patchAttr(it.olsEl, 'x1', it.olsCoords.x1.toFixed(1)); + patchAttr(it.olsEl, 'y1', it.olsCoords.y1.toFixed(1)); + patchAttr(it.olsEl, 'x2', it.olsCoords.x2.toFixed(1)); + patchAttr(it.olsEl, 'y2', it.olsCoords.y2.toFixed(1)); + } + continue; + } + + const activeLive = prevGrid.map((g) => ({ ...g })); + const fromOls = prevEntry?.ols || it.olsCoords || null; + const stateRec = { + committedGrid: it.gridPts, + liveGrid: activeLive, + ols: fromOls ? { ...fromOls } : null, + }; + stateByKey.set(it.key, stateRec); + jobs.push({ it, fromGrid: prevGrid, activeLive, fromOls, stateRec }); + } + + for (const k of Array.from(stateByKey.keys())) { + if (!activeSet.has(k)) stateByKey.delete(k); + } + + if (jobs.length === 0) return; + + const startTs = performance.now(); + const step = (nowTs) => { + const elapsed = Math.max(0, nowTs - startTs); + const rawT = Math.min(1, elapsed / durationMs); + if (rawT >= 1) { + morphRafId = 0; + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + jb.stateRec.liveGrid = null; + jb.stateRec.ols = jb.it.olsCoords || null; + patchAttr(jb.it.curveEl, 'd', jb.it.finalCurveD); + if (jb.it.bandEl) patchAttr(jb.it.bandEl, 'd', jb.it.finalBandD || ''); + if (jb.it.olsEl && jb.it.olsCoords) { + patchAttr(jb.it.olsEl, 'x1', jb.it.olsCoords.x1.toFixed(1)); + patchAttr(jb.it.olsEl, 'y1', jb.it.olsCoords.y1.toFixed(1)); + patchAttr(jb.it.olsEl, 'x2', jb.it.olsCoords.x2.toFixed(1)); + patchAttr(jb.it.olsEl, 'y2', jb.it.olsCoords.y2.toFixed(1)); + } + } + return; + } + + const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT); + for (let j = 0; j < jobs.length; j++) { + const jb = jobs[j]; + const { fromGrid, activeLive, it } = jb; + for (let i = 0; i < activeLive.length; i++) { + const a = fromGrid[i]; + const b = it.gridPts[i]; + const cur = activeLive[i]; + cur.x = a.x + (b.x - a.x) * ease; + cur.fitY = a.fitY + (b.fitY - a.fitY) * ease; + cur.highY = a.highY + (b.highY - a.highY) * ease; + cur.lowY = a.lowY + (b.lowY - a.lowY) * ease; + } + patchAttr(it.curveEl, 'd', buildGridFitPolylineD(activeLive)); + if (it.bandEl && it.finalBandD) { + patchAttr(it.bandEl, 'd', buildGridCiBandD(activeLive)); + } + if (it.olsEl && it.olsCoords && jb.fromOls) { + const ox1 = jb.fromOls.x1 + (it.olsCoords.x1 - jb.fromOls.x1) * ease; + const oy1 = jb.fromOls.y1 + (it.olsCoords.y1 - jb.fromOls.y1) * ease; + const ox2 = jb.fromOls.x2 + (it.olsCoords.x2 - jb.fromOls.x2) * ease; + const oy2 = jb.fromOls.y2 + (it.olsCoords.y2 - jb.fromOls.y2) * ease; + jb.stateRec.ols = { x1: ox1, y1: oy1, x2: ox2, y2: oy2 }; + patchAttr(it.olsEl, 'x1', ox1.toFixed(1)); + patchAttr(it.olsEl, 'y1', oy1.toFixed(1)); + patchAttr(it.olsEl, 'x2', ox2.toFixed(1)); + patchAttr(it.olsEl, 'y2', oy2.toFixed(1)); + } + } + morphRafId = window.requestAnimationFrame(step); + }; + + morphRafId = window.requestAnimationFrame(step); + } + + return { morphFits, cancel, reset }; +} + +/** + * Shared 2D pointer-following floating tooltip & focus-dot tracking controller. + * Positions `.trend-tooltip` smoothly around the pointer (`above -> right -> left -> below`), + * clamps inside the nearest scrollable viewport container, and arms `.is-tracking` (`150ms`) + * on both the tooltip and active SVG focus dots after the initial reveal frame. + */ +export function createFloatingChartTooltipController({ + containerEl, + tooltipEl, + defaultTipWidth = 216, + defaultTipHeight = 96, + defaultViewWidth = 460, + defaultViewHeight = 184, + clipSelector = '.view-pane, .cons-view-stage, .models-analytics-pane, .table-viewport', + useFloatingClass = true, +}) { + if (useFloatingClass) { + tooltipEl.classList.add('is-floating-tip'); + } + + let cachedWrapRect = null; + let cachedClipRect = undefined; + let cachedTipW = 0; + let cachedTipH = 0; + let lastSizeKey = null; + let tipTrackRaf = 0; + let activeTrackedDots = []; + + function cancelTrackRaf() { + if ( + tipTrackRaf && + typeof window !== 'undefined' && + typeof window.cancelAnimationFrame === 'function' + ) { + window.cancelAnimationFrame(tipTrackRaf); + } + tipTrackRaf = 0; + } + + function invalidateRects() { + cachedWrapRect = null; + cachedClipRect = undefined; + cachedTipW = 0; + cachedTipH = 0; + lastSizeKey = null; + } + + function getWrapRect() { + if (!cachedWrapRect) { + cachedWrapRect = containerEl.getBoundingClientRect?.() || null; + } + return cachedWrapRect; + } + + function syncTrackedDots(nextDots, isTrackingActive) { + const nextList = Array.isArray(nextDots) ? nextDots.filter(Boolean) : []; + for (let i = 0; i < activeTrackedDots.length; i++) { + const prevDot = activeTrackedDots[i]; + if (!nextList.includes(prevDot)) { + patchClasses(prevDot, { 'is-tracking': false }); + } + } + if (isTrackingActive) { + for (let i = 0; i < nextList.length; i++) { + patchClasses(nextList[i], { 'is-tracking': true }); + } + } + activeTrackedDots = nextList; + } + + function armTracking(wasHidden, nextDots) { + if (!wasHidden) { + syncTrackedDots(nextDots, tooltipEl.classList.contains('is-tracking')); + return; + } + patchClasses(tooltipEl, { 'is-tracking': false }); + const dotList = Array.isArray(nextDots) ? nextDots.filter(Boolean) : []; + for (let i = 0; i < dotList.length; i++) { + patchClasses(dotList[i], { 'is-tracking': false }); + } + activeTrackedDots = dotList; + void tooltipEl.offsetWidth; + cancelTrackRaf(); + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + tipTrackRaf = window.requestAnimationFrame(() => { + tipTrackRaf = 0; + if (!tooltipEl.hasAttribute('hidden')) { + patchClasses(tooltipEl, { 'is-tracking': true }); + for (let i = 0; i < activeTrackedDots.length; i++) { + patchClasses(activeTrackedDots[i], { 'is-tracking': true }); + } + } + }); + } else { + patchClasses(tooltipEl, { 'is-tracking': true }); + for (let i = 0; i < activeTrackedDots.length; i++) { + patchClasses(activeTrackedDots[i], { 'is-tracking': true }); + } + } + } + + function positionNearAnchor({ + fallbackX, + fallbackY, + pointer = null, + viewWidth = defaultViewWidth, + viewHeight = defaultViewHeight, + remeasureTip = false, + }) { + const wrapRect = getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(containerEl.clientWidth || viewWidth || defaultViewWidth); + const wrapH = + wrapRect && wrapRect.height > 0 + ? wrapRect.height + : Number(containerEl.offsetHeight || viewHeight || defaultViewHeight); + + if (remeasureTip || !(cachedTipW > 0) || !(cachedTipH > 0)) { + cachedTipW = Number(tooltipEl.offsetWidth || 0) || defaultTipWidth; + cachedTipH = Number(tooltipEl.offsetHeight || 0) || defaultTipHeight; + } + const tipW = cachedTipW; + const tipH = cachedTipH; + + const hasPointer = + pointer && + Number.isFinite(Number(pointer.clientX)) && + Number.isFinite(Number(pointer.clientY)) && + wrapRect && + wrapRect.width > 0 && + wrapRect.height > 0; + + const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX; + const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY; + + if (cachedClipRect === undefined) { + const clipEl = containerEl.closest?.(clipSelector) || null; + cachedClipRect = clipEl?.getBoundingClientRect?.() || null; + } + const clipRect = cachedClipRect; + const hasClip = Boolean( + clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0 + ); + const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16; + const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16; + + const maxLeft = Math.max(4, wrapW - tipW - 4); + let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2)); + const aboveY = anchorY - tipH - 14; + let topPx; + + if (aboveY >= minY) { + topPx = Math.min(maxY, aboveY); + } else if (anchorX + 16 + tipW <= wrapW - 4) { + leftPx = anchorX + 16; + topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); + } else if (anchorX - 16 - tipW >= 4) { + leftPx = anchorX - 16 - tipW; + topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2)); + } else { + topPx = Math.max(minY, Math.min(maxY, anchorY + 18)); + } + + patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`); + patchStyleVar(tooltipEl, '--tip-shift', '0px'); + patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`); + } + + function show({ + fallbackX, + fallbackY, + pointer = null, + trackedDots = [], + viewWidth = defaultViewWidth, + viewHeight = defaultViewHeight, + sizeKey = '', + }) { + const wasHidden = tooltipEl.hasAttribute('hidden'); + if (wasHidden) { + patchAttr(tooltipEl, 'hidden', false); + } + const normalizedKey = String(sizeKey || ''); + const shouldRemeasure = wasHidden || normalizedKey !== lastSizeKey; + lastSizeKey = normalizedKey; + positionNearAnchor({ + fallbackX, + fallbackY, + pointer, + viewWidth, + viewHeight, + remeasureTip: shouldRemeasure, + }); + armTracking(wasHidden, trackedDots); + } + + function hide() { + invalidateRects(); + cancelTrackRaf(); + patchAttr(tooltipEl, 'hidden', true); + patchClasses(tooltipEl, { + 'is-hm-bottom': false, + 'is-hm-top': false, + 'is-line-low': false, + 'is-tracking': false, + }); + for (let i = 0; i < activeTrackedDots.length; i++) { + patchClasses(activeTrackedDots[i], { 'is-tracking': false }); + } + activeTrackedDots = []; + } + + function destroy() { + cancelTrackRaf(); + invalidateRects(); + activeTrackedDots = []; + } + + return { + show, + hide, + getWrapRect, + invalidateRects, + destroy, + }; +} diff --git a/sidecars/panel/src/components/charts/stepChartMath.js b/sidecars/panel/src/components/charts/stepChartMath.js new file mode 100644 index 0000000..c2afd2f --- /dev/null +++ b/sidecars/panel/src/components/charts/stepChartMath.js @@ -0,0 +1,665 @@ +/** + * @fileoverview Pure regression math (OLS + IRLS-LOESS), nice axis tick generators, + * SVG spline/polyline path builders, and step metric formatters extracted from SessionStepCharts.js. + */ + +import { + formatAgentBadgeText, + formatMetric, + formatPctNumber, + formatSpeedMetric, + formatTokens, + formatTokensPrecise, + formatUsd, +} from '../../core/formatters.js'; +import { t } from '../../i18n/index.js'; + +/** 多模型节点和多曲线对比语义调色板(全部取自 tokens.css 语义变量,兼顾设计一致性和交叉曲线区分度) */ +export const MODEL_COLOR_VARS = Object.freeze([ + 'var(--ctx-cached)', + 'var(--ctx-skills)', + 'var(--ctx-user-input)', + 'var(--ctx-checkpoint)', + 'var(--ctx-tool-results)', + 'var(--ctx-subagent-msg)', +]); + +/** + * 提取步骤所属的基础模型分组键(和后端 `usage-aggregator.mjs` 中 `modelBreakdown[].label` 严格一致), + * 且不受“精简代号 / 原始模型 ID”或“自动压缩”后缀切换影响。 + * + * @param {object|null|undefined} step + * @returns {string} + */ +export function getStepModelGroupKey(step) { + if (!step || typeof step !== 'object') return t('fmt.unknownModel'); + const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '') + .replace(/\s*\[自动压缩\]\s*$/u, '') + .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') + .trim(); + if (rawLabel) return rawLabel; + const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '') + .replace(/·(?:压缩|Compact)\s*$/iu, '') + .trim(); + return rawShort || t('fmt.unknownModel'); +} + +/** + * 将逆序或混合代理的步骤列表归一化为严格时间升序序列(最旧 -> 最新)。 + * + * @param {Array} steps + * @param {boolean} isMergedAllAgents + * @returns {Array} + */ +export function toChronologicalSteps(steps, isMergedAllAgents = false) { + if (!Array.isArray(steps) || steps.length === 0) return []; + const copy = steps.slice(); + if (isMergedAllAgents) { + copy.sort( + (a, b) => + (Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) || + (Number(a?.agentIndex) || 0) - (Number(b?.agentIndex) || 0) || + (Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) + ); + return copy; + } + copy.sort( + (a, b) => + (Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) || + (Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) + ); + return copy; +} + +export function clampValue(v, minVal = 0, maxVal = Infinity) { + if (!Number.isFinite(v)) return minVal; + return Math.max(minVal, Math.min(maxVal, v)); +} + +/** + * 双侧 95% 置信区间对应的 Student-t 临界值近似表(t_{0.975, df})。 + * + * @param {number} df 残差自由度 + * @returns {number} + */ +function tCritical95(df) { + if (!Number.isFinite(df) || df <= 1.5) return 3.182; + if (df <= 2.5) return 3.182 + (2.5 - df) * 0.9; + if (df <= 3.5) return 2.776 + (3.5 - df) * 0.406; + if (df <= 4.5) return 2.571 + (4.5 - df) * 0.205; + if (df <= 6) return 2.447; + if (df <= 8) return 2.306; + if (df <= 10) return 2.228; + if (df <= 15) return 2.131; + if (df <= 20) return 2.086; + if (df <= 30) return 2.042; + if (df <= 60) return 2.0; + if (df <= 120) return 1.98; + return 1.96; +} + +/** + * 计算普通最小二乘线性回归(OLS: y = intercept + slope * x)。 + * + * @param {number[]} ys 样本纵坐标序列 + * @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [options] + * @returns {{ values: number[], slope: number, intercept: number, mean: number, r: number, r2: number }} + */ +export function computeLinearFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) { + const n = Array.isArray(ys) ? ys.length : 0; + if (n === 0) { + return { values: [], slope: 0, intercept: 0, mean: 0, r: 0, r2: 0 }; + } + const xArr = + Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx); + const meanY = ys.reduce((acc, v) => acc + v, 0) / n; + if (n === 1) { + const c = clampValue(ys[0], minVal, maxVal); + return { values: [c], slope: 0, intercept: c, mean: c, r: 0, r2: 0 }; + } + const meanX = xArr.reduce((acc, v) => acc + v, 0) / n; + let sxx = 0; + let sxy = 0; + let syy = 0; + for (let i = 0; i < n; i++) { + const dx = xArr[i] - meanX; + const dy = ys[i] - meanY; + sxx += dx * dx; + sxy += dx * dy; + syy += dy * dy; + } + const slope = sxx > 1e-12 ? sxy / sxx : 0; + const intercept = meanY - slope * meanX; + const r = + sxx > 1e-12 && syy > 1e-12 ? clampValue(sxy / Math.sqrt(sxx * syy), -1, 1) : 0; + const values = xArr.map((x) => clampValue(intercept + slope * x, minVal, maxVal)); + return { values, slope, intercept, mean: meanY, r, r2: r * r }; +} + +/** + * 学术论文级回归和 95% 置信带计算引擎(Cleveland & Devlin 高斯局部加权线性回归 LOESS + 精确帽子矩阵标准误, + * 小样本 n <= 5 时自动采用精确 OLS 线性回归和双曲 t 分布 95% 置信区间,等同于 R `ggplot2::geom_smooth(se = TRUE)`)。 + * + * @param {number[]} xs 严格递增或单调的样本横坐标序列 + * @param {number[]} ys 样本纵坐标序列 + * @param {{ minVal?: number, maxVal?: number, gridSize?: number, span?: number }} [options] + */ +export function computePublicationFit( + xs, + ys, + { minVal = 0, maxVal = Infinity, gridSize = 64, span = 0.5 } = {} +) { + const n = Math.min(Array.isArray(xs) ? xs.length : 0, Array.isArray(ys) ? ys.length : 0); + if (n === 0) { + return { + method: 'OLS', + mean: 0, + sd: 0, + slope: 0, + intercept: 0, + r: 0, + r2: 0, + sampleFits: [], + sampleCiLow: [], + sampleCiHigh: [], + sampleCiHalf: [], + grid: [], + }; + } + + const ols = computeLinearFit(ys, { minVal, maxVal, xs }); + let syy = 0; + for (let i = 0; i < n; i++) { + const dy = ys[i] - ols.mean; + syy += dy * dy; + } + const sd = n > 1 ? Math.sqrt(syy / (n - 1)) : 0; + + if (n === 1) { + const val = clampValue(ys[0], minVal, maxVal); + return { + method: 'OLS', + mean: val, + sd: 0, + slope: 0, + intercept: val, + r: 0, + r2: 0, + sampleFits: [val], + sampleCiLow: [val], + sampleCiHigh: [val], + sampleCiHalf: [0], + grid: [{ x: xs[0], fit: val, ciLow: val, ciHigh: val }], + }; + } + + const xMin = xs[0]; + const xMax = xs[n - 1]; + const xSpan = Math.max(1e-9, xMax - xMin); + const M = Math.max(2, gridSize); + const gridXs = Array.from({ length: M }, (_, k) => xMin + (k / (M - 1)) * xSpan); + + // 小样本(n <= 5):采用精确 OLS 线性回归和 Student-t 双曲 95% CI 置信带 + if (n <= 5) { + const meanX = xs.reduce((a, b) => a + b, 0) / n; + let sxx = 0; + let sse = 0; + for (let i = 0; i < n; i++) { + const dx = xs[i] - meanX; + sxx += dx * dx; + const resid = ys[i] - (ols.intercept + ols.slope * xs[i]); + sse += resid * resid; + } + const df = n - 2; + const seResid = df >= 1 ? Math.sqrt(sse / df) : 0; + const tCrit = df >= 1 ? tCritical95(df) : 0; + + const evalOlsAt = (x0) => { + const rawFit = ols.intercept + ols.slope * x0; + const sePred = + seResid > 0 + ? seResid * Math.sqrt(1 / n + (sxx > 1e-12 ? ((x0 - meanX) * (x0 - meanX)) / sxx : 0)) + : 0; + const half = tCrit * sePred; + return { + fit: clampValue(rawFit, minVal, maxVal), + ciLow: clampValue(rawFit - half, minVal, maxVal), + ciHigh: clampValue(rawFit + half, minVal, maxVal), + half, + }; + }; + + const sampleEval = xs.map(evalOlsAt); + const grid = gridXs.map((gx) => { + const g = evalOlsAt(gx); + return { x: gx, fit: g.fit, ciLow: g.ciLow, ciHigh: g.ciHigh }; + }); + + return { + method: 'OLS', + mean: ols.mean, + sd, + slope: ols.slope, + intercept: ols.intercept, + r: ols.r, + r2: ols.r2, + sampleFits: sampleEval.map((e) => e.fit), + sampleCiLow: sampleEval.map((e) => e.ciLow), + sampleCiHigh: sampleEval.map((e) => e.ciHigh), + sampleCiHalf: sampleEval.map((e) => e.half), + grid, + }; + } + + // n >= 6:Cleveland 高斯局部加权一阶线性回归(LOESS)+ 精确帽子矩阵杠杆度 95% CI 置信带 + const q = Math.max(5, Math.min(n, Math.ceil(span * n))); + const wBuf = new Float64Array(n); + const sortedXs = q <= n && xs.slice(0, n).every( + (x, i) => Number.isFinite(x) && (i === 0 || xs[i - 1] <= x) + ); + + function loessBandwidth(x0) { + // 有序 x 上的 q 个最近样本可取连续区间;二分比较两端,避免每个拟合点都排序。 + let left = 0; + let right = n - q; + while (left < right) { + const mid = (left + right) >>> 1; + if (x0 - xs[mid] > xs[mid + q] - x0) { + left = mid + 1; + } else { + right = mid; + } + } + return Math.max(Math.abs(xs[left] - x0), Math.abs(xs[left + q - 1] - x0)); + } + + function evalLoessPoint(x0, diagIdx = -1) { + let h; + if (sortedXs) { + h = loessBandwidth(x0); + if (h <= 1e-9) { + h = Math.max(Math.abs(xs[0] - x0), Math.abs(xs[n - 1] - x0), xSpan * 0.05, 1e-6); + } + } else { + const sortedDists = Array.from({ length: n }, (_, j) => Math.abs(xs[j] - x0)).sort((a, b) => a - b); + h = sortedDists[q - 1]; + if (h <= 1e-9) { + h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6); + } + } + const maxDist = h * 1.0001; + let start = 0; + let end = n; + if (sortedXs) { + // 三次权重的支持区间之外权重为零,保留区间内样本原来的累加顺序。 + let right = n; + while (start < right) { + const mid = (start + right) >>> 1; + if (x0 - xs[mid] >= maxDist) start = mid + 1; + else right = mid; + } + let left = start; + while (left < end) { + const mid = (left + end) >>> 1; + if (xs[mid] - x0 < maxDist) left = mid + 1; + else end = mid; + } + } + + let sw = 0; + let swx = 0; + for (let j = start; j < end; j++) { + const u = Math.abs(xs[j] - x0) / maxDist; + const base = 1 - u * u * u; + const w = u >= 1 ? 0 : base * base * base; + wBuf[j] = w; + sw += w; + swx += w * xs[j]; + } + + if (sw <= 1e-12) { + const fallbackVal = ols.intercept + ols.slope * x0; + return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n }; + } + + const mx = swx / sw; + let sxxW = 0; + for (let j = start; j < end; j++) { + const w = wBuf[j]; + if (w <= 0) continue; + const dx = xs[j] - mx; + sxxW += w * dx * dx; + } + + const dx0 = x0 - mx; + const useSlope = sxxW > 1e-12; + const inverseWeightSum = 1 / sw; + const slopeScale = useSlope ? dx0 / sxxW : 0; + const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0); + let rawFit = 0; + let leverageNormSq = 0; + let diagHat = 0; + + for (let j = start; j < end; j++) { + const w = wBuf[j]; + if (w <= 0) continue; + const lj = w * inverseWeightSum + (useSlope ? w * (xs[j] - mx) * slopeScale : 0); + rawFit += lj * ys[j]; + leverageNormSq += lj * lj; + if (j === diagIdx) diagHat = lj; + } + + return { rawFit, leverageNormSq, diagHat, localHatDiag }; + } + + const rawSampleFits = new Float64Array(n); + const sampleLevSq = new Float64Array(n); + let sse = 0; + let traceL = 0; + let precomputedGridEval = null; + + // 大样本(n > 200 且 x 单调有序)采用和 R `stats::loess(surface = "interpolate")` 一致的网格插值加速: + // 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值和杠杆度,避免 O(N²) 阻塞主线程。 + if (n > 200 && sortedXs && M >= 2) { + const gridRawFit = new Float64Array(M); + const gridLevSq = new Float64Array(M); + const gridHatDiag = new Float64Array(M); + for (let k = 0; k < M; k++) { + const res = evalLoessPoint(gridXs[k], -1); + gridRawFit[k] = res.rawFit; + gridLevSq[k] = res.leverageNormSq; + gridHatDiag[k] = res.localHatDiag; + } + precomputedGridEval = { gridRawFit, gridLevSq }; + + const invSpan = (M - 1) / xSpan; + const maxK0 = M - 2; + for (let i = 0; i < n; i++) { + const u = (xs[i] - xMin) * invSpan; + const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u); + const frac = Math.max(0, Math.min(1, u - k0)); + const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]); + const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0])); + const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]); + rawSampleFits[i] = rf; + sampleLevSq[i] = ls; + traceL += hd; + const diff = ys[i] - rf; + sse += diff * diff; + } + } else { + for (let i = 0; i < n; i++) { + const res = evalLoessPoint(xs[i], i); + rawSampleFits[i] = res.rawFit; + sampleLevSq[i] = res.leverageNormSq; + traceL += res.diagHat; + const diff = ys[i] - res.rawFit; + sse += diff * diff; + } + } + + const dfRes = Math.max(1, n - traceL); + const sigmaHat = Math.sqrt(sse / dfRes); + const tCrit = tCritical95(dfRes); + + const sampleFits = new Array(n); + const sampleCiLow = new Array(n); + const sampleCiHigh = new Array(n); + const sampleCiHalf = new Array(n); + let clampedSse = 0; + + for (let i = 0; i < n; i++) { + const fitVal = clampValue(rawSampleFits[i], minVal, maxVal); + const half = tCrit * sigmaHat * Math.sqrt(sampleLevSq[i]); + sampleFits[i] = fitVal; + sampleCiLow[i] = clampValue(rawSampleFits[i] - half, minVal, maxVal); + sampleCiHigh[i] = clampValue(rawSampleFits[i] + half, minVal, maxVal); + sampleCiHalf[i] = half; + const d = ys[i] - fitVal; + clampedSse += d * d; + } + + const grid = precomputedGridEval + ? gridXs.map((gx, k) => { + const rf = precomputedGridEval.gridRawFit[k]; + const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k])); + return { + x: gx, + fit: clampValue(rf, minVal, maxVal), + ciLow: clampValue(rf - half, minVal, maxVal), + ciHigh: clampValue(rf + half, minVal, maxVal), + }; + }) + : gridXs.map((gx) => { + const res = evalLoessPoint(gx, -1); + const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq); + return { + x: gx, + fit: clampValue(res.rawFit, minVal, maxVal), + ciLow: clampValue(res.rawFit - half, minVal, maxVal), + ciHigh: clampValue(res.rawFit + half, minVal, maxVal), + }; + }); + + const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1; + + return { + method: 'LOESS', + mean: ols.mean, + sd, + slope: ols.slope, + intercept: ols.intercept, + r: ols.r, + r2: r2Loess, + sampleFits, + sampleCiLow, + sampleCiHigh, + sampleCiHalf, + grid, + }; +} + +/** + * Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。 + */ +export function niceStepNumber(range, round) { + if (!Number.isFinite(range) || range <= 0) return 1; + const exponent = Math.floor(Math.log10(range)); + const fraction = range / 10 ** exponent; + let niceFraction; + if (round) { + if (fraction < 1.5) niceFraction = 1; + else if (fraction < 3) niceFraction = 2; + else if (fraction < 7) niceFraction = 5; + else niceFraction = 10; + } else if (fraction <= 1) niceFraction = 1; + else if (fraction <= 2) niceFraction = 2; + else if (fraction <= 5) niceFraction = 5; + else niceFraction = 10; + return niceFraction * 10 ** exponent; +} + +export function computeNiceYScale(dataMin, dataMax, { minBound = 0, maxBound = Infinity, tickCount = 4 } = {}) { + let lo = Number.isFinite(dataMin) ? dataMin : 0; + let hi = Number.isFinite(dataMax) ? dataMax : 1; + if (minBound === 0 && lo >= 0 && hi > 0 && lo <= hi * 0.32) { + lo = 0; + } + if (hi - lo <= 1e-9) { + const pad = lo > 0 ? lo * 0.15 : 1; + lo = Math.max(minBound, lo - pad); + hi = Math.min(maxBound, hi + pad); + if (hi - lo <= 1e-9) { + lo = Math.max(minBound, hi - 1); + } + } else { + const pad = (hi - lo) * 0.05; + lo = Math.max(minBound, lo - (lo === 0 ? 0 : pad)); + hi = Math.min(maxBound, hi + pad); + } + + const rawRange = niceStepNumber(hi - lo, false); + const step = niceStepNumber(rawRange / Math.max(2, tickCount - 1), true); + let graphMin = Math.max(minBound, Math.floor(lo / step) * step); + let graphMax = Math.min(maxBound, Math.ceil(hi / step) * step); + if (graphMax - graphMin <= 1e-9) { + graphMax = graphMin + step; + } + + const ticks = []; + for (let v = graphMin; v <= graphMax + step * 0.25; v += step) { + const clamped = clampValue(+v.toPrecision(10), minBound, maxBound); + if (ticks.length === 0 || Math.abs(clamped - ticks[ticks.length - 1]) > step * 1e-4) { + ticks.push(clamped); + } + if (ticks.length >= 8) break; + } + return { + min: ticks[0] ?? graphMin, + max: ticks[ticks.length - 1] ?? graphMax, + step, + ticks, + }; +} + +export function computeNiceXStepTicks(xs) { + const n = xs.length; + if (n === 0) return []; + if (n <= 5) { + return Array.from(new Set(xs.map((x) => Math.round(x)))); + } + const xMin = xs[0]; + const xMax = xs[n - 1]; + const span = xMax - xMin; + if (span <= 5) { + return Array.from(new Set(xs.map((x) => Math.round(x)))); + } + const step = Math.max(1, Math.round(niceStepNumber(span / 4.5, true))); + const firstTick = Math.ceil(xMin / step) * step; + const ticks = []; + if (firstTick - xMin > step * 0.45) { + ticks.push(Math.round(xMin)); + } + for (let v = firstTick; v <= xMax + 1e-6; v += step) { + ticks.push(Math.round(v)); + if (ticks.length >= 7) break; + } + if (ticks.length === 0) { + return [Math.round(xMin), Math.round(xMax)]; + } + return ticks; +} + +export function formatYAxisTick(metric, val, step) { + if (!Number.isFinite(val)) return ''; + if (Math.abs(val) < 1e-9) { + return metric === 'cost' ? '$0' : metric === 'cache' ? '0%' : metric === 'ttft' ? '0s' : '0'; + } + if (metric === 'tps') { + return step >= 1 ? `${Math.round(val)}` : val.toFixed(1); + } + if (metric === 'ttft') { + return step >= 1 ? `${Math.round(val)}s` : `${val.toFixed(1)}s`; + } + if (metric === 'cache') { + return step >= 1 ? `${Math.round(val)}%` : formatPctNumber(val, { withSymbol: true }); + } + if (metric === 'cost') { + if (step >= 1) return `$${Math.round(val)}`; + if (step >= 0.1) return `$${val.toFixed(1)}`; + if (step >= 0.01) return `$${val.toFixed(2)}`; + return `$${val.toFixed(3)}`; + } + return String(val); +} + +export function buildPolylinePath(points) { + if (!points.length) return ''; + let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; + for (let i = 1; i < points.length; i++) { + d += ` L ${points[i].x.toFixed(1)} ${points[i].y.toFixed(1)}`; + } + return d; +} + +export function buildSplinePath(points) { + if (!points.length) return ''; + if (points.length === 1) { + return `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; + } + let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; + for (let i = 0; i < points.length - 1; i++) { + const p0 = points[i]; + const p1 = points[i + 1]; + const cpx1 = p0.x + (p1.x - p0.x) * 0.38; + const cpx2 = p1.x - (p1.x - p0.x) * 0.38; + d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; + } + return d; +} + +export function computeStepTickIndices(count) { + if (count <= 0) return []; + if (count <= 6) return Array.from({ length: count }, (_, i) => i); + const maxTicks = 6; + const set = new Set(); + for (let k = 0; k < maxTicks; k++) { + set.add(Math.round((k / (maxTicks - 1)) * (count - 1))); + } + return Array.from(set).sort((a, b) => a - b); +} + +export function formatStepAxisTag(st, showAgentPrefix) { + const num = `#${Number(st?.stepIndex ?? 0)}`; + if (!showAgentPrefix) return num; + const badge = formatAgentBadgeText({ + agentKind: + st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), + isMain: !st?.isSubagent, + isSideQuestion: Boolean(st?.isSideQuestion), + sideIndex: st?.sideIndex || 0, + index: st?.agentIndex || 0, + badgeText: st?.agentBadge, + }); + return `${badge}${num}`; +} + +export function formatChartMetricValue(metric, val) { + if (!Number.isFinite(val)) return '—'; + switch (metric) { + case 'totalTokens': + case 'context': + return `${formatTokensPrecise(val)} tok`; + case 'tps': + return formatSpeedMetric(val, ' tok/s'); + case 'ttft': + return formatMetric(val, 's'); + case 'cache': + return formatPctNumber(val, { withSymbol: true }); + case 'cost': + return formatUsd(val, { precise: true }); + default: + return String(val); + } +} + +export function formatChartMetricCompact(metric, val) { + if (!Number.isFinite(val)) return '—'; + switch (metric) { + case 'totalTokens': + case 'context': + return formatTokens(val); + case 'tps': + return formatSpeedMetric(val, ' tok/s'); + case 'ttft': + return formatMetric(val, 's'); + case 'cache': + return formatPctNumber(val, { withSymbol: true }); + case 'cost': + return formatUsd(val, { precise: true }); + default: + return String(val); + } +} diff --git a/sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js b/sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js index bd07d2b..82cdeb2 100644 --- a/sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js +++ b/sidecars/panel/src/components/widgets/AccountQuotaTrendCard.js @@ -20,6 +20,11 @@ import { getEffectiveLocale, t } from '../../i18n/index.js'; import { CustomDateTimePicker } from '../ui/CustomDateTimePicker.js'; import { CustomSelect } from '../ui/CustomSelect.js'; import { SegmentedControl } from '../ui/SegmentedControl.js'; +import { + createFloatingChartTooltipController, + createMultiSeriesCurveMorphController, + pointsToNormalizedCubicSegs, +} from '../charts/chartMotion.js'; const POOL_COLORS = Object.freeze({ Gemini: 'var(--accent-primary)', @@ -83,6 +88,44 @@ function buildHorizontalTangentSpline(pts) { return d; } +const HOVER_SLOT_COUNT = 96; +const MAX_SVG_COLUMN_BUCKETS = 96; + +/** + * Downsamples dense sub-pixel SVG points (e.g. 12s poll bursts) into `<= maxCols` + * min/max-preserving visual knots so curve rasterization and morphing stay crisp and fast, + * while `rawPoints` remain intact for exact timestamp interpolation. + */ +function simplifySvgPointsForRender(svgPts, leftX, plotW, maxCols = MAX_SVG_COLUMN_BUCKETS) { + if (svgPts.length <= maxCols) return svgPts; + const colW = Math.max(1, plotW) / maxCols; + const out = [svgPts[0]]; + let idx = 1; + const endIdx = svgPts.length - 1; + while (idx < endIdx) { + const col = Math.floor((svgPts[idx].x - leftX) / colW); + let minPt = svgPts[idx]; + let maxPt = svgPts[idx]; + let j = idx + 1; + while (j < endIdx && Math.floor((svgPts[j].x - leftX) / colW) === col) { + const cand = svgPts[j]; + if (cand.y < minPt.y) minPt = cand; + if (cand.y > maxPt.y) maxPt = cand; + j += 1; + } + if (minPt === maxPt) { + out.push(minPt); + } else if (minPt.x <= maxPt.x) { + out.push(minPt, maxPt); + } else { + out.push(maxPt, minPt); + } + idx = j; + } + out.push(svgPts[endIdx]); + return out; +} + /** * Computes tight, integer-aligned `[yMin, yMid, yMax]` bounds (`0..100%`) around * observed `[dataMin, dataMax]` so small-to-moderate quota changes use the full @@ -452,6 +495,7 @@ export const AccountQuotaTrendCard = defineComponent({ options: [], onUpdateModelValue: (val) => { selectedAccountEmail = String(val || '').trim().toLowerCase(); + hideHover(); renderChart(); }, }); @@ -463,6 +507,7 @@ export const AccountQuotaTrendCard = defineComponent({ options: [{ value: 'all', label: t('cons.cyclePoolAll') }], onUpdateModelValue: (val) => { selectedPool = val || 'all'; + hideHover(); renderChart(); }, }); @@ -474,6 +519,7 @@ export const AccountQuotaTrendCard = defineComponent({ onUpdateModelValue: (val) => { selectedWin = val === 'weekly' ? 'weekly' : '5h'; winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() }); + hideHover(); renderChart(); }, }); @@ -489,6 +535,7 @@ export const AccountQuotaTrendCard = defineComponent({ endPicker.setValue(draftEndMs); } rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() }); + hideHover(); renderChart(); }, }); @@ -635,17 +682,42 @@ export const AccountQuotaTrendCard = defineComponent({ 'div', { className: 'trend-plot-stage', - onPointermove: handlePointerMove, - onPointerleave: hideHover, + onMousemove: handlePointerMove, + onMouseleave: hideHover, }, - [svg, tooltipEl] + [svg] ); const chartWrap = h('div', { className: 'trend-chart-wrap' }, [ plotStage, xAxisEl, legendRowEl, + tooltipEl, ]); + const tooltipCtrl = createFloatingChartTooltipController({ + containerEl: chartWrap, + tooltipEl, + defaultTipWidth: 204, + defaultTipHeight: 78, + defaultViewWidth: 460, + defaultViewHeight: VIEW_H, + }); + const seriesMorphCtrl = createMultiSeriesCurveMorphController(); + const seriesNodePoolByKey = new Map(); + const hoverDotPoolByKey = new Map(); + let xTickElements = []; + let hoveredSlotIdx = -1; + let lastActiveDots = []; + let lastFallbackX = 0; + let lastFallbackY = 0; + let lastSizeKey = ''; + let lastTipTimeStr = ''; + let lastTipWinStr = ''; + let lastHoveredTickIdx = -1; + let lastPointer = null; + let cachedSvgRect = null; + let lastPlotSig = ''; + const rootEl = h('section', { className: 'panel account-quota-trend-panel' }, [ h('div', { className: 'panel-header account-trend-toprow' }, [ h('span', { className: 'panel-title cons-overview-title' }, [ @@ -670,10 +742,29 @@ export const AccountQuotaTrendCard = defineComponent({ return BOTTOM_Y - ((clamped - plottedYScale.yMin) / plottedYScale.span) * SPAN_Y; } + function syncHoveredTickClass(activeTickIdx) { + if (activeTickIdx === lastHoveredTickIdx) return; + lastHoveredTickIdx = activeTickIdx; + for (let i = 0; i < xTickElements.length; i++) { + patchClasses(xTickElements[i], { 'is-hovered': i === activeTickIdx }); + } + } + function hideHover() { + cachedSvgRect = null; + hoveredSlotIdx = -1; + lastActiveDots = []; + lastTipTimeStr = ''; + lastTipWinStr = ''; + lastPointer = null; + tooltipCtrl.hide(); hoverLine.setAttribute('hidden', ''); hoverDotsGroup.setAttribute('hidden', ''); - patchAttr(tooltipEl, 'hidden', true); + for (const dot of hoverDotPoolByKey.values()) { + dot.setAttribute('hidden', ''); + patchClasses(dot, { 'is-tracking': false }); + } + syncHoveredTickClass(-1); } function sampleSeriesValueAt(points, targetMs) { @@ -697,75 +788,159 @@ export const AccountQuotaTrendCard = defineComponent({ return a.val + (b.val - a.val) * ((targetMs - a.ts) / span); } + function showHoverAtSlot(slotIdx, pointer = null, { forceRefresh = false } = {}) { + if (!plottedSeries.length || !(plottedEndMs > plottedStartMs) || slotIdx < 0) { + hideHover(); + return; + } + const clampedSlot = Math.max(0, Math.min(HOVER_SLOT_COUNT, slotIdx)); + const wasHidden = tooltipEl.hasAttribute('hidden'); + const changedSlot = forceRefresh || wasHidden || clampedSlot !== hoveredSlotIdx; + hoveredSlotIdx = clampedSlot; + if (pointer) lastPointer = pointer; + + if (changedSlot) { + const u = clampedSlot / HOVER_SLOT_COUNT; + const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); + const clampedX = LEFT_X + u * plotW; + const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs)); + + hoverLine.setAttribute('x1', clampedX.toFixed(1)); + hoverLine.setAttribute('x2', clampedX.toFixed(1)); + + const tipItems = []; + const activeDots = []; + let sumY = 0; + const usedKeys = new Set(); + + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + const val = sampleSeriesValueAt(s.rawPoints, targetMs); + if (val === null) continue; + usedKeys.add(s.poolKey); + const y = valueToSvgY(val); + sumY += y; + + let dot = hoverDotPoolByKey.get(s.poolKey); + if (!dot) { + dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('class', 'trend-hover-dot'); + dot.setAttribute('r', '3.2'); + dot.style.fill = 'var(--surface-panel)'; + hoverDotPoolByKey.set(s.poolKey, dot); + hoverDotsGroup.appendChild(dot); + } + if (dot._lastColor !== s.color) { + dot._lastColor = s.color; + dot.style.stroke = s.color; + } + dot.setAttribute('cx', clampedX.toFixed(1)); + dot.setAttribute('cy', y.toFixed(1)); + if (dot.hasAttribute('hidden')) dot.removeAttribute('hidden'); + activeDots.push(dot); + tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val }); + } + + for (const [k, dot] of hoverDotPoolByKey.entries()) { + if (!usedKeys.has(k) && !dot.hasAttribute('hidden')) { + dot.setAttribute('hidden', ''); + patchClasses(dot, { 'is-tracking': false }); + } + } + + if (tipItems.length === 0) { + hideHover(); + return; + } + if (hoverLine.hasAttribute('hidden')) hoverLine.removeAttribute('hidden'); + if (hoverDotsGroup.hasAttribute('hidden')) hoverDotsGroup.removeAttribute('hidden'); + + if (xTickElements.length > 1) { + syncHoveredTickClass(Math.round(u * (xTickElements.length - 1))); + } + + const nextTimeStr = formatHoverTimestamp(targetMs); + if (nextTimeStr !== lastTipTimeStr) { + lastTipTimeStr = nextTimeStr; + patchText(tipTimeEl, nextTimeStr); + } + const nextWinStr = t( + selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h' + ); + if (nextWinStr !== lastTipWinStr) { + lastTipWinStr = nextWinStr; + patchText(tipWinEl, nextWinStr); + } + + patchKeyedList(tipRowsHost, tipItems, { + keyFn: (it) => it.key, + sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`, + createRow: () => { + const sw = h('span', { className: 'dot-swatch' }); + const nm = h('span', { className: 'account-trend-tip-name' }); + const vl = h('strong', { className: 'text-mono' }); + const row = h('div', { className: 'account-trend-tip-row' }, [ + h('span', { className: 'legend-left' }, [sw, nm]), + vl, + ]); + return { el: row, refs: { sw, nm, vl } }; + }, + updateRow: (r, it) => { + if (r.sw._lastBg !== it.color) { + r.sw._lastBg = it.color; + r.sw.style.background = it.color; + } + patchText(r.nm, it.label); + patchText(r.vl, `${+it.val.toFixed(1)}%`); + }, + }); + + const wrapRect = tooltipCtrl.getWrapRect(); + const wrapW = + wrapRect && wrapRect.width > 0 + ? wrapRect.width + : Number(chartWrap.clientWidth || viewW || 460); + lastFallbackX = (clampedX / Math.max(1, viewW)) * wrapW; + lastFallbackY = sumY / activeDots.length + 6; + lastActiveDots = activeDots; + lastSizeKey = `rows:${tipItems.length}`; + } + + tooltipCtrl.show({ + fallbackX: lastFallbackX, + fallbackY: lastFallbackY, + pointer: pointer || lastPointer, + trackedDots: lastActiveDots, + viewWidth: viewW, + viewHeight: VIEW_H, + sizeKey: lastSizeKey, + }); + } + function handlePointerMove(ev) { if (!plottedSeries.length || !(plottedEndMs > plottedStartMs)) { hideHover(); return; } - const rect = svg.getBoundingClientRect?.(); + if (!cachedSvgRect) { + cachedSvgRect = svg.getBoundingClientRect?.() || null; + } + const rect = cachedSvgRect; const widthPx = Number(rect?.width || viewW); - if (!(widthPx > 0)) return; + if (!(widthPx > 0)) { + cachedSvgRect = null; + return; + } const offsetX = Number(ev.clientX || 0) - Number(rect?.left || 0); const svgX = (offsetX / widthPx) * viewW; const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD); const u = Math.max(0, Math.min(1, (svgX - LEFT_X) / plotW)); - const clampedX = LEFT_X + u * plotW; - const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs)); - - hoverLine.setAttribute('x1', clampedX.toFixed(1)); - hoverLine.setAttribute('x2', clampedX.toFixed(1)); - - while (hoverDotsGroup.firstChild) hoverDotsGroup.removeChild(hoverDotsGroup.firstChild); - const tipItems = []; - for (let i = 0; i < plottedSeries.length; i++) { - const s = plottedSeries[i]; - const val = sampleSeriesValueAt(s.rawPoints, targetMs); - if (val === null) continue; - const y = valueToSvgY(val); - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', clampedX.toFixed(1)); - dot.setAttribute('cy', y.toFixed(1)); - dot.setAttribute('r', '3.2'); - dot.setAttribute('fill', 'var(--surface-panel)'); - dot.setAttribute('stroke', s.color); - dot.setAttribute('stroke-width', '1.8'); - hoverDotsGroup.appendChild(dot); - tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val }); - } - if (tipItems.length === 0) { - hideHover(); - return; - } - hoverLine.removeAttribute('hidden'); - hoverDotsGroup.removeAttribute('hidden'); - - patchText(tipTimeEl, formatHoverTimestamp(targetMs)); - patchText(tipWinEl, t(selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h')); - patchKeyedList(tipRowsHost, tipItems, { - keyFn: (it) => it.key, - sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`, - createRow: () => { - const sw = h('span', { className: 'dot-swatch' }); - const nm = h('span', { className: 'account-trend-tip-name' }); - const vl = h('strong', { className: 'text-mono' }); - const row = h('div', { className: 'account-trend-tip-row' }, [ - h('span', { className: 'legend-left' }, [sw, nm]), - vl, - ]); - return { el: row, refs: { sw, nm, vl } }; - }, - updateRow: (r, it) => { - r.sw.style.background = it.color; - patchText(r.nm, it.label); - patchText(r.vl, `${+it.val.toFixed(1)}%`); - }, - }); - - const pctX = (clampedX / viewW) * 100; - const shift = pctX < 24 ? '0%' : pctX > 76 ? '-100%' : '-50%'; - patchStyleVar(tooltipEl, '--tip-x', `${pctX.toFixed(1)}%`); - patchStyleVar(tooltipEl, '--tip-shift', shift); - patchAttr(tooltipEl, 'hidden', false); + const slotIdx = Math.round(u * HOVER_SLOT_COUNT); + const pointer = + Number.isFinite(Number(ev?.clientX)) && Number.isFinite(Number(ev?.clientY)) + ? { clientX: Number(ev.clientX), clientY: Number(ev.clientY) } + : null; + showHoverAtSlot(slotIdx, pointer); } function resolveTargetAccountEmail() { @@ -849,10 +1024,9 @@ export const AccountQuotaTrendCard = defineComponent({ ); } - function renderChart() { - hideHover(); + function renderChart({ skipMorph = false } = {}) { const nowMs = Date.now(); - void getEffectiveLocale(); + const locale = getEffectiveLocale(); patchText(cardTitleText, t('settings.account.trendTitle')); patchText(rangeToEl, t('cons.rangeTo')); @@ -932,6 +1106,9 @@ export const AccountQuotaTrendCard = defineComponent({ patchAttr(emptyStateEl, 'hidden', hasPlot); if (!hasPlot) { plottedSeries = []; + lastPlotSig = ''; + seriesMorphCtrl.reset(); + hideHover(); patchText(emptyStateEl, t('settings.account.trendEmpty')); return; } @@ -947,9 +1124,8 @@ export const AccountQuotaTrendCard = defineComponent({ gl.setAttribute('x2', String(viewW)); } - plottedSeries = rawBuilt.map((rb) => ({ - ...rb, - svgPts: rb.rawPoints.map((sp) => { + plottedSeries = rawBuilt.map((rb) => { + const fullSvgPts = rb.rawPoints.map((sp) => { const u = Math.max(0, Math.min(1, (sp.ts - plottedStartMs) / spanMs)); return { x: LEFT_X + u * plotW, @@ -957,50 +1133,112 @@ export const AccountQuotaTrendCard = defineComponent({ val: sp.val, ts: sp.ts, }; - }), - })); + }); + return { + ...rb, + svgPts: simplifySvgPointsForRender(fullSvgPts, LEFT_X, plotW), + }; + }); - while (seriesGroup.firstChild) seriesGroup.removeChild(seriesGroup.firstChild); - for (let i = 0; i < plottedSeries.length; i++) { - const s = plottedSeries[i]; - const lineD = buildHorizontalTangentSpline(s.svgPts); - if (s.svgPts.length >= 2) { - const first = s.svgPts[0]; - const last = s.svgPts[s.svgPts.length - 1]; - const areaEl = document.createElementNS(SVG_NS, 'path'); - areaEl.setAttribute( - 'd', - `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z` - ); - if (plottedSeries.length === 1) { - stopTop.setAttribute('stop-color', s.color); - stopBot.setAttribute('stop-color', s.color); - areaEl.setAttribute('fill', `url(#${gradId})`); - } else { - areaEl.setAttribute('class', 'sstep-multi-area'); - areaEl.style.setProperty('--sstep-series-color', s.color); + const plotSig = + `${locale}|${viewW}|${targetEmail}|${selectedWin}|${selectedRange}|${selectedPool}|${plottedYScale.yMin}-${plottedYScale.yMax}|` + + plottedSeries + .map( + (s) => + `${s.poolKey}:${s.svgPts.length}:${s.svgPts[0]?.x.toFixed(1)}:${s.svgPts[0]?.y.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.x.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.y.toFixed(1)}` + ) + .join('|'); + + if (plotSig !== lastPlotSig) { + lastPlotSig = plotSig; + const activePoolKeys = new Set(); + const morphItems = []; + + for (let i = 0; i < plottedSeries.length; i++) { + const s = plottedSeries[i]; + activePoolKeys.add(s.poolKey); + let nodes = seriesNodePoolByKey.get(s.poolKey); + if (!nodes) { + const areaEl = document.createElementNS(SVG_NS, 'path'); + const lineEl = document.createElementNS(SVG_NS, 'path'); + lineEl.setAttribute('fill', 'none'); + lineEl.setAttribute('stroke-width', '1.9'); + lineEl.setAttribute('stroke-linecap', 'round'); + const endDotEl = document.createElementNS(SVG_NS, 'circle'); + endDotEl.setAttribute('r', '2.7'); + nodes = { areaEl, lineEl, endDotEl }; + seriesNodePoolByKey.set(s.poolKey, nodes); } - seriesGroup.appendChild(areaEl); - } - const pathEl = document.createElementNS(SVG_NS, 'path'); - pathEl.setAttribute('d', lineD); - pathEl.setAttribute('fill', 'none'); - pathEl.setAttribute('stroke', s.color); - pathEl.setAttribute('stroke-width', '1.9'); - pathEl.setAttribute('stroke-linecap', 'round'); - seriesGroup.appendChild(pathEl); - const endPt = s.svgPts[s.svgPts.length - 1]; - const endDot = document.createElementNS(SVG_NS, 'circle'); - endDot.setAttribute('cx', endPt.x.toFixed(1)); - endDot.setAttribute('cy', endPt.y.toFixed(1)); - endDot.setAttribute('r', '2.7'); - endDot.setAttribute('fill', s.color); - seriesGroup.appendChild(endDot); + const lineD = buildHorizontalTangentSpline(s.svgPts); + let areaD = ''; + if (s.svgPts.length >= 2) { + const first = s.svgPts[0]; + const last = s.svgPts[s.svgPts.length - 1]; + areaD = `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z`; + if (plottedSeries.length === 1) { + stopTop.setAttribute('stop-color', s.color); + stopBot.setAttribute('stop-color', s.color); + nodes.areaEl.removeAttribute('class'); + nodes.areaEl.style.removeProperty('--sstep-series-color'); + nodes.areaEl.setAttribute('fill', `url(#${gradId})`); + } else { + nodes.areaEl.removeAttribute('fill'); + nodes.areaEl.setAttribute('class', 'sstep-multi-area'); + nodes.areaEl.style.setProperty('--sstep-series-color', s.color); + } + nodes.areaEl.removeAttribute('hidden'); + } else { + nodes.areaEl.setAttribute('d', ''); + nodes.areaEl.setAttribute('hidden', ''); + } + + nodes.lineEl.setAttribute('stroke', s.color); + nodes.endDotEl.setAttribute('fill', s.color); + + seriesGroup.appendChild(nodes.areaEl); + seriesGroup.appendChild(nodes.lineEl); + seriesGroup.appendChild(nodes.endDotEl); + + const endPt = s.svgPts[s.svgPts.length - 1]; + morphItems.push({ + key: s.poolKey, + nextSegs: pointsToNormalizedCubicSegs(s.svgPts, BOTTOM_Y, { + leftX: LEFT_X, + spanX: plotW, + tension: 0.38, + }), + lineEl: nodes.lineEl, + areaEl: areaD ? nodes.areaEl : null, + endDotEl: nodes.endDotEl, + endX: endPt.x, + endY: endPt.y, + finalLineD: lineD, + finalAreaD: areaD, + }); + } + + for (const [k, nodes] of seriesNodePoolByKey.entries()) { + if (!activePoolKeys.has(k)) { + nodes.areaEl.remove(); + nodes.lineEl.remove(); + nodes.endDotEl.remove(); + } + } + + seriesMorphCtrl.morphSeries({ + items: morphItems, + leftX: LEFT_X, + spanX: plotW, + bottomY: BOTTOM_Y, + skipMorph, + }); } - // Edge-to-edge X-axis ticks (`0% .. 100%`) + // Edge-to-edge X-axis ticks (`0% .. 100%`) with active hover highlight & click-to-inspect const tickCount = 5; + const activeTickIdx = + hoveredSlotIdx >= 0 ? Math.round((hoveredSlotIdx / HOVER_SLOT_COUNT) * (tickCount - 1)) : -1; const ticks = []; for (let k = 0; k < tickCount; k++) { const ratio = k / (tickCount - 1); @@ -1008,25 +1246,37 @@ export const AccountQuotaTrendCard = defineComponent({ const leftPct = ratio * 100; ticks.push({ idx: k, + slotIdx: Math.round(ratio * HOVER_SLOT_COUNT), leftPct, label: formatAxisTickTime(tickMs, spanMs), + fullTitle: formatHoverTimestamp(tickMs), edge: k === 0 ? 'start' : k === tickCount - 1 ? 'end' : '', + isHovered: k === activeTickIdx, }); } + xTickElements = []; + lastHoveredTickIdx = activeTickIdx; patchKeyedList(xAxisEl, ticks, { keyFn: (tk) => tk.idx, - sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}`, + sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}:${tk.isHovered}`, createRow: () => { const el = h('span', { className: 'trend-x-tick text-mono' }); return { el, refs: { el } }; }, updateRow: (r, tk) => { patchText(r.el, tk.label); + patchAttr(r.el, 'title', tk.fullTitle); patchStyleVar(r.el, '--tick-x', `${tk.leftPct.toFixed(2)}%`); patchClasses(r.el, { 'is-start': tk.edge === 'start', 'is-end': tk.edge === 'end', + 'is-hovered': tk.isHovered, }); + r.el.onclick = () => { + lastPointer = null; + showHoverAtSlot(tk.slotIdx, null, { forceRefresh: true }); + }; + xTickElements[tk.idx] = r.el; }, }); @@ -1046,21 +1296,29 @@ export const AccountQuotaTrendCard = defineComponent({ patchText(r.vl, `${+s.latestVal.toFixed(1)}%`); }, }); + + if (hoveredSlotIdx >= 0) { + showHoverAtSlot(hoveredSlotIdx, lastPointer, { forceRefresh: true }); + } } let resizeObs = null; if (typeof ResizeObserver === 'function') { resizeObs = new ResizeObserver((entries) => { + cachedSvgRect = null; + tooltipCtrl.invalidateRects(); const w = Math.floor(Number(entries?.[0]?.contentRect?.width || 0)); if (w >= 180 && Math.abs(w - viewW) >= 2) { viewW = w; - renderChart(); + renderChart({ skipMorph: true }); } }); resizeObs.observe(plotStage); } onCleanup(() => { + seriesMorphCtrl.cancel(); + tooltipCtrl.destroy(); resizeObs?.disconnect(); accountSelect.destroy(); poolSelect.destroy(); @@ -1078,7 +1336,7 @@ export const AccountQuotaTrendCard = defineComponent({ renderChart(); return { el: rootEl, - refs: { update, refreshLabels: renderChart }, + refs: { update, refreshLabels: () => renderChart() }, }; }, }); diff --git a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index 359786d..f75dd30 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -182,6 +182,28 @@ export function patchCapsuleOdometerText( return true; } +function isValidTtftSec(val) { + return val != null && Number.isFinite(Number(val)) && Number(val) >= 0; +} + +function findFallbackRecentStepTtft(steps) { + if (!Array.isArray(steps) || steps.length === 0) return null; + const firstIdx = Number(steps[0]?.stepIndex ?? 0); + const lastIdx = Number(steps[steps.length - 1]?.stepIndex ?? 0); + if (firstIdx >= lastIdx) { + for (let i = 0; i < steps.length; i += 1) { + const candidate = steps[i]?.ttftSec; + if (isValidTtftSec(candidate)) return Number(candidate); + } + return null; + } + for (let i = steps.length - 1; i >= 0; i -= 1) { + const candidate = steps[i]?.ttftSec; + if (isValidTtftSec(candidate)) return Number(candidate); + } + return null; +} + /** * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. */ @@ -204,11 +226,29 @@ export function buildCapsuleSlotContext( ).toFixed(2); const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const convId = String(capActive.cascadeId || activeConv.cascadeId || '') + .trim() + .toLowerCase(); + const scopeId = String(scopedConv?.agentId || aggregated?.agentId || 'main'); + const conversationKey = convId ? `${convId}::${scopeId}` : ''; + const stepCount = Math.max(0, Number(capActive.stepCount ?? activeConv.stepCount ?? 0)); + + const rawTtft = + scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null; + const fallbackTtft = isValidTtftSec(rawTtft) + ? Number(rawTtft) + : scopedConv?.lastKnownTtftSec ?? + findFallbackRecentStepTtft(scopedConv?.recentSteps) ?? + aggregated?.lastKnownTtftSec ?? + activeConv.lastKnownTtftSec ?? + findFallbackRecentStepTtft(activeConv.recentSteps); + const resolvedTtft = isValidTtftSec(fallbackTtft) ? Number(fallbackTtft) : null; + const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); const sessionTokens = - Number(capActive.stepCount || 0) > 0 || + stepCount > 0 || capActive.totalTokens != null || capInTok + capCacheTok + capOutTok > 0 ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) @@ -216,12 +256,14 @@ export function buildCapsuleSlotContext( return { hasTelemetry: true, + conversationKey, + stepCount, usedPct, dashOffset, isRunning, tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null, avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null, - ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null, + ttft: resolvedTtft, stepCost: scopedConv?.latestStepCostUsd ?? aggregated?.latestStepCostUsd ?? @@ -351,6 +393,7 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) { textSpan, ringMounted: isCtx, prefixMounted: false, + heldTtft: null, }; } @@ -363,7 +406,25 @@ export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCt for (let i = 0; i < capsuleSlots.length; i += 1) { const slot = capsuleSlots[i]; const metricKey = i < slotKeys.length ? slotKeys[i] : 'none'; - const pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE); + if (!slotCtx?.hasTelemetry || metricKey !== 'ttft') { + slot.heldTtft = null; + } + let pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE); + if (metricKey === 'ttft' && slotCtx?.hasTelemetry) { + const convKey = String(slotCtx.conversationKey || ''); + if (isValidTtftSec(slotCtx.ttft)) { + slot.heldTtft = convKey ? { conversationKey: convKey, pres } : null; + } else if ( + convKey && + slot.heldTtft && + slot.heldTtft.conversationKey === convKey && + (slotCtx.isRunning || Number(slotCtx.stepCount) > 0) + ) { + pres = { ...slot.heldTtft.pres, running: Boolean(slotCtx.isRunning) }; + } else { + slot.heldTtft = null; + } + } if (pres.hidden) { patchAttr(slot.el, 'hidden', true); patchAttr(slot.el, 'data-metric', 'none'); diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 709360e..d9b8f5c 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -756,6 +756,7 @@ export function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false; if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false; if (pAct?.aggregated?.latestTtftSec !== nAct?.aggregated?.latestTtftSec) return false; + if (pAct?.aggregated?.lastKnownTtftSec !== nAct?.aggregated?.lastKnownTtftSec) return false; if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false; if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false; if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false; @@ -767,6 +768,7 @@ export function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.lastKnownTtftSec !== nAct?.lastKnownTtftSec) return false; if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false; if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false; if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false; @@ -805,6 +807,7 @@ export function isEquivalentTelemetry(prev, next) { pa?.liveActivity?.signature !== na?.liveActivity?.signature || pa?.latestTokPerSec !== na?.latestTokPerSec || pa?.latestTtftSec !== na?.latestTtftSec || + pa?.lastKnownTtftSec !== na?.lastKnownTtftSec || pa?.avgTokPerSec !== na?.avgTokPerSec || pa?.latestCacheHitPct !== na?.latestCacheHitPct || pa?.sessionCacheHitPct !== na?.sessionCacheHitPct || diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 6cdd8fa..9895e18 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -854,7 +854,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } -[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown) { +[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown):not(.is-floating-tip) { top: 2px; bottom: auto; transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0); @@ -868,6 +868,14 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { translateX(var(--tip-shift, 0px)); } +[data-modern-ui="true"] .trend-tooltip.is-floating-tip { + top: 0; + bottom: auto; + left: 0; + transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0) + translateX(var(--tip-shift, 0px)); +} + [data-modern-ui="true"] .trend-tooltip.is-tracking { transition: left 150ms var(--ease-modern), @@ -880,7 +888,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { transition: transform 150ms var(--ease-modern); } -[data-modern-ui="true"] .trend-hover-dot.is-tracking { +[data-modern-ui="true"] .trend-tooltip.is-floating-tip.is-tracking { + transition: transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-hover-dot.is-tracking, +[data-modern-ui="true"] .sstep-hover-raw-dot.is-tracking { transition: cx 150ms var(--ease-modern), cy 150ms var(--ease-modern); @@ -1008,6 +1021,13 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { will-change: transform; } +@starting-style { + :host([data-modern-ui="true"]) .wm-od-track, + [data-modern-ui="true"] .wm-od-track { + transform: translate3d(0, 0, 0); + } +} + :host([data-modern-ui="true"]) .wm-od-cell, [data-modern-ui="true"] .wm-od-cell { display: block; diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index cc7e829..12ce162 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -401,6 +401,7 @@ height: 184px; display: block; overflow: visible; + pointer-events: none; } .trend-grid line { @@ -459,20 +460,24 @@ z-index: 2; } -.cons-view-stage .progress-seg { +.cons-view-stage .progress-seg, +.models-analytics-pane .progress-seg { flex: 0 0 auto; transition: background-color 80ms ease, width 240ms cubic-bezier(0.22, 1, 0.36, 1); } -.cons-view-stage .progress-fill { +.cons-view-stage .progress-fill, +.account-cards-stack .progress-fill { transition: width 240ms cubic-bezier(0.22, 1, 0.36, 1); } @starting-style { .cons-view-stage.is-ready .progress-seg, - .cons-view-stage.is-ready .progress-fill { + .cons-view-stage.is-ready .progress-fill, + .models-analytics-pane .progress-seg, + .account-cards-stack .progress-fill { width: 0%; } } @@ -498,8 +503,13 @@ @media (prefers-reduced-motion: reduce) { .cons-view-stage .progress-seg, .cons-view-stage .progress-fill, + .models-analytics-pane .progress-seg, + .account-cards-stack .progress-fill, .trend-peak-pill.is-ready, - .trend-hm-cell { + .trend-hm-cell, + .trend-tooltip.is-tracking, + .trend-hover-dot.is-tracking, + .sstep-hover-raw-dot.is-tracking { transition: none !important; } .cons-item-list.is-bars-revealing .progress-track { @@ -1190,6 +1200,28 @@ contain: layout style; } +.trend-tooltip.is-floating-tip { + top: 0; + bottom: auto; + left: 0; + transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0) + translateX(var(--tip-shift, 0px)); + will-change: transform; + contain: layout style; +} + +.trend-tooltip.is-floating-tip.is-tracking, +.trend-tooltip.is-rich-breakdown.is-tracking { + transition: transform 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)); +} + +.trend-hover-dot.is-tracking, +.sstep-hover-raw-dot.is-tracking { + transition: + cx 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)), + cy 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)); +} + .trend-tooltip.is-rich-breakdown, .cons-breakdown-popover.is-rich-breakdown { min-width: 212px; diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 933465a..d1bbdc7 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -775,6 +775,7 @@ height: 106px; display: block; overflow: visible; + pointer-events: none; } .sstep-fit-svg { diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 7095733..0c58015 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -3200,6 +3200,7 @@ html[data-standalone="true"] .app-shell { height: 184px; display: block; overflow: visible; + pointer-events: none; } .trend-grid line { @@ -3258,20 +3259,24 @@ html[data-standalone="true"] .app-shell { z-index: 2; } -.cons-view-stage .progress-seg { +.cons-view-stage .progress-seg, +.models-analytics-pane .progress-seg { flex: 0 0 auto; transition: background-color 80ms ease, width 240ms cubic-bezier(0.22, 1, 0.36, 1); } -.cons-view-stage .progress-fill { +.cons-view-stage .progress-fill, +.account-cards-stack .progress-fill { transition: width 240ms cubic-bezier(0.22, 1, 0.36, 1); } @starting-style { .cons-view-stage.is-ready .progress-seg, - .cons-view-stage.is-ready .progress-fill { + .cons-view-stage.is-ready .progress-fill, + .models-analytics-pane .progress-seg, + .account-cards-stack .progress-fill { width: 0%; } } @@ -3297,8 +3302,13 @@ html[data-standalone="true"] .app-shell { @media (prefers-reduced-motion: reduce) { .cons-view-stage .progress-seg, .cons-view-stage .progress-fill, + .models-analytics-pane .progress-seg, + .account-cards-stack .progress-fill, .trend-peak-pill.is-ready, - .trend-hm-cell { + .trend-hm-cell, + .trend-tooltip.is-tracking, + .trend-hover-dot.is-tracking, + .sstep-hover-raw-dot.is-tracking { transition: none !important; } .cons-item-list.is-bars-revealing .progress-track { @@ -3989,6 +3999,28 @@ html[data-standalone="true"] .app-shell { contain: layout style; } +.trend-tooltip.is-floating-tip { + top: 0; + bottom: auto; + left: 0; + transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0) + translateX(var(--tip-shift, 0px)); + will-change: transform; + contain: layout style; +} + +.trend-tooltip.is-floating-tip.is-tracking, +.trend-tooltip.is-rich-breakdown.is-tracking { + transition: transform 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)); +} + +.trend-hover-dot.is-tracking, +.sstep-hover-raw-dot.is-tracking { + transition: + cx 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)), + cy 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)); +} + .trend-tooltip.is-rich-breakdown, .cons-breakdown-popover.is-rich-breakdown { min-width: 212px; @@ -5058,6 +5090,7 @@ html[data-standalone="true"] .app-shell { height: 106px; display: block; overflow: visible; + pointer-events: none; } .sstep-fit-svg { @@ -9109,7 +9142,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { border: none; } -[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown) { +[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown):not(.is-floating-tip) { top: 2px; bottom: auto; transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0); @@ -9123,6 +9156,14 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { translateX(var(--tip-shift, 0px)); } +[data-modern-ui="true"] .trend-tooltip.is-floating-tip { + top: 0; + bottom: auto; + left: 0; + transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0) + translateX(var(--tip-shift, 0px)); +} + [data-modern-ui="true"] .trend-tooltip.is-tracking { transition: left 150ms var(--ease-modern), @@ -9135,7 +9176,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { transition: transform 150ms var(--ease-modern); } -[data-modern-ui="true"] .trend-hover-dot.is-tracking { +[data-modern-ui="true"] .trend-tooltip.is-floating-tip.is-tracking { + transition: transform 150ms var(--ease-modern); +} + +[data-modern-ui="true"] .trend-hover-dot.is-tracking, +[data-modern-ui="true"] .sstep-hover-raw-dot.is-tracking { transition: cx 150ms var(--ease-modern), cy 150ms var(--ease-modern); @@ -9263,6 +9309,13 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { will-change: transform; } +@starting-style { + :host([data-modern-ui="true"]) .wm-od-track, + [data-modern-ui="true"] .wm-od-track { + transform: translate3d(0, 0, 0); + } +} + :host([data-modern-ui="true"]) .wm-od-cell, [data-modern-ui="true"] .wm-od-cell { display: block; diff --git a/sidecars/panel/test/modern-ui.test.mjs b/sidecars/panel/test/modern-ui.test.mjs index 79a21c9..8e9f02c 100644 --- a/sidecars/panel/test/modern-ui.test.mjs +++ b/sidecars/panel/test/modern-ui.test.mjs @@ -15,11 +15,19 @@ import { parseCssColorLuminance, } from '../src/core/appearance.js'; import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js'; -import { computePublicationFit } from '../src/components/charts/SessionStepCharts.js'; +import { + computePublicationFit, + createModelFitChart, + createSessionLineChart, +} from '../src/components/charts/SessionStepCharts.js'; import { CustomSelect } from '../src/components/ui/CustomSelect.js'; import { SegmentedControl } from '../src/components/ui/SegmentedControl.js'; +import { AccountQuotaTrendCard } from '../src/components/widgets/AccountQuotaTrendCard.js'; import { + buildCapsuleSlotContext, + createCapsuleSlotNode, patchCapsuleOdometerText, + syncCapsuleSlotNodes, tokenizeCapsuleOdometerText, } from '../src/components/widgets/CapsuleBarWidget.js'; import { ContextWindowWidget } from '../src/components/widgets/ContextWindowWidget.js'; @@ -558,12 +566,21 @@ test('SegmentedControl variable-width glider snaps cleanly on reveal and glides const tipEl = trendChart.el.querySelector('.trend-tooltip'); Object.assign(tipEl, { offsetWidth: 216, offsetHeight: 82 }); const plotStage = trendChart.el.querySelector('.trend-plot-stage'); + const trendPeakPill = trendChart.el.querySelector('.trend-peak-pill'); const svgEl = trendChart.el.querySelector('.trend-svg'); svgEl.getBoundingClientRect = () => ({ left: 0, top: 246, width: 460, height: 184, right: 460, bottom: 430 }); + // Zero-data slots must keep peak pill hidden even after hover + mouseleave + trendChart.update([{ index: 0, label: '00:53', fullLabel: '11月25日 00:53 - 00:54', tokens: 0, calls: 0, costUsd: 0 }]); + assert.equal(trendPeakPill.hasAttribute('hidden'), true, 'Zero-data chart must hide peak pill'); + plotStage.dispatchEvent({ type: 'mousemove', clientX: 200, clientY: 340 }); + plotStage.dispatchEvent({ type: 'mouseleave' }); + assert.equal(trendPeakPill.hasAttribute('hidden'), true, 'Peak pill stays hidden after mouseleave on zero-data chart'); + trendChart.update([ { index: 0, label: '00:00', fullLabel: '11月19日 00:00 - 01:00', tokens: 1000, calls: 2, costUsd: 0.1 }, { index: 1, label: '10:00', fullLabel: '11月19日 10:00 - 11:00', tokens: 25_000_000, calls: 80, costUsd: 6.37 }, ]); + assert.equal(trendPeakPill.hasAttribute('hidden'), false, 'Non-zero chart shows peak pill'); queuedRaf = null; plotStage.dispatchEvent({ type: 'mousemove', clientX: 80, clientY: 360 }); const firstY = tipEl.style.getPropertyValue('--tip-y'); @@ -581,6 +598,135 @@ test('SegmentedControl variable-width glider snaps cleanly on reveal and glides assert.equal(tipEl.style.getPropertyValue('--tip-y'), '54px'); trendChart.destroy(); + // 10b. SessionStepCharts (Summary view) and AccountQuotaTrendCard share 2D pointer-following tooltip + .is-tracking focus dots + const stepLineChart = createSessionLineChart(); + Object.assign(stepLineChart.el, { + clientWidth: 460, + offsetHeight: 130, + getBoundingClientRect: () => ({ left: 0, top: 200, width: 460, height: 130, right: 460, bottom: 330 }), + }); + const stepTipEl = stepLineChart.el.querySelector('.trend-tooltip'); + assert.equal(stepTipEl.classList.contains('is-floating-tip'), true); + Object.assign(stepTipEl, { offsetWidth: 208, offsetHeight: 76 }); + const stepStage = stepLineChart.el.querySelector('.sstep-plot-stage'); + const stepSvg = stepLineChart.el.querySelector('.sstep-svg'); + stepSvg.getBoundingClientRect = () => ({ left: 0, top: 206, width: 460, height: 106, right: 460, bottom: 312 }); + stepLineChart.update({ + steps: [ + { stepIndex: 1, createdAtMs: 1000, modelShort: 'Gemini', totalTokens: 12000, inputTokens: 8000, cacheReadTokens: 2000, outputTokens: 2000, tokPerSec: 60, ttftSec: 0.4 }, + { stepIndex: 2, createdAtMs: 2000, modelShort: 'Gemini', totalTokens: 28000, inputTokens: 16000, cacheReadTokens: 8000, outputTokens: 4000, tokPerSec: 75, ttftSec: 0.3 }, + ], + metric: 'totalTokens', + }); + queuedRaf?.(); + assert.equal(stepLineChart.el.querySelector('.trend-peak-pill').classList.contains('is-ready'), true); + queuedRaf = null; + stepStage.dispatchEvent({ type: 'mousemove', clientX: 120, clientY: 300 }); + assert.equal(stepTipEl.style.getPropertyValue('--tip-shift'), '0px'); + assert.equal(stepTipEl.style.getPropertyValue('--tip-y'), '10px'); + const stepHoverDot = stepLineChart.el.querySelector('.trend-hover-dot'); + assert.equal(stepTipEl.classList.contains('is-tracking'), false); + assert.equal(stepHoverDot.classList.contains('is-tracking'), false); + queuedRaf?.(); + assert.equal(stepTipEl.classList.contains('is-tracking'), true); + assert.equal(stepHoverDot.classList.contains('is-tracking'), true); + stepLineChart.destroy(); + + const fitChart = createModelFitChart(); + Object.assign(fitChart.el, { + clientWidth: 460, + offsetHeight: 160, + getBoundingClientRect: () => ({ left: 0, top: 200, width: 460, height: 160, right: 460, bottom: 360 }), + }); + const fitTipEl = fitChart.el.querySelector('.trend-tooltip'); + assert.equal(fitTipEl.classList.contains('is-floating-tip'), true); + Object.assign(fitTipEl, { offsetWidth: 212, offsetHeight: 74 }); + fitChart.el.querySelector('.sstep-fit-svg').getBoundingClientRect = () => ({ + left: 0, + top: 204, + width: 460, + height: 138, + right: 460, + bottom: 342, + }); + fitChart.update({ + steps: [ + { stepIndex: 1, createdAtMs: 1000, modelShort: 'Gemini', tokPerSec: 55 }, + { stepIndex: 2, createdAtMs: 2000, modelShort: 'Gemini', tokPerSec: 68 }, + { stepIndex: 3, createdAtMs: 3000, modelShort: 'Gemini', tokPerSec: 72 }, + ], + metric: 'tps', + }); + queuedRaf = null; + fitChart.el.querySelector('.sstep-plot-stage').dispatchEvent({ type: 'mousemove', clientX: 220, clientY: 310 }); + queuedRaf?.(); + assert.equal(fitTipEl.classList.contains('is-tracking'), true); + assert.equal(fitChart.el.querySelector('.trend-hover-dot').classList.contains('is-tracking'), true); + assert.equal(fitChart.el.querySelector('.sstep-hover-raw-dot').classList.contains('is-tracking'), true); + fitChart.destroy(); + + const nowQ = Date.now(); + const quotaCard = AccountQuotaTrendCard({}); + const quotaWrap = quotaCard.el.querySelector('.trend-chart-wrap'); + Object.assign(quotaWrap, { + clientWidth: 460, + offsetHeight: 210, + getBoundingClientRect: () => ({ left: 0, top: 200, width: 460, height: 210, right: 460, bottom: 410 }), + }); + const quotaTipEl = quotaCard.el.querySelector('.trend-tooltip'); + assert.equal(quotaTipEl.classList.contains('is-floating-tip'), true); + Object.assign(quotaTipEl, { offsetWidth: 200, offsetHeight: 74 }); + quotaCard.el.querySelector('.trend-svg').getBoundingClientRect = () => ({ + left: 0, + top: 206, + width: 460, + height: 184, + right: 460, + bottom: 390, + }); + quotaCard.refs.update({ + activeEmail: 'user@example.com', + activePools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + remainingPct: 91, + weeklyRemainingPct: 88, + resetTime: new Date(nowQ + 2 * 3600_000).toISOString(), + }, + ], + quotaHistory: { + 'user@example.com': { + pools: { + Gemini: { + label: 'Gemini', + reset5hMs: nowQ + 2 * 3600_000, + points: [ + [nowQ - 3 * 3600_000 + 2000, 100, 90], + [nowQ - 3600_000, 95, 89], + ], + }, + }, + }, + }, + }); + queuedRaf = null; + quotaCard.el.querySelector('.trend-plot-stage').dispatchEvent({ + type: 'mousemove', + clientX: 230, + clientY: 320, + }); + assert.equal(quotaTipEl.style.getPropertyValue('--tip-y'), '32px'); + queuedRaf?.(); + assert.equal(quotaTipEl.classList.contains('is-tracking'), true); + assert.equal(quotaCard.el.querySelector('.trend-hover-dot').classList.contains('is-tracking'), true); + assert.equal( + quotaCard.el.querySelectorAll('.trend-x-tick').some((tk) => tk.classList.contains('is-hovered')), + true, + 'Hovering quota chart highlights nearest X-axis tick' + ); + quotaCard.destroy(); + // 11. ContextWindowWidget + LiveActivityWidget use pure SVG chevrons and animate expand/collapse under [data-modern-ui="true"] document.documentElement.setAttribute('data-modern-ui', 'true'); const ctxWidget = ContextWindowWidget({}); @@ -1236,4 +1382,136 @@ test('Capsule odometer digit rolling (0.15s) and color transition (0.1s) stay st builtStyles, /\[data-modern-ui="true"\]\s+\.trend-tooltip\.is-rich-breakdown\.is-tracking\s*\{\s*transition:\s*transform\s+150ms\s+var\(--ease-modern\);\s*\}/ ); + assert.match( + builtStyles, + /@starting-style\s*\{[\s\S]*?\[data-modern-ui="true"\]\s+\.wm-od-track\s*\{\s*transform:\s*translate3d\(0,\s*0,\s*0\);/ + ); + assert.match( + builtStyles, + /\.trend-tooltip\.is-floating-tip\s*\{[^}]*left:\s*0;[^}]*transform:\s*translate3d\(var\(--tip-x,\s*0px\),\s*var\(--tip-y,\s*0px\),\s*0\)/ + ); + + // 6. Pending TTFT during a new step must NOT flash --s or destroy odometer reels before TTFT is calculated + const capHost = document.createElement('div'); + capHost.setAttribute('data-modern-ui', 'true'); + const capSlots = [ + createCapsuleSlotNode(0, 'tps'), + createCapsuleSlotNode(1, 'ttft'), + createCapsuleSlotNode(2, 'context'), + createCapsuleSlotNode(3, 'none'), + createCapsuleSlotNode(4, 'none'), + ]; + const capSeps = Array.from({ length: 4 }, () => document.createElement('span')); + for (const s of capSlots) capHost.appendChild(s.el); + document.body.appendChild(capHost); + + const slotKeys = ['tps', 'ttft', 'context']; + + // Poll 1: Step #10075 finished with ttft = 13.3s + syncCapsuleSlotNodes( + capSlots, + capSeps, + slotKeys, + buildCapsuleSlotContext({ + activeConversation: { + cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316', + isRunning: false, + stepCount: 2131, + latestTokPerSec: 7.4, + latestTtftSec: 13.3, + lastKnownTtftSec: 13.3, + context: { totalTokens: 130000, compactionLimitTokens: 256000 }, + }, + }) + ); + assert.equal(capSlots[1].textSpan.getAttribute('data-od-value'), '13.3s'); + const ttftReelsStep1 = capSlots[1].textSpan.querySelectorAll('.wm-od-digit'); + assert.equal(ttftReelsStep1.length, 3); + const savedOnesReel = ttftReelsStep1[1]; + const savedTenthsReel = ttftReelsStep1[2]; + + // Poll 2: Step #10077 streaming (10.5 t/s, latestTtftSec = null while TTFT is not calculated yet, even without lastKnownTtftSec) + syncCapsuleSlotNodes( + capSlots, + capSeps, + slotKeys, + buildCapsuleSlotContext({ + activeConversation: { + cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316', + isRunning: true, + stepCount: 2132, + latestTokPerSec: 10.5, + latestTtftSec: null, + context: { totalTokens: 131000, compactionLimitTokens: 256000 }, + }, + }) + ); + assert.equal( + capSlots[1].textSpan.getAttribute('data-od-value'), + '13.3s', + 'TTFT slot keeps previous valid TTFT while new step TTFT is still pending' + ); + const ttftReelsPending = capSlots[1].textSpan.querySelectorAll('.wm-od-digit'); + assert.equal(ttftReelsPending.length, 3); + assert.equal(ttftReelsPending[1], savedOnesReel); + assert.equal(ttftReelsPending[2], savedTenthsReel); + + // Poll 2b: Cold-mounted slot mid-generation resolves lastKnownTtftSec / recentSteps fallback instead of --s + const coldSlotCtx = buildCapsuleSlotContext({ + activeConversation: { + cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316', + isRunning: true, + stepCount: 2132, + latestTokPerSec: 10.5, + latestTtftSec: null, + lastKnownTtftSec: 13.3, + context: { totalTokens: 131000, compactionLimitTokens: 256000 }, + }, + }); + assert.equal(coldSlotCtx.ttft, 13.3); + + // Poll 3: Step #10077 TTFT calculated (8.4s) -> rolls directly 13.3s -> 8.4s on the preserved DOM reels + syncCapsuleSlotNodes( + capSlots, + capSeps, + slotKeys, + buildCapsuleSlotContext({ + activeConversation: { + cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316', + isRunning: true, + stepCount: 2132, + latestTokPerSec: 10.5, + latestTtftSec: 8.4, + lastKnownTtftSec: 8.4, + context: { totalTokens: 131000, compactionLimitTokens: 256000 }, + }, + }) + ); + assert.equal(capSlots[1].textSpan.getAttribute('data-od-value'), '8.4s'); + const ttftReelsResolved = capSlots[1].textSpan.querySelectorAll('.wm-od-digit'); + assert.equal(ttftReelsResolved.length, 2); + assert.equal(ttftReelsResolved[0], savedOnesReel, 'Ones reel stays mounted for 150ms roll'); + assert.equal(ttftReelsResolved[1], savedTenthsReel, 'Tenths reel stays mounted for 150ms roll'); + assert.equal(savedOnesReel.querySelector('.wm-od-track').style.getPropertyValue('--od-val'), '8'); + assert.equal(savedTenthsReel.querySelector('.wm-od-track').style.getPropertyValue('--od-val'), '4'); + + // Poll 4: Switching to a different conversation with no TTFT resets cleanly to --s without leaking + syncCapsuleSlotNodes( + capSlots, + capSeps, + slotKeys, + buildCapsuleSlotContext({ + activeConversation: { + cascadeId: 'dddddddd-7777-8888-9999-eeeeeeeeeeee', + isRunning: false, + stepCount: 8, + latestTokPerSec: 120.5, + latestTtftSec: null, + recentSteps: [], + context: { totalTokens: 64000, compactionLimitTokens: 256000 }, + }, + }) + ); + assert.equal(capSlots[1].textSpan.textContent, '--s'); + assert.equal(capSlots[1].textSpan.hasAttribute('data-od-active'), false); }); From de35e54589c70e03c36856f8769672f0b51ac1df Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Wed, 25 Nov 2026 01:39:56 +0900 Subject: [PATCH 24/30] refactor(panel): extract overlay anchors and consumption row builders - Extract host anchor discovery, 4-stage capsule layout hysteresis, and ShadowRoot stylesheet mounting from WindowOverlayShell into overlayHostAnchors - Extract reusable model, client-source, workspace, and top-conversation breakdown row builders from ConsumptionView into ConsumptionBreakdownRows - Add root CHANGELOG.md and regression coverage for extracted P3 modules and export header documentation --- CHANGELOG.md | 39 + sidecars/panel/app.js | 1892 +++++++++-------- sidecars/panel/backend/file-exporter.mjs | 6 +- sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 2 + .../components/layout/WindowOverlayShell.js | 919 +------- .../components/layout/overlayHostAnchors.js | 919 ++++++++ .../widgets/ConsumptionBreakdownRows.js | 887 ++++++++ sidecars/panel/src/views/ConsumptionView.js | 979 +-------- .../test/practical-enhancements.test.mjs | 112 + 10 files changed, 2977 insertions(+), 2782 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 sidecars/panel/src/components/layout/overlayHostAnchors.js create mode 100644 sidecars/panel/src/components/widgets/ConsumptionBreakdownRows.js diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..528d65e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,39 @@ +# Changelog + +All notable changes to **Antigravity Usage & Speed Monitor** are documented in this file. + +## [1.5.4] - Unreleased + +### Added +- **Local CloudCode Proxy & Dual Context-Window Controls**: Added `cloudcode-proxy.mjs` loopback reverse proxy (`SetCloudCodeURL`) to synchronize custom per-model context window limits to non-`self` subagents and Swarm workers alongside independent `contextWindowMainEnabled` / `contextWindowSwarmEnabled` toggles. +- **Experimental Quota Lease Reservation Estimator**: Added `quota-reservation.mjs` 5h/weekly dual-bucket in-flight quota lease tracking, FIFO settlement, delayed refund confirmation, outlier-filtered rolling median rate calibration, violet bar indicator, and `GET /api/quota-reservation/log`. +- **Native Multi-Sheet `.xlsx` & Markdown Exports**: Added zero-dependency OOXML workbook builder (`xlsxBuilder.js`) and localized multi-sheet Excel / Markdown report exports with local `~/Downloads` save and one-click file manager reveal toast. +- **Step Diagnostic Drawer & Live Filtering**: Added click-to-inspect `StepDiagnosticDrawer` (timing waterfall, token/cost breakdown, 9-kind V4 `anomaly.events` list, Markdown copy), live multi-term step search, and danger-tier diagnostic filter chips. +- **Workspace Cost Attribution & Session Migration**: Added **Projects (Workspaces)** cost ranking tab, session project tags, portable JSON settings backup/import, and opt-in cross-client session migration/cloning (`CLI ↔ Desktop/IDE` and `Legacy IDE`) with isolated UUID rewriting. +- **CLI `statusLine` Gauge Styles & JSON Output**: Added `--style pill|bar|compact`, `--preset compact|balanced|full`, and single-line `--json` snapshot output for external prompt/bar integrations. + +### Changed & Optimized +- **Hot-Path Performance (P1)**: Made `trajectoryCache` lazy via `createTrajectoryCacheStore` and added tail-row (`LIMIT 16`) SQLite reads for `cli-statusline.mjs` (`~419ms → <60ms`); skipped redundant per-poll WAL `statSync` on unchanged `IDLE` sessions; switched `cloudcode-proxy` Windows system proxy lookup to async `execFile` with TTL caching; deferred overlay `App()` instantiation until first popover open; coalesced host `MutationObserver` via `requestAnimationFrame`; shared `adoptedStyleSheets` across overlay portals and cached chart `DOMRect` on hover. +- **Shared Primitives & Modular Architecture (P2–P3)**: Extracted `fs-atomic.mjs`, `trajectory-cache-store.mjs`, `workspace-uri.mjs`, `prompt-clean.mjs`, `windows-shortcut-provision.ps1`, `ToggleSwitch.js` (cutting `SettingsView` `ResizeObserver` count by ~59%), `SearchInput.js`, `StepDiagnosticDrawer.js`, `ConsumptionBreakdownRows.js`, `stepChartMath.js`, and `overlayHostAnchors.js`; upgraded `build-bundle.mjs` regex-after-condition-paren lexer and inner-IIFE `import/export { a as b }` alias support. + +### Fixed +- **Telemetry & Inspector Accuracy (P0)**: Unified step selection keys so clicking any step reliably opens the diagnostic drawer; preserved V4 `nativeStreamSec`, `thinkingDurationSec`, and `hasToolCalls` across step projections; fixed `reportExporter.js` and `stepInspector.js` duration/waterfall fields and `anomaly.events` rendering; computed merged model average speed from exact `speedSummary.{tokens, seconds}` harmonic totals; honored `ANTIGRAVITY_GEMINI_DIR` override and cleaned up `multiRunningWidget` on overlay disposal. + +## [1.5.3] - 2026-04 + +### Added & Changed +- Graduated borderless **Modern UI** to default, defaulted language to host/system (`auto`), and unified token breakdown ordering and flat tooltip cards. +- Added SSH Remote multi-window isolation (`endpoint-registry.mjs`) with per-endpoint trajectory/quota caches and RPC routing. +- Added support for Opus 5.5 Orchestrator (`Neon` variants) and prevented unknown future variants from misrouting to Carbon pools. +- Fixed 5-hour quota cycle boundary accounting and macOS host relaunch ancestor process matching. + +## [1.5.2] - 2026-03 + +### Added & Changed +- Added runtime-only whitelist Release ZIP packager (`pack-release-zip.mjs`), Native Swarm mode worker telemetry, 9-category step anomaly diagnostics, virtualized large step tables (`>80` rows), and pruned `scope=consumption` / `scope=conversation` fast paths. +- Hardened Desktop `2.33.0+` launcher auto-provisioning and out-of-job 1-click host relaunch across Windows (UIPI-safe user relaunch + on-demand UAC), macOS, and Linux (`.desktop` / AppImage). + +## [1.5.1] - 2026-03 + +### Added & Changed +- Added hybrid SQLite + WAL direct reader, `384k` context window preset, time-phased promotional model pricing, scalable `--fs-*` typography tokens, and isolated `sidecar-worker.mjs` hot-reloadable runtime. diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 5dd7476..6e3b297 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -27295,6 +27295,878 @@ const StepTableWidget = defineComponent({ return { formatTurnPromptText, StepTableWidget }; })(); +// --- src/components/widgets/ConsumptionBreakdownRows.js --- +const { partitionModelSegments, createBreakdownItemRow, updateBreakdownItemRow, createConsumptionBreakdownRowBuilders } = (() => { +/** + * @fileoverview Reusable model, client-source, workspace, and top-conversation breakdown + * row builders (`ConsumptionBreakdownRows.js`) extracted from `ConsumptionView.js`. + * Consolidates shared long-tail model partitioning, hover-popover event binding, and top-model pill rendering. + */ + + +function createSourceModelSegment() { + const segEl = h('div', { className: 'progress-seg cons-model-seg' }); + return { el: segEl, refs: { segEl } }; +} + +function createSourceTopModelItem() { + const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' }); + const nameEl = h('span', { className: 'cons-source-top-name' }); + const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' }); + const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]); + return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } }; +} + +function formatCompactSourceSharePct(pct) { + const num = Number(pct || 0); + if (!Number.isFinite(num) || num <= 0) return '0%'; + if (num >= 10) return `${Math.round(num)}%`; + return `${num.toFixed(1)}%`; +} + +function renderSegmentedModelBarAndTopPills( + trackEl, + topModelsEl, + partitioned, + scaleRatio, + fallbackKey +) { + const barItems = + partitioned.length > 0 + ? partitioned.map((seg) => ({ + key: seg.key, + segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, + color: seg.color, + })) + : scaleRatio > 0 + ? [ + { + key: fallbackKey, + segPct: scaleRatio * 100, + color: 'var(--accent-primary)', + }, + ] + : []; + + patchKeyedList(trackEl, barItems, { + keyFn: (seg) => seg.key, + sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, + createRow: createSourceModelSegment, + updateRow: (segRefs, seg) => { + patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); + patchStyleVar(segRefs.segEl, '--seg-color', seg.color); + }, + }); + + const topModels = partitioned + .filter((seg) => !seg.isOther) + .slice(0, 3) + .map((seg) => ({ + key: seg.key, + label: seg.label, + pctText: formatCompactSourceSharePct(seg.pct), + color: seg.color, + })); + patchAttr(topModelsEl, 'hidden', topModels.length === 0); + patchKeyedList(topModelsEl, topModels, { + keyFn: (m) => m.key, + sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, + createRow: createSourceTopModelItem, + updateRow: (mRefs, m) => { + patchStyleVar(mRefs.dotEl, '--dot-color', m.color); + patchText(mRefs.nameEl, m.label); + patchText(mRefs.pctEl, m.pctText); + patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); + }, + }); + + return topModels; +} + +/** + * Collapses long-tail model entries into primary segments + an aggregated "Other (N)" tail. + */ +function partitionModelSegments( + mergedModels, + modelColorMap, + { maxMain = 5, minSharePct = 1.5 } = {} +) { + if (!Array.isArray(mergedModels) || mergedModels.length === 0) return []; + const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); + const mainModels = []; + const tailModels = []; + + for (let i = 0; i < mergedModels.length; i += 1) { + const m = mergedModels[i]; + const mTok = Number(m.totalTokens || 0); + const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0; + if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) { + mainModels.push(m); + } else { + tailModels.push(m); + } + } + + if (tailModels.length === 1) { + mainModels.push(tailModels.pop()); + } + + const out = mainModels.map((m) => { + const seed = getCanonicalModelColorSeed(m); + const color = + modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText); + const tok = Number(m.totalTokens || 0); + const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0; + const label = m.displayText || m.label || m.shortName || '—'; + const inputTokens = Math.max(0, Number(m.inputTokens || 0)); + const cacheReadTokens = Math.max(0, Number(m.cacheReadTokens || 0)); + const thinkingTokens = Math.max(0, Number(m.thinkingTokens || 0)); + const responseTokens = + m.responseTokens != null + ? Math.max(0, Number(m.responseTokens)) + : Math.max(0, Number(m.outputTokens || 0) - thinkingTokens); + return { + key: label, + label, + tok, + pct, + inputTokens, + cacheReadTokens, + thinkingTokens, + responseTokens, + outputTokens: responseTokens + thinkingTokens, + tokText: formatTokensPrecise(tok), + pctText: formatPctNumber(pct, { withSymbol: true }), + color, + isOther: false, + }; + }); + + if (tailModels.length >= 2) { + let otherTok = 0; + let otherIn = 0; + let otherCache = 0; + let otherThink = 0; + let otherResp = 0; + for (const m of tailModels) { + const mt = Math.max(0, Number(m.thinkingTokens || 0)); + const mr = + m.responseTokens != null + ? Math.max(0, Number(m.responseTokens)) + : Math.max(0, Number(m.outputTokens || 0) - mt); + otherTok += Number(m.totalTokens || 0); + otherIn += Math.max(0, Number(m.inputTokens || 0)); + otherCache += Math.max(0, Number(m.cacheReadTokens || 0)); + otherThink += mt; + otherResp += mr; + } + const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0; + const otherLabel = t('cons.otherModelsCount', { count: tailModels.length }); + out.push({ + key: '__other__', + label: otherLabel, + tok: otherTok, + pct: otherPct, + inputTokens: otherIn, + cacheReadTokens: otherCache, + thinkingTokens: otherThink, + responseTokens: otherResp, + outputTokens: otherResp + otherThink, + tokText: formatTokensPrecise(otherTok), + pctText: formatPctNumber(otherPct, { withSymbol: true }), + color: 'var(--cons-other-seg)', + isOther: true, + }); + } + + return out; +} + +/** + * Creates a model ranking row (`tokens` | `cost` | `speed` | `calls` sort modes). + */ +function createBreakdownItemRow() { + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const segBar = createFourSegmentBar(); + + const inLbl = h('span', { text: t('cons.footInput') }); + const cacheLbl = h('span', { text: t('cons.footCache') }); + const outLbl = h('span', { text: t('cons.footOutput') }); + const thinkLbl = h('span', { text: t('cons.footThinking') }); + const callsLbl = h('span', { text: t('cons.footCalls') }); + + const inVal = h('strong', { className: 'text-mono' }); + const cacheVal = h('strong', { className: 'text-mono' }); + const outVal = h('strong', { className: 'text-mono' }); + const thinkVal = h('strong', { className: 'text-mono' }); + const callsVal = h('strong', { className: 'text-mono' }); + const metricBarFillEl = h('div', { className: 'progress-seg cons-metric-fill' }); + const metricBarEl = h( + 'div', + { className: 'progress-track cons-seg-bar cons-metric-bar', hidden: true }, + [metricBarFillEl] + ); + const tokenFootEl = h('div', { className: 'cons-item-foot' }, [ + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-input' }), + inLbl, + inVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheLbl, + cacheVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-thinking' }), + thinkLbl, + thinkVal, + ]), + h('span', { className: 'legend-left' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outLbl, + outVal, + ]), + h('span', { className: 'legend-left' }, [callsLbl, callsVal]), + ]); + const perfMainEl = h('span', { className: 'cons-model-perf-main text-mono' }); + const perfUnitCostEl = h('span', { className: 'cons-model-unit-cost text-mono', hidden: true }); + const perfFootEl = h('div', { className: 'cons-model-perf-foot', hidden: true }, [ + perfMainEl, + perfUnitCostEl, + ]); + const focusLeftEl = h('span', { className: 'cons-model-focus-left text-mono' }); + const focusRightEl = h('span', { className: 'cons-model-focus-right text-mono' }); + const focusFootEl = h( + 'div', + { className: 'cons-item-foot cons-model-focus-foot', hidden: true }, + [focusLeftEl, focusRightEl] + ); + + const rowEl = h('div', { className: 'cons-item-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), + ]), + segBar.el, + metricBarEl, + tokenFootEl, + perfFootEl, + focusFootEl, + ]); + + return { + el: rowEl, + refs: { + nameEl, + nameTextEl, + pctBadge, + totalTokEl, + costEl, + segBar, + metricBarEl, + metricBarFillEl, + tokenFootEl, + inLbl, + cacheLbl, + outLbl, + thinkLbl, + callsLbl, + inVal, + cacheVal, + outVal, + thinkVal, + callsVal, + perfFootEl, + perfMainEl, + perfUnitCostEl, + focusFootEl, + focusLeftEl, + focusRightEl, + }, + }; +} + +/** + * Incrementally patches a model ranking row. + */ +function updateBreakdownItemRow(refs, item, totalsCtx, sortMode = 'tokens') { + const displayLabel = item.label || item.name || item.shortName || '—'; + patchText(refs.nameTextEl, displayLabel); + patchAttr(refs.nameEl, 'title', item.title || displayLabel); + + const total = Number(item.totalTokens || 0); + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + + const avgTps = + item.avgTokPerSec != null && + Number.isFinite(Number(item.avgTokPerSec)) && + Number(item.avgTokPerSec) > 0 + ? Number(item.avgTokPerSec) + : null; + const avgTtft = + item.avgTtftSec != null && + Number.isFinite(Number(item.avgTtftSec)) && + Number(item.avgTtftSec) >= 0 + ? Number(item.avgTtftSec) + : null; + const hasExplicitCachePct = + item.cacheHitPct != null && Number.isFinite(Number(item.cacheHitPct)); + const promptTok = Number(item.inputTokens || 0) + Number(item.cacheReadTokens || 0); + const cachePctVal = hasExplicitCachePct + ? Number(item.cacheHitPct) + : promptTok > 0 && Number(item.cacheReadTokens || 0) > 0 + ? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1) + : 0; + const cachePctStr = formatPctNumber(cachePctVal); + const effCostPer1M = + !isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null; + const outTok = Number( + item.outputTokens ?? Number(item.responseTokens || 0) + Number(item.thinkingTokens || 0) + ); + + if (sortMode === 'cost') { + const costBase = Number(totalsCtx?.totalCost || 0); + const costShare = costBase > 0 ? +((costVal / costBase) * 100).toFixed(1) : 0; + const barPct = + costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0; + patchAttr(refs.pctBadge, 'hidden', false); + patchAttr(refs.pctBadge, 'title', null); + patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true })); + patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal)); + patchText(refs.costEl, costText); + + patchAttr(refs.segBar.el, 'hidden', true); + patchAttr(refs.metricBarEl, 'hidden', false); + patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); + patchClasses(refs.metricBarFillEl, { + 'tone-cost': true, + 'tone-speed': false, + 'tone-calls': false, + }); + + patchAttr(refs.tokenFootEl, 'hidden', true); + patchAttr(refs.perfFootEl, 'hidden', true); + patchAttr(refs.focusFootEl, 'hidden', false); + const unitPart = + effCostPer1M !== null + ? t('cons.modelUnitCost', { + cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), + }) + : ''; + const cachePart = t('cons.topConvCacheMeta', { pct: cachePctStr }); + patchText(refs.focusLeftEl, unitPart ? `${unitPart} · ${cachePart}` : cachePart); + patchText( + refs.focusRightEl, + `${formatTokensPrecise(total)} · ${t('cons.callsCount', { calls: callsCount })}` + ); + return; + } + + if (sortMode === 'speed') { + const maxTps = Number(totalsCtx?.maxAvgTps || 0); + const speedPct = + maxTps > 0 && avgTps !== null ? Math.min(100, Math.max(2, (avgTps / maxTps) * 100)) : 0; + patchAttr(refs.pctBadge, 'hidden', avgTps === null); + patchAttr(refs.pctBadge, 'title', avgTps !== null ? t('cons.speedRelTip') : null); + patchText(refs.pctBadge, avgTps !== null ? `${Math.round(speedPct)}%` : ''); + patchText( + refs.totalTokEl, + avgTtft !== null ? t('cons.focusTtft', { ttft: formatMetric(avgTtft, 's') }) : '' + ); + patchText(refs.costEl, formatSpeedMetric(avgTps, ' tok/s')); + + patchAttr(refs.segBar.el, 'hidden', true); + patchAttr(refs.metricBarEl, 'hidden', false); + patchStyleVar(refs.metricBarFillEl, '--seg-w', `${speedPct.toFixed(2)}%`); + patchClasses(refs.metricBarFillEl, { + 'tone-cost': false, + 'tone-speed': true, + 'tone-calls': false, + }); + + patchAttr(refs.tokenFootEl, 'hidden', true); + patchAttr(refs.perfFootEl, 'hidden', true); + patchAttr(refs.focusFootEl, 'hidden', false); + patchText( + refs.focusLeftEl, + t('cons.focusSpeedMeta', { + ttft: formatMetric(avgTtft, 's'), + cache: cachePctStr, + out: formatTokensPrecise(outTok), + }) + ); + patchText(refs.focusRightEl, t('cons.callsCount', { calls: callsCount })); + return; + } + + if (sortMode === 'calls') { + const callsBase = Number(totalsCtx?.totalCalls || 0); + const callsShare = callsBase > 0 ? +((callsCount / callsBase) * 100).toFixed(1) : 0; + const barPct = + callsBase > 0 && callsCount > 0 + ? Math.min(100, Math.max(1, (callsCount / callsBase) * 100)) + : 0; + patchAttr(refs.pctBadge, 'hidden', false); + patchAttr(refs.pctBadge, 'title', null); + patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true })); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + patchText(refs.costEl, t('cons.callsCount', { calls: callsCount })); + + patchAttr(refs.segBar.el, 'hidden', true); + patchAttr(refs.metricBarEl, 'hidden', false); + patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); + patchClasses(refs.metricBarFillEl, { + 'tone-cost': false, + 'tone-speed': false, + 'tone-calls': true, + }); + + patchAttr(refs.tokenFootEl, 'hidden', true); + patchAttr(refs.perfFootEl, 'hidden', true); + patchAttr(refs.focusFootEl, 'hidden', false); + const avgPerCall = callsCount > 0 ? total / callsCount : 0; + patchText( + refs.focusLeftEl, + t('cons.focusCallsMeta', { + avgTok: formatTokensPrecise(avgPerCall), + cost: costText, + }) + ); + patchText(refs.focusRightEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); + return; + } + + patchText(refs.inLbl, t('cons.footInput')); + patchText(refs.cacheLbl, t('cons.footCache')); + patchText(refs.outLbl, t('cons.footOutput')); + patchText(refs.thinkLbl, t('cons.footThinking')); + patchText(refs.callsLbl, t('cons.footCalls')); + const grandTotalTokens = Number(totalsCtx?.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; + patchAttr(refs.pctBadge, 'hidden', false); + patchAttr(refs.pctBadge, 'title', null); + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + patchText(refs.costEl, costText); + + const responseTok = + item.responseTokens != null + ? Number(item.responseTokens) + : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); + const thinkingTok = Number(item.thinkingTokens || 0); + + patchAttr(refs.segBar.el, 'hidden', false); + patchAttr(refs.metricBarEl, 'hidden', true); + refs.segBar.update({ + inputTokens: Number(item.inputTokens || 0), + cacheReadTokens: Number(item.cacheReadTokens || 0), + responseTokens: responseTok, + thinkingTokens: thinkingTok, + scaleRatio, + }); + + patchAttr(refs.tokenFootEl, 'hidden', false); + patchAttr(refs.focusFootEl, 'hidden', true); + patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); + patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); + patchText(refs.outVal, formatTokensPrecise(responseTok)); + patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); + patchText(refs.callsVal, String(callsCount)); + + const hasPerfMeta = avgTps !== null || avgTtft !== null || effCostPer1M !== null; + patchAttr(refs.perfFootEl, 'hidden', !hasPerfMeta); + if (hasPerfMeta) { + if (avgTps !== null || avgTtft !== null) { + patchText( + refs.perfMainEl, + t('steps.modelPerfFoot', { + tps: formatSpeedMetric(avgTps, ' tok/s'), + ttft: formatMetric(avgTtft, 's'), + cache: cachePctStr, + }) + ); + } else { + patchText(refs.perfMainEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); + } + patchAttr(refs.perfUnitCostEl, 'hidden', effCostPer1M === null); + patchText( + refs.perfUnitCostEl, + effCostPer1M !== null + ? t('cons.modelUnitCost', { + cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), + }) + : '' + ); + } +} + +/** + * Binds shared popover hover callbacks to build source-breakdown and workspace/conversation rows. + */ +function createConsumptionBreakdownRowBuilders({ + showPopover, + movePopover, + hidePopover, + isHoveredTarget, + onSelectConversation, +}) { + function isNodeInside(root, node) { + if (!root || !node) return false; + if (typeof root.contains === 'function') return root.contains(node); + let cur = node; + while (cur) { + if (cur === root) return true; + cur = cur.parentNode || null; + } + return false; + } + + function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) { + zoneEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && isHoveredTarget(zoneEl)) { + movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + zoneEl.addEventListener('mouseleave', () => { + if (isHoveredTarget(zoneEl)) hidePopover(); + }); + + for (const childEl of compatTargets) { + if (!childEl) continue; + childEl.addEventListener('mouseenter', (e) => { + if (rowState.hoverPayload) { + showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mousemove', (e) => { + if (rowState.hoverPayload && isHoveredTarget(zoneEl)) { + movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); + } + }); + childEl.addEventListener('mouseleave', (e) => { + const nextEl = e?.relatedTarget || null; + if (isNodeInside(zoneEl, nextEl)) { + return; + } + if (isHoveredTarget(zoneEl)) hidePopover(); + }); + } + } + + function createSourceBreakdownRow() { + const nameTextEl = h('span', { className: 'cons-row-title-text' }); + const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); + const rowState = { hoverPayload: null }; + + const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); + const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); + + const callsLbl = h('span', { text: t('cons.footCalls') }); + const callsVal = h('strong', { className: 'text-mono' }); + + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + + const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ + h('div', { className: 'panel-header' }, [ + nameEl, + h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), + ]), + hoverZoneEl, + ]); + + return { + el: rowEl, + refs: { + nameEl, + nameTextEl, + pctBadge, + totalTokEl, + costEl, + hoverZoneEl, + barHitEl, + trackEl, + topModelsEl, + callsLbl, + callsVal, + rowState, + }, + }; + } + + function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) { + patchText(refs.callsLbl, t('cons.footCalls')); + const displayLabel = item.label || item.name || '—'; + patchText(refs.nameTextEl, displayLabel); + patchAttr(refs.nameEl, 'title', item.title || displayLabel); + + const total = Number(item.totalTokens || 0); + const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; + const scaleRatio = + grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); + patchText(refs.totalTokEl, formatTokensPrecise(total)); + + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + patchText(refs.costEl, costText); + patchText(refs.callsVal, String(callsCount)); + + const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; + const partitioned = partitionModelSegments(sourceModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + + renderSegmentedModelBarAndTopPills( + refs.trackEl, + refs.topModelsEl, + partitioned, + total > 0 ? scaleRatio : 0, + '__source_fallback__' + ); + + refs.rowState.hoverPayload = + total > 0 || callsCount > 0 + ? { + title: displayLabel, + calls: callsCount, + totalTokens: total, + costText, + inputTokens: item.inputTokens, + cacheReadTokens: item.cacheReadTokens, + thinkingTokens: item.thinkingTokens, + responseTokens: item.responseTokens, + outputTokens: item.outputTokens, + segments: partitioned, + } + : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); + } + + function createTopConversationRow() { + const titleTextEl = h('span', { className: 'cons-row-title-text' }); + const wsBadgeEl = h('span', { className: 'cons-ws-sessions-tag text-mono', hidden: true }); + const titleEl = h('strong', { className: 'cons-row-title cons-top-conv-title' }, [ + titleTextEl, + wsBadgeEl, + ]); + const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); + const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); + const costEl = h('strong', { className: 'cons-row-cost text-mono' }); + const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); + const rowState = { cascadeId: '', canJump: false, hoverPayload: null }; + + const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); + const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); + + const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true }); + const callsLbl = h('span', { text: t('cons.footCalls') }); + const callsVal = h('strong', { className: 'text-mono' }); + + const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ + barHitEl, + h('div', { className: 'cons-item-foot cons-source-foot' }, [ + topModelsEl, + fallbackMetaEl, + h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]), + ]), + ]); + attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); + + const rowEl = h( + 'div', + { + className: 'cons-top-conv-row', + onClick: () => { + if (!rowState.canJump || !rowState.cascadeId) return; + hidePopover(); + onSelectConversation?.(rowState.cascadeId); + }, + }, + [ + h('div', { className: 'panel-header' }, [ + titleEl, + h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]), + ]), + hoverZoneEl, + ] + ); + + return { + el: rowEl, + refs: { + rowEl, + titleEl, + titleTextEl, + wsBadgeEl, + pctBadge, + totalTokEl, + costEl, + hoverZoneEl, + barHitEl, + trackEl, + topModelsEl, + fallbackMetaEl, + callsLbl, + callsVal, + rowState, + }, + }; + } + + function updateTopConversationRow(refs, item, bases, modelColorMap, sortMode = 'cost') { + patchText(refs.callsLbl, t('cons.footCalls')); + const isWorkspaceRow = Boolean(item.isWorkspaceRow); + const title = isWorkspaceRow + ? item.isUnbound + ? t('cons.workspaceUnbound') + : String(item.label || item.workspacePath || '—').trim() + : String(item.title || item.cascadeId || '—').trim(); + refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || ''); + refs.rowState.canJump = + !isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId); + patchClasses(refs.rowEl, { + 'is-jumpable': refs.rowState.canJump, + 'cons-workspace-row': isWorkspaceRow, + }); + const baseTip = + isWorkspaceRow && item.workspacePath && item.workspacePath !== title + ? `${title} (${item.workspacePath})` + : title; + patchAttr( + refs.rowEl, + 'title', + refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip + ); + patchText(refs.titleTextEl, title); + if (refs.wsBadgeEl) { + const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0; + patchAttr(refs.wsBadgeEl, 'hidden', !showWsBadge); + if (showWsBadge) { + patchText(refs.wsBadgeEl, t('cons.workspaceSessions', { count: item.sessionCount })); + } + } + + const total = Number(item.totalTokens || 0); + const costVal = Number(item.costUsd || 0); + const callsCount = Number(item.calls || 0); + const isAllUnpriced = + callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); + const costText = formatUsd(isAllUnpriced ? null : costVal, { + precise: costVal > 0 && costVal < 0.1, + }); + + const tokBase = Number(bases?.tokens || 0); + const costBase = Number(bases?.cost || 0); + const useCostBasis = sortMode === 'cost' && costBase > 0; + const share = useCostBasis + ? +((costVal / costBase) * 100).toFixed(1) + : tokBase > 0 + ? +((total / tokBase) * 100).toFixed(1) + : 0; + const scaleRatio = useCostBasis + ? costVal > 0 + ? Math.min(1, Math.max(0.01, costVal / costBase)) + : 0 + : tokBase > 0 && total > 0 + ? Math.min(1, Math.max(0.01, total / tokBase)) + : 0; + + patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); + if (sortMode === 'tokens') { + patchText(refs.totalTokEl, costText); + patchText(refs.costEl, formatTokensPrecise(total)); + } else { + patchText(refs.totalTokEl, formatTokensPrecise(total)); + patchText(refs.costEl, costText); + } + patchText(refs.callsVal, String(callsCount)); + + const convModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; + const partitioned = partitionModelSegments(convModels, modelColorMap, { + maxMain: 5, + minSharePct: 1.5, + }); + const topModels = renderSegmentedModelBarAndTopPills( + refs.trackEl, + refs.topModelsEl, + partitioned, + scaleRatio, + '__conv_fallback__' + ); + + const showFallbackMeta = topModels.length === 0; + patchAttr(refs.fallbackMetaEl, 'hidden', !showFallbackMeta); + if (showFallbackMeta) { + const srcLabel = item.sourceName || item.appSource || ''; + const cacheLabel = t('cons.topConvCacheMeta', { + pct: formatPctNumber(item.cacheHitPct ?? 0), + }); + patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel); + } + + refs.rowState.hoverPayload = + partitioned.length > 0 && (total > 0 || callsCount > 0) + ? { + title, + calls: callsCount, + totalTokens: total, + costText, + inputTokens: item.inputTokens, + cacheReadTokens: item.cacheReadTokens, + thinkingTokens: item.thinkingTokens, + responseTokens: item.responseTokens, + outputTokens: item.outputTokens, + segments: partitioned, + } + : null; + patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); + } + + return { + createSourceBreakdownRow, + updateSourceBreakdownRow, + createTopConversationRow, + updateTopConversationRow, + }; +} +return { partitionModelSegments, createBreakdownItemRow, updateBreakdownItemRow, createConsumptionBreakdownRowBuilders }; +})(); + // --- src/components/settings/structurePreviewMock.js --- const { buildStructurePreviewTelemetry } = (() => { /** @@ -35635,911 +36507,28 @@ const ConsumptionView = defineComponent({ breakdownPopoverEl, ]); - /** - * 将分模型列表收敛为主力模型 + 长尾「其他 (N)」,避免进度条尾部与浮层出现 0.0% 碎屑噪音。 - */ - function partitionModelSegments( - mergedModels, - modelColorMap, - { maxMain = 5, minSharePct = 1.5 } = {} - ) { - if (!Array.isArray(mergedModels) || mergedModels.length === 0) return []; - const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0); - const mainModels = []; - const tailModels = []; - - for (let i = 0; i < mergedModels.length; i++) { - const m = mergedModels[i]; - const mTok = Number(m.totalTokens || 0); - const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0; - if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) { - mainModels.push(m); - } else { - tailModels.push(m); - } - } - - if (tailModels.length === 1) { - mainModels.push(tailModels.pop()); - } - - const out = mainModels.map((m) => { - const seed = getCanonicalModelColorSeed(m); - const color = - modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText); - const tok = Number(m.totalTokens || 0); - const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0; - const label = m.displayText || m.label || m.shortName || '—'; - const inputTokens = Math.max(0, Number(m.inputTokens || 0)); - const cacheReadTokens = Math.max(0, Number(m.cacheReadTokens || 0)); - const thinkingTokens = Math.max(0, Number(m.thinkingTokens || 0)); - const responseTokens = - m.responseTokens != null - ? Math.max(0, Number(m.responseTokens)) - : Math.max(0, Number(m.outputTokens || 0) - thinkingTokens); - return { - key: label, - label, - tok, - pct, - inputTokens, - cacheReadTokens, - thinkingTokens, - responseTokens, - outputTokens: responseTokens + thinkingTokens, - tokText: formatTokensPrecise(tok), - pctText: formatPctNumber(pct, { withSymbol: true }), - color, - isOther: false, - }; - }); - - if (tailModels.length >= 2) { - let otherTok = 0; - let otherIn = 0; - let otherCache = 0; - let otherThink = 0; - let otherResp = 0; - for (const m of tailModels) { - const mt = Math.max(0, Number(m.thinkingTokens || 0)); - const mr = - m.responseTokens != null - ? Math.max(0, Number(m.responseTokens)) - : Math.max(0, Number(m.outputTokens || 0) - mt); - otherTok += Number(m.totalTokens || 0); - otherIn += Math.max(0, Number(m.inputTokens || 0)); - otherCache += Math.max(0, Number(m.cacheReadTokens || 0)); - otherThink += mt; - otherResp += mr; - } - const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0; - const otherLabel = t('cons.otherModelsCount', { count: tailModels.length }); - out.push({ - key: '__other__', - label: otherLabel, - tok: otherTok, - pct: otherPct, - inputTokens: otherIn, - cacheReadTokens: otherCache, - thinkingTokens: otherThink, - responseTokens: otherResp, - outputTokens: otherResp + otherThink, - tokText: formatTokensPrecise(otherTok), - pctText: formatPctNumber(otherPct, { withSymbol: true }), - color: 'var(--cons-other-seg)', - isOther: true, + const { + createSourceBreakdownRow, + updateSourceBreakdownRow, + createTopConversationRow, + updateTopConversationRow, + } = createConsumptionBreakdownRowBuilders({ + showPopover: showBreakdownPopover, + movePopover: positionBreakdownPopover, + hidePopover: hideBreakdownPopover, + isHoveredTarget: (targetEl) => activeHoverTargetEl === targetEl, + onSelectConversation: (cascadeId) => { + selectConversation(cascadeId); + uiStore.setState({ + activeView: 'steps', + stepsSubTab: 'steps', + selectedAgentScope: 'all', + ctxInspectorAgentId: getDefaultCtxInspectorAgentId( + telemetryStore.getState().telemetry?.settings + ), }); - } - - return out; - } - - /** - * 创建热门模型单行 DOM 结构(模型名称 + 按总占比缩放的 4 段比例条 + 底部分项脚标)。 - */ - function createBreakdownItemRow() { - const nameTextEl = h('span', { className: 'cons-row-title-text' }); - const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); - const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); - const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); - const costEl = h('strong', { className: 'cons-row-cost text-mono' }); - const segBar = createFourSegmentBar(); - - const inLbl = h('span', { text: t('cons.footInput') }); - const cacheLbl = h('span', { text: t('cons.footCache') }); - const outLbl = h('span', { text: t('cons.footOutput') }); - const thinkLbl = h('span', { text: t('cons.footThinking') }); - const callsLbl = h('span', { text: t('cons.footCalls') }); - - const inVal = h('strong', { className: 'text-mono' }); - const cacheVal = h('strong', { className: 'text-mono' }); - const outVal = h('strong', { className: 'text-mono' }); - const thinkVal = h('strong', { className: 'text-mono' }); - const callsVal = h('strong', { className: 'text-mono' }); - const metricBarFillEl = h('div', { className: 'progress-seg cons-metric-fill' }); - const metricBarEl = h( - 'div', - { className: 'progress-track cons-seg-bar cons-metric-bar', hidden: true }, - [metricBarFillEl] - ); - const tokenFootEl = h('div', { className: 'cons-item-foot' }, [ - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-input' }), - inLbl, - inVal, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheLbl, - cacheVal, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-thinking' }), - thinkLbl, - thinkVal, - ]), - h('span', { className: 'legend-left' }, [ - h('span', { className: 'dot-swatch seg-output' }), - outLbl, - outVal, - ]), - h('span', { className: 'legend-left' }, [ - callsLbl, - callsVal, - ]), - ]); - const perfMainEl = h('span', { className: 'cons-model-perf-main text-mono' }); - const perfUnitCostEl = h('span', { className: 'cons-model-unit-cost text-mono', hidden: true }); - const perfFootEl = h('div', { className: 'cons-model-perf-foot', hidden: true }, [ - perfMainEl, - perfUnitCostEl, - ]); - const focusLeftEl = h('span', { className: 'cons-model-focus-left text-mono' }); - const focusRightEl = h('span', { className: 'cons-model-focus-right text-mono' }); - const focusFootEl = h( - 'div', - { className: 'cons-item-foot cons-model-focus-foot', hidden: true }, - [focusLeftEl, focusRightEl] - ); - - const rowEl = h('div', { className: 'cons-item-row' }, [ - h('div', { className: 'panel-header' }, [ - nameEl, - h('span', { className: 'cons-row-metrics' }, [ - pctBadge, - totalTokEl, - costEl, - ]), - ]), - segBar.el, - metricBarEl, - tokenFootEl, - perfFootEl, - focusFootEl, - ]); - - return { - el: rowEl, - refs: { - nameEl, - nameTextEl, - pctBadge, - totalTokEl, - costEl, - segBar, - metricBarEl, - metricBarFillEl, - tokenFootEl, - inLbl, - cacheLbl, - outLbl, - thinkLbl, - callsLbl, - inVal, - cacheVal, - outVal, - thinkVal, - callsVal, - perfFootEl, - perfMainEl, - perfUnitCostEl, - focusFootEl, - focusLeftEl, - focusRightEl, - }, - }; - } - - /** - * 增量更新模型排行单行: - * - `tokens` 模式展示完整四段 Token 构成及效率副行; - * - `cost` / `speed` / `calls` 模式切换对应占比百分比、进度条尺度及聚焦单行脚标。 - */ - function updateBreakdownItemRow(refs, item, totalsCtx, sortMode = 'tokens') { - const displayLabel = item.label || item.name || item.shortName || '—'; - patchText(refs.nameTextEl, displayLabel); - patchAttr(refs.nameEl, 'title', item.title || displayLabel); - - const total = Number(item.totalTokens || 0); - const costVal = Number(item.costUsd || 0); - const callsCount = Number(item.calls || 0); - const isAllUnpriced = - callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); - const costText = formatUsd(isAllUnpriced ? null : costVal, { - precise: costVal > 0 && costVal < 0.1, - }); - - const avgTps = - item.avgTokPerSec != null && - Number.isFinite(Number(item.avgTokPerSec)) && - Number(item.avgTokPerSec) > 0 - ? Number(item.avgTokPerSec) - : null; - const avgTtft = - item.avgTtftSec != null && - Number.isFinite(Number(item.avgTtftSec)) && - Number(item.avgTtftSec) >= 0 - ? Number(item.avgTtftSec) - : null; - const hasExplicitCachePct = - item.cacheHitPct != null && Number.isFinite(Number(item.cacheHitPct)); - const promptTok = Number(item.inputTokens || 0) + Number(item.cacheReadTokens || 0); - const cachePctVal = hasExplicitCachePct - ? Number(item.cacheHitPct) - : promptTok > 0 && Number(item.cacheReadTokens || 0) > 0 - ? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1) - : 0; - const cachePctStr = formatPctNumber(cachePctVal); - const effCostPer1M = - !isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null; - const outTok = Number( - item.outputTokens ?? - Number(item.responseTokens || 0) + Number(item.thinkingTokens || 0) - ); - - if (sortMode === 'cost') { - const costBase = Number(totalsCtx?.totalCost || 0); - const costShare = costBase > 0 ? +((costVal / costBase) * 100).toFixed(1) : 0; - const barPct = costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0; - patchAttr(refs.pctBadge, 'hidden', false); - patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true })); - patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal)); - patchText(refs.costEl, costText); - - patchAttr(refs.segBar.el, 'hidden', true); - patchAttr(refs.metricBarEl, 'hidden', false); - patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); - patchClasses(refs.metricBarFillEl, { - 'tone-cost': true, - 'tone-speed': false, - 'tone-calls': false, - }); - - patchAttr(refs.tokenFootEl, 'hidden', true); - patchAttr(refs.perfFootEl, 'hidden', true); - patchAttr(refs.focusFootEl, 'hidden', false); - const unitPart = - effCostPer1M !== null - ? t('cons.modelUnitCost', { - cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), - }) - : ''; - const cachePart = t('cons.topConvCacheMeta', { pct: cachePctStr }); - patchText(refs.focusLeftEl, unitPart ? `${unitPart} · ${cachePart}` : cachePart); - patchText( - refs.focusRightEl, - `${formatTokensPrecise(total)} · ${t('cons.callsCount', { calls: callsCount })}` - ); - return; - } - - if (sortMode === 'speed') { - const maxTps = Number(totalsCtx?.maxAvgTps || 0); - const speedPct = - maxTps > 0 && avgTps !== null ? Math.min(100, Math.max(2, (avgTps / maxTps) * 100)) : 0; - patchAttr(refs.pctBadge, 'hidden', avgTps === null); - patchAttr(refs.pctBadge, 'title', avgTps !== null ? t('cons.speedRelTip') : null); - patchText(refs.pctBadge, avgTps !== null ? `${Math.round(speedPct)}%` : ''); - patchText( - refs.totalTokEl, - avgTtft !== null ? t('cons.focusTtft', { ttft: formatMetric(avgTtft, 's') }) : '' - ); - patchText(refs.costEl, formatSpeedMetric(avgTps, ' tok/s')); - - patchAttr(refs.segBar.el, 'hidden', true); - patchAttr(refs.metricBarEl, 'hidden', false); - patchStyleVar(refs.metricBarFillEl, '--seg-w', `${speedPct.toFixed(2)}%`); - patchClasses(refs.metricBarFillEl, { - 'tone-cost': false, - 'tone-speed': true, - 'tone-calls': false, - }); - - patchAttr(refs.tokenFootEl, 'hidden', true); - patchAttr(refs.perfFootEl, 'hidden', true); - patchAttr(refs.focusFootEl, 'hidden', false); - patchText( - refs.focusLeftEl, - t('cons.focusSpeedMeta', { - ttft: formatMetric(avgTtft, 's'), - cache: cachePctStr, - out: formatTokensPrecise(outTok), - }) - ); - patchText(refs.focusRightEl, t('cons.callsCount', { calls: callsCount })); - return; - } - - if (sortMode === 'calls') { - const callsBase = Number(totalsCtx?.totalCalls || 0); - const callsShare = callsBase > 0 ? +((callsCount / callsBase) * 100).toFixed(1) : 0; - const barPct = - callsBase > 0 && callsCount > 0 ? Math.min(100, Math.max(1, (callsCount / callsBase) * 100)) : 0; - patchAttr(refs.pctBadge, 'hidden', false); - patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true })); - patchText(refs.totalTokEl, formatTokensPrecise(total)); - patchText(refs.costEl, t('cons.callsCount', { calls: callsCount })); - - patchAttr(refs.segBar.el, 'hidden', true); - patchAttr(refs.metricBarEl, 'hidden', false); - patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`); - patchClasses(refs.metricBarFillEl, { - 'tone-cost': false, - 'tone-speed': false, - 'tone-calls': true, - }); - - patchAttr(refs.tokenFootEl, 'hidden', true); - patchAttr(refs.perfFootEl, 'hidden', true); - patchAttr(refs.focusFootEl, 'hidden', false); - const avgPerCall = callsCount > 0 ? total / callsCount : 0; - patchText( - refs.focusLeftEl, - t('cons.focusCallsMeta', { - avgTok: formatTokensPrecise(avgPerCall), - cost: costText, - }) - ); - patchText(refs.focusRightEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); - return; - } - - // 默认 Token 模式:展示全部四段 Token 构成及效率副行 - patchText(refs.inLbl, t('cons.footInput')); - patchText(refs.cacheLbl, t('cons.footCache')); - patchText(refs.outLbl, t('cons.footOutput')); - patchText(refs.thinkLbl, t('cons.footThinking')); - patchText(refs.callsLbl, t('cons.footCalls')); - const grandTotalTokens = Number(totalsCtx?.totalTokens || 0); - const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; - const scaleRatio = - grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0; - patchAttr(refs.pctBadge, 'hidden', false); - patchAttr(refs.pctBadge, 'title', null); - patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); - patchText(refs.totalTokEl, formatTokensPrecise(total)); - patchText(refs.costEl, costText); - - const responseTok = - item.responseTokens != null - ? Number(item.responseTokens) - : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); - const thinkingTok = Number(item.thinkingTokens || 0); - - patchAttr(refs.segBar.el, 'hidden', false); - patchAttr(refs.metricBarEl, 'hidden', true); - refs.segBar.update({ - inputTokens: Number(item.inputTokens || 0), - cacheReadTokens: Number(item.cacheReadTokens || 0), - responseTokens: responseTok, - thinkingTokens: thinkingTok, - scaleRatio, - }); - - patchAttr(refs.tokenFootEl, 'hidden', false); - patchAttr(refs.focusFootEl, 'hidden', true); - patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); - patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); - patchText(refs.outVal, formatTokensPrecise(responseTok)); - patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); - patchText(refs.callsVal, String(callsCount)); - - const hasPerfMeta = avgTps !== null || avgTtft !== null || effCostPer1M !== null; - patchAttr(refs.perfFootEl, 'hidden', !hasPerfMeta); - if (hasPerfMeta) { - if (avgTps !== null || avgTtft !== null) { - patchText( - refs.perfMainEl, - t('steps.modelPerfFoot', { - tps: formatSpeedMetric(avgTps, ' tok/s'), - ttft: formatMetric(avgTtft, 's'), - cache: cachePctStr, - }) - ); - } else { - patchText(refs.perfMainEl, t('cons.topConvCacheMeta', { pct: cachePctStr })); - } - patchAttr(refs.perfUnitCostEl, 'hidden', effCostPer1M === null); - patchText( - refs.perfUnitCostEl, - effCostPer1M !== null - ? t('cons.modelUnitCost', { - cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }), - }) - : '' - ); - } - } - - function createSourceModelSegment() { - const segEl = h('div', { className: 'progress-seg cons-model-seg' }); - return { el: segEl, refs: { segEl } }; - } - - function createSourceTopModelItem() { - const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' }); - const nameEl = h('span', { className: 'cons-source-top-name' }); - const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' }); - const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]); - return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } }; - } - - function formatCompactSourceSharePct(pct) { - const num = Number(pct || 0); - if (!Number.isFinite(num) || num <= 0) return '0%'; - if (num >= 10) return `${Math.round(num)}%`; - return `${num.toFixed(1)}%`; - } - - /** - * 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。 - */ - function isNodeInside(root, node) { - if (!root || !node) return false; - if (typeof root.contains === 'function') return root.contains(node); - let cur = node; - while (cur) { - if (cur === root) return true; - cur = cur.parentNode || null; - } - return false; - } - - function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) { - zoneEl.addEventListener('mouseenter', (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); - } - }); - zoneEl.addEventListener('mousemove', (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { - positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); - } - }); - zoneEl.addEventListener('mouseleave', () => { - if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); - }); - - for (const childEl of compatTargets) { - if (!childEl) continue; - childEl.addEventListener('mouseenter', (e) => { - if (rowState.hoverPayload) { - showBreakdownPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null); - } - }); - childEl.addEventListener('mousemove', (e) => { - if (rowState.hoverPayload && activeHoverTargetEl === zoneEl) { - positionBreakdownPopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null); - } - }); - childEl.addEventListener('mouseleave', (e) => { - const nextEl = e?.relatedTarget || null; - if (isNodeInside(zoneEl, nextEl)) { - return; - } - if (activeHoverTargetEl === zoneEl) hideBreakdownPopover(); - }); - } - } - - function createSourceBreakdownRow() { - const nameTextEl = h('span', { className: 'cons-row-title-text' }); - const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]); - const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); - const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); - const costEl = h('strong', { className: 'cons-row-cost text-mono' }); - const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); - const rowState = { hoverPayload: null }; - - const barHitEl = h( - 'div', - { - className: 'cons-source-bar-hit', - }, - [trackEl] - ); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - - const callsLbl = h('span', { text: t('cons.footCalls') }); - const callsVal = h('strong', { className: 'text-mono' }); - - const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), - ]); - attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); - - const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [ - h('div', { className: 'panel-header' }, [ - nameEl, - h('span', { className: 'cons-row-metrics' }, [ - pctBadge, - totalTokEl, - costEl, - ]), - ]), - hoverZoneEl, - ]); - - return { - el: rowEl, - refs: { - nameEl, - nameTextEl, - pctBadge, - totalTokEl, - costEl, - hoverZoneEl, - barHitEl, - trackEl, - topModelsEl, - callsLbl, - callsVal, - rowState, - }, - }; - } - - function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) { - patchText(refs.callsLbl, t('cons.footCalls')); - const displayLabel = item.label || item.name || '—'; - patchText(refs.nameTextEl, displayLabel); - patchAttr(refs.nameEl, 'title', item.title || displayLabel); - - const total = Number(item.totalTokens || 0); - const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; - const scaleRatio = - grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0; - patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); - patchText(refs.totalTokEl, formatTokensPrecise(total)); - - const costVal = Number(item.costUsd || 0); - const callsCount = Number(item.calls || 0); - const isAllUnpriced = - callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); - const costText = formatUsd(isAllUnpriced ? null : costVal, { - precise: costVal > 0 && costVal < 0.1, - }); - patchText(refs.costEl, costText); - patchText(refs.callsVal, String(callsCount)); - - const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; - const partitioned = partitionModelSegments(sourceModels, modelColorMap, { - maxMain: 5, - minSharePct: 1.5, - }); - - const barItems = - partitioned.length > 0 - ? partitioned.map((seg) => ({ - key: seg.key, - segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, - color: seg.color, - })) - : total > 0 - ? [ - { - key: '__source_fallback__', - segPct: scaleRatio * 100, - color: 'var(--accent-primary)', - }, - ] - : []; - - patchKeyedList(refs.trackEl, barItems, { - keyFn: (seg) => seg.key, - sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, - createRow: createSourceModelSegment, - updateRow: (segRefs, seg) => { - patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); - patchStyleVar(segRefs.segEl, '--seg-color', seg.color); - }, - }); - - const topModels = partitioned - .filter((seg) => !seg.isOther) - .slice(0, 3) - .map((seg) => ({ - key: seg.key, - label: seg.label, - pctText: formatCompactSourceSharePct(seg.pct), - color: seg.color, - })); - patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0); - patchKeyedList(refs.topModelsEl, topModels, { - keyFn: (m) => m.key, - sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, - createRow: createSourceTopModelItem, - updateRow: (mRefs, m) => { - patchStyleVar(mRefs.dotEl, '--dot-color', m.color); - patchText(mRefs.nameEl, m.label); - patchText(mRefs.pctEl, m.pctText); - patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); - }, - }); - - refs.rowState.hoverPayload = - total > 0 || callsCount > 0 - ? { - title: displayLabel, - calls: callsCount, - totalTokens: total, - costText, - inputTokens: item.inputTokens, - cacheReadTokens: item.cacheReadTokens, - thinkingTokens: item.thinkingTokens, - responseTokens: item.responseTokens, - outputTokens: item.outputTokens, - segments: partitioned, - } - : null; - patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); - } - - function createTopConversationRow() { - const titleTextEl = h('span', { className: 'cons-row-title-text' }); - const wsBadgeEl = h('span', { className: 'cons-ws-sessions-tag text-mono', hidden: true }); - const titleEl = h('strong', { className: 'cons-row-title cons-top-conv-title' }, [ - titleTextEl, - wsBadgeEl, - ]); - const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); - const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); - const costEl = h('strong', { className: 'cons-row-cost text-mono' }); - const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' }); - const rowState = { cascadeId: '', canJump: false, hoverPayload: null }; - - const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]); - const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true }); - - const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true }); - const callsLbl = h('span', { text: t('cons.footCalls') }); - const callsVal = h('strong', { className: 'text-mono' }); - - const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [ - barHitEl, - h('div', { className: 'cons-item-foot cons-source-foot' }, [ - topModelsEl, - fallbackMetaEl, - h('span', { className: 'legend-left cons-calls-stat' }, [ - callsLbl, - callsVal, - ]), - ]), - ]); - attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState); - - const rowEl = h( - 'div', - { - className: 'cons-top-conv-row', - onClick: () => { - if (!rowState.canJump || !rowState.cascadeId) return; - hideBreakdownPopover(); - selectConversation(rowState.cascadeId); - uiStore.setState({ - activeView: 'steps', - stepsSubTab: 'steps', - selectedAgentScope: 'all', - ctxInspectorAgentId: getDefaultCtxInspectorAgentId( - telemetryStore.getState().telemetry?.settings - ), - }); - }, - }, - [ - h('div', { className: 'panel-header' }, [ - titleEl, - h('span', { className: 'cons-row-metrics' }, [ - pctBadge, - totalTokEl, - costEl, - ]), - ]), - hoverZoneEl, - ] - ); - - return { - el: rowEl, - refs: { - rowEl, - titleEl, - titleTextEl, - wsBadgeEl, - pctBadge, - totalTokEl, - costEl, - hoverZoneEl, - barHitEl, - trackEl, - topModelsEl, - fallbackMetaEl, - callsLbl, - callsVal, - rowState, - }, - }; - } - - function updateTopConversationRow(refs, item, bases, modelColorMap, sortMode = 'cost') { - patchText(refs.callsLbl, t('cons.footCalls')); - const isWorkspaceRow = Boolean(item.isWorkspaceRow); - const title = isWorkspaceRow - ? item.isUnbound - ? t('cons.workspaceUnbound') - : String(item.label || item.workspacePath || '—').trim() - : String(item.title || item.cascadeId || '—').trim(); - refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || ''); - refs.rowState.canJump = - !isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId); - patchClasses(refs.rowEl, { - 'is-jumpable': refs.rowState.canJump, - 'cons-workspace-row': isWorkspaceRow, - }); - const baseTip = - isWorkspaceRow && item.workspacePath && item.workspacePath !== title - ? `${title} (${item.workspacePath})` - : title; - patchAttr( - refs.rowEl, - 'title', - refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip - ); - patchText(refs.titleTextEl, title); - if (refs.wsBadgeEl) { - const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0; - patchAttr(refs.wsBadgeEl, 'hidden', !showWsBadge); - if (showWsBadge) { - patchText(refs.wsBadgeEl, t('cons.workspaceSessions', { count: item.sessionCount })); - } - } - - const total = Number(item.totalTokens || 0); - const costVal = Number(item.costUsd || 0); - const callsCount = Number(item.calls || 0); - const isAllUnpriced = - callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0); - const costText = formatUsd(isAllUnpriced ? null : costVal, { - precise: costVal > 0 && costVal < 0.1, - }); - - const tokBase = Number(bases?.tokens || 0); - const costBase = Number(bases?.cost || 0); - const useCostBasis = sortMode === 'cost' && costBase > 0; - const share = useCostBasis - ? +((costVal / costBase) * 100).toFixed(1) - : tokBase > 0 - ? +((total / tokBase) * 100).toFixed(1) - : 0; - const scaleRatio = useCostBasis - ? costVal > 0 - ? Math.min(1, Math.max(0.01, costVal / costBase)) - : 0 - : tokBase > 0 && total > 0 - ? Math.min(1, Math.max(0.01, total / tokBase)) - : 0; - - patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true })); - if (sortMode === 'tokens') { - patchText(refs.totalTokEl, costText); - patchText(refs.costEl, formatTokensPrecise(total)); - } else { - patchText(refs.totalTokEl, formatTokensPrecise(total)); - patchText(refs.costEl, costText); - } - patchText(refs.callsVal, String(callsCount)); - - // 复用客户端来源同款按模型配色分段进度条、Top 2-3 模型速览及共享悬浮详情浮层 - const convModels = Array.isArray(item.mergedModels) ? item.mergedModels : []; - const partitioned = partitionModelSegments(convModels, modelColorMap, { - maxMain: 5, - minSharePct: 1.5, - }); - const barItems = - partitioned.length > 0 - ? partitioned.map((seg) => ({ - key: seg.key, - segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0, - color: seg.color, - })) - : scaleRatio > 0 - ? [ - { - key: '__conv_fallback__', - segPct: scaleRatio * 100, - color: 'var(--accent-primary)', - }, - ] - : []; - - patchKeyedList(refs.trackEl, barItems, { - keyFn: (seg) => seg.key, - sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`, - createRow: createSourceModelSegment, - updateRow: (segRefs, seg) => { - patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`); - patchStyleVar(segRefs.segEl, '--seg-color', seg.color); - }, - }); - - const topModels = partitioned - .filter((seg) => !seg.isOther) - .slice(0, 3) - .map((seg) => ({ - key: seg.key, - label: seg.label, - pctText: formatCompactSourceSharePct(seg.pct), - color: seg.color, - })); - patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0); - patchKeyedList(refs.topModelsEl, topModels, { - keyFn: (m) => m.key, - sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`, - createRow: createSourceTopModelItem, - updateRow: (mRefs, m) => { - patchStyleVar(mRefs.dotEl, '--dot-color', m.color); - patchText(mRefs.nameEl, m.label); - patchText(mRefs.pctEl, m.pctText); - patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`); - }, - }); - - const showFallbackMeta = topModels.length === 0; - patchAttr(refs.fallbackMetaEl, 'hidden', !showFallbackMeta); - if (showFallbackMeta) { - const srcLabel = item.sourceName || item.appSource || ''; - const cacheLabel = t('cons.topConvCacheMeta', { - pct: formatPctNumber(item.cacheHitPct ?? 0), - }); - patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel); - } - - refs.rowState.hoverPayload = - partitioned.length > 0 && (total > 0 || callsCount > 0) - ? { - title, - calls: callsCount, - totalTokens: total, - costText, - inputTokens: item.inputTokens, - cacheReadTokens: item.cacheReadTokens, - thinkingTokens: item.thinkingTokens, - responseTokens: item.responseTokens, - outputTokens: item.outputTokens, - segments: partitioned, - } - : null; - patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) }); - } + }, + }); let latestSlice = null; let isDirty = false; @@ -36966,6 +36955,30 @@ const ConsumptionView = defineComponent({ patchAttr(topConvsEmptyEl, 'hidden', !showSessionsTab || sortedTopConvs.length > 0); patchText(topConvsEmptyEl, t('cons.topConvsEmpty')); + const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRankingKey = showWorkspacesTab + ? 'workspaces' + : showSessionsTab + ? 'sessions' + : 'models'; + const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`; + const activeRankingEl = showWorkspacesTab + ? workspacesListEl + : showSessionsTab + ? sortedTopConvs.length > 0 + ? topConvsListEl + : topConvsEmptyEl + : modelsListEl; + + const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig; + const tabSwitched = + hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey; + const sortSwitched = + hasCompletedInitialDraw && + !rangeSwitched && + !tabSwitched && + nextSortSig !== lastAnimatedSortSig; + patchKeyedList(modelsListEl, models, { keyFn: (m) => m.displayText || m.label || m.shortName, sigFn: (m) => @@ -37047,30 +37060,6 @@ const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; - const nextRankingKey = showWorkspacesTab - ? 'workspaces' - : showSessionsTab - ? 'sessions' - : 'models'; - const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`; - const activeRankingEl = showWorkspacesTab - ? workspacesListEl - : showSessionsTab - ? sortedTopConvs.length > 0 - ? topConvsListEl - : topConvsEmptyEl - : modelsListEl; - - const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig; - const tabSwitched = - hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey; - const sortSwitched = - hasCompletedInitialDraw && - !rangeSwitched && - !tabSwitched && - nextSortSig !== lastAnimatedSortSig; - if (tabSwitched || sortSwitched) { triggerConsAnim(activeRankingEl, 'is-bars-revealing'); } @@ -39697,25 +39686,17 @@ const App = defineComponent({ return { App }; })(); -// --- src/components/layout/WindowOverlayShell.js --- -const { computeCapsuleLayoutMode, mountWindowOverlay } = (() => { +// --- src/components/layout/overlayHostAnchors.js --- +const { CAPSULE_HOST_ID, PORTAL_HOST_ID, computeCapsuleLayoutMode, isImmediatelyBeforeNode, isIdeExtensionChatFrame, resolveActiveDockTarget, findNativeTopRightAnchor, getLeftSidebarRightEdge, attachShadowStyles } = (() => { /** - * @fileoverview 主窗口双栖挂载外壳 (WindowOverlayShell.js). - * - * 采用「分离式双 Shadow Host」架构,彻底规避宿主顶栏层叠上下文 (`z-0` / `overflow: hidden`) 裁切与路由重绘卸载问题: - * 1. `#ag-usage-monitor-capsule`:轻量顶栏胶囊,优先内嵌停靠至 `[class*="@container/titlebar"]` 右侧按钮组, - * 支持四级迟滞宽度自适应折叠(`wide` -> `compact` -> `minimal` -> `ring-only`),找不到顶栏时自动回退至右上角固定定位; - * 2. `#ag-usage-monitor-portal`:常驻 `document.body` 顶层的无遮挡浮层宿主,承载悬停速览卡与完整四标签 `App()` 监控面板, - * 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。 + * @fileoverview Host IDE/Desktop titlebar & composer button anchor discovery, + * 4-stage responsive capsule hysteresis, and shared ShadowRoot CSSStyleSheet mounting + * extracted from WindowOverlayShell.js. */ const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule'; const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; -const FLOATING_CARD_WIDTH = 522; -const POPOVER_BASE_WIDTH = 540; -const POPOVER_MAX_AUTO_WIDTH = 960; -const MULTI_PANEL_WIDTH = 464; /** * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 @@ -40290,7 +40271,7 @@ function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patch const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null; const activeRouteId = extractHostRouteCascadeId(); - // 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏与 Auto / 右簇发送按钮 + // 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏和 Auto / 右簇发送按钮 const rawEditors = querySimpleSelectorList(document, [ 'textarea', '[contenteditable]', @@ -40574,7 +40555,7 @@ function getLeftSidebarRightEdge(vw) { } /** - * 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 + * 在主窗口挂载双栖顶栏胶囊和完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 */ const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([ 'src/styles/views-overview.css', @@ -40620,6 +40601,29 @@ function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) { styleEl.textContent = slimCapsule ? buildSlimCapsuleCss(fullCss) : fullCss; shadowRoot.appendChild(styleEl); } +return { CAPSULE_HOST_ID, PORTAL_HOST_ID, computeCapsuleLayoutMode, isImmediatelyBeforeNode, isIdeExtensionChatFrame, resolveActiveDockTarget, findNativeTopRightAnchor, getLeftSidebarRightEdge, attachShadowStyles }; +})(); + +// --- src/components/layout/WindowOverlayShell.js --- +const { mountWindowOverlay } = (() => { +/** + * @fileoverview 主窗口双栖挂载外壳 (WindowOverlayShell.js). + * + * 采用「分离式双 Shadow Host」架构,彻底规避宿主顶栏层叠上下文 (`z-0` / `overflow: hidden`) 裁切与路由重绘卸载问题: + * 1. `#ag-usage-monitor-capsule`:轻量顶栏胶囊,优先内嵌停靠至 `[class*="@container/titlebar"]` 右侧按钮组, + * 支持四级迟滞宽度自适应折叠(`wide` -> `compact` -> `minimal` -> `ring-only`),找不到顶栏时自动回退至右上角固定定位; + * 2. `#ag-usage-monitor-portal`:常驻 `document.body` 顶层的无遮挡浮层宿主,承载悬停速览卡与完整四标签 `App()` 监控面板, + * 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。 + */ + + + + +const FLOATING_CARD_WIDTH = 522; +const POPOVER_BASE_WIDTH = 540; +const POPOVER_MAX_AUTO_WIDTH = 960; +const MULTI_PANEL_WIDTH = 464; + function mountWindowOverlay() { if (typeof window === 'undefined' || typeof document === 'undefined') return null; @@ -42675,7 +42679,7 @@ function mountWindowOverlay() { window[WINDOW_OVERLAY_KEY] = handle; return handle; } -return { computeCapsuleLayoutMode, mountWindowOverlay }; +return { mountWindowOverlay }; })(); // --- src/main.js --- diff --git a/sidecars/panel/backend/file-exporter.mjs b/sidecars/panel/backend/file-exporter.mjs index 5ead6ea..4fcec67 100644 --- a/sidecars/panel/backend/file-exporter.mjs +++ b/sidecars/panel/backend/file-exporter.mjs @@ -1,7 +1,7 @@ /** - * @fileoverview 本机安全文本文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。 - * 仅允许导出受控白名单文本扩展名(.json / .csv / .md / .txt),严格清洗文件名防止路径穿越, - * 并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。 + * @fileoverview 本机安全文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。 + * 仅允许导出受控白名单扩展名(.json / .csv / .md / .txt / .xlsx,含 UTF-8 文本和 Base64 二进制工作簿), + * 严格清洗文件名防止路径穿越,并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。 */ import { spawn } from 'node:child_process'; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 676c489..817c021 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index b8fea9d..56bbd33 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -636,6 +636,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/registries/stepColumnRegistry.js', 'src/components/widgets/CapsuleBarWidget.js', 'src/components/widgets/StepTableWidget.js', + 'src/components/widgets/ConsumptionBreakdownRows.js', 'src/components/settings/structurePreviewMock.js', 'src/components/settings/CollapsibleSection.js', 'src/components/settings/EditableSlotList.js', @@ -652,6 +653,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/views/StepsDetailView.js', 'src/views/SettingsView.js', 'src/App.js', + 'src/components/layout/overlayHostAnchors.js', 'src/components/layout/WindowOverlayShell.js', 'src/main.js', ]; diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 7d3230c..3404d0e 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -66,916 +66,25 @@ import { } from '../../store/telemetryStore.js'; import { uiStore } from '../../store/uiStore.js'; -const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule'; -const PORTAL_HOST_ID = 'ag-usage-monitor-portal'; +import { + CAPSULE_HOST_ID, + PORTAL_HOST_ID, + attachShadowStyles, + computeCapsuleLayoutMode, + findNativeTopRightAnchor, + getLeftSidebarRightEdge, + isIdeExtensionChatFrame, + isImmediatelyBeforeNode, + resolveActiveDockTarget, +} from './overlayHostAnchors.js'; + +export { computeCapsuleLayoutMode }; + const FLOATING_CARD_WIDTH = 522; const POPOVER_BASE_WIDTH = 540; const POPOVER_MAX_AUTO_WIDTH = 960; const MULTI_PANEL_WIDTH = 464; -/** - * 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。 - * 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊; - * 当槽位数超过 3 个(4..5 槽)时自动按槽位增量上浮 `wide` 阈值。 - * - * @param {number} availWidth - * @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode - * @param {{ showMulti?: boolean, hasUpdate?: boolean, slotCount?: number }} [options] - * @returns {'wide'|'compact'|'minimal'|'ring-only'} - */ -export function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) { - if (availWidth == null || Number.isNaN(availWidth)) return 'wide'; - const showMulti = options?.showMulti !== false; - const updateReserve = options?.hasUpdate ? 52 : 0; - const slotCount = Number(options?.slotCount || 3); - const extraSlotWidth = slotCount > 3 ? (slotCount - 3) * 58 : 0; - const wideKeep = 256 + extraSlotWidth; - const wideEnter = 272 + extraSlotWidth; - const baseEffWidth = showMulti ? availWidth : availWidth + 76; - const effWidth = baseEffWidth - updateReserve; - if (currentMode === 'wide') { - if (baseEffWidth < 78) return 'ring-only'; - if (effWidth < 196) return 'minimal'; - if (effWidth < wideKeep) return 'compact'; - return 'wide'; - } - if (currentMode === 'compact') { - if (effWidth >= wideEnter) return 'wide'; - if (baseEffWidth < 78) return 'ring-only'; - if (effWidth < 196) return 'minimal'; - return 'compact'; - } - if (currentMode === 'minimal') { - if (effWidth >= wideEnter) return 'wide'; - if (effWidth >= 212) return 'compact'; - if (baseEffWidth < 78) return 'ring-only'; - return 'minimal'; - } - if (effWidth >= wideEnter) return 'wide'; - if (effWidth >= 212) return 'compact'; - if (baseEffWidth >= 92) return 'minimal'; - return 'ring-only'; -} - -function findIdeWorkbenchTitlebar() { - try { - if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { - return null; - } - const workbench = document.querySelector('.monaco-workbench'); - if (!workbench?.querySelector) return null; - const partTitlebar = workbench.querySelector('.part.titlebar'); - if (!partTitlebar?.querySelector) return null; - if (partTitlebar.getBoundingClientRect) { - const pr = partTitlebar.getBoundingClientRect(); - if (pr.width <= 0 || pr.height <= 0) return null; - } - const container = - partTitlebar.querySelector(':scope > .titlebar-container') || - partTitlebar.querySelector('.titlebar-container'); - const rightGroup = - container?.querySelector?.(':scope > .titlebar-right') || - container?.querySelector?.('.titlebar-right'); - if (!container || !rightGroup) return null; - const actionToolbar = - rightGroup.querySelector?.(':scope > .action-toolbar-container') || - rightGroup.querySelector?.('.action-toolbar-container') || - null; - return { - kind: 'ide-titlebar', - workbench, - titlebar: container, - targetContainer: rightGroup, - actionToolbar, - }; - } catch { - return null; - } -} - -function findHostTitlebar() { - try { - if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { - return null; - } - const tb = document.querySelector('[class*="@container/titlebar"]'); - if (tb?.getBoundingClientRect) { - const r = tb.getBoundingClientRect(); - if (r.width <= 0 || r.height <= 0) return null; - } - return tb; - } catch { - return null; - } -} - -const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR = - '.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]'; -const COMPOSER_MODEL_LABEL_RE = - /\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i; -const COMPOSER_MODEL_ATTR_RE = - /\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i; -const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i; -const COMPOSER_MODE_TEXT_RE = - /^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|act|review|confirm|normal|fast|自动|询问|手动|始终允许|受控|规划)(?:\s*(?:mode|模式))?$/i; -const COMPOSER_MODE_ATTR_RE = - /\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i; -const COMPOSER_ICON_FONT_CLASS_RE = - /\b(?:codicon|material-symbols(?:-\w+)?|material-icons(?:-\w+)?|lucide(?:-\w+)?)\b/i; - -function querySimpleSelectorList(root, selectors) { - if (!root || typeof root.querySelectorAll !== 'function') return []; - const seen = new Set(); - const out = []; - for (const sel of selectors) { - let list = []; - try { - list = root.querySelectorAll(sel) || []; - } catch { - list = []; - } - for (const item of list) { - if (item && !seen.has(item)) { - seen.add(item); - out.push(item); - } - } - } - return out; -} - -function extractVisibleButtonText(node, isRoot = true) { - if (!node) return ''; - const tag = String(node.tagName || node.nodeName || '').toLowerCase(); - if (tag === 'svg' || tag === 'style' || tag === 'script') return ''; - if (!isRoot) { - if (node.getAttribute?.('aria-hidden') === 'true') return ''; - const cls = String(node.className || ''); - if (cls && COMPOSER_ICON_FONT_CLASS_RE.test(cls)) return ''; - } - if (tag === '#text' || node.nodeType === 3) { - return String(node.nodeValue ?? node.textContent ?? ''); - } - const childNodes = node.childNodes || node.children; - if (!childNodes || childNodes.length === 0) { - return String(node.textContent || ''); - } - let acc = ''; - for (const ch of childNodes) { - acc += ` ${extractVisibleButtonText(ch, false)}`; - } - return acc; -} - -function cleanComposerButtonText(btn) { - const raw = extractVisibleButtonText(btn, true) - .replace(/[\u200B-\u200D\uFEFF]/g, '') - .replace(/\s+/g, ' ') - .trim(); - if (!raw) return ''; - return raw.replace(/^[⌃⌄▾▴∨∧^<>›‹+\s]+|[⌃⌄▾▴∨∧^<>›‹\s]+$/g, '').trim(); -} - -function isComposerModelButtonItem(item) { - if (!item) return false; - if (item.cleanText && COMPOSER_MODEL_LABEL_RE.test(item.cleanText)) return true; - if (item.attrText && COMPOSER_MODEL_ATTR_RE.test(item.attrText)) return true; - return false; -} - -function hasExcludedComposerAncestor(el) { - if (!el) return false; - if (typeof el.closest === 'function') { - try { - if (el.closest(COMPOSER_EXCLUDED_ANCESTOR_SELECTOR)) return true; - } catch { - // 忽略选择器异常并回退祖先链遍历 - } - } - let cur = el.parentElement || el.parentNode; - while (cur) { - const cls = String(cur.className || ''); - if ( - cls.includes('@container/titlebar') || - cls.includes('quick-input-widget') || - cls.includes('suggest-widget') || - cls.includes('find-widget') || - cls.includes('scm-editor') || - cls.includes('search-view') || - (cls.includes('part') && (cls.includes('titlebar') || cls.includes('statusbar'))) - ) { - return true; - } - cur = cur.parentElement || cur.parentNode; - } - return false; -} - -function isNodeHiddenByStyle(el) { - if (!el) return true; - if (el.hasAttribute?.('hidden') || el.getAttribute?.('aria-hidden') === 'true') return true; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const cs = window.getComputedStyle(el); - if (cs?.display === 'none' || cs?.visibility === 'hidden') return true; - } catch { - // 忽略样式读取异常 - } - } - return false; -} - -function getInFlowHostChildren(container, capsuleNode, portalNode) { - const rawChildren = container?.children || []; - const out = []; - for (const ch of rawChildren) { - if (!ch || ch === capsuleNode || ch === portalNode) continue; - if (ch.id === CAPSULE_HOST_ID || ch.id === PORTAL_HOST_ID) continue; - if (ch.hasAttribute?.('hidden')) continue; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const cs = window.getComputedStyle(ch); - if (cs?.display === 'none') continue; - if (cs?.position === 'absolute' || cs?.position === 'fixed') continue; - } catch { - // 忽略计算样式异常 - } - } - out.push(ch); - } - return out; -} - -function isHorizontalFlexContainer(el) { - if (!el) return false; - const cls = String(el.className || ''); - if (/\b(?:inline-)?flex\b/.test(cls) && !/\bflex-col\b/.test(cls)) return true; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const cs = window.getComputedStyle(el); - const disp = String(cs?.display || ''); - const dir = String(cs?.flexDirection || 'row'); - if (disp.includes('flex') && !dir.startsWith('column')) return true; - } catch { - // 忽略计算样式异常 - } - } - return false; -} - -function isSpaceDistributedFlexContainer(el) { - if (!el) return false; - const cls = String(el.className || ''); - if (/\bjustify-(?:between|around|evenly)\b/.test(cls)) return true; - if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') { - try { - const jc = String(window.getComputedStyle(el)?.justifyContent || ''); - if (jc.includes('space-between') || jc.includes('space-around') || jc.includes('space-evenly')) { - return true; - } - } catch { - // 忽略计算样式异常 - } - } - return false; -} - -function buildComposerDockDescriptor(autoBtn, composerCard, bottomRowBtns, capsuleNode, portalNode, patchedNode) { - if (!autoBtn || !composerCard) return null; - let item = autoBtn; - while ( - (item.parentElement || item.parentNode) && - (item.parentElement || item.parentNode) !== composerCard && - (item.parentElement || item.parentNode) !== document.body - ) { - const parent = item.parentElement || item.parentNode; - const hostSiblings = getInFlowHostChildren(parent, capsuleNode, portalNode); - if (hostSiblings.length >= 2) break; - const grandParent = parent.parentElement || parent.parentNode; - const parentCls = String(parent.className || ''); - const parentInlineMl = String(parent.style?.marginLeft || '').trim(); - const isSingleClusterInSplitRow = - !/\b(?:relative|ml-auto|ms-auto)\b/.test(parentCls) && - parentInlineMl !== 'auto' && - isHorizontalFlexContainer(parent) && - grandParent && - isSpaceDistributedFlexContainer(grandParent) && - getInFlowHostChildren(grandParent, capsuleNode, portalNode).length >= 2; - if (isSingleClusterInSplitRow) { - break; - } - item = parent; - } - - const anchorNode = item; - const targetContainer = anchorNode.parentElement || anchorNode.parentNode; - if (!targetContainer) return null; - - const hostChildren = getInFlowHostChildren(targetContainer, capsuleNode, portalNode); - const anchorIdx = hostChildren.indexOf(anchorNode); - const isFirstHostChild = anchorIdx <= 0; - - let needsAutoMarginTransfer = false; - let patchMarginNode = null; - - if (!isFirstHostChild) { - const cls = String(anchorNode.className || ''); - const inlineMl = String(anchorNode.style?.marginLeft || '').trim(); - let computedLargeMl = false; - if ( - patchedNode !== anchorNode && - typeof window !== 'undefined' && - typeof window.getComputedStyle === 'function' - ) { - try { - const mlPx = parseFloat(window.getComputedStyle(anchorNode)?.marginLeft) || 0; - const prevSib = hostChildren[anchorIdx - 1]; - const aRect = anchorNode.getBoundingClientRect?.(); - const pRect = prevSib?.getBoundingClientRect?.(); - if (mlPx > 24 && aRect && pRect && aRect.left - pRect.right >= mlPx - 6) { - computedLargeMl = true; - } - } catch { - // 忽略边距测量异常 - } - } - - if ( - /\b(?:ml-auto|ms-auto)\b/.test(cls) || - inlineMl === 'auto' || - patchedNode === anchorNode || - computedLargeMl - ) { - needsAutoMarginTransfer = true; - patchMarginNode = anchorNode; - } else if (isSpaceDistributedFlexContainer(targetContainer)) { - needsAutoMarginTransfer = true; - } - } - - const autoRect = anchorNode.getBoundingClientRect?.() || autoBtn.getBoundingClientRect?.(); - let leftClusterRightEdge = 0; - if (autoRect && Array.isArray(bottomRowBtns)) { - for (const entry of bottomRowBtns) { - if (entry.btn === autoBtn || anchorNode.contains?.(entry.btn)) continue; - if (entry.rect.left < autoRect.left - 2 && entry.rect.right <= autoRect.left + 4) { - if (entry.rect.right > leftClusterRightEdge) { - leftClusterRightEdge = entry.rect.right; - } - } - } - } - - return { - kind: 'composer', - workbench: null, - titlebar: composerCard, - targetContainer, - actionToolbar: patchMarginNode, - anchorNode, - needsAutoMarginTransfer, - leftClusterRightEdge, - }; -} - -function buildComposerRightEndDockDescriptor( - leftAnchorBtn, - composerCard, - bottomRowBtns, - capsuleNode, - portalNode -) { - if (!leftAnchorBtn || !composerCard) return null; - const cardRect = composerCard.getBoundingClientRect?.(); - const minRowWidth = cardRect && cardRect.width > 0 ? cardRect.width * 0.65 : 180; - let toolbarRow = null; - let cur = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode; - for (let d = 0; d < 8 && cur && cur !== composerCard && cur !== document.body; d += 1) { - const r = cur.getBoundingClientRect?.(); - if (r && r.width >= minRowWidth && r.height > 0 && r.height <= 60 && isHorizontalFlexContainer(cur)) { - toolbarRow = cur; - break; - } - cur = cur.parentElement || cur.parentNode; - } - if (!toolbarRow) { - const p = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode; - if (!p || !isHorizontalFlexContainer(p)) return null; - toolbarRow = p; - } - - let leftClusterRightEdge = 0; - if (Array.isArray(bottomRowBtns)) { - for (const entry of bottomRowBtns) { - if (entry?.rect?.right > leftClusterRightEdge) { - leftClusterRightEdge = entry.rect.right; - } - } - } - - const rowChildren = getInFlowHostChildren(toolbarRow, capsuleNode, portalNode); - const lastChild = rowChildren.length >= 2 ? rowChildren[rowChildren.length - 1] : null; - if ( - lastChild && - !lastChild.contains?.(leftAnchorBtn) && - isHorizontalFlexContainer(lastChild) && - getInFlowHostChildren(lastChild, capsuleNode, portalNode).length === 0 - ) { - return { - kind: 'composer', - workbench: null, - titlebar: composerCard, - targetContainer: lastChild, - actionToolbar: null, - anchorNode: null, - needsAutoMarginTransfer: false, - leftClusterRightEdge, - }; - } - - return { - kind: 'composer', - workbench: null, - titlebar: composerCard, - targetContainer: toolbarRow, - actionToolbar: null, - anchorNode: null, - needsAutoMarginTransfer: true, - leftClusterRightEdge, - }; -} - -function collectComposerBottomButtons(container, editorEl, editorRect, capsuleNode, portalNode) { - const rawBtns = querySimpleSelectorList(container, ['button', '[role="button"]', '[aria-haspopup]']); - const hostBtns = []; - for (const btn of rawBtns) { - if (!btn || btn === editorEl || editorEl?.contains?.(btn)) continue; - if (editorEl && btn.contains?.(editorEl)) continue; - if ( - btn.id === CAPSULE_HOST_ID || - btn.id === PORTAL_HOST_ID || - capsuleNode?.contains?.(btn) || - portalNode?.contains?.(btn) - ) { - continue; - } - if (isNodeHiddenByStyle(btn)) continue; - // 仅排除嵌套在真实紧凑按钮内部的图标/子触发器,避免外层卡片级 role="button" 误杀工具栏按钮 - let nestedInBtn = false; - let p = btn.parentElement || btn.parentNode; - while (p && p !== container) { - const pTag = String(p.tagName || '').toLowerCase(); - if (pTag === 'button') { - nestedInBtn = true; - break; - } - if ( - (p.getAttribute?.('role') === 'button' || p.hasAttribute?.('aria-haspopup')) && - !(editorEl && p.contains?.(editorEl)) - ) { - const pr = p.getBoundingClientRect?.(); - if (pr && pr.height > 0 && pr.height <= 48 && pr.width > 0 && pr.width <= 360) { - nestedInBtn = true; - break; - } - } - p = p.parentElement || p.parentNode; - } - if (nestedInBtn) continue; - - const br = btn.getBoundingClientRect?.(); - if (!br || br.width <= 0 || br.height <= 0 || br.height > 48) continue; - const centerY = (br.top + br.bottom) / 2; - if (editorRect && centerY < editorRect.top - 4) continue; - hostBtns.push({ - btn, - rect: br, - centerY, - centerX: (br.left + br.right) / 2, - cleanText: cleanComposerButtonText(btn), - attrText: `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(), - }); - } - if (hostBtns.length === 0) return []; - let maxCenterY = -Infinity; - for (const item of hostBtns) { - if (item.centerY > maxCenterY) maxCenterY = item.centerY; - } - const bottomBand = hostBtns.filter((item) => Math.abs(item.centerY - maxCenterY) <= 22); - bottomBand.sort((a, b) => a.rect.left - b.rect.left); - return bottomBand; -} - -function pickAutoButtonFromRow(bottomRowBtns, containerRect, options = undefined) { - if (!Array.isArray(bottomRowBtns) || bottomRowBtns.length === 0) return null; - const requireModelForFallback = Boolean(options?.requireModelForFallback); - const rightSplitX = containerRect ? containerRect.left + containerRect.width * 0.35 : 0; - const rightFirst = [ - ...bottomRowBtns.filter((b) => b.centerX >= rightSplitX), - ...bottomRowBtns.filter((b) => b.centerX < rightSplitX), - ]; - - // Tier 1: 精确文本 Auto / 自动 匹配 - for (const item of rightFirst) { - if (COMPOSER_MODE_EXACT_RE.test(item.cleanText)) { - return { btn: item.btn, tier: 1 }; - } - } - - // Tier 2: 执行/权限模式文案或无障碍语义属性匹配(排除模型选择器按钮) - for (const item of rightFirst) { - if (isComposerModelButtonItem(item)) continue; - if ( - (item.cleanText && COMPOSER_MODE_TEXT_RE.test(item.cleanText)) || - (item.attrText && COMPOSER_MODE_ATTR_RE.test(item.attrText)) - ) { - return { btn: item.btn, tier: 2 }; - } - } - - const hasModelBtn = bottomRowBtns.some(isComposerModelButtonItem); - - // Tier 3: 几何右簇首按钮兜底(适配 Antigravity IDE 无 Auto 按钮、右侧为发送/语音按钮的输入栏布局) - if (bottomRowBtns.length >= 2 && (!requireModelForFallback || hasModelBtn)) { - let maxGap = -Infinity; - let splitIdx = -1; - for (let i = 1; i < bottomRowBtns.length; i += 1) { - const gap = bottomRowBtns[i].rect.left - bottomRowBtns[i - 1].rect.right; - if (gap > maxGap) { - maxGap = gap; - splitIdx = i; - } - } - if (splitIdx >= 1 && maxGap >= 16) { - return { btn: bottomRowBtns[splitIdx].btn, tier: 3 }; - } - } - - // Tier 4: 输入为空时若右侧发送按钮暂时隐藏、仅左侧存在模型选择器按钮,停靠至工具栏最右侧 - if (hasModelBtn && containerRect && containerRect.width >= 200) { - const lastItem = bottomRowBtns[bottomRowBtns.length - 1]; - if (lastItem.rect.right <= containerRect.left + containerRect.width * 0.72) { - return { btn: null, leftAnchorBtn: lastItem.btn, tier: 4 }; - } - } - - return null; -} - -function resolveComposerEditorRect(ed) { - const er = ed?.getBoundingClientRect?.(); - if (er && er.width >= 80 && er.height >= 12) return er; - let cur = ed; - for (let d = 0; d < 6 && cur; d += 1) { - if (String(cur.className || '').includes('monaco-editor')) { - const mr = cur.getBoundingClientRect?.(); - if (mr && mr.width >= 80 && mr.height >= 12) return mr; - break; - } - cur = cur.parentElement || cur.parentNode; - } - return er || null; -} - -function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patchedNode = null) { - try { - if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') { - return null; - } - const capEl = capsuleNode || document.getElementById?.(CAPSULE_HOST_ID) || null; - const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null; - const activeRouteId = extractHostRouteCascadeId(); - - // 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏与 Auto / 右簇发送按钮 - const rawEditors = querySimpleSelectorList(document, [ - 'textarea', - '[contenteditable]', - '[role="textbox"]', - '[data-lexical-editor]', - '.ProseMirror', - '.monaco-editor', - ]); - const scoredEditors = []; - for (const ed of rawEditors) { - if (!ed || capEl?.contains?.(ed) || porEl?.contains?.(ed)) continue; - if (ed.hasAttribute?.('contenteditable')) { - const ce = String(ed.getAttribute('contenteditable') || '').trim().toLowerCase(); - if (ce === 'false' && ed.getAttribute?.('role') !== 'textbox') continue; - } - if (isNodeHiddenByStyle(ed) || hasExcludedComposerAncestor(ed)) continue; - const er = resolveComposerEditorRect(ed); - if (!er || er.width < 100 || er.height < 12 || er.height > 540) continue; - - let score = Math.min(1200, er.width) + Math.max(0, er.bottom) * 0.2; - if (activeRouteId) { - let anc = ed.parentElement || ed.parentNode; - while (anc) { - const cid = anc.getAttribute?.('data-cascade-id'); - if (cid) { - score += cid === activeRouteId ? 4000 : -2000; - break; - } - anc = anc.parentElement || anc.parentNode; - } - } - if ( - document.activeElement && - (ed === document.activeElement || ed.contains?.(document.activeElement)) - ) { - score += 1000; - } - scoredEditors.push({ ed, rect: er, score }); - } - scoredEditors.sort((a, b) => b.score - a.score); - - for (const { ed, rect: er } of scoredEditors) { - const isMonacoCandidate = String(ed.className || '').includes('monaco-editor') || - String(ed.className || '').includes('inputarea'); - let tier3Candidate = null; - let tier4Candidate = null; - let cur = ed.parentElement || ed.parentNode; - for (let depth = 0; depth < 18 && cur; depth += 1) { - if (cur === document.body || cur === document.documentElement) break; - const tag = String(cur.tagName || '').toLowerCase(); - if (tag === 'main' || String(cur.className || '').includes('monaco-workbench')) break; - const cr = cur.getBoundingClientRect?.(); - if (cr && cr.height > 680) break; - if (cr && cr.width >= 180 && cr.height > 0) { - const bottomRowBtns = collectComposerBottomButtons(cur, ed, er, capEl, porEl); - const picked = pickAutoButtonFromRow(bottomRowBtns, cr, { - requireModelForFallback: isMonacoCandidate, - }); - if (picked) { - if (picked.tier <= 2) { - const desc = buildComposerDockDescriptor( - picked.btn, - cur, - bottomRowBtns, - capEl, - porEl, - patchedNode - ); - if (desc) return desc; - } else if (picked.tier === 3 && !tier3Candidate) { - tier3Candidate = { btn: picked.btn, card: cur, bottomRowBtns }; - } else if (picked.tier === 4 && !tier4Candidate) { - tier4Candidate = { leftAnchorBtn: picked.leftAnchorBtn, card: cur, bottomRowBtns }; - } - } - } - cur = cur.parentElement || cur.parentNode; - } - if (tier3Candidate) { - const desc = buildComposerDockDescriptor( - tier3Candidate.btn, - tier3Candidate.card, - tier3Candidate.bottomRowBtns, - capEl, - porEl, - patchedNode - ); - if (desc) return desc; - } - if (tier4Candidate) { - const desc = buildComposerRightEndDockDescriptor( - tier4Candidate.leftAnchorBtn, - tier4Candidate.card, - tier4Candidate.bottomRowBtns, - capEl, - porEl - ); - if (desc) return desc; - } - } - - // 2. 兜底路径:编辑器自定义封装或暂时只读时,直接扫描底部包含模型选择器或 Auto 按钮的输入工具栏 - const vh = Number(window.innerHeight || 800); - const allBtns = querySimpleSelectorList(document, ['button', '[role="button"]', '[aria-haspopup]']); - let modelToolbarFallback = null; - for (const btn of allBtns) { - if (!btn || capEl?.contains?.(btn) || porEl?.contains?.(btn)) continue; - if (isNodeHiddenByStyle(btn) || hasExcludedComposerAncestor(btn)) continue; - const br = btn.getBoundingClientRect?.(); - if (!br || br.width <= 0 || br.height <= 0 || br.height > 48 || br.top < vh * 0.2) continue; - const clean = cleanComposerButtonText(btn); - const attr = `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(); - const itemProbe = { cleanText: clean, attrText: attr }; - const isModeBtn = - COMPOSER_MODE_EXACT_RE.test(clean) || - (!isComposerModelButtonItem(itemProbe) && - ((clean && COMPOSER_MODE_TEXT_RE.test(clean)) || (attr && COMPOSER_MODE_ATTR_RE.test(attr)))); - const isModelBtn = isComposerModelButtonItem(itemProbe); - if (!isModeBtn && !isModelBtn) continue; - - let cur = btn.parentElement || btn.parentNode; - for (let depth = 0; depth < 12 && cur; depth += 1) { - if (cur === document.body || cur === document.documentElement) break; - if (String(cur.className || '').includes('monaco-workbench')) break; - const cr = cur.getBoundingClientRect?.(); - if (!cr || cr.height > 560) break; - if (cr.width >= 200) { - const rowBtns = collectComposerBottomButtons(cur, null, null, capEl, porEl); - if (isModeBtn) { - const hasModelSibling = rowBtns.some((b) => b.btn !== btn && isComposerModelButtonItem(b)); - if (hasModelSibling) { - const desc = buildComposerDockDescriptor(btn, cur, rowBtns, capEl, porEl, patchedNode); - if (desc) return desc; - } - } else if (isModelBtn && !modelToolbarFallback) { - const picked = pickAutoButtonFromRow(rowBtns, cr, { requireModelForFallback: true }); - if (picked) { - const desc = - picked.tier <= 3 && picked.btn - ? buildComposerDockDescriptor(picked.btn, cur, rowBtns, capEl, porEl, patchedNode) - : picked.tier === 4 && picked.leftAnchorBtn - ? buildComposerRightEndDockDescriptor( - picked.leftAnchorBtn, - cur, - rowBtns, - capEl, - porEl - ) - : null; - if (desc) { - if (picked.tier <= 2) return desc; - modelToolbarFallback = desc; - break; - } - } - } - } - cur = cur.parentElement || cur.parentNode; - } - } - if (modelToolbarFallback) return modelToolbarFallback; - } catch { - // 忽略输入框探测异常 - } - return null; -} - -function isImmediatelyBeforeNode(node, refNode) { - if (!node || !refNode) return false; - if (node.nextElementSibling !== undefined) { - return node.nextElementSibling === refNode; - } - if (node.nextSibling !== undefined) { - return node.nextSibling === refNode; - } - const parent = node.parentElement || node.parentNode; - if (!parent?.children) return false; - const idx = Array.prototype.indexOf.call(parent.children, node); - return idx >= 0 && parent.children[idx + 1] === refNode; -} - -function isIdeExtensionChatFrame() { - try { - if (typeof window === 'undefined') return false; - if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true; - return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || '')); - } catch { - return false; - } -} - -function resolveActiveDockTarget(options = undefined) { - const settings = telemetryStore.getState().telemetry?.settings; - const rawMode = - settings?.windowMountMode ?? - readInjectedWindowBridge()?.mountMode; - const mountMode = - options?.mountMode || - normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay); - if (isIdeExtensionChatFrame()) { - if (mountMode !== 'composer') return null; - return findHostComposerAutoTarget( - options?.capsuleNode || null, - options?.portalNode || null, - options?.patchedNode || null - ); - } - if (mountMode === 'composer') { - const composerTarget = findHostComposerAutoTarget( - options?.capsuleNode || null, - options?.portalNode || null, - options?.patchedNode || null - ); - if (composerTarget) return composerTarget; - } - const ideTarget = findIdeWorkbenchTitlebar(); - if (ideTarget) return ideTarget; - const titlebar = findHostTitlebar(); - if (!titlebar) return null; - let targetContainer = titlebar; - try { - const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild; - if (rightGroup && rightGroup !== titlebar.firstElementChild) { - targetContainer = rightGroup; - } - } catch { - // 忽略子选择器不兼容场景 - } - return { - kind: 'flow', - workbench: null, - titlebar, - targetContainer, - actionToolbar: null, - }; -} - -function findNativeTopRightAnchor() { - try { - if (typeof document === 'undefined' || typeof document.querySelector !== 'function') { - return null; - } - const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]'); - if (auxToggle?.closest) { - return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle; - } - const candidates = document.querySelectorAll('button, a, [role="button"]'); - for (const btn of candidates) { - const text = String(btn.textContent || '').trim(); - if ( - (text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) && - btn.getBoundingClientRect?.().top < 52 - ) { - return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn; - } - } - return document.querySelector('div.absolute.right-0.top-0'); - } catch { - return null; - } -} - -function getLeftSidebarRightEdge(vw) { - try { - if (typeof document !== 'undefined' && typeof document.querySelector === 'function') { - if (document.querySelector('.monaco-workbench')) { - return 0; - } - const navEl = document.querySelector('div[role="navigation"]'); - if (navEl?.getBoundingClientRect) { - const nr = navEl.getBoundingClientRect(); - if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) { - return Math.ceil(nr.right); - } - } - } - } catch { - // 忽略侧栏测量异常 - } - return 0; -} - -/** - * 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。 - */ -const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([ - 'src/styles/views-overview.css', - 'src/styles/views-consumption.css', - 'src/styles/views-tables.css', - 'src/styles/views-settings.css', - 'src/styles/controls.css', -]); - -let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null }; - -function buildSlimCapsuleCss(fullCss) { - if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss; - return fullCss - .split(/(?=\/\* --- src\/styles\/)/) - .filter((block) => { - const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//); - return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]); - }) - .join(''); -} - -function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) { - if (!shadowRoot) return; - if ( - fullCss && - typeof CSSStyleSheet === 'function' && - Array.isArray(shadowRoot.adoptedStyleSheets) - ) { - try { - if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) { - const sheet = new CSSStyleSheet(); - sheet.replaceSync(fullCss); - sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet }; - } - shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet]; - return; - } catch { - // 降级到传统