π€― 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
π fix(database): include operation usage in topic rollups (#17183)
AmAzing-8278201079a4
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex e47fa8b35a6..0d54984cfe0 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -9,6 +9,7 @@ import {type RecordOperationStartParams,} from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';+import { recomputeTopicUsage } from '@/database/models/topicUsage';import { VerifyRunModel } from '@/database/models/verifyRun';import { type LobeChatDatabase } from '@/database/type';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';@@ -267,6 +268,22 @@ export class CompletionLifecycle {} catch (error) {log('[%s] Failed to persist operation completion (non-fatal): %O', operationId, error);}++ // The topic rollup's tool / human-interaction stats derive from the+ // operation rows written above (`recomputeTopicUsage` reads their usage/cost+ // blobs), but its usual trigger is the assistant message's usage write,+ // which can land BEFORE this terminal persist. Refresh here so this op's+ // tool spend shows up without waiting for the next message mutation.+ // Idempotent (pure derived projection) and non-fatal.+ if (topicId) {+ try {+ await this.serverDB.transaction((trx) =>+ recomputeTopicUsage(trx, this.userId, topicId, this.workspaceId),+ );+ } catch (error) {+ log('[%s] Failed to recompute topic usage rollup (non-fatal): %O', operationId, error);+ }+ }}/** Best-effort child-usage rollup β a DB hiccup must not fail the completion write. */diff --git a/packages/database/src/models/__tests__/topics/topicUsage.race.test.ts b/packages/database/src/models/__tests__/topics/topicUsage.race.test.tsnew file mode 100644index 00000000000..5a2ca21f01d--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topicUsage.race.test.ts@@ -0,0 +1,111 @@+import { eq } from 'drizzle-orm';+import { afterAll, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agentOperations, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { recomputeTopicUsage } from '../../topicUsage';++// Real-Postgres reproduction of the lost-update interleave on the topic usage+// rollup (mirrors `topic.updateMetadata.race.test.ts`).+//+// `recomputeTopicUsage` is a read-aggregate-then-write projection. Without the+// up-front `SELECT β¦ FOR UPDATE` on the topic row, two concurrent completions+// can interleave so an older aggregate snapshot overwrites a newer rollup:+// A commits its operation row and reads the aggregates (missing B, not yet+// committed); B commits its op, recomputes A+B and writes it; then A's final+// UPDATE lands with A-only values β the tool spend stays undercounted until+// the next trigger.+//+// Under the client-db PGlite engine concurrent transactions serialize on the+// single session, so this passes trivially there; against a REAL node-postgres+// pool (`TEST_SERVER_DB=1`, separate connections β genuine interleave) it+// guards the row lock: every trial must count BOTH completions.++const userId = 'topic-usage-race-user';+const serverDB: LobeChatDatabase = await getTestDB();++const cleanup = async () => {+ await serverDB.delete(agentOperations).where(eq(agentOperations.userId, userId));+ await serverDB.delete(topics).where(eq(topics.userId, userId));+ await serverDB.delete(users).where(eq(users.id, userId));+};++/** The runtime's own-accumulator blobs for one op with a single tool call. */+const opBlobs = (toolName: string, toolCost: number) => ({+ cost: {+ calculatedAt: '2024-01-01T00:00:00.000Z',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: {+ byTool: [{ calls: 1, currency: 'USD', name: toolName, totalCost: toolCost }],+ currency: 'USD',+ total: toolCost,+ },+ total: toolCost,+ },+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: {+ byTool: [{ calls: 1, errors: 0, name: toolName, totalTimeMs: 100 }],+ totalCalls: 1,+ totalTimeMs: 100,+ },+ },+});++describe('recomputeTopicUsage β concurrent lost-update (real Postgres)', () => {+ beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: userId }]);+ });++ afterAll(cleanup);++ it('serializes concurrent completions so the rollup counts both', async () => {+ const TRIALS = 30;+ let undercounted = 0;++ for (let i = 0; i < TRIALS; i++) {+ const topicId = `usage-race-${i}`;+ await serverDB.insert(topics).values({ id: topicId, title: 't', userId });++ // Mirrors `CompletionLifecycle.persistCompletion`: write the terminal op+ // row, then recompute the topic rollup in its own transaction. Fired+ // concurrently so the read-aggregate-write sections can interleave.+ const complete = async (opId: string, toolName: string, toolCost: number) => {+ await serverDB.insert(agentOperations).values({+ ...opBlobs(toolName, toolCost),+ id: opId,+ status: 'done',+ topicId,+ userId,+ });+ await serverDB.transaction((trx) => recomputeTopicUsage(trx, userId, topicId));+ };++ await Promise.all([+ complete(`op-a-${i}`, 'web-search', 0.01),+ complete(`op-b-${i}`, 'code-runner', 0.02),+ ]);++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));+ const totalCalls = (topic?.usage as any)?.tools?.totalCalls;+ const costTotal = (topic?.cost as any)?.total;+ if (totalCalls !== 2 || Math.abs(Number(costTotal) - 0.03) > 1e-9) undercounted++;+ }++ console.log(`[topicUsage race] rollup undercounted in ${undercounted}/${TRIALS} trials`);++ // With the up-front row lock, the later recompute waits and re-reads after+ // the earlier one commits: every trial must include both completions. A+ // single undercount means the lost-update interleave is back.+ expect(undercounted).toBe(0);+ });+});diff --git a/packages/database/src/models/__tests__/topics/topicUsage.test.ts b/packages/database/src/models/__tests__/topics/topicUsage.test.tsindex f2b88ee9254..5ad301315f2 100644--- a/packages/database/src/models/__tests__/topics/topicUsage.test.ts+++ b/packages/database/src/models/__tests__/topics/topicUsage.test.ts@@ -3,7 +3,7 @@ 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 { agentOperations, messages, topics, users } from '../../../schemas';import type { LobeChatDatabase } from '../../../type';import { recomputeTopicUsage } from '../../topicUsage';@@ -60,6 +60,62 @@ const insertAssistantMessage = async (params: {return id;};+let opSeq = 0;++/**+ * Insert an `agent_operations` row carrying the runtime's own-accumulator+ * usage/cost blobs (the shape `CompletionLifecycle.persistCompletion` writes).+ */+const insertOperation = async (params: {+ cost?: Record<string, unknown> | null;+ id?: string;+ parentOperationId?: string;+ topicId?: string | null;+ usage?: Record<string, unknown> | null;+ userId?: string;+}) => {+ const id = params.id ?? `op-${(opSeq += 1)}`;+ await serverDB.insert(agentOperations).values({+ cost: params.cost ?? null,+ id,+ parentOperationId: params.parentOperationId ?? null,+ status: 'done',+ topicId: params.topicId === undefined ? topicId : params.topicId,+ usage: params.usage ?? null,+ userId: params.userId ?? userId,+ });+ return id;+};++const toolsUsage = (+ byTool: Array<{ calls: number; errors?: number; name: string; totalTimeMs: number }>,+) => ({+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: {+ byTool: byTool.map((t) => ({ errors: 0, ...t })),+ totalCalls: byTool.reduce((acc, t) => acc + t.calls, 0),+ totalTimeMs: byTool.reduce((acc, t) => acc + t.totalTimeMs, 0),+ },+});++const toolsCost = (byTool: Array<{ calls: number; name: string; totalCost: number }>) => ({+ calculatedAt: '2024-01-01T00:00:00.000Z',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: {+ byTool: byTool.map((t) => ({ currency: 'USD', ...t })),+ currency: 'USD',+ total: byTool.reduce((acc, t) => acc + t.totalCost, 0),+ },+ total: byTool.reduce((acc, t) => acc + t.totalCost, 0),+});+const recompute = (uid = userId, tid = topicId) =>serverDB.transaction((trx) => recomputeTopicUsage(trx, uid, tid));@@ -70,13 +126,17 @@ const getTopic = async (id = topicId) => {beforeEach(async () => {msgSeq = 0;+ opSeq = 0;await serverDB.delete(users);+ // agent_operations.user_id is intentionally not a FK β clean up explicitly.+ await serverDB.delete(agentOperations);await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);await serverDB.insert(topics).values({ id: topicId, userId });});afterEach(async () => {await serverDB.delete(users);+ await serverDB.delete(agentOperations);});describe('recomputeTopicUsage', () => {@@ -318,4 +378,182 @@ describe('recomputeTopicUsage', () => {expect(topic.model).toBeNull();expect(topic.provider).toBeNull();});++ it('short-circuits when the topic row is missing or owned by another user', async () => {+ await insertAssistantMessage({+ cost: 0.01,+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },+ });+ await recompute();+ expect((await getTopic()).totalTokens).toBe(15);++ // unknown topic id β the lock read matches nothing; no throw, no effect+ await recompute(userId, 'topic-usage-nonexistent');+ // another user recomputing this topic β not owned; must not reset/overwrite+ await recompute(otherUserId, topicId);++ expect((await getTopic()).totalTokens).toBe(15);+ });++ describe('operation-derived tool usage/cost', () => {+ it('rolls operation tool usage and cost into the topic; totals include tool cost', async () => {+ await insertAssistantMessage({+ cost: 0.002,+ usage: { totalInputTokens: 100, totalOutputTokens: 50, totalTokens: 150 },+ });+ await insertOperation({+ cost: toolsCost([{ calls: 2, name: 'web-search', totalCost: 0.03 }]),+ usage: toolsUsage([{ calls: 2, errors: 1, name: 'web-search', totalTimeMs: 800 }]),+ });++ await recompute();+ const topic = await getTopic();++ expect((topic.usage as any).tools).toEqual({+ byTool: [{ calls: 2, errors: 1, name: 'web-search', totalTimeMs: 800 }],+ totalCalls: 2,+ totalTimeMs: 800,+ });+ expect((topic.cost as any).tools).toEqual({+ byTool: [{ calls: 2, currency: 'USD', name: 'web-search', totalCost: 0.03 }],+ currency: 'USD',+ total: 0.03,+ });+ // llm side stays message-derived; grand totals include the tool spend+ expect((topic.cost as any).llm.total).toBeCloseTo(0.002, 6);+ expect((topic.cost as any).total).toBeCloseTo(0.032, 6);+ expect(topic.totalCost).toBeCloseTo(0.032, 6);+ expect(topic.totalTokens).toBe(150);+ });++ it('merges byTool across operations (same name summed, output sorted by name)', async () => {+ await insertAssistantMessage({+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },+ });+ await insertOperation({+ usage: toolsUsage([+ { calls: 2, errors: 1, name: 'web-search', totalTimeMs: 500 },+ { calls: 1, name: 'code-runner', totalTimeMs: 300 },+ ]),+ });+ await insertOperation({+ usage: toolsUsage([{ calls: 3, errors: 2, name: 'web-search', totalTimeMs: 700 }]),+ });++ await recompute();+ const topic = await getTopic();++ expect((topic.usage as any).tools).toEqual({+ byTool: [+ { calls: 1, errors: 0, name: 'code-runner', totalTimeMs: 300 },+ { calls: 5, errors: 3, name: 'web-search', totalTimeMs: 1200 },+ ],+ totalCalls: 6,+ totalTimeMs: 1500,+ });+ // no cost anywhere β cost stays NULL even though tools ran+ expect(topic.cost).toBeNull();+ expect(topic.totalCost).toBeNull();+ });++ it('counts a sub-agent child operation once (blobs are per-op own accumulators)', async () => {+ await insertAssistantMessage({+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },+ });+ const parentId = await insertOperation({+ usage: toolsUsage([{ calls: 1, name: 'callSubAgent', totalTimeMs: 100 }]),+ });+ await insertOperation({+ parentOperationId: parentId,+ usage: toolsUsage([{ calls: 4, name: 'web-search', totalTimeMs: 900 }]),+ });++ await recompute();+ const topic = await getTopic();++ expect((topic.usage as any).tools.totalCalls).toBe(5);+ expect((topic.usage as any).tools.totalTimeMs).toBe(1000);+ });++ it('ignores operations of another user, another topic, or without usage/cost', async () => {+ await insertAssistantMessage({+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },+ });+ await insertOperation({+ usage: toolsUsage([{ calls: 1, name: 'web-search', totalTimeMs: 100 }]),+ });+ // other user's op under the same topic id+ await insertOperation({+ usage: toolsUsage([{ calls: 9, name: 'web-search', totalTimeMs: 999 }]),+ userId: otherUserId,+ });+ // op without a topic linkage+ await insertOperation({+ topicId: null,+ usage: toolsUsage([{ calls: 9, name: 'web-search', totalTimeMs: 999 }]),+ });+ // running op that has not persisted any usage/cost yet+ await insertOperation({});++ await recompute();+ const topic = await getTopic();++ expect((topic.usage as any).tools).toEqual({+ byTool: [{ calls: 1, errors: 0, name: 'web-search', totalTimeMs: 100 }],+ totalCalls: 1,+ totalTimeMs: 100,+ });+ });++ it('writes a tools-only rollup when operations have data but no assistant usage exists', async () => {+ await insertOperation({+ cost: toolsCost([{ calls: 1, name: 'web-search', totalCost: 0.05 }]),+ usage: toolsUsage([{ calls: 1, name: 'web-search', totalTimeMs: 200 }]),+ });++ await recompute();+ const topic = await getTopic();++ // token scalars stay "not measured"; tool spend is still accounted+ expect(topic.totalInputTokens).toBeNull();+ expect(topic.totalOutputTokens).toBeNull();+ expect(topic.totalTokens).toBeNull();+ expect(topic.model).toBeNull();+ expect(topic.provider).toBeNull();+ expect(topic.totalCost).toBeCloseTo(0.05, 6);++ expect((topic.usage as any).llm).toEqual({+ apiCalls: 0,+ processingTimeMs: 0,+ tokens: { input: 0, output: 0, total: 0 },+ });+ expect((topic.usage as any).tools.totalCalls).toBe(1);+ expect((topic.cost as any).llm).toEqual({ byModel: [], currency: 'USD', total: 0 });+ expect((topic.cost as any).total).toBeCloseTo(0.05, 6);+ });++ it('aggregates humanInteraction stats from operations', async () => {+ await insertAssistantMessage({+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },+ });+ const usage = toolsUsage([]);+ usage.humanInteraction = {+ approvalRequests: 2,+ promptRequests: 1,+ selectRequests: 0,+ totalWaitingTimeMs: 4000,+ };+ await insertOperation({ usage });++ await recompute();+ const topic = await getTopic();++ expect((topic.usage as any).humanInteraction).toEqual({+ approvalRequests: 2,+ promptRequests: 1,+ selectRequests: 0,+ totalWaitingTimeMs: 4000,+ });+ });+ });});diff --git a/packages/database/src/models/topicUsage.ts b/packages/database/src/models/topicUsage.tsindex cd2e7221a61..8b047701ed6 100644--- a/packages/database/src/models/topicUsage.ts+++ b/packages/database/src/models/topicUsage.ts@@ -1,9 +1,39 @@-import { and, eq, sql } from 'drizzle-orm';+import { and, eq, type SQL, sql } from 'drizzle-orm';import { topics } from '../schemas';import type { Transaction } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';+interface ToolUsageEntry {+ calls: number;+ errors: number;+ name: string;+ totalTimeMs: number;+}++interface ToolCostEntry {+ calls: number;+ currency: string;+ name: string;+ totalCost: number;+}++interface HumanInteractionUsage {+ approvalRequests: number;+ promptRequests: number;+ selectRequests: number;+ totalWaitingTimeMs: 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. */+ hasData: boolean;+ humanInteraction: HumanInteractionUsage;+ toolsCost: { byTool: ToolCostEntry[]; total: number };+ toolsUsage: { byTool: ToolUsageEntry[]; totalCalls: number; totalTimeMs: number };+}+/*** ModelUsage numeric fields summed per (provider, model) to build the* `cost.llm.byModel[].usage` breakdown. Mirrors ModelUsageSchema in@@ -37,20 +67,143 @@ const USAGE_FIELDS = [const num = (v: unknown): number => (v == null ? 0 : Number(v));/**- * Recompute a topic's denormalized usage/cost rollup from its assistant messages.+ * Aggregate tool + human-interaction usage and tool cost from the topic's+ * `agent_operations` rows. This data only exists on operation rows β assistant+ * messages carry LLM usage but know nothing about tool execution.+ *+ * Reads the `usage` / `cost` jsonb blobs, which are contractually each op's OWN+ * accumulator (child spend is folded into the scalar columns only β see the+ * comment in `CompletionLifecycle.persistCompletion`). Sub-agent children and+ * group members are separate rows carrying the same `topic_id`, so summing the+ * blobs counts every op's spend exactly once, with no parent/child double count.+ * 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.+ */+const aggregateOperationUsage = async (+ trx: Transaction,+ ownership: SQL,+ topicId: string,+): Promise<OperationUsageRollup> => {+ const { rows } = await trx.execute(sql`+ SELECT+ usage->'tools' AS "toolsUsage",+ usage->'humanInteraction' AS "humanInteraction",+ cost->'tools' AS "toolsCost"+ FROM agent_operations+ WHERE topic_id = ${topicId}+ AND ${ownership}+ AND (usage IS NOT NULL OR cost IS NOT NULL)+ `);++ const usageByTool = new Map<string, ToolUsageEntry>();+ const costByTool = new Map<string, ToolCostEntry>();+ let totalCalls = 0;+ let totalTimeMs = 0;+ let costTotal = 0;+ const humanInteraction: HumanInteractionUsage = {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ };++ for (const row of rows as Array<Record<string, any>>) {+ const toolsUsage = row.toolsUsage;+ if (toolsUsage) {+ totalCalls += num(toolsUsage.totalCalls);+ totalTimeMs += num(toolsUsage.totalTimeMs);+ if (Array.isArray(toolsUsage.byTool)) {+ for (const entry of toolsUsage.byTool) {+ if (!entry?.name) continue;+ let merged = usageByTool.get(entry.name);+ if (!merged) {+ merged = { calls: 0, errors: 0, name: entry.name, totalTimeMs: 0 };+ usageByTool.set(entry.name, merged);+ }+ merged.calls += num(entry.calls);+ merged.errors += num(entry.errors);+ merged.totalTimeMs += num(entry.totalTimeMs);+ }+ }+ }++ const hi = row.humanInteraction;+ if (hi) {+ humanInteraction.approvalRequests += num(hi.approvalRequests);+ humanInteraction.promptRequests += num(hi.promptRequests);+ humanInteraction.selectRequests += num(hi.selectRequests);+ humanInteraction.totalWaitingTimeMs += num(hi.totalWaitingTimeMs);+ }++ const toolsCost = row.toolsCost;+ if (toolsCost) {+ costTotal += num(toolsCost.total);+ if (Array.isArray(toolsCost.byTool)) {+ for (const entry of toolsCost.byTool) {+ if (!entry?.name) continue;+ let merged = costByTool.get(entry.name);+ if (!merged) {+ merged = { calls: 0, currency: 'USD', name: entry.name, totalCost: 0 };+ costByTool.set(entry.name, merged);+ }+ merged.calls += num(entry.calls);+ merged.totalCost += num(entry.totalCost);+ }+ }+ }+ }++ const byName = <T extends { name: string }>(map: Map<string, T>) =>+ [...map.values()].sort((a, b) => a.name.localeCompare(b.name));++ const hasData =+ totalCalls > 0 ||+ totalTimeMs > 0 ||+ costTotal > 0 ||+ usageByTool.size > 0 ||+ costByTool.size > 0 ||+ Object.values(humanInteraction).some((v) => v > 0);++ return {+ hasData,+ humanInteraction,+ toolsCost: { byTool: byName(costByTool), total: costTotal },+ toolsUsage: { byTool: byName(usageByTool), totalCalls, totalTimeMs },+ };+};++/**+ * Recompute a topic's denormalized usage/cost rollup.+ *+ * Pure derived projection over two sources:+ * 1. LLM tokens/cost: SUM over the topic's `role='assistant'` messages+ * (thread messages count too β they also carry `topic_id`), preferring the+ * dedicated `usage` column and falling back to legacy `metadata.usage`.+ * 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.*- * Pure derived projection: SUM over the topic's `role='assistant'` messages- * (thread messages count too β they also carry `topic_id`), preferring the- * dedicated `usage` column and falling back to legacy `metadata.usage`. The- * stored shape mirrors `agent_operations`:+ * 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+ * - `cost` jsonb : { total, currency, llm: { total, currency, byModel[] }, tools } β or NULL when nothing reported cost* - model/provider : the dominant model by total_tokens+ * `total_cost` / `cost.total` include tool cost on top of LLM cost.+ *+ * Idempotent and non-cumulative: when neither source has measurable usage, the+ * columns are reset to NULL ("not measured"). Note the deletion asymmetry: LLM+ * stats follow the live messages (deletions / regenerations drop out), while+ * tool stats follow the operation audit rows, which survive message deletion β+ * that spend really happened, so it stays counted as long as the ops exist.*- * 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.+ * Concurrency: the owned topic row is locked (`FOR UPDATE`) BEFORE the+ * aggregate reads. Without it, two concurrent recomputes can interleave so+ * that an older aggregate snapshot overwrites a newer rollup (lost update),+ * undercounting until the next trigger. Writers already serialized on the row+ * lock at the final UPDATE β taking it up front makes the read+write atomic+ * per topic (blocked waiters re-read after the holder commits; READ COMMITTED+ * gives each new statement a fresh snapshot) without changing lock order.** Keep activity timestamps stable: recency is derived from `messages.updated_at`,* so this projection update must not bump `topics.updated_at` / `accessed_at`.@@ -58,7 +211,7 @@ const num = (v: unknown): number => (v == null ? 0 : Number(v));* themselves.** TODO: This still updates the `topics` row for usage/cost/token rollups. Under- * high-concurrency assistant finalization for the same topic, it can still+ * high-concurrency assistant finalization for the same topic, recomputes* serialize on the topic row lock. Consider moving this projection to a* debounced/asynchronous rollup or a separate per-topic usage table.*/@@ -68,16 +221,30 @@ export const recomputeTopicUsage = async (topicId: string,workspaceId?: string,): Promise<void> => {+ // Serialize concurrent recomputes for the same topic before any aggregate+ // read (see the concurrency note above). Every caller touches messages /+ // agent_operations before topics, so taking the topic lock last in that+ // order introduces no new deadlock path. Also short-circuits when the topic+ // row is missing or not owned β the final UPDATE could never match anyway.+ const [locked] = await trx+ .select({ id: topics.id })+ .from(topics)+ .where(and(eq(topics.id, topicId), buildWorkspaceWhere({ userId, workspaceId }, topics)))+ .for('update');++ if (!locked) return;+// Reads prefer the dedicated `usage` column, falling back to legacy// `metadata->'usage'` for rows written before the migration.const fieldSelects = USAGE_FIELDS.map((f) => `sum((COALESCE(usage, metadata->'usage')->>'${f}')::numeric) AS "${f}"`,).join(',\n ');- // Workspace-aware ownership predicate for the raw messages aggregate: in team- // mode rows are scoped by workspace_id (creator user_id is not part of the- // filter); in personal mode by user_id with workspace_id IS NULL.- const messageOwnership = workspaceId+ // Workspace-aware ownership predicate for the raw aggregates (messages and+ // agent_operations both carry user_id/workspace_id): in team mode rows are+ // scoped by workspace_id (creator user_id is not part of the filter); in+ // personal mode by user_id with workspace_id IS NULL.+ const rowOwnership = workspaceId? sql`workspace_id = ${workspaceId}`: sql`user_id = ${userId} AND workspace_id IS NULL`;@@ -91,7 +258,7 @@ export const recomputeTopicUsage = async (${sql.raw(fieldSelects)}FROM messagesWHERE topic_id = ${topicId}- AND ${messageOwnership}+ AND ${rowOwnership}AND role = 'assistant'AND (usage IS NOT NULL OR metadata ? 'usage')GROUP BY provider, model@@ -99,8 +266,11 @@ export const recomputeTopicUsage = async (const groups = rows as Array<Record<string, unknown>>;- // No measurable usage left β reset to NULL so the column reflects reality.- if (groups.length === 0) {+ const ops = await aggregateOperationUsage(trx, rowOwnership, topicId);++ // No measurable usage left in either source β reset to NULL so the columns+ // reflect reality.+ if (groups.length === 0 && !ops.hasData) {await trx.update(topics).set({@@ -170,31 +340,33 @@ export const recomputeTopicUsage = async (}const usage = {- humanInteraction: {- approvalRequests: 0,- promptRequests: 0,- selectRequests: 0,- totalWaitingTimeMs: 0,- },+ humanInteraction: ops.humanInteraction,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 },+ tools: ops.toolsUsage,};- const cost = hasCost+ // Tool cost rides on top of the LLM cost: `total_cost` / `cost.total` carry+ // the whole topic spend, while `cost.llm.total` stays LLM-only.+ const toolCostTotal = ops.toolsCost.total;+ const hasAnyCost = hasCost || toolCostTotal > 0;++ const cost = hasAnyCost? {currency: 'USD',llm: { byModel, currency: 'USD', total: totalCost },- total: totalCost,- tools: { byTool: [], currency: 'USD', total: 0 },+ total: totalCost + toolCostTotal,+ tools: { byTool: ops.toolsCost.byTool, currency: 'USD', total: toolCostTotal },}: null;+ // Token scalar columns stay message-derived: with no assistant usage rows the+ // tokens are "not measured" (NULL), even when operations contributed tool stats.+ const hasLlmGroups = groups.length > 0;+await trx.update(topics).set({@@ -202,10 +374,10 @@ export const recomputeTopicUsage = async (cost,model: primary?.model ?? null,provider: primary?.provider ?? null,- totalCost: hasCost ? totalCost : null,- totalInputTokens,- totalOutputTokens,- totalTokens,+ totalCost: hasAnyCost ? totalCost + toolCostTotal : null,+ totalInputTokens: hasLlmGroups ? totalInputTokens : null,+ totalOutputTokens: hasLlmGroups ? totalOutputTokens : null,+ totalTokens: hasLlmGroups ? totalTokens : null,updatedAt: topics.updatedAt,usage,})