🤯 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(channel): list the caller's Thread mentions apart from the read position (#23278)
Arvin Xu6c864a81b6f7
diff --git a/packages/database/src/repositories/channel/__tests__/view.test.ts b/packages/database/src/repositories/channel/__tests__/view.test.tsindex 2f06e76f77b..a2bca1bcbe4 100644--- a/packages/database/src/repositories/channel/__tests__/view.test.ts+++ b/packages/database/src/repositories/channel/__tests__/view.test.ts@@ -390,6 +390,39 @@ describe('Channel public view', () => {expect(await listed()).toMatchObject({ mentionCount: 0, unreadCount: 0 });});+ it('lists the newest Thread mention of the caller however far the Channel was read', async () => {+ const { asMember, asOwner, channel, member } = await fixture.createTeamChannel();+ const send = (content: string, mentions: string[] = [], threadId?: string) =>+ asOwner.send(channel.id, {+ content,+ mentions,+ requestKey: content,+ routing: 'fallback',+ threadId,+ });+ const root = await send('Root');+ const thread = await asOwner.createThread(channel.id, { rootMessageId: root.id });+ await send('First ping', [member.id], thread.id);+ const latest = await send('Second ping', [member.id], thread.id);+ await send('No ping', [], thread.id);+ await send('Main ping', [member.id]);++ const listed = async () => (await asMember.list()).find((item) => item.id === channel.id);+ const mentioned = [{ createdAt: latest.createdAt, threadId: thread.id }];+ expect((await listed())?.threadMentions).toEqual(mentioned);+ expect((await asOwner.list()).find((item) => item.id === channel.id)?.threadMentions).toEqual(+ [],+ );++ // Reading the main conversation consumes the count but not the Thread mention.+ await asMember.markRead(channel.id, latest.sequence + 2);+ expect(await listed()).toMatchObject({ mentionCount: 0, threadMentions: mentioned });++ // A trashed Thread cannot be opened, so its mentions are no longer listed.+ await asOwner.removeThread(channel.id, thread.id);+ expect((await listed())?.threadMentions).toEqual([]);+ });+it('preserves the actual reply author when a member is rebound', async () => {const { asOwner, channel } = await fixture.createTeamChannel();const original = await fixture.addAgent(channel.id, 'Original');diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 22eda7053bf..297d220bb96 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -4,6 +4,7 @@ import type {ChannelMemberConfig,ChannelMemberRole,ChannelReplyJob,+ ChannelThreadMention,ChannelVisibility,} from '@lobechat/types';import { agentDisplayName } from '@lobechat/types';@@ -59,6 +60,7 @@ import { type ChannelSearchOptions, searchChannelMessages } from './search';import { sendMessage } from './send';import type { ChannelStopScope } from './stop';import { stopScope } from './stop';+import { channelThreadMentions } from './threadMentions';import { audit, lockChannel } from './transaction';import type { ChannelAccess, ChannelAgentPairAccess, ChannelWriteOptions } from './types';import { createChannelThread, readChannelView } from './view';@@ -575,6 +577,7 @@ export class ChannelRepository {pinnedAt: Date | null;replyJobs: ChannelReplyJob[];sharedAgentHandle: string | null;+ threadMentions: ChannelThreadMention[];unreadCount: number;}>@@ -667,6 +670,12 @@ export class ChannelRepository {: [];const mentionCountOf = new Map(mentioned.map(({ channelId, count }) => [channelId, count]));+ // Thread mentions outlive the read position, which opening the main conversation moves.+ const threadMentionsOf = await channelThreadMentions(+ this.db,+ rows.map(({ memberId }) => memberId),+ );+// A group Channel's list avatar pictures its first members; a direct one, its Agent or the// other person, which also pictures a shared Agent the caller has no sidebar row for.const avatarsOf = await channelAvatarMembers(this.db, previewIds, this.userId);@@ -712,6 +721,7 @@ export class ChannelRepository {peerUserId: peerOf(channel, this.userId),pinnedAt,replyJobs: replyJobsOf.get(channel.id) ?? [],+ threadMentions: threadMentionsOf.get(channel.id) ?? [],unreadCount: Math.max(0, channel.sequence - (lastReadSequence ?? 0)),};},@@ -733,6 +743,7 @@ export class ChannelRepository {peerUserId: peerOf(channel, this.userId),pinnedAt: null,replyJobs: [],+ threadMentions: [],unreadCount: 0,})),].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());diff --git a/packages/database/src/repositories/channel/threadMentions.ts b/packages/database/src/repositories/channel/threadMentions.tsnew file mode 100644index 00000000000..953d1665f91--- /dev/null+++ b/packages/database/src/repositories/channel/threadMentions.ts@@ -0,0 +1,53 @@+import type { ChannelThreadMention } from '@lobechat/types';+import { and, desc, eq, gt, inArray, sql } from 'drizzle-orm';++import { channelMembers, channelMessages, channelThreads } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { notTrashed } from '../../utils/softDelete';++/**+ * The newest @mention of each member in each Thread of their Channel, keyed by Channel, however+ * the member's read position stands: opening the main conversation moves that position past+ * Thread messages nobody opened, so whether a Thread mention was seen is left to the client's+ * per-Thread reads. Older mentions are taken as seen, which keeps the scan to recent messages.+ * Trashed Threads are skipped: they can no longer be opened, so their mentions could never clear.+ */+export const channelThreadMentions = async (+ db: LobeChatDatabase,+ memberIds: string[],+): Promise<Map<string, ChannelThreadMention[]>> => {+ if (!memberIds.length) return new Map();++ const rows = await db+ .selectDistinctOn([channelMessages.channelId, channelMessages.threadId], {+ channelId: channelMessages.channelId,+ createdAt: channelMessages.createdAt,+ threadId: channelMessages.threadId,+ })+ .from(channelMessages)+ .innerJoin(channelMembers, eq(channelMembers.channelId, channelMessages.channelId))+ .innerJoin(+ channelThreads,+ and(+ eq(channelThreads.channelId, channelMessages.channelId),+ eq(channelThreads.id, channelMessages.threadId),+ ),+ )+ .where(+ and(+ inArray(channelMembers.id, memberIds),+ notTrashed(channelThreads.isDeleted),+ gt(channelMessages.createdAt, sql`now() - interval '30 days'`),+ sql`${channelMessages.mentions} @> jsonb_build_array(${channelMembers.id}::text)`,+ ),+ )+ .orderBy(channelMessages.channelId, channelMessages.threadId, desc(channelMessages.createdAt));++ const mentionsOf = new Map<string, ChannelThreadMention[]>();+ for (const { channelId, createdAt, threadId } of rows) {+ const mentions = mentionsOf.get(channelId) ?? [];+ mentions.push({ createdAt, threadId: threadId! });+ mentionsOf.set(channelId, mentions);+ }+ return mentionsOf;+};diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex e59a3303c8c..c92928ec781 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -564,6 +564,12 @@ export interface ChannelLastMessage {thread: { id: string; title: string | null } | null;}+/** The newest message in a Thread that @mentions the caller. */+export interface ChannelThreadMention {+ createdAt: Date;+ threadId: string;+}+/** 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. */@@ -625,6 +631,12 @@ export interface ChannelListItem {*/sharedAgentHandle?: string | null;status: ChannelStatus;+ /**+ * The newest @mention of the caller in each Thread from the last 30 days, read or not; set by+ * the Channel list. The read position cannot tell whether one was seen, so the client's+ * per-Thread reads decide.+ */+ threadMentions?: ChannelThreadMention[];title: string;/** Main-channel messages the caller has not read; set by the Channel list. */unreadCount?: number;