🤯 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
⚡️ perf: batch recent-topic previews instead of per-topic subquery (#17928)
Arvin Xu4e1663f78646
diff --git a/packages/database/package.json b/packages/database/package.jsonindex 8f4dbe91d63..b91afbcafb9 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -22,6 +22,7 @@"@lobechat/types": "workspace:*","@lobechat/utils": "workspace:*","random-words": "^2.0.1",+ "remove-markdown": "^0.6.4","ts-md5": "^2.0.1","type-fest": "^5.7.0","ws": "^8.21.0"diff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.tsindex 8a9da50f274..c5274ca0410 100644--- a/packages/database/src/models/__tests__/recent.test.ts+++ b/packages/database/src/models/__tests__/recent.test.ts@@ -610,6 +610,32 @@ describe('RecentModel', () => {expect(result[1].lastAssistantMessage).toBe('Last assistant answer');});+ it('strips markdown syntax from topic previews', async () => {+ await serverDB.insert(agents).values({ id: 'agent-inbox', userId, slug: 'inbox' });+ await serverDB.insert(topics).values({+ agentId: 'agent-inbox',+ id: 'topic-markdown-preview',+ status: 'active',+ updatedAt: minutesAgo(1),+ userId,+ });+ await serverDB.insert(messages).values({+ agentId: 'agent-inbox',+ content:+ '## Heading\n\nSome **bold** text with a [link](https://example.com) and `code`.',+ id: 'markdown-preview-message',+ role: 'assistant',+ topicId: 'topic-markdown-preview',+ userId,+ });++ const result = await recentModel.queryRecent(1, ['topic'], true);++ expect(result[0].lastAssistantMessage).toBe(+ 'Heading\n\nSome bold text with a link and code.',+ );+ });+it('returns Date objects for updatedAt', async () => {await serverDB.insert(agents).values({ id: 'agent-inbox', userId, slug: 'inbox' });await serverDB.insert(topics).values({diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.tsindex a7a7db1f6e6..6823c1db1df 100644--- a/packages/database/src/models/recent.ts+++ b/packages/database/src/models/recent.ts@@ -1,6 +1,7 @@import type { ChatTopicStatus, TaskStatus } from '@lobechat/types';import { and, desc, eq, inArray, isNotNull, isNull, ne, not, or, sql } from 'drizzle-orm';import { unionAll } from 'drizzle-orm/pg-core';+import removeMarkdown from 'remove-markdown';import { agents, DOCUMENT_FOLDER_TYPE, documents, messages, tasks, topics } from '../schemas';import type { LobeChatDatabase } from '../type';@@ -35,6 +36,16 @@ const TASK_FINAL_STATUSES = ['completed', 'canceled'];const TOPIC_INBOX_STATUSES: ChatTopicStatus[] = ['running', 'unread'];const LAST_MESSAGE_PREVIEW_LENGTH = 2000;+// Best-effort markdown → plain text; previews render in a plain-text row, so+// syntax noise (**, #, []() …) would show up literally.+const toPlainTextPreview = (markdown: string): string => {+ try {+ return removeMarkdown(markdown).trimEnd();+ } catch {+ return markdown;+ }+};+export class RecentModel {private userId: string;private workspaceId?: string;@@ -68,31 +79,12 @@ export class RecentModel {const mineDocumentWhere = mineOnly ? eq(documents.userId, this.userId) : undefined;const mineTaskWhere = mineOnly ? eq(tasks.createdByUserId, this.userId) : undefined;- const lastAssistantMessageSubquery = this.db- .select({- value: sql<string>`left(${messages.content}, ${LAST_MESSAGE_PREVIEW_LENGTH + 1})`,- })- .from(messages)- .where(- and(- eq(messages.topicId, topics.id),- eq(messages.role, 'assistant'),- buildWorkspaceWhere(scope, messages),- ne(messages.content, ''),- ),- )- .orderBy(desc(messages.createdAt))- .limit(1);-const topicArm = this.db.select({description: withTopicPreview? topics.description: sql<string | null>`NULL`.as('description'),id: topics.id,- lastAssistantMessage: withTopicPreview- ? sql<string | null>`(${lastAssistantMessageSubquery})`.as('last_assistant_message')- : sql<string | null>`NULL`.as('last_assistant_message'),metadata: sql<any>`${topics.metadata}`.as('metadata'),routeGroupId: sql<string | null>`${topics.groupId}`.as('route_group_id'),routeId: sql<string | null>`${topics.agentId}`.as('route_id'),@@ -124,7 +116,6 @@ export class RecentModel {.select({description: sql<string | null>`NULL`.as('description'),id: documents.id,- lastAssistantMessage: sql<string | null>`NULL`.as('last_assistant_message'),metadata: sql<any>`NULL`.as('metadata'),routeGroupId: sql<string | null>`NULL`.as('route_group_id'),routeId: sql<string | null>`NULL`.as('route_id'),@@ -154,7 +145,6 @@ export class RecentModel {.select({description: sql<string | null>`NULL`.as('description'),id: tasks.id,- lastAssistantMessage: sql<string | null>`NULL`.as('last_assistant_message'),metadata: sql<any>`NULL`.as('metadata'),routeGroupId: sql<string | null>`NULL`.as('route_group_id'),routeId: sql<string | null>`${tasks.assigneeAgentId}`.as('route_id'),@@ -177,21 +167,59 @@ export class RecentModel {.orderBy(desc(sql`updated_at`)).limit(limit);- return rows.map((row) => ({- description: row.description,- id: row.id,- lastAssistantMessage:- row.lastAssistantMessage && row.lastAssistantMessage.length > LAST_MESSAGE_PREVIEW_LENGTH- ? `${row.lastAssistantMessage.slice(0, LAST_MESSAGE_PREVIEW_LENGTH)}…`- : row.lastAssistantMessage,- metadata: row.metadata ?? undefined,- routeGroupId: row.routeGroupId,- routeId: row.routeId,- status: row.status,- title: row.title,- type: row.type,- updatedAt: row.updatedAt instanceof Date ? row.updatedAt : new Date(row.updatedAt as any),- userId: row.userId,- }));+ // Previews are fetched in a second batched query scoped to the final page+ // — inlining a correlated subquery in the topic arm would evaluate it for+ // every topic the user owns before the sort/limit prunes to `limit` rows.+ const previewByTopicId = withTopicPreview+ ? await this.queryLastAssistantPreviews(+ rows.filter((row) => row.type === 'topic').map((row) => row.id),+ )+ : new Map<string, string>();++ return rows.map((row) => {+ const preview = previewByTopicId.get(row.id) ?? null;+ return {+ description: row.description,+ id: row.id,+ lastAssistantMessage:+ preview && preview.length > LAST_MESSAGE_PREVIEW_LENGTH+ ? `${preview.slice(0, LAST_MESSAGE_PREVIEW_LENGTH)}…`+ : preview,+ metadata: row.metadata ?? undefined,+ routeGroupId: row.routeGroupId,+ routeId: row.routeId,+ status: row.status,+ title: row.title,+ type: row.type,+ updatedAt: row.updatedAt instanceof Date ? row.updatedAt : new Date(row.updatedAt as any),+ userId: row.userId,+ };+ });+ };++ private queryLastAssistantPreviews = async (topicIds: string[]): Promise<Map<string, string>> => {+ if (topicIds.length === 0) return new Map();++ const rows = await this.db+ .selectDistinctOn([messages.topicId], {+ topicId: messages.topicId,+ value: sql<string>`left(${messages.content}, ${LAST_MESSAGE_PREVIEW_LENGTH + 1})`,+ })+ .from(messages)+ .where(+ and(+ inArray(messages.topicId, topicIds),+ eq(messages.role, 'assistant'),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages),+ ne(messages.content, ''),+ ),+ )+ .orderBy(messages.topicId, desc(messages.createdAt));++ return new Map(+ rows+ .filter((row) => row.topicId !== null)+ .map((row) => [row.topicId!, toPlainTextPreview(row.value)]),+ );};}