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.

🐛 fix(channel): preview a conversation's newest Thread reply in the Channel list (#23204)

Arvin Xu9f57045664cd
diff --git a/packages/database/src/repositories/channel/__tests__/identity.test.ts b/packages/database/src/repositories/channel/__tests__/identity.test.ts
index 131b81fd652..4e0887590b2 100644
--- a/packages/database/src/repositories/channel/__tests__/identity.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/identity.test.ts
@@ -67,11 +67,39 @@ 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' },
+ lastMessage: { content: 'Second', thread: null },
unreadCount: 2,
});
});
+ // 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();
+ const repository = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel } = await repository.create({ agentId: agent.id, title: 'Direct' });
+ const root = await repository.send(channel.id, {
+ ...sendInput,
+ content: ' Root line\nmore',
+ requestKey: 'root',
+ });
+ const reply = await repository.send(channel.id, {
+ ...sendInput,
+ content: 'In the thread',
+ requestKey: 'thread-reply',
+ rootMessageId: root.id,
+ });
+ const listed = async () =>
+ (await repository.list()).find((item) => item.id === channel.id)?.lastMessage;
+
+ expect(await listed()).toMatchObject({
+ content: 'In the thread',
+ thread: { id: reply.threadId, title: 'Root line' },
+ });
+
+ await repository.removeThread(channel.id, reply.threadId!);
+ expect(await listed()).toMatchObject({ content: ' Root line\nmore', thread: null });
+ });
+
// A list row only knew a reply was in progress once its conversation was opened.
it('lists the main-conversation replies still pending', async () => {
const agent = await createAgent();
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index b5ec361ef49..08e3ae57928 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -1,5 +1,6 @@
import type {
ChannelAvatarMember,
+ ChannelLastMessage,
ChannelMemberConfig,
ChannelMemberRole,
ChannelReplyJob,
@@ -36,6 +37,7 @@ import { channelAvatarMembers } from './avatars';
import { findThread } from './delivery';
import { editMessage } from './edit';
import { ChannelError } from './error';
+import { channelLastMessages } from './lastMessage';
import { setMemberMuted } from './mute';
import { findPeer, lockPeerPair, peerOf, requirePeerRelation } from './peer';
import {
@@ -98,9 +100,6 @@ const WORKSPACE_MANAGER_ROLES = ['owner', 'admin'];
* scope (personal, or the given workspace). Every write runs inside `write`, which holds the
* `channels` row lock so mutations of one channel serialize in a transaction.
*/
-/** Characters of the latest message a Channel list item carries as its preview. */
-const LIST_PREVIEW_LENGTH = 200;
-
/** A member config with its reply strategy set, or without one when `wake` is empty. */
/** An environment plus the member's own settings that live beside it: reply strategy and mute. */
const withMemberWake = (
@@ -591,7 +590,7 @@ export class ChannelRepository {
ChannelItem & {
agentIds: string[];
canDelete: boolean;
- lastMessage: { content: string; createdAt: Date } | null;
+ lastMessage: ChannelLastMessage | null;
memberAvatars: ChannelAvatarMember[];
mentionCount: number;
replyJobs: ChannelReplyJob[];
@@ -619,28 +618,9 @@ export class ChannelRepository {
.where(and(this.membershipWhere(), notTrashed(channels.isDeleted)))
.orderBy(desc(channels.createdAt));
- // The newest main-channel message of each, for a conversation-list preview.
- const latest = rows.length
- ? await this.db
- .selectDistinctOn([channelMessages.channelId], {
- channelId: channelMessages.channelId,
- content: sql<string>`left(${channelMessages.content}, ${LIST_PREVIEW_LENGTH})`,
- createdAt: channelMessages.createdAt,
- })
- .from(channelMessages)
- .where(
- and(
- inArray(
- channelMessages.channelId,
- rows.map(({ channel }) => channel.id),
- ),
- isNull(channelMessages.threadId),
- ),
- )
- .orderBy(channelMessages.channelId, desc(channelMessages.sequence))
- : [];
- const lastMessageOf = new Map(
- latest.map(({ channelId, ...message }) => [channelId, message] as const),
+ const lastMessageOf = await channelLastMessages(
+ this.db,
+ rows.map(({ channel }) => channel.id),
);
// Main-conversation replies the list row shows as in progress: ones that can still publish,
diff --git a/packages/database/src/repositories/channel/lastMessage.ts b/packages/database/src/repositories/channel/lastMessage.ts
new file mode 100644
index 00000000000..92b5d812b45
--- /dev/null
+++ b/packages/database/src/repositories/channel/lastMessage.ts
@@ -0,0 +1,68 @@
+import type { ChannelLastMessage } from '@lobechat/types';
+import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';
+import { alias } from 'drizzle-orm/pg-core';
+
+import { channelMessages, channelThreads } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { notTrashed } from '../../utils/softDelete';
+
+/** Characters of the latest message a Channel list item carries as its preview. */
+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;
+
+/**
+ * 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.
+ */
+export const channelLastMessages = async (
+ db: LobeChatDatabase,
+ channelIds: string[],
+): Promise<Map<string, ChannelLastMessage>> => {
+ if (!channelIds.length) return new Map();
+ const root = alias(channelMessages, 'thread_root');
+
+ const latest = await db
+ .selectDistinctOn([channelMessages.channelId], {
+ channelId: channelMessages.channelId,
+ content: sql<string>`left(${channelMessages.content}, ${LIST_PREVIEW_LENGTH})`,
+ createdAt: channelMessages.createdAt,
+ 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}), '')
+ )`,
+ })
+ .from(channelMessages)
+ .leftJoin(
+ channelThreads,
+ and(
+ eq(channelThreads.channelId, channelMessages.channelId),
+ eq(channelThreads.id, channelMessages.threadId),
+ ),
+ )
+ .leftJoin(
+ root,
+ and(eq(root.channelId, channelThreads.channelId), eq(root.id, channelThreads.rootMessageId)),
+ )
+ .where(
+ and(
+ inArray(channelMessages.channelId, channelIds),
+ or(isNull(channelMessages.threadId), notTrashed(channelThreads.isDeleted)),
+ ),
+ )
+ .orderBy(channelMessages.channelId, desc(channelMessages.sequence));
+
+ return new Map(
+ latest.map(({ channelId, content, createdAt, threadId, threadTitle }) => [
+ channelId,
+ {
+ content,
+ createdAt,
+ thread: threadId ? { id: threadId, title: threadTitle } : null,
+ },
+ ]),
+ );
+};
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 4998b20e271..68d8913a2d8 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -472,6 +472,17 @@ export interface ChannelAvatarMember {
name: string | null;
}
+/** A Channel's newest message as its list row previews it. */
+export interface ChannelLastMessage {
+ content: string;
+ createdAt: Date;
+ /**
+ * The Thread it was posted in, named by its title or else the first line of its root message;
+ * null for the main conversation.
+ */
+ thread: { id: string; title: string | null } | null;
+}
+
/** Public client projection. No execution configuration, private topic or draft fields. */
export interface ChannelListItem {
/** The bound Agent of a direct conversation; null for a group. */
@@ -485,8 +496,8 @@ export interface ChannelListItem {
canDelete: boolean;
createdAt: Date;
id: string;
- /** The newest main-channel message, cut for a preview; set by the Channel list. */
- lastMessage?: { content: string; createdAt: Date } | null;
+ /** The newest message, Threads included, cut for a preview; set by the Channel list. */
+ lastMessage?: ChannelLastMessage | null;
/**
* The first members besides the caller, oldest first, for a group Channel's list avatar;
* set by the Channel list.