From d21f571e21cbba8a79d7a9efdaa89835e3856214 Mon Sep 17 00:00:00 2001 From: Stephen Schoettler Date: Thu, 26 Feb 2026 12:08:28 -0800 Subject: [PATCH] fix: add null guards to usage sort comparators Prevents crash when totals is undefined in byModel/byProvider/byAgent sort comparators. Fixes 'Cannot read properties of undefined (reading totalTokens)' crash that causes context overflow in active sessions. --- src/gateway/server-methods/usage.ts | 10 +++++----- src/infra/session-cost-usage.ts | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/gateway/server-methods/usage.ts b/src/gateway/server-methods/usage.ts index e40af58f5fe..3546c25723c 100644 --- a/src/gateway/server-methods/usage.ts +++ b/src/gateway/server-methods/usage.ts @@ -844,22 +844,22 @@ export const usageHandlers: GatewayRequestHandlers = { .toSorted((a, b) => b.count - a.count), }, byModel: Array.from(byModelMap.values()).toSorted((a, b) => { - const costDiff = b.totals.totalCost - a.totals.totalCost; + const costDiff = (b.totals?.totalCost ?? 0) - (a.totals?.totalCost ?? 0); if (costDiff !== 0) { return costDiff; } - return b.totals.totalTokens - a.totals.totalTokens; + return (b.totals?.totalTokens ?? 0) - (a.totals?.totalTokens ?? 0); }), byProvider: Array.from(byProviderMap.values()).toSorted((a, b) => { - const costDiff = b.totals.totalCost - a.totals.totalCost; + const costDiff = (b.totals?.totalCost ?? 0) - (a.totals?.totalCost ?? 0); if (costDiff !== 0) { return costDiff; } - return b.totals.totalTokens - a.totals.totalTokens; + return (b.totals?.totalTokens ?? 0) - (a.totals?.totalTokens ?? 0); }), byAgent: Array.from(byAgentMap.entries()) .map(([id, totals]) => ({ agentId: id, totals })) - .toSorted((a, b) => b.totals.totalCost - a.totals.totalCost), + .toSorted((a, b) => (b.totals?.totalCost ?? 0) - (a.totals?.totalCost ?? 0)), ...tail, }; diff --git a/src/infra/session-cost-usage.ts b/src/infra/session-cost-usage.ts index 230ebd60c2e..4c021bcc72f 100644 --- a/src/infra/session-cost-usage.ts +++ b/src/infra/session-cost-usage.ts @@ -707,11 +707,11 @@ export async function loadSessionCostSummary(params: { const modelUsage = modelUsageMap.size ? Array.from(modelUsageMap.values()).toSorted((a, b) => { - const costDiff = b.totals.totalCost - a.totals.totalCost; + const costDiff = (b.totals?.totalCost ?? 0) - (a.totals?.totalCost ?? 0); if (costDiff !== 0) { return costDiff; } - return b.totals.totalTokens - a.totals.totalTokens; + return (b.totals?.totalTokens ?? 0) - (a.totals?.totalTokens ?? 0); }) : undefined;