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): unify forum/forum_post with channel/thread (#399)
Generb0a8a48be183
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex fbfaee158..d2ca118ed 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -1,4 +1,4 @@-import { eq, and, or, asc, desc, isNull, isNotNull, max, inArray, count } from "drizzle-orm";+import { eq, and, asc, desc, isNull, max, inArray, count } from "drizzle-orm";import {communityChannel,communityCategory,@@ -8,7 +8,7 @@ import {} from "../../community-schema";import type { Database } from "../../index";import { createLogger } from "../../../logger";-import { canManageServer, canSeePrivateChannel, isForum, isForumPost } from "../../../utils/community-roles";+import { canManageServer, canSeePrivateChannel } from "../../../utils/community-roles";// Module-level logger — one tag per shared query module.const log = createLogger({ service: "community-queries" });@@ -139,19 +139,12 @@ export async function getChannelForMember(db: Database, channelId: string, userIif (!row) return null;const { memberRole, ...channelRow } = row;- // Privacy anchor vs roster anchor (nested-membership model):- // - thread (`parentMessageId` set) → BOTH climb to the parent channel; a- // thread never narrows access below its channel.- // - forum post (`type="forum_post"`) → privacy climbs to the forum (for the- // category flag), but the ROSTER is the post's OWN id + own `creatorId`.- // - top-level channel → self for both.- // The single anchor query below reads the PRIVACY anchor (self for a- // post/channel, parent for a thread) and its creator. For a post the roster- // creator is the post's own (already in `channelRow`, no extra query); the- // roster member-row lookup targets `rosterAnchorId`.- const isPost = isForumPost(channelRow.type);- const privacyAnchorId = channelRow.parentChannelId ?? channelRow.id;- const rosterAnchorId = isPost ? channelRow.id : privacyAnchorId;+ // Unified model — the anchor (`parentChannelId ?? id`) is both the privacy and+ // roster anchor. A forum_post/thread climbs to its parent forum/channel for+ // BOTH the category-privacy flag and the roster (member rows + creator); a+ // top-level channel/forum is its own anchor. The single query below reads that+ // anchor and its creator.+ const anchorId = channelRow.parentChannelId ?? channelRow.id;const anchor = await db.select({@@ -160,25 +153,21 @@ export async function getChannelForMember(db: Database, channelId: string, userI}).from(communityChannel).leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))- .where(eq(communityChannel.id, privacyAnchorId))+ .where(eq(communityChannel.id, anchorId)).limit(1);const isPrivate = (anchor[0]?.categoryPrivate ?? 0) === 1;if (isPrivate) {- // Roster creator: a post's own creator, else the privacy anchor's creator- // (for a top-level channel these coincide).- const rosterCreatorId = isPost ? channelRow.creatorId : anchor[0]?.creatorId;- const isCreator = rosterCreatorId === userId;- // Membership: a FORUM's access is derived from its posts (member of any- // child post); everything else checks a row on the roster anchor. NOTE:- // admins have NO content privilege for private units — no role short-circuit- // here; an admin must be the creator or an explicit member to see it.- const channelIsForum = isForum(channelRow.type);- const isMember = isCreator- ? false- : channelIsForum- ? await isMemberOfAnyChildPost(db, channelRow.id, userId)- : await isChannelMember(db, rosterAnchorId, userId);+ // ACCESS creator = the ANCHOR creator (the forum/parent-channel creator for a+ // post/thread). Feeds canSeePrivateChannel, so post access is pure inheritance+ // from the forum; post-manage rights are derived at the route from+ // channel.creatorId.+ const isCreator = anchor[0]?.creatorId === userId;+ // Membership checks a row on the anchor (own row for a forum/channel, the+ // parent forum/channel for a post/thread). Admins have NO content privilege+ // for private units — no role short-circuit here; an admin must be the+ // creator or an explicit member to see it.+ const isMember = isCreator ? false : await isChannelMember(db, anchorId, userId);if (!canSeePrivateChannel({ isCreator, isChannelMember: isMember })) {return null;}@@ -543,59 +532,6 @@ export async function listChannelMemberUserIds(return rows.map((r) => r.userId);}-// Of the given channel ids, which ones the user has an explicit member row on.-// Batch form of `isChannelMember` — used to filter a private forum's posts to-// the ones the viewer belongs to without an N+1 loop.-export async function listChannelIdsWithMember(- db: Database,- channelIds: string[],- userId: string-): Promise<string[]> {- if (channelIds.length === 0) return [];- const rows = await db- .select({ channelId: communityChannelMember.channelId })- .from(communityChannelMember)- .where(- and(- inArray(communityChannelMember.channelId, channelIds),- eq(communityChannelMember.userId, userId)- )- );- return rows.map((r) => r.channelId);-}--// Does the user have access to a FORUM via any of its posts? Forum access is-// derived (nested-membership model): a user sees a private forum iff they-// created it, or are the creator/an explicit member of at least one child post.-// Admins are handled by the caller (role check) before this runs.-export async function isMemberOfAnyChildPost(- db: Database,- forumId: string,- userId: string-): Promise<boolean> {- const rows = await db- .select({ id: communityChannel.id })- .from(communityChannel)- .leftJoin(- communityChannelMember,- and(- eq(communityChannelMember.channelId, communityChannel.id),- eq(communityChannelMember.userId, userId)- )- )- .where(- and(- eq(communityChannel.parentChannelId, forumId),- or(- eq(communityChannel.creatorId, userId),- isNotNull(communityChannelMember.id)- )- )- )- .limit(1);- return rows.length > 0;-}-export async function isChannelMember(db: Database,channelId: string,@@ -638,11 +574,11 @@ export async function countChannelsInCategory(/*** The full recipient audience for a PRIVATE channel: explicit members ∪ the- * unit's creator. Type-aware (nested-membership model). Resolves the anchor for- * 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).+ * unit's creator. Unified model — a unit's roster is always its anchor's+ * (`parentChannelId ?? id`), so a forum_post/thread inherits its parent+ * forum/channel's roster. Only meaningful for a private anchor; callers guard on+ * `isChannelPrivate` first (fan-out short-circuits public channels to+ * `listMemberUserIds` and never calls this).** NOTE: server admins/owner are NOT auto-included — an admin is in a private* audience only if they created it or were explicitly added, exactly like a@@ -656,7 +592,6 @@ export async function getPrivateChannelAudienceUserIds(.select({id: communityChannel.id,serverId: communityChannel.serverId,- type: communityChannel.type,creatorId: communityChannel.creatorId,parentChannelId: communityChannel.parentChannelId,})@@ -664,45 +599,18 @@ export async function getPrivateChannelAudienceUserIds(.where(eq(communityChannel.id, channelId)).limit(1);if (target.length === 0) return [];- const type = target[0]!.type;const set = new Set<string>();- // Nested-membership model — the roster depends on the unit type:- // - forum_post → the post's OWN explicit members ∪ its OWN creator (does- // NOT climb to the forum; a post is an access unit like a channel).- // - forum → the UNION of its posts' audiences ∪ the forum creator- // (derived, read-only aggregation).- // - thread → climbs to the parent channel's audience (a thread never- // narrows access).- // - text channel → its own explicit members ∪ its own creator.- if (isForum(type)) {- // Derived union = every post's own members ∪ every post's creator ∪ the- // forum creator. Computed in a fixed number of queries (list posts, then one- // `inArray` over their member rows) — NOT a per-post recursion (that was an- // N+1: one round-trip per post).- if (target[0]!.creatorId) set.add(target[0]!.creatorId);- const posts = await db- .select({ id: communityChannel.id, creatorId: communityChannel.creatorId })- .from(communityChannel)- .where(eq(communityChannel.parentChannelId, channelId));- for (const p of posts) if (p.creatorId) set.add(p.creatorId);- const postIds = posts.map((p) => p.id);- if (postIds.length > 0) {- const memberRows = await db- .select({ userId: communityChannelMember.userId })- .from(communityChannelMember)- .where(inArray(communityChannelMember.channelId, postIds));- for (const r of memberRows) set.add(r.userId);- }- return [...set];- }-- // post → roster on self; thread/channel → climb to the anchor.- const rosterAnchorId =- isForumPost(type) ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);+ // Unified access model — a unit's roster is always its anchor's roster:+ // - forum / text channel → its OWN explicit members ∪ its OWN creator.+ // - forum_post / thread → climbs `parentChannelId` to the anchor (the+ // forum / parent channel) and uses THAT roster — a post inherits the+ // forum's audience exactly like a thread inherits its channel's.+ // No derived union, no per-post roster: forum ≈ channel, forum_post ≈ thread.+ const rosterAnchorId = target[0]!.parentChannelId ?? target[0]!.id;const rosterCreatorId =- isForumPost(type)+ rosterAnchorId === target[0]!.id? target[0]!.creatorId: (await db.select({ creatorId: communityChannel.creatorId })@@ -717,15 +625,15 @@ export async function getPrivateChannelAudienceUserIds(/*** Top-level channels a viewer may SEE in a server (backs the server-detail- * tree). Nested-membership model:- * - admin/owner → every top-level channel.- * - otherwise → all public/uncategorized channels, PLUS private-category text- * channels where the viewer is the creator OR has a member row, PLUS private- * FORUMS the viewer can see via membership in any of their posts (derived).+ * tree). Unified model:+ * - all public/uncategorized channels/forums, PLUS+ * - private-category channels/forums where the viewer is the creator OR has a+ * member row (a forum owns its roster like a text channel; admins get NO+ * implicit access).* `parentChannelId IS NULL` (threads/posts excluded, mirroring* `listServerChannels`). The private-visibility set is computed by the shared- * `resolveVisibleChannelIdSet` (which knows the forum-derived rule), then the- * top-level rows are filtered by it in id space.+ * `resolveVisibleChannelIdSet`, then the top-level rows are filtered by it in id+ * space.*/export async function listServerChannelsForViewer(db: Database,@@ -808,47 +716,28 @@ async function resolveVisibleChannelIdSet(const memberChannelIds = new Set(memberRows.map((r) => r.channelId));const byId = new Map(rows.map((r) => [r.id, r]));- const postsByForum = new Map<string, typeof rows>();- for (const r of rows) {- if (isForumPost(r.type) && r.parentChannelId) {- const list = postsByForum.get(r.parentChannelId) ?? [];- list.push(r);- postsByForum.set(r.parentChannelId, list);- }- }const isPrivate = (r: { categoryId: string | null; categoryPrivate: number | null }) =>r.categoryId != null && r.categoryPrivate === 1;- // Pass 1 — top-level channels + forums.+ // Pass 1 — top-level channels + forums. A private forum is visible via its OWN+ // member row (or creator), exactly like a private text channel — no derived+ // per-post visibility.for (const r of rows) {if (r.parentChannelId != null) continue;- if (!isPrivate(r) || r.creatorId === userId) {- visible.add(r.id);- continue;- }- if (isForum(r.type)) {- const posts = postsByForum.get(r.id) ?? [];- if (posts.some((p) => p.creatorId === userId || memberChannelIds.has(p.id))) {- visible.add(r.id);- }- } else if (memberChannelIds.has(r.id)) {+ if (!isPrivate(r) || r.creatorId === userId || memberChannelIds.has(r.id)) {visible.add(r.id);}}- // Pass 2 — children (threads inherit; forum posts are their own access unit).+ // Pass 2 — children. Both forum posts AND threads INHERIT their parent's+ // visibility (a forum member sees every post; a channel member sees every+ // thread). No per-post access unit.for (const r of rows) {if (r.parentChannelId == null) continue;const parent = byId.get(r.parentChannelId);if (!parent) continue;- if (isForumPost(r.type)) {- // Public forum → post public; private forum → creator or own member row.- if (!isPrivate(parent) || r.creatorId === userId || memberChannelIds.has(r.id)) {- visible.add(r.id);- }- } else if (visible.has(parent.id)) {- // thread (or any other child) inherits the parent's visibility.+ if (visible.has(parent.id)) {visible.add(r.id);}}@@ -859,10 +748,9 @@ async function resolveVisibleChannelIdSet(/*** The set of channel ids (top-level AND child/thread/forum-post channels) a* viewer may see — backs read-path scoping for search / inbox / mark-all-read /- * mentions. Type-aware per the nested-membership model (see- * `resolveVisibleChannelIdSet`): threads inherit their parent's visibility;- * private forum posts are their own access unit; a private forum is visible via- * membership in any of its posts.+ * mentions. Unified model (see `resolveVisibleChannelIdSet`): forum posts AND+ * threads inherit their parent's visibility; a private forum/channel is visible+ * via the viewer's own member row (or creator).*/export async function listVisibleChannelIds(db: Database,@@ -881,8 +769,9 @@ export async function listVisibleChannelIds(* belongs to.** A viewer sees public/uncategorized channels plus private units they created- * or belong to (forum visibility derived from post membership). Admins get NO- * special visibility — same rule as everyone.+ * or belong to (a forum's visibility comes from its own member row, like a text+ * channel; posts/threads inherit their parent). Admins get NO special+ * visibility — same rule as everyone.** Bound-parameter ceiling (accepted risk): a viewer across many large servers* can produce a big id set; feeding it whole into a downstream `inArray`@@ -952,14 +841,11 @@ export async function resolveChannelAccessContext(if (anchorRows.length === 0) return null;const anchor = mapChannelRow(anchorRows[0]!);- // Privacy anchor vs roster anchor (nested-membership model):- // - forum post → privacy climbs to the forum (its category), but the ROSTER- // (member rows + creator) is the post's OWN id.- // - thread / top-level channel → privacy anchor == roster anchor.- const isPost = isForumPost(channel.type);- const rosterAnchorId = isPost ? channel.id : anchorId;- const rosterCreatorId = isPost ? channel.creatorId : anchor.creatorId;-+ // Unified model — privacy anchor == roster anchor == `parentChannelId ?? id`.+ // A forum_post/thread climbs to its parent (forum/channel) for BOTH the+ // category-privacy flag and the roster; a forum/top-level channel is its own+ // anchor. So post access is pure inheritance from the forum, exactly like a+ // thread inherits its channel — no per-post roster, no forum-derived union.let categoryPrivate = 0;if (anchor.categoryId) {const cat = await db@@ -970,15 +856,8 @@ export async function resolveChannelAccessContext(categoryPrivate = cat[0]?.private ?? 0;}- // A FORUM's access is derived from its posts (member of any child post);- // everything else checks a member row on the roster anchor.- const channelIsForum = isForum(channel.type);const memberFlag =- categoryPrivate === 1- ? channelIsForum- ? await isMemberOfAnyChildPost(db, channel.id, userId)- : await isChannelMember(db, rosterAnchorId, userId)- : false;+ categoryPrivate === 1 ? await isChannelMember(db, anchorId, userId) : false;return {channel,@@ -986,8 +865,10 @@ export async function resolveChannelAccessContext(role: member[0]!.role,isPrivate: categoryPrivate === 1,isChannelMember: memberFlag,- // Roster-anchor creator (post's own creator for a post) — the access gate- // must use this, NOT `anchor.creatorId`, which for a post is the forum's.- isCreator: rosterCreatorId === userId,+ // ACCESS creator = the ANCHOR creator (the forum/parent-channel creator for a+ // post/thread). Feeds canSeePrivateChannel/canManage. Post-manage rights+ // (edit tags / delete) are derived at the route from `channel.creatorId`, NOT+ // this flag.+ isCreator: anchor.creatorId === userId,};}diff --git a/src/shared/src/db/queries/community/members-resolver.ts b/src/shared/src/db/queries/community/members-resolver.tsindex d3872c0ac..d2d60c46c 100644--- a/src/shared/src/db/queries/community/members-resolver.ts+++ b/src/shared/src/db/queries/community/members-resolver.ts@@ -5,7 +5,7 @@ import {} from "../../community-schema";import type { Database } from "../../index";import type { CommunityRole } from "../../../utils/community-roles";-import { canManageServer, isForum, isForumPost } from "../../../utils/community-roles";+import { canManageServer } from "../../../utils/community-roles";import {getPrivateChannelAudienceUserIds,isChannelPrivate,@@ -13,9 +13,12 @@ import {} from "./channel";import { listMemberUserIds } from "./member";-// Scopes whose member set is derived, not stored. A thread / forum_post has no-// roster of its own — it inherits the audience of its anchor channel.-export type ScopeKind = "channel" | "thread" | "post";+// The ACCESS scopes — units that own (or inherit) a stored/derived access+// roster. `forum` resolves like a top-level text channel (its own roster);+// `channel` is a top-level text channel. Thread / forum_post are NOT here: they+// are the NOTIFICATION dimension (participant set), resolved at the call site+// via `listThreadParticipantUserIds` — never through this resolver.+export type ScopeKind = "channel" | "forum";// Why a user is in the resolved set. Lets callers distinguish an explicitly// added private-channel member from an inherited public-channel member or a@@ -29,20 +32,19 @@ export type ScopeMember = {};/**- * The single source of truth for "who is in this scope." Consolidates the- * public/private split that fan-out and the WS DO used to hand-roll:+ * The single source of truth for "who can access this scope." Consolidates the+ * public/private split for the ACCESS dimension:*- * - public / uncategorized channel (or a thread/post anchored to one) →- * every server member (unfiltered — matches `listMemberUserIds`, so a- * soft-deleted user is still in the set; a dead user simply has no live- * socket to receive a broadcast).- * - private-category channel (or a thread/post anchored to one) → the- * channel audience: explicit members ∪ anchor creator ∪ server- * admins/owner (delegates to `getPrivateChannelAudienceUserIds`, which- * already climbs `parentChannelId`).+ * - public / uncategorized channel/forum → every server member (unfiltered —+ * matches `listMemberUserIds`, so a soft-deleted user is still in the set; a+ * dead user simply has no live socket to receive a broadcast).+ * - private-category channel/forum → the channel audience: explicit members ∪+ * creator (delegates to `getPrivateChannelAudienceUserIds`, which climbs+ * `parentChannelId` so a forum resolves its own roster like a text channel).*- * `thread` / `post` resolve identically to `channel` — every reader climbs to- * the anchor — so the scope tag is documentation, not branching.+ * Only ACCESS units (`channel`/`forum`) reach here. Notify units (thread /+ * forum_post) resolve their recipient set from the participant table at the+ * call site.*/export async function resolveScopeMemberUserIds(db: Database,@@ -80,7 +82,6 @@ export async function resolveScopeMembers(.select({id: communityChannel.id,serverId: communityChannel.serverId,- type: communityChannel.type,creatorId: communityChannel.creatorId,parentChannelId: communityChannel.parentChannelId,})@@ -89,7 +90,6 @@ export async function resolveScopeMembers(.limit(1);if (target.length === 0) return [];const serverId = target[0]!.serverId;- const type = target[0]!.type;// Server roles for every resolved user — scoped to this server up front.const roleRows = await db@@ -101,41 +101,24 @@ export async function resolveScopeMembers(const isPrivate = await isChannelPrivate(db, scopeId);- // "explicit" = the added members ∪ the unit's own creator, per the- // nested-membership roster rules:- // - forum_post → the post's OWN members ∪ post creator (no forum climb).- // - forum → the union of its posts' explicit members ∪ post creators ∪- // forum creator (derived).- // - thread/channel → the (climbed) anchor's members ∪ anchor creator.- // For a PRIVATE unit every resolved user is now `explicit` (admins are no- // longer auto-included — the audience is exactly members ∪ creator). For a- // PUBLIC unit the audience is all server members, tagged admin/inherited.+ // "explicit" = the anchor's added members ∪ the anchor's own creator. The+ // anchor is `parentChannelId ?? id`, so a forum/channel uses its own roster.+ // For a PRIVATE unit every resolved user is `explicit` (admins are no longer+ // auto-included — the audience is exactly members ∪ creator). For a PUBLIC+ // unit the audience is all server members, tagged admin/inherited.const explicit = new Set<string>();if (isPrivate) {- if (isForum(type)) {- if (target[0]!.creatorId) explicit.add(target[0]!.creatorId);- const posts = await db- .select({ id: communityChannel.id, creatorId: communityChannel.creatorId })- .from(communityChannel)- .where(eq(communityChannel.parentChannelId, scopeId));- for (const p of posts) {- for (const id of await listChannelMemberUserIds(db, p.id)) explicit.add(id);- if (p.creatorId) explicit.add(p.creatorId);- }- } else {- const rosterAnchorId =- isForumPost(type) ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);- for (const id of await listChannelMemberUserIds(db, rosterAnchorId)) explicit.add(id);- const rosterCreatorId =- isForumPost(type)- ? target[0]!.creatorId- : (await db- .select({ creatorId: communityChannel.creatorId })- .from(communityChannel)- .where(eq(communityChannel.id, rosterAnchorId))- .limit(1))[0]?.creatorId;- if (rosterCreatorId) explicit.add(rosterCreatorId);- }+ const anchorId = target[0]!.parentChannelId ?? target[0]!.id;+ for (const id of await listChannelMemberUserIds(db, anchorId)) explicit.add(id);+ const anchorCreatorId =+ anchorId === target[0]!.id+ ? target[0]!.creatorId+ : (await db+ .select({ creatorId: communityChannel.creatorId })+ .from(communityChannel)+ .where(eq(communityChannel.id, anchorId))+ .limit(1))[0]?.creatorId;+ if (anchorCreatorId) explicit.add(anchorCreatorId);}return userIds.map((userId) => {diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex ae4951ba4..6499e5aab 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -1,5 +1,5 @@import { and, eq, inArray } from "drizzle-orm";-import { communityThreadParticipant } from "../../community-schema";+import { communityChannel, communityThreadParticipant } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -145,6 +145,36 @@ export async function removeThreadParticipant(return rows[0] ?? null;}+// Drop a user's participant rows from EVERY child channel (forum_post OR thread)+// under a top-level unit. Called when a member is removed from a forum/channel's+// access roster: their access is gone, so their leftover notify rows on the+// unit's posts/threads must go too — else fan-out keeps live-pushing new+// post/thread messages to someone who can no longer open them. A later+// mention/speak (which requires access) re-adds them. Returns the count of+// removed rows.+export async function removeParticipantFromChildChannels(+ db: Database,+ parentChannelId: string,+ userId: string+): Promise<number> {+ const children = await db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(eq(communityChannel.parentChannelId, parentChannelId));+ const childIds = children.map((c) => c.id);+ if (childIds.length === 0) return 0;+ const removed = await db+ .delete(communityThreadParticipant)+ .where(+ and(+ inArray(communityThreadParticipant.threadChannelId, childIds),+ eq(communityThreadParticipant.userId, userId)+ )+ )+ .returning();+ return removed.length;+}+// Of the given thread ids, which the user participates in. Batch form for the// inbox unread-threads filter.export async function listParticipatingThreadIds(diff --git a/src/shared/test/queries/community-members-resolver.test.ts b/src/shared/test/queries/community-members-resolver.test.tsindex cc21edf69..99f17679c 100644--- a/src/shared/test/queries/community-members-resolver.test.ts+++ b/src/shared/test/queries/community-members-resolver.test.ts@@ -87,12 +87,12 @@ describe("resolveScopeMemberUserIds", () => {expect(mockGetPrivateChannelAudienceUserIds).not.toHaveBeenCalled();});- it("thread / post resolve identically to channel (delegates to the same primitives)", async () => {+ it("forum resolves identically to channel (delegates to the same primitives)", async () => {mockIsChannelPrivate.mockResolvedValue(true);mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"]);const db = makeDb({ select: [[{ serverId: "srv-1" }]] });- const ids = await resolveScopeMemberUserIds(db, { scope: "thread", scopeId: CHANNEL });+ const ids = await resolveScopeMemberUserIds(db, { scope: "forum", scopeId: CHANNEL });expect(ids).toEqual(["u1"]);});@@ -136,13 +136,14 @@ describe("resolveScopeMembers — source tagging", () => {const db = makeDb({select: [[{ serverId: "srv-1" }], // resolveScopeMemberUserIds channel lookup- [{ serverId: "srv-1", parentChannelId: null }], // resolveScopeMembers target lookup+ // resolveScopeMembers target lookup — top-level channel is its own+ // anchor, so its creatorId is read directly (no separate anchor query).+ [{ id: CHANNEL, serverId: "srv-1", parentChannelId: null, creatorId: "creator1" }],[ // role rows{ userId: "member1", role: "member" },{ userId: "creator1", role: "member" },{ userId: "admin1", role: "admin" },],- [{ creatorId: "creator1" }], // anchor creator lookup],});diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.tsindex 75e52b76f..8e01cfa4a 100644--- a/src/shared/test/queries/community-thread.test.ts+++ b/src/shared/test/queries/community-thread.test.ts@@ -102,3 +102,36 @@ describe("listParticipatingThreadIds", () => {expect(res).toEqual(["t1", "t3"]);});});++describe("removeParticipantFromChildChannels — member-remove notify cascade", () => {+ function makeDb(postRows: any[], deletedRows: any[]) {+ const selectChain: any = {};+ selectChain.select = vi.fn(() => selectChain);+ selectChain.from = vi.fn(() => selectChain);+ selectChain.where = vi.fn(() => Promise.resolve(postRows));+ const deleteChain: any = {};+ deleteChain.delete = vi.fn(() => deleteChain);+ deleteChain.where = vi.fn(() => deleteChain);+ deleteChain.returning = vi.fn(() => Promise.resolve(deletedRows));+ return {+ select: selectChain.select,+ from: selectChain.from,+ where: selectChain.where,+ delete: deleteChain.delete,+ } as any;+ }++ it("skips the delete when the parent has no children", async () => {+ const db = makeDb([], []);+ const n = await threadQueries.removeParticipantFromChildChannels(db, "forum_1", "u_removed");+ expect(n).toBe(0);+ expect(db.delete).not.toHaveBeenCalled();+ });++ it("deletes the user's participant rows across the parent's children", async () => {+ const db = makeDb([{ id: "p1" }, { id: "p2" }], [{ id: "tp1" }, { id: "tp2" }]);+ const n = await threadQueries.removeParticipantFromChildChannels(db, "forum_1", "u_removed");+ expect(n).toBe(2);+ expect(db.delete).toHaveBeenCalled();+ });+});diff --git a/src/web/migrations/0061_unify_forum_membership.sql b/src/web/migrations/0061_unify_forum_membership.sqlnew file mode 100644index 000000000..29809cfe5--- /dev/null+++ b/src/web/migrations/0061_unify_forum_membership.sql@@ -0,0 +1,101 @@+-- Unify forum/forum_post membership with channel/thread.+-- See plans/unify-forum-forumpost-channel-thread.md.+--+-- Model change: a `forum` now owns its access roster like a text channel, and a+-- `forum_post` INHERITS that roster (it is the NOTIFY dimension, like a thread),+-- rather than each post being its own access unit. This reverses the DIRECTION+-- of 0059 (which copied a forum's members DOWN onto each post): we now merge+-- post rosters UP into the forum and drop the post-level access rows.+--+-- Access only WIDENS (a post's added members + post creators become forum-wide);+-- no one loses access. Participant (notify) rows are the new panel + notify+-- source for a post, so we also backfill them for existing posts that predate+-- participant enrollment.+--+-- All statements are idempotent (INSERT OR IGNORE against the unique indexes;+-- DELETE is naturally idempotent). `hex(randomblob(16))` = a fresh row id.++-- 1. Merge each private forum_post's explicit member rows UP into its parent+-- forum. Restricted to posts under a PRIVATE forum (a public forum has no+-- roster). Copies only EXPLICIT rows — admins/creator are re-derived at query+-- time, never stored.+INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, added_by, added_at)+SELECT+ lower(hex(randomblob(16))),+ forum.id,+ pm.user_id,+ pm.added_by,+ pm.added_at+FROM community_channel AS post+JOIN community_channel AS forum ON forum.id = post.parent_channel_id+JOIN community_category AS cat ON cat.id = forum.category_id AND cat.private = 1+JOIN community_channel_member AS pm ON pm.channel_id = post.id+WHERE post.type = 'forum_post';++-- 2. Merge each private forum_post's CREATOR up into the parent forum roster.+-- Old-model forum access was granted to a post creator via `creatorId` (see+-- isMemberOfAnyChildPost), but a post creator was only ever enrolled as a+-- PARTICIPANT, never as a channel_member row — so without this a post author+-- who isn't the forum creator would lose access to their own post.+INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, added_by, added_at)+SELECT+ lower(hex(randomblob(16))),+ forum.id,+ post.creator_id,+ post.creator_id,+ post.created_at+FROM community_channel AS post+JOIN community_channel AS forum ON forum.id = post.parent_channel_id+JOIN community_category AS cat ON cat.id = forum.category_id AND cat.private = 1+WHERE post.type = 'forum_post' AND post.creator_id IS NOT NULL;++-- 3. Backfill participant (notify) rows for existing forum_posts — 0060 only+-- covered type='thread'. A post's panel AND notify set are now its+-- participants, so a post predating enrollment would otherwise render an empty+-- panel and notify nobody. Seed from the people who demonstrably belong:+-- (a) distinct authors of messages in the post ("spoke"),+-- (b) the post creator,+-- (c) the post's soon-to-be-deleted explicit members (so pre-existing+-- access members keep getting notified even if they never spoke).+-- All tagged 'spoke' — the distinction only matters for future joins.++-- 3a. Message authors in the post.+INSERT OR IGNORE INTO community_thread_participant (id, thread_channel_id, user_id, source, added_at)+SELECT DISTINCT+ lower(hex(randomblob(16))),+ p.id,+ m.author_id,+ 'spoke',+ p.created_at+FROM community_channel AS p+JOIN community_message AS m ON m.channel_id = p.id+WHERE p.type = 'forum_post';++-- 3b. Post creator (may not have posted).+INSERT OR IGNORE INTO community_thread_participant (id, thread_channel_id, user_id, source, added_at)+SELECT+ lower(hex(randomblob(16))),+ p.id,+ p.creator_id,+ 'spoke',+ p.created_at+FROM community_channel AS p+WHERE p.type = 'forum_post' AND p.creator_id IS NOT NULL;++-- 3c. The post's explicit access members (about to be deleted in step 4).+INSERT OR IGNORE INTO community_thread_participant (id, thread_channel_id, user_id, source, added_at)+SELECT+ lower(hex(randomblob(16))),+ p.id,+ cm.user_id,+ 'spoke',+ cm.added_at+FROM community_channel AS p+JOIN community_channel_member AS cm ON cm.channel_id = p.id+WHERE p.type = 'forum_post';++-- 4. Drop all forum_post access rows — a post no longer owns an access roster+-- (it inherits its forum). Their participant rows (the new notify source)+-- were preserved/backfilled above.+DELETE FROM community_channel_member+WHERE channel_id IN (SELECT id FROM community_channel WHERE type = 'forum_post');diff --git a/src/web/src/app/api/community/agent/channelMember/route.test.ts b/src/web/src/app/api/community/agent/channelMember/route.test.tsindex 3110e6ab1..fda0b9b9e 100644--- a/src/web/src/app/api/community/agent/channelMember/route.test.ts+++ b/src/web/src/app/api/community/agent/channelMember/route.test.ts@@ -213,12 +213,13 @@ describe("POST /api/community/agent/channelMember", () => {expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "th_1")})- it("forum post inside a PUBLIC forum → still private on the wire; roster is post-scoped, not the whole server", async () => {+ it("forum post inside a PUBLIC forum → still private on the wire; roster is the PARTICIPANT set, not the whole server", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])mockResolveChannelByNameForMember.mockResolvedValue([{ id: "post_1", name: "bug-42", type: "forum_post", parentChannelId: "forum_1" }])- // Access context: public forum (isPrivate=false, categoryId=null) but the- // channel itself is a `forum_post` — the route must NOT fall into the- // public/hint branch, since a post is its own access unit.+ // Access context: public forum (isPrivate=false) but the channel itself is a+ // `forum_post` — the route must NOT fall into the public/hint branch. A post+ // is the NOTIFY dimension: its roster is the participant set (like a thread),+ // never the whole server.mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "post_1", serverId: "srv_1", type: "forum_post", parentChannelId: "forum_1", creatorId: "bot_1", categoryId: null },anchor: { id: "forum_1", type: "forum", creatorId: "owner_1", categoryId: null },@@ -227,10 +228,7 @@ describe("POST /api/community/agent/channelMember", () => {isCreator: true,isPrivate: false,})- mockResolveScopeMembers.mockResolvedValue([- { userId: "u_bot", role: "member", source: "explicit" },- { userId: "u_alice", role: "member", source: "explicit" },- ])+ mockListThreadParticipantUserIds.mockResolvedValue(["u_bot", "u_alice"])mockGetMembersByUserIds.mockResolvedValue([{ userName: "gus", discriminator: "4821", role: "member", nickname: null },{ userName: "alice", discriminator: "0193", role: "member", nickname: null },@@ -241,6 +239,7 @@ describe("POST /api/community/agent/channelMember", () => {const body = await res.json()expect(body.visibility).toBe("private")expect(body.members).toHaveLength(2)- expect(mockResolveScopeMembers).toHaveBeenCalledWith(expect.anything(), { scope: "post", scopeId: "post_1" })+ expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "post_1")+ expect(mockResolveScopeMembers).not.toHaveBeenCalledWith(expect.anything(), { scope: "post", scopeId: "post_1" })})})diff --git a/src/web/src/app/api/community/agent/channelMember/route.ts b/src/web/src/app/api/community/agent/channelMember/route.tsindex b40bc05fa..53f162162 100644--- a/src/web/src/app/api/community/agent/channelMember/route.ts+++ b/src/web/src/app/api/community/agent/channelMember/route.ts@@ -5,6 +5,7 @@ import {DM_SERVER,formatHandle,isForumPost,+ isThread,parseRef,} from "@alook/shared"import type {@@ -24,13 +25,11 @@ import { requireChannelAccess } from "@/lib/community/permissions"* - DM ref → 400 (channel-scoped). Rejected UP FRONT (before* `resolveTargetForMember`) so an un-opened DM surfaces the correct* channel-scoped 400 instead of a misleading 404 "dm not found".- * - thread (`type = "thread"`) → always private on the wire; returns the- * thread-participant roster (`community_thread_participant`). The- * parent-channel visibility does not leak here; a thread carries its own- * notify set irrespective of its parent's public/private state.- * - forum post (`type = "forum_post"`) → always private on the wire — a- * post is its own access unit even inside a PUBLIC forum, and the roster- * is the post-scoped member set, not the whole server.+ * - thread / forum post (`type = "thread" | "forum_post"`) → always private on+ * the wire; returns the participant roster (`community_thread_participant`).+ * Both are the NOTIFY dimension: a thread/post carries its own notify set+ * irrespective of its parent channel/forum's public/private state, so a+ * public post lists only its participants, never the whole server.* - public top-level channel/forum → `{ visibility: "public", hint }` (no* roster enumeration — every server member can see it, so the agent should* use `alook server member --server <name>` instead).@@ -86,24 +85,16 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {const { channel, isPrivate } = access.value- // Thread branch: always private on the wire; roster is the thread's- // participant set (`community_thread_participant`), regardless of parent- // channel visibility.- if (channel.type === "thread") {+ // Thread / forum-post branch: both are the NOTIFY dimension — the roster is+ // the participant set (`community_thread_participant`), always private on the+ // wire, regardless of the parent channel/forum's public/private state. A+ // public forum post therefore lists only its participants, not the server.+ if (isThread(channel.type) || isForumPost(channel.type)) {const userIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)const members = await hydrateMembers(db, channel.serverId, userIds)return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })}- // Forum post branch: even inside a PUBLIC forum, a post is its own access- // unit — return its post-scoped roster rather than the public/hint fallback.- if (isForumPost(channel.type)) {- const scoped = await queries.communityMembersResolver.resolveScopeMembers(db, { scope: "post", scopeId: channelId })- const userIds = scoped.map((s) => s.userId)- const members = await hydrateMembers(db, channel.serverId, userIds)- return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })- }-if (!isPrivate) {const server = await queries.communityServer.getServer(db, channel.serverId)const serverName = server?.name ?? channel.serverIddiff --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.tsindex d93e81b32..18eeb01fb 100644--- 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.ts@@ -10,6 +10,7 @@ const mockDeleteChannelMember = vi.fn()const mockGetPrivateChannelAudienceUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()const mockLogAudit = vi.fn()+const mockRemoveParticipantFromChildChannels = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -23,6 +24,9 @@ vi.mock("@alook/shared", async () => {deleteChannelMember: (...a: unknown[]) => mockDeleteChannelMember(...a),getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),},+ communityThread: {+ removeParticipantFromChildChannels: (...a: unknown[]) => mockRemoveParticipantFromChildChannels(...a),+ },},}})@@ -82,6 +86,25 @@ describe("DELETE /channels/[id]/members/[userId]", () => {expect(res.status).toBe(204)expect(mockDeleteChannelMember).toHaveBeenCalledWith(expect.anything(), "c1", "u2")expect(mockBroadcastToUserSafe).toHaveBeenCalled()+ // A removed channel member also loses their child-thread notify rows.+ expect(mockRemoveParticipantFromChildChannels).toHaveBeenCalledWith(expect.anything(), "c1", "u2")+ })++ it("removing a FORUM member cascades: drops their participant rows across posts", async () => {+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "f1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "u1" },+ anchor: { id: "f1", serverId: "s1", parentChannelId: null, creatorId: "u1" },+ role: "member", isPrivate: true, isChannelMember: true, isCreator: true,+ })+ const res = await DELETE(+ new NextRequest("http://localhost/api/community/channels/f1/members/u2", { method: "DELETE" }),+ { params: { id: "f1", userId: "u2" } } as any,+ )+ expect(res.status).toBe(204)+ expect(mockDeleteChannelMember).toHaveBeenCalledWith(expect.anything(), "f1", "u2")+ // The ex-member's leftover notify rows on the forum's posts are cleaned so+ // fan-out stops pushing new-post messages they can no longer read.+ expect(mockRemoveParticipantFromChildChannels).toHaveBeenCalledWith(expect.anything(), "f1", "u2")})it("cannot remove the creator (400)", async () => {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.tsindex 3adbb0903..508dfc5a2 100644--- 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.ts@@ -37,6 +37,12 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const removed = await queries.communityChannel.deleteChannelMember(db, channelId, targetUserId)if (!removed) return writeError("member not found", 404)+ // A removed member loses access to every child unit (a forum's posts, a+ // channel's threads); drop their leftover participant (notify) rows across+ // those children so fan-out stops pushing new post/thread messages they can no+ // longer read. A later mention/speak (which requires access) re-adds them.+ await queries.communityThread.removeParticipantFromChildChannels(db, channelId, targetUserId)+const event = {type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,serverId: channel.serverId,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.tsindex cb66e6d80..18f9baae3 100644--- 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.ts@@ -16,6 +16,7 @@ const mockGetMembersByUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()const mockLogAudit = vi.fn()const mockAddThreadParticipants = vi.fn()+const mockListThreadParticipants = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -39,6 +40,7 @@ vi.mock("@alook/shared", async () => {},communityThread: {addThreadParticipants: (...a: unknown[]) => mockAddThreadParticipants(...a),+ listThreadParticipants: (...a: unknown[]) => mockListThreadParticipants(...a),},user: { getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a) },},@@ -133,35 +135,40 @@ describe("GET /channels/[id]/members", () => {expect(body.members[0].userId).toBe("u1")})- it("resolves a thread to its anchor channel's audience", async () => {+ it("resolves a thread to its PARTICIPANT set (notify dimension)", async () => {mockResolveChannelAccessContext.mockResolvedValue({- channel: { id: "t1", serverId: "s1", parentChannelId: "c1", creatorId: "u1" },+ channel: { id: "t1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", creatorId: "u1" },anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },- role: "admin", isPrivate: true, isChannelMember: true,+ role: "admin", isPrivate: true, isChannelMember: true, isCreator: true,})+ mockListThreadParticipants.mockResolvedValue([+ { userId: "u1", source: "spoke", userName: "Ann", userImage: null, discriminator: "0001", addedAt: "" },+ ])const res = await GET(new NextRequest("http://localhost/api/community/channels/t1/members"), { params: { id: "t1" } } as any)expect(res.status).toBe(200)- // scope resolves against the requested channel id (climbs internally).- expect(mockResolveScopeMembers).toHaveBeenCalledWith(expect.anything(), { scope: "channel", scopeId: "t1" })- // hydration is scoped to the anchor's server.- expect(mockGetMembersByUserIds).toHaveBeenCalledWith(expect.anything(), "s1", expect.any(Array))+ // A thread reads participants, NOT the access audience.+ expect(mockListThreadParticipants).toHaveBeenCalledWith(expect.anything(), "t1")+ expect(mockResolveScopeMembers).not.toHaveBeenCalled()+ expect(mockGetMembersByUserIds).toHaveBeenCalledWith(expect.anything(), "s1", ["u1"])})- it("badges a forum post's OWN creator, not the forum owner", async () => {- // Post p1 owned by u2; the forum (anchor) is owned by u1. The post roster- // is u1 (forum owner, added as a member) + u2 (post creator).+ it("forum post reads PARTICIPANTS and badges the post's OWN creator", async () => {+ // Post p1 authored by u2; the forum (anchor) is owned by u1. A public post's+ // panel is its participant set — NOT the whole server / access audience.mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "p1", serverId: "s1", type: "forum_post", parentChannelId: "f1", parentMessageId: null, creatorId: "u2" },anchor: { id: "f1", serverId: "s1", parentChannelId: null, creatorId: "u1" },- role: "member", isPrivate: true, isChannelMember: true, isCreator: false,+ role: "member", isPrivate: false, isChannelMember: false, isCreator: false,})- mockResolveScopeMembers.mockResolvedValue([- { userId: "u1", role: "member", source: "explicit" },- { userId: "u2", role: "member", source: "explicit" },+ mockListThreadParticipants.mockResolvedValue([+ { userId: "u2", source: "spoke", userName: "Bob", userImage: null, discriminator: "0002", addedAt: "" },+ { userId: "u1", source: "added", userName: "Ann", userImage: null, discriminator: "0001", addedAt: "" },])const res = await GET(new NextRequest("http://localhost/api/community/channels/p1/members"), { params: { id: "p1" } } as any)const body = await res.json()- // The post creator (u2) is the roster creator — NOT the forum owner (u1).+ expect(mockListThreadParticipants).toHaveBeenCalledWith(expect.anything(), "p1")+ expect(mockResolveScopeMembers).not.toHaveBeenCalled()+ // The post creator (u2) is badged — NOT the forum owner (u1).expect(body.members.find((m: any) => m.userId === "u2").isCreator).toBe(true)expect(body.members.find((m: any) => m.userId === "u1").isCreator).toBe(false)})@@ -231,34 +238,29 @@ describe("POST /channels/[id]/members", () => {expect(res.status).toBe(400)})- it("rejects adding to a FORUM (400): forum membership is derived from its posts", async () => {+ it("ALLOWS adding to a private FORUM (it owns its roster like a channel)", async () => {mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "f1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "u1" },anchor: { id: "f1", serverId: "s1", parentChannelId: null, creatorId: "u1" },role: "member", isPrivate: true, isChannelMember: true, isCreator: true,})const res = await POST(postReq({ userId: "u2" }), { params: { id: "f1" } } as any)- expect(res.status).toBe(400)- // A forum member row would never be read (access is the union of posts) —- // the write must be rejected, not silently no-op.- expect(mockCreateChannelMember).not.toHaveBeenCalled()+ expect(res.status).toBe(201)+ expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), {+ channelId: "f1", userId: "u2", addedBy: "u1",+ })})- it("allows adding to a private forum post (own access unit)", async () => {+ it("rejects adding to a forum POST (400): posts take participants, not members", async () => {mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "p1", serverId: "s1", type: "forum_post", parentChannelId: "f1", parentMessageId: null, creatorId: "u1" },anchor: { id: "f1", serverId: "s1", parentChannelId: null, creatorId: "u1" },role: "member", isPrivate: true, isChannelMember: true, isCreator: true,})const res = await POST(postReq({ userId: "u2" }), { params: { id: "p1" } } as any)- expect(res.status).toBe(201)- expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), {- channelId: "p1", userId: "u2", addedBy: "u1",- })- // Access → notify coupling: an added private-post member also joins the- // post's participant (notify) set so they receive fan-out.- expect(mockAddThreadParticipants).toHaveBeenCalledWith(expect.anything(), "p1", [- { userId: "u2", source: "added" },- ])+ expect(res.status).toBe(400)+ // A post inherits its forum's access — no access rows. Add participants via+ // the participants route instead.+ expect(mockCreateChannelMember).not.toHaveBeenCalled()})})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.tsindex f42ddcbcf..7f7c6a02f 100644--- a/src/web/src/app/api/community/channels/[id]/members/route.ts+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts@@ -24,9 +24,37 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {const access = await requireChannelAccess(db, channelId, ctx.userId)if (!access.ok) return writeError(access.error, access.status)- const { anchor } = access.value+ const { anchor, channel } = access.value++ // Thread / forum-post: the NOTIFY dimension. The panel == the participant set+ // (not the access audience), so a public forum post lists only its+ // participants, never the whole server. The row's `isCreator` locks the+ // UNIT's own author (`channel.creatorId`), NOT the access anchor. NOTE: the+ // live /c UI reads `/participants` for these units; this branch is API/agent+ // parity so a direct GET of a post's `/members` agrees.+ if (isThread(channel.type) || isForumPost(channel.type)) {+ const participants = await queries.communityThread.listThreadParticipants(db, channelId)+ const userIds = participants.map((p) => p.userId)+ const rows = await queries.communityMember.getMembersByUserIds(db, channel.serverId, userIds)+ const rowByUser = new Map(rows.map((r) => [r.userId, r]))+ const members = participants+ .map((p) => {+ const row = rowByUser.get(p.userId)+ if (!row) return null+ return mapMemberForApi(row, ctx.userId, {+ isCreator: p.userId === channel.creatorId,+ source: p.source,+ })+ })+ .filter((m): m is NonNullable<typeof m> => m !== null)+ return writeJSON({ members })+ }++ // Channel / forum: the ACCESS dimension. Resolve the audience (public → all+ // server members; private → own roster ∪ creator). The anchor IS the roster+ // for these top-level units, so the roster creator is `anchor.creatorId`.const scopeMembers = await queries.communityMembersResolver.resolveScopeMembers(db, {- scope: "channel",+ scope: isForum(channel.type) ? "forum" : "channel",scopeId: channelId,})const rows = await queries.communityMember.getMembersByUserIds(@@ -36,16 +64,6 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {)const rowByUser = new Map(rows.map((r) => [r.userId, r]))- // The roster creator is the UNIT's own creator: a forum post owns its roster,- // so its creator is the post's `channel.creatorId` — NOT `anchor.creatorId`,- // which for a post is the forum owner. For a thread/channel the anchor IS the- // roster, so both agree. Mirrors the `rosterCreatorId` split in- // `resolveChannelAccessContext`.- const rosterCreatorId =- isForumPost(access.value.channel.type)- ? access.value.channel.creatorId- : anchor.creatorId-// `resolveScopeMembers` order is the source of truth for membership; hydrate// display via the server-member rows (soft-deleted users drop out — expected).const members = scopeMembers@@ -53,7 +71,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {const row = rowByUser.get(sm.userId)if (!row) return nullreturn mapMemberForApi(row, ctx.userId, {- isCreator: sm.userId === rosterCreatorId,+ isCreator: sm.userId === anchor.creatorId,source: sm.source,})})@@ -63,13 +81,13 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {})/**- * Add a member to a private access unit — a top-level channel OR a forum post- * (both own their roster in the nested-membership model). ANY current member- * (or the creator) may add — passing `requireChannelAccess` for a private unit- * already means the caller is the creator or an added member (admins have no- * implicit access). The target must be an existing server member. Threads are- * rejected — they're the notification dimension and inherit the parent- * channel's roster (participants join via mention/speak/owner-add, not here).+ * Add a member to a private ACCESS unit — a top-level text channel OR a forum+ * (both own their roster; a forum resolves access like a channel). ANY current+ * member (or the creator) may add — passing `requireChannelAccess` for a private+ * unit already means the caller is the creator or an added member (admins have+ * no implicit access). The target must be an existing server member. Threads AND+ * forum posts are rejected — they're the NOTIFY dimension, inherit the parent's+ * roster, and take PARTICIPANTS (via the participants route), not access members.*/export const POST = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -80,20 +98,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channel- // Threads are notify-only (roster lives on the participant table); a thread- // has a `parentMessageId`. A forum post also has a `parentChannelId` but NO- // `parentMessageId` and IS its own access unit, so it's allowed.- if (isThread(channel.type) || channel.parentMessageId) {- return writeError("threads inherit their parent channel's members", 400)+ // Threads AND forum posts are the NOTIFY dimension — they inherit their parent+ // channel/forum's access roster and store their own set in the participant+ // table. You add PARTICIPANTS to them (via the participants route), not access+ // members. A thread has a `parentMessageId`; a forum post has a+ // `parentChannelId` but no `parentMessageId`.+ if (isThread(channel.type) || isForumPost(channel.type) || channel.parentMessageId) {+ return writeError("threads and forum posts inherit their parent's members — add participants instead", 400)}- // A FORUM's membership is DERIVED from its posts (the union) — it has no roster- // of its own, so a member row on the forum would never be read. Reject: add- // people to individual posts, not the forum.- if (isForum(channel.type)) {- return writeError("forum membership is derived from its posts — add members to a post", 400)- }- // `isPrivate` from requireChannelAccess reflects the (climbed) category — for- // a post that's the forum's category. Public units have no explicit roster.+ // `isPrivate` from requireChannelAccess reflects the category. A public+ // channel/forum has no explicit roster (everyone can access it).if (!access.value.isPrivate) {return writeError("channel is not in a private category", 400)}@@ -118,17 +132,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {addedBy: ctx.userId,})- // Couple access → notify for a private forum post: an added member also joins- // the post's participant (notify) set, so they receive fan-out. A post's- // participant set is thus always a subset of its access roster. Idempotent —- // if they already spoke/were mentioned, this is a no-op. (A top-level private- // channel notifies via its access audience, so it needs no participant row.)- if (isForumPost(channel.type)) {- await queries.communityThread.addThreadParticipants(db, channelId, [- { userId: targetUserId, source: "added" },- ])- }-const event = {type: WS_EVENTS.CHANNEL_MEMBER_ADD,serverId: channel.serverId,diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.tsindex 6ea0cc04c..4217a7f6d 100644--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts@@ -2,17 +2,16 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { queries } from "@alook/shared"+import { queries, isThread, isForumPost } from "@alook/shared"import { requireChannelAccess } from "@/lib/community/permissions"/**- * Leave a thread (remove a participant row). The viewer may remove THEMSELVES;- * the thread creator may remove anyone. Thread-only. A later mention/speak- * re-adds a user who left.+ * Leave a thread/forum-post (remove a participant row). The viewer may remove+ * THEMSELVES; the unit creator may remove anyone. Thread/forum-post only. A+ * later mention/speak re-adds a user who left.*- * (Muting a thread is NOT here — that's the outer channel-header notification- * level, per-layer, same control a channel uses. Participation is add/leave- * only.)+ * (Muting is NOT here — that's the outer channel-header notification level,+ * per-layer, same control a channel uses. Participation is add/leave only.)*/export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -22,15 +21,18 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {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.channel.type !== "thread") return writeError("not a thread", 400)+ const type = access.value.channel.type+ if (!isThread(type) && !isForumPost(type)) {+ return writeError("not a thread or forum post", 400)+ }- // Removing another participant is the THREAD creator's call — the person who- // started the thread (`channel.creatorId`), NOT `access.value.isCreator`,- // which for a thread resolves to the parent channel's creator (the roster- // anchor). Any participant may always remove themselves.+ // Removing another participant is the UNIT creator's call — the person who+ // started the thread/post (`channel.creatorId`), NOT `access.value.isCreator`,+ // which resolves to the parent channel/forum's creator (the access anchor).+ // Any participant may always remove themselves.const isSelf = targetUserId === ctx.userId- const isThreadCreator = access.value.channel.creatorId === ctx.userId- if (!isSelf && !isThreadCreator) return writeError("forbidden", 403)+ const isUnitCreator = access.value.channel.creatorId === ctx.userId+ if (!isSelf && !isUnitCreator) return writeError("forbidden", 403)const removed = await queries.communityThread.removeThreadParticipant(db, channelId, targetUserId)if (!removed) return writeError("participant not found", 404)diff --git a/src/web/src/app/api/community/channels/[id]/participants/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/route.test.tsindex 6d37dc761..42e85c026 100644--- a/src/web/src/app/api/community/channels/[id]/participants/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/route.test.ts@@ -90,7 +90,17 @@ describe("GET /channels/[id]/participants", () => {expect(body.participants[1]).not.toHaveProperty("muted")})- it("400 when the channel is not a thread", async () => {+ it("also serves a forum_post (its panel is the participant set)", async () => {+ mockResolveChannelAccessContext.mockResolvedValue(threadCtx({+ channel: { id: "p1", serverId: "s1", type: "forum_post", parentChannelId: "f1", parentMessageId: null, creatorId: "u1" },+ }))+ const res = await GET(new NextRequest("http://localhost/api/community/channels/p1/participants"), { params: { id: "p1" } } as any)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.participants).toHaveLength(2)+ })++ it("400 when the channel is not a thread or forum post", async () => {mockResolveChannelAccessContext.mockResolvedValue(threadCtx({ channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "u1" } }))const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/participants"), ctx)expect(res.status).toBe(400)diff --git a/src/web/src/app/api/community/channels/[id]/participants/route.ts b/src/web/src/app/api/community/channels/[id]/participants/route.tsindex ea9adc818..e866a169a 100644--- a/src/web/src/app/api/community/channels/[id]/participants/route.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/route.ts@@ -2,15 +2,16 @@ 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 { queries, WS_EVENTS, isThread, isForumPost } from "@alook/shared"import { broadcastToUserSafe } from "@/lib/community/fanout"import { requireChannelAccess } from "@/lib/community/permissions"import { avatarInitial } from "@/lib/community/avatar"/**- * List a thread's participants — the NOTIFY set (incl. muted rows, so the- * viewer's own muted state shows). Thread-only. Any member of the parent- * channel (who therefore passes the thread access gate) may read the list.+ * List a thread/forum-post's participants — the NOTIFY set. Both thread and+ * forum_post are the notification dimension (their panel == their notify set),+ * so both use this endpoint. Any member with access (who therefore passes the+ * access gate) may read the list.*/export const GET = withAuth(async (_req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -19,8 +20,9 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {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.channel.type !== "thread") {- return writeError("not a thread", 400)+ const type = access.value.channel.type+ if (!isThread(type) && !isForumPost(type)) {+ return writeError("not a thread or forum post", 400)}const rows = await queries.communityThread.listThreadParticipants(db, channelId)@@ -35,13 +37,12 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {})/**- * Add a participant to a thread — the "add from channel" flow. ANY current- * viewer with access to the thread may add (passing `requireChannelAccess`- * means the caller can see the thread — i.e. is a member of the parent channel;- * mirrors the channel/post "any member can add" rule). Other joins happen- * automatically via mention/speak. The target must be a member of the thread's- * PARENT CHANNEL audience (a thread can only pull in people who can already see- * the channel it lives in).+ * Add a participant to a thread/forum-post — the "add from channel" flow. ANY+ * current viewer with access may add (passing `requireChannelAccess` means the+ * caller can see the unit — i.e. is a member of the parent channel/forum).+ * Other joins happen automatically via mention/speak. The target must be a+ * member of the PARENT's access audience (you can only pull in people who can+ * already see the channel/forum the unit lives in).*/export const POST = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -51,7 +52,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const access = await requireChannelAccess(db, channelId, ctx.userId)if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channel- if (channel.type !== "thread") return writeError("not a thread", 400)+ if (!isThread(channel.type) && !isForumPost(channel.type)) {+ return writeError("not a thread or forum post", 400)+ }let body: { userId?: string }try {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 6dc6c97a6..f84568fdf 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@@ -3,7 +3,6 @@ import { NextRequest } from "next/server"const mockGetChannelForMember = vi.fn()const mockResolveChannelAccessContext = vi.fn()-const mockListChannelIdsWithMember = vi.fn(async () => [])const mockCreateChannel = vi.fn()const mockCreateMessage = vi.fn()const mockGetMessage = vi.fn()@@ -29,7 +28,6 @@ vi.mock("@alook/shared", async () => {communityChannel: {getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),- listChannelIdsWithMember: (...a: unknown[]) => mockListChannelIdsWithMember(...a),createChannel: (...a: unknown[]) => mockCreateChannel(...a),listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),// createCommunityMessage's private-channel scoping guard is only hit@@ -325,28 +323,24 @@ describe("GET /api/community/channels/[id]/posts — private-forum post visibilireturn new NextRequest("http://localhost/api/community/channels/ch1/posts")}- it("non-manager member sees only posts they're in or created (no leak)", async () => {- // Forum access is derived: the viewer is a member of some post, so- // requireChannelAccess grants access (isChannelMember true via the- // post-union check inside resolveChannelAccessContext, mocked here).+ it("a forum member sees ALL posts (unified model: posts inherit forum access)", async () => {+ // Reaching here means requireChannelAccess already granted forum access; a+ // forum member sees every post under it (no per-post filter). A non-member+ // 403s up front (next test).mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "ch1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "owner", tags: [] },anchor: { id: "ch1", serverId: "s1", parentChannelId: null, creatorId: "owner" },role: "member", isPrivate: true, isChannelMember: true, isCreator: false,})- // viewer has a member row only on p_mine.- mockListChannelIdsWithMember.mockResolvedValue(["p_mine"])const res = await GET(getReq(), ctx)expect(res.status).toBe(200)const body = await res.json()const ids = body.posts.map((p: { id: string }) => p.id).sort()- expect(ids).toEqual(["p_created", "p_mine"]) // p_hidden filtered out+ expect(ids).toEqual(["p_created", "p_hidden", "p_mine"]) // all posts visible})- it("server admin WITH forum access sees every post (bypasses per-post filter)", async () => {- // Admin has content access (isChannelMember true, e.g. member of a post →- // derived forum access); the post-list filter is skipped for server admins.+ it("server admin WITH forum access sees every post", async () => {mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "ch1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "owner", tags: [] },anchor: { id: "ch1", serverId: "s1", parentChannelId: null, creatorId: "owner" },@@ -356,29 +350,23 @@ describe("GET /api/community/channels/[id]/posts — private-forum post visibiliconst res = await GET(getReq(), ctx)const body = await res.json()expect(body.posts).toHaveLength(3)- expect(mockListChannelIdsWithMember).not.toHaveBeenCalled()})- it("admin without forum access is forbidden (no content privilege)", async () => {+ it("non-member is forbidden up front (no post leak)", async () => {mockResolveChannelAccessContext.mockResolvedValue(null)const res = await GET(getReq(), ctx)expect(res.status).toBe(403)})- it("forum creator (non-admin) is NOT special: sees only their own posts, empty if none", async () => {- // u1 created the forum but is a plain member; canManage may be true via- // being the forum creator, but the post filter keys off server-admin only.+ it("forum creator sees every post (like any forum member)", async () => {mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "ch1", serverId: "s1", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "u1", tags: [] },anchor: { id: "ch1", serverId: "s1", parentChannelId: null, creatorId: "u1" },role: "member", isPrivate: true, isChannelMember: true, isCreator: true,})- mockListChannelIdsWithMember.mockResolvedValue([]) // no post memberships- // none of the seeded posts were created by u1 except p_created.const res = await GET(getReq(), ctx)const body = await res.json()- const ids = body.posts.map((p: { id: string }) => p.id)- expect(ids).toEqual(["p_created"]) // only the post u1 created; forum-creator gets no blanket view- expect(mockListChannelIdsWithMember).toHaveBeenCalled()+ const ids = body.posts.map((p: { id: string }) => p.id).sort()+ expect(ids).toEqual(["p_created", "p_hidden", "p_mine"]) // all posts, not just their own})})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 39164f3d1..6c92ab816 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@@ -9,7 +9,6 @@ import {MESSAGE_PREVIEW_LENGTH,WS_EVENTS,slugify,- canManageServer,} from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember, requireChannelAccess } from "@/lib/community/permissions"@@ -41,24 +40,11 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {childChannels = childChannels.filter((ch) => ch.tags.includes(tag))}- // Nested-membership model: a private forum's posts are each their own access- // unit. Only surface posts the viewer created or has a member row on. Only- // SERVER ADMINS/OWNER see all posts — the FORUM CREATOR is NOT special here- // (a forum creator with no posts of their own sees an empty list; they only- // get to OPEN the forum). Prevents leaking private post names + previews to a- // forum-visible non-member. Public forums are unchanged.- if (auth.value.isPrivate && !canManageServer(auth.value.member.role)) {- const memberIds = new Set(- await queries.communityChannel.listChannelIdsWithMember(- db,- childChannels.map((c) => c.id),- ctx.userId,- ),- )- childChannels = childChannels.filter(- (c) => c.creatorId === ctx.userId || memberIds.has(c.id),- )- }+ // Unified model: a forum's posts INHERIT the forum's access (a post is not its+ // own access unit — like a thread inherits its channel). Reaching here means+ // `requireChannelAccess` already granted the viewer access to the forum (a+ // private forum 403s a non-member up front), so they see ALL of its posts. No+ // per-post membership filter.// Batch-fetch all creators in one queryconst creatorIds = [...new Set(childChannels.map((t) => t.creatorId).filter(Boolean) as string[])]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 defc2972c..5325e276e 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@@ -229,6 +229,20 @@ describe("PATCH /channels/[id] — forum-post tag carve-out", () => {expect(mockUpdateChannel).not.toHaveBeenCalled()})+ it("the FORUM creator cannot edit a post they didn't author (isCreator is access-only)", async () => {+ // Unified model: access `isCreator` collapses to the forum (anchor) creator.+ // The post-tag carve-out must key off the POST's own creator, so a forum+ // creator who isn't the post author is NOT granted edit (would be a+ // regression if it keyed off `access.value.isCreator`).+ mockResolveChannelAccessContext.mockResolvedValue({+ ...forumPostCtx({ isCreator: false }), // post authored by "someone_else"+ isCreator: true, // but caller u1 IS the forum/anchor creator (access flag)+ })+ const res = await PATCH(patchReq({ forumTags: JSON.stringify(["x"]) }), ctx)+ expect(res.status).toBe(403)+ expect(mockUpdateChannel).not.toHaveBeenCalled()+ })+it("rejects forumTags on a non-forum_post channel (400)", async () => {// A manager editing a plain text channel: canManage true, but tags are a// per-post concept only.@@ -378,6 +392,18 @@ describe("DELETE /channels/[id]", () => {expect(mockDeleteChannel).not.toHaveBeenCalled()})+ it("the FORUM creator cannot delete a post they didn't author (isCreator is access-only)", async () => {+ // Regression guard: the delete carve-out keys off the POST's own creator+ // (`channel.creatorId`), not the collapsed access `isCreator` (= forum creator).+ mockResolveChannelAccessContext.mockResolvedValue({+ ...forumPostCtx({ isCreator: false }), // post authored by "someone_else"+ isCreator: true, // caller u1 is the forum/anchor creator (access flag)+ })+ const res = await DELETE(delReq(), ctx)+ expect(res.status).toBe(403)+ expect(mockDeleteChannel).not.toHaveBeenCalled()+ })+it("the broadcast CHANNEL_DELETE payload carries parentChannelId", async () => {mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))const res = await DELETE(delReq(), ctx)diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.tsindex dea384882..589143dd4 100644--- a/src/web/src/app/api/community/channels/[id]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/route.ts@@ -24,14 +24,14 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channelconst isAdmin = canManageServer(access.value.member.role)- // A forum post's creator may edit that post's tags even without full- // `canManage` (a PUBLIC post's creator has `canManage === false`; a private- // post's creator already passes it via `isPrivate && isCreator`). Scoped to- // the `forumTags` field only below — every other field still requires- // `canManage`. `access.value.isCreator` is the vetted post-own-creator flag- // (NOT the forum creator), so we don't re-derive it from `channel.creatorId`.+ // A forum post's OWN creator may edit that post's tags even without full+ // `canManage`. `access.value.isCreator` is the ACCESS creator (the forum+ // creator for a post), so we derive the post-own-creator directly from+ // `channel.creatorId` — the same pattern the participants route uses for the+ // unit-creator lock. Scoped to the `forumTags` field only below; every other+ // field still requires `canManage`.const canEditPostTags =- channel.type === "forum_post" && access.value.isCreator+ channel.type === "forum_post" && channel.creatorId === ctx.userIdif (!access.value.canManage && !canEditPostTags) return writeError("forbidden", 403)let body: { name?: string; topic?: string; categoryId?: string | null; forumTags?: string | null }@@ -169,14 +169,13 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const access = await requireChannelAccess(db, channelId, ctx.userId)if (!access.ok) return writeError(access.error, access.status)const channel = access.value.channel- // A forum post's creator may delete their own post even without full- // `canManage` (a PUBLIC post's creator has `canManage === false`; a private- // post's creator already passes it via `isPrivate && isCreator`). Mirrors the- // PATCH tag carve-out. `access.value.isCreator` is the vetted post-own-creator- // flag (NOT the forum creator). Scoped to `forum_post` so normal-channel and- // thread creators are not granted delete.+ // A forum post's OWN creator may delete their own post even without full+ // `canManage`. Mirrors the PATCH tag carve-out. `access.value.isCreator` is the+ // ACCESS creator (the forum creator for a post), so derive the post-own-creator+ // directly from `channel.creatorId`. Scoped to `forum_post` so normal-channel+ // and thread creators are not granted delete.const canDeletePost =- channel.type === "forum_post" && access.value.isCreator+ channel.type === "forum_post" && channel.creatorId === ctx.userIdif (!access.value.canManage && !canDeletePost) return writeError("forbidden", 403)// Resolve the private-channel audience BEFORE deleting (the member rowsdiff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex 98eae3d5d..5b8fdb4e6 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -127,10 +127,15 @@ function ChannelView() {}, [currentServer, channelId])const isForum = isForumType(channelInServer?.type)const isChildChannel = !channelInServer && !!currentServer?.categories- // A thread is a child channel rooted on a message (`parentMessageId`). Forum- // posts are child channels too but have no `parentMessageId`. Threads are the- // notification dimension — their drawer shows PARTICIPANTS, not an audience.- const isThread = isChildChannel && !!currentChannelMeta?.parentMessageId+ // A thread (child channel rooted on a `parentMessageId`) and a forum post+ // (child channel with no `parentMessageId`) are both the NOTIFICATION+ // dimension: their drawer shows PARTICIPANTS (not an access audience), their+ // add button adds a PARTICIPANT, and their @-mention pool is the parent+ // channel/forum's members. Since every child channel is one or the other,+ // `isNotifyUnit === isChildChannel` — a load-stable value that doesn't flip+ // while `currentChannelMeta` hydrates. The thread/post distinction affects+ // only labels, handled inline, so a single flag drives all behavior here.+ const isNotifyUnit = isChildChannel// Local filter for the private-channel Members drawer (the channel audience is// small, so search is client-side — no scoped search endpoint).@@ -152,18 +157,21 @@ function ChannelView() {const cat = cats.find((c) => c.channels.some((ch) => ch.id === anchorId))return !!cat?.private}, [currentServer, isChildChannel, currentChannelMeta, channelId])- const channelMembersHook = useChannelMembers(channelId, currentChannelPrivate && !isThread)- // Thread drawer shows the notify PARTICIPANT set, not the channel audience.- const threadParticipantsHook = useThreadParticipants(channelId, isThread)+ // A notify unit (thread/post) has no roster of its own — its own+ // `useChannelMembers` stays disabled; its panel is the participant set.+ const channelMembersHook = useChannelMembers(channelId, currentChannelPrivate && !isNotifyUnit)+ // Thread/post drawer shows the notify PARTICIPANT set, not the channel audience.+ const threadParticipantsHook = useThreadParticipants(channelId, isNotifyUnit)const removeThreadParticipantMut = useRemoveThreadParticipant(channelId)const addThreadParticipantMut = useAddThreadParticipant(channelId)- // Channel/post add-picker source + mutations (add: any member; remove/leave).- const addableChannelMembers = useAddableMembers(channelId, currentChannelPrivate && !isThread)+ // Top-level channel/forum add-picker source + mutations (add: any member).+ const addableChannelMembers = useAddableMembers(channelId, currentChannelPrivate && !isNotifyUnit)const addChannelMemberMut = useAddChannelMember(channelId)const removeChannelMemberMut = useRemoveChannelMember(channelId)- // Thread add-picker source = the parent channel's roster (minus current- // participants + self, computed at dialog build). Enabled only for threads.- const threadParentId = isThread ? (currentChannelMeta?.parentChannelId ?? null) : null+ // Notify-unit add-picker source = the parent channel/forum's roster (minus+ // current participants + self, computed at dialog build). A thread's parent is+ // its channel; a post's parent is its forum. Enabled for both.+ const threadParentId = isNotifyUnit ? (currentChannelMeta?.parentChannelId ?? null) : nullconst parentChannelMembersHook = useChannelMembers(threadParentId ?? "", !!threadParentId)// Members shown in the right-panel Members drawer:@@ -197,8 +205,8 @@ function ChannelView() {const matches = (name: string, disc?: string | null) =>!q || name.toLowerCase().includes(q) || (disc ?? "").toLowerCase().includes(q)- if (isThread) {- const threadCreatorId = currentChannelMeta?.creatorId+ if (isNotifyUnit) {+ const unitCreatorId = currentChannelMeta?.creatorIdreturn threadParticipantsHook.participants.filter((p) => matches(p.name ?? "", p.discriminator)).map((p) => withPresence({@@ -206,9 +214,9 @@ function ChannelView() {name: displayName(p),discriminator: p.discriminator ?? "0000",avatar: p.avatar,- // Thread rows are all real participants (removable); the thread- // creator's row is locked.- isCreator: p.userId === threadCreatorId,+ // Rows are all real participants (removable); the unit creator's+ // (thread starter / post author) row is locked.+ isCreator: p.userId === unitCreatorId,}))}if (!currentChannelPrivate) return members@@ -216,7 +224,7 @@ function ChannelView() {.filter((m) => matches(m.name, m.discriminator)).map((m) => withPresence(m))}, [- isThread,+ isNotifyUnit,threadParticipantsHook.participants,currentChannelMeta,currentChannelPrivate,@@ -242,11 +250,11 @@ function ChannelView() {if (!currentChannelPrivate) {return members.filter((m) => m.userId !== currentUser.id)}- // Private unit: scope to the unit's roster. A thread has NO roster of its- // own — its `channelMembersHook` is disabled — so its mention candidates are- // the parent channel's members (the same source the add-participants dialog- // uses). A private channel/post uses its own roster.- const scopedRoster = isThread ? parentChannelMembersHook.members : channelMembersHook.members+ // Private unit: scope to the unit's roster. A thread/post has NO roster of+ // its own — its `channelMembersHook` is disabled — so its mention candidates+ // are the parent channel/forum's members (the same source the add-participant+ // dialog uses). A private top-level channel/forum uses its own roster.+ const scopedRoster = isNotifyUnit ? parentChannelMembersHook.members : channelMembersHook.membersreturn scopedRoster.filter((m) => m.userId !== currentUser.id).map((m) => {@@ -260,7 +268,7 @@ function ChannelView() {})}, [currentChannelPrivate,- isThread,+ isNotifyUnit,members,channelMembersHook.members,parentChannelMembersHook.members,@@ -704,20 +712,18 @@ function ChannelView() {: channelInServer?.creatorIdconst viewerIsUnitCreator = !!unitCreatorId && unitCreatorId === currentUser.id// The drawer's manage affordance:- // - thread → add participants (any participant); rows right-click to- // leave/remove.- // - private channel/post → add members (any member); rows right-click to- // leave (self) / remove (creator).- // - FORUM → NO manage button: its membership is the DERIVED union of its- // posts (read-only). Add people to individual posts, not the forum.- // Public channels: no manage button.- const showManageButton = isThread || (currentChannelPrivate && !isForum)+ // - thread/post (notify unit) → add PARTICIPANTS (any participant); rows+ // right-click to leave/remove.+ // - private top-level channel/forum → add MEMBERS (any member); rows+ // right-click to leave (self) / remove (creator).+ // Public top-level channels/forums: no manage button (everyone can access).+ const showManageButton = isNotifyUnit || currentChannelPrivate// Whether the drawer is on a scoped (participant/audience) source vs the// paginated server roster.- const scopedDrawer = isThread || currentChannelPrivate- // Row right-click Leave/Remove context — private channel/post + thread only.- // Remove is creator-only on every unit; the wired mutation differs by unit.- const manageContext = scopedDrawer && !isForum+ const scopedDrawer = isNotifyUnit || currentChannelPrivate+ // Row right-click Leave/Remove context. Remove is creator-only on every unit;+ // the wired mutation differs by unit (participant vs channel-member).+ const manageContext = scopedDrawer? {viewerUserId: currentUser.id,viewerIsCreator: viewerIsUnitCreator,@@ -725,15 +731,15 @@ function ChannelView() {// Return the promise so the confirm dialog can show a loading state and// surface errors from ONE place (MemberList's confirm catch).onLeave: (userId: string) =>- (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),+ (isNotifyUnit ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),onRemove: (userId: string) =>- (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),+ (isNotifyUnit ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),}: undefinedconst panelProps = {onOpenThread: enterThread,members: panelMembers,- membersLoading: isThread+ membersLoading: isNotifyUnit? threadParticipantsHook.isLoading: currentChannelPrivate ? channelMembersHook.isLoading : membersHook.loading,membersLoadingMore: scopedDrawer ? false : membersHook.loadingMore,@@ -769,16 +775,15 @@ function ChannelView() {}// Add-members dialog (shared), mounted when the drawer's Add button fires.- // - thread → candidates = parent-channel members not yet participating;- // onAdd = add thread participant.- // - private channel/post → candidates = server members not in the unit;- // onAdd = add channel member (targets `channelId` directly — a forum post- // is its own access unit).+ // - thread/post (notify unit) → candidates = parent channel/forum members+ // not yet participating; onAdd = add participant.+ // - private top-level channel/forum → candidates = server members not in the+ // unit; onAdd = add channel member (targets `channelId` directly).// The current-member list + leave/remove live in the drawer row right-click// menu (`manageContext`), not here.const manageMembersDialog = (() => {if (!manageMembersOpen) return null- if (isThread) {+ if (isNotifyUnit) {const participantIds = new Set(threadParticipantsHook.participants.map((p) => p.userId))const candidates = parentChannelMembersHook.members.filter((m) => !participantIds.has(m.userId) && m.userId !== currentUser.id)@@ -786,7 +791,7 @@ function ChannelView() {return (<AddMembersDialogtitle={`Add participants to /${currentChannelMeta?.name ?? channelName}`}- subtitle="Added people are notified of new replies. Anyone with access can already read the thread."+ subtitle="Added people are notified of new replies. Anyone with access can already read it."candidates={candidates}onAdd={(userId) => addThreadParticipantMut.mutateAsync(userId)}onClose={() => setManageMembersOpen(false)}@@ -801,7 +806,7 @@ function ChannelView() {return (<AddMembersDialogtitle={`Add members to /${channelName}`}- subtitle="Added members can see and post in this channel."+ subtitle="Added members can see and post here."candidates={candidates}onAdd={(userId) => addChannelMemberMut.mutateAsync(userId)}onClose={() => setManageMembersOpen(false)}@@ -884,6 +889,10 @@ function ChannelView() {forum={isForumType(parentChannel?.type)}rightPanel={rightPanel}onToggle={togglePanel}+ notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}+ onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {+ onError: (e) => toastApiError(e, "Failed to update notification level"),+ })}onBack={bp === "mobile" ? () => router.back() : undefined}server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}tools={{ threads: false }}@@ -908,6 +917,7 @@ function ChannelView() {messages={messages}loading={messagesLoading}pinnedIds={pinnedIds}+ newDividerBefore={newDividerBefore}typingUsers={typingUsers.map((id) => resolveUserName(id))}onOpenThread={() => { }}{...threadActions}@@ -917,6 +927,10 @@ function ChannelView() {hero={opener}onScrollRoot={setScrollRootEl}viewerUserId={currentUser.id}+ // Same gate as the top-level channel view: hold the mount-time+ // scroll until the read snapshot resolves and its anchor is loaded,+ // so a thread/forum-post opens on the "New" divider too.+ initialScrollReady={!readSnapshotFetching && anchorInCache}hasMore={hasMoreMessages}isFetchingOlder={isFetchingOlderMessages}onLoadOlder={fetchOlderMessages}diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex 2ca239408..7b0498e5d 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -193,6 +193,34 @@ describe("useCommunityWs — message.create", () => {expect(cache?.pages[0].messages).toEqual([])})+ it("invalidates threadParticipants for the focused channel (live panel growth)", async () => {+ // A thread/forum_post enrolls the sender + mentioned users as participants+ // server-side; the panel must refetch so a new speaker appears without a+ // manual refresh.+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()++ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ capturedOnMessage!(messageCreate("ch_1"))++ expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })+ })++ it("does NOT invalidate threadParticipants for an unfocused channel", async () => {+ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ capturedOnMessage!(messageCreate("ch_other"))+ const calls = spy.mock.calls.filter(+ (c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(communityKeys.threadParticipants("ch_other")),+ )+ expect(calls).toHaveLength(0)+ })+it("dedupes by messageId — a repeat event is a no-op", async () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")@@ -683,6 +711,39 @@ describe("useCommunityWs — member events", () => {})})+describe("useCommunityWs — channel.member_add/remove → invalidate rosters", () => {+ it("member_add invalidates channelMembers AND threadParticipants (forum_post add-participant path)", async () => {+ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ capturedOnMessage!({+ type: "community:channel.member_add",+ serverId: "srv_1",+ channelId: "ch_1",+ userId: "u_new",+ })+ const invalidated = (key: unknown) =>+ spy.mock.calls.some((c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(key))+ expect(invalidated(communityKeys.channelMembers("ch_1"))).toBe(true)+ expect(invalidated(communityKeys.threadParticipants("ch_1"))).toBe(true)+ })++ it("member_remove invalidates threadParticipants too", async () => {+ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ capturedOnMessage!({+ type: "community:channel.member_remove",+ serverId: "srv_1",+ channelId: "ch_1",+ userId: "u_gone",+ })+ expect(+ spy.mock.calls.some(+ (c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(communityKeys.threadParticipants("ch_1")),+ ),+ ).toBe(true)+ })+})+describe("useCommunityWs — friend + mention → invalidate", () => {it("friend.request invalidates communityKeys.friends()", async () => {await mountHook()diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 394dc2c2d..e43dac8b7 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -428,6 +428,14 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {communityKeys.channelMessages(event.channelId),(c) => insertMessageIntoCache(c, event.message),)+ // A thread/forum_post enrolls its sender + mentioned users as+ // participants server-side on send. That set IS its Members panel,+ // so refetch it live — otherwise a new speaker/mention only appears+ // after a manual refresh. No-op for a plain channel (whose panel is+ // the access roster, not participants); the query is disabled there.+ void queryClient.invalidateQueries({+ queryKey: communityKeys.threadParticipants(event.channelId),+ })} else if (event.dmConversationId && event.dmConversationId === sub.dmConversationId) {queryClient.setQueryData<PageCache>(communityKeys.dmMessages(event.dmConversationId),@@ -751,6 +759,10 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// a peer's add/remove changes it too, so an open add dialog doesn't// offer a just-added member (whose Add would 400) or hide a removed one.void queryClient.invalidateQueries({ queryKey: communityKeys.channelAddableMembers(event.channelId) })+ // A forum_post's "Add participant" emits this same MEMBER_ADD event —+ // its Members panel is the participant set, so refetch it too. No-op+ // for a plain channel (participants query disabled there).+ void queryClient.invalidateQueries({ queryKey: communityKeys.threadParticipants(event.channelId) })return}diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 1d4b55a34..3fa876d26 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -51,7 +51,7 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s* post no longer pings every roster member on every message — only the people* actually involved. Nested-membership model.* - channel / forum → the access audience via the shared resolver- * (public/private split + forum-union).+ * (public/private split; a forum owns its roster like a text channel).** The split lives here so fan-out and bot-wake use the same recipient set.*/diff --git a/src/web/src/lib/community/permissions.ts b/src/web/src/lib/community/permissions.tsindex 76e121abe..849c6d0e0 100644--- a/src/web/src/lib/community/permissions.ts+++ b/src/web/src/lib/community/permissions.ts@@ -75,8 +75,8 @@ export type ChannelAccess = {* - public/uncategorized → access; canManage only for admins* - private → access iff creator or added member (admins have NO implicit* content access); canManage iff admin (who can see it) or the unit creator- * Threads inherit their parent anchor's audience (the context query climbs- * `parentChannelId`); a forum post is its own access unit (roster on the post).+ * Threads AND forum posts inherit their parent anchor's audience (the context+ * query climbs `parentChannelId`); a forum/top-level channel owns its roster.** Because access now requires membership/creator even for admins, an admin who* isn't in a private channel gets a 403 here — so `canManage` for an admin is@@ -92,9 +92,9 @@ export async function requireChannelAccess(if (!ctx) return err(403, "forbidden")const isAdmin = canManageServer(ctx.role)- // `ctx.isCreator` is the roster-anchor creator (a post's OWN creator, else the- // channel/thread anchor's) — NOT `ctx.anchor.creatorId`, which for a post is- // the forum's creator.+ // `ctx.isCreator` is the ACCESS creator (the anchor's creator — for a+ // post/thread that's the forum/parent-channel creator). Post-manage rights+ // (edit tags / delete) are derived at the route from `channel.creatorId`.const isCreator = ctx.isCreator// Visibility: public → any server member; private → creator or added memberdiff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.tsindex 5fee71431..3054a2fce 100644--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts@@ -37,9 +37,9 @@ test.describe.serial("mentions — candidate scope", () => {let privateForumId: stringlet privatePostId: stringlet threadId: string- let alice: { id: string; discriminator: string }- let bob: { id: string; discriminator: string }- let carol: { id: string; discriminator: string }+ let alice: { id: string; name: string; discriminator: string }+ let bob: { id: string; name: string; discriminator: string }+ let carol: { id: string; name: string; discriminator: string }test.beforeAll(async () => {serverId = await seedServer("alice", `Scope ${Date.now()}`)@@ -60,8 +60,11 @@ test.describe.serial("mentions — candidate scope", () => {await seedChannelMember("alice", privateChannelId, userId("bob"))privateForumId = await seedChannel("alice", serverId, "private-forum", "forum", privateCatId)+ // A forum owns its roster; a post inherits it (the notify dimension). Add bob+ // to the FORUM, not the post — posts reject access-member adds and derive+ // their mention pool from the parent forum's audience.+ await seedChannelMember("alice", privateForumId, userId("bob"))privatePostId = await seedForumPost("alice", privateForumId, `Post ${Date.now()}`, "post body")- await seedChannelMember("alice", privatePostId, userId("bob"))// A thread rooted on a message in the private channel — its scope is the// PARENT channel's audience (alice+bob), NOT its own participant set.@@ -177,9 +180,11 @@ test.describe.serial("mentions — candidate scope", () => {const body = composerEditable(page)await expect(body).toBeVisible({ timeout: 10_000 })- // Typing @ opens the same mention popup the chat composer uses.+ // Typing @<name-prefix> opens the same mention popup the chat composer uses.+ // Query by bob's ACTUAL display name — an earlier serial spec may have+ // renamed the shared account, so a hardcoded "@bob" would match nothing.await body.click()- await body.pressSequentially("@bob")+ await body.pressSequentially(`@${bob.name.slice(0, 3)}`)await expect(page.getByTestId(tid.mentionOption(bob.id))).toBeVisible({ timeout: 15_000 })})diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex 6d7aee1fc..d7c9379cb 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -213,22 +213,24 @@ export async function renameUser(key: UserKey, name: string): Promise<void> {throw new Error(`renameUser failed (${lastStatus})`)}-// A member's row id + discriminator, read from a server's member list (the-// same NOT NULL column the mention grammar depends on). The mention popup keys-// its option testid off the row `id`, and the pill/profile card shows the-// `discriminator`, so the mention specs need both. `viewer` must be a member of-// `serverId`; `targetUserId` is the member being looked up.+// A member's row id + display name + discriminator, read from a server's member+// list (the same NOT NULL column the mention grammar depends on). The mention+// popup keys its option testid off the row `id`, filters candidates by `name`+// prefix, and the pill/profile card shows the `discriminator` — so the mention+// specs need all three (a hardcoded query like "@bob" breaks once an earlier+// serial spec renames the account). `viewer` must be a member of `serverId`;+// `targetUserId` is the member being looked up.export async function memberInfo(viewer: UserKey,serverId: string,targetUserId: string,-): Promise<{ id: string; discriminator: string }> {+): Promise<{ id: string; name: string; discriminator: string }> {const res = await fetch(`${WEB_URL}/api/community/servers/${serverId}/members`, {headers: { Cookie: sessionCookie(viewer), Origin: WEB_URL },})if (!res.ok) throw new Error(`memberInfo list failed (${res.status})`)- const data = (await res.json()) as { members: Array<{ id: string; userId: string; discriminator?: string }> }+ const data = (await res.json()) as { members: Array<{ id: string; userId: string; name: string; discriminator?: string }> }const found = data.members.find((m) => m.userId === targetUserId)if (!found?.discriminator) throw new Error(`memberInfo: no discriminator for ${targetUserId}`)- return { id: found.id, discriminator: found.discriminator }+ return { id: found.id, name: found.name, discriminator: found.discriminator }}diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex b95a5ad24..b5f8d03ac 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -232,6 +232,10 @@ vi.mock("@alook/shared", () => {return {createDb: (d1: unknown) => mockCreateDb(d1),createLogger: () => noopLogger,+ // Real type-guard impls — fanOutTyping branches on these to route a+ // thread/forum_post to the participant set vs the access audience.+ isThread: (t: unknown) => t === "thread",+ isForumPost: (t: unknown) => t === "forum_post",// Minimal `readOrStale` shim — bypasses the classifier so tests can// inject arbitrary Error shapes at the query-fn boundary and observe// fail-closed semantics. Real production behavior (retry then fallback)@@ -2178,6 +2182,30 @@ describe("WebSocketDurableObject", () => {expect(mockStubFetch).toHaveBeenCalledTimes(1)})+ it("forum_post: typing fans out to PARTICIPANTS, not the whole server", async () => {+ const { durable, env } = createDO()+ mockGetChannelForMember.mockResolvedValueOnce({ id: "post-1", serverId: "server-1" })+ mockGetChannelType.mockResolvedValueOnce("forum_post")+ mockListThreadParticipantUserIds.mockResolvedValueOnce(["sender-1", "part-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: "post-1" }),+ )+ await flush()++ // A public forum post reaches only its participants — same path as a+ // message fan-out — never the access-audience resolver (the whole server).+ expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "post-1")+ expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:part-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 7684b985d..6cae1d41a 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -14,6 +14,8 @@ import {HostBotAuditEventFrameSchema,pickBotActivityPreset,RUNNING_PRESETS,+ isThread,+ isForumPost,} from "@alook/shared"import type { CommunityMachineRuntime, CommunityMachineSummary } from "@alook/shared"@@ -1226,16 +1228,16 @@ export class WebSocketDurableObject extends DurableObject<Env> {log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId: targetId })return}- // Recipient set (nested-membership model):- // - THREAD → the thread's participant NOTIFY set (muted=0). Typing in- // a thread reaches only its participants, not the whole parent- // channel (decision 6). Admins are never auto-participants.- // - channel / post / forum → the access audience (public/private split- // + post-own / forum-union) via the shared resolver. Never leaks- // "X is typing" to non-members.+ // Recipient set — same split as the message fan-out (fanout.ts):+ // - THREAD / FORUM_POST → the participant NOTIFY set. Typing reaches+ // only its participants, not the whole parent channel/server. A+ // public forum post therefore never leaks "X is typing" to the+ // server. Admins are never auto-participants.+ // - channel / forum → the access audience (public/private split) via+ // the shared resolver. Never leaks to non-members.const channelType = await queries.communityChannel.getChannelType(db, targetId)recipientUserIds =- channelType === "thread"+ isThread(channelType) || isForumPost(channelType)? await queries.communityThread.listThreadParticipantUserIds(db, targetId): await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {scope: "channel",