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