fix(panel): preserve sessions and global usage on account switch while isolating quota pools per step

This commit is contained in:
fish
2026-11-18 13:52:16 +09:00
parent 1602897178
commit 612f57fbcb
7 changed files with 299 additions and 89 deletions
+89 -32
View File
@@ -282,6 +282,68 @@ export function loadExternalDeepStatsCache() {
const MAX_CONCURRENT_RPC = 4;
const LEGACY_MIGRATION_BATCH_SIZE = 8;
const stepFieldChecks = new WeakMap();
function normalizeOwnerAccount(value) {
return typeof value === 'string' ? value.trim().toLowerCase() : '';
}
/**
* 为会话步骤维护细粒度账号归属:
* - 已存在于旧缓存中的历史步骤保留原归属账号(兼容跨账号续聊同一会话);
* - 切换账号后在该会话中新产生的步骤写入当前活跃账号 `step.accountName`,仅供「可用额度」按账号隔离统计。
*/
function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountName) {
if (!Array.isArray(steps) || steps.length === 0) return steps;
const activeOwner = normalizeOwnerAccount(currentAccountName);
const entryOwner = normalizeOwnerAccount(entryAccountName);
const prevOwner = normalizeOwnerAccount(prev?.accountName);
const prevSteps = Array.isArray(prev?.steps) ? prev.steps : [];
if (prevSteps.length === 0) {
const initialOwner = prevOwner || activeOwner || entryOwner;
if (!initialOwner || initialOwner === entryOwner) return steps;
return steps.map((s) => ({ ...s, accountName: initialOwner }));
}
const prevByIndex = new Map();
let maxPrevStepIndex = -1;
let maxPrevCreatedAtMs = 0;
for (const ps of prevSteps) {
if (!ps || typeof ps !== 'object') continue;
const idx = Number(ps.stepIndex);
if (Number.isFinite(idx)) {
prevByIndex.set(idx, ps);
if (idx > maxPrevStepIndex) maxPrevStepIndex = idx;
}
const cMs = Number(ps.createdAtMs || 0);
if (cMs > maxPrevCreatedAtMs) maxPrevCreatedAtMs = cMs;
}
let mutated = false;
const out = steps.map((s) => {
const idx = Number(s?.stepIndex);
const matchedPrev = Number.isFinite(idx) ? prevByIndex.get(idx) : null;
let stepOwner = '';
if (matchedPrev) {
stepOwner = normalizeOwnerAccount(matchedPrev.accountName) || prevOwner;
} else {
const cMs = Number(s?.createdAtMs || 0);
const isHistoricalBackfill =
(Number.isFinite(idx) && maxPrevStepIndex >= 0 && idx <= maxPrevStepIndex) ||
(cMs > 0 && maxPrevCreatedAtMs > 0 && cMs <= maxPrevCreatedAtMs);
stepOwner = isHistoricalBackfill ? prevOwner || activeOwner : activeOwner || prevOwner;
}
const storedAccount = stepOwner && stepOwner !== entryOwner ? stepOwner : undefined;
if (s?.accountName === storedAccount) return s;
mutated = true;
if (storedAccount) {
return { ...s, accountName: storedAccount };
}
const { accountName: _removed, ...rest } = s;
return rest;
});
return mutated ? out : steps;
}
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
const FAILED_RPC_COOLDOWN_MS = 60_000;
const ACTIVE_FAILED_RPC_COOLDOWN_MS = 15_000;
@@ -1227,15 +1289,8 @@ export async function enumerateAndSyncConversations({
}
}
// 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表
// 从所有本地缓存会话收集 subagentRefs,确保跨账号切换时历史会话与派生子代理均不丢失
for (const [, entry] of listCachedTrajectoryEntries()) {
if (
entry?.accountName &&
currentAccountName !== '' &&
entry.accountName !== currentAccountName
) {
continue;
}
for (const ref of entry?.subagentRefs || []) {
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
if (refCid && !canonicalIdByLower.has(refCid)) {
@@ -1253,13 +1308,6 @@ export async function enumerateAndSyncConversations({
const item = summariesByLower.get(cidLower);
const localSum = item ? null : localSummaryByLower.get(cidLower) || null;
const cached = getCachedTrajectory(cascadeId);
if (
cached?.accountName &&
currentAccountName !== '' &&
cached.accountName !== currentAccountName
) {
continue;
}
const diskFiles = diskConvMap.get(cidLower) || [];
const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null;
const dbPath = sqliteDbInfo?.dbPath || '';
@@ -1296,6 +1344,7 @@ export async function enumerateAndSyncConversations({
localSum?.parentConversationId ||
localSum?.forkParentConversationId ||
cached?.parentConversationId ||
cached?.parentCascadeId ||
''
).toLowerCase();
const rawRootCid = String(
@@ -1332,6 +1381,7 @@ export async function enumerateAndSyncConversations({
const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null;
const isSubagent =
isSideQuestion ||
Boolean(cached?.isSubagent) ||
Boolean(parentConversationId) ||
Boolean(rootConversationId && rootConversationId !== cidLower);
const latestLocalTouchMs = Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0);
@@ -1676,20 +1726,27 @@ export async function enumerateAndSyncConversations({
liveActivityMemo.delete(cidLower);
}
const entryAccountName = prev ? prev.accountName || '' : currentAccountName || '';
const stepsWithOwners = attachStepAccountOwners(
steps,
prev,
currentAccountName,
entryAccountName
);
const cacheEntry = {
signature: finalSig,
accountName: prev?.accountName || currentAccountName || '',
accountName: entryAccountName,
title: conv.title,
lastModifiedMs: resolvedLastModMs,
diskMtimeMs:
conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(cidLower)),
rawStepCount: conv.rawStepCount ?? steps.length,
rawStepCount: conv.rawStepCount ?? stepsWithOwners.length,
wasRunning: isRunning,
contextLimitTelemetry: true,
speedClearedTelemetry: true,
turnRailTelemetry: true,
contextGroupsTelemetry: 2,
steps,
steps: stepsWithOwners,
subagentRefs,
};
if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig;
@@ -1723,7 +1780,7 @@ export async function enumerateAndSyncConversations({
!prev.turnRailTelemetry ||
!prev.contextGroupsTelemetry ||
metaChanged ||
!isDeepStrictEqual(prev.steps, steps);
!isDeepStrictEqual(prev.steps, stepsWithOwners);
if (!stepsChanged) cacheEntry.steps = prev.steps;
setCachedTrajectory(conv.cascadeId, cacheEntry);
@@ -1738,13 +1795,6 @@ export async function enumerateAndSyncConversations({
for (const ext of loadExternalDeepStatsCache().values()) {
const extCid = String(ext?.cascadeId || '').toLowerCase();
if (!extCid) continue;
if (
ext.accountName &&
currentAccountName !== '' &&
ext.accountName !== currentAccountName
) {
continue;
}
const existingExt = lazyExternalByLower.get(extCid);
if (!existingExt || (ext.steps?.length || 0) > (existingExt.steps?.length || 0)) {
lazyExternalByLower.set(extCid, ext);
@@ -1775,10 +1825,18 @@ export async function enumerateAndSyncConversations({
Boolean(conv.parentConversationId) ||
Boolean(conv.rootConversationId && conv.rootConversationId !== cidLower);
const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles);
const offlineAccountName = prev
? prev.accountName || offlineFallback.accountName || ''
: offlineFallback.accountName || currentAccountName || '';
const offlineStepsWithOwners = attachStepAccountOwners(
offlineFallback.steps,
prev,
offlineFallback.accountName || currentAccountName,
offlineAccountName
);
const offlineEntry = {
signature: sig,
accountName:
prev?.accountName || offlineFallback.accountName || currentAccountName || '',
accountName: offlineAccountName,
title: offlineFallback.title,
...(offlineFallback.appSource ? { appSource: offlineFallback.appSource } : {}),
lastModifiedMs: offlineFallback.lastModifiedMs,
@@ -1790,7 +1848,7 @@ export async function enumerateAndSyncConversations({
speedClearedTelemetry: true,
turnRailTelemetry: true,
contextGroupsTelemetry: 2,
steps: offlineFallback.steps,
steps: offlineStepsWithOwners,
subagentRefs: offlineFallback.subagentRefs,
};
if (conv.isSubagent) {
@@ -2296,9 +2354,8 @@ export async function enumerateAndSyncConversations({
))) ||
conversations[0] ||
null;
const requestedOwner = getCachedTrajectory(canonicalIdByLower.get(reqLower))?.accountName;
const safeReqId = requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) &&
(!requestedOwner || currentAccountName === '' || requestedOwner === currentAccountName) ? requestedConvId : null;
const safeReqId =
requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) ? requestedConvId : null;
const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null;
return {
+22 -13
View File
@@ -98,13 +98,13 @@ function readTrajectoryModelFacts(steps) {
}
/** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */
function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
function buildKnownUpstreamModelMap(contextLimits) {
const knownUpstreamByModelKey = new Map();
for (const [, entry] of listCachedTrajectoryEntries()) {
if (!entry?.steps?.length) continue;
const facts = readTrajectoryModelFacts(entry.steps);
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
if (entry.subagentSpec || (entry.accountName && entry.accountName !== currentAccountName)) continue;
if (entry.subagentSpec) continue;
if (facts.limits) {
for (const [key, limit] of facts.limits) {
const previous = contextLimits.get(key);
@@ -785,7 +785,7 @@ export async function buildTelemetryPayloadInternal(
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
const reportedContextLimits = new Map();
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName);
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits);
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
const activeSteps = activeEntry?.steps || [];
const subagentSummaries = activeConvSummary?.subagents || [];
@@ -1188,6 +1188,7 @@ export async function buildTelemetryPayloadInternal(
currentYear,
monthlySeries,
weekBucket,
quotaWeekBucket,
modelBreakdown,
poolCycleStats,
poolsWeeklySummary,
@@ -1536,6 +1537,7 @@ export async function buildTelemetryPayloadInternal(
});
}
const officialFallbackWeekBucket = quotaWeekBucket || weekBucket;
const finalPayload = {
timestamp: new Date().toISOString(),
hostPlatform: process.platform || 'unknown',
@@ -1657,19 +1659,26 @@ export async function buildTelemetryPayloadInternal(
title: isCustomWeeklyMode
? '每周限额 (自定义本机)'
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
calls: !isCustomWeeklyMode && poolsWeeklySummary ? poolsWeeklySummary.calls : weekBucket.calls,
tokens:
!isCustomWeeklyMode && poolsWeeklySummary
calls: isCustomWeeklyMode
? weekBucket.calls
: poolsWeeklySummary
? poolsWeeklySummary.calls
: officialFallbackWeekBucket.calls,
tokens: isCustomWeeklyMode
? weekBucket.totalTokens
: poolsWeeklySummary
? poolsWeeklySummary.tokens
: weekBucket.totalTokens,
costUsd:
!isCustomWeeklyMode && poolsWeeklySummary
: officialFallbackWeekBucket.totalTokens,
costUsd: isCustomWeeklyMode
? weekBucket.costUsd
: poolsWeeklySummary
? poolsWeeklySummary.costUsd
: weekBucket.costUsd,
unpricedCalls:
!isCustomWeeklyMode && poolsWeeklySummary
: officialFallbackWeekBucket.costUsd,
unpricedCalls: isCustomWeeklyMode
? weekBucket.unpricedCalls
: poolsWeeklySummary
? poolsWeeklySummary.unpricedCalls
: weekBucket.unpricedCalls,
: officialFallbackWeekBucket.unpricedCalls,
usedPct: weeklyUsedPct,
remainingPct: weeklyRemainingPct,
remainingIntPct: weeklyRemainingIntPct,
+35 -20
View File
@@ -30,6 +30,10 @@ function safeTok(val) {
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
}
function normalizeOwnerAccount(val) {
return typeof val === 'string' ? val.trim().toLowerCase() : '';
}
/**
* 获取本地当日 00:00:00.000 的毫秒时间戳。
*
@@ -399,7 +403,8 @@ function sameUsageEntries(previous, current) {
return previous.length === current.length && current.every((entry, index) => {
const before = previous[index];
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
entry.appSource === before.appSource && entry.isCurrentConv === before.isCurrentConv;
entry.appSource === before.appSource && entry.accountName === before.accountName &&
entry.isCurrentConv === before.isCurrentConv;
});
}
@@ -515,6 +520,9 @@ export function aggregateMultiWindowUsage({
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
const poolByModel = new Map();
const quotaWeekBucket = createUsageBucket();
const normalizedQuotaAccount =
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
const perModelStats = new Map();
@@ -563,15 +571,6 @@ export function aggregateMultiWindowUsage({
for (const ext of externalConvos.values()) {
const extCidLower = String(ext?.cascadeId || '').toLowerCase();
if (!extCidLower) continue;
const knownLive = allLiveByLower.get(extCidLower);
const ownerAccount = ext.accountName || knownLive?.accountName || '';
if (
ownerAccount &&
currentAccountName !== '' &&
ownerAccount !== currentAccountName
) {
continue;
}
const prevExt = externalByCid.get(extCidLower);
if (!prevExt || (ext.steps?.length || 0) > (prevExt.steps?.length || 0)) {
externalByCid.set(extCidLower, ext);
@@ -581,13 +580,6 @@ export function aggregateMultiWindowUsage({
const allEntriesToAggregate = [];
for (const [cidLower, entry] of allLiveByLower.entries()) {
if (
entry?.accountName &&
currentAccountName !== '' &&
entry.accountName !== currentAccountName
) {
continue;
}
const extMatch = externalByCid.get(cidLower);
if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) {
continue;
@@ -598,6 +590,7 @@ export function aggregateMultiWindowUsage({
allEntriesToAggregate.push({
cascadeId: groupCascadeId,
appSource: entry?.appSource || 'standalone',
accountName: entry?.accountName || extMatch?.accountName || '',
steps: entry?.steps || [],
isCurrentConv: familySet.has(cidLower),
});
@@ -611,6 +604,7 @@ export function aggregateMultiWindowUsage({
allEntriesToAggregate.push({
cascadeId: extCidLower,
appSource: ext.appSource || 'ide',
accountName: ext.accountName || liveEntry?.accountName || '',
steps: ext.steps || [],
isCurrentConv: familySet.has(extCidLower),
});
@@ -624,7 +618,9 @@ export function aggregateMultiWindowUsage({
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
const snapshot = lastUsageSnapshot;
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
currentYear === snapshot.currentYear && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
currentYear === snapshot.currentYear &&
normalizedQuotaAccount === snapshot.normalizedQuotaAccount &&
modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
@@ -645,11 +641,19 @@ export function aggregateMultiWindowUsage({
for (const entry of allEntriesToAggregate) {
const { cascadeId, isCurrentConv } = entry;
const entryOwner = normalizeOwnerAccount(entry.accountName);
const srcKey = entry.appSource || 'standalone';
const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
for (const st of entry.steps || []) {
if (!st || typeof st !== 'object') continue;
const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner;
const includeInQuotaPools =
normalizedQuotaAccount === null
? false
: normalizedQuotaAccount === ''
? true
: stepOwner === normalizedQuotaAccount;
const mInfo = resolveStepModel(st);
const inTok = safeTok(st.inputTokens);
const cacheTok = safeTok(st.cacheReadTokens);
@@ -698,10 +702,13 @@ export function aggregateMultiWindowUsage({
if (isCurrentConv) {
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId);
}
if (k === 'week' && includeInQuotaPools) {
accumulateStepIntoBucket(quotaWeekBucket, stepUsage, cascadeId);
}
}
}
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
if (includeInQuotaPools && poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
let cachedPool = poolByModel.get(mInfo);
if (!cachedPool || cachedPool.key !== st.modelKey ||
cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) {
@@ -961,6 +968,7 @@ export function aggregateMultiWindowUsage({
const todayBucket = finalizedPresets.today.account;
const weekBucket = finalizedPresets.week.account;
const finalizedQuotaWeekBucket = finalizeUsageBucket(quotaWeekBucket);
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
const formatCycleSummary = (b) => {
@@ -1014,6 +1022,7 @@ export function aggregateMultiWindowUsage({
monthlySeries,
todayBucket,
weekBucket,
quotaWeekBucket: finalizedQuotaWeekBucket,
modelBreakdown,
poolCycleStats,
poolsWeeklySummary,
@@ -1021,7 +1030,13 @@ export function aggregateMultiWindowUsage({
if (modelInputs) {
if (!sameSnapshot) {
lastUsageSnapshot = {
timeZone, modelInputs, currentYear, entries: allEntriesToAggregate, dates: null, ranges: new Map(),
timeZone,
modelInputs,
currentYear,
normalizedQuotaAccount,
entries: allEntriesToAggregate,
dates: null,
ranges: new Map(),
};
}
const { ranges } = lastUsageSnapshot;