Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(topic): roll lump-sum operation LLM cost into the topic total (#21220)

Arvin Xu4a6959b5df69
diff --git a/packages/database/src/models/__tests__/topics/topicUsage.test.ts b/packages/database/src/models/__tests__/topics/topicUsage.test.ts
index 10ffe01c328..edb32caacff 100644
--- a/packages/database/src/models/__tests__/topics/topicUsage.test.ts
+++ b/packages/database/src/models/__tests__/topics/topicUsage.test.ts
@@ -69,7 +69,9 @@ let opSeq = 0;
const insertOperation = async (params: {
cost?: Record<string, unknown> | null;
id?: string;
+ model?: string;
parentOperationId?: string;
+ provider?: string;
topicId?: string | null;
usage?: Record<string, unknown> | null;
userId?: string;
@@ -78,7 +80,9 @@ const insertOperation = async (params: {
await serverDB.insert(agentOperations).values({
cost: params.cost ?? null,
id,
+ model: params.model ?? null,
parentOperationId: params.parentOperationId ?? null,
+ provider: params.provider ?? null,
status: 'done',
topicId: params.topicId === undefined ? topicId : params.topicId,
usage: params.usage ?? null,
@@ -567,4 +571,98 @@ describe('recomputeTopicUsage', () => {
});
});
});
+
+ describe('lump-sum operation LLM cost (heterogeneous CLI runs)', () => {
+ it('fills the LLM cost from the op total when its messages carry tokens but no cost', async () => {
+ await insertAssistantMessage({
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ usage: { totalInputTokens: 1000, totalOutputTokens: 200, totalTokens: 1200 },
+ });
+ await insertAssistantMessage({
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ usage: { totalInputTokens: 500, totalOutputTokens: 100, totalTokens: 600 },
+ });
+ await insertOperation({
+ cost: { total: 7.92 },
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ });
+
+ await recompute();
+ const topic = await getTopic();
+
+ expect(topic.totalCost).toBeCloseTo(7.92, 6);
+ expect(topic.totalTokens).toBe(1800);
+ expect((topic.cost as any).llm.total).toBeCloseTo(7.92, 6);
+ expect((topic.cost as any).llm.byModel).toEqual([
+ expect.objectContaining({
+ id: 'claude-code/claude-opus-5-5',
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ totalCost: 7.92,
+ usage: expect.objectContaining({ cost: 7.92, totalTokens: 1800 }),
+ }),
+ ]);
+ });
+
+ it('sums lump-sum ops and keeps tool cost out of the LLM share', async () => {
+ await insertOperation({
+ cost: { total: 1 },
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ });
+ await insertOperation({
+ cost: {
+ tools: { byTool: [{ calls: 1, name: 'web-search', totalCost: 0.25 }], total: 0.25 },
+ total: 2.25,
+ },
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ });
+
+ await recompute();
+ const topic = await getTopic();
+
+ expect((topic.cost as any).llm.total).toBeCloseTo(3, 6);
+ expect((topic.cost as any).tools.total).toBeCloseTo(0.25, 6);
+ expect(topic.totalCost).toBeCloseTo(3.25, 6);
+ });
+
+ it('does not double count a lump-sum op whose provider already itemizes cost on messages', async () => {
+ await insertAssistantMessage({
+ cost: 0.04,
+ model: 'deepseek-flash',
+ provider: 'lobehub',
+ usage: { totalInputTokens: 100, totalOutputTokens: 10, totalTokens: 110 },
+ });
+ await insertOperation({
+ cost: { total: 0.04 },
+ model: 'deepseek-flash',
+ provider: 'lobehub',
+ });
+
+ await recompute();
+
+ expect((await getTopic()).totalCost).toBeCloseTo(0.04, 6);
+ });
+
+ it('ignores an op total that already carries an llm breakdown', async () => {
+ await insertAssistantMessage({
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
+ });
+ await insertOperation({
+ cost: { llm: { byModel: [], currency: 'USD', total: 0.5 }, total: 0.5 },
+ model: 'claude-opus-5-5',
+ provider: 'claude-code',
+ });
+
+ await recompute();
+
+ expect((await getTopic()).totalCost).toBeNull();
+ });
+ });
});
diff --git a/packages/database/src/models/topicUsage.ts b/packages/database/src/models/topicUsage.ts
index 48d7f2b0104..1801912fcdb 100644
--- a/packages/database/src/models/topicUsage.ts
+++ b/packages/database/src/models/topicUsage.ts
@@ -26,13 +26,26 @@ interface HumanInteractionUsage {
totalWaitingTimeMs: number;
}
+/** LLM spend an operation reported as one lump sum, per (provider, model). */
+interface UnitemizedLlmCost {
+ model: string | null;
+ provider: string | null;
+ totalCost: number;
+}
+
/** Tool / human-interaction rollup derived from the topic's operation rows. */
interface OperationUsageRollup {
- /** True when any operation contributed a non-zero tool / human-interaction stat. */
+ /** True when any operation contributed a non-zero tool / human-interaction stat or cost. */
hasData: boolean;
humanInteraction: HumanInteractionUsage;
toolsCost: { byTool: ToolCostEntry[]; total: number };
toolsUsage: { byTool: ToolUsageEntry[]; totalCalls: number; totalTimeMs: number };
+ /**
+ * LLM spend of operations whose cost blob carries no `llm` breakdown β€” a
+ * heterogeneous CLI run (Claude Code / Codex) reports only the run's total, and
+ * its assistant messages carry tokens but no per-message `cost`.
+ */
+ unitemizedLlmCost: UnitemizedLlmCost[];
}
/**
@@ -80,6 +93,10 @@ const num = (v: unknown): number => (v == null ? 0 : Number(v));
* Park/resume cycles are safe too: `waiting_for_async_tool` resumes overwrite
* the same row, and a `waiting_for_human` resume runs under a NEW operationId
* with a fresh accumulator.
+ *
+ * An op whose cost blob has no `llm` key reported its LLM spend as a lump total
+ * that never reached the messages; that remainder (total minus tool cost) is
+ * returned as `unitemizedLlmCost` so the caller can fill the message-side gap.
*/
const aggregateOperationUsage = async (
trx: Transaction,
@@ -90,7 +107,11 @@ const aggregateOperationUsage = async (
SELECT
usage->'tools' AS "toolsUsage",
usage->'humanInteraction' AS "humanInteraction",
- cost->'tools' AS "toolsCost"
+ cost->'tools' AS "toolsCost",
+ cost ? 'llm' AS "hasLlmCost",
+ (cost->>'total')::numeric AS "costTotal",
+ provider,
+ model
FROM agent_operations
WHERE topic_id = ${topicId}
AND ${ownership}
@@ -99,6 +120,7 @@ const aggregateOperationUsage = async (
const usageByTool = new Map<string, ToolUsageEntry>();
const costByTool = new Map<string, ToolCostEntry>();
+ const unitemizedByModel = new Map<string, UnitemizedLlmCost>();
let totalCalls = 0;
let totalTimeMs = 0;
let costTotal = 0;
@@ -153,6 +175,19 @@ const aggregateOperationUsage = async (
}
}
}
+
+ if (row.hasLlmCost === false) {
+ const llmCost = num(row.costTotal) - num(toolsCost?.total);
+ if (llmCost > 0) {
+ const key = `${row.provider ?? ''}/${row.model ?? ''}`;
+ let merged = unitemizedByModel.get(key);
+ if (!merged) {
+ merged = { model: row.model ?? null, provider: row.provider ?? null, totalCost: 0 };
+ unitemizedByModel.set(key, merged);
+ }
+ merged.totalCost += llmCost;
+ }
+ }
}
const byName = <T extends { name: string }>(map: Map<string, T>) =>
@@ -164,6 +199,7 @@ const aggregateOperationUsage = async (
costTotal > 0 ||
usageByTool.size > 0 ||
costByTool.size > 0 ||
+ unitemizedByModel.size > 0 ||
Object.values(humanInteraction).some((v) => v > 0);
return {
@@ -171,6 +207,7 @@ const aggregateOperationUsage = async (
humanInteraction,
toolsCost: { byTool: byName(costByTool), total: costTotal },
toolsUsage: { byTool: byName(usageByTool), totalCalls, totalTimeMs },
+ unitemizedLlmCost: [...unitemizedByModel.values()],
};
};
@@ -184,6 +221,8 @@ const aggregateOperationUsage = async (
* 2. Tool + human-interaction usage and tool cost: SUM over the topic's
* `agent_operations` usage/cost blobs (see {@link aggregateOperationUsage})
* β€” this data never lands on messages, so operations are its only source.
+ * Operations that reported their LLM spend as a lump total also fill the
+ * LLM cost of any provider whose messages carry no cost.
*
* The stored shape mirrors `agent_operations`:
* - scalar columns : total_input_tokens / total_output_tokens / total_tokens / total_cost
@@ -301,6 +340,30 @@ export const recomputeTopicUsage = async (
let apiCalls = 0;
let processingTimeMs = 0;
const byModel: Array<Record<string, unknown>> = [];
+ // Providers whose messages itemize cost; an op's lump-sum LLM cost for one of
+ // these is already counted message by message.
+ const itemizedProviders = new Set<unknown>();
+
+ // cost.llm.byModel mirrors the operation shape: cost-bearing models only,
+ // each carrying its merged ModelUsage breakdown.
+ const pushModelCost = (
+ provider: string | null,
+ model: string | null,
+ rowCost: number,
+ group?: Record<string, unknown>,
+ ) => {
+ const usageObj: Record<string, number> = {};
+ if (group) for (const f of USAGE_FIELDS) if (group[f] != null) usageObj[f] = Number(group[f]);
+ usageObj.cost = rowCost;
+
+ byModel.push({
+ id: `${provider ?? 'unknown'}/${model ?? 'unknown'}`,
+ model,
+ provider,
+ totalCost: rowCost,
+ usage: usageObj,
+ });
+ };
for (const g of groups) {
const rowTotalTokens = num(g.totalTokens);
@@ -314,23 +377,17 @@ export const recomputeTopicUsage = async (
if (rowCost != null) {
totalCost += rowCost;
hasCost = true;
+ itemizedProviders.add(g.provider);
+ pushModelCost((g.provider as string) ?? null, (g.model as string) ?? null, rowCost, g);
}
+ }
- // cost.llm.byModel mirrors the operation shape: cost-bearing models only,
- // each carrying its merged ModelUsage breakdown.
- if (rowCost != null) {
- const usageObj: Record<string, number> = {};
- for (const f of USAGE_FIELDS) if (g[f] != null) usageObj[f] = Number(g[f]);
- usageObj.cost = rowCost;
-
- byModel.push({
- id: `${(g.provider as string) ?? 'unknown'}/${(g.model as string) ?? 'unknown'}`,
- model: (g.model as string) ?? null,
- provider: (g.provider as string) ?? null,
- totalCost: rowCost,
- usage: usageObj,
- });
- }
+ for (const entry of ops.unitemizedLlmCost) {
+ if (itemizedProviders.has(entry.provider)) continue;
+ totalCost += entry.totalCost;
+ hasCost = true;
+ const group = groups.find((g) => g.provider === entry.provider && g.model === entry.model);
+ pushModelCost(entry.provider, entry.model, entry.totalCost, group);
}
const usage = {