diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index e44d9b6..6d35eba 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -3716,12 +3716,6 @@ async function requestTelemetry(params, force) { consecutivePollFailures = 0; const latestSt = telemetryStore.getState(); - const previousAccount = latestSt.telemetry?.account; - const nextAccount = payload?.account; - const accountChanged = previousAccount?.status === 'signedIn' && - (nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' && - (previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name))); - const accountPatch = accountChanged ? { selectedConversationId: '' } : {}; if (force) { const elapsed = Date.now() - startMs; if (elapsed < 220) { @@ -3732,7 +3726,6 @@ async function requestTelemetry(params, force) { } if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ - ...accountPatch, telemetry: payload, minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', @@ -3745,7 +3738,6 @@ async function requestTelemetry(params, force) { const isSame = isEquivalentTelemetry(latestSt.telemetry, payload); const nextTelemetry = isSame ? latestSt.telemetry : payload; telemetryStore.setState({ - ...accountPatch, telemetry: nextTelemetry, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 9b0ed06..f805b66 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -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 { diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 8084893..4e986e5 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -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, diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 77d4268..2cf9c5b 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -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; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 1246fb6..727c19a 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index a565a3c..052232e 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1031,12 +1031,6 @@ async function requestTelemetry(params, force) { consecutivePollFailures = 0; const latestSt = telemetryStore.getState(); - const previousAccount = latestSt.telemetry?.account; - const nextAccount = payload?.account; - const accountChanged = previousAccount?.status === 'signedIn' && - (nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' && - (previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name))); - const accountPatch = accountChanged ? { selectedConversationId: '' } : {}; if (force) { const elapsed = Date.now() - startMs; if (elapsed < 220) { @@ -1047,7 +1041,6 @@ async function requestTelemetry(params, force) { } if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ - ...accountPatch, telemetry: payload, minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', @@ -1060,7 +1053,6 @@ async function requestTelemetry(params, force) { const isSame = isEquivalentTelemetry(latestSt.telemetry, payload); const nextTelemetry = isSame ? latestSt.telemetry : payload; telemetryStore.setState({ - ...accountPatch, telemetry: nextTelemetry, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 6d94293..2b0c33c 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -130,7 +130,9 @@ test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as assert.equal(quotaPoolsMap.get('Gemini')?.isAvailable, true); }); -test('BUG-02 & BUG-11: ide: external sessions do not double-count live conversations, cross-account entries are isolated, and orphan subagents never leak to top-level list', async () => { +test('BUG-02 & BUG-11: ide: external sessions do not double-count live conversations, only quota pools isolate cross-account entries, and orphan subagents never leak to top-level list', async () => { + const reset5hIso = new Date(Date.now() + 4 * 3600_000).toISOString(); + const resetWkIso = new Date(Date.now() + 6 * 24 * 3600_000).toISOString(); const stepObj = { status: 'CORTEX_STEP_STATUS_DONE', metadata: { @@ -147,6 +149,17 @@ test('BUG-02 & BUG-11: ide: external sessions do not double-count live con }; const h = backendHarness({ userStatus: { email: 'alice@example.com' }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.9, resetTime: reset5hIso }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.95, resetTime: resetWkIso }, + ], + }, + ], + }, deepStats: { accountName: 'alice@example.com', perConvo: { @@ -159,7 +172,7 @@ test('BUG-02 & BUG-11: ide: external sessions do not double-count live con { ts: doneIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 }, ], }, - // Different account -> must be excluded when logged in as alice@example.com! + // Different account -> retained in global consumption, isolated out of Alice's quota pools! 'ide:bob-conv': { accountName: 'bob@example.com', appSource: 'ide', @@ -187,10 +200,18 @@ test('BUG-02 & BUG-11: ide: external sessions do not double-count live con }); const p = await h.buildTelemetryPayloadInternal('abcd-1234', false, { range: 'all' }); - // ide:AbCd-1234 has 2 entries vs live abcd-1234's 1 step -> deduplicated (no 1 + 2 = 3 double counting!), bob excluded! - assert.equal(p.consumption.account.conversationsCount, 1); - assert.equal(p.consumption.account.calls, 2); - assert.equal(p.consumption.account.totalTokens, 70_000); + // ide:AbCd-1234 (70k) deduplicates live abcd-1234 (35k); global consumption retains ide:bob-conv (100k) + orphan-sub (35k) + assert.equal(p.consumption.account.conversationsCount, 3); + assert.equal(p.consumption.account.calls, 4); + assert.equal(p.consumption.account.totalTokens, 205_000); + // Quota pools & weekly cycle strictly isolate to alice@example.com (2 calls = 70,000 tokens) + const geminiPool = p.quotas.pools.find((pool) => pool.poolKey === 'Gemini'); + assert.equal(geminiPool.cycle5h.calls, 2); + assert.equal(geminiPool.cycle5h.tokens, 70_000); + assert.equal(geminiPool.cycleWeekly.calls, 2); + assert.equal(geminiPool.cycleWeekly.tokens, 70_000); + assert.equal(p.quotas.weekly.calls, 2); + assert.equal(p.quotas.weekly.tokens, 70_000); assert.equal( p.conversations.some((c) => c.cascadeId === 'orphan-sub'), false, @@ -198,6 +219,130 @@ test('BUG-02 & BUG-11: ide: external sessions do not double-count live con ); }); +test('account switch preserves conversation list, locked session steps, and consumption history while isolating quota pools per step across mid-conversation switches', async () => { + const baseMs = Date.now() - 60_000; + const reset5hIso = new Date(baseMs + 4 * 3600_000).toISOString(); + const resetWkIso = new Date(baseMs + 6 * 24 * 3600_000).toISOString(); + const makeStepAt = (idx, inTok, outTok, offsetMs) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx }, + createdAt: new Date(baseMs + offsetMs).toISOString(), + completedAt: new Date(baseMs + offsetMs + 1000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: String(inTok), + cacheReadTokens: '0', + outputTokens: String(outTok), + }, + }, + }); + const makeQuota = (rem5h, remWk) => ({ + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: rem5h, resetTime: reset5hIso }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: remWk, resetTime: resetWkIso }, + ], + }, + ], + }); + + const sharedStep1 = makeStepAt(1, 25_000, 5_000, 1_000); // 30,000 + const sharedStep2 = makeStepAt(2, 25_000, 5_000, 3_000); // 30,000 + const aliceOldStep = makeStepAt(1, 35_000, 5_000, 5_000); // 40,000 + + const h = backendHarness({ + userStatus: { email: 'alice@example.com', userTier: { name: 'Google AI Ultra' } }, + quotaSummary: makeQuota(0.8, 0.9), + summaries: { + 'conv-shared': { + stepCount: 2, + lastModifiedTime: new Date(baseMs + 4_000).toISOString(), + status: 'IDLE', + annotations: { title: 'Greeting and Hello' }, + }, + 'conv-alice-old': { + stepCount: 1, + lastModifiedTime: new Date(baseMs + 6_000).toISOString(), + status: 'IDLE', + annotations: { title: 'Earlier Alice Session' }, + }, + }, + trajectories: { + 'conv-shared': { trajectory: { steps: [sharedStep1, sharedStep2] } }, + 'conv-alice-old': { trajectory: { steps: [aliceOldStep] } }, + }, + }); + + // 1. Initial state under Alice: 3 calls = 100,000 tokens in both consumption and Alice's quota pools + const pAlice = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pAlice.conversations.length, 2); + assert.equal(pAlice.activeConversation.cascadeId, 'conv-shared'); + assert.equal(pAlice.activeConversation.stepCount, 2); + assert.equal(pAlice.consumption.account.calls, 3); + assert.equal(pAlice.consumption.account.totalTokens, 100_000); + assert.equal(pAlice.quotas.weekly.calls, 3); + assert.equal(pAlice.quotas.weekly.tokens, 100_000); + + // 2. Switch to Bob and create 1 new step (15,900 tokens) in conv-bob while keeping conv-shared locked + const bobStep1 = makeStepAt(1, 15_552, 348, 10_000); // 15,900 + h.state.userStatus = { email: 'bob@example.com', userTier: { name: 'Google AI Ultra' } }; + h.state.quotaSummary = makeQuota(0.977, 0.994); + h.state.summaries['conv-bob'] = { + stepCount: 1, + lastModifiedTime: new Date(baseMs + 11_000).toISOString(), + status: 'IDLE', + annotations: { title: 'New Bob Session' }, + }; + h.state.trajectories['conv-bob'] = { trajectory: { steps: [bobStep1] } }; + + const pBob = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pBob.conversations.length, 3, 'All historical conversations remain visible after account switch'); + assert.equal(pBob.activeConversation.cascadeId, 'conv-shared', 'Locked conversation stays selected'); + assert.equal(pBob.activeConversation.stepCount, 2, 'Step details of locked conversation are preserved'); + assert.equal(pBob.consumption.account.calls, 4, 'Global consumption retains all 4 calls across accounts'); + assert.equal(pBob.consumption.account.totalTokens, 115_900); + const bobGemini = pBob.quotas.pools.find((pool) => pool.poolKey === 'Gemini'); + assert.equal(bobGemini.cycle5h.calls, 1, 'Quota 5h isolates strictly to Bob'); + assert.equal(bobGemini.cycle5h.tokens, 15_900); + assert.equal(bobGemini.cycleWeekly.tokens, 15_900); + assert.equal(pBob.quotas.weekly.calls, 1); + assert.equal(pBob.quotas.weekly.tokens, 15_900); + + // 3. Continue chatting inside conv-shared while logged in as Bob (step #3 = 25,000 tokens) + const sharedStep3ByBob = makeStepAt(3, 24_000, 1_000, 20_000); // 25,000 + h.state.summaries['conv-shared'] = { + ...h.state.summaries['conv-shared'], + stepCount: 3, + lastModifiedTime: new Date(baseMs + 21_000).toISOString(), + }; + h.state.trajectories['conv-shared'] = { + trajectory: { steps: [sharedStep1, sharedStep2, sharedStep3ByBob] }, + }; + + const pBobContinued = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pBobContinued.activeConversation.stepCount, 3); + assert.equal(pBobContinued.consumption.account.calls, 5); + assert.equal(pBobContinued.consumption.account.totalTokens, 140_900); + const bobGeminiAfter = pBobContinued.quotas.pools.find((pool) => pool.poolKey === 'Gemini'); + assert.equal(bobGeminiAfter.cycle5h.calls, 2, 'Bob quota includes conv-bob + his new step #3 in conv-shared'); + assert.equal(bobGeminiAfter.cycle5h.tokens, 40_900); + assert.equal(pBobContinued.quotas.weekly.calls, 2); + assert.equal(pBobContinued.quotas.weekly.tokens, 40_900); + + // 4. Switch back to Alice -> Alice quota remains strictly her 3 calls (100,000 tokens) + h.state.userStatus = { email: 'alice@example.com', userTier: { name: 'Google AI Ultra' } }; + h.state.quotaSummary = makeQuota(0.8, 0.9); + const pAliceBack = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pAliceBack.consumption.account.calls, 5); + assert.equal(pAliceBack.consumption.account.totalTokens, 140_900); + assert.equal(pAliceBack.quotas.weekly.calls, 3); + assert.equal(pAliceBack.quotas.weekly.tokens, 100_000); +}); + test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd rounding, and dynamicModelMap default', async () => { const badStep = { status: 'CORTEX_STEP_STATUS_DONE',