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.

✨ feat(cli): constrained analytics query layer for lh (#16395)

Arvin Xu57870103dc32
diff --git a/apps/cli/src/commands/config.ts b/apps/cli/src/commands/config.ts
index 09a415289bd..ca197a8b1e3 100644
--- a/apps/cli/src/commands/config.ts
+++ b/apps/cli/src/commands/config.ts
@@ -43,13 +43,15 @@ export function registerConfigCommand(program: Command) {
.command('usage')
.description('View usage statistics')
.option('--month <YYYY-MM>', 'Month to query (default: current)')
+ .option('--agent-id <id>', 'Filter usage to a single agent')
.option('--daily', 'Group by day')
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
- .action(async (options: { daily?: boolean; json?: string | boolean; month?: string }) => {
+ .action(async (options: { agentId?: string; daily?: boolean; json?: string | boolean; month?: string }) => {
const client = await getTrpcClient();
- const input: { mo?: string } = {};
+ const input: { agentId?: string; mo?: string } = {};
if (options.month) input.mo = options.month;
+ if (options.agentId) input.agentId = options.agentId;
if (options.json !== undefined) {
let jsonResult: any;
@@ -163,6 +165,7 @@ export function registerConfigCommand(program: Command) {
try {
// Try single-request endpoint first
yearLogs = await client.usage.findAndGroupByDateRange.query({
+ agentId: input.agentId,
endAt: now.toISOString().slice(0, 10),
startAt: rangeStart.toISOString().slice(0, 10),
});
@@ -174,7 +177,7 @@ export function registerConfigCommand(program: Command) {
monthKeys.push(d.toISOString().slice(0, 7));
}
const results = await Promise.all(
- monthKeys.map((mo) => client.usage.findAndGroupByDay.query({ mo })),
+ monthKeys.map((mo) => client.usage.findAndGroupByDay.query({ agentId: input.agentId, mo })),
);
yearLogs = results.flat();
}
diff --git a/apps/cli/src/commands/message.test.ts b/apps/cli/src/commands/message.test.ts
index 2013e171a6c..a8644a89348 100644
--- a/apps/cli/src/commands/message.test.ts
+++ b/apps/cli/src/commands/message.test.ts
@@ -7,12 +7,14 @@ const { mockTrpcClient } = vi.hoisted(() => ({
mockTrpcClient: {
message: {
count: { query: vi.fn() },
+ countByTopic: { query: vi.fn() },
getHeatmaps: { query: vi.fn() },
getMessages: { query: vi.fn() },
listAll: { query: vi.fn() },
removeMessage: { mutate: vi.fn() },
removeMessages: { mutate: vi.fn() },
searchMessages: { query: vi.fn() },
+ topicStats: { query: vi.fn() },
},
},
}));
@@ -185,5 +187,115 @@ describe('message command', () => {
expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify({ count: 42 }));
});
+
+ it('should forward topic / agent / role filters', async () => {
+ mockTrpcClient.message.count.query.mockResolvedValue(3);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'message',
+ 'count',
+ '--topic-id',
+ 't1',
+ '--agent-id',
+ 'a1',
+ '--role',
+ 'user',
+ ]);
+
+ expect(mockTrpcClient.message.count.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ role: 'user',
+ topicId: 't1',
+ });
+ });
+
+ it('should group by topic', async () => {
+ mockTrpcClient.message.countByTopic.query.mockResolvedValue([
+ { count: 7, topicId: 't1' },
+ { count: 2, topicId: 't2' },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'message',
+ 'count',
+ '--group-by',
+ 'topic',
+ '--agent-id',
+ 'a1',
+ '--json',
+ ]);
+
+ expect(mockTrpcClient.message.countByTopic.query).toHaveBeenCalledWith({ agentId: 'a1' });
+ expect(mockTrpcClient.message.count.query).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ JSON.stringify([
+ { count: 7, topicId: 't1' },
+ { count: 2, topicId: 't2' },
+ ]),
+ );
+ });
+
+ it('should reject an unsupported --group-by', async () => {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'count', '--group-by', 'agent']);
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(mockTrpcClient.message.countByTopic.query).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('stats', () => {
+ const sampleStats = {
+ histogram: [
+ { topics: 1, userCount: 1 },
+ { topics: 1, userCount: 5 },
+ ],
+ max: 5,
+ mean: 3,
+ median: 3,
+ min: 1,
+ oneshot: 1,
+ oneshotRatio: 0.5,
+ p90: 5,
+ p99: 5,
+ topics: 2,
+ totalMessages: 6,
+ };
+
+ it('should default to user-role distribution', async () => {
+ mockTrpcClient.message.topicStats.query.mockResolvedValue(sampleStats);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'stats', '--agent-id', 'a1']);
+
+ expect(mockTrpcClient.message.topicStats.query).toHaveBeenCalledWith({
+ agentId: 'a1',
+ role: 'user',
+ });
+ });
+
+ it('should support --all-roles', async () => {
+ mockTrpcClient.message.topicStats.query.mockResolvedValue(sampleStats);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'stats', '--all-roles']);
+
+ expect(mockTrpcClient.message.topicStats.query).toHaveBeenCalledWith({});
+ });
+
+ it('should output JSON', async () => {
+ mockTrpcClient.message.topicStats.query.mockResolvedValue(sampleStats);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'message', 'stats', '--json']);
+
+ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(sampleStats, null, 2));
+ });
});
});
diff --git a/apps/cli/src/commands/message.ts b/apps/cli/src/commands/message.ts
index 01871adffd4..2bae5e5b43a 100644
--- a/apps/cli/src/commands/message.ts
+++ b/apps/cli/src/commands/message.ts
@@ -141,26 +141,143 @@ export function registerMessageCommand(program: Command) {
message
.command('count')
- .description('Count messages')
+ .description('Count messages, optionally grouped by topic')
+ .option('--topic-id <id>', 'Filter by topic ID')
+ .option('--agent-id <id>', 'Filter by agent ID')
+ .option('--role <role>', 'Filter by role (user, assistant, system)')
.option('--start <date>', 'Start date (ISO format)')
.option('--end <date>', 'End date (ISO format)')
+ .option('--group-by <field>', 'Group counts by field (topic)')
.option('--json', 'Output JSON')
- .action(async (options: { end?: string; json?: boolean; start?: string }) => {
- const client = await getTrpcClient();
+ .action(
+ async (options: {
+ agentId?: string;
+ end?: string;
+ groupBy?: string;
+ json?: boolean;
+ role?: string;
+ start?: string;
+ topicId?: string;
+ }) => {
+ const client = await getTrpcClient();
- const input: Record<string, any> = {};
- if (options.start) input.startDate = options.start;
- if (options.end) input.endDate = options.end;
+ const input: Record<string, any> = {};
+ if (options.topicId) input.topicId = options.topicId;
+ if (options.agentId) input.agentId = options.agentId;
+ if (options.role) input.role = options.role;
+ if (options.start) input.startDate = options.start;
+ if (options.end) input.endDate = options.end;
- const count = await client.message.count.query(input as any);
+ if (options.groupBy && options.groupBy !== 'topic') {
+ log.error(`Unsupported --group-by "${options.groupBy}". Only "topic" is supported.`);
+ process.exit(1);
+ }
- if (options.json) {
- console.log(JSON.stringify({ count }));
- return;
- }
+ if (options.groupBy === 'topic') {
+ const rows = (await client.message.countByTopic.query(input as any)) as {
+ count: number;
+ topicId: string;
+ }[];
- console.log(`Messages: ${pc.bold(String(count))}`);
- });
+ if (options.json) {
+ console.log(JSON.stringify(rows));
+ return;
+ }
+
+ if (rows.length === 0) {
+ console.log('No messages.');
+ return;
+ }
+
+ printTable(
+ rows.map((r) => [r.topicId, String(r.count)]),
+ ['TOPIC', 'COUNT'],
+ );
+ return;
+ }
+
+ const count = await client.message.count.query(input as any);
+
+ if (options.json) {
+ console.log(JSON.stringify({ count }));
+ return;
+ }
+
+ console.log(`Messages: ${pc.bold(String(count))}`);
+ },
+ );
+
+ // ── stats ─────────────────────────────────────────────
+
+ message
+ .command('stats')
+ .description('Distribution of message counts per topic (mean/median/p90/p99/one-shot)')
+ .option('--agent-id <id>', 'Filter by agent ID')
+ .option('--role <role>', 'Filter by role (default: user)')
+ .option('--all-roles', 'Include every role instead of only user messages')
+ .option('--start <date>', 'Start date (ISO format)')
+ .option('--end <date>', 'End date (ISO format)')
+ .option('--json', 'Output JSON')
+ .action(
+ async (options: {
+ agentId?: string;
+ allRoles?: boolean;
+ end?: string;
+ json?: boolean;
+ role?: string;
+ start?: string;
+ }) => {
+ const client = await getTrpcClient();
+
+ const input: Record<string, any> = {};
+ if (options.agentId) input.agentId = options.agentId;
+ // Default to user messages β€” the common "how many turns per topic" question.
+ if (!options.allRoles) input.role = options.role || 'user';
+ else if (options.role) input.role = options.role;
+ if (options.start) input.startDate = options.start;
+ if (options.end) input.endDate = options.end;
+
+ const stats = (await client.message.topicStats.query(input as any)) as {
+ histogram: { topics: number; userCount: number }[];
+ max: number;
+ mean: number;
+ median: number;
+ min: number;
+ oneshot: number;
+ oneshotRatio: number;
+ p90: number;
+ p99: number;
+ topics: number;
+ totalMessages: number;
+ };
+
+ if (options.json) {
+ console.log(JSON.stringify(stats, null, 2));
+ return;
+ }
+
+ if (stats.topics === 0) {
+ console.log('No topics match the given filters.');
+ return;
+ }
+
+ const round = (n: number) => Math.round(n * 100) / 100;
+ printTable(
+ [
+ ['Topics', String(stats.topics)],
+ ['Total messages', String(stats.totalMessages)],
+ ['Mean', String(round(stats.mean))],
+ ['Median', String(round(stats.median))],
+ ['P90', String(round(stats.p90))],
+ ['P99', String(round(stats.p99))],
+ ['Min', String(stats.min)],
+ ['Max', String(stats.max)],
+ ['One-shot', `${stats.oneshot} (${(stats.oneshotRatio * 100).toFixed(1)}%)`],
+ ],
+ ['METRIC', 'VALUE'],
+ );
+ },
+ );
// ── create ────────────────────────────────────────────
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 4bee704054e..2c728731d11 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -40,6 +40,20 @@ const messageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
});
});
+/**
+ * Shared input for the ownership-scoped message analytics queries
+ * (count / countByTopic / topicStats). Every field is an optional filter
+ * applied on top of the `userId Γ— workspace` ownership predicate.
+ */
+const messageAnalyticsSchema = z.object({
+ agentId: z.string().optional(),
+ endDate: z.string().optional(),
+ range: z.tuple([z.string(), z.string()]).optional(),
+ role: z.string().optional(),
+ startDate: z.string().optional(),
+ topicId: z.string().optional(),
+});
+
export const messageRouter = router({
addFilesToMessage: messageProcedure
.use(withScopedPermission('message:update'))
@@ -102,19 +116,21 @@ export const messageRouter = router({
}),
count: messageProcedure
- .input(
- z
- .object({
- endDate: z.string().optional(),
- range: z.tuple([z.string(), z.string()]).optional(),
- startDate: z.string().optional(),
- })
- .optional(),
- )
+ .input(messageAnalyticsSchema.optional())
.query(async ({ ctx, input }) => {
return ctx.messageModel.count(input);
}),
+ /**
+ * Count messages grouped by topic (server-side GROUP BY), sorted by count
+ * desc. Optionally scoped by agent / role / date range.
+ */
+ countByTopic: messageProcedure
+ .input(messageAnalyticsSchema.optional())
+ .query(async ({ ctx, input }) => {
+ return ctx.messageModel.countGroupByTopic(input);
+ }),
+
countWords: messageProcedure
.input(
z
@@ -260,6 +276,17 @@ export const messageRouter = router({
return ctx.messageModel.rankModels();
}),
+ /**
+ * Distribution of message counts per topic (topics / mean / median / p90 /
+ * p99 / one-shot ratio + histogram). Aggregated server-side; optionally
+ * scoped by agent / role / date range.
+ */
+ topicStats: messageProcedure
+ .input(messageAnalyticsSchema.optional())
+ .query(async ({ ctx, input }) => {
+ return ctx.messageModel.topicMessageStats(input);
+ }),
+
removeAllMessages: messageProcedure
.use(withScopedPermission('message:delete'))
.mutation(async ({ ctx }) => {
diff --git a/apps/server/src/routers/lambda/usage.ts b/apps/server/src/routers/lambda/usage.ts
index 9fd08170eb6..96c53e7caed 100644
--- a/apps/server/src/routers/lambda/usage.ts
+++ b/apps/server/src/routers/lambda/usage.ts
@@ -22,31 +22,38 @@ export const usageRouter = router({
findAndGroupByDateRange: usageProcedure
.input(
z.object({
+ agentId: z.string().optional(),
endAt: z.string(),
startAt: z.string(),
}),
)
.query(async ({ ctx, input }) => {
- return await ctx.usageRecordService.findAndGroupByDateRange(input.startAt, input.endAt);
+ return await ctx.usageRecordService.findAndGroupByDateRange(
+ input.startAt,
+ input.endAt,
+ input.agentId,
+ );
}),
findAndGroupByDay: usageProcedure
.input(
z.object({
+ agentId: z.string().optional(),
mo: z.string().optional(),
}),
)
.query(async ({ ctx, input }) => {
- return await ctx.usageRecordService.findAndGroupByDay(input.mo);
+ return await ctx.usageRecordService.findAndGroupByDay(input.mo, input.agentId);
}),
findByMonth: usageProcedure
.input(
z.object({
+ agentId: z.string().optional(),
mo: z.string().optional(),
}),
)
.query(async ({ ctx, input }) => {
- return await ctx.usageRecordService.findByMonth(input.mo);
+ return await ctx.usageRecordService.findByMonth(input.mo, input.agentId);
}),
});
diff --git a/apps/server/src/services/usage/index.test.ts b/apps/server/src/services/usage/index.test.ts
index c9902747367..993f92ed670 100644
--- a/apps/server/src/services/usage/index.test.ts
+++ b/apps/server/src/services/usage/index.test.ts
@@ -162,6 +162,14 @@ describe('UsageRecordService', () => {
expect(result).toHaveLength(0);
});
+
+ it('forwards agentId to findByDateRange', async () => {
+ const spy = vi.spyOn(service, 'findByDateRange').mockResolvedValue([]);
+
+ await service.findByMonth('2024-01', 'agent-42');
+
+ expect(spy).toHaveBeenCalledWith(expect.any(String), expect.any(String), 'agent-42');
+ });
});
describe('findAndGroupByDay', () => {
@@ -308,6 +316,14 @@ describe('UsageRecordService', () => {
}
});
+ it('forwards agentId to findByDateRange', async () => {
+ const spy = vi.spyOn(service, 'findByDateRange').mockResolvedValue([]);
+
+ await service.findAndGroupByDay('2024-01', 'agent-99');
+
+ expect(spy).toHaveBeenCalledWith(expect.any(String), expect.any(String), 'agent-99');
+ });
+
it('should handle specific month parameter', async () => {
const mockMessages = [
{
diff --git a/apps/server/src/services/usage/index.ts b/apps/server/src/services/usage/index.ts
index b3c4c5d37f1..b4c4f52b695 100644
--- a/apps/server/src/services/usage/index.ts
+++ b/apps/server/src/services/usage/index.ts
@@ -24,8 +24,13 @@ export class UsageRecordService {
/**
* @description Find usage records by date range.
+ * @param agentId Optional agent id to attribute usage to a single agent.
*/
- findByDateRange = async (startAt: string, endAt: string): Promise<UsageRecordItem[]> => {
+ findByDateRange = async (
+ startAt: string,
+ endAt: string,
+ agentId?: string,
+ ): Promise<UsageRecordItem[]> => {
const spends = await this.db
.select({
createdAt: messages.createdAt,
@@ -46,6 +51,7 @@ export class UsageRecordService {
{ userId: messages.userId, workspaceId: messages.workspaceId },
),
eq(messages.role, 'assistant'),
+ agentId ? eq(messages.agentId, agentId) : undefined,
genRangeWhere([startAt, endAt], messages.createdAt, (date) => date.toDate()),
]),
)
@@ -83,7 +89,7 @@ export class UsageRecordService {
* @param mo Month
* @returns UsageRecordItem[]
*/
- findByMonth = async (mo?: string): Promise<UsageRecordItem[]> => {
+ findByMonth = async (mo?: string, agentId?: string): Promise<UsageRecordItem[]> => {
let startAt: string;
let endAt: string;
if (mo && dayjs(mo, 'YYYY-MM', true).isValid()) {
@@ -93,7 +99,7 @@ export class UsageRecordService {
startAt = dayjs().startOf('month').format('YYYY-MM-DD');
endAt = dayjs().endOf('month').format('YYYY-MM-DD');
}
- return this.findByDateRange(startAt, endAt);
+ return this.findByDateRange(startAt, endAt, agentId);
};
/**
@@ -170,7 +176,7 @@ export class UsageRecordService {
return paddedUsageLogs;
};
- findAndGroupByDay = async (mo?: string): Promise<UsageLog[]> => {
+ findAndGroupByDay = async (mo?: string, agentId?: string): Promise<UsageLog[]> => {
let startAt: string;
let endAt: string;
if (mo && dayjs(mo, 'YYYY-MM', true).isValid()) {
@@ -180,7 +186,7 @@ export class UsageRecordService {
startAt = dayjs().startOf('month').format('YYYY-MM-DD');
endAt = dayjs().endOf('month').format('YYYY-MM-DD');
}
- const spends = await this.findByDateRange(startAt, endAt);
+ const spends = await this.findByDateRange(startAt, endAt, agentId);
return this.groupByDay(spends, startAt, endAt);
};
@@ -188,8 +194,12 @@ export class UsageRecordService {
* @description Find usage grouped by day for a custom date range (e.g. past 12 months).
* Does not pad missing days for large ranges.
*/
- findAndGroupByDateRange = async (startAt: string, endAt: string): Promise<UsageLog[]> => {
- const spends = await this.findByDateRange(startAt, endAt);
+ findAndGroupByDateRange = async (
+ startAt: string,
+ endAt: string,
+ agentId?: string,
+ ): Promise<UsageLog[]> => {
+ const spends = await this.findByDateRange(startAt, endAt, agentId);
return this.groupByDay(spends, startAt, endAt, false);
};
}
diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.ts
index 07e176d3f42..f14005d7b22 100644
--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts
@@ -702,6 +702,178 @@ describe('MessageModel Statistics Tests', () => {
});
});
+ describe('count with agent / topic / role filters', () => {
+ const agentId = 'agent-count-filters';
+ const topicA = 'topic-count-a';
+ const topicB = 'topic-count-b';
+
+ beforeEach(async () => {
+ await serverDB.insert(agents).values([
+ { id: agentId, userId },
+ { id: 'agent-other', userId },
+ ]);
+ await serverDB.insert(topics).values([
+ { id: topicA, userId, agentId, title: 'a' },
+ { id: topicB, userId, agentId, title: 'b' },
+ ]);
+ await serverDB.insert(messages).values([
+ { id: 'cf1', userId, role: 'user', content: 'q', agentId, topicId: topicA },
+ { id: 'cf2', userId, role: 'assistant', content: 'a', agentId, topicId: topicA },
+ { id: 'cf3', userId, role: 'user', content: 'q2', agentId, topicId: topicB },
+ // another agent / no topic
+ { id: 'cf4', userId, role: 'user', content: 'other', agentId: 'agent-other' },
+ ]);
+ });
+
+ it('filters by agentId', async () => {
+ expect(await messageModel.count({ agentId })).toBe(3);
+ });
+
+ it('filters by topicId', async () => {
+ expect(await messageModel.count({ topicId: topicA })).toBe(2);
+ });
+
+ it('filters by role', async () => {
+ expect(await messageModel.count({ agentId, role: 'user' })).toBe(2);
+ });
+
+ it('combines filters', async () => {
+ expect(await messageModel.count({ agentId, role: 'user', topicId: topicB })).toBe(1);
+ });
+ });
+
+ describe('countGroupByTopic', () => {
+ const agentId = 'agent-count-by-topic';
+ const topicA = 'topic-cbt-a';
+ const topicB = 'topic-cbt-b';
+
+ beforeEach(async () => {
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ await serverDB.insert(topics).values([
+ { id: topicA, userId, agentId, title: 'a' },
+ { id: topicB, userId, agentId, title: 'b' },
+ ]);
+ await serverDB.insert(messages).values([
+ { id: 'g1', userId, role: 'user', content: '1', agentId, topicId: topicA },
+ { id: 'g2', userId, role: 'user', content: '2', agentId, topicId: topicA },
+ { id: 'g3', userId, role: 'user', content: '3', agentId, topicId: topicA },
+ { id: 'g4', userId, role: 'user', content: '4', agentId, topicId: topicB },
+ // assistant + null-topic rows must be excluded by role / topic filters
+ { id: 'g5', userId, role: 'assistant', content: 'x', agentId, topicId: topicA },
+ { id: 'g6', userId, role: 'user', content: 'no-topic', agentId },
+ // other user must not leak
+ { id: 'g7', userId: otherUserId, role: 'user', content: 'leak', topicId: topicA },
+ ]);
+ });
+
+ it('returns per-topic counts sorted by count desc', async () => {
+ const result = await messageModel.countGroupByTopic({ agentId, role: 'user' });
+ expect(result).toEqual([
+ { count: 3, topicId: topicA },
+ { count: 1, topicId: topicB },
+ ]);
+ });
+
+ it('excludes rows without a topicId', async () => {
+ const result = await messageModel.countGroupByTopic({ agentId });
+ // g6 (no topic) excluded; topicA has 3 user + 1 assistant = 4, topicB has 1
+ expect(result).toEqual([
+ { count: 4, topicId: topicA },
+ { count: 1, topicId: topicB },
+ ]);
+ });
+ });
+
+ describe('topicMessageStats', () => {
+ const agentId = 'agent-topic-stats';
+ const otherAgentId = 'agent-topic-stats-other';
+
+ beforeEach(async () => {
+ await serverDB.insert(agents).values([
+ { id: agentId, userId },
+ { id: otherAgentId, userId },
+ ]);
+ // 4 topics under agentId with 1 / 2 / 3 / 4 user messages each,
+ // plus one topic under another agent that must be excluded by the filter.
+ const topicRows = [
+ { id: 's-t1', count: 1 },
+ { id: 's-t2', count: 2 },
+ { id: 's-t3', count: 3 },
+ { id: 's-t4', count: 4 },
+ ];
+ await serverDB.insert(topics).values([
+ ...topicRows.map((t) => ({ id: t.id, userId, agentId, title: t.id })),
+ { id: 's-other', userId, agentId: otherAgentId, title: 'other' },
+ ]);
+
+ const msgRows = topicRows.flatMap((t) =>
+ Array.from({ length: t.count }).map((_, i) => ({
+ id: `${t.id}-u${i}`,
+ userId,
+ role: 'user',
+ content: `m${i}`,
+ agentId,
+ topicId: t.id,
+ })),
+ );
+ await serverDB.insert(messages).values([
+ ...msgRows,
+ // assistant messages in agentId topics β€” excluded by role=user
+ { id: 's-t1-a', userId, role: 'assistant', content: 'a', agentId, topicId: 's-t1' },
+ // other agent's topic
+ { id: 's-other-u', userId, role: 'user', content: 'x', agentId: otherAgentId, topicId: 's-other' },
+ // other user must not leak
+ { id: 's-leak', userId: otherUserId, role: 'user', content: 'leak', topicId: 's-t1' },
+ ]);
+ });
+
+ it('computes the per-topic distribution scoped by agent + role', async () => {
+ const stats = await messageModel.topicMessageStats({ agentId, role: 'user' });
+
+ expect(stats.topics).toBe(4);
+ expect(stats.totalMessages).toBe(10);
+ expect(stats.min).toBe(1);
+ expect(stats.max).toBe(4);
+ expect(stats.mean).toBe(2.5);
+ // percentile_cont over [1,2,3,4]
+ expect(stats.median).toBeCloseTo(2.5);
+ expect(stats.p90).toBeCloseTo(3.7);
+ expect(stats.oneshot).toBe(1);
+ expect(stats.oneshotRatio).toBeCloseTo(0.25);
+ expect(stats.histogram).toEqual([
+ { topics: 1, userCount: 1 },
+ { topics: 1, userCount: 2 },
+ { topics: 1, userCount: 3 },
+ { topics: 1, userCount: 4 },
+ ]);
+ });
+
+ it('returns an all-zero summary when nothing matches', async () => {
+ const stats = await messageModel.topicMessageStats({ agentId: 'no-such-agent' });
+ expect(stats).toEqual({
+ histogram: [],
+ max: 0,
+ mean: 0,
+ median: 0,
+ min: 0,
+ oneshot: 0,
+ oneshotRatio: 0,
+ p90: 0,
+ p99: 0,
+ topics: 0,
+ totalMessages: 0,
+ });
+ });
+
+ it('does not leak other users’ topics', async () => {
+ const otherModel = new MessageModel(serverDB, otherUserId);
+ const stats = await otherModel.topicMessageStats({ role: 'user' });
+ // otherUser only has the single leaked message in s-t1
+ expect(stats.topics).toBe(1);
+ expect(stats.totalMessages).toBe(1);
+ });
+ });
+
describe('hasMoreThanN', () => {
it('should return true when message count is greater than N', async () => {
// Create test data
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 7a2e3198240..ea6d45cbaae 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -192,6 +192,111 @@ interface SplitCreateMessageParams {
relations: CreateMessageRelationParams;
}
+/**
+ * Shared, ownership-scoped filters for the analytics queries
+ * (count / countGroupByTopic / topicMessageStats). All of these are
+ * applied on top of the workspace ownership predicate, so the resulting
+ * query never leaks across `userId Γ— workspace`.
+ */
+export interface MessageAnalyticsFilters {
+ agentId?: string;
+ endDate?: string;
+ range?: [string, string];
+ role?: string;
+ startDate?: string;
+ topicId?: string;
+}
+
+/** A single `{ topicId, count }` row from a per-topic count aggregation. */
+export interface TopicMessageCountItem {
+ count: number;
+ topicId: string;
+}
+
+/**
+ * Distribution of message counts per topic, computed server-side.
+ * Mirrors what a `SELECT count(*) ... GROUP BY topic_id` + percentile
+ * aggregation would produce, so the CLI receives only the summary instead
+ * of paginating raw rows.
+ */
+export interface TopicMessageStats {
+ /** Per distinct message-count value, how many topics have it. Ascending. */
+ histogram: { topics: number; userCount: number }[];
+ max: number;
+ mean: number;
+ median: number;
+ min: number;
+ /** Number of topics with exactly one matching message ("one-shot"). */
+ oneshot: number;
+ /** oneshot / topics, in [0, 1]. 0 when there are no topics. */
+ oneshotRatio: number;
+ p90: number;
+ p99: number;
+ /** Number of topics that have at least one matching message. */
+ topics: number;
+ /** Total matching messages across all topics. */
+ totalMessages: number;
+}
+
+/**
+ * Linear-interpolation percentile over an ascending-sorted array, matching
+ * PostgreSQL's `percentile_cont`. Returns 0 for an empty input.
+ */
+const percentileCont = (sorted: number[], q: number): number => {
+ const n = sorted.length;
+ if (n === 0) return 0;
+ if (n === 1) return sorted[0];
+ const rank = q * (n - 1);
+ const lo = Math.floor(rank);
+ const hi = Math.ceil(rank);
+ if (lo === hi) return sorted[lo];
+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (rank - lo);
+};
+
+/** Reduce a list of per-topic message counts into a {@link TopicMessageStats}. */
+const computeTopicMessageStats = (counts: number[]): TopicMessageStats => {
+ const topics = counts.length;
+ if (topics === 0) {
+ return {
+ histogram: [],
+ max: 0,
+ mean: 0,
+ median: 0,
+ min: 0,
+ oneshot: 0,
+ oneshotRatio: 0,
+ p90: 0,
+ p99: 0,
+ topics: 0,
+ totalMessages: 0,
+ };
+ }
+
+ const sorted = [...counts].sort((a, b) => a - b);
+ const totalMessages = sorted.reduce((acc, c) => acc + c, 0);
+ const oneshot = sorted.filter((c) => c === 1).length;
+
+ const bucket = new Map<number, number>();
+ for (const c of sorted) bucket.set(c, (bucket.get(c) ?? 0) + 1);
+ const histogram = [...bucket.entries()]
+ .sort(([a], [b]) => a - b)
+ .map(([userCount, topicCount]) => ({ topics: topicCount, userCount }));
+
+ return {
+ histogram,
+ max: sorted[topics - 1],
+ mean: totalMessages / topics,
+ median: percentileCont(sorted, 0.5),
+ min: sorted[0],
+ oneshot,
+ oneshotRatio: oneshot / topics,
+ p90: percentileCont(sorted, 0.9),
+ p99: percentileCont(sorted, 0.99),
+ topics,
+ totalMessages,
+ };
+};
+
export class MessageModel {
private userId: string;
private db: LobeChatDatabase;
@@ -1460,34 +1565,77 @@ export class MessageModel {
return result as DBMessageItem[];
};
- count = async (params?: {
- endDate?: string;
- range?: [string, string];
- startDate?: string;
- }): Promise<number> => {
+ /**
+ * Ownership-scoped analytics filter conditions, shared by count /
+ * countGroupByTopic / topicMessageStats. The first entry is always the
+ * `userId Γ— workspace` ownership predicate; later entries are optional.
+ */
+ private analyticsConditions = (params?: MessageAnalyticsFilters) => [
+ this.ownership(),
+ params?.agentId ? eq(messages.agentId, params.agentId) : undefined,
+ params?.topicId ? eq(messages.topicId, params.topicId) : undefined,
+ params?.role ? eq(messages.role, params.role) : undefined,
+ params?.range
+ ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())
+ : undefined,
+ params?.endDate
+ ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())
+ : undefined,
+ params?.startDate
+ ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())
+ : undefined,
+ ];
+
+ count = async (params?: MessageAnalyticsFilters): Promise<number> => {
const result = await this.db
.select({
count: count(messages.id),
})
.from(messages)
- .where(
- genWhere([
- this.ownership(),
- params?.range
- ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())
- : undefined,
- params?.endDate
- ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())
- : undefined,
- params?.startDate
- ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())
- : undefined,
- ]),
- );
+ .where(genWhere(this.analyticsConditions(params)));
return result[0].count;
};
+ /**
+ * Count matching messages grouped by topic, sorted by count desc.
+ * Topics without a `topicId` are excluded. Pushes the GROUP BY to the DB
+ * so callers don't have to paginate raw rows and count client-side.
+ */
+ countGroupByTopic = async (
+ params?: MessageAnalyticsFilters,
+ ): Promise<TopicMessageCountItem[]> => {
+ const rows = await this.db
+ .select({
+ count: count(messages.id),
+ topicId: messages.topicId,
+ })
+ .from(messages)
+ .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))
+ .groupBy(messages.topicId)
+ .orderBy(desc(sql`count`), asc(messages.topicId));
+
+ return rows.map((r) => ({ count: r.count, topicId: r.topicId! }));
+ };
+
+ /**
+ * Distribution of message counts per topic (topics / mean / median /
+ * p90 / p99 / min / max / one-shot ratio + histogram). The per-topic
+ * counts are aggregated in the DB; only the final summary is returned.
+ */
+ topicMessageStats = async (params?: MessageAnalyticsFilters): Promise<TopicMessageStats> => {
+ const rows = await this.db
+ .select({
+ count: count(messages.id),
+ topicId: messages.topicId,
+ })
+ .from(messages)
+ .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))
+ .groupBy(messages.topicId);
+
+ return computeTopicMessageStats(rows.map((r) => r.count));
+ };
+
hasTopicMessages = async (topicId: string): Promise<boolean> => {
const rows = await this.db
.select({ id: messages.id })