Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): enforce notification mute on delivery (wake + notify)
Simoneddb2c281e56e
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 18946b913..dac470b08 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -396,6 +396,18 @@ export type CommunityMentionCreate = {authorName: string}+// Per-user unread/badge signal. Unlike MESSAGE_CREATE (a single broadcast to+// every recipient), the badge is per-recipient — user A may be muted while user+// B is not for the same message — so it rides a per-user event, gated by the+// recipient's effective notification level in the notify pipeline. The client's+// MESSAGE_CREATE handler no longer bumps the badge itself (it only appends+// content); the badge is bumped only on this event.+export type CommunityUnreadBump = {+ type: "community:unread.bump"+ userId: string+ channelId: string+}+// ── Presence events ───────────────────────────────────────────────────────────export type CommunityPresenceUpdate = {@@ -562,6 +574,7 @@ export type CommunityWsEvent =| CommunityPresenceUpdate| CommunityStatusUpdate| CommunityMentionCreate+ | CommunityUnreadBump| CommunityMachineCreated| CommunityMachineStatus| CommunityMachineUpdated@@ -607,6 +620,7 @@ export const WS_EVENTS = {FRIEND_BLOCK: "community:friend.block",INVITE_CREATE: "community:invite.create",MENTION_CREATE: "community:mention.create",+ UNREAD_BUMP: "community:unread.bump",PRESENCE_UPDATE: "community:presence.update",STATUS_UPDATE: "community:status.update",MACHINE_CREATED: "community:machine.created",diff --git a/src/shared/src/db/queries/community/notification-setting.ts b/src/shared/src/db/queries/community/notification-setting.tsindex 51f187283..333282e15 100644--- a/src/shared/src/db/queries/community/notification-setting.ts+++ b/src/shared/src/db/queries/community/notification-setting.ts@@ -1,15 +1,71 @@-import { eq, and, or, isNotNull, inArray } from "drizzle-orm";-import { communityNotificationSetting } from "../../community-schema";+import { eq, and, or, isNull, isNotNull, inArray } from "drizzle-orm";+import { communityNotificationSetting, communityChannel } from "../../community-schema";import type { Database } from "../../index";+import type { NotificationLevelValue } from "../../../constants/community";-export async function getMutedUserIds(+type EffectiveLevelChannel = {+ id: string;+ serverId: string;+ parentChannelId: string | null;+};++type EffectiveLevelSetting = {+ channelId: string | null;+ serverId: string | null;+ level: string;+};++// Resolve a user's effective notification level for a channel: own-channel+// override beats parent-channel (forum/thread → its parent) beats server+// default beats the global default "all". A DM channel has serverId null and no+// parent, so it matches none of the fallbacks and lands on its OWN setting or+// the "all" default — a DM's level is self-contained, never inherited from a+// server/parent (a `nothing` set elsewhere can't cascade onto a DM).+export function computeEffectiveLevel(+ settings: EffectiveLevelSetting[],+ channel: EffectiveLevelChannel+): NotificationLevelValue {+ const own = settings.find((s) => s.channelId === channel.id);+ if (own) return own.level as NotificationLevelValue;++ if (channel.parentChannelId) {+ const parent = settings.find((s) => s.channelId === channel.parentChannelId);+ if (parent) return parent.level as NotificationLevelValue;+ }++ const server = settings.find(+ (s) => s.channelId == null && s.serverId === channel.serverId+ );+ if (server) return server.level as NotificationLevelValue;++ return "all";+}++async function loadChannel(+ db: Database,+ channelId: string+): Promise<EffectiveLevelChannel | null> {+ const rows = await db+ .select({+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ })+ .from(communityChannel)+ .where(eq(communityChannel.id, channelId));+ return rows[0] ?? null;+}++async function loadScopedSettings(db: Database,userIds: string[],- opts: { channelId?: string; serverId?: string }-): Promise<Set<string>> {- if (userIds.length === 0) return new Set()+ channel: EffectiveLevelChannel+): Promise<(EffectiveLevelSetting & { userId: string })[]> {+ const channelIds = channel.parentChannelId+ ? [channel.id, channel.parentChannelId]+ : [channel.id];- const rows = await db+ return db.select({userId: communityNotificationSetting.userId,channelId: communityNotificationSetting.channelId,@@ -17,23 +73,53 @@ export async function getMutedUserIds(level: communityNotificationSetting.level,}).from(communityNotificationSetting)- .where(and(- inArray(communityNotificationSetting.userId, userIds),- or(- opts.channelId ? eq(communityNotificationSetting.channelId, opts.channelId) : undefined,- opts.serverId ? and(eq(communityNotificationSetting.serverId, opts.serverId), isNotNull(communityNotificationSetting.serverId)) : undefined,- ),- ))-- const muted = new Set<string>()+ .where(+ and(+ inArray(communityNotificationSetting.userId, userIds),+ or(+ inArray(communityNotificationSetting.channelId, channelIds),+ and(+ eq(communityNotificationSetting.serverId, channel.serverId),+ isNull(communityNotificationSetting.channelId)+ )+ )+ )+ );+}++export async function resolveEffectiveLevel(+ db: Database,+ userId: string,+ channelId: string+): Promise<NotificationLevelValue> {+ const channel = await loadChannel(db, channelId);+ if (!channel) return "all";+ const settings = await loadScopedSettings(db, [userId], channel);+ return computeEffectiveLevel(settings, channel);+}++// Batch resolver: 2 queries total (one channel load + one scoped settings+// fetch) regardless of recipient count.+export async function resolveEffectiveLevelForUsers(+ db: Database,+ userIds: string[],+ channelId: string+): Promise<Map<string, NotificationLevelValue>> {+ const result = new Map<string, NotificationLevelValue>();+ if (userIds.length === 0) return result;++ const channel = await loadChannel(db, channelId);+ if (!channel) {+ for (const uid of userIds) result.set(uid, "all");+ return result;+ }++ const rows = await loadScopedSettings(db, userIds, channel);for (const uid of userIds) {- const userRows = rows.filter((r) => r.userId === uid)- const channelSetting = userRows.find((r) => r.channelId != null)- const serverSetting = userRows.find((r) => r.serverId != null)- const effective = channelSetting ?? serverSetting- if (effective?.level === "nothing") muted.add(uid)+ const userSettings = rows.filter((r) => r.userId === uid);+ result.set(uid, computeEffectiveLevel(userSettings, channel));}- return muted+ return result;}export async function getSettings(db: Database, userId: string) {diff --git a/src/shared/test/queries/community-notification-setting.test.ts b/src/shared/test/queries/community-notification-setting.test.tsnew file mode 100644index 000000000..70f1a1927--- /dev/null+++ b/src/shared/test/queries/community-notification-setting.test.ts@@ -0,0 +1,184 @@+import { describe, it, expect, vi } from "vitest";+import * as notif from "../../src/db/queries/community/notification-setting";++// Each `db.select().from().where()` resolves to the next queued result set.+function createSelectMock(resultSets: unknown[][]) {+ let call = 0;+ const chain: any = {};+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve(resultSets[call++] ?? []));+ const db: any = { select: vi.fn(() => chain), __chain: chain };+ return db;+}++const TEXT_CHANNEL = { id: "c1", serverId: "s1", parentChannelId: null };+const POST = { id: "p1", serverId: "s1", parentChannelId: "c1" };+// A DM channel: no server, no parent (post-#412 DMs are channels, but a DM row+// has serverId null and parentChannelId null).+const DM = { id: "dm1", serverId: null as unknown as string, parentChannelId: null };++describe("community/notification-setting exports", () => {+ it("exports the three effective-level functions", () => {+ expect(typeof notif.computeEffectiveLevel).toBe("function");+ expect(typeof notif.resolveEffectiveLevel).toBe("function");+ expect(typeof notif.resolveEffectiveLevelForUsers).toBe("function");+ });++ it("keeps the CRUD helpers", () => {+ expect(typeof notif.getSettings).toBe("function");+ expect(typeof notif.setServerLevel).toBe("function");+ expect(typeof notif.setChannelLevel).toBe("function");+ expect(typeof notif.removeChannelOverride).toBe("function");+ });++ it("no longer exports the dead getMutedUserIds", () => {+ expect((notif as Record<string, unknown>).getMutedUserIds).toBeUndefined();+ });+});++describe("computeEffectiveLevel — 3-tier climb", () => {+ it("no setting rows at all → global default 'all'", () => {+ expect(notif.computeEffectiveLevel([], TEXT_CHANNEL)).toBe("all");+ });++ it("server-level setting wins when no channel override exists", () => {+ const settings = [{ channelId: null, serverId: "s1", level: "mentions" }];+ expect(notif.computeEffectiveLevel(settings, TEXT_CHANNEL)).toBe("mentions");+ });++ it("channel override beats the server default", () => {+ const settings = [+ { channelId: null, serverId: "s1", level: "all" },+ { channelId: "c1", serverId: null, level: "nothing" },+ ];+ expect(notif.computeEffectiveLevel(settings, TEXT_CHANNEL)).toBe("nothing");+ });++ it("only reads the server row matching the channel's serverId", () => {+ const settings = [{ channelId: null, serverId: "other", level: "nothing" }];+ expect(notif.computeEffectiveLevel(settings, TEXT_CHANNEL)).toBe("all");+ });+});++describe("computeEffectiveLevel — post/thread parent inheritance", () => {+ it("post inherits the parent channel's override when it has none of its own", () => {+ const settings = [{ channelId: "c1", serverId: null, level: "nothing" }];+ expect(notif.computeEffectiveLevel(settings, POST)).toBe("nothing");+ });++ it("post inherits the server default when neither post nor parent has an override", () => {+ const settings = [{ channelId: null, serverId: "s1", level: "mentions" }];+ expect(notif.computeEffectiveLevel(settings, POST)).toBe("mentions");+ });++ it("a sub-channel override beats the parent override", () => {+ const settings = [+ { channelId: "c1", serverId: null, level: "nothing" },+ { channelId: "p1", serverId: null, level: "all" },+ ];+ expect(notif.computeEffectiveLevel(settings, POST)).toBe("all");+ });++ it("post override beats server default and parent absence", () => {+ const settings = [+ { channelId: null, serverId: "s1", level: "all" },+ { channelId: "p1", serverId: null, level: "mentions" },+ ];+ expect(notif.computeEffectiveLevel(settings, POST)).toBe("mentions");+ });++ it("post with no rows → global default 'all'", () => {+ expect(notif.computeEffectiveLevel([], POST)).toBe("all");+ });+});++describe("computeEffectiveLevel — DM independence (Gener/Melly #4)", () => {+ it("a DM with no own setting → 'all' (self-contained, defaults to all)", () => {+ expect(notif.computeEffectiveLevel([], DM)).toBe("all");+ });++ it("a DM honors its OWN 'nothing' setting (active mute)", () => {+ const settings = [{ channelId: "dm1", serverId: null, level: "nothing" }];+ expect(notif.computeEffectiveLevel(settings, DM)).toBe("nothing");+ });++ it("a 'nothing' set on some OTHER server does NOT cascade onto a DM (no inheritance)", () => {+ // The DM's serverId is null, so a server-scoped setting can never match it.+ const settings = [{ channelId: null, serverId: "s1", level: "nothing" }];+ expect(notif.computeEffectiveLevel(settings, DM)).toBe("all");+ });++ it("a 'nothing' set on another channel does NOT touch a DM", () => {+ const settings = [{ channelId: "c1", serverId: null, level: "nothing" }];+ expect(notif.computeEffectiveLevel(settings, DM)).toBe("all");+ });+});++describe("resolveEffectiveLevel — single user", () => {+ it("returns 'all' when the channel does not exist", async () => {+ const db = createSelectMock([[] /* channel lookup empty */]);+ expect(await notif.resolveEffectiveLevel(db, "u1", "missing")).toBe("all");+ });++ it("climbs to the channel override for the user", async () => {+ const db = createSelectMock([+ [TEXT_CHANNEL],+ [{ userId: "u1", channelId: "c1", serverId: null, level: "nothing" }],+ ]);+ expect(await notif.resolveEffectiveLevel(db, "u1", "c1")).toBe("nothing");+ });++ it("falls back to the server default when the user has no channel row", async () => {+ const db = createSelectMock([+ [TEXT_CHANNEL],+ [{ userId: "u1", channelId: null, serverId: "s1", level: "mentions" }],+ ]);+ expect(await notif.resolveEffectiveLevel(db, "u1", "c1")).toBe("mentions");+ });+});++describe("resolveEffectiveLevelForUsers — batch", () => {+ it("returns an empty map for no users without touching the db", async () => {+ const db = createSelectMock([]);+ const map = await notif.resolveEffectiveLevelForUsers(db, [], "c1");+ expect(map.size).toBe(0);+ expect(db.select).not.toHaveBeenCalled();+ });++ it("defaults every user to 'all' when the channel is missing", async () => {+ const db = createSelectMock([[] /* channel lookup empty */]);+ const map = await notif.resolveEffectiveLevelForUsers(db, ["u1", "u2"], "gone");+ expect(map.get("u1")).toBe("all");+ expect(map.get("u2")).toBe("all");+ });++ it("resolves distinct per-user levels on the same channel", async () => {+ const db = createSelectMock([+ [TEXT_CHANNEL],+ [+ { userId: "u1", channelId: "c1", serverId: null, level: "nothing" },+ { userId: "u2", channelId: null, serverId: "s1", level: "mentions" },+ ],+ ]);+ const map = await notif.resolveEffectiveLevelForUsers(db, ["u1", "u2", "u3"], "c1");+ expect(map.get("u1")).toBe("nothing");+ expect(map.get("u2")).toBe("mentions");+ expect(map.get("u3")).toBe("all");+ });++ it("fetches the channel once and scopes settings to that channel (single select round for settings)", async () => {+ const db = createSelectMock([+ [POST],+ [+ { userId: "u1", channelId: "c1", serverId: null, level: "nothing" },+ { userId: "u2", channelId: "p1", serverId: null, level: "all" },+ ],+ ]);+ const map = await notif.resolveEffectiveLevelForUsers(db, ["u1", "u2"], "p1");+ // u1 inherits the parent 'nothing'; u2 has a post-level 'all' override.+ expect(map.get("u1")).toBe("nothing");+ expect(map.get("u2")).toBe("all");+ // 1 channel lookup + 1 settings fetch = 2 selects total, regardless of user count.+ expect(db.select).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex e79728363..db1b8e062 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -27,6 +27,8 @@ const mockListReactionsByMessageIds = vi.fn()const mockGetUserInternal = vi.fn()const mockFanOutToChannel = vi.fn()+const mockResolveChannelRecipients = vi.fn(async () => [] as string[])+const mockDispatchMessageNotify = vi.fn(async () => {})const mockBroadcastToUser = vi.fn()const mockCheckMessageRateLimit = vi.fn()@@ -84,6 +86,11 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/community/fanout", () => ({fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),+ resolveChannelRecipients: (...a: unknown[]) => mockResolveChannelRecipients(...a),+}))++vi.mock("@/lib/community/notify", () => ({+ dispatchMessageNotify: (...a: unknown[]) => mockDispatchMessageNotify(...a),}))vi.mock("@/lib/broadcast", () => ({@@ -210,8 +217,13 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(payload.kind).toBe("mention")expect(payload.userIds.sort()).toEqual(["u2", "u3"])- const broadcastTargets = mockBroadcastToUser.mock.calls.map((c) => c[0]).sort()- expect(broadcastTargets).toEqual(["u2", "u3"])+ // MENTION_CREATE pushes now flow through the level-gated notify pipeline+ // (not raw broadcastToUser). The @everyone expansion is handed to it as the+ // mention set — @everyone counts as a mention (Gener #28), author excluded.+ expect(mockDispatchMessageNotify).toHaveBeenCalledTimes(1)+ const notifyArgs = mockDispatchMessageNotify.mock.calls[0]+ const mentionedUserIds = (notifyArgs[4] as { mentionedUserIds: string[] }).mentionedUserIds+ expect([...mentionedUserIds].sort()).toEqual(["u2", "u3"])})it("resolves @Bob candidate via listMembers (name-projected) when content includes '@'", async () => {diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.tsindex e8a1990ca..cb79adfeb 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts@@ -78,6 +78,11 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/community/fanout", () => ({fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),fanOutToDM: vi.fn(async () => {}),+ resolveChannelRecipients: vi.fn(async () => [] as string[]),+}))++vi.mock("@/lib/community/notify", () => ({+ dispatchMessageNotify: vi.fn(async () => {}),}))// createCommunityMessage's non-fanout side effects — stub so the pipeline runs.diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts b/src/web/src/app/api/community/dm/[id]/messages/route.test.tsindex 3323cfd64..5c93faa38 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.test.ts@@ -25,6 +25,8 @@ const mockGetUserInternal = vi.fn()const mockFanOutToChannel = vi.fn()const mockFanOutToDM = vi.fn()+const mockResolveChannelRecipients = vi.fn(async () => [] as string[])+const mockDispatchMessageNotify = vi.fn(async () => {})const mockBroadcastToUser = vi.fn()const mockCheckMessageRateLimit = vi.fn()@@ -82,6 +84,11 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/community/fanout", () => ({fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),+ resolveChannelRecipients: (...a: unknown[]) => mockResolveChannelRecipients(...a),+}))++vi.mock("@/lib/community/notify", () => ({+ dispatchMessageNotify: (...a: unknown[]) => mockDispatchMessageNotify(...a),}))vi.mock("@/lib/broadcast", () => ({diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex f20f01ade..3f5cf5c83 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -153,6 +153,10 @@ function messageCreate(channelId: string, msgId = "m_1"): CommunityMessageCreate}}+function unreadBump(channelId: string, userId: string) {+ return { type: "community:unread.bump" as const, userId, channelId }+}+describe("useCommunityWs — message.create", () => {it("patches channelMessages cache when the event matches the focused channel", async () => {await mountHook()@@ -440,13 +444,13 @@ describe("useCommunityWs — message.create patches channel unread in the open s}}- it("flips the channel's unread to true when it belongs to the currently-open server's cached ServerDetail", async () => {+ it("flips the channel's unread to true on unread.bump when it belongs to the currently-open server's cached ServerDetail", async () => {await mountHook({ viewerUserId: "u_me" })const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().setCurrentServerId("srv_open")capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))- capturedOnMessage!(messageCreate("ch_random"))+ capturedOnMessage!(unreadBump("ch_random", "u_me"))const cache = capturedQueryClient.getQueryData<{categories: { channels: { id: string; unread: boolean }[] }[]@@ -454,18 +458,31 @@ describe("useCommunityWs — message.create patches channel unread in the open sexpect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_random", unread: true })})- it("does NOT flip unread for a message authored by the viewer themself", async () => {+ it("message.create alone does NOT flip the sidebar unread (mute-gated bump is the only trigger now)", async () => {+ // Regression pin: mute ≠ blindness. The message.create still arrives (and+ // content syncs), but the unread dot is flipped ONLY by the server's+ // per-recipient, mute-gated unread.bump — so a muted channel's message.create+ // must NOT light the dot. Don't "fix" this back onto message.create.await mountHook({ viewerUserId: "u_me" })const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().setCurrentServerId("srv_open")capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))- const event: CommunityMessageCreate = {- type: "community:message.create",- channelId: "ch_random",- message: { id: "m_self", authorId: "u_me", authorName: "me", content: "hi", createdAt: "2026-07-03T00:00:00.000Z" },- }- capturedOnMessage!(event)+ capturedOnMessage!(messageCreate("ch_random"))++ const cache = capturedQueryClient.getQueryData<{+ categories: { channels: { id: string; unread: boolean }[] }[]+ }>(communityKeys.server("srv_open"))+ expect(cache?.categories[0].channels[0].unread).toBe(false)+ })++ it("does NOT flip unread on a bump addressed to a different user", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().setCurrentServerId("srv_open")+ capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))++ capturedOnMessage!(unreadBump("ch_random", "someone_else"))const cache = capturedQueryClient.getQueryData<{categories: { channels: { id: string; unread: boolean }[] }[]@@ -484,7 +501,7 @@ describe("useCommunityWs — message.create patches channel unread in the open sawait mountHook({ viewerUserId: "u_me" })capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))- capturedOnMessage!(messageCreate("ch_random"))+ capturedOnMessage!(unreadBump("ch_random", "u_me"))const cache = capturedQueryClient.getQueryData<{categories: { channels: { id: string; unread: boolean }[] }[]@@ -498,7 +515,7 @@ describe("useCommunityWs — message.create patches channel unread in the open suseCommunityStore.getState().setCurrentServerId("srv_open")capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_other"))- expect(() => capturedOnMessage!(messageCreate("ch_random"))).not.toThrow()+ expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()const cache = capturedQueryClient.getQueryData<{categories: { channels: { id: string; unread: boolean }[] }[]@@ -509,10 +526,10 @@ describe("useCommunityWs — message.create patches channel unread in the open sit("does not crash and is a no-op when no server is currently open", async () => {await mountHook({ viewerUserId: "u_me" })- expect(() => capturedOnMessage!(messageCreate("ch_random"))).not.toThrow()+ expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()})- it("existing focused-channel message patch and debounced inbox invalidation still fire alongside the new unread patch", async () => {+ it("existing focused-channel message patch and debounced inbox invalidation still fire on message.create", async () => {vi.useFakeTimers()try {await mountHook({ viewerUserId: "u_me" })diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 795cf48bf..e4c68441f 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -479,27 +479,12 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {scheduleInboxInvalidate()}- // 3) Live channel-sidebar unread dot: if this message landed in a- // channel that belongs to the currently-open server's cached- // `ServerDetail`, flip that channel's `unread` to `true` —- // no network round-trip. Skip for the viewer's own sends (never- // unread to themselves) and for the currently-**subscribed**- // channel (the dot is already suppressed there via `!active` in- // `sortable-channel.tsx`, but skipping the cache patch too- // avoids a stale `unread: true` lingering for when the user- // later navigates away without the watermark path re-clearing- // it). No-op automatically (via the helper's own "no matching- // channel" branch) if that server's detail isn't cached or- // doesn't contain this channel.- if (event.channelId && event.channelId !== sub.channelId && event.message.authorId !== viewerId) {- const currentServerId = useCommunityStore.getState().currentServerId- if (currentServerId) {- queryClient.setQueryData<ServerDetail | undefined>(- communityKeys.server(currentServerId),- (cache) => patchChannelUnread(cache, event.channelId!, true),- )- }- }+ // 3) Live channel-sidebar unread dot is NO LONGER flipped here.+ // Unread is per-recipient and mute-gated on the server now, so it+ // rides the dedicated `community:unread.bump` event (below) — a+ // muted (`nothing`/unmentioned-`mentions`) channel must NOT light+ // an unread dot even though its `message.create` still arrives+ // (mute ≠ blindness: content syncs, the badge does not).// Note: no auto-mark-read here. See #3 — the// IntersectionObserver in `useChannelWatermark` advances the@@ -514,6 +499,27 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}+ // ── Per-user unread/badge signal ─────────────────────────────────+ // Mute-gated on the server (only recipients whose effective level+ // delivers get this), so the sidebar unread dot flips ONLY here — a+ // muted channel's `message.create` no longer lights it. Skip the+ // currently-subscribed channel (dot suppressed there anyway) and never+ // for the viewer's own sends (the server excludes the author, but guard+ // defensively).+ case "community:unread.bump": {+ const viewerId = viewerUserIdRef.current+ if (event.userId === viewerId && event.channelId !== sub.channelId) {+ const currentServerId = useCommunityStore.getState().currentServerId+ if (currentServerId) {+ queryClient.setQueryData<ServerDetail | undefined>(+ communityKeys.server(currentServerId),+ (cache) => patchChannelUnread(cache, event.channelId, true),+ )+ }+ }+ return+ }+// ── Reactions ───────────────────────────────────────────────────case "community:reaction.add":case "community:reaction.remove": {diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex f34900157..8227b2976 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -31,7 +31,7 @@ type BroadcastableEvent = CommunityWsEvent & { type: string }* event.type !== MESSAGE_CREATE) → no wake dispatch, e.g.* `CHILD_CHANNEL_UPDATE` never wakes anyone.*/-type WakeOpts = { wakeMessageRow?: WakeMessageRow }+type WakeOpts = { wakeMessageRow?: WakeMessageRow; mentionedUserIds?: string[] }/*** Resolves all member user IDs for a server.@@ -72,18 +72,32 @@ async function getChannelRecipientUserIds(db: Database, channelId: string): Prom})}+/**+ * Public wrapper so `message-handler` can resolve a channel's recipient set+ * ONCE and share it between the unfiltered `MESSAGE_CREATE` fan-out and the+ * level-filtered notify pipeline (no second membership query). Same split as+ * `getChannelRecipientUserIds` (thread/forum_post → participants; dm → access+ * members; channel/forum → scope audience).+ */+export async function resolveChannelRecipients(db: Database, channelId: string): Promise<string[]> {+ return getChannelRecipientUserIds(db, channelId)+}+/*** Fan out an event to all members of the server that owns a channel.*/export async function fanOutToChannel(channelId: string,event: BroadcastableEvent,- opts?: { excludeUserId?: string } & WakeOpts+ opts?: { excludeUserId?: string; recipients?: string[] } & WakeOpts): Promise<void> {try {const { env } = getCloudflareContext()const db = getDb((env as Env).DB)- const userIds = await getChannelRecipientUserIds(db, channelId)+ // Reuse a pre-resolved recipient set when the caller already resolved it+ // (message-handler shares one set between fan-out and the notify pipeline),+ // else resolve here.+ const userIds = opts?.recipients ?? await getChannelRecipientUserIds(db, channelId)await broadcastToRecipients(userIds, event, opts?.excludeUserId)maybeEnqueueWakes(event, userIds, { channelId }, opts)} catch (err) {@@ -144,6 +158,7 @@ function maybeEnqueueWakes(recipients: filtered,...scope,messageRow: opts.wakeMessageRow,+ mentionedUserIds: opts.mentionedUserIds,}).catch((err) => {log.warn("enqueue_bot_wakes_from_fanout_failed", { err: String(err) })})diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 791142f2a..dc860c4ed 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -68,10 +68,17 @@ vi.mock("@alook/shared", async () => {const mockFanOutToChannel = vi.fn()const mockFanOutToDM = vi.fn()const mockBroadcastToUserSafe = vi.fn()+const mockResolveChannelRecipients = vi.fn(async () => [] as string[])vi.mock("./fanout", () => ({fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),+ resolveChannelRecipients: (...a: unknown[]) => mockResolveChannelRecipients(...a),+}))++const mockDispatchMessageNotify = vi.fn(async () => {})+vi.mock("./notify", () => ({+ dispatchMessageNotify: (...a: unknown[]) => mockDispatchMessageNotify(...a),}))const mockBroadcastToUser = vi.fn()diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex de56b6b46..049f528f9 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -9,8 +9,8 @@ import {} from "@alook/shared"import type { MentionType } from "@alook/shared"import type { Database } from "@alook/shared"-import { fanOutToChannel, fanOutToDM } from "./fanout"-import { broadcastToUser } from "../broadcast"+import { fanOutToChannel, resolveChannelRecipients } from "./fanout"+import { dispatchMessageNotify } from "./notify"import { mapMessageForWs } from "./message-payload"import { mediaUrlFromKey } from "./storage"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "./audit"@@ -619,43 +619,43 @@ export async function createCommunityMessage(params: {// All WS side effects live here so `deferBroadcast` can hand them back as a// thunk instead of firing them inline.const doBroadcast = async (): Promise<void> => {- if (liveMentions.length > 0 || liveReplies.length > 0) {- const authorName = row.authorName- const channelIdForBroadcast = target.channelId- for (const userId of [...liveMentions, ...liveReplies]) {- broadcastToUser(userId, {- type: WS_EVENTS.MENTION_CREATE,- userId,- messageId: row.id,- channelId: channelIdForBroadcast,- authorName,- }).catch(() => { })- }- }-- if (isDmTarget(target)) {- // DMs are channels now — fan out MESSAGE_CREATE keyed by channelId to- // both access members (no separate DM event).- fanOutToChannel(- target.channelId,- {- type: WS_EVENTS.MESSAGE_CREATE,- channelId: target.channelId,- message: messagePayload,- },- { excludeUserId: fanoutExclude, wakeMessageRow },- ).catch(() => { })- } else {- fanOutToChannel(- target.channelId,- {- type: WS_EVENTS.MESSAGE_CREATE,- channelId: target.channelId,- message: messagePayload,- },- { excludeUserId: fanoutExclude, wakeMessageRow },- ).catch(() => { })-+ // Resolve the recipient set ONCE and share it between the unfiltered+ // MESSAGE_CREATE fan-out (mute ≠ blindness: content always syncs) and the+ // level-filtered notify pipeline (per-recipient MENTION_CREATE push ++ // UNREAD_BUMP badge) — no second membership query. DMs are channels now, so+ // both DM and channel targets flow through the same path; the notify+ // pipeline resolves each recipient's effective level (a DM's level is+ // self-contained, defaulting to `all`).+ const recipients = await resolveChannelRecipients(db, target.channelId)++ fanOutToChannel(+ target.channelId,+ {+ type: WS_EVENTS.MESSAGE_CREATE,+ channelId: target.channelId,+ message: messagePayload,+ },+ {+ excludeUserId: fanoutExclude,+ recipients,+ wakeMessageRow,+ mentionedUserIds: [...liveMentions, ...liveReplies],+ },+ ).catch(() => { })++ // Level-filtered human notify legs. Author is excluded (never notifies+ // self); mention sets are already author-excluded upstream. `nothing`+ // recipients are dropped from push + badge — but their mention ROWS were+ // already written above (createMentions is never level-gated).+ dispatchMessageNotify(+ db,+ { authorName: row.authorName },+ { id: row.id, channelId: row.channelId },+ recipients.filter((id) => id !== authorId),+ { mentionedUserIds: [...liveMentions, ...liveReplies] },+ ).catch(() => { })++ if (!isDmTarget(target)) {if (hasParentChannel(target)) {const updated = await queries.communityChannel.getChannel(db,diff --git a/src/web/src/lib/community/notify.test.ts b/src/web/src/lib/community/notify.test.tsnew file mode 100644index 000000000..88deaacbe--- /dev/null+++ b/src/web/src/lib/community/notify.test.ts@@ -0,0 +1,110 @@+import { describe, it, expect, vi, beforeEach } from "vitest"++const mockResolveEffectiveLevelForUsers = vi.fn()+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),+ queries: {+ communityNotificationSetting: {+ resolveEffectiveLevelForUsers: (...a: unknown[]) =>+ mockResolveEffectiveLevelForUsers(...(a as [unknown, string[], string])),+ },+ },+ }+})++const mockBroadcastToUser = vi.fn(() => Promise.resolve())+vi.mock("../broadcast", () => ({+ broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),+}))++import { dispatchMessageNotify, shouldDeliver } from "./notify"++const db = {} as never++function bumpEvents() {+ return mockBroadcastToUser.mock.calls.map((c) => c[1]).filter((e: any) => e.type === "community:unread.bump")+}+function mentionEvents() {+ return mockBroadcastToUser.mock.calls.map((c) => c[1]).filter((e: any) => e.type === "community:mention.create")+}++describe("shouldDeliver", () => {+ it("all → always", () => {+ expect(shouldDeliver("all", false)).toBe(true)+ expect(shouldDeliver("all", true)).toBe(true)+ })+ it("mentions → only when mentioned", () => {+ expect(shouldDeliver("mentions", false)).toBe(false)+ expect(shouldDeliver("mentions", true)).toBe(true)+ })+ it("nothing → never", () => {+ expect(shouldDeliver("nothing", false)).toBe(false)+ expect(shouldDeliver("nothing", true)).toBe(false)+ })+})++describe("dispatchMessageNotify", () => {+ beforeEach(() => vi.clearAllMocks())++ const msg = { id: "m1", channelId: "c1" }+ const ctx = { authorName: "Alice" }++ it("all-level recipient: gets a badge; a mentioned all-level recipient also gets the mention push", async () => {+ mockResolveEffectiveLevelForUsers.mockResolvedValue(+ new Map([["u_plain", "all"], ["u_mentioned", "all"]]),+ )+ await dispatchMessageNotify(db, ctx, msg, ["u_plain", "u_mentioned"], {+ mentionedUserIds: ["u_mentioned"],+ })+ expect(bumpEvents().map((e: any) => e.userId).sort()).toEqual(["u_mentioned", "u_plain"])+ expect(mentionEvents().map((e: any) => e.userId)).toEqual(["u_mentioned"])+ })++ it("mentions-level: plain recipient gets nothing; mentioned recipient gets badge + push", async () => {+ mockResolveEffectiveLevelForUsers.mockResolvedValue(+ new Map([["u_plain", "mentions"], ["u_mentioned", "mentions"]]),+ )+ await dispatchMessageNotify(db, ctx, msg, ["u_plain", "u_mentioned"], {+ mentionedUserIds: ["u_mentioned"],+ })+ expect(bumpEvents().map((e: any) => e.userId)).toEqual(["u_mentioned"])+ expect(mentionEvents().map((e: any) => e.userId)).toEqual(["u_mentioned"])+ })++ it("@everyone counts as a mention: a mentions-level recipient in the mention set gets badge + push", async () => {+ // @everyone expands into mentionedUserIds upstream — no carve-out (Gener #28).+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["u_e", "mentions"]]))+ await dispatchMessageNotify(db, ctx, msg, ["u_e"], { mentionedUserIds: ["u_e"] })+ expect(bumpEvents().map((e: any) => e.userId)).toEqual(["u_e"])+ expect(mentionEvents().map((e: any) => e.userId)).toEqual(["u_e"])+ })++ it("nothing-level recipient (even mentioned): NO badge, NO push (mention ROW is written elsewhere, not here)", async () => {+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["u_muted", "nothing"]]))+ await dispatchMessageNotify(db, ctx, msg, ["u_muted"], { mentionedUserIds: ["u_muted"] })+ expect(bumpEvents()).toEqual([])+ expect(mentionEvents()).toEqual([])+ // Never emits MESSAGE_CREATE — that's the caller's unconditional fan-out.+ const anyMessageCreate = mockBroadcastToUser.mock.calls.some(+ (c: any) => c[1]?.type === "community:message.create",+ )+ expect(anyMessageCreate).toBe(false)+ })++ it("missing level defaults to 'all' (DM independence — resolver returns no row)", async () => {+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ await dispatchMessageNotify(db, ctx, msg, ["u_dm"], { mentionedUserIds: [] })+ expect(bumpEvents().map((e: any) => e.userId)).toEqual(["u_dm"])+ })++ it("absorbs a resolver failure without throwing (send must not fail on a notify blip)", async () => {+ mockResolveEffectiveLevelForUsers.mockRejectedValue(new Error("d1 blip"))+ await expect(+ dispatchMessageNotify(db, ctx, msg, ["u1"], { mentionedUserIds: [] }),+ ).resolves.toBeUndefined()+ expect(bumpEvents()).toEqual([])+ })+})diff --git a/src/web/src/lib/community/notify.ts b/src/web/src/lib/community/notify.tsnew file mode 100644index 000000000..7d6a608b0--- /dev/null+++ b/src/web/src/lib/community/notify.ts@@ -0,0 +1,128 @@+/**+ * Unified per-recipient message-notify pipeline (adapted from PR-408 batch 3,+ * commit 2b61535d, to main's post-#412 DM-as-channel model).+ *+ * ONE trunk for the HUMAN notify legs of a new message: resolve each+ * recipient's effective notification level, apply the 3-tier matrix, then+ * dispatch the mute-gated per-user signals — a `MENTION_CREATE` live push (when+ * that recipient was mentioned) and a per-user `UNREAD_BUMP` badge. Writes NO+ * persistent state — offline replay rides the existing `community_read_state`+ * cursors.+ *+ * Scope boundaries (Melly #23 ruling):+ * - This pipeline does NOT own bot WAKE. Wake gating lives in+ * `wake-producer` (the produce/enqueue seam), gated by the SAME+ * effective-level resolver. Keeping wake out of here keeps notify.ts to the+ * human legs and avoids a double gate.+ * - This pipeline NEVER emits `MESSAGE_CREATE`. That broadcast is the ONLY+ * content-sync path, stays in `fanOutToChannel`, and is unfiltered by level —+ * so a user viewing their own muted channel still sees messages live, and a+ * bot's `inbox pull` / `channel history` are never affected (mute ≠+ * blindness).+ * - Mention ROWS (`createMentions`) are written by the caller, independent of+ * this pipeline and NEVER level-gated — a `nothing` recipient's mention still+ * persists and surfaces via inbox.+ *+ * The 3-tier matrix (bots and users, same predicate — Gener #28):+ * level plain msg (not mentioned) mentioned+ * all badge badge + MENTION_CREATE push+ * mentions silent badge + MENTION_CREATE push+ * nothing silent silent (mention row still written)+ *+ * where "mentioned" = personal @ ∪ @everyone ∪ reply-to-me (the caller's full+ * mention set — @everyone counts, no split; Gener #28).+ */+import { queries, WS_EVENTS, createLogger } from "@alook/shared"+import type { Database, NotificationLevelValue } from "@alook/shared"+import { broadcastToUser } from "../broadcast"++const log = createLogger({ service: "community-notify" })++export interface MessageNotifyContext {+ /**+ * Snapshot author name for the `MENTION_CREATE` payload. The author is+ * already excluded from `recipients`/`mentionedUserIds` upstream — this is+ * only the label mentioned users see.+ */+ authorName: string+}++/**+ * `true` when a recipient at `level` should receive the human notify legs for a+ * message where `wasMentioned` reflects whether THIS recipient was mentioned+ * (personal @ ∪ @everyone ∪ reply). Governs both badge and the mention push+ * uniformly.+ */+export function shouldDeliver(level: NotificationLevelValue, wasMentioned: boolean): boolean {+ if (level === "all") return true+ if (level === "mentions") return wasMentioned+ return false // "nothing" — never+}++/**+ * Dispatch level-filtered HUMAN notify signals for one just-created message.+ * Fire-and-forget: absorbs all failures (the message already synced via+ * `MESSAGE_CREATE`; a level-resolution blip must never fail the send).+ *+ * @param channelId the message's channel scope. Every scope (channel, thread,+ * forum_post, AND dm) resolves its per-recipient level here — there is NO+ * channelId-nullness bypass (main's DMs are channels with a channelId; a DM's+ * level is self-contained and defaults to `all`, so routing it through the+ * resolver both honors an explicit per-DM mute and never inherits a+ * server/parent `nothing`).+ * @param recipients the fan-out recipient set (human + bot), already+ * author-excluded — the SAME list resolved for the `MESSAGE_CREATE` broadcast.+ * @param mentionedUserIds the full mention set (explicit @ ∪ @everyone+ * expansion ∪ reply targets), already author-excluded — @everyone counts as a+ * mention (Gener #28), no carve-out.+ */+export async function dispatchMessageNotify(+ db: Database,+ ctx: MessageNotifyContext,+ message: { id: string; channelId: string },+ recipients: string[],+ opts: { mentionedUserIds: string[] },+): Promise<void> {+ try {+ const { channelId } = message+ const mentioned = new Set(opts.mentionedUserIds)++ const everyone = [...new Set([...recipients, ...opts.mentionedUserIds])]+ const levels = await queries.communityNotificationSetting.resolveEffectiveLevelForUsers(+ db,+ everyone,+ channelId,+ )+ const levelOf = (userId: string): NotificationLevelValue => levels.get(userId) ?? "all"++ // MENTION_CREATE live push — only to mentioned recipients whose level+ // delivers. A `nothing` mentioned recipient gets NO push, but their mention+ // ROW is still written by the caller.+ for (const userId of mentioned) {+ if (!shouldDeliver(levelOf(userId), true)) continue+ broadcastToUser(userId, {+ type: WS_EVENTS.MENTION_CREATE,+ userId,+ messageId: message.id,+ channelId,+ authorName: ctx.authorName,+ }).catch(() => {})+ }++ // Per-user UNREAD_BUMP badge — per-recipient (A muted, B not), so it rides a+ // per-user event, not a flag on the shared MESSAGE_CREATE payload.+ for (const userId of recipients) {+ if (!shouldDeliver(levelOf(userId), mentioned.has(userId))) continue+ broadcastToUser(userId, {+ type: WS_EVENTS.UNREAD_BUMP,+ userId,+ channelId,+ }).catch(() => {})+ }+ } catch (err) {+ log.warn("dispatch_message_notify_failed", {+ messageId: message.id,+ err: String(err),+ })+ }+}diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.tsindex e5bef6b66..1decbc1bc 100644--- a/src/web/src/lib/community/wake-producer.test.ts+++ b/src/web/src/lib/community/wake-producer.test.ts@@ -11,6 +11,11 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockFindWakeCandidates = vi.fn()const mockCanBotReadWakeScope = vi.fn()+// Default: every bot resolves to "all" (no mute) — existing tests wake as+// before. The mute-gate tests below override this.+const mockResolveEffectiveLevelForUsers = vi.fn(+ async (_db: unknown, userIds: string[]) => new Map(userIds.map((id) => [id, "all"])),+)const mockWarn = vi.fn()const mockInfo = vi.fn()@@ -31,6 +36,9 @@ vi.mock("@alook/shared", async () => {communityMember: {canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),},+ communityNotificationSetting: {+ resolveEffectiveLevelForUsers: (...a: unknown[]) => mockResolveEffectiveLevelForUsers(...(a as [unknown, string[]])),+ },},}})@@ -122,6 +130,82 @@ describe("enqueueBotWakes", () => {expect(payloads).toEqual([{ messageId: "msg_1", botUserId: "bot_visible" }])})+ // ── Mute gate (net-new #4) ──────────────────────────────────────────────+ it("MUTE GATE — a bot at 'nothing' never wakes, even when mentioned", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_muted", name: "z", machineId: "m1", runtime: "claude" },+ ])+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["bot_muted", "nothing"]]))++ await enqueueBotWakes({+ recipients: ["bot_muted"],+ channelId: "c1",+ messageRow,+ mentionedUserIds: ["bot_muted"], // even mentioned+ })++ expect(mockQueueSend).not.toHaveBeenCalled()+ })++ it("MUTE GATE — a bot at 'mentions' wakes only when in the mention set (incl. @everyone)", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_mentioned", name: "a", machineId: "m1", runtime: "claude" },+ { botUserId: "bot_plain", name: "b", machineId: "m2", runtime: "codex" },+ ])+ mockResolveEffectiveLevelForUsers.mockResolvedValue(+ new Map([+ ["bot_mentioned", "mentions"],+ ["bot_plain", "mentions"],+ ]),+ )++ await enqueueBotWakes({+ recipients: ["bot_mentioned", "bot_plain"],+ channelId: "c1",+ messageRow,+ mentionedUserIds: ["bot_mentioned"], // only this one is in the mention set+ })++ expect(mockQueueSend).toHaveBeenCalledTimes(1)+ const [payloads] = mockQueueSend.mock.calls[0]!+ expect(payloads).toEqual([{ messageId: "msg_1", botUserId: "bot_mentioned" }])+ })++ it("MUTE GATE — a bot at 'all' wakes on any unread, mentioned or not", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_all", name: "a", machineId: "m1", runtime: "claude" },+ ])+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["bot_all", "all"]]))++ await enqueueBotWakes({+ recipients: ["bot_all"],+ channelId: "c1",+ messageRow,+ mentionedUserIds: [], // not mentioned — still wakes at 'all'+ })++ expect(mockQueueSend).toHaveBeenCalledTimes(1)+ const [payloads] = mockQueueSend.mock.calls[0]!+ expect(payloads).toEqual([{ messageId: "msg_1", botUserId: "bot_all" }])+ })++ it("MUTE GATE — a bot with no setting defaults to 'all' (wakes) — covers DM independence (no server/parent to inherit a mute from)", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_dm", name: "a", machineId: "m1", runtime: "claude" },+ ])+ // resolver returns an empty map → levelOf falls back to "all"+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())++ await enqueueBotWakes({+ recipients: ["bot_dm"],+ channelId: "dm_channel",+ messageRow,+ mentionedUserIds: [],+ })++ expect(mockQueueSend).toHaveBeenCalledTimes(1)+ })+it("drops (does NOT throw or collapse the batch) when a single candidate's gate check rejects", async () => {// Regression guard: a transient D1 blip on ONE candidate's gate check// must not wipe every wake for the message — `allSettled`, not `all`.diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.tsindex 056d503ea..45c86d8f0 100644--- a/src/web/src/lib/community/wake-producer.ts+++ b/src/web/src/lib/community/wake-producer.ts@@ -20,6 +20,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, createLogger } from "@alook/shared"import type { WakePayload } from "@alook/shared"import { getDb } from "../db"+import { shouldDeliver } from "./notify"import { createQueueWakeTransport, createDevHttpWakeTransport } from "./wake-transport"import type { WakeTransport } from "./wake-transport"@@ -46,6 +47,13 @@ export interface EnqueueBotWakesOpts {recipients: string[]channelId: stringmessageRow: WakeMessageRow+ /**+ * The message's full mention set (personal @ ∪ @everyone ∪ reply), already+ * author-excluded. Used by the mute gate: a bot at `mentions` level only+ * wakes when it's in this set. Omitted → treated as "nobody mentioned" (so a+ * `mentions`-level bot won't wake on a plain message).+ */+ mentionedUserIds?: string[]}/**@@ -123,7 +131,27 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v})if (gated.length === 0) return- const payloads: WakePayload[] = gated.map((c) => ({+ // Mute gate (net-new — server-side notification level applied to bot wake).+ // A bot's effective level for this channel decides whether a new message+ // wakes it: `all` → any unread wakes; `mentions` → only if this bot is in the+ // message's mention set (personal @ ∪ @everyone ∪ reply — Gener #28: bots and+ // users share one predicate, @everyone counts); `nothing` → never. This gates+ // ONLY wake — it never affects what the bot can read via inbox pull / channel+ // history (mute ≠ blindness). A DM's level is self-contained (resolver finds+ // no server/parent row → defaults to `all`), so a `nothing` set elsewhere+ // never suppresses a DM wake.+ const mentioned = new Set(opts.mentionedUserIds ?? [])+ const levels = await queries.communityNotificationSetting.resolveEffectiveLevelForUsers(+ db,+ gated.map((c) => c.botUserId),+ channelId,+ )+ const woken = gated.filter((c) =>+ shouldDeliver(levels.get(c.botUserId) ?? "all", mentioned.has(c.botUserId)),+ )+ if (woken.length === 0) return++ const payloads: WakePayload[] = woken.map((c) => ({messageId: messageRow.id,botUserId: c.botUserId,}))