mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): filter family-group and external usage from quota reservation
This commit is contained in:
+61
-8
@@ -1467,6 +1467,12 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'quota.ratePopSamples': '{n} 样本',
|
'quota.ratePopSamples': '{n} 样本',
|
||||||
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。',
|
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。',
|
||||||
'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。',
|
'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。',
|
||||||
|
'quota.ratePopSharedBadge': '共享活跃',
|
||||||
|
'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示',
|
||||||
|
'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占',
|
||||||
|
'quota.ratePopExternalBaseline': '检测到本周期存在家庭组 / 其他设备消耗,预占和费率仅按本机实测校准',
|
||||||
|
'quota.ratePopExt5h': '5h {pct}%',
|
||||||
|
'quota.ratePopExtWk': '周限 {pct}%',
|
||||||
|
|
||||||
// Live Activity Widget
|
// Live Activity Widget
|
||||||
'live.currentSession': '当前会话',
|
'live.currentSession': '当前会话',
|
||||||
@@ -2355,6 +2361,12 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'quota.ratePopSamples': '{n} samples',
|
'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.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.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 Activity Widget
|
||||||
'live.currentSession': 'Current Session',
|
'live.currentSession': 'Current Session',
|
||||||
@@ -19285,7 +19297,8 @@ const QuotaPoolsWidget = defineComponent({
|
|||||||
const hasPoolFallback =
|
const hasPoolFallback =
|
||||||
models.length === 0 &&
|
models.length === 0 &&
|
||||||
(Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd));
|
(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 poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool';
|
||||||
const rows =
|
const rows =
|
||||||
@@ -19301,7 +19314,8 @@ const QuotaPoolsWidget = defineComponent({
|
|||||||
samples: item.samples,
|
samples: item.samples,
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
: [
|
: hasPoolFallback
|
||||||
|
? [
|
||||||
createRateModelCard({
|
createRateModelCard({
|
||||||
name: t('quota.ratePopPoolFallback'),
|
name: t('quota.ratePopPoolFallback'),
|
||||||
isMutedName: true,
|
isMutedName: true,
|
||||||
@@ -19312,16 +19326,55 @@ const QuotaPoolsWidget = defineComponent({
|
|||||||
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
|
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
|
||||||
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
|
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
|
||||||
}),
|
}),
|
||||||
];
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
populatedGroups.push(
|
const headChildren = [h('div', { className: 'quota-rate-pool-label', text: poolLabel })];
|
||||||
h('div', { className: 'quota-rate-pool-group' }, [
|
if (ext?.activeRecently) {
|
||||||
h('div', { className: 'quota-rate-pool-label', text: poolLabel }),
|
headChildren.push(
|
||||||
h('div', { className: 'quota-rate-model-list' }, rows),
|
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) {
|
if (populatedGroups.length === 0) {
|
||||||
ratePopBodyEl.appendChild(
|
ratePopBodyEl.appendChild(
|
||||||
h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') })
|
h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') })
|
||||||
|
|||||||
@@ -41,6 +41,22 @@ export const QR_CONSUME_MIN_SHORTFALL_PCT = 0.03;
|
|||||||
export const QR_CONSUME_SHORTFALL_RATIO = 0.35;
|
export const QR_CONSUME_SHORTFALL_RATIO = 0.35;
|
||||||
export const QR_MODEL_RATE_MIN_UI_SAMPLES = 3;
|
export const QR_MODEL_RATE_MIN_UI_SAMPLES = 3;
|
||||||
export const QR_MODEL_SINGLE_DOMINANCE_RATIO = 0.95;
|
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_MODELS_PER_BUCKET = 16;
|
||||||
const QR_MAX_TRACKED_BUCKETS = 128;
|
const QR_MAX_TRACKED_BUCKETS = 128;
|
||||||
const QR_MAX_ACTIVE_LEASES = 16;
|
const QR_MAX_ACTIVE_LEASES = 16;
|
||||||
@@ -74,14 +90,29 @@ function qrResolveExactUsedPct(poolObj, win) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function qrSumLeases(leases) {
|
function qrSumLeases(leases, { includeTentative = true } = {}) {
|
||||||
let sum = 0;
|
let sum = 0;
|
||||||
for (let i = 0; i < leases.length; i += 1) {
|
for (let i = 0; i < leases.length; i += 1) {
|
||||||
|
if (!includeTentative && leases[i]?.tentative) continue;
|
||||||
sum += Math.max(0, Number(leases[i]?.remainingPct) || 0);
|
sum += Math.max(0, Number(leases[i]?.remainingPct) || 0);
|
||||||
}
|
}
|
||||||
return sum;
|
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) {
|
function qrConsumeLeasesFifo(leases, amountPct) {
|
||||||
let left = Math.max(0, Number(amountPct) || 0);
|
let left = Math.max(0, Number(amountPct) || 0);
|
||||||
if (left <= 0 || leases.length === 0) return 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)) {
|
if (state.ratePctPerUsd !== null && Number.isFinite(state.ratePctPerUsd)) {
|
||||||
return 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 qrClampRate(officialUsedPct / cycleCostUsd);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -164,16 +196,20 @@ function qrPruneExpiredLeases(state, nowMs) {
|
|||||||
for (let i = state.activeLeases.length - 1; i >= 0; i -= 1) {
|
for (let i = state.activeLeases.length - 1; i >= 0; i -= 1) {
|
||||||
const lease = state.activeLeases[i];
|
const lease = state.activeLeases[i];
|
||||||
const lastActiveMs = lease.lastTouchedMs || lease.createdAtMs || 0;
|
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 idleExpired = lastActiveMs > 0 && nowMs - lastActiveMs >= QR_LEASE_IDLE_EXPIRY_MS;
|
||||||
const maxAgeExpired = nowMs - (lease.createdAtMs || 0) >= QR_LEASE_MAX_AGE_MS;
|
const maxAgeExpired = nowMs - (lease.createdAtMs || 0) >= QR_LEASE_MAX_AGE_MS;
|
||||||
if (idleExpired || maxAgeExpired) {
|
if (tentativeExpired || idleExpired || maxAgeExpired) {
|
||||||
state.activeLeases.splice(i, 1);
|
state.activeLeases.splice(i, 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function qrFormatOutput(state, officialUsedPct) {
|
function qrFormatOutput(state, officialUsedPct) {
|
||||||
const rawSum = qrSumLeases(state.activeLeases);
|
const rawSum = qrSumLeases(state.activeLeases, { includeTentative: false });
|
||||||
let dropOffset = 0;
|
let dropOffset = 0;
|
||||||
if (state.pendingDrop && Number.isFinite(state.pendingDrop.preDropUsedPct)) {
|
if (state.pendingDrop && Number.isFinite(state.pendingDrop.preDropUsedPct)) {
|
||||||
const costSinceDrop = Math.max(
|
const costSinceDrop = Math.max(
|
||||||
@@ -197,7 +233,10 @@ function qrFormatOutput(state, officialUsedPct) {
|
|||||||
}
|
}
|
||||||
const rounded = qrClamp(qrRound1(rawReserved), 0, qrRound1(officialUsedPct));
|
const rounded = qrClamp(qrRound1(rawReserved), 0, qrRound1(officialUsedPct));
|
||||||
let earliestExpiresAtMs = null;
|
let earliestExpiresAtMs = null;
|
||||||
|
let visibleCount = 0;
|
||||||
for (let i = 0; i < state.activeLeases.length; i += 1) {
|
for (let i = 0; i < state.activeLeases.length; i += 1) {
|
||||||
|
if (state.activeLeases[i]?.tentative) continue;
|
||||||
|
visibleCount += 1;
|
||||||
const exp =
|
const exp =
|
||||||
(state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) +
|
(state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) +
|
||||||
QR_LEASE_TTL_MS;
|
QR_LEASE_TTL_MS;
|
||||||
@@ -207,7 +246,7 @@ function qrFormatOutput(state, officialUsedPct) {
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
reservedPct: rounded,
|
reservedPct: rounded,
|
||||||
reservedLeaseCount: state.activeLeases.length,
|
reservedLeaseCount: visibleCount,
|
||||||
reservedExpiresAtMs: earliestExpiresAtMs,
|
reservedExpiresAtMs: earliestExpiresAtMs,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -229,6 +268,10 @@ function qrSanitizePersistedLeases(rawLeases) {
|
|||||||
createdAtMs,
|
createdAtMs,
|
||||||
lastTouchedMs,
|
lastTouchedMs,
|
||||||
sessionCount: Math.max(1, Number(item.sessionCount) || 1),
|
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;
|
return out;
|
||||||
@@ -353,7 +396,7 @@ function qrEstimateModelWeightedPct(st, deltaModelCosts, totalDeltaCostUsd, fall
|
|||||||
return weightedPct + unattributedCost * fallbackRate;
|
return weightedPct + unattributedCost * fallbackRate;
|
||||||
}
|
}
|
||||||
|
|
||||||
function qrBuildPoolRateEstimate(st5h, stWk) {
|
function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) {
|
||||||
const raw5hPool =
|
const raw5hPool =
|
||||||
st5h && st5h.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st5h.ratePctPerUsd)
|
st5h && st5h.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st5h.ratePctPerUsd)
|
||||||
? st5h.ratePctPerUsd
|
? st5h.ratePctPerUsd
|
||||||
@@ -425,7 +468,28 @@ function qrBuildPoolRateEstimate(st5h, stWk) {
|
|||||||
delete m._rawRw;
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -437,9 +501,83 @@ function qrBuildPoolRateEstimate(st5h, stWk) {
|
|||||||
samples5h: st5h?.rateSamples || 0,
|
samples5h: st5h?.rateSamples || 0,
|
||||||
samplesWeekly: stWk?.rateSamples || 0,
|
samplesWeekly: stWk?.rateSamples || 0,
|
||||||
models,
|
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 } = {}) {
|
function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) {
|
||||||
if (!raw || typeof raw !== 'object') return null;
|
if (!raw || typeof raw !== 'object') return null;
|
||||||
const lastOfficial =
|
const lastOfficial =
|
||||||
@@ -484,6 +622,10 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) {
|
|||||||
lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0),
|
lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0),
|
||||||
lastRefundAtMs: Math.max(0, Number(raw.lastRefundAtMs) || 0),
|
lastRefundAtMs: Math.max(0, Number(raw.lastRefundAtMs) || 0),
|
||||||
lastRefundPct: Math.max(0, Number(raw.lastRefundPct) || 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,
|
lastBounceAtMs: st.lastBounceAtMs,
|
||||||
lastRefundAtMs: st.lastRefundAtMs,
|
lastRefundAtMs: st.lastRefundAtMs,
|
||||||
lastRefundPct: st.lastRefundPct,
|
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 {
|
return {
|
||||||
@@ -572,12 +718,15 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
eventKind === 'idle' ||
|
eventKind === 'idle' ||
|
||||||
eventKind === 'lag_pending' ||
|
eventKind === 'lag_pending' ||
|
||||||
eventKind === 'drop_pending' ||
|
eventKind === 'drop_pending' ||
|
||||||
eventKind === 'replica_flip'
|
eventKind === 'replica_flip' ||
|
||||||
|
eventKind === 'lease_tentative'
|
||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const isUrgent =
|
const isUrgent =
|
||||||
eventKind === 'lease' ||
|
eventKind === 'lease' ||
|
||||||
|
eventKind === 'lease_rejected' ||
|
||||||
|
eventKind === 'external_usage' ||
|
||||||
eventKind === 'refund' ||
|
eventKind === 'refund' ||
|
||||||
eventKind === 'reset' ||
|
eventKind === 'reset' ||
|
||||||
eventKind === 'expire';
|
eventKind === 'expire';
|
||||||
@@ -633,6 +782,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
lastBounceAtMs: 0,
|
lastBounceAtMs: 0,
|
||||||
lastRefundAtMs: 0,
|
lastRefundAtMs: 0,
|
||||||
lastRefundPct: 0,
|
lastRefundPct: 0,
|
||||||
|
hasExternalUsage: false,
|
||||||
|
lastExternalUsageAtMs: 0,
|
||||||
|
externalUsedPct: 0,
|
||||||
|
externalEvents: 0,
|
||||||
};
|
};
|
||||||
buckets.set(bucketKey, st);
|
buckets.set(bucketKey, st);
|
||||||
return st;
|
return st;
|
||||||
@@ -651,6 +804,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
poolLastActivityMs = 0,
|
poolLastActivityMs = 0,
|
||||||
activeSessionCount10m = 0,
|
activeSessionCount10m = 0,
|
||||||
recent10mCostUsd = 0,
|
recent10mCostUsd = 0,
|
||||||
|
hasRunningLocalSession = false,
|
||||||
|
forceExternalJump = false,
|
||||||
|
peerLastExternalUsageAtMs = 0,
|
||||||
nowMs = Date.now(),
|
nowMs = Date.now(),
|
||||||
}) {
|
}) {
|
||||||
if (officialUsedPct === null || !Number.isFinite(officialUsedPct)) {
|
if (officialUsedPct === null || !Number.isFinite(officialUsedPct)) {
|
||||||
@@ -723,12 +879,17 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.pendingModelCostsUsd = {};
|
st.pendingModelCostsUsd = {};
|
||||||
st.activeLeases = [];
|
st.activeLeases = [];
|
||||||
st.pendingDrop = null;
|
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);
|
const out = qrFormatOutput(st, safeUsed);
|
||||||
recordLog('reset', { deltaOfficial: safeUsed - prevUsed, ...out });
|
recordLog('reset', { deltaOfficial: safeUsed - prevUsed, ...out });
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(不入中位数样本池)
|
// 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(检测到外部消耗时跳过累计比值反推)
|
||||||
if (st.lastOfficialUsedPct === null) {
|
if (st.lastOfficialUsedPct === null) {
|
||||||
st.resetTimeMs = safeResetMs;
|
st.resetTimeMs = safeResetMs;
|
||||||
st.lastQuotaTs = safeFetchTs;
|
st.lastQuotaTs = safeFetchTs;
|
||||||
@@ -736,7 +897,12 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.lastCycleCostUsd = safeCost;
|
st.lastCycleCostUsd = safeCost;
|
||||||
st.lastModelCostsUsd = safeModelCosts;
|
st.lastModelCostsUsd = safeModelCosts;
|
||||||
st.lastUnpricedCalls = safeUnpriced;
|
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.ratePctPerUsd = qrClampRate(safeUsed / safeCost);
|
||||||
st.rateSamples = 1;
|
st.rateSamples = 1;
|
||||||
}
|
}
|
||||||
@@ -822,8 +988,29 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
let excessPct = deltaOfficial - expectedDeltaPct;
|
let excessPct = deltaOfficial - expectedDeltaPct;
|
||||||
const isIdleRefundReady =
|
const isIdleRefundReady =
|
||||||
poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS;
|
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';
|
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 = () => {
|
const clearPendingCost = () => {
|
||||||
st.pendingCostUsd = 0;
|
st.pendingCostUsd = 0;
|
||||||
st.pendingCostAtMs = 0;
|
st.pendingCostAtMs = 0;
|
||||||
@@ -851,6 +1038,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
|
|
||||||
if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) {
|
if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) {
|
||||||
// 4A. 同周期余额回升:区分「静默到期真退还」及「活跃期双副本回落待确认」
|
// 4A. 同周期余额回升:区分「静默到期真退还」及「活跃期双副本回落待确认」
|
||||||
|
if (st.activeLeases.length > 0) {
|
||||||
|
qrConfirmAllLeases(st.activeLeases);
|
||||||
|
}
|
||||||
const prevHigh = st.pendingDrop
|
const prevHigh = st.pendingDrop
|
||||||
? Math.max(st.pendingDrop.preDropUsedPct, st.lastOfficialUsedPct)
|
? Math.max(st.pendingDrop.preDropUsedPct, st.lastOfficialUsedPct)
|
||||||
: st.lastOfficialUsedPct;
|
: st.lastOfficialUsedPct;
|
||||||
@@ -898,22 +1088,35 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
safeUsed >= reboundFloor;
|
safeUsed >= reboundFloor;
|
||||||
|
|
||||||
if (isReplicaRebound) {
|
if (isReplicaRebound) {
|
||||||
|
if (st.activeLeases.length > 0) {
|
||||||
|
qrConfirmAllLeases(st.activeLeases);
|
||||||
|
}
|
||||||
const excessAboveHighWater = safeUsed - (pd.preDropUsedPct + expectedSinceDrop);
|
const excessAboveHighWater = safeUsed - (pd.preDropUsedPct + expectedSinceDrop);
|
||||||
st.pendingDrop = null;
|
st.pendingDrop = null;
|
||||||
st.lastBounceAtMs = nowMs;
|
st.lastBounceAtMs = nowMs;
|
||||||
clearPendingCost();
|
clearPendingCost();
|
||||||
if (rate !== null && excessAboveHighWater >= QR_MIN_JUMP_EXCESS_PCT) {
|
if (rate !== null && excessAboveHighWater >= QR_MIN_JUMP_EXCESS_PCT) {
|
||||||
|
if (!hasLocalPoolActivity || forceExternalJump) {
|
||||||
|
recordExternalDelta(excessAboveHighWater);
|
||||||
|
eventKind = 'external_usage';
|
||||||
|
} else {
|
||||||
|
const isTentative = externalActiveRecently;
|
||||||
st.activeLeases.push({
|
st.activeLeases.push({
|
||||||
amountPct: excessAboveHighWater,
|
amountPct: excessAboveHighWater,
|
||||||
remainingPct: excessAboveHighWater,
|
remainingPct: excessAboveHighWater,
|
||||||
createdAtMs: nowMs,
|
createdAtMs: nowMs,
|
||||||
lastTouchedMs: nowMs,
|
lastTouchedMs: nowMs,
|
||||||
sessionCount: Math.max(1, safeSess10m || 1),
|
sessionCount: Math.max(1, safeSess10m || 1),
|
||||||
|
confirmed: false,
|
||||||
|
tentative: isTentative,
|
||||||
|
unabsorbedNormalSteps: 0,
|
||||||
|
unabsorbedExpectedPct: 0,
|
||||||
});
|
});
|
||||||
if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) {
|
if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) {
|
||||||
st.activeLeases.splice(0, 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 {
|
} else {
|
||||||
eventKind = 'replica_flip';
|
eventKind = 'replica_flip';
|
||||||
}
|
}
|
||||||
@@ -951,7 +1154,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (deltaOfficial > 1e-3) {
|
} 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 detectedWithRate = rate !== null && excessPct >= QR_MIN_JUMP_EXCESS_PCT;
|
||||||
const detectedColdStart =
|
const detectedColdStart =
|
||||||
rate === null &&
|
rate === null &&
|
||||||
@@ -963,30 +1168,70 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
expectedDeltaPct > 0 &&
|
expectedDeltaPct > 0 &&
|
||||||
shortfall >= Math.max(QR_CONSUME_MIN_SHORTFALL_PCT, expectedDeltaPct * QR_CONSUME_SHORTFALL_RATIO);
|
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 leaseRemaining = detectedWithRate ? excessPct : deltaOfficial;
|
||||||
|
const isTentative = externalActiveRecently;
|
||||||
st.activeLeases.push({
|
st.activeLeases.push({
|
||||||
amountPct: leaseRemaining,
|
amountPct: leaseRemaining,
|
||||||
remainingPct: leaseRemaining,
|
remainingPct: leaseRemaining,
|
||||||
createdAtMs: nowMs,
|
createdAtMs: nowMs,
|
||||||
lastTouchedMs: nowMs,
|
lastTouchedMs: nowMs,
|
||||||
sessionCount: Math.max(1, safeSess10m || 1),
|
sessionCount: Math.max(1, safeSess10m || 1),
|
||||||
|
confirmed: false,
|
||||||
|
tentative: isTentative,
|
||||||
|
unabsorbedNormalSteps: 0,
|
||||||
|
unabsorbedExpectedPct: 0,
|
||||||
});
|
});
|
||||||
if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) {
|
if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) {
|
||||||
st.activeLeases.splice(0, 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) {
|
} else if (isSignificantShortfall) {
|
||||||
// 租约期内出现明显低于预期的官方增量:仅把显著缺口计入当前租约内消费
|
// 租约期内出现明显低于预期的官方增量:佐证租约存在并把显著缺口计入当前租约内消费
|
||||||
|
qrConfirmAllLeases(st.activeLeases);
|
||||||
qrConsumeLeasesFifo(st.activeLeases, shortfall);
|
qrConsumeLeasesFifo(st.activeLeases, shortfall);
|
||||||
for (let i = 0; i < st.activeLeases.length; i += 1) {
|
for (let i = 0; i < st.activeLeases.length; i += 1) {
|
||||||
st.activeLeases[i].lastTouchedMs = nowMs;
|
st.activeLeases[i].lastTouchedMs = nowMs;
|
||||||
}
|
}
|
||||||
eventKind = 'consume';
|
eventKind = 'consume';
|
||||||
} else {
|
} 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 =
|
const outsideBounceCooldown =
|
||||||
st.lastBounceAtMs === 0 || nowMs - st.lastBounceAtMs >= QR_RATE_BOUNCE_COOLDOWN_MS;
|
st.lastBounceAtMs === 0 || nowMs - st.lastBounceAtMs >= QR_RATE_BOUNCE_COOLDOWN_MS;
|
||||||
if (
|
if (
|
||||||
|
!rejectedLease &&
|
||||||
st.activeLeases.length === 0 &&
|
st.activeLeases.length === 0 &&
|
||||||
outsideBounceCooldown &&
|
outsideBounceCooldown &&
|
||||||
!pendingValid &&
|
!pendingValid &&
|
||||||
@@ -1003,7 +1248,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
mr.lastSeenMs = nowMs;
|
mr.lastSeenMs = nowMs;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
eventKind = 'normal';
|
eventKind = rejectedLease ? 'lease_rejected' : 'normal';
|
||||||
}
|
}
|
||||||
clearPendingCost();
|
clearPendingCost();
|
||||||
} else if (rawDeltaCost > 0) {
|
} else if (rawDeltaCost > 0) {
|
||||||
@@ -1021,6 +1266,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
}
|
}
|
||||||
const sinceMs = hasBufferedLeaseCost ? st.pendingCostSinceMs : nowMs;
|
const sinceMs = hasBufferedLeaseCost ? st.pendingCostSinceMs : nowMs;
|
||||||
if (nowMs - sinceMs >= QR_CONSUME_LAG_GRACE_MS) {
|
if (nowMs - sinceMs >= QR_CONSUME_LAG_GRACE_MS) {
|
||||||
|
qrConfirmAllLeases(st.activeLeases);
|
||||||
const consumedPct = qrEstimateModelWeightedPct(st, accModelCosts, accCost, rate);
|
const consumedPct = qrEstimateModelWeightedPct(st, accModelCosts, accCost, rate);
|
||||||
expectedDeltaPct = consumedPct;
|
expectedDeltaPct = consumedPct;
|
||||||
excessPct = deltaOfficial - expectedDeltaPct;
|
excessPct = deltaOfficial - expectedDeltaPct;
|
||||||
@@ -1055,6 +1301,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
nowMs - st.pendingCostSinceMs >= QR_CONSUME_LAG_GRACE_MS
|
nowMs - st.pendingCostSinceMs >= QR_CONSUME_LAG_GRACE_MS
|
||||||
) {
|
) {
|
||||||
// 4C-2. 无新增花费但已跨过 25s 延迟观察窗且官方仍原地踏步:确认此前缓冲成本已在租约内消化
|
// 4C-2. 无新增花费但已跨过 25s 延迟观察窗且官方仍原地踏步:确认此前缓冲成本已在租约内消化
|
||||||
|
qrConfirmAllLeases(st.activeLeases);
|
||||||
const consumedPct = qrEstimateModelWeightedPct(
|
const consumedPct = qrEstimateModelWeightedPct(
|
||||||
st,
|
st,
|
||||||
st.pendingModelCostsUsd,
|
st.pendingModelCostsUsd,
|
||||||
@@ -1104,10 +1351,13 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
accountScope = '',
|
accountScope = '',
|
||||||
quotaPoolsMap = null,
|
quotaPoolsMap = null,
|
||||||
poolCycleStats = null,
|
poolCycleStats = null,
|
||||||
|
runningPoolKeys = null,
|
||||||
|
hasUnknownRunningPool = false,
|
||||||
quotaFetchedAtMs = 0,
|
quotaFetchedAtMs = 0,
|
||||||
nowMs = Date.now(),
|
nowMs = Date.now(),
|
||||||
} = {}) {
|
} = {}) {
|
||||||
if (!(quotaPoolsMap instanceof Map) || quotaPoolsMap.size === 0) return;
|
if (!(quotaPoolsMap instanceof Map) || quotaPoolsMap.size === 0) return;
|
||||||
|
ensureHydrated();
|
||||||
const normalizedAccountScope = String(accountScope || '').trim().toLowerCase();
|
const normalizedAccountScope = String(accountScope || '').trim().toLowerCase();
|
||||||
const scopePrefix = `${String(endpointId || 'local')}::${normalizedAccountScope}`;
|
const scopePrefix = `${String(endpointId || 'local')}::${normalizedAccountScope}`;
|
||||||
|
|
||||||
@@ -1118,9 +1368,52 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
const poolLastActivityMs = Number(recent10m?.lastActivityMs) || 0;
|
const poolLastActivityMs = Number(recent10m?.lastActivityMs) || 0;
|
||||||
const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0;
|
const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0;
|
||||||
const recent10mCostUsd = Number(recent10m?.costUsd) || 0;
|
const recent10mCostUsd = Number(recent10m?.costUsd) || 0;
|
||||||
|
const hasRunningLocalSession = Boolean(
|
||||||
|
hasUnknownRunningPool ||
|
||||||
|
(runningPoolKeys instanceof Set && runningPoolKeys.has(poolKey))
|
||||||
|
);
|
||||||
|
|
||||||
const key5h = `${scopePrefix}::${poolKey}::5h`;
|
const key5h = `${scopePrefix}::${poolKey}::5h`;
|
||||||
|
const keyWk = `${scopePrefix}::${poolKey}::weekly`;
|
||||||
const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null;
|
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 =
|
const res5h =
|
||||||
used5hExact !== null
|
used5hExact !== null
|
||||||
? observeBucket({
|
? observeBucket({
|
||||||
@@ -1128,20 +1421,26 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
poolKey,
|
poolKey,
|
||||||
win: '5h',
|
win: '5h',
|
||||||
officialUsedPct: used5hExact,
|
officialUsedPct: used5hExact,
|
||||||
resetTimeMs: parseIsoMs(poolObj.resetTime),
|
resetTimeMs: reset5hMs,
|
||||||
quotaFetchedAtMs,
|
quotaFetchedAtMs,
|
||||||
cycleCostUsd: pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0,
|
cycleCostUsd: cost5hUsd,
|
||||||
modelCostsUsd: pStats?.modelCosts5h || null,
|
modelCostsUsd: modelCosts5h,
|
||||||
unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0,
|
unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0,
|
||||||
poolLastActivityMs,
|
poolLastActivityMs,
|
||||||
activeSessionCount10m,
|
activeSessionCount10m,
|
||||||
recent10mCostUsd,
|
recent10mCostUsd,
|
||||||
|
hasRunningLocalSession,
|
||||||
|
forceExternalJump: isProportionalExternal,
|
||||||
|
peerLastExternalUsageAtMs: peerExtTs5h,
|
||||||
nowMs,
|
nowMs,
|
||||||
})
|
})
|
||||||
: { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null };
|
: { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null };
|
||||||
|
|
||||||
const keyWk = `${scopePrefix}::${poolKey}::weekly`;
|
const updated5hExtTs = Math.max(
|
||||||
const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null;
|
peerExtTsWk,
|
||||||
|
Number(buckets.get(key5h)?.lastExternalUsageAtMs) || 0
|
||||||
|
);
|
||||||
|
|
||||||
const resWk =
|
const resWk =
|
||||||
usedWkExact !== null
|
usedWkExact !== null
|
||||||
? observeBucket({
|
? observeBucket({
|
||||||
@@ -1149,14 +1448,17 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
poolKey,
|
poolKey,
|
||||||
win: 'weekly',
|
win: 'weekly',
|
||||||
officialUsedPct: usedWkExact,
|
officialUsedPct: usedWkExact,
|
||||||
resetTimeMs: parseIsoMs(poolObj.weeklyResetTime),
|
resetTimeMs: resetWkMs,
|
||||||
quotaFetchedAtMs,
|
quotaFetchedAtMs,
|
||||||
cycleCostUsd: pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0,
|
cycleCostUsd: costWkUsd,
|
||||||
modelCostsUsd: pStats?.modelCostsWeekly || null,
|
modelCostsUsd: modelCostsWk,
|
||||||
unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0,
|
unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0,
|
||||||
poolLastActivityMs,
|
poolLastActivityMs,
|
||||||
activeSessionCount10m,
|
activeSessionCount10m,
|
||||||
recent10mCostUsd,
|
recent10mCostUsd,
|
||||||
|
hasRunningLocalSession,
|
||||||
|
forceExternalJump: isProportionalExternal,
|
||||||
|
peerLastExternalUsageAtMs: updated5hExtTs,
|
||||||
nowMs,
|
nowMs,
|
||||||
})
|
})
|
||||||
: { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null };
|
: { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null };
|
||||||
@@ -1167,7 +1469,11 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
poolObj.weeklyReservedPct = resWk.reservedPct;
|
poolObj.weeklyReservedPct = resWk.reservedPct;
|
||||||
poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount;
|
poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount;
|
||||||
poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs;
|
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,
|
rateSamples: st.rateSamples,
|
||||||
reservedPct: out.reservedPct,
|
reservedPct: out.reservedPct,
|
||||||
leases: out.reservedLeaseCount,
|
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 } : {}),
|
...(Object.keys(byModel).length > 0 ? { byModel } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1729,11 +1729,57 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
poolObj.cycleWeekly = pStats?.cycleWeekly || createEmptyCycleSummary();
|
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({
|
updatePoolQuotaReservationEstimates({
|
||||||
endpointId,
|
endpointId,
|
||||||
accountScope: accountScope || '',
|
accountScope: accountScope || '',
|
||||||
quotaPoolsMap,
|
quotaPoolsMap,
|
||||||
poolCycleStats,
|
poolCycleStats,
|
||||||
|
runningPoolKeys,
|
||||||
|
hasUnknownRunningPool,
|
||||||
quotaFetchedAtMs: officialQuotaInfo?.fetchedAtMs || 0,
|
quotaFetchedAtMs: officialQuotaInfo?.fetchedAtMs || 0,
|
||||||
nowMs: Date.now(),
|
nowMs: Date.now(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1795426864084">
|
<link rel="stylesheet" href="/styles.css?v=1795451677737">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1795426864084"></script>
|
<script src="/app.js?v=1795451677737"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -648,7 +648,8 @@ export const QuotaPoolsWidget = defineComponent({
|
|||||||
const hasPoolFallback =
|
const hasPoolFallback =
|
||||||
models.length === 0 &&
|
models.length === 0 &&
|
||||||
(Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd));
|
(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 poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool';
|
||||||
const rows =
|
const rows =
|
||||||
@@ -664,7 +665,8 @@ export const QuotaPoolsWidget = defineComponent({
|
|||||||
samples: item.samples,
|
samples: item.samples,
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
: [
|
: hasPoolFallback
|
||||||
|
? [
|
||||||
createRateModelCard({
|
createRateModelCard({
|
||||||
name: t('quota.ratePopPoolFallback'),
|
name: t('quota.ratePopPoolFallback'),
|
||||||
isMutedName: true,
|
isMutedName: true,
|
||||||
@@ -675,16 +677,55 @@ export const QuotaPoolsWidget = defineComponent({
|
|||||||
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
|
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
|
||||||
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
|
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
|
||||||
}),
|
}),
|
||||||
];
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
populatedGroups.push(
|
const headChildren = [h('div', { className: 'quota-rate-pool-label', text: poolLabel })];
|
||||||
h('div', { className: 'quota-rate-pool-group' }, [
|
if (ext?.activeRecently) {
|
||||||
h('div', { className: 'quota-rate-pool-label', text: poolLabel }),
|
headChildren.push(
|
||||||
h('div', { className: 'quota-rate-model-list' }, rows),
|
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) {
|
if (populatedGroups.length === 0) {
|
||||||
ratePopBodyEl.appendChild(
|
ratePopBodyEl.appendChild(
|
||||||
h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') })
|
h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') })
|
||||||
|
|||||||
@@ -208,6 +208,12 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'quota.ratePopSamples': '{n} samples',
|
'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.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.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 Activity Widget
|
||||||
'live.currentSession': 'Current Session',
|
'live.currentSession': 'Current Session',
|
||||||
|
|||||||
@@ -208,6 +208,12 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'quota.ratePopSamples': '{n} 样本',
|
'quota.ratePopSamples': '{n} 样本',
|
||||||
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。',
|
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。',
|
||||||
'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。',
|
'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。',
|
||||||
|
'quota.ratePopSharedBadge': '共享活跃',
|
||||||
|
'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示',
|
||||||
|
'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占',
|
||||||
|
'quota.ratePopExternalBaseline': '检测到本周期存在家庭组 / 其他设备消耗,预占和费率仅按本机实测校准',
|
||||||
|
'quota.ratePopExt5h': '5h {pct}%',
|
||||||
|
'quota.ratePopExtWk': '周限 {pct}%',
|
||||||
|
|
||||||
// Live Activity Widget
|
// Live Activity Widget
|
||||||
'live.currentSession': '当前会话',
|
'live.currentSession': '当前会话',
|
||||||
|
|||||||
@@ -738,12 +738,51 @@
|
|||||||
border-top: 1px solid var(--border-hairline);
|
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 {
|
.quota-rate-pool-label {
|
||||||
font-size: var(--fs-2xs);
|
font-size: var(--fs-2xs);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-muted);
|
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 {
|
.quota-rate-model-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -2456,12 +2456,51 @@ html[data-standalone="true"] .app-shell {
|
|||||||
border-top: 1px solid var(--border-hairline);
|
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 {
|
.quota-rate-pool-label {
|
||||||
font-size: var(--fs-2xs);
|
font-size: var(--fs-2xs);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-muted);
|
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 {
|
.quota-rate-model-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -783,11 +783,123 @@ test('experimentalQuotaReservation setting defaults true and round-trips through
|
|||||||
assert.equal(disabledParsed.patch.experimentalQuotaReservation, false);
|
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;
|
let now = T0;
|
||||||
const h = backendHarness({
|
const h = backendHarness({
|
||||||
clock: () => now,
|
clock: () => now,
|
||||||
userStatus: { email: 'tester@example.com', userTier: { name: 'Google AI Ultra' } },
|
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: {
|
quotaSummary: {
|
||||||
groups: [
|
groups: [
|
||||||
{
|
{
|
||||||
@@ -813,11 +925,9 @@ test('backendHarness buildTelemetry populates reservedPct on pools across offici
|
|||||||
|
|
||||||
const p1 = await h.buildTelemetryPayloadInternal(null, true);
|
const p1 = await h.buildTelemetryPayloadInternal(null, true);
|
||||||
const g1 = p1.quotas.pools.find((p) => p.poolKey === 'Gemini');
|
const g1 = p1.quotas.pools.find((p) => p.poolKey === 'Gemini');
|
||||||
assert.equal(p1.settings.experimentalQuotaReservation, true);
|
|
||||||
assert.equal(g1.reservedPct, 0);
|
assert.equal(g1.reservedPct, 0);
|
||||||
assert.equal(g1.weeklyReservedPct, 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;
|
now += 20_000;
|
||||||
h.state.quotaSummary = {
|
h.state.quotaSummary = {
|
||||||
groups: [
|
groups: [
|
||||||
@@ -1490,3 +1600,383 @@ test('QuotaPoolsWidget renders circle-? hover popover for account-isolated model
|
|||||||
globalThis.window = origWindow;
|
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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user