π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(database): maintain denormalized topic usage/cost rollup from messages (#15365)
Arvin Xuc3f91f10ac18
diff --git a/packages/database/src/models/__tests__/messages/message.delete.test.ts b/packages/database/src/models/__tests__/messages/message.delete.test.tsindex 0fd2b180c78..22cf2742175 100644--- a/packages/database/src/models/__tests__/messages/message.delete.test.ts+++ b/packages/database/src/models/__tests__/messages/message.delete.test.ts@@ -837,4 +837,44 @@ describe('MessageModel Delete Tests', () => {expect(remaining[0].id).toBe('msg-keep-empty');});});++ describe('topic usage rollup', () => {+ const usageMsg = (id: string, totalTokens: number, cost: number) => ({+ id,+ metadata: { usage: { cost, totalInputTokens: totalTokens, totalTokens } },+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ topicId: 'usage-del-topic',+ userId,+ });++ beforeEach(async () => {+ await serverDB.insert(topics).values({ id: 'usage-del-topic', userId });+ });++ it('deleteMessage recomputes the topic rollup, dropping the removed message', async () => {+ await serverDB+ .insert(messages)+ .values([usageMsg('keep-msg', 20, 0.01), usageMsg('drop-msg', 50, 0.02)]);++ await messageModel.deleteMessage('drop-msg');++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'usage-del-topic'));+ expect(topic.totalTokens).toBe(20);+ expect(topic.totalCost).toBeCloseTo(0.01, 6);+ });++ it('deleteMessages resets the rollup to NULL once all assistant usage is gone', async () => {+ await serverDB.insert(messages).values([usageMsg('m1', 20, 0.01), usageMsg('m2', 50, 0.02)]);++ await messageModel.deleteMessages(['m1', 'm2']);++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'usage-del-topic'));+ expect(topic.totalTokens).toBeNull();+ expect(topic.totalCost).toBeNull();+ expect(topic.usage).toBeNull();+ expect(topic.cost).toBeNull();+ });+ });});diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.tsindex 48b2cb8d041..d94895d5969 100644--- a/packages/database/src/models/__tests__/messages/message.update.test.ts+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts@@ -13,6 +13,7 @@ import {messageTranslates,messageTTS,sessions,+ topics,users,} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';@@ -1433,4 +1434,67 @@ describe('MessageModel Update Tests', () => {expect(result.success).toBe(false);});});++ describe('topic usage rollup', () => {+ beforeEach(async () => {+ await serverDB.insert(topics).values({ id: 'update-usage-topic', userId });+ });++ it('recomputes the topic rollup when the update carries metadata.usage', async () => {+ await serverDB.insert(messages).values({+ id: 'finalize-msg',+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ topicId: 'update-usage-topic',+ userId,+ });++ // assistant finalize: the write that first carries token usage+ await messageModel.update('finalize-msg', {+ metadata: {+ usage: { cost: 0.004, totalInputTokens: 70, totalOutputTokens: 30, totalTokens: 100 },+ } as any,+ });++ const [topic] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'update-usage-topic'));+ expect(topic.totalTokens).toBe(100);+ expect(topic.totalCost).toBeCloseTo(0.004, 6);+ expect((topic.usage as any).llm.apiCalls).toBe(1);+ });++ it('does NOT recompute on a content-only update (no metadata.usage)', async () => {+ // an already-finalized assistant message with usage+ await serverDB.insert(messages).values({+ id: 'done-msg',+ metadata: { usage: { cost: 0.01, totalInputTokens: 10, totalTokens: 20 } },+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ topicId: 'update-usage-topic',+ userId,+ });+ await messageModel.update('done-msg', {+ metadata: { usage: { cost: 0.01, totalInputTokens: 10, totalTokens: 20 } } as any,+ });+ const [seeded] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'update-usage-topic'));+ expect(seeded.totalTokens).toBe(20);++ // a streaming content-only update must not touch the rollup+ await messageModel.update('done-msg', { content: 'streamed text' });++ const [topic] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'update-usage-topic'));+ expect(topic.totalTokens).toBe(20);+ expect(topic.totalCost).toBeCloseTo(0.01, 6);+ });+ });});diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex c7c87d1a016..5692bef5e7c 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -1,7 +1,8 @@+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { sessions, topics, users } from '../../../schemas';+import { messages, sessions, topics, users } from '../../../schemas';import type { LobeChatDatabase } from '../../../type';import { TopicModel } from '../../topic';@@ -123,4 +124,61 @@ describe('TopicModel - Update', () => {expect(result).toHaveLength(0);});});++ describe('recomputeUsage', () => {+ it('rolls the topic assistant messages into the denormalized usage/cost columns', async () => {+ const topicId = 'usage-recompute-1';+ await serverDB.insert(topics).values({ id: topicId, sessionId, userId });+ await serverDB.insert(messages).values([+ {+ id: 'usage-msg-1',+ metadata: {+ performance: { duration: 500 },+ usage: { cost: 0.003, totalInputTokens: 60, totalOutputTokens: 40, totalTokens: 100 },+ },+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ topicId,+ userId,+ },+ // a non-usage message must be ignored+ { id: 'usage-msg-2', content: 'hi', role: 'user', topicId, userId },+ ]);++ await topicModel.recomputeUsage(topicId);++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));+ expect(topic.totalTokens).toBe(100);+ expect(topic.totalInputTokens).toBe(60);+ expect(topic.totalOutputTokens).toBe(40);+ expect(topic.totalCost).toBeCloseTo(0.003, 6);+ expect(topic.model).toBe('gpt-4o');+ expect(topic.provider).toBe('openai');+ expect((topic.usage as any).llm).toEqual({+ apiCalls: 1,+ processingTimeMs: 500,+ tokens: { input: 60, output: 40, total: 100 },+ });+ });++ it('resets the usage columns to NULL when the topic has no measurable usage', async () => {+ const topicId = 'usage-recompute-2';+ await serverDB.insert(topics).values({+ id: topicId,+ sessionId,+ totalCost: 1.23,+ totalTokens: 999,+ userId,+ });++ await topicModel.recomputeUsage(topicId);++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));+ expect(topic.totalTokens).toBeNull();+ expect(topic.totalCost).toBeNull();+ expect(topic.usage).toBeNull();+ expect(topic.cost).toBeNull();+ });+ });});diff --git a/packages/database/src/models/__tests__/topics/topicUsage.test.ts b/packages/database/src/models/__tests__/topics/topicUsage.test.tsnew file mode 100644index 00000000000..89915d39a1b--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topicUsage.test.ts@@ -0,0 +1,280 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { messages, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { recomputeTopicUsage } from '../../topicUsage';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'topic-usage-user';+const otherUserId = 'topic-usage-other-user';+const topicId = 'topic-usage-topic';++interface UsageInput {+ [field: string]: number | undefined;+ cost?: number;+ totalInputTokens?: number;+ totalOutputTokens?: number;+ totalTokens?: number;+}++let msgSeq = 0;++const insertAssistantMessage = async (params: {+ cost?: number;+ duration?: number;+ id?: string;+ model?: string;+ provider?: string;+ role?: string;+ userId?: string;+ // when omitted, the message carries no `metadata.usage` and must be excluded+ usage?: UsageInput | null;+}) => {+ const id = params.id ?? `msg-${(msgSeq += 1)}`;+ const usage =+ params.usage === null+ ? undefined+ : { ...params.usage, ...(params.cost == null ? {} : { cost: params.cost }) };++ const metadata =+ params.usage === null+ ? { tps: 1 } // realistic non-usage metadata (e.g. content-only)+ : {+ performance: params.duration == null ? undefined : { duration: params.duration },+ usage,+ };++ await serverDB.insert(messages).values({+ id,+ metadata,+ model: params.model ?? 'gpt-4o',+ provider: params.provider ?? 'openai',+ role: params.role ?? 'assistant',+ topicId,+ userId: params.userId ?? userId,+ });+ return id;+};++const recompute = (uid = userId, tid = topicId) =>+ serverDB.transaction((trx) => recomputeTopicUsage(trx, uid, tid));++const getTopic = async (id = topicId) => {+ const [row] = await serverDB.select().from(topics).where(eq(topics.id, id));+ return row;+};++beforeEach(async () => {+ msgSeq = 0;+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(topics).values({ id: topicId, userId });+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('recomputeTopicUsage', () => {+ it('rolls a single assistant message into scalar totals, usage and cost jsonb', async () => {+ await insertAssistantMessage({+ cost: 0.0021,+ duration: 1200,+ model: 'gpt-4o',+ provider: 'openai',+ usage: {+ inputTextTokens: 100,+ outputTextTokens: 50,+ totalInputTokens: 100,+ totalOutputTokens: 50,+ totalTokens: 150,+ },+ });++ await recompute();+ const topic = await getTopic();++ expect(topic.totalInputTokens).toBe(100);+ expect(topic.totalOutputTokens).toBe(50);+ expect(topic.totalTokens).toBe(150);+ expect(topic.totalCost).toBeCloseTo(0.0021, 6);+ expect(topic.model).toBe('gpt-4o');+ expect(topic.provider).toBe('openai');++ expect(topic.usage).toEqual({+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: {+ apiCalls: 1,+ processingTimeMs: 1200,+ tokens: { input: 100, output: 50, total: 150 },+ },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ });++ expect(topic.cost).toMatchObject({+ currency: 'USD',+ llm: {+ byModel: [+ {+ id: 'openai/gpt-4o',+ model: 'gpt-4o',+ provider: 'openai',+ totalCost: 0.0021,+ usage: expect.objectContaining({+ cost: 0.0021,+ totalInputTokens: 100,+ totalOutputTokens: 50,+ totalTokens: 150,+ }),+ },+ ],+ currency: 'USD',+ },+ tools: { byTool: [], currency: 'USD', total: 0 },+ });+ expect((topic.cost as any).total).toBeCloseTo(0.0021, 6);+ expect((topic.cost as any).llm.total).toBeCloseTo(0.0021, 6);+ });++ it('groups by (provider, model) and sums per group; apiCalls counts messages', async () => {+ // two gpt-4o calls + one claude call+ await insertAssistantMessage({+ cost: 0.002,+ duration: 100,+ model: 'gpt-4o',+ provider: 'openai',+ usage: { totalInputTokens: 80, totalOutputTokens: 40, totalTokens: 120 },+ });+ await insertAssistantMessage({+ cost: 0.001,+ duration: 200,+ model: 'gpt-4o',+ provider: 'openai',+ usage: { totalInputTokens: 50, totalOutputTokens: 30, totalTokens: 80 },+ });+ await insertAssistantMessage({+ cost: 0.005,+ duration: 300,+ model: 'claude-3-5-sonnet',+ provider: 'anthropic',+ usage: { totalInputTokens: 200, totalOutputTokens: 100, totalTokens: 300 },+ });++ await recompute();+ const topic = await getTopic();++ expect(topic.totalInputTokens).toBe(330);+ expect(topic.totalOutputTokens).toBe(170);+ expect(topic.totalTokens).toBe(500);+ expect(topic.totalCost).toBeCloseTo(0.008, 6);++ const usage = topic.usage as any;+ expect(usage.llm.apiCalls).toBe(3);+ expect(usage.llm.processingTimeMs).toBe(600);+ expect(usage.llm.tokens).toEqual({ input: 330, output: 170, total: 500 });++ // dominant model = largest token volume (claude 300 > gpt-4o 200)+ expect(topic.model).toBe('claude-3-5-sonnet');+ expect(topic.provider).toBe('anthropic');++ const byModel = (topic.cost as any).llm.byModel as any[];+ expect(byModel).toHaveLength(2);+ const gpt = byModel.find((m) => m.id === 'openai/gpt-4o');+ const claude = byModel.find((m) => m.id === 'anthropic/claude-3-5-sonnet');+ expect(gpt.totalCost).toBeCloseTo(0.003, 6);+ expect(gpt.usage.totalTokens).toBe(200);+ expect(claude.totalCost).toBeCloseTo(0.005, 6);+ expect(claude.usage.totalTokens).toBe(300);+ });++ it('only counts role=assistant messages with metadata.usage', async () => {+ // counted+ await insertAssistantMessage({+ cost: 0.01,+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },+ });+ // excluded: a user message (even if it somehow had usage)+ await insertAssistantMessage({+ cost: 0.99,+ role: 'user',+ usage: { totalInputTokens: 999, totalOutputTokens: 999, totalTokens: 999 },+ });+ // excluded: assistant message without metadata.usage (content-only)+ await insertAssistantMessage({ role: 'assistant', usage: null });++ await recompute();+ const topic = await getTopic();++ expect(topic.totalTokens).toBe(15);+ expect((topic.usage as any).llm.apiCalls).toBe(1);+ expect(topic.totalCost).toBeCloseTo(0.01, 6);+ });++ it('scopes the rollup to the given userId', async () => {+ await insertAssistantMessage({+ cost: 0.01,+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },+ });+ // a different user's message sitting under the same topic id must be ignored+ await insertAssistantMessage({+ cost: 0.5,+ userId: otherUserId,+ usage: { totalInputTokens: 500, totalOutputTokens: 500, totalTokens: 1000 },+ });++ await recompute();+ const topic = await getTopic();++ expect(topic.totalTokens).toBe(15);+ expect(topic.totalCost).toBeCloseTo(0.01, 6);+ });++ it('leaves cost NULL when no model reported a cost, but still sums tokens', async () => {+ await insertAssistantMessage({+ usage: { totalInputTokens: 30, totalOutputTokens: 20, totalTokens: 50 },+ });++ await recompute();+ const topic = await getTopic();++ expect(topic.totalTokens).toBe(50);+ expect(topic.totalInputTokens).toBe(30);+ expect(topic.totalCost).toBeNull();+ expect(topic.cost).toBeNull();+ // usage jsonb is still populated+ expect((topic.usage as any).llm.tokens.total).toBe(50);+ });++ it('resets every rollup column to NULL when no measurable usage remains', async () => {+ // first populate+ const id = await insertAssistantMessage({+ cost: 0.02,+ usage: { totalInputTokens: 40, totalOutputTokens: 10, totalTokens: 50 },+ });+ await recompute();+ expect((await getTopic()).totalTokens).toBe(50);++ // remove the only assistant message β nothing left to measure+ await serverDB.delete(messages).where(eq(messages.id, id));+ await recompute();++ const topic = await getTopic();+ expect(topic.totalInputTokens).toBeNull();+ expect(topic.totalOutputTokens).toBeNull();+ expect(topic.totalTokens).toBeNull();+ expect(topic.totalCost).toBeNull();+ expect(topic.usage).toBeNull();+ expect(topic.cost).toBeNull();+ expect(topic.model).toBeNull();+ expect(topic.provider).toBeNull();+ });+});diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 5a0f8794d02..67fc12a64e0 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -73,6 +73,7 @@ import type { LobeChatDatabase, Transaction } from '../type';import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';+import { recomputeTopicUsage } from './topicUsage';/*** Options for querying messages with relations@@ -1940,6 +1941,19 @@ export class MessageModel {() => this.touchTopicUpdatedAt(trx, [updated.topicId!]),{ topicCount: 1 },);++ // When this write carries token usage (assistant finalize / hetero+ // step), recompute the topic's denormalized usage rollup from its+ // messages. Gated on the *incoming* payload so streaming+ // content-only updates don't trigger needless recomputes.+ if ((metadata as { usage?: unknown } | undefined)?.usage) {+ await runTimedStage(+ timing,+ 'db.message.update.topic.recomputeUsage',+ () => recomputeTopicUsage(trx, this.userId, updated.topicId!),+ { topicCount: 1 },+ );+ }}}),{@@ -2303,6 +2317,12 @@ export class MessageModel {await tx.delete(messages).where(and(eq(messages.userId, this.userId), inArray(messages.id, messageIdsToDelete)));++ // 7. Keep the topic's usage rollup in sync (pure derived β a removed+ // assistant message must drop out of the topic totals).+ if (message[0].topicId) {+ await recomputeTopicUsage(tx, this.userId, message[0].topicId);+ }});};@@ -2312,7 +2332,7 @@ export class MessageModel {return this.db.transaction(async (tx) => {// 1. Query all messages to be deleted with their parentIdconst toDelete = await tx- .select({ id: messages.id, parentId: messages.parentId })+ .select({ id: messages.id, parentId: messages.parentId, topicId: messages.topicId }).from(messages).where(and(eq(messages.userId, this.userId), inArray(messages.id, ids)));@@ -2376,6 +2396,14 @@ export class MessageModel {await tx.delete(messages).where(and(eq(messages.userId, this.userId), inArray(messages.id, ids)));++ // 7. Recompute the usage rollup for every affected topic (pure derived).+ const affectedTopicIds = [+ ...new Set(toDelete.map((m) => m.topicId).filter(Boolean) as string[]),+ ];+ for (const topicId of affectedTopicIds) {+ await recomputeTopicUsage(tx, this.userId, topicId);+ }});};diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 54062b6406f..fc187f00154 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -34,6 +34,7 @@ import type { LobeChatDatabase } from '../type';import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';+import { recomputeTopicUsage } from './topicUsage';type OnboardingSessionMetadataPatch = Partial<NonNullable<ChatTopicMetadata['onboardingSession']>>;type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'> & {@@ -889,6 +890,15 @@ export class TopicModel {.returning();};+ /**+ * Recompute this topic's denormalized usage/cost rollup from its assistant+ * messages. The canonical aggregation lives in `recomputeTopicUsage`; the+ * live path (MessageModel) calls it inline within its own transaction, while+ * external callers use this wrapper. Runs in a transaction for consistency.+ */+ recomputeUsage = async (id: string) =>+ this.db.transaction((trx) => recomputeTopicUsage(trx, this.userId, id));+/*** Update topic metadata with merge logic* This method merges new metadata with existing metadata instead of replacing itdiff --git a/packages/database/src/models/topicUsage.ts b/packages/database/src/models/topicUsage.tsnew file mode 100644index 00000000000..d5b014bfcdf--- /dev/null+++ b/packages/database/src/models/topicUsage.ts@@ -0,0 +1,192 @@+import { and, eq, sql } from 'drizzle-orm';++import { topics } from '../schemas';+import type { Transaction } from '../type';++/**+ * ModelUsage numeric fields summed per (provider, model) to build the+ * `cost.llm.byModel[].usage` breakdown. Mirrors ModelUsageSchema in+ * `@lobechat/types` (message/common/metadata.ts) β keep in sync if it changes.+ */+const USAGE_FIELDS = [+ 'totalInputTokens',+ 'totalOutputTokens',+ 'totalTokens',+ 'inputTextTokens',+ 'inputImageTokens',+ 'inputAudioTokens',+ 'inputVideoTokens',+ 'inputCitationTokens',+ 'inputToolTokens',+ 'inputCachedTokens',+ 'inputCacheMissTokens',+ 'inputWriteCacheTokens',+ 'inputCachedTextTokens',+ 'inputCachedImageTokens',+ 'inputCachedAudioTokens',+ 'inputCachedVideoTokens',+ 'outputTextTokens',+ 'outputImageTokens',+ 'outputAudioTokens',+ 'outputReasoningTokens',+ 'acceptedPredictionTokens',+ 'rejectedPredictionTokens',+] as const;++const num = (v: unknown): number => (v == null ? 0 : Number(v));++/**+ * Recompute a topic's denormalized usage/cost rollup from its assistant messages.+ *+ * Pure derived projection: SUM over the topic's `role='assistant'` messages+ * (thread messages count too β they also carry `topic_id`), reading the+ * canonical `metadata.usage`. The stored shape mirrors `agent_operations`:+ * - scalar columns : total_input_tokens / total_output_tokens / total_tokens / total_cost+ * - `usage` jsonb : flat aggregate { llm: { apiCalls, processingTimeMs, tokens }, tools, humanInteraction }+ * - `cost` jsonb : { total, currency, llm: { total, currency, byModel[] }, tools } β or NULL when no model reported cost+ * - model/provider : the dominant model by total_tokens+ *+ * Idempotent and non-cumulative: when the topic has no measurable assistant+ * usage (e.g. after deletions), the columns are reset to NULL ("not measured"),+ * so deletes / regenerations are reflected correctly.+ *+ * NOTE: this writes through drizzle, whose `topics.updatedAt` has `$onUpdate`,+ * so calling it bumps `updated_at`. That's intended for the live path (the+ * topic is active anyway). The historical backfill must NOT use this β it runs+ * its own raw-SQL aggregate that leaves `updated_at` untouched.+ */+export const recomputeTopicUsage = async (+ trx: Transaction,+ userId: string,+ topicId: string,+): Promise<void> => {+ const fieldSelects = USAGE_FIELDS.map(+ (f) => `sum((metadata->'usage'->>'${f}')::numeric) AS "${f}"`,+ ).join(',\n ');++ const { rows } = await trx.execute(sql`+ SELECT+ provider,+ model,+ count(*)::int AS "msgCount",+ sum((metadata->'usage'->>'cost')::numeric) AS "cost",+ sum((metadata->'performance'->>'duration')::numeric) AS "durationMs",+ ${sql.raw(fieldSelects)}+ FROM messages+ WHERE topic_id = ${topicId}+ AND user_id = ${userId}+ AND role = 'assistant'+ AND metadata ? 'usage'+ GROUP BY provider, model+ `);++ const groups = rows as Array<Record<string, unknown>>;++ // No measurable usage left β reset to NULL so the column reflects reality.+ if (groups.length === 0) {+ await trx+ .update(topics)+ .set({+ cost: null,+ model: null,+ provider: null,+ totalCost: null,+ totalInputTokens: null,+ totalOutputTokens: null,+ totalTokens: null,+ usage: null,+ })+ .where(and(eq(topics.id, topicId), eq(topics.userId, userId)));+ return;+ }++ let totalInputTokens = 0;+ let totalOutputTokens = 0;+ let totalTokens = 0;+ let totalCost = 0;+ let hasCost = false;+ let apiCalls = 0;+ let processingTimeMs = 0;+ const byModel: Array<Record<string, unknown>> = [];+ let primary: { model: string | null; provider: string | null; tokens: number } | null = null;++ for (const g of groups) {+ const rowTotalTokens = num(g.totalTokens);+ totalInputTokens += num(g.totalInputTokens);+ totalOutputTokens += num(g.totalOutputTokens);+ totalTokens += rowTotalTokens;+ apiCalls += num(g.msgCount);+ processingTimeMs += num(g.durationMs);++ const rowCost = g.cost == null ? null : Number(g.cost);+ if (rowCost != null) {+ totalCost += rowCost;+ hasCost = true;+ }++ // Dominant model = largest token volume.+ if (!primary || rowTotalTokens > primary.tokens) {+ primary = {+ model: (g.model as string) ?? null,+ provider: (g.provider as string) ?? null,+ tokens: rowTotalTokens,+ };+ }++ // 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,+ });+ }+ }++ const usage = {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: {+ apiCalls,+ processingTimeMs,+ tokens: { input: totalInputTokens, output: totalOutputTokens, total: totalTokens },+ },+ // Tool / human-interaction accounting isn't reconstructable from assistant+ // messages alone; left as a zero skeleton to keep the shape aligned with operations.+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ };++ const cost = hasCost+ ? {+ currency: 'USD',+ llm: { byModel, currency: 'USD', total: totalCost },+ total: totalCost,+ tools: { byTool: [], currency: 'USD', total: 0 },+ }+ : null;++ await trx+ .update(topics)+ .set({+ cost,+ model: primary?.model ?? null,+ provider: primary?.provider ?? null,+ totalCost: hasCost ? totalCost : null,+ totalInputTokens,+ totalOutputTokens,+ totalTokens,+ usage,+ })+ .where(and(eq(topics.id, topicId), eq(topics.userId, userId)));+};