Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): role-based category/channel permissions + private-channel visibility (#354)
Gener6b8402786285
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 94424ebaf..461efafb4 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -170,6 +170,26 @@ export type CommunityChannelReorder = {channels: { id: string; position: number }[]}+// ── Channel-member events (private-category channels) ─────────────────────────+//+// Sent to the affected user (so their sidebar gains/loses the channel) and to+// the existing channel members. The client invalidates the server-detail tree+// on receipt; the removed user additionally evicts that channel's caches.++export type CommunityChannelMemberAdd = {+ type: "community:channel.member_add"+ serverId: string+ channelId: string+ userId: string+}++export type CommunityChannelMemberRemove = {+ type: "community:channel.member_remove"+ serverId: string+ channelId: string+ userId: string+}+// ── Category events ───────────────────────────────────────────────────────────export type CommunityCategoryCreate = {@@ -456,6 +476,8 @@ export type CommunityWsEvent =| CommunityChannelUpdate| CommunityChannelDelete| CommunityChannelReorder+ | CommunityChannelMemberAdd+ | CommunityChannelMemberRemove| CommunityCategoryCreate| CommunityCategoryUpdate| CommunityCategoryDelete@@ -500,6 +522,8 @@ export const WS_EVENTS = {CHANNEL_UPDATE: "community:channel.update",CHANNEL_DELETE: "community:channel.delete",CHANNEL_REORDER: "community:channel.reorder",+ CHANNEL_MEMBER_ADD: "community:channel.member_add",+ CHANNEL_MEMBER_REMOVE: "community:channel.member_remove",CATEGORY_CREATE: "community:category.create",CATEGORY_UPDATE: "community:category.update",CATEGORY_DELETE: "community:category.delete",diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex ac4096aa9..991ce1bd8 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -75,6 +75,30 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(]);+// 3b. community_channel_member+// Explicit per-channel membership. Rows exist ONLY for channels in PRIVATE+// categories (creator + directly-added members). Public/uncategorized channels+// imply access via server membership and store nothing here; threads inherit+// their parent channel's audience and never get their own rows.+export const communityChannelMember = sqliteTable(+ "community_channel_member",+ {+ id: text("id").primaryKey().$defaultFn(() => nanoid()),+ channelId: text("channel_id")+ .notNull()+ .references(() => communityChannel.id, { onDelete: "cascade" }),+ userId: text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ addedBy: text("added_by").references(() => user.id, { onDelete: "set null" }),+ addedAt: text("added_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ (t) => [+ unique("uq_channel_member").on(t.channelId, t.userId),+ index("idx_channel_member_user").on(t.userId),+ ]+);+// 4. community_dm_conversationexport const communityDmConversation = sqliteTable("community_dm_conversation",diff --git a/src/shared/src/db/queries/community/category.ts b/src/shared/src/db/queries/community/category.tsindex d898fa3fc..77c73ba0d 100644--- a/src/shared/src/db/queries/community/category.ts+++ b/src/shared/src/db/queries/community/category.ts@@ -1,5 +1,5 @@-import { eq, inArray } from "drizzle-orm";-import { communityCategory } from "../../community-schema";+import { eq, inArray, count } from "drizzle-orm";+import { communityCategory, communityChannel } from "../../community-schema";import type { Database } from "../../index";export async function getCategoriesByIds(db: Database, categoryIds: string[]) {@@ -59,6 +59,20 @@ export async function deleteCategory(db: Database, categoryId: string) {return rows[0] ?? null;}+/**+ * Whether a category still contains any channel. Gates the private/public+ * toggle and category delete (both blocked when non-empty to prevent a+ * privacy-class flip / `set null` widening). See+ * plans/channel-category-role-permissions.md.+ */+export async function hasChannels(db: Database, categoryId: string): Promise<boolean> {+ const rows = await db+ .select({ cnt: count() })+ .from(communityChannel)+ .where(eq(communityChannel.categoryId, categoryId));+ return (rows[0]?.cnt ?? 0) > 0;+}+export async function reorderCategories(db: Database,serverId: string,diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex e896aa44d..e9c706be3 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -1,11 +1,14 @@-import { eq, and, asc, desc, isNull, max, inArray } from "drizzle-orm";+import { eq, and, or, asc, desc, isNull, isNotNull, max, inArray, count } from "drizzle-orm";import {communityChannel,+ communityCategory,+ communityChannelMember,communityServerMember,communityMessage,} from "../../community-schema";import type { Database } from "../../index";import { createLogger } from "../../../logger";+import { canManageServer, canSeePrivateChannel } from "../../../utils/community-roles";// Module-level logger — one tag per shared query module.const log = createLogger({ service: "community-queries" });@@ -55,6 +58,7 @@ function mapChannelRow<return { ...rest, tags: safeParseForumTags(forumTags, row.id) };}+export async function createChannel(db: Database,data: {@@ -93,9 +97,19 @@ export async function getChannel(db: Database, channelId: string) {return row ? mapChannelRow(row) : null;}+/**+ * Fetch a channel scoped to what `userId` may READ/POST — the read/post gate+ * used by every message-scoped route. Server membership is the base gate+ * (inner join); on top of that a channel in a PRIVATE category (or a thread+ * whose parent anchor is private) resolves only for a server admin/owner, the+ * anchor's creator, or a user with a `community_channel_member` row on the+ * anchor. Public/uncategorized channels resolve for any server member. Returns+ * null when the caller can't see it. Scope-first (AGENTS.md): the visibility+ * predicate is in SQL, not a post-fetch check.+ */export async function getChannelForMember(db: Database, channelId: string, userId: string) {const rows = await db- .select(CHANNEL_COLUMNS)+ .select({ ...CHANNEL_COLUMNS, memberRole: communityServerMember.role }).from(communityChannel).innerJoin(communityServerMember,@@ -106,7 +120,37 @@ export async function getChannelForMember(db: Database, channelId: string, userI).where(eq(communityChannel.id, channelId));const row = rows[0];- return row ? mapChannelRow(row) : null;+ if (!row) return null;+ const { memberRole, ...channelRow } = row;++ // Resolve the anchor (self for a top-level channel, parent for a thread) and+ // check its privacy + the viewer's access. Only runs the extra lookups when+ // the anchor is actually in a private category.+ const anchorId = channelRow.parentChannelId ?? channelRow.id;+ const anchor = await db+ .select({+ creatorId: communityChannel.creatorId,+ categoryPrivate: communityCategory.private,+ })+ .from(communityChannel)+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))+ .where(eq(communityChannel.id, anchorId))+ .limit(1);++ const isPrivate = (anchor[0]?.categoryPrivate ?? 0) === 1;+ if (isPrivate) {+ const isCreator = anchor[0]?.creatorId === userId;+ // Skip the member-row lookup when role/creator already grant access.+ const isMember =+ canManageServer(memberRole) || isCreator+ ? false+ : await isChannelMember(db, anchorId, userId);+ if (!canSeePrivateChannel({ role: memberRole, isCreator, isChannelMember: isMember })) {+ return null;+ }+ }++ return mapChannelRow(channelRow);}export async function updateChannel(@@ -189,24 +233,28 @@ export async function resolveChannelByNameForMember(/*** Top-level channels (no threads — `parentChannelId IS NULL`, mirroring- * `listServerChannels`) a bot can see via `listChannels`, scoped to server- * membership only — same visibility rule the human server-channels route- * uses (no extra private-category filter on read; decided in plan §7 v3).+ * `listServerChannels`) a viewer can see via `listChannels`, scoped to server+ * membership AND private-channel visibility: a channel in a PRIVATE category is+ * only returned if the viewer is an admin, the channel's creator, or has a+ * `community_channel_member` row for it. Public/uncategorized channels are+ * visible to any server member. This is the human-tree rule+ * (`listServerChannelsForViewer`) applied to the bot/agent surface.*/export async function listChannelsForMember(db: Database, serverId: string, userId: string) {- const rows = await db- .select(CHANNEL_COLUMNS)- .from(communityChannel)- .innerJoin(- communityServerMember,+ const member = await db+ .select({ role: communityServerMember.role })+ .from(communityServerMember)+ .where(and(- eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.serverId, serverId),eq(communityServerMember.userId, userId)))- .where(and(eq(communityChannel.serverId, serverId), isNull(communityChannel.parentChannelId)))- .orderBy(asc(communityChannel.position));- return rows.map(mapChannelRow);+ .limit(1);+ if (member.length === 0) return [];+ return listServerChannelsForViewer(db, serverId, userId, {+ isAdmin: canManageServer(member[0]!.role),+ });}/**@@ -257,7 +305,10 @@ export async function createThreadChannel() {const [parentServer, parentMessage] = await Promise.all([db- .select({ serverId: communityChannel.serverId })+ .select({+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ }).from(communityChannel).where(eq(communityChannel.id, parentChannelId)),db@@ -268,6 +319,18 @@ export async function createThreadChannel(const serverId = parentServer[0]?.serverId;if (!serverId) throw new Error(`createThreadChannel: parent channel ${parentChannelId} not found`);+ // A thread may only root on a TOP-LEVEL channel. Rooting on a child channel+ // (a forum post, or another thread) would make this a grandchild whose+ // privacy the single-level anchor climb can't resolve — it would read the+ // child's own `categoryId` (always NULL) as public and leak a private+ // forum's thread server-wide. Single chokepoint for every caller (web+ // threads route, agent send/resolve auto-thread, future callers).+ if (parentServer[0]?.parentChannelId) {+ throw new Error(+ `createThreadChannel: cannot root a thread on child channel ${parentChannelId}`+ );+ }+const rawContent = parentMessage[0]?.content?.trim() ?? "";const name = rawContent.length > 0 ? rawContent.slice(0, 40) : "Thread";@@ -351,3 +414,485 @@ export async function getChannelsByIds(db: Database, channelIds: string[]) {.where(inArray(communityChannel.id, channelIds));return rows.map(mapChannelRow);}++// ---------------------------------------------------------------------------+// Private-channel membership + visibility+// (plans/channel-category-role-permissions.md)+// ---------------------------------------------------------------------------++/**+ * A channel is PRIVATE when its (anchor's) category has `private = 1`.+ * Uncategorized channels (`categoryId IS NULL`) and channels in public+ * categories are both PUBLIC. Climbs `parentChannelId` first so a thread+ * inherits its parent's privacy (a thread's own `categoryId` is always NULL).+ */+export async function isChannelPrivate(db: Database, channelId: string): Promise<boolean> {+ const target = await db+ .select({+ id: communityChannel.id,+ parentChannelId: communityChannel.parentChannelId,+ })+ .from(communityChannel)+ .where(eq(communityChannel.id, channelId))+ .limit(1);+ if (target.length === 0) return false;+ const anchorId = target[0]!.parentChannelId ?? target[0]!.id;++ const rows = await db+ .select({ private: communityCategory.private })+ .from(communityChannel)+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))+ .where(eq(communityChannel.id, anchorId))+ .limit(1);+ return (rows[0]?.private ?? 0) === 1;+}++export async function createChannelMember(+ db: Database,+ data: { channelId: string; userId: string; addedBy?: string | null }+) {+ const rows = await db+ .insert(communityChannelMember)+ .values({+ channelId: data.channelId,+ userId: data.userId,+ addedBy: data.addedBy ?? null,+ })+ .onConflictDoNothing({+ target: [communityChannelMember.channelId, communityChannelMember.userId],+ })+ .returning();+ return rows[0] ?? null;+}++export async function deleteChannelMember(+ db: Database,+ channelId: string,+ userId: string+) {+ const rows = await db+ .delete(communityChannelMember)+ .where(+ and(+ eq(communityChannelMember.channelId, channelId),+ eq(communityChannelMember.userId, userId)+ )+ )+ .returning();+ return rows[0] ?? null;+}++/**+ * Members explicitly added to a channel, joined to `user` for display. Scoped+ * to one channel id — cross-channel ids never resolve.+ */+export async function listChannelMembers(db: Database, channelId: string) {+ return db+ .select({+ id: communityChannelMember.id,+ channelId: communityChannelMember.channelId,+ userId: communityChannelMember.userId,+ addedBy: communityChannelMember.addedBy,+ addedAt: communityChannelMember.addedAt,+ })+ .from(communityChannelMember)+ .where(eq(communityChannelMember.channelId, channelId))+ .orderBy(asc(communityChannelMember.addedAt));+}++export async function listChannelMemberUserIds(+ db: Database,+ channelId: string+): Promise<string[]> {+ const rows = await db+ .select({ userId: communityChannelMember.userId })+ .from(communityChannelMember)+ .where(eq(communityChannelMember.channelId, channelId));+ return rows.map((r) => r.userId);+}++export async function isChannelMember(+ db: Database,+ channelId: string,+ userId: string+): Promise<boolean> {+ const rows = await db+ .select({ id: communityChannelMember.id })+ .from(communityChannelMember)+ .where(+ and(+ eq(communityChannelMember.channelId, channelId),+ eq(communityChannelMember.userId, userId)+ )+ )+ .limit(1);+ return rows.length > 0;+}++export async function getChannelMemberCount(+ db: Database,+ channelId: string+): Promise<number> {+ const rows = await db+ .select({ cnt: count() })+ .from(communityChannelMember)+ .where(eq(communityChannelMember.channelId, channelId));+ return rows[0]?.cnt ?? 0;+}++export async function countChannelsInCategory(+ db: Database,+ categoryId: string+): Promise<number> {+ const rows = await db+ .select({ cnt: count() })+ .from(communityChannel)+ .where(eq(communityChannel.categoryId, categoryId));+ return rows[0]?.cnt ?? 0;+}++/**+ * The full recipient audience for a PRIVATE channel: explicit members ∪ the+ * anchor channel's creator ∪ every server admin/owner. Resolves the anchor+ * first (a thread — `parentChannelId` set — inherits its parent's audience).+ * Only meaningful for a private anchor; callers guard on `isChannelPrivate`+ * first (fan-out short-circuits public channels to `listMemberUserIds` and+ * never calls this). Called on a public/uncategorized anchor it would return+ * just admins + creator, NOT all members — do not use it as a public-channel+ * recipient resolver.+ */+export async function getPrivateChannelAudienceUserIds(+ db: Database,+ channelId: string+): Promise<string[]> {+ const target = await db+ .select({+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ })+ .from(communityChannel)+ .where(eq(communityChannel.id, channelId))+ .limit(1);+ if (target.length === 0) return [];+ const anchorId = target[0]!.parentChannelId ?? target[0]!.id;+ const serverId = target[0]!.serverId;++ // Anchor row: creator + its category privacy.+ const anchor = await db+ .select({+ creatorId: communityChannel.creatorId,+ categoryPrivate: communityCategory.private,+ })+ .from(communityChannel)+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))+ .where(eq(communityChannel.id, anchorId))+ .limit(1);+ if (anchor.length === 0) return [];++ // Server admins/owner always belong to the audience.+ const admins = await db+ .select({ userId: communityServerMember.userId })+ .from(communityServerMember)+ .where(+ and(+ eq(communityServerMember.serverId, serverId),+ or(+ eq(communityServerMember.role, "owner"),+ eq(communityServerMember.role, "admin")+ )+ )+ );+ const members = await listChannelMemberUserIds(db, anchorId);++ const set = new Set<string>();+ for (const a of admins) set.add(a.userId);+ for (const m of members) set.add(m);+ if (anchor[0]!.creatorId) set.add(anchor[0]!.creatorId as string);+ return [...set];+}++/**+ * Top-level channels a viewer may SEE in a server (backs the server-detail+ * tree). Rule, all in SQL (no JS post-filter):+ * - admin/owner → every top-level channel.+ * - otherwise → all public/uncategorized channels, PLUS private-category+ * channels where the viewer is the creator OR has a member row.+ * `parentChannelId IS NULL` (threads excluded, mirroring `listServerChannels`).+ */+export async function listServerChannelsForViewer(+ db: Database,+ serverId: string,+ userId: string,+ opts: { isAdmin: boolean }+) {+ const base = and(+ eq(communityChannel.serverId, serverId),+ isNull(communityChannel.parentChannelId)+ );++ if (opts.isAdmin) {+ const rows = await db+ .select(CHANNEL_COLUMNS)+ .from(communityChannel)+ .where(base)+ .orderBy(asc(communityChannel.position));+ return rows.map(mapChannelRow);+ }++ const rows = await db+ .select(CHANNEL_COLUMNS)+ .from(communityChannel)+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))+ .leftJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityChannel.id),+ eq(communityChannelMember.userId, userId)+ )+ )+ .where(+ and(+ base,+ or(+ // public / uncategorized+ isNull(communityChannel.categoryId),+ eq(communityCategory.private, 0),+ // private but visible to this viewer+ eq(communityChannel.creatorId, userId),+ isNotNull(communityChannelMember.id)+ )+ )+ )+ .orderBy(asc(communityChannel.position));+ return rows.map(mapChannelRow);+}++/**+ * The set of channel ids (top-level AND child/thread channels) a viewer may+ * see — backs read-path scoping for search / inbox / mark-all-read / mentions.+ * A thread inherits its parent's visibility, so it's included iff its+ * `parentChannelId` is in the visible top-level set. Scoping is done entirely+ * in SQL (the second query is scoped by the first's id set via `inArray`) —+ * no fetch-all-then-filter-in-JS leak.+ */+export async function listVisibleChannelIds(+ db: Database,+ serverId: string,+ userId: string,+ opts: { isAdmin: boolean }+): Promise<string[]> {+ if (opts.isAdmin) {+ const rows = await db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(eq(communityChannel.serverId, serverId));+ return rows.map((r) => r.id);+ }++ // Visible TOP-LEVEL channels: public/uncategorized ∪ private-where-viewer-is+ // creator-or-member.+ const topLevel = await db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))+ .leftJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityChannel.id),+ eq(communityChannelMember.userId, userId)+ )+ )+ .where(+ and(+ eq(communityChannel.serverId, serverId),+ isNull(communityChannel.parentChannelId),+ or(+ isNull(communityChannel.categoryId),+ eq(communityCategory.private, 0),+ eq(communityChannel.creatorId, userId),+ isNotNull(communityChannelMember.id)+ )+ )+ );+ const topLevelIds = topLevel.map((r) => r.id);+ if (topLevelIds.length === 0) return [];++ // Threads inherit from their parent: include children of visible top-level+ // channels (scoped by the id set — SQL, not JS). No `type` filter on the+ // children subquery, so forum_posts are covered alongside threads.+ const children = await db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(+ and(+ eq(communityChannel.serverId, serverId),+ inArray(communityChannel.parentChannelId, topLevelIds)+ )+ );+ return [...topLevelIds, ...children.map((r) => r.id)];+}++/**+ * Cross-server sibling of `listVisibleChannelIds` — every channel id (top-level+ * AND child/thread/forum-post) a viewer may see across ALL of their servers, in+ * a handful of queries instead of an N+1 loop-per-server. Backs the inbox+ * consumers (unread + mentions + mark-all), which span every server the viewer+ * belongs to.+ *+ * Same rule as the per-server form: admin/owner sees every channel in that+ * server; a non-admin sees public/uncategorized channels plus private-category+ * channels where they're the creator or have a member row. A child inherits its+ * parent's visibility (included iff its `parentChannelId` is in the visible+ * top-level set). Scoping is entirely in SQL.+ *+ * Bound-parameter ceiling (accepted risk): a viewer across many large servers+ * can produce a big id set; feeding it whole into a downstream `inArray`+ * approaches SQLite's bound-param limit. Same unchunked pattern as+ * `searchMessagesInServer` (single-server there, larger here). Chunk only if it+ * proves a real limit in practice.+ */+export async function listVisibleChannelIdsForUser(+ db: Database,+ userId: string+): Promise<string[]> {+ const memberships = await db+ .select({+ serverId: communityServerMember.serverId,+ role: communityServerMember.role,+ })+ .from(communityServerMember)+ .where(eq(communityServerMember.userId, userId));+ if (memberships.length === 0) return [];++ const adminServerIds: string[] = [];+ const memberServerIds: string[] = [];+ for (const m of memberships) {+ if (canManageServer(m.role)) adminServerIds.push(m.serverId);+ else memberServerIds.push(m.serverId);+ }++ const topLevelIds: string[] = [];++ // Admin servers: every top-level channel, no privacy filter.+ if (adminServerIds.length > 0) {+ const rows = await db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(+ and(+ inArray(communityChannel.serverId, adminServerIds),+ isNull(communityChannel.parentChannelId)+ )+ );+ for (const r of rows) topLevelIds.push(r.id);+ }++ // Member (non-admin) servers: public/uncategorized ∪ private-where-viewer-is+ // creator-or-member.+ if (memberServerIds.length > 0) {+ const rows = await db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))+ .leftJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityChannel.id),+ eq(communityChannelMember.userId, userId)+ )+ )+ .where(+ and(+ inArray(communityChannel.serverId, memberServerIds),+ isNull(communityChannel.parentChannelId),+ or(+ isNull(communityChannel.categoryId),+ eq(communityCategory.private, 0),+ eq(communityChannel.creatorId, userId),+ isNotNull(communityChannelMember.id)+ )+ )+ );+ for (const r of rows) topLevelIds.push(r.id);+ }++ if (topLevelIds.length === 0) return [];++ const children = await db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(inArray(communityChannel.parentChannelId, topLevelIds));+ return [...topLevelIds, ...children.map((r) => r.id)];+}++/**+ * Single joined row backing `requireChannelAccess` — resolves in ONE round+ * trip everything the access predicate needs: the target channel, its anchor+ * (self when top-level, parent when a thread), the anchor's category privacy,+ * the viewer's server-member role, and whether the viewer has a member row on+ * the anchor. Returns null when the channel doesn't exist OR the viewer isn't+ * a server member (the membership gate). `role`/`memberFlag` reflect the+ * anchor's server.+ */+export async function resolveChannelAccessContext(+ db: Database,+ channelId: string,+ userId: string+) {+ const target = await db+ .select(CHANNEL_COLUMNS)+ .from(communityChannel)+ .where(eq(communityChannel.id, channelId))+ .limit(1);+ if (target.length === 0) return null;+ const channel = mapChannelRow(target[0]!);+ const anchorId = channel.parentChannelId ?? channel.id;++ // Server-membership gate against the target's server.+ const member = await db+ .select({ role: communityServerMember.role })+ .from(communityServerMember)+ .where(+ and(+ eq(communityServerMember.serverId, channel.serverId),+ eq(communityServerMember.userId, userId)+ )+ )+ .limit(1);+ if (member.length === 0) return null;++ const anchorRows =+ anchorId === channel.id+ ? [target[0]!]+ : await db+ .select(CHANNEL_COLUMNS)+ .from(communityChannel)+ .where(eq(communityChannel.id, anchorId))+ .limit(1);+ if (anchorRows.length === 0) return null;+ const anchor = mapChannelRow(anchorRows[0]!);++ let categoryPrivate = 0;+ if (anchor.categoryId) {+ const cat = await db+ .select({ private: communityCategory.private })+ .from(communityCategory)+ .where(eq(communityCategory.id, anchor.categoryId))+ .limit(1);+ categoryPrivate = cat[0]?.private ?? 0;+ }++ const memberFlag =+ categoryPrivate === 1+ ? await isChannelMember(db, anchorId, userId)+ : false;++ return {+ channel,+ anchor,+ role: member[0]!.role,+ isPrivate: categoryPrivate === 1,+ isChannelMember: memberFlag,+ };+}diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex ba70c52cf..e006ac16b 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -1,4 +1,4 @@-import { and, eq, isNotNull, isNull, or } from "drizzle-orm";+import { and, eq, isNotNull, isNull, inArray, or } from "drizzle-orm";import {communityChannel,communityDmConversation,@@ -16,6 +16,9 @@ export interface UnreadChannelRow {serverName: string;lastMessageAt: string;lastReadAt: string | null;+ // null for a top-level channel; set for a thread / forum-post child. The+ // inbox route uses this to nest child unreads under their parent channel.+ parentChannelId: string | null;}/**@@ -52,16 +55,25 @@ export function isChannelUnread(row: {export async function listUnreadChannels(db: Database,- userId: string+ userId: string,+ visibleChannelIds: string[]): Promise<UnreadChannelRow[]> {- // All top-level channels in servers the user is a member of, plus read state.- // Filtering happens in JS via `isChannelUnread` so we can keep one query.+ // All channels — top-level AND child threads/forum-posts — the viewer may+ // see (the `visibleChannelIds` set, resolved once per inbox fetch via+ // `listVisibleChannelIdsForUser`), plus read state. Visibility is the id-set+ // `inArray`, NOT an inlined category `or()`: a child channel's own+ // `categoryId` is always NULL, so a flat `isNull(categoryId)` would treat+ // every thread as public and leak private threads. The id set is built by+ // parent-climbing, so a child is present only when its parent is visible.+ // Filtering to actually-unread happens in JS via `isChannelUnread`.+ if (visibleChannelIds.length === 0) return [];const rows = await db.select({channelId: communityChannel.id,channelName: communityChannel.name,serverId: communityChannel.serverId,serverName: communityServer.name,+ parentChannelId: communityChannel.parentChannelId,lastMessageAt: communityChannel.lastMessageAt,lastReadAt: communityReadState.lastReadAt,archived: communityChannel.archived,@@ -88,7 +100,7 @@ export async function listUnreadChannels(.where(and(eq(communityServerMember.userId, userId),- isNull(communityChannel.parentChannelId),+ inArray(communityChannel.id, visibleChannelIds),isNotNull(communityChannel.lastMessageAt)));@@ -107,6 +119,7 @@ export async function listUnreadChannels(channelName: r.channelName,serverId: r.serverId,serverName: r.serverName,+ parentChannelId: r.parentChannelId,lastMessageAt: r.lastMessageAt!,lastReadAt: r.lastReadAt,}));diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex f93f7bc1d..5c8f8ea0d 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -7,6 +7,8 @@ import {MAX_MEMBERS_PAGE_SIZE,} from "../../../constants/community";import { escapeLikePattern } from "../../../utils/sql-like";+import { canSeePrivateChannel } from "../../../utils/community-roles";+import { resolveChannelAccessContext } from "./channel";export async function addMember(db: Database,@@ -392,9 +394,12 @@ export async function removeOwnerBotsFromServer(* revoked, DM peer changed); this must return false rather than let the* caller wake a bot that lost access to the scope.*- * Thread scopes are ordinary `communityChannel` rows (own id, own- * `serverId`) — the same server-membership check as a top-level channel- * covers them, no separate thread-membership concept exists.+ * A channel in a PRIVATE category is only readable by the bot if it's the+ * channel creator or has a `community_channel_member` row (server admins too);+ * public/uncategorized channels need only server membership. Thread scopes are+ * ordinary `communityChannel` rows that inherit their parent's audience — the+ * shared `resolveChannelAccessContext` predicate climbs `parentChannelId`, so+ * this delegates to it rather than re-deriving the rule.*/export async function canBotReadWakeScope(db: Database,@@ -402,19 +407,14 @@ export async function canBotReadWakeScope(scope: { channelId?: string; dmConversationId?: string }): Promise<boolean> {if (scope.channelId) {- const rows = await db- .select({ serverId: communityChannel.serverId })- .from(communityChannel)- .innerJoin(- communityServerMember,- and(- eq(communityServerMember.serverId, communityChannel.serverId),- eq(communityServerMember.userId, botUserId)- )- )- .where(eq(communityChannel.id, scope.channelId))- .limit(1);- return rows.length > 0;+ const ctx = await resolveChannelAccessContext(db, scope.channelId, botUserId);+ if (!ctx) return false;+ if (!ctx.isPrivate) return true;+ return canSeePrivateChannel({+ role: ctx.role,+ isCreator: ctx.anchor.creatorId === botUserId,+ isChannelMember: ctx.isChannelMember,+ });}if (scope.dmConversationId) {const rows = await dbdiff --git a/src/shared/src/db/queries/community/mention.ts b/src/shared/src/db/queries/community/mention.tsindex e8a65ffc9..8a93c462f 100644--- a/src/shared/src/db/queries/community/mention.ts+++ b/src/shared/src/db/queries/community/mention.ts@@ -1,4 +1,4 @@-import { eq, and, inArray } from "drizzle-orm";+import { eq, and, inArray, desc } from "drizzle-orm";import { communityMention, communityMessage } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -26,13 +26,29 @@ export async function createMentions(export async function listUnreadMentions(db: Database,userId: string,- opts: { kind?: "mention" | "reply"; limit?: number } = {}+ opts: {+ kind?: "mention" | "reply";+ limit?: number;+ /**+ * Scope mentions to channels the viewer may see (scope-first, in-query —+ * NOT a post-fetch filter). Closes the removed-from-private-channel leak:+ * a user @-mentioned in a private channel then removed no longer sees that+ * mention. `NULL IN (...)` is never true in SQL, so DM reply rows+ * (`channelId = NULL`) are naturally excluded — which is intended, the+ * Mentions tab does not surface DM replies. Omitted → no channel scoping+ * (callers that don't need it, e.g. a single-kind agent read).+ */+ visibleChannelIds?: string[];+ } = {}) {const conditions = [eq(communityMention.userId, userId),eq(communityMention.read, 0),];if (opts.kind) conditions.push(eq(communityMention.kind, opts.kind));+ if (opts.visibleChannelIds) {+ conditions.push(inArray(communityMessage.channelId, opts.visibleChannelIds));+ }const q = db.select({@@ -46,7 +62,10 @@ export async function listUnreadMentions(eq(communityMention.messageId, communityMessage.id)).innerJoin(user, eq(communityMessage.authorId, user.id))- .where(and(...conditions));+ .where(and(...conditions))+ // Deterministic truncation: combining mention + reply kinds under a limit+ // needs an explicit order so the newest mentions win the cap.+ .orderBy(desc(communityMessage.createdAt));return opts.limit !== undefined ? q.limit(opts.limit) : q;}diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 1ea5c10d0..7a99cc859 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -589,6 +589,58 @@ export async function getLatestMessagesByChannelIds(return Array.from(bestByChannel.values());}+/**+ * DM sibling of `getLatestMessagesByChannelIds` — one latest row per DM+ * conversation that HAS messages (empty conversations omitted). Backs the+ * `markAllDmsRead` mass mark-read path; same MAX-per-scope subquery + id+ * dedupe as the channel form.+ */+export async function getLatestMessagesByDmIds(+ db: Database,+ dmConversationIds: string[]+): Promise<Array<{ dmConversationId: string; id: string; createdAt: string }>> {+ if (dmConversationIds.length === 0) return [];++ const latestDates = db+ .select({+ dmConversationId: communityMessage.dmConversationId,+ maxCreatedAt: sql<string>`MAX(${communityMessage.createdAt})`.as("max_created_at"),+ })+ .from(communityMessage)+ .where(inArray(communityMessage.dmConversationId, dmConversationIds))+ .groupBy(communityMessage.dmConversationId)+ .as("latest_dm_dates");++ const rows = await db+ .select({+ dmConversationId: communityMessage.dmConversationId,+ id: communityMessage.id,+ createdAt: communityMessage.createdAt,+ })+ .from(communityMessage)+ .innerJoin(+ latestDates,+ and(+ eq(communityMessage.dmConversationId, latestDates.dmConversationId),+ eq(communityMessage.createdAt, latestDates.maxCreatedAt)+ )+ );++ const bestByDm = new Map<string, { dmConversationId: string; id: string; createdAt: string }>();+ for (const r of rows) {+ if (!r.dmConversationId) continue;+ const existing = bestByDm.get(r.dmConversationId);+ if (!existing || r.id > existing.id) {+ bestByDm.set(r.dmConversationId, {+ dmConversationId: r.dmConversationId,+ id: r.id,+ createdAt: r.createdAt,+ });+ }+ }+ return Array.from(bestByDm.values());+}+export async function getFirstMessageByChannelIds(db: Database, channelIds: string[]) {if (channelIds.length === 0) return [];// Use a subquery to get the min createdAt per channel, then join to get the contentdiff --git a/src/shared/src/db/queries/community/read-state.ts b/src/shared/src/db/queries/community/read-state.tsindex 368b75b8d..d12808571 100644--- a/src/shared/src/db/queries/community/read-state.ts+++ b/src/shared/src/db/queries/community/read-state.ts@@ -1,11 +1,11 @@-import { eq, and, inArray, lt, sql } from "drizzle-orm";-import {- communityReadState,- communityChannel,- communityServerMember,-} from "../../community-schema";+import { eq, and, or, inArray, lt, sql } from "drizzle-orm";+import { communityReadState, communityDmConversation } from "../../community-schema";import type { Database } from "../../index";-import { getLatestMessagesByChannelIds, getMessageByChannelAndSeq } from "./message";+import {+ getLatestMessagesByChannelIds,+ getLatestMessagesByDmIds,+ getMessageByChannelAndSeq,+} from "./message";/*** # Community read-state invariant@@ -185,19 +185,19 @@ export async function markReadToMessage(// `markReadToMessageBuilder` above.export async function markAllServerChannelsRead(db: Database,- userId: string+ userId: string,+ visibleChannelIds: string[]): Promise<number> {- const channelRows = await db- .select({ channelId: communityChannel.id })- .from(communityServerMember)- .innerJoin(- communityChannel,- eq(communityChannel.serverId, communityServerMember.serverId)- )- .where(eq(communityServerMember.userId, userId));-- const channelIds = channelRows.map((r) => r.channelId);- if (channelIds.length === 0) return 0;+ // Scope to the channels the viewer may see — the same visible-id set the+ // inbox unread + mentions consumers use (resolved once per fetch via+ // `listVisibleChannelIdsForUser`). Convergence on the id set replaces the+ // old inlined category `or()`, which climbed nothing and so evaluated child+ // threads/forum-posts by their own (always-NULL) categoryId as public. The+ // id set parent-climbs, so a child under a private parent the viewer can't+ // see is now correctly EXCLUDED — mark-all no longer writes read-state rows+ // for channels behind an invisible private parent.+ if (visibleChannelIds.length === 0) return 0;+ const channelIds = visibleChannelIds;const latest = await getLatestMessagesByChannelIds(db, channelIds);if (latest.length === 0) return 0;@@ -278,6 +278,96 @@ export async function markAllServerChannelsRead(return latest.length;}+/**+ * DM sibling of `markAllServerChannelsRead`: mark every DM the viewer+ * participates in read at that conversation's latest message. Same invariant+ * (lastReadAt === message.createdAt AND lastReadMessageId = message.id), same+ * monotone guard, same "empty conversations are skipped, no row written"+ * semantics. Returns the count of conversations that actually got a write.+ */+// lastReadSeq intentionally not maintained here — see comment on+// `markReadToMessageBuilder` above.+export async function markAllDmsRead(+ db: Database,+ userId: string+): Promise<number> {+ const dmRows = await db+ .select({ id: communityDmConversation.id })+ .from(communityDmConversation)+ .where(+ or(+ eq(communityDmConversation.user1Id, userId),+ eq(communityDmConversation.user2Id, userId)+ )+ );+ const dmIds = dmRows.map((r) => r.id);+ if (dmIds.length === 0) return 0;++ const latest = await getLatestMessagesByDmIds(db, dmIds);+ if (latest.length === 0) return 0;++ // Existing rows for these DMs — split into UPDATE vs INSERT so we don't run+ // one query per conversation. Mirrors the channel path exactly.+ const existing = await db+ .select({+ id: communityReadState.id,+ dmConversationId: communityReadState.dmConversationId,+ })+ .from(communityReadState)+ .where(+ and(+ eq(communityReadState.userId, userId),+ inArray(+ communityReadState.dmConversationId,+ latest.map((l) => l.dmConversationId)+ )+ )+ );++ const existingByDm = new Map<string, string>();+ for (const row of existing) {+ if (row.dmConversationId) existingByDm.set(row.dmConversationId, row.id);+ }++ const toUpdate: Array<{ id: string; msgId: string; createdAt: string }> = [];+ const toInsert: Array<{ dmConversationId: string; msgId: string; createdAt: string }> = [];+ for (const l of latest) {+ const existingId = existingByDm.get(l.dmConversationId);+ if (existingId) {+ toUpdate.push({ id: existingId, msgId: l.id, createdAt: l.createdAt });+ } else {+ toInsert.push({ dmConversationId: l.dmConversationId, msgId: l.id, createdAt: l.createdAt });+ }+ }++ // Monotone guard mirrors `markAllServerChannelsRead`.+ for (const u of toUpdate) {+ await db+ .update(communityReadState)+ .set({ lastReadAt: u.createdAt, lastReadMessageId: u.msgId })+ .where(+ and(+ eq(communityReadState.id, u.id),+ lt(communityReadState.lastReadAt, u.createdAt)+ )+ );+ }++ if (toInsert.length > 0) {+ await db.insert(communityReadState).values(+ toInsert.map((i) => ({+ userId,+ channelId: null,+ dmConversationId: i.dmConversationId,+ lastReadAt: i.createdAt,+ lastReadMessageId: i.msgId,+ }))+ );+ }++ return latest.length;+}+/*** The agent `ack` route's cursor-advance — the ONLY writer of `lastReadSeq`* outside `createMessage`'s author-watermark upsert (design §4). `Cursor =diff --git a/src/shared/src/db/queries/community/search.ts b/src/shared/src/db/queries/community/search.tsindex 91e8dbcbe..9d1d2f5c7 100644--- a/src/shared/src/db/queries/community/search.ts+++ b/src/shared/src/db/queries/community/search.ts@@ -1,4 +1,4 @@-import { eq, and, sql } from "drizzle-orm";+import { eq, and, inArray, sql } from "drizzle-orm";import { communityMessage, communityChannel } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -25,6 +25,10 @@ export async function searchMessages(channelId?: string;dmConversationId?: string;serverId?: string;+ // Scope for the server branch — the caller's visible channel ids+ // (public/uncategorized ∪ private-where-member). Enforced in SQL so+ // private-channel content never leaks into server-wide search results.+ visibleChannelIds?: string[];limit?: number;}) {@@ -34,6 +38,7 @@ export async function searchMessages(return searchMessagesInServer(db, {query: opts.query,serverId: opts.serverId,+ visibleChannelIds: opts.visibleChannelIds,limit,});}@@ -63,12 +68,27 @@ export async function searchMessagesInServer(opts: {query: string;serverId: string;+ // The caller's visible channel ids — scopes the search so private-channel+ // content the viewer can't see never appears. `undefined` means "not+ // scoped" (internal/trusted callers only); the community search route+ // ALWAYS passes it. An empty array yields zero results.+ visibleChannelIds?: string[];limit?: number;}) {const limit = opts.limit ?? DEFAULT_LIMIT;+ if (opts.visibleChannelIds && opts.visibleChannelIds.length === 0) return [];+const pattern = `%${escapeLikePattern(opts.query)}%`;+ const conditions = [+ sql`${communityMessage.content} LIKE ${pattern} ESCAPE '\\'`,+ eq(communityChannel.serverId, opts.serverId),+ ];+ if (opts.visibleChannelIds) {+ conditions.push(inArray(communityMessage.channelId, opts.visibleChannelIds));+ }+return db.select({message: communityMessage,@@ -80,11 +100,6 @@ export async function searchMessagesInServer(communityChannel,eq(communityMessage.channelId, communityChannel.id))- .where(- and(- sql`${communityMessage.content} LIKE ${pattern} ESCAPE '\\'`,- eq(communityChannel.serverId, opts.serverId)- )- )+ .where(and(...conditions)).limit(limit);}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 80736fd11..187d02d3e 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -499,6 +499,7 @@ export { truncateTitle } from "./utils/title";export {canManageServer,isServerOwner,+ canSeePrivateChannel,isAssignableRole,isChannelType,ROLES,diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.tsindex 2b6e2063a..81f41a127 100644--- a/src/shared/src/utils/community-roles.ts+++ b/src/shared/src/utils/community-roles.ts@@ -20,6 +20,22 @@ export function isServerOwner(role?: string | null): boolean {return role === ROLES.OWNER}+/**+ * The single private-channel visibility rule, shared by both access predicates+ * (`getChannelForMember` — read/post path — and `requireChannelAccess` /+ * `resolveChannelAccessContext` — manage path) plus `canBotReadWakeScope`, so+ * the rule can never drift between them. A server admin/owner, the anchor's+ * creator, or an explicit channel member may see a private channel. Callers+ * only invoke this once they know the anchor is private. Pure.+ */+export function canSeePrivateChannel(input: {+ role: string | null | undefined+ isCreator: boolean+ isChannelMember: boolean+}): boolean {+ return canManageServer(input.role) || input.isCreator || input.isChannelMember+}+export function isAssignableRole(role: unknown): role is AssignableRole {return typeof role === "string" && (ASSIGNABLE_ROLES as readonly string[]).includes(role)}diff --git a/src/shared/test/queries/community-channel-access.test.ts b/src/shared/test/queries/community-channel-access.test.tsnew file mode 100644index 000000000..64d2ed5c2--- /dev/null+++ b/src/shared/test/queries/community-channel-access.test.ts@@ -0,0 +1,131 @@+import { describe, it, expect, vi } from "vitest";++vi.mock("../../src/logger", () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++import * as channelQueries from "../../src/db/queries/community/channel";+import { canSeePrivateChannel } from "../../src/utils/community-roles";++function channelRow(over: Record<string, unknown> = {}) {+ return {+ id: "c1",+ serverId: "s1",+ categoryId: null,+ name: "chan",+ type: "text",+ topic: "",+ position: 0,+ forumTags: null,+ parentChannelId: null,+ creatorId: "creator",+ messageCount: 0,+ archived: 0,+ parentMessageId: null,+ lastMessageAt: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ ...over,+ };+}++/**+ * Sequenced select mock: `queue` holds the resolved rows for each select() in+ * call order. getChannelForMember issues: (1) channel+member join → (2) anchor+ * + category-private join → (3, optional) isChannelMember lookup.+ */+function makeSeqDb(queue: any[][]) {+ let i = 0;+ const db: any = {+ select: vi.fn(() => {+ const rows = queue[i++] ?? [];+ const chain: any = {};+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => Object.assign(Promise.resolve(rows), chain));+ chain.limit = vi.fn(() => Promise.resolve(rows));+ chain.orderBy = vi.fn(() => Promise.resolve(rows));+ return chain;+ }),+ };+ return db;+}++describe("canSeePrivateChannel — shared rule", () => {+ it("admin/owner sees it regardless of membership", () => {+ expect(canSeePrivateChannel({ role: "admin", isCreator: false, isChannelMember: false })).toBe(true)+ expect(canSeePrivateChannel({ role: "owner", isCreator: false, isChannelMember: false })).toBe(true)+ })+ it("creator sees it", () => {+ expect(canSeePrivateChannel({ role: "member", isCreator: true, isChannelMember: false })).toBe(true)+ })+ it("added member sees it", () => {+ expect(canSeePrivateChannel({ role: "member", isCreator: false, isChannelMember: true })).toBe(true)+ })+ it("unrelated member cannot", () => {+ expect(canSeePrivateChannel({ role: "member", isCreator: false, isChannelMember: false })).toBe(false)+ })+})++describe("getChannelForMember — private visibility", () => {+ it("non-server-member → null (empty join)", async () => {+ const db = makeSeqDb([[]]);+ expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();+ });++ it("public channel → returns the channel for any member", async () => {+ const db = makeSeqDb([+ [{ ...channelRow({ categoryId: null }), memberRole: "member" }],+ [{ creatorId: "creator", categoryPrivate: 0 }],+ ]);+ const res = await channelQueries.getChannelForMember(db, "c1", "u1");+ expect(res?.id).toBe("c1");+ });++ it("private channel + non-member, non-creator, non-admin → null", async () => {+ const db = makeSeqDb([+ [{ ...channelRow({ categoryId: "cat1" }), memberRole: "member" }],+ [{ creatorId: "creator", categoryPrivate: 1 }],+ [], // isChannelMember → no row+ ]);+ expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();+ });++ it("private channel + admin → returns the channel without a member row", async () => {+ const db = makeSeqDb([+ [{ ...channelRow({ categoryId: "cat1" }), memberRole: "admin" }],+ [{ creatorId: "creator", categoryPrivate: 1 }],+ ]);+ const res = await channelQueries.getChannelForMember(db, "c1", "u1");+ expect(res?.id).toBe("c1");+ });++ it("private channel + creator → returns the channel", async () => {+ const db = makeSeqDb([+ [{ ...channelRow({ categoryId: "cat1", creatorId: "u1" }), memberRole: "member" }],+ [{ creatorId: "u1", categoryPrivate: 1 }],+ ]);+ const res = await channelQueries.getChannelForMember(db, "c1", "u1");+ expect(res?.id).toBe("c1");+ });++ it("private channel + added member → returns the channel", async () => {+ const db = makeSeqDb([+ [{ ...channelRow({ categoryId: "cat1" }), memberRole: "member" }],+ [{ creatorId: "creator", categoryPrivate: 1 }],+ [{ id: "cm1" }], // isChannelMember → row present+ ]);+ const res = await channelQueries.getChannelForMember(db, "c1", "u1");+ expect(res?.id).toBe("c1");+ });++ it("strips the joined memberRole from the returned row", async () => {+ const db = makeSeqDb([+ [{ ...channelRow(), memberRole: "member" }],+ [{ creatorId: "creator", categoryPrivate: 0 }],+ ]);+ const res = await channelQueries.getChannelForMember(db, "c1", "u1");+ expect(res).not.toHaveProperty("memberRole");+ expect(res).toHaveProperty("tags");+ });+});diff --git a/src/shared/test/queries/community-channel-tags.test.ts b/src/shared/test/queries/community-channel-tags.test.tsindex dac86dc88..025a10fa9 100644--- a/src/shared/test/queries/community-channel-tags.test.ts+++ b/src/shared/test/queries/community-channel-tags.test.ts@@ -42,6 +42,7 @@ function createSelectMock(rows: any[]) {chain.innerJoin = vi.fn(() => chain);chain.leftJoin = vi.fn(() => chain);chain.where = vi.fn(() => terminal());+ chain.limit = vi.fn(() => Promise.resolve(rows));chain.orderBy = vi.fn(() => Promise.resolve(rows));return chain;}diff --git a/src/shared/test/queries/community-channel-threads.test.ts b/src/shared/test/queries/community-channel-threads.test.tsindex 37dd19558..35c2fcb04 100644--- a/src/shared/test/queries/community-channel-threads.test.ts+++ b/src/shared/test/queries/community-channel-threads.test.ts@@ -101,4 +101,15 @@ describe("createThreadChannel", () => {const db = createMockDb({ selectResponses: [[], [{ content: "hi" }]], insertedId: "x" });await expect(createThreadChannel(db, "ch_missing", "m_root", "u_1")).rejects.toThrow(/not found/);});++ it("throws when the parent is itself a child channel (forum post / thread) — no grandchild threads, closes the private-forum leak", async () => {+ const db = createMockDb({+ // parent-channel lookup returns a row whose own parentChannelId is set →+ // it's a forum_post/thread, not a top-level channel.+ selectResponses: [[{ serverId: "srv_1", parentChannelId: "forum_1" }], [{ content: "hi" }]],+ insertedId: "x",+ });+ await expect(createThreadChannel(db, "forum_post_1", "m_root", "u_1")).rejects.toThrow(/child channel/);+ expect(db.__insertValues).not.toHaveBeenCalled();+ });});diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex fd5a63bf7..ae201c05e 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -142,13 +142,14 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {channelName: "channel A",serverId: "srv_1",serverName: "server 1",+ parentChannelId: null,lastMessageAt: ts,lastReadAt: ts, // author's watermark advanced to this exact messagearchived: false,joinedAt: j,},]);- const result = await inboxQueries.listUnreadChannels(db, "u_author");+ const result = await inboxQueries.listUnreadChannels(db, "u_author", ["ch_A"]);expect(result).toEqual([]);});@@ -165,13 +166,14 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {channelName: "channel A",serverId: "srv_1",serverName: "server 1",+ parentChannelId: null,lastMessageAt: t2,lastReadAt: t1,archived: false,joinedAt: j,},]);- const result = await inboxQueries.listUnreadChannels(db, "u_author");+ const result = await inboxQueries.listUnreadChannels(db, "u_author", ["ch_A"]);expect(result).toHaveLength(1);expect(result[0]!.channelId).toBe("ch_A");expect(result[0]!.lastMessageAt).toBe(t2);@@ -185,13 +187,14 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {channelName: "old",serverId: "srv_1",serverName: "server 1",+ parentChannelId: null,lastMessageAt: "2026-07-06T00:00:00.000Z",lastReadAt: null,archived: true,joinedAt: j,},]);- const result = await inboxQueries.listUnreadChannels(db, "u_1");+ const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_archived"]);expect(result).toEqual([]);});@@ -204,13 +207,14 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {channelName: "brand new",serverId: "srv_1",serverName: "server 1",+ parentChannelId: null,lastMessageAt: "2026-07-06T00:01:00.000Z",lastReadAt: null,archived: false,joinedAt: j,},]);- const result = await inboxQueries.listUnreadChannels(db, "u_1");+ const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_new"]);expect(result).toHaveLength(1);expect(result[0]!.channelId).toBe("ch_new");});@@ -225,13 +229,14 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {channelName: "old history",serverId: "srv_1",serverName: "server 1",+ parentChannelId: null,lastMessageAt: "2026-07-05T00:00:00.000Z", // predates joinedAtlastReadAt: null,archived: false,joinedAt: j,},]);- const result = await inboxQueries.listUnreadChannels(db, "u_1");+ const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_old"]);expect(result).toEqual([]);});});diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.tsindex 951c3b70f..637955ee6 100644--- a/src/shared/test/queries/community-message.test.ts+++ b/src/shared/test/queries/community-message.test.ts@@ -1080,25 +1080,20 @@ describe("read-state invariant property — every write path", () => {});// Path F: markAllServerChannelsRead — one channel with a latest message,- // no existing row → insert path.+ // no existing row → insert path. The visible-channel id set is passed as an+ // argument now, so the only select this issues is the existing-read-state+ // lookup (returns empty → insert path).const dbF: any = makePropertyDb();- // Rewire the two selects: first returns member channels, second returns- // existing readState rows. All other selects fall through to the default- // empty-select chain in makePropertyDb.- let selectCall = 0;dbF.select = vi.fn(() => {const chain: any = {};chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);chain.groupBy = vi.fn(() => chain);chain.as = vi.fn(() => chain);chain.orderBy = vi.fn(() => chain);chain.limit = vi.fn(() => Promise.resolve([]));- chain.where = vi.fn(() => {- selectCall += 1;- if (selectCall === 1) return Promise.resolve([{ channelId: "c_mass" }]);- return Promise.resolve([]);- });+ chain.where = vi.fn(() => Promise.resolve([]));return chain;});const spy = vi@@ -1106,7 +1101,7 @@ describe("read-state invariant property — every write path", () => {.mockResolvedValue([{ channelId: "c_mass", id: "m_mass_latest", createdAt: "2026-07-06T00:00:00.000Z" },]);- await readState.markAllServerChannelsRead(dbF, "u_1");+ await readState.markAllServerChannelsRead(dbF, "u_1", ["c_mass"]);spy.mockRestore();// The invariant assertion: every captured write must have BOTH fieldsdiff --git a/src/shared/test/queries/community-read-state.test.ts b/src/shared/test/queries/community-read-state.test.tsindex a91e48256..63df0fb90 100644--- a/src/shared/test/queries/community-read-state.test.ts+++ b/src/shared/test/queries/community-read-state.test.ts@@ -167,42 +167,28 @@ function makeMassMarkDbMock(opts: {const updates: Array<{ id: string; set: any }> = [];const inserts: any[] = [];- // The db has two select shapes we need to fake:- // 1. select({channelId: communityChannel.id}).from(communityServerMember).innerJoin(communityChannel).where(...)- // → returns [{channelId}] rows (member channels).- // 2. select({...}).from(communityMessage) via getLatestMessagesByChannelIds- // → we intercept the batched helper instead by using vi.spyOn on the module.- // 3. select({id, channelId}).from(communityReadState).where(...) → existing rows.- //- // Since we can't easily distinguish select shapes on a chain mock, we drive- // by call order: first select is member channels, second is existing rows.- let selectCall = 0;+ // Post-id-set convergence, `markAllServerChannelsRead` takes the visible+ // channel id set as an ARGUMENT (no member-channel select of its own). The+ // only select it now issues is the existing-read-state-rows lookup:+ // select({id, channelId}).from(communityReadState).where(...) → existing rows.+ // (`getLatestMessagesByChannelIds` is intercepted via vi.spyOn.)const db: any = {select: vi.fn(() => {const chain: any = {};chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);chain.groupBy = vi.fn(() => chain);chain.as = vi.fn(() => chain);- chain.where = vi.fn(() => {- selectCall += 1;- if (selectCall === 1) {- return Promise.resolve(opts.memberChannelIds.map((c) => ({ channelId: c })));- }- if (selectCall === 2) {- // Second select is the getLatestMessagesByChannelIds subquery-inner- // — but our spy intercepts that helper directly, so this branch is- // reached ONLY for the existing-rows select.- return Promise.resolve(- opts.existingReadStateChannels.map((c, i) => ({- id: `rs_${i}_${c}`,- channelId: c,- }))- );- }- return Promise.resolve([]);- });+ chain.where = vi.fn(() =>+ Promise.resolve(+ opts.existingReadStateChannels.map((c, i) => ({+ id: `rs_${i}_${c}`,+ channelId: c,+ }))+ )+ );return chain;}),update: vi.fn(() => ({@@ -240,7 +226,7 @@ describe("markAllServerChannelsRead", () => {const messageModule = await import("../../src/db/queries/community/message");const spy = vi.spyOn(messageModule, "getLatestMessagesByChannelIds").mockResolvedValue([]);- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1");+ const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", []);expect(count).toBe(0);expect(db.__updates).toHaveLength(0);expect(db.__inserts).toHaveLength(0);@@ -257,7 +243,7 @@ describe("markAllServerChannelsRead", () => {// Every channel is empty — the batched helper returns nothing.const spy = vi.spyOn(messageModule, "getLatestMessagesByChannelIds").mockResolvedValue([]);- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1");+ const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b"]);expect(count).toBe(0);// The invariant: empty channels get no row.expect(db.__updates).toHaveLength(0);@@ -278,7 +264,7 @@ describe("markAllServerChannelsRead", () => {{ channelId: "c_b", id: "m_b_latest", createdAt: "2026-07-05T11:00:00Z" },]);- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1");+ const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b", "c_c_empty"]);expect(count).toBe(2);expect(db.__updates).toHaveLength(0);// One batched insert containing both rows.@@ -316,7 +302,7 @@ describe("markAllServerChannelsRead", () => {{ channelId: "c_b", id: "m_b_new", createdAt: "2026-07-05T11:00:00Z" },]);- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1");+ const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b"]);expect(count).toBe(2);// Two UPDATEs, no INSERT.expect(db.__updates).toHaveLength(2);@@ -350,7 +336,7 @@ describe("markAllServerChannelsRead", () => {{ channelId: "c_a", id: "m_a_new", createdAt: "2026-07-05T10:00:00Z" },]);- await readStateQueries.markAllServerChannelsRead(db, "u_1");+ await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a"]);// A raw eq(id, ...) is a Drizzle SQL fragment; a guarded and(eq(...), lt(...))// is a distinct fragment. We can't evaluate them structurally without// spinning up SQLite, but the WHERE clause is definitely not undefineddiff --git a/src/web/migrations/0056_community_channel_member.sql b/src/web/migrations/0056_community_channel_member.sqlnew file mode 100644index 000000000..73a0f2975--- /dev/null+++ b/src/web/migrations/0056_community_channel_member.sql@@ -0,0 +1,21 @@+-- Per-channel membership for PRIVATE-category channels.+-- See plans/channel-category-role-permissions.md.+--+-- Rows exist ONLY for channels in private categories (creator + directly-added+-- members). Public/uncategorized channels imply access via server membership;+-- threads inherit their parent channel's audience and never get their own rows.+-- Not yet deployed → no backfill; new visibility rules apply going forward.++CREATE TABLE community_channel_member (+ id TEXT PRIMARY KEY,+ channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ added_by TEXT REFERENCES user(id) ON DELETE SET NULL,+ added_at TEXT NOT NULL+);++-- One membership row per (channel, user).+CREATE UNIQUE INDEX uq_channel_member ON community_channel_member(channel_id, user_id);++-- Reverse lookup: which private channels a user belongs to (viewer-scoped tree).+CREATE INDEX idx_channel_member_user ON community_channel_member(user_id);diff --git a/src/web/src/app/api/community/agent/listChannels/route.ts b/src/web/src/app/api/community/agent/listChannels/route.tsindex c73a3214e..1e2a085e5 100644--- a/src/web/src/app/api/community/agent/listChannels/route.ts+++ b/src/web/src/app/api/community/agent/listChannels/route.ts@@ -11,8 +11,8 @@ import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-aut* `listMembers` uses), or omit to list across every server the bot is in.* Top-level channels only (`listChannelsForMember` filters* `parentChannelId IS NULL`, mirroring `listServerChannels`) — same- * visibility rule a human server-channels route uses, no extra- * private-category filter on read.+ * visibility rule a human sees: private-category channels appear only when the+ * bot is an admin, the channel's creator, or an added member.** Response items are `{ ref, name, type }` (plan §Decisions #12) — `ref` is* directly reusable as `--channel`/`--target` on every other command, anddiff --git a/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts b/src/web/src/app/api/community/channels/[id]/addable-members/route.test.tsnew file mode 100644index 000000000..1c1717ea7--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts@@ -0,0 +1,91 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++const mockResolveChannelAccessContext = vi.fn()+const mockListMembers = vi.fn()+const mockListChannelMemberUserIds = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityChannel: {+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),+ listChannelMemberUserIds: (...a: unknown[]) => mockListChannelMemberUserIds(...a),+ },+ communityMember: { listMembers: (...a: unknown[]) => mockListMembers(...a) },+ },+ }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { GET } from "./route"++const ctx = { params: { id: "c1" } } as any+function req() {+ return new NextRequest("http://localhost/api/community/channels/c1/addable-members")+}++function managerCtx() {+ return {+ channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ role: "member",+ isPrivate: true,+ isChannelMember: true,+ }+}++describe("GET /channels/[id]/addable-members", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockResolveChannelAccessContext.mockResolvedValue(managerCtx())+ mockListMembers.mockResolvedValue([+ { userId: "u1", userName: "Creator", userImage: null, discriminator: "0001" },+ { userId: "u2", userName: "Bob", userImage: null, discriminator: "0002" },+ { userId: "u3", userName: "Cara", userImage: null, discriminator: "0003" },+ ])+ mockListChannelMemberUserIds.mockResolvedValue(["u2"])+ })++ it("excludes existing channel members and the creator", async () => {+ const res = await GET(req(), ctx)+ expect(res.status).toBe(200)+ const body = await res.json()+ const ids = body.members.map((m: { userId: string }) => m.userId)+ expect(ids).toEqual(["u3"]) // u1 = creator, u2 = already member+ })++ it("rejects a non-manager (403)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue({+ ...managerCtx(),+ channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" },+ role: "member",+ isChannelMember: true,+ })+ const res = await GET(req(), ctx)+ expect(res.status).toBe(403)+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/addable-members/route.ts b/src/web/src/app/api/community/channels/[id]/addable-members/route.tsnew file mode 100644index 000000000..2166ac3c8--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/addable-members/route.ts@@ -0,0 +1,42 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { requireChannelAccess } from "@/lib/community/permissions"+import { avatarInitial } from "@/lib/community/avatar"++/**+ * Server members who are NOT yet in this private-category channel — backs the+ * "add members" picker. Only creator/admins (canManage) may see it. Scoped by+ * subtracting the channel roster from the server member list server-side (a+ * stale client cache can't leak the wrong set).+ */+export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const channelId = ctx.params?.id+ if (!channelId) return writeError("missing channel id", 400)++ const db = getDb(ctx.env.DB)+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (!access.value.canManage) return writeError("forbidden", 403)++ const channel = access.value.channel+ const [members, channelMemberIds] = await Promise.all([+ queries.communityMember.listMembers(db, channel.serverId),+ queries.communityChannel.listChannelMemberUserIds(db, channelId),+ ])+ const inChannel = new Set(channelMemberIds)+ if (channel.creatorId) inChannel.add(channel.creatorId)++ const addable = members+ .filter((m) => !inChannel.has(m.userId))+ .map((m) => ({+ userId: m.userId,+ name: m.userName,+ discriminator: m.discriminator,+ avatar: m.userImage ?? avatarInitial(m.userName ?? ""),+ }))++ return writeJSON({ members: addable })+})diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.tsnew file mode 100644index 000000000..4f80302b0--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts@@ -0,0 +1,103 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++const mockResolveChannelAccessContext = vi.fn()+const mockDeleteChannelMember = vi.fn()+const mockGetPrivateChannelAudienceUserIds = vi.fn()+const mockBroadcastToUserSafe = vi.fn()+const mockLogAudit = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityChannel: {+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),+ deleteChannelMember: (...a: unknown[]) => mockDeleteChannelMember(...a),+ getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),+ },+ },+ }+})++vi.mock("@/lib/community/fanout", () => ({+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),+}))+vi.mock("@/lib/community/audit", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { DELETE } from "./route"++function req() {+ return new NextRequest("http://localhost/api/community/channels/c1/members/u2", { method: "DELETE" })+}+const ctx = { params: { id: "c1", userId: "u2" } } as any++function managerCtx(creatorId = "u1") {+ return {+ channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId },+ role: "member",+ isPrivate: true,+ isChannelMember: true,+ }+}++describe("DELETE /channels/[id]/members/[userId]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockResolveChannelAccessContext.mockResolvedValue(managerCtx())+ mockDeleteChannelMember.mockResolvedValue({ id: "cm1" })+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"])+ })++ it("creator/admin removes a member", async () => {+ const res = await DELETE(req(), ctx)+ expect(res.status).toBe(204)+ expect(mockDeleteChannelMember).toHaveBeenCalledWith(expect.anything(), "c1", "u2")+ expect(mockBroadcastToUserSafe).toHaveBeenCalled()+ })++ it("cannot remove the creator (400)", async () => {+ const res = await DELETE(+ new NextRequest("http://localhost/api/community/channels/c1/members/u1", { method: "DELETE" }),+ { params: { id: "c1", userId: "u1" } } as any,+ )+ expect(res.status).toBe(400)+ expect(mockDeleteChannelMember).not.toHaveBeenCalled()+ })++ it("rejects a non-manager (403)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue({+ ...managerCtx("other"),+ isChannelMember: true,+ role: "member",+ })+ const res = await DELETE(req(), ctx)+ expect(res.status).toBe(403)+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.tsnew file mode 100644index 000000000..b0e5908ef--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts@@ -0,0 +1,56 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries, WS_EVENTS } from "@alook/shared"+import { broadcastToUserSafe } from "@/lib/community/fanout"+import { logAudit } from "@/lib/community/audit"+import { requireChannelAccess } from "@/lib/community/permissions"++/**+ * Remove a member from a private-category channel. Only creator/admins+ * (canManage) may remove, and the channel creator can never be removed (they+ * always retain access). The removed user gets a CHANNEL_MEMBER_REMOVE so+ * their sidebar drops the channel + evicts its caches.+ */+export const DELETE = withAuth(async (_req: NextRequest, ctx) => {+ const channelId = ctx.params?.id+ const targetUserId = ctx.params?.userId+ if (!channelId || !targetUserId) return writeError("missing params", 400)++ const db = getDb(ctx.env.DB)+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (!access.value.canManage) return writeError("forbidden", 403)++ const channel = access.value.channel+ if (channel.creatorId === targetUserId) {+ return writeError("can't remove the channel creator", 400)+ }++ const removed = await queries.communityChannel.deleteChannelMember(db, channelId, targetUserId)+ if (!removed) return writeError("member not found", 404)++ const event = {+ type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,+ serverId: channel.serverId,+ channelId,+ userId: targetUserId,+ } as const+ // Notify the removed user (drop the channel) plus the remaining audience.+ const recipients = await queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId)+ await Promise.all(+ [...new Set([...recipients, targetUserId])].map((uid) => broadcastToUserSafe(uid, event))+ )++ logAudit(db, {+ serverId: channel.serverId,+ actorId: ctx.userId,+ action: "channel_member_remove",+ targetType: "channel",+ targetId: channelId,+ changes: JSON.stringify({ userId: targetUserId }),+ })++ return new Response(null, { status: 204 })+})diff --git a/src/web/src/app/api/community/channels/[id]/members/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/route.test.tsnew file mode 100644index 000000000..9814e9c80--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/members/route.test.ts@@ -0,0 +1,151 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++const mockResolveChannelAccessContext = vi.fn()+const mockGetMember = vi.fn()+const mockCreateChannelMember = vi.fn()+const mockListChannelMembers = vi.fn()+const mockGetPrivateChannelAudienceUserIds = vi.fn()+const mockGetUsersByIds = vi.fn()+const mockBroadcastToUserSafe = vi.fn()+const mockLogAudit = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityChannel: {+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),+ createChannelMember: (...a: unknown[]) => mockCreateChannelMember(...a),+ listChannelMembers: (...a: unknown[]) => mockListChannelMembers(...a),+ getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),+ },+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },+ user: { getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a) },+ },+ }+})++vi.mock("@/lib/community/fanout", () => ({+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),+}))+vi.mock("@/lib/community/audit", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { GET, POST } from "./route"++const ctx = { params: { id: "c1" } } as any+function postReq(body: unknown) {+ return new NextRequest("http://localhost/api/community/channels/c1/members", {+ method: "POST",+ body: JSON.stringify(body),+ })+}++// A private top-level channel the caller can manage.+function managerCtx() {+ return {+ channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ role: "member",+ isPrivate: true,+ isChannelMember: true,+ }+}++describe("GET /channels/[id]/members", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockResolveChannelAccessContext.mockResolvedValue(managerCtx())+ mockListChannelMembers.mockResolvedValue([{ userId: "u1", addedBy: "u1", addedAt: "t", channelId: "c1", id: "cm1" }])+ mockGetUsersByIds.mockResolvedValue([{ id: "u1", name: "Ann", image: null, discriminator: "0001" }])+ })++ it("lists members for a caller with access", async () => {+ const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.members[0].userId).toBe("u1")+ expect(body.members[0].isCreator).toBe(true)+ })++ it("403 for a caller without access", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(null)+ const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)+ expect(res.status).toBe(403)+ })+})++describe("POST /channels/[id]/members", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockResolveChannelAccessContext.mockResolvedValue(managerCtx())+ mockGetMember.mockResolvedValue({ id: "m2", userId: "u2", role: "member" })+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"])+ })++ it("adds an existing server member", async () => {+ const res = await POST(postReq({ userId: "u2" }), ctx)+ expect(res.status).toBe(201)+ expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), {+ channelId: "c1", userId: "u2", addedBy: "u1",+ })+ })++ it("rejects adding a non-server-member (400)", async () => {+ mockGetMember.mockResolvedValue(null)+ const res = await POST(postReq({ userId: "u2" }), ctx)+ expect(res.status).toBe(400)+ expect(mockCreateChannelMember).not.toHaveBeenCalled()+ })++ it("rejects a non-manager (403)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue({ ...managerCtx(), creatorId: "other", channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" }, anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" }, isChannelMember: true, role: "member" })+ const res = await POST(postReq({ userId: "u2" }), ctx)+ expect(res.status).toBe(403)+ })++ it("rejects adding to a public/uncategorized channel (400)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ role: "admin", isPrivate: false, isChannelMember: false,+ })+ const res = await POST(postReq({ userId: "u2" }), ctx)+ expect(res.status).toBe(400)+ })++ it("rejects adding on a thread channel (400)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "t1", serverId: "s1", parentChannelId: "c1", creatorId: "u1" },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ role: "admin", isPrivate: true, isChannelMember: true,+ })+ const res = await POST(postReq({ userId: "u2" }), { params: { id: "t1" } } as any)+ expect(res.status).toBe(400)+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.tsnew file mode 100644index 000000000..b7be62950--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts@@ -0,0 +1,107 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries, WS_EVENTS } from "@alook/shared"+import { broadcastToUserSafe } from "@/lib/community/fanout"+import { logAudit } from "@/lib/community/audit"+import { requireChannelAccess } from "@/lib/community/permissions"+import { avatarInitial } from "@/lib/community/avatar"++/**+ * List the explicit members of a private-category channel. Any caller with+ * access to the channel may read the roster (creator, added members, admins).+ */+export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const channelId = ctx.params?.id+ if (!channelId) return writeError("missing channel id", 400)++ const db = getDb(ctx.env.DB)+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)++ const rows = await queries.communityChannel.listChannelMembers(db, channelId)+ const users = await queries.user.getUsersByIds(db, rows.map((r) => r.userId))+ const byId = new Map(users.map((u) => [u.id, u]))+ const creatorId = access.value.channel.creatorId++ const members = rows.map((r) => {+ const u = byId.get(r.userId)+ return {+ userId: r.userId,+ name: u?.name ?? null,+ discriminator: u?.discriminator ?? null,+ avatar: u?.image ?? avatarInitial(u?.name ?? ""),+ addedAt: r.addedAt,+ isCreator: r.userId === creatorId,+ }+ })++ return writeJSON({ members })+})++/**+ * Add a server member to a private-category channel. Only the creator/admins+ * (canManage) may add. The target must be an existing server member, and the+ * channel must be a top-level channel in a PRIVATE category (threads inherit+ * their parent's roster — their own `categoryId` is NULL — so they're rejected).+ */+export const POST = withAuth(async (req: NextRequest, ctx) => {+ const channelId = ctx.params?.id+ if (!channelId) return writeError("missing channel id", 400)++ const db = getDb(ctx.env.DB)+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (!access.value.canManage) return writeError("forbidden", 403)++ const channel = access.value.channel+ if (channel.parentChannelId) {+ return writeError("threads inherit their parent channel's members", 400)+ }+ // Top-level channel → its anchor is itself, so `isPrivate` reflects its own+ // category. Public/uncategorized channels have no explicit roster.+ if (!access.value.isPrivate) {+ return writeError("channel is not in a private category", 400)+ }++ let body: { userId?: string }+ try {+ body = await req.json()+ } catch {+ return writeError("invalid request body", 400)+ }+ const targetUserId = body.userId+ if (!targetUserId || typeof targetUserId !== "string") {+ return writeError("userId is required", 400)+ }++ const targetMember = await queries.communityMember.getMember(db, channel.serverId, targetUserId)+ if (!targetMember) return writeError("user is not a member of this server", 400)++ await queries.communityChannel.createChannelMember(db, {+ channelId,+ userId: targetUserId,+ addedBy: ctx.userId,+ })++ const event = {+ type: WS_EVENTS.CHANNEL_MEMBER_ADD,+ serverId: channel.serverId,+ channelId,+ userId: targetUserId,+ } as const+ const recipients = await queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId)+ await Promise.all([...new Set([...recipients, targetUserId])].map((uid) => broadcastToUserSafe(uid, event)))++ logAudit(db, {+ serverId: channel.serverId,+ actorId: ctx.userId,+ action: "channel_member_add",+ targetType: "channel",+ targetId: channelId,+ changes: JSON.stringify({ userId: targetUserId }),+ })++ return writeJSON({ ok: true }, 201)+})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex 0c1573423..bb24c54c1 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -16,6 +16,8 @@ const mockListMemberUserIds = vi.fn()const mockCreateMentions = vi.fn()const mockCreateAttachment = vi.fn()const mockListChildChannels = vi.fn()+const mockIsChannelPrivate = vi.fn(() => false)+const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])const mockListMessages = vi.fn()const mockListMessagesAround = vi.fn()const mockListMessagesSince = vi.fn()@@ -43,6 +45,8 @@ vi.mock("@alook/shared", async () => {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),getChannel: (...a: unknown[]) => mockGetChannel(...a),listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),+ isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),+ getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),},communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.tsindex 5f2715e64..02f86964e 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts@@ -4,7 +4,9 @@ import { NextRequest } from "next/server"const mockGetChannelForMember = vi.fn()const mockCreateChannel = vi.fn()const mockCreateMessage = vi.fn()+const mockGetMessage = vi.fn()const mockGetUserSelf = vi.fn()+const mockGetUserInternal = vi.fn()const mockFanOutToChannel = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({@@ -21,12 +23,25 @@ vi.mock("@alook/shared", async () => {communityChannel: {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),createChannel: (...a: unknown[]) => mockCreateChannel(...a),+ // createCommunityMessage's private-channel scoping guard is only hit+ // when there are mentions; the happy-path posts have none, so these+ // return public/empty.+ isChannelPrivate: vi.fn(async () => false),},communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),+ getMessage: (...a: unknown[]) => mockGetMessage(...a),+ },+ communityMember: {+ listMembers: vi.fn(async () => []),+ listMemberUserIds: vi.fn(async () => []),+ },+ communityMention: {+ createMentions: vi.fn(async () => []),},user: {getUserSelf: (...a: unknown[]) => mockGetUserSelf(...a),+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),},},}@@ -34,6 +49,16 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/community/fanout", () => ({fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),+ fanOutToDM: vi.fn(async () => {}),+}))++// createCommunityMessage's non-fanout side effects — stub so the pipeline runs.+vi.mock("@/lib/broadcast", () => ({+ broadcastToUser: vi.fn(async () => {}),+}))+vi.mock("@/lib/community/audit", () => ({+ logAudit: vi.fn(),+ COMMUNITY_AUDIT_ACTIONS: { MESSAGE_AUTHORED_AS_BOT: "message_authored_as_bot" },}))vi.mock("@/lib/middleware/auth", () => ({@@ -69,7 +94,24 @@ describe("POST /api/community/channels/[id]/posts — name normalization", () =>vi.clearAllMocks()mockGetChannelForMember.mockResolvedValue({ id: "ch1", serverId: "s1", type: "forum", tags: [] })mockCreateMessage.mockResolvedValue({ id: "m1", createdAt: "2026-07-02T00:00:00.000Z" })+ // createCommunityMessage re-fetches the row via getMessage after insert.+ mockGetMessage.mockResolvedValue({+ id: "m1",+ authorId: "u1",+ authorName: "Alice",+ authorImage: null,+ content: "hello",+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ channelId: "post1",+ dmConversationId: null,+ seq: 1,+ createdAt: "2026-07-02T00:00:00.000Z",+ })mockGetUserSelf.mockResolvedValue({ id: "u1", name: "Alice", image: null })+ mockGetUserInternal.mockResolvedValue({ id: "u1", name: "Alice", isBot: false })mockFanOutToChannel.mockResolvedValue(undefined)})diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.tsindex b0728020b..f57c47876 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts@@ -13,6 +13,7 @@ import {import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember } from "@/lib/community/permissions"import { avatarInitial } from "@/lib/community/avatar"+import { createCommunityMessage } from "@/lib/community/message-handler"export const GET = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -139,12 +140,22 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {})}- // Create the first message in the post- const message = await queries.communityMessage.createMessage(db, {+ // Create the first message in the post through the unified pipeline so it+ // gets mention extraction + private-channel audience scoping (the forum's+ // privacy climbs the parent via `isChannelPrivate`) — the direct+ // `createMessage` insert this replaced dropped mentions (plan gap #2). Route+ // as `kind:"channel"` with the post's OWN channelId (NOT `kind:"thread"` —+ // that fires a CHILD_CHANNEL_UPDATE colliding with the CHILD_CHANNEL_CREATE+ // this route already emits below). The emitted MESSAGE_CREATE is deduped by+ // id on the client against that CHILD_CHANNEL_CREATE.+ const created = await createCommunityMessage({+ db,authorId: ctx.userId,- content: body.content,- channelId: postChannel.id,+ target: { kind: "channel", channelId: postChannel.id, serverId: channel.serverId },+ body: { content: body.content },})+ if (!created.ok) return writeError(created.error, created.status)+ const message = created.row// Resolve author info for responseconst creator = await queries.user.getUserSelf(db, ctx.userId)diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.tsindex 59efce70b..e918eb440 100644--- a/src/web/src/app/api/community/channels/[id]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts@@ -1,16 +1,21 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"-const mockGetChannel = vi.fn()-const mockGetMember = vi.fn()-const mockUpdateChannel = vi.fn()-const mockLogAction = vi.fn()-const mockFanOut = vi.fn()-vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),}))+const mockResolveChannelAccessContext = vi.fn()+const mockIsChannelPrivate = vi.fn(() => false)+const mockGetCategory = vi.fn()+const mockUpdateChannel = vi.fn()+const mockDeleteChannel = vi.fn()+const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])+const mockFanOutToServerMembers = vi.fn()+const mockFanOutToChannel = vi.fn()+const mockBroadcastToUserSafe = vi.fn()+const mockLogAudit = vi.fn()+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))vi.mock("@alook/shared", async () => {@@ -19,20 +24,26 @@ vi.mock("@alook/shared", async () => {...actual,queries: {communityChannel: {- getChannel: (...a: unknown[]) => mockGetChannel(...a),+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),+ isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),updateChannel: (...a: unknown[]) => mockUpdateChannel(...a),+ deleteChannel: (...a: unknown[]) => mockDeleteChannel(...a),+ getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),},- communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },- communityAuditLog: {- logAction: (...a: unknown[]) => mockLogAction(...a),- },+ communityCategory: { getCategory: (...a: unknown[]) => mockGetCategory(...a) },},}})vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),+ fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),}))+vi.mock("@/lib/community/audit", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }+})vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {@@ -45,41 +56,104 @@ vi.mock("@/lib/middleware/helpers", () => {const { NextResponse } = require("next/server")return {writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),}})-import { PATCH } from "./route"+import { PATCH, DELETE } from "./route"const ctx = { params: { id: "c1" } } as any-function patchReq(body: unknown) {return new NextRequest("http://localhost/api/community/channels/c1", {method: "PATCH",body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },})}+function delReq() {+ return new NextRequest("http://localhost/api/community/channels/c1", { method: "DELETE" })+}-describe("PATCH /api/community/channels/[id]", () => {+// Raw `resolveChannelAccessContext` return shape (the route calls the REAL+// `requireChannelAccess`, which derives canManage from this). To model a+// canManage=false caller we make them a non-admin, non-creator member of a+// private channel; canManage=true is either admin, or the private-channel+// creator. `anchorCategoryId` is what the cross-boundary check reads for the+// channel's current privacy class.+function accessCtx(over: Partial<{+ role: string+ canManage: boolean+ isPrivate: boolean+ anchorCategoryId: string | null+ creatorId: string+}> = {}) {+ const {+ role = "member",+ canManage = true,+ isPrivate = false,+ anchorCategoryId = null,+ } = over+ // Derive a context that yields the desired canManage under requireChannelAccess:+ // canManage = isAdmin || (isPrivate && isCreator)+ const isAdmin = role === "owner" || role === "admin"+ let creatorId = over.creatorId ?? "u1"+ let ctxIsPrivate = isPrivate+ if (!canManage) {+ // non-admin, non-creator, private (so access is member-only, no manage)+ creatorId = "someone_else"+ ctxIsPrivate = true+ } else if (!isAdmin) {+ // canManage via being the private-channel creator+ creatorId = "u1"+ ctxIsPrivate = true+ }+ const channel = { id: "c1", serverId: "s1", parentChannelId: null, creatorId, categoryId: anchorCategoryId }+ return {+ channel,+ anchor: { ...channel },+ role,+ isPrivate: ctxIsPrivate,+ isChannelMember: !canManage, // member-only access for the non-manage case+ }+}++describe("PATCH /channels/[id] — permission gate", () => {beforeEach(() => {vi.clearAllMocks()- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", categoryId: null, creatorId: "u1" })- mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })- mockFanOut.mockResolvedValue(undefined)- mockLogAction.mockResolvedValue(undefined)+ mockUpdateChannel.mockResolvedValue({ id: "c1", name: "renamed" })+ mockIsChannelPrivate.mockResolvedValue(false)+ })++ it("403 when the caller can't see the channel (null context)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(null)+ const res = await PATCH(patchReq({ name: "x" }), ctx)+ expect(res.status).toBe(403)+ expect(mockUpdateChannel).not.toHaveBeenCalled()+ })++ it("403 when the caller has access but not canManage", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: false }))+ const res = await PATCH(patchReq({ name: "x" }), ctx)+ expect(res.status).toBe(403)+ expect(mockUpdateChannel).not.toHaveBeenCalled()+ })++ it("manager can rename", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: true }))+ const res = await PATCH(patchReq({ name: "renamed" }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateChannel).toHaveBeenCalledWith(expect.anything(), "c1", { name: "renamed" })})it("normalizes a spaced rename via slugify before calling updateChannel", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: true }))mockUpdateChannel.mockResolvedValue({ id: "c1", name: "General-Chat" })-const res = await PATCH(patchReq({ name: "General Chat" }), ctx)expect(res.status).toBe(200)expect(mockUpdateChannel).toHaveBeenCalledWith(expect.anything(), "c1", { name: "General-Chat" })})it("returns 400 (and never calls updateChannel) when the renamed name is all disallowed characters", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: true }))const res = await PATCH(patchReq({ name: " " }), ctx)expect(res.status).toBe(400)expect(mockUpdateChannel).not.toHaveBeenCalled()@@ -102,3 +176,99 @@ describe("PATCH /api/community/channels/[id]", () => {await expect(PATCH(patchReq({ name: "general" }), ctx)).rejects.toThrow("boom")})})++describe("PATCH /channels/[id] — categoryId move", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUpdateChannel.mockResolvedValue({ id: "c1" })+ mockIsChannelPrivate.mockResolvedValue(false)+ })++ it("403 when a non-admin (but private-channel creator) tries to move it", async () => {+ // canManage true via creator, but role is member → not admin.+ mockResolveChannelAccessContext.mockResolvedValue(+ accessCtx({ role: "member", canManage: true, isPrivate: true, anchorCategoryId: "catP" }),+ )+ const res = await PATCH(patchReq({ categoryId: "catP2" }), ctx)+ expect(res.status).toBe(403)+ expect(mockUpdateChannel).not.toHaveBeenCalled()+ })++ it("admin move within the same privacy class (public→public) persists categoryId", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(+ accessCtx({ role: "admin", canManage: true, isPrivate: false, anchorCategoryId: "catA" }),+ )+ // target category is public+ mockGetCategory.mockResolvedValue({ id: "catB", serverId: "s1", private: 0 })+ const res = await PATCH(patchReq({ categoryId: "catB" }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateChannel).toHaveBeenCalledWith(expect.anything(), "c1", { categoryId: "catB" })+ })++ it("admin move public→private is blocked with 400", async () => {+ // current channel is public (anchor has no categoryId → currentPrivate=false)+ mockResolveChannelAccessContext.mockResolvedValue(+ accessCtx({ role: "admin", canManage: true, isPrivate: false, anchorCategoryId: null }),+ )+ mockGetCategory.mockResolvedValue({ id: "catP", serverId: "s1", private: 1 })+ const res = await PATCH(patchReq({ categoryId: "catP" }), ctx)+ expect(res.status).toBe(400)+ expect(mockUpdateChannel).not.toHaveBeenCalled()+ })++ it("admin move private→public (to uncategorized, categoryId=null) is blocked with 400", async () => {+ // current channel is private (anchor has a categoryId + isChannelPrivate=true)+ mockResolveChannelAccessContext.mockResolvedValue(+ accessCtx({ role: "admin", canManage: true, isPrivate: true, anchorCategoryId: "catP" }),+ )+ mockIsChannelPrivate.mockResolvedValue(true) // currentPrivate+ const res = await PATCH(patchReq({ categoryId: null }), ctx)+ expect(res.status).toBe(400)+ expect(mockUpdateChannel).not.toHaveBeenCalled()+ })++ it("404 when the target category belongs to another server", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(+ accessCtx({ role: "admin", canManage: true, isPrivate: false, anchorCategoryId: "catA" }),+ )+ mockGetCategory.mockResolvedValue({ id: "catB", serverId: "OTHER", private: 0 })+ const res = await PATCH(patchReq({ categoryId: "catB" }), ctx)+ expect(res.status).toBe(404)+ expect(mockUpdateChannel).not.toHaveBeenCalled()+ })+})++describe("DELETE /channels/[id]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockDeleteChannel.mockResolvedValue({ id: "c1" })+ mockIsChannelPrivate.mockResolvedValue(false)+ })++ it("403 when not canManage", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: false }))+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(403)+ expect(mockDeleteChannel).not.toHaveBeenCalled()+ })++ it("manager deletes a public channel; fans out server-wide", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(204)+ expect(mockFanOutToServerMembers).toHaveBeenCalled()+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()+ })++ it("private-channel delete fans out to the resolved audience only", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(+ accessCtx({ role: "member", canManage: true, isPrivate: true, anchorCategoryId: "catP" }),+ )+ mockIsChannelPrivate.mockResolvedValue(true)+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1", "u2"])+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(204)+ expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(2)+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.tsindex 4f023bb38..7dd392ca0 100644--- a/src/web/src/app/api/community/channels/[id]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/route.ts@@ -11,49 +11,20 @@ import {WS_EVENTS,slugify,} from "@alook/shared"-import type { Database } from "@alook/shared"-import { fanOutToServerMembers } from "@/lib/community/fanout"+import { fanOutToServerMembers, fanOutToChannel, broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"--type ChannelRow = NonNullable<- Awaited<ReturnType<typeof queries.communityChannel.getChannel>>->--/**- * Resolve the channel + verify the caller can modify it.- * - Admin/owner of the server can edit any channel.- * - Channel creator can edit their own (unless it sits in a private category).- */-async function loadChannelForMutation(- db: Database,- channelId: string,- userId: string,-): Promise<{ ok: true; channel: ChannelRow } | { ok: false; status: 403 | 404; error: string }> {- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return { ok: false, status: 404, error: "channel not found" }-- const member = await queries.communityMember.getMember(db, channel.serverId, userId)- if (!member) return { ok: false, status: 403, error: "forbidden" }-- const isAdmin = canManageServer(member.role)- const isCreator = channel.creatorId === userId- if (!isAdmin && !isCreator) return { ok: false, status: 403, error: "forbidden" }-- if (!isAdmin && channel.categoryId) {- const category = await queries.communityCategory.getCategory(db, channel.categoryId)- if (category?.private) return { ok: false, status: 403, error: "forbidden" }- }- return { ok: true, channel }-}+import { requireChannelAccess } from "@/lib/community/permissions"export const PATCH = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.idif (!channelId) return writeError("missing channel id", 400)const db = getDb(ctx.env.DB)- const check = await loadChannelForMutation(db, channelId, ctx.userId)- if (!check.ok) return writeError(check.error, check.status)- const channel = check.channel+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (!access.value.canManage) return writeError("forbidden", 403)+ const channel = access.value.channel+ const isAdmin = canManageServer(access.value.member.role)let body: { name?: string; topic?: string; categoryId?: string | null; forumTags?: string | null }try {@@ -83,11 +54,23 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {changes.topic = body.topic}if (body.categoryId !== undefined) {+ // Moving a channel between categories is admin-only AND may not cross a+ // public↔private boundary (that would silently widen/tighten visibility+ // without member reconciliation).+ if (!isAdmin) return writeError("admin permission required", 403)+ let targetPrivate = falseif (body.categoryId !== null) {const category = await queries.communityCategory.getCategory(db, body.categoryId)if (!category || category.serverId !== channel.serverId) {return writeError("category not found", 404)}+ targetPrivate = !!category.private+ }+ const currentPrivate = access.value.anchor.categoryId+ ? await queries.communityChannel.isChannelPrivate(db, channelId)+ : false+ if (targetPrivate !== currentPrivate) {+ return writeError("Can't move a channel across a public/private boundary", 400)}changes.categoryId = body.categoryId}@@ -108,12 +91,22 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {}if (!updated) return writeError("channel not found", 404)- await fanOutToServerMembers(channel.serverId, {- type: WS_EVENTS.CHANNEL_UPDATE,- serverId: channel.serverId,- channelId,- changes,- })+ const isPrivate = await queries.communityChannel.isChannelPrivate(db, channelId)+ if (isPrivate) {+ await fanOutToChannel(channelId, {+ type: WS_EVENTS.CHANNEL_UPDATE,+ serverId: channel.serverId,+ channelId,+ changes,+ })+ } else {+ await fanOutToServerMembers(channel.serverId, {+ type: WS_EVENTS.CHANNEL_UPDATE,+ serverId: channel.serverId,+ channelId,+ changes,+ })+ }logAudit(db, {serverId: channel.serverId,@@ -132,18 +125,32 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {if (!channelId) return writeError("missing channel id", 400)const db = getDb(ctx.env.DB)- const check = await loadChannelForMutation(db, channelId, ctx.userId)- if (!check.ok) return writeError(check.error, check.status)- const channel = check.channel+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (!access.value.canManage) return writeError("forbidden", 403)+ const channel = access.value.channel++ // Resolve the private-channel audience BEFORE deleting (the member rows+ // cascade away with the channel row), so the delete event still reaches+ // exactly the people who could see it.+ const isPrivate = await queries.communityChannel.isChannelPrivate(db, channelId)+ const audience = isPrivate+ ? await queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId)+ : nullconst deleted = await queries.communityChannel.deleteChannel(db, channelId)if (!deleted) return writeError("channel not found", 404)- await fanOutToServerMembers(channel.serverId, {+ const event = {type: WS_EVENTS.CHANNEL_DELETE,serverId: channel.serverId,channelId,- })+ } as const+ if (audience) {+ await Promise.all(audience.map((userId) => broadcastToUserSafe(userId, event)))+ } else {+ await fanOutToServerMembers(channel.serverId, event)+ }logAudit(db, {serverId: channel.serverId,diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.tsindex 240a1a973..5ded82538 100644--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts@@ -7,6 +7,7 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockGetChannel = vi.fn()const mockGetMember = vi.fn()+const mockResolveChannelAccessContext = vi.fn()const mockListChildChannels = vi.fn()const mockGetMessagesByIds = vi.fn()const mockGetUsersByIds = vi.fn()@@ -25,6 +26,7 @@ vi.mock("@alook/shared", async () => {communityChannel: {getChannel: (...a: unknown[]) => mockGetChannel(...a),listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),},communityMember: {getMember: (...a: unknown[]) => mockGetMember(...a),@@ -71,6 +73,15 @@ describe("GET /api/community/channels/[id]/threads", () => {vi.clearAllMocks()mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })mockGetMember.mockResolvedValue({ id: "m1", userId: "u1", serverId: "s1" })+ // requireChannelAccess resolves through resolveChannelAccessContext — a+ // public channel the caller is a member of.+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null },+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null },+ role: "member",+ isPrivate: false,+ isChannelMember: false,+ })})it("resolves parent/creator/first-message via three batched calls (never per-item)", async () => {diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.tsindex ea9c47638..2a97360a4 100644--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts@@ -3,6 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"+import { requireChannelAccess } from "@/lib/community/permissions"export const GET = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -10,11 +11,11 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return writeError("channel not found", 404)-- const member = await queries.communityMember.getMember(db, channel.serverId, ctx.userId)- if (!member) return writeError("forbidden", 403)+ // Gate through the shared access predicate: a channel in a PRIVATE category+ // must not leak its thread titles/previews to non-members. Public channels+ // behave as before (any server member).+ const access = await requireChannelAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)const archivedParam = req.nextUrl.searchParams.get("archived")const archived = archivedParam === "true" ? true : archivedParam === "false" ? false : undefineddiff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.tsindex d031ad168..147112a23 100644--- a/src/web/src/app/api/community/friends/request/route.ts+++ b/src/web/src/app/api/community/friends/request/route.ts@@ -6,6 +6,7 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"import { broadcastToUserSafe } from "@/lib/community/fanout"import { requireNotBlocked } from "@/lib/community/permissions"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"+import { createCommunityMessage } from "@/lib/community/message-handler"export const POST = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)@@ -77,11 +78,23 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {userId1: target.id,userId2: target.ownerUserId,})- const msg = await queries.communityMessage.createMessage(db, {+ // Unified pipeline, but broadcast-deferred: the DM card must not reach the+ // owner until the approval-request row commits (otherwise they'd see a+ // phantom card with no approve/deny buttons). `skipMentions`/`skipWake` —+ // a bot DM card mentions no one and wakes no one. We never invoke the+ // returned `broadcast` thunk; the route fires its own minimal+ // `DM_NEW_MESSAGE` after the approval row is persisted.+ const created = await createCommunityMessage({+ db,authorId: target.id,- content: "A friend wants to be my friend. Approve?",- dmConversationId: dm.id,+ target: { kind: "dm", dmId: dm.id, otherUserId: target.ownerUserId },+ body: { content: "A friend wants to be my friend. Approve?" },+ skipMentions: true,+ skipWake: true,+ deferBroadcast: true,})+ if (!created.ok) return writeError(created.error, created.status)+ const msg = created.rowtry {await queries.communityBot.createApprovalRequestStatement(db, {botId: target.id,diff --git a/src/web/src/app/api/community/inbox/dms/read-all/route.ts b/src/web/src/app/api/community/inbox/dms/read-all/route.tsnew file mode 100644index 000000000..f25dc4243--- /dev/null+++ b/src/web/src/app/api/community/inbox/dms/read-all/route.ts@@ -0,0 +1,18 @@+import { queries } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON } from "@/lib/middleware/helpers"++/**+ * POST /api/community/inbox/dms/read-all+ *+ * Mark every DM the viewer participates in read at its latest message. Kept a+ * DISTINCT route from `/inbox/unreads/read-all` (channels) so the inbox+ * "mark all read" affordance fires three independent POSTs — mentions ++ * channel-unreads + dms — each idempotent and independently retryable.+ */+export const POST = withAuth(async (_req, ctx) => {+ const db = getDb(ctx.env.DB)+ const count = await queries.communityReadState.markAllDmsRead(db, ctx.userId)+ return writeJSON({ ok: true, count })+})diff --git a/src/web/src/app/api/community/inbox/mentions/route.test.ts b/src/web/src/app/api/community/inbox/mentions/route.test.tsindex 1b1667891..fa45c9399 100644--- a/src/web/src/app/api/community/inbox/mentions/route.test.ts+++ b/src/web/src/app/api/community/inbox/mentions/route.test.ts@@ -4,6 +4,7 @@ import { NextRequest } from "next/server"const mockListUnreadMentions = vi.fn()const mockGetChannelsByIds = vi.fn()const mockGetServersByIds = vi.fn()+const mockListVisibleChannelIds = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -21,6 +22,7 @@ vi.mock("@alook/shared", async () => {},communityChannel: {getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),+ listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),},communityServer: {getServersByIds: (...args: unknown[]) => mockGetServersByIds(...args),@@ -51,18 +53,22 @@ describe("GET /api/community/inbox/mentions", () => {vi.clearAllMocks()mockGetChannelsByIds.mockResolvedValue([])mockGetServersByIds.mockResolvedValue([])+ mockListVisibleChannelIds.mockResolvedValue(["c1"])})- it("queries only kind='mention' so replies don't leak into Mentions tab", async () => {+ it("queries BOTH mention + reply kinds (no kind filter) scoped to visible channels", async () => {mockListUnreadMentions.mockResolvedValue([])await GET(new NextRequest("http://localhost/api/community/inbox/mentions"))- expect(mockListUnreadMentions).toHaveBeenCalledWith({}, "u1", expect.objectContaining({ kind: "mention" }))+ // No `kind` narrowing — both @-mentions and reply notifications surface.+ const opts = mockListUnreadMentions.mock.calls[0][2]+ expect(opts.kind).toBeUndefined()+ expect(opts.visibleChannelIds).toEqual(["c1"])})- it("hydrates server + channel names into the response", async () => {+ it("hydrates server + channel names and the mention kind into the response", async () => {mockListUnreadMentions.mockResolvedValue([{- mention: { id: "mn1" },+ mention: { id: "mn1", kind: "mention" },message: { id: "m1", channelId: "c1", content: "@u1 hi", createdAt: "2026-06-25T10:00:00Z" },author: { name: "Alice", email: "[email protected]", image: null },},@@ -75,6 +81,7 @@ describe("GET /api/community/inbox/mentions", () => {expect(body.mentions).toHaveLength(1)expect(body.mentions[0]).toMatchObject({id: "mn1",+ kind: "mention",server: "Server 1",serverId: "s1",channel: "general",@@ -83,6 +90,21 @@ describe("GET /api/community/inbox/mentions", () => {})})+ it("tags reply-kind rows so the UI can label them 'replied to you'", async () => {+ mockListUnreadMentions.mockResolvedValue([+ {+ mention: { id: "mn2", kind: "reply" },+ message: { id: "m2", channelId: "c1", content: "sure", createdAt: "2026-06-25T11:00:00Z" },+ author: { name: "Bob", email: "[email protected]", image: null },+ },+ ])+ mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])+ mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/mentions"))+ const body = await res.json()+ expect(body.mentions[0].kind).toBe("reply")+ })+it("returns empty mentions array when none", async () => {mockListUnreadMentions.mockResolvedValue([])const res = await GET(new NextRequest("http://localhost/api/community/inbox/mentions"))@@ -95,6 +117,6 @@ describe("GET /api/community/inbox/mentions", () => {const res = await GET(new NextRequest("http://localhost/api/community/inbox/mentions?limit=99999"))const body = await res.json()expect(body.limit).toBe(200) // MAX_INBOX_PAGE_SIZE- expect(mockListUnreadMentions).toHaveBeenCalledWith({}, "u1", { kind: "mention", limit: 200 })+ expect(mockListUnreadMentions).toHaveBeenCalledWith({}, "u1", { limit: 200, visibleChannelIds: ["c1"] })})})diff --git a/src/web/src/app/api/community/inbox/mentions/route.ts b/src/web/src/app/api/community/inbox/mentions/route.tsindex ddcbbeef2..09381f300 100644--- a/src/web/src/app/api/community/inbox/mentions/route.ts+++ b/src/web/src/app/api/community/inbox/mentions/route.ts@@ -18,9 +18,15 @@ export const GET = withAuth(async (req, ctx) => {MAX_INBOX_PAGE_SIZE,)+ // Both `@`-mentions AND reply notifications surface in the Mentions tab now.+ // Scope to the viewer's visible channels (scope-first, in-query) so a+ // removed-from-private-channel user no longer sees leftover mentions; the+ // `inArray(channelId, visibleIds)` also naturally excludes DM reply rows+ // (channelId = NULL), which stay out of the Mentions tab by design.+ const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)const rows = await queries.communityMention.listUnreadMentions(db, ctx.userId, {- kind: "mention",limit,+ visibleChannelIds,})const channelIds = [...new Set(rows.filter((r) => r.message.channelId).map((r) => r.message.channelId!))]@@ -36,6 +42,9 @@ export const GET = withAuth(async (req, ctx) => {const srv = ch ? serverMap.get(ch.serverId) : undefinedreturn {id: row.mention.id,+ // "mention" (@-mention) vs "reply" — the UI labels them differently+ // ("mentioned you" vs "replied to you").+ kind: row.mention.kind,// srv/ch fall back to "Unknown" only when the underlying row was deleted// between mention insert and this read — unrelated to user-name integrity.server: srv ? srv.name : "Unknown",diff --git a/src/web/src/app/api/community/inbox/unreads/read-all/route.test.ts b/src/web/src/app/api/community/inbox/unreads/read-all/route.test.tsindex 7ec0b8136..57a3c8ecf 100644--- a/src/web/src/app/api/community/inbox/unreads/read-all/route.test.ts+++ b/src/web/src/app/api/community/inbox/unreads/read-all/route.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mockMarkAllServerChannelsRead = vi.fn()+const mockListVisibleChannelIds = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -15,6 +16,9 @@ vi.mock("@alook/shared", () => ({communityReadState: {markAllServerChannelsRead: (...args: unknown[]) => mockMarkAllServerChannelsRead(...args),},+ communityChannel: {+ listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),+ },},}))@@ -36,7 +40,10 @@ vi.mock("@/lib/middleware/helpers", () => {import { POST } from "./route"describe("POST /api/community/inbox/unreads/read-all", () => {- beforeEach(() => vi.clearAllMocks())+ beforeEach(() => {+ vi.clearAllMocks()+ mockListVisibleChannelIds.mockResolvedValue(["c1", "c2"])+ })it("returns the count of NON-EMPTY channels marked read (invariant: empty channels excluded)", async () => {// Post-invariant: count == channels that actually received an aligned@@ -46,7 +53,8 @@ describe("POST /api/community/inbox/unreads/read-all", () => {const body = await res.json()expect(res.status).toBe(200)expect(body).toEqual({ ok: true, count: 7 })- expect(mockMarkAllServerChannelsRead).toHaveBeenCalledWith({}, "u1")+ // Scoped to the viewer's visible channels (resolved once, passed through).+ expect(mockMarkAllServerChannelsRead).toHaveBeenCalledWith({}, "u1", ["c1", "c2"])})it("returns count 0 when every channel is empty (nothing to write)", async () => {diff --git a/src/web/src/app/api/community/inbox/unreads/read-all/route.ts b/src/web/src/app/api/community/inbox/unreads/read-all/route.tsindex fad1f29d3..a0645f97c 100644--- a/src/web/src/app/api/community/inbox/unreads/read-all/route.ts+++ b/src/web/src/app/api/community/inbox/unreads/read-all/route.ts@@ -5,6 +5,10 @@ import { writeJSON } from "@/lib/middleware/helpers"export const POST = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)- const count = await queries.communityReadState.markAllServerChannelsRead(db, ctx.userId)+ // Resolve the viewer's visible channels once (top-level + threads/forum-posts,+ // parent-climbed) and scope the mark-all to them — a private thread under an+ // invisible parent is excluded.+ const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)+ const count = await queries.communityReadState.markAllServerChannelsRead(db, ctx.userId, visibleChannelIds)return writeJSON({ ok: true, count })})diff --git a/src/web/src/app/api/community/inbox/unreads/route.test.ts b/src/web/src/app/api/community/inbox/unreads/route.test.tsindex be0d48889..7a53db8ee 100644--- a/src/web/src/app/api/community/inbox/unreads/route.test.ts+++ b/src/web/src/app/api/community/inbox/unreads/route.test.ts@@ -5,6 +5,8 @@ const mockListUnreadChannels = vi.fn()const mockGetSettings = vi.fn()const mockListUnreadMentions = vi.fn()const mockListUnreadDms = vi.fn()+const mockListVisibleChannelIds = vi.fn()+const mockGetChannelsByIds = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -27,6 +29,10 @@ vi.mock("@alook/shared", async () => {communityMention: {listUnreadMentions: (...args: unknown[]) => mockListUnreadMentions(...args),},+ communityChannel: {+ listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),+ getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),+ },},}})@@ -48,12 +54,13 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"-function row(overrides: Partial<{ channelId: string; channelName: string; serverId: string; serverName: string; lastMessageAt: string; lastReadAt: string | null }>) {+function row(overrides: Partial<{ channelId: string; channelName: string; serverId: string; serverName: string; parentChannelId: string | null; lastMessageAt: string; lastReadAt: string | null }>) {return {channelId: "c1",channelName: "general",serverId: "s1",serverName: "Server 1",+ parentChannelId: null,lastMessageAt: "2026-06-25T10:00:00Z",lastReadAt: null,...overrides,@@ -66,6 +73,8 @@ describe("GET /api/community/inbox/unreads", () => {mockGetSettings.mockResolvedValue([])mockListUnreadMentions.mockResolvedValue([])mockListUnreadDms.mockResolvedValue([])+ mockListVisibleChannelIds.mockResolvedValue([])+ mockGetChannelsByIds.mockResolvedValue([])})it("groups channels by server", async () => {@@ -186,4 +195,91 @@ describe("GET /api/community/inbox/unreads", () => {expect(body.servers).toHaveLength(1)expect(body.dms).toHaveLength(1)})++ // ── Threads / forum-posts as child sub-rows ────────────────────────────────++ 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([+ row({ channelId: "t1", channelName: "budget-2026", parentChannelId: "c1", lastMessageAt: "2026-06-25T10:00:00Z" }),+ ])+ mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])++ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const body = await res.json()++ expect(res.status).toBe(200)+ expect(mockGetChannelsByIds).toHaveBeenCalledWith(expect.anything(), ["c1"])+ expect(body.servers).toHaveLength(1)+ expect(body.servers[0].channels).toHaveLength(1)+ const parent = body.servers[0].channels[0]+ expect(parent.channelId).toBe("c1")+ expect(parent.channelName).toBe("general")+ expect(parent.children.map((c: { channelId: string }) => c.channelId)).toEqual(["t1"])+ })++ it("nests a child under a parent that ALSO has a direct unread (no re-resolve)", async () => {+ mockListUnreadChannels.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" }),+ ])+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const body = await res.json()+ // Parent was already present → no getChannelsByIds resolve needed.+ expect(mockGetChannelsByIds).not.toHaveBeenCalled()+ const parent = body.servers[0].channels[0]+ expect(parent.channelId).toBe("c1")+ expect(parent.children.map((c: { channelId: string }) => c.channelId)).toEqual(["t1"])+ })++ it("attributes per-channel mentionCount to the correct child row", async () => {+ mockListUnreadChannels.mockResolvedValue([+ row({ channelId: "t1", channelName: "thread", parentChannelId: "c1" }),+ ])+ 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/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" }])+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const body = await res.json()+ expect(body.servers).toHaveLength(0)+ })++ 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([+ 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" }),+ ])+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads?limit=2"))+ const body = await res.json()+ expect(body.truncated).toBe(true)+ const parent = body.servers[0].channels[0]+ expect(parent.channelId).toBe("c1")+ // Newest child first, capped to 1.+ expect(parent.children.map((c: { channelId: string }) => c.channelId)).toEqual(["t1"])+ })++ it("top-level channels carry an empty children array", async () => {+ mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const body = await res.json()+ expect(body.servers[0].channels[0].children).toEqual([])+ })})diff --git a/src/web/src/app/api/community/inbox/unreads/route.ts b/src/web/src/app/api/community/inbox/unreads/route.tsindex d445e4a5f..116ebb8cc 100644--- a/src/web/src/app/api/community/inbox/unreads/route.ts+++ b/src/web/src/app/api/community/inbox/unreads/route.ts@@ -18,10 +18,14 @@ export const GET = withAuth(async (req, ctx) => {MAX_INBOX_PAGE_SIZE,)+ // Resolve the viewer's visible channels once (top-level + threads/forum-posts,+ // parent-climbed) and thread the id set into BOTH consumers so neither+ // recomputes it. Private threads under an invisible parent are excluded.+ const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)const [unread, settings, mentions, unreadDms] = await Promise.all([- queries.communityInbox.listUnreadChannels(db, ctx.userId),+ queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds),queries.communityNotificationSetting.getSettings(db, ctx.userId),- queries.communityMention.listUnreadMentions(db, ctx.userId),+ queries.communityMention.listUnreadMentions(db, ctx.userId, { visibleChannelIds }),queries.communityInbox.listUnreadDms(db, ctx.userId),])@@ -40,32 +44,132 @@ export const GET = withAuth(async (req, ctx) => {mentionCountByChannel.set(cid, (mentionCountByChannel.get(cid) ?? 0) + 1)}- const grouped = new Map<- string,- { serverId: string; serverName: string; channels: Array<{ channelId: string; channelName: string; lastMessageAt: string; mentionCount: number }> }- >()+ // Split unread rows into top-level channels and child threads/forum-posts.+ // A child nests under its `parentChannelId`; a parent surfaces in the tree+ // even when it has no direct unread of its own (only unread children).+ type UnreadChild = { channelId: string; channelName: string; lastMessageAt: string; mentionCount: number }+ type ParentNode = {+ channelId: string+ channelName: string+ serverId: string+ serverName: string+ lastMessageAt: string+ mentionCount: number+ hasDirectUnread: boolean+ children: UnreadChild[]+ }++ const parents = new Map<string, ParentNode>()+ const childrenByParent = new Map<string, UnreadChild[]>()+for (const row of unread) {- // Skip orphan rows where the server/channel was deleted between fetch- // and join — the UI can't render them anyway.if (!row.serverId || !row.channelId || !row.serverName || !row.channelName) continueif (mutedServers.has(row.serverId)) continue- if (mutedChannels.has(row.channelId)) continue- let bucket = grouped.get(row.serverId)+ if (row.parentChannelId) {+ // Child (thread / forum-post). 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)) continue+ const list = childrenByParent.get(row.parentChannelId) ?? []+ list.push({+ channelId: row.channelId,+ channelName: row.channelName,+ lastMessageAt: row.lastMessageAt,+ mentionCount: mentionCountByChannel.get(row.channelId) ?? 0,+ })+ childrenByParent.set(row.parentChannelId, list)+ } else {+ if (mutedChannels.has(row.channelId)) continue+ parents.set(row.channelId, {+ channelId: row.channelId,+ channelName: row.channelName,+ serverId: row.serverId,+ serverName: row.serverName,+ lastMessageAt: row.lastMessageAt,+ mentionCount: mentionCountByChannel.get(row.channelId) ?? 0,+ hasDirectUnread: true,+ children: [],+ })+ }+ }++ // Parents that have an unread child but no direct unread aren't in `unread`,+ // so their name isn't available — batch-resolve them. `getChannelsByIds` has+ // 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))+ if (missingParentIds.length > 0) {+ const resolved = await queries.communityChannel.getChannelsByIds(db, missingParentIds)+ const resolvedById = new Map(resolved.map((c) => [c.id, c]))+ for (const pid of missingParentIds) {+ const ch = resolvedById.get(pid)+ if (!ch) continue+ if (mutedServers.has(ch.serverId)) continue+ parents.set(pid, {+ channelId: pid,+ channelName: ch.name,+ serverId: ch.serverId,+ // serverName + a sort timestamp are backfilled from the child rows+ // below (those rows carry serverName via the communityServer join).+ serverName: "",+ lastMessageAt: "",+ mentionCount: mentionCountByChannel.get(pid) ?? 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).+ for (const [pid, kids] of childrenByParent) {+ const parent = parents.get(pid)+ if (!parent) continue // parent muted or unresolved → drop the subtree+ parent.children.push(...kids)+ }++ // Resolved-only parents (unread child, no direct unread) need serverName + a+ // sort timestamp. Backfill from the child rows, which carry both.+ for (const row of unread) {+ if (!row.parentChannelId) continue+ const parent = parents.get(row.parentChannelId)+ if (!parent || parent.hasDirectUnread) continue+ if (!parent.serverName && row.serverName) parent.serverName = row.serverName+ if (row.lastMessageAt > parent.lastMessageAt) parent.lastMessageAt = row.lastMessageAt+ }++ // Drop any parent that ended up with neither a direct unread nor a surviving+ // child (e.g. all children muted), or that never got a serverName.+ const grouped = new Map<+ string,+ { serverId: string; serverName: string; channels: Array<ParentNode & { children: UnreadChild[] }> }+ >()+ for (const parent of parents.values()) {+ if (!parent.hasDirectUnread && parent.children.length === 0) continue+ if (!parent.serverName) continue+ parent.children.sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))+ let bucket = grouped.get(parent.serverId)if (!bucket) {- bucket = { serverId: row.serverId, serverName: row.serverName, channels: [] }- grouped.set(row.serverId, bucket)+ bucket = { serverId: parent.serverId, serverName: parent.serverName, channels: [] }+ grouped.set(parent.serverId, bucket)}- bucket.channels.push({- channelId: row.channelId,- channelName: row.channelName,- lastMessageAt: row.lastMessageAt,- mentionCount: mentionCountByChannel.get(row.channelId) ?? 0,- })+ bucket.channels.push(parent)}const allServers = Array.from(grouped.values()).map((g) => ({- ...g,- channels: g.channels.sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1)),+ serverId: g.serverId,+ serverName: g.serverName,+ channels: g.channels+ .sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))+ .map((c) => ({+ channelId: c.channelId,+ channelName: c.channelName,+ lastMessageAt: c.lastMessageAt,+ mentionCount: c.mentionCount,+ children: c.children,+ })),}))allServers.sort((a, b) => {const aLatest = a.channels[0]?.lastMessageAt ?? ""@@ -73,22 +177,33 @@ export const GET = withAuth(async (req, ctx) => {return aLatest < bLatest ? 1 : aLatest > bLatest ? -1 : 0})- // Cap by channel count rather than server count — a single very active- // server shouldn't be able to drown out the rest of the inbox payload.+ // Cap by total row count — each parent AND each child counts as one row, so a+ // single very active server (or one channel with many unread threads) can't+ // drown out the rest of the inbox payload.+ const nodeWeight = (c: { children: unknown[] }) => 1 + c.children.length+ const grandTotal = allServers.reduce((n, s) => n + s.channels.reduce((m, c) => m + nodeWeight(c), 0), 0)const servers: typeof allServers = []let total = 0for (const s of allServers) {- const remaining = limit - total- if (remaining <= 0) break- if (s.channels.length <= remaining) {- servers.push(s)- total += s.channels.length- } else {- servers.push({ ...s, channels: s.channels.slice(0, remaining) })- total = limit+ if (total >= limit) break+ const keptChannels: typeof s.channels = []+ for (const c of s.channels) {+ const remaining = limit - total+ if (remaining <= 0) break+ const weight = nodeWeight(c)+ if (weight <= remaining) {+ keptChannels.push(c)+ total += weight+ } else {+ // Parent takes one slot; the rest go to children (may be zero).+ keptChannels.push({ ...c, children: c.children.slice(0, remaining - 1) })+ total = limit+ break+ }}+ if (keptChannels.length > 0) servers.push({ ...s, channels: keptChannels })}- const truncated = total < allServers.reduce((n, s) => n + s.channels.length, 0)+ const truncated = total < grandTotal// DMs are a flat list sorted most-recent first. DM notification settings// don't exist today (`communityNotificationSetting` scopes are server/channeldiff --git a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts b/src/web/src/app/api/community/messages/[id]/threads/route.test.tsindex d56ec354d..1f219a1cd 100644--- a/src/web/src/app/api/community/messages/[id]/threads/route.test.ts+++ b/src/web/src/app/api/community/messages/[id]/threads/route.test.ts@@ -73,6 +73,9 @@ const ctx = { params: { id: "msg-p" } } as anydescribe("POST /api/community/messages/[id]/threads", () => {beforeEach(() => {vi.clearAllMocks()+ // The unified pipeline fires `fanOutToChannel(...).catch(...)` — the mock+ // must return a promise so the `.catch` chain resolves.+ mockFanOutToChannel.mockResolvedValue(undefined)mockGetChannelForMember.mockResolvedValue({id: "c-parent",serverId: "s1",@@ -182,12 +185,15 @@ describe("POST /api/community/messages/[id]/threads", () => {type: "community:message.create",message: expect.objectContaining({ id: "sysmsg-1", type: "system", systemKind: "thread" }),}),+ expect.objectContaining({ excludeUserId: undefined }),)const systemMessageCall = mockFanOutToChannel.mock.calls.find((call) => (call[1] as { type?: string }).type === "community:message.create",)expect(systemMessageCall).toBeDefined()- expect(systemMessageCall).toHaveLength(2)+ // The unified pipeline passes an opts arg; `includeAuthorInFanout` means+ // no `excludeUserId` so the creator also receives the broadcast.+ expect((systemMessageCall![2] as { excludeUserId?: string }).excludeUserId).toBeUndefined()})it("rejects a second thread on the same parent message", async () => {@@ -219,6 +225,20 @@ describe("POST /api/community/messages/[id]/threads", () => {expect(res.status).toBe(404)})+ it("400s when the parent message lives in a child channel (forum post / thread) — no grandchild threads", async () => {+ // A message inside a forum_post/thread: its channel has parentChannelId set.+ // Rooting a thread here would create a grandchild the single-level privacy+ // anchor climb can't resolve, leaking a private forum's thread server-wide.+ mockGetChannelForMember.mockResolvedValue({+ id: "forum-post-1",+ serverId: "s1",+ parentChannelId: "forum-1",+ })+ const res = await POST(req({ name: "x" }), ctx)+ expect(res.status).toBe(400)+ expect(mockCreateChannel).not.toHaveBeenCalled()+ })+it("403s when the caller isn't a member of the parent channel's server", async () => {mockGetChannelForMember.mockResolvedValue(null)const res = await POST(req({ name: "x" }), ctx)diff --git a/src/web/src/app/api/community/messages/[id]/threads/route.ts b/src/web/src/app/api/community/messages/[id]/threads/route.tsindex e0f91229d..233fbfa9c 100644--- a/src/web/src/app/api/community/messages/[id]/threads/route.ts+++ b/src/web/src/app/api/community/messages/[id]/threads/route.ts@@ -5,7 +5,7 @@ import { getDb } from "@/lib/db"import { queries, MAX_CHANNEL_NAME_LENGTH, WS_EVENTS } from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember } from "@/lib/community/permissions"-import { mapMessageForWs } from "@/lib/community/message-payload"+import { createCommunityMessage } from "@/lib/community/message-handler"export const POST = withAuth(async (req: NextRequest, ctx) => {const messageId = ctx.params?.id@@ -21,6 +21,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (!auth.ok) return writeError(auth.error, auth.status)const channel = auth.value+ // Threads may only root on a TOP-LEVEL channel's message. Rooting on a child+ // channel (a forum post, or another thread) would make the new thread a+ // grandchild whose privacy the single-level anchor climb can't resolve — it+ // would read the child's own `categoryId` (always NULL) as public and leak a+ // private forum's thread server-wide. The UI already forbids this (child+ // views pass no create-thread action); enforce it on the API too.+ if (channel.parentChannelId) {+ return writeError("can't start a thread on a message in a thread or forum post", 400)+ }+let body: { name?: string }try {body = await req.json()@@ -82,26 +92,24 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// `type: "thread_created"` was already documented as a possible// `communityMessage.type` value (see `message-payload.ts`) but never// actually written anywhere until now.+ // System notice through the unified pipeline: `thread_created` type,+ // `skipMentions` (a system message @-mentions no one), `skipWake` (no bot+ // wake), and `includeAuthorInFanout` so the creator — who has no optimistic+ // client row — receives the MESSAGE_CREATE and sees it without a refresh+ // (reproduces the old no-`excludeUserId` broadcast). `insertMessageIntoCache`+ // dedupes by id, so this is safe even if a future change adds an optimistic+ // row for the creator.const creator = await queries.user.getUserInternal(db, ctx.userId)- const systemMessage = await queries.communityMessage.createMessage(db, {+ await createCommunityMessage({+ db,authorId: ctx.userId,- content: `${creator?.name ?? "Someone"} started a thread: ${name}`,- channelId: message.channelId,- type: "thread_created",+ target: { kind: "channel", channelId: message.channelId, serverId: channel.serverId },+ body: { content: `${creator?.name ?? "Someone"} started a thread: ${name}` },+ messageType: "thread_created",+ skipMentions: true,+ skipWake: true,+ includeAuthorInFanout: true,})- const systemRow = await queries.communityMessage.getMessage(db, systemMessage.id)- if (systemRow) {- // No `excludeUserId` here — unlike most sends, the thread creator did- // not author this system message client-side (no optimistic row), so- // they need the WS broadcast too to see it without a refresh.- // `insertMessageIntoCache` dedupes by id, so this is safe even if a- // future change adds an optimistic row for the creator.- fanOutToChannel(message.channelId, {- type: WS_EVENTS.MESSAGE_CREATE,- channelId: message.channelId,- message: mapMessageForWs(systemRow, { replyMap: new Map(), attachments: [] }),- })- }return writeJSON(childChannel, 201)})diff --git a/src/web/src/app/api/community/search/route.test.ts b/src/web/src/app/api/community/search/route.test.tsnew file mode 100644index 000000000..f407a4c2b--- /dev/null+++ b/src/web/src/app/api/community/search/route.test.ts@@ -0,0 +1,79 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++const mockGetMember = vi.fn()+const mockListVisibleChannelIds = vi.fn()+const mockSearchMessagesInServer = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },+ communityChannel: { listVisibleChannelIds: (...a: unknown[]) => mockListVisibleChannelIds(...a) },+ communitySearch: { searchMessagesInServer: (...a: unknown[]) => mockSearchMessagesInServer(...a) },+ },+ }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ }+})++import { GET } from "./route"++describe("GET /api/community/search — server scope", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetMember.mockResolvedValue({ id: "m1", role: "member" })+ mockListVisibleChannelIds.mockResolvedValue(["c_pub", "c_priv_mine"])+ mockSearchMessagesInServer.mockResolvedValue([])+ })++ it("scopes the server search to the viewer's visible channel ids", async () => {+ const res = await GET(+ new NextRequest("http://localhost/api/community/search?q=hello&serverId=s1"),+ { params: {} } as any,+ )+ expect(res.status).toBe(200)+ expect(mockListVisibleChannelIds).toHaveBeenCalledWith(+ expect.anything(),+ "s1",+ "u1",+ { isAdmin: false },+ )+ expect(mockSearchMessagesInServer).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ serverId: "s1", visibleChannelIds: ["c_pub", "c_priv_mine"] }),+ )+ })++ it("resolves isAdmin from the caller's role", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "owner" })+ await GET(+ new NextRequest("http://localhost/api/community/search?q=hello&serverId=s1"),+ { params: {} } as any,+ )+ expect(mockListVisibleChannelIds).toHaveBeenCalledWith(+ expect.anything(), "s1", "u1", { isAdmin: true },+ )+ })+})diff --git a/src/web/src/app/api/community/search/route.ts b/src/web/src/app/api/community/search/route.tsindex a682367a2..652441d32 100644--- a/src/web/src/app/api/community/search/route.ts+++ b/src/web/src/app/api/community/search/route.ts@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"+import { queries, canManageServer, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"import {requireServerMember,requireChannelMember,@@ -32,9 +32,18 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {if (serverId) {const auth = await requireServerMember(db, serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)+ // Scope to the viewer's visible channels so private-channel content never+ // surfaces in server-wide search.+ const visibleChannelIds = await queries.communityChannel.listVisibleChannelIds(+ db,+ serverId,+ ctx.userId,+ { isAdmin: canManageServer(auth.value!.role) },+ )const results = await queries.communitySearch.searchMessagesInServer(db, {query: q,serverId,+ visibleChannelIds,})return writeJSON({ results })}diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.tsindex dc9505bc4..7e6862c2f 100644--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts@@ -12,6 +12,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"+import { createCommunityMessage } from "@/lib/community/message-handler"const log = createLogger({ service: "community-bots-server-add" })@@ -101,12 +102,23 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// string "undefined".const requesterLabel = callerMember.nickname?.trim() || "A friend"const botName = target.name || "the bot"- const msg = await queries.communityMessage.createMessage(db, {+ // Unified pipeline, broadcast-deferred: the card must not reach the owner+ // until the approval-request row commits (a rollback below would otherwise+ // leave a phantom, unactionable card). `skipMentions`/`skipWake` — a bot DM+ // card mentions no one and wakes no one. The returned `broadcast` thunk is+ // never invoked; this route fires its own minimal `DM_NEW_MESSAGE` after the+ // approval row persists.+ const created = await createCommunityMessage({+ db,authorId: botId,- content: `${requesterLabel} wants to add me to a server. Approve?`,- dmConversationId: dm.id,- type: "default",+ target: { kind: "dm", dmId: dm.id, otherUserId: ownerId },+ body: { content: `${requesterLabel} wants to add me to a server. Approve?` },+ skipMentions: true,+ skipWake: true,+ deferBroadcast: true,})+ if (!created.ok) return writeError(created.error, created.status)+ const msg = created.row// Write the approval-request row. If the partial unique index rejects a// concurrent duplicate, roll back by hard-deleting the DM card so the owner// never sees a phantom card without approve/deny buttons.diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.tsindex 0bb1e99a5..67c9d9f14 100644--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.test.ts@@ -1,15 +1,17 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"+vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))+const mockGetMember = vi.fn()const mockGetCategory = vi.fn()const mockUpdateCategory = vi.fn()-const mockLogAction = vi.fn()+const mockDeleteCategory = vi.fn()+const mockHasChannels = vi.fn()const mockFanOut = vi.fn()--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))+const mockLogAudit = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -22,9 +24,8 @@ vi.mock("@alook/shared", async () => {communityCategory: {getCategory: (...a: unknown[]) => mockGetCategory(...a),updateCategory: (...a: unknown[]) => mockUpdateCategory(...a),- },- communityAuditLog: {- logAction: (...a: unknown[]) => mockLogAction(...a),+ deleteCategory: (...a: unknown[]) => mockDeleteCategory(...a),+ hasChannels: (...a: unknown[]) => mockHasChannels(...a),},},}@@ -34,6 +35,11 @@ vi.mock("@/lib/community/fanout", () => ({fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),}))+vi.mock("@/lib/community/audit", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }+})+vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params@@ -45,12 +51,11 @@ vi.mock("@/lib/middleware/helpers", () => {const { NextResponse } = require("next/server")return {writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),}})-import { PATCH } from "./route"+import { PATCH, DELETE } from "./route"const ctx = { params: { id: "s1", catId: "cat1" } } as any@@ -62,21 +67,26 @@ function patchReq(body: unknown) {})}-describe("PATCH /api/community/servers/[id]/categories/[catId]", () => {+function delReq() {+ return new NextRequest("http://localhost/api/community/servers/s1/categories/cat1", { method: "DELETE" })+}++describe("PATCH /api/community/servers/[id]/categories/[catId] — unique name", () => {beforeEach(() => {vi.clearAllMocks()mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", creatorId: "u1" })mockFanOut.mockResolvedValue(undefined)- mockLogAction.mockResolvedValue(undefined)+ mockLogAudit.mockResolvedValue(undefined)})it("renames a category", async () => {- mockUpdateCategory.mockResolvedValue({ id: "cat1", name: "General" })+ mockUpdateCategory.mockResolvedValue({ id: "cat1", name: "GENERAL" })const res = await PATCH(patchReq({ name: "General" }), ctx)expect(res.status).toBe(200)- expect(mockUpdateCategory).toHaveBeenCalledWith(expect.anything(), "cat1", { name: "General" })+ // Category names are stored uppercased (matches the client's optimistic rename).+ expect(mockUpdateCategory).toHaveBeenCalledWith(expect.anything(), "cat1", { name: "GENERAL" })})it("returns 409 when renaming onto a name already used by another category in the server", async () => {@@ -96,3 +106,70 @@ describe("PATCH /api/community/servers/[id]/categories/[catId]", () => {await expect(PATCH(patchReq({ name: "General" }), ctx)).rejects.toThrow("boom")})})++describe("PATCH /categories/[catId] — permission + immutable privacy", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", private: 0 })+ mockUpdateCategory.mockResolvedValue({ id: "cat1", serverId: "s1", name: "X", private: 0 })+ mockHasChannels.mockResolvedValue(false)+ })++ it("rejects a plain member with 403", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "member" })+ const res = await PATCH(patchReq({ name: "New" }), ctx)+ expect(res.status).toBe(403)+ })++ it("admin can rename", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ const res = await PATCH(patchReq({ name: "New" }), ctx)+ expect(res.status).toBe(200)+ expect(mockUpdateCategory).toHaveBeenCalled()+ })++ it("ignores private (immutable after creation): a private-only body is 'no changes'", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ const res = await PATCH(patchReq({ private: true }), ctx)+ expect(res.status).toBe(400) // no name → nothing to change+ expect(mockUpdateCategory).not.toHaveBeenCalled()+ })++ it("renames and drops any private field from the update", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ const res = await PATCH(patchReq({ name: "New", private: true }), ctx)+ expect(res.status).toBe(200)+ // Category names are stored uppercased (matches the client's optimistic rename).+ expect(mockUpdateCategory).toHaveBeenCalledWith(expect.anything(), "cat1", { name: "NEW" })+ })+})++describe("DELETE /categories/[catId]", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", private: 1 })+ mockDeleteCategory.mockResolvedValue({ id: "cat1" })+ })++ it("rejects a plain member with 403", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "member" })+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(403)+ })++ it("blocks delete when the category still has channels (409, no widening)", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ mockHasChannels.mockResolvedValue(true)+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(409)+ expect(mockDeleteCategory).not.toHaveBeenCalled()+ })++ it("admin deletes an empty category", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ mockHasChannels.mockResolvedValue(false)+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(204)+ expect(mockDeleteCategory).toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.tsindex 53b495b5a..1c3244b4a 100644--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts@@ -4,14 +4,13 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import {queries,- canManageServer,isUniqueConstraintError,MAX_CATEGORY_NAME_LENGTH,WS_EVENTS,} from "@alook/shared"import { fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"-import { requireServerMember } from "@/lib/community/permissions"+import { requireServerAdmin } from "@/lib/community/permissions"export const PATCH = withAuth(async (req: NextRequest, ctx) => {const serverId = ctx.params?.id@@ -19,39 +18,35 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {if (!serverId || !categoryId) return writeError("missing params", 400)const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)+ const auth = await requireServerAdmin(db, serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const member = auth.value!const category = await queries.communityCategory.getCategory(db, categoryId)if (!category || category.serverId !== serverId) return writeError("category not found", 404)- const isAdmin = canManageServer(member.role)- if (!isAdmin && category.creatorId !== ctx.userId) {- return writeError("forbidden", 403)- }-- let body: { name?: string; private?: boolean }+ // Only the name is mutable. Category privacy (public/private) is fixed at+ // creation — flipping it would silently widen/tighten channel visibility, so+ // `private` is intentionally NOT accepted here (change it by recreating the+ // category). See plans/channel-category-role-permissions.md.+ let body: { name?: string }try {body = await req.json()} catch {return writeError("invalid request body", 400)}- if (body.private !== undefined && !isAdmin) {- return writeError("only admins can change private setting", 403)- }-- const changes: { name?: string; private?: boolean } = {}+ const changes: { name?: string } = {}if (body.name !== undefined) {if (typeof body.name !== "string") return writeError("name must be a string", 400)const trimmed = body.name.trim()if (!trimmed || trimmed.length > MAX_CATEGORY_NAME_LENGTH) {return writeError(`name must be 1-${MAX_CATEGORY_NAME_LENGTH} characters`, 400)}- changes.name = trimmed+ // Category names are displayed uppercase; store them uppercased so the+ // persisted value matches the client's optimistic rename (which uppercases+ // too) — otherwise the sidebar briefly diverges until the next refetch.+ changes.name = trimmed.toUpperCase()}- if (body.private !== undefined) changes.private = body.privateif (Object.keys(changes).length === 0) {return writeError("no changes provided", 400)@@ -93,16 +88,19 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {if (!serverId || !categoryId) return writeError("missing params", 400)const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)+ const auth = await requireServerAdmin(db, serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const member = auth.value!const category = await queries.communityCategory.getCategory(db, categoryId)if (!category || category.serverId !== serverId) return writeError("category not found", 404)- const isAdmin = canManageServer(member.role)- if (!isAdmin && category.creatorId !== ctx.userId) {- return writeError("forbidden", 403)+ // Deleting a non-empty category would `set null` its channels' categoryId,+ // silently re-classifying private channels as public (visible to everyone)+ // while leaving stale channel_member rows. Block it; admin moves/deletes the+ // channels first.+ const hasChannels = await queries.communityCategory.hasChannels(db, categoryId)+ if (hasChannels) {+ return writeError("Move or delete its channels first", 409)}const deleted = await queries.communityCategory.deleteCategory(db, categoryId)diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/route.test.tsindex e3b11302e..2ec16732e 100644--- a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts@@ -63,7 +63,8 @@ function postReq(body: unknown) {describe("POST /api/community/servers/[id]/categories", () => {beforeEach(() => {vi.clearAllMocks()- mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })+ // Category creation is admin/owner-only in the permission model.+ mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })mockFanOut.mockResolvedValue(undefined)mockLogAction.mockResolvedValue(undefined)})diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.ts b/src/web/src/app/api/community/servers/[id]/categories/route.tsindex 98f1d0ebd..9435821f1 100644--- a/src/web/src/app/api/community/servers/[id]/categories/route.ts+++ b/src/web/src/app/api/community/servers/[id]/categories/route.ts@@ -4,23 +4,21 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import {queries,- canManageServer,isUniqueConstraintError,MAX_CATEGORY_NAME_LENGTH,WS_EVENTS,} from "@alook/shared"import { fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"-import { requireServerMember } from "@/lib/community/permissions"+import { requireServerAdmin } from "@/lib/community/permissions"export const POST = withAuth(async (req: NextRequest, ctx) => {const serverId = ctx.params?.idif (!serverId) return writeError("missing server id", 400)const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)+ const auth = await requireServerAdmin(db, serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const member = auth.value!let body: { name?: string; private?: boolean }try {@@ -37,10 +35,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError(`name must be 1-${MAX_CATEGORY_NAME_LENGTH} characters`, 400)}- if (body.private && !canManageServer(member.role)) {- return writeError("only admins can create private categories", 403)- }-+ // requireServerAdmin above already guarantees admin/owner, so main's+ // per-member private-create check is redundant here. Keep the unique-name+ // 409 wrapper.let rowtry {row = await queries.communityCategory.createCategory(db, {diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.test.tsindex d7e66962a..70799ad92 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.test.ts@@ -1,15 +1,18 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"-const mockGetMember = vi.fn()-const mockCreateChannel = vi.fn()-const mockLogAction = vi.fn()-const mockFanOut = vi.fn()-vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),}))+const mockGetMember = vi.fn()+const mockGetCategory = vi.fn()+const mockCreateChannel = vi.fn()+const mockCreateChannelMember = vi.fn()+const mockFanOutToServerMembers = vi.fn()+const mockFanOutToChannel = vi.fn()+const mockLogAudit = vi.fn()+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))vi.mock("@alook/shared", async () => {@@ -18,19 +21,23 @@ vi.mock("@alook/shared", async () => {...actual,queries: {communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },+ communityCategory: { getCategory: (...a: unknown[]) => mockGetCategory(...a) },communityChannel: {createChannel: (...a: unknown[]) => mockCreateChannel(...a),- },- communityAuditLog: {- logAction: (...a: unknown[]) => mockLogAction(...a),+ createChannelMember: (...a: unknown[]) => mockCreateChannelMember(...a),},},}})vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),+ fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),+ fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),}))+vi.mock("@/lib/community/audit", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }+})vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {@@ -43,43 +50,69 @@ vi.mock("@/lib/middleware/helpers", () => {const { NextResponse } = require("next/server")return {writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),}})import { POST } from "./route"const ctx = { params: { id: "s1" } } as any--function postReq(body: unknown) {+function req(body: unknown) {return new NextRequest("http://localhost/api/community/servers/s1/channels", {method: "POST",body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },})}-describe("POST /api/community/servers/[id]/channels", () => {+describe("POST /servers/[id]/channels", () => {beforeEach(() => {vi.clearAllMocks()- mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })- mockFanOut.mockResolvedValue(undefined)- mockLogAction.mockResolvedValue(undefined)+ mockCreateChannel.mockResolvedValue({+ id: "c_new", name: "chan", type: "text", categoryId: null, topic: "", position: 0,+ createdAt: "2026-07-12T00:00:00Z",+ })})- it("normalizes a spaced name via slugify before creating the channel", async () => {- mockCreateChannel.mockResolvedValue({- id: "c1",- name: "General-Chat",- type: "text",- categoryId: null,- topic: null,- position: 0,- createdAt: "2026-07-02T00:00:00.000Z",+ it("rejects a plain member creating an uncategorized channel (403, admin-only)", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "member" })+ const res = await POST(req({ name: "chan" }), ctx)+ expect(res.status).toBe(403)+ expect(mockCreateChannel).not.toHaveBeenCalled()+ })++ it("admin can create an uncategorized channel; fans out server-wide", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ const res = await POST(req({ name: "chan" }), ctx)+ expect(res.status).toBe(201)+ expect(mockFanOutToServerMembers).toHaveBeenCalled()+ expect(mockFanOutToChannel).not.toHaveBeenCalled()+ })++ it("rejects a plain member creating in a public category (403)", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "member" })+ mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", private: 0 })+ const res = await POST(req({ name: "chan", categoryId: "cat1" }), ctx)+ expect(res.status).toBe(403)+ })++ it("member CAN create in a private category; seeds a creator member row + channel-scoped fanout", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "member" })+ mockGetCategory.mockResolvedValue({ id: "cat1", serverId: "s1", private: 1 })+ const res = await POST(req({ name: "chan", categoryId: "cat1" }), ctx)+ expect(res.status).toBe(201)+ expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), {+ channelId: "c_new",+ userId: "u1",+ addedBy: "u1",})+ expect(mockFanOutToChannel).toHaveBeenCalled()+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()+ })- const res = await POST(postReq({ name: "General Chat" }), ctx)+ it("normalizes a spaced name via slugify before creating the channel", async () => {+ // Admin, since an uncategorized channel is admin-only to create.+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ const res = await POST(req({ name: "General Chat" }), ctx)expect(res.status).toBe(201)expect(mockCreateChannel).toHaveBeenCalledWith(expect.anything(),@@ -88,27 +121,30 @@ describe("POST /api/community/servers/[id]/channels", () => {})it("returns 400 (and never calls createChannel) when the name is all disallowed characters", async () => {- const res = await POST(postReq({ name: "###" }), ctx)+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })+ const res = await POST(req({ name: "###" }), ctx)expect(res.status).toBe(400)expect(mockCreateChannel).not.toHaveBeenCalled()- expect(mockFanOut).not.toHaveBeenCalled()})it("returns 409 when a channel with this name already exists in the server", async () => {+ // Uncategorized create is admin-only.+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })mockCreateChannel.mockRejectedValue(Object.assign(new Error("UNIQUE constraint failed: community_channel.server_id, community_channel.name"), {code: "SQLITE_CONSTRAINT_UNIQUE",}),)- const res = await POST(postReq({ name: "general" }), ctx)+ const res = await POST(req({ name: "general" }), ctx)expect(res.status).toBe(409)expect(await res.json()).toEqual({ error: "a channel with this name already exists" })- expect(mockFanOut).not.toHaveBeenCalled()+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()})it("rethrows non-uniqueness errors from createChannel", async () => {+ mockGetMember.mockResolvedValue({ id: "m1", role: "admin" })mockCreateChannel.mockRejectedValue(new Error("boom"))- await expect(POST(postReq({ name: "general" }), ctx)).rejects.toThrow("boom")+ await expect(POST(req({ name: "general" }), ctx)).rejects.toThrow("boom")})})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 cc87cdc00..9dd70497a 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@@ -13,7 +13,7 @@ import {slugify,type ChannelType,} from "@alook/shared"-import { fanOutToServerMembers } from "@/lib/community/fanout"+import { fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"import { logAudit } from "@/lib/community/audit"import { requireServerMember } from "@/lib/community/permissions"@@ -54,15 +54,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}}+ // Who may create depends on the target location:+ // - uncategorized OR public category → admin/owner only+ // - private category → any server member (they own the channel + its roster)const isAdmin = canManageServer(member.role)+ let isPrivateCategory = falseif (body.categoryId) {const category = await queries.communityCategory.getCategory(db, body.categoryId)if (!category || category.serverId !== serverId) {return writeError("category not found", 404)}- if (category.private && !isAdmin) {- return writeError("only admins can create channels in private categories", 403)- }+ isPrivateCategory = !!category.private+ }+ if (!isPrivateCategory && !isAdmin) {+ return writeError("admin permission required", 403)}let row@@ -82,6 +87,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {throw err}+ // Private-category channels track an explicit roster; seed the creator so+ // audience resolution + the manage-members list are single queries.+ if (isPrivateCategory) {+ await queries.communityChannel.createChannelMember(db, {+ channelId: row.id,+ userId: ctx.userId,+ addedBy: ctx.userId,+ })+ }+const channel = {id: row.id,name: row.name,@@ -92,11 +107,22 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {createdAt: row.createdAt,}- await fanOutToServerMembers(serverId, {- type: WS_EVENTS.CHANNEL_CREATE,- serverId,- channel,- })+ // A private channel's creation must NOT fan out to the whole server (that+ // would leak its existence). Route it through the channel audience (creator+ // + admins); public/uncategorized channels stay server-wide.+ if (isPrivateCategory) {+ await fanOutToChannel(row.id, {+ type: WS_EVENTS.CHANNEL_CREATE,+ serverId,+ channel,+ })+ } else {+ await fanOutToServerMembers(serverId, {+ type: WS_EVENTS.CHANNEL_CREATE,+ serverId,+ channel,+ })+ }logAudit(db, {serverId,diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.tsindex 4672fcdd5..66ff0995e 100644--- a/src/web/src/app/api/community/servers/[id]/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts@@ -8,6 +8,7 @@ const mockFanOut = vi.fn()const mockGetServer = vi.fn()const mockListServerChannels = vi.fn()const mockListUnreadChannels = vi.fn()+const mockListVisibleChannelIds = vi.fn()const mockFindManyCategories = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({@@ -31,7 +32,8 @@ vi.mock("@alook/shared", async () => {updateServer: (...a: unknown[]) => mockUpdateServer(...a),},communityChannel: {- listServerChannels: (...a: unknown[]) => mockListServerChannels(...a),+ listServerChannelsForViewer: (...a: unknown[]) => mockListServerChannels(...a),+ listVisibleChannelIdsForUser: (...a: unknown[]) => mockListVisibleChannelIds(...a),},communityInbox: {listUnreadChannels: (...a: unknown[]) => mockListUnreadChannels(...a),@@ -112,6 +114,7 @@ describe("GET /api/community/servers/[id]", () => {beforeEach(() => {vi.clearAllMocks()+ mockListVisibleChannelIds.mockResolvedValue([])mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })mockGetServer.mockResolvedValue({id: "s1",diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.tsindex 648c0620f..e7c80d1e4 100644--- a/src/web/src/app/api/community/servers/[id]/route.ts+++ b/src/web/src/app/api/community/servers/[id]/route.ts@@ -4,6 +4,7 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import {queries,+ canManageServer,isServerOwner,MAX_SERVER_NAME_LENGTH,MAX_SERVER_DESCRIPTION_LENGTH,@@ -22,15 +23,20 @@ export const GET = withAuth(async (_req, ctx) => {const db = getDb(ctx.env.DB)const auth = await requireServerMember(db, serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)+ const isAdmin = canManageServer(auth.value!.role)+ const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)const [server, rawChannels, categories, unreadRows] = await Promise.all([queries.communityServer.getServer(db, serverId),- queries.communityChannel.listServerChannels(db, serverId),+ // Viewer-scoped: private-category channels are only returned if the viewer+ // is an admin, the channel creator, or an added member. Private category+ // HEADERS still appear (below) so members can create channels in them.+ queries.communityChannel.listServerChannelsForViewer(db, serverId, ctx.userId, { isAdmin }),db.query.communityCategory.findMany({where: (t, { eq }) => eq(t.serverId, serverId),orderBy: (t, { asc }) => [asc(t.position)],}),- queries.communityInbox.listUnreadChannels(db, ctx.userId),+ queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds),])if (!server) return writeError("server not found", 404)@@ -54,7 +60,11 @@ export const GET = withAuth(async (_req, ctx) => {categoriesWithChannels.push({id: "__uncategorized__",serverId: server.id,- name: "Channels",+ // Empty name is load-bearing: the sidebar detects the uncategorized+ // bucket by `name === ""` (renders its channels as the bare top list, and+ // maps a drag INTO it back to `categoryId: null`). Must match the mock in+ // preview/_mock.ts.+ name: "",position: -1,private: 0,channels: uncategorized,diff --git a/src/web/src/app/api/community/threads/[id]/read/route.test.ts b/src/web/src/app/api/community/threads/[id]/read/route.test.tsindex 49d32dec3..9e8cff195 100644--- a/src/web/src/app/api/community/threads/[id]/read/route.test.ts+++ b/src/web/src/app/api/community/threads/[id]/read/route.test.ts@@ -9,9 +9,14 @@ const mockGetChannel = vi.fn()const mockGetChannelForMember = vi.fn()const mockGetMessage = vi.fn()const mockGetLatestMessage = vi.fn()-const mockMarkReadToMessage = vi.fn()+const mockMarkReadToMessageBuilder = vi.fn()+const mockMarkChannelMentionsReadBuilder = vi.fn()+const mockBatch = vi.fn()-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+// The route now fires read-watermark + mention-clear in one `db.batch([...])`+// (mirrors the channel read route). The builders return opaque statement+// markers the batch collects; assert on the builder args, not the statements.+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ batch: (...a: unknown[]) => mockBatch(...a) })) }))vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -27,7 +32,10 @@ vi.mock("@alook/shared", async () => {getLatestMessage: (...a: unknown[]) => mockGetLatestMessage(...a),},communityReadState: {- markReadToMessage: (...a: unknown[]) => mockMarkReadToMessage(...a),+ markReadToMessageBuilder: (...a: unknown[]) => mockMarkReadToMessageBuilder(...a),+ },+ communityMention: {+ markChannelMentionsReadBuilder: (...a: unknown[]) => mockMarkChannelMentionsReadBuilder(...a),},},}@@ -62,10 +70,12 @@ function putReq(body?: unknown) {describe("PUT /api/community/threads/[id]/read", () => {beforeEach(() => {vi.clearAllMocks()- mockMarkReadToMessage.mockResolvedValue(undefined)+ mockMarkReadToMessageBuilder.mockReturnValue({ __stmt: "read" })+ mockMarkChannelMentionsReadBuilder.mockReturnValue({ __stmt: "mentions" })+ mockBatch.mockResolvedValue(undefined)})- it("body id present: fetches message, scope-checks, aligns write to (msg.id, msg.createdAt)", async () => {+ it("body id present: fetches message, scope-checks, batches read + mention-clear to (msg.id, msg.createdAt)", async () => {mockGetChannel.mockResolvedValue({ id: "t1", serverId: "s1" })mockGetChannelForMember.mockResolvedValue({ id: "t1", serverId: "s1" })mockGetMessage.mockResolvedValue({@@ -78,13 +88,16 @@ describe("PUT /api/community/threads/[id]/read", () => {expect(res.status).toBe(200)expect(mockGetMessage).toHaveBeenCalledWith(expect.anything(), "m9")- expect(mockMarkReadToMessage).toHaveBeenCalledTimes(1)- const call = mockMarkReadToMessage.mock.calls[0][1]- expect(call).toEqual({+ expect(mockMarkReadToMessageBuilder).toHaveBeenCalledTimes(1)+ expect(mockMarkReadToMessageBuilder.mock.calls[0][1]).toEqual({userId: "u1",channelId: "t1",message: { id: "m9", createdAt: "2026-07-04T09:00:00.000Z" },})+ // The thread's own mentions are cleared in the same batch (plan gap #4).+ expect(mockMarkChannelMentionsReadBuilder).toHaveBeenCalledWith(expect.anything(), "u1", "t1")+ expect(mockBatch).toHaveBeenCalledTimes(1)+ expect(mockBatch.mock.calls[0][0]).toEqual([{ __stmt: "read" }, { __stmt: "mentions" }])expect(mockGetLatestMessage).not.toHaveBeenCalled()})@@ -99,7 +112,7 @@ describe("PUT /api/community/threads/[id]/read", () => {const res = await PUT(putReq({ lastReadMessageId: "m9" }), { params: { id: "t1" } } as any)expect(res.status).toBe(400)- expect(mockMarkReadToMessage).not.toHaveBeenCalled()+ expect(mockBatch).not.toHaveBeenCalled()})it("body id present but message does not exist → 404, no write", async () => {@@ -109,7 +122,7 @@ describe("PUT /api/community/threads/[id]/read", () => {const res = await PUT(putReq({ lastReadMessageId: "m_ghost" }), { params: { id: "t1" } } as any)expect(res.status).toBe(404)- expect(mockMarkReadToMessage).not.toHaveBeenCalled()+ expect(mockBatch).not.toHaveBeenCalled()})it("no body: uses latest message and aligns write to it", async () => {@@ -123,11 +136,12 @@ describe("PUT /api/community/threads/[id]/read", () => {const res = await PUT(putReq(), { params: { id: "t1" } } as any)expect(res.status).toBe(200)expect(mockGetLatestMessage).toHaveBeenCalledWith(expect.anything(), { channelId: "t1" })- expect(mockMarkReadToMessage).toHaveBeenCalledWith(expect.anything(), {+ expect(mockMarkReadToMessageBuilder).toHaveBeenCalledWith(expect.anything(), {userId: "u1",channelId: "t1",message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z" },})+ expect(mockBatch).toHaveBeenCalledTimes(1)// Body path never consults getMessage.expect(mockGetMessage).not.toHaveBeenCalled()})@@ -140,7 +154,7 @@ describe("PUT /api/community/threads/[id]/read", () => {const res = await PUT(putReq(), { params: { id: "t1" } } as any)expect(res.status).toBe(200)expect(await res.json()).toEqual({ ok: true })- expect(mockMarkReadToMessage).not.toHaveBeenCalled()+ expect(mockBatch).not.toHaveBeenCalled()})it("returns 400 when the id is missing", async () => {@@ -156,7 +170,7 @@ describe("PUT /api/community/threads/[id]/read", () => {const res = await PUT(putReq(), { params: { id: "t1" } } as any)expect(res.status).toBe(404)expect(mockGetChannelForMember).not.toHaveBeenCalled()- expect(mockMarkReadToMessage).not.toHaveBeenCalled()+ expect(mockBatch).not.toHaveBeenCalled()})it("returns 403 when the channel exists but the caller is not a member", async () => {@@ -165,6 +179,6 @@ describe("PUT /api/community/threads/[id]/read", () => {const res = await PUT(putReq(), { params: { id: "t1" } } as any)expect(res.status).toBe(403)- expect(mockMarkReadToMessage).not.toHaveBeenCalled()+ expect(mockBatch).not.toHaveBeenCalled()})})diff --git a/src/web/src/app/api/community/threads/[id]/read/route.ts b/src/web/src/app/api/community/threads/[id]/read/route.tsindex e67bd4058..f16a72ffa 100644--- a/src/web/src/app/api/community/threads/[id]/read/route.ts+++ b/src/web/src/app/api/community/threads/[id]/read/route.ts@@ -49,11 +49,18 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {if (!target) return writeJSON({ ok: true })}- await queries.communityReadState.markReadToMessage(db, {- userId: ctx.userId,- channelId,- message: target,- })+ // A thread IS a channel — mirror the channel read route: advance the read+ // watermark AND clear the thread's own mentions in one D1 batch (keyed on the+ // thread's channelId). Without the mention clear, opening a thread wouldn't+ // dismiss its mentions (plan gap #4).+ await db.batch([+ queries.communityReadState.markReadToMessageBuilder(db, {+ userId: ctx.userId,+ channelId,+ message: target,+ }),+ queries.communityMention.markChannelMentionsReadBuilder(db, ctx.userId, channelId),+ ])return writeJSON({ ok: true })})diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsxindex cf0186dbc..96414f911 100644--- a/src/web/src/app/community/channels/layout.tsx+++ b/src/web/src/app/community/channels/layout.tsx@@ -40,6 +40,7 @@ import { useNotificationSettings } from "@/hooks/community/use-notification-settimport {useCreateChannel,useDeleteChannel,+ useMoveChannel,useCreateCategory,useUpdateCategory,useDeleteCategory,@@ -105,6 +106,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {// Mutationsconst createChannelMut = useCreateChannel()const deleteChannelMut = useDeleteChannel()+ const moveChannelMut = useMoveChannel()const createCategoryMut = useCreateCategory()const updateCategoryMut = useUpdateCategory()const deleteCategoryMut = useDeleteCategory()@@ -310,8 +312,8 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const onDeleteCategoryInSidebar = useCallback((categoryId: string) => {deleteCategoryMut.mutate({ serverId, categoryId }, { onError: () => toast("Failed to delete category") })}, [deleteCategoryMut, serverId])- const onUpdateCategoryInSidebar = useCallback((categoryId: string, opts: { name?: string; isPrivate?: boolean }) => {- updateCategoryMut.mutate({ serverId, categoryId, name: opts.name, isPrivate: opts.isPrivate }, { onError: () => toast("Failed to update category") })+ const onUpdateCategoryInSidebar = useCallback((categoryId: string, opts: { name?: string }) => {+ updateCategoryMut.mutate({ serverId, categoryId, name: opts.name }, { onError: () => toast("Failed to update category") })}, [updateCategoryMut, serverId])const onReorderCategoriesInSidebar = useCallback((categoryIds: string[]) => {reorderCategoriesMut.mutate({ serverId, categoryIds }, { onError: () => toast("Failed to save category order") })@@ -319,6 +321,12 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const onReorderChannelsInSidebar = useCallback((channelIds: string[]) => {reorderChannelsMut.mutate({ serverId, channelIds }, { onError: () => toast("Failed to save channel order") })}, [reorderChannelsMut, serverId])+ const onMoveChannelInSidebar = useCallback((channelId: string, categoryId: string | null) => {+ moveChannelMut.mutate({ serverId, channelId, categoryId }, { onError: () => toast("Failed to move channel") })+ }, [moveChannelMut, serverId])+ const onBlockedMove = useCallback(() => {+ toast("Can't move a channel between public and private categories")+ }, [])const channelProps = useMemo(() => ({tree: channelTree,@@ -339,6 +347,8 @@ export default function ServerLayout({ children }: { children: ReactNode }) {onUpdateCategory: onUpdateCategoryInSidebar,onReorderCategories: onReorderCategoriesInSidebar,onReorderChannels: onReorderChannelsInSidebar,+ onMoveChannel: onMoveChannelInSidebar,+ onBlockedMove,serverId,invitePopoverOpen,onInvitePopoverOpenChange: setInvitePopoverOpen,@@ -349,6 +359,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel,onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar,onReorderCategoriesInSidebar, onReorderChannelsInSidebar,+ onMoveChannelInSidebar, onBlockedMove,serverId, invitePopoverOpen,])diff --git a/src/web/src/app/community/preview/_mock.ts b/src/web/src/app/community/preview/_mock.tsindex d182ae966..9b23ec95f 100644--- a/src/web/src/app/community/preview/_mock.ts+++ b/src/web/src/app/community/preview/_mock.ts@@ -339,15 +339,23 @@ export const UNREAD_SERVERS: UnreadServer[] = [serverId: "sv_alook",serverName: "Alook",channels: [- { channelId: "ch_general", channelName: "general", lastMessageAt: "2026-06-25T10:00:00Z", mentionCount: 1 },- { channelId: "ch_releases", channelName: "releases", lastMessageAt: "2026-06-25T07:30:00Z", mentionCount: 0 },+ {+ channelId: "ch_general",+ channelName: "general",+ lastMessageAt: "2026-06-25T10:00:00Z",+ mentionCount: 1,+ children: [+ { channelId: "th_budget", channelName: "budget-2026", lastMessageAt: "2026-06-25T09:45:00Z", mentionCount: 0 },+ ],+ },+ { channelId: "ch_releases", channelName: "releases", lastMessageAt: "2026-06-25T07:30:00Z", mentionCount: 0, children: [] },],},{serverId: "sv_cf",serverName: "Cloudflare",channels: [- { channelId: "ch_flagship", channelName: "flagship", lastMessageAt: "2026-06-25T08:43:00Z", mentionCount: 1 },+ { channelId: "ch_flagship", channelName: "flagship", lastMessageAt: "2026-06-25T08:43:00Z", mentionCount: 1, children: [] },],},]diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex afb082990..6a30536d5 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -253,6 +253,10 @@ export type AuditEntry = {// ── Mentions / inbox ─────────────────────────────────────────────────────────export type Mention = {id: string+ // "mention" (@-mention) vs "reply" (reply to your message). Drives the row+ // label ("mentioned you" vs "replied to you"). Optional for back-compat with+ // any cached payload written before the field existed.+ kind?: "mention" | "reply"server: stringserverId?: stringchannel: string@@ -260,7 +264,17 @@ export type Mention = {m: Msg}-// "Unreads" — channels with unread messages, grouped by server.+// A single unread thread / forum-post nested under its parent channel.+type UnreadChild = {+ channelId: string+ channelName: string+ lastMessageAt: string+ mentionCount: number+}++// "Unreads" — channels with unread messages, grouped by server. Each channel+// may carry `children` (unread threads/forum-posts) rendered as indented+// sub-rows; a parent can appear solely to host unread children.export type UnreadServer = {serverId: stringserverName: string@@ -269,6 +283,7 @@ export type UnreadServer = {channelName: stringlastMessageAt: stringmentionCount: number+ children: UnreadChild[]}>}diff --git a/src/web/src/components/community/category-settings-dialog.tsx b/src/web/src/components/community/category-settings-dialog.tsxindex a79152b47..7d88fd6d6 100644--- a/src/web/src/components/community/category-settings-dialog.tsx+++ b/src/web/src/components/community/category-settings-dialog.tsx@@ -4,43 +4,57 @@ import { useState } from "react"import { Lock } from "lucide-react"import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"import { Button } from "@/components/ui/button"-import { Switch } from "@/components/ui/switch"+import { Input } from "@/components/ui/input"+import { Field } from "./field"-// Category settings dialog — toggle privacy. A private category restricts channel-// creation to admins (default public).-export function CategorySettingsDialog({ name, isPrivate, canTogglePrivate = true, onClose, onSave }: {+// Category settings dialog — rename only. Privacy (public/private) is fixed at+// creation and can't be changed here: flipping it would silently widen/tighten+// channel visibility. To change privacy, delete the category and recreate it.+// The current privacy is shown read-only for context.+export function CategorySettingsDialog({ name, isPrivate, onClose, onSave }: {name: stringisPrivate: boolean- canTogglePrivate?: booleanonClose: () => void- onSave: (isPrivate: boolean) => void+ onSave: (name: string) => void}) {- const [priv, setPriv] = useState(isPrivate)+ const [nameDraft, setNameDraft] = useState(name)+ const trimmedName = nameDraft.trim()+ const save = () => {+ if (!trimmedName) return+ onSave(trimmedName.toUpperCase())+ onClose()+ }return (<Dialog open onOpenChange={(o) => { if (!o) onClose() }}><DialogContent className="w-105 max-w-[calc(100vw-2rem)] p-0"><DialogHeader className="border-b border-border px-4 py-4"><DialogTitle>Category Settings</DialogTitle>- <p className="text-sm text-muted-foreground">{name}</p></DialogHeader>- <div className="px-4 pb-5">- {canTogglePrivate && (- <label className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-2">- <Lock className="size-4 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <div className="text-sm font-medium">Private Category</div>- <div className="text-xs text-muted-foreground">Only admins can create channels here.</div>+ <div className="space-y-4 px-4 pb-5">+ <Field label="Category name">+ <Input+ value={nameDraft}+ onChange={(e) => setNameDraft(e.target.value)}+ onKeyDown={(e) => { if (e.key === "Enter") save() }}+ placeholder="e.g. text channels"+ autoFocus+ />+ </Field>+ {isPrivate && (+ <div className="flex items-center gap-3 rounded-md border border-border bg-card px-3 py-2">+ <Lock className="size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium">Private category</div>+ <div className="text-xs text-muted-foreground">+ Members create their own channels here, visible only to invited members. Privacy can't be changed after creation.+ </div>+ </div></div>- <Switch checked={priv} onCheckedChange={setPriv} />- </label>- )}- {!canTogglePrivate && (- <p className="text-sm text-muted-foreground">No settings available to change.</p>)}</div><DialogFooter className="mx-0 mb-0 flex-row items-center justify-end gap-2 rounded-b-xl border-t border-border bg-card px-4 py-3"><Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>- {canTogglePrivate && <Button size="sm" onClick={() => { onSave(priv); onClose() }}>Save</Button>}+ <Button size="sm" onClick={save} disabled={!trimmedName}>Save</Button></DialogFooter></DialogContent></Dialog>diff --git a/src/web/src/components/community/channel-members-dialog.tsx b/src/web/src/components/community/channel-members-dialog.tsxnew file mode 100644index 000000000..40851f11b--- /dev/null+++ b/src/web/src/components/community/channel-members-dialog.tsx@@ -0,0 +1,153 @@+"use client"++import { useMemo, useState } from "react"+import { Search, X } from "lucide-react"+import { toast } from "sonner"+import { Dialog, DialogContent } from "@/components/ui/dialog"+import { Input } from "@/components/ui/input"+import { Button } from "@/components/ui/button"+import { Skeleton } from "@/components/ui/skeleton"+import { Avatar } from "./avatar"+import {+ useChannelMembers,+ useAddableMembers,+ useAddChannelMember,+ useRemoveChannelMember,+} from "@/hooks/community/use-channel-members"++/**+ * Manage the roster of a private-category channel: current members (creator+ * locked, everyone else removable) plus a picker of server members not yet in+ * the channel. Adding grants read/post access immediately; removing evicts.+ */+export function ChannelMembersDialog({+ channelId,+ channelName,+ serverId: _serverId,+ onClose,+}: {+ channelId: string+ channelName: string+ serverId: string+ onClose: () => void+}) {+ const { members, isLoading: membersLoading } = useChannelMembers(channelId)+ const { members: addable, isLoading: addableLoading } = useAddableMembers(channelId)+ const addMember = useAddChannelMember(channelId)+ const removeMember = useRemoveChannelMember(channelId)+ const [query, setQuery] = useState("")++ const filteredAddable = useMemo(() => {+ const q = query.trim().toLowerCase()+ if (!q) return addable+ return addable.filter((m) => (m.name ?? "").toLowerCase().includes(q))+ }, [addable, query])++ const onAdd = async (userId: string) => {+ try {+ await addMember.mutateAsync(userId)+ } catch (err) {+ toast(err instanceof Error ? err.message : "Couldn't add member")+ }+ }++ const onRemove = async (userId: string) => {+ try {+ await removeMember.mutateAsync(userId)+ } catch (err) {+ toast(err instanceof Error ? err.message : "Couldn't remove member")+ }+ }++ return (+ <Dialog open onOpenChange={(o) => { if (!o) onClose() }}>+ <DialogContent className="flex max-h-[80vh] w-full flex-col gap-0 p-0 sm:max-w-md">+ <header className="border-b border-border px-4 py-3">+ <h2 className="truncate text-sm font-semibold">Members of /{channelName}</h2>+ <p className="text-xs text-muted-foreground">+ Only these members and admins can see and post in this channel.+ </p>+ </header>++ <div className="min-h-0 flex-1 overflow-y-auto thin-scrollbar px-2 py-2">+ {membersLoading && members.length === 0 ? (+ <div className="space-y-2 px-2">+ {Array.from({ length: 3 }).map((_, i) => (+ <div key={i} className="flex items-center gap-3">+ <Skeleton className="size-8 rounded-full" />+ <Skeleton className="h-3 w-32 rounded" />+ </div>+ ))}+ </div>+ ) : (+ members.map((m) => (+ <div key={m.userId} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">+ <Avatar label={m.avatar || m.name || ""} size={32} />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium">+ {m.name ?? "Unknown"}+ {m.isCreator && (+ <span className="ml-2 text-xs font-normal text-muted-foreground">Creator</span>+ )}+ </div>+ </div>+ {!m.isCreator && (+ <button+ onClick={() => onRemove(m.userId)}+ disabled={removeMember.isPending}+ className="grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed"+ aria-label={`Remove ${m.name ?? "member"}`}+ title="Remove member"+ >+ <X className="size-4" />+ </button>+ )}+ </div>+ ))+ )}+ </div>++ <footer className="border-t border-border px-4 py-3">+ <div className="mb-2 text-xs font-medium text-muted-foreground">Add members</div>+ <label className="relative block">+ <Search aria-hidden className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search members"+ className="pl-9"+ />+ </label>+ <div className="mt-2 max-h-48 overflow-y-auto thin-scrollbar">+ {addableLoading && addable.length === 0 ? (+ <div className="space-y-2 py-2">+ {Array.from({ length: 3 }).map((_, i) => (+ <div key={i} className="flex items-center gap-3">+ <Skeleton className="size-8 rounded-full" />+ <Skeleton className="h-3 w-28 rounded" />+ </div>+ ))}+ </div>+ ) : filteredAddable.length === 0 ? (+ <p className="py-4 text-center text-sm text-muted-foreground">+ {addable.length === 0+ ? "Everyone in the server is already here."+ : "No matches."}+ </p>+ ) : (+ filteredAddable.map((m) => (+ <div key={m.userId} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">+ <Avatar label={m.avatar || m.name || ""} size={32} />+ <div className="min-w-0 flex-1 truncate text-sm font-medium">{m.name ?? "Unknown"}</div>+ <Button size="sm" disabled={addMember.isPending} onClick={() => onAdd(m.userId)}>+ Add+ </Button>+ </div>+ ))+ )}+ </div>+ </footer>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsxindex f01cf0fbb..e6a12e23a 100644--- a/src/web/src/components/community/channel-sidebar.tsx+++ b/src/web/src/components/community/channel-sidebar.tsx@@ -1,6 +1,6 @@"use client"-import { memo, useState } from "react"+import { memo, useRef, useState } from "react"import { Settings, Users, Link2, Bell, ScrollText, ChevronDown, UserPlus } from "lucide-react"import {DndContext, closestCenter, PointerSensor, useSensor, useSensors,@@ -14,8 +14,9 @@ import { SortableChannel } from "./sortable-channel"import { CreateChannelDialog } from "./create-channel-dialog"import { CreateCategoryDialog } from "./create-category-dialog"import { CategorySettingsDialog } from "./category-settings-dialog"-import { catId, type ChannelTree } from "./use-channel-tree"+import { catId, catOf, isCat, type ChannelTree } from "./use-channel-tree"import { InviteDialog } from "./invite-dialog"+import { ChannelMembersDialog } from "./channel-members-dialog"import type { Channel, SettingsSection } from "./_types"import type { ChannelType } from "@alook/shared"@@ -25,6 +26,7 @@ type Dialog =| { kind: "edit-channel"; id: string; categoryId: string; name: string; type: ChannelType }| { kind: "create-category" }| { kind: "category-settings"; categoryId: string }+ | { kind: "manage-members"; channelId: string; channelName: string }| null// The channel sidebar (server view). Category/channel reorder + add/remove/rename live in@@ -36,6 +38,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({isAdmin = true, currentUserId, onBlockedCreate, mutedChannels, loading,onCreateChannel, onCreateCategory, onDeleteChannel, onDeleteCategory,onUpdateCategory, onRenameChannel, onReorderCategories, onReorderChannels,+ onMoveChannel, onBlockedMove,serverId, invitePopoverOpen, onInvitePopoverOpenChange,}: {tree: ChannelTree@@ -53,16 +56,28 @@ export const ChannelSidebar = memo(function ChannelSidebar({onCreateCategory?: (name: string, opts?: { private?: boolean }) => Promise<string | null> | voidonDeleteChannel?: (channelId: string) => voidonDeleteCategory?: (categoryId: string) => void- onUpdateCategory?: (categoryId: string, opts: { name?: string; isPrivate?: boolean }) => void+ onUpdateCategory?: (categoryId: string, opts: { name?: string }) => voidonRenameChannel?: (channelId: string, name: string) => voidonReorderCategories?: (categoryIds: string[]) => voidonReorderChannels?: (channelIds: string[]) => void+ onMoveChannel?: (channelId: string, categoryId: string | null) => void+ onBlockedMove?: () => voidserverId?: stringinvitePopoverOpen?: booleanonInvitePopoverOpenChange?: (open: boolean) => void}) {- const { collapsed, catOrder, order, catNames, catPrivate, catCreators, toggleCat, removeChannel, renameChannel, removeCategory, setCategoryPrivate, onDragOver, onDragEnd: treeDragEnd } = tree+ const { collapsed, catOrder, order, catNames, catPrivate, toggleCat, removeChannel, renameChannel, removeCategory, renameCategory, onDragOver, onDragEnd: treeDragEnd } = tree+ // Category the dragged channel started in — captured at drag start, because+ // `onDragOver` mutates `order` mid-drag so by drop time it already reflects+ // the destination.+ const dragOriginCat = useRef<string | undefined>(undefined)+ const onDragStart = (e: { active: { id: string | number } }) => {+ const activeStr = String(e.active.id)+ dragOriginCat.current = isCat(activeStr) ? undefined : catOf(activeStr, order)+ }const onDragEnd = (e: Parameters<typeof treeDragEnd>[0]) => {+ const originCat = dragOriginCat.current+ dragOriginCat.current = undefinedtreeDragEnd(e)const { active, over } = eif (!over || active.id === over.id) return@@ -80,7 +95,29 @@ export const ChannelSidebar = memo(function ChannelSidebar({})() : nullif (reordered) onReorderCategories?.(reordered)} else if (!activeStr.startsWith("cat_")) {+ // The channel's category AFTER onDragOver settled the optimistic move.+ const destCat = catOf(activeStr, order)+ // A blocked public↔private move: the cursor landed in a different-privacy+ // category, so onDragOver refused to move it and destCat === originCat.+ // Detect the attempt from the drop target and warn.+ const dropTargetCat = isCat(overStr) ? overStr : catOf(overStr, order)+ if (+ originCat && dropTargetCat && dropTargetCat !== originCat &&+ destCat === originCat &&+ !!catPrivate[originCat] !== !!catPrivate[dropTargetCat]+ ) {+ onBlockedMove?.()+ return+ }+ // Persist a same-privacy cross-category move: write the new categoryId+ // (translating the synthetic uncategorized bucket to null), then reorder.const allChannelIds = catOrder.flatMap((cat) => (order[cat] ?? []).map((c) => c.id))+ if (destCat && originCat && destCat !== originCat) {+ // The uncategorized bucket (empty name, synthetic id) maps back to a+ // real `categoryId: null` for the PATCH.+ const isUncategorized = catNames[destCat] === "" || destCat === "__uncategorized__"+ onMoveChannel?.(activeStr, isUncategorized ? null : destCat)+ }onReorderChannels?.(allChannelIds)}}@@ -101,8 +138,13 @@ export const ChannelSidebar = memo(function ChannelSidebar({if (loading) return <ChannelSidebarSkeleton noHeader={noHeader} />+ // Who may create a channel where:+ // - uncategorized (empty categoryId) / public category → admins only+ // - private category → any member (they own the channel + its roster)+ const canCreateInCategory = (categoryId: string) =>+ catPrivate[categoryId] ? true : isAdminconst requestCreateChannel = (categoryId: string) => {- if (catPrivate[categoryId] && !isAdmin) { onBlockedCreate?.(); return }+ if (!canCreateInCategory(categoryId)) { onBlockedCreate?.(); return }setDialog({ kind: "create-channel", categoryId })}@@ -158,7 +200,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({render={<div className="flex-1 overflow-y-auto thin-scrollbar px-2 py-4" />}>{/* one DndContext spans everything: categories sort among themselves, channels across categories */}- <DndContext id="d-channels" sensors={sensors} collisionDetection={closestCenter} onDragOver={onDragOver} onDragEnd={onDragEnd}>+ <DndContext id="d-channels" sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragOver={onDragOver} onDragEnd={onDragEnd}>{/* uncategorized channels (empty-name category) render bare at the top — no header */}{noneCatId && order[noneCatId]?.length > 0 && (<SortableContext items={order[noneCatId].map((c) => c.id)} strategy={verticalListSortingStrategy}>@@ -168,9 +210,10 @@ export const ChannelSidebar = memo(function ChannelSidebar({key={ch.id}ch={withMute(ch)}active={ch.id === activeChannel}+ canReorder={isAdmin}onClick={() => setActiveChannel(ch.id)}- onEdit={(isAdmin || ch.creatorId === currentUserId) ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: noneCatId, name: ch.name, type: ch.type ?? "text" }) : undefined}- onDelete={(isAdmin || ch.creatorId === currentUserId) ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}+ onEdit={isAdmin ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: noneCatId, name: ch.name, type: ch.type ?? "text" }) : undefined}+ onDelete={isAdmin ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}/>))}</div>@@ -184,23 +227,33 @@ export const ChannelSidebar = memo(function ChannelSidebar({name={catNames[id] ?? id}open={!collapsed.has(id)}onToggle={() => toggleCat(id)}- onAddChannel={(!catPrivate[id] || isAdmin) ? () => requestCreateChannel(id) : undefined}+ onAddChannel={canCreateInCategory(id) ? () => requestCreateChannel(id) : undefined}onSettings={isAdmin ? () => setDialog({ kind: "category-settings", categoryId: id }) : undefined}- onDelete={(isAdmin || catCreators[id] === currentUserId) ? () => { removeCategory(id); onDeleteCategory?.(id) } : undefined}+ onDelete={isAdmin ? () => { removeCategory(id); onDeleteCategory?.(id) } : undefined}isPrivate={catPrivate[id]}+ canReorder={isAdmin}><SortableContext items={(order[id] ?? []).map((c) => c.id)} strategy={verticalListSortingStrategy}><div className="mt-1 min-h-2 space-y-1">- {(order[id] ?? []).map((ch) => (- <SortableChannel- key={ch.id}- ch={withMute(ch)}- active={ch.id === activeChannel}- onClick={() => setActiveChannel(ch.id)}- onEdit={(isAdmin || (!catPrivate[id] && ch.creatorId === currentUserId)) ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: id, name: ch.name, type: ch.type ?? "text" }) : undefined}- onDelete={(isAdmin || (!catPrivate[id] && ch.creatorId === currentUserId)) ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}- />- ))}+ {(order[id] ?? []).map((ch) => {+ // Manage/edit rights:+ // - admins everywhere+ // - private category: the channel creator too+ // Public-category channels are admin-managed only.+ const canManageChannel = isAdmin || (!!catPrivate[id] && ch.creatorId === currentUserId)+ return (+ <SortableChannel+ key={ch.id}+ ch={withMute(ch)}+ active={ch.id === activeChannel}+ canReorder={isAdmin}+ onClick={() => setActiveChannel(ch.id)}+ onEdit={canManageChannel ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: id, name: ch.name, type: ch.type ?? "text" }) : undefined}+ onDelete={canManageChannel ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}+ onManageMembers={(catPrivate[id] && canManageChannel) ? () => setDialog({ kind: "manage-members", channelId: ch.id, channelName: ch.name }) : undefined}+ />+ )+ })}</div></SortableContext></SortableCategory>@@ -209,8 +262,12 @@ export const ChannelSidebar = memo(function ChannelSidebar({</DndContext></ContextMenuTrigger><ContextMenuContent className="w-48">- <ContextMenuItem onClick={() => requestCreateChannel(noneCatId)}>Create channel</ContextMenuItem>- <ContextMenuItem onClick={() => setDialog({ kind: "create-category" })}>Create category</ContextMenuItem>+ {isAdmin && (+ <>+ <ContextMenuItem onClick={() => requestCreateChannel(noneCatId)}>Create channel</ContextMenuItem>+ <ContextMenuItem onClick={() => setDialog({ kind: "create-category" })}>Create category</ContextMenuItem>+ </>+ )}</ContextMenuContent></ContextMenu>@@ -240,9 +297,19 @@ export const ChannelSidebar = memo(function ChannelSidebar({<CategorySettingsDialogname={catNames[dialog.categoryId] ?? ""}isPrivate={!!catPrivate[dialog.categoryId]}- canTogglePrivate={isAdmin}onClose={() => setDialog(null)}- onSave={(priv) => { setCategoryPrivate(dialog.categoryId, priv); onUpdateCategory?.(dialog.categoryId, { isPrivate: priv }) }}+ onSave={(nextName) => {+ renameCategory(dialog.categoryId, nextName)+ onUpdateCategory?.(dialog.categoryId, { name: nextName })+ }}+ />+ )}+ {dialog?.kind === "manage-members" && serverId && (+ <ChannelMembersDialog+ channelId={dialog.channelId}+ channelName={dialog.channelName}+ serverId={serverId}+ onClose={() => setDialog(null)}/>)}</aside>diff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex 778cd8afb..35ed0a3a2 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -1,4 +1,4 @@-import { ChevronRight, Hash, Inbox, MoreHorizontal, Trash2 } from "lucide-react"+import { ChevronRight, CornerDownRight, Hash, Inbox, MoreHorizontal, Trash2 } from "lucide-react"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"@@ -6,6 +6,15 @@ import { Avatar } from "./avatar"import { EmptyState } from "./empty-state"import type { Mention, UnreadDm, UnreadServer } from "./_types"+function MentionBadge({ count }: { count: number }) {+ if (count <= 0) return null+ return (+ <span className="grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-xs font-semibold text-primary-foreground">+ {count}+ </span>+ )+}+function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {servers: UnreadServer[]dms: UnreadDm[]@@ -38,18 +47,30 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {<div key={s.serverId} className="mb-3"><div className="px-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{s.serverName}</div>{s.channels.map((c) => (- <button- key={c.channelId}- onClick={() => onOpenChannel?.(s.serverId, c.channelId)}- className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"- >- <Hash className="size-4 shrink-0 text-muted-foreground" />- <span className="min-w-0 flex-1 truncate">{c.channelName}</span>- {c.mentionCount > 0 && (- <span className="grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-xs font-semibold text-primary-foreground">{c.mentionCount}</span>- )}- <ChevronRight className="size-4 shrink-0 text-muted-foreground" />- </button>+ <div key={c.channelId}>+ <button+ onClick={() => onOpenChannel?.(s.serverId, c.channelId)}+ className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"+ >+ <Hash className="size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate">{c.channelName}</span>+ <MentionBadge count={c.mentionCount} />+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" />+ </button>+ {/* Unread threads / forum-posts, indented under their parent. */}+ {c.children.map((child) => (+ <button+ key={child.channelId}+ onClick={() => onOpenChannel?.(s.serverId, child.channelId)}+ className="flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm hover:bg-accent"+ >+ <CornerDownRight className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate text-muted-foreground">{child.channelName}</span>+ <MentionBadge count={child.mentionCount} />+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" />+ </button>+ ))}+ </div>))}</div>))}@@ -74,7 +95,9 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {<div className="min-w-0 flex-1"><div className="text-sm"><span className="font-medium">{mn.m.authorName}</span>{" "}- <span className="text-xs text-muted-foreground">in {mn.server} · #{mn.channel}</span>+ <span className="text-xs text-muted-foreground">+ {mn.kind === "reply" ? "replied to you" : "mentioned you"} in {mn.server} · #{mn.channel}+ </span></div><div className="truncate text-sm text-muted-foreground">{mn.m.content}</div></div>diff --git a/src/web/src/components/community/create-category-dialog.tsx b/src/web/src/components/community/create-category-dialog.tsxindex ee91ff006..e83e530be 100644--- a/src/web/src/components/community/create-category-dialog.tsx+++ b/src/web/src/components/community/create-category-dialog.tsx@@ -8,15 +8,17 @@ import { Input } from "@/components/ui/input"import { Switch } from "@/components/ui/switch"import { Field } from "./field"-// Create Category dialog — name + private toggle (default public). A private category-// restricts channel creation to admins.+// Create Category dialog — name + private toggle (defaults to private). In a+// private category any member can create a channel, but each channel is visible+// only to its creator + invited members (and admins). A public category's+// channels are admin-managed and visible to everyone.export function CreateCategoryDialog({ onClose, onCreate, canTogglePrivate = true }: {onClose: () => voidonCreate: (name: string, opts: { private: boolean }) => voidcanTogglePrivate?: boolean}) {const [name, setName] = useState("")- const [isPrivate, setIsPrivate] = useState(false)+ const [isPrivate, setIsPrivate] = useState(true)const submit = () => {const trimmed = name.trim()if (!trimmed) return@@ -44,7 +46,11 @@ export function CreateCategoryDialog({ onClose, onCreate, canTogglePrivate = tru<Lock className="size-4 shrink-0 text-muted-foreground" /><div className="min-w-0 flex-1"><div className="text-sm font-medium">Private category</div>- <div className="text-xs text-muted-foreground">Only admins can create channels here.</div>+ <div className="text-xs text-muted-foreground">+ {isPrivate+ ? "Members create their own channels here, visible only to invited members."+ : "Channels here are admin-managed and visible to everyone."}+ </div></div><Switch checked={isPrivate} onCheckedChange={setIsPrivate} /></label>diff --git a/src/web/src/components/community/message-list.older-load.test.ts b/src/web/src/components/community/message-list.older-load.test.tsnew file mode 100644index 000000000..c937408ac--- /dev/null+++ b/src/web/src/components/community/message-list.older-load.test.ts@@ -0,0 +1,121 @@+import { describe, it, expect, vi } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { MessageList } from "./message-list"++// Regression for the "scroll up once → loads ALL history" cascade.+//+// The top sentinel's IntersectionObserver must stay STABLE across fetch-state+// ticks. A fresh observer fires its callback immediately for an+// already-intersecting target, so if the effect re-ran on every+// `isFetchingOlder`/`onLoadOlder` change, each `fetchOlder` would recreate the+// observer, which would re-fire against the still-visible sentinel and trigger+// the next fetch — draining every older page in one go.+//+// This drives the real observer callback: intersect once, flip+// `isFetchingOlder` true→false across re-renders (what a real fetch does), and+// assert `onLoadOlder` fires exactly ONCE, not once per re-render.+describe("MessageList — older-load sentinel does not cascade", () => {+ it("fires onLoadOlder once per intersection, not on every fetch-state re-render", () => {+ // Capture the observer callback so the test can drive intersections itself.+ let ioCallback: ((entries: Array<{ isIntersecting: boolean }>) => void) | null = null+ const mockScrollEl = {+ scrollHeight: 1000,+ scrollTop: 0,+ clientHeight: 500,+ firstElementChild: null,+ scrollTo: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),+ querySelector: () => null,+ querySelectorAll: () => [],+ }+ const g = globalThis as unknown as { ResizeObserver: unknown; IntersectionObserver: unknown }+ const prevRO = g.ResizeObserver+ const prevIO = g.IntersectionObserver+ g.ResizeObserver = class {+ observe() {}+ disconnect() {}+ }+ g.IntersectionObserver = class {+ // The top-sentinel observer is the one whose callback reads the+ // load-older ref guards; the bottom one is inert here (hasMoreNewer+ // false). Both share this class — capture the LAST-constructed callback,+ // which in render order is the bottom sentinel's, so instead capture the+ // FIRST (top) by only assigning once.+ constructor(cb: (entries: Array<{ isIntersecting: boolean }>) => void) {+ if (!ioCallback) ioCallback = cb+ }+ observe() {}+ disconnect() {}+ }++ try {+ const messages = [{ id: "m1", authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }]+ const onLoadOlder = vi.fn()+ const genericMock = { willUpdate: () => {}, didUpdate: () => {}, addEventListener: () => {}, removeEventListener: () => {} }++ const render = (isFetchingOlder: boolean) =>+ React.createElement(MessageList, {+ channel: "general",+ messages,+ loading: false,+ hasMore: true,+ onLoadOlder,+ isFetchingOlder,+ onOpenThread: vi.fn(),+ })++ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(render(false), {+ createNodeMock: (node) => (node.type === "div" ? mockScrollEl : genericMock),+ })+ })++ expect(ioCallback).not.toBeNull()++ // Sentinel scrolls into view → the first (and only) legitimate load.+ act(() => {+ ioCallback!([{ isIntersecting: true }])+ })+ expect(onLoadOlder).toHaveBeenCalledTimes(1)++ // A real fetchOlder flips isFetchingOlder true, then back to false when+ // the page lands. Each flip re-renders MessageList. The OLD bug+ // recreated the observer on these re-renders and re-fired against the+ // still-visible sentinel. With the stable observer, no new intersection+ // event occurs, so onLoadOlder must NOT be called again.+ act(() => {+ renderer!.update(render(true))+ })+ act(() => {+ renderer!.update(render(false))+ })+ expect(onLoadOlder).toHaveBeenCalledTimes(1)++ // While a fetch is in flight, a genuine intersection must be ignored+ // (guarded by isFetchingOlder read from the ref).+ act(() => {+ renderer!.update(render(true))+ })+ act(() => {+ ioCallback!([{ isIntersecting: true }])+ })+ expect(onLoadOlder).toHaveBeenCalledTimes(1)++ // Once the fetch settles, the next real intersection loads the next page.+ act(() => {+ renderer!.update(render(false))+ })+ act(() => {+ ioCallback!([{ isIntersecting: true }])+ })+ expect(onLoadOlder).toHaveBeenCalledTimes(2)+ } finally {+ g.ResizeObserver = prevRO+ g.IntersectionObserver = prevIO+ }+ })+})diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxindex fcbd56820..d86b6059b 100644--- a/src/web/src/components/community/message-list.tsx+++ b/src/web/src/components/community/message-list.tsx@@ -184,23 +184,43 @@ export function MessageList({// is false) — this needs NO virtualizer-specific rework: an// IntersectionObserver on a real sentinel node works identically whether// the sibling content is virtualized or not.+ // The observer MUST stay stable across fetches. A fresh IntersectionObserver+ // fires its callback immediately for an already-intersecting target, so if+ // this effect re-ran on every `isFetchingOlder`/`onLoadOlder` change (both+ // flip on each fetch — `fetchOlder` is `useCallback([query])`, a new identity+ // per TanStack state tick), each load would tear down and recreate the+ // observer, which then re-fires against the still-visible sentinel and kicks+ // off the next load — cascading until `hasMore` goes false (i.e. loading ALL+ // history in one scroll). Instead: create the observer ONCE per scroll+ // container and read the mutable guards from refs, so it only fires on a+ // genuine scroll-in transition.const topSentinelRef = useRef<HTMLDivElement>(null)+ const loadOlderStateRef = useRef({ onLoadOlder, hasMore, isFetchingOlder })+ loadOlderStateRef.current = { onLoadOlder, hasMore, isFetchingOlder }useEffect(() => {- if (!onLoadOlder || !hasMore) returnconst el = topSentinelRef.currentconst root = scrollRef.currentif (!el || !root) returnconst observer = new IntersectionObserver((entries) => {+ const { onLoadOlder, hasMore, isFetchingOlder } = loadOlderStateRef.current+ if (!onLoadOlder || !hasMore || isFetchingOlder) returnfor (const entry of entries) {- if (entry.isIntersecting && !isFetchingOlder) onLoadOlder()+ if (entry.isIntersecting) {+ onLoadOlder()+ break+ }}},{ root, rootMargin: "200px" },)observer.observe(el)return () => observer.disconnect()- }, [onLoadOlder, hasMore, isFetchingOlder, scrollRef])+ // Re-observe only when the sentinel node mounts/unmounts (it's absent+ // while `hasMore` is false) or the scroll container changes — never on a+ // fetch-state tick. `hasMore` gates whether the sentinel node renders at+ // all, so it belongs here to (re-)attach when history reappears.+ }, [hasMore, scrollRef])// Bottom sentinel — symmetric to the top one. Only mounted when the loaded// window is not tail-attached (`hasMoreNewer === true`). Appended rows from@@ -208,23 +228,33 @@ export function MessageList({// `mergeMessagesPages` they land at the natural tail of `messages`, which// grows the container downward and leaves the viewer's scrollTop untouched.// No compensating scroll needed. Rendered after the virtualized range.+ // Same stable-observer discipline as the top sentinel above — read the+ // mutable guards from a ref so a fetch-state tick never recreates the+ // observer (which would re-fire against the still-visible sentinel and+ // cascade through all newer pages).const bottomSentinelRef = useRef<HTMLDivElement>(null)+ const loadNewerStateRef = useRef({ onLoadNewer, hasMoreNewer, isFetchingNewer })+ loadNewerStateRef.current = { onLoadNewer, hasMoreNewer, isFetchingNewer }useEffect(() => {- if (!onLoadNewer || !hasMoreNewer) returnconst el = bottomSentinelRef.currentconst root = scrollRef.currentif (!el || !root) returnconst observer = new IntersectionObserver((entries) => {+ const { onLoadNewer, hasMoreNewer, isFetchingNewer } = loadNewerStateRef.current+ if (!onLoadNewer || !hasMoreNewer || isFetchingNewer) returnfor (const entry of entries) {- if (entry.isIntersecting && !isFetchingNewer) onLoadNewer()+ if (entry.isIntersecting) {+ onLoadNewer()+ break+ }}},{ root, rootMargin: "200px" },)observer.observe(el)return () => observer.disconnect()- }, [onLoadNewer, hasMoreNewer, isFetchingNewer, scrollRef])+ }, [hasMoreNewer, scrollRef])// `jumpTo` — click a reply pill, scroll to (and briefly highlight) an// earlier message. Replaces the old `querySelector('[data-msg-id="..."]')`diff --git a/src/web/src/components/community/sortable-category.tsx b/src/web/src/components/community/sortable-category.tsxindex fbfea0f27..38b195dac 100644--- a/src/web/src/components/community/sortable-category.tsx+++ b/src/web/src/components/community/sortable-category.tsx@@ -14,7 +14,7 @@ import { DropLine } from "./drop-line"// activation distance distinguishes a click (collapse) from a drag. It is also a drop// target so channels can be dropped onto it (including its empty space). Right-click// (or the gear) opens Settings; the "+" creates a channel; a lock shows when private.-export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChannel, onSettings, onDelete, isPrivate, children }: {+export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChannel, onSettings, onDelete, isPrivate, canReorder = true, children }: {id: stringname: stringopen: boolean@@ -23,10 +23,11 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChanonSettings?: () => voidonDelete?: () => voidisPrivate?: boolean+ canReorder?: booleanchildren: React.ReactNode}) {const [confirmingDelete, setConfirmingDelete] = useState(false)- const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: catDndId })+ const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: catDndId, disabled: !canReorder })const { setNodeRef: setDropRef, isOver: isChannelOver } = useDroppable({ id: catDndId })const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }const showLine = isOver && !isDragging@@ -41,7 +42,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan{...attributes}{...listeners}onClick={onToggle}- className="group flex w-full cursor-grab touch-none items-center gap-1 rounded px-1 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80 hover:text-foreground active:cursor-grabbing"+ className={`group flex w-full touch-none items-center gap-1 rounded px-1 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80 hover:text-foreground ${canReorder ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"}`}/>}>diff --git a/src/web/src/components/community/sortable-channel.tsx b/src/web/src/components/community/sortable-channel.tsxindex 30a3c45b0..93799884f 100644--- a/src/web/src/components/community/sortable-channel.tsx+++ b/src/web/src/components/community/sortable-channel.tsx@@ -1,7 +1,7 @@"use client"import { useState } from "react"-import { ListChevronsUpDown, BellOff, Pencil, Trash2 } from "lucide-react"+import { ListChevronsUpDown, BellOff, Pencil, Trash2, Users } from "lucide-react"import { ChannelIcon } from "./channel-icon"import { useSortable } from "@dnd-kit/sortable"import { CSS } from "@dnd-kit/utilities"@@ -13,15 +13,17 @@ import type { Channel } from "./_types"// A single drag-sortable channel row. The whole row is the drag surface (no handle);// a 5px activation distance keeps a tap = "switch channel" and a drag = reorder.// Right-click opens an edit/mute/delete menu.-export function SortableChannel({ ch, active, onClick, onEdit, onDelete }: {+export function SortableChannel({ ch, active, onClick, onEdit, onDelete, onManageMembers, canReorder = true }: {ch: Channelactive: booleanonClick: () => voidonEdit?: () => voidonDelete?: () => void+ onManageMembers?: () => void+ canReorder?: boolean}) {const [confirmingDelete, setConfirmingDelete] = useState(false)- const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: ch.id })+ const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: ch.id, disabled: !canReorder })const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }const showLine = isOver && !isDraggingconst lineSide: "top" | "bottom" = activeIndex !== -1 && activeIndex < index ? "bottom" : "top"@@ -33,7 +35,8 @@ export function SortableChannel({ ch, active, onClick, onEdit, onDelete }: {{...attributes}{...listeners}className={[- "group relative flex h-8 w-full cursor-pointer touch-none items-center gap-2 rounded-md px-2 text-sm active:cursor-grabbing",+ "group relative flex h-8 w-full cursor-pointer touch-none items-center gap-2 rounded-md px-2 text-sm",+ canReorder ? "active:cursor-grabbing" : "",active? "bg-sidebar-accent text-foreground": ch.muted@@ -66,6 +69,7 @@ export function SortableChannel({ ch, active, onClick, onEdit, onDelete }: {<ContextMenuContent className="w-48"><div className="truncate px-2 py-2 text-xs font-semibold text-muted-foreground">/{ch.name}</div>{onEdit && <ContextMenuItem onClick={onEdit}><Pencil className="size-4" /> Edit channel</ContextMenuItem>}+ {onManageMembers && <ContextMenuItem onClick={onManageMembers}><Users className="size-4" /> Manage members</ContextMenuItem>}{onDelete && (<>{onEdit && <ContextMenuSeparator />}diff --git a/src/web/src/components/community/use-channel-tree.ts b/src/web/src/components/community/use-channel-tree.tsindex ab156ae6b..6871656dd 100644--- a/src/web/src/components/community/use-channel-tree.ts+++ b/src/web/src/components/community/use-channel-tree.ts@@ -199,13 +199,27 @@ export function useChannelTree(categories: Category[]) {setCatNames((prev) => Object.fromEntries(Object.entries(prev).filter(([k]) => k !== id)))setCatPrivate((prev) => Object.fromEntries(Object.entries(prev).filter(([k]) => k !== id)))}, [])- const setCategoryPrivate = useCallback((id: string, isPrivate: boolean) =>- setCatPrivate((prev) => ({ ...prev, [id]: isPrivate })), [])+ const renameCategory = useCallback((id: string, name: string) =>+ setCatNames((prev) => (prev[id] === name ? prev : { ...prev, [id]: name })), [])++ const catPrivateRef = useRef(catPrivate)+ catPrivateRef.current = catPrivateconst onDragOver = useCallback((e: DragEndEvent) => {const { active, over } = eif (!over || isCat(String(active.id))) return // category drags handled on drop- setOrder((prev) => moveChannelAcrossCategories(prev, String(active.id), String(over.id)))+ setOrder((prev) => {+ const fromCat = catOf(String(active.id), prev)+ const toCat = catOf(String(over.id), prev)+ // Never let a channel cross a public↔private boundary during the drag —+ // visibility would silently widen/tighten. Same-class cross-category+ // moves still follow the cursor. `onDragEnd` toasts on a blocked attempt.+ if (fromCat && toCat && fromCat !== toCat &&+ !!catPrivateRef.current[fromCat] !== !!catPrivateRef.current[toCat]) {+ return prev+ }+ return moveChannelAcrossCategories(prev, String(active.id), String(over.id))+ })}, [])const onDragEnd = useCallback((e: DragEndEvent) => {@@ -222,11 +236,11 @@ export function useChannelTree(categories: Category[]) {return useMemo(() => ({collapsed, catOrder, order, catNames, catPrivate, catCreators,toggleCat, removeChannel, renameChannel, markRead, removeCategory,- setCategoryPrivate, onDragOver, onDragEnd,+ renameCategory, onDragOver, onDragEnd,}), [collapsed, catOrder, order, catNames, catPrivate, catCreators,toggleCat, removeChannel, renameChannel, markRead, removeCategory,- setCategoryPrivate, onDragOver, onDragEnd,+ renameCategory, onDragOver, onDragEnd,])}diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.tsindex e404ee96b..6657fb438 100644--- a/src/web/src/hooks/community/mutations/channels.test.ts+++ b/src/web/src/hooks/community/mutations/channels.test.ts@@ -122,3 +122,36 @@ describe("useReorderServers — cancels in-flight refetches before optimistic wrexpect(cache?.servers.map((s) => s.id)).toEqual(["srv_1", "srv_2"])})})++describe("useMoveChannel", () => {+ it("PATCHes the channel with the new categoryId and invalidates the server tree", async () => {+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await load()+ mod.useMoveChannel()+ const invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")++ await runMutation({ serverId: "s1", channelId: "c1", categoryId: "cat2" })++ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/channels/c1",+ { method: "PATCH", body: JSON.stringify({ categoryId: "cat2" }) },+ )+ expect(+ invalidateSpy.mock.calls.some((c) => {+ const k = c[0]?.queryKey as unknown[] | undefined+ return Array.isArray(k) && k[0] === "community" && k[1] === "servers" && k[2] === "s1"+ }),+ ).toBe(true)+ })++ it("sends categoryId: null when moving to uncategorized", async () => {+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await load()+ mod.useMoveChannel()+ await runMutation({ serverId: "s1", channelId: "c1", categoryId: null })+ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/channels/c1",+ { method: "PATCH", body: JSON.stringify({ categoryId: null }) },+ )+ })+})diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 9089af722..db9de9db5 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -38,6 +38,34 @@ export function useCreateChannel() {})}+export type MoveChannelArgs = {+ serverId: string+ channelId: string+ categoryId: string | null+}++/**+ * Move a channel to another category (or to uncategorized with `null`). The+ * backend (`channels/[id]` PATCH) is admin-only and rejects a move that would+ * cross a public↔private boundary — the sidebar blocks that before it gets+ * here, this mutation covers the same-privacy case. Invalidates the tree so+ * positions/category resettle from the server.+ */+export function useMoveChannel() {+ const queryClient = useQueryClient()+ return useMutation<void, Error, MoveChannelArgs>({+ mutationFn: async ({ channelId, categoryId }) => {+ await apiFetch(`/api/community/channels/${channelId}`, {+ method: "PATCH",+ body: JSON.stringify({ categoryId }),+ })+ },+ onSuccess: (_data, args) => {+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })+ },+ })+}+export type DeleteChannelArgs = { serverId: string; channelId: string }export function useDeleteChannel() {@@ -78,20 +106,20 @@ export function useCreateCategory() {})}+// Category privacy is immutable after creation, so this only renames.export type UpdateCategoryArgs = {serverId: stringcategoryId: stringname?: string- isPrivate?: boolean}export function useUpdateCategory() {const queryClient = useQueryClient()return useMutation<void, Error, UpdateCategoryArgs>({- mutationFn: async ({ serverId, categoryId, name, isPrivate }) => {+ mutationFn: async ({ serverId, categoryId, name }) => {await apiFetch(`/api/community/servers/${serverId}/categories/${categoryId}`, {method: "PATCH",- body: JSON.stringify({ name, private: isPrivate }),+ body: JSON.stringify({ name }),})},onSuccess: (_data, args) => {diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex 13d85695a..7231e1cbe 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -909,7 +909,7 @@ describe("useMarkDmRead — rollback", () => {// ── useMarkAllInboxRead ───────────────────────────────────────────────────describe("useMarkAllInboxRead", () => {- it("fires exactly two POSTs — mentions read-all + unreads read-all", async () => {+ it("fires exactly three POSTs — mentions + unreads + dms read-all", async () => {capturedQc.setQueryData(communityKeys.inboxUnreads(), { servers: [] })capturedQc.setQueryData(communityKeys.inboxMentions(), { mentions: [] })apiFetchMock.mockResolvedValue(undefined)@@ -919,9 +919,10 @@ describe("useMarkAllInboxRead", () => {const posts = apiFetchMock.mock.calls.filter((c) => (c[1] as { method?: string })?.method === "POST",)- expect(posts).toHaveLength(2)+ expect(posts).toHaveLength(3)const paths = posts.map((c) => c[0] as string).sort()expect(paths).toEqual([+ "/api/community/inbox/dms/read-all","/api/community/inbox/mentions/read-all","/api/community/inbox/unreads/read-all",])diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 4a870f4c8..a9bd31348 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -914,14 +914,13 @@ export function useMarkAllInboxRead() {await Promise.all([apiFetch("/api/community/inbox/mentions/read-all", { method: "POST" }),apiFetch("/api/community/inbox/unreads/read-all", { method: "POST" }),+ apiFetch("/api/community/inbox/dms/read-all", { method: "POST" }),])},onMutate: async () => {- // DMs live under `inboxUnreads` too — clear both keys so the popover's- // "caught up" empty state renders while the mutation is in flight. The- // `read-all` route only marks server channels; DM unread counts will- // re-populate on the next refetch. Users mostly hit this to clear- // mention/channel noise, so the brief DM flash is acceptable.+ // Clear both inbox keys so the popover's "caught up" empty state renders+ // while the mutation is in flight. DMs live under `inboxUnreads` and are+ // now marked read server-side too (the dms/read-all POST above).queryClient.setQueryData(communityKeys.inboxUnreads(), { servers: [], dms: [] })queryClient.setQueryData(communityKeys.inboxMentions(), { mentions: [] })},diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsnew file mode 100644index 000000000..3b81602a6--- /dev/null+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -0,0 +1,86 @@+"use client"++import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"+import { apiFetch } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"++export type ChannelMember = {+ userId: string+ name: string | null+ discriminator: string | null+ avatar: string+ addedAt: string+ isCreator: boolean+}++export type AddableMember = {+ userId: string+ name: string | null+ discriminator: string | null+ avatar: string+}++const EMPTY_MEMBERS: readonly ChannelMember[] = Object.freeze([])+const EMPTY_ADDABLE: readonly AddableMember[] = Object.freeze([])++/** Current roster of a private-category channel. */+export function useChannelMembers(+ channelId: string,+ enabled = true,+): UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[] } {+ const query = useQuery({+ queryKey: communityKeys.channelMembers(channelId),+ queryFn: () =>+ apiFetch<{ members: ChannelMember[] }>(+ `/api/community/channels/${encodeURIComponent(channelId)}/members`,+ ),+ enabled: enabled && !!channelId,+ })+ return { ...query, members: query.data?.members ?? (EMPTY_MEMBERS as ChannelMember[]) }+}++/** Server members not yet in the channel — the add picker. */+export function useAddableMembers(+ channelId: string,+ enabled = true,+): UseQueryResult<{ members: AddableMember[] }> & { members: AddableMember[] } {+ const query = useQuery({+ queryKey: communityKeys.channelAddableMembers(channelId),+ queryFn: () =>+ apiFetch<{ members: AddableMember[] }>(+ `/api/community/channels/${encodeURIComponent(channelId)}/addable-members`,+ ),+ enabled: enabled && !!channelId,+ })+ return { ...query, members: query.data?.members ?? (EMPTY_ADDABLE as AddableMember[]) }+}++export function useAddChannelMember(channelId: string) {+ const qc = useQueryClient()+ return useMutation({+ mutationFn: (userId: string) =>+ apiFetch(`/api/community/channels/${encodeURIComponent(channelId)}/members`, {+ method: "POST",+ body: JSON.stringify({ userId }),+ }),+ onSuccess: () => {+ void qc.invalidateQueries({ queryKey: communityKeys.channelMembers(channelId) })+ void qc.invalidateQueries({ queryKey: communityKeys.channelAddableMembers(channelId) })+ },+ })+}++export function useRemoveChannelMember(channelId: string) {+ const qc = useQueryClient()+ return useMutation({+ mutationFn: (userId: string) =>+ apiFetch(+ `/api/community/channels/${encodeURIComponent(channelId)}/members/${encodeURIComponent(userId)}`,+ { method: "DELETE" },+ ),+ onSuccess: () => {+ void qc.invalidateQueries({ queryKey: communityKeys.channelMembers(channelId) })+ void qc.invalidateQueries({ queryKey: communityKeys.channelAddableMembers(channelId) })+ },+ })+}diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 989153362..fb3706216 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -698,6 +698,26 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return}+ // ── Channel membership (private channels) ────────────────────────+ // Re-run the viewer-scoped server tree so the sidebar gains/loses the+ // private channel. On REMOVE for the viewer, evict that channel's+ // scoped caches so no private content lingers locally (mirrors the+ // channel.delete eviction above).+ case "community:channel.member_add":+ case "community:channel.member_remove": {+ if (+ event.type === "community:channel.member_remove" &&+ event.userId === viewerUserIdRef.current+ ) {+ queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })+ queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })+ queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })+ queryClient.removeQueries({ queryKey: communityKeys.forumPosts(event.channelId) })+ }+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })+ return+ }+// ── Members ─────────────────────────────────────────────────────case "community:member.join":case "community:member.leave":diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 36b32bb71..685e08dce 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -25,6 +25,8 @@ vi.mock("@alook/shared", async () => {},communityChannel: {getChannel: (...a: unknown[]) => mockGetChannel(...a),+ isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),+ getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),},communityDm: {getDM: (...a: unknown[]) => mockGetDM(...a),@@ -53,6 +55,8 @@ vi.mock("./wake-producer", () => ({const mockListMembers = vi.fn()const mockListMemberUserIds = vi.fn()const mockGetChannel = vi.fn()+const mockIsChannelPrivate = vi.fn(() => false)+const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])const mockGetDM = vi.fn()const mockGetCoMemberUserIds = vi.fn()const mockGetFriendUserIds = vi.fn()diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 67f4f7885..c4c88d7a0 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -41,7 +41,13 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s}/**- * Resolves the server a channel belongs to, then returns all member user IDs.+ * Resolves the recipient set for a channel event.+ * - public / uncategorized channel (or a thread whose anchor is public) →+ * all server members (unchanged behavior).+ * - private-category channel (or a thread anchored to one) → the channel+ * audience: explicit members ∪ creator ∪ server admins.+ * `isChannelPrivate` and `getPrivateChannelAudienceUserIds` both climb+ * `parentChannelId`, so threads inherit their parent's audience automatically.*/async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {const channel = await queries.communityChannel.getChannel(db, channelId)@@ -49,6 +55,10 @@ async function getChannelRecipientUserIds(db: Database, channelId: string): Promlog.warn("fanOutToChannel: channel not found", { channelId })return []}+ const isPrivate = await queries.communityChannel.isChannelPrivate(db, channelId)+ if (isPrivate) {+ return queries.communityChannel.getPrivateChannelAudienceUserIds(db, channelId)+ }return getServerMemberUserIds(db, channel.serverId)}diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 5442e660a..7bb2046ca 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -8,6 +8,8 @@ const mockListMembers = vi.fn()const mockListMemberUserIds = vi.fn()const mockCreateMentions = vi.fn()const mockGetChannel = vi.fn()+const mockIsChannelPrivate = vi.fn(() => false)+const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -30,6 +32,8 @@ vi.mock("@alook/shared", async () => {},communityChannel: {getChannel: (...a: unknown[]) => mockGetChannel(...a),+ isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),+ getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),},user: {getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 31ec517db..140ab7232 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -63,6 +63,15 @@ type CreateMessageOk = {ok: truerow: FullMessageRowattachments: CreatedAttachment[]+ /**+ * Present ONLY when the caller passed `deferBroadcast: true`. Invoking it+ * fires the WS side effects (MENTION_CREATE, MESSAGE_CREATE fan-out, DM peer+ * ping / CHILD_CHANNEL_UPDATE, bot-wake enqueue) that `createCommunityMessage`+ * would otherwise have run inline. The DM-card producers deliberately never+ * invoke this — they persist their approval-request row first and fire their+ * own minimal `DM_NEW_MESSAGE` after it commits (see plan §producer).+ */+ broadcast?: () => Promise<void>}export type CreateMessageResult = CreateMessageOk | CreateMessageError@@ -92,8 +101,51 @@ export async function createCommunityMessage(params: {* thread posts), which keep the unconditional, always-succeeds claim.*/expectedSeq?: number+ /**+ * Sets `communityMessage.type` (e.g. `"thread_created"`). Defaults to+ * `"default"` — every normal-message caller is untouched.+ */+ messageType?: string+ /**+ * Skip `@`/reply mention extraction + `communityMention` writes + the+ * `MENTION_CREATE` broadcast. System/card messages (thread_created, bot DM+ * cards) opt in — they never mention anyone.+ */+ skipMentions?: boolean+ /**+ * Skip the bot-wake enqueue that rides the `MESSAGE_CREATE` fan-out. System+ * / card messages set this — they must not wake bots.+ */+ skipWake?: boolean+ /**+ * Fan out `MESSAGE_CREATE` WITHOUT `excludeUserId`, so the author also+ * receives the event. The thread_created system message needs this — its+ * creator has no optimistic client row and must get the WS broadcast to see+ * it without a refresh.+ */+ includeAuthorInFanout?: boolean+ /**+ * Do NOT run any WS side effect inline. Instead, on success, return a+ * `broadcast` thunk on the OK result the caller can invoke once its own+ * follow-up writes have committed. Used by the DM-card producers, which+ * persist an approval-request row after the message and roll it back on+ * conflict — broadcasting before that commit would show a phantom card.+ */+ deferBroadcast?: boolean}): Promise<CreateMessageResult> {- const { db, authorId, target, body, source, expectedSeq } = params+ const {+ db,+ authorId,+ target,+ body,+ source,+ expectedSeq,+ messageType,+ skipMentions,+ skipWake,+ includeAuthorInFanout,+ deferBroadcast,+ } = paramsconst content = typeof body.content === "string" ? body.content : ""if (content.length > MAX_MESSAGE_CONTENT_LENGTH) {@@ -139,6 +191,7 @@ export async function createCommunityMessage(params: {dmConversationId: target.kind === "dm" ? target.dmId : undefined,replyToId,mentionType,+ ...(messageType !== undefined ? { type: messageType } : {}),}// `createMessage`'s overloads key off whether the `expectedSeq` property// is present at all, not just its runtime value — a `number | undefined`@@ -211,7 +264,7 @@ export async function createCommunityMessage(params: {// below.const replyMap = new Map<string, { id: string; authorName: string; content: string | null }>()const replyTargets = new Set<string>()- if (row.replyToId) {+ if (!skipMentions && row.replyToId) {// single-id path — see `dm/[id]/messages/route.ts` / `channels/[id]/messages/route.ts` for the batched N-id pathconst scope = target.kind === "dm" ? { dmConversationId: target.dmId } : { channelId: target.channelId }const replyMsg = await queries.communityMessage.getMessageInScope(db, row.replyToId, scope)@@ -235,7 +288,7 @@ export async function createCommunityMessage(params: {// still issue a single `listMembers` call — it's a superset of userIds,// never double-query.const mentionTargets = new Set<string>()- if (target.kind !== "dm") {+ if (!skipMentions && target.kind !== "dm") {const hasAtMention = typeof row.content === "string" && row.content.includes("@")if (hasAtMention) {const members = await queries.communityMember.listMembers(db, target.serverId)@@ -263,6 +316,24 @@ export async function createCommunityMessage(params: {// Mention beats reply — never double-count the same user.for (const id of mentionTargets) replyTargets.delete(id)+ // Private-channel scoping: a message in a channel inside a PRIVATE category+ // can only mention/reply-notify users in that channel's audience (members ∪+ // creator ∪ admins). Otherwise an @-mention would push private content into+ // a non-member's Mentions tab. Public/uncategorized channels are unchanged.+ if (target.kind !== "dm" && (mentionTargets.size > 0 || replyTargets.size > 0)) {+ const isPrivate = await queries.communityChannel.isChannelPrivate(db, target.channelId)+ if (isPrivate) {+ const audience = new Set(+ await queries.communityChannel.getPrivateChannelAudienceUserIds(db, target.channelId)+ )+ for (const id of [...mentionTargets]) if (!audience.has(id)) mentionTargets.delete(id)+ for (const id of [...replyTargets]) if (!audience.has(id)) replyTargets.delete(id)+ }+ }++ // Mention/reply ROW writes are persistence, not broadcast — they run inline+ // even under `deferBroadcast` (only the WS emissions defer). When+ // `skipMentions` both sets are empty, so these are no-ops.const liveMentions = [...mentionTargets]const liveReplies = [...replyTargets]if (liveMentions.length > 0) {@@ -279,22 +350,7 @@ export async function createCommunityMessage(params: {kind: "reply",})}- if (liveMentions.length > 0 || liveReplies.length > 0) {- const authorName = row.authorName- const channelIdForBroadcast =- target.kind === "dm" ? undefined : target.channelId- for (const userId of [...liveMentions, ...liveReplies]) {- broadcastToUser(userId, {- type: WS_EVENTS.MENTION_CREATE,- userId,- messageId: row.id,- ...(channelIdForBroadcast ? { channelId: channelIdForBroadcast } : {}),- authorName,- }).catch(() => { })- }- }- // Fan-out + per-kind side effects (DM peer ping, parent CHILD_CHANNEL_UPDATE).const messagePayload = mapMessageForWs(row, {replyMap,attachments: attachments.map((a) => ({@@ -314,63 +370,93 @@ export async function createCommunityMessage(params: {// `fanOutToChannel`/`fanOutToDM` can enqueue bot wakes using the SAME// recipient list already resolved for the human-WS broadcast, no second// membership query. Deliberately no `content`/`createdAt` — the queue- // payload only ever carries `{ messageId, botUserId }`.- const wakeMessageRow = {- id: row.id,- seq: row.seq,- authorId: row.authorId,- channelId: row.channelId,- dmConversationId: row.dmConversationId,- }+ // payload only ever carries `{ messageId, botUserId }`. Suppressed when+ // `skipWake` (system/card messages never wake bots).+ const wakeMessageRow = skipWake+ ? undefined+ : {+ id: row.id,+ seq: row.seq,+ authorId: row.authorId,+ channelId: row.channelId,+ dmConversationId: row.dmConversationId,+ }- if (target.kind === "dm") {- fanOutToDM(- target.dmId,- {- type: WS_EVENTS.MESSAGE_CREATE,- dmConversationId: target.dmId,- message: messagePayload,- },- { excludeUserId: authorId, wakeMessageRow },- ).catch(() => { })+ // `includeAuthorInFanout` fans out MESSAGE_CREATE without `excludeUserId`+ // (thread_created: the creator has no optimistic row and needs the event).+ const fanoutExclude = includeAuthorInFanout ? undefined : authorId- broadcastToUser(target.otherUserId, {- type: WS_EVENTS.DM_NEW_MESSAGE,- dmConversationId: target.dmId,- message: messagePayload,- }).catch(() => { })- } else {- fanOutToChannel(- target.channelId,- {- type: WS_EVENTS.MESSAGE_CREATE,- channelId: target.channelId,- message: messagePayload,- },- { excludeUserId: authorId, wakeMessageRow },- ).catch(() => { })+ // All WS side effects live here so `deferBroadcast` can hand them back as a+ // thunk instead of firing them inline.+ const doBroadcast = async (): Promise<void> => {+ if (liveMentions.length > 0 || liveReplies.length > 0) {+ const authorName = row.authorName+ const channelIdForBroadcast =+ target.kind === "dm" ? undefined : target.channelId+ for (const userId of [...liveMentions, ...liveReplies]) {+ broadcastToUser(userId, {+ type: WS_EVENTS.MENTION_CREATE,+ userId,+ messageId: row.id,+ ...(channelIdForBroadcast ? { channelId: channelIdForBroadcast } : {}),+ authorName,+ }).catch(() => { })+ }+ }- if (target.kind === "thread") {- const updated = await queries.communityChannel.getChannel(- db,- target.channelId,- )+ if (target.kind === "dm") {+ fanOutToDM(+ target.dmId,+ {+ type: WS_EVENTS.MESSAGE_CREATE,+ dmConversationId: target.dmId,+ message: messagePayload,+ },+ { excludeUserId: fanoutExclude, wakeMessageRow },+ ).catch(() => { })++ broadcastToUser(target.otherUserId, {+ type: WS_EVENTS.DM_NEW_MESSAGE,+ dmConversationId: target.dmId,+ message: messagePayload,+ }).catch(() => { })+ } else {fanOutToChannel(- target.parentChannelId,+ target.channelId,{- type: WS_EVENTS.CHILD_CHANNEL_UPDATE,- parentChannelId: target.parentChannelId,+ type: WS_EVENTS.MESSAGE_CREATE,channelId: target.channelId,- changes: {- messageCount: updated?.messageCount ?? 1,- lastMessageAt:- updated?.lastMessageAt ?? new Date().toISOString(),- },+ message: messagePayload,},- { excludeUserId: authorId },+ { excludeUserId: fanoutExclude, wakeMessageRow },).catch(() => { })++ if (target.kind === "thread") {+ const updated = await queries.communityChannel.getChannel(+ db,+ target.channelId,+ )+ fanOutToChannel(+ target.parentChannelId,+ {+ type: WS_EVENTS.CHILD_CHANNEL_UPDATE,+ parentChannelId: target.parentChannelId,+ channelId: target.channelId,+ changes: {+ messageCount: updated?.messageCount ?? 1,+ lastMessageAt:+ updated?.lastMessageAt ?? new Date().toISOString(),+ },+ },+ { excludeUserId: fanoutExclude },+ ).catch(() => { })+ }}}+ if (deferBroadcast) {+ return { ok: true, row, attachments, broadcast: doBroadcast }+ }+ await doBroadcast()return { ok: true, row, attachments }}diff --git a/src/web/src/lib/community/permissions.test.ts b/src/web/src/lib/community/permissions.test.tsindex 191c66afd..31bf575d0 100644--- a/src/web/src/lib/community/permissions.test.ts+++ b/src/web/src/lib/community/permissions.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"const getMember = vi.fn()const getChannelForMember = vi.fn()+const resolveChannelAccessContext = vi.fn()const getDM = vi.fn()const isBlocked = vi.fn()@@ -11,7 +12,10 @@ vi.mock("@alook/shared", async () => {...actual,queries: {communityMember: { getMember: (...a: unknown[]) => getMember(...a) },- communityChannel: { getChannelForMember: (...a: unknown[]) => getChannelForMember(...a) },+ communityChannel: {+ getChannelForMember: (...a: unknown[]) => getChannelForMember(...a),+ resolveChannelAccessContext: (...a: unknown[]) => resolveChannelAccessContext(...a),+ },communityDm: { getDM: (...a: unknown[]) => getDM(...a) },communityFriendship: { isBlocked: (...a: unknown[]) => isBlocked(...a) },},@@ -22,10 +26,41 @@ import {requireServerMember,requireServerAdmin,requireChannelMember,+ requireChannelAccess,requireDMParticipant,requireNotBlocked,} from "./permissions"+// Build a resolveChannelAccessContext return row. `anchor` defaults to the+// channel itself (top-level); pass a distinct anchor for the thread cases.+function ctxRow(over: Partial<{+ channelId: string+ serverId: string+ parentChannelId: string | null+ creatorId: string | null+ role: string+ isPrivate: boolean+ isChannelMember: boolean+}> = {}) {+ const {+ channelId = "c1",+ serverId = "s1",+ parentChannelId = null,+ creatorId = "creator",+ role = "member",+ isPrivate = false,+ isChannelMember = false,+ } = over+ const channel = { id: channelId, serverId, parentChannelId, creatorId }+ return {+ channel,+ anchor: parentChannelId ? { id: parentChannelId, serverId, parentChannelId: null, creatorId } : channel,+ role,+ isPrivate,+ isChannelMember,+ }+}+const db = {} as neverdescribe("requireServerMember", () => {@@ -90,6 +125,81 @@ describe("requireChannelMember", () => {})})+describe("requireChannelAccess", () => {+ beforeEach(() => vi.clearAllMocks())++ it("returns 403 for a non-server-member (null context)", async () => {+ resolveChannelAccessContext.mockResolvedValue(null)+ const res = await requireChannelAccess(db, "c1", "u1")+ expect(res).toEqual({ ok: false, status: 403, error: "forbidden" })+ })++ it("public channel: any member has access, canManage only for admins", async () => {+ resolveChannelAccessContext.mockResolvedValue(ctxRow({ role: "member", isPrivate: false }))+ const res = await requireChannelAccess(db, "c1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.canManage).toBe(false)+ })++ it("public channel: admin gets canManage", async () => {+ resolveChannelAccessContext.mockResolvedValue(ctxRow({ role: "admin", isPrivate: false }))+ const res = await requireChannelAccess(db, "c1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.canManage).toBe(true)+ })++ it("private channel: creator has access + canManage", async () => {+ resolveChannelAccessContext.mockResolvedValue(+ ctxRow({ role: "member", isPrivate: true, creatorId: "u1" }),+ )+ const res = await requireChannelAccess(db, "c1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.canManage).toBe(true)+ })++ it("private channel: added member has access, not canManage", async () => {+ resolveChannelAccessContext.mockResolvedValue(+ ctxRow({ role: "member", isPrivate: true, creatorId: "other", isChannelMember: true }),+ )+ const res = await requireChannelAccess(db, "c1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.canManage).toBe(false)+ })++ it("private channel: unrelated member is forbidden", async () => {+ resolveChannelAccessContext.mockResolvedValue(+ ctxRow({ role: "member", isPrivate: true, creatorId: "other", isChannelMember: false }),+ )+ const res = await requireChannelAccess(db, "c1", "u1")+ expect(res).toEqual({ ok: false, status: 403, error: "forbidden" })+ })++ it("private channel: admin always has access + canManage", async () => {+ resolveChannelAccessContext.mockResolvedValue(+ ctxRow({ role: "owner", isPrivate: true, creatorId: "other", isChannelMember: false }),+ )+ const res = await requireChannelAccess(db, "c1", "u1")+ expect(res.ok).toBe(true)+ if (res.ok) expect(res.value.canManage).toBe(true)+ })++ it("thread under a private channel: added member of the parent has access", async () => {+ resolveChannelAccessContext.mockResolvedValue(+ ctxRow({ channelId: "t1", parentChannelId: "c1", role: "member", isPrivate: true, creatorId: "other", isChannelMember: true }),+ )+ const res = await requireChannelAccess(db, "t1", "u1")+ expect(res.ok).toBe(true)+ })++ it("thread under a private channel: unrelated member is forbidden", async () => {+ resolveChannelAccessContext.mockResolvedValue(+ ctxRow({ channelId: "t1", parentChannelId: "c1", role: "member", isPrivate: true, creatorId: "other", isChannelMember: false }),+ )+ const res = await requireChannelAccess(db, "t1", "u1")+ expect(res).toEqual({ ok: false, status: 403, error: "forbidden" })+ })+})+describe("requireDMParticipant", () => {beforeEach(() => vi.clearAllMocks())diff --git a/src/web/src/lib/community/permissions.ts b/src/web/src/lib/community/permissions.tsindex bf98ba37b..e1bc81381 100644--- a/src/web/src/lib/community/permissions.ts+++ b/src/web/src/lib/community/permissions.ts@@ -1,4 +1,4 @@-import { queries, canManageServer } from "@alook/shared"+import { queries, canManageServer, canSeePrivateChannel } from "@alook/shared"import type { Database } from "@alook/shared"type PermissionError =@@ -33,7 +33,17 @@ export async function requireServerAdmin(return ok(member)}-/** Verify the caller is a member of the server that owns the channel; returns the channel row. */+/**+ * Verify the caller may READ/POST in a channel; returns the channel row.+ *+ * The read/post gate for every message-scoped route (messages, pins,+ * reactions, uploads, read-state, threads, media, agent). Private-channel+ * visibility is enforced inside `getChannelForMember` itself (scope-first, per+ * AGENTS.md): it returns null when the caller can't see a channel in a private+ * category (or its thread), so this stays a thin wrapper and every existing+ * caller inherits the gating. Routes that need `canManage` (edit/delete, member+ * management) call `requireChannelAccess` directly.+ */export async function requireChannelMember(db: Database,channelId: string,@@ -44,6 +54,59 @@ export async function requireChannelMember(return ok(channel)}+type ChannelAccessContext = NonNullable<+ Awaited<ReturnType<typeof queries.communityChannel.resolveChannelAccessContext>>+>++export type ChannelAccess = {+ channel: ChannelAccessContext["channel"]+ anchor: ChannelAccessContext["anchor"]+ member: { role: string | null }+ canManage: boolean+ isPrivate: boolean+}++/**+ * Single-source-of-truth channel access gate. Resolves in one context query+ * (target + anchor + category privacy + member role + channel-member flag),+ * then applies the rule:+ * - not a server member → 403+ * - admin/owner → access + canManage+ * - public/uncategorized → access; canManage only for admins+ * - private → access iff creator or added member; canManage iff admin or+ * anchor creator+ * Threads inherit their parent anchor's audience (the context query climbs+ * `parentChannelId`), so thread member rows never exist.+ */+export async function requireChannelAccess(+ db: Database,+ channelId: string,+ userId: string,+): Promise<Result<ChannelAccess>> {+ const ctx = await queries.communityChannel.resolveChannelAccessContext(db, channelId, userId)+ if (!ctx) return err(403, "forbidden")++ const isAdmin = canManageServer(ctx.role)+ const isCreator = ctx.anchor.creatorId === userId++ // Visibility: public → any server member; private → the shared+ // canSeePrivateChannel rule (admin | creator | member). Manage: admin+ // anywhere, plus the creator of a private channel.+ const hasAccess = ctx.isPrivate+ ? canSeePrivateChannel({ role: ctx.role, isCreator, isChannelMember: ctx.isChannelMember })+ : true+ const canManage = isAdmin || (ctx.isPrivate && isCreator)++ if (!hasAccess) return err(403, "forbidden")+ return ok({+ channel: ctx.channel,+ anchor: ctx.anchor,+ member: { role: ctx.role },+ canManage,+ isPrivate: ctx.isPrivate,+ })+}+type DMRow = {id: stringuser1Id: stringdiff --git a/src/web/src/lib/community/resolve-ref.ts b/src/web/src/lib/community/resolve-ref.tsindex b8259765f..03b09cbb0 100644--- a/src/web/src/lib/community/resolve-ref.ts+++ b/src/web/src/lib/community/resolve-ref.ts@@ -111,6 +111,14 @@ export async function resolveTargetForMember(return { kind: "channel", channelId: channel.id }}+ // A thread may only root on a TOP-LEVEL channel — never on a forum post or+ // another thread (that grandchild would defeat the single-level privacy+ // anchor climb and leak a private forum's thread server-wide). Reject with a+ // clean 400 here; `createThreadChannel` also enforces this as a last resort.+ if (channel.parentChannelId) {+ return { error: 400, message: "can't start a thread inside a thread or forum post" }+ }+// Thread form (`/server/channel/#N`) — translate the root seq to the// parent message's id, then find (or create) the thread's own channel row.const rootMessage = await queries.communityMessage.getMessageByChannelAndSeq(diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex 334eb3a66..a41d90b35 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -52,6 +52,13 @@ export const communityKeys = {dmMessagesPage: (dmId: string, cursor?: string | null) =>[...communityKeys.dmMessages(dmId), cursor ?? null] as const,+ // Explicit membership roster of a private-category channel + the addable+ // (not-yet-member) server members for its picker.+ channelMembers: (channelId: string) =>+ [...communityKeys.all, "channel", channelId, "members"] as const,+ channelAddableMembers: (channelId: string) =>+ [...communityKeys.all, "channel", channelId, "addable-members"] as const,+pins: (channelId: string) =>[...communityKeys.all, "channel", channelId, "pins"] as const,threads: (channelId: string) =>diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex 0cf9420a1..b35ac22ae 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -77,6 +77,8 @@ const mockMarkMachineOnlineIfOffline = vi.fn()const mockGetCoMemberUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])const mockGetChannelForMember = vi.fn()+const mockIsChannelPrivate = vi.fn<(db: unknown, channelId: string) => Promise<boolean>>().mockResolvedValue(false)+const mockGetPrivateChannelAudienceUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])const mockGetDM = vi.fn()const mockListMembers = vi.fn()const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])@@ -184,6 +186,8 @@ vi.mock("@alook/shared", () => {},communityChannel: {getChannelForMember: (...a: any[]) => mockGetChannelForMember(...a),+ isChannelPrivate: (...a: any[]) => mockIsChannelPrivate(...a),+ getPrivateChannelAudienceUserIds: (...a: any[]) => mockGetPrivateChannelAudienceUserIds(...a),},communityDm: {getDM: (...a: any[]) => mockGetDM(...a),@@ -230,6 +234,8 @@ describe("WebSocketDurableObject", () => {mockListBotsForMachine.mockResolvedValue([])mockIsBotOnline.mockResolvedValue(false)mockGetUserInternal.mockResolvedValue(null)+ mockIsChannelPrivate.mockResolvedValue(false)+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue([])})describe("fetch — WebSocket upgrade", () => {@@ -1381,6 +1387,31 @@ describe("WebSocketDurableObject", () => {expect(mockStubFetch).toHaveBeenCalledTimes(2)})+ it("private channel: fans out to the channel audience, not all server members", async () => {+ const { durable, env } = createDO()+ mockGetChannelForMember.mockResolvedValueOnce({ id: "chan-p", serverId: "server-1" })+ mockIsChannelPrivate.mockResolvedValueOnce(true)+ // Audience = creator + added member + admin (server-wide members would be+ // more than this — the assertion below proves we used the audience).+ mockGetPrivateChannelAudienceUserIds.mockResolvedValueOnce(["sender-1", "member-1"])++ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })++ await durable.webSocketMessage(+ ws as any,+ JSON.stringify({ type: "community:typing.start", channelId: "chan-p" }),+ )+ await flush()++ expect(mockGetPrivateChannelAudienceUserIds).toHaveBeenCalledWith(expect.anything(), "chan-p")+ expect(mockListMembers).not.toHaveBeenCalled()+ // Only the non-sender audience member gets a broadcast POST.+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:member-1")+ expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")+ expect(mockStubFetch).toHaveBeenCalledTimes(1)+ })+it("does not fan out when sender is not a participant of the target DM", async () => {const { durable, env } = createDO()mockGetDM.mockResolvedValueOnce({diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 033323290..7498374ae 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -929,8 +929,18 @@ export class WebSocketDurableObject extends DurableObject<Env> {log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId: targetId })return}- const members = await queries.communityMember.listMembers(db, membership.serverId)- recipientUserIds = members.map((m) => m.userId)+ // Private-category channels (and their threads) fan out only to the+ // channel audience — never leak "X is typing" to non-members. Also+ // re-gates the sender: a server member who isn't in the private+ // channel won't appear in its own audience, so they broadcast to+ // nobody. Public/uncategorized channels stay server-wide.+ const isPrivate = await queries.communityChannel.isChannelPrivate(db, targetId)+ if (isPrivate) {+ recipientUserIds = await queries.communityChannel.getPrivateChannelAudienceUserIds(db, targetId)+ } else {+ const members = await queries.communityMember.listMembers(db, membership.serverId)+ recipientUserIds = members.map((m) => m.userId)+ }}}