🤯 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(channel): list previews carry the sender and attachments of the latest message (#23410)
Lobehub Coder304b9468b8b3
diff --git a/packages/database/src/repositories/channel/__tests__/attachments.test.ts b/packages/database/src/repositories/channel/__tests__/attachments.test.tsindex e26882ceabd..5c2df9163dc 100644--- a/packages/database/src/repositories/channel/__tests__/attachments.test.ts+++ b/packages/database/src/repositories/channel/__tests__/attachments.test.ts@@ -15,11 +15,11 @@ const execution = new ChannelExecutionRepository(db);beforeEach(fixture.setup);afterEach(fixture.cleanup);-const createFile = async (name: string) => {+const createFile = async (name: string, fileType = 'text/plain') => {const [file] = await db.insert(files).values({- fileType: 'text/plain',+ fileType,name,size: 1,url: `files/${name}`,@@ -82,4 +82,25 @@ describe('channel message attachments', () => {expect.objectContaining({ fileIds: [kept], id: message.id }),]);});++ // A message of only an image left its list row's preview blank.+ it('previews a message without text by its first attachment type and count', async () => {+ const { asMember, channel } = await fixture.createTeamChannel();+ const [image, text] = [await createFile('shot.png', 'image/png'), await createFile('a.txt')];++ await asMember.send(channel.id, {+ content: '',+ fileIds: [image, text],+ requestKey: 'req-1',+ routing: 'decision',+ });++ expect((await asMember.list()).find((item) => item.id === channel.id)).toMatchObject({+ lastMessage: {+ attachments: { count: 2, fileType: 'image/png' },+ author: { id: fixture.memberId, type: 'user' },+ content: '',+ },+ });+ });});diff --git a/packages/database/src/repositories/channel/__tests__/identity.test.ts b/packages/database/src/repositories/channel/__tests__/identity.test.tsindex 6a524fccf69..8607b2392ef 100644--- a/packages/database/src/repositories/channel/__tests__/identity.test.ts+++ b/packages/database/src/repositories/channel/__tests__/identity.test.ts@@ -67,12 +67,33 @@ describe('direct Channel identity', () => {await repository.send(channel.id, { ...sendInput, content: 'First', requestKey: 'first' });await repository.send(channel.id, { ...sendInput, content: 'Second', requestKey: 'second' });expect((await repository.list()).find((item) => item.id === channel.id)).toMatchObject({- lastMessage: { content: 'Second', thread: null },+ lastMessage: {+ attachments: null,+ author: { id: fixture.ownerId, type: 'user' },+ content: 'Second',+ thread: null,+ },// The caller's own messages are never unread for them.unreadCount: 0,});});+ // A list row could not tell "Me: …" from the other side's message.+ it('previews the newest message with its sender, an Agent reply by the Agent name', async () => {+ const agent = await createAgent();+ const repository = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ const { channel } = await repository.create({ agentId: agent.id, title: 'Direct' });+ const request = await repository.send(channel.id, sendInput);+ await publish(channel.id, request.id);++ expect((await repository.list()).find((item) => item.id === channel.id)).toMatchObject({+ lastMessage: {+ author: { id: agent.id, name: 'Assistant', type: 'agent' },+ content: 'Answer',+ },+ });+ });+// The preview stopped at the main conversation, so a newer Thread reply looked like no news.it('previews a newer Thread reply with its Thread, until the Thread is trashed', async () => {const agent = await createAgent();diff --git a/packages/database/src/repositories/channel/lastMessage.ts b/packages/database/src/repositories/channel/lastMessage.tsindex 10bb6ab9f1b..d89938bf0d5 100644--- a/packages/database/src/repositories/channel/lastMessage.ts+++ b/packages/database/src/repositories/channel/lastMessage.ts@@ -1,10 +1,18 @@import type { ChannelLastMessage } from '@lobechat/types';-import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';import { alias } from 'drizzle-orm/pg-core';-import { channelMessages, channelThreads } from '../../schemas';+import {+ agents,+ channelMessageFiles,+ channelMessages,+ channelThreads,+ files,+ users,+} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { notTrashed } from '../../utils/softDelete';+import { isAgentAuthored } from './author';import { messageStands } from './tombstone';/** Characters of the latest message a Channel list item carries as its preview. */@@ -12,11 +20,31 @@ const LIST_PREVIEW_LENGTH = 200;/** Characters of a Thread name taken from its root message, as the client names one. */const THREAD_TITLE_LENGTH = 60;+/** Attachment count and first attachment type of each message, for a preview of a file-only one. */+const attachmentsByMessage = async (db: LobeChatDatabase, messageIds: string[]) => {+ const result = new Map<string, { count: number; fileType: string }>();+ if (!messageIds.length) return result;++ const rows = await db+ .select({ fileType: files.fileType, messageId: channelMessageFiles.messageId })+ .from(channelMessageFiles)+ .innerJoin(files, eq(files.id, channelMessageFiles.fileId))+ .where(inArray(channelMessageFiles.messageId, messageIds))+ .orderBy(asc(channelMessageFiles.messageId), asc(channelMessageFiles.sortOrder));+ for (const { fileType, messageId } of rows) {+ const current = result.get(messageId);+ if (current) current.count += 1;+ else result.set(messageId, { count: 1, fileType });+ }+ return result;+};+/*** The newest message of each Channel, for a conversation-list preview. Thread replies count, as* they do for the unread count: a reply in a Thread is the conversation's latest activity, and a* preview stopped at the main conversation reads as nothing new. Trashed Threads are skipped.- * A Thread is named by its title, else the first line of the message it branched from.+ * A Thread is named by its title, else the first line of the message it branched from. The+ * sender and attachments come along, so a list can read "Me: [Image]".*/export const channelLastMessages = async (db: LobeChatDatabase,@@ -27,14 +55,22 @@ export const channelLastMessages = async (const latest = await db.selectDistinctOn([channelMessages.channelId], {+ agentId: channelMessages.agentId,+ agentName: agents.name,+ agentTitle: agents.title,channelId: channelMessages.channelId,content: sql<string>`left(${channelMessages.content}, ${LIST_PREVIEW_LENGTH})`,createdAt: channelMessages.createdAt,+ id: channelMessages.id,+ routingStatus: channelMessages.routingStatus,threadId: channelMessages.threadId,threadTitle: sql<string | null>`coalesce(nullif(${channelThreads.metadata} ->> 'title', ''),nullif(left(split_part(btrim(${root.content}), E'\n', 1), ${THREAD_TITLE_LENGTH}), ''))`,+ userFullName: users.fullName,+ userId: channelMessages.userId,+ username: users.username,}).from(channelMessages).leftJoin(@@ -48,6 +84,8 @@ export const channelLastMessages = async (root,and(eq(root.channelId, channelThreads.channelId), eq(root.id, channelThreads.rootMessageId)),)+ .leftJoin(users, eq(users.id, channelMessages.userId))+ .leftJoin(agents, eq(agents.id, channelMessages.agentId)).where(and(inArray(channelMessages.channelId, channelIds),@@ -57,14 +95,28 @@ export const channelLastMessages = async ().orderBy(channelMessages.channelId, desc(channelMessages.sequence));+ const attachmentsOf = await attachmentsByMessage(+ db,+ latest.map(({ id }) => id),+ );+return new Map(- latest.map(({ channelId, content, createdAt, threadId, threadTitle }) => [- channelId,- {- content,- createdAt,- thread: threadId ? { id: threadId, title: threadTitle } : null,- },- ]),+ latest.map((row) => {+ const isAgent = isAgentAuthored(row);+ return [+ row.channelId,+ {+ attachments: attachmentsOf.get(row.id) ?? null,+ author: {+ id: isAgent ? row.agentId : row.userId,+ name: isAgent ? row.agentName || row.agentTitle : row.userFullName || row.username,+ type: isAgent ? ('agent' as const) : ('user' as const),+ },+ content: row.content,+ createdAt: row.createdAt,+ thread: row.threadId ? { id: row.threadId, title: row.threadTitle } : null,+ },+ ];+ }),);};diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex c92928ec781..592c28b04be 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -555,6 +555,13 @@ export interface ChannelAvatarMember {/** A Channel's newest message as its list row previews it. */export interface ChannelLastMessage {+ /**+ * The first attachment's MIME type and how many there are, so a message of only an image+ * still has a preview line; null without attachments.+ */+ attachments: { count: number; fileType: string } | null;+ /** Who sent it, so a list can read "Me: …" or "Alice: …"; `id` is null after deletion. */+ author: { id: string | null; name: string | null; type: ChannelMemberActorType };content: string;createdAt: Date;/**