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(shared): unify notification attention, unread, and wake semantics (#480)
Gustavo Ye1fd8c6a71617
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex b7c3ba558..d4ea0de19 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -54,7 +54,7 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {channelMember: async () => ({ visibility: "public", hint: "" }),inboxPull: async () => ({ messages: [], hasMore: false, markedCount: 0 }),inboxSnapshot: async () => ({ rows: [], pendingChannels: 0, pendingMessages: 0 }),- ack: async () => undefined,+ ack: async (req) => ({ ok: true, applied: req.cursors, failed: [] }),send: async () => ({ state: "sent", message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" } }),createPost: async () => ({ ref: "/s/c/post", name: "post", seq: 1 }),read: async () => ({ items: [], hasMore: false }),@@ -400,7 +400,9 @@ describe("message send --reply", () => {describe("inbox pull", () => {it("never acks a rejected pull and only advances the returned cursor after repair", async () => {- const ackSpy = vi.fn(async () => undefined);+ const ackSpy = vi.fn(async (req: { cursors: Array<{ channel: string; seq: number }> }) => ({+ ok: true, applied: req.cursors, failed: [],+ }));const pullSpy = vi.fn().mockRejectedValueOnce(new Error("DM peer identity unavailable")).mockResolvedValueOnce({@@ -424,7 +426,9 @@ describe("inbox pull", () => {});it("acks by default and returns messages in success", async () => {- const ackSpy = vi.fn(async () => undefined);+ const ackSpy = vi.fn(async (req: { cursors: Array<{ channel: string; seq: number }> }) => ({+ ok: true, applied: req.cursors, failed: [],+ }));setApiForTesting(stubApi({inboxPull: async () => ({@@ -446,7 +450,9 @@ describe("inbox pull", () => {});it("--no-ack skips advancing the waterline", async () => {- const ackSpy = vi.fn(async () => undefined);+ const ackSpy = vi.fn(async (req: { cursors: Array<{ channel: string; seq: number }> }) => ({+ ok: true, applied: req.cursors, failed: [],+ }));setApiForTesting(stubApi({inboxPull: async () => ({@@ -510,7 +516,7 @@ describe("inbox pull", () => {hasMore: false,markedCount: 0,}),- ack: async () => undefined,+ ack: async (req) => ({ ok: true, applied: req.cursors, failed: [] }),}),);await main(["inbox", "pull"]);@@ -521,6 +527,43 @@ describe("inbox pull", () => {expect(env.success.ackError).toBeUndefined();});+ it("reports only applied cursors as acked and preserves partial failures", async () => {+ setApiForTesting(+ stubApi({+ inboxPull: async () => ({+ messages: [+ { seq: "#2", channel: "/s#0042/general", sender: "@x", content: { text: "ok" }, time: "" },+ { seq: "#4", channel: "/s#0042/private", sender: "@x", content: { text: "blocked" }, time: "" },+ ],+ hasMore: false,+ markedCount: 0,+ }),+ ack: async () => ({+ ok: false,+ applied: [{ channel: "/s#0042/general", seq: 2 }],+ failed: [{+ channel: "/s#0042/private",+ seq: 4,+ code: "forbidden",+ error: "forbidden",+ }],+ }),+ }),+ );++ await main(["inbox", "pull"]);+ const env = parseEnvelope(cap.lines()) as {+ success: { acked: number; failed: Array<{ channel: string; seq: number; code: string; error: string }> };+ };+ expect(env.success.acked).toBe(1);+ expect(env.success.failed).toEqual([{+ channel: "/s#0042/private",+ seq: 4,+ code: "forbidden",+ error: "forbidden",+ }]);+ });+it.each([[0, undefined],[1, "You have 1 marked message. Resolve it before going dark unless blocked."],diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex 1a3a5ce20..4c0fd9d89 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -18,7 +18,7 @@ import { Command, CommanderError } from "commander";import { realpathSync } from "node:fs";import { randomUUID } from "node:crypto";import { pathToFileURL } from "node:url";-import type { ServerApi, Cursor, Message } from "../server/contract.js";+import type { ServerApi, Cursor, Message, AckFailure } from "../server/contract.js";import { parseRef } from "../server/contract.js";import { proxyServerApiFromEnv } from "./proxyServerApi.js";import { daemonResume, daemonRunFromIpc, daemonStart, daemonStartById, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";@@ -655,6 +655,7 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {let acked = 0;let ackError: string | undefined;+ let failed: AckFailure[] | undefined;if (opts.ack !== false && messages.length > 0) {const latest = new Map<string, Cursor>();for (const m of messages) {@@ -663,8 +664,9 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {if (!cur || seqN > cur.seq) latest.set(m.channel, { channel: m.channel, seq: seqN });}try {- await api.ack({ agentId: agent, cursors: [...latest.values()] });- acked = latest.size;+ const result = await api.ack({ agentId: agent, cursors: [...latest.values()] });+ acked = result.applied.length;+ failed = result.failed;} catch (err) {// Do NOT rethrow: the pull already succeeded, and if ack fails on a// single scope (e.g. a stale visibility mismatch) the whole envelope@@ -681,6 +683,7 @@ async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {hasMore,acked,pulledAt,+ ...(failed ? { failed } : {}),...(ackError ? { ackError } : {}),...(markedCount > 0? {diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.tsindex 86c31c7a6..8d9a9a4f7 100644--- a/src/daemon/src/cli/proxyServerApi.test.ts+++ b/src/daemon/src/cli/proxyServerApi.test.ts@@ -450,7 +450,8 @@ describe("createProxyServerApi — inbox trinity pull/snapshot/ack (retargeted treturn jsonBody(JSON.stringify({ ok: true, applied: [], failed: [] }), { status: 200 });});const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });- await api.ack({ agentId: "a1", cursors: [{ channel: "/s/c", seq: 5 }] } as never);+ const result = await api.ack({ agentId: "a1", cursors: [{ channel: "/s/c", seq: 5 }] } as never);+ expect(result).toEqual({ ok: true, applied: [], failed: [] });expect(seen[0].url).toBe("http://proxy.test/api/community/users/me/inbox/ack");expect(seen[0].init?.method).toBe("POST");const body = JSON.parse(String(seen[0].init?.body ?? "{}"));diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex d286ffeb4..4dd0e3221 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -29,6 +29,7 @@ import type {InboxPullResponse,InboxSnapshot,AckRequest,+ AckResponse,SendRequest,SendResponse,CreatePostRequest,@@ -469,15 +470,15 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return parseJsonResponse<MessageMarkListResponse>(res, "markList");}- async function callAck(req: AckRequest): Promise<void> {+ async function callAck(req: AckRequest): Promise<AckResponse> {// RETARGETED off the flat `ack` verb onto POST users/me/inbox/ack (route/disc// 接口树统一, Gener #215 乙) — ack is the ADVANCE operation of the inbox// fetch↔advance trinity (snapshot=peek / pull=fetch / ack=advance, Aigneis// #41). Self-scoped to the voucher's bot — the wire carries only the cursors,// no target-user param (users/me/* family). Body byte-identical to the flat// verb (the endpoint is a MOVE-FLAT, same seq-native/failed[]-batch/no-create- // shape — only the URL moved). The legacy flat route is deleted. Returns void (the daemon- // fire-and-forgets the {ok,applied,failed} body, same as the flat verb).+ // shape — only the URL moved). The legacy flat route is deleted. The body+ // is returned intact so partial success cannot be reported as a full ack.const { agentId: _omit, ...wire } = (req ?? {}) as unknown as Record<string, unknown>;const res = await fetchImpl(`${base}/api/community/users/me/inbox/ack`, {method: "POST",@@ -487,7 +488,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {},body: JSON.stringify(wire),});- return parseJsonResponse<void>(res, "ack");+ return parseJsonResponse<AckResponse>(res, "ack");}async function callFriendRequest(req: { agentId: AgentId; username: string }): Promise<FriendRequestResult> {diff --git a/src/daemon/src/inbox/stateMachine.test.ts b/src/daemon/src/inbox/stateMachine.test.tsindex feb7ce383..ac618878e 100644--- a/src/daemon/src/inbox/stateMachine.test.ts+++ b/src/daemon/src/inbox/stateMachine.test.ts@@ -45,6 +45,22 @@ describe("planAgentInboxSideEffect — freshness guard", () => {expect(r.target).toBe("#general");});+ it("derives the model-seen boundary only from the messages actually returned", () => {+ const r = planAgentInboxSideEffect(+ base({+ pendingMessages: [+ { seq: 4, sender_name: "x", message_id: "m4" },+ { seq: 6, sender_name: "y", message_id: "m6" },+ ],+ modelSeenSeq: 0,+ }),+ );+ expect(r.outcome).toBe("held");+ expect((r.localResponse as any)?.seenUpToSeq).toBe(6);+ const decision = r.effects.find((effect) => effect.type === "record_freshness_decision");+ expect(decision && (decision as any).decision.pendingMaxSeq).toBe(6);+ });+it("forwards when the model has already seen the pending messages", () => {const r = planAgentInboxSideEffect(base({diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 68479971c..faed7d2ad 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -43,6 +43,8 @@ export type {InboxPullRequest,InboxPullResponse,AckRequest,+ AckResponse,+ AckFailure,SendRequest,SendResponse,CreatePostRequest,diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 1bb1a15ad..2e4d2af76 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -310,6 +310,17 @@ export interface AckRequest {cursors: Cursor[];}+export interface AckFailure extends Cursor {+ code: "unresolvable" | "forbidden" | "no_such_seq";+ error: string;+}++export interface AckResponse {+ ok: boolean;+ applied: Cursor[];+ failed: AckFailure[];+}+export interface SendRequest {agentId: AgentId;/** Path ref of the destination channel/DM/thread. */@@ -630,7 +641,7 @@ export interface ServerApi {inboxSnapshot(req: { agentId: AgentId }): Promise<InboxSnapshot>;/** Advance per-channel read waterlines (so drained messages stop reappearing). */- ack(req: AckRequest): Promise<void>;+ ack(req: AckRequest): Promise<AckResponse>;/** Send a message to a channel ref. May be held by the freshness guard. */send(req: SendRequest): Promise<SendResponse>;diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex e422f7ab2..6f7819826 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -7,10 +7,11 @@ import { utcDayKey } from "../utils/day-key";import * as message from "../db/queries/community/message";import * as bot from "../db/queries/community/bot";import * as member from "../db/queries/community/member";-import * as readState from "../db/queries/community/read-state";import * as agentInbox from "../db/queries/community/agent-inbox";import * as mention from "../db/queries/community/mention";import * as botAuditLog from "../db/queries/community/bot-audit-log";+import * as notificationEligibility from "../db/queries/community/notification-eligibility";+import { policyAllows } from "../db/queries/community/notification-setting";import { getUsersByIds } from "../db/queries/user";import type { Database } from "../db/index";@@ -100,9 +101,11 @@ export type SkipReason =| "bot_missing"| "bot_deleted"| "bot_unbound"- | "bot_not_in_scope"+ | "forbidden"| "notice_channel_unresolvable"- | "already_read";+ | "already_read"+ | "muted"+ | "mention_only";export type BuildUnreadWakeResult =| {@@ -149,10 +152,27 @@ export async function buildUnreadWakeCommand(if (botCtx.state !== "ready") return { state: "skip", reason: botCtx.state };const canRead = await member.canBotReadWakeScope(db, input.botUserId, scope);- if (!canRead) return { state: "skip", reason: "bot_not_in_scope" };+ if (!canRead) return { state: "skip", reason: "forbidden" };- const lastReadSeq = await readState.getWakeReadSeq(db, input.botUserId, scope);- if (lastReadSeq >= msg.seq) return { state: "skip", reason: "already_read" };+ // Queue items are hints, not authority. Re-check current policy, persisted+ // attention, and the read cursor in one snapshot so a concurrent setting+ // mutation cannot clear this message between separate gates.+ const policyByUser = await notificationEligibility.resolveNotificationEligibilityForUsers(+ db,+ [input.botUserId],+ input.messageId,+ );+ const policy = policyByUser.get(input.botUserId);+ if (!policy) return { state: "skip", reason: "message_missing" };+ if (!policy.isReadable) return { state: "skip", reason: "forbidden" };+ if (!policy.isUnread) return { state: "skip", reason: "already_read" };+ const currentAllowed = policyAllows(policy.currentLevel, policy.hasAttention);+ if (!currentAllowed) {+ return {+ state: "skip",+ reason: policy.currentLevel === "nothing" ? "muted" : "mention_only",+ };+ }const channel = await agentInbox.resolveUnreadNoticeChannel(db, scope, input.botUserId);if (!channel) return { state: "skip", reason: "notice_channel_unresolvable" };diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 0293571b3..af4cc9304 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -49,6 +49,7 @@ export * as communityReadState from "./queries/community/read-state";export * as communityUserProfile from "./queries/community/user-profile";export * as communitySearch from "./queries/community/search";export * as communityNotificationSetting from "./queries/community/notification-setting";+export * as communityNotificationEligibility from "./queries/community/notification-eligibility";export * as communityServerFolder from "./queries/community/server-folder";export * as communityInbox from "./queries/community/inbox";export * as communityMachine from "./queries/community/machine";diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.tsindex fef095f11..d9c491b31 100644--- a/src/shared/src/db/queries/community/agent-inbox.ts+++ b/src/shared/src/db/queries/community/agent-inbox.ts@@ -9,7 +9,7 @@* self-message-excluding) — a different shape from `message.ts`'s* `createdAt`-ordered, DB-shaped human-UI queries.*/-import { eq, and, inArray, gt, lt, ne, asc, desc, sql } from "drizzle-orm";+import { eq, and, inArray, gt, lt, ne, asc, desc, or, sql } from "drizzle-orm";import {communityMessage,communityChannel,@@ -39,6 +39,7 @@ import { getMessagesByIdsInScope, type MessageScope } from "./message";import { reachIsParticipantSet, type StoredChannelType } from "../../../utils/community-roles";import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";import { withD1Retry } from "../../resilience";+import { hasDirectMentionSql, notificationEligibleSql } from "./notification-eligibility";type RawAgentMessage = {id: string;@@ -612,7 +613,18 @@ export async function listUnreadMessagesForAgent(ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,inArray(communityMessage.channelId, ids),- channelJoinBaselineGuard+ channelJoinBaselineGuard,+ notificationEligibleSql(+ botUserId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ },+ ),)).orderBy(asc(communityMessage.channelId), asc(communityMessage.seq))@@ -715,7 +727,18 @@ export async function hasDeliverableUnreadForAgentScope(eq(communityMessage.channelId, channelId),ne(communityMessage.authorId, botUserId),gt(communityMessage.seq, seen),- channelJoinBaselineGuard+ channelJoinBaselineGuard,+ notificationEligibleSql(+ botUserId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ },+ ),)).limit(1);@@ -739,16 +762,22 @@ export type InboxSnapshotRow = {* Visibility rule mirrors `listUnreadMessagesForAgent`: (1) channel scopes* restricted to `listVisibleChannelIdsForUser(botUserId)`, and (2) scopes of* child threads additionally require a- * `community_channel_member(relation='notify')` row for the bot (post-filter). Because the- * outer `WHERE` is `inArray(channelId, visibleChannelIds)` and scopes lacking- * the bot's `community_channel_member(relation='notify')` row- * thread rows are dropped in the post-filter, `hasMention` (a correlated- * sub-select keyed on the surviving row's `channel_id`) can never inherit a- * mention from an invisible or non-notified thread — do NOT try to- * sub-select mentions independently or the leak reopens on this axis.+ * `community_channel_member(relation='notify')` row for the bot. Readability,+ * notification eligibility, unread cursor, and join baseline are all applied+ * before GROUP BY; aggregate metadata therefore describes exactly the rows a+ * pull can deliver. Latest sender is hydrated from each aggregate's exact+ * `(channelId, latestSeq)` pair in bounded batches.*/-export async function getInboxSnapshotForAgent(db: Database, botUserId: string): Promise<InboxSnapshotRow[]> {- const allowedChannelIds = await listAgentAllowedChannelIds(db, botUserId);+export async function getInboxSnapshotForAgent(+ db: Database,+ botUserId: string,+ opts?: { accessVisibleChannelIds?: string[] },+): Promise<InboxSnapshotRow[]> {+ const allowedChannelIds = await listAgentAllowedChannelIds(+ db,+ botUserId,+ opts?.accessVisibleChannelIds,+ );if (allowedChannelIds.length === 0) return [];// Chunk the `inArray` for D1's 100-param limit. GROUP BY channelId partitions@@ -762,14 +791,7 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):pendingCount: sql<number>`COUNT(*)`,firstPendingSeq: sql<number>`MIN(${communityMessage.seq})`,latestSeq: sql<number>`MAX(${communityMessage.seq})`,- latestSenderId: sql<string>`(SELECT author_id FROM community_message m2- WHERE m2.channel_id = ${communityMessage.channelId}- ORDER BY m2.seq DESC LIMIT 1)`,- mentionCount: sql<number>`(SELECT COUNT(*) FROM community_mention cm- INNER JOIN community_message m3 ON m3.id = cm.message_id- WHERE cm.user_id = ${botUserId} AND cm.kind = 'mention'- AND m3.channel_id = ${communityMessage.channelId}- AND m3.seq > COALESCE(${communityReadState.lastReadSeq}, 0))`,+ mentionCount: sql<number>`SUM(CASE WHEN ${hasDirectMentionSql(botUserId, communityMessage.id)} THEN 1 ELSE 0 END)`,}).from(communityMessage).leftJoin(@@ -800,7 +822,18 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,inArray(communityMessage.channelId, ids),- channelJoinBaselineGuard+ channelJoinBaselineGuard,+ notificationEligibleSql(+ botUserId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ },+ ),)).groupBy(communityMessage.channelId);@@ -811,9 +844,31 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):if (rows.length === 0) return [];- const filtered = rows;+ // Resolve the sender from each scope's exact latest ELIGIBLE seq. Looking up+ // "latest message in channel" would let a newer muted row leak into the+ // snapshot even though the aggregate above correctly excluded it.+ const latestMessageRows = (+ await Promise.all(+ chunk(rows, Math.floor(D1_MAX_IN_PARAMS / 2)).map((pairs) =>+ db+ .select({+ channelId: communityMessage.channelId,+ seq: communityMessage.seq,+ authorId: communityMessage.authorId,+ })+ .from(communityMessage)+ .where(or(...pairs.map((r) => and(+ eq(communityMessage.channelId, r.channelId),+ eq(communityMessage.seq, r.latestSeq),+ ))))+ )+ )+ ).flat();+ const latestSenderIdByChannel = new Map(+ latestMessageRows.map((row) => [row.channelId, row.authorId]),+ );- const senderIds = [...new Set(filtered.map((r) => r.latestSenderId).filter(Boolean))];+ const senderIds = [...new Set(latestMessageRows.map((r) => r.authorId).filter(Boolean))];// Chunk the `inArray` for D1's 100-param limit — one distinct sender per// pending channel, so >100 channels yields >100 ids; no order/limit → concat.const users = senderIds.length@@ -830,8 +885,9 @@ export async function getInboxSnapshotForAgent(db: Database, botUserId: string):: [];const userById = new Map(users.map((u) => [u.id, u]));- return filtered.map((r) => {- const sender = userById.get(r.latestSenderId);+ return rows.map((r) => {+ const senderId = latestSenderIdByChannel.get(r.channelId);+ const sender = senderId ? userById.get(senderId) : undefined;return {channelId: r.channelId,pendingCount: r.pendingCount,@@ -897,13 +953,20 @@ export async function toInboxRows(* dimensions are folded into the SQL WHERE via `listAgentAllowedChannelIds`* so `LIMIT 1` returns the newest allowed row directly — an earlier shape* used a bounded post-filter window that could return `null` when older- * allowed unread existed outside the top-N-by-createdAt slice.+ * allowed unread existed outside the top-N-by-createdAt slice. Notification+ * eligibility is applied before `LIMIT 1` too, so a newer muted row cannot+ * obscure an older eligible unread during daemon reconnect resync.*/export async function getLatestUnreadMessageForAgent(db: Database,- botUserId: string+ botUserId: string,+ opts?: { accessVisibleChannelIds?: string[] },): Promise<{ messageId: string } | null> {- const allowedChannelIds = await listAgentAllowedChannelIds(db, botUserId);+ const allowedChannelIds = await listAgentAllowedChannelIds(+ db,+ botUserId,+ opts?.accessVisibleChannelIds,+ );if (allowedChannelIds.length === 0) return null;// Chunk the `inArray` for D1's 100-param limit; each chunk returns its own@@ -945,7 +1008,18 @@ export async function getLatestUnreadMessageForAgent(ne(communityMessage.authorId, botUserId),sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,inArray(communityMessage.channelId, ids),- channelJoinBaselineGuard+ channelJoinBaselineGuard,+ notificationEligibleSql(+ botUserId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ },+ ),)).orderBy(desc(communityMessage.createdAt))diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex 531efdcc4..3085ae791 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -1,4 +1,5 @@import { eq, and, asc, desc, isNotNull, isNull, max, inArray, count, or, sql } from "drizzle-orm";+import type { SQLWrapper } from "drizzle-orm";import {communityChannel,communityCategory,@@ -30,6 +31,56 @@ const CHANNEL_COLUMNS = {createdAt: communityChannel.createdAt,} as const;+/**+ * SQL form of the canonical channel visibility rule used by+ * `getChannelForMember`/`resolveChannelAccessContext`: DMs require an access+ * row; server channels require current server membership; private children+ * inherit the anchor's creator/access roster. Admins receive no private-content+ * bypass. Keep this expression beside those authoritative read gates so query+ * projections can filter before aggregation without re-deriving visibility.+ */+export function channelReadableSql(+ userId: string | SQLWrapper,+ channel: {+ id: SQLWrapper;+ type: SQLWrapper;+ serverId: SQLWrapper;+ parentChannelId: SQLWrapper;+ },+) {+ return sql<boolean>`(+ case+ when ${channel.type} = 'dm' then exists(+ select 1 from ${communityChannelMember}+ where ${communityChannelMember.channelId} = ${channel.id}+ and ${communityChannelMember.userId} = ${userId}+ and ${communityChannelMember.relation} = 'access'+ )+ else exists(+ select 1 from ${communityServerMember}+ where ${communityServerMember.serverId} = ${channel.serverId}+ and ${communityServerMember.userId} = ${userId}+ ) and exists(+ select 1+ from community_channel as readable_anchor+ left join community_category as readable_category+ on readable_category.id = readable_anchor.category_id+ where readable_anchor.id = coalesce(${channel.parentChannelId}, ${channel.id})+ and (+ coalesce(readable_category.private, 0) = 0+ or readable_anchor.creator_id = ${userId}+ or exists(+ select 1 from ${communityChannelMember}+ where ${communityChannelMember.channelId} = readable_anchor.id+ and ${communityChannelMember.userId} = ${userId}+ and ${communityChannelMember.relation} = 'access'+ )+ )+ )+ end+ )`;+}+export async function createChannel(db: Database,diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex 4199f79a6..fbd187622 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -12,6 +12,7 @@ import { user } from "../../schema";import type { Database } from "../../index";import { listParticipatingThreadIds } from "./thread";import { reachIsParticipantSet } from "../../../utils/community-roles";+import { hasUnreadAttentionSql, notificationEligibleSql } from "./notification-eligibility";export interface UnreadChannelRow {channelId: string;@@ -27,6 +28,10 @@ export interface UnreadChannelRow {parentChannelId: string | null;}+export interface EligibleUnreadChannelRow extends UnreadChannelRow {+ mentionCount: number;+}+export interface UnreadForumOpenerRow {forumChannelId: string;openerMessageId: string;@@ -192,6 +197,97 @@ export async function listUnreadChannels(}));}+/**+ * Web Inbox channel summary over the same attention-eligible unread set used+ * by bot pull/snapshot and wake delivery. Policy filtering happens before the+ * aggregate, so its timestamp and mention count describe the eligible subset+ * rather than raw channel backlog.+ */+export async function listEligibleUnreadChannels(+ db: Database,+ userId: string,+ visibleChannelIds: string[]+): Promise<EligibleUnreadChannelRow[]> {+ if (visibleChannelIds.length === 0) return [];++ const rows = (+ await Promise.all(+ chunk(visibleChannelIds, D1_MAX_IN_PARAMS).map((ids) =>+ db+ .select({+ channelId: communityChannel.id,+ channelName: communityChannel.name,+ serverId: communityChannel.serverId,+ serverName: communityServer.name,+ type: communityChannel.type,+ parentChannelId: communityChannel.parentChannelId,+ lastMessageAt: sql<string>`MAX(${communityMessage.createdAt})`,+ mentionCount: sql<number>`SUM(CASE WHEN ${hasUnreadAttentionSql(userId, communityMessage.id)} THEN 1 ELSE 0 END)`,+ })+ .from(communityMessage)+ .innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .innerJoin(communityServer, eq(communityServer.id, communityChannel.serverId))+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.userId, userId)+ )+ )+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.channelId, communityChannel.id),+ eq(communityReadState.userId, userId)+ )+ )+ .where(+ and(+ inArray(communityChannel.id, ids),+ eq(communityChannel.archived, 0),+ or(+ and(+ isNotNull(communityReadState.id),+ gt(+ communityMessage.seq,+ sql<number>`COALESCE(${communityReadState.lastReadSeq}, 0)`+ )+ ),+ and(+ isNull(communityReadState.id),+ gt(communityMessage.createdAt, communityServerMember.joinedAt)+ )+ ),+ notificationEligibleSql(+ userId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ }+ )+ )+ )+ .groupBy(communityChannel.id)+ )+ )+ ).flat();++ const notifyScopedIds = rows+ .filter((row) => reachIsParticipantSet(row.type))+ .map((row) => row.channelId);+ const participatingIds = notifyScopedIds.length > 0+ ? new Set(await listParticipatingThreadIds(db, notifyScopedIds, userId))+ : new Set<string>();++ return rows.filter(+ (row) => !reachIsParticipantSet(row.type) || participatingIds.has(row.channelId)+ );+}+/*** Project every unread forum opener under an already-authorized parent scope.*@@ -266,6 +362,17 @@ export async function listUnreadForumOpeners(isNull(communityReadState.id),gt(communityMessage.createdAt, communityServerMember.joinedAt))+ ),+ notificationEligibleSql(+ userId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ })))@@ -484,3 +591,85 @@ export async function listUnreadDms(lastMessageAt: r.lastMessageAt!,}));}++/** DM counterpart of `listEligibleUnreadChannels`. */+export async function listEligibleUnreadDms(+ db: Database,+ userId: string+): Promise<UnreadDmRow[]> {+ const selfRows = await db+ .select({ channelId: communityChannelMember.channelId })+ .from(communityChannelMember)+ .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId))+ .where(+ and(+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "access"),+ eq(communityChannel.type, "dm")+ )+ );+ const dmChannelIds = selfRows.map((row) => row.channelId);+ if (dmChannelIds.length === 0) return [];++ const rows = (+ await Promise.all(+ chunk(dmChannelIds, D1_MAX_IN_PARAMS).map((ids) =>+ db+ .select({+ channelId: communityChannel.id,+ otherUserId: user.id,+ otherUserName: user.name,+ otherUserImage: user.image,+ lastMessageAt: sql<string>`MAX(${communityMessage.createdAt})`,+ })+ .from(communityMessage)+ .innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .innerJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityChannel.id),+ eq(communityChannelMember.relation, "access"),+ ne(communityChannelMember.userId, userId)+ )+ )+ .innerJoin(user, eq(user.id, communityChannelMember.userId))+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.channelId, communityChannel.id),+ eq(communityReadState.userId, userId)+ )+ )+ .where(+ and(+ inArray(communityChannel.id, ids),+ isNull(user.deletedAt),+ gt(+ communityMessage.seq,+ sql<number>`COALESCE(${communityReadState.lastReadSeq}, 0)`+ ),+ notificationEligibleSql(+ userId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ {+ id: communityMessage.id,+ }+ )+ )+ )+ .groupBy(communityChannel.id, user.id)+ )+ )+ ).flat();++ const seen = new Set<string>();+ return rows.filter((row) => {+ if (seen.has(row.channelId)) return false;+ seen.add(row.channelId);+ return true;+ });+}diff --git a/src/shared/src/db/queries/community/notification-eligibility.ts b/src/shared/src/db/queries/community/notification-eligibility.tsnew file mode 100644index 000000000..29fc904fb--- /dev/null+++ b/src/shared/src/db/queries/community/notification-eligibility.ts@@ -0,0 +1,160 @@+import { and, eq, inArray, sql } from "drizzle-orm";+import type { SQLWrapper } from "drizzle-orm";+import {+ communityMention,+ communityMessage,+ communityChannel,+ communityNotificationSetting,+ communityReadState,+} from "../../community-schema";+import { user } from "../../schema";+import type { Database } from "../../index";+import type { NotificationLevelValue } from "../../../constants/community";+import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";+import { channelReadableSql } from "./channel";++type SqlValue = string | number | SQLWrapper;++export type NotificationChannelSql = {+ id: SQLWrapper;+ serverId: SQLWrapper;+ parentChannelId: SQLWrapper;+};++export type NotificationMessageSql = {+ id: SQLWrapper;+};++export function currentEffectiveLevelSql(+ userId: SqlValue,+ channel: NotificationChannelSql,+) {+ return sql<NotificationLevelValue>`coalesce(+ (select ${communityNotificationSetting.level}+ from ${communityNotificationSetting}+ where ${communityNotificationSetting.userId} = ${userId}+ and ${communityNotificationSetting.channelId} = ${channel.id}+ limit 1),+ (select ${communityNotificationSetting.level}+ from ${communityNotificationSetting}+ where ${communityNotificationSetting.userId} = ${userId}+ and ${communityNotificationSetting.channelId} = ${channel.parentChannelId}+ limit 1),+ (select ${communityNotificationSetting.level}+ from ${communityNotificationSetting}+ where ${communityNotificationSetting.userId} = ${userId}+ and ${communityNotificationSetting.serverId} = ${channel.serverId}+ and ${communityNotificationSetting.channelId} is null+ limit 1),+ 'all'+ )`;+}++export function hasAttentionSql(userId: SqlValue, messageId: SqlValue) {+ return sql<boolean>`exists(+ select 1 from ${communityMention}+ where ${communityMention.userId} = ${userId}+ and ${communityMention.messageId} = ${messageId}+ )`;+}++/** Snapshot's historical `mention` flag excludes reply-only attention. */+export function hasDirectMentionSql(userId: SqlValue, messageId: SqlValue) {+ return sql<boolean>`exists(+ select 1 from ${communityMention}+ where ${communityMention.userId} = ${userId}+ and ${communityMention.messageId} = ${messageId}+ and ${communityMention.kind} = 'mention'+ )`;+}++/** Web mention badges count only attention facts not dismissed in that tab. */+export function hasUnreadAttentionSql(userId: SqlValue, messageId: SqlValue) {+ return sql<boolean>`exists(+ select 1 from ${communityMention}+ where ${communityMention.userId} = ${userId}+ and ${communityMention.messageId} = ${messageId}+ and ${communityMention.read} = 0+ )`;+}++export function policyAllowsSql(level: SQLWrapper, hasAttention: SQLWrapper) {+ return sql<boolean>`case+ when ${level} = 'all' then 1+ when ${level} = 'mentions' then ${hasAttention}+ else 0+ end`;+}++/** Current-policy attention gate shared by every unread and wake surface. */+export function notificationEligibleSql(+ userId: SqlValue,+ channel: NotificationChannelSql,+ message: NotificationMessageSql,+) {+ const attention = hasAttentionSql(userId, message.id);+ return policyAllowsSql(currentEffectiveLevelSql(userId, channel), attention);+}++export type NotificationEligibilityState = {+ currentLevel: NotificationLevelValue;+ hasAttention: boolean;+ isUnread: boolean;+ isReadable: boolean;+};++/** Resolve current policy, attention, and cursor state in one batched snapshot. */+export async function resolveNotificationEligibilityForUsers(+ db: Database,+ userIds: string[],+ messageId: string,+): Promise<Map<string, NotificationEligibilityState>> {+ const result = new Map<string, NotificationEligibilityState>();+ if (userIds.length === 0) return result;++ const channelSql = {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ };+ const runChunk = (ids: string[]) => {+ const attention = hasAttentionSql(user.id, communityMessage.id);+ return db+ .select({+ userId: user.id,+ currentLevel: currentEffectiveLevelSql(user.id, channelSql),+ hasAttention: attention,+ isUnread: sql<boolean>`${communityMessage.seq} > coalesce(${communityReadState.lastReadSeq}, 0)`,+ isReadable: channelReadableSql(user.id, {+ id: communityChannel.id,+ type: communityChannel.type,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ }),+ })+ .from(user)+ .innerJoin(communityMessage, eq(communityMessage.id, messageId))+ .innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.userId, user.id),+ eq(communityReadState.channelId, communityMessage.channelId),+ ),+ )+ .where(inArray(user.id, ids));+ };++ const rows = (+ await Promise.all(chunk(userIds, D1_MAX_IN_PARAMS - 1).map(runChunk))+ ).flat();+ for (const row of rows) {+ result.set(row.userId, {+ currentLevel: row.currentLevel,+ hasAttention: Boolean(row.hasAttention),+ isUnread: Boolean(row.isUnread),+ isReadable: Boolean(row.isReadable),+ });+ }+ return result;+}diff --git a/src/shared/src/db/queries/community/notification-setting.ts b/src/shared/src/db/queries/community/notification-setting.tsindex 333282e15..f950c5c76 100644--- a/src/shared/src/db/queries/community/notification-setting.ts+++ b/src/shared/src/db/queries/community/notification-setting.ts@@ -1,7 +1,30 @@-import { eq, and, or, isNull, isNotNull, inArray } from "drizzle-orm";-import { communityNotificationSetting, communityChannel } from "../../community-schema";+import {+ eq,+ and,+ or,+ isNull,+ isNotNull,+ inArray,+ gt,+ notExists,+ sql,+} from "drizzle-orm";+import type { SQLWrapper } from "drizzle-orm";+import { alias } from "drizzle-orm/sqlite-core";+import { nanoid } from "nanoid";+import {+ communityNotificationSetting,+ communityChannel,+ communityCategory,+ communityChannelMember,+ communityMessage,+ communityReadState,+ communityServerMember,+} from "../../community-schema";import type { Database } from "../../index";import type { NotificationLevelValue } from "../../../constants/community";+import { currentEffectiveLevelSql } from "./notification-eligibility";+import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";type EffectiveLevelChannel = {id: string;@@ -15,6 +38,14 @@ type EffectiveLevelSetting = {level: string;};+export function policyAllows(+ level: NotificationLevelValue,+ hasAttention: boolean,+): boolean {+ if (level === "nothing") return false;+ return level === "all" || hasAttention;+}+// 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@@ -65,26 +96,34 @@ async function loadScopedSettings(? [channel.id, channel.parentChannelId]: [channel.id];- return db- .select({- userId: communityNotificationSetting.userId,- channelId: communityNotificationSetting.channelId,- serverId: communityNotificationSetting.serverId,- level: communityNotificationSetting.level,- })- .from(communityNotificationSetting)- .where(- and(- inArray(communityNotificationSetting.userId, userIds),- or(- inArray(communityNotificationSetting.channelId, channelIds),+ // Reserve one bind for serverId plus one per own/parent channel id. The+ // remainder is the safe recipient batch under D1's 100-bind ceiling.+ const usersPerQuery = D1_MAX_IN_PARAMS - channelIds.length - 1;+ const rows = await Promise.all(+ chunk(userIds, usersPerQuery).map((ids) =>+ db+ .select({+ userId: communityNotificationSetting.userId,+ channelId: communityNotificationSetting.channelId,+ serverId: communityNotificationSetting.serverId,+ level: communityNotificationSetting.level,+ })+ .from(communityNotificationSetting)+ .where(and(- eq(communityNotificationSetting.serverId, channel.serverId),- isNull(communityNotificationSetting.channelId)+ inArray(communityNotificationSetting.userId, ids),+ or(+ inArray(communityNotificationSetting.channelId, channelIds),+ and(+ eq(communityNotificationSetting.serverId, channel.serverId),+ isNull(communityNotificationSetting.channelId)+ )+ )))- )- );+ )+ );+ return rows.flat();}export async function resolveEffectiveLevel(@@ -98,8 +137,8 @@ export async function resolveEffectiveLevel(return computeEffectiveLevel(settings, channel);}-// Batch resolver: 2 queries total (one channel load + one scoped settings-// fetch) regardless of recipient count.+// Batch resolver: one channel load plus one bounded settings query per D1-safe+// recipient chunk. This is O(chunks), never N+1.export async function resolveEffectiveLevelForUsers(db: Database,userIds: string[],@@ -129,83 +168,357 @@ export async function getSettings(db: Database, userId: string) {.where(eq(communityNotificationSetting.userId, userId));}-export async function setServerLevel(+export async function getServerSetting(db: Database,- data: { userId: string; serverId: string; level: string }+ userId: string,+ serverId: string,) {- const existing = await db+ const rows = await db.select().from(communityNotificationSetting).where(and(- eq(communityNotificationSetting.userId, data.userId),- eq(communityNotificationSetting.serverId, data.serverId),- isNotNull(communityNotificationSetting.serverId)+ eq(communityNotificationSetting.userId, userId),+ eq(communityNotificationSetting.serverId, serverId),+ isNull(communityNotificationSetting.channelId),+ ),+ )+ .limit(1);+ return rows[0] ?? null;+}++export async function getChannelSetting(+ db: Database,+ userId: string,+ channelId: string,+) {+ const rows = await db+ .select()+ .from(communityNotificationSetting)+ .where(+ and(+ eq(communityNotificationSetting.userId, userId),+ eq(communityNotificationSetting.channelId, channelId),+ isNull(communityNotificationSetting.serverId),+ ),+ )+ .limit(1);+ return rows[0] ?? null;+}++type MutationScope =+ | { kind: "server"; id: string }+ | { kind: "channel"; id: string };++type SettingChange =+ | { kind: "set-server"; id: string; level: string }+ | { kind: "set-channel"; id: string; level: string }+ | { kind: "remove-channel"; id: string };++function affectedChannelWhere(scope: MutationScope) {+ return scope.kind === "server"+ ? eq(communityChannel.serverId, scope.id)+ : or(+ eq(communityChannel.id, scope.id),+ eq(communityChannel.parentChannelId, scope.id),+ )!;+}++/** The target identity must be able to read every channel whose cursor moves. */+function userCanAccessChannelSql(userId: string) {+ const anchorId = sql`coalesce(${communityChannel.parentChannelId}, ${communityChannel.id})`;+ const anchorPrivate = sql<number>`coalesce((+ select ${communityCategory.private}+ from ${communityChannel} notification_anchor+ left join ${communityCategory}+ on ${communityCategory.id} = notification_anchor.category_id+ where notification_anchor.id = ${anchorId}+ limit 1+ ), 0)`;+ const anchorCreator = sql`(+ select notification_anchor.creator_id+ from ${communityChannel} notification_anchor+ where notification_anchor.id = ${anchorId}+ limit 1+ )`;+ const hasChannelAccess = sql<boolean>`exists(+ select 1 from ${communityChannelMember}+ where ${communityChannelMember.channelId} = ${anchorId}+ and ${communityChannelMember.userId} = ${userId}+ and ${communityChannelMember.relation} = 'access'+ )`;+ const hasServerMembership = sql<boolean>`exists(+ select 1 from ${communityServerMember}+ where ${communityServerMember.serverId} = ${communityChannel.serverId}+ and ${communityServerMember.userId} = ${userId}+ )`;++ return sql<boolean>`case+ when ${communityChannel.serverId} is null then ${hasChannelAccess}+ else ${hasServerMembership} and (+ ${anchorPrivate} = 0+ or ${anchorCreator} = ${userId}+ or ${hasChannelAccess}+ )+ end`;+}++function settingLevelForChannelSql(+ userId: string,+ channelId: SQLWrapper,+ extraWhere?: ReturnType<typeof sql>,+) {+ return sql`(+ select ${communityNotificationSetting.level}+ from ${communityNotificationSetting}+ where ${communityNotificationSetting.userId} = ${userId}+ and ${communityNotificationSetting.channelId} = ${channelId}+ ${extraWhere ? sql`and ${extraWhere}` : sql``}+ limit 1+ )`;+}++function serverLevelSql(userId: string) {+ return sql`(+ select ${communityNotificationSetting.level}+ from ${communityNotificationSetting}+ where ${communityNotificationSetting.userId} = ${userId}+ and ${communityNotificationSetting.serverId} = ${communityChannel.serverId}+ and ${communityNotificationSetting.channelId} is null+ limit 1+ )`;+}++/** Effective level each affected channel will have after the requested write. */+function nextEffectiveLevelSql(userId: string, change: SettingChange) {+ if (change.kind === "set-server") {+ return sql<NotificationLevelValue>`coalesce(+ ${settingLevelForChannelSql(userId, communityChannel.id)},+ ${settingLevelForChannelSql(userId, communityChannel.parentChannelId)},+ ${change.level}+ )`;+ }++ if (change.kind === "set-channel") {+ return sql<NotificationLevelValue>`case+ when ${communityChannel.id} = ${change.id} then ${change.level}+ else coalesce(+ ${settingLevelForChannelSql(userId, communityChannel.id)},+ ${change.level})+ end`;+ }++ // Remove the target override from the resolver without actually deleting it+ // yet. For the target, its direct parent remains eligible inheritance; for+ // a child, parentChannelId === target and must be excluded as the row being+ // removed. A child's own override still wins and therefore yields no change.+ return sql<NotificationLevelValue>`coalesce(+ ${settingLevelForChannelSql(+ userId,+ communityChannel.id,+ sql`${communityChannel.id} <> ${change.id}`,+ )},+ ${settingLevelForChannelSql(+ userId,+ communityChannel.parentChannelId,+ sql`${communityChannel.parentChannelId} <> ${change.id}`,+ )},+ ${serverLevelSql(userId)},+ 'all'+ )`;+}++/**+ * Build the cursor half of a notification-setting mutation.+ *+ * The product contract treats a setting change as handling every old unread+ * in the affected scope. The statement selects each channel's latest real+ * message and advances all three aligned read-state fields together. Empty+ * channels produce no row, while the conflict guard prevents a concurrent or+ * already-newer cursor from regressing.+ */+function buildClearAffectedUnreadStatement(+ db: Database,+ userId: string,+ change: SettingChange,+) {+ const scope: MutationScope = change.kind === "set-server"+ ? { kind: "server", id: change.id }+ : { kind: "channel", id: change.id };+ const latestMessage = alias(communityMessage, "notification_latest_message");+ const newerMessage = alias(communityMessage, "notification_newer_message");+ const channelSql = {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ };+ const currentLevel = currentEffectiveLevelSql(userId, channelSql);+ const nextLevel = nextEffectiveLevelSql(userId, change);+ const selected = db+ .select({+ id: sql<string>`lower(hex(randomblob(16)))`.as("id"),+ userId: sql<string>`${userId}`.as("user_id"),+ channelId: communityChannel.id,+ lastReadAt: latestMessage.createdAt,+ lastReadMessageId: latestMessage.id,+ lastReadSeq: latestMessage.seq,+ })+ .from(communityChannel)+ .innerJoin(+ latestMessage,+ eq(latestMessage.channelId, communityChannel.id),+ )+ .where(+ and(+ affectedChannelWhere(scope),+ userCanAccessChannelSql(userId),+ sql`${currentLevel} <> ${nextLevel}`,+ notExists(+ db+ .select({ one: sql<number>`1` })+ .from(newerMessage)+ .where(+ and(+ eq(newerMessage.channelId, latestMessage.channelId),+ gt(newerMessage.seq, latestMessage.seq),+ ),+ ),+ ),+ ),);- if (existing.length > 0) {- const [updated] = await db- .update(communityNotificationSetting)- .set({ level: data.level })- .where(eq(communityNotificationSetting.id, existing[0]!.id))- .returning();- return updated!;- }+ return db+ .insert(communityReadState)+ .select(selected)+ .onConflictDoUpdate({+ target: [communityReadState.userId, communityReadState.channelId],+ set: {+ lastReadAt: sql`excluded.last_read_at`,+ lastReadMessageId: sql`excluded.last_read_message_id`,+ lastReadSeq: sql`excluded.last_read_seq`,+ },+ setWhere: sql`${communityReadState.lastReadSeq} < excluded.last_read_seq`,+ });+}- const [inserted] = await db+async function applySettingMutation(+ db: Database,+ userId: string,+ change: SettingChange,+ mutation: unknown,+) {+ // Clear first while the current projection still represents the "before"+ // level used by the changed-effective predicate. D1 batch is atomic, so no+ // observer can see the cursor advance without the setting write (or vice+ // versa), and any failure rolls both statements back.+ const clearUnread = buildClearAffectedUnreadStatement(db, userId, change);+ await db.batch([clearUnread, mutation] as any);+}++export async function setServerLevel(+ db: Database,+ data: { userId: string; serverId: string; level: string }+) {+ const mutation = db.insert(communityNotificationSetting).values({+ id: nanoid(),userId: data.userId,serverId: data.serverId,channelId: null,level: data.level,})- .returning();- return inserted!;-}+ .onConflictDoUpdate({+ target: [+ communityNotificationSetting.userId,+ communityNotificationSetting.serverId,+ ],+ targetWhere: isNotNull(communityNotificationSetting.serverId),+ set: { level: data.level },+ });-export async function setChannelLevel(- db: Database,- data: { userId: string; channelId: string; level: string }-) {- const existing = await db+ await applySettingMutation(+ db,+ data.userId,+ { kind: "set-server", id: data.serverId, level: data.level },+ mutation,+ );++ const rows = await db.select().from(communityNotificationSetting).where(and(eq(communityNotificationSetting.userId, data.userId),- eq(communityNotificationSetting.channelId, data.channelId),- isNotNull(communityNotificationSetting.channelId)- )- );-- if (existing.length > 0) {- const [updated] = await db- .update(communityNotificationSetting)- .set({ level: data.level })- .where(eq(communityNotificationSetting.id, existing[0]!.id))- .returning();- return updated!;- }+ eq(communityNotificationSetting.serverId, data.serverId),+ isNull(communityNotificationSetting.channelId),+ ),+ )+ .limit(1);+ return rows[0]!;+}- const [inserted] = await db+export async function setChannelLevel(+ db: Database,+ data: { userId: string; channelId: string; level: string }+) {+ const mutation = db.insert(communityNotificationSetting).values({+ id: nanoid(),userId: data.userId,serverId: null,channelId: data.channelId,level: data.level,})- .returning();- return inserted!;+ .onConflictDoUpdate({+ target: [+ communityNotificationSetting.userId,+ communityNotificationSetting.channelId,+ ],+ targetWhere: isNotNull(communityNotificationSetting.channelId),+ set: { level: data.level },+ });++ await applySettingMutation(+ db,+ data.userId,+ { kind: "set-channel", id: data.channelId, level: data.level },+ mutation,+ );++ const rows = await db+ .select()+ .from(communityNotificationSetting)+ .where(+ and(+ eq(communityNotificationSetting.userId, data.userId),+ eq(communityNotificationSetting.channelId, data.channelId),+ isNull(communityNotificationSetting.serverId),+ ),+ )+ .limit(1);+ return rows[0]!;}export async function removeChannelOverride(db: Database,data: { userId: string; channelId: string }) {- const [deleted] = await db+ const existingRows = await db+ .select()+ .from(communityNotificationSetting)+ .where(+ and(+ eq(communityNotificationSetting.userId, data.userId),+ eq(communityNotificationSetting.channelId, data.channelId),+ isNotNull(communityNotificationSetting.channelId),+ ),+ )+ .limit(1);++ const mutation = db.delete(communityNotificationSetting).where(and(@@ -213,7 +526,13 @@ export async function removeChannelOverride(eq(communityNotificationSetting.channelId, data.channelId),isNotNull(communityNotificationSetting.channelId))- )- .returning();- return deleted ?? null;+ );++ await applySettingMutation(+ db,+ data.userId,+ { kind: "remove-channel", id: data.channelId },+ mutation,+ );+ return existingRows[0] ?? null;}diff --git a/src/shared/src/db/queries/community/read-state.ts b/src/shared/src/db/queries/community/read-state.tsindex cfb97c6e1..19cdb8ecd 100644--- a/src/shared/src/db/queries/community/read-state.ts+++ b/src/shared/src/db/queries/community/read-state.ts@@ -273,9 +273,11 @@ export async function markAllDmsRead(}/**- * The agent `ack` route's cursor-advance — the ONLY writer of `lastReadSeq`- * outside `createMessage`'s author-watermark upsert (design §4). `Cursor =- * { channel, seq }` carries no message id, so this first resolves+ * The agent `ack` route's cursor-advance — one of two intentional writers of+ * `lastReadSeq` outside `createMessage`'s author-watermark upsert (design §4),+ * alongside notification-policy clears. Both paths advance the complete+ * read-state triple together. `Cursor = { channel, seq }` carries no message+ * id, so this first resolves* `(target, seq) → { id, createdAt }` via `getMessageByChannelAndSeq`, then* upserts all three of `lastReadSeq`/`lastReadMessageId`/`lastReadAt`* together — NEVER bump `lastReadSeq` alone, or the table's documenteddiff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.tsindex dadaa4b0b..a0230f98e 100644--- a/src/shared/src/db/queries/community/server.ts+++ b/src/shared/src/db/queries/community/server.ts@@ -7,6 +7,7 @@ import {communityServerMember,communityMention,communityMessage,+ communityReadState,} from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -15,6 +16,8 @@ import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";import { MENTION_KIND } from "../../../constants/community";import { withUniqueDiscriminator } from "../user";import { parseNameAndTag } from "../../../lib/discriminator";+import { notificationEligibleSql } from "./notification-eligibility";+import { channelReadableSql } from "./channel";export async function createServer(db: Database,@@ -188,11 +191,34 @@ export async function listUserServers(db: Database, userId: string) {.from(communityMention).innerJoin(communityMessage, eq(communityMessage.id, communityMention.messageId)).innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.userId, userId),+ eq(communityReadState.channelId, communityChannel.id)+ )+ ).where(and(eq(communityMention.userId, userId),eq(communityMention.read, 0),- eq(communityMention.kind, MENTION_KIND.MENTION)+ eq(communityMention.kind, MENTION_KIND.MENTION),+ sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,+ channelReadableSql(userId, {+ id: communityChannel.id,+ type: communityChannel.type,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ }),+ notificationEligibleSql(+ userId,+ {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ },+ { id: communityMessage.id }+ ))).groupBy(communityChannel.serverId)diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 4f6da37bb..09f0786b1 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -421,6 +421,8 @@ export type {InboxPullRequest as CommunityCliInboxPullRequest,InboxPullResponse as CommunityCliInboxPullResponse,AckRequest as CommunityCliAckRequest,+ AckResponse as CommunityCliAckResponse,+ AckFailure as CommunityCliAckFailure,SendRequest as CommunityCliSendRequest,SendResponse as CommunityCliSendResponse,CommunityAgentReactAddResponse,diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.tsindex b75a80c41..3b6ab1883 100644--- a/src/shared/test/community/wake-dispatch-build.test.ts+++ b/src/shared/test/community/wake-dispatch-build.test.ts@@ -32,16 +32,17 @@ vi.mock("../../src/db/queries/community/member", () => ({canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),}));-const mockGetWakeReadSeq = vi.fn();-vi.mock("../../src/db/queries/community/read-state", () => ({- getWakeReadSeq: (...a: unknown[]) => mockGetWakeReadSeq(...a),-}));-const mockResolveUnreadNoticeChannel = vi.fn();vi.mock("../../src/db/queries/community/agent-inbox", () => ({resolveUnreadNoticeChannel: (...a: unknown[]) => mockResolveUnreadNoticeChannel(...a),}));+const mockResolveNotificationEligibilityForUsers = vi.fn();+vi.mock("../../src/db/queries/community/notification-eligibility", () => ({+ resolveNotificationEligibilityForUsers: (...a: unknown[]) =>+ mockResolveNotificationEligibilityForUsers(...a),+}));+import { buildUnreadWakeCommand } from "../../src/community/wake-dispatch";import type { Database } from "../../src/db/index";@@ -78,16 +79,21 @@ function seedHappyPath(overrides?: {message?: Partial<typeof MESSAGE_CHANNEL>;bot?: Partial<typeof BOT_READY>;canRead?: boolean;- readSeq?: number;+ isUnread?: boolean;channel?: string | null;}) {mockGetWakeMessageScopeById.mockResolvedValue({ ...MESSAGE_CHANNEL, ...overrides?.message });mockGetBotWakeContext.mockResolvedValue({ ...BOT_READY, ...overrides?.bot });mockCanBotReadWakeScope.mockResolvedValue(overrides?.canRead ?? true);- mockGetWakeReadSeq.mockResolvedValue(overrides?.readSeq ?? 0);mockResolveUnreadNoticeChannel.mockResolvedValue(overrides?.channel === undefined ? "/srv_1/general" : overrides.channel,);+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_1", {+ currentLevel: "all",+ hasAttention: false,+ isUnread: overrides?.isUnread ?? true,+ isReadable: true,+ }]]));// Audit path best-effort defaults — happy replies so the wake still fires.mockGetUsersByIds.mockResolvedValue([{ id: "u_human", name: "gustavo", discriminator: "0042" }]);mockHasMentionForMessage.mockResolvedValue(false);@@ -121,7 +127,11 @@ describe("buildUnreadWakeCommand", () => {expect(mockGetWakeMessageScopeById).toHaveBeenCalledWith(fakeDb, "msg_1");expect(mockGetBotWakeContext).toHaveBeenCalledWith(fakeDb, "bot_1");expect(mockCanBotReadWakeScope).toHaveBeenCalledWith(fakeDb, "bot_1", { channelId: "ch_1" });- expect(mockGetWakeReadSeq).toHaveBeenCalledWith(fakeDb, "bot_1", { channelId: "ch_1" });+ expect(mockResolveNotificationEligibilityForUsers).toHaveBeenCalledWith(+ fakeDb,+ ["bot_1"],+ "msg_1",+ );expect(mockResolveUnreadNoticeChannel).toHaveBeenCalledWith(fakeDb, { channelId: "ch_1" }, "bot_1");});@@ -227,17 +237,17 @@ describe("buildUnreadWakeCommand", () => {expect(result).toEqual({ state: "skip", reason: "bot_unbound" });});- it("skip: bot_not_in_scope when the bot lost membership/participant access before the queue drained", async () => {+ it("skip: forbidden when the bot lost membership/participant access before the queue drained", async () => {seedHappyPath({ canRead: false });const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });- expect(result).toEqual({ state: "skip", reason: "bot_not_in_scope" });- expect(mockGetWakeReadSeq).not.toHaveBeenCalled();+ expect(result).toEqual({ state: "skip", reason: "forbidden" });+ expect(mockResolveNotificationEligibilityForUsers).not.toHaveBeenCalled();});it("skip: already_read when lastReadSeq >= message.seq (an earlier inboxPull already caught the bot up)", async () => {- seedHappyPath({ readSeq: 7 });+ seedHappyPath({ isUnread: false });const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });@@ -245,14 +255,43 @@ describe("buildUnreadWakeCommand", () => {expect(mockResolveUnreadNoticeChannel).not.toHaveBeenCalled();});- it("skip: already_read also fires when lastReadSeq is strictly greater (batched catch-up past this seq)", async () => {- seedHappyPath({ readSeq: 9 });+ it("skip: already_read also covers a cursor advanced past this message", async () => {+ seedHappyPath({ isUnread: false });const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });expect(result).toEqual({ state: "skip", reason: "already_read" });});+ it("skip: muted when current policy changes to nothing while a queue item waits", async () => {+ seedHappyPath();+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_1", {+ currentLevel: "nothing",+ hasAttention: true,+ isUnread: true,+ isReadable: true,+ }]]));++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "muted" });+ expect(mockResolveUnreadNoticeChannel).not.toHaveBeenCalled();+ });++ it("skip: mention_only for a plain message under the current mentions policy", async () => {+ seedHappyPath();+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_1", {+ currentLevel: "mentions",+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ }]]));++ const result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });++ expect(result).toEqual({ state: "skip", reason: "mention_only" });+ });+it("skip: notice_channel_unresolvable when the scope can't be strictly resolved to a ChannelRef (never falls back to /unknown/...)", async () => {seedHappyPath({ channel: null });@@ -320,7 +359,7 @@ describe("buildUnreadWakeCommand", () => {expect(args.payload.reason).toBe("mention");});- it("NEVER writes an audit row when the wake was skipped (bot_not_in_scope)", async () => {+ it("NEVER writes an audit row when the wake was skipped (forbidden)", async () => {seedHappyPath({ canRead: false });await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });diff --git a/src/shared/test/community/wake-dispatch-one.test.ts b/src/shared/test/community/wake-dispatch-one.test.tsindex 2a33883b2..ad2a2a3d6 100644--- a/src/shared/test/community/wake-dispatch-one.test.ts+++ b/src/shared/test/community/wake-dispatch-one.test.ts@@ -30,9 +30,10 @@ vi.mock("../../src/db/queries/community/member", () => ({canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),}));-const mockGetWakeReadSeq = vi.fn();-vi.mock("../../src/db/queries/community/read-state", () => ({- getWakeReadSeq: (...a: unknown[]) => mockGetWakeReadSeq(...a),+const mockResolveNotificationEligibilityForUsers = vi.fn();+vi.mock("../../src/db/queries/community/notification-eligibility", () => ({+ resolveNotificationEligibilityForUsers: (...a: unknown[]) =>+ mockResolveNotificationEligibilityForUsers(...a),}));const mockResolveUnreadNoticeChannel = vi.fn();@@ -67,7 +68,9 @@ function seedReady() {mockGetWakeMessageScopeById.mockResolvedValue(MESSAGE_CHANNEL);mockGetBotWakeContext.mockResolvedValue(BOT_READY);mockCanBotReadWakeScope.mockResolvedValue(true);- mockGetWakeReadSeq.mockResolvedValue(0);+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([+ ["bot_1", { currentLevel: "all", hasAttention: false, isUnread: true, isReadable: true }],+ ]));mockResolveUnreadNoticeChannel.mockResolvedValue("/srv_1/general");mockGetUsersByIds.mockResolvedValue([{ id: "u_human", name: "gustavo", discriminator: "0042" }]);mockHasMentionForMessage.mockResolvedValue(false);diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.tsindex b1d125dfd..e2b8d973e 100644--- a/src/shared/test/queries/community-agent-inbox.test.ts+++ b/src/shared/test/queries/community-agent-inbox.test.ts@@ -742,7 +742,10 @@ describe("getInboxSnapshotForAgent", () => {const channelTypes = channels.map(({ id, type }) => ({ id, type }));const aggregated = Array.from({ length: 101 }, (_, i) => ({channelId: `ch_${i}`, pendingCount: i + 1, firstPendingSeq: i + 2,- latestSeq: i + 3, latestSenderId: `sender_${i}`, mentionCount: i % 2,+ latestSeq: i + 3, mentionCount: i % 2,+ }));+ const latestMessages = Array.from({ length: 101 }, (_, i) => ({+ channelId: `ch_${i}`, seq: i + 3, authorId: `sender_${i}`,}));const firstSenderChunk = Array.from({ length: 100 }, (_, i) => ({id: `sender_${i}`, name: `Sender${i}`, discriminator: String(i).padStart(4, "0"),@@ -750,6 +753,7 @@ describe("getInboxSnapshotForAgent", () => {const db = createSequentialDb([[{ serverId: "srv_1" }], channels, [], [], [], channelTypes.slice(0, 100), channelTypes.slice(100),aggregated.slice(0, 100), aggregated.slice(100),+ latestMessages.slice(0, 50), latestMessages.slice(50, 100), latestMessages.slice(100),firstSenderChunk, [], // sender_100 is absent in the second hydration chunk]);const out = await agentInbox.getInboxSnapshotForAgent(db, "bot_1");@@ -782,7 +786,6 @@ describe("getInboxSnapshotForAgent", () => {pendingCount: 3,firstPendingSeq: 5,latestSeq: 7,- latestSenderId: "u_1",mentionCount: 1,},{@@ -790,10 +793,13 @@ describe("getInboxSnapshotForAgent", () => {pendingCount: 1,firstPendingSeq: 9,latestSeq: 9,- latestSenderId: "u_2",mentionCount: 0,},],+ [+ { channelId: "ch_1", seq: 7, authorId: "u_1" },+ { channelId: "ch_2", seq: 9, authorId: "u_2" },+ ],[{ id: "u_1", name: "Alice", discriminator: "1234" },],diff --git a/src/shared/test/queries/community-notification-cursor-clear.test.ts b/src/shared/test/queries/community-notification-cursor-clear.test.tsnew file mode 100644index 000000000..4c8d25871--- /dev/null+++ b/src/shared/test/queries/community-notification-cursor-clear.test.ts@@ -0,0 +1,493 @@+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { eq, sql } from "drizzle-orm";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { Database } from "../../src/db";+import {+ policyAllows,+ removeChannelOverride,+ setChannelLevel,+ setServerLevel,+} from "../../src/db/queries/community/notification-setting";+import {+ notificationEligibleSql,+ resolveNotificationEligibilityForUsers,+} from "../../src/db/queries/community/notification-eligibility";+import { communityChannel } from "../../src/db/community-schema";+import { listUserServers } from "../../src/db/queries/community/server";+import {+ getInboxSnapshotForAgent,+ getLatestUnreadMessageForAgent,+ hasDeliverableUnreadForAgentScope,+ listUnreadMessagesForAgent,+} from "../../src/db/queries/community/agent-inbox";+import { listEligibleUnreadChannels } from "../../src/db/queries/community/inbox";++describe("policyAllows", () => {+ it.each([+ ["all", false, true],+ ["all", true, true],+ ["mentions", false, false],+ ["mentions", true, true],+ ["nothing", false, false],+ ["nothing", true, false],+ ] as const)("maps %s / attention=%s to %s", (level, attention, expected) => {+ expect(policyAllows(level, attention)).toBe(expected);+ });+});++describe("notification setting cursor-clear contract", () => {+ let sqlite: Sqlite.Database;+ let db: Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL DEFAULT '',+ discriminator TEXT NOT NULL DEFAULT '0000',+ image TEXT,+ deleted_at TEXT+ );+ INSERT INTO user (id, name, discriminator) VALUES+ ('u', 'Bot', '0001'),+ ('author', 'Human', '0002');+ CREATE TABLE community_server (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ discriminator TEXT NOT NULL DEFAULT '0000',+ description TEXT NOT NULL DEFAULT '',+ icon TEXT,+ owner_id TEXT NOT NULL DEFAULT 'author',+ created_at TEXT NOT NULL DEFAULT '2025-01-01T00:00:00Z'+ );+ INSERT INTO community_server (id, name) VALUES ('server', 'Server');+ CREATE TABLE community_channel (+ id TEXT PRIMARY KEY,+ server_id TEXT,+ category_id TEXT,+ parent_channel_id TEXT,+ creator_id TEXT,+ type TEXT NOT NULL DEFAULT 'text',+ name TEXT NOT NULL DEFAULT '',+ archived INTEGER NOT NULL DEFAULT 0,+ last_message_at TEXT+ );+ CREATE TABLE community_category (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ private INTEGER NOT NULL DEFAULT 0+ );+ CREATE TABLE community_message (+ id TEXT PRIMARY KEY,+ channel_id TEXT NOT NULL,+ author_id TEXT NOT NULL DEFAULT 'author',+ content TEXT NOT NULL DEFAULT '',+ created_at TEXT NOT NULL,+ seq INTEGER NOT NULL,+ reply_to_id TEXT+ );+ CREATE TABLE community_read_state (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ channel_id TEXT NOT NULL,+ last_read_at TEXT NOT NULL,+ last_read_message_id TEXT,+ last_read_seq INTEGER NOT NULL DEFAULT 0,+ UNIQUE(user_id, channel_id)+ );+ CREATE TABLE community_channel_member (+ channel_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ relation TEXT NOT NULL,+ added_at TEXT NOT NULL+ );+ CREATE TABLE community_server_member (+ server_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ joined_at TEXT NOT NULL,+ role TEXT NOT NULL DEFAULT 'member',+ rail_order INTEGER NOT NULL DEFAULT 0+ );+ CREATE TABLE community_notification_setting (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ server_id TEXT,+ channel_id TEXT,+ level TEXT NOT NULL,+ CHECK ((server_id IS NOT NULL) != (channel_id IS NOT NULL))+ );+ CREATE UNIQUE INDEX idx_notification_setting_user_server+ ON community_notification_setting(user_id, server_id) WHERE server_id IS NOT NULL;+ CREATE UNIQUE INDEX idx_notification_setting_user_channel+ ON community_notification_setting(user_id, channel_id) WHERE channel_id IS NOT NULL;+ CREATE TABLE community_mention (+ id TEXT PRIMARY KEY,+ message_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ read INTEGER NOT NULL DEFAULT 0+ );+ INSERT INTO community_channel (id, server_id, parent_channel_id) VALUES+ ('parent', 'server', NULL),+ ('child', 'server', 'parent'),+ ('sibling', 'server', NULL),+ ('empty', 'server', NULL),+ ('dm', NULL, NULL);+ INSERT INTO community_message (id, channel_id, created_at, seq) VALUES+ ('parent-1', 'parent', '2026-01-01T00:00:01Z', 1),+ ('parent-2', 'parent', '2026-01-01T00:00:02Z', 2),+ ('child-3', 'child', '2026-01-01T00:00:03Z', 3),+ ('sibling-4', 'sibling', '2026-01-01T00:00:04Z', 4),+ ('dm-5', 'dm', '2026-01-01T00:00:05Z', 5);+ INSERT INTO community_server_member (server_id, user_id, joined_at)+ VALUES ('server', 'u', '2025-01-01T00:00:00Z');+ INSERT INTO community_channel_member (channel_id, user_id, relation, added_at)+ VALUES ('dm', 'u', 'access', '2025-01-01T00:00:00Z');+ `);+ const betterDb = drizzle(sqlite);+ (betterDb as any).batch = async (statements: any[]) =>+ sqlite.transaction(() => statements.map((statement) => statement.run()))();+ db = betterDb as unknown as Database;+ });++ afterEach(() => sqlite.close());++ const cursors = () => sqlite.prepare(`+ SELECT channel_id, last_read_message_id, last_read_at, last_read_seq+ FROM community_read_state+ WHERE user_id = 'u'+ ORDER BY channel_id+ `).all();++ it("atomically sets a server level and clears every non-empty channel in that server", async () => {+ await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" });++ expect(cursors()).toEqual([+ { channel_id: "child", last_read_message_id: "child-3", last_read_at: "2026-01-01T00:00:03Z", last_read_seq: 3 },+ { channel_id: "parent", last_read_message_id: "parent-2", last_read_at: "2026-01-01T00:00:02Z", last_read_seq: 2 },+ { channel_id: "sibling", last_read_message_id: "sibling-4", last_read_at: "2026-01-01T00:00:04Z", last_read_seq: 4 },+ ]);+ expect(sqlite.prepare("SELECT level FROM community_notification_setting WHERE user_id='u' AND server_id='server'").get())+ .toEqual({ level: "nothing" });+ });++ it("does not clear a private channel the target identity cannot access", async () => {+ sqlite.exec(`+ INSERT INTO community_category (id, server_id, private) VALUES ('private', 'server', 1);+ UPDATE community_channel SET category_id = 'private', creator_id = 'author' WHERE id = 'sibling';+ `);++ await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" });+ expect(cursors().map((row: any) => row.channel_id)).toEqual(["child", "parent"]);+ });++ it("a parent override clears the parent and its children, but not a sibling", async () => {+ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions" });+ expect(cursors().map((row: any) => row.channel_id)).toEqual(["child", "parent"]);+ });++ it("server changes do not clear descendants protected by a more specific override", async () => {+ sqlite.prepare(`+ INSERT INTO community_notification_setting (id, user_id, channel_id, level)+ VALUES ('child-own', 'u', 'child', 'all')+ `).run();++ await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" });+ expect(cursors().map((row: any) => row.channel_id)).toEqual(["parent", "sibling"]);+ });++ it("does not clear when an explicit override leaves the effective level unchanged", async () => {+ await setServerLevel(db, { userId: "u", serverId: "server", level: "mentions" });+ sqlite.prepare("DELETE FROM community_read_state").run();++ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions" });+ expect(cursors()).toEqual([]);+ });++ it("an idempotent retry preserves messages that arrived after the successful change", async () => {+ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing" });+ sqlite.exec(`+ INSERT INTO community_message (id, channel_id, created_at, seq) VALUES+ ('parent-6', 'parent', '2026-01-01T00:00:06Z', 6),+ ('child-7', 'child', '2026-01-01T00:00:07Z', 7);+ `);++ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing" });+ expect(cursors()).toEqual([+ { channel_id: "child", last_read_message_id: "child-3", last_read_at: "2026-01-01T00:00:03Z", last_read_seq: 3 },+ { channel_id: "parent", last_read_message_id: "parent-2", last_read_at: "2026-01-01T00:00:02Z", last_read_seq: 2 },+ ]);+ });++ it("a DM uses the same channel-scope setting and only clears that DM", async () => {+ await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing" });+ expect(cursors()).toEqual([+ { channel_id: "dm", last_read_message_id: "dm-5", last_read_at: "2026-01-01T00:00:05Z", last_read_seq: 5 },+ ]);+ });++ it("empty channels never manufacture a read-state row", async () => {+ await setChannelLevel(db, { userId: "u", channelId: "empty", level: "nothing" });+ expect(cursors()).toEqual([]);+ });++ it("never regresses an already-newer aligned cursor", async () => {+ sqlite.exec(`+ INSERT INTO community_message (id, channel_id, created_at, seq)+ VALUES ('parent-9', 'parent', '2026-01-01T00:00:09Z', 9);+ INSERT INTO community_read_state+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)+ VALUES ('rs', 'u', 'parent', '2026-01-01T00:00:09Z', 'parent-9', 9);+ DELETE FROM community_message WHERE id = 'parent-9';+ `);++ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "all" });+ expect(sqlite.prepare("SELECT last_read_message_id, last_read_seq FROM community_read_state WHERE id='rs'").get())+ .toEqual({ last_read_message_id: "parent-9", last_read_seq: 9 });+ });++ it("rolls the setting back when cursor advancement fails", async () => {+ sqlite.exec(`+ CREATE TRIGGER reject_read_state BEFORE INSERT ON community_read_state+ BEGIN SELECT RAISE(ABORT, 'cursor rejected'); END;+ `);++ await expect(setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" }))+ .rejects.toThrow("cursor rejected");+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting").get())+ .toEqual({ count: 0 });+ });++ it("override removal also clears old unread before inheriting again", async () => {+ await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing" });+ sqlite.prepare("DELETE FROM community_read_state").run();+ await removeChannelOverride(db, { userId: "u", channelId: "dm" });++ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting WHERE channel_id='dm'").get())+ .toEqual({ count: 0 });+ expect(cursors().map((row: any) => row.channel_id)).toEqual(["dm"]);+ });++ it("a no-op override removal preserves unread and creates no cursor", async () => {+ expect(await removeChannelOverride(db, { userId: "u", channelId: "dm" })).toBeNull();+ expect(cursors()).toEqual([]);+ });++ it("SQL eligibility uses the current override hierarchy and attention fact", async () => {+ sqlite.exec(`+ INSERT INTO community_notification_setting (id, user_id, channel_id, level)+ VALUES ('setting', 'u', 'child', 'mentions');+ INSERT INTO community_mention (id, message_id, user_id, kind)+ VALUES ('mention', 'child-3', 'u', 'mention');+ `);+ const channelSql = {+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ };+ const row = await (db as any)+ .select({+ mentioned: notificationEligibleSql("u", channelSql, { id: sql`'child-3'` }),+ plain: notificationEligibleSql("u", channelSql, { id: sql`'plain'` }),+ })+ .from(communityChannel)+ .where(eq(communityChannel.id, "child"))+ .get();++ expect(row).toEqual({ mentioned: 1, plain: 0 });+ });++ it("rail mention badge follows policy changes and the aligned read cursor", async () => {+ sqlite.exec(`+ INSERT INTO community_mention (id, message_id, user_id, kind, read)+ VALUES ('rail-old', 'child-3', 'u', 'mention', 0);+ `);+ const railCount = async () => (await listUserServers(db, "u"))[0]?.mentions;++ await expect(railCount()).resolves.toBe(1);+ await setChannelLevel(db, { userId: "u", channelId: "child", level: "nothing" });+ await expect(railCount()).resolves.toBe(0);++ sqlite.exec(`+ INSERT INTO community_message (id, channel_id, created_at, seq)+ VALUES ('child-6', 'child', '2026-01-01T00:00:06Z', 6);+ INSERT INTO community_mention (id, message_id, user_id, kind, read)+ VALUES ('rail-muted', 'child-6', 'u', 'mention', 0);+ `);+ await expect(railCount()).resolves.toBe(0);++ await setChannelLevel(db, { userId: "u", channelId: "child", level: "mentions" });+ await expect(railCount()).resolves.toBe(0);+ sqlite.exec(`+ INSERT INTO community_message (id, channel_id, created_at, seq)+ VALUES ('child-7', 'child', '2026-01-01T00:00:07Z', 7);+ INSERT INTO community_mention (id, message_id, user_id, kind, read)+ VALUES ('rail-new', 'child-7', 'u', 'mention', 0);+ `);+ await expect(railCount()).resolves.toBe(1);+ });++ it("rail mention badge disappears immediately when private-channel access is revoked", async () => {+ sqlite.exec(`+ INSERT INTO community_category (id, server_id, private) VALUES ('private-rail', 'server', 1);+ INSERT INTO community_channel+ (id, server_id, category_id, creator_id, type, name)+ VALUES ('private-room', 'server', 'private-rail', 'author', 'text', 'private-room');+ INSERT INTO community_channel_member (channel_id, user_id, relation, added_at)+ VALUES ('private-room', 'u', 'access', '2025-01-01T00:00:00Z');+ INSERT INTO community_message (id, channel_id, created_at, seq)+ VALUES ('private-mention', 'private-room', '2026-01-01T00:00:08Z', 8);+ INSERT INTO community_mention (id, message_id, user_id, kind, read)+ VALUES ('private-mention-row', 'private-mention', 'u', 'mention', 0);+ `);+ const railCount = async () => (await listUserServers(db, "u"))[0]?.mentions;++ await expect(railCount()).resolves.toBe(1);+ sqlite.prepare(`+ DELETE FROM community_channel_member+ WHERE channel_id = 'private-room' AND user_id = 'u' AND relation = 'access'+ `).run();+ await expect(railCount()).resolves.toBe(0);+ });++ it("delivery state fails closed after private access is revoked", async () => {+ sqlite.exec(`+ INSERT INTO community_category (id, server_id, private) VALUES ('private-delivery', 'server', 1);+ INSERT INTO community_channel+ (id, server_id, category_id, creator_id, type, name)+ VALUES ('private-delivery-room', 'server', 'private-delivery', 'author', 'text', 'private-delivery-room');+ INSERT INTO community_channel_member (channel_id, user_id, relation, added_at)+ VALUES ('private-delivery-room', 'u', 'access', '2025-01-01T00:00:00Z');+ INSERT INTO community_message (id, channel_id, created_at, seq)+ VALUES ('private-delivery-message', 'private-delivery-room', '2026-01-01T00:00:08Z', 8);+ `);++ await expect(resolveNotificationEligibilityForUsers(db, ["u"], "private-delivery-message"))+ .resolves.toEqual(new Map([["u", {+ currentLevel: "all",+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ }]]));++ sqlite.prepare(`+ DELETE FROM community_channel_member+ WHERE channel_id = 'private-delivery-room' AND user_id = 'u' AND relation = 'access'+ `).run();+ await expect(resolveNotificationEligibilityForUsers(db, ["u"], "private-delivery-message"))+ .resolves.toEqual(new Map([["u", {+ currentLevel: "all",+ hasAttention: false,+ isUnread: true,+ isReadable: false,+ }]]));+ });++ it("forum child badges stay policy-eligible across a cold projection", async () => {+ sqlite.exec(`+ INSERT INTO community_channel (id, server_id, parent_channel_id, type, name) VALUES+ ('forum-parent', 'server', NULL, 'forum', 'forum'),+ ('forum-child', 'server', 'forum-parent', 'thread', 'post');+ INSERT INTO community_channel_member (channel_id, user_id, relation, added_at)+ VALUES ('forum-child', 'u', 'notify', '2025-01-01T00:00:00Z');+ `);+ await setChannelLevel(db, { userId: "u", channelId: "forum-child", level: "mentions" });+ sqlite.exec(`+ INSERT INTO community_message (id, channel_id, created_at, seq, content)+ VALUES ('forum-normal', 'forum-child', '2026-01-01T00:00:01Z', 1, 'normal');+ `);+ await expect(listEligibleUnreadChannels(db, "u", ["forum-child"])).resolves.toEqual([]);++ sqlite.exec(`+ INSERT INTO community_message (id, channel_id, created_at, seq, content)+ VALUES ('forum-mention', 'forum-child', '2026-01-01T00:00:02Z', 2, '@u');+ INSERT INTO community_mention (id, message_id, user_id, kind, read)+ VALUES ('forum-mention-row', 'forum-mention', 'u', 'mention', 0);+ `);+ await expect(listEligibleUnreadChannels(db, "u", ["forum-child"]))+ .resolves.toEqual([expect.objectContaining({ channelId: "forum-child", mentionCount: 1 })]);+ });++ it("resync skips the newest muted unread and finds an older eligible unread", async () => {+ sqlite.exec(`+ INSERT INTO community_message (id, channel_id, created_at, seq)+ VALUES ('parent-newest', 'parent', '2026-01-01T00:00:10Z', 10);+ INSERT INTO community_notification_setting (id, user_id, channel_id, level) VALUES+ ('mute-parent', 'u', 'parent', 'nothing'),+ ('allow-child', 'u', 'child', 'all');+ `);++ const latest = await getLatestUnreadMessageForAgent(db, "u", {+ accessVisibleChannelIds: ["parent", "child"],+ });+ expect(latest).toEqual({ messageId: "child-3" });+ });++ it("filters before page limits and keeps pull, snapshot, alignment, and web summaries identical", async () => {+ sqlite.exec(`+ INSERT INTO community_channel+ (id, server_id, parent_channel_id, type, name, last_message_at)+ VALUES+ ('a_muted', 'server', NULL, 'text', 'muted', '2026-01-01T00:03:00Z'),+ ('z_eligible', 'server', NULL, 'text', 'eligible', '2026-01-01T00:02:00Z');+ INSERT INTO community_notification_setting (id, user_id, channel_id, level)+ VALUES ('mute', 'u', 'a_muted', 'nothing');+ INSERT INTO community_message+ (id, author_id, channel_id, seq, created_at, content)+ VALUES+ ('muted_newer', 'author', 'a_muted', 1, '2026-01-01T00:03:00Z', 'muted'),+ ('eligible_older', 'author', 'z_eligible', 1, '2026-01-01T00:02:00Z', 'eligible'),+ ('eligible_second', 'author', 'z_eligible', 2, '2026-01-01T00:02:30Z', 'eligible 2');+ INSERT INTO community_mention (id, message_id, user_id, kind, read)+ VALUES+ ('dismissed_reply', 'eligible_older', 'u', 'reply', 1),+ ('active_mention', 'eligible_second', 'u', 'mention', 0);+ `);+ const insertMuted = sqlite.prepare(`+ INSERT INTO community_message (id, author_id, channel_id, seq, created_at, content)+ VALUES (?, 'author', 'a_muted', ?, '2026-01-01T00:03:00Z', 'muted')+ `);+ sqlite.transaction(() => {+ for (let seq = 2; seq <= 200; seq += 1) insertMuted.run(`muted_${seq}`, seq);+ })();++ const visible = ["a_muted", "z_eligible"];+ await expect(listUnreadMessagesForAgent(db, "u", {+ max: 1,+ visibleChannelIds: visible,+ })).resolves.toMatchObject([{ id: "eligible_older", channelId: "z_eligible" }]);+ await expect(listUnreadMessagesForAgent(db, "u", {+ max: 2,+ visibleChannelIds: visible,+ })).resolves.toMatchObject([+ { id: "eligible_older", channelId: "z_eligible" },+ { id: "eligible_second", channelId: "z_eligible" },+ ]);++ await expect(getInboxSnapshotForAgent(db, "u", {+ accessVisibleChannelIds: visible,+ })).resolves.toEqual([{+ channelId: "z_eligible",+ pendingCount: 2,+ firstPendingSeq: 1,+ latestSeq: 2,+ latestSender: "@Human#0002",+ hasMention: true,+ }]);++ await expect(hasDeliverableUnreadForAgentScope(db, "u", "a_muted", 0))+ .resolves.toBe(false);+ await expect(hasDeliverableUnreadForAgentScope(db, "u", "z_eligible", 0))+ .resolves.toBe(true);++ await expect(listEligibleUnreadChannels(db, "u", visible)).resolves.toEqual([+ expect.objectContaining({+ channelId: "z_eligible",+ lastMessageAt: "2026-01-01T00:02:30Z",+ mentionCount: 1,+ }),+ ]);+ });+});diff --git a/src/shared/test/queries/community-notification-eligibility.test.ts b/src/shared/test/queries/community-notification-eligibility.test.tsnew file mode 100644index 000000000..05389f3cb--- /dev/null+++ b/src/shared/test/queries/community-notification-eligibility.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it, vi } from "vitest";+import { resolveNotificationEligibilityForUsers } from "../../src/db/queries/community/notification-eligibility";++function createSelectMock(resultSets: unknown[][]) {+ let call = 0;+ const chain: any = {};+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve(resultSets[call++] ?? []));+ return { select: vi.fn(() => chain), __chain: chain } as any;+}++describe("resolveNotificationEligibilityForUsers", () => {+ it("returns no rows without querying for an empty recipient set", async () => {+ const db = createSelectMock([]);++ await expect(resolveNotificationEligibilityForUsers(db, [], "m1")).resolves.toEqual(new Map());+ expect(db.select).not.toHaveBeenCalled();+ });++ it("chunks more than 90 recipients and preserves policy, attention, and cursor state", async () => {+ const userIds = Array.from({ length: 150 }, (_, index) => `u${index}`);+ const first = userIds.slice(0, 89).map((userId, index) => ({+ userId,+ currentLevel: index === 0 ? "nothing" : "all",+ hasAttention: 0,+ isUnread: 1,+ isReadable: 1,+ }));+ const second = userIds.slice(89).map((userId, index) => ({+ userId,+ currentLevel: index === 31 ? "mentions" : "all",+ hasAttention: index === 31 ? 1 : 0,+ isUnread: index === 60 ? 0 : 1,+ isReadable: index === 0 ? 0 : 1,+ }));+ const db = createSelectMock([first, second]);++ const result = await resolveNotificationEligibilityForUsers(db, userIds, "m1");++ expect(result).toHaveLength(150);+ expect(result.get("u0")).toEqual({ currentLevel: "nothing", hasAttention: false, isUnread: true, isReadable: true });+ expect(result.get("u89")).toEqual({ currentLevel: "all", hasAttention: false, isUnread: true, isReadable: false });+ expect(result.get("u120")).toEqual({ currentLevel: "mentions", hasAttention: true, isUnread: true, isReadable: true });+ expect(result.get("u149")).toEqual({ currentLevel: "all", hasAttention: false, isUnread: false, isReadable: true });+ expect(db.select).toHaveBeenCalledTimes(2);+ expect(db.__chain.leftJoin).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/shared/test/queries/community-notification-setting.test.ts b/src/shared/test/queries/community-notification-setting.test.tsindex 70f1a1927..287760bcb 100644--- a/src/shared/test/queries/community-notification-setting.test.ts+++ b/src/shared/test/queries/community-notification-setting.test.ts@@ -181,4 +181,22 @@ describe("resolveEffectiveLevelForUsers — batch", () => {// 1 channel lookup + 1 settings fetch = 2 selects total, regardless of user count.expect(db.select).toHaveBeenCalledTimes(2);});++ it("chunks more than 90 recipients without dropping all/mentions/nothing groups", async () => {+ const userIds = Array.from({ length: 150 }, (_, index) => `u${index}`);+ const db = createSelectMock([+ [POST],+ [{ userId: "u0", channelId: "p1", serverId: null, level: "nothing" }],+ [{ userId: "u120", channelId: null, serverId: "s1", level: "mentions" }],+ ]);++ const map = await notif.resolveEffectiveLevelForUsers(db, userIds, "p1");++ expect(map.size).toBe(150);+ expect(map.get("u0")).toBe("nothing");+ expect(map.get("u120")).toBe("mentions");+ expect(map.get("u149")).toBe("all");+ // 1 channel lookup + 2 bounded recipient chunks, never one query/user.+ expect(db.select).toHaveBeenCalledTimes(3);+ });});diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.tsindex 9e1e2db52..f641ec442 100644--- a/src/shared/test/queries/server.test.ts+++ b/src/shared/test/queries/server.test.ts@@ -8,6 +8,7 @@ import {communityServerMember,communityMention,communityMessage,+ communityReadState,} from "../../src/db/community-schema";// Mocks a Drizzle DB where each insert()/select() chain resolves to a@@ -369,6 +370,8 @@ describe("listUserServers — mention aggregate for the rail badge", () => {const joinedTables = sub.innerJoins.map((j: any) => j.table);expect(joinedTables).toContain(communityMessage);expect(joinedTables).toContain(communityChannel);+ expect(sub.leftJoins).toHaveLength(1);+ expect(sub.leftJoins[0].table).toBe(communityReadState);// groupBy on channel.serverId so the row shape is (serverId, count).expect(sub.groupBy).toBe(communityChannel.serverId);expect(sub.aliased).toBe("mention_counts");@@ -461,6 +464,13 @@ describe("listUserServers — filter predicates (source-level pin)", () => {expect(src).toMatch(/MENTION_KIND\.MENTION/);});+ it("gates the rail count by current policy and the aligned read cursor", () => {+ expect(src).toMatch(/notificationEligibleSql/);+ expect(src).toMatch(/channelReadableSql/);+ expect(src).toMatch(/communityMessage\.seq/);+ expect(src).toMatch(/communityReadState\.lastReadSeq/);+ });+it("joins go through community_message → community_channel so DM mentions never land in the aggregate", () => {// DM messages have channelId=NULL and would be excluded by INNER JOIN on// `community_channel.id = message.channelId`. Pin the join topology.diff --git a/src/wake-worker/src/index.test.ts b/src/wake-worker/src/index.test.tsindex 306718092..96183d7be 100644--- a/src/wake-worker/src/index.test.ts+++ b/src/wake-worker/src/index.test.ts@@ -66,7 +66,7 @@ describe("wake-worker queue consumer", () => {"bot_missing","bot_deleted","bot_unbound",- "bot_not_in_scope",+ "forbidden","notice_channel_unresolvable","already_read",] as const)("acks for skip reason %s", async (reason) => {@@ -255,7 +255,9 @@ const RESOLUTION_SCENARIOS = [{ name: "sent", outcome: { outcome: "sent" as const } },{ name: "delivered_nowhere", outcome: { outcome: "delivered_nowhere" as const, machineId: "m1" } },{ name: "skip: already_read", outcome: { outcome: "skip" as const, reason: "already_read" as const } },- { name: "skip: bot_not_in_scope", outcome: { outcome: "skip" as const, reason: "bot_not_in_scope" as const } },+ { name: "skip: forbidden", outcome: { outcome: "skip" as const, reason: "forbidden" as const } },+ { name: "skip: muted", outcome: { outcome: "skip" as const, reason: "muted" as const } },+ { name: "skip: mention_only", outcome: { outcome: "skip" as const, reason: "mention_only" as const } },]describe("wake-worker queue() vs fetch() — same resolution for the same candidate", () => {diff --git a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.tsnew file mode 100644index 000000000..4034fc768--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const getBotOwnedBy = vi.fn()+const getChannelSetting = vi.fn()+const setChannelLevel = vi.fn()+const removeChannelOverride = vi.fn()+const requireMessageSurfaceAccess = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: () => ({}) }))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityBot: { getBotOwnedBy: (...args: unknown[]) => getBotOwnedBy(...args) },+ communityNotificationSetting: {+ getChannelSetting: (...args: unknown[]) => getChannelSetting(...args),+ setChannelLevel: (...args: unknown[]) => setChannelLevel(...args),+ removeChannelOverride: (...args: unknown[]) => removeChannelOverride(...args),+ },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({+ requireMessageSurfaceAccess: (...args: unknown[]) => requireMessageSurfaceAccess(...args),+}))+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {+ env: { DB: {} }, userId: ctx.actor ?? "owner", email: "owner@test", params: ctx.params,+ }),+}))++import { DELETE, PUT } from "./route"++const ctx = { params: { id: "bot_1", scopeId: "dm_1" } } as any+const put = () => new NextRequest("http://local", { method: "PUT", body: JSON.stringify({ level: "mentions" }) })++describe("owner bot channel notification settings", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ getBotOwnedBy.mockResolvedValue({ id: "bot_1", ownerUserId: "owner" })+ requireMessageSurfaceAccess.mockResolvedValue({ ok: true, value: { surface: "dm" } })+ setChannelLevel.mockResolvedValue({ level: "mentions" })+ })++ it("writes the owned bot identity after checking the bot's DM access", async () => {+ const response = await PUT(put(), ctx)+ expect(response.status).toBe(200)+ expect(getBotOwnedBy).toHaveBeenCalledWith({}, "bot_1", "owner")+ expect(requireMessageSurfaceAccess).toHaveBeenCalledWith({}, "dm_1", "bot_1")+ expect(setChannelLevel).toHaveBeenCalledWith({}, {+ userId: "bot_1", channelId: "dm_1", level: "mentions",+ })+ })++ it("masks a non-owned bot and never checks scope", async () => {+ getBotOwnedBy.mockResolvedValue(null)+ const response = await PUT(put(), { ...ctx, actor: "stranger" } as any)+ expect(response.status).toBe(404)+ expect(requireMessageSurfaceAccess).not.toHaveBeenCalled()+ expect(setChannelLevel).not.toHaveBeenCalled()+ })++ it("rejects a bot without target scope access", async () => {+ requireMessageSurfaceAccess.mockResolvedValue({ ok: false, status: 404, error: "not found" })+ const response = await PUT(put(), ctx)+ expect(response.status).toBe(404)+ expect(setChannelLevel).not.toHaveBeenCalled()+ })++ it("uses the same bot access gate before deleting an override", async () => {+ const response = await DELETE(new NextRequest("http://local", { method: "DELETE" }), ctx)+ expect(response.status).toBe(204)+ expect(requireMessageSurfaceAccess).toHaveBeenCalledWith({}, "dm_1", "bot_1")+ expect(removeChannelOverride).toHaveBeenCalledWith({}, { userId: "bot_1", channelId: "dm_1" })+ })+})diff --git a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.tsnew file mode 100644index 000000000..386539a75--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts@@ -0,0 +1,53 @@+import { NextRequest } from "next/server"+import { NOTIFICATION_LEVEL_VALUES, queries } from "@alook/shared"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"+import { getDb } from "@/lib/db"+import { withAuth, type AuthContext } from "@/lib/middleware/auth"+import { writeError, writeJSON } from "@/lib/middleware/helpers"++async function authorize(ctx: AuthContext & { params?: Record<string, string> }) {+ const botId = ctx.params?.id+ const channelId = ctx.params?.scopeId+ if (!botId || !channelId) return { ok: false as const, response: writeError("missing scope id", 400) }+ const db = getDb(ctx.env.DB)+ const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)+ if (!bot) return { ok: false as const, response: writeError("bot not found", 404) }+ const access = await requireMessageSurfaceAccess(db, channelId, bot.id)+ if (!access.ok) return { ok: false as const, response: writeError(access.error, access.status) }+ return { ok: true as const, db, botId: bot.id, channelId }+}++export const GET = withAuth(async (_req, ctx) => {+ const auth = await authorize(ctx)+ if (!auth.ok) return auth.response+ const setting = await queries.communityNotificationSetting.getChannelSetting(+ auth.db, auth.botId, auth.channelId,+ )+ return writeJSON({ level: setting?.level ?? null })+})++export const PUT = withAuth(async (req: NextRequest, ctx) => {+ const auth = await authorize(ctx)+ if (!auth.ok) return auth.response+ let body: { level?: string }+ try { body = await req.json() } catch { return writeError("invalid request body", 400) }+ if (!body.level || !(NOTIFICATION_LEVEL_VALUES as readonly string[]).includes(body.level)) {+ return writeError(`level must be one of: ${NOTIFICATION_LEVEL_VALUES.join(", ")}`, 400)+ }+ const setting = await queries.communityNotificationSetting.setChannelLevel(auth.db, {+ userId: auth.botId,+ channelId: auth.channelId,+ level: body.level,+ })+ return writeJSON(setting)+})++export const DELETE = withAuth(async (_req, ctx) => {+ const auth = await authorize(ctx)+ if (!auth.ok) return auth.response+ await queries.communityNotificationSetting.removeChannelOverride(auth.db, {+ userId: auth.botId,+ channelId: auth.channelId,+ })+ return new Response(null, { status: 204 })+})diff --git a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.tsnew file mode 100644index 000000000..4fed947e8--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts@@ -0,0 +1,59 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const getBotOwnedBy = vi.fn()+const setServerLevel = vi.fn()+const requireServerMember = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: () => ({}) }))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityBot: { getBotOwnedBy: (...args: unknown[]) => getBotOwnedBy(...args) },+ communityNotificationSetting: {+ getServerSetting: vi.fn(),+ setServerLevel: (...args: unknown[]) => setServerLevel(...args),+ },+ },+ }+})+vi.mock("@/lib/community/permissions", () => ({+ requireServerMember: (...args: unknown[]) => requireServerMember(...args),+}))+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {+ env: { DB: {} }, userId: ctx.actor ?? "owner", email: "owner@test", params: ctx.params,+ }),+}))++import { PUT } from "./route"++const ctx = { params: { id: "bot_1", scopeId: "server_1" } } as any+const put = () => new NextRequest("http://local", { method: "PUT", body: JSON.stringify({ level: "nothing" }) })++describe("owner bot server notification settings", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ getBotOwnedBy.mockResolvedValue({ id: "bot_1", ownerUserId: "owner" })+ requireServerMember.mockResolvedValue({ ok: true, value: { role: "member" } })+ setServerLevel.mockResolvedValue({ level: "nothing" })+ })++ it("checks bot membership and writes the bot user id", async () => {+ const response = await PUT(put(), ctx)+ expect(response.status).toBe(200)+ expect(requireServerMember).toHaveBeenCalledWith({}, "server_1", "bot_1")+ expect(setServerLevel).toHaveBeenCalledWith({}, {+ userId: "bot_1", serverId: "server_1", level: "nothing",+ })+ })++ it("rejects a bot that cannot access the server", async () => {+ requireServerMember.mockResolvedValue({ ok: false, status: 403, error: "not a member" })+ const response = await PUT(put(), ctx)+ expect(response.status).toBe(403)+ expect(setServerLevel).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.tsnew file mode 100644index 000000000..a099a9c55--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts@@ -0,0 +1,43 @@+import { NextRequest } from "next/server"+import { NOTIFICATION_LEVEL_VALUES, queries } from "@alook/shared"+import { requireServerMember } from "@/lib/community/permissions"+import { getDb } from "@/lib/db"+import { withAuth, type AuthContext } from "@/lib/middleware/auth"+import { writeError, writeJSON } from "@/lib/middleware/helpers"++async function authorize(ctx: AuthContext & { params?: Record<string, string> }) {+ const botId = ctx.params?.id+ const serverId = ctx.params?.scopeId+ if (!botId || !serverId) return { ok: false as const, response: writeError("missing scope id", 400) }+ const db = getDb(ctx.env.DB)+ const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)+ if (!bot) return { ok: false as const, response: writeError("bot not found", 404) }+ const access = await requireServerMember(db, serverId, bot.id)+ if (!access.ok) return { ok: false as const, response: writeError(access.error, access.status) }+ return { ok: true as const, db, botId: bot.id, serverId }+}++export const GET = withAuth(async (_req, ctx) => {+ const auth = await authorize(ctx)+ if (!auth.ok) return auth.response+ const setting = await queries.communityNotificationSetting.getServerSetting(+ auth.db, auth.botId, auth.serverId,+ )+ return writeJSON({ level: setting?.level ?? null })+})++export const PUT = withAuth(async (req: NextRequest, ctx) => {+ const auth = await authorize(ctx)+ if (!auth.ok) return auth.response+ let body: { level?: string }+ try { body = await req.json() } catch { return writeError("invalid request body", 400) }+ if (!body.level || !(NOTIFICATION_LEVEL_VALUES as readonly string[]).includes(body.level)) {+ return writeError(`level must be one of: ${NOTIFICATION_LEVEL_VALUES.join(", ")}`, 400)+ }+ const setting = await queries.communityNotificationSetting.setServerLevel(auth.db, {+ userId: auth.botId,+ serverId: auth.serverId,+ level: body.level,+ })+ return writeJSON(setting)+})diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.tsindex f5e137125..9f0ce8caa 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts@@ -5,7 +5,7 @@ const mockGetMember = vi.fn()const mockListServerChannelsForViewer = vi.fn()const mockListParticipatingForumThreads = vi.fn()const mockGetMessagesByIds = vi.fn()-const mockListUnreadChannels = vi.fn()+const mockListEligibleUnreadChannels = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))vi.mock("@alook/shared", async () => {@@ -29,7 +29,7 @@ vi.mock("@alook/shared", async () => {},communityInbox: {...actual.queries.communityInbox,- listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),+ listEligibleUnreadChannels: (...args: unknown[]) => mockListEligibleUnreadChannels(...args),},},}@@ -47,7 +47,7 @@ import { GET } from "./route"describe("GET /api/community/servers/[id]/channels — human resource", () => {beforeEach(() => {vi.clearAllMocks()- mockListUnreadChannels.mockResolvedValue([])+ mockListEligibleUnreadChannels.mockResolvedValue([])})it("returns only viewer-visible channel rows after one server membership gate", async () => {@@ -80,7 +80,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {}mockListParticipatingForumThreads.mockResolvedValue({ canonical: [thread], retained: thread })mockGetMessagesByIds.mockResolvedValue([{ id: "message_1", content: "Current title" }])- mockListUnreadChannels.mockResolvedValue([{ channelId: "thread_1" }])+ mockListEligibleUnreadChannels.mockResolvedValue([{ channelId: "thread_1" }])try {const response = await GET(@@ -114,7 +114,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {included: { parentMessages: [{ id: "message_1", content: "Current title" }] },serverNow: "2026-08-08T12:00:00.000Z",})- expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["thread_1"])+ expect(mockListEligibleUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["thread_1"])expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["message_1"])} finally {vi.useRealTimers()diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.tsindex 0c2bc3a24..87dc3f543 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts@@ -75,7 +75,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {.filter((id): id is string => !!id)const [parentMessages, unreadRows] = await Promise.all([queries.communityMessage.getMessagesByIds(db, parentMessageIds),- queries.communityInbox.listUnreadChannels(db, ctx.actor.userId, rows.map((channel) => channel.id)),+ queries.communityInbox.listEligibleUnreadChannels(db, ctx.actor.userId, rows.map((channel) => channel.id)),])const unreadIds = new Set(unreadRows.map((row) => row.channelId))const projectChannel = (channel: (typeof rows)[number]) => ({diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.test.tsindex ec5d45094..4376868c6 100644--- a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts@@ -3,7 +3,7 @@ import { NextRequest } from "next/server"const mockGetMember = vi.fn()const mockListVisibleChannelIds = vi.fn()-const mockListUnreadChannels = vi.fn()+const mockListEligibleUnreadChannels = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))vi.mock("@alook/shared", async () => {@@ -19,7 +19,7 @@ vi.mock("@alook/shared", async () => {},communityInbox: {...actual.queries.communityInbox,- listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),+ listEligibleUnreadChannels: (...args: unknown[]) => mockListEligibleUnreadChannels(...args),},},}@@ -39,7 +39,7 @@ describe("GET /api/community/servers/[id]/unreads", () => {vi.clearAllMocks()mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })mockListVisibleChannelIds.mockResolvedValue(["channel_1", "channel_2", "other_1"])- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([{ serverId: "server_1", channelId: "channel_1" },{ serverId: "server_1", channelId: "channel_2", parentChannelId: "channel_1" },{ serverId: "server_2", channelId: "other_1" },@@ -58,17 +58,17 @@ describe("GET /api/community/servers/[id]/unreads", () => {childChannels: [{ id: "channel_2", parentChannelId: "channel_1" }],stale: false,})- expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["channel_1", "channel_2", "other_1"])+ expect(mockListEligibleUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["channel_1", "channel_2", "other_1"])})- it("does not consult notification settings, so server/channel mute cannot hide read-state", async () => {+ it("uses the shared readable, cursor, policy, and attention projection on refetch", async () => {const response = await GET(new NextRequest("http://localhost/api/community/servers/server_1/unreads"),{ params: { id: "server_1" } } as never,)expect(await response.json()).toMatchObject({ channelIds: ["channel_1", "channel_2"] })- expect(mockListUnreadChannels).toHaveBeenCalledOnce()+ expect(mockListEligibleUnreadChannels).toHaveBeenCalledOnce()})it("fails closed when the viewer is not a server member", async () => {@@ -80,7 +80,7 @@ describe("GET /api/community/servers/[id]/unreads", () => {expect(response.status).toBe(403)expect(mockListVisibleChannelIds).not.toHaveBeenCalled()- expect(mockListUnreadChannels).not.toHaveBeenCalled()+ expect(mockListEligibleUnreadChannels).not.toHaveBeenCalled()})it("marks retry-exhausted reads stale instead of caching an empty read set", async () => {diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.tsindex f98be1719..32543a549 100644--- a/src/web/src/app/api/community/servers/[id]/unreads/route.ts+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.ts@@ -4,11 +4,7 @@ import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { requireServerMember } from "@/lib/community/permissions"-/**- * Raw read-state projection for one server. Unlike the inbox notification- * feed, this resource deliberately does not apply notification preferences:- * muting a server/channel must not turn its sidebar read-state badge off.- */+/** Attention-eligible read-state projection for one server's sidebar badges. */export const GET = withAuth(async (_req, ctx) => {const serverId = ctx.params?.idif (!serverId) return NextResponse.json({ error: "missing server id" }, { status: 400 })@@ -20,15 +16,15 @@ export const GET = withAuth(async (_req, ctx) => {const { value, stale } = await readOrStale(async () => {const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)- const unread = (await queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds))+ const unread = (await queries.communityInbox.listEligibleUnreadChannels(db, ctx.userId, visibleChannelIds)).filter((row) => row.serverId === serverId)return {channelIds: unread.map((row) => row.channelId),// Preserve the canonical child → parent attribution. The client needs// this even when a participating forum post is outside the sidebar's// 72h / top-five projection, otherwise a cold boot loses its unread- // signal entirely. `listUnreadChannels` has already applied access,- // archive, and participant filtering, so these are safe candidates;+ // signal entirely. `listEligibleUnreadChannels` has already applied+ // access, archive, participant, read-cursor, and policy filtering;// the client narrows them to parents whose canonical type is `forum`.childChannels: unread.flatMap((row) => row.parentChannelId? [{ id: row.channelId, parentChannelId: row.parentChannelId }]diff --git a/src/web/src/app/api/community/users/me/inbox/ack/route.ts b/src/web/src/app/api/community/users/me/inbox/ack/route.tsindex c635fc90d..38918638f 100644--- a/src/web/src/app/api/community/users/me/inbox/ack/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/ack/route.ts@@ -1,5 +1,5 @@import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry, CommunityAgentAckRequestSchema } from "@alook/shared"+import { queries, withD1Retry, CommunityAgentAckRequestSchema, type CommunityCliAckResponse } from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"import { resolveTargetForMember } from "@/lib/community/resolve-ref"@@ -109,5 +109,6 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {applied.push({ channel: cursor.channel, seq: cursor.seq })}- return NextResponse.json({ ok: failed.length === 0, applied, failed })+ const response: CommunityCliAckResponse = { ok: failed.length === 0, applied, failed }+ return NextResponse.json(response)})diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.tsindex 398999490..64d6090b4 100644--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts@@ -1,12 +1,10 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"-const mockListUnreadChannels = vi.fn()+const mockListEligibleUnreadChannels = vi.fn()const mockListUnreadForumOpeners = vi.fn()const mockListForumOpenersByChildIds = vi.fn()-const mockGetSettings = vi.fn()-const mockListUnreadMentions = vi.fn()-const mockListUnreadDms = vi.fn()+const mockListEligibleUnreadDms = vi.fn()const mockListVisibleChannelIds = vi.fn()const mockGetChannelsByIds = vi.fn()@@ -22,16 +20,10 @@ vi.mock("@alook/shared", async () => {...actual,queries: {communityInbox: {- listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),+ listEligibleUnreadChannels: (...args: unknown[]) => mockListEligibleUnreadChannels(...args),listUnreadForumOpeners: (...args: unknown[]) => mockListUnreadForumOpeners(...args),listForumOpenersByChildIds: (...args: unknown[]) => mockListForumOpenersByChildIds(...args),- listUnreadDms: (...args: unknown[]) => mockListUnreadDms(...args),- },- communityNotificationSetting: {- getSettings: (...args: unknown[]) => mockGetSettings(...args),- },- communityMention: {- listUnreadMentions: (...args: unknown[]) => mockListUnreadMentions(...args),+ listEligibleUnreadDms: (...args: unknown[]) => mockListEligibleUnreadDms(...args),},communityChannel: {listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),@@ -58,7 +50,7 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"-function row(overrides: Partial<{ channelId: string; channelName: string; serverId: string; serverName: string; type: string | null; parentChannelId: string | null; lastMessageAt: string; lastReadAt: string | null }>) {+function row(overrides: Partial<{ channelId: string; channelName: string; serverId: string; serverName: string; type: string | null; parentChannelId: string | null; lastMessageAt: string; lastReadAt: string | null; mentionCount: number }>) {return {channelId: "c1",channelName: "general",@@ -68,6 +60,7 @@ function row(overrides: Partial<{ channelId: string; channelName: string; serverparentChannelId: null,lastMessageAt: "2026-06-25T10:00:00Z",lastReadAt: null,+ mentionCount: 0,...overrides,}}@@ -94,9 +87,7 @@ function opener(overrides: Partial<{describe("GET /api/community/users/me/inbox/unreads", () => {beforeEach(() => {vi.clearAllMocks()- mockGetSettings.mockResolvedValue([])- mockListUnreadMentions.mockResolvedValue([])- mockListUnreadDms.mockResolvedValue([])+ mockListEligibleUnreadDms.mockResolvedValue([])mockListUnreadForumOpeners.mockResolvedValue([])mockListForumOpenersByChildIds.mockResolvedValue([])mockListVisibleChannelIds.mockResolvedValue([])@@ -104,7 +95,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("groups channels by server", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ serverId: "s1", channelId: "c1", channelName: "general", lastMessageAt: "2026-06-25T10:00:00Z" }),row({ serverId: "s1", channelId: "c2", channelName: "releases", lastMessageAt: "2026-06-25T09:00:00Z" }),row({ serverId: "s2", serverName: "Other", channelId: "c3", channelName: "lounge", lastMessageAt: "2026-06-25T11:00:00Z" }),@@ -122,39 +113,8 @@ describe("GET /api/community/users/me/inbox/unreads", () => {expect(body.servers[1].channels.map((c: { channelId: string }) => c.channelId)).toEqual(["c1", "c2"])})- it("filters muted servers", async () => {- mockListUnreadChannels.mockResolvedValue([- row({ serverId: "s1" }),- row({ serverId: "s2", serverName: "Other", channelId: "c2", channelName: "lounge" }),- ])- mockGetSettings.mockResolvedValue([{ serverId: "s1", channelId: null, level: "nothing" }])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()-- expect(body.servers.map((s: { serverId: string }) => s.serverId)).toEqual(["s2"])- })-- it("filters muted channels", async () => {- mockListUnreadChannels.mockResolvedValue([- row({ serverId: "s1", channelId: "c1" }),- row({ serverId: "s1", channelId: "c2", channelName: "spam" }),- ])- mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "c2", level: "nothing" }])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()-- expect(body.servers[0].channels.map((c: { channelId: string }) => c.channelId)).toEqual(["c1"])- })-- it("attaches mentionCount from unread mentions per channel", async () => {- mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- mockListUnreadMentions.mockResolvedValue([- { message: { channelId: "c1" } },- { message: { channelId: "c1" } },- { message: { channelId: "c-other" } },- ])+ it("uses the mentionCount already aggregated over eligible unread", async () => {+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1", mentionCount: 2 })])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].mentionCount).toBe(2)@@ -162,7 +122,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {it("truncates by total channel count when over the limit", async () => {// 3 channels under one server, limit=2 → only first 2 returned, truncated=true.- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ serverId: "s1", channelId: "c1", lastMessageAt: "2026-06-25T12:00:00Z" }),row({ serverId: "s1", channelId: "c2", lastMessageAt: "2026-06-25T11:00:00Z" }),row({ serverId: "s1", channelId: "c3", lastMessageAt: "2026-06-25T10:00:00Z" }),@@ -177,15 +137,15 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("reports truncated=false when total channel count fits the limit", async () => {- mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=10"))const body = await res.json()expect(body.truncated).toBe(false)})it("returns unread DMs sorted most-recent first", async () => {- mockListUnreadChannels.mockResolvedValue([])- mockListUnreadDms.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([])+ mockListEligibleUnreadDms.mockResolvedValue([{ channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T09:00:00Z" },{ channelId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },])@@ -203,8 +163,8 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("returns empty dms array when only channels are unread", async () => {- mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- mockListUnreadDms.mockResolvedValue([])+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])+ mockListEligibleUnreadDms.mockResolvedValue([])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.dms).toEqual([])@@ -212,8 +172,8 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("returns dms alongside servers when both have unreads", async () => {- mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- mockListUnreadDms.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])+ mockListEligibleUnreadDms.mockResolvedValue([{ channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))@@ -227,7 +187,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {it("nests an unread thread under its parent channel; parent surfaces w/o direct unread", async () => {// Parent c1 has NO direct unread (not in the unread list); its child thread// t1 does. The route must batch-resolve the parent's name via getChannelsByIds.- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "t1", channelName: "budget-2026", parentChannelId: "c1", lastMessageAt: "2026-06-25T10:00:00Z" }),])mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])@@ -246,7 +206,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("nests a child under a parent that ALSO has a direct unread (no re-resolve)", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1", channelName: "general", lastMessageAt: "2026-06-25T10:00:00Z" }),row({ channelId: "t1", channelName: "budget-2026", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),])@@ -260,35 +220,27 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("attributes per-channel mentionCount to the correct child row", async () => {- mockListUnreadChannels.mockResolvedValue([- row({ channelId: "t1", channelName: "thread", parentChannelId: "c1" }),+ mockListEligibleUnreadChannels.mockResolvedValue([+ row({ channelId: "t1", channelName: "thread", parentChannelId: "c1", mentionCount: 2 }),])mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])- mockListUnreadMentions.mockResolvedValue([- { message: { channelId: "t1" } },- { message: { channelId: "t1" } },- ])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].children[0].mentionCount).toBe(2)})- it("cascades a muted parent's mute to its unread child rows", async () => {- mockListUnreadChannels.mockResolvedValue([- row({ channelId: "t1", channelName: "thread", parentChannelId: "c1" }),- ])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])- // Parent c1 muted → the whole subtree is suppressed.- mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "c1", level: "nothing" }])+ it("does not reconstruct channels absent from the eligible unread set", async () => {+ mockListEligibleUnreadChannels.mockResolvedValue([])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers).toHaveLength(0)+ expect(mockGetChannelsByIds).not.toHaveBeenCalled()})it("counts child rows toward the truncation limit", async () => {// Parent c1 (weight 1) + 2 children (weight 2) = 3 rows; limit=2 → parent +// 1 child kept, truncated=true.- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1", channelName: "general", lastMessageAt: "2026-06-25T09:00:00Z" }),row({ channelId: "t1", channelName: "thread-1", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),row({ channelId: "t2", channelName: "thread-2", parentChannelId: "c1", lastMessageAt: "2026-06-25T10:00:00Z" }),@@ -303,7 +255,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("top-level channels carry an empty children array", async () => {- mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].children).toEqual([])@@ -312,7 +264,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {// ── Entity type plumbing (drives the inbox icon) ───────────────────────────it("surfaces channel `type` so the inbox can pick the right entity icon", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1", channelName: "general", type: "text" }),row({ channelId: "c2", channelName: "help-forum", type: "forum", lastMessageAt: "2026-06-25T09:00:00Z" }),])@@ -325,7 +277,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("surfaces child `type` (thread / forum_post) on nested rows", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1", channelName: "general", type: "text" }),row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),])@@ -337,7 +289,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("carries `type` from getChannelsByIds when the parent is backfilled", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1" }),])mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "help-forum", serverId: "s1", type: "forum" }])@@ -348,24 +300,22 @@ describe("GET /api/community/users/me/inbox/unreads", () => {// ── Per-post forum opener projection ──────────────────────────────────────- it("queries only visible, direct-unread, unmuted top-level forum parents", async () => {+ it("queries only visible top-level forum parents with eligible direct unread", async () => {mockListVisibleChannelIds.mockResolvedValue(["f1", "f2", "text1", "post1"])- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "f1", channelName: "Forum 1", type: "forum" }),- row({ channelId: "f2", channelName: "Muted forum", type: "forum" }),row({ channelId: "text1", channelName: "Text", type: "text" }),row({ channelId: "post1", channelName: "Post", type: "thread", parentChannelId: "f1" }),])- mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "f2", level: "nothing" }])await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "u1", ["f1", "f2", "text1", "post1"])+ expect(mockListEligibleUnreadChannels).toHaveBeenCalledWith(expect.anything(), "u1", ["f1", "f2", "text1", "post1"])expect(mockListUnreadForumOpeners).toHaveBeenCalledWith(expect.anything(), "u1", ["f1"])})it("renders every unread opener as a separately titled child row, newest first", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "f1", channelName: "Forum", type: "forum", lastMessageAt: "2026-06-25T11:00:00Z" }),])mockListUnreadForumOpeners.mockResolvedValue([@@ -386,16 +336,12 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("dedupes an unread opener and child replies by childChannelId while retaining the parent target", async () => {- mockListUnreadChannels.mockResolvedValue([- row({ channelId: "f1", channelName: "Forum", type: "forum", lastMessageAt: "2026-06-25T10:00:00Z" }),- row({ channelId: "p1", channelName: "Derived title", type: "thread", parentChannelId: "f1", lastMessageAt: "2026-06-25T12:00:00Z" }),- ])mockListUnreadForumOpeners.mockResolvedValue([opener({ title: "Canonical opener title", createdAt: "2026-06-25T10:00:00Z", openerSeq: 7 }),])- mockListUnreadMentions.mockResolvedValue([- { message: { channelId: "p1" } },- { message: { channelId: "p1" } },+ mockListEligibleUnreadChannels.mockResolvedValue([+ row({ channelId: "f1", channelName: "Forum", type: "forum", lastMessageAt: "2026-06-25T10:00:00Z" }),+ row({ channelId: "p1", channelName: "Derived title", type: "thread", parentChannelId: "f1", lastMessageAt: "2026-06-25T12:00:00Z", mentionCount: 2 }),])const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()@@ -411,7 +357,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {})it("uses canonical opener metadata when only a child reply is unread", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({channelId: "post_1",channelName: "stale derived title",@@ -440,35 +386,26 @@ describe("GET /api/community/users/me/inbox/unreads", () => {])})- it("prefilters muted server, parent, and child ids before canonical child lookup", async () => {- mockListUnreadChannels.mockResolvedValue([- row({ channelId: "post_server", serverId: "muted_server", parentChannelId: "forum_a", type: "thread" }),- row({ channelId: "post_parent", parentChannelId: "forum_muted", type: "thread" }),- row({ channelId: "post_child", parentChannelId: "forum_ok", type: "thread" }),+ it("looks up canonical opener metadata only for eligible child ids", async () => {+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "post_ok", parentChannelId: "forum_ok", type: "thread" }),])- mockGetSettings.mockResolvedValue([- { serverId: "muted_server", channelId: null, level: "nothing" },- { serverId: "s1", channelId: "forum_muted", level: "nothing" },- { serverId: "s1", channelId: "post_child", level: "nothing" },- ])await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))expect(mockListForumOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), ["post_ok"])})- it("drops opener rows whose child channel is individually muted", async () => {- mockListUnreadChannels.mockResolvedValue([+ it("renders no opener children when the eligible opener query returns none", async () => {+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "f1", channelName: "Forum", type: "forum" }),])- mockListUnreadForumOpeners.mockResolvedValue([opener()])- mockGetSettings.mockResolvedValue([{ serverId: null, channelId: "p1", level: "nothing" }])+ mockListUnreadForumOpeners.mockResolvedValue([])const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()expect(body.servers[0].channels[0].children).toEqual([])})it("uses opener seq/id as deterministic tie-breaks before child cap truncation", async () => {- mockListUnreadChannels.mockResolvedValue([+ mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "f1", channelName: "Forum", type: "forum" }),])mockListUnreadForumOpeners.mockResolvedValue([diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.tsindex 735f22528..c36f5ec55 100644--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts@@ -11,19 +11,6 @@ import { writeJSON } from "@/lib/middleware/helpers"import { parseBoundedInt } from "@/lib/community/messages"import { avatarInitial } from "@/lib/community/avatar"-function notificationMuteSets(- settings: Array<{ level: string; serverId: string | null; channelId: string | null }>,-) {- const mutedServers = new Set<string>()- const mutedChannels = new Set<string>()- for (const setting of settings) {- if (setting.level !== "nothing") continue- if (setting.channelId) mutedChannels.add(setting.channelId)- else if (setting.serverId) mutedServers.add(setting.serverId)- }- return { mutedServers, mutedChannels }-}-export const GET = withAuth(async (req, ctx) => {const db = getDb(ctx.env.DB)const url = new URL(req.url)@@ -36,38 +23,29 @@ export const GET = withAuth(async (req, ctx) => {// Resolve the viewer's visible channels once (top-level + child threads,// parent-climbed) and thread the id set into BOTH consumers so neither// recomputes it. Private threads under an invisible parent are excluded.- type UnreadRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadChannels>>[number]- type SettingRow = Awaited<ReturnType<typeof queries.communityNotificationSetting.getSettings>>[number]- type MentionRow = Awaited<ReturnType<typeof queries.communityMention.listUnreadMentions>>[number]- type UnreadDmRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadDms>>[number]+ type UnreadRow = Awaited<ReturnType<typeof queries.communityInbox.listEligibleUnreadChannels>>[number]+ type UnreadDmRow = Awaited<ReturnType<typeof queries.communityInbox.listEligibleUnreadDms>>[number]type ForumOpenerRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadForumOpeners>>[number]const { value: fetched, stale } = await readOrStale<{unread: UnreadRow[]- settings: SettingRow[]- mentions: MentionRow[]unreadDms: UnreadDmRow[]forumOpeners: ForumOpenerRow[]}>(async () => {const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)- const [unread, settings, mentions, unreadDms] = await Promise.all([- queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds),- queries.communityNotificationSetting.getSettings(db, ctx.userId),- queries.communityMention.listUnreadMentions(db, ctx.userId, { visibleChannelIds }),- queries.communityInbox.listUnreadDms(db, ctx.userId),+ const [unread, unreadDms] = await Promise.all([+ queries.communityInbox.listEligibleUnreadChannels(db, ctx.userId, visibleChannelIds),+ queries.communityInbox.listEligibleUnreadDms(db, ctx.userId),])- // Expand only top-level forum parents that have already passed the- // visibility and notification-mute gates. The shared query receives no- // global discovery surface — just this bounded parent id set.- const { mutedServers, mutedChannels } = notificationMuteSets(settings)+ // Expand only top-level forum parents that already have eligible unread.+ // The opener query applies the same current readability, cursor, policy,+ // and persisted-attention gate before returning individual post rows.const forumParentIds = [...new Set(unread.filter((row) =>!row.parentChannelId &&- row.type === "forum" &&- !mutedServers.has(row.serverId) &&- !mutedChannels.has(row.channelId),+ row.type === "forum",).map((row) => row.channelId),)]@@ -75,10 +53,7 @@ export const GET = withAuth(async (req, ctx) => {unread.filter((row) =>- !!row.parentChannelId &&- !mutedServers.has(row.serverId) &&- !mutedChannels.has(row.parentChannelId) &&- !mutedChannels.has(row.channelId),+ !!row.parentChannelId,).map((row) => row.channelId),)]@@ -89,24 +64,15 @@ export const GET = withAuth(async (req, ctx) => {const forumOpeners = [...new Map([...directForumOpeners, ...childForumOpeners].map((row) => [row.childChannelId, row]),).values()]- return { unread, settings, mentions, unreadDms, forumOpeners }+ return { unread, unreadDms, forumOpeners }},- { unread: [], settings: [], mentions: [], unreadDms: [], forumOpeners: [] },+ { unread: [], unreadDms: [], forumOpeners: [] },{ route: "community/inbox/unreads" },)if (stale) {return writeJSON({ servers: [], dms: [], limit, truncated: false, stale: true })}- const { unread, settings, mentions, unreadDms, forumOpeners } = fetched-- const { mutedServers, mutedChannels } = notificationMuteSets(settings)-- const mentionCountByChannel = new Map<string, number>()- for (const m of mentions) {- const cid = m.message.channelId- if (!cid) continue- mentionCountByChannel.set(cid, (mentionCountByChannel.get(cid) ?? 0) + 1)- }+ const { unread, unreadDms, forumOpeners } = fetched// Split unread rows into top-level channels and child threads.// A child nests under its `parentChannelId`; a parent surfaces in the tree@@ -140,26 +106,19 @@ export const GET = withAuth(async (req, ctx) => {for (const row of unread) {if (!row.serverId || !row.channelId || !row.serverName || !row.channelName) continue- if (mutedServers.has(row.serverId)) continueif (row.parentChannelId) {- // Child thread. Skip if the child itself is muted; the- // parent-mute cascade is applied later (once we know which parents are- // muted) so a child under a muted parent is dropped even if it isn't- // individually muted.- if (mutedChannels.has(row.channelId)) continueconst children = childrenByParent.get(row.parentChannelId) ?? new Map<string, UnreadChild>()children.set(row.channelId, {channelId: row.channelId,channelName: row.channelName,type: row.type,lastMessageAt: row.lastMessageAt,- mentionCount: mentionCountByChannel.get(row.channelId) ?? 0,+ mentionCount: row.mentionCount,sortSeq: 0,sortId: row.channelId,})childrenByParent.set(row.parentChannelId, children)} else {- if (mutedChannels.has(row.channelId)) continueparents.set(row.channelId, {channelId: row.channelId,channelName: row.channelName,@@ -167,7 +126,7 @@ export const GET = withAuth(async (req, ctx) => {serverId: row.serverId,serverName: row.serverName,lastMessageAt: row.lastMessageAt,- mentionCount: mentionCountByChannel.get(row.channelId) ?? 0,+ mentionCount: row.mentionCount,hasDirectUnread: true,children: [],})@@ -179,12 +138,11 @@ export const GET = withAuth(async (req, ctx) => {// while retaining the opener id as the parent forum's progressive-read// target. The authoritative title is supplied by the opener query.for (const opener of forumOpeners) {- if (mutedChannels.has(opener.childChannelId)) continueconst parent = parents.get(opener.forumChannelId)const unreadChild = unreadByChannelId.get(opener.childChannelId)if (!parent && unreadChild?.parentChannelId !== opener.forumChannelId) continueconst serverId = parent?.serverId ?? unreadChild?.serverId- if (!serverId || mutedServers.has(serverId) || mutedChannels.has(opener.forumChannelId)) continue+ if (!serverId) continueconst children = childrenByParent.get(opener.forumChannelId) ?? new Map<string, UnreadChild>()const existing = children.get(opener.childChannelId)@@ -203,7 +161,7 @@ export const GET = withAuth(async (req, ctx) => {channelName: opener.title,type: "thread",lastMessageAt: opener.createdAt,- mentionCount: mentionCountByChannel.get(opener.childChannelId) ?? 0,+ mentionCount: unreadChild?.mentionCount ?? 0,openerMessageId: opener.openerMessageId,sortSeq: opener.openerSeq,sortId: opener.openerMessageId,@@ -217,7 +175,7 @@ export const GET = withAuth(async (req, ctx) => {// no visibility filter, but that's fine: the child already passed visibility,// which implies the parent is visible. serverId/serverName come from the// child rows (they joined `communityServer`).- const missingParentIds = [...childrenByParent.keys()].filter((pid) => !parents.has(pid) && !mutedChannels.has(pid))+ const missingParentIds = [...childrenByParent.keys()].filter((pid) => !parents.has(pid))if (missingParentIds.length > 0) {const resolved = await withD1Retry(() => queries.communityChannel.getChannelsByIds(db, missingParentIds),@@ -227,7 +185,6 @@ export const GET = withAuth(async (req, ctx) => {for (const pid of missingParentIds) {const ch = resolvedById.get(pid)if (!ch) continue- if (mutedServers.has(ch.serverId)) continueparents.set(pid, {channelId: pid,channelName: ch.name,@@ -237,15 +194,15 @@ export const GET = withAuth(async (req, ctx) => {// below (those rows carry serverName via the communityServer join).serverName: "",lastMessageAt: "",- mentionCount: mentionCountByChannel.get(pid) ?? 0,+ mentionCount: 0,hasDirectUnread: false,children: [],})}}- // Attach children to their parents (dropping children whose parent is muted- // — the mute cascade — or whose parent couldn't be resolved).+ // Attach children to their parents. Parent/server policy inheritance was+ // already resolved in SQL for each child's eligible message set.for (const [pid, kids] of childrenByParent) {const parent = parents.get(pid)if (!parent) continue // parent muted or unresolved → drop the subtree@@ -345,10 +302,10 @@ export const GET = withAuth(async (req, ctx) => {}const truncated = total < grandTotal- // DMs are a flat list sorted most-recent first. DM notification settings- // don't exist today (`communityNotificationSetting` scopes are server/channel- // only), so no muting pass — every unread DM the viewer participates in- // surfaces. Blocked-user filtering intentionally stays off: DM messages+ // DMs are a flat list sorted most-recent first. A DM is a channel-scoped+ // notification unit, so `listEligibleUnreadDms` has already applied current+ // participation, cursor, policy, and attention. Blocked-user filtering stays+ // off intentionally: DM messages// route gates on `requireDMAccess`; an unread from a blocked user is still// the viewer's DM and should appear here.const dms = unreadDmsdiff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.tsnew file mode 100644index 000000000..3373efa42--- /dev/null+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts@@ -0,0 +1,48 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const requireMessageSurfaceAccess = vi.fn()+const setChannelLevel = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: () => ({}) }))+vi.mock("@/lib/community/permissions", () => ({+ requireMessageSurfaceAccess: (...args: unknown[]) => requireMessageSurfaceAccess(...args),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: { communityNotificationSetting: {+ setChannelLevel: (...args: unknown[]) => setChannelLevel(...args),+ removeChannelOverride: vi.fn(),+ } },+ }+})+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {+ env: { DB: {} }, userId: "user_1", email: "u@test", params: ctx.params,+ }),+}))++import { PUT } from "./route"++describe("human DM notification settings", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ requireMessageSurfaceAccess.mockResolvedValue({ ok: true, value: { surface: "dm" } })+ setChannelLevel.mockResolvedValue({ level: "mentions" })+ })++ it("uses the unified message-surface gate so DM block and participant checks apply", async () => {+ const request = new NextRequest("http://local", {+ method: "PUT",+ body: JSON.stringify({ level: "mentions" }),+ })+ const response = await PUT(request, { params: { id: "dm_1" } } as any)+ expect(response.status).toBe(200)+ expect(requireMessageSurfaceAccess).toHaveBeenCalledWith({}, "dm_1", "user_1")+ expect(setChannelLevel).toHaveBeenCalledWith({}, {+ userId: "user_1", channelId: "dm_1", level: "mentions",+ })+ })+})diff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.tsindex d4eee4f9e..58a60c3bf 100644--- a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts@@ -3,14 +3,14 @@ import { queries, NOTIFICATION_LEVEL_VALUES } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { requireChannelMember } from "@/lib/community/permissions"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"export const PUT = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.idif (!channelId) return writeError("missing channel id", 400)const db = getDb(ctx.env.DB)- const auth = await requireChannelMember(db, channelId, ctx.userId)+ const auth = await requireMessageSurfaceAccess(db, channelId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)let body: { level: string }@@ -38,7 +38,7 @@ export const DELETE = withAuth(async (_req, ctx) => {if (!channelId) return writeError("missing channel id", 400)const db = getDb(ctx.env.DB)- const auth = await requireChannelMember(db, channelId, ctx.userId)+ const auth = await requireMessageSurfaceAccess(db, channelId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)await queries.communityNotificationSetting.removeChannelOverride(db, {diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex 33406a565..1698d8d71 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -47,7 +47,10 @@ import {type ForumSidebarThread,} from "@/hooks/community/use-forum-sidebar-threads"import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"-import { useNotificationSettings } from "@/hooks/community/use-notification-settings"+import {+ resolveServerNotificationDisplayLevel,+ useNotificationSettings,+} from "@/hooks/community/use-notification-settings"import {useCreateChannel,useDeleteChannel,@@ -104,7 +107,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const presence = usePresence(serverId)const { online: initialOnline } = presenceconst notifs = useNotificationSettings()- const notifLevel = notifs.server[serverId] ?? notifLevelDisplay("mentions")+ const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])const channelNotif = notifs.channelconst currentChannelId = useCurrentChannelId()const currentChannelMeta = useCurrentChannelMeta()diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 8cec2138d..0478ffbca 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -47,6 +47,10 @@ import {advanceCommunityOnboarding,readCommunityOnboardingState,} from "@/lib/community-onboarding"+import { notifLevelDisplay, type NotifLevel } from "@alook/shared"+import { useNotificationSettings } from "@/hooks/community/use-notification-settings"+import { useSetChannelNotif } from "@/hooks/community/mutations"+import { toastApiError } from "@/lib/api/client"// Thin re-mount wrapper — same reason as the server-side channel view: the// dynamic segment reuses the same component instance across DM switches, so@@ -63,6 +67,8 @@ function DmView() {const currentUser = useCurrentUser()const currentChannelId = useCurrentChannelId()const uiHandlers = useUiHandlers()+ const notifications = useNotificationSettings()+ const setNotification = useSetChannelNotif()const { dms, isLoading: dmsLoading } = useDms()const { friends: rawFriends, blocked } = useFriends()@@ -370,7 +376,14 @@ function DmView() {return (<>- <DmHeader dm={dm} onBack={bp === "mobile" ? goBack : undefined} />+ <DmHeader+ dm={dm}+ onBack={bp === "mobile" ? goBack : undefined}+ notifLevel={(notifications.channel[dmId] ?? notifLevelDisplay("all")) as NotifLevel}+ onSetNotifLevel={(level) => setNotification.mutate({ channelId: dmId, level }, {+ onError: (error) => toastApiError(error, "Failed to update notification level"),+ })}+ /><main className="flex min-h-0 flex-1 flex-col"><MessageListkey={dmId}diff --git a/src/web/src/components/community/channels/dm-header.tsx b/src/web/src/components/community/channels/dm-header.tsxindex c33243910..6008b65af 100644--- a/src/web/src/components/community/channels/dm-header.tsx+++ b/src/web/src/components/community/channels/dm-header.tsx@@ -1,13 +1,17 @@-import { ChevronLeft } from "lucide-react"+import { Bell, BellOff, Check, ChevronLeft } from "lucide-react"+import { NOTIF_LEVELS, type NotifLevel } from "@alook/shared"import { Button } from "@/components/ui/button"+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "../avatar"import type { DM } from "@/lib/community/models/people"-export function DmHeader({ dm, onBack, titleAs: Title = "h1" }: {+export function DmHeader({ dm, onBack, titleAs: Title = "h1", notifLevel, onSetNotifLevel }: {dm: DMonBack?: () => voidtitleAs?: "h1" | "div"+ notifLevel?: NotifLevel+ onSetNotifLevel?: (level: NotifLevel) => void}) {return (<header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-3">@@ -23,10 +27,33 @@ export function DmHeader({ dm, onBack, titleAs: Title = "h1" }: {</span>)}</Title>+ {notifLevel && <DmNotifDropdown level={notifLevel} onSetLevel={onSetNotifLevel} />}</header>)}+function DmNotifDropdown({ level, onSetLevel }: { level: NotifLevel; onSetLevel?: (level: NotifLevel) => void }) {+ const muted = level === "Nothing"+ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={+ <Button variant="ghost" size="icon-sm" className={`ml-auto ${muted ? "text-destructive" : "text-muted-foreground"}`} aria-label="Direct message notifications" />+ }>+ {muted ? <BellOff className="size-4" /> : <Bell className="size-4" />}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-60">+ {NOTIF_LEVELS.map((option) => (+ <DropdownMenuItem key={option.value} onClick={() => onSetLevel?.(option.display)}>+ <span className="min-w-0 flex-1">{option.label}</span>+ {level === option.display && <Check className="size-4 text-primary" />}+ </DropdownMenuItem>+ ))}+ <div className="px-2 py-1.5 text-xs text-muted-foreground">Changes clear existing unread in this conversation.</div>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}+// Loading placeholder for <DmHeader> — same h-12 footprint so the body below// stays anchored across the route change.export function DmHeaderSkeleton({ onBack }: { onBack?: () => void }) {diff --git a/src/web/src/components/community/settings/server-settings-notifications.test.ts b/src/web/src/components/community/settings/server-settings-notifications.test.tsnew file mode 100644index 000000000..43dd740f6--- /dev/null+++ b/src/web/src/components/community/settings/server-settings-notifications.test.ts@@ -0,0 +1,57 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"++vi.mock("@/hooks/community/use-bots", () => ({+ useBots: () => ({ bots: [] }),+}))++vi.mock("@/hooks/community/use-notification-settings", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/hooks/community/use-notification-settings")>()+ return {+ ...actual,+ useBotNotificationSetting: () => ({ data: undefined, isError: false, isLoading: false }),+ useSetBotNotificationSetting: () => ({ mutate: vi.fn(), isPending: false }),+ }+})++import { SettingsNotifications } from "./server-settings"++function buttonText(node: TestRenderer.ReactTestInstance): string {+ return node+ .findAll((child) => typeof child.children?.[0] === "string")+ .flatMap((child) => child.children.filter((value): value is string => typeof value === "string"))+ .join(" ")+}++describe("SettingsNotifications server default", () => {+ const onSetLevel = vi.fn()++ beforeEach(() => {+ onSetLevel.mockReset()+ })++ it("shows All Messages for no setting row and sends the first explicit choice", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(SettingsNotifications, {+ serverId: "server_no_setting",+ level: undefined,+ onSetLevel,+ }),+ )+ })++ const buttons = renderer.root.findAllByType("button")+ const all = buttons.find((button) => buttonText(button).includes("Every message"))+ const mentions = buttons.find((button) => buttonText(button).includes("Mentions only"))++ expect(all?.props.className.split(/\s+/)).toContain("bg-accent")+ expect(mentions?.props.className.split(/\s+/)).not.toContain("bg-accent")++ act(() => mentions?.props.onClick())+ expect(onSetLevel).toHaveBeenCalledOnce()+ expect(onSetLevel).toHaveBeenCalledWith("Only @mentions")+ })+})diff --git a/src/web/src/components/community/settings/server-settings.tsx b/src/web/src/components/community/settings/server-settings.tsxindex 781b418d0..468022266 100644--- a/src/web/src/components/community/settings/server-settings.tsx+++ b/src/web/src/components/community/settings/server-settings.tsx@@ -29,6 +29,13 @@ import type { SettingsSection } from "@/components/community/settings/settings-timport type { Member, InviteRow } from "@/lib/community/models/people"import type { OpenProfile } from "@/components/community/social/profile-types"import { SettingsShell, SettingsShellPanel, type SettingsShellTab } from "./settings-shell"+import { useBots } from "@/hooks/community/use-bots"+import {+ resolveServerNotificationDisplayLevel,+ useBotNotificationSetting,+ useSetBotNotificationSetting,+} from "@/hooks/community/use-notification-settings"+import { toastApiError } from "@/lib/api/client"const SETTABLE_ROLES: Role[] = ["admin", "member"]@@ -102,7 +109,7 @@ export function ServerSettings({<SettingsShellPanel value="overview"><SettingsOverview serverId={serverId} serverName={serverName} serverDescription={serverDescription} serverIcon={serverIcon} onUploadIcon={onUploadIcon} onUpdateServer={onUpdateServer} onRequestDelete={() => setConfirmDelete(true)} /></SettingsShellPanel><SettingsShellPanel value="members"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></SettingsShellPanel><SettingsShellPanel value="invites"><SettingsInvites invites={invites} loading={invitesLoading} onRevokeInvite={onRevokeInvite} onCopyInvite={onCopyInvite} /></SettingsShellPanel>- <SettingsShellPanel value="notifications"><SettingsNotifications level={notifLevel ?? notifLevelDisplay("mentions")} onSetLevel={onSetNotifLevel} /></SettingsShellPanel>+ <SettingsShellPanel value="notifications"><SettingsNotifications serverId={serverId} level={notifLevel} onSetLevel={onSetNotifLevel} /></SettingsShellPanel></SettingsShell></>)@@ -364,25 +371,51 @@ function SettingsInvites({ invites, loading, onRevokeInvite, onCopyInvite }: {)}-function SettingsNotifications({ level, onSetLevel }: { level: string; onSetLevel?: (l: string) => void }) {+export function SettingsNotifications({ serverId, level, onSetLevel }: { serverId: string; level?: string; onSetLevel?: (l: string) => void }) {+ const { bots } = useBots()+ const [botId, setBotId] = useState<string | null>(null)+ const botSetting = useBotNotificationSetting(botId, { kind: "server", id: serverId })+ const setBotSetting = useSetBotNotificationSetting()+ const selectedLevel = botId+ ? notifLevelDisplay((botSetting.data?.level ?? "all") as "all" | "mentions" | "nothing")+ : resolveServerNotificationDisplayLevel(level)// Server-level dropdown = the three shared levels (no "Use Server Default"// sentinel — that's channel-only). Value/label/hint from the single source.- const levels: { value: string; label: string; hint: string }[] = NOTIF_LEVELS.map((l) => ({+ const levels = NOTIF_LEVELS.map((l) => ({value: l.display,+ raw: l.value,label: l.label,hint: l.value === "all" ? "Notify for every new message on this server" : l.hint,}))+ const update = (display: string, raw: "all" | "mentions" | "nothing") => {+ if (!botId) return onSetLevel?.(display)+ setBotSetting.mutate({ botId, scope: { kind: "server", id: serverId }, level: raw }, {+ onError: (error) => toastApiError(error, "Failed to update bot notifications"),+ })+ }return (<div className="mx-auto max-w-md space-y-2"><div className="mb-3 text-sm text-muted-foreground">Default notifications for this server</div>+ {bots.length > 0 && (+ <div className="mb-4 flex flex-wrap gap-1" aria-label="Notification actor">+ <Button size="sm" variant={botId === null ? "secondary" : "ghost"} onClick={() => setBotId(null)}>You</Button>+ {bots.map((bot) => (+ <Button key={bot.id} size="sm" variant={botId === bot.id ? "secondary" : "ghost"} onClick={() => setBotId(bot.id)}>{bot.name}</Button>+ ))}+ </div>+ )}+ {botId && botSetting.isError && (+ <div className="rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">This bot cannot access this server.</div>+ )}{levels.map((l) => (<buttonkey={l.value}- onClick={() => onSetLevel?.(l.value)}- className={`flex w-full items-center gap-3 rounded-md px-2 py-2 text-left transition-colors ${level === l.value ? "bg-accent" : "hover:bg-accent/40"}`}+ onClick={() => update(l.value, l.raw)}+ disabled={Boolean(botId && (botSetting.isLoading || botSetting.isError || setBotSetting.isPending))}+ className={`flex w-full items-center gap-3 rounded-md px-2 py-2 text-left transition-colors disabled:opacity-50 ${selectedLevel === l.value ? "bg-accent" : "hover:bg-accent/40"}`}>- <span className={`grid size-4 shrink-0 place-items-center rounded-full border ${level === l.value ? "border-primary" : "border-muted-foreground"}`}>- {level === l.value && <span className="size-2 rounded-full bg-primary" />}+ <span className={`grid size-4 shrink-0 place-items-center rounded-full border ${selectedLevel === l.value ? "border-primary" : "border-muted-foreground"}`}>+ {selectedLevel === l.value && <span className="size-2 rounded-full bg-primary" />}</span><div className="min-w-0 flex-1"><div className="text-sm font-medium">{l.label}</div>@@ -390,6 +423,7 @@ function SettingsNotifications({ level, onSetLevel }: { level: string; onSetLeve</div></button>))}+ <p className="pt-2 text-xs text-muted-foreground">Changing this setting clears existing unread in every affected channel.</p></div>)}diff --git a/src/web/src/hooks/community/mutations/notifications.test.ts b/src/web/src/hooks/community/mutations/notifications.test.tsnew file mode 100644index 000000000..86dc3c7cd--- /dev/null+++ b/src/web/src/hooks/community/mutations/notifications.test.ts@@ -0,0 +1,63 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"++const apiFetch = vi.fn()+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))++type MutationConfig = {+ onSuccess?: (data: unknown, args: any) => void+}+let config: MutationConfig | null = null+let queryClient: QueryClient++vi.mock("@tanstack/react-query", async () => {+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")+ return {+ ...actual,+ useQueryClient: () => queryClient,+ useMutation: (next: MutationConfig) => {+ config = next+ return {}+ },+ }+})++beforeEach(() => {+ vi.resetModules()+ config = null+ queryClient = new QueryClient()+})++describe("notification mutation cache refresh", () => {+ it("refreshes settings, inbox, and all read-state snapshots after a server change", async () => {+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")+ const { useSetServerNotifLevel } = await import("./notifications")+ useSetServerNotifLevel()+ config!.onSuccess?.(undefined, { serverId: "server_1", level: "Nothing" })++ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.notificationSettings() })+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.servers() })+ expect(invalidate).toHaveBeenCalledWith(expect.objectContaining({ predicate: expect.any(Function) }))+ })++ it("refreshes every read-state snapshot after a parent channel change", async () => {+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")+ const { useSetChannelNotif } = await import("./notifications")+ useSetChannelNotif()+ config!.onSuccess?.(undefined, { channelId: "parent_1", level: "Nothing" })++ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.servers() })+ const predicateCall = invalidate.mock.calls.find(+ ([filters]) => typeof filters?.predicate === "function",+ )+ const predicate = predicateCall?.[0].predicate+ expect(predicate).toBeTypeOf("function")+ expect(predicate!({ queryKey: communityKeys.channelReadStateSnapshot("parent_1") } as any)).toBe(true)+ expect(predicate!({ queryKey: communityKeys.channelReadStateSnapshot("child_1") } as any)).toBe(true)+ expect(predicate!({ queryKey: communityKeys.dmReadStateSnapshot("dm_1") } as any)).toBe(true)+ expect(predicate!({ queryKey: communityKeys.inbox() } as any)).toBe(false)+ })+})diff --git a/src/web/src/hooks/community/mutations/notifications.ts b/src/web/src/hooks/community/mutations/notifications.tsindex 41e8f2d39..b7db46cac 100644--- a/src/web/src/hooks/community/mutations/notifications.ts+++ b/src/web/src/hooks/community/mutations/notifications.ts@@ -44,6 +44,14 @@ export function useSetServerNotifLevel() {onError: (_err, _args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.notificationSettings(), ctx.snapshot)},+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: communityKeys.notificationSettings() })+ queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ queryClient.invalidateQueries({ queryKey: communityKeys.servers() })+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) => queryKey.includes("read-state-snapshot"),+ })+ },})}@@ -90,5 +98,13 @@ export function useSetChannelNotif() {onError: (_err, _args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.notificationSettings(), ctx.snapshot)},+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: communityKeys.notificationSettings() })+ queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ queryClient.invalidateQueries({ queryKey: communityKeys.servers() })+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) => queryKey.includes("read-state-snapshot"),+ })+ },})}diff --git a/src/web/src/hooks/community/use-notification-settings.test.ts b/src/web/src/hooks/community/use-notification-settings.test.tsindex baccf62ac..80c4fbe8b 100644--- a/src/web/src/hooks/community/use-notification-settings.test.ts+++ b/src/web/src/hooks/community/use-notification-settings.test.ts@@ -12,6 +12,12 @@ beforeEach(() => {})describe("useNotificationSettings / notificationSettingsQueryFn", () => {+ it("uses the backend-compatible all default when a server has no setting row", async () => {+ const { resolveServerNotificationDisplayLevel } = await import("./use-notification-settings")+ expect(resolveServerNotificationDisplayLevel(undefined)).toBe("All Messages")+ expect(resolveServerNotificationDisplayLevel("Only @mentions")).toBe("Only @mentions")+ })+it("groups rows into server/channel maps with display strings", async () => {apiFetchMock.mockResolvedValueOnce([{ serverId: "srv_1", channelId: null, level: "all" },diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.tsindex b2e9438c2..72d980a1b 100644--- a/src/web/src/hooks/community/use-notification-settings.ts+++ b/src/web/src/hooks/community/use-notification-settings.ts@@ -1,6 +1,6 @@"use client"-import { useQuery, type UseQueryResult } from "@tanstack/react-query"+import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"import { notifLevelDisplay } from "@alook/shared"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"@@ -34,6 +34,12 @@ const EMPTY_NOTIF_CHANNEL: Readonly<Record<string, string>> = Object.freeze({})// drifted on casing ("All Messages" vs the shared const's "All messages").const displayNotifLevel = notifLevelDisplay+const DEFAULT_SERVER_NOTIFICATION_LEVEL = notifLevelDisplay("all")++export function resolveServerNotificationDisplayLevel(level?: string): string {+ return level ?? DEFAULT_SERVER_NOTIFICATION_LEVEL+}+export const notificationSettingsQueryFn = async (): Promise<NotificationSettings> => {const rows = await apiFetch<NotificationSettingRow[]>("/api/community/users/me/notifications",@@ -62,3 +68,50 @@ export function useNotificationSettings(): UseQueryResult<NotificationSettings>channel: query.data?.channel ?? (EMPTY_NOTIF_CHANNEL as Record<string, string>),}}++export type BotNotificationScope = { kind: "server" | "channel"; id: string }++type BotNotificationSetting = { level: string | null }++export function useBotNotificationSetting(+ botId: string | null,+ scope: BotNotificationScope,+) {+ return useQuery({+ queryKey: communityKeys.botNotificationSetting(botId ?? "", scope.kind, scope.id),+ queryFn: () => apiFetch<BotNotificationSetting>(+ `/api/community/bots/${botId}/notifications/${scope.kind}/${scope.id}`,+ ),+ enabled: Boolean(botId),+ })+}++export function useSetBotNotificationSetting() {+ const queryClient = useQueryClient()+ return useMutation({+ mutationFn: async ({ botId, scope, level }: {+ botId: string+ scope: BotNotificationScope+ level: string | null+ }) => {+ const url = `/api/community/bots/${botId}/notifications/${scope.kind}/${scope.id}`+ if (level === null) {+ await apiFetch(url, { method: "DELETE" })+ } else {+ await apiFetch(url, {+ method: "PUT",+ body: JSON.stringify({ level }),+ })+ }+ },+ onSuccess: (_data, args) => {+ queryClient.invalidateQueries({+ queryKey: communityKeys.botNotificationSetting(args.botId, args.scope.kind, args.scope.id),+ })+ queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) => queryKey.includes("read-state-snapshot"),+ })+ },+ })+}diff --git a/src/web/src/lib/community/notify.test.ts b/src/web/src/lib/community/notify.test.tsindex 577643e83..12c8d47d2 100644--- a/src/web/src/lib/community/notify.test.ts+++ b/src/web/src/lib/community/notify.test.ts@@ -4,7 +4,7 @@ const mockInfo = vi.fn()const mockWarn = vi.fn()const mockWaitUntil = vi.fn()const mockGetCloudflareContext = vi.fn()-const mockResolveEffectiveLevelForUsers = vi.fn()+const mockResolveNotificationEligibilityForUsers = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: () => mockGetCloudflareContext(),@@ -22,8 +22,11 @@ vi.mock("@alook/shared", async () => {}),queries: {communityNotificationSetting: {- resolveEffectiveLevelForUsers: (...args: unknown[]) =>- mockResolveEffectiveLevelForUsers(...args),+ policyAllows: actual.queries.communityNotificationSetting.policyAllows,+ },+ communityNotificationEligibility: {+ resolveNotificationEligibilityForUsers: (...args: unknown[]) =>+ mockResolveNotificationEligibilityForUsers(...args),},},}@@ -37,7 +40,6 @@ vi.mock("../broadcast", () => ({import {dispatchMessageNotify,settleNotifyTasks,- shouldDeliver,} from "./notify"const db = {} as never@@ -60,22 +62,23 @@ function eventsOfType(type: string): Record<string, unknown>[] {.filter((event) => event.type === type)}-describe("shouldDeliver", () => {- it("delivers every all-level notification", () => {- expect(shouldDeliver("all", false)).toBe(true)- expect(shouldDeliver("all", true)).toBe(true)- })-- it("delivers mentions-level notifications only when mentioned", () => {- expect(shouldDeliver("mentions", false)).toBe(false)- expect(shouldDeliver("mentions", true)).toBe(true)- })-- it("never delivers nothing-level notifications", () => {- expect(shouldDeliver("nothing", false)).toBe(false)- expect(shouldDeliver("nothing", true)).toBe(false)- })-})+function deliveryStates(+ ids: string[],+ overrides: Partial<{+ currentLevel: "all" | "mentions" | "nothing"+ hasAttention: boolean+ isUnread: boolean+ isReadable: boolean+ }> = {},+) {+ return new Map(ids.map((id) => [id, {+ currentLevel: "all" as const,+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ ...overrides,+ }]))+}describe("settleNotifyTasks", () => {it.each([0, 1, 3, 4, 1001])(@@ -157,8 +160,8 @@ describe("dispatchMessageNotify", () => {})it("registers the returned work before the level resolver settles", async () => {- const levels = deferred<Map<string, "all">>()- mockResolveEffectiveLevelForUsers.mockReturnValue(levels.promise)+ const states = deferred<ReturnType<typeof deliveryStates>>()+ mockResolveNotificationEligibilityForUsers.mockReturnValue(states.promise)const work = dispatchMessageNotify(db, notifyContext, message, ["u1"], {mentionedUserIds: [],@@ -166,13 +169,15 @@ describe("dispatchMessageNotify", () => {expect(mockWaitUntil).toHaveBeenCalledWith(work)expect(mockBroadcastToUser).not.toHaveBeenCalled()- levels.resolve(new Map([["u1", "all"]]))+ states.resolve(deliveryStates(["u1"]))await workexpect(mockBroadcastToUser).toHaveBeenCalledTimes(1)})it("keeps aggregate work pending until every lazily started leaf settles", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(+ deliveryStates(["u0", "u1", "u2", "u3"]),+ )const gates = Array.from({ length: 4 }, () => deferred<void>())mockBroadcastToUser.mockImplementation(() => {const index = mockBroadcastToUser.mock.calls.length - 1@@ -211,7 +216,10 @@ describe("dispatchMessageNotify", () => {})it("builds mention tasks before deduplicated unread tasks", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ const states = deliveryStates(["u_plain", "u_mentioned", "u_extra"])+ states.set("u_mentioned", { ...states.get("u_mentioned")!, hasAttention: true })+ states.set("u_extra", { ...states.get("u_extra")!, hasAttention: true })+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(states)await dispatchMessageNotify(db,@@ -247,7 +255,9 @@ describe("dispatchMessageNotify", () => {})it("isolates one rejected leaf and continues remaining deliveries", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(+ deliveryStates(["u0", "u1", "u2", "u3"]),+ )mockBroadcastToUser.mockImplementation((userId: string) => (userId === "u1" ? Promise.reject(new Error("binding failed")) : Promise.resolve()))@@ -271,10 +281,10 @@ describe("dispatchMessageNotify", () => {})it("preserves all and mentions notification-level behavior", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([- ["u_all", "all"],- ["u_mentions_plain", "mentions"],- ["u_mentions_hit", "mentions"],+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([+ ["u_all", { currentLevel: "all", hasAttention: false, isUnread: true, isReadable: true }],+ ["u_mentions_plain", { currentLevel: "mentions", hasAttention: false, isUnread: true, isReadable: true }],+ ["u_mentions_hit", { currentLevel: "mentions", hasAttention: true, isUnread: true, isReadable: true }],]))await dispatchMessageNotify(@@ -295,7 +305,9 @@ describe("dispatchMessageNotify", () => {})it("suppresses nothing-level deliveries without emitting message-create", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["u_muted", "nothing"]]))+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([+ ["u_muted", { currentLevel: "nothing", hasAttention: true, isUnread: true, isReadable: true }],+ ]))await dispatchMessageNotify(db, notifyContext, message, ["u_muted"], {mentionedUserIds: ["u_muted"],@@ -308,18 +320,67 @@ describe("dispatchMessageNotify", () => {)})- it("defaults a missing level to all", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ it("fails closed when a recipient is missing from the delivery snapshot", async () => {+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map())await dispatchMessageNotify(db, notifyContext, message, ["u_dm"], {mentionedUserIds: [],})- expect(eventsOfType("community:unread.bump").map((event) => event.userId)).toEqual(["u_dm"])+ expect(mockBroadcastToUser).not.toHaveBeenCalled()+ })++ it("does not relight a message cleared before deferred notify, but delivers a newer unread", async () => {+ mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([+ ["u_mentioned", { currentLevel: "mentions", hasAttention: true, isUnread: false, isReadable: true }],+ ]))++ await dispatchMessageNotify(db, notifyContext, message, ["u_mentioned"], {+ mentionedUserIds: ["u_mentioned"],+ })+ expect(mockBroadcastToUser).not.toHaveBeenCalled()++ mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([+ ["u_mentioned", { currentLevel: "mentions", hasAttention: true, isUnread: true, isReadable: true }],+ ]))+ await dispatchMessageNotify(+ db,+ notifyContext,+ { id: "m2", channelId: "c1" },+ ["u_mentioned"],+ { mentionedUserIds: ["u_mentioned"] },+ )+ expect(mockBroadcastToUser.mock.calls.map((call) => (call[1] as { type: string }).type)).toEqual([+ "community:mention.create",+ "community:unread.bump",+ ])+ })++ it("does not notify a captured recipient after current access is revoked", async () => {+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([+ ["u_removed", { currentLevel: "all", hasAttention: true, isUnread: true, isReadable: false }],+ ]))++ await dispatchMessageNotify(db, notifyContext, message, ["u_removed"], {+ mentionedUserIds: ["u_removed"],+ })++ expect(mockBroadcastToUser).not.toHaveBeenCalled()++ await dispatchMessageNotify(+ db,+ notifyContext,+ { id: "m_after_revoke", channelId: "c1" },+ ["u_removed"],+ { mentionedUserIds: ["u_removed"] },+ )+ expect(mockBroadcastToUser).not.toHaveBeenCalled()})it("preserves optional unread routing fields", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ const states = deliveryStates(["u_plain", "u_mentioned"])+ states.set("u_mentioned", { ...states.get("u_mentioned")!, hasAttention: true })+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(states)await dispatchMessageNotify(db, notifyContext, message, ["u_plain", "u_mentioned"], {mentionedUserIds: ["u_mentioned"],@@ -338,7 +399,7 @@ describe("dispatchMessageNotify", () => {})it("omits optional unread routing fields for a direct message", async () => {- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(deliveryStates(["u_dm"]))await dispatchMessageNotify(db, notifyContext, message, ["u_dm"], {mentionedUserIds: [],@@ -351,7 +412,7 @@ describe("dispatchMessageNotify", () => {})it("absorbs a resolver failure and records its duration", async () => {- mockResolveEffectiveLevelForUsers.mockRejectedValue(new Error("d1 blip"))+ mockResolveNotificationEligibilityForUsers.mockRejectedValue(new Error("d1 blip"))const work = dispatchMessageNotify(db, notifyContext, message, ["u1"], {mentionedUserIds: [],@@ -374,7 +435,7 @@ describe("dispatchMessageNotify", () => {mockGetCloudflareContext.mockImplementation(() => {throw new Error("not in a request context")})- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(deliveryStates(["u1"]))await expect(dispatchMessageNotify(db,diff --git a/src/web/src/lib/community/notify.ts b/src/web/src/lib/community/notify.tsindex bd7b1b18c..f5788e310 100644--- a/src/web/src/lib/community/notify.ts+++ b/src/web/src/lib/community/notify.ts@@ -3,7 +3,7 @@* 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+ * recipient's current delivery state, 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`@@ -12,7 +12,7 @@* 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+ * shared delivery-state 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 —@@ -34,7 +34,7 @@*/import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, WS_EVENTS, createLogger } from "@alook/shared"-import type { Database, NotificationLevelValue, WsMessage } from "@alook/shared"+import type { Database, WsMessage } from "@alook/shared"import { broadcastToUser } from "../broadcast"const log = createLogger({ service: "community-notify" })@@ -105,12 +105,6 @@ export interface MessageNotifyContext {* (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@@ -149,19 +143,22 @@ async function runMessageNotify(const { channelId } = messageconst recipientIds = [...new Set(recipients)]const mentionedIds = [...new Set(opts.mentionedUserIds)]- const mentioned = new Set(mentionedIds)-const everyone = [...new Set([...recipientIds, ...mentionedIds])]- const levels = await queries.communityNotificationSetting.resolveEffectiveLevelForUsers(+ const delivery = await queries.communityNotificationEligibility.resolveNotificationEligibilityForUsers(db,everyone,- channelId,+ message.id,)- const levelOf = (userId: string): NotificationLevelValue => levels.get(userId) ?? "all"const tasks: NotifyLeafTask[] = []for (const userId of mentionedIds) {- if (!shouldDeliver(levelOf(userId), true)) continue+ const state = delivery.get(userId)+ if (+ !state?.isReadable ||+ !state.hasAttention ||+ !state.isUnread ||+ !queries.communityNotificationSetting.policyAllows(state.currentLevel, state.hasAttention)+ ) continuetasks.push({kind: "mention",userId,@@ -176,8 +173,12 @@ async function runMessageNotify(}for (const userId of recipientIds) {- const isMention = mentioned.has(userId)- if (!shouldDeliver(levelOf(userId), isMention)) continue+ const state = delivery.get(userId)+ if (+ !state?.isReadable ||+ !state.isUnread ||+ !queries.communityNotificationSetting.policyAllows(state.currentLevel, state.hasAttention)+ ) continuetasks.push({kind: "unread",userId,@@ -187,7 +188,7 @@ async function runMessageNotify(channelId,...(opts.serverId !== undefined ? { serverId: opts.serverId } : {}),...(opts.railChannelId !== undefined ? { railChannelId: opts.railChannelId } : {}),- isMention,+ isMention: state.hasAttention,},})}diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.tsindex 7db6f7d0a..90d78905a 100644--- a/src/web/src/lib/community/wake-producer.test.ts+++ b/src/web/src/lib/community/wake-producer.test.ts@@ -11,10 +11,15 @@ 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"])),+// Default: every bot passes the current-policy gate. Policy tests below+// override individual states.+const mockResolveNotificationEligibilityForUsers = vi.fn(+ async (_db: unknown, userIds: string[]) => new Map(userIds.map((id) => [id, {+ currentLevel: "all",+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ }])),)const mockWarn = vi.fn()const mockInfo = vi.fn()@@ -37,7 +42,11 @@ vi.mock("@alook/shared", async () => {canBotReadWakeScope: (...a: unknown[]) => mockCanBotReadWakeScope(...a),},communityNotificationSetting: {- resolveEffectiveLevelForUsers: (...a: unknown[]) => mockResolveEffectiveLevelForUsers(...(a as [unknown, string[]])),+ policyAllows: actual.queries.communityNotificationSetting.policyAllows,+ },+ communityNotificationEligibility: {+ resolveNotificationEligibilityForUsers: (...a: unknown[]) =>+ mockResolveNotificationEligibilityForUsers(...(a as [unknown, string[]])),},},}@@ -66,9 +75,19 @@ const messageRow = {dmConversationId: null,}+function defaultEligibility(_db: unknown, userIds: string[]) {+ return Promise.resolve(new Map(userIds.map((id) => [id, {+ currentLevel: "all",+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ }])))+}+describe("enqueueBotWakes", () => {beforeEach(() => {vi.clearAllMocks()+ mockResolveNotificationEligibilityForUsers.mockImplementation(defaultEligibility)mockQueueSend.mockResolvedValue(undefined)mockDevHttpSend.mockResolvedValue(undefined)// Default: every candidate passes the wake gate. Tests that need to@@ -135,7 +154,12 @@ describe("enqueueBotWakes", () => {mockFindWakeCandidates.mockResolvedValue([{ botUserId: "bot_muted", name: "z", machineId: "m1", runtime: "claude" },])- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["bot_muted", "nothing"]]))+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_muted", {+ currentLevel: "nothing",+ hasAttention: true,+ isUnread: true,+ isReadable: true,+ }]]))await enqueueBotWakes({recipients: ["bot_muted"],@@ -152,10 +176,10 @@ describe("enqueueBotWakes", () => {{ botUserId: "bot_mentioned", name: "a", machineId: "m1", runtime: "claude" },{ botUserId: "bot_plain", name: "b", machineId: "m2", runtime: "codex" },])- mockResolveEffectiveLevelForUsers.mockResolvedValue(+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([- ["bot_mentioned", "mentions"],- ["bot_plain", "mentions"],+ ["bot_mentioned", { currentLevel: "mentions", hasAttention: true, isUnread: true, isReadable: true }],+ ["bot_plain", { currentLevel: "mentions", hasAttention: false, isUnread: true, isReadable: true }],]),)@@ -175,7 +199,12 @@ describe("enqueueBotWakes", () => {mockFindWakeCandidates.mockResolvedValue([{ botUserId: "bot_all", name: "a", machineId: "m1", runtime: "claude" },])- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["bot_all", "all"]]))+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_all", {+ currentLevel: "all",+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ }]]))await enqueueBotWakes({recipients: ["bot_all"],@@ -193,8 +222,12 @@ describe("enqueueBotWakes", () => {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())+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_dm", {+ currentLevel: "all",+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ }]]))await enqueueBotWakes({recipients: ["bot_dm"],@@ -206,6 +239,50 @@ describe("enqueueBotWakes", () => {expect(mockQueueSend).toHaveBeenCalledTimes(1)})+ it("CURSOR GATE — a message cleared before deferred enqueue never wakes, while a newer unread does", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_1", name: "a", machineId: "m1", runtime: "claude" },+ ])+ mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([["bot_1", {+ currentLevel: "all",+ hasAttention: false,+ isUnread: false,+ isReadable: true,+ }]]))++ await enqueueBotWakes({ recipients: ["bot_1"], channelId: "c1", messageRow })+ expect(mockQueueSend).not.toHaveBeenCalled()++ mockResolveNotificationEligibilityForUsers.mockResolvedValueOnce(new Map([["bot_1", {+ currentLevel: "all",+ hasAttention: false,+ isUnread: true,+ isReadable: true,+ }]]))+ await enqueueBotWakes({+ recipients: ["bot_1"],+ channelId: "c1",+ messageRow: { ...messageRow, id: "msg_2", seq: 8 },+ })+ expect(mockQueueSend).toHaveBeenCalledWith([{ messageId: "msg_2", botUserId: "bot_1" }])+ })++ it("READABILITY GATE — a captured bot removed from the scope is dropped before enqueue", async () => {+ mockFindWakeCandidates.mockResolvedValue([+ { botUserId: "bot_removed", name: "a", machineId: "m1", runtime: "claude" },+ ])+ mockResolveNotificationEligibilityForUsers.mockResolvedValue(new Map([["bot_removed", {+ currentLevel: "all",+ hasAttention: true,+ isUnread: true,+ isReadable: false,+ }]]))++ await enqueueBotWakes({ recipients: ["bot_removed"], channelId: "c1", messageRow })++ expect(mockQueueSend).not.toHaveBeenCalled()+ })+it("retains a candidate when its producer prefilter rejects without collapsing the batch", async () => {// Regression guard: a transient D1 blip on ONE candidate's gate check// must not permanently lose that candidate. The consumer performs the@@ -322,6 +399,7 @@ describe("enqueueBotWakes — dev HTTP transport selection (NODE_ENV=developmentbeforeEach(() => {vi.clearAllMocks()+ mockResolveNotificationEligibilityForUsers.mockImplementation(defaultEligibility)mockQueueSend.mockResolvedValue(undefined)mockDevHttpSend.mockResolvedValue(undefined)process.env.NODE_ENV = "development"diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.tsindex 232507aaa..95a91ac66 100644--- a/src/web/src/lib/community/wake-producer.ts+++ b/src/web/src/lib/community/wake-producer.ts@@ -20,7 +20,6 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, createLogger, withD1Retry } 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"@@ -48,10 +47,9 @@ export interface EnqueueBotWakesOpts {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).+ * Compatibility hint carried by the fan-out call. The authoritative gate+ * deliberately rehydrates persisted mention/reply facts with current policy,+ * so a stale or incomplete in-memory set cannot change delivery.*/mentionedUserIds?: string[]}@@ -130,28 +128,25 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<v})if (gated.length === 0) return- // 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 withD1Retry(+ // Resolve current readability, read cursor, persisted attention, and policy+ // together so a deferred enqueue cannot relight cleared or revoked work.+ const eligibility = await withD1Retry(() =>- queries.communityNotificationSetting.resolveEffectiveLevelForUsers(+ queries.communityNotificationEligibility.resolveNotificationEligibilityForUsers(db,gated.map((c) => c.botUserId),- channelId,+ messageRow.id,),- { route: "wake-producer:effective-levels" },- )- const woken = gated.filter((c) =>- shouldDeliver(levels.get(c.botUserId) ?? "all", mentioned.has(c.botUserId)),+ { route: "wake-producer:notification-eligibility" },)+ const woken = gated.filter((c) => {+ const state = eligibility.get(c.botUserId)+ if (!state?.isReadable || !state.isUnread) return false+ return queries.communityNotificationSetting.policyAllows(+ state.currentLevel,+ state.hasAttention,+ )+ })if (woken.length === 0) returnconst payloads: WakePayload[] = woken.map((c) => ({diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex f4d3fa05e..7dd7e0878 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -135,6 +135,8 @@ export const communityKeys = {// ── Notification settings ───────────────────────────────────────────────notificationSettings: () =>[...communityKeys.all, "notification-settings"] as const,+ botNotificationSetting: (botId: string, scope: "server" | "channel", scopeId: string) =>+ [...communityKeys.all, "bot", botId, "notification-settings", scope, scopeId] as const,// ── Profile / user cards ────────────────────────────────────────────────profile: (userId: string) =>