🤯 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): notify people of direct messages and contact requests (#23132)
Arvin Xu57a593ff0738
diff --git a/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts b/apps/server/src/routers/lambda/__tests__/contact.notify.test.tsnew file mode 100644index 00000000000..091b8771216--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/contact.notify.test.ts@@ -0,0 +1,80 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { acceptRequest, notify, sendRequest } = vi.hoisted(() => ({+ acceptRequest: vi.fn(),+ notify: vi.fn(),+ sendRequest: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));+vi.mock('@/server/services/channel/featureGate', () => ({+ isChannelEnabled: vi.fn().mockResolvedValue(true),+}));+vi.mock('@/database/models/contact', () => ({+ ContactModel: vi.fn(function () {+ return { acceptRequest, sendRequest };+ }),+}));+vi.mock('@/server/services/contact/notify', () => ({+ notifyContactRequestAfterResponse: notify,+}));++const { contactRouter } = await import('../contact');++const REQUEST_ID = '6f1c1d2e-4b0a-4c55-9a39-3b1d8f0e2a11';++describe('contactRouter notifications', () => {+ const caller = () => contactRouter.createCaller({ serverDB: {}, userId: 'me' } as any);++ beforeEach(() => vi.clearAllMocks());++ it('tells the addressee about a new request', async () => {+ sendRequest.mockResolvedValue({ requestId: REQUEST_ID, status: 'pending' });++ await expect(caller().sendRequest({ userId: 'them' })).resolves.toEqual({+ requestId: REQUEST_ID,+ status: 'pending',+ });+ expect(notify).toHaveBeenCalledWith({+ actorUserId: 'me',+ kind: 'received',+ recipientUserId: 'them',+ requestId: REQUEST_ID,+ });+ });++ it('tells them theirs was accepted when sending answers their pending request', async () => {+ sendRequest.mockResolvedValue({ requestId: REQUEST_ID, status: 'accepted' });++ await caller().sendRequest({ userId: 'them' });+ expect(notify).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'accepted', recipientUserId: 'them' }),+ );+ });++ it('tells the requester their request was accepted', async () => {+ acceptRequest.mockResolvedValue({ contactUserId: 'them' });++ await expect(caller().acceptRequest({ requestId: REQUEST_ID })).resolves.toEqual({+ contactUserId: 'them',+ });+ expect(notify).toHaveBeenCalledWith({+ actorUserId: 'me',+ kind: 'accepted',+ recipientUserId: 'them',+ requestId: REQUEST_ID,+ });+ });++ it('notifies no one when the request fails', async () => {+ sendRequest.mockRejectedValue(new Error('Already a contact'));++ await expect(caller().sendRequest({ userId: 'them' })).rejects.toThrow();+ expect(notify).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/contact.ts b/apps/server/src/routers/lambda/contact.tsindex efa9d4eac73..3af44e319b5 100644--- a/apps/server/src/routers/lambda/contact.ts+++ b/apps/server/src/routers/lambda/contact.ts@@ -6,6 +6,7 @@ import { ContactModel } from '@/database/models/contact';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { isChannelEnabled } from '@/server/services/channel/featureGate';+import { notifyContactRequestAfterResponse } from '@/server/services/contact/notify';/*** The address book belongs to the Channel experience: contacts are who you can message there.@@ -43,11 +44,30 @@ export const contactRouter = router({userId,}),)- .mutation(async ({ ctx, input }) => ctx.contactModel.sendRequest(input.userId, input.message)),+ .mutation(async ({ ctx, input }) => {+ const result = await ctx.contactModel.sendRequest(input.userId, input.message);+ // Sending while their request is pending accepts theirs, so they hear it was accepted.+ notifyContactRequestAfterResponse({+ actorUserId: ctx.userId,+ kind: result.status === 'accepted' ? 'accepted' : 'received',+ recipientUserId: input.userId,+ requestId: result.requestId,+ });+ return result;+ }),acceptRequest: contactProcedure.input(z.object({ requestId }))- .mutation(async ({ ctx, input }) => ctx.contactModel.acceptRequest(input.requestId)),+ .mutation(async ({ ctx, input }) => {+ const result = await ctx.contactModel.acceptRequest(input.requestId);+ notifyContactRequestAfterResponse({+ actorUserId: ctx.userId,+ kind: 'accepted',+ recipientUserId: result.contactUserId,+ requestId: input.requestId,+ });+ return result;+ }),declineRequest: contactProcedure.input(z.object({ requestId }))diff --git a/apps/server/src/services/channel/ChannelService.routing.test.ts b/apps/server/src/services/channel/ChannelService.routing.test.tsindex b36a1fde39c..7bdd15c4ce7 100644--- a/apps/server/src/services/channel/ChannelService.routing.test.ts+++ b/apps/server/src/services/channel/ChannelService.routing.test.ts@@ -23,6 +23,7 @@ vi.mock('@/server/services/agent', () => ({ AgentService: class {} }));vi.mock('@/server/services/file', () => ({ FileService: class {} }));vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));vi.mock('./mention', () => ({ notifyChannelMentions: mocks.notifyMentions }));+vi.mock('./directMessage', () => ({ notifyChannelDirectMessages: vi.fn() }));vi.mock('./notify', () => ({ notifyChannel: mocks.notify }));vi.mock('./queue', () => ({ wakeChannel: mocks.wake }));vi.mock('./routingConfig', () => ({ resolveChannelRoutingConfig: mocks.config }));diff --git a/apps/server/src/services/channel/ChannelService.test.ts b/apps/server/src/services/channel/ChannelService.test.tsindex e4b989d85c8..4b4456e3649 100644--- a/apps/server/src/services/channel/ChannelService.test.ts+++ b/apps/server/src/services/channel/ChannelService.test.ts@@ -3,15 +3,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { ChannelService } from './ChannelService';-const { remove, removeThread, wake, notify, notifyMentions, send, routing } = vi.hoisted(() => ({- remove: vi.fn(),- send: vi.fn(),- routing: vi.fn(),- removeThread: vi.fn(),- wake: vi.fn(),- notify: vi.fn(),- notifyMentions: vi.fn(),-}));+const { remove, removeThread, wake, notify, notifyMentions, notifyDirect, send, routing } =+ vi.hoisted(() => ({+ remove: vi.fn(),+ send: vi.fn(),+ routing: vi.fn(),+ removeThread: vi.fn(),+ wake: vi.fn(),+ notify: vi.fn(),+ notifyMentions: vi.fn(),+ notifyDirect: vi.fn(),+ }));vi.mock('@/database/repositories/channel', async (original) => ({...(await original<object>()),ChannelRepository: class {@@ -25,6 +27,7 @@ vi.mock('@/server/services/agent', () => ({ AgentService: class {} }));vi.mock('@/server/services/file', () => ({ FileService: class {} }));vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));vi.mock('./mention', () => ({ notifyChannelMentions: notifyMentions }));+vi.mock('./directMessage', () => ({ notifyChannelDirectMessages: notifyDirect }));vi.mock('./notify', () => ({ notifyChannel: notify }));vi.mock('./routingConfig', () => ({ resolveChannelRoutingConfig: routing }));vi.mock('./queue', () => ({ wakeChannel: wake }));@@ -98,7 +101,7 @@ describe('Channel reply dispatch', () => {expect(send).toHaveBeenNthCalledWith(2, 'channel', { ...input, routing: 'fallback' });});- it('pings mentioned people once the message is stored, even when scheduling Agents fails', async () => {+ it('pings mentioned people and the other person of a conversation once the message is stored, even when scheduling Agents fails', async () => {const message = { id: 'message', mentions: ['member'], routingStatus: 'directed' };send.mockResolvedValue(message);wake.mockRejectedValueOnce(new Error('queue unavailable'));@@ -108,5 +111,10 @@ describe('Channel reply dispatch', () => {{ userId: 'owner', workspaceId: 'workspace' },message,);+ expect(notifyDirect).toHaveBeenCalledWith(+ expect.anything(),+ { userId: 'owner', workspaceId: 'workspace' },+ message,+ );});});diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex 9c0540ebbd9..3378d373f58 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -27,6 +27,7 @@ import { deviceGateway } from '@/server/services/deviceGateway';import { FileService } from '@/server/services/file';import { ChannelCoordinator } from './ChannelCoordinator';+import { notifyChannelDirectMessages } from './directMessage';import { notifyChannelMentions } from './mention';import { notifyChannel } from './notify';import { wakeChannel } from './queue';@@ -409,7 +410,9 @@ export class ChannelService {...input,routing: config ? 'decision' : 'fallback',});- notifyChannelMentions(this.db, { userId: this.userId, workspaceId: this.workspaceId }, message);+ const notifyContext = { userId: this.userId, workspaceId: this.workspaceId };+ notifyChannelMentions(this.db, notifyContext, message);+ notifyChannelDirectMessages(this.db, notifyContext, message);// A human quote without mentions only updates the public feed; it schedules no Agent work.if (message.replyToId && message.routingStatus === 'skipped') await this.changed(channelId);else await Promise.all([wakeChannel(channelId), this.changed(channelId)]);diff --git a/apps/server/src/services/channel/directMessage.test.ts b/apps/server/src/services/channel/directMessage.test.tsnew file mode 100644index 00000000000..0baeb71de68--- /dev/null+++ b/apps/server/src/services/channel/directMessage.test.ts@@ -0,0 +1,87 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { notifyChannelDirectMessages } from './directMessage';++const { after, notifyChannelDirectMessage } = vi.hoisted(() => ({+ after: vi.fn(),+ notifyChannelDirectMessage: vi.fn(),+}));+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after }));+vi.mock('@/business/server/channel-message/notifyActivity', () => ({+ notifyChannelDirectMessage,+}));++const dbReturning = (rows: { ownerId: string | null; peerUserId: string | null }[]) => {+ const limit = vi.fn().mockResolvedValue(rows);+ return { select: () => ({ from: () => ({ where: () => ({ limit }) }) }) } as never;+};++const runScheduled = async () => {+ expect(after).toHaveBeenCalledTimes(1);+ await after.mock.calls[0][0]();+};++const message = { channelId: 'channel', id: 'message' };+const conversation = { ownerId: 'opener', peerUserId: 'peer' };++describe('notifyChannelDirectMessages', () => {+ beforeEach(() => vi.resetAllMocks());++ it('pings the peer about a message from the person who opened the conversation', async () => {+ notifyChannelDirectMessages(dbReturning([conversation]), { userId: 'opener' }, message);+ expect(notifyChannelDirectMessage).not.toHaveBeenCalled();+ await runScheduled();++ expect(notifyChannelDirectMessage).toHaveBeenCalledWith({+ actorUserId: 'opener',+ channelId: 'channel',+ messageId: 'message',+ recipientUserId: 'peer',+ });+ });++ it('pings the opener when the peer writes back', async () => {+ notifyChannelDirectMessages(dbReturning([conversation]), { userId: 'peer' }, message);+ await runScheduled();++ expect(notifyChannelDirectMessage).toHaveBeenCalledWith(+ expect.objectContaining({ actorUserId: 'peer', recipientUserId: 'opener' }),+ );+ });++ it('skips workspace Channels without reading the Channel', () => {+ notifyChannelDirectMessages(+ dbReturning([conversation]),+ { userId: 'opener', workspaceId: 'workspace' },+ message,+ );+ expect(after).not.toHaveBeenCalled();+ });++ it('skips personal Channels that are not between two people', async () => {+ notifyChannelDirectMessages(+ dbReturning([{ ownerId: 'opener', peerUserId: null }]),+ { userId: 'opener' },+ message,+ );+ await runScheduled();+ expect(notifyChannelDirectMessage).not.toHaveBeenCalled();+ });++ it('skips a sender who is neither person of the conversation', async () => {+ notifyChannelDirectMessages(dbReturning([conversation]), { userId: 'stranger' }, message);+ await runScheduled();+ expect(notifyChannelDirectMessage).not.toHaveBeenCalled();+ });++ it('never fails the send when the notification fails', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ notifyChannelDirectMessage.mockRejectedValue(new Error('down'));+ notifyChannelDirectMessages(dbReturning([conversation]), { userId: 'opener' }, message);++ await expect(runScheduled()).resolves.toBeUndefined();+ expect(error).toHaveBeenCalled();+ error.mockRestore();+ });+});diff --git a/apps/server/src/services/channel/directMessage.ts b/apps/server/src/services/channel/directMessage.tsnew file mode 100644index 00000000000..90ae0dcf0a7--- /dev/null+++ b/apps/server/src/services/channel/directMessage.ts@@ -0,0 +1,59 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { eq } from 'drizzle-orm';++import { notifyChannelDirectMessage } from '@/business/server/channel-message/notifyActivity';+import { channels } from '@/database/schemas';+import { after } from '@/server/utils/scheduleAfterResponse';++interface SentMessage {+ channelId: string;+ id: string;+}++/**+ * Ping the other person of a personal conversation between two contacts about a message the+ * sender posted there. Every message counts, @mention or not. Runs after the response and never+ * fails the send; a retried send returns the same message, so its notification dedupes. The+ * business slot is a no-op outside Cloud.+ */+export const notifyChannelDirectMessages = (+ db: LobeChatDatabase,+ context: { userId: string; workspaceId?: string },+ message: SentMessage,+) => {+ const { userId, workspaceId } = context;+ // Conversations between people are personal.+ if (workspaceId) return;++ after(async () => {+ try {+ const [channel] = await db+ .select({ ownerId: channels.userId, peerUserId: channels.peerUserId })+ .from(channels)+ .where(eq(channels.id, message.channelId))+ .limit(1);+ if (!channel?.peerUserId) return;++ const recipientUserId =+ channel.ownerId === userId+ ? channel.peerUserId+ : channel.peerUserId === userId+ ? channel.ownerId+ : null;+ if (!recipientUserId) return;++ await notifyChannelDirectMessage({+ actorUserId: userId,+ channelId: message.channelId,+ messageId: message.id,+ recipientUserId,+ });+ } catch (error) {+ console.error('[channel] Failed to send direct message notification', {+ channelId: message.channelId,+ error,+ messageId: message.id,+ });+ }+ });+};diff --git a/apps/server/src/services/contact/notify.ts b/apps/server/src/services/contact/notify.tsnew file mode 100644index 00000000000..d085c618606--- /dev/null+++ b/apps/server/src/services/contact/notify.ts@@ -0,0 +1,22 @@+import type { NotifyContactRequestParams } from '@/business/server/contact/notifyActivity';+import { notifyContactRequest } from '@/business/server/contact/notifyActivity';+import { after } from '@/server/utils/scheduleAfterResponse';++/**+ * Tell the other person about a contact request: a new one, or theirs that was accepted. Runs+ * after the response and never fails the request; repeating a request returns the same id, so+ * its notification dedupes. The business slot is a no-op outside Cloud.+ */+export const notifyContactRequestAfterResponse = (params: NotifyContactRequestParams) => {+ after(async () => {+ try {+ await notifyContactRequest(params);+ } catch (error) {+ console.error('[contact] Failed to send contact request notification', {+ error,+ kind: params.kind,+ requestId: params.requestId,+ });+ }+ });+};diff --git a/locales/en-US/notification.json b/locales/en-US/notification.jsonindex 3f6f84e5e8b..f60b8d33442 100644--- a/locales/en-US/notification.json+++ b/locales/en-US/notification.json@@ -32,12 +32,15 @@"billboard.menuLabel": "Announcements","category.agent": "Agent","category.billing": "Billing",+ "category.contact": "Contacts","category.generation": "Generation","category.mention": "Mentions","category.pending": "Pending","category.schedule": "Scheduled tasks","category.system": "System notifications","category.workspace": "Workspace updates",+ "channel_direct_message": "{{actorLabel}} sent you a message.",+ "channel_direct_message_title": "New message","channel_mentioned": "{{actorLabel}} mentioned you in the channel \"{{channelTitle}}\".","channel_mentioned_title": "You were mentioned in a channel","checkout_abandoned_subscription": "You started upgrading to {{plan}} but did not finish checkout. Your upgrade is still available whenever you are ready.",@@ -46,6 +49,10 @@"checkout_abandoned_topup": "Your top-up was not completed, so no balance was added. You can finish it anytime from the balance page.","checkout_abandoned_topup_action": "Top up","checkout_abandoned_topup_title": "Your top-up is unfinished",+ "contact_request_accepted": "{{actorLabel}} accepted your contact request.",+ "contact_request_accepted_title": "Contact request accepted",+ "contact_request_received": "{{actorLabel}} wants to add you as a contact.",+ "contact_request_received_title": "New contact request","credit_balance_low": "Your balance is running low — about {{balance}} remaining. Turn on auto top-up so your balance refills automatically and your work is never interrupted.","credit_balance_low_action": "Set up auto top-up","credit_balance_low_title": "Your balance is running low",diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.jsonindex e5aa23334ec..7f570050cb5 100644--- a/locales/zh-CN/notification.json+++ b/locales/zh-CN/notification.json@@ -32,12 +32,15 @@"billboard.menuLabel": "公告","category.agent": "Agent","category.billing": "账单",+ "category.contact": "联系人","category.generation": "生成","category.mention": "提及","category.pending": "待处理","category.schedule": "定时任务","category.system": "系统消息","category.workspace": "工作区动态",+ "channel_direct_message": "{{actorLabel}} 给你发了一条消息。",+ "channel_direct_message_title": "新消息","channel_mentioned": "{{actorLabel}} 在频道「{{channelTitle}}」中提到了你。","channel_mentioned_title": "你在频道中被提及","checkout_abandoned_subscription": "你开始升级到 {{plan}},但还没有完成付款。随时可以回来继续升级。",@@ -46,6 +49,10 @@"checkout_abandoned_topup": "你的充值没有完成,余额尚未到账。随时可以在余额页面继续充值。","checkout_abandoned_topup_action": "继续充值","checkout_abandoned_topup_title": "充值尚未完成",+ "contact_request_accepted": "{{actorLabel}} 通过了你的好友申请。",+ "contact_request_accepted_title": "好友申请已通过",+ "contact_request_received": "{{actorLabel}} 请求添加你为联系人。",+ "contact_request_received_title": "新的好友申请","credit_balance_low": "你的余额即将用尽,当前约剩余 {{balance}}。建议开启自动充值,余额不足时自动续费,让你的工作不被中断。","credit_balance_low_action": "开启自动充值","credit_balance_low_title": "你的余额即将用尽",diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.tsindex c24e94f45c1..59b2cc99964 100644--- a/packages/locales/src/default/notification.ts+++ b/packages/locales/src/default/notification.ts@@ -42,6 +42,7 @@ export default {'billboard.menuLabel': 'Announcements','category.agent': 'Agent','category.billing': 'Billing',+ 'category.contact': 'Contacts','category.generation': 'Generation','category.mention': 'Mentions','category.pending': 'Pending',@@ -56,6 +57,10 @@ export default {'Your top-up was not completed, so no balance was added. You can finish it anytime from the balance page.','checkout_abandoned_topup_action': 'Top up','checkout_abandoned_topup_title': 'Your top-up is unfinished',+ 'contact_request_accepted': '{{actorLabel}} accepted your contact request.',+ 'contact_request_accepted_title': 'Contact request accepted',+ 'contact_request_received': '{{actorLabel}} wants to add you as a contact.',+ 'contact_request_received_title': 'New contact request','credit_balance_low':'Your balance is running low — about {{balance}} remaining. Turn on auto top-up so your balance refills automatically and your work is never interrupted.','credit_balance_low_action': 'Set up auto top-up',@@ -116,6 +121,8 @@ export default {'document_comment_activity_thread_title': 'New reply in your comment thread','document_comment_mentioned': '{{actorLabel}} mentioned you in a comment on "{{documentTitle}}".','document_comment_mentioned_title': 'You were mentioned in a document comment',+ 'channel_direct_message': '{{actorLabel}} sent you a message.',+ 'channel_direct_message_title': 'New message','channel_mentioned': '{{actorLabel}} mentioned you in the channel "{{channelTitle}}".','channel_mentioned_title': 'You were mentioned in a channel','document_mentioned': '{{actorLabel}} mentioned you in "{{documentTitle}}".',diff --git a/src/business/server/channel-message/notifyActivity.ts b/src/business/server/channel-message/notifyActivity.tsnew file mode 100644index 00000000000..c51dd72df14--- /dev/null+++ b/src/business/server/channel-message/notifyActivity.ts@@ -0,0 +1,15 @@+/**+ * A person sent a message in a personal conversation between two contacts. Fired once per sent+ * message; the caller has already resolved the recipient as the conversation's other person.+ */+export interface NotifyChannelDirectMessageParams {+ actorUserId: string;+ channelId: string;+ messageId: string;+ /** The other person of the conversation. */+ recipientUserId: string;+}++export const notifyChannelDirectMessage = (+ _params: NotifyChannelDirectMessageParams,+): Promise<void> => Promise.resolve();diff --git a/src/business/server/contact/notifyActivity.ts b/src/business/server/contact/notifyActivity.tsnew file mode 100644index 00000000000..77ab77666ca--- /dev/null+++ b/src/business/server/contact/notifyActivity.ts@@ -0,0 +1,14 @@+/**+ * A contact request reached a person: `received` is a new request to them, `accepted` means+ * the request they sent was accepted. Fired once per outcome.+ */+export interface NotifyContactRequestParams {+ /** Who sent the request (`received`) or accepted it (`accepted`). */+ actorUserId: string;+ kind: 'accepted' | 'received';+ recipientUserId: string;+ requestId: string;+}++export const notifyContactRequest = (_params: NotifyContactRequestParams): Promise<void> =>+ Promise.resolve();