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.

✨ feat(channel): let a person mute a Channel's notifications for themself (#23602)

Arvin Xuddc72964fb63
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index df3fc1a5ec6..0d00b18cf4d 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -348,6 +348,16 @@ export const channelRouter = router({
data: await ctx.channelService.repository.markRead(input.channelId, input.sequence),
success: true,
})),
+ /**
+ * Turns the caller's own push notifications for the conversation off or on. Personal: Agents
+ * still reply (see `setMemberMuted` for that) and other members are untouched.
+ */
+ setNotificationsMuted: externalChannelProcedure
+ .input(z.object({ channelId, muted: z.boolean() }))
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.channelService.repository.setNotificationsMuted(input.channelId, input.muted),
+ success: true,
+ })),
/** Pins or unpins the conversation atop the caller's own list. */
setPinned: externalChannelProcedure
.input(z.object({ channelId, pinned: z.boolean() }))
diff --git a/apps/server/src/services/channel/directMessage.test.ts b/apps/server/src/services/channel/directMessage.test.ts
index bc1f407a597..8b63a7e5fdd 100644
--- a/apps/server/src/services/channel/directMessage.test.ts
+++ b/apps/server/src/services/channel/directMessage.test.ts
@@ -12,8 +12,12 @@ vi.mock('@/business/server/channel-message/notifyActivity', () => ({
notifyChannelDirectMessage,
}));
-const dbReturning = (rows: { ownerId: string | null; peerUserId: string | null }[]) => {
- const limit = vi.fn().mockResolvedValue(rows);
+/** The conversation lookup, then the recipient's own member row (muted or not). */
+const dbReturning = (
+ rows: { ownerId: string | null; peerUserId: string | null }[],
+ recipient: { muted: boolean }[] = [{ muted: false }],
+) => {
+ const limit = vi.fn().mockResolvedValueOnce(rows).mockResolvedValueOnce(recipient);
return { select: () => ({ from: () => ({ where: () => ({ limit }) }) }) } as never;
};
@@ -63,6 +67,16 @@ describe('notifyChannelDirectMessages', () => {
);
});
+ it('skips a recipient who muted the conversation for themself', async () => {
+ notifyChannelDirectMessages(
+ dbReturning([conversation], [{ muted: true }]),
+ { userId: 'opener' },
+ message,
+ );
+ await runScheduled();
+ expect(notifyChannelDirectMessage).not.toHaveBeenCalled();
+ });
+
it('skips personal Channels that are not between two people', async () => {
notifyChannelDirectMessages(
dbReturning([{ ownerId: 'opener', peerUserId: null }]),
diff --git a/apps/server/src/services/channel/directMessage.ts b/apps/server/src/services/channel/directMessage.ts
index 9d4f7ec0e9e..3a982e47399 100644
--- a/apps/server/src/services/channel/directMessage.ts
+++ b/apps/server/src/services/channel/directMessage.ts
@@ -1,8 +1,9 @@
import type { LobeChatDatabase } from '@lobechat/database';
-import { eq } from 'drizzle-orm';
+import { and, eq } from 'drizzle-orm';
import { notifyChannelDirectMessage } from '@/business/server/channel-message/notifyActivity';
-import { channels } from '@/database/schemas';
+import { notificationsMutedSql } from '@/database/repositories/channel/notificationMute';
+import { channelMembers, channels } from '@/database/schemas';
import { after } from '@/server/utils/scheduleAfterResponse';
interface SentMessage {
@@ -40,6 +41,19 @@ export const notifyChannelDirectMessages = (
: null;
if (!recipientUserId) return;
+ // The recipient turned off their own notifications for this conversation.
+ const [recipient] = await db
+ .select({ muted: notificationsMutedSql() })
+ .from(channelMembers)
+ .where(
+ and(
+ eq(channelMembers.channelId, message.channelId),
+ eq(channelMembers.userId, recipientUserId),
+ ),
+ )
+ .limit(1);
+ if (recipient?.muted) return;
+
await notifyChannelDirectMessage({
actorUserId: userId,
channelId: message.channelId,
diff --git a/apps/server/src/services/channel/mention.db.test.ts b/apps/server/src/services/channel/mention.db.test.ts
index ed0d22c852f..b90531d04b8 100644
--- a/apps/server/src/services/channel/mention.db.test.ts
+++ b/apps/server/src/services/channel/mention.db.test.ts
@@ -60,6 +60,30 @@ describe('notifyChannelMentions against the database', () => {
});
});
+ it('skips a mentioned person who muted the Channel for themself', async () => {
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel } = await owner.create({ title: 'People' });
+ const member = await owner.addUser(channel.id, fixture.memberId);
+ await new ChannelRepository(db, fixture.memberId, fixture.workspaceId).setNotificationsMuted(
+ channel.id,
+ true,
+ );
+ const message = await owner.send(channel.id, {
+ content: '@mia please review',
+ mentions: [member.id],
+ requestKey: 'muted',
+ routing: 'fallback',
+ });
+ notifyChannelMentions(
+ db,
+ { userId: fixture.ownerId, workspaceId: fixture.workspaceId },
+ message,
+ );
+ await after.mock.calls[0][0]();
+
+ expect(notifyChannelMention).not.toHaveBeenCalled();
+ });
+
it('skips a person who left the workspace but still has a Channel member row', async () => {
const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
const { channel } = await owner.create({ title: 'People' });
diff --git a/apps/server/src/services/channel/mention.ts b/apps/server/src/services/channel/mention.ts
index 6ecfb694615..5c911d59b9b 100644
--- a/apps/server/src/services/channel/mention.ts
+++ b/apps/server/src/services/channel/mention.ts
@@ -1,7 +1,8 @@
import type { LobeChatDatabase } from '@lobechat/database';
-import { and, eq, inArray, isNull } from 'drizzle-orm';
+import { and, eq, inArray, isNull, not } from 'drizzle-orm';
import { notifyChannelMention } from '@/business/server/channel-mention/notifyActivity';
+import { notificationsMutedSql } from '@/database/repositories/channel/notificationMute';
import { channelMembers, workspaceMembers } from '@/database/schemas';
import { after } from '@/server/utils/scheduleAfterResponse';
@@ -45,6 +46,8 @@ export const notifyChannelMentions = (
inArray(channelMembers.id, message.mentions),
eq(channelMembers.actorType, 'user'),
eq(channelMembers.status, 'active'),
+ // Muting the Channel's notifications stops even an @mention's push.
+ not(notificationsMutedSql()),
),
);
const recipientUserIds = [
diff --git a/packages/database/src/repositories/channel/__tests__/notificationMute.test.ts b/packages/database/src/repositories/channel/__tests__/notificationMute.test.ts
new file mode 100644
index 00000000000..49c102a0fa4
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/notificationMute.test.ts
@@ -0,0 +1,103 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channelMembers } from '../../../schemas';
+import { ChannelRepository } from '..';
+import { setNotificationsMuted } from '../notificationMute';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-notification-mute');
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+const metadataOf = async (memberId: string) => {
+ const [row] = await db
+ .select({ metadata: channelMembers.metadata })
+ .from(channelMembers)
+ .where(eq(channelMembers.id, memberId));
+ return row.metadata;
+};
+
+describe('Channel notification mute', () => {
+ it("mutes the caller's own notifications only, in list and detail", async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+
+ expect(await asOwner.list()).toEqual([
+ expect.objectContaining({ id: channel.id, notificationsMuted: false }),
+ ]);
+
+ await expect(asOwner.setNotificationsMuted(channel.id, true)).resolves.toBe(true);
+ // Setting it again is a no-op.
+ await expect(asOwner.setNotificationsMuted(channel.id, true)).resolves.toBe(true);
+
+ expect(await asOwner.list()).toEqual([
+ expect.objectContaining({ id: channel.id, notificationsMuted: true }),
+ ]);
+ expect((await asOwner.detail(channel.id)).channel.notificationsMuted).toBe(true);
+ // Another member's own list and detail are untouched.
+ expect(await asMember.list()).toEqual([
+ expect.objectContaining({ id: channel.id, notificationsMuted: false }),
+ ]);
+ expect((await asMember.detail(channel.id)).channel.notificationsMuted).toBe(false);
+
+ await expect(asOwner.setNotificationsMuted(channel.id, false)).resolves.toBe(false);
+ expect(await asOwner.list()).toEqual([
+ expect.objectContaining({ id: channel.id, notificationsMuted: false }),
+ ]);
+ });
+
+ it('keeps the other metadata keys of the member row', async () => {
+ const { asMember, channel, member } = await fixture.createTeamChannel();
+ await db
+ .update(channelMembers)
+ .set({ metadata: { invitedBy: 'someone' } })
+ .where(eq(channelMembers.id, member.id));
+
+ await asMember.setNotificationsMuted(channel.id, true);
+ expect(await metadataOf(member.id)).toEqual({ invitedBy: 'someone', notificationsMuted: true });
+
+ await asMember.setNotificationsMuted(channel.id, false);
+ expect(await metadataOf(member.id)).toEqual({ invitedBy: 'someone' });
+ });
+
+ it('does not mute an Agent member, which keeps replying', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(channel.id, 'Helper');
+
+ await asOwner.setNotificationsMuted(channel.id, true);
+
+ const [row] = await db.select().from(channelMembers).where(eq(channelMembers.id, agent.id));
+ expect(row.config?.muted).toBeUndefined();
+ expect(row.metadata).not.toHaveProperty('notificationsMuted');
+ });
+
+ it("fails closed instead of muting a row that is not the caller's own", async () => {
+ const { member, owner } = await fixture.createTeamChannel();
+
+ // A caller holding somebody else's member id cannot rewrite that row: the predicate carries
+ // the caller's own user id, so no row matches and the helper refuses rather than reporting a
+ // mute it never wrote.
+ await expect(
+ db.transaction((tx) =>
+ setNotificationsMuted(tx, { memberId: owner.id, userId: member.userId! }, true),
+ ),
+ ).rejects.toThrow('Channel member not found for this person');
+
+ expect(await metadataOf(owner.id)).toEqual({});
+ expect(await metadataOf(member.id)).toEqual({});
+ });
+
+ it('works in an archived conversation and refuses a non-member', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ await asOwner.archive(channel.id);
+ await expect(asOwner.setNotificationsMuted(channel.id, true)).resolves.toBe(true);
+
+ const stranger = new ChannelRepository(db, 'channel-notification-mute-stranger');
+ await expect(stranger.setNotificationsMuted(channel.id, true)).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+});
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 6f1e6aa43fb..f4ca7d29345 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -47,6 +47,7 @@ import { syncMemberGrant } from './grants';
import { channelLastMessages } from './lastMessage';
import { leaveChannel, removeChannelMember } from './membership';
import { setMemberMuted } from './mute';
+import { notificationsMutedSql, setNotificationsMuted } from './notificationMute';
import { openPeerConversation, peerOf } from './peer';
import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';
import type { ChannelAgentPostInput } from './post';
@@ -66,7 +67,7 @@ import type { ChannelSendInput } from './send';
import { sendMessage } from './send';
import type { ChannelStopScope } from './stop';
import { stopScope } from './stop';
-import { channelThreadMentions } from './threadMentions';
+import { channelMentionCounts, channelThreadMentions } from './threadMentions';
import { audit, lockChannel } from './transaction';
import type { ChannelAccess, ChannelAgentPairAccess, ChannelWriteOptions } from './types';
import { createChannelThread, readChannelView, viewerJobs } from './view';
@@ -467,10 +468,11 @@ export class ChannelRepository {
async (tx, access) => {
if (access.channel.isDeleted) throw new ChannelError('NOT_FOUND', 'Channel not found');
const admin = hasRole(access.member.role, 'admin');
+ const notificationsMuted = access.member.metadata?.notificationsMuted === true;
const view = await readChannelView(tx, channelId, options, this.userId);
const shared = await sharedAgentView(tx, access.channel, this.userId);
return {
- channel: { ...access.channel, canDelete: admin, ...shared.channel },
+ channel: { ...access.channel, canDelete: admin, notificationsMuted, ...shared.channel },
joined: true,
sharedAgentOwner: shared.owner,
...view,
@@ -502,6 +504,15 @@ export class ChannelRepository {
{ allowArchived: true, allowTrashed: true },
);
+ /** Turns the caller's own push notifications for the conversation off or on. */
+ setNotificationsMuted = async (channelId: string, muted: boolean) =>
+ this.write(
+ channelId,
+ (tx, { member }) =>
+ setNotificationsMuted(tx, { memberId: member.id, userId: this.userId }, muted),
+ { allowArchived: true, allowTrashed: true },
+ );
+
/** Pins the conversation atop the caller's own list (joining an open one), or unpins it. */
setPinned = async (channelId: string, pinned: boolean) =>
this.write(
@@ -560,6 +571,7 @@ export class ChannelRepository {
memberRole: ChannelMemberRole | null;
mentionCount: number;
hidden: boolean;
+ notificationsMuted: boolean;
pinnedAt: Date | null;
replyJobs: ChannelReplyJob[];
sectionId: string | null;
@@ -578,6 +590,7 @@ export class ChannelRepository {
hidden: channelMembers.hidden,
lastReadSequence: channelMembers.lastReadSequence,
memberId: channelMembers.id,
+ notificationsMuted: notificationsMutedSql(),
pinnedAt: channelMembers.pinnedAt,
role: this.callerRole(),
sectionId: channelMembers.sectionId,
@@ -640,24 +653,7 @@ export class ChannelRepository {
const unreadMemberIds = rows
.filter(({ channel, lastReadSequence }) => channel.sequence > (lastReadSequence ?? 0))
.map(({ memberId }) => memberId);
- const mentioned = unreadMemberIds.length
- ? await this.db
- .select({
- channelId: channelMessages.channelId,
- count: sql<number>`count(*)::int`,
- })
- .from(channelMessages)
- .innerJoin(channelMembers, eq(channelMembers.channelId, channelMessages.channelId))
- .where(
- and(
- inArray(channelMembers.id, unreadMemberIds),
- sql`${channelMessages.sequence} > coalesce(${channelMembers.lastReadSequence}, 0)`,
- sql`${channelMessages.mentions} @> jsonb_build_array(${channelMembers.id}::text)`,
- ),
- )
- .groupBy(channelMessages.channelId)
- : [];
- const mentionCountOf = new Map(mentioned.map(({ channelId, count }) => [channelId, count]));
+ const mentionCountOf = await channelMentionCounts(this.db, unreadMemberIds);
// Thread mentions outlive the read position, which opening the main conversation moves.
const threadMentionsOf = await channelThreadMentions(
@@ -697,6 +693,7 @@ export class ChannelRepository {
channel,
hidden,
lastReadSequence,
+ notificationsMuted,
pinnedAt,
role,
sectionId,
@@ -715,6 +712,7 @@ export class ChannelRepository {
memberAvatars: avatarsOf.get(channel.id) ?? [],
memberRole: role,
mentionCount: mentionCountOf.get(channel.id) ?? 0,
+ notificationsMuted,
peerUserId: peerOf(channel, this.userId),
pinnedAt,
replyJobs: replyJobsOf.get(channel.id) ?? [],
@@ -739,6 +737,7 @@ export class ChannelRepository {
memberAvatars: avatarsOf.get(channel.id) ?? [],
memberRole: null,
mentionCount: 0,
+ notificationsMuted: false,
peerUserId: peerOf(channel, this.userId),
pinnedAt: null,
replyJobs: [],
diff --git a/packages/database/src/repositories/channel/notificationMute.ts b/packages/database/src/repositories/channel/notificationMute.ts
new file mode 100644
index 00000000000..39ee74ce372
--- /dev/null
+++ b/packages/database/src/repositories/channel/notificationMute.ts
@@ -0,0 +1,40 @@
+import { and, eq, sql } from 'drizzle-orm';
+
+import { channelMembers } from '../../schemas';
+import type { Transaction } from '../../type';
+
+/**
+ * Whether a person member turned off their own push notifications for the Channel, as SQL over
+ * `channel_members`, so a notification query can leave them out. Only their pushes stop: they
+ * still get every message, and Agents still reply (muting an Agent is `config.muted`).
+ */
+export const notificationsMutedSql = () =>
+ sql<boolean>`coalesce((${channelMembers.metadata} ->> 'notificationsMuted')::boolean, false)`;
+
+/**
+ * Turns the caller's own push notifications for one Channel off or on. Kept in the member row's
+ * metadata, not a column; the other metadata keys stay as they are.
+ *
+ * The predicate carries the caller's `userId` next to `memberId`, so this helper cannot rewrite
+ * somebody else's row even if a future caller hands it a foreign member id; when no row matches it
+ * fails closed instead of reporting a mute that never happened.
+ */
+export const setNotificationsMuted = async (
+ tx: Transaction,
+ caller: { memberId: string; userId: string },
+ muted: boolean,
+) => {
+ const metadata = sql`coalesce(${channelMembers.metadata}, '{}'::jsonb)`;
+ const [updated] = await tx
+ .update(channelMembers)
+ .set({
+ metadata: muted
+ ? sql`${metadata} || '{"notificationsMuted": true}'::jsonb`
+ : sql`${metadata} - 'notificationsMuted'`,
+ })
+ .where(and(eq(channelMembers.id, caller.memberId), eq(channelMembers.userId, caller.userId)))
+ .returning({ id: channelMembers.id });
+
+ if (!updated) throw new Error('Channel member not found for this person');
+ return muted;
+};
diff --git a/packages/database/src/repositories/channel/threadMentions.ts b/packages/database/src/repositories/channel/threadMentions.ts
index 953d1665f91..5183c3ef601 100644
--- a/packages/database/src/repositories/channel/threadMentions.ts
+++ b/packages/database/src/repositories/channel/threadMentions.ts
@@ -51,3 +51,27 @@ export const channelThreadMentions = async (
}
return mentionsOf;
};
+
+/**
+ * Unread messages, Threads included, that @mention each member, keyed by Channel and counted
+ * from the member's read position, as `unreadCount` is.
+ */
+export const channelMentionCounts = async (
+ db: LobeChatDatabase,
+ memberIds: string[],
+): Promise<Map<string, number>> => {
+ if (!memberIds.length) return new Map();
+ const rows = await db
+ .select({ channelId: channelMessages.channelId, count: sql<number>`count(*)::int` })
+ .from(channelMessages)
+ .innerJoin(channelMembers, eq(channelMembers.channelId, channelMessages.channelId))
+ .where(
+ and(
+ inArray(channelMembers.id, memberIds),
+ sql`${channelMessages.sequence} > coalesce(${channelMembers.lastReadSequence}, 0)`,
+ sql`${channelMessages.mentions} @> jsonb_build_array(${channelMembers.id}::text)`,
+ ),
+ )
+ .groupBy(channelMessages.channelId);
+ return new Map(rows.map(({ channelId, count }) => [channelId, count]));
+};
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 8f36151657f..237d7a204b5 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -147,6 +147,11 @@ export interface ChannelMemberWorktree {
export type ChannelMemberMetadata = Record<string, unknown> & {
/** The member who added this one; absent when they joined on their own or before it was kept. */
invitedBy?: string;
+ /**
+ * This person turned off their own push notifications for the Channel. Agents still reply;
+ * that is the Agent member's `config.muted`.
+ */
+ notificationsMuted?: boolean;
/** Worktree per conversation branch: a Thread id, or `main` for the main timeline. */
worktrees?: Record<string, ChannelMemberWorktree>;
/** The configured directory could not host a worktree (e.g. not a git repo); retried later. */
@@ -750,6 +755,12 @@ export interface ChannelListItem {
memberRole?: ChannelMemberRole | null;
/** Unread messages, Threads included, that @mention the caller; set by the Channel list. */
mentionCount?: number;
+ /**
+ * The caller turned off their own push notifications here, so a client leaves it out of the
+ * app badge too; set by the Channel list and detail. Personal: other members never see it, and
+ * Agents still reply.
+ */
+ notificationsMuted?: boolean;
/**
* On a conversation between two people, the other person (relative to the viewer), who is also
* the only entry of `memberAvatars`; null otherwise.