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.
This commit is contained in:
Stephen Schoettler 2026-02-26 12:08:28 -08:00
parent 0f2dce0483
commit d21f571e21
2 changed files with 7 additions and 7 deletions

View File

@ -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,
};

View File

@ -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;