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
This commit is contained in:
fish
2026-11-25 03:42:33 +09:00
parent 1330b31ef7
commit e520efe84e
20 changed files with 4103 additions and 1235 deletions
+1593 -345
View File
File diff suppressed because it is too large Load Diff
@@ -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();
}
+9 -1
View File
@@ -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 };
}
+56 -3
View File
@@ -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?.();
+1
View File
@@ -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)。
@@ -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,
@@ -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
@@ -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,
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795527403692">
<link rel="stylesheet" href="/styles.css?v=1795532361594">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795527403692"></script>
<script src="/app.js?v=1795532361594"></script>
</body>
</html>
+1
View File
@@ -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',
File diff suppressed because it is too large Load Diff
+7
View File
@@ -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',
+7
View File
@@ -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': '保存失败',
@@ -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);
}
+70 -267
View File
@@ -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;
}
File diff suppressed because it is too large Load Diff
+70 -267
View File
@@ -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;
}
+171 -1
View File
@@ -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'
);
});
+5 -4
View File
@@ -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',
@@ -2062,6 +2062,30 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> 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');